language
large_stringclasses 1
value | text
stringlengths 9
2.95M
|
|---|---|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* sections.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: pfichepo <pfichepo@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2018/03/14 10:12:45 by pfichepo #+# #+# */
/* Updated: 2018/03/29 10:43:44 by pfichepo ### ########.fr */
/* */
/* ************************************************************************** */
#include <nm.h>
void add_list(char *name, t_lsection *list)
{
t_section *add;
if ((add = (t_section*)malloc(sizeof(t_section))) == NULL)
return ;
add->name = name;
add->next = NULL;
if (list->first == NULL)
{
list->first = add;
list->last = add;
add->nb = 1;
}
else
{
add->nb = list->last->nb + 1;
list->last->next = add;
list->last = add;
}
}
void add_segment64(\
struct segment_command_64 *com, t_lsection *list, bool swap)
{
unsigned int i;
struct section_64 *sec;
struct segment_command_64 *seg;
i = 0;
seg = (struct segment_command_64*)com;
sec = (struct section_64*)(seg + sizeof(seg) / sizeof(void*));
com->nsects = (swap) ? swap_uint64(com->nsects) : com->nsects;
while (i < com->nsects)
{
add_list(sec->sectname, list);
sec = (struct section_64 *)(((void*)sec) + sizeof(struct section_64));
i++;
}
}
void add_segment32(\
struct segment_command *com, t_lsection *list, bool swap)
{
unsigned int i;
struct section *sec;
struct segment_command *seg;
i = 0;
seg = (struct segment_command*)com;
sec = (struct section*)(seg + sizeof(seg) / sizeof(void*));
com->nsects = (swap) ? swap_uint32(com->nsects) : com->nsects;
while (i < com->nsects)
{
add_list(sec->sectname, list);
sec = (struct section *)(((void*)sec) + sizeof(struct section));
i++;
}
}
void *ft_memcpy(void *dst,
const void *src, size_t n)
{
unsigned int i;
char *dest;
const char *sourc;
if (src == NULL || dst == NULL)
return (NULL);
dest = dst;
sourc = src;
i = 0;
while (i < n)
{
dest[i] = sourc[i];
i++;
}
return (dst);
}
|
C
|
#include<stdio.h>
#include<stdlib.h>
char token=0,input[50];
int i;
void f_s();
void f_ss();
void f_A();
void f_AA();
char nextToken();
int main()
{
i=0;
printf("Enter the string\n");
scanf("%s",input);
token=nextToken();
f_s();
if(token=='$')
printf("Success\n");
else
printf("Fail\n");
}
void f_s()
{
if(token=='a')
{
token=nextToken();
f_ss();
if(token=='c')
token=nextToken();
}
else
{
printf("error2\n");
exit(0);
}
}
void f_ss()
{
if(token=='a')
{
token=nextToken();
f_ss();
if(token=='c')
token=nextToken();
else
{
printf("error3\n");
exit(0);
}
}
else if(token=='b')
{
f_A();
}
else
{
printf("error4\n");
exit(0);
}
}
void f_A()
{
if(token=='b')
{
token=nextToken();
f_AA();
}
else
{
printf("error5\n");
exit(0);
}
}
void f_AA()
{
if(token=='b')
{
f_A();
if (token=='c')
token=nextToken();
}
else if(token=='c')
{
token=nextToken();
}
else
{
printf("error6\n");
exit(0);
}
}
char nextToken()
{
return input[i++];
}
|
C
|
#include "holberton.h"
/**
* _strchr - Function that locates a character in a string..
* @s: Input string.
* @c: Character to locates.
* Return: dest.
*/
char *_strchr(char *s, char c)
{
unsigned int i = 0, y = 0;
while (s[y] != '\0')
y++;
while (i <= y)
{
if (s[i] == c)
return (&s[i]);
i++;
}
return ('\0');
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <netinet/in.h>
int main()
{
int sockfd;
struct sockaddr_in mysock;
sockfd = socket(AF_INET, SOCK_STREAM, 0);
bzero(&mysock, sizeof(mysock));
mysock.sin_family = AF_INET;
mysock.sin_port = htons(800);
mysock.sin_addr.s_addr = inet_addr("192.168.1.0");
bind(sockfd, (struct sockaddr*)&mysock, sizeof(struct sockaddr));
return 0;
}
int GetLargestN(const vector<int>& data, int k)
{
int n = data.size();
if(n == 0 || n < k || k <= 0)
return -1;
multiset<int, less<int>> heap;
for(int i=0; i<n; i++)
{
if(i < k)
heap.insert(data[i]);
else
{
multiset<int, less<int>>::const_iterator it = heap.begin();
if(*it < data[i])
{
heap.erase(it);
heap.insert(data[i]);
}
}
}
return *heap.begin();
}
|
C
|
#include<stdio.h>
#define JAN 1
#define FEB 2
#define MAR 3
#define APR 4
#define MAY 5
#define JUNE 6
#define JULY 7
#define AUG 8
#define SEP 9
#define OCT 10
#define NOV 11
#define DEC 12
int main()
{
int mnt;
printf("enter the month 1-12\n");
scanf("%d",&mnt);
switch(mnt)
{
case JAN : printf("%d days \n",31);
break;
case MAR: printf("%d days \n",31);
break;
case MAY: printf("%d days \n",31);
break;
case JULY: printf("%d days \n",31);
break;
case AUG: printf("%d days \n",31);
break;
case OCT: printf("%d days \n",31);
break;
case DEC: printf("%d days \n",31);
break;
case FEB: printf("%d days \n",28);
break;
case APR: printf("%d days \n",30);
break;
case JUNE: printf("%d days \n",30);
break;
case SEP: printf("%d days \n",30);
break;
case NOV: printf("%d days \n",30);
break;
default : printf("INVALID");
}
}
|
C
|
/*!
* @file tetris.c
* @brief Console tetris
* @author koturn
*/
#include <memory.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#ifdef _MSC_VER
# include <sys/timeb.h>
#else
# include <sys/time.h>
# include <unistd.h>
#endif
#include <termutil.h>
#ifndef __UNUSED__
# if defined(__cplusplus)
# define __UNUSED__(x)
# elif defined(__GNUC__)
# define __UNUSED__(x) __UNUSED___ ## x __attribute__((unused))
# elif defined(_MSC_VER)
# define __UNUSED__(x) __pragma(warning(suppress: 4100)) x
# elif defined(__LCLINT__)
# define __UNUSED__(x) /*@unused@*/ x
# else
# define __UNUSED__(x) x
# endif
#endif
#ifdef _MSC_VER
# define msec_sleep(x) Sleep(x)
#else
# define msec_sleep(x) usleep(x * 1000)
#endif
#define LENGTHOF(array) (sizeof(array) / sizeof((array)[0]))
#define N_NEXT_BLOCK 3
#define STAGE_WIDTH 12 /*!< Width of stage */
#define STAGE_HEIGHT 21 /*!< Height of stage */
#define BLOCK_WIDTH 4 /*!< Width of blocks */
#define BLOCK_HEIGHT 4 /*!< Height of blocks */
#define N_BLOCK 7 /*!< The number of block types */
#define SPACE 0 /*!< Indicate there is nothing */
#define WALL 9 /*!< Indicate there is wall */
#define FIELD_X 0 /*!< X-coordinate of player's field */
#define FIELD_Y 2 /*!< Y-coordinate of player's field */
#define SCORE_X 36 /*!< X-coordinate of player's score */
#define SCORE_Y 10 /*!< Y-coordinate of player's score */
#define NEXT_BLOCK_X 23
static const int NEXT_BLOCK_YS[] = {3, 10, 17};
#define SCORE_LEN 10 /*!< Buffer size of score label */
#define SCORE1 100
#define SCORE2 300
#define SCORE3 500
#define SCORE4 1000
#define CURSOR_X 0 /*!< X-coordinate of temporary cursor position */
#define CURSOR_Y 0 /*!< Y-coordinate of temporary cursor position */
#define TIME_X 36 /*!< X-coordinate of time label */
#define TIME_Y 5 /*!< Y-coordinate of time label */
#define TIME_LEN 5 /*!< Buffer size of time label */
#ifndef TRUE
# define TRUE 1
#endif
#ifndef FALSE
# define FALSE 0
#endif
typedef struct {
int x;
int y;
} Position;
typedef struct {
int block;
int next_block;
int score;
int time;
} UpdateFlag;
/*! Key-codes */
enum keycode {
CTRL_B = 0x02, /*!< Ctrl-B */
CTRL_F = 0x06, /*!< Ctrl-F */
CTRL_N = 0x0e /*!< Ctrl-N */
};
/*! The direction of rotation of the block */
typedef enum {
RIGHT, /*!< Indicates right-handed rotation */
LEFT /*!< Indicates right-handed rotation */
} Direction;
unsigned int next_idx = 0;
static unsigned char next_blocks[N_NEXT_BLOCK];
static unsigned char stage[STAGE_HEIGHT][STAGE_WIDTH];
static unsigned char block[BLOCK_HEIGHT][BLOCK_WIDTH];
static unsigned char field[STAGE_HEIGHT][STAGE_WIDTH];
/*! Seven blocks */
static const unsigned char block_list[N_BLOCK][BLOCK_HEIGHT][BLOCK_WIDTH] = {
{{0, 1, 0, 0},
{0, 1, 0, 0},
{0, 1, 0, 0},
{0, 1, 0, 0}},
{{0, 0, 0, 0},
{0, 2, 2, 0},
{0, 2, 0, 0},
{0, 2, 0, 0}},
{{0, 0, 3, 0},
{0, 3, 3, 0},
{0, 3, 0, 0},
{0, 0, 0, 0}},
{{0, 4, 0, 0},
{0, 4, 4, 0},
{0, 0, 4, 0},
{0, 0, 0, 0}},
{{0, 0, 0, 0},
{0, 5, 0, 0},
{5, 5, 5, 0},
{0, 0, 0, 0}},
{{0, 0, 0, 0},
{0, 6, 6, 0},
{0, 6, 6, 0},
{0, 0, 0, 0}},
{{0, 0, 0, 0},
{0, 7, 7, 0},
{0, 0, 7, 0},
{0, 0, 7, 0}}};
static UpdateFlag update_flag = {FALSE, FALSE, FALSE, FALSE};
static Position block_pos = {0, 4}; /*!< Block position */
static int score = 0; /*!< Player's score */
static time_t gametime = (time_t) -1; /*!< Player's score */
static int is_gameover = FALSE; /*!< Flag of gameover */
static void
initialize(void);
static void
control_block(void);
static void
drop_block(void);
static void
create_block(void);
static void
change_background_color(int color_nr);
static int
check_overlap(int x, int y);
static void
move_block(int new_x, int new_y);
static int
turn_block(Direction direction);
static void
lock_block(void);
static void
check_lines(void);
static void
update_screen(void);
static void
print_labels(void);
static void
print_wall(void);
static void
print_field(unsigned char field[STAGE_HEIGHT][STAGE_WIDTH], int x);
static void
print_next_blocks(void);
static void
print_score(int _score);
static void
print_time(time_t time);
static time_t
get_utc(void);
static void
sigint_handler(int sig);
/*!
* @brief An entry point of this program
* @return exit-status
*/
int
main(void)
{
int cnt = 1;
time_t base_time = time(NULL);
initialize();
while (!is_gameover) {
update_screen();
control_block();
if ((cnt = (cnt + 1) % 32) == 0) {
drop_block();
}
if (gametime != time(NULL) - base_time) {
gametime = time(NULL) - base_time;
update_flag.time = TRUE;
}
tu_move(CURSOR_Y, CURSOR_X);
msec_sleep(20);
}
printf("GAME OVER!!!!\n");
tu_refresh();
msec_sleep(2000);
return EXIT_SUCCESS;
}
/*!
* @brief Initialize game configurations
*/
static void
initialize(void)
{
int i, j;
srand((unsigned int) get_utc());
tu_init();
tu_setcur(0);
tu_clear();
tu_cbreak();
tu_noecho();
tu_nonblocking();
atexit(tu_cleanup);
signal(SIGINT, sigint_handler);
print_labels();
for (i = 0; i < STAGE_HEIGHT; i++) {
for (j = 0; j < STAGE_WIDTH; j++) {
if ((j == 0) || (j == STAGE_WIDTH - 1) || (i == STAGE_HEIGHT - 1)) {
field[i][j] = stage[i][j] = WALL;
} else {
field[i][j] = stage[i][j] = SPACE;
}
}
}
for (i = 0; i < (int) LENGTHOF(next_blocks); i++) {
next_blocks[i] = (unsigned char) (rand() % N_BLOCK);
}
create_block();
print_wall();
print_next_blocks();
print_field(field, FIELD_X);
}
/*!
* @brief Control block with key input
*/
static void
control_block(void)
{
switch (tu_getch()) {
/* ----- Like vi ----- */
case 'l':
if (!check_overlap(block_pos.x + 1, block_pos.y)) {
move_block(block_pos.x + 1, block_pos.y);
}
break;
case 'h':
if (!check_overlap(block_pos.x - 1, block_pos.y)) {
move_block(block_pos.x - 1, block_pos.y);
}
break;
case 'j':
if (!check_overlap(block_pos.x, block_pos.y + 1)) {
move_block(block_pos.x, block_pos.y + 1);
}
break;
/* ----- Like Emacs ----- */
case CTRL_F:
if (!check_overlap(block_pos.x + 1, block_pos.y)) {
move_block(block_pos.x + 1, block_pos.y);
}
break;
case CTRL_B:
if (!check_overlap(block_pos.x - 1, block_pos.y)) {
move_block(block_pos.x - 1, block_pos.y);
}
break;
case CTRL_N:
if (!check_overlap(block_pos.x, block_pos.y + 1)) {
move_block(block_pos.x, block_pos.y + 1);
}
break;
/* ----- Rotate block ----- */
case 'a':
turn_block(RIGHT);
break;
case 's':
turn_block(LEFT);
break;
case ' ':
turn_block(RIGHT);
break;
}
}
/*!
* @brief Drop a block
*/
static void
drop_block(void)
{
if (!check_overlap(block_pos.x, block_pos.y + 1)) {
move_block(block_pos.x, block_pos.y + 1);
} else {
lock_block();
create_block();
update_flag.block = TRUE;
update_flag.next_block = TRUE;
}
}
/*!
* @brief Create block
*/
static void
create_block(void)
{
int i, j;
block_pos.y = 0;
block_pos.x = 4;
memcpy((void *) block, (const void *) block_list[next_blocks[next_idx]], sizeof(block));
next_blocks[next_idx] = (unsigned char) (rand() % N_BLOCK);
next_idx = (next_idx + 1) % LENGTHOF(next_blocks);
for (i = 0; i < BLOCK_HEIGHT; i++) {
for (j = 0; j < BLOCK_WIDTH; j++) {
/* Gameover if locked block is already exist on in initial position */
if (stage[i][j + 4] != 0) {
is_gameover = TRUE;
return;
}
field[i][j + 4] = block[i][j];
}
}
}
/*!
* @brief Change background color
* @param [in] color_nr Color number
*/
static void
change_background_color(int color_nr)
{
switch (color_nr) {
case SPACE:
tu_set_background(TU_DEFAULT_COLOR);
break;
case 1:
tu_set_background(TU_GRAY);
break;
case 2:
tu_set_background(TU_RED);
break;
case 3:
tu_set_background(TU_GREEN);
break;
case 4:
tu_set_background(TU_BLUE);
break;
case 5:
tu_set_background(TU_YELLOW);
break;
case 6:
tu_set_background(TU_MAGENTA);
break;
case 7:
tu_set_background(TU_CYAN);
break;
}
}
/*!
* @brief Check whether the block overlaps
* @param [in] x X-coordinate of base position
* @param [in] y Y-coordinate of base position
* @return Return 1, if block overlaps, otherwise return 0.
*/
static int
check_overlap(int x, int y)
{
int i, j;
for (i = 0; i < BLOCK_HEIGHT; i++) {
for (j = 0; j < BLOCK_WIDTH; j++) {
if (block[i][j] && stage[y + i][x + j] != 0) {
return TRUE;
}
}
}
return FALSE;
}
/*!
* @brief Move block
* @param [in] new_x New X-coordinate of block
* @param [in] new_y New Y-coordinate of block
*/
static void
move_block(int new_x, int new_y)
{
int i, j;
/* Delete block on old position */
for (i = 0; i < BLOCK_HEIGHT; i++) {
for (j = 0; j < BLOCK_WIDTH; j++) {
field[block_pos.y + i][block_pos.x + j] -= block[i][j];
}
}
/* Update block position */
block_pos.x = new_x;
block_pos.y = new_y;
/* Push block into new position */
for (i = 0; i < BLOCK_HEIGHT; i++) {
for (j = 0; j < BLOCK_WIDTH; j++) {
field[block_pos.y + i][block_pos.x + j] += block[i][j];
}
}
update_flag.block = TRUE;
}
/*!
* @brief Rotate block
* @param [in] direction Value which indicates right or left
* @return Return 0 if rotate is enable, otherwise return 1.
*/
static int
turn_block(Direction direction)
{
static unsigned char temp[BLOCK_HEIGHT][BLOCK_WIDTH];
int i, j;
memcpy((void *) temp, (const void *) block, sizeof(temp));
if (direction == RIGHT) { /* Right-handed rotation */
for (i = 0; i < BLOCK_HEIGHT; i++) {
for (j = 0; j < BLOCK_WIDTH; j++) {
block[i][j] = temp[(BLOCK_WIDTH - 1) - j][i];
}
}
} else { /* Left-handed rotation */
for (i = 0; i < BLOCK_HEIGHT; i++) {
for (j = 0; j < BLOCK_WIDTH; j++) {
block[i][j] = temp[j][(BLOCK_WIDTH - 1) - i];
}
}
}
/* If block is overlapped, return to the original. */
if (check_overlap(block_pos.x, block_pos.y)) {
memcpy((void *) block, (const void *) temp, sizeof(block));
return FALSE;
}
/* Delete old block and add new block */
for (i = 0; i < BLOCK_HEIGHT; i++) {
for (j = 0; j < BLOCK_WIDTH; j++) {
field[block_pos.y + i][block_pos.x + j] -= temp[i][j];
field[block_pos.y + i][block_pos.x + j] += block[i][j];
}
}
update_flag.block = TRUE;
return TRUE;
}
/*!
* @brief Fix block after landing
*
* Also check whether a single horizontal row are aligned.
*/
static void
lock_block(void)
{
/* Lock block */
memcpy((void *) stage, (const void *) field, sizeof(stage));
check_lines();
/* Update */
memcpy((void *) field, (const void *) stage, sizeof(field));
}
/*!
* @brief Check whether a single horizontal row are aligned
*
* If horizontal row are aligned, delete the row and drop upper blocks.
*/
static void
check_lines(void)
{
int comp;
int lines = 0;
for (;;) {
int i, j, k;
for (i = 0; i < STAGE_HEIGHT - 1; i++) {
comp = TRUE;
for (j = 1; j < STAGE_WIDTH - 1; j++) {
if (stage[i][j] == 0) {
comp = FALSE;
}
}
if (comp) break;
}
if (!comp) break;
lines++;
/* Delete rows */
for (j = 1; j < STAGE_WIDTH - 1; j++) {
stage[i][j] = 0;
}
/* Drop upper blocks */
for (j = i; j > 0; j--) {
for (k = 1; k < STAGE_WIDTH - 1; k++) {
stage[j][k] = stage[j - 1][k];
}
}
}
/* Add score depending on the number of simultaneously erase line */
switch (lines) {
case 1:
score += SCORE1;
update_flag.score = TRUE;
break;
case 2:
score += SCORE2;
update_flag.score = TRUE;
break;
case 3:
score += SCORE3;
update_flag.score = TRUE;
break;
case 4:
score += SCORE4;
update_flag.score = TRUE;
break;
}
}
/*!
* @brief Update screen
*/
static void
update_screen(void)
{
if (update_flag.block) {
print_field(field, FIELD_X);
update_flag.block = FALSE;
}
if (update_flag.next_block) {
print_next_blocks();
update_flag.next_block = FALSE;
}
if (update_flag.time) {
print_time(gametime);
update_flag.time = FALSE;
}
if (update_flag.score) {
print_score(score);
update_flag.score = FALSE;
}
tu_refresh();
}
/*!
* @brief Draw labels
*/
static void
print_labels(void)
{
tu_mvaddstr(TIME_Y - 1, TIME_X - 1, "time:");
tu_mvaddstr(SCORE_Y - 1, SCORE_X - 1, "score:");
print_score(0);
tu_mvaddstr(SCORE_Y + 2, SCORE_X - 1, "h : move left");
tu_mvaddstr(SCORE_Y + 3, SCORE_X - 1, "l : move right");
tu_mvaddstr(SCORE_Y + 4, SCORE_X - 1, "j : drop a block");
tu_mvaddstr(SCORE_Y + 5, SCORE_X - 1, "a : right-handed rotation");
tu_mvaddstr(SCORE_Y + 6, SCORE_X - 1, "s : left-handed rotation");
}
/*!
* @brief Draw wall
*/
static void
print_wall(void)
{
int i;
tu_mvaddstr(FIELD_Y - 1, 0, "xxxxx xxxxxxxxxxxxxxxx");
for (i = 0; i < STAGE_HEIGHT - 1; i++) {
tu_mvaddstr(i + FIELD_Y, 0, "x x x");
}
for (i = 1; i < (int) LENGTHOF(next_blocks); i++) {
tu_mvaddstr(NEXT_BLOCK_YS[i] - 2, NEXT_BLOCK_X - 1, "xxxxxxxxxx");
}
tu_mvaddstr(FIELD_Y + STAGE_HEIGHT - 1, 0, "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx");
}
/*!
* @brief Draw field
*
* @param [in] field Field data
* @param [in] x X-coordinate of the field
*/
static void
print_field(unsigned char field[STAGE_HEIGHT][STAGE_WIDTH], int x)
{
int i, j;
for (i = 0; i < STAGE_HEIGHT - 1; i++) {
tu_move(i + FIELD_Y, x + 1);
for (j = 1; j < STAGE_WIDTH - 1; j++) {
change_background_color(field[i][j]);
tu_addstr(" ");
}
}
tu_set_foreground(TU_DEFAULT_COLOR);
tu_set_background(TU_DEFAULT_COLOR);
}
/*!
* @brief Print next blocks
*/
static void
print_next_blocks(void)
{
int i, j, k, idx;
for (i = 0; i < (int) LENGTHOF(next_blocks); i++) {
idx = next_blocks[(next_idx + i) % LENGTHOF(next_blocks)];
for (j = 0; j < BLOCK_HEIGHT; j++) {
for (k = 0; k < BLOCK_WIDTH; k++) {
if (block_list[idx][j][k]) {
change_background_color(block_list[idx][j][k]);
} else {
tu_set_background(TU_DEFAULT_COLOR);
}
tu_mvaddstr(NEXT_BLOCK_YS[i] + j, NEXT_BLOCK_X + k * 2, " ");
}
}
}
tu_set_background(TU_DEFAULT_COLOR);
}
/*!
* @brief Draw player's score
* @param [in] x X-coordinate of score
* @param [in] y Y-coordinate of score
* @param [in] score Player's score
*/
static void
print_score(int _score)
{
tu_mvprintw(SCORE_Y, SCORE_X, "%5d", _score);
}
/*!
* @brief Draw elapsed time
* @param [in] time elapsed time
*/
static void
print_time(time_t time)
{
tu_mvprintw(TIME_Y, TIME_X, "%5lu", time);
}
/*!
* @brief Return mill second of current time (UTC)
* @return Mill second of current time
*/
static time_t
get_utc(void)
{
time_t sec;
long int msec;
#ifdef _MSC_VER
struct _timeb timeb;
_ftime_s(&timeb);
sec = timeb.time;
msec = timeb.millitm;
#elif defined(_POSIX_TIMERS)
struct timespec tp;
clock_gettime(CLOCK_REALTIME, &tp);
sec = tp.tv_sec;
msec = tp.tv_nsec / 10000000;
#else
struct timeval tv;
gettimeofday(&tv, 0);
sec = tv.tv_sec;
msec = tv.tv_usec / 1000;
#endif
return sec * 1000 + msec;
}
/*!
* @brief Signal handler for SIGINT
* @param [in] sig Signal number (unused variable)
*/
static void
sigint_handler(int __UNUSED__(sig))
{
tu_cleanup();
exit(EXIT_SUCCESS);
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* parse_manipulate_string.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: kankim <kankim@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/05/14 19:15:07 by kankim #+# #+# */
/* Updated: 2021/05/17 19:30:44 by kankim ### ########.fr */
/* */
/* ************************************************************************** */
#include "minishell.h"
void get_arg(char *dst, char *cmdline, int s, int e)
{
int i;
char c;
i = 0;
c = cmdline[s];
if (c == '\'')
{
while (s < e && cmdline[++s] != '\'')
dst[i++] = cmdline[s];
}
else if (c == '"')
{
while (s < e && cmdline[++s] != '"')
{
c = cmdline[s + 1];
if (cmdline[s] == '\\' && (c == '`' || c == '$' || c == '\\' || c == '"'))
dst[i++] = cmdline[++s];
else
dst[i++] = cmdline[s];
}
}
else
{
while (s < e)
{
c = cmdline[s + 1];
if (cmdline[s] == '\\' && (c == '`' || c == '$' || c == '\\' || c == '"'))
dst[i++] = cmdline[++s];
// else if (cmdline[s] != '\"' && cmdline[s] != '\'')
// dst[i++] = cmdline[s];
else
dst[i++] = cmdline[s];
++s;
}
}
}
// dst 문자열의 i인덱스에 src문자열 삽입
// src는 동적할당되어 들어오며 여기서 프리시켜줌
void insert_str(char **dst, char *src, int i)
{
char *tmp;
char *tmp2;
char *tmp3;
tmp = ft_strndup(*dst, i);
tmp2 = ft_strndup(*dst + i, ft_strlen(*dst + i));
tmp3 = ft_strjoin(tmp, src);
free(*dst);
free(src);
*dst = ft_strjoin(tmp3, tmp2);
free(tmp);
free(tmp2);
free(tmp3);
}
// str문자열의 s인덱스부터 e - 1까지 삭제
void remove_str(char **str, int s, int e)
{
char *tmp;
char *tmp2;
tmp = ft_strndup(*str, s);
tmp2 = ft_strndup(*str + e, ft_strlen(*str + e));
free(*str);
*str = ft_strjoin(tmp, tmp2);
free(tmp);
free(tmp2);
}
|
C
|
#include "../inc/libmx.h"
char **mx_strsplit(const char *s, char c) {
if (!s)
return NULL;
char **new_str = (char **)malloc(
(mx_count_words(s,c) + 1) * sizeof(char *));
unsigned int i = 0;
int count;
for (unsigned int j = 0; s[j]; j++) {
if (s[j] != c) {
count = mx_letters(&s[j], c);
new_str[i] = mx_strnew(count);
for (int k = 0; k < count; k++) {
new_str[i][k] = s[j];
j++;
}
i++;
}
}
new_str[i] = NULL;
return new_str;
}
|
C
|
/*===========================================================================*\
|
| Ninja Code Framework
|
| Copyright 2000-2001 Harry Denholm. All Rights Reserved.
|===========================================================================*
|
| 2D Vector support
|
| $Author: Harry Denholm $
| $Revision: 3 $
| $Date: 5/06/01 0:42 $
| $Archive: /base/vector2.h $
|
\*===========================================================================*/
#ifndef __NJFW_VECTOR2_
#define __NJFW_VECTOR2_
/*===========================================================================*\
| x,y 2D coorindate
\*===========================================================================*/
typedef struct sVector2
{
sFloat x,y;
// constructors
inline sVector2(void) { x = 0.0f; y = 0.0f; };
inline sVector2(const sFloat ix, const sFloat iy);
inline sVector2(const sInt32 ix, const sInt32 iy);
inline sVector2(const sVector2 &v);
// unary operators
inline sVector2 operator - (void) const;
// binary operators
inline sVector2 &operator = (const sVector2 &v);
inline sVector2 operator + (const sVector2 &v) const;
inline sVector2 operator - (const sVector2 &v) const;
inline sVector2 operator * (const sFloat s) const;
inline sVector2 operator / (const sFloat s) const;
// comparison operators
inline sBool operator == (const sVector2 &v) const;
inline sBool operator != (const sVector2 &v) const;
} sVector2;
const sVector2 vector2Zero(0.0f, 0.0f);
/*===========================================================================*\
| implimentation of sVector2 inline functions
\*===========================================================================*/
inline sVector2::sVector2(const sFloat ix, const sFloat iy)
{
x = ix;
y = iy;
}
inline sVector2::sVector2(const sInt32 ix, const sInt32 iy)
{
x = intToFloat(ix);
y = intToFloat(iy);
}
inline sVector2::sVector2(const sVector2 &v)
{
x = v.x;
y = v.y;
}
inline sVector2 sVector2::operator - (void) const
{
return sVector2(-x,-y);
}
inline sVector2 &sVector2::operator = (const sVector2 &v)
{
x = v.x;
y = v.y;
return *this;
}
inline sVector2 sVector2::operator + (const sVector2 &v) const
{
return sVector2( x+v.x, y+v.y );
}
inline sVector2 sVector2::operator - (const sVector2 &v) const
{
return sVector2( x-v.x, y-v.y );
}
inline sVector2 sVector2::operator * (const sFloat s) const
{
return sVector2( x*s, y*s );
}
inline sVector2 sVector2::operator / (const sFloat s) const
{
return sVector2( x/s, y/s );
}
inline sBool sVector2::operator == (const sVector2 &v) const
{
if(x!=v.x) return FALSE;
if(y!=v.y) return FALSE;
return TRUE;
}
inline sBool sVector2::operator != (const sVector2 &v) const
{
if(x!=v.x) return TRUE;
if(y!=v.y) return TRUE;
return FALSE;
}
/*===========================================================================*\
| another alias for a 2D x,y pair - a UV texture coordinate
\*===========================================================================*/
typedef struct sUVCoordinate
{
sFloat u,v;
// constructors
inline sUVCoordinate (void) { u = 0.0f; v = 0.0f; };
inline sUVCoordinate (const sFloat iu, const sFloat iv);
inline sUVCoordinate (const sInt32 iu, const sInt32 iv);
inline sUVCoordinate (const sUVCoordinate &c);
} sUVCoordinate;
const sUVCoordinate uvTopLeft(0.0f, 0.0f);
const sUVCoordinate uvTopRight(1.0f, 0.0f);
const sUVCoordinate uvBottomLeft(0.0f, 1.0f);
const sUVCoordinate uvBottomRight(1.0f, 1.0f);
/*===========================================================================*\
| implimentation of sUVCoordinate inline functions
\*===========================================================================*/
inline sUVCoordinate::sUVCoordinate(const sFloat iu, const sFloat iv)
{
u = iu;
v = iv;
}
inline sUVCoordinate::sUVCoordinate(const sInt32 iu, const sInt32 iv)
{
u = intToFloat(iu);
v = intToFloat(iv);
}
inline sUVCoordinate::sUVCoordinate(const sUVCoordinate &c)
{
u = c.u;
v = c.v;
}
#endif
|
C
|
// More Next chapter: https://viewsourcecode.org/snaptoken/kilo/05.aTextEditor.html
#pragma region includes
#define _DEFAULT_SOURCE
#define _BSD_SOURCE
#define _GNU_SOURCE
#include <ctype.h>
#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdarg.h>
#include <stdlib.h>
#include <string.h>
#include <sys/ioctl.h>
#include <sys/types.h>
#include <termios.h>
#include <time.h>
#include <unistd.h>
#pragma endregion
#pragma region defines
#define CTRL_KEY(k) ((k)&0x1f)
#define OCLEAR_SCREEN "\x1b[2J"
#define OCURSOR_HOME "\x1b[H"
#define KILO_VERSION "0.0.1"
#define KILO_TABSTOP 8
#define KILO_KILL_QUIT 3
enum editorKey
{
BACKSPACE = 127,
ARROW_LEFT = 1000,
ARROW_RIGHT,
ARROW_UP,
ARROW_DOWN,
DEL_KEY,
HOME_KEY,
END_KEY,
PAGE_UP,
PAGE_DOWN
};
#pragma endregion
#pragma region data
typedef struct erow
{
int size;
int rsize;
char *chars;
char *render;
} erow;
struct editorConfig
{
int rowoff;
int coloff;
int cx, cy;
int rx;
int screenRows;
int screenCols;
int numRows;
erow *row;
int dirty;
char *filename;
char statusmsg[80];
time_t statusmsg_time;
struct termios orig_termios;
};
struct editorConfig E;
#pragma endregion
#pragma region prototypes
void editorSetStatusMessage(const char *fmt, ...);
#pragma endregion
#pragma region terminal
void clearScreen()
{
write(STDOUT_FILENO, OCLEAR_SCREEN, 4);
write(STDOUT_FILENO, OCURSOR_HOME, 3);
}
void die(const char *s)
{
clearScreen();
perror(s);
exit(1);
}
void disableRowMode()
{
if (tcsetattr(STDIN_FILENO, TCSAFLUSH, &E.orig_termios) == -1)
die("tcsetattr");
}
void enableRawMode()
{
if (tcgetattr(STDIN_FILENO, &E.orig_termios) == -1)
die("tcgetattr");
atexit(disableRowMode);
struct termios raw = E.orig_termios;
raw.c_iflag &= ~(IXON | ICRNL | BRKINT | INPCK);
raw.c_oflag &= ~(OPOST);
raw.c_cflag |= (CS8);
raw.c_lflag &= ~(ECHO | ICANON | ISIG | IEXTEN);
raw.c_cc[VMIN] = 0;
raw.c_cc[VTIME] = 1;
if (tcsetattr(STDIN_FILENO, TCSAFLUSH, &raw) == -1)
die("tcgetattr");
}
int editorReadKey()
{
int nread;
char c;
while ((nread = read(STDIN_FILENO, &c, 1)) != 1)
{
if (nread == -1)
{
die("read");
}
}
if (c == '\x1b')
{
char seq[3];
if (read(STDIN_FILENO, &seq[0], 1) != 1)
return '\x1b';
if (read(STDIN_FILENO, &seq[1], 1) != 1)
return '\x1b';
if (seq[0] == '[')
{
// [0-9]~
if (seq[1] >= '0' && seq[1] <= '9')
{
if (read(STDIN_FILENO, &seq[2], 1) != 1)
return '\x1b';
if (seq[2] == '~')
{
switch (seq[1])
{
case '3':
return DEL_KEY;
case '5':
return PAGE_UP;
case '6':
return PAGE_DOWN;
case '1':
case '7':
return HOME_KEY;
case '4':
case '8':
return END_KEY;
}
}
return '\x1b';
}
else
{
switch (seq[1])
{
case 'A':
return ARROW_UP;
case 'B':
return ARROW_DOWN;
case 'C':
return ARROW_RIGHT;
case 'D':
return ARROW_LEFT;
case 'F':
return END_KEY;
case 'H':
return HOME_KEY;
}
}
}
else if (seq[0] == 'O')
{
switch (seq[1])
{
case 'H':
return HOME_KEY;
case 'F':
return END_KEY;
}
}
return '\x1b';
}
return c;
}
int getCursorPosition(int *rows, int *cols)
{
char buf[32];
unsigned int i = 0;
if (write(STDOUT_FILENO, "\x1b[6n", 4) != 4)
return -1;
while (i < sizeof(buf) - 1)
{
if (read(STDIN_FILENO, &buf[i], 1) != 1)
break;
if (buf[i] == 'R')
break;
i++;
}
buf[i] = '\0';
if (buf[0] != '\x1b' || buf[1] != '[')
return -1;
if (sscanf(&buf[2], "%d;%d", rows, cols) != 2)
return -1;
return 0;
}
int getWindowSize(int *rows, int *cols)
{
struct winsize ws;
if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &ws) == -1 || ws.ws_col == 0)
{
if (write(STDOUT_FILENO, "\x1b[999C\x1b[999B", 12) != 12)
return -1;
return getCursorPosition(rows, cols);
}
else
{
*cols = ws.ws_col;
*rows = ws.ws_row;
return 0;
}
}
#pragma endregion
#pragma region row operations
int editorCxToRx(erow *row, int cx)
{
int rx = 0;
for (int j = 0; j < cx; ++j)
{
if (row->chars[j] == '\t')
rx += (KILO_TABSTOP - 1) - (rx % KILO_TABSTOP);
rx++;
}
return rx;
}
void editorUpdateRow(erow *row)
{
int tabs = 0;
for (int j = 0; j < row->size; j++)
{
if (row->chars[j] == '\t')
tabs++;
}
free(row->render);
row->render = malloc(row->size + tabs * (KILO_TABSTOP - 1) + 1);
int idx = 0;
for (int j = 0; j < row->size; ++j)
{
if (row->chars[j] == '\t')
{
do
{
row->render[idx++] = ' ';
} while (idx % KILO_TABSTOP != 0);
}
else
{
row->render[idx++] = row->chars[j];
}
}
row->render[idx] = '\0';
row->rsize = idx;
}
void editorInsertRow(int at, char *s, size_t len)
{
if (at < 0 || at > E.numRows)
return;
E.row = realloc(E.row, sizeof(erow) * (E.numRows + 1));
memmove(&E.row[at + 1], &E.row[at], sizeof(erow) * (E.numRows - at));
E.row[at].size = len;
E.row[at].chars = malloc(len + 1);
memcpy(E.row[at].chars, s, len);
E.row[at].chars[len] = '\0';
E.row[at].rsize = 0;
E.row[at].render = NULL;
editorUpdateRow(&E.row[at]);
E.numRows++;
E.dirty++;
}
void editorFreeRow(erow *row)
{
free(row->chars);
free(row->render);
}
void editorDelRow(int at)
{
if (at < 0 || at >= E.numRows)
return;
erow *row = &E.row[at];
editorFreeRow(row);
memmove(&E.row[at], &E.row[at + 1], sizeof(erow) * (E.numRows - at - 1));
E.numRows--;
E.dirty++;
}
void editorRowInsertChar(erow *row, int at, char c)
{
if (at < 0 || at > row->size)
at = row->size;
row->chars = realloc(row->chars, row->size + 2);
memcpy(&row->chars[at + 1], &row->chars[at], row->size + 1 - at);
row->size++;
row->chars[at] = c;
editorUpdateRow(row);
E.dirty++;
}
void editorRowAppendString(erow *row, char *str, size_t len)
{
row->chars = realloc(row->chars, row->size + len + 1);
memcpy(&row->chars[row->size], str, len);
row->size += len;
row->chars[row->size] = '\0';
editorUpdateRow(row);
E.dirty++;
}
void editorRowDelChar(erow *row, int at)
{
if (at < 0 || at > row->size)
return;
memmove(&row->chars[at], &row->chars[at + 1], row->size - at);
row->size--;
E.dirty++;
editorUpdateRow(row);
}
#pragma endregion
#pragma region editor operations
void editorInsertChar(char c)
{
if (E.cy == E.numRows)
{
editorInsertRow(E.numRows, "", 0);
}
editorRowInsertChar(&E.row[E.cy], E.cx, c);
E.cx++;
}
void editorDelChar()
{
if (E.cy == E.numRows)
return;
if (E.cx == 0 && E.cy == 0)
return;
erow *row = &E.row[E.cy];
if (E.cx > 0)
{
editorRowDelChar(row, E.cx - 1);
E.cx--;
}
else
{
E.cx = E.row[E.cy - 1].size;
editorRowAppendString(&E.row[E.cy - 1], row->chars, row->size);
editorDelRow(E.cy);
E.cy--;
}
}
void editorInsertNewLine()
{
if (E.cx == 0)
{
editorInsertRow(E.cy, "", 0);
}
else
{
erow *row = &E.row[E.cy];
editorInsertRow(E.cy + 1, &row->chars[E.cx], row->size - E.cx);
row = &E.row[E.cy];
row->size = E.cx;
row->chars[E.cx] = '\0';
editorUpdateRow(row);
}
E.cy++;
E.cx = 0;
}
#pragma endregion
#pragma region file i / o
char *editorRowsToString(int *bufferlen)
{
int totallen = 0;
for (int j = 0; j < E.numRows; j++)
{
totallen += E.row[j].size + 1;
}
*bufferlen = totallen;
char *buffer = malloc(totallen);
char *p = buffer;
for (int j = 0; j < E.numRows; j++)
{
memcpy(p, E.row[j].chars, E.row[j].size);
p += E.row[j].size;
*p = '\n';
p++;
}
return buffer;
}
void editorOpen(char *filename)
{
free(E.filename);
E.filename = strdup(filename);
FILE *fp = fopen(filename, "r");
if (!fp)
die("fopen");
char *line = NULL;
size_t linecap = 0;
ssize_t linelen;
while ((linelen = getline(&line, &linecap, fp)) != -1)
{
while (linelen > 0 && (line[linelen - 1] == '\n' || line[linelen - 1] == '\r'))
linelen--;
editorInsertRow(E.numRows, line, linelen);
}
free(line);
fclose(fp);
E.dirty = 0;
}
void editorSave()
{
if (E.filename == NULL)
return;
int len;
char *buffer = editorRowsToString(&len);
int fd = open(E.filename, O_RDWR | O_CREAT, 0644);
if (fd != -1)
{
if (ftruncate(fd, len) != -1)
{
if (write(fd, buffer, len) == len)
{
close(fd);
free(buffer);
E.dirty = 0;
editorSetStatusMessage("%d bytes written to disk!", len);
return;
}
}
close(fd);
}
free(buffer);
editorSetStatusMessage("Can't save! I/O error: %s", strerror(errno));
}
#pragma endregion
#pragma region append buffer
struct abuf
{
char *b;
int len;
};
#define ABUF_INIT \
{ \
NULL, 0 \
}
void abAppend(struct abuf *ab, const char *s, int len)
{
char *new = realloc(ab->b, ab->len + len);
if (new == NULL)
return;
memcpy(&new[ab->len], s, len);
ab->b = new;
ab->len += len;
}
void abFree(struct abuf *ab)
{
free(ab->b);
}
#pragma endregion
#pragma region output
void editorScroll()
{
E.rx = 0;
if (E.cy < E.numRows)
{
E.rx = editorCxToRx(&E.row[E.cy], E.cx);
}
if (E.cy < E.rowoff)
{
E.rowoff = E.cy;
}
if (E.cy >= E.rowoff + E.screenRows)
{
E.rowoff = E.cy - E.screenRows + 1;
}
if (E.rx < E.coloff)
{
E.coloff = E.rx;
}
if (E.rx >= E.coloff + E.screenCols)
{
E.coloff = E.rx - E.screenCols + 1;
}
}
void editorDrawRows(struct abuf *ab)
{
for (int y = 0; y < E.screenRows; ++y)
{
int filerow = E.rowoff + y;
int filecol = E.coloff;
if (filerow >= E.numRows)
{
if (E.numRows == 0 && y == E.screenRows / 3)
{
char welcome[80];
int welcomelen = snprintf(welcome, sizeof(welcome), "Kilo editor -- version %s", KILO_VERSION);
if (welcomelen > E.screenCols)
welcomelen = E.screenCols;
int padding = (E.screenCols - welcomelen) / 2;
if (padding)
{
abAppend(ab, "~", 1);
padding--;
}
while (padding--)
{
abAppend(ab, " ", 1);
}
abAppend(ab, welcome, welcomelen);
}
else
abAppend(ab, "~", 1);
}
else
{
int len = E.row[filerow].rsize - filecol;
if (len > E.screenCols)
len = E.screenCols;
if (len > 0)
{
abAppend(ab, &E.row[filerow].render[filecol], len);
}
}
abAppend(ab, "\x1b[K", 3); // clear rest of line
abAppend(ab, "\r\n", 2);
}
}
void editorDrawStatusBar(struct abuf *ab)
{
abAppend(ab, "\x1b[7m", 4);
char status[80], rstatus[80];
int len = snprintf(status, sizeof(status), "%.20s - %d lines %s", E.filename ? E.filename : "[No Name]", E.numRows, E.dirty ? "(modified)" : "");
if (len > E.screenCols)
len = E.screenCols;
abAppend(ab, status, len);
int rlen = snprintf(rstatus, sizeof(rstatus), "%d / %d", E.cy + 1, E.numRows);
while (len < E.screenCols)
{
if (E.screenCols - len == rlen)
{
abAppend(ab, rstatus, rlen);
break;
}
abAppend(ab, " ", 1);
len++;
}
abAppend(ab, "\x1b[m", 3);
abAppend(ab, "\r\n", 2);
}
void editorDrawMessageBar(struct abuf *ab)
{
abAppend(ab, "\x1b[K", 3);
int msglen = strlen(E.statusmsg);
if (msglen > E.screenCols)
msglen = E.screenCols;
if (msglen && time(NULL) - E.statusmsg_time < 5)
abAppend(ab, E.statusmsg, msglen);
}
void editorRefreshScreen()
{
editorScroll();
struct abuf ab = ABUF_INIT;
abAppend(&ab, "\x1b[?25l", 6); // hide cursor
abAppend(&ab, "\x1b[H", 3); // move cursor to position default (1;1)
editorDrawRows(&ab);
editorDrawStatusBar(&ab);
editorDrawMessageBar(&ab);
char buf[32];
snprintf(buf, sizeof(buf), "\x1b[%d;%dH", (E.cy - E.rowoff) + 1, (E.rx - E.coloff) + 1); // move the cursor to E position
abAppend(&ab, buf, strlen(buf));
abAppend(&ab, "\x1b[?25h", 6); // show cursor
write(STDOUT_FILENO, ab.b, ab.len);
abFree(&ab);
}
void editorSetStatusMessage(const char *fmt, ...)
{
va_list ap;
va_start(ap, fmt);
vsnprintf(E.statusmsg, sizeof(E.statusmsg), fmt, ap);
va_end(ap);
E.statusmsg_time = time(NULL);
}
#pragma endregion
#pragma region input
void editorMoveCursor(int c)
{
erow *row = (E.cy >= E.numRows) ? NULL : &E.row[E.cy];
switch (c)
{
case ARROW_UP:
if (E.cy > 0)
E.cy--;
break;
case ARROW_LEFT:
if (E.cx > 0)
E.cx--;
else if (E.cy > 0)
{
E.cy--;
E.cx = E.row[E.cy].size;
}
break;
case ARROW_DOWN:
if (E.cy < E.numRows)
E.cy++;
break;
case ARROW_RIGHT:
if (row && E.cx < row->size)
E.cx++;
else if (row)
{
E.cx = 0;
E.cy++;
}
break;
}
row = (E.cy >= E.numRows) ? NULL : &E.row[E.cy];
int rowlen = row ? row->size : 0;
if (E.cx >= rowlen)
{
E.cx = rowlen;
}
}
void editorProcessKeypress()
{
static int quit_times = KILO_KILL_QUIT;
int c = editorReadKey();
switch (c)
{
case '\r':
editorInsertNewLine();
break;
case ARROW_UP:
case ARROW_LEFT:
case ARROW_DOWN:
case ARROW_RIGHT:
editorMoveCursor(c);
break;
case PAGE_DOWN:
case PAGE_UP:
{
if (c == PAGE_UP)
{
E.cy = E.rowoff;
}
else if (c == PAGE_DOWN)
{
E.cy = E.rowoff + E.screenRows - 1;
if (E.cy > E.numRows)
E.cy = E.numRows;
}
int times = E.screenRows;
while (times--)
{
editorMoveCursor(c == PAGE_UP ? ARROW_UP : ARROW_DOWN);
}
}
break;
case CTRL_KEY('q'):
if (E.dirty && quit_times > 0)
{
editorSetStatusMessage("WARNING!!! File has unsaved changes. "
"Press Ctrl-Q %d more times to quit.",
quit_times);
quit_times--;
return;
}
clearScreen();
exit(0);
break;
case CTRL_KEY('s'):
editorSave();
break;
case HOME_KEY:
E.cx = 0;
break;
case END_KEY:
if (E.cy < E.numRows)
E.cx = E.row[E.cx].size;
break;
case BACKSPACE:
case CTRL_KEY('h'):
case DEL_KEY:
if (c == DEL_KEY)
editorMoveCursor(ARROW_RIGHT);
editorDelChar();
break;
case CTRL_KEY('l'):
case '\x1b':
break;
default:
editorInsertChar(c);
break;
}
quit_times = KILO_KILL_QUIT;
}
#pragma endregion
#pragma region init
void initEditor()
{
E.rowoff = 0;
E.coloff = 0;
E.cx = 0;
E.cy = 0;
E.rx = 0;
E.numRows = 0;
E.row = NULL;
E.filename = NULL;
E.statusmsg[0] = '\0';
E.statusmsg_time = 0;
E.dirty = 0;
if (getWindowSize(&E.screenRows, &E.screenCols) == -1)
{
die("getWindowSize");
}
E.screenRows -= 2;
}
#pragma endregion
int main(int argc, char *argv[])
{
enableRawMode();
initEditor();
if (argc >= 2)
{
editorOpen(argv[1]);
}
editorSetStatusMessage("HELP: Ctrl-Q = quit, Ctrl-S = save");
while (1)
{
editorRefreshScreen();
editorProcessKeypress();
}
return 0;
}
|
C
|
#ifndef AST_TYPES_H
#define AST_TYPES_H
#include "../ast_declare.h"
#include "../sd_inttype.h"
struct ArrayType {
struct ASTNode super;
struct Type* element_type;
};
struct BasicType {
struct ASTNode super;
//these are alternatives,
//only one of these is != NULL
struct SimpleType* simple_type; //may be NULL
struct SubrType* subr_type; //may be NULL
};
struct PrimitiveType {
struct ASTNode super;
//PType means 'Primitive Type'
bool is_int_type;
bool is_float_type;
bool is_char_type;
bool is_bool_type;
enum INTTYPE int_type;
};
struct StructType {
struct ASTNode super;
char type_name[DEFAULT_STR_SIZE];
//the number of the type parameters
uint8_t count_type_params;
uint8_t* type_params;
};
struct SimpleType {
struct ASTNode super;
struct PrimitiveType* primitive_type; //may be NULL
struct StructType* struct_type; //may be NULL
};
struct SubrType {
struct ASTNode super;
struct Type* return_type;
struct Type** arg_types;
uint8_t count_arg_types;
bool has_side_effects;
bool throws;
};
struct Type {
struct ASTNode super;
//only one of these is != NULL
struct BasicType* m1;
struct TypeParam* m2;
struct ArrayType* m3;
};
struct TypeParam {
struct ASTNode super;
uint8_t index; /*type parameter index */
};
#endif
|
C
|
#include<stdio.h>
#include<pthread.h>
int cnt = 0;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
void *reproduce(void* arg)
{
while(1){
pthread_mutex_lock(&mutex);
printf("%s, lock \n", __func__);
cnt++;
//printf("%s, cnt = %d \n", __func__, cnt);
printf("A \n");
if(cnt)
{
pthread_cond_signal(&cond);
}
printf("%s, unlock \n", __func__);
pthread_mutex_unlock(&mutex);
sleep(1);
}
return NULL;
}
void *consumer(void* arg)
{
while(1){
pthread_mutex_lock(&mutex);
printf("%s, lock \n", __func__);
while(cnt <= 0)
{
pthread_cond_wait(&cond, &mutex);
}
cnt --;
printf("B \n");
//printf("%s, cnt = %d \n", __func__, cnt);
printf("%s, unlock \n", __func__);
pthread_mutex_unlock(&mutex);
sleep(1);
}
return NULL;
}
int main()
{
pthread_t conThread, repThread;
pthread_create(&conThread, NULL, consumer, NULL);
pthread_create(&repThread, NULL, reproduce, NULL);
pthread_join(conThread, NULL);
pthread_join(repThread, NULL);
pthread_cond_destroy(&cond);
return 0;
}
|
C
|
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
#define READ 0
#define WRITE 1
int main()
{
int pid1, pid2, pfd[2], fd, ret;
if (pipe(pfd) < 0)
{ // create a pipe
printf("Pipe creation error\n");
return 1;
}
// create child1 process
if ((pid1 = fork()) < 0)
{
printf("Fork error \n");
return 2;
}
if (pid1 == 0)
{ /* ----- child1 executes here -----*/
printf("<Child1> mypid<%d> ppid<%d>\n", getpid(), getppid());
close(pfd[READ]); // close read end of the pipe
dup2(pfd[WRITE], 1); // overwrite stdout with pipe
close(pfd[WRITE]); // close write end of the pipe
ret = execlp("cat", "cat" ,"/etc/passwd",NULL);
if (ret == -1)
{
perror("execlp");
exit(1);
}
exit(0);
} /* ------- end of child code -----------*/
else
{
wait(); // wait child1 to terminate
if ((pid2 = fork()) < 0)
{
printf("Fork error \n");
return 3;
}
if (pid2 == 0)
{
/* ----- child2 executes here -----*/
printf("<Child2> mypid<%d> ppid<%d>\n", getpid(), getppid());
close(pfd[WRITE]); // close write end of the pipe
dup2(pfd[READ], 0); // // overwrite stdin with pipe
close(pfd[READ]); // close read end of the pipe
ret = execlp("grep", "grep", "/var",NULL);
if (ret == -1)
{
perror("execlp");
exit(1);
}
exit(0);
}
else
{
/*--- Parent continues from here ------*/
close(pfd[READ]); // close read end of the pipe
close(pfd[WRITE]); // close write end of the pipe
wait(); // wait child2 to terminate
return 0;
}
}
}
|
C
|
//program using files
#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE *f1,*f2,*f3;
int num,i;
printf("contents of data file");
f1=fopen("DATA","w");
for(i=1;i<=30;i++)
{
scanf("%d",&num);
if(num==0)
break;
putw(num,f1);
}
fclose(f1);
f1=fopen("DATA","r");
f2=fopen("ODD","w");
f3=fopen("EVEN","w");
while((num=getw(f1))!=EOF)
{
if(num%2==0)
putw(num,f3);
else
putw(num,f2);
}
fclose(f1);
fclose(f2);
fclose(f3);
f2=fopen("ODD","r");
f3=fopen("EVEN","r");
printf("contents of odd file\n");
while((num=getw(f2))!=EOF)
printf("%4d\n",num);
printf("contents of odd file\n");
while((num=getw(f3))!=EOF)
printf("%4d\n",num);
fclose(f2);
fclose(f3);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#define MAX_SIZE 10000
#define SWAP(x, y, t) ( (t)=(x), (x)=(y), (y)=(t))
int list[MAX_SIZE];
int n;
void selection_sort(int list[], int n){
int i, j, least, temp;
for(i=0; i<n-1; i++){
least = i;
for(j=i+1; j<n; j++) //최솟값 탐색
if(list[j]<list[least]) least = j;
SWAP(list[i], list[least], temp);
}
}
void main(){
int i;
n= MAX_SIZE;
for(i=0; i<n; i++) // 난수 생성 및 출력
list[i] = rand()%n; // 난수 발생 범위 0~n-1
selection_sort(list, n); // 선택 정렬 호출
for(i=0; i<n; i++) // 정렬 결과 출력
printf("%d\n", list[i]);
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* check_args.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: ytuz <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2018/03/06 13:37:24 by ytuz #+# #+# */
/* Updated: 2018/03/06 15:57:42 by ytuz ### ########.fr */
/* */
/* ************************************************************************** */
#include "corewar.h"
static char check_first_four_bytes_corewar(char *file)
{
char first_four[4];
unsigned int *u_int_t;
char *char_t;
int fd;
char ret_status;
u_int_t = (unsigned int *)malloc(sizeof(unsigned int) * 1);
*u_int_t = COREWAR_EXEC_MAGIC;
char_t = (char*)u_int_t;
fd = open(file, O_RDONLY);
ret_status = 1;
if (fd == -1)
ret_status = 0;
if (ret_status)
{
read(fd, &first_four, 4);
if (first_four[0] != char_t[3] || first_four[1] != char_t[2] ||
first_four[2] != char_t[1] || first_four[3] != char_t[0])
ret_status = 0;
}
free(u_int_t);
return (ret_status);
}
static char check_file_corewar(char *file)
{
char *last_period;
last_period = ft_strrchr(file, '.');
if (ft_strequ(last_period, ".cor") == 0)
{
ft_error(file);
ft_error(": not a .cor file\n");
return (0);
}
if (check_first_four_bytes_corewar(file) == 0)
{
ft_error(file);
ft_error(": corrupt or inaccessible file\n");
return (0);
}
return (1);
}
static char print_usage_corewar(void)
{
ft_error("Usage:\t./corewar options (-n n1) champion1 (-n n2) champion2 ...\n");
ft_error("Options:\t-dump nbr_cycles:\tdump the core on STDOUT and exit after nbr_cycles\n");
ft_error("\t\t-n number:\t\toptional. set the number for the player\n");
return (0);
}
char check_args_corewar(int ac, char **av)
{
if (ac < 3)
return (print_usage_corewar());
av++;
while (*av)
{
if (**av == '-')
av += 2;
else
{
if (check_file_corewar(*av) == 0)
return (0);
av++;
}
}
return (1);
}
|
C
|
#include<stdio.h>
#include<stdlib.h>
struct node {
int num;
struct node *left, *right;
};
struct node *root = NULL;
int insert(int n)
{
struct node *temp = (struct node *)malloc(sizeof(struct node));
int h = 1;
temp->num = n;
temp->left = NULL;
temp->right = NULL;
if (root == NULL) {
root = temp;
printf("inserted %d\n", h);
return 0;
}
struct node *ptr = root, *prev = NULL;
while (ptr != NULL) {
h++;
if (ptr->num == n) {
printf("duplicate\n");
return 0;
} else if (ptr->num > n) {
prev = ptr;
ptr = ptr->left;
} else {
prev = ptr;
ptr = ptr->right;
}
}
if (prev->num > n) {
prev->left = temp;
} else {
prev->right = temp;
}
printf("inserted %d\n", h);
return 0;
}
int search(int n)
{
struct node *temp = root;
int h = 1;
while (temp != NULL) {
if (temp->num == n) {
printf("present %d\n", h);
return 1;
} else if (temp->num > n) {
temp = temp->left;
} else {
temp = temp->right;
}
h++;
}
printf("absent\n");
return 0;
}
int freeMemory(struct node *temp)
{
if (temp == NULL)
return 0;
freeMemory(temp->left);
freeMemory(temp->right);
free(temp);
return 0;
}
int main(int argc, char **argv)
{
if (argc < 2) {
printf("no file name given\n");
exit(0);
}
char *filename = argv[1];
// char filename[] = "1.txt"; //alt
FILE *fp;
char ch;
int num;
fp = fopen(filename, "r");
if (fp == NULL) {
printf("error");
exit(0);
}
while (fscanf(fp, "%c %d\n", &ch, &num) != EOF) {
if (ch == 'i') {
insert(num);
} else if (ch == 's') {
search(num);
} else {
printf("error");
exit(0);
}
}
fclose(fp);
freeMemory(root);
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#include "../common/constants.h"
#include "../topology/topology.h"
#include "dvtable.h"
//这个函数动态创建距离矢量表.
//距离矢量表包含n+1个条目, 其中n是这个节点的邻居数,剩下1个是这个节点本身.
//距离矢量表中的每个条目是一个dv_t结构,它包含一个源节点ID和一个有N个dv_entry_t结构的数组, 其中N是重叠网络中节点总数.
//每个dv_entry_t包含一个目的节点地址和从该源节点到该目的节点的链路代价.
//距离矢量表也在这个函数中初始化.从这个节点到其邻居的链路代价使用提取自topology.dat文件中的直接链路代价初始化.
//其他链路代价被初始化为INFINITE_COST.
//该函数返回动态创建的距离矢量表.
int nbrs;
dv_t *dvtable_create()
{
nbrs = topology_getNbrNum();
dv_t *dv = (dv_t *)malloc(sizeof(dv_t) * (nbrs+1));
int *nbrArr = topology_getNbrArray();
int *nodeArr = topology_getNodeArray();
for (int i = 0; i < nbrs; i++)
{
dv[i].nodeID = nbrArr[i];
for (int j = 0; j < topology_getNodeNum(); j ++){
dv[i].dvEntry[j].nodeID = nodeArr[j];
dv[i].dvEntry[j].cost = INFINITE_COST;
}
}
dv[nbrs].nodeID = topology_getMyNodeID();
for (int j = 0; j < topology_getNodeNum(); j ++){
dv[nbrs].dvEntry[j].nodeID = nodeArr[j];
if(dv[nbrs].nodeID == nodeArr[j])
dv[nbrs].dvEntry[j].cost = 0;
else
dv[nbrs].dvEntry[j].cost = topology_getCost(dv[nbrs].nodeID, nodeArr[j]);
}
free(nbrArr);
free(nodeArr);
return dv;
}
//这个函数删除距离矢量表.
//它释放所有为距离矢量表动态分配的内存.
void dvtable_destroy(dv_t* dvtable)
{
free(dvtable);
}
//这个函数设置距离矢量表中2个节点之间的链路代价.
//如果这2个节点在表中发现了,并且链路代价也被成功设置了,就返回1,否则返回-1.
int dvtable_setcost(dv_t* dvtable,int fromNodeID,int toNodeID, unsigned int cost)
{
return 0;
}
//这个函数返回距离矢量表中2个节点之间的链路代价.
//如果这2个节点在表中发现了,就返回链路代价,否则返回INFINITE_COST.
unsigned int dvtable_getcost(dv_t* dvtable, int fromNodeID, int toNodeID)
{
return 0;
}
//这个函数打印距离矢量表的内容.
void dvtable_print(dv_t* dvtable)
{
printf("--------------------------\n");
printf("| DV |");
for (int j = 0; j < topology_getNodeNum(); j++)
printf("%4d|", dvtable[0].dvEntry[j].nodeID);
printf("\n");
for (int i = 0; i <= nbrs; i++)
{
printf("|%4d|", dvtable[i].nodeID);
for (int j = 0; j < topology_getNodeNum(); j++)
{
printf("%4d|", dvtable[i].dvEntry[j].cost);
}
printf("\n");
}
printf("--------------------------\n");
}
|
C
|
/*
** EPITECH PROJECT, 2019
** set_back
** File description:
** set back
*/
#include <stdlib.h>
#include "my.h"
void init_sec_back2(back_t *back)
{
back->cond_back2[0] = 0.1;
back->cond_back2[1] = 0.5;
for (int i = 2; i < 14; i++)
back->cond_back2[i] = 0.02;
back->cond_back2[14] = 0.4;
back->cond_back2[15] = 0.8;
for (int i = 16; i < 33; i++)
back->cond_back2[i] = 0.02;
back->cond_back2[33] = 0.8;
back->i_back = 0;
}
void init_back(back_t *back)
{
back->t_back = sfTexture_createFromFile("assets/back1.png", NULL);
back->t_back2 = sfTexture_createFromFile("assets/back2.png", NULL);
back->t_back3 = sfTexture_createFromFile("assets/back3.png", NULL);
back->s_back = sfSprite_create();
sfSprite_setTexture(back->s_back, back->t_back, sfTrue);
back->p_back.x = 0;
back->p_back.y = 0;
sfSprite_setPosition(back->s_back, back->p_back);
back->r_back.top = 0;
back->r_back.left = 0;
back->r_back.width = 1920;
back->r_back.height = 1054;
sfSprite_setTextureRect(back->s_back, back->r_back);
back->c_back = sfClock_create();
back->sec_back = 0;
init_sec_back2(back);
}
void init_end(back_t *back)
{
back->t_end = sfTexture_createFromFile("assets/end.png", NULL);
back->p_end.x = 0;
back->p_end.y = 0;
back->r_end.top = 0;
back->r_end.left = 0;
back->r_end.width = 1920;
back->r_end.height = 1080;
back->s_end = sfSprite_create();
sfSprite_setTexture(back->s_end, back->t_end, sfTrue);
sfSprite_setPosition(back->s_end, back->p_end);
sfSprite_setTextureRect(back->s_back, back->r_back);
}
bool create_back(back_t *back)
{
back->cond_back2 = malloc(sizeof(float) * 35);
if (back->cond_back2 == NULL)
return (false);
init_back(back);
init_end(back);
return (true);
}
|
C
|
#include <stdio.h>
#include "lists.h"
/**
* insert_nodeint_at_index - inserts a new node at a given position
* @head: head
* @idx: idx
* @n: n
* Return: the address of the new node.
*/
listint_t *insert_nodeint_at_index(listint_t **head, unsigned int idx, int n)
{
listint_t *tmp_node = *head, *new_node;
unsigned int i = 1;
if (head == NULL)
return (NULL);
while (i < idx)
{
/*hasta que i llegue a ser 5 se seguirá iterando*/
/**tmp_node apuntara a la siguiente estructura hasta*/
/*que llegue a la posicion de idx*/
if (tmp_node != NULL)
tmp_node = tmp_node->next;
else
return (NULL);
i++;
}
new_node = malloc(sizeof(listint_t));
if (new_node == NULL)
return (NULL);
/*a new_node se le asignará el valor que se le da*/
/*en el main al llamar a la función*/
new_node->n = n;
/*En caso idx sea 0 a new_node se le asignara el valor al*/
/*que apunta *head que es el valor de 0*/
if (idx == 0)
{
new_node->next = *head;
*head = new_node;
}
else if (tmp_node)
{
/*En caso idx tenga un valor que no es cero a new_node que*/
/*anteriormente se le asigno un espacio con malloc que es una*/
/*estructura, esta tendra un puntero que apuntara al nodo*/
/*al que apunta tmp_node que es el nodo de 98, a este nodo*/
/*new_node asumira la posicion 5 y su puntero direccionara*/
/*a 98 y con tmp_nod->next = new_node, el puntero de 4 ahora*/
/*direccionara al nuevo puntero*/
new_node->next = tmp_node->next;
tmp_node->next = new_node;
}
return (new_node);
}
|
C
|
/* spi.c - SPI test source file */
/*
* Copyright (c) 2015 Intel Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <zephyr.h>
#if defined(CONFIG_STDOUT_CONSOLE)
#include <stdio.h>
#define PRINT printf
#else
#include <misc/printk.h>
#define PRINT printk
#endif
#define SYS_LOG_LEVEL SYS_LOG_LEVEL_INFO
#include <misc/sys_log.h>
#include <string.h>
#include <spi.h>
#define SPI_DRV_NAME "SPI_0"
#ifdef CONFIG_SPI_INTEL
#include <spi/spi_intel.h>
#if defined(CONFIG_SPI_1)
#define SPI_DRV_NAME "SPI_1"
#endif
#define SPI_SLAVE 0
#elif defined(CONFIG_SPI_DW)
#define SPI_MAX_CLK_FREQ_250KHZ 128
#define SPI_SLAVE 2
#elif defined(CONFIG_SPI_QMSI)
#define SPI_MAX_CLK_FREQ_250KHZ 128
#define SPI_SLAVE 1
#endif
unsigned char wbuf[16] = "Hello";
unsigned char rbuf[16] = {};
static void print_buf_hex(unsigned char *b, uint32_t len)
{
for (; len > 0; len--) {
PRINT("0x%x ", *(b++));
}
PRINT("\n");
}
struct spi_config spi_conf = {
.config = SPI_MODE_CPOL | SPI_MODE_CPHA | (8 << 4),
.max_sys_freq = SPI_MAX_CLK_FREQ_250KHZ,
};
static void _spi_show(struct spi_config *spi_conf)
{
SYS_LOG_INF("SPI Configuration:");
SYS_LOG_INF("\tbits per word: %u",
SPI_WORD_SIZE_GET(spi_conf->config));
SYS_LOG_INF("\tMode: %u", SPI_MODE(spi_conf->config));
SYS_LOG_INF("\tMax speed Hz: 0x%X", spi_conf->max_sys_freq);
}
void main(void)
{
struct device *spi;
SYS_LOG_INF("==== SPI Test Application ====");
spi = device_get_binding(SPI_DRV_NAME);
SYS_LOG_INF("Running...");
spi_configure(spi, &spi_conf);
spi_slave_select(spi, SPI_SLAVE);
_spi_show(&spi_conf);
SYS_LOG_INF("Writing...");
spi_write(spi, (uint8_t *) wbuf, 6);
SYS_LOG_INF("SPI sent: %s", wbuf);
print_buf_hex(rbuf, 6);
strcpy(wbuf, "So what then?");
spi_transceive(spi, wbuf, 14, rbuf, 16);
SYS_LOG_INF("SPI transceived: %s", rbuf);
print_buf_hex(rbuf, 6);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <locale.h>
#include <math.h>
#include <string.h>
int main()
{
setlocale(LC_ALL,"portuguese");
int numeros[4];
int soma;
for (int contador = 0; contador < 4; contador++){
printf("Digite um número da posição: [%d]",contador );
scanf("%d",&numeros[contador]);
soma = soma + numeros[contador];
}
printf("%d\n",soma );
return 0;
}
|
C
|
/**
* --------------------------------------------------------------------------------------------+
* @name Main example st7735 LCD driver
* --------------------------------------------------------------------------------------------+
* Copyright (C) 2020 Marian Hrinko.
* Written by Marian Hrinko (mato.hrinko@gmail.com)
*
* @author Marian Hrinko
* @datum 13.10.2020
* @update 21.06.2021
* @file main.c
* @version 2.0
* @tested AVR Atmega328
*
* @depend st7735.h
* --------------------------------------------------------------------------------------------+
* @descr Version 1.0 -> applicable for 1 display
* Version 2.0 -> applicable for more than 1 display
*/
#include "lib/st7735.h"
/**
* @desc Main function
*
* @param Void
*
* @return Void
*/
int main (void)
{
// start
uint8_t start = 30;
// end
uint8_t end = MAX_X - start;
// LCD 1 - init struct
// ----------------------------------------------------------
// Chip Select
struct signal cs = { .ddr = &DDRB, .port = &PORTB, .pin = 2 };
// Back Light
struct signal bl = { .ddr = &DDRB, .port = &PORTB, .pin = 1 };
// Data / Command
struct signal dc = { .ddr = &DDRB, .port = &PORTB, .pin = 0 };
// Reset
struct signal rs = { .ddr = &DDRD, .port = &PORTD, .pin = 7 };
// LCD struct
struct st7735 lcd1 = { .cs = &cs, .bl = &bl, .dc = &dc, .rs = &rs };
// LCD 2 - init struct
// ----------------------------------------------------------
// Chip Select
struct signal cs2 = { .ddr = &DDRD, .port = &PORTD, .pin = 0 };
// Back Light
struct signal bl2 = { .ddr = &DDRD, .port = &PORTD, .pin = 1 };
// Data / Command
struct signal dc2 = { .ddr = &DDRB, .port = &PORTB, .pin = 0 };
// Reset
struct signal rs2 = { .ddr = &DDRD, .port = &PORTD, .pin = 3 };
// LCD struct
struct st7735 lcd2 = { .cs = &cs2, .bl = &bl2, .dc = &dc2, .rs = &rs2 };
// LCD 1
// ----------------------------------------------------------
// init lcd 1
ST7735_Init (&lcd1);
// clear screen
ST7735_ClearScreen (&lcd1, BLACK);
// set position X, Y
ST7735_SetPosition (start + 5, 10);
// draw string
ST7735_DrawString (&lcd1, "Loading DATA ...", WHITE, X2);
// draw Loading
for (uint8_t i = start; i < end; i++) {
// draw rectangle
ST7735_DrawRectangle (&lcd1, start, i, 30, 40, RED);
}
// LCD 2
// ----------------------------------------------------------
// init lcd 2
ST7735_Init (&lcd2);
// clear screen
ST7735_ClearScreen (&lcd2, BLACK);
// set position X, Y
ST7735_SetPosition (17, 10);
// draw string
ST7735_DrawString (&lcd2, "ST7735 LCD 2", WHITE, X3);
// draw fast horizontal line
ST7735_DrawLineHorizontal (&lcd2, 5, MAX_X - 5, 27, WHITE);
// EXIT
// -------------------------------------------------
// return & exit
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <math.h>
#include "4_1_1.h"
BtNode NodeCreate(int data)
{
BtNode node = (BtNode)malloc(sizeof(struct BtNode_));
node->data = data;
node->left = NULL;
node->right = NULL;
return node;
}
void InorderTraverse(BtNode root) //LDR
{
if(root == NULL)
{
return;
}
InorderTraverse(root->left);
printf("%d\n", root->data);
InorderTraverse(root->right);
return;
}
int ChooseMax(int left, int right)
{
int maximum = left >= right ? left : right;
return maximum;
}
int FindHeight(BtNode root)
{
int height;
if(root == NULL){
height = -1;
return height;
}
printf("testing: node is %d\n", root->data);
height = ChooseMax(FindHeight(root->left), FindHeight(root->right)) + 1;
printf("testing: height is %d\n", height);
return height;
}
// bool IsLeftRightHightBalanced(BtNode node)
// {
// int absoulute = abs(FindHeight(node->left) - FindHeight(node->right));
// if(absoulute <= 1)
// {
// return true;
// }
// return false;
// }
bool IsBalancedTree(BtNode root)
{
if(root == NULL)
{
return true;
}
if(abs(FindHeight(root->left) - FindHeight(root->right)) > 1)
{
return false;
}
else
{
if(IsBalancedTree(root->left) && IsBalancedTree(root->right))
{
return true;
}
else
{
return false;
}
}
}
|
C
|
#ifndef ITEM_H
#define ITEM_H
/****************************************************************************************
*
* 1. Estruturas
*
*****************************************************************************************/
typedef struct hashtag {
char *text;
int count;
} *Item;
/****************************************************************************************
*
* 2. Prototipos
*
*****************************************************************************************/
/* Cria um novo Item */
extern Item NewItem(char*text, int size);
/* Elimino Item e liberto memoria associada */
extern void deleteItem(Item item);
/* Atualiza contador de um Item */
extern void updateCount(Item item);
/* Mostra o conteudo de um Item */
extern void showItem(Item x);
/* Devolve chave do item */
extern char* key(Item item);
/* Compara dois Items */
extern int cmpItem(const void *a, const void *b);
#endif
|
C
|
#include "stdio.h"
#include "conio.h"
int main(){
char c,lc;
int i = 1;
char s[256];
lc = getchar();
s[0] = lc;
while((c = getchar()) != '\n'){
if(c != lc){
s[i] = c;
i++;
lc = c;
}
}
s[i] = '\0';
printf("%s\n", s);
getch();
}
|
C
|
/* Author: hpain001
* Partner(s) Name:
* Lab Section:
* Assignment: Lab # Exercise #
* Exercise Description: [optional - include for your own benefit]
*
* I acknowledge all content contained herein, excluding template or example
* code, is my own original work.
*/
#include <avr/io.h>
#ifdef _SIMULATE_
#include "simAVRHeader.h"
#endif
int main(void) {
/* Insert DDR and PORT initializations */
DDRA = 0x00; PORTA = 0x0F;
DDRB = 0xFF; PORTB = 0x00; // PA0 1 means door open
DDRC = 0xFF; PORTC = 0x00; // PA1 means light is sensed
// PB0 is LED if PA0 && PA1 are true we turn on PB0
/* Insert your solution below */
unsigned char cntavail = 0x00;
unsigned char a = 0x00;
unsigned char b = 0x00;
unsigned char c = 0x00;
unsigned char d = 0x00;
while (1) {
a =( PINA & 0x08) >> 3;
b = (PINA & 0x04) >> 2;
c = (PINA & 0x02) >> 1;
d = PINA & 0x01;
cntavail = 4 - ( a + b + c + d);
PORTC = cntavail;
}
return 0;
}
|
C
|
/*calculae sum f number*/
#include<stdio.h>
#include<conio.h>
int main(int argc, char const *argv[])
{
int rem,sum=0,n;
printf("enter the num : ");
scanf("%d",&n);
while(n>0)
{
rem = n%10;
sum = sum +rem;
n = n/10;
}
printf("the sum of number is : %d", sum);
return 0;
}
|
C
|
#include<stdio.h>
int main()
{
char ch;
printf("enter a characher; ");
ch = getchar();
putchar(ch);
}
|
C
|
#ifndef _COCO_BASIC_
#error This program must be compiled for a CoCo Disk Basic environment.
#endif
#include "coco.h"
#include "stdarg.h"
#include "gfx.h"
word setupTimerIRQ();
word timerVal();
extern byte blackout[];
extern byte rgbColorValues[];
//MAME memory window Cmd+D
void wait() {
while(!inkey()) {
}
}
int abs(int a) {
if(a<0)
return -a;
return a;
}
void swap(int* a,int* b) {
int t=*a;
*a=*b;
*b=t;
}
void line(int x1,int y1,int x2,int y2,int n) {
int d,dx,dy;
int Ainc,Binc,Yinc;
int x,y;
if(x1 > x2) {
swap(&x1,&x2);
swap(&y1,&y2);
}
if(y2>y1)
Yinc=1;
else
Yinc=-1;
dx=x2-x1;
dy=abs(y2-y1);
d=2*dy-dx;
Ainc=2*(dy-dx);
Binc=2*dy;
x=x1;
y=y1;
setPixel(x,y,n);
for(x=x1+1; x<=x2; x++) {
if(d>=0) {
y+=Yinc;
d+=Ainc;
}
else {
d+=Binc;
}
setPixel(x,y,n);
}
}
//just change a pixel value so you know the program didn't crash, but you want an infinate loop
void burnAddr(byte* addr) {
unsigned short *p = 0x8000;
while(1) {
*p = timerVal();
// for(byte i=0; i<=255; i++) {
// *addr = i; //same color on both pixels
// }
}
}
//setup 256x192x16 color mode in C
void setup256c() {
byte *init0 = 0xFF90;
unsigned short *vmode = 0xFF98;
byte *MMU1 = 0xFFA4;
unsigned short *videoOffset = 0xFF9D;
*init0 = 0x44;
*vmode = 0x801A;
*videoOffset = 0xC000;
byte* addr = 0x8000;
for(int i=0; i<3; i++) {
*MMU1 = 0x30+(byte)i;
memset(0x8000,0,0x2000);
*addr = 255; //show the start of the memory block
}
burnAddr(0x8100);
}
int main() {
initCoCoSupport();
if(!isCoCo3) {
printf("You need to be running on a Coco 3.\n");
}
/*
setupTimerIRQ();
unsigned short* p = 0x400;
while(1) {
*p = timerVal();
//printf("TIMER=%u\n",timerVal());
}
byte pixel = 0x44;
byte color = 7;
printf("SETTING HIGH NIBBLE TO %X = %X\n",color,(pixel & 0x0F) | (color<<4));
printf("SETTING LOW NIBBLE TP %X = %X\n",color,(pixel & 0xF0) | color);
int x=0;
int y=0;
byte* addr = scrnBuffer + (y*bytesPerLine+(x>>1));
printf("X=%d Y=%d ADDR=%X\n",x,y,addr);
x++;
addr = scrnBuffer + (y*bytesPerLine+(x>>1));
printf("X=%d Y=%d ADDR=%X\n",x,y,addr);
x++;
addr = scrnBuffer + (y*bytesPerLine+(x>>1));
printf("X=%d Y=%d ADDR=%X\n",x,y,addr);
wait();
*/
mapColors(blackout);
setHighSpeed(1);
initGraphics();
clearScreen(MED_CYAN);
mapColors(rgbColorValues);
//clearScreen(5);
/*
int c=0;
for(int x=0; x<256; x++) {
csetPixel(x,2,(byte)c);
setPixel(x,4,x);
++c;
if(c==16)
c=0;
}
*/
setPixel(0,96,BLACK);
setPixel(1,96,BLACK+1);
setPixel(2,96,BLACK+2);
setPixel(3,96,BLACK+3);
setPixel(4,96,BLACK);
setPixel(5,96,BLACK+1);
setPixel(6,96,BLACK+2);
setPixel(7,96,BLACK+3);
setPixel(0, 96,BLACK);
setPixel(0, 97,BLACK+1);
setPixel(0, 98,BLACK+2);
setPixel(0, 99,BLACK+3);
setPixel(0,100,BLACK);
setPixel(0,101,BLACK+1);
setPixel(0,102,BLACK+2);
setPixel(0,103,BLACK+3);
hline(0,92,1,DARK_RED);
hline(0,93,2,DARK_RED);
hline(0,94,3,MED_RED);
hline(0,95,4,DARK_GREEN);
vline(1,97,1,RED);
vline(2,97,2,RED);
vline(3,97,3,RED);
vline(4,97,4,RED);
byte ballWidth=6;
byte ball1[] = {
0,0,3,3,0,0,
0,3,1,1,3,0,
3,1,1,1,1,3,
3,1,1,1,1,3,
0,3,1,1,3,0,
0,0,3,3,0,0
};
int i=0;
for(int y=0; y<ballWidth; y++) {
for(int x=0; x<ballWidth; x++) {
if(ball1[i]) {
setPixel(128+x,96+y,CYAN+ball1[i]-1);
}
++i;
}
}
bar(100,100,16,8);
rect(100,100,16,8);
/*
//draw small 2x2 pixel block in top left of screen
setPixel(0,0,MED_RED); //top left
setPixel(1,0,MED_GREEN);
setPixel(0,1,MED_YELLOW);
setPixel(1,1,LIGHT_GREY);
//draw small 2x2 pixel block in center of screen
setPixel(128,96,1);
setPixel(129,96,2);
setPixel(128,97,3);
setPixel(129,97,4);
setPixel(255,0,1); //top right corner
setPixel(0,191,1); //bottom left corner
setPixel(255,191,1); //bottom right corner
setPixel(9,10,1);
line(10,10,128,20,2);
setPixel(129,20,1);
setPixel(10,29,1);
hline(10,30,50,2);
setPixel(60,29,1);
setPixel(0,96,BLACK);
setPixel(1,96,BLACK+1);
setPixel(2,96,BLACK+2);
setPixel(3,96,BLACK+3);
*/
burnAddr(0x8003);
while(1) {}
return 0;
}
|
C
|
#include<stdio.h>
int main(){
int i,n;
scanf("%d",&n);
int start,start2,mid,mid2;
mid=mid2=3;
int star,star2;
star=star2=1;
start=2*n-2;
for(i=1;i<=n;i++){
start2=start;
while(start2>0){
printf(" ");
start2--;
}
star2=star;
while(star2>0){
printf("*");
mid2=mid;
while(mid2>0 && star!=1){
printf(" ");
mid2--;
}
star2--;
}
printf("\n");
star++;
start-=2;
}
start=2;
star-=2;
for(i=1;i<n;i++){
start2=start;
// printf("start2=(%d)",start2);
while(start2>0){
printf(" ");
start2--;
}
star2=star;
while(star2>0){
printf("*");
mid2=mid;
while(mid2>0 && star!=1){
printf(" ");
mid2--;
}
star2--;
}
printf("\n");
start+=2;
star--;
}
return 0;
}
|
C
|
#include <stdio.h>
#include <limits.h>
#include <time.h>
#include <stdlib.h>
#include "mapa.h"
#define TAM 12
int main(void) {
int i;
int chavedada;
Mapa *mapa1 = cria();
printf ("inserção sempre à esquerda:\n");
for (i=TAM-1;i>=0;i--) {
mapa1 = insere (mapa1, i, i);
}
debug_mostra_mapa(mapa1);
destroi(mapa1);
printf("escolhendo onde inserir -------------- \n");
mapa1 = cria();
while (1) {
printf ("inserir em mapa1 (digite -1 para terminar): ");
scanf ("%d", &chavedada);
if (chavedada==-1) break;
mapa1 = insere(mapa1, chavedada, chavedada);
debug_mostra_mapa(mapa1);
}
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
typedef unsigned long long int ulli;
typedef struct node{
double value; //8
ulli i, j; //8
struct node *r_node, *b_node; //16
}Node;
typedef struct head{
ulli pos;
struct head *next;
Node *node; //8
}Head;
typedef struct sparse_m{
ulli numc, numr; //16
Head *row, *col; //16
}Sparse_Matrix;
Head* InsertHead(Head *first, ulli pos)
{
Head *curr, *tmp;
curr = first;
tmp = malloc(sizeof(Head));
if(curr->pos > pos){
tmp->pos = curr->pos;
tmp->next = curr->next;
tmp->node = curr->node;
first->next = tmp;
first->pos = pos;
first->node = NULL;
return first;
}
while(curr->next !=NULL && curr->next->pos <= pos) curr = curr->next;
if(curr->pos == pos) return curr;
tmp->node = NULL;
tmp->pos = pos;
tmp->next = NULL;
if(curr->pos < pos){
tmp->next = curr->next;
curr->next = tmp;
return tmp;
}
if(curr->next == NULL){
curr->next = tmp;
return tmp;
}
}
void InsertFirstNode(Sparse_Matrix *first, ulli row, ulli col, double val)
{
Node *tmp = malloc(sizeof(Node));
tmp->i = row;
tmp->j = col;
tmp->value = val;
tmp->b_node = NULL;
tmp->r_node = NULL;
Head *c, *r;
first->col = malloc(sizeof(Head));
first->row = malloc(sizeof(Head));
c = first->col;
r = first->row;
c->pos = col;
c->node = tmp;
c->next = NULL;
r->pos = row;
r->node = tmp;
r->next = NULL;
}
Node *SearchNode(Node *node, ulli pos, int horizontal){
Node *curr;
curr = node;
if(horizontal){
while(curr->r_node != NULL && curr->r_node->j < pos) curr = curr->r_node;
}else{
while(curr->b_node != NULL && curr->b_node->i < pos) curr = curr->b_node;
}
return curr;
}
void InsertNode(Sparse_Matrix *first, ulli row, ulli col, double val)
{
Node *tmp = malloc(sizeof(Node));
tmp->i=row;
tmp->j=col;
tmp->value=val;
tmp->b_node = NULL;
tmp->r_node = NULL;
Head *c, *r;
c = InsertHead(first->col, col);
r = InsertHead(first->row, row);
Node *curr;
if(c->node == NULL) c->node = tmp;
else if(c->node->i > row){
tmp->b_node = c->node;
c->node = tmp;
}
else
{
curr = SearchNode(c->node, row, 0); //busca ao longo da coluna
if(curr->i > row){
tmp->b_node = curr->b_node;
tmp->i = curr->i;
tmp->j = curr->j;
tmp->r_node = curr->r_node;
tmp->value = curr->value;
curr->b_node= tmp;
curr->i = row;
curr->j = col;
curr->r_node= NULL;
curr->value = val;
}else if(curr->b_node == NULL){
curr->b_node = tmp;
}else{
tmp->b_node = curr->b_node;
curr->b_node = tmp;
}
}
if(r->node == NULL) r->node = tmp;
else if(r->node->j > col){
tmp->r_node = r->node;
r->node = tmp;
}
else
{
curr = SearchNode(r->node, col, 1); //busca ao longo da coluna
if(curr->j > col){
tmp->b_node = curr->b_node;
tmp->i = curr->i;
tmp->j = curr->j;
tmp->r_node = curr->r_node;
tmp->value = curr->value;
curr->b_node= NULL;
curr->i = row;
curr->j = col;
curr->r_node= tmp;
curr->value = val;
}else if(curr->j == col){
tmp->r_node = curr->r_node;
curr->r_node = tmp;
}else if(curr->r_node == NULL){
curr->r_node = tmp;
}
}
}
void PrintMatrix(Sparse_Matrix *first)
{
if(first == NULL){
printf("ERRO\n\n");
return;
}
ulli i, j, c, r;
c = first->numc;
r = first->numr;
Head *row = first->row;
Node *node;
for(i=0; i<r; i++){
if(row != NULL) node = row->node;
printf("[");
for(j=0; j<c; j++){
if(node->i == i && node->j == j)
{
printf("%0.lf ", node->value);
if(node->r_node != NULL) node = node->r_node;
}
else printf("0 ");
}
if(row != NULL && row->pos == i) row = row->next;
printf("]\n");
}
printf("\n");
}
void ReadMatrix(ulli nums, Sparse_Matrix *first)
{
ulli i, r, c;
double val;
Sparse_Matrix *tmp = first;
for(i=0; i<nums; i++)
{
scanf("%llu %llu %lf", &r, &c, &val);
if(i==0) InsertFirstNode(tmp, r, c, val);
else InsertNode(tmp, r, c, val);
}
}
double DotProd(Head *A, Head *B, ulli k){
double sum = 0;
ulli i;
Node *nodeA, *nodeB;
nodeA = A->node;
nodeB = B->node;
for(i = 0; i < k; i++){
if(nodeA->j == nodeB->i && nodeB->i == i)
sum += nodeA->value * nodeB->value;
if(nodeA->r_node && nodeA->j <= i) nodeA = nodeA->r_node;
if(nodeB->b_node && nodeB->i <= i) nodeB = nodeB->b_node;
}
return sum;
}
Sparse_Matrix * MultMatrix(Sparse_Matrix *A, Sparse_Matrix *B){
if(A->numc != B->numr) {
return NULL;
}
Sparse_Matrix *M = malloc(sizeof(Sparse_Matrix));
ulli i, j, r, c, k;
r = A->numr;
c = B->numc;
k = A->numc;
double sum;
M->numc = c;
M->numr = r;
M->col = NULL;
M->row = NULL;
Head *row = A->row;
Head *col = B->col;
for (i = 0; i < r; i++) {
if(row->pos == i){
for (j = 0; j < c; j++) {
if(col->pos == j){
sum = DotProd(row, col, k);
if(M->col == NULL && M->row == NULL && sum != 0) InsertFirstNode(M, i, j, sum);
else if(sum != 0) InsertNode(M, i, j, sum);
sum = 0;
if(col->next != NULL) col = col->next;
}
}
col = B->col;
if(row->next != NULL) row = row->next;
}
}
return M;
}
void freeMatrix(Sparse_Matrix *A){
if(!A) return;
Head *c, *r, *tmpr, *tmpc;
Node *tmp, *curr;
c = A->col;
r = A->row;
tmp = r->node;
curr = r->node;
while(r){
while(curr){
tmp = curr->r_node;
free(curr);
curr = tmp;
}
tmpr = r->next;
free(r);
r = tmpr;
if(r) curr = r->node;
}
while(c){
tmpc = c->next;
free(c);
c = tmpc;
}
}
int main()
{
Sparse_Matrix *A, *B, *M;
B = malloc(sizeof(Sparse_Matrix));
A = malloc(sizeof(Sparse_Matrix));
ulli NA, NB;
char op;
A->row = NULL;
A->col = NULL;
B->row = NULL;
B->col = NULL;
scanf("%llu %llu %llu %llu %llu %llu", &A->numr, &A->numc, &NA, &B->numr, &B->numc, &NB);
//printf("%llu %llu %llu %llu %llu %llu\n", A->numr, A->numc, NA, B->numr, B->numc, NB);
ReadMatrix(NA, A);
ReadMatrix(NB, B);
M = MultMatrix(A,B);
scanf("\n%c", &op);
while(op!='S'){
if(op == 'A') PrintMatrix(A);
else if(op == 'B') PrintMatrix(B);
else if(op == 'M') PrintMatrix(M);
scanf("\n%c", &op);
}
freeMatrix(A);
freeMatrix(B);
freeMatrix(M);
free(A);
free(B);
free(M);
return 0;
}
|
C
|
#include <stdio.h>
#include <math.h>
#include <string.h>
#include "misc.h"
bool is_triangle_num(int num)
{
int m;
m = sqrt(1+8*num);
if(m>=3 && (m %2 == 1) && (m*m == (1+8*num)))
return TRUE;
else
return FALSE;
}
int main()
{
FILE *stream; int ch; int n, cnt=0;
char tmp[20],tmp1; int sum=0;
stream = fopen("./files/words.txt","r");
if(stream == NULL)
{
printf("file open error\n");
return 0;
}
fseek(stream, 0, SEEK_SET);
n = 0;
tmp[0]='\0';
do {
ch = fgetc (stream);
if (ch== 44 || ch== EOF)
{
tmp[n]='\0';
printf("%s - %d\n", tmp, sum);
if(is_triangle_num(sum))
cnt++;
n=0;
tmp[0]='\0';
sum = 0;
}
else if (ch != 34)
{
tmp[n++] = (char)ch;
sum += ch - 'A' + 1;
}
} while (ch != EOF);
printf("Total cnt: %d\n", cnt);
fclose(stream);
return 1;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define SIZE 10
typedef struct stk{
int top; //Will be incremented everytime an element is inserted, initialized to -1
//to show that the list is empty
char elem [64][SIZE];
}Stack;
void initialize(Stack *ptr);
void insert(Stack *ptr, char str[]);
void deleteElem (Stack *ptr);
void display(Stack ptr);
char* get(Stack *ptr);
int main (void)
{
Stack s;
char* catcher;
initialize (&s);
insert(&s, "Ex1");
insert(&s, "Ex2");
insert(&s, "Ex3");
//deleteElem(&s);
display(s);
catcher = get(&s);
printf("\n");
display(s);
printf("\n");
//Two ways to print a string but I opted to use %s
printf("Returned string: %s", get(&s));
//puts(get(&s));
free(catcher); //free the catcher after it is used to put the borrowed memory back into the heap
return 0;
}
void initialize (Stack *ptr)
{
ptr->top = 0;
}
void insert(Stack *ptr, char str[])
{
if(ptr->top < SIZE){
strcpy(ptr->elem[ptr->top], str);
ptr->top++;
}
}
//Normal way to delete is to just decrement top
void deleteElem (Stack *ptr)
{
ptr->top--;
}
void display(Stack ptr)
{
int ctr;
for(ctr = 0; ctr < ptr.top; ctr++){
printf("[%d]", ctr);
puts(ptr.elem[ctr]);
}
}
//Another way to delete
//This function will get the string at the top of stack and return it
//to the calling function
char* get (Stack *ptr)
{
char *str = ptr->elem[ptr->top];
char *ret = (char*)malloc(strlen(str)); //allocate space for the string to be returned
strcpy(ret, str); //copy the string to the variable to be returned
ptr->top--; //decrement to "delete" the element
return ret;
}
|
C
|
// Kenny Jin jjin59@wisc.edu
// Ying Zhang yzhang865@wisc.edu
#include "537malloc.h"
// In addition to actually allocating the memory by calling malloc(),
// this function will record a tuple (addri, leni), for the memory that you allocate in the heap.
void *malloc537(size_t size){
void *ptr;
if (size == 0) {
fprintf(stderr, "%s\n", "Memory size is 0.");
//return NULL;
}
ptr = malloc(size);
if (ptr == NULL) {
return NULL;
}
NodeList *overlapped = getOverlappedNodes(rangeTree.root, ptr, size);
// If the new malloc does not use the previously freed regions
// Just insert the node to the tree
if (overlapped -> num_nodes == 0) {
destroyNodeList(overlapped);
rangeTree.root = recordTuple(rangeTree.root, ptr, size, false); // Insertion
return ptr;
}
// Sanity check
// All the overlapped node should be freed, otherwise there is an error
for (int i = 0; i < overlapped -> num_nodes; i++) {
if (!overlapped -> nodeArray[i] -> freed) {
fprintf(stderr, "%s\n", "Sanity check failed, the overlapped node is not freed");
exit(-1);
}
}
void * firstNodeStartAddr = overlapped -> nodeArray[0] -> addr;
// Remove all the overlapped freed nodes
for (int i = 0; i < overlapped -> num_nodes; i++) {
rangeTree.root = removeTuple(overlapped -> nodeArray[i]); // Deletion
//destroyNode(overlapped -> nodeArray[i]);
}
destroyNodeList(overlapped);
// If the ptr is in the middle of a freed block,
// we need to add the first half of the freed block back to tree
if (firstNodeStartAddr < ptr) {
rangeTree.root = recordTuple(rangeTree.root, firstNodeStartAddr, ptr - firstNodeStartAddr, true);
}
rangeTree.root = recordTuple(rangeTree.root, ptr, size, false); // Insertion
return ptr;
}
// This function will first check to make sure that freeing the memory specified by ptr makes sense,
// then will call free() to do the actual free. Some of the error conditions are checked
void free537(void *ptr) {
if (ptr == NULL) {
fprintf(stderr, "%s\n", "Trying to free NULL pointer");
exit(-1);
}
Node *node = getNode(rangeTree.root, ptr);
// Trying to free memory that has not been allocated with malloc537().
if (!addrRangeInTree(node)) {
fprintf(stderr, "The memory address %p has not been allocated with malloc537().\n", ptr);
exit(-1);
}
// Freeing memory that is not the first byte of the range of memory that was allocated.
if (!startAddrInTree(node, ptr)) {
fprintf(stderr, "The memory address %p is not the first byte of the range of memory that was allocated.\n", ptr);
exit(-1);
}
// Freeing memory that was previously freed (double free).
// How to deal with freed memory address is tricky
if (addrRangeFreed(node)) {
fprintf(stderr, "The memory address %p was previously freed.\n", ptr);
exit(-1);
}
node -> freed = true;
free(ptr);
}
// If ptr is NULL,then this follows the specification of malloc537() above.
// If size is zero and ptr is not NULL,then this follows the specification
// of free537() above. Otherwise, in addition to changing the memory allocation
// by calling realloc(), this function will first check to see if there was a
// tuple for the (addr = ptr, and removes that tuple, then adds a new one where
// addr is the return value from realloc() and len is size
void *realloc537(void *ptr, size_t size){
void *newptr;
if (ptr == NULL) {
newptr = malloc537(size);
return newptr;
}
else if (size == 0) {
free537(ptr);
return NULL;
}
Node *node = getNode(rangeTree.root, ptr);
// Freeing memory that has not been allocated with malloc537().
if (!addrRangeInTree(node)) {
fprintf(stderr, "The memory address %p has not been allocated with malloc537().\n", ptr);
exit(-1);
}
// Freeing memory that is not the first byte of the range of memory that was allocated.
if (!startAddrInTree(node, ptr)) {
fprintf(stderr, "The memory address %p is not the first byte of the range of memory that was allocated.\n", ptr);
exit(-1);
}
// Freeing memory that was previously freed (double free).
// How to deal with freed memory address is tricky
if (addrRangeFreed(node)) {
fprintf(stderr, "The memory address %p was previously freed.\n", ptr);
exit(-1);
}
rangeTree.root = removeTuple(node);
// if ((newptr = realloc(ptr, size)) == NULL) {
// fprintf(stderr, "%s\n", "Failed to reallocate memory.");
// exit(-1);
// }
newptr = realloc(ptr, size);
if (newptr == NULL) {
return NULL;
}
NodeList *overlapped = getOverlappedNodes(rangeTree.root, newptr, size);
// If the new malloc does not use the previously freed regions
// Just insert the node to the tree
if (overlapped -> num_nodes == 0) {
rangeTree.root = recordTuple(rangeTree.root, newptr, size, false); // Insertion
destroyNodeList(overlapped);
return newptr;
}
// Sanity check
// All the overlapped node should be freed, otherwise there is an error
for (int i = 0; i < overlapped -> num_nodes; i++) {
if (!overlapped -> nodeArray[i] -> freed) {
fprintf(stderr, "%s\n", "Sanity check failed, the overlapped node is not freed");
exit(-1);
}
}
void * firstNodeStartAddr = overlapped -> nodeArray[0] -> addr;
// Remove all the overlapped freed nodes
for (int i = 0; i < overlapped -> num_nodes; i++) {
rangeTree.root = removeTuple(overlapped -> nodeArray[i]); // Deletion
//destroyNode(overlapped -> nodeArray[i]);
}
destroyNodeList(overlapped);
// If the ptr is in the middle of a freed block,
// we need to add the first half of the freed block back to tree
if (firstNodeStartAddr < newptr) {
rangeTree.root = recordTuple(rangeTree.root, firstNodeStartAddr, newptr - firstNodeStartAddr, true);
}
rangeTree.root = recordTuple(rangeTree.root, newptr, size, false);
return newptr;
}
// This function checks to see the address range specified by address ptr and length size
// are fully within a range allocated by malloc537() and memory not yet freed by free537().
// When an error is detected, then print out a detailed and informative error message and
// exit the program (with a -1 status).
void memcheck537(void *ptr, size_t size){
NodeList *overlapped = getOverlappedNodes(rangeTree.root, ptr, size);
if (overlapped -> num_nodes != 1) {
fprintf(stderr, "the address range specified by address %p and length %zu are not fully within a range allocated by malloc537().\n", ptr, size);
exit(-1);
}
Node *node = overlapped -> nodeArray[0];
destroyNodeList(overlapped);
if ((node -> addr) > ptr || ((node -> addr) + (node -> len)) < (ptr + size)) {
fprintf(stderr, "the address range specified by address %p and length %zu are not fully within a range allocated by malloc537().\n", ptr, size);
exit(-1);
}
if (addrRangeFreed(node)) {
fprintf(stderr, "the address range specified by address %p and length %zu are already freed.\n", ptr, size);
exit(-1);
}
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
int main(){
int a, d, m, n;
scanf("%d", &n);
a = n/365;
m = n%365/30;
d = n%365%30;
printf("%d ano(s)\n%d mes(es)\n%d dia(s)\n", a,m,d);
return 0;
}
|
C
|
/*
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_NUM_INTS 13
#define BUFFER_SIZE 128
int check_number(char *input)
{
// checks the number to make sure its a int.
// returns 0 for a good int.
// returns 0 for a bad entry
char alphabet[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
if (atoi(input) != 0)
{
// checking to see if atoi does not have errors.
return 0;
}
else if (atoi(input)==0 && (input == "0"))
{
// checking whether the number is actually 0
return 0;
}
else if (strspn(input,alphabet)>0)
{
printf("I am very dissapointed in you. Letters cannot be added together. Please try again. \n");
// there are letters in the input
return 1;
}
else if (strsp(input,".")>0)
{
// you probably gave me a float
printf("\nIs this a float? Were you even listening to me? I told you to give me INTEGERS. INTEGERS you fool are WHOLE NUMBERS.\n");
return 1;
}
else
{
printf("\nI dont know what to say except... \n ... \n...\n...\n WRONG INPUT. I ADD NUMBERS NOT WHATEVER THIS IS.\n");
return 1;
}
}
int sum_num(int num_num, int* array)
{
// sums all the numbers in the 13 long array.
int sum = 0;
int *s = ∑
for (int i =0; i < num_num;i++)
{
*s = sum + array[i];
}
return sum;
}
int main()
{
int num_nums = 0; // number of numbers
int *num_nums_p = &num_nums; //pointer for num nums.
char name[20];
char answer[20];
char current_val[BUFFER_SIZE];
int numbers[MAX_NUM_INTS];
int *nums = numbers;
// beginning of game interface.
printf("Hello. What is your name?\n");
fgets(name,20,stdin);
printf("\nNice to meet you %s I am Adder. Would you like to play a game?\n",name);
fgets(answer,20,stdin);
printf("\nWell. I dont really care what you want.\n I am an Adder. Type in up to %d integers one at a time, push Control-D when you are done.\n \n And I will (gasp) add them together.\n\n",MAX_NUM_INTS);
while(num_nums < MAX_NUM_INTS && current_val != "d")
{
fgets(current_val, BUFFER_SIZE,stdin);
while( check_number(current_val)!=0 && current_val != "stahp")
{
printf("\nTry Again.\n");
fgets(current_val,BUFFER_SIZE,stdin);
}
nums[num_nums]= atoi(current_val);
*num_nums_p= num_nums+1;
}
if (num_nums==(MAX_NUM_INTS-1))
{
printf("\nI only take %d integers. Remember?\n",MAX_NUM_INTS);
}
printf("\nAnyway... all those numbers added together equal....\n drumroll please \n %d \n Your Welcome.\n Bye Bye \n", sum_num(num_nums,nums));
}
|
C
|
/*
ϰ8-7 ַ 20 ֣
Ҫд5ַС˳
ʽ
Ϊɿոָ5ǿַÿַոƱзȿհַС80
ʽ
¸ʽĽ
After sorted:
ÿһַ
red yellow blue green white
After sorted:
blue
green
red
white
yellow
*/
#include <stdio.h>
#include <math.h>
#include <string.h>
#include <stdlib.h>
int main() {
const int SIZE = 5;
char c[SIZE][80];
char *p[SIZE];
int i, j;
for (i = 0; i < SIZE; i++) {
scanf("%79s", c[i]);
p[i] = c[i];
}
for (i = 0; i < SIZE; i++) {
for (j = i; j < SIZE; j++) {
if (strcmp(p[i], p[j]) > 0) {
char *t = p[i];
p[i] = p[j];
p[j] = t;
}
}
}
printf("After sorted:\n");
for (i = 0; i < SIZE; i++) {
printf("%s\n", p[i]);
}
return 0;
}
|
C
|
// program 14.2 Finding occurrences of one wide character string in another
#include <stdio.h>
#include <wchar.h>
#include <wctype.h>
#define TEXT_SIZE 100
#define SUBSTR_SIZE 40
wchar_t *wstr_towupper(wchar_t *wstr, size_t size);
int main(void)
{
wchar_t text[TEXT_SIZE];
wchar_t substr[SUBSTR_SIZE];
wprintf_s(L"Enter the string to be searched (less than %d charcaters):\n", TEXT_SIZE);
fgetws(text, TEXT_SIZE, stdin);
wprintf_s(L"\nEnter the string sought (less than %d characters):\n", SUBSTR_SIZE);
fgetws(substr, SUBSTR_SIZE, stdin);
int textlen = wcsnlen_s(text, sizeof(text)/sizeof(wchar_t));
int substrlen = wcsnlen_s(substr, sizeof(substr)/sizeof(wchar_t));
text[--textlen] = L'\0';
substr[--substrlen] = L'\0';
fwprintf_s(stdout, L"\nFirst string entered:\n%ls\n", text);
fwprintf_s(substr, L"Second string entered:\n%ls\n", substr);
wstr_towupper(text, sizeof(text)/sizeof(wchar_t));
wstr_towupper(substr, sizeof(substr)/sizeof(wchar_t));
wchar_t *pwstr = text;
int count = 0;
while((pwstr < text + textlen - substrlen) && (pwstr = wcsstr(pwstr, substr)))
{
++count;
pwstr += substrlen;
wprintf_s(L"The second string %ls found in the fiest%ls", count ? L"was" : L"was not", count ? L" " : L".\n");
if(count)
wprintf_s(L"%d times.\n", count);
return 0;
}
}
wchar_t *wstr_towupper(wchar_t *wstr, size_t size)
{
for(size_t i = 0; i < wcsnlen(wstr, size); ++i)
wstr[i] = towupper(wstr[i]);
return wstr;
}
|
C
|
#include<stdio.h>
main()
{
int arr[5];
int i,t,r,sum,s,c;
printf("Enter the elements");
for(i=0;i<5;i++)
{
scanf("%d",&arr[i]);
}
for(i=0;i<5;i++)
{
t=arr[i];
sum=0;
c=0;
s=0;
while(arr[i]>0)
{
r=arr[i]%10;
arr[i]=arr[i]/10;
c++;
s=r*c;
sum=sum+s;
}
if(sum%11==0 && c==10)
printf("%d\t",t);
}
}
|
C
|
/*
* stm32f407xx_usart.h
*
* Created on: 8 nov. 2020
* Author: javi
*/
#ifndef INC_STM32F407XX_USART_H_
#define INC_STM32F407XX_USART_H_
#include "stm32f407xx.h"
/*
* Configuration structure for USARTx peripheral
*/
typedef struct {
uint8_t USART_Mode; /* <! Possible values from @USART_Mode >*/
uint32_t USART_Baud; /* <! Possible values from @USART_Baud>*/
uint8_t USART_StopBits; /* <! Possible values from @USART_StopBits >*/
uint8_t USART_WordLength; /* <! Possible values from @USART_WordLength >*/
uint8_t USART_ParityControl; /* <! Possible values from @USART_ParityControl >*/
uint8_t USART_HWFlowControl; /* <! Possible values from @USART_HWFlowControl >*/
}USART_Config_t;
/*
* Handler structure for for USARTx peripheral
*/
typedef struct {
USART_RegDef_t *pUSARTx; /* <! This holds the base address of USARTx peripheral >*/
USART_Config_t USART_Config; /* <! This holds USARTx configuration settings >*/
uint8_t *pTxBuffer; /* <! To store the app. Tx buffer address >*/
uint8_t *pRxBuffer; /* <! To store the app. Rx buffer address >*/
uint32_t TxLen; /* <! To store the Tx buffer len >*/
uint32_t RxLen; /* <! To store the Rx buffer len >*/
uint8_t TxRxState; /* <! To store the communication state >*/
}USART_handle_t;
/*
*@USART_Mode
*Possible options for USART_Mode
*/
#define USART_MODE_ONLY_TX 0
#define USART_MODE_ONLY_RX 1
#define USART_MODE_TXRX 2
/*
*@USART_Baud
*Possible options for USART_Baud
*/
#define USART_STD_BAUD_1200 1200
#define USART_STD_BAUD_2400 400
#define USART_STD_BAUD_9600 9600
#define USART_STD_BAUD_19200 19200
#define USART_STD_BAUD_38400 38400
#define USART_STD_BAUD_57600 57600
#define USART_STD_BAUD_115200 115200
#define USART_STD_BAUD_230400 230400
#define USART_STD_BAUD_460800 460800
#define USART_STD_BAUD_921600 921600
#define USART_STD_BAUD_2M 2000000
#define SUART_STD_BAUD_3M 3000000
/*
*@USART_ParityControl
*Possible options for USART_ParityControl
*/
#define USART_PARITY_DISABLE 0
#define USART_PARITY_EN_EVEN 1
#define USART_PARITY_EN_ODD 2
/*
*@USART_WordLength
*Possible options for USART_WordLength
*/
#define USART_WORDLEN_8BITS 0
#define USART_WORDLEN_9BITS 1
/*
*@USART_StopBits
*Possible options for USART_StopBits
*/
#define USART_STOPBITS_1 0
#define USART_STOPBITS_0_5 1
#define USART_STOPBITS_2 2
#define USART_STOPBITS_1_5 3
/*
*@USART_HWFlowControl
*Possible options for USART_HWFlowControl
*/
#define USART_HW_FLOW_CTRL_NONE 0
#define USART_HW_FLOW_CTRL_CTS 1
#define USART_HW_FLOW_CTRL_RTS 2
#define USART_HW_FLOW_CTRL_CTS_RTS 3
/*
* USART related status flags definitions
*/
#define USART_PE_FLAG (1 << USART_SR_PE)
#define USART_FE_FLAG (1 << USART_SR_FE)
#define USART_NF_FLAG (1 << USART_SR_NF)
#define USART_ORE_FLAG (1 << USART_SR_ORE)
#define USART_IDLE_FLAG (1 << USART_SR_IDLE)
#define USART_RXNE_FLAG (1 << USART_SR_RXNE)
#define USART_TC_FLAG (1 << USART_SR_TC)
#define USART_TXE_FLAG (1 << USART_SR_TXE)
#define USART_LBD_FLAG (1 << USART_SR_LBD)
#define USART_CTS_FLAG (1 << USART_SR_CTS)
/*
* USART application states
*/
#define USART_READY 0
#define USART_BUSY_IN_RX 1
#define USART_BUSY_IN_TX 2
/*
* I2C application events macros
*/
typedef enum USART_events{
USART_EVENT_TX_CMPLT,
USART_EVENT_RX_CMPLT,
USART_EVENT_CTS,
USART_EVENT_IDLE,
USART_EVENT_ORE,
USART_ERREVENT_FE,
USART_ERREVENT_NF,
USART_ERREVENT_ORE
}USART_events_t;
/******************************************************************************************
* APIs supported by this driver
* For more information about the APIs check the function definitions
******************************************************************************************/
/*
* Peripheral Clock setup
*/
void USART_ClockControl(USART_RegDef_t *pUSARTx, uint8_t status);
/*
* Init and De-init
*/
void USART_Init(USART_handle_t *pUSARTHandle);
void USART_DeInit(USART_RegDef_t *pUSARTx);
/*
* Data Send and Receive
*/
void USART_SendData(USART_handle_t *pUSARTHandle, uint8_t *pTxBuffer, uint32_t len);
void USART_ReceiveData(USART_handle_t *pUSARTHandle, uint8_t *pRxBuffer, uint32_t len);
uint8_t USART_SendDataIT(USART_handle_t *pUSARTHandle,uint8_t *pTxBuffer, uint32_t len);
uint8_t USART_ReceiveDataIT(USART_handle_t *pUSARTHandle, uint8_t *pRxBuffer, uint32_t len);
/*
* IRQ Configuration and ISR handling
*/
void USART_IRQInterruptConfig(uint8_t IRQNumber, uint8_t EnorDi);
void USART_IRQPriorityConfig(uint8_t IRQNumber, uint32_t IRQPriority);
void USART_IRQHandling(USART_handle_t *pHandle);
/*
* Other Peripheral Control APIs
*/
void USART_PeripheralControl(USART_RegDef_t *pUSARTx, uint8_t status);
uint8_t USART_GetFlagStatus(USART_RegDef_t *pUSARTx , uint32_t flag);
void USART_ClearFlag(USART_RegDef_t *pUSARTx, uint16_t flag);
void USART_SetBaudRate(USART_RegDef_t *pUSARTx, uint32_t BaudRate);
/*
* Application callback
*/
void USART_ApplicationEventCallback(USART_handle_t *pUSARTHandle, USART_events_t AppEv);
#endif /* INC_STM32F407XX_USART_H_ */
|
C
|
#include "stdio.h"
int main() {
char operator;
float firstNumber,secondNumber;
double result;
printf("Enter an operator + or - or * or % ");
scanf("%c", &operator);
printf("\nEnter two operands: ");
scanf("%f %f",&firstNumber, &secondNumber);
/* Swicth case to perfrom the required operations */
switch(operator)
{
case '+':
result = firstNumber + secondNumber;
printf("\n%f + %f = %lf",firstNumber, secondNumber, result);
break;
case '-':
result = firstNumber - secondNumber;
printf("\n%f - %f = %lf",firstNumber, secondNumber, result);
break;
case '*':
result = firstNumber * secondNumber;
printf("\n%f * %f = %lf",firstNumber, secondNumber, result);
break;
case '/':
result = firstNumber / secondNumber;
printf("\n%f / %f = %lf",firstNumber, secondNumber, result);
break;
/* operator doesn't match any case constant (+, -, *, /) */
default:
printf("Error! operator is not correct");
}
return 0;
}
|
C
|
#include <stdio.h>
#include <math.h>
void gotocond(short a, short *p)
{
if(a && *p < a)
goto label1;
label1:
*p = a;
}
|
C
|
// dfs doesn't help with shortest paths. it finds any path.
// for cycle detection, use dfs visit pattern storing the parent and if a neighbour is marked and is not parent, there is a cycle
// symbol graph contains a hash table containing string keys paired with integer indexes, another array is maintained to get string keys for integer index, 2 pass
#ifndef DFS_H
#include <stdlib.h>
#include <stdio.h>
#include "vertex_indexed_graph.h"
#define DFS_H
typedef struct dfs * dfs;
#ifndef STACK_H
#include "stack.h"
STACK(int)
#endif
struct dfs {
int count;
int s;
int *marked;
int *edge_to;
Graph g;
};
dfs init_dfs(Graph g, int s) {
dfs p_dfs = malloc(sizeof(struct dfs));
p_dfs->s = s;
p_dfs->g = g;
p_dfs->marked = malloc(g->V * sizeof(int));
p_dfs->edge_to = malloc(g->V * sizeof(int));
for (size_t i = 0; i < g->V; i++) {
p_dfs->marked[i] = 0;
}
return p_dfs;
}
void df_search(dfs p_dfs, Graph g, int v) {
p_dfs->marked[v] = 1;
p_dfs->count++;
Ints_Bag bag = g->adj[v];
while (bag) {
int w = bag->v;
// printf("marked val = %d\n", p_dfs->marked[w]);
if (!p_dfs->marked[w]) {
p_dfs->edge_to[w] = v;
df_search(p_dfs, g, w);
bag = bag->next;
continue;
}
bag = bag->next;
}
}
int is_marked(dfs p_dfs, int w) {
return p_dfs->marked[w];
}
int count(dfs p_dfs) {
return p_dfs->count;
}
int_stack path_dfs(dfs p_dfs, int v) {
if (!p_dfs->marked[v]) return NULL;
int_stack st;
init_int_stack(&st);
for (int x = v; x != p_dfs->s; x = p_dfs->edge_to[x]) {
push_int_stack(&st, x);
}
return st;
}
#endif
|
C
|
//sercet code translation
//begin with + A become C
//- E to C
//+ Z to B
#include <string.h>
#include <stdio.h>
int main(){
char a[100],b[100];
int i;
// gets(a); //dangerous to use?
scanf("%s",&a);
if(a[0]=='+'){
for(i=1;i<strlen(a);i++){
a[i]=a[i]+2; //a[i]+=2 A to C
if(((a[i]>'Z')&&(a[i]<'a'))||(a[i]>'z')){
a[i]-=26; //
}
}
}
if(a[0]=='-'){
for(i=1;i<strlen(a);i++){
a[i]-=2; //C to A
if((a[i]<'A')||((a[i]>'Z')&&(a[i]<'a'))){
a[i]+=26; //
}
}
}
puts(a+1); //+1 to delete 1st element"+"/"-"
printf("%s\n",a+1);
return 0;
}
|
C
|
#include <stdio.h>
void jz(int n) {
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (j == 0) {
if (i == 0) {
printf("1");
} else {
printf("0");
}
} else {
if (j == i) {
printf(" 1");
} else {
printf(" 0");
}
}
}
printf("\n");
}
}
int main() {
int n;
while (scanf("%d", &n) != EOF) {
jz(n);
printf("\n");
}
}
/**************************************************************
Problem: 1506
User: 201801011012
Language: C
Result: Accepted
Time:84 ms
Memory:748 kb
****************************************************************/
|
C
|
#include <stdlib.h>
#include <stdio.h>
int main(void) {
FILE *rfp, *wfp;
int c;
if ((rfp = fopen("3-1.txt", "r")) == NULL) {
/* 고수준 파일 입출력을 이용해 3-1.txt를 open
r : 파일을 읽기 전용으로 연다 */
perror("fopen: 3-1.txt"); // 파일 오픈 실패 시 에러메시지 출력
exit(1); // 시스템 종료
}
if ((wfp = fopen("3-5.txt", "w")) == NULL) {
/* 고수준 파일 입출력을 이용해 3-5.txt를 open
w : 새로 쓰기용으로 텍스트 파일을 연다 */
perror("fopen: 3-5.txt"); // 에러 메시지 출력
exit(1);
}
while ((c = fgetc(rfp)) != EOF) { // rfp파일을 c에 문자 기반으로 입력한다
fputc(c, wfp); // wfp파일에 c를 문자 기반으로 출력해 작성한다
}
fclose(rfp); // 3-1.txt 파일 닫기
fclose(wfp); // 3-3.txt 파일 닫기
return 0;
}
|
C
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/*
* File: parseLog.c
* Author: zw
*
* Created on May 24, 2018, 1:21 PM
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "parselog.h"
int main(int argc, char *argv[])
{
if(argc < 1){
printf("error: no input paths specified\n");
return 1;
}
// open files and check for valid pointers
FILE *fLog = fopen(argv[1], "r");
FILE *fDur = fopen(argv[2], "r");
FILE *fSes = fopen(argv[3], "w");
if(fLog==NULL) printf("Error opening log file");
if(fDur==NULL) printf("Error opening inactivity_period file");
if(fSes==NULL) printf("Error opening write file");
rewind(fLog);
// var definitions
int n = 40000; // num users
int min_users = n/2; // minimum user num
SESSION *S = malloc(n*sizeof(*S)); // session struct array
int *rank2idx = malloc(n*sizeof(int)); // rank mapping of ip list
int *idx2rank = malloc(n*sizeof(int)); // idx mapping of rank list
rank2idx[0]=0;
idx2rank[0]=0;
int nActive = 0; // total active sessions
int t_curr=0; // time stamp on current line (sec)
int t_prev=0; // time of last t_update (sec)
int dur = 0; // max session duration (sec)
int ct = 0; // total line count
// get session duration from file
char txtline[2048];
fgets(txtline, sizeof txtline, fDur);
for(int i=0; i<strlen(txtline)-1; i++){
int str_digit = txtline[i]-'0';
dur = dur + str_digit * intlog10(strlen(txtline)-i-2);
}
fclose(fDur);
LINE ls; // parsed single line data
fgets(txtline, sizeof txtline, fLog); // read log header
// parse lines until the end of the file
while (fgets(txtline, sizeof txtline, fLog))
{
// parse single line
ls = parse_line(txtline, ",\n");
ct++;
// update t_current and search rank sorted list for ip match
int idx = matchIP(ls.ip, S, nActive, rank2idx, idx2rank);
t_curr = str2time(ls.time);
if(t_curr == -1)
{
t_curr = t_prev;
}
// append new session or update existing session data
if((idx >= nActive) | nActive==0){
strcpy(S[nActive].ip,ls.ip);
strcpy(S[nActive].start_date,ls.date);
strcpy(S[nActive].request_date,ls.date);
S[nActive].start_t = t_curr;
S[nActive].request_t = t_curr;
S[nActive].request_tlag = t_curr;
S[nActive].request_n = 1;
nActive++;
}
else{
strcpy(S[idx].request_date,ls.date);
S[idx].request_t = t_curr;
S[idx].request_n++;
}
// check for expired sessions if clock advances
if(t_curr!=t_prev){
t_prev = t_curr; // set time stamp of previous line
int n_out = 0; // num sessions to output
int out[2000]; // placeholder for output indices
// identify number and indices of sessions to output
t_update(t_curr, dur, S, nActive, out, &n_out);
// write data to output and remove expired sessions from S
if(n_out)
{
write_data(fSes, S, out, n_out);
trim_sessions(S, out, n_out, rank2idx, idx2rank, &nActive);
}
}
// manage memory usage
if(nActive > n - 2)
{
n = n*2;
printf("allocating %i active users\n",n);
S = realloc(S,n*(sizeof(*S)));
rank2idx = realloc(rank2idx,n*(sizeof(*rank2idx)));
idx2rank = realloc(idx2rank,n*(sizeof(*idx2rank)));
}
else if(nActive < n/2 && nActive > min_users)
{
n = n/2;
printf("allocating %i active users\n",n);
S = realloc(S,n*(sizeof(*S)));
rank2idx = realloc(rank2idx,n*(sizeof(*rank2idx)));
idx2rank = realloc(idx2rank,n*(sizeof(*idx2rank)));
}
}
// write any remaining sessions at end of file
int n_out = nActive;
int out[nActive];
for(int i=0; i<nActive; i++){
out[i] = i;
}
if(n_out)
{
write_data(fSes, S, out, n_out);
trim_sessions(S, out, n_out, rank2idx, idx2rank, &nActive);
}
free(S);
free(idx2rank);
free(rank2idx);
printf("total lines parsed: %i\n",ct);
// close output file
fclose(fSes);
return 0;
}
|
C
|
#include "elf_dwarf_base_type.h"
#include "assert.h"
void elf_dwarf_build_base_type(ElfDwarfDieType *die)
{
int i;
uint32 size;
DwarfDataBaseType *obj = dwarf_alloc_data_type(DATA_TYPE_BASE);
ElfDwarfAttributeType *attr;
ElfDwarfAbbrevType *abbrev;
DwAtType attr_type;
for (i = 0; i < die->attribute->current_array_size; i++) {
abbrev = (ElfDwarfAbbrevType *)die->abbrev_info;
attr = (ElfDwarfAttributeType*)die->attribute->data[i];
attr_type = abbrev->attribute_name->data[i];
switch (attr_type) {
case DW_AT_byte_size:
obj->info.size = elf_dwarf_info_get_value(abbrev->attribute_form->data[i], attr, &size);
break;
case DW_AT_name:
obj->info.typename = attr->encoded.string;
break;
case DW_AT_encoding:
obj->encoding = elf_dwarf_info_get_value(abbrev->attribute_form->data[i], attr, &size);
//printf("encoding=0x%x\n", obj->encoding);
break;
default:
ASSERT(0);
}
}
obj->info.die = die;
dwarf_register_data_type(&obj->info);
return;
}
|
C
|
//
// Created by sea on 2019/11/29.
//
#ifndef LIBCOLL_TMAP_H
#define LIBCOLL_TMAP_H
#include <stdbool.h>
#include <stddef.h>
#include "seq.h"
typedef unsigned char coll_entry_color_t; // map entry color
#define COLL_ENTRY_COLOR_RED 0x01u
#define COLL_ENTRY_COLOR_BLACK 0x00u
typedef struct coll_tmap_entry coll_tmap_entry_t; // map entry, node of red-black tree
struct coll_tmap_entry {
void *key, *val;
coll_tmap_entry_t *left, *right, *parent;
coll_entry_color_t color;
};
struct coll_tmap {
coll_tmap_entry_t *root;
size_t size;
int (*cmp)(void *, void *);
};
typedef struct coll_tmap coll_tmap_t;
void coll_tmap_init(coll_tmap_t *map);
void coll_tmap_init_custom(coll_tmap_t *map, int (*cmp)(void *, void *));
void *coll_tmap_insert(coll_tmap_t *map, void *key, void *value);
void *coll_tmap_value_of(coll_tmap_t *map, void *key);
coll_seq_t coll_tmap_keys(coll_tmap_t *map);
coll_seq_t coll_tmap_values(coll_tmap_t *map);
size_t coll_tmap_size(coll_tmap_t *map);
bool coll_tmap_empty(coll_tmap_t *map);
bool coll_tmap_contains_key(coll_tmap_t *map, void *key);
bool coll_tmap_contains_value(coll_tmap_t *map, void *value);
void *coll_tmap_remove(coll_tmap_t *map, void *key);
void coll_tmap_clear(coll_tmap_t *map);
void coll_tmap_foreach(coll_tmap_t *map, void (*visit)(void *key, void *value));
void coll_tmap_free(coll_tmap_t *map);
// compare functions
int coll_cmp_ptr(void *, void *);
int coll_cmp_int(void *, void *);
int coll_cmp_char(void *, void *);
int coll_cmp_str(void *, void *);
int coll_cmp_double(void *, void *);
#endif // LIBCOLL_TMAP_H
|
C
|
#include<stdio.h>
int main() {
unsigned int n;
while(scanf("%d", &n) != EOF) {
if(n < 1) {
printf("vai ter copa!\n");
} else {
printf("vai ter duas!\n");
}
}
return 0;
}
|
C
|
#include <stdio.h>
#include "Dijkstra.h"
int G[MAX][MAX]; /* 迭 */
int V[MAX]; /* ó üũ 迭 */
int D[MAX]; /* ִܰŸ 迭 */
int P[MAX]; /* 迭 */
int vertex; /* 迭 */
int edge; /* 迭 */
/*--------------------------------------------------------------------------------------
Լ : dijkstra() - õ
ּ ġ ϰ θڽ 踦
: s - õ ȣ
ϰ:
--------------------------------------------------------------------------------------*/
void dijkstra(int s) {
/* distance predecessor, visited 迭 ʱȭ */
int i;
int j;
for (i=0 ; i<vertex ; i++) {
D[i] = G[s][i];
V[i] = 0;
if (G[s][i] != INF) {
P[i] = s;
}
else {
P[i] = NIL;
}
}
V[s] = 1;
for (i=0 ; i<vertex ; i++) {
int minIndex = 0;
int minValue = INF;
for (j=0 ; j<vertex ; j++) {
if ((V[j] == 0) && (D[j] < minValue)) {
minIndex = j;
minValue = D[j];
}
}
V[minIndex] = 1;
for (j=0 ; j<vertex ; j++) {
if (V[j] == 0) {
if ((D[minIndex] + G[minIndex][j]) < D[j]) {
D[j] = D[minIndex] + G[minIndex][j];
P[j] = minIndex;
}
}
}
}
}
void printVisited(void) {
int i;
printf("-------------------------------------\n");
for (i=0 ; i<vertex ; i++) {
printf("%2c", i + 'A');
}
printf("\n");
for (i=0 ; i<vertex ; i++) {
printf("%2d", V[i]);
}
printf("\n");
printf("-------------------------------------\n");
}
void printPredecessor(void) {
int i;
for (i=0 ; i<vertex ; i++) {
printf("%2c ", i + 'A');
}
printf("\n");
for (i=0 ; i<vertex ; i++) {
printf("%2c ", P[i] + 'A');
}
printf("\n");
}
/*--------------------------------------------------------------------------------------
Լ : pathPrint() - -> path ġ
: parent - θ, ڽİ踦 迭 ּ
weightArray - ġ 迭 ּ
startVNum - ȣ
endVNum - ȣ
ϰ:
--------------------------------------------------------------------------------------*/
void printPath(int s, int t) {
int stack[MAX] = { 0 };
int top = 0;
stack[top++] = t;
while (P[t] != s) {
t = P[t];
stack[top++] = t;
}
if (s == P[t]) {
printf("̵ : %c -> ", s + 'A');
while (top > 0) {
printf("%c", stack[--top] + 'A');
if (top > 0) {
printf(" -> ");
}
}
printf("\n");
}
else {
printf(" Ұ!!!\n");
}
}
void printDistance(int s) {
int i;
printf("%c > ", s + 'A');
for (i=0 ; i<vertex ; i++) {
printf("%2c", i + 'A');
}
printf("\n");
printf(" ");
for (i=0 ; i<vertex ; i++) {
if (D[i] == INF) {
printf("%2c", 'x');
}
else {
printf("%2d", D[i]);
}
}
printf("\n");
}
void initGraph(void) {
int i;
int j;
for (i=0 ; i<MAX ; i++) {
for (j=0 ; j<MAX ; j++) {
if (i == j) {
G[i][j] = 0;
}
else {
G[i][j] = INF;
}
}
}
}
void printGraph(void) {
int i;
int j;
printf("%2s", "");
for (i=0 ; i<vertex ; i++) {
printf("%2c", 'A' + i);
}
printf("\n");
for (i=0 ; i<vertex ; i++) {
printf("%2c", 'A' + i);
for (j=0 ; j<vertex ; j++) {
if (G[i][j] == INF) {
printf("%3s", "");
}
else {
printf("%2d", G[i][j]);
}
}
printf("\n");
}
printf("\n");
}
void createGraph(void) {
int i;
char s;
char t;
int w;
scanf("%d %d", &vertex, &edge);
for (i=0 ; i<edge ; i++) {
scanf(" %c %c %d", &s, &t, &w);
G[s - 'A'][t - 'A'] = w;
G[t - 'A'][s - 'A'] = w;
}
}
|
C
|
#include "Common.h"
enum ReadStatus{
NotDone,
Done,
TimedOut,
ClientClosedConnection
};
int16_t ReadInt(const char *message){
int16_t number;
printf("%s", message);
while (scanf("%hi", &number) != 1){
printf("%s", message);
ClearStdIn();
}
return number;
}
uint16_t ReadUInt16(const char* message){
uint16_t number;
printf("%s", message);
while (scanf("%hu", &number) != 1){
ClearStdIn();
printf("%s", message);
}
return number;
}
struct Array ReadArray(){
uint16_t i;
char message[10];
struct Array array = ARRAY_INIT;
array.Length = ReadUInt16("Dimensiune sir: ");
if (array.Length > 0){
array.Items = (int16_t*)calloc(array.Length, sizeof(int16_t));
for (i = 0; i < array.Length; i++){
sprintf(message, "sir[%hu]=", i);
array.Items[i] = ReadInt(message);
}
}
return array;
}
void PrintArray(struct Array* array){
uint16_t i;
printf("Dimensiune sir: %u\n", array->Length);
if (array->Length > 0){
for (i = 0; i < array->Length - 1; i++)
printf("%hi, ", array->Items[i]);
printf("%hi\n", array->Items[array->Length - 1]);
}
}
void ClearArray(struct Array* array){
if (array->Length > 0){
free(array->Items);
array->Items = NULL;
array->Length = 0;
}
}
struct Array CastArray(struct Array* array, uint16_t (*cast)(uint16_t)){
uint16_t i;
struct Array result;
result.Length = cast(array->Length);
if (array->Length > 0){
result.Items = (int16_t*)calloc(result.Length, sizeof(int16_t));
for (i = 0; i < result.Length; i++)
result.Items[i] = cast(array->Items[i]);
}
else
result.Items = NULL;
return result;
}
int SendArray(int sock, struct Array* array){
struct Array converted = CastArray(array, htons);
if (send(sock, (void*) &converted.Length, sizeof(converted.Length), 0) != -1 &&
array->Length > 0 &&
send(sock, (void*) converted.Items, array->Length * sizeof(array->Items[0]), 0) != -1)
return 0;
else
return -1;
}
int RecvUInt16(int sock, int timeOut_ms, uint16_t* value){
struct pollfd pollFd = {sock, POLLIN ,0};
if (poll(&pollFd, 1, timeOut_ms) == 1){
recv(sock, (void*) value, sizeof(*value), 0);
*value = ntohs(*value);
return 0;
}
else
return -1;
}
int RecvArrayAux(int sock, time_t timeOut_ms, struct Array* array){
ssize_t recvResult;
uint16_t hasBeenRead = 0, i, lengthInBytes = sizeof(int16_t) * array->Length;
enum ReadStatus readStatus = NotDone;
struct pollfd pollFd = {sock, POLLIN, 0};
do{
if (poll(&pollFd, 1, timeOut_ms) == 1){
recvResult = recv(sock, ((char*)array->Items) + hasBeenRead, sizeof(int16_t), 0);
if (recvResult == -1)
readStatus = ClientClosedConnection;
else{
hasBeenRead += recvResult;
if (hasBeenRead == lengthInBytes)
readStatus = Done;
}
}
else
readStatus = TimedOut;
}while (readStatus == NotDone);
switch (readStatus){
case Done:
for (i = 0; i < array->Length; i++)
array->Items[i] = ntohs(array->Items[i]);
return 0;
case TimedOut:
return -1;
case ClientClosedConnection:
return -2;
}
}
int RecvArray(int sock, time_t timeOut, struct Array* array){
struct Array result = ARRAY_INIT;
if (RecvUInt16(sock, timeOut, &result.Length) == -1)
return -1;
else
if (result.Length > 0){
result.Items = (int16_t*)calloc(result.Length, sizeof(int16_t));
switch (RecvArrayAux(sock, timeOut, &result)){
case 0:
*array = result;
return 0;
case -1:
return -2;
case -2:
return -3;
}
}
else
return 0;
}
|
C
|
#include <stdio.h>
long int fibonacci(int);
void usage();
int main(int argc, char **argv)
{
int input;
long int output;
if (argc != 2) {
usage();
return 0;
}
input = atoi(argv[1]);
if (input < 0) {
printf("input must be >= 0");
usage();
return 0;
}
output = fibonacci(input);
printf("the result of fibonacci %d is %ld\n", input, output);
return 0;
}
long int fibonacci(int input)
{
long int result;
if (input >= 2) {
result = fibonacci(input-1) + fibonacci(input-2);
} else {
switch (input) {
case 0:
result = 0;
break;
case 1:
result = 1;
break;
}
}
return result;
}
void usage()
{
printf("Usage:\n");
printf("\ta.out number\n");
return;
}
|
C
|
#pragma once
#include<fstream>
#include"NSGA2.h"
vector<individual> moead_solution;
vector<individual> aesmoead_solution;
vector<individual> non_dominated_solution;
void read_solution(string str, int hangshu, vector<individual>& solution) //ȡstrݵsolutionݵhangshu
{ //ЩⶼEPֻȡĿֵĴСIGD
ifstream infile(str);
if (!infile)
cout << "ļûд" << endl;
for (int i = 0; i < hangshu; i++)
{
individual a;
for (int j = 0; j < objective; j++)
{
infile >> a.value[j];
}
solution.push_back(a);
}
infile.close();
}
void add_solution(vector<individual> b, vector<individual>& c)
{ //abĽһеķ֧ŵc
for (int i = 0; i < b.size(); i++)
{
for (int j = 0; j < c.size(); j++) //ɾcбb֧Ľ
{
if (b[i] < c[j])
{
//c[j].print();
c.erase(c.begin() + j);
j--;
}
}
//ȻٿǷb뵽c
int flag = 1; //1-cû֧bнĽ⣬Խ뵽c
for (int j = 0; j < c.size(); j++)
{
if (c[j] < b[i])
{
flag = 0;
break;
}
int count = 0; //Ŀֵȵĸ
for (int k = 0; k < objective; k++)
{
if (c[j].value[k] == b[i].value[k])
count++;
}
if (count == objective)
flag = 0;
}
if (flag)
c.push_back(b[i]);
//else
// b[i].print();
}
}
double cal_IGD(vector<individual> a, vector<individual> b)
{ //⼯abʵPF)ϵIGD
double igd = 0;
for (int i = 0; i < b.size(); i++)
{
double d_min = RAND_MAX;
for (int j = 0; j < a.size(); j++)
{
double d1[objective] = { 0 };
for (int k = 0; k < objective; k++)
{
d1[k] = pow((b[i].value[k] - a[j].value[k]), 2);
d1[0] += d1[k];
}
if (sqrt(d1[0]) < d_min)
d_min = d1[0];
}
igd += d_min;
}
return igd / b.size();
}
double cal_coverage(vector<individual> a, vector<individual> b)
{
int count = 0;
for (int i = 0; i < b.size(); i++)
{
for (int j = 0; j < a.size(); j++)
{
if (a[j] < b[i])
{
count++;
break;
}
}
}
//cout << count;
return count / (b.size() * 1.0);
}
|
C
|
//
// Created by HISONA on 2016. 2. 29..
//
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <signal.h>
#include <sys/socket.h>
#include <unistd.h>
#include <netdb.h>
#include "ca_cert.h"
#include "https.h"
/*---------------------------------------------------------------------*/
static int _error;
/*---------------------------------------------------------------------*/
char *strtoken(char *src, char *dst, int size);
static int parse_url(char *src_url, int *https, char *host, char *port, char *url);
static int http_header(HTTP_INFO *hi, char *param);
static int http_parse(HTTP_INFO *hi);
static int https_init(HTTP_INFO *hi, BOOL https, BOOL verify);
static int https_close(HTTP_INFO *hi);
static int https_connect(HTTP_INFO *hi, char *host, char *port);
static int https_write(HTTP_INFO *hi, char *buffer, int len);
static int https_read(HTTP_INFO *hi, char *buffer, int len);
/*---------------------------------------------------------------------------*/
char *strtoken(char *src, char *dst, int size)
{
char *p, *st, *ed;
int len = 0;
// l-trim
p = src;
while(TRUE)
{
if((*p == '\n') || (*p == 0)) return NULL; /* value is not exists */
if((*p != ' ') && (*p != '\t')) break;
p++;
}
st = p;
while(TRUE)
{
ed = p;
if(*p == ' ') {
p++;
break;
}
if((*p == '\n') || (*p == 0)) break;
p++;
}
// r-trim
while(TRUE)
{
ed--;
if(st == ed) break;
if((*ed != ' ') && (*ed != '\t')) break;
}
len = (int)(ed - st + 1);
if((size > 0) && (len >= size)) len = size - 1;
strncpy(dst, st, len);
dst[len]=0;
return p;
}
/*---------------------------------------------------------------------*/
static int parse_url(char *src_url, int *https, char *host, char *port, char *url)
{
char *p1, *p2;
char str[1024];
memset(str, 0, 1024);
if(strncmp(src_url, "http://", 7)==0) {
p1=&src_url[7];
*https = 0;
} else if(strncmp(src_url, "https://", 8)==0) {
p1=&src_url[8];
*https = 1;
} else {
p1 = &src_url[0];
*https = 0;
}
if((p2=strstr(p1, "/")) == NULL)
{
sprintf(str, "%s", p1);
sprintf(url, "/");
}
else
{
strncpy(str, p1, p2-p1);
snprintf(url, 256, "%s", p2);
}
if((p1=strstr(str, ":")) != NULL)
{
*p1=0;
snprintf(host, 256, "%s", str);
snprintf(port, 5, "%s", p1+1);
}
else
{
snprintf(host, 256, "%s", str);
if(*https == 0)
snprintf(port, 5, "80");
else
snprintf(port, 5, "443");
}
return 0;
}
/*---------------------------------------------------------------------*/
static int http_header(HTTP_INFO *hi, char *param)
{
char *token;
char t1[256], t2[256];
int len;
token = param;
if((token=strtoken(token, t1, 256)) == 0) return -1;
if((token=strtoken(token, t2, 256)) == 0) return -1;
if(strncasecmp(t1, "HTTP", 4) == 0)
{
hi->response.status = atoi(t2);
}
else if(strncasecmp(t1, "set-cookie:", 11) == 0)
{
snprintf(hi->response.cookie, 512, "%s", t2);
}
else if(strncasecmp(t1, "location:", 9) == 0)
{
len = (int)strlen(t2);
strncpy(hi->response.location, t2, len);
hi->response.location[len] = 0;
}
else if(strncasecmp(t1, "content-length:", 15) == 0)
{
hi->response.content_length = atoi(t2);
}
else if(strncasecmp(t1, "transfer-encoding:", 18) == 0)
{
if(strncasecmp(t2, "chunked", 7) == 0)
{
hi->response.chunked = TRUE;
}
}
else if(strncasecmp(t1, "connection:", 11) == 0)
{
if(strncasecmp(t2, "close", 5) == 0)
{
hi->response.close = TRUE;
}
}
return 1;
}
/*---------------------------------------------------------------------*/
static int http_parse(HTTP_INFO *hi)
{
char *p1, *p2;
long len;
if(hi->r_len <= 0) return -1;
p1 = hi->r_buf;
while(1)
{
if(hi->header_end == FALSE) // header parser
{
if((p2 = strstr(p1, "\r\n")) != NULL)
{
len = (long)(p2 - p1);
*p2 = 0;
if(len > 0)
{
// printf("header: %s(%ld)\n", p1, len);
http_header(hi, p1);
p1 = p2 + 2; // skip CR+LF
}
else
{
hi->header_end = TRUE; // reach the header-end.
// printf("header_end .... \n");
p1 = p2 + 2; // skip CR+LF
if(hi->response.chunked == TRUE)
{
len = hi->r_len - (p1 - hi->r_buf);
if(len > 0)
{
if((p2 = strstr(p1, "\r\n")) != NULL)
{
*p2 = 0;
if((hi->length = strtol(p1, NULL, 16)) == 0)
{
hi->response.chunked = FALSE;
}
else
{
hi->response.content_length += hi->length;
}
p1 = p2 + 2; // skip CR+LF
}
else
{
// copy the data as chunked size ...
strncpy(hi->r_buf, p1, len);
hi->r_buf[len] = 0;
hi->r_len = len;
hi->length = -1;
break;
}
}
else
{
hi->r_len = 0;
hi->length = -1;
break;
}
}
else
{
hi->length = hi->response.content_length;
}
}
}
else
{
len = hi->r_len - (p1 - hi->r_buf);
if(len > 0)
{
// keep the partial header data ...
strncpy(hi->r_buf, p1, len);
hi->r_buf[len] = 0;
hi->r_len = len;
}
else
{
hi->r_len = 0;
}
break;
}
}
else // body parser ...
{
if(hi->response.chunked == TRUE && hi->length == -1)
{
len = hi->r_len - (p1 - hi->r_buf);
if(len > 0)
{
if ((p2 = strstr(p1, "\r\n")) != NULL)
{
*p2 = 0;
if((hi->length = strtol(p1, NULL, 16)) == 0)
{
hi->response.chunked = FALSE;
}
else
{
hi->response.content_length += hi->length;
}
p1 = p2 + 2; // skip CR+LF
}
else
{
// copy the remain data as chunked size ...
strncpy(hi->r_buf, p1, len);
hi->r_buf[len] = 0;
hi->r_len = len;
hi->length = -1;
break;
}
}
else
{
hi->r_len = 0;
break;
}
}
else
{
if(hi->length > 0)
{
len = hi->r_len - (p1 - hi->r_buf);
if(len > hi->length)
{
// copy the data for response ..
if(hi->body_len < hi->body_size-1)
{
if (hi->body_size > (hi->body_len + hi->length))
{
strncpy(&(hi->body[hi->body_len]), p1, hi->length);
hi->body_len += hi->length;
hi->body[hi->body_len] = 0;
}
else
{
strncpy(&(hi->body[hi->body_len]), p1, hi->body_size - hi->body_len - 1);
hi->body_len = hi->body_size - 1;
hi->body[hi->body_len] = 0;
}
}
p1 += hi->length;
len -= hi->length;
if(hi->response.chunked == TRUE && len >= 2)
{
p1 += 2; // skip CR+LF
hi->length = -1;
}
else
{
return -1;
}
}
else
{
// copy the data for response ..
if(hi->body_len < hi->body_size-1)
{
if (hi->body_size > (hi->body_len + len))
{
strncpy(&(hi->body[hi->body_len]), p1, len);
hi->body_len += len;
hi->body[hi->body_len] = 0;
}
else
{
strncpy(&(hi->body[hi->body_len]), p1, hi->body_size - hi->body_len - 1);
hi->body_len = hi->body_size - 1;
hi->body[hi->body_len] = 0;
}
}
hi->length -= len;
hi->r_len = 0;
if(hi->response.chunked == FALSE && hi->length <= 0) return 1;
break;
}
}
else
{
if(hi->response.chunked == FALSE) return 1;
// chunked size check ..
if((hi->r_len > 2) && (memcmp(p1, "\r\n", 2) == 0))
{
p1 += 2;
hi->length = -1;
}
else
{
hi->length = -1;
hi->r_len = 0;
}
}
}
}
}
return 0;
}
/*---------------------------------------------------------------------*/
static int https_init(HTTP_INFO *hi, BOOL https, BOOL verify)
{
memset(hi, 0, sizeof(HTTP_INFO));
if(https == TRUE)
{
mbedtls_ssl_init( &hi->tls.ssl );
mbedtls_ssl_config_init( &hi->tls.conf );
mbedtls_x509_crt_init( &hi->tls.cacert );
mbedtls_ctr_drbg_init( &hi->tls.ctr_drbg );
}
mbedtls_net_init(&hi->tls.ssl_fd);
hi->tls.verify = verify;
hi->url.https = https;
// printf("https_init ... \n");
return 0;
}
/*---------------------------------------------------------------------*/
static int https_close(HTTP_INFO *hi)
{
if(hi->url.https == 1)
{
mbedtls_ssl_close_notify(&hi->tls.ssl);
}
mbedtls_net_free( &hi->tls.ssl_fd );
if(hi->url.https == 1)
{
mbedtls_x509_crt_free(&hi->tls.cacert);
mbedtls_ssl_free(&hi->tls.ssl);
mbedtls_ssl_config_free(&hi->tls.conf);
mbedtls_ctr_drbg_free(&hi->tls.ctr_drbg);
mbedtls_entropy_free(&hi->tls.entropy);
}
// printf("https_close ... \n");
return 0;
}
/*
* Initiate a TCP connection with host:port and the given protocol
* waiting for timeout (ms)
*/
static int mbedtls_net_connect_timeout( mbedtls_net_context *ctx, const char *host, const char *port,
int proto, uint32_t timeout )
{
int ret;
struct addrinfo hints, *addr_list, *cur;
signal( SIGPIPE, SIG_IGN );
/* Do name resolution with both IPv6 and IPv4 */
memset( &hints, 0, sizeof( hints ) );
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = proto == MBEDTLS_NET_PROTO_UDP ? SOCK_DGRAM : SOCK_STREAM;
hints.ai_protocol = proto == MBEDTLS_NET_PROTO_UDP ? IPPROTO_UDP : IPPROTO_TCP;
if( getaddrinfo( host, port, &hints, &addr_list ) != 0 )
return( MBEDTLS_ERR_NET_UNKNOWN_HOST );
/* Try the sockaddrs until a connection succeeds */
ret = MBEDTLS_ERR_NET_UNKNOWN_HOST;
for( cur = addr_list; cur != NULL; cur = cur->ai_next )
{
ctx->fd = (int) socket( cur->ai_family, cur->ai_socktype,
cur->ai_protocol );
if( ctx->fd < 0 )
{
ret = MBEDTLS_ERR_NET_SOCKET_FAILED;
continue;
}
if( mbedtls_net_set_nonblock( ctx ) < 0 )
{
close( ctx->fd );
ctx->fd = -1;
ret = MBEDTLS_ERR_NET_CONNECT_FAILED;
break;
}
if( connect( ctx->fd, cur->ai_addr, cur->ai_addrlen ) == 0 )
{
ret = 0;
break;
}
else if( errno == EINPROGRESS )
{
int fd = (int)ctx->fd;
int opt;
socklen_t slen;
struct timeval tv;
fd_set fds;
while(1)
{
FD_ZERO( &fds );
FD_SET( fd, &fds );
tv.tv_sec = timeout / 1000;
tv.tv_usec = ( timeout % 1000 ) * 1000;
ret = select( fd+1, NULL, &fds, NULL, timeout == 0 ? NULL : &tv );
if( ret == -1 )
{
if(errno == EINTR) continue;
}
else if( ret == 0 )
{
close( fd );
ctx->fd = -1;
ret = MBEDTLS_ERR_NET_CONNECT_FAILED;
}
else
{
ret = 0;
slen = sizeof(int);
if( (getsockopt(fd, SOL_SOCKET, SO_ERROR, (void *)&opt, &slen) == 0) && (opt > 0) )
{
close( fd );
ctx->fd = -1;
ret = MBEDTLS_ERR_NET_CONNECT_FAILED;
}
}
break;
}
break;
}
close( ctx->fd );
ctx->fd = -1;
ret = MBEDTLS_ERR_NET_CONNECT_FAILED;
}
freeaddrinfo( addr_list );
if( (ret == 0) && (mbedtls_net_set_block( ctx ) < 0) )
{
close( ctx->fd );
ctx->fd = -1;
ret = MBEDTLS_ERR_NET_CONNECT_FAILED;
}
return( ret );
}
/*---------------------------------------------------------------------*/
static int https_connect(HTTP_INFO *hi, char *host, char *port)
{
int ret, https;
https = hi->url.https;
if(https == 1)
{
mbedtls_entropy_init( &hi->tls.entropy );
ret = mbedtls_ctr_drbg_seed( &hi->tls.ctr_drbg, mbedtls_entropy_func, &hi->tls.entropy, NULL, 0);
if( ret != 0 )
{
return ret;
}
ca_crt_rsa[ca_crt_rsa_size - 1] = 0;
ret = mbedtls_x509_crt_parse(&hi->tls.cacert, (uint8_t *)ca_crt_rsa, ca_crt_rsa_size);
if( ret != 0 )
{
return ret;
}
ret = mbedtls_ssl_config_defaults( &hi->tls.conf,
MBEDTLS_SSL_IS_CLIENT,
MBEDTLS_SSL_TRANSPORT_STREAM,
MBEDTLS_SSL_PRESET_DEFAULT );
if( ret != 0 )
{
return ret;
}
/* OPTIONAL is not optimal for security,
* but makes interop easier in this simplified example */
mbedtls_ssl_conf_authmode( &hi->tls.conf, MBEDTLS_SSL_VERIFY_OPTIONAL );
mbedtls_ssl_conf_ca_chain( &hi->tls.conf, &hi->tls.cacert, NULL );
mbedtls_ssl_conf_rng( &hi->tls.conf, mbedtls_ctr_drbg_random, &hi->tls.ctr_drbg );
mbedtls_ssl_conf_read_timeout( &hi->tls.conf, 5000 );
ret = mbedtls_ssl_setup( &hi->tls.ssl, &hi->tls.conf );
if( ret != 0 )
{
return ret;
}
ret = mbedtls_ssl_set_hostname( &hi->tls.ssl, host );
if( ret != 0 )
{
return ret;
}
}
ret = mbedtls_net_connect_timeout(&hi->tls.ssl_fd, host, port, MBEDTLS_NET_PROTO_TCP, 5000);
if( ret != 0 )
{
return ret;
}
if(https == 1)
{
mbedtls_ssl_set_bio(&hi->tls.ssl, &hi->tls.ssl_fd, mbedtls_net_send, mbedtls_net_recv, mbedtls_net_recv_timeout);
while ((ret = mbedtls_ssl_handshake(&hi->tls.ssl)) != 0)
{
if (ret != MBEDTLS_ERR_SSL_WANT_READ && ret != MBEDTLS_ERR_SSL_WANT_WRITE)
{
return ret;
}
}
/* In real life, we probably want to bail out when ret != 0 */
if( hi->tls.verify && (mbedtls_ssl_get_verify_result(&hi->tls.ssl) != 0) )
{
return MBEDTLS_ERR_X509_CERT_VERIFY_FAILED;
}
}
return 0;
}
/*---------------------------------------------------------------------*/
static int https_write(HTTP_INFO *hi, char *buffer, int len)
{
printf("11111111https_write %s \n", buffer);
int ret, slen = 0;
while(1)
{
if(hi->url.https == 1)
ret = mbedtls_ssl_write(&hi->tls.ssl, (u_char *)&buffer[slen], (size_t)(len-slen));
else
ret = mbedtls_net_send(&hi->tls.ssl_fd, (u_char *)&buffer[slen], (size_t)(len-slen));
if(ret == MBEDTLS_ERR_SSL_WANT_WRITE) continue;
else if(ret <= 0) return ret;
slen += ret;
if(slen >= len) break;
}
return slen;
}
/*---------------------------------------------------------------------*/
static int https_read(HTTP_INFO *hi, char *buffer, int len)
{
if(hi->url.https == 1)
{
return mbedtls_ssl_read(&hi->tls.ssl, (u_char *)buffer, (size_t)len);
}
else
{
return mbedtls_net_recv_timeout(&hi->tls.ssl_fd, (u_char *)buffer, (size_t)len, 5000);
}
}
/*---------------------------------------------------------------------*/
int http_init(HTTP_INFO *hi, BOOL verify)
{
return https_init(hi, 0, verify);
}
/*---------------------------------------------------------------------*/
int http_close(HTTP_INFO *hi)
{
return https_close(hi);
}
/*---------------------------------------------------------------------*/
int http_get(HTTP_INFO *hi, char *url, char *response, int size)
{
char request[1024], err[100];
char host[256], port[10], dir[1024];
int sock_fd, https, verify;
int ret, opt, len;
socklen_t slen;
if(NULL == hi) return -1;
verify = hi->tls.verify;
parse_url(url, &https, host, port, dir);
if( (hi->tls.ssl_fd.fd == -1) || (hi->url.https != https) ||
(strcmp(hi->url.host, host) != 0) || (strcmp(hi->url.port, port) != 0) )
{
https_close(hi);
https_init(hi, https, verify);
if((ret=https_connect(hi, host, port)) < 0)
{
https_close(hi);
mbedtls_strerror(ret, err, 100);
snprintf(response, 256, "socket error: %s(%d)", err, ret);
return -1;
}
}
else
{
sock_fd = hi->tls.ssl_fd.fd;
slen = sizeof(int);
if((getsockopt(sock_fd, SOL_SOCKET, SO_ERROR, (void *)&opt, &slen) < 0) || (opt > 0))
{
https_close(hi);
https_init(hi, https, verify);
if((ret=https_connect(hi, host, port)) < 0)
{
https_close(hi);
mbedtls_strerror(ret, err, 100);
snprintf(response, 256, "socket error: %s(%d)", err, ret);
return -1;
}
}
}
/* Send HTTP request. */
len = snprintf(request, 1024,
"GET %s HTTP/1.1\r\n"
"User-Agent: Mozilla/4.0\r\n"
"Host: %s:%s\r\n"
"Content-Type: application/json; charset=utf-8\r\n"
"Connection: Keep-Alive\r\n"
"%s\r\n",
dir, host, port, hi->request.cookie);
if((ret = https_write(hi, request, len)) != len)
{
https_close(hi);
mbedtls_strerror(ret, err, 100);
snprintf(response, 256, "socket error: %s(%d)", err, ret);
return -1;
}
// printf("request: %s \r\n\r\n", request);
hi->response.status = 0;
hi->response.content_length = 0;
hi->response.close = 0;
hi->r_len = 0;
hi->header_end = 0;
hi->body = response;
hi->body_size = size;
hi->body_len = 0;
while(1)
{
ret = https_read(hi, &hi->r_buf[hi->r_len], (int)(H_READ_SIZE - hi->r_len));
if(ret == MBEDTLS_ERR_SSL_WANT_READ) continue;
else if(ret < 0)
{
https_close(hi);
mbedtls_strerror(ret, err, 100);
snprintf(response, 256, "socket error: %s(%d)", err, ret);
return -1;
}
else if(ret == 0)
{
https_close(hi);
break;
}
hi->r_len += ret;
hi->r_buf[hi->r_len] = 0;
// printf("read(%ld): |%s| \n", hi->r_len, hi->r_buf);
// printf("read(%ld) ... \n", hi->r_len);
if(http_parse(hi) != 0) break;
}
if(hi->response.close == 1)
{
https_close(hi);
}
else
{
strncpy(hi->url.host, host, strlen(host));
strncpy(hi->url.port, port, strlen(port));
strncpy(hi->url.path, dir, strlen(dir));
}
/*
printf("status: %d \n", hi->response.status);
printf("cookie: %s \n", hi->response.cookie);
printf("location: %s \n", hi->response.location);
printf("referrer: %s \n", hi->response.referrer);
printf("length: %ld \n", hi->response.content_length);
printf("body: %ld \n", hi->body_len);
*/
return hi->response.status;
}
/*---------------------------------------------------------------------*/
int http_post(HTTP_INFO *hi, char *url, char *data, char *response, int size)
{
char request[1024], err[100];
char host[256], port[10], dir[1024];
int sock_fd, https, verify;
int ret, opt, len;
socklen_t slen;
if(NULL == hi) return -1;
verify = hi->tls.verify;
parse_url(url, &https, host, port, dir);
if( (hi->tls.ssl_fd.fd == -1) || (hi->url.https != https) ||
(strcmp(hi->url.host, host) != 0) || (strcmp(hi->url.port, port) != 0) )
{
if(hi->tls.ssl_fd.fd != -1)
https_close(hi);
https_init(hi, https, verify);
if((ret=https_connect(hi, host, port)) < 0)
{
https_close(hi);
mbedtls_strerror(ret, err, 100);
snprintf(response, 256, "socket error: %s(%d)", err, ret);
return -1;
}
}
else
{
sock_fd = hi->tls.ssl_fd.fd;
slen = sizeof(int);
if((getsockopt(sock_fd, SOL_SOCKET, SO_ERROR, (void *)&opt, &slen) < 0) || (opt > 0))
{
https_close(hi);
https_init(hi, https, verify);
if((ret=https_connect(hi, host, port)) < 0)
{
https_close(hi);
mbedtls_strerror(ret, err, 100);
snprintf(response, 256, "socket error: %s(%d)", err, ret);
return -1;
}
}
// else
// printf("socket reuse: %d \n", sock_fd);
}
/* Send HTTP request. */
len = snprintf(request, 1024,
"POST %s HTTP/1.1\r\n"
"User-Agent: Mozilla/4.0\r\n"
"Host: %s:%s\r\n"
"Connection: Keep-Alive\r\n"
"Accept: */*\r\n"
"Content-Type: application/json; charset=utf-8\r\n"
"Content-Length: %d\r\n"
"%s\r\n"
"%s",
dir, host, port,
(int)strlen(data),
hi->request.cookie,
data);
if((ret = https_write(hi, request, len)) != len)
{
https_close(hi);
mbedtls_strerror(ret, err, 100);
snprintf(response, 256, "socket error: %s(%d)", err, ret);
return -1;
}
// printf("request: %s \r\n\r\n", request);
hi->response.status = 0;
hi->response.content_length = 0;
hi->response.close = 0;
hi->r_len = 0;
hi->header_end = 0;
hi->body = response;
hi->body_size = size;
hi->body_len = 0;
hi->body[0] = 0;
while(1)
{
ret = https_read(hi, &hi->r_buf[hi->r_len], (int)(H_READ_SIZE - hi->r_len));
if(ret == MBEDTLS_ERR_SSL_WANT_READ) continue;
else if(ret < 0)
{
https_close(hi);
mbedtls_strerror(ret, err, 100);
snprintf(response, 256, "socket error: %s(%d)", err, ret);
return -1;
}
else if(ret == 0)
{
https_close(hi);
break;
}
hi->r_len += ret;
hi->r_buf[hi->r_len] = 0;
// printf("read(%ld): %s \n", hi->r_len, hi->r_buf);
// printf("read(%ld) \n", hi->r_len);
if(http_parse(hi) != 0) break;
}
if(hi->response.close == 1)
{
https_close(hi);
}
else
{
strncpy(hi->url.host, host, strlen(host));
strncpy(hi->url.port, port, strlen(port));
strncpy(hi->url.path, dir, strlen(dir));
}
/*
printf("status: %d \n", hi->response.status);
printf("cookie: %s \n", hi->response.cookie);
printf("location: %s \n", hi->response.location);
printf("referrer: %s \n", hi->response.referrer);
printf("length: %d \n", hi->response.content_length);
printf("body: %d \n", hi->body_len);
*/
return hi->response.status;
}
/*---------------------------------------------------------------------*/
void http_strerror(char *buf, int len)
{
mbedtls_strerror(_error, buf, len);
}
/*---------------------------------------------------------------------*/
int http_open(HTTP_INFO *hi, char *url)
{
char host[256], port[10], dir[1024];
int sock_fd, https, verify;
int ret, opt;
socklen_t slen;
if (NULL == hi) return -1;
verify = hi->tls.verify;
parse_url(url, &https, host, port, dir);
if ((hi->tls.ssl_fd.fd == -1) || (hi->url.https != https) ||
(strcmp(hi->url.host, host) != 0) || (strcmp(hi->url.port, port) != 0))
{
if (hi->tls.ssl_fd.fd != -1)
https_close(hi);
https_init(hi, https, verify);
if ((ret = https_connect(hi, host, port)) < 0)
{
https_close(hi);
_error = ret;
return -1;
}
}
else
{
sock_fd = hi->tls.ssl_fd.fd;
slen = sizeof(int);
if ((getsockopt(sock_fd, SOL_SOCKET, SO_ERROR, (void *) &opt, &slen) < 0) || (opt > 0))
{
https_close(hi);
https_init(hi, https, verify);
if ((ret = https_connect(hi, host, port)) < 0)
{
https_close(hi);
_error = ret;
return -1;
}
}
// else
// printf("socket reuse: %d \n", sock_fd);
}
strncpy(hi->url.host, host, strlen(host));
strncpy(hi->url.port, port, strlen(port));
strncpy(hi->url.path, dir, strlen(dir));
return 0;
}
/*---------------------------------------------------------------------*/
int http_write_header(HTTP_INFO *hi)
{
char request[4096], buf[H_FIELD_SIZE];
int ret, len, l;
if (NULL == hi) return -1;
/* Send HTTP request. */
len = snprintf(request, 1024,
"%s %s HTTP/1.1\r\n"
"User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/49.0.2623.108 Chrome/49.0.2623.108 Safari/537.36\r\n"
"Host: %s:%s\r\n"
"Content-Type: %s\r\n",
hi->request.method, hi->url.path,
hi->url.host, hi->url.port,
hi->request.content_type);
if(hi->request.referrer[0] != 0)
{
len += snprintf(&request[len], H_FIELD_SIZE,
"Referer: %s\r\n", hi->request.referrer);
}
if(hi->request.chunked == TRUE)
{
len += snprintf(&request[len], H_FIELD_SIZE,
"Transfer-Encoding: chunked\r\n");
}
else
{
len += snprintf(&request[len], H_FIELD_SIZE,
"Content-Length: %ld\r\n", hi->request.content_length);
}
if(hi->request.close == TRUE)
{
len += snprintf(&request[len], H_FIELD_SIZE,
"Connection: close\r\n");
}
else
{
len += snprintf(&request[len], H_FIELD_SIZE,
"Connection: Keep-Alive\r\n");
}
if(hi->request.cookie[0] != 0)
{
len += snprintf(&request[len], H_FIELD_SIZE,
"Cookie: %s\r\n", hi->request.cookie);
}
len += snprintf(&request[len], H_FIELD_SIZE, "\r\n");
printf("%s", request);
if ((ret = https_write(hi, request, len)) != len)
{
https_close(hi);
_error = ret;
return -1;
}
return 0;
}
/*---------------------------------------------------------------------*/
int http_write(HTTP_INFO *hi, char *data, int len)
{
printf("22222https_write %s \n", data);
char str[10];
int ret, l;
if(NULL == hi || len <= 0) return -1;
if(hi->request.chunked == TRUE)
{
l = snprintf(str, 10, "%x\r\n", len);
if ((ret = https_write(hi, str, l)) != l)
{
https_close(hi);
_error = ret;
return -1;
}
}
if((ret = https_write(hi, data, len)) != len)
{
https_close(hi);
_error = ret;
return -1;
}
if(hi->request.chunked == TRUE)
{
if ((ret = https_write(hi, "\r\n", 2)) != 2)
{
https_close(hi);
_error = ret;
return -1;
}
}
return len;
}
/*---------------------------------------------------------------------*/
int http_write_end(HTTP_INFO *hi)
{
char str[10];
int ret, len;
if (NULL == hi) return -1;
if(hi->request.chunked == TRUE)
{
len = snprintf(str, 10, "0\r\n\r\n");
}
else
{
len = snprintf(str, 10, "\r\n\r\n");
}
if ((ret = https_write(hi, str, len)) != len)
{
https_close(hi);
_error = ret;
return -1;
}
return len;
}
/*---------------------------------------------------------------------*/
int http_read_chunked(HTTP_INFO *hi, char *response, int size)
{
int ret;
if (NULL == hi) return -1;
// printf("request: %s \r\n\r\n", request);
hi->response.status = 0;
hi->response.content_length = 0;
hi->response.close = 0;
hi->r_len = 0;
hi->header_end = 0;
hi->body = response;
hi->body_size = size;
hi->body_len = 0;
hi->body[0] = 0;
while(1)
{
ret = https_read(hi, &hi->r_buf[hi->r_len], (int)(H_READ_SIZE - hi->r_len));
if(ret == MBEDTLS_ERR_SSL_WANT_READ) continue;
else if(ret < 0)
{
https_close(hi);
_error = ret;
return -1;
}
else if(ret == 0)
{
https_close(hi);
break;
}
hi->r_len += ret;
hi->r_buf[hi->r_len] = 0;
// printf("read(%ld): %s \n", hi->r_len, hi->r_buf);
// printf("read(%ld) \n", hi->r_len);
if(http_parse(hi) != 0) break;
}
if(hi->response.close == 1)
{
https_close(hi);
}
/*
printf("status: %d \n", hi->status);
printf("cookie: %s \n", hi->cookie);
printf("location: %s \n", hi->location);
printf("referrer: %s \n", hi->referrer);
printf("length: %d \n", hi->content_length);
printf("body: %d \n", hi->body_len);
*/
return hi->response.status;
}
|
C
|
// Bibliotecas incluidas no compilador C
#include <stdio.h>
//Bibliotecas criadas
#include "ajuda.h"
/*
Os arquivos no formato ".h" no possui implementao das funes utilizadas, possui apenas
os prottipos de funes. As implementaes esto em um arquivo no formato ".c" que possui
o mesmo nome do aquivo ".h".
*/
int main(){
int n1, n2, ret_s, ret_m;
mensagem();
printf("Informe o primeiro nmero: ");
fflush(stdout);
scanf("%d", &n1);
printf("Informe o segundo nmero: ");
fflush(stdout);
scanf("%d", &n2);
ret_s = soma(n1, n2);
printf("A soma de %d com %d %d\n", n1, n2, ret_s);
ret_m = mult(n1, n2);
printf("A multiplicao de %d com %d %d", n1, n2, ret_m);
return 0;
}
|
C
|
#include <argp.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "libabikeccak.h"
#include "modedictionary.h"
#include "modenonce.h"
enum Mode { DICTIONARY, NONCE, HASH };
struct arguments {
enum Mode mode;
char *from;
char *fromPrefix;
char *to;
char *toPrefix;
int threadCount;
};
int arguments_parse_mode(char *string, enum Mode *toBeSet) {
if (string == NULL)
return 0;
else if (strcmp(string, "DICTIONARY") == 0) {
*toBeSet = DICTIONARY;
return 1;
} else if (strcmp(string, "NONCE") == 0) {
*toBeSet = NONCE;
return 1;
} else if (strcmp(string, "HASH") == 0) {
*toBeSet = NONCE;
return 1;
} else
return 0;
}
error_t arguments_parse(int key, char *arg, struct argp_state *state) {
struct arguments *arguments = state->input;
int parsed;
switch (key) {
case 'm':
if (!arguments_parse_mode(arg, &(arguments->mode))) argp_usage(state);
break;
case 'f':
arguments->fromPrefix = arg;
break;
case 't':
arguments->toPrefix = arg;
break;
case 'c':
parsed = atoi(arg);
if (parsed > 0) {
arguments->threadCount = parsed;
} else {
argp_usage(state);
}
break;
case ARGP_KEY_ARG:
if (state->arg_num >= 2)
argp_usage(state);
else if (state->arg_num == 0) {
arguments->from = arg;
break;
} else if (state->arg_num == 1) {
arguments->to = arg;
break;
}
break;
case ARGP_KEY_END:
if (!((arguments->mode == HASH && state->arg_num == 1) ||
(arguments->mode == NONCE && state->arg_num == 2) ||
(arguments->mode == DICTIONARY && state->arg_num == 2)))
argp_usage(state);
break;
default:
return ARGP_ERR_UNKNOWN;
}
return 0;
}
int main(int argc, char *argv[]) {
char *argp_program_version = "SACT v1.0";
char *argp_program_bug_address = "konstantin.fickel@student.uni-augsburg.de";
char doc[] = "A program calculating collisions of the Solidity ABI.";
char args_doc[] = "from to";
struct argp_option options[] = {
{"mode", 'm', "HASH|DICTIONARY|NONCE", 0, "Mode of execution."},
{"from-prefix", 'f', "STRING", 0, "Prefix to be used on the from-side."},
{"to-prefix", 't', "FILE", 0, "Prefix to be used on the to-side."},
{"threads", 'c', "INTEGER", 0,
"Amount of threads used when no dictionary is used at the from-side."},
{0}};
struct arguments arguments;
arguments.mode = HASH;
arguments.from = NULL;
arguments.fromPrefix = NULL;
arguments.to = NULL;
arguments.toPrefix = NULL;
arguments.threadCount = 4;
struct argp argp = {options, arguments_parse, args_doc, doc};
argp_parse(&argp, argc, argv, 0, 0, &arguments);
if (arguments.mode == DICTIONARY) {
bruteforce_mode_dictionary(arguments.from, arguments.to,
arguments.fromPrefix, NULL, arguments.toPrefix,
NULL);
return EXIT_SUCCESS;
} else if (arguments.mode == NONCE) {
bruteforce_mode_nonce(
arguments.fromPrefix == NULL ? "" : arguments.fromPrefix,
arguments.from, arguments.toPrefix == NULL ? "" : arguments.toPrefix,
arguments.to, arguments.threadCount);
return EXIT_SUCCESS;
} else if (arguments.mode == HASH) {
char *hash;
calculate_contract_abi_hash(arguments.from, &hash);
printf("%s\n", hash);
free(hash);
return EXIT_SUCCESS;
}
return EXIT_FAILURE;
}
|
C
|
#include <stdlib.h> // C standard library include
#include <stdio.h> // I/O library include
#include <unistd.h> // Needed for fork() call
#include <sys/types.h> // Needed for waitpid routine (and other things...)
#include <sys/wait.h> // Needed for waitpid() routine
void first_processing_job(int *); // Routine to do the first processing job
void second_processing_job(int *); // Routine to do the second processing job
void finalize_processing(int, int); // Routine to finalize processing
main(void) {
pid_t child1_pid, child2_pid; // Child process ID's
int status; // Status variable for waitpid() call
int job1numIterations; // Number of iterations in Job1
int job2numIterations; // Number of iterations in Job2
job1numIterations = 0; // Initialize job1's iteration count
job2numIterations = 0; // Initialize job2's iteration count
if ((child1_pid = fork()) == 0) { // first child process
printf(" Process ID = %d (inside first forked() process)\n", child1_pid);
first_processing_job(&job1numIterations);
printf(" First process iterations: %d\n", job1numIterations);
exit(0);
}
if ((child2_pid = fork()) == 0) { // second child process
printf(" Process ID = %d (inside second forked() process)\n", child2_pid);
second_processing_job(&job2numIterations);
printf(" Second process iterations: %d\n", job2numIterations);
exit(0);
}
printf("Process ID of first process = %d\n", child1_pid);
printf("Process ID of second process = %d\n", child2_pid);
// Wait for both processes to compelte
waitpid(child1_pid, &status, 0);
waitpid(child2_pid, &status, 0);
// Sumarize information from the two processing jobs
finalize_processing(job1numIterations, job2numIterations);
return 0;
}
void first_processing_job(int *numIterations) {
int i,j,x;
for (i=0; i<4; ++i) {
printf(" --> first job doing something...\n");
// Do some processing here!
sleep(5);
(*numIterations)++;
}
}
void second_processing_job(int *numIterations) {
int i,j,x;
for (i=0; i<4; ++i) {
printf(" --> second job doing something!!!\n");
// Do some processing here!
sleep(3);
(*numIterations)++;
}
}
void finalize_processing(int one_times, int another_times) {
int total;
total = one_times + another_times;
printf("Processing Summary:\n");
printf(" Total number of iterations: %d\n", total);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <dbus/dbus.h> //dbus 헤더파일
static void publish(DBusConnection *connection)
{
DBusMessage *message;
message = dbus_message_new_signal("/org/share/linux", "org.share.linux", "publish");
/* Send the signal */
dbus_connection_send (connection, message, NULL);
dbus_message_unref(message);
}
int main (int argc, char **argv)
{
DBusConnection *connection;
DBusError error;
dbus_error_init (&error);
connection = dbus_bus_get (DBUS_BUS_SYSTEM, &error);
if (!connection)
{
printf ("Failed to connect to the D-BUS daemon: %s", error.message);
dbus_error_free (&error);
return 1;
}
publish(connection);
return 0;
}
|
C
|
/* ************************************************************************** */
/* LE - / */
/* / */
/* expand_tilde.c .:: .:/ . .:: */
/* +:+:+ +: +: +:+:+ */
/* By: mmoya <mmoya@student.le-101.fr> +:+ +: +: +:+ */
/* #+# #+ #+ #+# */
/* Created: 2019/02/25 18:38:33 by mmoya #+# ## ## #+# */
/* Updated: 2019/05/07 13:33:44 by mmoya ### #+. /#+ ###.fr */
/* / */
/* / */
/* ************************************************************************** */
#include "parse/expand.h"
static char *expand_getdir(t_cmd *cmd, t_sh_state *sh_state, size_t i)
{
char *new;
new = NULL;
if (cmd->str[i + 1] == '+')
new = get_stored(sh_state->internal_storage, "PWD");
else if (cmd->str[i + 1] == '-')
new = get_stored(sh_state->internal_storage, "OLDPWD");
return (new);
}
static char *expand_getuhome(char *str, size_t len)
{
struct passwd *user;
char *new;
char *tmp;
user = NULL;
if (!(tmp = ft_strndup(str, len)))
return (NULL);
if (!(user = getpwnam(tmp)))
{
ft_strdel(&tmp);
return (NULL);
}
new = ft_strdup(user->pw_dir);
ft_strdel(&tmp);
return (new);
}
char *expand_gethome(t_sh_state *sh_state)
{
struct passwd *user;
char *new;
user = NULL;
new = get_stored(sh_state->internal_storage, "HOME");
if (!new)
{
if (!(user = getpwuid(getuid())))
return (NULL);
new = ft_strdup(user->pw_dir);
}
return (new);
}
static int expand_tilde(t_cmd *cmd, t_sh_state *sh_state, size_t i, size_t end)
{
char *new;
char *tmp;
int len;
if (end - i - 1 == 0)
new = expand_gethome(sh_state);
else if (end - i - 1 == 1)
new = expand_getdir(cmd, sh_state, i);
else
new = expand_getuhome(cmd->str + i + 1, end - i - 1);
if (new)
{
len = ft_strlen(new);
if (!(tmp = strinsert(cmd->str, new, i, end)))
{
ft_strdel(&new);
return (0);
}
ft_strdel(&new);
cmd->str = tmp;
return (len);
}
return (0);
}
int parse_tilde(t_cmd *cmd, t_sh_state *sh_state)
{
size_t i;
size_t end;
i = 0;
end = 0;
while (cmd->str[i])
{
while (cmd->str[i] && is_quoted(cmd->str, i))
i++;
if (cmd->str[i] == '~' && (i == 0 || ft_isspace(cmd->str[i - 1])))
{
end = i;
while (cmd->str[end] && !ft_isspace(cmd->str[end]) &&
cmd->str[end] != '/')
end++;
i += expand_tilde(cmd, sh_state, i, end);
}
cmd->str[i] ? i++ : 0;
}
return (0);
}
|
C
|
/**
*Author: SungHa Park
*Date: 08/30/1018
*This program prompts user
*to enter the latitude and longitude
*of two locations and then computes
*the distance between them using the above formulas
*
*/
#include<stdlib.h>
#include<stdio.h>
#include<math.h>
int main(int argc, char **argv) {
double latitudeA, latitudeB, longitudeA, longitudeB;
printf("Enter the latitude of location A: ");
scanf("%lf", &latitudeA);
printf("\n");
printf("Enter the longitude of location A: ");
scanf("%lf", &longitudeA);
printf("\n");
printf("Enter the latitude of location B: ");
scanf("%lf", &latitudeB);
printf("\n");
printf("Enter the longitude of location B: ");
scanf("%lf", &longitudeB);
printf("\n");
double latitudeAR, latitudeBR, longitudeAR, longitudeBR;
latitudeAR = (latitudeA/180)*M_PI;
latitudeBR = (latitudeB/180)*M_PI;
longitudeAR = (longitudeA/180)*M_PI;
longitudeBR = (longitudeB/180)*M_PI;
double Dif = longitudeBR - longitudeAR;
double Dis = acos(sin(latitudeAR)*sin(latitudeBR)+cos(latitudeAR)*cos(latitudeBR)*cos(Dif))*6371;
printf("Origin: %f, %f\n Destination: %f, %f\n Air distance is: %f\n", latitudeA, longitudeA, latitudeB, longitudeB, Dis);
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
/** 1.1 **/
/**
void cargarString(char** str){
int i=0;char aux;
*str=malloc(sizeof(char));
aux=getche();
while(aux!='\r'){
*(*str+i)=aux;
i++;
*str=realloc(*str,sizeof(char)*(i+2));
aux=getche();
}
*(*str+i)='\0';
} **/
/** 1.2 **/
/**
void ordenar(t_per** per){
int i=0,j=0;t_per aux;
for(i=0;(*(*per+i))->dni!=0;i++)
{
for(j=i+1;*(*per+j))->dni!=0;j++)
{
if(((*(*per+i))->dni)<((*(*per+i))->dni)){
aux=*per+i;
*per+i=*per+j;
*per+j=aux;
}
}
}
}**/
/** 2.1 h) **/
/**
int foo(int n, int m){
int miFoo=1;
if(m>0){
miFoo=n*foo(n,m-1);
}
return miFoo;
}
int main(){
printf("%d",foo(3,4));
return 0;
}**/
/** 2.2 a)(0,0) **/
/**
int main(){
char*s[5];int i=0;
char c='2';
s[i]=&c; //0 false y 1 true
for(i=0;i<5;i++){
s[i]=&c;
c=c+1;
}
printf("%d,%d",(c=='2'),!(s[0]==&c));
return 0;
}**/
/** 2.3 f)error ejecucion **/
/**
int main(){
char* s=NULL; int i;
for(i=0;i<4;i++){
*(s+i)='a'+i;
}
s[i]='\0';
printf("%s",s); ///esto es valido OJOOOO!!!
return 0;
}**/
/**2.4 e)0 **/
/**
int foo(unsigned char n, unsigned char filter){
return n& ( (255&(filter<<n+n))>1);
}
int main(){
printf("%u",foo(3,4));
return 0;
}
**/
|
C
|
/*
* jraid-btree.h
*
* Copyright(C) 2019
* Contact: JeCortex@yahoo.com
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
#ifndef __JRAID_BTREE_H__
#define __JRAID_BTREE_H__
#include "jraid-block-manager.h"
#include <linux/types.h>
#include <linux/kernel.h>
#ifdef __CHECKER__
# define __jd_written_to_disk(x) __releases(x)
# define __jd_reads_from_disk(x) __acquires(x)
# define __jd_bless_for_disk(x) __acquire(x)
# define __jd_unblessfor_disk(x) __release(x)
#else
# define __jd_written_to_disk(x)
# define __jd_reads_from_disk(x)
# define __jd_bless_for_disk(x)
# define __jd_unbless_for_disk(x)
#endif
struct jd_transaction_manager;
extern struct jd_block_validator btree_node_validator;
enum node_flags {
INTERNAL_NODE = 1,
LEAF_NODE = 1 << 1
};
/*
* Every btree node begins with this structure. make sure it's a multiple
* of 8-bytes in size, otherwise the 64bit keys will be mis-aligned.
*/
struct node_header {
__le32 csum;
__le32 flags;
__le64 blocknr;
__le32 nr_entries;
__le32 max_entries;
__le32 value_size;
__le32 padding;
} __packed;
struct btree_node {
struct node_header header;
__le64 keys[0];
} __packed;
struct jd_btree_value_type {
void *context;
uint32_t size;
void (*inc)(void *context, const void *value);
void (*dec)(void *context, const void *value);
int (*equal)(void *context, const void *value1, const void *value2);
};
struct shadow_spine {
struct jd_btree_info *info;
int count;
struct jd_block *nodes[2];
jd_block_t root;
};
struct jd_btree_info {
struct jd_transaction_manager *tm;
/*
* Number of nested btrees. (not the depth of a single tree.)
*/
unsigned levels;
struct jd_btree_value_type value_type;
};
struct ro_spine {
struct jd_btree_info *info;
int count;
struct jd_block *nodes[2];
};
static inline void *value_base(struct btree_node *n)
{
return &n->keys[le32_to_cpu(n->header.max_entries)];
}
static inline void *value_ptr(struct btree_node *n, uint32_t index)
{
uint32_t value_size = le32_to_cpu(n->header.value_size);
return value_base(n) + (value_size * index);
}
/*
* Assumes the values are suitably-aligned and converts to core format.
*/
static inline uint64_t value64(struct btree_node *n, uint32_t index)
{
__le64 *values_le = value_base(n);
return le64_to_cpu(values_le[index]);
}
static inline __le64 *key_ptr(struct btree_node *n, uint32_t index)
{
return n->keys + index;
}
int jd_btree_empty(struct jd_btree_info *info, jd_block_t *root);
int jd_btree_lookup(struct jd_btree_info *info, jd_block_t root,
uint64_t *keys, void *value_le);
int jd_btree_insert(struct jd_btree_info *info, jd_block_t root,
uint64_t *keys, void *value, jd_block_t *new_root)
__jd_written_to_disk(value);
int jd_btree_remove(struct jd_btree_info *info, jd_block_t root,
uint64_t *keys, jd_block_t *new_root);
void inc_children(struct jd_transaction_manager *tm, struct btree_node *n,
struct jd_btree_value_type *vt);
struct jd_block *shadow_current(struct shadow_spine *s);
int jd_tm_read_lock(struct jd_transaction_manager *tm, jd_block_t b,
struct jd_block_validator *v,
struct jd_block **blk);
int lower_bound(struct btree_node *n, uint64_t key);
int shadow_step(struct shadow_spine *s, jd_block_t b,
struct jd_btree_value_type *vt);
int shadow_has_parent(struct shadow_spine *s);
int shadow_root(struct shadow_spine *s);
struct jd_block *shadow_parent(struct shadow_spine *s);
int exit_shadow_spine(struct shadow_spine *s);
void init_le64_type(struct jd_transaction_manager *tm,
struct jd_btree_value_type *vt);
void init_shadow_spine(struct shadow_spine *s, struct jd_btree_info *info);
#endif
|
C
|
#include<stdio.h>
int main()
{
int n,t;
scanf("%d %d",&n,&t);
int a[n],i,j;
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
int c=0,d=0,k=0,b=0;
for(i=0;i<n;i++)
{
c=c+a[i];
d++;
if(c>t)
{
i=b;
b++;
c=0;
d=0;
}
if(k<d)
k=d;
}
printf("%d\n",k);
}
|
C
|
#include <stdio.h>
#include <string.h>
int main() {
char exp[11];
while (scanf("%s", exp) != EOF) {
size_t i;
for (i = 0; i < strlen(exp); i++) {
if (exp[i] == '+' || exp[i] == '-') {
break;
}
}
char numst1[11], numst2[11];
int num1, num2;
size_t j;
for (j = 0; j < i; j++) {
numst1[j] = exp[j];
}
numst1[j] = '\0';
for (j = i+1; j < strlen(exp)+1; j++) {
numst2[j-i-1] = exp[j];
}
num1 = atoi(numst1);
num2 = atoi(numst2);
switch (exp[i]) {
case '+':
printf("%d\n", num1+num2);
break;
default:
printf("%d\n", num1-num2);
break;
}
}
}
|
C
|
#include "tournament.h"
#include "player.h"
#include "string.h"
#include "stdlib.h"
struct tournament_t {
char* location;
int max_games_per_player;
TournamentStatus status;
int max_play_time;
int number_of_players;
int winner_id;
Map games;
};
void* copyTournament(void* tournament)
{
if (tournament == NULL) {
return NULL;
}
Tournament new_tournament = createTournament(((Tournament) tournament)->max_games_per_player,
((Tournament) tournament)->location,
((Tournament) tournament)->status,
((Tournament) tournament)->max_play_time,
((Tournament) tournament)->number_of_players,
((Tournament) tournament)->winner_id);
MAP_FOREACH(int*, i, ((Tournament) tournament)->games) {
if (mapPut(new_tournament->games, i, mapGet(((Tournament) tournament)->games, i)) != MAP_SUCCESS) {
freeTournament(new_tournament);
freeGameIndex(i);
return NULL;
}
freeGameIndex(i);
}
return new_tournament;
}
void* copyTournamentId(void* tournament_id)
{
if (tournament_id == NULL) {
return NULL;
}
int* new_tournament_id = malloc(sizeof(*new_tournament_id));
if (new_tournament_id == NULL) {
return NULL;
}
*new_tournament_id = *(int*) tournament_id;
return new_tournament_id;
}
void freeTournament(void* tournament)
{
if (tournament == NULL) {
return;
}
mapDestroy(((Tournament) tournament)->games);
free(((Tournament) tournament)->location);
free(tournament);
}
void freeTournamentId(void* tournament_id)
{
free(tournament_id);
}
int compareTournamentId(void* first_tournament_id, void* second_tournament_id)
{
if (first_tournament_id == NULL || second_tournament_id == NULL) {
return 0;
}
return *(int*) first_tournament_id - *(int*) second_tournament_id;
}
Tournament createTournament(int max_games_per_player, const char* tournament_location,
TournamentStatus status, int max_play_time, int number_of_players, int winner_id)
{
if (tournament_location == NULL) {
return NULL;
}
Tournament tournament = malloc(sizeof(*tournament));
if (tournament == NULL) {
return NULL;
}
char* location = malloc(strlen(tournament_location) + 1);
if (location == NULL) {
free(tournament);
return NULL;
}
strcpy(location, tournament_location);
Map games = mapCreate(copyGame, copyGameIndex, freeGame, freeGameIndex, compareGameIndex);
if (games == NULL) {
free(location);
free(tournament);
return NULL;
}
tournament->location = location;
tournament->max_games_per_player = max_games_per_player;
tournament->status = status;
tournament->max_play_time = max_play_time;
tournament->number_of_players = number_of_players;
tournament->winner_id = winner_id;
tournament->games = games;
return tournament;
}
const char* getTournamentLocation(Tournament tournament)
{
if (tournament == NULL) {
return NULL;
}
return tournament->location;
}
int getMaxGamesPerPlayer(Tournament tournament)
{
return tournament->max_games_per_player;
}
int getPlayerParticipationNumber(Tournament tournament, int player_id)
{
int counter = 0;
MAP_FOREACH(int*, i, tournament->games) {
Game game = mapGet(tournament->games, i);
if (player_id == getFirstPlayerId(game) || player_id == getSecondPlayerId(game)) {
counter++;
}
freeGameIndex(i);
}
return counter;
}
Map getTournamentGames(Tournament tournament)
{
if (tournament == NULL) {
return NULL;
}
return tournament->games;
}
int getTournamentNumberOfGames(Tournament tournament)
{
if (tournament == NULL) {
return 0;
}
return mapGetSize(tournament->games);
}
TournamentStatus getTournamentStatus(Tournament tournament)
{
if (tournament == NULL) {
return ENDED;
}
return tournament->status;
}
int getTournamentWinner(Tournament tournament)
{
if (tournament == NULL) {
return INVALID_PLAYER_ID;
}
return tournament->winner_id;
}
int getTournamentMaxPlayTime(Tournament tournament)
{
if (tournament == NULL) {
return 0;
}
return tournament->max_play_time;
}
double getTournamentAveragePlayTime(Tournament tournament)
{
if (tournament == NULL) {
return 0;
}
double average_play_time = 0;
MAP_FOREACH(int*, game_index, tournament->games) {
Game game = mapGet(tournament->games, game_index);
average_play_time += getPlayTime(game);
freeGameIndex(game_index);
}
if (getTournamentNumberOfGames(tournament) > 0) {
average_play_time /= getTournamentNumberOfGames(tournament);
}
return average_play_time;
}
int getTournamentNumberOfPlayers(Tournament tournament)
{
if (tournament == NULL) {
return 0;
}
return tournament->number_of_players;
}
void setTournamentStatus(Tournament tournament, TournamentStatus status)
{
if (tournament == NULL) {
return;
}
tournament->status = status;
}
void setTournamentWinner(Tournament tournament, int winner_id)
{
if (tournament == NULL) {
return;
}
tournament->winner_id = winner_id;
}
bool isGameExist(Tournament tournament, int first_player_id, int second_player_id)
{
if (tournament == NULL || first_player_id <= INVALID_PLAYER_ID || second_player_id <= INVALID_PLAYER_ID) {
return false;
}
MAP_FOREACH(int*, i, tournament->games) {
Game game = mapGet(tournament->games, i);
if (getFirstPlayerId(game) == first_player_id && getSecondPlayerId(game) == second_player_id) {
freeGameIndex(i);
return true;
}
if (getFirstPlayerId(game) == second_player_id && getSecondPlayerId(game) == first_player_id) {
freeGameIndex(i);
return true;
}
freeGameIndex(i);
}
return false;
}
static bool isPlayerInTournament(Tournament tournament, int player_id)
{
if (tournament == NULL || player_id <= INVALID_PLAYER_ID) {
return false;
}
MAP_FOREACH(int*, game_index, tournament->games) {
Game game = mapGet(tournament->games, game_index);
if (player_id == getFirstPlayerId(game) || player_id == getSecondPlayerId(game)) {
freeGameIndex(game_index);
return true;
}
freeGameIndex(game_index);
}
return false;
}
MapResult addTournamentGame(Tournament tournament, int first_player, int second_player, Winner winner, int play_time)
{
if (tournament == NULL) {
return MAP_NULL_ARGUMENT;
}
Game game = createGame(first_player, second_player, winner, play_time);
if (game == NULL) {
return MAP_OUT_OF_MEMORY;
}
if (!isPlayerInTournament(tournament, first_player)) {
tournament->number_of_players++;
}
if (!isPlayerInTournament(tournament, second_player)) {
tournament->number_of_players++;
}
int index = mapGetSize(tournament->games);
MapResult result = mapPut(tournament->games, &index, game);
if (result != MAP_SUCCESS) {
freeGame(game);
return result;
}
freeGame(game);
if (tournament->max_play_time < play_time) {
tournament->max_play_time = play_time;
}
return MAP_SUCCESS;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#define COLUMN_SIZE 4096
extern int v[COLUMN_SIZE];
extern int num_rows;
typedef int Array[][COLUMN_SIZE];
void matvec(Array matrix,int result[]){
for(int b=0;b<num_rows;b+=1){
result[b] = 0;
}
for(int a=0;a<COLUMN_SIZE;a+=1){
for(int b=0;b<num_rows;b+=1){
result[b] += matrix[b][a] * v[a];
}
}
}
|
C
|
#include <stdio.h>
#include <cs50.h>
#include <string.h>
#include <ctype.h>
int main(int argc, string argv[])
{
bool keySuccessful = false;
int key = 0;
int input_length = 0;
string text = "";
do
{
if(argc != 2)
{
printf("You didn't submit a valid encryption key.\n");
printf("Please check your input and re-run the programm.\n");
printf("We require an integer as encryption key.\n");
return 1;
}
else
{
key = atoi(argv[1]);
keySuccessful = true;
}
} while(!keySuccessful);
text = GetString();
input_length = strlen(text);
for(int i = 0; i < input_length; i++)
{
if(isalpha(text[i]))
{
if(islower(text[i]))
{
printf("%c", ((((text[i] - 97)+key)%26)+97));
}
else
{
printf("%c", ((((text[i] - 65)+key)%26)+65));
}
}
else
{
printf("%c", text[i]);
}
}
printf("\n");
return 0;
}
|
C
|
/* ====================================================================
* Copyright (c) 1997-2000 Carnegie Mellon University. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* This work was supported in part by funding from the Defense Advanced
* Research Projects Agency and the National Science Foundation of the
* United States of America, and the CMU Sphinx Speech Consortium.
*
* THIS SOFTWARE IS PROVIDED BY CARNEGIE MELLON UNIVERSITY ``AS IS'' AND
* ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY
* NOR ITS EMPLOYEES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* ====================================================================
*
*/
/*********************************************************************
*
* File: heap.c
*
* Description:
* Maintain a list of floating point values and a corresponding
* list of keys in a heap.
*
* Author:
* Pirated from Algorithms book.
*********************************************************************/
#include <sphinxbase/err.h>
#include <s3/heap.h>
#include <s3/s3.h>
#define LEFT(i) ((i<<1) + 1)
#define RIGHT(i) ((i<<1) + 2)
#define PARENT(i) ((i-1) >> 1)
/*
* float32 heaps
*/
int
heap32b_max_comp(float32 a, float32 b)
{
return (a > b);
}
int
heap32b_min_comp(float32 a, float32 b)
{
return (a < b);
}
void
heapify32b(float32 *a, uint32 *k,
uint32 i,
uint32 sz,
hcmpfn32b_t cmp)
{
uint32 l, r, b, t_k;
float32 t_a;
l = LEFT(i);
r = RIGHT(i);
/* Determine the "best" node of i, l or r */
if ((l < sz) && cmp(a[l], a[i]))
b = l;
else
b = i;
if ((r < sz) && cmp(a[r], a[b]))
b = r;
/* If node i is not the first in the ordering,
* then switch i with the left or right child that is first and
* heapify the the tree rooted at the new node i position
*/
if (b != i) {
/* exchange the values... */
t_a = a[i];
a[i] = a[b];
a[b] = t_a;
/* ... and the keys */
t_k = k[i];
k[i] = k[b];
k[b] = t_k;
heapify32b(a, k, b, sz, cmp);
}
}
void
heap32b_a2h(float32 *a, uint32 *k, uint32 sz, hcmpfn32b_t cmp)
{
int32 i;
for (i = (sz>>1)-1; i >= 0; i--)
heapify32b(a, k, i, sz, cmp);
}
uint32
heap32b_ins(float32 *a, uint32 *k, uint32 sz,
float32 a_v, uint32 k_v,
hcmpfn32b_t cmp)
{
uint32 i, p;
++sz;
i = sz-1;
p = PARENT(i);
/* if the parent does not satisfy the ordering,
* then switch with i */
while ((i > 0) && !cmp(a[p], a_v)) {
a[i] = a[p];
k[i] = k[p];
i = p;
p = PARENT(p);
}
a[i] = a_v;
k[i] = k_v;
return sz;
}
uint32
heap32b_extr_top(float32 *out_a,
uint32 *out_k,
float32 *a, uint32 *k, uint32 sz,
hcmpfn32b_t cmp)
{
if (sz < 1) {
E_ERROR("Heap underflow\n");
return NO_KEY;
}
*out_a = a[0];
*out_k = k[0];
a[0] = a[sz-1];
k[0] = k[sz-1];
sz--;
heapify32b(a, k, 0, sz, cmp);
return sz;
}
/*
* float64 heaps
*/
int
heap64b_max_comp(float64 a, float64 b)
{
return (a > b);
}
int
heap64b_min_comp(float64 a, float64 b)
{
return (a < b);
}
void
heapify64b(float64 *a, uint32 *k,
uint32 i,
uint32 sz,
hcmpfn64b_t cmp)
{
uint32 l, r, b, t_k;
float64 t_a;
l = LEFT(i);
r = RIGHT(i);
/* Determine "best" node
* given node i and its left and right
* children
*/
if ((l < sz) && cmp(a[l], a[i]))
b = l;
else
b = i;
if ((r < sz) && cmp(a[r], a[b]))
b = r;
/* If node i is not the first in the ordering,
* then switch i with the left or right child that is first and
* heapify the the tree rooted at the new node i position
*/
if (b != i) {
/* exchange the values... */
t_a = a[i];
a[i] = a[b];
a[b] = t_a;
/* ... and the keys */
t_k = k[i];
k[i] = k[b];
k[b] = t_k;
heapify64b(a, k, b, sz, cmp);
}
}
void
heap64b_a2h(float64 *a, uint32 *k, uint32 sz, hcmpfn64b_t cmp)
{
int32 i;
for (i = (sz>>1)-1; i >= 0; i--)
heapify64b(a, k, i, sz, cmp);
}
uint32
heap64b_ins(float64 *a, uint32 *k, uint32 sz,
float64 a_v, uint32 k_v,
hcmpfn64b_t cmp)
{
uint32 i, p;
++sz;
i = sz-1;
p = PARENT(i);
/* if the parent does not satisfy the ordering,
* then switch with i */
while ((i > 0) && !cmp(a[p], a_v)) {
a[i] = a[p];
k[i] = k[p];
i = p;
p = PARENT(p);
}
a[i] = a_v;
k[i] = k_v;
return sz;
}
uint32
heap64b_extr_top(float64 *out_a,
uint32 *out_k,
float64 *a, uint32 *k, uint32 sz,
hcmpfn64b_t cmp)
{
if (sz < 1) {
E_ERROR("Heap underflow\n");
return NO_KEY;
}
*out_a = a[0];
*out_k = k[0];
/* grab some item from the heap and
stick it in the hole */
a[0] = a[sz-1];
k[0] = k[sz-1];
sz--;
heapify64b(a, k, 0, sz, cmp);
return sz;
}
#ifdef TEST
#include <stdio.h>
main()
{
float64 a[] = {4,1,3,2,16,9,10,14,8,7};
float64 h[] = {4,1,3,2,16,9,10,14,8,7};
float64 t_a;
uint32 k[] = {0,1,2,3, 4,5, 6, 7,8,9};
uint32 t_k;
uint32 i, sz;
printf("a[] ==");
for (i = 0; i < 10; i++) {
printf(" %3.1f", a[i]);
}
printf("\n");
printf("k[] ==");
for (i = 0; i < 10; i++) {
printf(" %3u", k[i]);
}
printf("\n");
for (i = 0, sz = 0; i < 10; i++) {
sz = heap64b_ins(h, k, sz, a[i], i, &heap64b_min_comp);
}
for (i = 0; i < 10; i++) {
sz = heap64b_extr_top(&t_a, &t_k, h, k, sz, &heap64b_min_comp);
printf("%u %3.1f\n", t_k, t_a);
}
}
#endif
/*
* Log record. Maintained by RCS.
*
* $Log$
* Revision 1.4 2004/07/21 18:05:39 egouvea
* Changed the license terms to make it the same as sphinx2 and sphinx3.
*
* Revision 1.3 2001/04/05 20:02:30 awb
* *** empty log message ***
*
* Revision 1.2 2000/09/29 22:35:13 awb
* *** empty log message ***
*
* Revision 1.1 2000/09/24 21:38:31 awb
* *** empty log message ***
*
* Revision 1.1 97/07/16 11:36:22 eht
* Initial revision
*
*
*/
|
C
|
// See LICENSE for license details.
#include <stdint.h>
#include <stddef.h>
#include <assert.h>
#include <stdlib.h>
#include <stdio.h>
#ifndef BAREMETAL
#include <sys/mman.h>
#endif
#include "include/gemmini.h"
#if (N*DIM) > (BANK_NUM*BANK_ROWS)
#error not enough scratchpad space
#endif
elem_t extract_4bit_signed(elem_t num, elem_t high) {
elem_t mask = 0b1111;
if (high) {
num = num >> 4;
}
num = num & mask;
elem_t extend = (num >> 3) & 1;
if (extend) {
return num | 0xf0;
} else {
return num;
}
}
void decompress_matrix(elem_t src[DIM][DIM/2], elem_t dst[DIM][DIM]) {
for (size_t i = 0; i < DIM; ++i) {
for (size_t j = 0; j < DIM; ++j) {
dst[i][j] = extract_4bit_signed(src[i][j/2], j % 2);
}
}
}
int main() {
#ifndef BAREMETAL
if (mlockall(MCL_CURRENT | MCL_FUTURE) != 0) {
perror("mlockall failed");
exit(1);
}
#endif
// printf("Flush\n");
gemmini_flush(0);
static elem_t In[DIM][DIM/2] row_align(1);
static elem_t In_decompressed[DIM][DIM] row_align(1);
static elem_t Out[2][DIM][DIM] row_align(1);
// Matrix used to make sure the mvout doesn't write more than DIM * DIM/2 bytes
static elem_t OneTwentyThree[DIM][DIM] row_align(1);
for (size_t i = 0; i < DIM; ++i) {
for (size_t j = 0; j < DIM; ++j) {
In[i][j/2] = (rand() % 256);
Out[1][i][j] = 123;
OneTwentyThree[i][j] = 123;
}
}
printf("Set the load bitwidth to 4 (2^2)\n");
gemmini_config_ld_precision_bits(DIM /2, 2); // Use 2 because 4 = 2^2
printf("Move In the data\n");
gemmini_mvin(In, DIM);
printf("Set the store bitwidth to 8 (2^3)\n");
gemmini_config_st_precision_bits(DIM, 3); // Use 3 because 8 = 2^3
printf("Move Out the data\n");
gemmini_mvout(Out[0], DIM);
printf("Fence\n");
gemmini_fence();
decompress_matrix(In, In_decompressed);
int exitcode = 0;
if (!is_equal(In_decompressed, Out[0])) {
printf("Input and Output Matrix do not match\n");
printf("Matrix Input:\n");
printMatrix(In_decompressed);
printf("Matrix Output:\n");
printMatrix(Out[0]);
printf("\n");
exitcode = 1;
}
if (!is_equal(OneTwentyThree, Out[1])) {
printf("Output matrix had more than DIM * DIM/2 Bytes changed\n");
printf("Expected Leftover Bytes:\n");
printMatrix(OneTwentyThree);
printf("Actual Leftover Output:\n");
printMatrix(Out[1]);
printf("\n");
exitcode = 1;
}
if (exitcode == 0) {
printf("Success!\n");
}
exit(exitcode);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
int f(int n, int x, int y)
{
return (x + y*2 + 1)%n;
}
int main(int argc, char **argv)
{
int i, j, n = atoi(argv[1]);
for (i = 0; i < n; i++) {
for (j = 0; j < n; j++)
printf("% 4d", f(n, n - j - 1, i)*n + f(n, j, i) + 1);
putchar('\n');
}
return 0;
}
|
C
|
#include "input.h"
enum DIRECTION readInput (void) {
if (_kbhit()) {
int code = _getch();
enum DIRECTION dir;
switch(code) {
case 75: case 97: return LEFT;
case 72: case 119: return TOP;
case 77: case 100: return RIGHT;
case 80: case 115: return BOTTOM;
}
}
return NUL;
}
|
C
|
//Não deu tempo de terminar antes do prazo, mas farei depois para treinar para a prova
#include <stdio.h>
#include <stdlib.h>
#include "redesocial.h"
int M[NUM_PESSOAS][NUM_PESSOAS];
void inicializar_rede(){
int i, j;
for (i=0;i<NUM_PESSOAS;i++){
for (j=0;j<NUM_PESSOAS; j++){
M[i][j]=0;
}
}
}
void adicionar_amizade(int i, int j){
M [i][j] = 1;
M [j][i] = 1;
}
float random_float(){
float aux = rand()/RAND_MAX;
return aux;
}
void popularRedeSocialAleatoriamente(float P){
int i,j;
float aux;
for (i=0;i<NUM_PESSOAS;i++){
for (j=0;j<NUM_PESSOAS;j++){
aux = random_float();
if (i!=j && aux<P){ //if (i!=j && M[i][j] !=1 && aux<P){
adicionar_amizade;
}
}
}
}
void imprimirRedeSocial(){
int i,j;
for (i=0; i<NUM_PESSOAS;i++){
for (j=0; j<NUM_PESSOAS; j++){
printf ("%d ", M[i][j]);
}
printf ("\n");
}
}
int numAmigosEmComum(int v, int u){
}
|
C
|
#include<stdio.h>
//#include<string.h>
#include<math.h>
int main()
{
double s,a;
char t[3];
while(scanf("%lf%lf%s",&s,&a,&t)==3)
{
if(strcmp(t,"deg")==0)
{
if(a>180)
a=-360;
a=(a*M_PI)/180;
}
else
{
a=a/60;
if(a>180)
a=-360;
a=(a*M_PI)/180;
}
printf("%.6lf %.6lf\n",a*(s+6440),(sin(a)*(s+6440))/sin((M_PI-a)/2));
}
return 0;
}
|
C
|
#define _CRT_SECURE_NO_WARNINGS 1
#include <stdio.h>
#include <string.h>
void print_star()
{
printf("**********************\n");
}
void print_message()
{
printf(" How do you do ! \n");
}
int main()
{
print_star();
print_star();
print_message();
print_star();
print_star();
return 0;
}
//int main()
//{
// printf("**********************\n");
// printf(" How do you do ! \n");
// printf("**********************\n");
// return 0;
//}
//Ŀƣ
//ַת
//Ŀݣ
//дһжһַǷΪһַתַ֮
//磺s1 = AABCDs2 = BCDAA1
//s1 = abcds2 = ACBD0.
//AABCDһַõABCDA
//AABCDַõBCDAA
//AABCDһַõDAABC
//
//int main()
//{
// char arr1[] = "abcdef";
// char arr2[] = "cdefab";
// //arr2ǷΪarr1תõģ
// int i = 0;
// int len = strlen(arr1);
// for (i = 0; i < len; i++)
// {
// //ת1ַ
// char tmp = arr1[0];
// int j = 0;
// for (j = 0; j < len - 1; j++)
// {
// arr1[j] = arr1[j + 1];
// }
// arr1[len - 1] = tmp;
// //תַ֮arr2ȽǷ
// if (strcmp(arr1, arr2) == 0)
// {
// printf("arr2arr1ת\n");
// break;
// }
// }
// if (i == len)
// {
// printf("arr2arr1ת\n");
// }
// return 0;
//}
//ַת-
//Ŀƣ
//ַ
//Ŀݣ
//ʵһַеkַ
//磺
//ABCDһַõBCDA
//ABCDַõCDAB
#include <stdio.h>
#include <string.h>
//
//int main()
//{
//
// //2
// char arr[20] = "abcdef";
// int k = 4;
// int len = strlen(arr);
// int left = 0;
// int right = k - 1;
// //ߵַ
// while (left<right)
// {
// char tmp = arr[left];
// arr[left] = arr[right];
// arr[right] = tmp;
// left++;
// right--;
// }
// //ұߵַ
// left = k;
// right = len - 1;
// while (left<right)
// {
// char tmp = arr[left];
// arr[left] = arr[right];
// arr[right] = tmp;
// left++;
// right--;
// }
// //ַ
// left = 0;
// right = len - 1;
// while (left<right)
// {
// char tmp = arr[left];
// arr[left] = arr[right];
// arr[right] = tmp;
// left++;
// right--;
// }
// printf("%s\n", arr);
// //1
// //char arr[20] = "abcdef";
// //תַ
// //int k = 4;
// //int i = 0;
// //int len = strlen(arr);//6
//
// //for (i = 0; i < k; i++)
// //{
// // //ת1ַ
// // char tmp = arr[0];
// // int j = 0;
// // for (j = 0; j < len - 1; j++)
// // {
// // arr[j] = arr[j + 1];
// // }
// // arr[len - 1] = tmp;
// //}
//
// //printf("%s\n", arr);
//
// return 0;
//}
//ʹȫλżǰ档
//Ŀ
//һ飬ʵһ
//ֵ˳ʹеλǰ벿֣
//żλĺ벿֡
#include <stdio.h>
//
//int main()
//{
// int arr[10] = { 0 };
// int i = 0;
// int sz = sizeof(arr) / sizeof(arr[0]);
//
// for (i = 0; i < sz; i++)
// {
// scanf("%d", &arr[i]);
// }
// //Ԫ
// int left = 0;//±
// int right = sz - 1;//±
//
// while (left<right)
// {
// //ǰż
// while ((left <= right) && (arr[left] % 2 == 1))
// {
// left++;
// }
// //Ӻǰ
// while ((left <= right) && (arr[right] % 2 == 0))
// {
// right--;
// }
// //ҵż
// if (left < right)
// {
// int tmp = arr[left];
// arr[left] = arr[right];
// arr[right] = tmp;
// }
// }
//
// for (i = 0; i < sz; i++)
// {
// printf("%d ", arr[i]);
// }
//
// return 0;
//}
//
//int main()
//{
// //
// int arr[10] = { 0 };
// int i = 0;
// int sz = sizeof(arr) / sizeof(arr[0]);
// //1 2 3 4 5 6 7 8 9 10
// for (i = 0; i < sz; i++)
// {
// scanf("%d", &arr[i]);
// }
// //
// int tmp[10] = { 0 };
// //
// int j = 0;
// for (i = 0; i < sz; i++)
// {
// if (arr[i] % 2 == 1)
// {
// tmp[j] = arr[i];
// j++;
// }
// }
// //ż
// for (i = 0; i < sz; i++)
// {
// if (arr[i] % 2 == 0)
// {
// tmp[j] = arr[i];
// j++;
// }
// }
// //
// for (i = 0; i < sz; i++)
// {
// arr[i] = tmp[i];
// }
// //ӡ
// for (i = 0; i < sz; i++)
// {
// printf("%d ", arr[i]);
// }
//
// return 0;
//}
//
//
|
C
|
/*
** my_third_action.c for my_select in /home/saurs_f/rendu/PSU_2014_my_select
**
** Made by Florian Saurs
** Login <saurs_f@epitech.net>
**
** Started on Sat Jan 10 14:45:32 2015 Florian Saurs
** Last update Fri May 22 00:43:49 2015 guillaume wilmot
*/
#include "edit.h"
void my_left(t_tools tool, t_list **list, int buff, struct winsize argp)
{
int cmpt;
int nbr;
nbr = 1;
if (buff == LEFT)
{
cmpt = (*list)->cmpt;
(*list) = (*list)->next;
while ((*list)->cmpt != cmpt)
{
(*list) = (*list)->next;
++nbr;
}
if ((*list)->cmpt - argp.ws_row + 2 >= 0)
{
(*list)->pos = 0;
while (argp.ws_row - 2 > 0)
{
(*list) = (*list)->prev;
--argp.ws_row;
}
(*list)->pos = 1;
my_show_list(*list, tool, tool.command);
}
}
}
void print_my_list_right(t_list **list, struct winsize argp, t_tools tool)
{
(*list)->pos = 0;
while (argp.ws_row - 2 > 0)
{
(*list) = (*list)->next;
--argp.ws_row;
}
(*list)->pos = 1;
my_show_list(*list, tool, tool.command);
}
void my_right(t_tools tool, t_list **list, int buff, struct winsize argp)
{
int cmpt;
int nbr;
int max;
nbr = 1;
if (buff == RIGHT)
{
cmpt = (*list)->cmpt;
max = cmpt;
(*list) = (*list)->next;
while ((*list)->cmpt != cmpt)
{
if ((*list)->cmpt > max)
max = (*list)->cmpt;
(*list) = (*list)->next;
++nbr;
}
if (nbr > argp.ws_row - 2 && (*list)->cmpt + argp.ws_row - 2 <= max)
print_my_list_right(list, argp, tool);
}
}
void my_next(t_tools tool, t_list **list, int buff)
{
struct winsize argp;
struct termios tmp;
tmp.c_iflag = 0;
if (ioctl (0, TIOCGWINSZ, &argp) == -1)
{
my_restore(tool, tmp);
my_errors("Ioctl : error\n", NULL);
}
my_left(tool, list, buff, argp);
my_right(tool, list, buff, argp);
}
void my_conditions(t_tools tool, t_list **list, int buff)
{
if (buff == DOWN || buff == 9)
{
(*list)->pos = 0;
(*list) = (*list)->next;
(*list)->pos = 1;
my_show_list(*list, tool, tool.command);
}
else if (buff == UP)
{
(*list)->pos = 0;
*list = (*list)->prev;
(*list)->pos = 1;
my_show_list(*list, tool, tool.command);
}
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include "structureTree.h"
int a=0;
int b=0;
Node *makeNode( double x, double y, int level ) {
int i;
Node *node = (Node *)malloc(sizeof(Node));
node->level = level;
node->xy[0] = x;
node->xy[1] = y;
for( i=0;i<4;++i )
node->child[i] = NULL;
return node;
}
void makeChildren( Node *parent ) {
double x = parent->xy[0];
double y = parent->xy[1];
int level = parent->level;
double hChild = pow(2.0,-(level+1));
parent->child[0] = makeNode( x,y, level+1 );
parent->child[1] = makeNode( x+hChild,y, level+1 );
parent->child[2] = makeNode( x+hChild,y+hChild, level+1 );
parent->child[3] = makeNode( x,y+hChild, level+1 );
return;
}
void growTree( Node *head ){
int i;
if( head->child[0] == NULL )
makeChildren( head );
else {
for ( i=0; i<4; ++i ) {
growTree( head->child[i] );
}
}
return;
}
void destroyTree( Node *parent ) {
int i;
if( parent->child[0] == NULL )
free(parent);
else
{
for(i=0;i<4;++i)
{
destroyTree(parent->child[i]);
}
free(parent);
}
return;
}
void removeChildren(Node *parent) {
int i;
for(i=0;i<4;i++)
{
free(parent->child[i]);
parent->child[i]=NULL;
}
}
// Data functionvalue
double value( double x, double y, double time ) {
return( 2.0*exp(-8.0*(x-time)*(x-time)) - 1.0 ) ;
}
// Evaluate function at centre of quadtree node
double nodeValue( Node *node, double time ) {
int level = node->level;
double x = node->xy[0];
double y = node->xy[1];
double h = pow(2.0,-level);
return( value( x+0.5*h, y+0.5*h, time ) );
}
double judge( Node *head ){
int i,j;
head->flag=0;
if(head->child[0]==NULL)
{
if( nodeValue(head,0) < -0.5 )
head->flag=-1;
else if( nodeValue(head,0) > 0.5 )
head->flag= 1;
else
head->flag= 0;
}
else if(head->child[0]!=NULL)
{
for(i=0;i<4;i++)
judge(head->child[i]);
}
}
int *change( Node *node , int st[])
{
int i,j;
judge( node );
if(node->child[0]==NULL&& node->flag==1)
{
makeChildren(node);
st[0]+=4;
}
else if(node->child[0]!=NULL)
{
for(i=0;i<4;i++)
{
change( node->child[i] , st);
}
j=0;
for(i=0;i<4;i++)
{
if(node->child[i]->flag==-1)
j++;
}
if(j==4)
{
removeChildren(node);
st[1]+=4;
}
}
return st;
}
int *chang( Node *node , int st[])
{
int i,j;
int maxlevel=6;
if(node->child[0]==NULL&& node->flag==1&&node->level<maxlevel)
{
makeChildren(node);
st[0]+=4;
}
else if(node->child[0]!=NULL)
{
for(i=0;i<4;i++)
{
change( node->child[i] , st);
}
j=0;
for(i=0;i<4;i++)
{
if(node->child[i]->flag==-1)
j++;
}
if(j==4)
{
removeChildren(node);
st[1]+=4;
}
}
return st;
}
int *adapt( Node *node , int st[])
{
do
{
st[0]=0;
st[1]=0;
judge(node);
chang( node , st);
printf("%i\n%i\n",st[0],st[1]);
}
while(st[0]!=0 && st[1]!=0);
return;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <windows.h>
#include "main.h"
#include "proexe.h"
//size of fread/fwrite buffer
#define BUFFER_SIZE 4096
int exeSectionSize(FILE *fIn);
void restoreBackup(char* fileName, char* backupName);
void fixExe(char* fileName)
{
//makes a backup of the exe then fixes it
FILE *fIn, *fOut;
int exeSection;
long exeSize, written = 0;
int read;
char backupName[strlen(fileName) + 5];
void *buffer;
strcpy(backupName, fileName);
strcat(backupName, ".old");
//backup exe
if (MoveFile(fileName, backupName) == FALSE)
{
errorMsg("Can't backup exe.");
return;
}
if ((fIn = fopen(backupName, "rb")) == NULL)
{
restoreBackup(fileName, backupName);
errorMsg("Can't open backup for reading.");
return;
}
if ((fOut = fopen(fileName, "wb")) == NULL)
{
fclose(fIn);
restoreBackup(fileName, backupName);
errorMsg("Can't open file for writing");
return;
}
//find size of exe
fseek(fIn, 0, SEEK_END);
exeSize = ftell(fIn);
fseek(fIn, 0, SEEK_SET);
//find size of exe section
exeSection = exeSectionSize(fIn);
if (exeSection == -1)
{
//bad exe
fclose(fIn);
fclose(fOut);
restoreBackup(fileName, backupName);
return;
}
if (exeSection == exeSize)
{
//exe has no appended data
fclose(fIn);
fclose(fOut);
restoreBackup(fileName, backupName);
errorMsg("Exe has no appended data.");
}
buffer = malloc(BUFFER_SIZE);
if (buffer == NULL)
{
fclose(fIn);
fclose(fOut);
restoreBackup(fileName, backupName);
errorMsg("malloc failed.");
}
//copy backup file to new exe except for last 4 bytes
while ((read = fread(buffer, 1, BUFFER_SIZE, fIn)))
{
if (written + read >= exeSize - 4)
{
read = exeSize - 4 - written;
}
if (read > 0)
{
fwrite(buffer, 1, read, fOut);
written += read;
}
}
//write size of exe section to end of exe
fwrite(&exeSection, 4, 1, fOut);
free(buffer);
fclose(fIn);
fclose(fOut);
}
int exeSectionSize(FILE *fIn)
{
//returns size of exe section or -1 on error
char validSig[] = "MZ";
char fileSig[3];
fileSig[2] = 0;
int e_lfannew, pos, i , size;
short numberOfSections;
//check exe sig
fread(fileSig, 2, 1, fIn);
if (strcmp(validSig, fileSig) != 0)
{
errorMsg("Input file is not an exe.");
return -1;
}
//skip dos stub
fseek(fIn, 60, SEEK_SET);
fread(&e_lfannew, 1, 4, fIn);
fseek(fIn, e_lfannew + 6, SEEK_SET);
//IMAGE_FILE_HEADER
fread(&numberOfSections, 1, 2, fIn);
fseek(fIn, 240, SEEK_CUR);
//end of IMAGE_OPTIONAL_HEADER
//section directories
for (i = 0; i < numberOfSections; i++)
{
fseek(fIn, 16, SEEK_CUR);
fread(&size, 1, 4, fIn);
fread(&pos, 1, 4, fIn);
fseek(fIn, 16, SEEK_CUR);
}
//end of section directories
//seek back to start of file
fseek(fIn, 0, SEEK_SET);
return pos + size;
}
void restoreBackup(char* fileName, char* backupName)
{
//move backup file back to original location
DeleteFile(fileName);
MoveFile(backupName, fileName);
}
|
C
|
#include <stdlib.h>
#include "clientes.h"
#include "Item.h"
cliente cria_cliente(long int ref, char n, long int v_cheque, estado_geral* State)
{
cliente client;
client.ref=ref;
if (n=='b')
{
client.nchB = 1;
client.vchB = v_cheque;
client.nchE = 0;
client.vchE =0;
}
else
{
client.nchE = 1;
client.vchE = v_cheque;
client.nchB = 0;
client.vchB =0;
}
State->clientes_ativ++;
return client;
}
void altera_clientes(long int ref, char n, long int v_cheque, p_cabeca estrut, estado_geral* State)
{
linkC a;
cliente client;
a=searchR(cab(estrut),ref); /*procura o cliente para ver se ele ja existe ou nao na arvore; o a e um ponteiro para um no*/
if (a==NULL) /*caso em que o cliente nao existe na arvore*/
{
client = cria_cliente(ref,n,v_cheque, State);
cab(estrut)=insertR(cab(estrut), newItemC(client));
}
else if (n=='b')
{
if ((a->item).nchB == 0 && (a->item).nchE == 0)
State->clientes_ativ++;
(a->item).nchB++;
(a->item).vchB=(a->item).vchB+v_cheque;
}
else
{
if ((a->item).nchB == 0 && (a->item).nchE == 0)
State->clientes_ativ++;
(a->item).nchE++;
(a->item).vchE=(a->item).vchE+v_cheque;
}
}
void altera_infocliente(long int ref,long int v_cheque,char n,p_cabeca estrut, estado_geral* State)
{
linkC a;
a=searchR(cab(estrut),ref);
if (n=='b')
{
(a->item).nchB--;
(a->item).vchB=(a->item).vchB-v_cheque;
}
else
{
(a->item).nchE--;
(a->item).vchE=(a->item).vchE-v_cheque;
}
if ((a->item).nchB == 0 && (a->item).nchE == 0)
State->clientes_ativ--;
}
void print_info_clientes(linkC h)
{
if(h==NULL)
return;
print_info_clientes(h->l);
if((h->item).nchE !=0 || (h->item).nchB !=0 )
{
printf("*");
printItemC(h->item);
}
print_info_clientes(h->r);
}
|
C
|
/*
Transpose 4x4 matrix (in-place) using SSE instructions, $Revision: 1.4 $
Author: Wojciech Muła
e-mail: wojciech_mula@poczta.onet.pl
www: http://0x80.pl/
License: public domain
initial release 10.03.2002, last update $Date: 2008-06-08 23:00:44 $
*/
#include "sse-aux.c"
// start-snippet
void sse_transpose(float mat[4*4]) {
__asm__ volatile (
// 0 1 2 3 <- index
"movups 0x00(%0), %%xmm0 \n" // xmm0 := a0 a1 a2 a3
"movups 0x10(%0), %%xmm1 \n" // xmm1 := b0 b1 b2 b3
"movups 0x20(%0), %%xmm2 \n" // xmm2 := c0 c1 c2 c3
"movups 0x30(%0), %%xmm3 \n" // xmm3 := d0 d1 d2 d3
"movaps %%xmm0, %%xmm4 \n"
"unpcklps %%xmm2, %%xmm0 \n" // xmm0 := a0 c0 a1 c1
"unpckhps %%xmm2, %%xmm4 \n" // xmm4 := a2 c2 a3 c3
"movaps %%xmm1, %%xmm2 \n"
"unpcklps %%xmm3, %%xmm1 \n" // xmm1 := b0 d0 b1 d1
"unpckhps %%xmm3, %%xmm2 \n" // xmm2 := b2 d2 b3 d3
"movaps %%xmm0, %%xmm3 \n"
"unpcklps %%xmm1, %%xmm0 \n" // xmm0 := a0 b0 c0 d0
"unpckhps %%xmm1, %%xmm3 \n" // xmm3 := a1 b1 c1 d1
"movaps %%xmm4, %%xmm1 \n"
"unpcklps %%xmm2, %%xmm1 \n" // xmm1 := a2 b2 c2 d2
"unpckhps %%xmm2, %%xmm4 \n" // xmm4 := a3 b3 c3 d3
"movups %%xmm0, 0x00(%0) \n"
"movups %%xmm3, 0x10(%0) \n"
"movups %%xmm1, 0x20(%0) \n"
"movups %%xmm4, 0x30(%0) \n"
: "=r" (mat)
: "0" (mat)
: "memory"
);
}
// end-snippet
int main() {
initfrand();
float mat[4*4];
int i=0;
for (i=0; i < 4*4; i++)
mat[i] = i;
printf("M = \n");
for (i=0; i < 4; i++) print_vec_float(&mat[i*4]);
sse_transpose(mat);
printf("M^T = \n");
for (i=0; i < 4; i++) print_vec_float(&mat[i*4]);
return 0;
}
// vim: ts=4 sw=4 nowrap
|
C
|
#define F_CPU 16000000/* 16 MHz CPU clock */
#include <avr/io.h>
#include <avr/interrupt.h>
#include <util/delay.h>
void initLED() {
DDRC |= 0x80; //Nakes PORTC as Output
}
void Blink() {
PORTC |= 0x80; //Turns ON LEDs
_delay_ms(1000); //1 second delay
PORTC &= ~(0x80); //Turns OFF LEDs
_delay_ms(1000); //1 second delay
}
int main()
{
initLED();
while(1) //infinite loop
{
Blink();
}
return 0;
}
|
C
|
#include<stdio.h>
#include<string.h>
#define ll long long
int main()
{
ll gg,hh,i,j,k,n;
char s[55],p[1000005];
ll y[27]={0};
k=0;
scanf("%lld",&gg);
while(gg--)
{
scanf("%s",s);
j=strlen(s);
k+=j;
for(i=0;i<j;i++)
y[s[i]-'A']++;
}
scanf("%s",p);
n=strlen(p);
if(n<k)
{
printf("-1");
return 0;
}
ll z[27]={0};
for(i=0;i<n;i++)
z[p[i]-'A']++;
hh=0;
for(i=0;i<26;i++)
z[i]-=y[i];
for(i=0;i<26;i++)
if(z[i]<0)
hh+=(z[i]*-1);
printf("%lld",hh);
return 0;
}
|
C
|
#ifndef GAME_H_
#define GAME_H_
#include <unistd.h>
#include "snake.h"
typedef struct game_params g_params;
enum window_size { WIN_LINES = 24, WIN_COLS = 80 }; /* main window size */
enum level { /* level numbers */
LEVEL_1 = 1,
LEVEL_2,
LEVEL_3,
LEVEL_4,
LEVEL_5,
LEVEL_6,
LEVEL_7,
LEVEL_8,
LEVEL_9,
LEVEL_10
};
enum speed {
SNAKE_SPEED_DEFAULT = 60000, /* default snake sleep time (0,06s) */
SNAKE_SPEED_1 = 200000, /* level 1 snake sleep time (0,2s) */
SNAKE_SPEED_2 = 150000, /* level 2 snake sleep time (0,15s) */
SNAKE_SPEED_3 = 100000, /* level 3 snake sleep time (0,1s) */
SNAKE_SPEED_4 = 90000, /* level 4 snake sleep time (0,09s) */
SNAKE_SPEED_5 = 80000, /* level 5 snake sleep time (0,08s) */
SNAKE_SPEED_6 = 70000, /* level 6 snake sleep time (0,07s) */
SNAKE_SPEED_7 = 60000, /* level 7 snake sleep time (0,06s) */
SNAKE_SPEED_8 = 50000, /* level 8 snake sleep time (0,05s) */
SNAKE_SPEED_9 = 45000, /* level 9 snake sleep time (0,045s) */
SNAKE_SPEED_10 = 40000, /* level 10 snake sleep time (0,04s) */
};
enum keys {
ENTER_KEY = 10,
EXIT_KEY = 113, /* key "q" code */
YES_KEY = 121, /* key "y" code */
NO_KEY = 110 /* key "n" code */
};
/* standart VIM keys for snake control */
enum vim_keys {
VIM_UP = 107, /* key "k" code */
VIM_DOWN = 106, /* key "j" code */
VIM_RIGHT = 108, /* key "l" code */
VIM_LEFT = 104 /* key "h" code */
};
struct game_params {
long snake_speed; /* snake sleep time in microseconds (0,06s) */
int key_up; /* up-key code */
int key_down; /* down-key code */
int key_right; /* right-key code */
int key_left; /* left-key code */
};
int start_game(g_params* params);
void set_control_keys(g_params *params, int key_up, int key_down, int key_right, int key_left);
void set_snake_speed(g_params *params, enum speed snake_speed);
enum speed get_speed_value(char **argv, int arg_number);
enum speed calculate_snake_speed(enum level speed_level);
#endif
|
C
|
#include <stdio.h>
int main()
{
double pi = 3.14159, R, VOLUME;
scanf(" %lf", &R);
VOLUME = ((4.0/3.0) * pi * (R*R*R));
printf("VOLUME = %.3lf\n", VOLUME);
}
|
C
|
/* Name & Email: Jonathan Oaks, joaks001@ucr.edu
* Lab Section: 25
* Assignment: Final Project
* Exercise Description:
*
* Stepmania game.
* Gather input from the SNES controller
* Play music on Piezo Buzzers
* Display title and scores on LCD Screen
* Display game on 16x32 RGB LED Matrix
* Communicate with matrix using USART
*
* I acknowledge all content contained herein, excluding template or example
* code, is my own original work.
*/
#include <avr/io.h>
#include <avr/sleep.h>
#include "lcd_4bit.h"
#include "timer.h"
#include "usart.h"
#include "globals.h"
#include "controllerSM.h"
#include "lcdSM.h"
#include "music_playerSM.h"
#include "usartSM.h"
typedef struct _task {
/*Tasks should have members that include: state, period,
a measurement of elapsed time, and a function pointer.*/
signed char state; //Task's current state
unsigned long period; //Task period
unsigned long elapsed_time; //Time elapsed since last task tick
int (*TickFunction)(int); //Task tick function
} Task;
static Task controllerTask, lcdTask, musicTask, usartTask;
static Task *tasks[] = { &controllerTask, &lcdTask, &musicTask, &usartTask };
void TimerISR()
{
for(unsigned char i = 0; i < sizeof tasks / sizeof *tasks; i++)
{
if(tasks[i]->elapsed_time >= tasks[i]->period)
{
tasks[i]->state = tasks[i]->TickFunction(tasks[i]->state);
tasks[i]->elapsed_time = 0;
}
tasks[i]->elapsed_time += 1;
}
}
unsigned long int findGCD(unsigned long a, unsigned long b)
{
unsigned long c;
while(1){
c = a%b;
if(c==0){return b;}
a = b;
b = c;
}
return 0;
}
void init_Tasks()
{
unsigned long controller_period = 10;
unsigned long LCD_period = 100;
unsigned long music_period = 5;
unsigned long usart_period = findGCD(controller_period, music_period);
set_ControllerPeriod(controller_period);
set_LCDPeriod(LCD_period);
set_MusicPeriod(music_period);
set_USARTPeriod(usart_period);
unsigned long gcd = findGCD(controller_period, LCD_period);
gcd = findGCD(gcd, music_period);
set_ProgramPeriod(gcd);
unsigned char i = 0;
tasks[i]->state = 0;
tasks[i]->period = controller_period/gcd;
tasks[i]->elapsed_time = tasks[i]->period;
tasks[i]->TickFunction = controller_GetTick();
i++;
tasks[i]->state = 0;
tasks[i]->period = LCD_period/gcd;
tasks[i]->elapsed_time = tasks[i]->period;
tasks[i]->TickFunction = lcd_GetTick();
i++;
tasks[i]->state = 0;
tasks[i]->period = music_period/gcd;
tasks[i]->elapsed_time = tasks[i]->period;
tasks[i]->TickFunction = music_GetTick();
i++;
tasks[i]->state = 0;
tasks[i]->period = usart_period/gcd;
tasks[i]->elapsed_time = tasks[i]->period;
tasks[i]->TickFunction = usart_GetTick();
}
int main(void)
{
DDRA = 0xFE; PORTA = 0x01;
DDRB = 0xFF; PORTB = 0x00;
DDRC = 0xFF; PORTC = 0x00;
DDRD = 0xFF; PORTD = 0x00;
if(get_Max_Combo_Prom() >= 255)
{
set_Max_Combo_Prom(0);
}
if(get_Max_Hits_Prom() >= 255)
{
set_Max_Hits_Prom(0);
}
set_Max_Combo(get_Max_Combo_Prom());
set_Max_Hits(get_Max_Hits_Prom());
initUSART();
LCD_init();
init_Tasks();
TimerSet(get_ProgramPeriod());
TimerOn();
set_sleep_mode(3);
while(1) { sleep_enable(); }
return 0;
}
|
C
|
///////////////////////////////////////////////////////////////////////////////////////////////////
// Includes Section
///////////////////////////////////////////////////////////////////////////////////////////////////
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include "I2cWrapper.h"
///////////////////////////////////////////////////////////////////////////////////////////////////
// Defines & Macros Section
///////////////////////////////////////////////////////////////////////////////////////////////////
#define ACCELEROMETER_ADDRESS 0x1E
#define WHO_AM_I_REGISTER 0x0D
#define ACCELEROMETER_BUFFER_SIZE 6
#define ACCELEROMETER_CONTROL_REGISTER 0x2B
#define ACCELEROMETER_X_DATA_MSB_REGISTER 0x01
///////////////////////////////////////////////////////////////////////////////////////////////////
// Typedef Section
///////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////
// Function Prototypes Section
///////////////////////////////////////////////////////////////////////////////////////////////////
static void Sensor_PrintSignedNumber(int16_t DataToDisplay);
///////////////////////////////////////////////////////////////////////////////////////////////////
// Global Constants Section
///////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////
// Static Constants Section
///////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////
// Global Variables Section
///////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////
// Static Variables Section
///////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////
// Functions Section
///////////////////////////////////////////////////////////////////////////////////////////////////
int main (int argc, char * argv[])
{
i2c_status_t I2cStatus;
i2c_handler_t I2cHandler;
uint8_t * AccelerometerReadBuffer;
uint8_t * AccelerometerWriteBuffer;
int16_t AxisX;
int16_t AxisY;
int16_t AxisZ;
if(argc >= 2)
{
I2cStatus = I2c_Init((uint8_t*)argv[1],&I2cHandler);
if(I2cStatus == I2C_OK)
{
AccelerometerReadBuffer = (uint8_t*)malloc(ACCELEROMETER_BUFFER_SIZE);
AccelerometerWriteBuffer = (uint8_t*)malloc(ACCELEROMETER_BUFFER_SIZE);
if((AccelerometerReadBuffer != NULL) && (AccelerometerWriteBuffer != NULL))
{
/* Assume the buffers were allocated */
AccelerometerWriteBuffer[0] = WHO_AM_I_REGISTER;
I2cStatus = I2c_Read(&I2cHandler, ACCELEROMETER_ADDRESS, AccelerometerWriteBuffer,\
1, AccelerometerReadBuffer, 1);
if((I2cStatus == I2C_OK) && (AccelerometerReadBuffer[0] == 0xC7))
{
printf("FXOS8700CQ Found!\n\r");
/* Enable accelerometer */
AccelerometerWriteBuffer[0] = ACCELEROMETER_CONTROL_REGISTER;
AccelerometerWriteBuffer[1] = 0x01;
I2cStatus = I2c_Write(&I2cHandler, ACCELEROMETER_ADDRESS, AccelerometerWriteBuffer,2);
if(I2cStatus == I2C_OK)
{
AccelerometerWriteBuffer[0] = ACCELEROMETER_X_DATA_MSB_REGISTER;
printf("\n\rPress enter for a new reading...");
while(1)
{
fgets((char*)&AccelerometerWriteBuffer[4],2,stdin);
I2cStatus = I2c_Read(&I2cHandler, ACCELEROMETER_ADDRESS, AccelerometerWriteBuffer,\
1, AccelerometerReadBuffer, 6);
if(I2cStatus != I2C_OK)
{
printf("\n\rError Reading Accelerometer\n\r");
}
/* Accelerometer data is 14-bit 2's Complement left justified */
AxisX = (int16_t)((uint16_t)((uint16_t)AccelerometerReadBuffer[0] << 8) | (uint16_t)AccelerometerReadBuffer[1]) >> 2U;
AxisY = (int16_t)((uint16_t)((uint16_t)AccelerometerReadBuffer[2] << 8) | (uint16_t)AccelerometerReadBuffer[3]) >> 2U;
AxisZ = (int16_t)((uint16_t)((uint16_t)AccelerometerReadBuffer[4] << 8) | (uint16_t)AccelerometerReadBuffer[5]) >> 2U;
printf("\n\rX Axis: ");
Sensor_PrintSignedNumber(AxisX);
printf("\n\rY Axis: ");
Sensor_PrintSignedNumber(AxisY);
printf("\n\rZ Axis: ");
Sensor_PrintSignedNumber(AxisZ);
}
}
else
{
printf("\n\rError writing to I2C Device: %d\n\r",I2cStatus);
}
}
}
else
{
printf("Error while allocating buffers\n\r");
}
}
else
{
printf("\n\rError opening I2C Device: %d\n\r",I2cStatus);
}
}
else
{
printf("Error Usage\n\rI2cWrapperTest <i2cdevice>\n\r");
}
return(0);
}
static void Sensor_PrintSignedNumber(int16_t DataToDisplay)
{
uint16_t Data = (uint16_t)DataToDisplay;
/* verify if data is positive or negative */
/* note this function will work only with 14-bit numbers */
if(Data < 0x1FFF)
{
printf("+");
}
else
{
printf("-");
/* convert 2's complement back*/
Data = ((~Data) + 1);
}
printf("%d",Data);
}
/* EOF */
|
C
|
#include <stdio.h>
int main(){
int num;
printf("Enter number of staircases: ");
scanf("%d", &num);
if (num > 100){
printf("n=%d", num);
printf( ", must be in [1, 100]\n");
return 1;
}
int cycles = num / 5;
int numws;
int i, j, k, z;
for(j = 1; j <= cycles; j++) /*repeating rows of 5*/
{
for (k = 1; k <= 3; k++) /*going thru num of columns*/
{
numws = 3 - k; /*for whitespaces*/
for (i = 1; i <= 5; i++) /*going thru num of rows*/
{
printf( "%*s ", numws, "");
for (z = 1; z <= k; z++) printf("#");
if (i==5) printf("\n");
}
}
}
/*for the remainder of staircases left */
int rem = num % 5;
for (k = 1; k <= 3; k++)
{
numws = 3 - k; /* for whitespaces */
for (i = 1; i <= rem; i++) /* going thru num of rows */
{
printf( "%*s ", numws, "");
for (z = 1; z <= k; z++)
printf("#");
if (i==rem) printf("\n");
}
}
return 0;
}
|
C
|
#include<stdio.h>
#include<stdlib.h>
#include"structbst.h"
int main(void) {
FILE* f;
nodetype* tree = NULL;
char s[100];
if( (f= fopen("student.txt", "r")) == NULL ) {
puts("Could not open file");
}
else {
while( (fscanf(f, " %[^\n]", s)) != EOF ) {
elmtype data = nameToData(s);
tree = insertNode(tree, data);
}
int choice;
do {
printf("1.display students\n2.Search student\n3.Delete student\n4.Exit\nYour choice ? ");
scanf("%d", &choice);
if( choice == 1 ) {
display(tree);
}
else if( choice == 2 ) {
char last[20];
printf("Enter last name: ");
scanf("%s", last);
nodetype* result = search(tree, last);
if( result == NULL ) puts("Could not found");
else printf("Result: %s %s %s\n", result->element.firstName, result->element.middleName, result->element.lastName);
}
else if( choice == 3 ) {
char s[100];
printf("Enter name: ");
scanf(" %[^\n]", s);
elmtype data = nameToData(s);
deleteNode(tree, data);
puts("Done");
}
else if( choice == 4 ) puts("Exit");
else puts("Invalid choice");
} while( choice != 4 );
}
freetree(tree);
fclose(f);
}
|
C
|
#include <stdio.h>
int generate_a_word(int x, int y){
return (x & 0xff) | (y & 0xffffff00);
}
//н
int generate_a_word(int x, int y){
return (x & 0xff) | (y & ~0xff);
}
int main(){
int a = 0x89abcdef;
int b = 0x76543210;
printf("%x", generate_a_word(a, b));
return 0;
}
|
C
|
/*
* This is sample code generated by rpcgen.
* These are only templates and you can use them
* as a guideline for developing your own functions.
*/
#include "RPC_Assign.h"
void
rpc_prog_1(char *host) {
CLIENT *clnt;
char **result_1;
char *hostname_1_arg;
sortArray *result_2;
sortArray mergesort_1_arg;
char **result_3;
char *encryptecho_1_arg;
char **result_4;
char *listfiles_1_arg;
complxNo *result_5;
complxNo addcomplx_1_arg;
#ifndef DEBUG
clnt = clnt_create(host, RPC_PROG, RPC_VERS, "udp");
if (clnt == NULL) {
clnt_pcreateerror(host);
exit(1);
}
#endif /* DEBUG */
int ch, i;
while (1) {
//Menu for different operation
printf("\n********Welcome to RPC Program ********\n");
printf("1. Get hostname\n");
printf("2. Merge Sort\n");
printf("3. Encrypted Echo\n");
printf("4. List all files\n");
printf("5. Add complex number\n");
printf("6. Exit\n");
printf("Enter your choice:");
scanf("%d", &ch);
switch (ch) {
case 1:
//Get the server host name
result_1 = hostname_1((void *) &hostname_1_arg, clnt);
if (result_1 == (char **) NULL) {
clnt_perror(clnt, "call failed");
} else {
printf("The host name is: %s\n", *result_1);
}
break;
case 2:
//Sort the 2 unsorted list into 1 sorted array
printf("Enter the element of 1st array: ");
for (i = 0; i < 5; i++) {
scanf("%d", &mergesort_1_arg.l1[i]);
}
printf("Enter the element of 2nd array: ");
for (i = 0; i < 5; i++) {
scanf("%d", &mergesort_1_arg.l2[i]);
}
//rpc call to sort the lists
result_2 = mergesort_1(&mergesort_1_arg, clnt);
if (result_2 == (sortArray *) NULL) {
clnt_perror(clnt, "call failed");
} else {
printf("The Merged sorted list is\n");
for (i = 0; i < 10; i++) {
printf("%d\t", result_2->res[i]);
}
}
printf("\n");
break;
case 3:;
//Encrypt the string entered by the user
char echo_str[1024];
getchar();
printf("Enter the string:");
scanf("%[^\n]s", &echo_str);
encryptecho_1_arg = echo_str;
//rpc call to encrypt the string
result_3 = encryptecho_1(&encryptecho_1_arg, clnt);
if (result_3 == (char **) NULL) {
clnt_perror(clnt, "call failed");
} else {
printf("The encrypted string is: %s\n", *result_3);
}
break;
case 4:
//Get the list of all the files in the directory
result_4 = listfiles_1((void *) &listfiles_1_arg, clnt);
if (result_4 == (char **) NULL) {
clnt_perror(clnt, "call failed");
} else {
printf("The list of files is: %s\n", *result_4);
}
break;
case 5:
//Add 2 complex numbers
printf("Enter the 1st real part: ");
scanf("%d", &addcomplx_1_arg.real1);
printf("Enter the 1st img part: ");
scanf("%d", &addcomplx_1_arg.img1);
printf("Enter the 2nd real part: ");
scanf("%d", &addcomplx_1_arg.real2);
printf("Enter the 2nd img part: ");
scanf("%d", &addcomplx_1_arg.img2);
//rpc call to add 2 complex numbers
result_5 = addcomplx_1(&addcomplx_1_arg, clnt);
if (result_5 == (complxNo *) NULL) {
clnt_perror(clnt, "call failed");
} else {
printf("The addition of 2 complex no is : %d + (%d)i\n", result_5->real, result_5->img);
}
break;
case 6:
//Exit the client
exit(0);
break;
default:
printf("Enter valid Option!!\n");
break;
}//switch
}//while
#ifndef DEBUG
clnt_destroy(clnt);
#endif /* DEBUG */
}
int
main(int argc, char *argv[]) {
char *host;
if (argc < 2) {
printf("usage: %s server_host\n", argv[0]);
exit(1);
}
host = argv[1];
rpc_prog_1(host);
exit(0);
}
|
C
|
#include "fdf.h"
void venegparse(t_fdfwin *store, int x, int y, double o)
{
if (store->sign[y][x] == 1 && store->sign[y + 1][x] == 0)
oparseve(store, x, y, o);
if (store->sign[y][x] == 0 && store->sign[y + 1][x] == 1)
dparseve(store, x, y, o);
if (store->sign[y][x] == 1 && store->sign[y + 1][x] == 1)
tparseve(store, x, y, o);
}
void veposparse(t_fdfwin *store, int x, int y, double o)
{
if (store->tab[y][x] == store->tab[y + 1][x])
egalve(store);
if (store->tab[y][x] < store->tab[y + 1][x])
moinsve(store, x, y, o);
if (store->tab[y][x] > store->tab[y + 1][x])
plusve(store, x, y, o);
}
void honegparse(t_fdfwin *store, int x, int y, double o)
{
if (store->sign[y][x] == 1 && store->sign[y][x + 1] == 0)
oparseho(store, x, y, o);
if (store->sign[y][x] == 0 && store->sign[y][x + 1] == 1)
dparseho(store, x, y, o);
if (store->sign[y][x] == 1 && store->sign[y][x + 1] == 1)
tparseho(store, x, y, o);
}
void hoposparse(t_fdfwin *store, int x, int y, double o)
{
if (store->tab[y][x] == store->tab[y][x + 1])
egalho(store);
if (store->tab[y][x] < store->tab[y][x + 1])
moinsho(store, x, y, o);
if (store->tab[y][x] > store->tab[y][x + 1])
plusho(store, x, y, o);
}
void freetab(int **tableau)
{
free(tableau[0]);
free(tableau);
}
|
C
|
#include <stdio.h>
#include "../ADT/Matriks/matriks.h"
#include "../ADT/Point/point.h"
#include "../ADT/Graph/graph.h"
#include "PetaWahana.h"
void MakeMap(Graph *G, MATRIKS *M)
{
char filename[] = "File-Eksternal/map1.txt";
BacaMATRIKS(G, M, 12, 12, filename);
G++;
M++;
char filename2[] = "File-Eksternal/map2.txt";
BacaMATRIKS(G, M, 12, 12, filename2);
G++;
M++;
char filename3[] = "File-Eksternal/map3.txt";
BacaMATRIKS(G, M, 12, 12, filename3);
G++;
M++;
char filename4[] = "File-Eksternal/map4.txt";
BacaMATRIKS(G, M, 12, 12, filename4);
G++;
M++;
char filename8[] = "File-Eksternal/saveMap.txt";
BacaMATRIKS(G, M, 12, 12, filename8);
G++;
M++;
// posisi Map:
// 0 1
// 2 3
// Kalo ketemu simbol '>' maka idx matriks +1
// Kalo '<' -1
// Kalo '^' -2
// Kalo 'v' +2
}
void A(Graph G[5], POINT *P, MATRIKS *M, MATRIKS *MK, int *idxmap)
{
//MK itu arrray of matriks (isi map 1 sampe 4)
//G itu list graph dri masing2 map
//map itu index map
//Cek Posisi sebelum pindah
if (Absis(*P) == 9 && Ordinat(*P) == 9 && *idxmap == 0)
{
Elmt(*M, Absis(*P), Ordinat(*P)) = 'O';
}
else
{
Elmt(*M, Absis(*P), Ordinat(*P)) = '-';
}
// Cek posisi setelah pindah
if (Elmt(*M, Absis(*P), Ordinat(*P) - 1) == '-' || Elmt(*M, Absis(*P), Ordinat(*P) - 1) == 'O')
{
Ordinat(*P) = Ordinat(*P) - 1;
}
else if (Elmt(*M, Absis(*P), Ordinat(*P) - 1) == '<')
{
CopyMATRIKS(*M, MK + *idxmap);
*idxmap -= 1;
CopyMATRIKS(*(MK + *idxmap), M);
adrNode T = SearchOrdinat(G[*idxmap], 11);
Absis(*P) = Absis(Id(T));
Ordinat(*P) = Ordinat(Id(T)) - 1;
}
else
{
printf("Operasi tidak dapat dilakukan\n");
}
Elmt(*M, Absis(*P), Ordinat(*P)) = 'P';
}
void W(Graph G[5], POINT *P, MATRIKS *M, MATRIKS *MK, int *idxmap)
{
//Cek Posisi sebelum pindah
if (Absis(*P) == 9 && Ordinat(*P) == 9 && *idxmap == 0)
{
Elmt(*M, Absis(*P), Ordinat(*P)) = 'O';
}
else
{
Elmt(*M, Absis(*P), Ordinat(*P)) = '-';
}
//Cek Posisi setelah pindah
if (Elmt(*M, Absis(*P) - 1, Ordinat(*P)) == '-' || Elmt(*M, Absis(*P) - 1, Ordinat(*P)) == 'O')
{
Absis(*P) = Absis(*P) - 1;
}
else if (Elmt(*M, Absis(*P) - 1, Ordinat(*P)) == '^')
{
CopyMATRIKS(*M, MK + *idxmap);
*idxmap -= 2;
CopyMATRIKS(*(MK + *idxmap), M);
adrNode T = SearchAbsis(G[*idxmap], 11);
Absis(*P) = Absis(Id(T)) - 1;
Ordinat(*P) = Ordinat(Id(T));
}
else
{
printf("Operasi tidak dapat dilakukan\n");
}
Elmt(*M, Absis(*P), Ordinat(*P)) = 'P';
}
void D(Graph G[5], POINT *P, MATRIKS *M, MATRIKS *MK, int *idxmap)
{
//Cek Jalan atau Gedung atau Tembok
if (Absis(*P) == 9 && Ordinat(*P) == 9 && *idxmap == 0)
{
Elmt(*M, Absis(*P), Ordinat(*P)) = 'O';
}
else
{
Elmt(*M, Absis(*P), Ordinat(*P)) = '-';
}
if (Elmt(*M, Absis(*P), Ordinat(*P) + 1) == '-' || Elmt(*M, Absis(*P), Ordinat(*P) + 1) == 'O')
{
Ordinat(*P) = Ordinat(*P) + 1;
}
else if (Elmt(*M, Absis(*P), Ordinat(*P) + 1) == '>')
{
CopyMATRIKS(*M, MK + *idxmap);
*idxmap += 1;
CopyMATRIKS(*(MK + *idxmap), M);
adrNode T = SearchOrdinat(G[*idxmap], 0);
Absis(*P) = Absis(Id(T));
Ordinat(*P) = Ordinat(Id(T)) + 1;
}
else
{
printf("Operasi tidak dapat dilakukan\n");
}
Elmt(*M, Absis(*P), Ordinat(*P)) = 'P';
}
void S(Graph G[5], POINT *P, MATRIKS *M, MATRIKS *MK, int *idxmap)
{
//Cek Jalan atau Gedung atau Tembok
if (Absis(*P) == 9 && Ordinat(*P) == 9 && *idxmap == 0)
{
Elmt(*M, Absis(*P), Ordinat(*P)) = 'O';
}
else
{
Elmt(*M, Absis(*P), Ordinat(*P)) = '-';
}
if (Elmt(*M, Absis(*P) + 1, Ordinat(*P)) == '-' || Elmt(*M, Absis(*P) + 1, Ordinat(*P)) == 'O')
{
Absis(*P) = Absis(*P) + 1;
}
else if (Elmt(*M, Absis(*P) + 1, Ordinat(*P)) == 'v')
{
CopyMATRIKS(*M, MK + *idxmap);
*idxmap += 2;
CopyMATRIKS(*(MK + *idxmap), M);
adrNode T = SearchAbsis(G[*idxmap], 0);
Absis(*P) = Absis(Id(T)) + 1;
Ordinat(*P) = Ordinat(Id(T));
}
else
{
printf("Operasi tidak dapat dilakukan\n");
}
Elmt(*M, Absis(*P), Ordinat(*P)) = 'P';
}
|
C
|
#include <stdlib.h>
#include <netdb.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <unistd.h>
#include <string.h>
#define NSLOTS 256
#define EMPTY_SLOT -1
typedef int slot_t;
slot_t* slots = NULL;
static void check_and_init() {
int i;
if (slots == NULL) {
slots = (slot_t*) malloc(NSLOTS*sizeof(slot_t));
for (i = 0; i < NSLOTS; i++) {
slots[i] = EMPTY_SLOT;
}
}
}
static int find_empty_slot() {
int i;
for (i = 0; i < NSLOTS; i++) {
if (slots[i] == EMPTY_SLOT)
return i;
}
return -1;
}
/// returns slotnumber or negative error code
int simplenet_connect(const char * hostname, int port) {
int sockfd;
struct hostent *server;
struct sockaddr_in serv_addr;
int result;
check_and_init();
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd == -1)
return -1;
server = gethostbyname(hostname);
if (server == NULL)
return -2;
memset(&serv_addr, 0, sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
memcpy(&serv_addr.sin_addr.s_addr, server->h_addr, server->h_length);
serv_addr.sin_port = htons(port);
if (connect(sockfd,(struct sockaddr *) &serv_addr,sizeof(serv_addr)) < 0)
return -3;
result = find_empty_slot();
if (result == -1)
return -4;
slots[result] = sockfd;
return result;
}
/// returns a byte from socket, -1 on end of file, -2 on error
int simplenet_read(int slotnumber) {
int len;
unsigned char buf;
check_and_init();
len = read(slots[slotnumber], &buf, 1);
if (len == -1)
return -2;
if (len == 0)
return -1;
return buf;
}
int simplenet_write_buf(int slotnumber, const char * buf, int size) {
check_and_init();
return write(slots[slotnumber], buf, size);
}
int simplenet_write_char(int slotnumber, int character) {
char c = (char)character;
return simplenet_write_buf(slotnumber, &c, 1);
}
int simplenet_flush(int slotnumber) {
return fsync(slots[slotnumber]);
}
// returns 0 on success, -1 on error
int simplenet_close(int slotnumber) {
int suc;
check_and_init();
suc = close(slots[slotnumber]);
if (suc == 0) {
slots[slotnumber] = EMPTY_SLOT;
return 0;
}
return -1;
}
int simplenet_set_timeout(int slotnumber, int timeoutmillis) {
struct timeval timeout;
int sockfd;
int suc;
check_and_init();
sockfd = slots[slotnumber];
timeout.tv_sec = timeoutmillis / 1000;
timeout.tv_usec = (timeoutmillis % 1000) * 1000;
suc = setsockopt(sockfd, SOL_SOCKET, SO_RCVTIMEO, (void*)&timeout, sizeof(timeout));
if (suc != 0)
return -1;
suc = setsockopt(sockfd, SOL_SOCKET, SO_SNDTIMEO, (void*)&timeout, sizeof(timeout));
if (suc != 0)
return -2;
return 0;
}
|
C
|
#include <stdio.h>
#define MAX 1000001
int primos[MAX];
int main(){
int i = 0, n = 0, j = 0, c = 0, N = 0, k = 0;
for(i = 0; i < MAX; i++)
primos[i] = i % 2;
primos[1] = 0;
primos[2] = 1;
for(i = 3; i * i < MAX; i++){
if(primos[i]){
for(j = i * i; j < MAX; j += i)
primos[j] = 0;
}
}
while(1){
scanf("%d", &n);
if(!n)
break;
N = n;
c = 0;
k = 1;
for(i = 2; i <= n && i * i <= MAX;){
if(primos[i] && (n % i == 0)){
c += k;
n /= i;
k = 0;
}else{
i++;
k = 1;
}
}
if(primos[n])
c++;
printf("%d : %d\n", N, c);
}
return 0;
}
|
C
|
// Copyright (c) 2021, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
#include <stdlib.h>
// Reverses a UTF-8 string in-place.
void reverse(char *str) {
// Calculate length of string.
int l = 0;
while (*(str + l) != '\0')
l++;
// Initialize.
int i;
char *first, *last, temp;
first = str;
last = str;
for (i = 0; i < l - 1; i++) {
last++;
}
// Iterate from both ends, swapping first and last as we go.
for (i = 0; i < l / 2; i++) {
temp = *last;
*last = *first;
*first = temp;
first++;
last--;
}
}
|
C
|
#include "stdbool.h"
#include "math.h"
#include "stdio.h"
int oindex;
int eindex;
int graph[100][100];
int odd[100];
int even[100];
int pairs[100];
int mem[100];
bool find(int i)
{
for(int j=0;j<oindex;j++)
{
if(graph[i][j])
{
if(mem[j])
continue;
mem[j]=1;
if(pairs[j]==0||find(pairs[j]-1))
{
pairs[j]=i+1;
return true;
}
}
}
return false;
}
bool isPrem(int even, int odd)
{
int sum=odd+even;
int num=sqrt(sum);
for(int i=2;i<=num;i++)
{
if(sum%i==0)
return false;
}
return true;
}
int main()
{
int N;
while(scanf("%d",&N)!=EOF)
{
memset(graph,0,sizeof(graph));
memset(odd,0,sizeof(odd));
memset(even,0,sizeof(even));
memset(pairs,0,sizeof(pairs));
oindex=0;
eindex=0;
for(int i=0;i<N;i++)
{
int tmp;
scanf("%d",&tmp);
if(tmp%2==0)
even[eindex++]=tmp;
else
odd[oindex++]=tmp;
}
for(int i=0;i<eindex;i++)
{
for(int j=0;j<oindex;j++)
{
if(isPrem(even[i],odd[j]))
graph[i][j]=1;
}
}
int result=0;
for(int i=0;i<eindex;i++)
{
memset(mem,0,sizeof(mem));
if(find(i))
result++;
}
printf("%d\n",result);
}
return 0;
}
|
C
|
#include<stdio.h>
int main()
{
int a,i=0;
//taking the input
printf("enter the number whose table you want\n");
scanf("%d",&a);
//making the table and showing output
for(i=1;i<11;i++)
{
printf("%d * %d=",a,i);
printf("%d\n",a*i);
}
return 0;
}
|
C
|
#include <stdio.h>
#include "em.h"
arith cur_pos = 0;
dist( lab)
char *lab;
/* Just output a reference which must be filled in on a second pass */
{
out( "($%s$ - %ld)", lab, cur_pos);
}
#define MAX_LABEL 10
#define TRUE 1
#define FALSE 0
struct t_label {
char *lab;
arith position;
};
struct t_label label_list[ MAX_LABEL];
int n_labs = 0;
handle_label( lab)
char *lab;
/* Record position of this label */
{
char *Salloc();
if ( n_labs >= MAX_LABEL)
error( "Too many labels!!\n");
else {
label_list[ n_labs].lab = Salloc( lab, strlen( lab) + 1);
label_list[ n_labs++].position = cur_pos;
}
process_label( lab);
}
relocate( f)
FILE *f;
/* Output position-count of the label in file 'f', remove also trailing $ */
{
char buf[256];
int i;
fscanf( f, " %[^$]$", buf);
for ( i = 0; i < n_labs; i++)
if ( strcmp( buf, label_list[i].lab) == 0) {
out( "%ld", label_list[i].position);
return;
}
error( "relocate() : can't find local label %s\n", buf);
}
#include <system.h>
File *oldout;
extern File *outfile;
back_patch()
/* Echo the text on file '.tmp', but replace every occurence of label-
*reference's by its position-count. Reference of label 'foo' is '$foo$'.
*/
{
FILE *save;
char c, c1;
sys_close( outfile);
outfile = oldout;
save = fopen( ".tmp", "r");
while ( ( c = getc( save)) != EOF)
if ( c == '$')
relocate( save);
else if ( c == '/') { /* skip comments */
c = getc( save);
out( "/%c", c);
if ( c == '*') {
c = getc( save);
do {
out( "%c", c);
c1 = c;
c = getc( save);
}
while ( !( c1 == '*' && c == '/'));
out( "%c", c);
}
}
else
out( "%c", c);
fclose( save);
}
save_output()
{
extern arith cur_pos;
extern int n_labs;
oldout = outfile;
if ( ! sys_open( ".tmp", OP_WRITE, &outfile))
fprint( STDERR, "can't open .tmp\n");
cur_pos = 0;
n_labs = 0;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.