language
large_string | text
string |
---|---|
C | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_lstmap.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: lnickole <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2019/05/03 16:52:25 by lnickole #+# #+# */
/* Updated: 2019/05/10 17:29:14 by lnickole ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
t_list *ft_lstmap(t_list *lst, t_list *(*f)(t_list *elem))
{
t_list *result;
t_list *head;
t_list *element;
if (lst == NULL || f == NULL)
return (NULL);
element = f(lst);
result = ft_lstnew(element->content, element->content_size);
if (result == NULL)
return (NULL);
head = result;
lst = lst->next;
while (lst != NULL)
{
element = f(lst);
result->next = ft_lstnew(element->content, element->content_size);
if (result == NULL)
return (NULL);
result = result->next;
lst = lst->next;
}
return (head);
}
|
C | /* ˽ָйص㣬Ϥĵַ */
#include <stdio.h>
#include <stdlib.h>
int main(){
int a=100, b, *p=&a; // һָpѱaĵַָp
printf("a=%d\tp_address=%x\t*p=%d\n", a, p, *p); // *pʾaĵַΪ100
printf("\n");
b=*p; // ൱b=a
printf("b=%d\n", b); // ʱb=a=100
printf("\n");
a=200; // a
printf("a=%d\tp_address=%x\t*p=%d\n", a, p, *p);
p=&b; // ѱbĵַָp
printf("b=%d\tp_address=%x\t*p=%d\n", b, p, *p);
printf("\n"); // һ
return 0;
}
|
C | #include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
#include <stdint.h>
#define TABLE_SIZE 200000000000
bool is_even(unsigned long n)
{
return (n % 2 == 0);
}
unsigned long next_value(unsigned long n, unsigned long *table)
{
if (n < TABLE_SIZE && table[n]) {
return table[n];
}
unsigned long res = 0;
if (is_even(n)) {
res = n / 2;
} else {
res = (n * 3) + 1;
}
if (n < TABLE_SIZE) {
table[n] = res;
}
return res;
}
unsigned long calc_cycle_length(unsigned long n, unsigned long *table)
{
unsigned long count = 1;
do {
n = next_value(n, table);
count++;
} while (n != 1);
return count;
}
int main(void)
{
unsigned long i, j;
unsigned long n, max, new_max;
unsigned long *table = malloc(sizeof(unsigned long) * TABLE_SIZE);
if (table == NULL) {
printf("Error: could not allocate memory for lookup table");
return EXIT_FAILURE;
}
memset(table, '\0', sizeof(table));
while(scanf("%lu %lu", &i, &j) != EOF) {
max = calc_cycle_length(i, table);
n = i;
while (n++ <= j) {
new_max = calc_cycle_length(n, table);
if (new_max > max) {
max = new_max;
}
}
printf("%lu %lu %lu\n", i, j, max);
}
free(table);
return EXIT_SUCCESS;
}
/* Performance:
$ time echo '100001 2000000' | ./3n_c
100001 2000000 557
real 0m7.662s
user 0m7.648s
sys 0m0.009s
*/
|
C | #include <stdio.h>
#include <stdlib.h>
#include "DataStructures.h"
void printStructure(names*, char*);
int main(void) {
names min, max;
char *minLabel = "min structure";
char *maxLabel = "max structure";
min.nameA = 50;
min.nameB = 20;
min.nameC = 33;
max.nameA = 100;
max.nameB = 55;
max.nameC = 77;
printStructure(&min, minLabel);
printStructure(&max, maxLabel);
return EXIT_SUCCESS;
}
void printStructure(names* data, char* label)
{
puts(label);
printf("nameA = %c, nameB = %d, nameC = %c\n", data->nameA, data->nameB, data->nameC);
}
|
C | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* solve_b.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: sdiego <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2020/06/18 18:36:53 by sdiego #+# #+# */
/* Updated: 2020/11/04 19:15:52 by sdiego ### ########.fr */
/* */
/* ************************************************************************** */
#include "../include/push_swap.h"
void move_a_b_stacks(t_stack *a, t_stack *b, t_direction *d, t_stack *rules)
{
if (d->a_rule == ROTATE)
{
rr(a, b);
stack_push(rules, RR, -1);
}
else
{
rrr(a, b);
stack_push(rules, RRR, -1);
}
}
void move_a_stack(t_stack *a, t_direction *d, t_stack *rules)
{
if (d->a_rule == ROTATE)
{
rotate_a_b(a);
stack_push(rules, RA, -1);
}
else
{
rr_a_b(a);
stack_push(rules, RRA, -1);
}
}
void move_b_stack(t_stack *b, t_direction *d, t_stack *rules)
{
if (d->b_rule == ROTATE)
{
rotate_a_b(b);
stack_push(rules, RB, -1);
}
else
{
rr_a_b(b);
stack_push(rules, RRB, -1);
}
}
/*
** We put the previously selected numbers at the beginning
** of the stack a and stack b
*/
void move_stacks(t_stack *a, t_stack *b, t_direction *d, t_stack *rules)
{
while (d->a_node->nbr != a->head->nbr || d->b_node->nbr != b->head->nbr)
{
if (d->a_rule == d->b_rule && d->a_node->nbr != a->head->nbr &&
d->b_node->nbr != b->head->nbr)
move_a_b_stacks(a, b, d, rules);
else if (d->a_node->nbr != a->head->nbr)
move_a_stack(a, d, rules);
else if (d->b_node->nbr != b->head->nbr)
move_b_stack(b, d, rules);
}
}
/*
** From Stack B to Stack A
*/
void from_b_to_a(t_stack *a, t_stack *b, t_stack *rules)
{
t_direction *d;
d = init_direction_struct();
while (b->size > 0)
{
d->status = FALSE;
optimal_direction(a, b, d);
move_stacks(a, b, d, rules);
push_a(a, b);
stack_push(rules, PA, -1);
}
}
|
C | #include "libTinyFS.h"
#include "libDisk.h"
#include "TinyFS_errno.h"
int num_blocks;
int disk_num = -1;
int open_files;
int total_files;
fileDescriptor next_fd = 0;
fileEntry **file_table;
openFile **open_file_table;
freeBlock* head;
void *checkedCalloc(int size) {
void *data = calloc(1, size);
if (data == NULL) {
fprintf(stderr, "Failed to allocate blocks to disk\n");
exit(CALLOC_ERROR);
}
return data;
}
int writeSuperblock() {
char *superblock = checkedCalloc(BLOCKSIZE);
int status;
superblock[TYPE_BYTE] = SUPERBLOCK;
superblock[MAGIC_BYTE] = MAGIC_NUMBER;
superblock[ADDR_BYTE] = 0;
superblock[SIZE_BYTE] = num_blocks;
status = writeBlock(disk_num, 0, superblock);
return status;
}
freeBlock *addFreeBlock(freeBlock *tail, int block_num) {
freeBlock *temp_block = checkedCalloc(sizeof(freeBlock));
temp_block->next = NULL;
temp_block->block_num = block_num;
tail->next = temp_block;
tail = tail->next;
return tail;
}
int popFreeBlock() {
int block_num = -1;
freeBlock *temp = head;
block_num = head->block_num;
if (head->next != NULL) {
head = head->next;
free(temp);
} else {
head->block_num = 0;
}
return block_num;
}
int setupFreeBlocks() {
int i;
int status = 0;
char *block = checkedCalloc(sizeof(BLOCKSIZE));
freeBlock *tail;
head = checkedCalloc(sizeof(freeBlock));
head->block_num = 0;
head->next = NULL;
tail = head;
for (i = 1; i < num_blocks; i++) {
int free_block_num = i + 1;
if (i + 1 == num_blocks) {
free_block_num = 0;
}
block[TYPE_BYTE] = FREE_BLOCK;
block[MAGIC_BYTE] = MAGIC_NUMBER;
block[ADDR_BYTE] = free_block_num;
status |= writeBlock(disk_num, i, block);
tail = addFreeBlock(tail, i);
}
popFreeBlock();
free(block);
return status;
}
int loadFiles() {
int status = 0, i;
char super_block_buf[BLOCKSIZE];
char inode_buffer[BLOCKSIZE];
char filename[9];
fileEntry *file;
readBlock(disk_num, 0, super_block_buf);
total_files = super_block_buf[SIZE_BYTE];
for (i = 0; i < total_files; i++) {
int index = 0;
int inode_index = SIZE_BYTE + i + 1;
file = checkedCalloc(sizeof(fileEntry));
file->fd = i;
file->inode_block_num = super_block_buf[inode_index];
file->num_copies = 0;
status |= readBlock(disk_num, super_block_buf[inode_index], inode_buffer);
while (inode_buffer[NAME_BYTE + index] != '\0' && index < NAME_BYTE) {
filename[index] = inode_buffer[NAME_BYTE + index];
++index;
}
filename[index] = '\0';
file->name = filename;
file->permissions = inode_buffer[PERMISSION_BYTE];
getFileTimes(file, inode_buffer);
file_table[i] = file;
}
return status;
}
freeBlock *getTail() {
freeBlock *temp = head;
while (temp->next != NULL) {
temp = temp->next;
}
return temp;
}
int loadAllData() {
int status = 0, cur_block = 0, prev_block = 0;
char buf[BLOCKSIZE];
freeBlock *temp;
if (head != NULL) {
return status;
}
head = checkedCalloc(sizeof(freeBlock));
temp = head;
head->block_num = 0;
head->next = NULL;
do {
prev_block = cur_block;
status |= readBlock(disk_num, cur_block, buf);
cur_block = (int) buf[ADDR_BYTE];
addFreeBlock(getTail(), cur_block);
} while (cur_block != 0);
popFreeBlock();
status |= loadFiles();
return status;
}
int tfs_mkfs(char *filename, int nBytes) {
int disk_fd;
int status = 0;
if ((disk_fd = openDisk(filename, nBytes)) < 0) {
fprintf(stderr, "Failed to open disk\n");
return DISK_ERROR;
}
disk_num = disk_fd;
num_blocks = nBytes / BLOCKSIZE;
if (nBytes > 0) {
status |= writeSuperBlock();
status |= setupFreeBlocks();
}
return status;
}
int tfs_mount(char *filename) {
int status = 0;
char block[256];
if ((disk_num = openDisk(filename, 0)) < 0) {
return DISK_ERROR;
}
file_table = checkedCalloc(num_blocks * sizeof(fileEntry));
open_file_table = checkedCalloc(num_blocks * sizeof(openFile));
open_files = 0;
total_files = 0;
loadAllData();
status |= readBlock(disk_num, 0, block);
if (block[MAGIC_BYTE] != MAGIC_NUMBER) {
status |= DISK_ERROR;
}
return status;
}
int saveAllData() {
int i, status = 0, free_block = 0, write_block = 0;;
char buf[BLOCKSIZE];
freeBlock *temp = head;
char *empty_block = checkedCalloc(BLOCKSIZE);
readBlock(disk_num, 0, buf);
buf[SIZE_BYTE] = total_files;
for (i = 1; i <= total_files; i++) {
buf[SIZE_BYTE + i] = file_table[i - 1]->inode_block_num;
}
status |= writeBlock(disk_num, 0, buf);
readBlock(disk_num, 0, buf);
free_block = temp->block_num;
empty_block[ADDR_BYTE] = temp->block_num;
status |= writeBlock(disk_num, write_block, empty_block);
temp = temp->next;
write_block = free_block;
empty_block[TYPE_BYTE] = FREE_BLOCK;
empty_block[MAGIC_BYTE] = MAGIC_NUMBER;
while (temp != NULL) {
free_block = temp->block_num;
empty_block[ADDR_BYTE] = free_block;
status |= writeBlock(disk_num, write_block, empty_block);
temp = temp->next;
write_block = free_block;
}
free_block = 0;
empty_block[ADDR_BYTE] = free_block;
status |= writeBlock(disk_num, write_block, empty_block);
free(empty_block);
return status;
}
int tfs_unmount(void) {
saveAllData();
free(file_table);
free(open_file_table);
return 0;
}
char *getCurrentTime() {
time_t raw_time;
struct tm *time_info;
char* time_string;
time(&raw_time);
time_info = localtime(&raw_time);
time_string = asctime(time_info);
return time_string;
}
fileDescriptor tfs_openFile(char *name) {
int i = -1, found = 0;
char block[BLOCKSIZE];
openFile *open_file = checkedCalloc(sizeof(openFile));
fileEntry *file;
for (i = 0; i < total_files; i++) {
if (strcmp(file_table[i]->name, name) == 0) {
file = file_table[i];
file_table[i]->num_copies++;
break;
}
}
if (i == -1) {
file = checkedCalloc(sizeof(fileEntry));
file_table[total_files++] = file;
file->name = name;
file->creation_time = getCurrentTime();
file->modification_time = file->creation_time;
file->access_time = file->creation_time;
file->fd = total_files;
file->num_copies = 1;
file->inode_block_num = -1;
file->permissions = READ_WRITE;
}
open_file->fd = open_files;
open_file->file_index = file->fd;
open_file->first_block = -1;
if (file_table[open_file->file_index]->inode_block_num != 0) {
char buf[BLOCKSIZE];
readBlock(disk_num, file_table[open_file->file_index]->inode_block_num, buf);
open_file->first_block = (int) buf[ADDR_BYTE];
}
open_file->cur_position = 0;
open_file_table[open_files++] = open_file;
return open_file->fd;
}
void shiftOpenFileTable(int index) {
int i;
free(open_file_table[index]);
for(i = index; i < open_files - 1; i++){
open_file_table[i] = open_file_table[i+1];
}
}
int tfs_closeFile(fileDescriptor fd) {
int i, status = 0;
for (i = 0; i < open_files; i++) {
if (open_file_table[i]->fd == fd) {
int file_table_index = open_file_table[i]->file_index;
shiftOpenFileTable(i);
file_table[file_table_index]->num_copies--;
--open_files;
break;
}
}
return status;
}
int tfs_writeFile(fileDescriptor fd, char *buffer, int size) {
int status = 0;
return status;
}
int tfs_deleteFile(fileDescriptor fd) {
int status = 0;
return status;
}
int tfs_readByte(fileDescriptor fd, char *buffer) {
int status = 0;
return status;
}
int tfs_seek(fileDescriptor fd, int offset) {
int status = 0;
return status;
}
|
C | #include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include "revbit.h"
int main(void) {
unsigned int i;
float x[] = {0,1,2,3,4,5,6,7}; /* Teszt adatsor felvétele. */
for(i=0;i<8;++i){
printf("x[%d]=%6.4f\n",i,x[i]); /* Teszt adatsor kiírása. */
}
printf("\nBit-reversal shorting...\n\n");
revbit_short(x,3); /* A teszt adatsor rendezése. */
for(i=0;i<8;++i){
printf("x[%d]=%6.4f\n",i,x[i]); /* Rendezett adatsor kiírása. */
}
return 0;
}
|
C | #define uchar unsigned char // 8-bit byte
#define uint unsigned int // 32-bit word
// DBL_INT_ADD treats two unsigned ints a and b as one 64-bit integer and adds c to it
#define DBL_INT_ADD(a,b,c) if (a > 0xffffffff - (c)) ++b; a += c;
#define ROTLEFT(a,b) (((a) << (b)) | ((a) >> (32-(b))))
#define ROTRIGHT(a,b) (((a) >> (b)) | ((a) << (32-(b))))
#define CH(x,y,z) (((x) & (y)) ^ (~(x) & (z)))
#define MAJ(x,y,z) (((x) & (y)) ^ ((x) & (z)) ^ ((y) & (z)))
#define EP0(x) (ROTRIGHT(x,2) ^ ROTRIGHT(x,13) ^ ROTRIGHT(x,22))
#define EP1(x) (ROTRIGHT(x,6) ^ ROTRIGHT(x,11) ^ ROTRIGHT(x,25))
#define SIG0(x) (ROTRIGHT(x,7) ^ ROTRIGHT(x,18) ^ ((x) >> 3))
#define SIG1(x) (ROTRIGHT(x,17) ^ ROTRIGHT(x,19) ^ ((x) >> 10))
typedef struct
{
uchar data[64];
uint datalen;
uint bitlen[2];
uint state[8];
} SHA256_CTX;
uint k[64] = {
0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1,
0x923f82a4, 0xab1c5ed5,
0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe,
0x9bdc06a7, 0xc19bf174,
0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa,
0x5cb0a9dc, 0x76f988da,
0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147,
0x06ca6351, 0x14292967,
0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb,
0x81c2c92e, 0x92722c85,
0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624,
0xf40e3585, 0x106aa070,
0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a,
0x5b9cca4f, 0x682e6ff3,
0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb,
0xbef9a3f7, 0xc67178f2
};
void sha256_transform(SHA256_CTX * ctx, uchar data[])
{
uint a, b, c, d, e, f, g, h, i, j, t1, t2, m[64];
for (i = 0, j = 0; i < 16; ++i, j += 4)
m[i] =
(data[j] << 24) | (data[j + 1] << 16) | (data[j + 2] << 8) |
(data[j + 3]);
for (; i < 64; ++i)
m[i] = SIG1(m[i - 2]) + m[i - 7] + SIG0(m[i - 15]) + m[i - 16];
a = ctx->state[0];
b = ctx->state[1];
c = ctx->state[2];
d = ctx->state[3];
e = ctx->state[4];
f = ctx->state[5];
g = ctx->state[6];
h = ctx->state[7];
for (i = 0; i < 64; ++i)
{
t1 = h + EP1(e) + CH(e, f, g) + k[i] + m[i];
t2 = EP0(a) + MAJ(a, b, c);
h = g;
g = f;
f = e;
e = d + t1;
d = c;
c = b;
b = a;
a = t1 + t2;
}
ctx->state[0] += a;
ctx->state[1] += b;
ctx->state[2] += c;
ctx->state[3] += d;
ctx->state[4] += e;
ctx->state[5] += f;
ctx->state[6] += g;
ctx->state[7] += h;
}
void sha256_init(SHA256_CTX * ctx)
{
ctx->datalen = 0;
ctx->bitlen[0] = 0;
ctx->bitlen[1] = 0;
ctx->state[0] = 0x6a09e667;
ctx->state[1] = 0xbb67ae85;
ctx->state[2] = 0x3c6ef372;
ctx->state[3] = 0xa54ff53a;
ctx->state[4] = 0x510e527f;
ctx->state[5] = 0x9b05688c;
ctx->state[6] = 0x1f83d9ab;
ctx->state[7] = 0x5be0cd19;
}
void sha256_update(SHA256_CTX * ctx, uchar data[], uint len)
{
uint t, i;
for (i = 0; i < len; ++i)
{
ctx->data[ctx->datalen] = data[i];
ctx->datalen++;
if (ctx->datalen == 64)
{
sha256_transform(ctx, ctx->data);
DBL_INT_ADD(ctx->bitlen[0], ctx->bitlen[1], 512);
ctx->datalen = 0;
}
}
}
void sha256_final(SHA256_CTX * ctx, uchar hash[], int *result, int size, int P)
{
uint i;
i = ctx->datalen;
// Pad whatever data is left in the buffer.
if (ctx->datalen < 56)
{
ctx->data[i++] = 0x80;
while (i < 56)
ctx->data[i++] = 0x00;
}
else
{
ctx->data[i++] = 0x80;
while (i < 64)
ctx->data[i++] = 0x00;
sha256_transform(ctx, ctx->data);
memset(ctx->data, 0, 56);
}
// Append to the padding the total message's length in bits and transform.
DBL_INT_ADD(ctx->bitlen[0], ctx->bitlen[1], ctx->datalen * 8);
ctx->data[63] = ctx->bitlen[0];
ctx->data[62] = ctx->bitlen[0] >> 8;
ctx->data[61] = ctx->bitlen[0] >> 16;
ctx->data[60] = ctx->bitlen[0] >> 24;
ctx->data[59] = ctx->bitlen[1];
ctx->data[58] = ctx->bitlen[1] >> 8;
ctx->data[57] = ctx->bitlen[1] >> 16;
ctx->data[56] = ctx->bitlen[1] >> 24;
sha256_transform(ctx, ctx->data);
// Since this implementation uses little endian byte ordering and SHA uses big endian,
// reverse all the bytes when copying the final state to the output hash.
for (i = 0; i < 4; ++i)
{
hash[i] = (ctx->state[0] >> (24 - i * 8)) & 0x000000ff;
hash[i + 4] = (ctx->state[1] >> (24 - i * 8)) & 0x000000ff;
hash[i + 8] = (ctx->state[2] >> (24 - i * 8)) & 0x000000ff;
hash[i + 12] = (ctx->state[3] >> (24 - i * 8)) & 0x000000ff;
hash[i + 16] = (ctx->state[4] >> (24 - i * 8)) & 0x000000ff;
hash[i + 20] = (ctx->state[5] >> (24 - i * 8)) & 0x000000ff;
hash[i + 24] = (ctx->state[6] >> (24 - i * 8)) & 0x000000ff;
hash[i + 28] = (ctx->state[7] >> (24 - i * 8)) & 0x000000ff;
}
//~ Hash to integer q
char *buf = malloc(size + 3);
printf(" - sha256(m):\t");
for (i = 0; i < size; ++i)
{
printf("%02x ", hash[i]);
//~ Convert hash to integer
char tmp[size];
snprintf(tmp, size, "%02x", hash[i]);
strcpy(buf, "0x");
strcat(buf, tmp);
unsigned long un = strtoul(tmp, NULL, 16);
*result += (un % P);
}
}
|
C | //
// main.c
// 记忆游戏
//
// Created by 黄梓伦 on 3/15/16.
// Copyright © 2016 黄梓伦. All rights reserved.
//
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
#include <stdbool.h>
#include <ctype.h>
int main(int argc, const char * argv[]) {
int digits = 3; //初始化打印的随机数个数
int tries = 1;
int delay = 1;
time_t wait_time = 0;
int i = 0;
time_t seed = 0; //随机函数种子值
int number = 0;
char another_game = 'Y';
do
{
bool correct = true;
while(correct)
{
if(tries % 3 == 0 && tries != 3)
digits++;
srand((unsigned int)time(&seed));
for ( i = 1; i <= digits; i++ )
{
printf("%d ",rand() % 10);//打印digits个随机数
}
fflush(stdout);
wait_time = clock();
for(;clock() - wait_time < delay*CLOCKS_PER_SEC;);//等待3秒
printf("\r");//返回行首
for(i = 1; i <= digits;i++)
{
printf(" ");//清空原有的输出数字
}
printf("\r");//返回行首
srand((unsigned int)seed);
for(i = 1;i <= digits;i++)
{
// scanf("%*[^\n]");
// scanf("%*c");// 清空输入缓冲全数据
scanf("%d",&number);
if ( number != rand() % 10)
{
correct =false;
break;
}
}
printf("%s\n",correct ? "Correct!":"Wrong!");//返回结果
tries++;
}
// fflush(stdin);
scanf("%*[^\n]");
scanf("%*c");
printf("Another Game?\n");
scanf("%c",&another_game);
}while(toupper(another_game)=='Y');
return 0;
}
|
C | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "../src/tor_string.h"
char msg[] = "test tor_string.c";
void test(void) {
char *p;
int use = 0;
int size = 0;
sprintfcat(&p, &use, &size, "12345");
printf("%s:%d:%d:%ld\n", p, use, size, strlen("12345"));
sprintfcat(&p, &use, &size, "abcdef");
printf("%s:%d:%d:%ld\n", p, use, size, strlen("abcdef"));
sprintfcat(&p, &use, &size, "6789a");
printf("%s:%d:%d:%ld\n", p, use, size, strlen("6789a"));
sprintfcat(&p, &use, &size, "6789a");
printf("%s:%d:%d:%ld\n", p, use, size, strlen("6789a"));
sprintfcat(&p, &use, &size, "6789a");
printf("%s:%d:%d:%ld\n", p, use, size, strlen("6789a"));
sprintfcat(&p, &use, &size, "6789a");
printf("%s:%d:%d:%ld\n", p, use, size, strlen("6789a"));
sprintfcat(&p, &use, &size, "6789a");
printf("%s:%d:%d:%ld\n", p, use, size, strlen("6789a"));
sprintfcat(&p, &use, &size, "6789a");
printf("%s:%d:%d:%ld\n", p, use, size, strlen("6789a"));
free(p);
}
|
C | #include <math.h>
#include <stdio.h>
double f(double x)
{
double rez;
if(x<=2)
{
rez = x*x+3*x+5;
}
else if(x<8)
{
rez = 3*x;
}
else
{
rez = pow(2.718, x)+2;
}
return rez;
}
double g(double x, double y)
{
double rez;
rez = 3*x*x + (sin(x)/pow(y, 1/4.));
return rez;
}
void afis(int pas, double y)
{
double i;
printf("Valorile functiilor f si g pentru x din [0, 10] cu pasul %d\n", pas);
for(i=0; i<=10; i += pas)
{
printf("f(%.lf, %.2lf)=%.2lf\ng(%.lf, %.2lf)=%.2lf\n\n", i, y, f(i), i, y, g(i, y));
}
}
|
C | //for string
size_t BKDRHash(const T *str)
{
register size_t hash = 0;
while (size_t ch = (size_t)*str++)
{
hash = hash * 131 + ch; // 也可以乘以31、131、1313、13131、131313..
// 可将乘法分解为位运算及加减法可以提高效率,如将上式表达为:hash = hash << 7 + hash << 1 + hash + ch;
}
return hash;
}
unsigned int times33(char *str)
{
unsigned int val = 0;
while (*str)
val = (val << 5) + val + (*str++);
return val;
}
|
C | /* we bulid a multi link stack at here.
* the stack number is SIZE*/
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define SIZE 100
typedef int TYPE;
struct node{
TYPE data;
struct node* next;
};
struct node* top[SIZE];
void init()
{
memset(top,'\0',sizeof(top));
}
int push(TYPE value,int i)
{
struct node* temp=(struct node*)malloc(sizeof(struct node));
if(!temp)
return 0;
temp->next=top[i];
temp->data=value;
top[i]=temp;
return 1;
}
int pop(TYPE* value,int i)
{
if(!top[i])
return 0;
struct node* temp;
temp=top[i];
*value=temp->data;
top[i]=temp->next;
free(temp);
}
|
C | #include "../definitions/defs.h"
#include "polykeys.h"
typedef struct
{
U64 key;
unsigned short move;
unsigned short weight;
unsigned int learn;
} S_POLY_BOOK_ENTRY;
long NumEntries = 0;
S_POLY_BOOK_ENTRY *entries;
const int PolyKindOfPiece[13] = {
-1, 1, 3, 5, 7, 9, 11, 0, 2, 4, 6, 8, 10};
void InitPolyBook()
{
EngineOptions->UseBook = FALSE;
FILE *pFile = fopen("performance.bin", "rb");
if (pFile == NULL)
{
printf("Book File Not Read\n");
}
else
{
fseek(pFile, 0, SEEK_END);
long position = ftell(pFile);
if (position < sizeof(S_POLY_BOOK_ENTRY))
{
printf("No entries found\n");
return;
}
NumEntries = position / sizeof(S_POLY_BOOK_ENTRY);
printf("%ld Entries Found in File\n", NumEntries);
entries = (S_POLY_BOOK_ENTRY *)malloc(NumEntries * sizeof(S_POLY_BOOK_ENTRY));
rewind(pFile);
size_t returnValue;
returnValue = fread(entries, sizeof(S_POLY_BOOK_ENTRY), NumEntries, pFile);
printf("fread() %ld Entries Read In From in File\n", returnValue);
if (NumEntries > 0)
{
EngineOptions->UseBook = TRUE;
}
}
}
void CleanPolyBook()
{
free(entries);
}
int HasPawnForCapture(const S_BOARD *board)
{
int sqWithPawn = 0;
int targetPce = (board->side == WHITE) ? wP : bP;
if (board->enPas != NO_SQ)
{
sqWithPawn = (board->side == WHITE) ? board->enPas - 10 : board->enPas + 10;
if (board->pieces[sqWithPawn + 1] == targetPce)
{
return TRUE;
}
else if (board->pieces[sqWithPawn - 1] == targetPce)
{
return TRUE;
}
}
return FALSE;
}
U64 PolyKeyFromBoard(const S_BOARD *board)
{
int sq = 0, rank = 0, file = 0;
U64 finalKey = 0;
int piece = EMPTY;
int polyPiece = 0;
int offset = 0;
for (sq = 0; sq < BRD_SQ_NUM; ++sq)
{
piece = board->pieces[sq];
if (piece != NO_SQ && piece != EMPTY && piece != OFFBOARD)
{
ASSERT(piece >= wP && piece <= bK);
polyPiece = PolyKindOfPiece[piece];
rank = RanksBrd[sq];
file = FilesBrd[sq];
finalKey ^= Random64Poly[(64 * polyPiece) + (8 * rank) + file];
}
}
// castling
offset = 768;
if (board->castlePerm & WKCA)
finalKey ^= Random64Poly[offset + 0];
if (board->castlePerm & WQCA)
finalKey ^= Random64Poly[offset + 1];
if (board->castlePerm & BKCA)
finalKey ^= Random64Poly[offset + 2];
if (board->castlePerm & BQCA)
finalKey ^= Random64Poly[offset + 3];
// enpassant
offset = 772;
if (HasPawnForCapture(board) == TRUE)
{
file = FilesBrd[board->enPas];
finalKey ^= Random64Poly[offset + file];
}
if (board->side == WHITE)
{
finalKey ^= Random64Poly[780];
}
return finalKey;
}
unsigned short endian_swap_u16(unsigned short x)
{
x = (x >> 8) |
(x << 8);
return x;
}
unsigned int endian_swap_u32(unsigned int x)
{
x = (x >> 24) |
((x << 8) & 0x00FF0000) |
((x >> 8) & 0x0000FF00) |
(x << 24);
return x;
}
U64 endian_swap_u64(U64 x)
{
x = (x >> 56) |
((x << 40) & 0x00FF000000000000) |
((x << 24) & 0x0000FF0000000000) |
((x << 8) & 0x000000FF00000000) |
((x >> 8) & 0x00000000FF000000) |
((x >> 24) & 0x0000000000FF0000) |
((x >> 40) & 0x000000000000FF00) |
(x << 56);
return x;
}
int ConvertPolyMoveToInternalMove(unsigned short polymove, S_BOARD *board)
{
int ff = (polymove >> 6) & 7;
int fr = (polymove >> 9) & 7;
int tf = (polymove >> 0) & 7;
int tr = (polymove >> 3) & 7;
int pp = (polymove >> 12) & 7;
char moveString[6];
if (pp == 0)
{
sprintf(moveString, "%c%c%c%c",
FileChar[ff],
RankChar[fr],
FileChar[tf],
RankChar[tr]);
}
else
{
char promChar = 'q';
switch (pp)
{
case 1:
promChar = 'n';
break;
case 2:
promChar = 'b';
break;
case 3:
promChar = 'r';
break;
}
sprintf(moveString, "%c%c%c%c%c",
FileChar[ff],
RankChar[fr],
FileChar[tf],
RankChar[tr],
promChar);
}
return ParseMove(moveString, board);
}
int GetBookMove(S_BOARD *board)
{
int index = 0;
S_POLY_BOOK_ENTRY *entry;
unsigned short move;
const int MAXBOOKMOVES = 32;
int bookMoves[MAXBOOKMOVES];
int tempMove = NOMOVE;
int count = 0;
U64 polyKey = PolyKeyFromBoard(board);
for (entry = entries; entry < entries + NumEntries; entry++)
{
if (polyKey == endian_swap_u64(entry->key))
{
move = endian_swap_u16(entry->move);
tempMove = ConvertPolyMoveToInternalMove(move, board);
if (tempMove != NOMOVE)
{
bookMoves[count++] = tempMove;
if (count > MAXBOOKMOVES)
break;
}
}
}
if (count != 0)
{
int randMove = rand() % count;
return bookMoves[randMove];
}
else
{
return NOMOVE;
}
}
|
C | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* parser_validating.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: kicausse <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2019/03/01 20:23:39 by kicausse #+# #+# */
/* Updated: 2019/03/04 23:05:46 by dilaouid ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
#include "utils.h"
#include "fdf.h"
#include <fcntl.h>
#include <unistd.h>
#include <limits.h>
static int is_valid_char(char c)
{
return (c == ' ' || ft_ishex(c) || c == ',' || c == '-');
}
int validchars(char *line)
{
int i;
i = -1;
while (line[++i])
{
if (is_valid_char(line[i]) == 0)
return (0);
}
return (1);
}
static int ft_atoiv2(const char *str)
{
int result;
int i;
int neg;
i = 0;
result = 0;
neg = 0;
if (str[0] == '-')
{
neg = 1;
++i;
}
while (str[i] >= '0' && str[i] <= '9')
result = result * 10 + str[i++] - '0';
return (neg ? -result : result);
}
void parse_values(char *str, t_point *data)
{
data->value = ft_atoiv2(str);
while (*str && *str != ',')
++str;
if (*str)
++str;
if (*str)
data->color = ft_atoi_hex(str);
else
data->color = DEFAULT_LINE_COLOR;
}
int count_file_lines(char *filename)
{
int fd;
int ret;
unsigned int count;
char buffer[2048 + 1];
if ((fd = open(filename, O_RDONLY)) == -1)
return (-1);
count = 0;
while ((ret = read(fd, buffer, 2048)) > 0)
{
buffer[ret] = 0;
count += ft_ccount(buffer, '\n');
if ((int)ft_strlen(buffer) != ret
|| ft_isstrascii(buffer) == 0
|| count > INT_MAX)
{
ret = -1;
break ;
}
}
close(fd);
return (ret == -1 ? -1 : count + 1);
}
|
C |
#include "problem4.h"
#include <stdio.h>
#include <math.h>
Triangle getLarger(Triangle first, Triangle second)
{
Triangle t;
// Fill in this function
// You'll want to replace this with something that returns a meaningful
// result.
float area1, area2;
area1 = fabs(((first.a.x)*(first.b.y - first.c.y)) + ((first.b.x)*(first.c.y - first.a.y)) + ((first.c.x)*(first.a.y - first.b.y)))/2; //fabs computes the absolute value of a floating point number
area2 = fabs(((second.a.x)*(second.b.y - second.c.y)) + ((second.b.x)*(second.c.y - second.a.y)) + ((second.c.x)*(second.a.y - second.b.y)))/2;
printf("Area 1: %.2f Area 2: %.2f\n", area1, area2);
if(area1 > area2)
t = first;
else
t = second;
return(t);
}
|
C | /************************************
ACH2024 - Algoritmos e Estruturas de Dados II
Implementacao de Grafos utilizando Listas de Adjacencia
(vetor de ponteiros no qual cada posicao indexa um vertice e
contem o ponteiro para a cabeca de sua lista de adjacencia)
*************************************/
#include <stdbool.h> /* variaveis bool assumem valores "true" ou "false" */
#include <stdint.h> /* cast para converter ponteiros para int e vice-versa */
#define COR_BRANCO 0
#define COR_CINZA 1
#define COR_PRETO 2
#define INFINITO 9999
typedef int TipoPeso;
typedef int TipoCor;
/*
tipo estruturado taresta:
vertice destino, peso, ponteiro p/ prox. aresta
*/
typedef struct taresta {
int vdest;
TipoPeso peso;
struct taresta *prox;
} TipoAresta;
typedef TipoAresta* TipoApontador;
/*
tipo estruturado grafo:
vetor de listas de adjacencia (cada posicao contem o ponteiro
para o inicio da lista de adjacencia do vertice)
numero de vertices
*/
typedef struct {
TipoApontador *listaAdj;
int numVertices;
int numArestas;
} TipoGrafo;
typedef struct tno {
int v;
struct tno *prox;
} TipoNo;
typedef struct {
TipoNo *inicio;
TipoNo *fim;
} TipoLista;
/********************
Prototipos dos metodos sobre grafos
*********************/
/*
inicializaGrafo(TipoGrafo* grafo, int nv): Cria um grafo com n vertices.
Aloca espaco para o vetor de apontadores de listas de adjacencias e,
para cada vertice, inicializa o apontador de sua lista de adjacencia.
Retorna true se inicializou com sucesso e false caso contrario.
Vertices vao de 1 a nv.
*/
bool inicializaGrafo(TipoGrafo *grafo, int nv);
/*
void insereAresta(int v1, int v2, TipoPeso peso, TipoGrafo *grafo):
Insere a aresta (v1, v2) com peso "peso" no grafo.
Nao verifica se a aresta ja existe.
*/
void insereAresta(int v1, int v2, TipoPeso peso, TipoGrafo *grafo);
/*
bool existeAresta(int v1, int v2, TipoGrafo *grafo):
Retorna true se existe a aresta (v1, v2) no grafo e false caso contrário
*/
bool existeAresta(int v1, int v2, TipoGrafo *grafo);
/*
bool removeAresta(int v1, int v2, TipoPeso* peso, TipoGrafo *grafo);
Remove a aresta (v1, v2) do grafo.
Se a aresta existia, coloca o peso dessa aresta em "peso" e retorna true,
caso contrario retorna false (e "peso" é inalterado).
*/
bool removeAresta(int v1, int v2, TipoPeso* peso, TipoGrafo *grafo);
/*
bool listaAdjVazia(int v, TipoGrafo* grafo):
Retorna true se a lista de adjacencia (de vertices adjacentes) do vertice v é vazia, e false caso contrário.
*/
bool listaAdjVazia(int v, TipoGrafo *grafo);
/*
TipoApontador primeiroListaAdj(int v, TipoGrafo* grafo):
Retorna o endereco do primeiro vertice da lista de adjacencia de v
ou NULL se a lista de adjacencia estiver vazia.
*/
TipoApontador primeiroListaAdj(int v, TipoGrafo *grafo);
/*
TipoApontador proxListaAdj(int v, TipoGrafo* grafo):
Retorna o proximo vertice adjacente a v, partindo do vertice "prox" adjacente a v
ou NULL se a lista de adjacencia tiver terminado sem um novo proximo.
*/
TipoApontador proxListaAdj(int v, TipoGrafo *grafo, TipoApontador prox);
/*
void imprimeGrafo(TipoGrafo* grafo):
Imprime os vertices e arestas do grafo no seguinte formato:
v1: (adj11, peso11); (adj12, peso12); ...
v2: (adj21, peso21); (adj22, peso22); ...
Assuma que cada vértice é um inteiro de até 2 dígitos.
*/
void imprimeGrafo(TipoGrafo *grafo);
/*
void liberaGrafo (TipoGrafo *grafo): Libera o espaco ocupado por um grafo.
*/
void liberaGrafo (TipoGrafo *grafo);
/*
LeGrafo(nomearq, Grafo)
Le o arquivo nomearq e armazena na estrutura Grafo
Lay-out:
A 1a linha deve conter o número de vertices e o numero de arestas do grafo,
separados por espaço.
A 2a linha em diante deve conter a informacao de cada aresta, que consiste
no indice do vertice de origem, indice do vertice de destino e o peso da
aresta, tambem separados por espacos.
Observações:
Os vertices devem ser indexados de 0 a |V|-1
Os pesos das arestas sao numeros racionais nao negativos.
Exemplo: O arquivo abaixo contem um grafo com 4 verticennnns (0,1,2,3) e
7 arestas.
4 7
0 3 6.3
2 1 5.0
2 0 9
1 3 1.7
0 1 9
3 1 5.6
0 2 7.2
Codigo de saida:
1: leitura bem sucedida
0: erro na leitura do arquivo
*/
int leGrafo(char* nomearq, TipoGrafo *grafo);
/*
fimListaAdj(v, p, Grafo): indica se o ponteiro atual p chegou ao
fim da lista de adjacencia de v (p == NULL).
*/
bool fimListaAdj(int v, TipoApontador p, TipoGrafo *grafo);
/*
recuperaAdj(v, p, u, peso, grafo): dado um vertice v e um
ponteiro para uma aresta da lista de adjacencia de v,
devolve nas variaveis "peso" e "u" respectivamente o peso
da aresta e o numero do vertice adjacente
*/
void recuperaAdj(int v, TipoApontador p, int *u, TipoPeso *peso,
TipoGrafo *grafo);
/*
TipoApontador existeERetornaAresta(int v1, int v2, TipoGrafo *grafo):
Retorna um apontador para a aresta (v1,v2) se ela existir e NULL caso Contrario.
*/
TipoApontador existeERetornaAresta(int v1, int v2, TipoGrafo *grafo);
/*
TipoLista criaLista(): cria uma lista ligada vazia para inteiros
*/
TipoLista *criaLista();
/*
int contaLista(TipoLista *lista): conta elementos numa lista
*/
int contaLista(TipoLista *lista);
/*
insereOrdenado(int v, TipoLista *lista): insere um elemento na sua posição de acordo com o
valor indicado
*/
void insereOrdenado(int v, TipoLista *lista);
/*
insereFila(int v, TipoLista *fila): insere um elemento no fim da fila.
*/
void insereFila(int v, TipoLista *fila);
/*
int removeFila(TipoLista *fila): remove um elemento do início da fila.
*/
int removeFila(TipoLista *fila);
/*
bool filaVazia(TipoLista *lista): verifica se a lista está vazia
*/
bool listaVazia(TipoLista *lista);
/*
TipoNo *ultimoNo(TipoLista *fila): percorre a fila até o último nó
*/
TipoNo *ultimoNo(TipoLista *fila);
/*
void imprimeFila(TipoLista *lista): imprime os elementos da lista
*/
void imprimeLista(TipoLista *lista);
/*
inserePilha(int v, TipoLista *pilha): insere um elemento no topo da pilha.
*/
void inserePilha(int v, TipoLista *pilha);
/*
BFS(int *antecessores, int *distancias, TipoGrafo *grafo, TipoLista *descobertas):
Executa a busca em largura no grafo
*/
void BFS(int *antecessores, int *distancias, TipoGrafo *grafo, TipoLista *descobertas);
/*
visitaBFS(int v, TipoGrafo *grafo, TipoCor *cores, int *antecessores, int *distancias, TipoLista *descobertas):
visita cada elemento do grafo e dispara a busca por novos elementos, atribuindo as novas cores e distâncias
*/
void visitaBFS(int v, TipoGrafo *grafo, TipoCor *cores, int *antecessores, int *distancias, TipoLista *descobertas);
/*
imprimeBFS(TipoGrafo *grafo): imprime os dados de descobertas e caminhos do grafo
*/
void imprimeBFS(TipoGrafo *grafo);
/*
imprimeCaminho(int v, int *antecessores): imprime um caminho de um vértice até sua raiz segundo a busca realizada
*/
void imprimeCaminho(int v, int *antecessores);
/*
DFS(int *antecessores, int *distancias, TipoGrafo *grafo, TipoLista *descobertas):
Executa a busca em profundidade no grafo
*/
void DFS(int *antecessores, TipoGrafo *grafo, TipoLista *descobertas);
/*
visitaDFS(int v, TipoGrafo *grafo, TipoCor *cores, int *antecessores, int *distancias, TipoLista *descobertas):
visita cada elemento do grafo e dispara a busca por novos elementos, atribuindo as novas cores e distâncias
*/
void visitaDFS(int v, TipoGrafo *grafo, int *tempo, TipoCor *cores, int *tdesc, int *tterm, int *antecessores, TipoLista *descobertas);
/*
imprimeDFS(TipoGrafo *grafo): imprime os dados de descobertas e caminhos do grafo
*/
void imprimeDFS(TipoGrafo *grafo);
/*
imprimeConjuntosConectados(TipoGrafo *grafo): imprime os conjuntos conectados encontrados no grafo
*/
void imprimeConjuntosConectados(TipoLista *conjuntos);
/*
TipoLista *conjuntosConectados(TipoGrafo *grafo): cria uma lista com os conjuntos conectados do grafo
*/
TipoLista *conjuntosConectados(TipoGrafo *grafo);
/*
visitaConjuntosConectados(int v, TipoGrafo *grafo, TipoCor *cores, TipoLista *fila):
percorre o grafo encontrando elementos para os conjuntos conectados
*/
void visitaConjuntosConectados(int v, TipoGrafo *grafo, TipoCor *cores, TipoLista *fila);
/*
TipoLista *verticesDeArticulacao(TipoGrafo *grafo): cria uma lista com os vértices de articulação do grafo
*/
TipoLista *verticesDeArticulacao(TipoGrafo *grafo, TipoLista *conjuntos);
/*
TipoLista *conjuntosConectadosSemVertice(TipoGrafo *grafo, int excluido): cria uma lista com os conjuntos conectados
de um grafo excluindo um vértice dado como parâmetro
*/
TipoLista *conjuntosConectadosSemVertice(TipoGrafo *grafo, int excluido);
/*
void visitaConjuntosConectadosSemVertice(int v, TipoGrafo *grafo, TipoCor *cores, TipoLista *fila, int excluido):
percorre o grafo encontrando elementos para os conjuntos conectados evitando arestas que apontem para um vértice dado
como parâmetro
*/
void visitaConjuntosConectadosSemVertice(int v, TipoGrafo *grafo, TipoCor *cores, TipoLista *fila, int excluido);
|
C | #include<stdio.h>
#include<stdlib.h>
struct node
{
int info;
struct node *link;
};
struct node *addatbeg(struct node *start,int data)
{
struct node *tmp;
tmp=(struct node *)malloc(sizeof(struct node));
tmp->info=data;
tmp->link=start;
start=tmp;
return start;
}/*End of addatbeg()*/
struct node *addatend(struct node *start,int data)
{
struct node *p,*tmp;
tmp=(struct node *)malloc(sizeof(struct node));
tmp->info=data;
p=start;
while(p->link!=NULL)
p=p->link;
p->link=tmp;
tmp->link=NULL;
return start;
}/*End of addatend()*/
struct node *addafter(struct node *start,int data,int item)
{
struct node *tmp,*p;
p=start;
while(p!=NULL)
{
if(p->info == item)
{
tmp=(struct node *)malloc(sizeof(struct node));
tmp->info=data;
tmp->link=p->link;
p->link=tmp;
return start;
}
p=p->link;
}
printf("%d not present in the list\n",item);
return start;
}/*End of addafter()*/
struct node *addbefore(struct node *start,int data,int item)
{
struct node *tmp,*p;
if(start == NULL )
{
printf("List is empty\n");
return start;
}
/*If data to be inserted before first node*/
if(item==start->info)
{
tmp=(struct node *)malloc(sizeof(struct node));
tmp->info=data;
tmp->link=start;
start=tmp;
return start;
}
p = start;
while(p->link!=NULL)
{
if(p->link->info==item)
{
tmp=(struct node *)malloc(sizeof(struct node));
tmp->info=data;
tmp->link=p->link;
p->link=tmp;
return start;
}
p=p->link;
}
printf("%d not present in the list\n",item);
return start;
}/*End of addbefore()*/
struct node *addatpos(struct node *start,int data,int pos)
{
struct node *tmp,*p;
int i;
p=start;
for(i=1; i<pos-1 && p!=NULL; i++)
p=p->link;
if(p==NULL)
printf("There are less than %d elements\n",pos);
else
{
tmp=(struct node *)malloc(sizeof(struct node));
tmp->info=data;
if(pos==1)
{
tmp->link=start;
start=tmp;
}
else
{
tmp->link=p->link;
p->link=tmp;
}
}
return start;
}/*End of addatpos()*/
|
C | #include <cs50.h>
#include <stdio.h>
int main() {
int i, j, rows;
while(true){
rows = get_int("Height: ");
if(rows >= 0 && rows <=23){
for(i = 1; i <= rows; i++){
for(j = 1; j <= rows+1; j++){
if(j <= rows-i){
printf(" ");
} else {
printf("#");
}
}
printf("\n");
}
break;
}
}
return 0;
}
|
C | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_putcolors.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: bsautron <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2014/12/03 15:30:52 by bsautron #+# #+# */
/* Updated: 2014/12/03 18:31:16 by bsautron ### ########.fr */
/* */
/* ************************************************************************** */
#include "ft_ls.h"
void no_colors(t_dir *file, t_option *op)
{
if (S_ISLNK(file->buf.st_mode))
{
ft_putstr(file->name);
if (op->format == LONG)
{
ft_putstr(" -> ");
ft_putstr(file->format->linkname);
}
}
else
ft_putstr(file->name);
ft_putendl("");
}
void ft_putcolors(t_dir *file, t_option *op)
{
if (op->pipe == PIPE && S_ISDIR(file->buf.st_mode))
file->name = ft_makedir(file->name);
if (op->colors == COLORS)
{
if (S_ISDIR(file->buf.st_mode))
ft_putstr("\033[33;31m");
if (S_ISLNK(file->buf.st_mode))
{
ft_putstr("\033[33;32m");
ft_putstr(file->name);
if (op->format == LONG)
{
ft_putstr("\033[33;37m -> ");
ft_putstr(file->format->linkname);
}
}
else
ft_putstr(file->name);
ft_putendl("\033[33;37m");
}
else
no_colors(file, op);
}
|
C | #include <stdio.h>
int factorial(int);
int main(void) {
int y = 0;
for (int i = 0; i <= 100; i++) {
y += i;
printf("\n%d ---Iterativa---> %d", i, y);
}
printf("\nEl factorial de 100 es %d", factorial(100));
return 0;
}
int factorial(int n) {
int r;
if (n == 1) {
r = 1;
printf("\nCaso base alcanzado");
} else {
printf("\nCaso recursivo para n = %d", n);
r = n + factorial(n - 1);
printf("\nn = %d ---> %d", n, r);
}
return r;
} |
C | #include "async_serial_1.h"
#include <avr/io.h>
void async_serial_1_init(SerialSpeed speed){
switch(speed){
case SERIAL_SPEED_9600:
//Clear double speed bit and errors
UCSR1A = 0;
UBRR1 = 103;
break;
case SERIAL_SPEED_19200:
UCSR1A = 0;
UBRR1 = 51;
break;
case SERIAL_SPEED_38400:
UCSR1A = 0;
UBRR1 = 25;
break;
case SERIAL_SPEED_76800:
UCSR1A = 0;
UBRR1 = 12;
break;
default:
case SERIAL_SPEED_115200:
//double speed
UCSR1A = 1<<U2X1;
UBRR1 = 16;
break;
}
//enable tx & rx, no ints
UCSR1B = (1<<RXEN1) | (1<<TXEN1);
//8N1 async data
UCSR1C = (1<<UCSZ11)|(1<<UCSZ10);
}
char async_serial_1_byte_ready(){
return UCSR1A & (1<<RXC1);
}
char async_serial_1_read_byte(){
while (!(UCSR1A & (1<<RXC1))){}
return UDR1;
}
void async_serial_1_write_byte(char data){
while (!(UCSR1A & (1<<UDRE1))){}
UDR1 = data;
}
void async_serial_1_write_string(const char *string){
int i;
for (i=0; string[i]; i++){
async_serial_1_write_byte(string[i]);
}
}
void async_serial_1_rx_interrupt(char on) {
if (on) UCSR1B = UCSR1B | 1<<RXCIE1;
else UCSR1B = UCSR1B & (~(1<<RXCIE1));
}
|
C | //
// pointer.c
// Hello
//
// Created by Hui Zhou on 6/8/14.
// Copyright (c) 2014 Hui Zhou. All rights reserved.
//
#include <stdio.h>
#define ALLOCSIZE 10000 /* size of available space */
static char allocbuf[ALLOCSIZE]; /* storage for alloc */
static char *allocp = allocbuf; /* next free position */
char * alloc(int n) {/*return pointer to n characters */
if(allocbuf + ALLOCSIZE - allocp >= n){
allocp += n;
return allocp - n;
} else {
return 0;
}
}
void afree(char *p) { /* free storage pointed by p */
if (p >= allocbuf && p < allocbuf + ALLOCSIZE){
allocp = p;
}
}
|
C | /*
Get the system time.
which can be accurate to seconds (for general events),
one decimal place (for triggering events),
or milliseconds (for sampling)
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/timeb.h>
#include <sys/types.h>
#include <time.h>
#include "../include/systime.h"
int eq_year, eq_month, eq_day, eq_hour, eq_min, eq_sec;
//Get the system time, accurate to seconds
double get_system_time()
{
struct timeb nowtime;
double t;
ftime(&nowtime);
t = nowtime.time;
return t;
}
//Get the system time, accurate to one decimal place
double get_system_time1f()
{
struct timeb nowtime;
int temp_decimal_time;
long long temp_integer_time;
double t;
ftime(&nowtime);
temp_integer_time = (1000 * nowtime.time + nowtime.millitm)/100;
temp_decimal_time = (1000 * nowtime.time + nowtime.millitm)%100;
if(temp_decimal_time >= 50){
temp_integer_time += 1;
}
t = temp_integer_time /10.0;
return t;
}
//Get the system time, accurate to milliseconds
double get_system_time3f()
{
struct timeb nowtime;
double t;
ftime(&nowtime);
t = (nowtime.time * 1000 + nowtime.millitm)/1000.0;
return t;
}
void get_date_time()
{
time_t rawtime;
struct tm * timeinfo;
time(&rawtime);
timeinfo = localtime(&rawtime);
eq_year = timeinfo->tm_year % 100;
eq_month = timeinfo->tm_mon + 1;
eq_day = timeinfo->tm_mday;
eq_hour = timeinfo->tm_hour;
eq_min = timeinfo->tm_min;
eq_sec = timeinfo->tm_sec;
} |
C | #include <stdio.h>
int main(){
int n,x=1,i;
scanf("%d",&n);
while (x<=n){
for(i=1;i<x;i++){
printf("%02d ",x);
}
printf("%02d",x);
printf("\n");
x++;
}
printf("\n");
x=1;
while (x<=n){
for(i=1;i<x;i++){
printf("%02d ",i);
}
printf("%02d",i);
printf("\n");
x++;
}
return 0;
}
|
C | #include<stdio.h>
void main(){
int a;
char ch;
printf("Enter number:\n");
scanf("%d",&a);
printf("%d is ascii of %c\n",a,a);
}
|
C | /*
* ingresos.h
*
* Created on: 17 oct. 2021
* Author: MariaElena
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
int UTN_validarNumeroEnteroIngresado(char *pIngreso);
int UTN_validarNumeroFlotanteIngresado(char *pIngreso);
int UTN_validadCaracterIngresado(char ingreso);
int UTN_validarCadenaAlfabeticaIngresada(char *pIngreso);
int UTN_ingresoInt(char* variableTexto, char* textoError);
float UTN_ingresoFloat(char* variableTexto, char* textoError);
char UTN_ingresoChar(char* variableTexto, char* textoError);
int UTN_ingresoTextoReintentos(char pIngreso[],int tam, char* variableTexto, char* textoError, int reintentos);
int UTN_ingresoIntReintentos(int* pIngreso, char* variableTexto, char* textoError, int reintentos);
float UTN_ingresoFloatReintentos(float* pIngreso, char* variableTexto, char* textoError, int reintentos);
char UTN_ingresoCharReintentos(char* pIngreso, char* variableTexto, char* textoError,int reintentos);
int UTN_ingresoIntReintentosMinMax(int* pIngreso, char* variableTexto, char* textoError, int min, int max, int reintentos);
float UTN_ingresoFloatReintentosMinMax(float* pIngreso, char* variableTexto, char* textoError, float min, float max,int reintentos);
char UTN_ingresoCharReintentosMinMax(char* pIngreso,char* variableTexto, char* textoError, char min, char max, int reintentos);
|
C | //Variant 5
#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
#include <string.h>
#include "func.h"
int main(int argc, char *argv[])
{
const char *prog_name = argv[0];
if (argc != 2)
{
printf("usage: %s num\n", prog_name);
return EXIT_FAILURE;
}
FILE *file = fopen(argv[1], "r");
if (file == 0)
{
printf("not found %s\n", argv[1]);
return EXIT_FAILURE;
}
// printf("chisla %d %d %d\n", rows, cols, notnull);
matrix* m1 = create_matrix_from_file(file);
if(m1 == NULL)
{
return EXIT_FAILURE;
}
if(real_amount_notnull_elem(file, m1) == EXIT_FAILURE)
{
return EXIT_FAILURE;
}
fseek(file, (5), SEEK_SET);
// long pos;
// pos = ftell(file);
// printf("pos %ld\n", pos);
if (set_notnull_elem(file, m1) == EXIT_FAILURE)
{
return EXIT_FAILURE;
}
fclose(file);
print(m1);
int norma = norma_L(m1);
free_memory(m1);
printf("norma %d\n", norma);
return EXIT_SUCCESS;
}
|
C | /*
* PostDims.c
*
* Created: 16-Feb-17 15:00:24
* Author: Andreas
*/
#include <avr/io.h>
#define F_CPU 3868400
#include <util/delay.h>
#include <avr/cpufunc.h>
#include <avr/interrupt.h>
#include <stdio.h>
#include <string.h>
#include "memoryHandler.h"
#include "localMemoryHandler.h"
#include "smsHandler.h"
#include "uart.h"
#include "phonenumber.h"
#include "ADC.h"
#define DDR_switch DDRA
#define PIN_switch PINA
#define DDR_led DDRB
#define PORT_led PORTB
FlushArray(char *array, char size);
SMSType ParseBody(char *number, char *body, char size);
void HandleMemoryFromType(SMSType type, char *number);
char receivedChar = 0;
char header[100] = {0};
char body[100] = {0};
char adcData = 0xFF;
phonenumber numbers[10];
char phoneNumberCounter = 0;
char mailCounter = 0;
ISR(ADC_vect) {
adcData = ADCH;
StartADC();
}
void TurnOffStatusLEDS();
int main(void)
{
// PRODUCTION --v
DDR_led = 0xFF;
DDRA &= 0b11110011;
PORT_led = 0xFF;
SetupMemory();
PORT_led &= ~(1<<0);
InitUART(9600, 8);
InitADC();
PORT_led &= ~(1<<1);
InitSMS('0', '1', "3257");
PORT_led &= ~(1<<2);
DeleteAll(20);
PORT_led &= ~(1<<3);
LoadAllNumbersFromEEPROM(numbers, &phoneNumberCounter);
PORT_led &= ~(1<<4);
while (1) {
if (adcData < 30) {
TurnOffStatusLEDS();
PORT_led &= ~(1<<7);
SendSMSToAll(numbers, phoneNumberCounter);
mailCounter++;
PORT_led &= ~(1<<6);
}
if ((PINA & (1<<2)) == 0) {
TurnOffStatusLEDS();
mailCounter = 0;
PORT_led &= ~(1<<6);
}
if (!CharReady()) {
continue;
}
receivedChar = ReadChar();
if(receivedChar == '+') {
TurnOffStatusLEDS();
PORT_led &= ~(1<<5);
while (ReadChar() != ',') {
}
char index = ReadChar();
// Read CR and LF after index
ReadChar();
ReadChar();
ReadSMS(index, header, body);
DeleteSMS(index);
PORT_led &= ~(1<<6);
char number[9];
ExtractNumber(header, number);
UART_Flush();
SMSType type = ParseBody(number, body, 100);
SendSMS(number, type, mailCounter);
PORT_led &= ~(1<<7);
// Handle local memory (subscribe/unsubscribe
HandleMemoryFromType(type, number);
// Empty header and body
FlushArray(header, 100);
FlushArray(body, 100);
}
}
_NOP();
while (1);
}
FlushArray(char *array, char size) {
for (char i = 0; i < size; i++) {
if (array[i] == 0) {
break;
}
array[i] = 0;
}
}
SMSType ParseBody(char *number, char *body, char size) {
if (strcmp("SUBSCRIBE", body) == 0) {
if (FindNumber(numbers, number, phoneNumberCounter) > -1) {
return ALREADY_SUBSCRIBED;
}
else if (phoneNumberCounter >= 10) {
return NUMBERS_FULL;
}
return SUBSCRIBED;
}
else if (strcmp("UNSUBSCRIBE", body) == 0) {
if (FindNumber(numbers, number, phoneNumberCounter) == -1) {
return NOT_SUBSCRIBED;
}
return UNSUBSCRIBED;
}
else if (strcmp("HELP", body) == 0) {
return HELP;
}
else if (strcmp("STATUS", body) == 0) {
return STATUS;
}
return UNKNOWN_COMMAND;
}
void HandleMemoryFromType(SMSType type, char *number) {
if (type == SUBSCRIBED) {
SaveNumberInLocalMemory(numbers, number, &phoneNumberCounter);
SaveNumber(number);
}
else if (type == UNSUBSCRIBED) {
RemoveNumberFromLocalMemory(numbers, number, &phoneNumberCounter);
DeleteNumber(number);
}
}
void TurnOffStatusLEDS() {
PORT_led |= ((1<<5) | (1<<6) | (1<<7));
} |
C | #include <stdio.h>
int main(void) {
int data;
printf("Digite uma data no formato DDMMAAAA, onde DD corresponde ao dia, MM ao mês e AAAA ao ano: \n");
scanf("%d", &data);
printf("%d de %d de %d\n", (data / 1000000), ((data / 10000) % 10), (data % 10000));
return 0;
}
|
C | /*
* MaxIntegerInFile.c
*
* Created on: 05/09/2012
* Author: Jens
*/
#include <stdio.h>
static const char filename[] = "ECG.txt";
int MaxIntegerInFile() {
int max;
int i1;
int success;
FILE *file = fopen(filename, "r");
fscanf(file, "%i", &i1);
max = i1;
do {
success = fscanf(file, "%i", &i1);
if (i1 > max) {
max = i1;
}
} while (success != EOF);
printf("Max found: %i", max);
return 0;
}
|
C | #include<stdio.h>
#include<string.h>
int main()
{
int A[3][3];
printf("Please input array-A,sir/madam: \n");
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
{
scanf("%d", &A[i][j]);
}
}
printf("the array is:\n");
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
{
printf("%3d",A[i][j]);
}
printf("\n");
}
printf("memset \n");
memset(A,0,sizeof(A));
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
{
printf("%3d",A[i][j]);
}
printf("\n");
}
} |
C | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_map_parser.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: dkarthus <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2020/12/04 15:08:56 by dkarthus #+# #+# */
/* Updated: 2020/12/06 20:00:16 by dkarthus ### ########.fr */
/* */
/* ************************************************************************** */
#include "../cub3d.h"
static char **ft_create_map(char *file, char **map)
{
int fd;
int i;
int j;
i = 1;
j = 0;
fd = open(file, O_RDONLY);
while (i)
{
i = ft_get_next_line(fd, &map[j]);
j++;
if (i == -1)
return (NULL);
}
close(fd);
return (map);
}
char **ft_parse(char *file)
{
int fd;
int i;
char *line;
char **map;
size_t lines;
lines = 0;
i = 1;
if ((fd = open(file, O_RDONLY)) == -1)
return (NULL);
while (i)
{
i = ft_get_next_line(fd, &line);
free(line);
lines++;
}
if (!(map = ft_calloc((lines + 1), sizeof(char *))))
return (NULL);
close(fd);
return (ft_create_map(file, map));
}
|
C | #include <stdio.h>
void trace(int A[], int N);
void bubbleSort(int A[], int N);
int main(){
int A[100],N;
scanf("%d",&N);
for(int i=0; i<N; i++){
scanf("%d", &A[i]);
}
trace(A,N);
bubbleSort(A,N);
trace(A,N);
}
void trace(int A[],int N){
for(int i=0; i<N; i++){
printf("%d ",A[i]);
}
printf("\n");
}
void bubbleSort(int A[],int N){
int flag = 1;
int i = 0;
while(flag){
flag = 0;
trace(A,N);
for(int j=N-1;j>i; j--){
if(A[j] < A[j-1]){
int num = A[j];
A[j] = A[j-1];
A[j-1] = num;
flag = 1;
}
trace(A,N);
}
printf("\n");
printf("flag = %d\n", flag);
i++;
}
}
|
C | #include <stdlib.h>
#include <stdio.h>
#include <stdint.h>
#include <ctype.h>
#include <string.h>
#include <assert.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include "parse.h"
static void wrtype(FILE *fd, Type *val);
static void rdtype(FILE *fd, Type **dest);
static void wrstab(FILE *fd, Stab *val);
static Stab *rdstab(FILE *fd);
static void wrsym(FILE *fd, Node *val);
static Node *rdsym(FILE *fd, Trait *ctx);
static void pickle(FILE *fd, Node *n);
static Node *unpickle(FILE *fd);
/* type fixup list */
static Htab *tydedup; /* map from name -> type, contains all Tynames loaded ever */
static Htab *tidmap; /* map from tid -> type */
static Htab *trmap; /* map from trait id -> trait */
static Type ***typefixdest; /* list of types we need to replace */
static size_t ntypefixdest; /* size of replacement list */
static intptr_t *typefixid; /* list of types we need to replace */
static size_t ntypefixid; /* size of replacement list */
#define Builtinmask (1 << 30)
/* Outputs a symbol table to file in a way that can be
* read back usefully. Only writes declarations, types
* and sub-namespaces. Captured variables are ommitted. */
static void wrstab(FILE *fd, Stab *val)
{
size_t n, i;
void **keys;
pickle(fd, val->name);
/* write decls */
keys = htkeys(val->dcl, &n);
wrint(fd, n);
for (i = 0; i < n; i++)
wrsym(fd, getdcl(val, keys[i]));
free(keys);
/* write types */
keys = htkeys(val->ty, &n);
wrint(fd, n);
for (i = 0; i < n; i++) {
pickle(fd, keys[i]); /* name */
wrtype(fd, gettype(val, keys[i])); /* type */
}
free(keys);
/* write stabs */
keys = htkeys(val->ns, &n);
wrint(fd, n);
for (i = 0; i < n; i++)
wrstab(fd, getns(val, keys[i]));
free(keys);
}
/* Reads a symbol table from file. The converse
* of wrstab. */
static Stab *rdstab(FILE *fd)
{
Stab *st;
Type *ty;
Node *nm;
int n;
int i;
/* read dcls */
st = mkstab();
st->name = unpickle(fd);
n = rdint(fd);
for (i = 0; i < n; i++)
putdcl(st, rdsym(fd, NULL));
/* read types */
n = rdint(fd);
for (i = 0; i < n; i++) {
nm = unpickle(fd);
rdtype(fd, &ty);
puttype(st, nm, ty);
}
/* read stabs */
n = rdint(fd);
for (i = 0; i < n; i++)
putns(st, rdstab(fd));
return st;
}
static void wrucon(FILE *fd, Ucon *uc)
{
wrint(fd, uc->line);
wrint(fd, uc->id);
wrbool(fd, uc->synth);
pickle(fd, uc->name);
wrbool(fd, uc->etype != NULL);
if (uc->etype)
wrtype(fd, uc->etype);
}
static Ucon *rducon(FILE *fd, Type *ut)
{
Type *et;
Node *name;
Ucon *uc;
size_t id;
int line;
int synth;
et = NULL;
line = rdint(fd);
id = rdint(fd);
synth = rdbool(fd);
name = unpickle(fd);
uc = mkucon(line, name, ut, et);
if (rdbool(fd))
rdtype(fd, &uc->etype);
uc->id = id;
uc->synth = synth;
return uc;
}
/* Writes the name and type of a variable,
* but only writes its intializer for things
* we want to inline cross-file (currently,
* the only cross-file inline is generics) */
static void wrsym(FILE *fd, Node *val)
{
/* sym */
wrint(fd, val->line);
pickle(fd, val->decl.name);
wrtype(fd, val->decl.type);
/* symflags */
wrint(fd, val->decl.vis);
wrbool(fd, val->decl.isconst);
wrbool(fd, val->decl.isgeneric);
wrbool(fd, val->decl.isextern);
if (val->decl.isgeneric && !val->decl.trait)
pickle(fd, val->decl.init);
}
static Node *rdsym(FILE *fd, Trait *ctx)
{
int line;
Node *name;
Node *n;
line = rdint(fd);
name = unpickle(fd);
n = mkdecl(line, name, NULL);
rdtype(fd, &n->decl.type);
if (rdint(fd) == Vishidden)
n->decl.ishidden = 1;
n->decl.trait = ctx;
n->decl.isconst = rdbool(fd);
n->decl.isgeneric = rdbool(fd);
n->decl.isextern = rdbool(fd);
if (n->decl.isgeneric && !ctx)
n->decl.init = unpickle(fd);
return n;
}
/* Writes types to a file. Errors on
* internal only types like Tyvar that
* will not be meaningful in another file*/
static void typickle(FILE *fd, Type *ty)
{
size_t i;
if (!ty) {
die("trying to pickle null type\n");
return;
}
wrbyte(fd, ty->type);
wrbyte(fd, ty->vis);
/* tid is generated; don't write */
/* FIXME: since we only support hardcoded traits, we just write
* out the set of them. we should write out the trait list as
* well */
if (!ty->traits) {
wrint(fd, 0);
} else {
wrint(fd, bscount(ty->traits));
for (i = 0; bsiter(ty->traits, &i); i++)
wrint(fd, i);
}
wrint(fd, ty->nsub);
switch (ty->type) {
case Tyunres:
pickle(fd, ty->name);
break;
case Typaram:
wrstr(fd, ty->pname);
break;
case Tystruct:
wrint(fd, ty->nmemb);
for (i = 0; i < ty->nmemb; i++)
pickle(fd, ty->sdecls[i]);
break;
case Tyunion:
wrint(fd, ty->nmemb);
for (i = 0; i < ty->nmemb; i++)
wrucon(fd, ty->udecls[i]);
break;
case Tyarray:
wrtype(fd, ty->sub[0]);
pickle(fd, ty->asize);
break;
case Tyslice:
wrtype(fd, ty->sub[0]);
break;
case Tyvar:
die("Attempting to pickle %s. This will not work.\n", tystr(ty));
break;
case Tyname:
pickle(fd, ty->name);
wrbool(fd, ty->issynth);
wrint(fd, ty->nparam);
for (i = 0; i < ty->nparam; i++)
wrtype(fd, ty->param[i]);
wrint(fd, ty->narg);
for (i = 0; i < ty->narg; i++)
wrtype(fd, ty->arg[i]);
wrtype(fd, ty->sub[0]);
break;
default:
for (i = 0; i < ty->nsub; i++)
wrtype(fd, ty->sub[i]);
break;
}
}
static void traitpickle(FILE *fd, Trait *tr)
{
size_t i;
wrint(fd, tr->uid);
wrbool(fd, tr->ishidden);
pickle(fd, tr->name);
typickle(fd, tr->param);
wrint(fd, tr->nmemb);
for (i = 0; i < tr->nmemb; i++)
wrsym(fd, tr->memb[i]);
wrint(fd, tr->nfuncs);
for (i = 0; i < tr->nfuncs; i++)
wrsym(fd, tr->funcs[i]);
}
static void wrtype(FILE *fd, Type *ty)
{
if (ty->tid >= Builtinmask)
die("Type id %d for %s too big", ty->tid, tystr(ty));
if (ty->vis == Visbuiltin)
wrint(fd, ty->type | Builtinmask);
else
wrint(fd, ty->tid);
}
static void rdtype(FILE *fd, Type **dest)
{
intptr_t tid;
tid = rdint(fd);
if (tid & Builtinmask) {
*dest = mktype(-1, tid & ~Builtinmask);
} else {
lappend(&typefixdest, &ntypefixdest, dest);
lappend(&typefixid, &ntypefixid, itop(tid));
}
}
/* Writes types to a file. Errors on
* internal only types like Tyvar that
* will not be meaningful in another file */
static Type *tyunpickle(FILE *fd)
{
size_t i, n;
size_t v;
Type *ty;
Trait *tr;
Ty t;
t = rdbyte(fd);
ty = mktype(-1, t);
if (rdbyte(fd) == Vishidden)
ty->ishidden = 1;
/* tid is generated; don't write */
n = rdint(fd);
if (n > 0) {
ty->traits = mkbs();
for (i = 0; i < n; i++) {
v = rdint(fd);
tr = htget(trmap, itop(v));
settrait(ty, tr);
}
}
ty->nsub = rdint(fd);
if (ty->nsub > 0)
ty->sub = zalloc(ty->nsub * sizeof(Type*));
switch (ty->type) {
case Tyunres:
ty->name = unpickle(fd);
break;
case Typaram:
ty->pname = rdstr(fd);
break;
case Tystruct:
ty->nmemb = rdint(fd);
ty->sdecls = zalloc(ty->nmemb * sizeof(Node*));
for (i = 0; i < ty->nmemb; i++)
ty->sdecls[i] = unpickle(fd);
break;
case Tyunion:
ty->nmemb = rdint(fd);
ty->udecls = zalloc(ty->nmemb * sizeof(Node*));
for (i = 0; i < ty->nmemb; i++)
ty->udecls[i] = rducon(fd, ty);
break;
case Tyarray:
rdtype(fd, &ty->sub[0]);
ty->asize = unpickle(fd);
break;
case Tyslice:
rdtype(fd, &ty->sub[0]);
break;
case Tyname:
ty->name = unpickle(fd);
ty->issynth = rdbool(fd);
ty->nparam = rdint(fd);
ty->param = zalloc(ty->nparam * sizeof(Type *));
for (i = 0; i < ty->nparam; i++)
rdtype(fd, &ty->param[i]);
ty->narg = rdint(fd);
ty->arg = zalloc(ty->narg * sizeof(Type *));
for (i = 0; i < ty->narg; i++)
rdtype(fd, &ty->arg[i]);
rdtype(fd, &ty->sub[0]);
break;
default:
for (i = 0; i < ty->nsub; i++)
rdtype(fd, &ty->sub[i]);
break;
}
return ty;
}
Trait *traitunpickle(FILE *fd)
{
Trait *tr;
size_t i, n;
intptr_t uid;
/* create an empty trait */
tr = mktrait(-1, NULL, NULL, NULL, 0, NULL, 0, 0);
uid = rdint(fd);
tr->ishidden = rdbool(fd);
tr->name = unpickle(fd);
tr->param = tyunpickle(fd);
n = rdint(fd);
for (i = 0; i < n; i++)
lappend(&tr->memb, &tr->nmemb, rdsym(fd, tr));
n = rdint(fd);
for (i = 0; i < n; i++)
lappend(&tr->funcs, &tr->nfuncs, rdsym(fd, tr));
htput(trmap, itop(uid), tr);
return tr;
}
/* Pickles a node to a file. The format
* is more or less equivalen to to
* simplest serialization of the
* in-memory representation. Minimal
* checking is done, so a bad type can
* crash the compiler */
static void pickle(FILE *fd, Node *n)
{
size_t i;
if (!n) {
wrbyte(fd, Nnone);
return;
}
wrbyte(fd, n->type);
wrint(fd, n->line);
switch (n->type) {
case Nfile:
wrstr(fd, n->file.name);
wrint(fd, n->file.nuses);
for (i = 0; i < n->file.nuses; i++)
pickle(fd, n->file.uses[i]);
wrint(fd, n->file.nstmts);
for (i = 0; i < n->file.nstmts; i++)
pickle(fd, n->file.stmts[i]);
wrstab(fd, n->file.globls);
wrstab(fd, n->file.exports);
break;
case Nexpr:
wrbyte(fd, n->expr.op);
wrtype(fd, n->expr.type);
wrbool(fd, n->expr.isconst);
pickle(fd, n->expr.idx);
wrint(fd, n->expr.nargs);
for (i = 0; i < n->expr.nargs; i++)
pickle(fd, n->expr.args[i]);
break;
case Nname:
wrbool(fd, n->name.ns != NULL);
if (n->name.ns) {
wrstr(fd, n->name.ns);
}
wrstr(fd, n->name.name);
break;
case Nuse:
wrbool(fd, n->use.islocal);
wrstr(fd, n->use.name);
break;
case Nlit:
wrbyte(fd, n->lit.littype);
wrtype(fd, n->lit.type);
wrint(fd, n->lit.nelt);
switch (n->lit.littype) {
case Lchr: wrint(fd, n->lit.chrval); break;
case Lint: wrint(fd, n->lit.intval); break;
case Lflt: wrflt(fd, n->lit.fltval); break;
case Lstr: wrstr(fd, n->lit.strval); break;
case Llbl: wrstr(fd, n->lit.lblval); break;
case Lbool: wrbool(fd, n->lit.boolval); break;
case Lfunc: pickle(fd, n->lit.fnval); break;
}
break;
case Nloopstmt:
pickle(fd, n->loopstmt.init);
pickle(fd, n->loopstmt.cond);
pickle(fd, n->loopstmt.step);
pickle(fd, n->loopstmt.body);
break;
case Niterstmt:
pickle(fd, n->iterstmt.elt);
pickle(fd, n->iterstmt.seq);
pickle(fd, n->iterstmt.body);
break;
case Nmatchstmt:
pickle(fd, n->matchstmt.val);
wrint(fd, n->matchstmt.nmatches);
for (i = 0; i < n->matchstmt.nmatches; i++)
pickle(fd, n->matchstmt.matches[i]);
break;
case Nmatch:
pickle(fd, n->match.pat);
pickle(fd, n->match.block);
break;
case Nifstmt:
pickle(fd, n->ifstmt.cond);
pickle(fd, n->ifstmt.iftrue);
pickle(fd, n->ifstmt.iffalse);
break;
case Nblock:
wrstab(fd, n->block.scope);
wrint(fd, n->block.nstmts);
for (i = 0; i < n->block.nstmts; i++)
pickle(fd, n->block.stmts[i]);
break;
case Ndecl:
/* sym */
pickle(fd, n->decl.name);
wrtype(fd, n->decl.type);
/* symflags */
wrint(fd, n->decl.isconst);
wrint(fd, n->decl.isgeneric);
wrint(fd, n->decl.isextern);
/* init */
pickle(fd, n->decl.init);
break;
case Nfunc:
wrtype(fd, n->func.type);
wrstab(fd, n->func.scope);
wrint(fd, n->func.nargs);
for (i = 0; i < n->func.nargs; i++)
pickle(fd, n->func.args[i]);
pickle(fd, n->func.body);
break;
case Nimpl:
pickle(fd, n->impl.traitname);
wrint(fd, n->impl.trait->uid);
wrtype(fd, n->impl.type);
wrint(fd, n->impl.ndecls);
for (i = 0; i < n->impl.ndecls; i++)
wrsym(fd, n->impl.decls[i]);
break;
case Nnone:
die("Nnone should not be seen as node type!");
break;
}
}
/* Unpickles a node from a file. Minimal checking
* is done. Specifically, no checks are done for
* sane arities, a bad file can crash the compiler */
static Node *unpickle(FILE *fd)
{
size_t i;
Ntype type;
Node *n;
type = rdbyte(fd);
if (type == Nnone)
return NULL;
n = mknode(-1, type);
n->line = rdint(fd);
switch (n->type) {
case Nfile:
n->file.name = rdstr(fd);
n->file.nuses = rdint(fd);
n->file.uses = zalloc(sizeof(Node*)*n->file.nuses);
for (i = 0; i < n->file.nuses; i++)
n->file.uses[i] = unpickle(fd);
n->file.nstmts = rdint(fd);
n->file.stmts = zalloc(sizeof(Node*)*n->file.nstmts);
for (i = 0; i < n->file.nstmts; i++)
n->file.stmts[i] = unpickle(fd);
n->file.globls = rdstab(fd);
n->file.exports = rdstab(fd);
break;
case Nexpr:
n->expr.op = rdbyte(fd);
rdtype(fd, &n->expr.type);
n->expr.isconst = rdbool(fd);
n->expr.idx = unpickle(fd);
n->expr.nargs = rdint(fd);
n->expr.args = zalloc(sizeof(Node *)*n->expr.nargs);
for (i = 0; i < n->expr.nargs; i++)
n->expr.args[i] = unpickle(fd);
break;
case Nname:
if (rdbool(fd))
n->name.ns = rdstr(fd);
n->name.name = rdstr(fd);
break;
case Nuse:
n->use.islocal = rdbool(fd);
n->use.name = rdstr(fd);
break;
case Nlit:
n->lit.littype = rdbyte(fd);
rdtype(fd, &n->lit.type);
n->lit.nelt = rdint(fd);
switch (n->lit.littype) {
case Lchr: n->lit.chrval = rdint(fd); break;
case Lint: n->lit.intval = rdint(fd); break;
case Lflt: n->lit.fltval = rdflt(fd); break;
case Lstr: n->lit.strval = rdstr(fd); break;
case Llbl: n->lit.lblval = rdstr(fd); break;
case Lbool: n->lit.boolval = rdbool(fd); break;
case Lfunc: n->lit.fnval = unpickle(fd); break;
}
break;
case Nloopstmt:
n->loopstmt.init = unpickle(fd);
n->loopstmt.cond = unpickle(fd);
n->loopstmt.step = unpickle(fd);
n->loopstmt.body = unpickle(fd);
break;
case Niterstmt:
n->iterstmt.elt = unpickle(fd);
n->iterstmt.seq = unpickle(fd);
n->iterstmt.body = unpickle(fd);
break;
case Nmatchstmt:
n->matchstmt.val = unpickle(fd);
n->matchstmt.nmatches = rdint(fd);
n->matchstmt.matches = zalloc(sizeof(Node *)*n->matchstmt.nmatches);
for (i = 0; i < n->matchstmt.nmatches; i++)
n->matchstmt.matches[i] = unpickle(fd);
break;
case Nmatch:
n->match.pat = unpickle(fd);
n->match.block = unpickle(fd);
break;
case Nifstmt:
n->ifstmt.cond = unpickle(fd);
n->ifstmt.iftrue = unpickle(fd);
n->ifstmt.iffalse = unpickle(fd);
break;
case Nblock:
n->block.scope = rdstab(fd);
n->block.nstmts = rdint(fd);
n->block.stmts = zalloc(sizeof(Node *)*n->block.nstmts);
n->block.scope->super = curstab();
pushstab(n->func.scope->super);
for (i = 0; i < n->block.nstmts; i++)
n->block.stmts[i] = unpickle(fd);
popstab();
break;
case Ndecl:
n->decl.did = ndecls; /* unique within file */
/* sym */
n->decl.name = unpickle(fd);
rdtype(fd, &n->decl.type);
/* symflags */
n->decl.isconst = rdint(fd);
n->decl.isgeneric = rdint(fd);
n->decl.isextern = rdint(fd);
/* init */
n->decl.init = unpickle(fd);
lappend(&decls, &ndecls, n);
break;
case Nfunc:
rdtype(fd, &n->func.type);
n->func.scope = rdstab(fd);
n->func.nargs = rdint(fd);
n->func.args = zalloc(sizeof(Node *)*n->func.nargs);
n->func.scope->super = curstab();
pushstab(n->func.scope->super);
for (i = 0; i < n->func.nargs; i++)
n->func.args[i] = unpickle(fd);
n->func.body = unpickle(fd);
popstab();
break;
case Nimpl:
n->impl.traitname = unpickle(fd);
i = rdint(fd);
n->impl.trait = htget(trmap, itop(i));
rdtype(fd, &n->impl.type);
n->impl.ndecls = rdint(fd);
n->impl.decls = zalloc(sizeof(Node *)*n->impl.ndecls);
for (i = 0; i < n->impl.ndecls; i++)
n->impl.decls[i] = rdsym(fd, n->impl.trait);
break;
case Nnone:
die("Nnone should not be seen as node type!");
break;
}
return n;
}
static Stab *findstab(Stab *st, char *pkg)
{
Node *n;
Stab *s;
if (!pkg) {
if (!st->name)
return st;
else
return NULL;
}
n = mkname(-1, pkg);
if (getns(st, n)) {
s = getns(st, n);
} else {
s = mkstab();
s->name = n;
putns(st, s);
}
return s;
}
static void fixmappings(Stab *st)
{
size_t i;
Type *t, *old;
/*
* merge duplicate definitions.
* This allows us to compare named types by id, instead
* of doing a deep walk through the type. This ability is
* depended on when we do type inference.
*/
for (i = 0; i < ntypefixdest; i++) {
t = htget(tidmap, itop(typefixid[i]));
if (!t)
die("Unable to find type for id %zd\n", i);
if (t->type == Tyname && !t->issynth) {
old = htget(tydedup, t->name);
if (old != t)
if (t != old)
t = old;
}
*typefixdest[i] = t;
if (!*typefixdest[i])
die("Couldn't find type %zd\n", typefixid[i]);
}
/* check for duplicate type definitions */
for (i = 0; i < ntypefixdest; i++) {
t = htget(tidmap, itop(typefixid[i]));
if (t->type != Tyname || t->issynth)
continue;
old = htget(tydedup, t->name);
if (old && !tyeq(t, old))
fatal(-1, "Duplicate definition of type %s", tystr(old));
}
lfree(&typefixdest, &ntypefixdest);
lfree(&typefixid, &ntypefixid);
}
/* Usefile format:
* U<pkgname>
* T<pickled-type>
* R<picled-trait>
* I<pickled-impl>
* D<picled-decl>
* G<pickled-decl><pickled-initializer>
*/
int loaduse(FILE *f, Stab *st)
{
intptr_t tid;
size_t i;
char *pkg;
Node *dcl, *impl;
Stab *s;
Type *ty;
Trait *tr;
char *lib;
int c;
pushstab(file->file.globls);
if (!tydedup)
tydedup = mkht(namehash, nameeq);
if (fgetc(f) != 'U')
return 0;
pkg = rdstr(f);
/* if the package names match up, or the usefile has no declared
* package, then we simply add to the current stab. Otherwise,
* we add a new stab under the current one */
if (st->name) {
if (pkg && !strcmp(pkg, namestr(st->name))) {
s = st;
} else {
s = findstab(st, pkg);
}
} else {
if (pkg) {
s = findstab(st, pkg);
} else {
s = st;
}
}
tidmap = mkht(ptrhash, ptreq);
trmap = mkht(ptrhash, ptreq);
/* builtin traits */
for (i = 0; i < Ntraits; i++)
htput(trmap, itop(i), traittab[i]);
while ((c = fgetc(f)) != EOF) {
switch(c) {
case 'L':
lib = rdstr(f);
for (i = 0; i < file->file.nlibdeps; i++)
if (!strcmp(file->file.libdeps[i], lib))
/* break out of both loop and switch */
goto foundlib;
lappend(&file->file.libdeps, &file->file.nlibdeps, lib);
foundlib:
break;
case 'G':
case 'D':
dcl = rdsym(f, NULL);
putdcl(s, dcl);
break;
case 'R':
tr = traitunpickle(f);
puttrait(s, tr->name, tr);
for (i = 0; i < tr->nfuncs; i++)
putdcl(s, tr->funcs[i]);
break;
case 'T':
tid = rdint(f);
ty = tyunpickle(f);
htput(tidmap, itop(tid), ty);
/* fix up types */
if (ty->type == Tyname) {
if (ty->issynth)
break;
if (!gettype(st, ty->name) && !ty->ishidden)
puttype(s, ty->name, ty);
if (!hthas(tydedup, ty->name))
htput(tydedup, ty->name, ty);
} else if (ty->type == Tyunion) {
for (i = 0; i < ty->nmemb; i++)
if (!getucon(s, ty->udecls[i]->name) && !ty->udecls[i]->synth)
putucon(s, ty->udecls[i]);
}
break;
case 'I':
impl = unpickle(f);
putimpl(s, impl);
/* specialized declarations always go into the global stab */
for (i = 0; i < impl->impl.ndecls; i++)
putdcl(file->file.globls, impl->impl.decls[i]);
break;
case EOF:
break;
}
}
fixmappings(s);
htfree(tidmap);
popstab();
return 1;
}
void readuse(Node *use, Stab *st)
{
size_t i;
FILE *fd;
char *p, *q;
/* local (quoted) uses are always relative to the cwd */
fd = NULL;
if (use->use.islocal) {
fd = fopen(use->use.name, "r");
/* nonlocal (barename) uses are always searched on the include path */
} else {
for (i = 0; i < nincpaths; i++) {
p = strjoin(incpaths[i], "/");
q = strjoin(p, use->use.name);
fd = fopen(q, "r");
if (fd) {
free(p);
free(q);
break;
}
}
}
if (!fd)
fatal(use->line, "Could not open %s", use->use.name);
if (!loaduse(fd, st))
die("Could not load usefile %s", use->use.name);
}
/* Usefile format:
* U<pkgname>
* T<pickled-type>
* D<picled-decl>
* G<pickled-decl><pickled-initializer>
* Z
*/
void writeuse(FILE *f, Node *file)
{
Stab *st;
void **k;
Node *s, *u;
size_t i, n;
assert(file->type == Nfile);
st = file->file.exports;
/* usefile name */
wrbyte(f, 'U');
if (st->name)
wrstr(f, namestr(st->name));
else
wrstr(f, NULL);
/* library deps */
for (i = 0; i < file->file.nuses; i++) {
u = file->file.uses[i];
if (!u->use.islocal) {
wrbyte(f, 'L');
wrstr(f, u->use.name);
}
}
for (i = 0; i < file->file.nlibdeps; i++) {
wrbyte(f, 'L');
wrstr(f, file->file.libdeps[i]);
}
for (i = 0; i < ntypes; i++) {
if (types[i]->vis == Visexport || types[i]->vis == Vishidden) {
wrbyte(f, 'T');
wrint(f, types[i]->tid);
typickle(f, types[i]);
}
}
for (i = 0; i < ntraittab; i++) {
if (traittab[i]->vis == Visexport || traittab[i]->vis == Vishidden) {
wrbyte(f, 'R');
traitpickle(f, traittab[i]);
}
}
for (i = 0; i < nexportimpls; i++) {
/* merging during inference should remove all protos */
assert(!exportimpls[i]->impl.isproto);
if (exportimpls[i]->impl.vis == Visexport || exportimpls[i]->impl.vis == Vishidden) {
wrbyte(f, 'I');
pickle(f, exportimpls[i]);
}
}
k = htkeys(st->dcl, &n);
for (i = 0; i < n; i++) {
s = getdcl(st, k[i]);
/* trait functions get written out with their traits */
if (s->decl.trait)
continue;
if (s && s->decl.isgeneric)
wrbyte(f, 'G');
else
wrbyte(f, 'D');
wrsym(f, s);
}
free(k);
}
|
C | /**
* @file fun.h
* @author 311305
* @ Cryptography Encryption Algorithms
*/
#ifndef __FUN_H
#define __FUN_H
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<ctype.h>
/*function prototypes for all functions*/
/**
* Perform ceaser encryption algorithm
* @param[in] value1
* @param[in] value2
* @param[out] value3
* @return Result of value3
*/
char ceaser(char *string, int n, char *encrypted_msg);
/*function prototypes for all functions*/
/**
* Perform vernem encryption algorithm
* @param[in] value1
* @param[in] value2
* @param[out] value3
* @return Result of value3
*/
char vernem(char *str, char *key, char *encrypted_msg);
/*function prototypes for all functions*/
/**
* Perform ceaser encryption algorithm
* @param[in] value1
* @param[in] value2
* @param[out] value3
* @param[out] value4
* @return Result of value3
*/
char vignere(char *message, char *key, char *temp_key, char *encrypted_message);
#endif /* #define __Cryptography_Encryption_Algorithms_H__ */ |
C | #include <stdio.h>
#include <math.h>
#include <complex.h>
#define E 2.71828
int main()
{
char inflexao = 0;
double complex z;
double y;
puts("Os valores (pontos) da funcao sao:");
for (int x = -10; x <= 10; x++)
{
z = cpow(x, E);
y = cabs(z);
if (creal(z) < 0)
y *= -1;
if (!inflexao && cimag(z) == 0)
{
inflexao++;
printf("Ponto de inflexao: ");
}
printf("(%d, %g)\n", x, y);
}
return 0;
}
|
C | #include "Tmisc.h"
// --------------------------------------- MATRIX OPERATIONS FUNCTIONS ---------------------------------------------- //
/* Function for matrix multiplications: matrixA with mxn dimension, matrixB with pxq dimension */
void multiply_matrix( int m, int n, int p, int q, float mA[m][n], float mB[p][q], float mR[m][q])
{
int i = 0;
int j = 0;
int k = 0;
float sum = 0.0;
for ( i=0; i<m; i++ ){
for ( j=0; j<q; j++ ){
for ( k=0; k<p; k++ ){
sum = sum + ( mA[i][k] * mB[k][j] );
}
mR[i][j] = sum;
sum = 0.0; // --> restart the addition counter for a column change
}
}
}
/* Function for matrix addition */
void add_matrix( int m, int n, float mA[m][n], float mB[m][n], float mR[m][n])
{
int i = 0;
int j = 0;
for ( i=0; i<m; i++ ){
for ( j=0; j<n; j++ ){
mR[i][j] = mA[i][j] + mB[i][j];
}
}
}
/* Function for matrix subtraction */
void sub_matrix( int m, int n, float mA[m][n], float mB[m][n], float mR[m][n])
{
int i = 0;
int j = 0;
for ( i=0; i<m; i++ ){
for ( j=0; j<n; j++ ){
mR[i][j] = mA[i][j] - mB[i][j];
}
}
}
/* Set array values */
void set_matrix( int m, int n, float mS[m][n], float set_value)
{
int i = 0;
int j = 0;
for ( i=0; i<m; i++ ){
for ( j=0; j<n; j++ ){
mS[i][j] = set_value;
}
}
}
|
C | #include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <assert.h>
#include <limits.h>
typedef struct Node {
int val;
struct Node* left;
struct Node* right;
} node;
node* newNode(int val);
void insert*(node** root, int val);
void countNode(node* root);
void inorderPrint(node* root);
void preorderPrint(node* root);
void postorderPrint(node* root);
void morrisPrint(node* root);
void getHeight(node* root);
void deleteTree(node* root);
bool find(node* root, int val);
int getHeight(node* root);
int minNode(node* root);
int maxNode(node* root);
bool isBst(node* root);
void delete(node **root, int item);
node* getNode(Node* root, int item);
node* getSuccessor(node* root, int data); |
C | #include <string.h>
#include <stdlib.h>
#include "interpreter.h"
#include "common.h"
#include "opcodes.h"
#include "typesys.h"
struct ts_TYPE_REGISTRY {
char* name;
struct ts_TYPE* type;
struct ts_TYPE_REGISTRY* next;
};
static struct ts_TYPE_REGISTRY* global_registry = NULL;
static uint32_t type_id = 3;
void ts_init_global_registry() {
// Create and initialize an int type
global_registry = mm_malloc(sizeof(struct ts_TYPE_REGISTRY));
global_registry->name = strdup("int");
global_registry->type = mm_malloc(sizeof(struct ts_TYPE));
struct ts_TYPE* int_type = global_registry->type;
int_type->id = 0;
int_type->name = strdup("int");
int_type->heirarchy_len = 1;
int_type->heirarchy = mm_malloc(sizeof(struct ts_TYPE*));
int_type->heirarchy[0] = int_type;
int_type->category = ts_CATEGORY_PRIMITIVE;
// Create and initialize a bool type
global_registry->next = mm_malloc(sizeof(struct ts_TYPE_REGISTRY));
global_registry->next->next = NULL;
global_registry->next->name = strdup("bool");
global_registry->next->type = mm_malloc(sizeof(struct ts_TYPE));
struct ts_TYPE* bool_type = global_registry->next->type;
bool_type->id = 1;
bool_type->name = strdup("bool");
bool_type->heirarchy_len = 1;
bool_type->heirarchy = mm_malloc(sizeof(struct ts_TYPE*));
bool_type->heirarchy[0] = bool_type;
bool_type->category = ts_CATEGORY_PRIMITIVE;
global_registry->next->next = mm_malloc(sizeof(struct ts_TYPE_REGISTRY));
global_registry->next->next->next = NULL;
global_registry->next->next->name = strdup("void");
global_registry->next->next->type = mm_malloc(sizeof(struct ts_TYPE));
struct ts_TYPE* void_type = global_registry->next->next->type;
void_type->id = 2;
bool_type->name = strdup("bool");
void_type->heirarchy_len = 1;
void_type->heirarchy = mm_malloc(sizeof(struct ts_TYPE*));
void_type->heirarchy[0] = void_type;
void_type->category = ts_CATEGORY_PRIMITIVE;
}
uint32_t ts_allocate_type_id() {
return type_id++;
}
uint32_t ts_get_largest_type_id() {
// This is only used (at least as of yet) in cl_arrange_method_tables_inner.
return type_id;
}
void ts_register_type(struct ts_TYPE* type, char* name) {
// CONTRACT: name must be immutable
if(global_registry == NULL) {
ts_init_global_registry();
}
struct ts_TYPE_REGISTRY* end = global_registry;
while(end->next != NULL) {
end = end->next;
}
end->next = mm_malloc(sizeof(struct ts_TYPE_REGISTRY));
end->next->name = name;
end->next->type = type;
end->next->next = NULL;
}
bool ts_is_subcontext(struct ts_GENERIC_TYPE_CONTEXT* child, struct ts_GENERIC_TYPE_CONTEXT* parent) {
if(child == parent) {
return true;
}
if(child->parent != NULL && ts_is_subcontext(child->parent, parent)) {
return true;
}
return false;
}
bool ts_is_from_context(struct ts_TYPE* type, struct ts_GENERIC_TYPE_CONTEXT* context) {
if(type->category == ts_CATEGORY_TYPE_PARAMETER) {
return ts_is_subcontext(context, type->data.type_parameter.context);
} else if(type->category == ts_CATEGORY_ARRAY) {
return ts_is_from_context(type->data.array.parent_type, context);
}
return true;
}
struct ts_TYPE* ts_get_type_by_id_optional(int id) {
struct ts_TYPE_REGISTRY* registry = global_registry;
while(registry != NULL) {
if(registry->type->id == id) {
return registry->type;
}
registry = registry->next;
}
return NULL;
}
struct ts_TYPE* ts_get_type_inner(char* name, struct ts_GENERIC_TYPE_CONTEXT* context) {
#if DEBUG
printf("Searching for type '%s'\n", name);
#endif
if(global_registry == NULL) {
ts_init_global_registry();
}
struct ts_TYPE_REGISTRY* registry = global_registry;
while(registry != NULL) {
if(strcmp(registry->name, name) == 0) {
if(ts_is_from_context(registry->type, context)) {
return registry->type;
}
}
registry = registry->next;
}
return NULL;
}
struct ts_TYPE* ts_create_array_type(struct ts_TYPE* parent_type) {
if(global_registry == NULL) {
ts_init_global_registry();
}
struct ts_TYPE* result = mm_malloc(sizeof(struct ts_TYPE));
result->category = ts_CATEGORY_ARRAY;
result->id = ts_allocate_type_id();
size_t parent_name_length = strlen(parent_type->name);
result->name = mm_malloc(sizeof(char) * (parent_name_length + 3));
sprintf(result->name, "[%s]", parent_type->name);
ts_register_type(result, result->name);
result->heirarchy_len = 1;
result->heirarchy = mm_malloc(sizeof(struct ts_TYPE*) * 1);
result->heirarchy[0] = result;
result->data.array.parent_type = parent_type;
ts_register_type(result, result->name);
return result;
}
struct ts_TYPE* ts_get_or_create_array_type(struct ts_TYPE* parent_type) {
if(global_registry == NULL) {
ts_init_global_registry();
}
struct ts_TYPE_REGISTRY* registry = global_registry;
while(registry != NULL) {
if(registry->type->category != ts_CATEGORY_ARRAY) {
registry = registry->next;
continue;
}
if(registry->type->data.array.parent_type->id == parent_type->id) {
return registry->type;
}
registry = registry->next;
}
return ts_create_array_type(parent_type);
}
struct ts_TYPE* ts_search_generic_type_context_optional(char* name, struct ts_GENERIC_TYPE_CONTEXT* context) {
if(context == NULL) {
return NULL;
}
for(int i = 0; i < context->count; i++) {
if(strcmp(context->arguments[i]->name, name) == 0 && ts_is_from_context(context->arguments[i], context)) {
return context->arguments[i];
}
}
if(context->parent != NULL) {
return ts_search_generic_type_context_optional(name, context->parent);
}
return NULL;
}
struct ts_TYPE* ts_parse_and_get_type(char* name, struct ts_GENERIC_TYPE_CONTEXT* context, int* const index) {
// This is an internal function only called recursively and by ts_get_type_optional.
// It implements a simple recursive descent parser to parse type names.
// Mixed in here is some logic around actually creating the types. This is
// kind of unclean.
const int identifier_start_index = *index;
if(name[*index] == '[') {
(*index)++;
struct ts_TYPE* member_type = ts_parse_and_get_type(name, context, index);
if(name[(*index)++] != ']') {
printf("Index: %d, type: '%s': expected ']'", *index, name);
fatal("Expected ']'");
}
return ts_get_or_create_array_type(member_type);
}
while(name[*index] != 0) {
if(name[*index] == ' ') {
// This isn't perfect, but the compiler doesn't ever emit
// whitespace anyway.
(*index)++;
continue;
}
if(name[*index] == ',' || name[*index] == ']' || name[*index] == '>') {
break;
}
if(name[*index] == '<') {
int raw_type_start_index = identifier_start_index;
// So that the recursive call to ts_parse_and_get_type sees that the string ends at *index
name[*index] = '\0';
struct ts_TYPE* raw_type = ts_parse_and_get_type(name, context, &raw_type_start_index);
if(raw_type == NULL) {
return NULL;
}
if(raw_type->category != ts_CATEGORY_CLAZZ) {
fatal("Attempt to specialize something that isn't a class");
}
name[*index] = '<';
(*index)++;
int type_arguments_index = 0;
int type_arguments_size = 1;
struct ts_TYPE** type_arguments = mm_malloc(sizeof(struct ts_TYPE*) * type_arguments_size);
while(true) {
struct ts_TYPE* argument_type = ts_parse_and_get_type(name, context, index);
if(argument_type == NULL) {
return NULL;
}
if(type_arguments_index >= type_arguments_size) {
type_arguments_size *= 2;
type_arguments = realloc(type_arguments, sizeof(struct ts_TYPE*) * type_arguments_size);
}
type_arguments[type_arguments_index++] = argument_type;
if(argument_type == NULL) {
return NULL;
}
if(name[*index] == ',') {
(*index)++;
} else if(name[*index] == '>') {
(*index)++;
if(raw_type->data.clazz.type_parameters->count == 0) {
fatal("Parameterizing non-generic type");
}
struct ts_TYPE* ret = cl_specialize_class(raw_type, ts_create_type_arguments(raw_type->data.clazz.type_parameters, type_arguments_index, type_arguments));
free(type_arguments);
return ret;
} else {
printf("Index: %d, character: '%c'\n", *index, name[*index]);
fatal("Expected ',' or '>'");
}
}
// Unreachable
}
(*index)++;
}
char* type_name = mm_malloc(sizeof(char) * ((*index) - identifier_start_index + 1));
type_name[(*index) - identifier_start_index] = 0;
memcpy(type_name, name + identifier_start_index, (*index) - identifier_start_index);
struct ts_TYPE* ret = NULL;
if(context != NULL) {
ret = ts_search_generic_type_context_optional(type_name, context);
}
if(ret == NULL) {
ret = ts_get_type_inner(type_name, context);
}
memset(type_name, 0, *index - identifier_start_index + 1);
free(type_name);
return ret;
}
struct ts_GENERIC_TYPE_CONTEXT* ts_get_method_type_context(struct it_METHOD* method) {
if(method->containing_clazz != NULL) {
if(ts_method_is_generic(method)) {
fatal("Generic method is a class member");
}
return method->containing_clazz->data.clazz.type_parameters;
}
return method->type_parameters;
}
struct ts_TYPE* ts_get_type_optional(char* name, struct ts_GENERIC_TYPE_CONTEXT* context) {
if(global_registry == NULL) {
ts_init_global_registry();
}
int index = 0;
// ts_parse_and_get_type can temporarily modify its input, and we don't
// know that the memory pointed to by name is mutable.
char name_copy[strlen(name) + 1];
name_copy[strlen(name)] = '\0';
strcpy(name_copy, name);
return ts_parse_and_get_type(name_copy, context, &index);
}
struct ts_TYPE* ts_get_type(char* name, struct ts_GENERIC_TYPE_CONTEXT* context) {
if(global_registry == NULL) {
ts_init_global_registry();
}
struct ts_TYPE* result = ts_get_type_optional(name, context);
if(result == NULL) {
printf("Tried to find type: '%s'\n", name);
fatal("Cannot find type");
}
return result;
}
bool ts_is_compatible(struct ts_TYPE* type1, struct ts_TYPE* type2) {
if(global_registry == NULL) {
ts_init_global_registry();
}
if(type1->category == ts_CATEGORY_INTERFACE) {
return type1 == type2;
}
if(type2->category == ts_CATEGORY_INTERFACE) {
if(type1->category != ts_CATEGORY_CLAZZ) {
return false;
}
return cl_class_implements_interface(type1, type2);
}
int min_heirarchy_len = type1->heirarchy_len;
if(type2->heirarchy_len < min_heirarchy_len) {
min_heirarchy_len = type2->heirarchy_len;
}
return type1->heirarchy[min_heirarchy_len] == type2->heirarchy[min_heirarchy_len];
}
bool ts_instanceof(struct ts_TYPE* lhs, struct ts_TYPE* rhs) {
if(global_registry == NULL) {
ts_init_global_registry();
}
// Test if lhs instanceof rhs
#if DEBUG
printf("Asked if %s instanceof %s\n", lhs->name, rhs->name);
#endif
if(lhs->category == ts_CATEGORY_ARRAY) {
if(rhs->category != ts_CATEGORY_ARRAY) {
return false;
}
// There's only ever one instance of an array type, so this is correct
return lhs == rhs;
}
if(rhs->category == ts_CATEGORY_INTERFACE) {
if(lhs->category != ts_CATEGORY_CLAZZ) {
return false;
}
return cl_class_implements_interface(lhs, rhs);
}
if(lhs->heirarchy_len < rhs->heirarchy_len) {
return false;
}
#if DEBUG
printf("rhs->heirarchy_len: %d\n", rhs->heirarchy_len);
printf("Types: %s and %s\n", lhs->heirarchy[rhs->heirarchy_len - 1]->name, rhs->heirarchy[rhs->heirarchy_len - 1]->name);
#endif
return lhs->heirarchy[rhs->heirarchy_len - 1] == rhs->heirarchy[rhs->heirarchy_len - 1];
}
struct ts_GENERIC_TYPE_CONTEXT* ts_create_generic_type_context(uint32_t num_arguments, struct ts_GENERIC_TYPE_CONTEXT* parent) {
struct ts_GENERIC_TYPE_CONTEXT* context = mm_malloc(sizeof(struct ts_GENERIC_TYPE_CONTEXT) + sizeof(struct ts_TYPE*) * num_arguments);
context->count = num_arguments;
context->parent = NULL;
return context;
}
struct ts_TYPE* ts_allocate_type_parameter(char* name, struct ts_GENERIC_TYPE_CONTEXT* context, struct ts_TYPE* extends, int implementsc, struct ts_TYPE** implements) {
struct ts_TYPE* parameter = mm_malloc(sizeof(struct ts_TYPE));
parameter->category = ts_CATEGORY_TYPE_PARAMETER;
parameter->heirarchy = mm_malloc(sizeof(struct ts_TYPE*));
parameter->heirarchy[0] = parameter;
parameter->heirarchy_len = 1;
parameter->id = ts_allocate_type_id();
parameter->name = name;
parameter->data.type_parameter.context = context;
parameter->data.type_parameter.extends = extends;
parameter->data.type_parameter.implementsc = implementsc;
parameter->data.type_parameter.implements = mm_malloc(sizeof(struct ts_TYPE*) * implementsc);
memcpy(parameter->data.type_parameter.implements, implements, sizeof(struct ts_TYPE*) * implementsc);
return parameter;
}
bool ts_method_is_generic(struct it_METHOD* method) {
return method->type_parameters->count > 0;
}
bool ts_class_is_specialization(struct ts_TYPE* type) {
if(type->category != ts_CATEGORY_CLAZZ) {
fatal("Argument to ts_class_is_specialization isn't a class");
}
return type->data.clazz.specialized_from != type;
}
bool ts_class_is_generic(struct ts_TYPE* type) {
if(type->category != ts_CATEGORY_CLAZZ) {
fatal("Argument to ts_class_is_generic isn't a class");
}
return type->data.clazz.type_parameters->count > 0;
}
bool ts_clazz_is_raw(struct ts_TYPE* type) {
return ts_class_is_generic(type) && !ts_class_is_specialization(type);
}
struct ts_TYPE_ARGUMENTS* ts_create_type_arguments(struct ts_GENERIC_TYPE_CONTEXT* context, int typeargsc, struct ts_TYPE** typeargs) {
if(typeargsc != context->count) {
fatal("ts_create_type_arguments: typeargsc != context->count");
}
struct ts_TYPE_ARGUMENTS* result = mm_malloc(sizeof(struct ts_TYPE_ARGUMENTS) + sizeof(result->mapping[0]) * typeargsc);
result->context = context;
for(int i = 0; i < typeargsc; i++) {
result->mapping[i].key = context->arguments[i];
result->mapping[i].value = typeargs[i];
}
return result;
}
struct ts_TYPE_ARGUMENTS* ts_compose_type_arguments(struct ts_TYPE_ARGUMENTS* first, struct ts_TYPE_ARGUMENTS* second) {
if(first == NULL) {
return second;
}
if(second == NULL) {
return first;
}
if(first->context->parent != NULL || second->context->parent != NULL) {
fatal("Composing type arguments whose contexts have parents isn't supported");
}
// Some explanation for this in GenericTypeParameters.compose in typesys.py.
uint32_t new_count = first->context->count + second->context->count;
struct ts_GENERIC_TYPE_CONTEXT* new_context = mm_malloc(sizeof(struct ts_GENERIC_TYPE_CONTEXT) + sizeof(struct ts_TYPE*) * new_count);
new_context->parent = NULL;
new_context->count = new_count;
memcpy(new_context->arguments, first->context->arguments, sizeof(struct ts_TYPE*) * first->context->count);
memcpy(new_context->arguments + first->context->count, second->context->arguments, sizeof(struct ts_TYPE*) * second->context->count);
struct ts_TYPE_ARGUMENTS* result = mm_malloc(sizeof(struct ts_TYPE_ARGUMENTS) + sizeof(result->mapping[0]) * new_count);
result->context = new_context;
for(int i = 0; i < first->context->count; i++) {
result->mapping[i].key = first[i].mapping[i].key;
result->mapping[i].value = ts_reify_type(first->mapping[i].value, second);
}
memcpy(result->mapping + first->context->count, second->mapping, sizeof(result->mapping[0]) * second->context->count);
return result;
}
bool ts_type_arguments_are_equivalent(struct ts_TYPE_ARGUMENTS* first, struct ts_TYPE_ARGUMENTS* second) {
// TODO: This is n^2
for(int i = 0; i < first->context->count; i++) {
bool foundIt = false;
for(int j = 0; j < second->context->count; j++) {
if(first->mapping[i].key == second->mapping[j].key) {
if(first->mapping[i].value == second->mapping[j].value) {
foundIt = true;
break;
}
return false;
}
}
if(!foundIt) {
return false;
}
}
return true;
}
struct ts_TYPE* ts_reify_type(struct ts_TYPE* type, struct ts_TYPE_ARGUMENTS* type_arguments) {
if(type->category == ts_CATEGORY_PRIMITIVE || type->category == ts_CATEGORY_INTERFACE) {
return type;
} else if(type->category == ts_CATEGORY_CLAZZ) {
if(!ts_class_is_generic(type)) {
return type;
}
if(ts_clazz_is_raw(type)) {
fatal("Cannot reify a raw type directly");
}
struct ts_TYPE_ARGUMENTS* new_arguments = ts_compose_type_arguments(type->data.clazz.type_arguments, type_arguments);
struct ts_TYPE* result = cl_specialize_class(type, new_arguments);
free(new_arguments);
return result;
} else if(type->category == ts_CATEGORY_ARRAY) {
struct ts_TYPE* reified = ts_reify_type(type->data.array.parent_type, type_arguments);
struct ts_TYPE* ret = ts_get_or_create_array_type(reified);
return ret;
} else if(type->category == ts_CATEGORY_TYPE_PARAMETER) {
for(int i = 0; i < type_arguments->context->count; i++) {
if(type_arguments->mapping[i].key == type) {
return type_arguments->mapping[i].value;
}
}
}
printf("Type: %s\n", type->name);
fatal("Failed to reify type");
return NULL; // Unreachable
}
void ts_update_method_reification(struct it_METHOD* specialization) {
struct ts_TYPE_ARGUMENTS* arguments = specialization->typeargs;
struct it_METHOD* generic_method = specialization->reified_from;
// TODO: Switch to using indirect method references like we do with type
// references (so we can use the same opcodes for every instance of a
// method)? Or is it necessary?
if(generic_method->opcodes != NULL && specialization->opcodes == NULL) {
specialization->opcodes = mm_malloc(sizeof(struct it_OPCODE) * generic_method->opcodec);
specialization->opcodec = generic_method->opcodec;
memcpy(specialization->opcodes, generic_method->opcodes, sizeof(struct it_OPCODE) * generic_method->opcodec);
}
if(generic_method->register_types != NULL && specialization->register_types == NULL) {
struct ts_TYPE** new_register_types = mm_malloc(sizeof(struct ts_TYPE*) * generic_method->registerc);
memcpy(new_register_types, generic_method->register_types, sizeof(struct ts_TYPE*) * generic_method->registerc);
specialization->register_types = new_register_types;
// Reify register types
for(int i = 0; i < specialization->registerc; i++) {
specialization->register_types[i] = ts_reify_type(generic_method->register_types[i], arguments);
}
}
if(generic_method->typereferences != NULL && specialization->typereferences == NULL) {
specialization->typereferences = mm_malloc(sizeof(struct ts_TYPE*) * generic_method->typereferencec);
memcpy(specialization->typereferences, generic_method->typereferences, sizeof(struct ts_TYPE*) * generic_method->typereferencec);
// Reify type references
for(int i = 0; i < specialization->typereferencec; i++) {
specialization->typereferences[i] = ts_reify_type(generic_method->typereferences[i], arguments);
}
}
if(generic_method->returntype != NULL && specialization->returntype == NULL) {
// Reify return type
// (parameters are reified via register types)
specialization->returntype = ts_reify_type(generic_method->returntype, arguments);
}
}
struct it_METHOD* ts_get_method_reification(struct it_METHOD* generic_method, struct ts_TYPE_ARGUMENTS* arguments) {
if(arguments->context->count <= 0) {
return generic_method;
}
if(generic_method->reified_from != generic_method) {
if(generic_method->typeargs == NULL) {
fatal("Invalid state in ts_get_method_reification");
}
struct ts_TYPE_ARGUMENTS* final_arguments = ts_compose_type_arguments(generic_method->typeargs, arguments);
struct it_METHOD* ret = ts_get_method_reification(generic_method->reified_from, final_arguments);
free(final_arguments);
return ret;
}
if(generic_method->reifications != NULL) {
for(int i = 0; i < generic_method->reificationsc; i++) {
// TODO: This code doesn't at all support nested generic type contexts
// We know reification->typeargs has length typeargsc
struct it_METHOD* reification = generic_method->reifications[i];
assert(reification != NULL);
assert(reification->typeargs != NULL);
bool compatible = true;
for(int j = 0; j < arguments->context->count; j++) {
if(reification->typeargs->mapping[j].value != arguments->mapping[j].value) {
compatible = false;
break;
}
}
if(compatible) {
return reification;
}
}
}
if(generic_method->reifications_size < generic_method->reificationsc + 1) {
generic_method->reifications_size *= 2;
if(generic_method->reifications_size < 1) {
generic_method->reifications_size = 1;
}
generic_method->reifications = realloc(generic_method->reifications, sizeof(struct it_METHOD*) * generic_method->reifications_size);
}
struct it_METHOD* ret = mm_malloc(sizeof(struct it_METHOD));
memcpy(ret, generic_method, sizeof(struct it_METHOD));
if(arguments->context->parent != NULL) {
fatal("Reifying methods in type contexts with parents isn't supported");
}
ret->reified_from = generic_method;
ret->opcodes = NULL;
ret->typeargs = NULL;
ret->register_types = NULL;
ret->typereferences = NULL;
ret->returntype = NULL;
ret->type_parameters = mm_malloc(sizeof(struct ts_GENERIC_TYPE_CONTEXT) + sizeof(struct ts_TYPE*) * 0);
ret->type_parameters->parent = NULL;
ret->type_parameters->count = 0;
// TODO: Create a function or macro to determine this size
size_t type_args_size = sizeof(struct ts_TYPE_ARGUMENTS) + sizeof(ret->typeargs->mapping[0]) * arguments->context->count;
ret->typeargs = mm_malloc(type_args_size);
memcpy(ret->typeargs, arguments, type_args_size);
ts_update_method_reification(ret);
generic_method->reifications[generic_method->reificationsc++] = ret;
ret->typereferencec = generic_method->typereferencec;
return ret;
}
struct it_METHOD* ts_get_unreified_method_from_reification(struct it_METHOD* reification) {
while(reification->reified_from != reification) {
reification = reification->reified_from;
}
return reification;
}
void ts_reify_generic_references(struct it_METHOD* method) {
if(ts_method_is_generic(method)) {
// We shouldn't need this check but it won't hurt
return;
}
for(int i = 0; i < method->opcodec; i++) {
struct it_OPCODE* opcode = &method->opcodes[i];
if(opcode->type == OPCODE_CALL) {
if(!ts_method_is_generic(opcode->data.call.callee)) {
if(method->typeargs != NULL) {
opcode->data.call.callee = ts_get_method_reification(ts_get_unreified_method_from_reification(opcode->data.call.callee), method->typeargs);
}
continue;
}
// I could use a VLA here but it's not necessary
struct ts_TYPE* type_arguments[TS_MAX_TYPE_ARGS];
for(int i = 0; i < opcode->data.call.type_paramsc; i++) {
type_arguments[i] = method->typereferences[opcode->data.call.type_params[i]];
}
struct ts_TYPE_ARGUMENTS* type_arguments_struct = ts_create_type_arguments(opcode->data.call.callee->type_parameters, opcode->data.call.type_paramsc, &type_arguments[0]);
struct it_METHOD* reification = ts_get_method_reification(opcode->data.call.callee, type_arguments_struct);
free(type_arguments_struct);
opcode->data.call.callee = reification;
} else if(opcode->type == OPCODE_CLASSCALLSPECIAL) {
if(method->typeargs != NULL) {
opcode->data.call.callee = ts_get_method_reification(ts_get_unreified_method_from_reification(opcode->data.call.callee), method->typeargs);
}
}
}
method->has_had_references_reified = true;
} |
C | #include "shell.h"
int k_number_of_bg=0;
int pid_foreground_process = -1;
char foreground_process_name[30];
void handler(int signum)
{
pid_t pid1;
int status1;
// pid = wait(NULL); //process id of the exited child process
pid1 = waitpid(-1, &status1, WNOHANG);
if(pid1>0)
{
for(int j=0; j<k_number_of_bg; j++)
{
if(s[j].pid == pid1 && s[j].running == 1)
{
fprintf(stdout,"%s process with pid %d exited normally\n", s[j].name, pid1);
s[j].running = 0;
break;
}
}
}
}
void execute(char** args)
{
pid_t pid,wait_pid;
int status, flag=0, i=0;
int status1, wait_pid1;
// flag=1 -> background process
// flag=0 -> foreground process
while(args[i])
{
if(!strcmp(args[i],"&")) // if background process
{
flag=1;
args[i] = NULL;
break;
}
i++;
}
if(flag==1)
{
pid = fork();
if(pid < 0)
{
fprintf(stderr, "Error: cannot create process\n");
}
else if(pid == 0) // running for the child
{
setpgid(0, 0); // here first argument is 0 as pid for child is 0
if(execvp(args[0],args)<0)
{
fprintf(stderr, "Error: cannot execute process\n");
exit(EXIT_FAILURE); // kill child if can't execute command otherwise 2 shells formed
}
}
else // running for parent
{
setpgid(pid, 0);
tcsetpgrp(STDIN_FILENO, getpgrp());
printf("%d\n",pid); // prints pid of child
// = return value of fork for parent
s[k_number_of_bg].pid = pid;
strcpy(s[k_number_of_bg].name,args[0]);
s[k_number_of_bg].running = 1;
k_number_of_bg++;
// while ((wait_pid1 = waitpid(-1, &status1, WNOHANG)) > 0){
// printf("Exit status of %d was %d \n", wait_pid1, status1);
// }
// wait_pid1 = waitpid(pid,&status1,WNOHANG);
// if(wait_pid1>0)
// fprintf(stdout,"process with pid %d exited normally\n", pid);
// sets stdin to only foreground
} // tcsetpgrp — set the foreground process group ID
}
else
{
pid = fork();
if(pid < 0)
{
fprintf(stderr, "Error: cannot create process\n");
}
else if(pid == 0) // running for the child
{
setpgid(0, 0);
if(execvp(args[0],args)<0)
{
fprintf(stderr, "Error: cannot execute process\n");
exit(EXIT_FAILURE); // kill child if can't execute command otherwise 2 shells formed
}
}
else // running for parent
{ // wait for child to exit
int savePid = pid;
pid_foreground_process = pid;
strcpy(foreground_process_name,args[0]);
// int shellPid = getpid();
signal(SIGTTOU, SIG_IGN);
signal(SIGTTIN, SIG_IGN);
setpgid(pid, 0);
tcsetpgrp(0, pid);
// tcsetpgrp(1, pid);
do
{
waitpid(savePid, &status, WUNTRACED);
} while (!WIFEXITED(status) && !WIFSIGNALED(status) && !WIFSTOPPED(status));
// tcsetpgrp(0, getpgid(shellPid));
tcsetpgrp(0, getpgrp());
// tcsetpgrp(1, getpgid(shellPid));
signal(SIGTTOU, SIG_DFL);
signal(SIGTTIN, SIG_DFL);
if(WIFSTOPPED(status))
{
if (pid_foreground_process != -1)
{
s[k_number_of_bg].pid = pid_foreground_process;
strcpy(s[k_number_of_bg].name,foreground_process_name);
s[k_number_of_bg].running = 1;
k_number_of_bg++;
}
pid_foreground_process = -1;
}
}
}
return;
} |
C | #include<stdio.h>
#include<stdlib.h>
#define MAX 20
void push(int stack[],int item);
void pop(int stack[]);
void display(int stack[]);
int stack[MAX];
int TOP;
int main()
{
int k,item,x;
do
{
printf("1.PUSH 2.POP 3.DISPLAY\n");
scanf("%d",&k);
switch(k)
{
case 1: printf("\nEnter the item to be added: ");
scanf("%d",&item);
push(stack,item);
break;
case 2: pop(stack);
break;
case 3: display(stack);
break;
default: printf("\n INVALID OPTION!!! \n");
}
printf("\n1.Continue.. 2.Stop\n");
scanf("%d",&x);
}while(x==1);
return 0;
}
void push(int stack[],int item)
{
if(TOP==MAX-1)
printf("Stack Overflow!!");
else
{
TOP=TOP+1;
stack[TOP]=item;
}
return;
}
void pop(int stack[])
{
int del_item;
if(TOP==-1)
printf("Stack Underflow!!");
else
{
del_item=stack[TOP];
TOP=TOP-1;
}
return;
}
void display(int stack[])
{
int i=0;
if(TOP==-1)
{
printf("Stack Overflow!!");
}
else
{
for(i=TOP;i>0;i--)
printf("%d ",stack[i]);
}
return;
}
|
C | #include<stdio.h>
int main()
{
int *arr[5];
int a=10,b=20,c=30,d=40,e=50;
int i;
arr[0]=&a;
arr[1]=&b;
arr[2]=&c;
arr[3]=&d;
arr[4]=&e;
for (i=0;i<5;i++)
{
printf("ADDRES OF [%d]=%d\tVALUE OF *[%d]=%d=\n=",i,arr[i],i,*arr[i]);
}
return 0;
}
|
C | #include<stdio.h>
#include<math.h>
int f(int n)
{
if(n==1)
return 1;
for(int i=2;i<=sqrt(n);i++)
{
if(n % i==0)
return 0;
}
return 1;
}
|
C | /*
* AUTHOR
* Copyright (C) 2012, Joan Maspons, [email protected]
* based on negative binomial distribution code from The R Core Team
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* 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.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, a copy is available at
* http://www.r-project.org/Licenses/
*
*
* DESCRIPTION
*
* Computes the negative binomial distribution. For integer size,
* this is probability of x failures before the nth success in a
* sequence of Bernoulli trials. We do not enforce integer size, since
* the distribution is well defined for non-integers,
* and this can be useful for e.g. overdispersed discrete survival times.
*/
#include <R.h>
#include <Rmath.h>
#include "dpq.h"
#include "R_ext/Visibility.h"
// #include <mpfr.h>
double attribute_hidden dbetanbinom_raw(double x, double size, double shape1, double shape2, int give_log)
{
if (x < 0 || !R_FINITE(x)) return R_D__0;
double ans;
if (log_p) {
ans = lgammafn(shape1 + size) - lgammafn(shape1) + lgammafn(size + x) - lgammafn(size) + lgammafn(shape2 + x) - lgammafn(shape2)
- (lgammafn(x+1) + lgammafn(shape1 + shape2 + size) - lgammafn(shape1 + shape2) + lgammafn(size + shape1 + shape2 + x) - lgammafn(size + shape1 + shape2));
} else {
//FIXME gammafn doesn't suport x > 171
//TODO mpfr
ans = gammafn(shape1 + size) / gammafn(shape1) * gammafn(size + x) / gammafn(size) * gammafn(shape2 + x) / gammafn(shape2) /
(gammafn(x+1) * gammafn(shape1 + shape2 + size) / gammafn(shape1 + shape2) * gammafn(size + shape1 + shape2 + x) / gammafn(size + shape1 + shape2)); //factorial(x) = gamma(x+1)
}
return ans;
}
double dbetanbinom(double x, double size, double shape1, double shape2, int give_log)
{
#ifdef IEEE_754
if (ISNAN(x) || ISNAN(size) || ISNAN(shape1) || ISNAN(shape2))
return x + size + shape1 + shape2;
#endif
if (shape1 <= 0 || shape2 <= 0 || size < 0) return R_NaN;
R_D_nonint_check(x);
x = R_D_forceint(x);
return dbetanbinom_raw(x, size, shape1, shape2, give_log);
}
/*
* DESCRIPTION
*
* The distribution function of the Beta negative binomial distribution.
*
* NOTES
*
* x = the number of failures before the n-th success
*/
double attribute_hidden pbetanbinom_raw(double x, double size, double shape1, double shape2)
{
double ans = 0;
int i;
for (i = 0; i <= x; ++i) {
// give_log = TRUE increase the range of the parameters
ans += exp(dbetanbinom_raw(i, size, shape1, shape2, /*give_log*/ TRUE));
}
return ans;
}
double pbetanbinom(double x, double size, double shape1, double shape2, int lower_tail, int log_p)
{
#ifdef IEEE_754
if (ISNAN(x) || ISNAN(size) || ISNAN(shape1) || ISNAN(shape2))
return x + size + shape1 + shape2;
if(!R_FINITE(size) || !R_FINITE(shape1) || !R_FINITE(shape2)) return R_NaN;
#endif
if (size <= 0 || shape1 <= 0 || shape2 <= 0) return R_NaN;
if (x < 0) return R_DT_0;
if (!R_FINITE(x)) return R_DT_1;
x = floor(x + 1e-7);
double ans = pbetanbinom_raw(x, size, shape1, shape2);
return R_DT_val(ans);
}
/*
* DESCRIPTION
*
* The quantile function of the Beta negative binomial distribution.
*
* NOTES
*
* x = the number of failures before the n-th success
*/
double qbetanbinom(double p, double size, double shape1, double shape2, int lower_tail, int log_p)
{
#ifdef IEEE_754
if (ISNAN(p) || ISNAN(size) || ISNAN(shape1) || ISNAN(shape2))
return p + size + shape1 + shape2;
#endif
if (shape1 <= 0 || shape2 <= 0|| size < 0) return R_NaN;
R_Q_P01_boundaries(p, 0, R_PosInf);
p = R_DT_qIv(p); //TODO check /* need check again (cancellation!): */
double pi = 0, i = 0;
while (pi < p) {
// give_log = TRUE increase the range of the parameters
pi += exp(dbetanbinom_raw(i, size, shape1, shape2, /*give_log*/ TRUE));
i++;
R_CheckUserInterrupt(); //TODO remove after tests: small shape1 < 0.2 parameter take very long time
}
return i;
}
/*
* DESCRIPTION
*
* Random variates from the Beta negative binomial distribution.
*
* NOTES
*
* x = the number of failures before the n-th success
*/
double rbetanbinom(double size, double shape1, double shape2)
{
return rnbinom(size, rbeta(shape1, shape2));
}
|
C | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* operator.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: mszczesn <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2016/01/12 10:59:10 by mszczesn #+# #+# */
/* Updated: 2016/02/10 22:06:12 by mszczesn ### ########.fr */
/* */
/* ************************************************************************** */
#include "push_swap.h"
int ft_sa(t_reperelist *list_a, t_reperelist *list_b, t_option *opt)
{
int tmp;
t_elementlist *e1;
t_elementlist *e2;
e1 = list_a->last;
e2 = list_a->last->prev;
if (e1 == NULL)
return (-1);
if (e2 == NULL)
return (0);
tmp = e1->number;
e1->number = e2->number;
e2->number = tmp;
write(1, " sa", 3);
opt->nbr++;
if (opt->afflist == 1)
ft_printlist(list_a, list_b);
return (1);
}
int ft_sb(t_reperelist *list_b, t_reperelist *list_a, t_option *opt)
{
int tmp;
t_elementlist *e1;
t_elementlist *e2;
e1 = list_b->last;
e2 = list_b->last->prev;
if (e1 == NULL)
return (-1);
if (e2 == NULL)
return (0);
tmp = e1->number;
e1->number = e2->number;
e2->number = tmp;
write(1, " sb", 3);
opt->nbr++;
if (opt->afflist == 1)
ft_printlist(list_a, list_b);
return (1);
}
int ft_pa(t_reperelist *list_a, t_reperelist *list_b, t_option *opt)
{
t_elementlist *tmp;
if (list_a == NULL)
return (-1);
if (list_b == NULL)
return (0);
tmp = list_b->last;
if (list_b->first == list_b->last)
{
list_b->first = NULL;
list_b->last = NULL;
list_a->last->next = tmp;
tmp->prev = list_a->last;
list_a->last = tmp;
write(1, " pa", 3);
opt->nbr++;
if (opt->afflist == 1)
ft_printlist(list_a, list_b);
return (1);
}
ft_pa2(list_a, list_b, tmp, opt);
return (1);
}
int ft_pa2(t_reperelist *list_a, t_reperelist *list_b,
t_elementlist *tmp, t_option *opt)
{
if (list_b->last->prev != NULL)
{
list_b->last = list_b->last->prev;
list_b->last->next = NULL;
}
if (list_b->last != NULL)
list_b->last->next = NULL;
tmp->next = NULL;
if (list_a->last != NULL)
{
list_a->last->next = tmp;
tmp->prev = list_a->last;
list_a->last = tmp;
}
else
{
tmp->prev = NULL;
list_a->first = tmp;
list_a->last = tmp;
}
write(1, " pa", 3);
opt->nbr++;
if (opt->afflist == 1)
ft_printlist(list_a, list_b);
return (1);
}
int ft_pb(t_reperelist *list_a, t_reperelist *list_b, t_option *opt)
{
t_elementlist *tmp;
if (list_b == NULL)
return (-1);
if (list_a == NULL)
return (0);
tmp = list_a->last;
{
list_a->last = list_a->last->prev;
list_a->last->next = NULL;
}
if (list_a->first == list_a->last)
{
list_a->first = NULL;
list_a->last = NULL;
}
if (list_a->last != NULL)
list_a->last->next = NULL;
tmp->next = NULL;
ft_pb2(list_a, list_b, tmp, opt);
return (1);
}
|
C | #include "monty.h"
/**
* op_pall - prints out the stack
* @stack: the stack
* @line_number: the line
*/
void op_pall(stack_t **stack, unsigned int line_number)
{
stack_t *temp;
(void)line_number;
if (!*stack)
return;
temp = *stack;
while (temp != NULL)
{
printf("%d\n", temp->n);
temp = temp->next;
}
}
|
C | // 程序填空,不要改变与输入输出有关的语句。
// 输入2个整数,分别将其逆向输出。
// 要求定义并调用函数 fun(n),它的功能是返回 n 的逆向值,函数形参 n 的类型是int,函数类型是int。例如,fun(123)的返回值是321。
// 输入输出示例:括号内是说明
// 输入:
// 123
// -910
// 输出:
// 123的逆向是321
// -910的逆向是-19
#include <stdio.h>
int fun(int n);
int main(void)
{
int m1,m2;
scanf("%d%d", &m1, &m2);
printf("%d的逆向是%d\n", m1, fun(m1));
printf("%d的逆向是%d\n", m2, fun(m2));
}
int fun(int n) {
int temp = 0,flag;
flag = n<0?-1:1;
n = n<0?-n:n;
do {
temp = temp*10 + n%10;
n /= 10;
} while (n!=0);
return temp*flag;
} |
C | #include "push_swap.h"
static void exit_all(t_list **stack_a, t_list **stack_b, bool err)
{
if (stack_a)
ft_lstclear(stack_a, free);
if (stack_b)
ft_lstclear(stack_b, free);
if (err)
ft_putstr("Error\n");
exit (0);
}
int main(int argc, char **argv)
{
t_list *stack_a;
t_list *stack_b;
stack_a = NULL;
stack_b = NULL;
if (argc == 1)
return (0);
if (!validate_input(argv, &stack_a))
exit_all(&stack_a, &stack_b, true);
if (!stack_sorted(stack_a, ft_lstsize(stack_a)))
sort_stack(&stack_a, &stack_b, argc - 1);
exit_all(&stack_a, &stack_b, false);
}
|
C | List Reverse(List L)
{
if(L->Next == NULL || L->Next->Next == NULL)
return L;
List p = L->Next; //Already reserved
List q = p->Next; //Not resserved yet
p->Next = NULL;
while (q)
{
List t = q->Next;
q->Next = p;
p = q;
q = t;
}
L->Next = p;
return L;
}
|
C | #include<stdio.h>
#include<stdlib.h>
//int main()
//{
// int ch;
// printf("һַ:\n");
// while ((ch = getchar()) != EOF)
// {
// if (ch >= 'a'&&ch <= 'z')
// {
// ch = ch - 32;
// printf("%c\n", ch);
// }
// else if (ch >= 'A'&&ch <= 'Z')
// {
// printf("%c\n", ch + 32);
// ch = ch + 32;
// }
// else
// if (ch >= '0'&&ch <= '9')
// ;
// else
// ;
// }
// printf("\n");
// system("pause");
//}
void output(int a)
{
int i, j;
for (i = 1; i <= a; i++)
{
for (j = 1; j <= i; j++)
printf("%d*%d=%2d ", i, j, i*j);
putchar('\n');
}
}
int main()
{
printf("Ҫӡ\n");
int a = 0;
scanf_s("%d", &a);
output(a);
system("pause");
}
|
C | #include<stdio.h>
int main() {
int F[20] = { 1,1 };
for (int i = 2; i <= 19; i++) {
F[i] = F[i - 1] + F[i - 2];
}
for (int i = 0; i <= 19; i++) {
if (i % 5 == 0)
printf("\n");
printf("%12d",F[i]);
}
return 0;
}
|
C | #include "infi.h"
#include <stdlib.h>
#include <assert.h>
#define MID(a, b) ((a + b) / 2.0)
#define DELTA(a, b, n) ((b - a) / n)
/**
* This function will return the middle values of the x between [a,b].
* @param a left x bound
* @param n number of sums
* @param dx the change in range [a,b]
* @return pointer to the middle points of [a,b]
*/
double *getMidPoints(double a, unsigned int n, double dx)
{
double *middles = (double *) calloc(n, sizeof(double));
for (unsigned int i = 0; i < n; i++)
{
middles[i] = MID(a + i * dx, a + (i + 1) * dx);
}
return middles;
}
/**
* This function will estimate the integral value of a function f using Riemann sums
* @param f pointer to a function
* @param a left bound for x
* @param b right bound for x
* @param n number of Riemann's sums
* @return the estimated integral value
*/
double integration(RealFunction f, double a, double b, unsigned int n)
{
assert(n > 0 && (double) (int) n == n);
assert(a < b);
double delta = DELTA(a, b, n);
double sum = 0, singleVal = 0;
double *midPoints = getMidPoints(a, n, delta);
for (unsigned int i = 0; i < n; i++)
{
singleVal = f(midPoints[i]);
assert(!isnan(singleVal));
sum += delta * (singleVal);
}
free(midPoints);
return sum;
}
/**
* This function will estimate the slope (derivative) of a function f in the point x0.
* @param f the given function
* @param x0 the point
* @param h the epsilon
* @return the slope in x0
*/
double derivative(RealFunction f, double x0, double h)
{
assert(h > 0);
double leftVal = f(x0 + h), rightVal = f(x0 - h);
assert(!isnan(leftVal));
assert(!isnan(rightVal));
return DELTA(rightVal, leftVal, (2 * h));
}
|
C | /* lamap - fast two-way and three-way admixture likelihood functions
Copyright (C) 2013 Giulio Genovese
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
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.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>. */
/* Written by Giulio Genovese <[email protected]> */
// lkl is a vector with likelihoods computed from ancestry proportions
// n is the number of samples
// frqA is the frequency of the alternate allele for ancestry A
// frqB is the frequency of the alternate allele for ancestry B
// frqC is the frequency of the alternate allele for ancestry C
// ancAA is the sample proportion of ancestry AA
// ancAB is the sample proportion of ancestry AB
// ancBB is the sample proportion of ancestry BB
// ancAC is the sample proportion of ancestry AC
// ancBC is the sample proportion of ancestry BC
// ancCC is the sample proportion of ancestry CC
// la is a local ancestry assignment
// gl0 is the likelihood of homozygous reference
// gl1 is the likelihood of heterozygous alternate
// gl2 is the likelihood of homozygous alternate
#include <stdio.h>
#include <stdlib.h>
// structure with emission frequencies for two ancestries
typedef struct {
double aa0;
double aa1;
double aa2;
double ab0;
double ab1;
double ab2;
double bb0;
double bb1;
double bb2;
} snp_emis2_t;
// structure with emission frequencies for three ancestries
typedef struct {
double aa0;
double aa1;
double aa2;
double ab0;
double ab1;
double ab2;
double bb0;
double bb1;
double bb2;
double ac0;
double ac1;
double ac2;
double bc0;
double bc1;
double bc2;
double cc0;
double cc1;
double cc2;
} snp_emis3_t;
snp_emis2_t emis2(double frqA, double frqB) {
snp_emis2_t f;
f.aa0 = (1-frqA)*(1-frqA);
f.aa1 = 2*frqA*(1-frqA);
f.aa2 = frqA*frqA;
f.ab0 = (1-frqA)*(1-frqB);
f.ab1 = frqA*(1-frqB)+(1-frqA)*frqB;
f.ab2 = frqA*frqB;
f.bb0 = (1-frqB)*(1-frqB);
f.bb1 = 2*frqB*(1-frqB);
f.bb2 = frqB*frqB;
return f;
}
snp_emis3_t emis3(double frqA, double frqB, double frqC) {
snp_emis3_t f;
f.aa0 = (1-frqA)*(1-frqA);
f.aa1 = 2*frqA*(1-frqA);
f.aa2 = frqA*frqA;
f.ab0 = (1-frqA)*(1-frqB);
f.ab1 = frqA*(1-frqB)+(1-frqA)*frqB;
f.ab2 = frqA*frqB;
f.bb0 = (1-frqB)*(1-frqB);
f.bb1 = 2*frqB*(1-frqB);
f.bb2 = frqB*frqB;
f.ac0 = (1-frqA)*(1-frqC);
f.ac1 = frqA*(1-frqC)+(1-frqA)*frqC;
f.ac2 = frqA*frqC;
f.bc0 = (1-frqB)*(1-frqC);
f.bc1 = frqB*(1-frqC)+(1-frqB)*frqC;
f.bc2 = frqB*frqC;
f.cc0 = (1-frqC)*(1-frqC);
f.cc1 = 2*frqC*(1-frqC);
f.cc2 = frqC*frqC;
return f;
}
// compute the likelihood for the genotypes from ancestry proportions
void lkl2(double *lkl, long n, double frqA, double frqB, double *ancAA, double *ancAB, double *ancBB, double *gl0, double *gl1, double *gl2) {
snp_emis2_t f = emis2(frqA, frqB);
long i;
for (i=0; i<n; i++) {
lkl[i] = ( (f.aa0 * gl0[i] + f.aa1 * gl1[i] + f.aa2 * gl2[i]) * ancAA[i] +
(f.ab0 * gl0[i] + f.ab1 * gl1[i] + f.ab2 * gl2[i]) * ancAB[i] +
(f.bb0 * gl0[i] + f.bb1 * gl1[i] + f.bb2 * gl2[i]) * ancBB[i] ) /
(ancAA[i] + ancAB[i] + ancBB[i]);
}
}
// compute the odds ratio for the genotypes from local ancestry assignments and ancestry proportions
double odd2(long n, double frqA, double frqB, char *la, double *gl0, double *gl1, double *gl2, double *lkl) {
snp_emis2_t f = emis2(frqA, frqB);
long i;
double lod = 1;
for (i=0; i<n; i++) {
switch( la[i] ) {
case 1: // AA
lod *= ( f.aa0 * gl0[i] + f.aa1 * gl1[i] + f.aa2 * gl2[i] ) / lkl[i];
break;
case 2: // AB
lod *= ( f.ab0 * gl0[i] + f.ab1 * gl1[i] + f.ab2 * gl2[i] ) / lkl[i];
break;
case 3: // BB
lod *= ( f.bb0 * gl0[i] + f.bb1 * gl1[i] + f.bb2 * gl2[i] ) / lkl[i];
break;
}
}
return lod;
}
// compute the likelihood for the genotypes from ancestry proportions
void lkl3(double *lkl, long n, double frqA, double frqB, double frqC, double *ancAA, double *ancAB, double *ancBB, double *ancAC, double *ancBC, double *ancCC, double *gl0, double *gl1, double *gl2) {
snp_emis3_t f = emis3(frqA, frqB, frqC);
long i;
for (i=0; i<n; i++) {
lkl[i] = ( (f.aa0 * gl0[i] + f.aa1 * gl1[i] + f.aa2 * gl2[i]) * ancAA[i] +
(f.ab0 * gl0[i] + f.ab1 * gl1[i] + f.ab2 * gl2[i]) * ancAB[i] +
(f.bb0 * gl0[i] + f.bb1 * gl1[i] + f.bb2 * gl2[i]) * ancBB[i] +
(f.ac0 * gl0[i] + f.ac1 * gl1[i] + f.ac2 * gl2[i]) * ancAC[i] +
(f.bc0 * gl0[i] + f.bc1 * gl1[i] + f.bc2 * gl2[i]) * ancBC[i] +
(f.cc0 * gl0[i] + f.cc1 * gl1[i] + f.cc2 * gl2[i]) * ancCC[i] ) /
(ancAA[i] + ancAB[i] + ancBB[i] + ancAC[i] + ancBC[i] + ancCC[i]);
}
}
// compute the odds ratio for the genotypes from local ancestry assignments and ancestry proportions
double odd3(long n, double frqA, double frqB, double frqC, char *la, double *gl0, double *gl1, double *gl2, double *lkl) {
snp_emis3_t f = emis3(frqA, frqB, frqC);
long i;
double lod = 1;
for (i=0; i<n; i++) {
switch( la[i] ) {
case 1: // AA
lod *= ( f.aa0 * gl0[i] + f.aa1 * gl1[i] + f.aa2 * gl2[i] ) / lkl[i];
break;
case 2: // AB
lod *= ( f.ab0 * gl0[i] + f.ab1 * gl1[i] + f.ab2 * gl2[i] ) / lkl[i];
break;
case 3: // BB
lod *= ( f.bb0 * gl0[i] + f.bb1 * gl1[i] + f.bb2 * gl2[i] ) / lkl[i];
break;
case 4: // AC
lod *= ( f.ac0 * gl0[i] + f.ac1 * gl1[i] + f.ac2 * gl2[i] ) / lkl[i];
break;
case 5: // BC
lod *= ( f.bc0 * gl0[i] + f.bc1 * gl1[i] + f.bc2 * gl2[i] ) / lkl[i];
break;
case 6: // CC
lod *= ( f.cc0 * gl0[i] + f.cc1 * gl1[i] + f.cc2 * gl2[i] ) / lkl[i];
break;
}
}
return lod;
}
// fast code (4x improvement over load numpy.loadtxt) to load the local ancestry inference matrix
void getla(long *chrom, long *start, long *end, char* la, long n, long m, char** str) {
long i, j, offset;
for (i=0; i<n; i++) {
if(sscanf(*str,"%ld%ld%ld%ln",chrom,start,end,&offset)!=3) {
fprintf(stderr, "Wrong format at line %ld in the bedgraph file ...\n",i+2);
exit(EXIT_FAILURE);
}
*str += offset;
for (j=0; j<m; j++) {
if(sscanf(*str,"%hhd%ln",la,&offset)!=1) {
fprintf(stderr, "Wrong format at line %ld, column %ld in the bedgraph file ...\n",i+2,j+4);
exit(EXIT_FAILURE);
}
*str += offset;
la++;
}
chrom++; start++; end++; str++;
}
}
void getsig(long *chrom, long *pos, char* sig, long T, long n, char** str) {
long i, j, offset;
char buffer[256];
for (i=0; i<T; i++) {
if(sscanf(*str,"%ld%ld%s%ln",chrom,pos,buffer,&offset)!=3) {
fprintf(stderr, "Wrong format at line %ld in the signature file ...\n",i+1);
exit(EXIT_FAILURE);
}
*str += offset;
for (j=0; j<n; j++) {
if(sscanf(*str,"%hhd%ln",sig,&offset)!=1) {
fprintf(stderr, "Wrong format at line %ld, column %ld in the signature file ...\n",i+1,j+4);
exit(EXIT_FAILURE);
}
*str += offset;
sig++;
}
chrom++; pos++; str++;
}
}
// compute the Viterbi path for the local ancestry deconvolution
void getpath(char *path, long T, long n, double *trans, char *phased, char *matobs, char *patobs) {
long t, i, j, n2 = n*n;
double prob[n2];
double newprob[n2];
char ptr[(T-1)*n2];
double tmp;
for (i=0; i<n2; i++)
prob[i] = matobs[i/n] + patobs[i%n];
for (t=1; t<T; t++) {
for (i=0; i<n2; i++)
for (j=0; j<n2; j++) {
if (phased[t] || matobs[t*n+i/n] + patobs[t*n+i%n] < matobs[t*n+i%n] + patobs[t*n+i/n])
tmp = prob[j] + trans[j*n2+i] + (double)(matobs[t*n+i/n] + patobs[t*n+i%n]);
else
tmp = prob[j] + trans[j*n2+i] + (double)(matobs[t*n+i%n] + patobs[t*n+i/n]);
if (j==0 || tmp<newprob[i]) {
newprob[i] = tmp;
ptr[(t-1)*n2+i] = j;
}
}
for (i=0; i<n2; i++)
prob[i] = newprob[i];
}
for (i=0; i<n2; i++)
if (i==0 || prob[i]<prob[path[T-1]])
path[T-1] = i;
for (t=T-2; t>=0; t--)
path[t] = ptr[t*n2+path[t+1]];
}
|
C | #include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#define x 4
#define y 2
#define z 5
pthread_t tid[x*z];
pthread_attr_t attr;
int iret[x*z];
key_t key = 1234;
int *matrix;
void *hitung(void *arguments);
int main(void){
int total=x*z;
int shmid = shmget(key, sizeof(matrix), IPC_CREAT | 0666);
matrix = shmat(shmid, 0, 0);
int cnt=0;
for(int i=1; i<x+1; i++){
for(int j=1; j<z+1; j++){
printf("%d\t", matrix[cnt]);
cnt++;
}
printf("\n");
}
printf("\n");
cnt=0;
for(int i=1; i<x+1; i++){
for(int j=1; j<z+1; j++){
pthread_attr_init(&attr);
iret[cnt] = pthread_create(&tid[cnt], &attr, hitung, &matrix[cnt]);
if(iret[cnt]){
fprintf(stderr,"Error - pthread_create() return code: %d\n", iret[cnt]);
exit(EXIT_FAILURE);
}
pthread_join(tid[cnt], NULL);
cnt++;
}
printf("\n");
}
for(int i=0; i<total; i++){
pthread_join(tid[i], NULL);
}
shmdt(matrix);
shmctl(shmid, IPC_RMID, NULL);
return 0;
}
void *hitung(void *arguments){
int temp=0;
int c = *((int *)arguments);
for(c; c>0; c--){
temp=temp+c;
}
printf("%d\t", temp);
pthread_exit(0);
} |
C | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* check_first_rdir_a.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: yunslee <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/01/29 15:49:59 by jikang #+# #+# */
/* Updated: 2021/01/29 17:23:26 by yunslee ### ########.fr */
/* */
/* ************************************************************************** */
#include "minishell.h"
int find_rdir(char *str, int i)
{
if (str[i] == '>')
{
while (str[i] == ' ' || str[i] == '>')
i++;
while (str[i] != ' ' && str[i] && str[i] != '>')
{
i++;
if (str[i] == '\0')
return (-1);
}
while (str[i] == ' ')
i++;
return (find_rdir(str, i));
}
else
return (i);
return (i);
}
int find_next_rdir(char *str, int k)
{
while (str[k] != '>' && str[k])
k++;
return (k);
}
char *insert_space(char **line, char *str)
{
*line = ft_calloc(ft_strlen(str) + 2, sizeof(char));
*line[0] = ' ';
ft_memcpy(*line + 1, str, ft_strlen(str));
return (*line);
}
char *conv_first_redir(char *str)
{
char *line;
t_var v;
v.k = find_rdir(str, 0);
v.l = find_next_rdir(str, v.k);
if (v.k == -1)
return (insert_space(&line, str));
line = ft_calloc(ft_strlen(str) + 1, sizeof(char));
v.i = 0;
v.j = v.k;
drag_redir_to_right_place(line, str, &v);
return (line);
}
char *check_first_redir(char *str)
{
char *line;
line = conv_first_redir(str);
free_swap(&str, line);
line = NULL;
return (str);
}
|
C | #include <stdio.h>
#include <stdlib.h>
int buscaBinaria(int A[], int inicio, int fim, int valor);
int main() {
int V[]={1,2,3,4,5,6,7,8};
int result;
result = BB(&V[7],1,7,2);
printf("%d\n", result);
return 0;
}
int buscaBinaria(int A[], int inicio, int fim, int valor){
int meio;
while(inicio <= fim){
meio = (inicio + fim)/2;
if(A[meio] == valor)
return meio;
else if(A[meio] < valor)
inicio = meio + 1;
else
fim = meio -1;
}
return -1;
} |
C | /*
* MinPerimeterRectangle
* Find the minimal perimeter of any rectangle whose area equals N.
*/
int solution(int N)
{
int biggest_factor = 1;
int i = 1, j;
while (i*i <= N) {
if (N % i = 0) biggest_factor = i;
i++;
}
j = N/biggest_factor;
return 2*(j + biggest_factor);
}
|
C | /*
* File: paging.h
* Description: Describes the 4-level page mapping
* *****************************************************************************
* Copyright 2020 Scott Maday
* Check the LICENSE file that came with this program for licensing terms
*/
#pragma once
#include "memory.h"
typedef uint64_t page_directory_entry_t;
typedef page_directory_entry_t page_table_entry_t;
enum PageDirectoryFlagBit {
PAGE_DIRECTORY_PRESENT = 0, // (P) Page is in RAM and MMU can access it
PAGE_DIRECTORY_WRITABLE = 1, // (R) Page can be written to
PAGE_DIRECTORY_USERSPACE = 2, // (U) Page can be accessed by userspace
PAGE_DIRECTORY_WRITETHROUGH = 3, // (W/WT) Write-through cache (else write-back)
PAGE_DIRECTORY_NOCACHE = 4, // (D/CD) Disable cache
PAGE_DIRECTORY_ACCESSED = 5, // (A) The page has previously been accessed
PAGE_DIRECTORY_LARGERPAGES = 7, // (S) Page points to a page that describes a 4Mb page
PAGE_DIRECTORY_OS_AVAILABLE = 11, // OS-specific (3 bits)
PAGE_DIRECTORY_NOEXECUTE = 63 // Disabe execution, only if supported
};
enum PageTableFlagBit {
PAGE_TABLE_PRESENT = PAGE_DIRECTORY_PRESENT,
PAGE_TABLE_WRITABLE = PAGE_DIRECTORY_WRITABLE,
PAGE_TABLE_USERSPACE = PAGE_DIRECTORY_USERSPACE,
PAGE_TABLE_WRITETHROUGH = 3, // (PWT) Page writethrough
PAGE_TABLE_NOCACHE = 4, // (C/PCD) Page cache disable
PAGE_TABLE_ACCESSED = PAGE_DIRECTORY_ACCESSED,
PAGE_TABLE_PAT = 7, // (PAT) Page attribute table
PAGE_TABLE_GLOBAL = 8, // (G) Prevents the TLB from updating the address in its cache if CR3 is reset
PAGE_TABLE_OS_AVAILABLE = PAGE_DIRECTORY_OS_AVAILABLE,
PAGE_TABLE_NOEXECUTE = PAGE_DIRECTORY_NOEXECUTE
};
enum PagePATMode {
PAGE_PAT_UNCACHED = 0, // Write combining and speculative accesses are not allowed
PAGE_PAT_WRITE_COMBINE = 1, // Write combining is allowed & speculative reads are allowed
PAGE_PAT_WRITE_THROUGH = 4, // Write hits update the cache and main memory
PAGE_PAT_WRITE_PROTECTED = 5, // Write hits invalidate the cache line and update main memory
PAGE_PAT_WRITE_BACK = 6, // Writes allocate to the modified state on a cache miss (default)
PAGE_PAT_UC_MINUS = 7, // Uncached, but can be overridden by MTRR
};
struct PageTable {
uint64_t entries[MEMORY_PAGE_ENTRY_SIZE];
} __attribute__((aligned(MEMORY_PAGE_SIZE)));
// x86_64 multi-level addressing
struct PageLevelIndexes {
uint16_t L4_i; // Index to the page directory pointer table
uint16_t L3_i; // Index to the page directory table
uint16_t L2_i; // Index to the page table
uint16_t L1_i; // Index to the page
};
// *** Miscellaneous functions *** //
// Breaks the virtual [address] into its indexes and puts it in [out]
void paging_get_indexes(void* address, struct PageLevelIndexes* out);
// Returns the [entry] with the [address] applied to it
page_directory_entry_t paging_set_entry_address(page_directory_entry_t entry, void* address);
// Gets the kernel page table level 4 pointer
struct PageTable* paging_get_pagetable_l4();
// *** Assembly functions *** //
// Loads the paging information into the appropriate control register
void paging_load();
// Loads the PAT (page attribute table) MSR and invalidates cache
void paging_load_pat();
// *** Class functions *** //
// Initializes paging by creating the kernel's page table level 4 and sets the initial mapping between virtual and physical memory.
void paging_init();
// Initializes the PAT by preparing MMIO OS-preferred caches (does not load the PAT and this should be called after doing so)
void paging_init_pat();
// Maps [virtual_address] to [physical_address]
void paging_map_page(struct PageTable* pagetable_l4, void* virtual_address, void* physical_address);
void paging_map(struct PageTable* pagetable_l4, void* virtual_address, void* physical_address, size_t pages);
// Identity maps [address] for the kernel's page table Is not write protected. Should only be used with MMIO.
void paging_identity_map(void* address, size_t pages);
void paging_identity_map_size(void* address, size_t size);
// Sets the page directory attributes of [virtual_address] for [pages] of [attribute] to [enabled]
// Also assumes [attribute] is the same for the page table attributes
void paging_set_attribute(struct PageTable* pagetable_l4, void* virtual_address, size_t pages, enum PageDirectoryFlagBit attribute, bool enabled);
// Sets the page table corresponding to [virtual_address] for [pages] for the kernel's page table to have a cache policy of [mode]
void paging_set_cache(void* virtual_address, size_t pages, enum PagePATMode mode);
void paging_set_cache_size(void* virtual_address, size_t size, enum PagePATMode mode);
// Sets [pages] (or [size] rounded up to the nearest page) at [virtual_address] for the kernel's page table to be writable
// Assumes the page has been mapped previously
void paging_set_writable(void* virtual_address, size_t pages);
void paging_set_writable_size(void* virtual_address, size_t size); |
C | #include "SizeBuffer.h"
#include "StringBuilder.h"
#pragma pack(push)
#pragma pack(1)
PLAIN_OLD_DATA(_SizeBufferMetadata)
{
_SizeBuffer buffer[0];
uint64_t capacity;
uint64_t size;
char data[0];
};
#pragma pack(pop)
NAMESPACE_METHOD_IMPLEMENT(SizeBuffer, EvaluatePhysicalSize, uint64_t, uint64_t capacity)
{
return capacity + sizeof(_SizeBufferMetadata);
}
NAMESPACE_METHOD_IMPLEMENT(SizeBuffer, Initialize, _SizeBuffer*, void* buffer, uint64_t bufferSize, OUT uint64_t* capacity)
{
if (!buffer || !bufferSize)
{
return NULL;
}
/*capacity and size occupied all space*/
if (sizeof(_SizeBufferMetadata) >= bufferSize)
{
return NULL;
}
uint64_t realCapacity = bufferSize - sizeof(_SizeBufferMetadata);
capacity && (*capacity = realCapacity);
_SizeBufferMetadata* sb = (_SizeBufferMetadata*)buffer;
sb->capacity = realCapacity;
sb->size = 0;
return sb->buffer;
}
NAMESPACE_METHOD_IMPLEMENT(SizeBuffer, InitializeByString, _SizeBuffer*, void* buffer, uint64_t bufferSize, const char* data, int64_t dataSize, OUT void** end)
{
if (!data)
{
return NONINSTANTIAL_NAMESPACE_METHOD_CALL(SizeBuffer, Initialize, buffer, bufferSize, NULL);
}
if (0 > dataSize)
{
dataSize = strlen(data);
}
if (bufferSize < dataSize + sizeof(_SizeBufferMetadata))
{
return NULL;
}
_SizeBufferMetadata* sb = (_SizeBufferMetadata*)buffer;
sb->capacity = sb->size = dataSize;
I_MEMMOVE(sb->data, data, dataSize);
end && (*end = POINTER_OFFSET(sb->data, dataSize));
return (_SizeBuffer*)buffer;
}
NAMESPACE_METHOD_IMPLEMENT(SizeBuffer, New, _SizeBuffer*, uint64_t capacity)
{
if (!capacity)
{
return NULL;
}
_SizeBufferMetadata* sb = (_SizeBufferMetadata*)I_MALLOC(capacity + sizeof(_SizeBufferMetadata));
if (!sb)
{
return NULL;
}
sb->capacity = capacity;
sb->size = 0;
return sb->buffer;
}
NAMESPACE_METHOD_IMPLEMENT(SizeBuffer, Clone, _SizeBuffer*, const _SizeBuffer* data)
{
_SizeBufferMetadata* sb = (_SizeBufferMetadata*)data;
uint64_t physicalSize = sb->capacity + sizeof(_SizeBufferMetadata);
void* buffer = I_MALLOC(physicalSize);
if (!buffer)
{
return NULL;
}
I_MEMMOVE(buffer, data, physicalSize);
return (_SizeBuffer*)buffer;
}
NAMESPACE_METHOD_IMPLEMENT(SizeBuffer, Delete, void, _SizeBuffer* data)
{
I_FREE(data);
}
NAMESPACE_METHOD_IMPLEMENT(SizeBuffer, Capacity, uint64_t, const _SizeBuffer* data)
{
return ((_SizeBufferMetadata*)data)->capacity;
}
NAMESPACE_METHOD_IMPLEMENT(SizeBuffer, Size, uint64_t, const _SizeBuffer* data)
{
return ((_SizeBufferMetadata*)data)->size;
}
NAMESPACE_METHOD_IMPLEMENT(SizeBuffer, Data, char*, _SizeBuffer* data)
{
return ((_SizeBufferMetadata*)data)->data;
}
NAMESPACE_METHOD_IMPLEMENT(SizeBuffer, Begin, void*, _SizeBuffer* data)
{
return data;
}
NAMESPACE_METHOD_IMPLEMENT(SizeBuffer, End, void*, _SizeBuffer* data)
{
return POINTER_OFFSET(data, ((_SizeBufferMetadata*)data)->capacity + sizeof(_SizeBufferMetadata));
}
NAMESPACE_METHOD_IMPLEMENT(SizeBuffer, MetadataSize, uint64_t, const _SizeBuffer* data)
{
return sizeof(_SizeBufferMetadata);
}
NAMESPACE_METHOD_IMPLEMENT(SizeBuffer, SetSize, bool, _SizeBuffer* data, uint64_t size)
{
_SizeBufferMetadata* sb = (_SizeBufferMetadata*)data;
if (size > sb->capacity)
{
return false;
}
sb->size = size;
return true;
}
NAMESPACE_METHOD_IMPLEMENT(SizeBuffer, AppendAsPath, bool, _SizeBuffer* data, const char* substring, int substringSize)
{
uint64_t capacity = NONINSTANTIAL_NAMESPACE_METHOD_CALL(SizeBuffer, Capacity, data);
int64_t size = NONINSTANTIAL_NAMESPACE_METHOD_CALL(SizeBuffer, Size, data);
char* realData = NONINSTANTIAL_NAMESPACE_METHOD_CALL(SizeBuffer, Data, data);
size = StringBuilder.AppendAsPath(realData, size, capacity, substring, substringSize);
if (0 > size)
{
return false;
}
return NONINSTANTIAL_NAMESPACE_METHOD_CALL(SizeBuffer, SetSize, data, size);
}
NAMESPACE_METHOD_IMPLEMENT(SizeBuffer, Append, bool, _SizeBuffer* data, const char* substring, int substringSize)
{
uint64_t capacity = NONINSTANTIAL_NAMESPACE_METHOD_CALL(SizeBuffer, Capacity, data);
int64_t size = NONINSTANTIAL_NAMESPACE_METHOD_CALL(SizeBuffer, Size, data);
char* realData = NONINSTANTIAL_NAMESPACE_METHOD_CALL(SizeBuffer, Data, data);
size = StringBuilder.Append(realData, size, capacity, substring, substringSize);
if (0 > size)
{
return false;
}
return NONINSTANTIAL_NAMESPACE_METHOD_CALL(SizeBuffer, SetSize, data, size);
}
NAMESPACE_METHOD_IMPLEMENT(SizeBuffer, AppendFormatAsPath, bool, _SizeBuffer* data, const char* formatString, ...)
{
uint64_t capacity = NONINSTANTIAL_NAMESPACE_METHOD_CALL(SizeBuffer, Capacity, data);
int64_t size = NONINSTANTIAL_NAMESPACE_METHOD_CALL(SizeBuffer, Size, data);
char* realData = NONINSTANTIAL_NAMESPACE_METHOD_CALL(SizeBuffer, Data, data);
va_list args;
va_start(args, formatString);
size = StringBuilder.VFormat(realData, size, capacity, true, formatString, args);
va_end(args);
if (0 > size)
{
return false;
}
return NONINSTANTIAL_NAMESPACE_METHOD_CALL(SizeBuffer, SetSize, data, size);
}
NAMESPACE_METHOD_IMPLEMENT(SizeBuffer, AppendFormat, bool, _SizeBuffer* data, const char* formatString, ...)
{
uint64_t capacity = NONINSTANTIAL_NAMESPACE_METHOD_CALL(SizeBuffer, Capacity, data);
int64_t size = NONINSTANTIAL_NAMESPACE_METHOD_CALL(SizeBuffer, Size, data);
char* realData = NONINSTANTIAL_NAMESPACE_METHOD_CALL(SizeBuffer, Data, data);
va_list args;
va_start(args, formatString);
size = StringBuilder.VFormat(realData, size, capacity, false, formatString, args);
va_end(args);
if (0 > size)
{
return false;
}
return NONINSTANTIAL_NAMESPACE_METHOD_CALL(SizeBuffer, SetSize, data, size);
}
NAMESPACE_METHOD_IMPLEMENT(SizeBuffer, CopyTo, _SizeBuffer*, _SizeBuffer* data, void* buffer, uint64_t bufferSize)
{
_SizeBufferMetadata* sb = (_SizeBufferMetadata*)data;
uint64_t physicalSize = sb->capacity + sizeof(_SizeBufferMetadata);
if (bufferSize < physicalSize)
{
return NULL;
}
I_MEMMOVE(buffer, sb, physicalSize);
return (_SizeBuffer*)buffer;
}
NAMESPACE_METHOD_IMPLEMENT(SizeBuffer, Compare, int64_t, _SizeBuffer* data1, _SizeBuffer* data2)
{
_SizeBufferMetadata* sb1 = (_SizeBufferMetadata*)data1;
_SizeBufferMetadata* sb2 = (_SizeBufferMetadata*)data2;
int64_t sizeComparison = sb1->size - sb2->size;
uint64_t minimalComparisonSize = 0 > sizeComparison ? sb1->size : sb2->size;
char* p1 = sb1->data;
char* p2 = sb2->data;
int i = 0;
int result = 0;
for (i = 0; i < minimalComparisonSize; ++i)
{
if ((result = p1[i] - p2[i]))
{
return result;
}
}
return sizeComparison;
}
NAMESPACE_INITIALIZE(SizeBuffer)
{
NAMESPACE_METHOD_INITIALIZE(SizeBuffer, EvaluatePhysicalSize)
NAMESPACE_METHOD_INITIALIZE(SizeBuffer, Initialize)
NAMESPACE_METHOD_INITIALIZE(SizeBuffer, InitializeByString)
NAMESPACE_METHOD_INITIALIZE(SizeBuffer, New)
NAMESPACE_METHOD_INITIALIZE(SizeBuffer, Clone)
NAMESPACE_METHOD_INITIALIZE(SizeBuffer, Delete)
NAMESPACE_METHOD_INITIALIZE(SizeBuffer, Capacity)
NAMESPACE_METHOD_INITIALIZE(SizeBuffer, Size)
NAMESPACE_METHOD_INITIALIZE(SizeBuffer, Data)
NAMESPACE_METHOD_INITIALIZE(SizeBuffer, Begin)
NAMESPACE_METHOD_INITIALIZE(SizeBuffer, End)
NAMESPACE_METHOD_INITIALIZE(SizeBuffer, MetadataSize)
NAMESPACE_METHOD_INITIALIZE(SizeBuffer, SetSize)
NAMESPACE_METHOD_INITIALIZE(SizeBuffer, AppendAsPath)
NAMESPACE_METHOD_INITIALIZE(SizeBuffer, Append)
NAMESPACE_METHOD_INITIALIZE(SizeBuffer, AppendFormatAsPath)
NAMESPACE_METHOD_INITIALIZE(SizeBuffer, AppendFormat)
NAMESPACE_METHOD_INITIALIZE(SizeBuffer, CopyTo)
NAMESPACE_METHOD_INITIALIZE(SizeBuffer, Compare)
};
|
C |
#include "unit_test.h"
// Used by __puthex*
char * lut = "0123456789ABCDEF";
// Base address of the memory mapped IO region
volatile uint32_t * __mmio_base = (uint32_t*)0x00001000;
//! Direct access to mtime
volatile uint64_t * __mtime = (uint64_t*)0x00001000;
//! Direct access to mtimecmp
volatile uint64_t * __mtimecmp = (uint64_t*)0x00001008;
volatile uint32_t * UART = (volatile uint32_t*)0x40600000;
//! Write a character to the uart.
void __putchar(char c) {
UART[0] = c;
}
//! Write a null terminated string to the uart.
void __putstr(char *s) {
int i = 0;
if(s[0] == 0) {
return;
}
do {
uint32_t tw = s[i];
UART[0] = tw;
i++;
} while(s[i] != 0) ;
}
//! Print a 64-bit number as hex
void __puthex64(uint64_t w) {
for(int i = 7; i >= 0; i --) {
uint8_t b_0 = (w >> (8*i )) & 0xF;
uint8_t b_1 = (w >> (8*i + 4)) & 0xF;
__putchar(lut[b_1]);
__putchar(lut[b_0]);
}
}
//! Print a 64-bit number as hex. No leading zeros.
void __puthex64_nlz(uint64_t w) {
char nz_seen = 0;
for(int i = 7; i >= 0; i --) {
uint8_t b_0 = (w >> (8*i )) & 0xF;
uint8_t b_1 = (w >> (8*i + 4)) & 0xF;
if(b_1 > 0 || nz_seen) {
nz_seen = 1;
__putchar(lut[b_1]);
}
if(b_0 > 0 || nz_seen) {
nz_seen = 1;
__putchar(lut[b_0]);
}
}
}
//! Print a 32-bit number as hex
void __puthex32(uint32_t w) {
for(int i = 3; i >= 0; i --) {
uint8_t b_0 = (w >> (8*i )) & 0xF;
uint8_t b_1 = (w >> (8*i + 4)) & 0xF;
__putchar(lut[b_1]);
__putchar(lut[b_0]);
}
}
//! Print an 8-bit number as hex
void __puthex8(uint8_t w) {
uint8_t b_0 = (w >> ( 0)) & 0xF;
uint8_t b_1 = (w >> ( 4)) & 0xF;
__putchar(lut[b_1]);
__putchar(lut[b_0]);
}
|
C | #define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct humanBeing {
char name[10];
int age;
float salary;
} humanBeing;
void main() {
humanBeing p1, p2;
printf("input person1's name, age, and salary: \n");
scanf("%s %d %f", p1.name, &p1.age, &p1.salary);
printf("input person2's name, age, and salary: \n");
scanf("%s %d %f", p2.name, &p2.age, &p2.salary);
printf("%s", !strcmp(p1.name,p2.name)&&p1.age==p2.age&&p1.salary==p2.salary?"same!":"not same!");
} |
C | #include <stdio.h>
#include <windows.h>
void main()
{int i,o;
int a[2][3]=
{
{999,9999,9999},
{999,999,999}
};
for(i=0;i<2;i++)
{
for(o=0;o<3;o++)
{
printf("%d ",a[i][o]);
}
printf("\n");
}
Sleep(1000);
for(i=0;i<2;i++)
{
for(o=0;o<3;o++)
{
a[i][o]=0;
printf("%d ",a[i][o]);
}
printf("\n");
}
Sleep(1000);
for(i=0;i<2;i++)
{
for(o=0;o<3;o++)
{
a[i][o]=999;
printf("%d ",a[i][o]);
}
printf("\n");
}
}
|
C | ///////////////////////////////////////////////////////////////
//
// dumpscreen.h
//
// - dump screen utility to grad screen from OpenGL
//
// by Philip Fu ([email protected])
//
// 3/4/2003 2:22P
//
// All rights reserved
//
///////////////////////////////////////////////////////////////
#ifndef _DUMPSCREEN_H
#define _DUMPSCREEN_H
///////////////////////////////////////////////////////////////
//
// Input Parameters:
//
// - viewport is the screen region
// - x ( window coordinates x )
// - y ( window coordinates y )
// - w ( width )
// - h ( height )
// - will be clamped by the current viewport internally
// - mode
// - GL_FRONT, GL_BACK, GL_LEFT, GL_RIGHT, etc.
// (see glReadBuffer)
// - buf
// - IF input buf == NULL
// - dumpscreen routines will allocate memory internally
// - ELSE
// - assume intput buf has enough space to hold the data
//
///////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////
// (1) Dump to the allocated buf
///////////////////////////////////////////////////////////////
// return the buffer on success else NULL
unsigned char * dumpScreenToBuf ( unsigned char *buf, int mode, int x, int y, int w, int h ) ;
unsigned char * dumpScreenToBuf ( unsigned char *buf, int mode ) ;
///////////////////////////////////////////////////////////////
// (2) Dump to a File
///////////////////////////////////////////////////////////////
// return 0 on success else 1 on error
int dumpScreenToFile ( const char *filename, unsigned char *buf, int mode, int x, int y, int w, int h ) ;
int dumpScreenToFile ( const char *filename, unsigned char *buf, int mode ) ;
#endif
|
C | /**************************************************************/
/* Thomas Fox, CS 4352, Client program Due: 4/8/93 */
/* */
/* The client sends a message to the server and then waits */
/* for a reply. The server MSGKEY is fixed in this stage. */
/**************************************************************/
#include <stdio.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <errno.h>
#include "mymsg.h"
/* Two arbitrarily chosen keys. The server-key must be known to
client. Client can then obtain queue-id of the server.
Client's queue-id is passed with request to server.
The keys can be thought of as port number used in TCP/IP protocols. */
#define S_MSGKEY 8987
#define C_MSGKEY 0991
int myqid;
void main()
{
void cleanup(); /* Failure recovery procedure */
int servqid, each;
int msgflag;
int mtype;
MSGTOSERVER to_server;
MSGTOCLIENT to_client;
/* Below shows a very trivial processing in case, the client dies,
because it received a signal. It shows failure handling.*/
for (each = 0; each < 20; each++) /* Kill queue when a signal occurs */
signal (each, cleanup);
/* 0777 | IPC_CREAT denotes no read/write/execute restrictions;
create a queue if one does not exists associated to given KEY. */
msgflag = 0777|IPC_CREAT;
myqid = msgget (C_MSGKEY, msgflag);/* Get own queue */
printf ("client qid = %d\n", myqid); //for debugging
/* Get server's queue-id. Server is supposed to have open queue
before with no restrictions.*/
msgflag = 0777;
servqid = msgget (S_MSGKEY, msgflag);
printf ("server qid = %d\n", servqid);
/* Prepare request message. The data is just the client's q-id. */
to_server.mtype = 1;
to_server.clienttext.code = myqid; /* Any messgae to pass */
/* Client sends a request of message type 1 and awaits to receive
reply of any mtype. mtype = 0 denotes any type.
perror is library function to print error. */
mtype = 0;
msgflag = 0777;
if (msgsnd (servqid, &to_server, sizeof (REQUEST), msgflag) == -1)
{
printf ("Client: Request not sent.\n");
perror (NULL);
}
else
if (msgrcv (myqid, &to_client, sizeof (REPLY), mtype, msgflag) == -1)
{
printf ("Client: Reply not received.\n");
perror (NULL);
}
else
printf ("Client: Sent qid=%d, Received qid=%d\n",
myqid, to_client.servertext.reply);
}
/* This procedure is called automatically, when the process
receives any signals. */
void cleanup () /* Remove queue */
{
msgctl (myqid, IPC_RMID, 0);
exit(0);
}
|
C | #include "binary_trees.h"
/**
* print_num - Prints a number
*
* @n: Number to be printed
*/
void print_num(int n)
{
printf("%d\n", n);
}
|
C | #include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <stdbool.h>
// Bericht ber den Energieverbrauch
// DEBUG
// Energy Consumption(mJ)
// 140,469.360
//
// RELEASE
// Energy Consumption (mJ)
// 59,315.186
#define MIN 10
#define MAX 200
float random_float(const float min, const float max)
{
if (max == min) return min;
else if (min < max) return (max - min) * ((float)rand() / RAND_MAX) + min;
// return 0 if min > max
return 0;
}
int multipy(float *MATRIX_A, float *MATRIX_B, float *MATRIX_C, int N) {
int msec = 0;
clock_t start, finish;
start = clock();
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
// Multiply the row of MATRIX_A by the column of MATRIX_B to get the row of MATRIC_C.
for (int k = 0; k < N; k++) {
MATRIX_C[i * N + j] += MATRIX_A[i * N + k] * MATRIX_B[k * N + j];
}
}
}
finish = clock();
msec = 1000.0 * (finish - start) / CLOCKS_PER_SEC;
return msec;
}
void printMatrixF(float* MATRIX, int N) {
for (int i = 0; i < N; i++) {
printf("\n");
for (int j = 0; j < N; j++) {
printf("\t%f", MATRIX[i * N + j]);
}
printf("\n");
}
}
void initMatrix(float* MATRIX, bool initToZero, int N) {
if (initToZero) {
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
MATRIX[i * N + j] = 0;
}
}
}
else {
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
MATRIX[i * N + j] = random_float(MIN, MAX);
}
}
}
}
// DEBUG
// Function/CallStack CPU Time Clockticks Instructions Retired CPI Rate Retiring Front-End Bound Bad Speculation Back-End Bound Average CPU Frequency Module Function (Full) Source File Start Address
// multipy 7.174s 29,284,200,000 29,026,800, 000 1.009 25.1 % 0.3 % 0.3 % 74.3 % 4.1 GHz mxm_standard.exe multipy MatrixMultiplicationStandard.c 0x411b90
// random_float 0.043s 162,000,000 156,600,000 1.034 33.3 % 16.7 % 66.7 % 0.0 % 3.8 GHz mxm_standard.exe random_float MatrixMultiplicationStandard.c 0x411ea0
// initMatrix 0.005s 27,000,000 28,800,000 0.938 0.0 % 0.0 % 100.0 % 0.0 % 5.8 GHz mxm_standard.exe initMatrix MatrixMultiplicationStandard.c 0x411860
//
// RELEASE
// Function/CallStack CPU Time Clockticks Instructions Retired CPI Rate Retiring Front-End Bound Bad Speculation Back-End Bound Average CPU Frequency Module Function (Full) Source File Start Address
// main 2.456s 10,481,400,000 8, 602, 200, 000 1.218 17.9 % 2.7 % 1.4 % 78.0 % 4.3 GHz mxm_standard.exe main MatrixMultiplicationStandard.c 0x4010f01
// initMatrix 0.017s 57,600,000 99, 000, 000 0.582 0.0 % 0.0 % 0.0 % 100.0 % 3.4 GHz mxm_standard.exe initMatrix MatrixMultiplicationStandard.c 0x401040
void main(void)
{
int N = 1024;
float* MATRIX_A = malloc(N * N * sizeof(float));
float* MATRIX_B = malloc(N * N * sizeof(float));
float* MATRIX_C = malloc(N * N * sizeof(float));
//DATENSTRUKTUR MATRIX_A INITIALISIEREN
initMatrix(MATRIX_A, false, N, N);
//DATENSTRUKTUR MATRIX_A AUSGEBEN
//printf("\n\n Print out of matrix A\n\n");
//printMatrixF(MATRIX_A, N, N);
//printf("\n\n End of A!\n\n");
//_getch();
//DATENSTRUKTUR MATRIX_B INITIALISIEREN
//printf("\n\n Input elements of matrix B\n\n");
initMatrix(MATRIX_B, false, N);
//DATENSTRUKTUR MATRIX_B AUSGEBEN
//printf("\n\n Print out of matrix B\n\n");
//printMatrixF(MATRIX_B, N, N);
//printf("\n\n End of B!\n\n");
//_getch();
//DATENSTRUKTUR MATRIX_C INITIALISIEREN
initMatrix(MATRIX_C, true, N);
// Matrizenmultiplikation
int standard_msec = multipy(MATRIX_A, MATRIX_B, MATRIX_C, N);
//DATENSTRUKTUR MATRIX_C AUSGEBEN
printf("\n\n print out of matrix*matrix product C standard\n\n");
printf("\n\n Execution Time: %d in milliseconds\n\n", standard_msec);
//printMatrixF(MATRIX_C, N);
//_getch();
free(MATRIX_A);
free(MATRIX_B);
free(MATRIX_C);
} |
C | /* Time parser for skim.me
* By Xiang Zhang @ New York University
* Version 0.1, 03/28/2012
*
* Usage: ./dtime [method]
* [method]: 0: GMT
* 1: Local time
* The program accepts input from stdin, and write to stdout
* each row output is: hindex,stamp,sec,min,hour,mday,mon,year,wday,yday,dst
*/
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <mba/csv.h>
#define SC_SUCCESS 0
#define SC_FAILURE 1
#define BUF_SIZE 10240 //Buffer 10K
unsigned char buf[BUF_SIZE];
unsigned char *row[2];
int method;
int parseGMT();
int parseLT();
int main(int argc, char *argv[]){
int ret;
if(argc < 2){
printf("No enough arguments.\n");
return SC_FAILURE;
}
if((method = atoi(argv[1])) != 0 && method != 1){
printf("Invalid arguments.\n");
return SC_FAILURE;
}
switch(method){
case 0:
ret = parseGMT();
break;
case 1:
ret = parseLT();
break;
default:
printf("Invalid method.\n");
return SC_FAILURE;
break;
}
if(ret != SC_SUCCESS){
printf("Parsing failure.\n");
return ret;
}
return 0;
}
int parseGMT(){
struct tm *pt;
time_t stamp;
time_t seconds;
int hindex;
int n;
while((n = csv_row_fread(stdin, buf, BUF_SIZE, row, 2, ',', CSV_TRIM | CSV_QUOTES)) > 0){
hindex = atoi(row[0]);
stamp = atol(row[1]);
seconds = stamp/1000L;
pt = gmtime(&seconds);
printf("%d,%ld,%d,%d,%d,%d,%d,%d,%d,%d,%d\n",hindex,stamp,
pt->tm_sec,pt->tm_min,pt->tm_hour,pt->tm_mday,pt->tm_mon,1900 + pt->tm_year,pt->tm_wday,pt->tm_yday,pt->tm_isdst);
}
return SC_SUCCESS;
}
int parseLT(){
struct tm *pt;
time_t stamp;
time_t seconds;
int hindex;
int n;
while((n = csv_row_fread(stdin, buf, BUF_SIZE, row, 2, ',', CSV_TRIM | CSV_QUOTES)) > 0){
hindex = atoi(row[0]);
stamp = atol(row[1]);
seconds = stamp/1000L;
pt = localtime(&seconds);
printf("%d,%ld,%d,%d,%d,%d,%d,%d,%d,%d,%d\n",hindex,stamp,
pt->tm_sec,pt->tm_min,pt->tm_hour,pt->tm_mday,pt->tm_mon,1900 + pt->tm_year,pt->tm_wday,pt->tm_yday,pt->tm_isdst);
}
return SC_SUCCESS;
}
|
C | #include"Library.h"
void text_add(FILE* f, fpos_t* end) {
printf("Enter your numbers please:\n");
char bufer;
fsetpos(f, &end);
while (1) {
scanf("%c", &bufer);
if (bufer == '\n') {
fprintf(f, "%c", ' ');
fgetpos(f, &end);
break;
}
fprintf(f, "%c", bufer);
}
fgetpos(f, &end);
}
int bin_add(FILE* f) {
int amount, i, num;
printf("Enter the amount of numbers please:\n");
while (1) {
rewind(stdin);
if (!(scanf("%d", &amount)) || amount < 1)
printf("Wrong number!\n"); else break;
}
printf("Please,enter numbers:\n");
for (i = 0; i < amount; i++) {
rewind(stdin);
scanf("%d", &num);
fwrite(&num, sizeof(num), 1, f);
}
return amount;
}
void text_add_1(FILE* f, fpos_t* end, int k, char* arr) {
while (1) {
rewind(stdin);
if ((f = fopen(arr, "a+")) == NULL){
printf("Open error\n");
return 0;
}
else break;
}
fseek(f, 0, 2);
while (k > 0) {
fprintf(f, "%c", ' ');
k--;
}
fgetpos(f, &end);
fclose(f);
}
void text_matches(FILE* f) {
int num, num1;
int kol = 0;
printf("Please,enter a number for match:\n");
rewind(stdin);
scanf_s("%d", &num);
rewind(stdin);
while (!feof(f)) {
fscanf(f, "%d", &num1);
if (feof(f)) {
rewind(stdin);
break;
}
if (num1 == num)
kol++;
}
rewind(stdin);
printf("Amount of matches:%d\n", kol);
}
void bin_matches(FILE* f) {
int num, num1;
int kol = 0;
printf("Please,enter a number for match:\n");
rewind(stdin);
scanf_s("%d", &num);
rewind(stdin);
fseek(f, 0, 0);
while (!feof(f)) {
fread(&num1, sizeof(int), 1, f);
if (feof(f)) {
rewind(stdin);
break;
}
if (num1 == num)
kol++;
}
rewind(stdin);
printf("Amount of matches:%d\n", kol);
}
void text_out(FILE* f, char arr) {
char w;
printf("Your file's content:\n");
rewind(stdin);
fseek(f, 0, 0);
while (!feof(f)) {
fscanf(f, "%c", &w);
if (feof(f))
break;
printf("%c", w);
}
rewind(stdin);
}
void bin_out(FILE* f) {
int w;
fpos_t cur;
printf("Your file's content:\n");
rewind(stdin);
fseek(f, 0, 0);
while (!feof(f)) {
fread(&w, sizeof(int), 1, f);
if (feof(f)) {
rewind(stdin);
break;
}
fgetpos(f, &cur);
printf("%d ", w);
}
rewind(stdin);
printf("\n");
}
void textShift(FILE* f, fpos_t end, fpos_t current, int k, char* arr) {
char space = ' ';
char cur;
int amount = 0;
int first;//number in the end
char sym;
int num,num1;//for the end of shifting
current = 0;
while (1) {
rewind(stdin);
if ((f = fopen(arr, "r+")) == NULL) {
printf("Open error\n");
return 0;
}
else break;
}
while (k > 0) {
fseek(f, -2, 2);
fgetpos(f, &end);
num = end;
num1 = num;
while (end != 0) {
fscanf(f, "%c", &cur);
amount++;
end--;
if (cur == space) {
end += 2;
amount--;
fsetpos(f, &end);
fscanf(f, "%d", &first);
break;
}
fsetpos(f, &end);
}
end--;
fsetpos(f, &end);
current = end - 1;
num = num - current + 1;
while (num > 0) {
fprintf(f, "%c", space);
num--;
}
end = num1;
while (current >= 0) {
fsetpos(f, ¤t);
fscanf(f, "%c", &sym);
current--;
fsetpos(f, &end);
fprintf(f, "%c", sym);
end--;
rewind(stdin);
}
fseek(f, 0, 0);
fprintf(f, "%d", first);
fprintf(f, "%c", space);
k--;
}
fclose(f);
}
void text_shift(FILE* f, fpos_t end, fpos_t cur, int k, char* arr) {
char sym;
char sym1, sym2;
int position = 1;
int num;
while (1) {
rewind(stdin);
if ((f = fopen(arr, "r+")) == NULL){
printf("Open error\n");
return 0;
}
else break;
}
fseek(f, 0, 2);
fgetpos(f, &end);
num = end - k;
cur = (end - k - 1);
end--;
/*printf("Cur==");
fsetpos(f, &cur);
fscanf(f, "%c", &sym1);
printf("%c", sym1);
//for checking start numbers:current and end(the last one)
printf("\nEnd==");
fsetpos(f, &end);
fscanf(f, "%c", &sym2);
printf("%c\n", sym2);*/
fseek(f, 0, 2);
while (num > 0) {
fsetpos(f, &cur);
fscanf(f, "%c", &sym);
cur--;
fsetpos(f, &end);
fprintf(f, "%c", sym);
end--;
num--;
/*printf("%d try:\n", position++); //for checking during the transformation
text_out(f, arr);
printf("\n");*/
rewind(stdin);
}
char space = ' ';//i wanna put spaces(==k) in the beginning of the string after the shift
int num1 = k;
rewind(stdin);
fseek(f, 0, 0);
while (num1 > 0) {
fprintf(f, "%c", space);
num1--;
}
fclose(f);
}
int bin_max(FILE* f) {
int max, current;
rewind(stdin);
fread(&max, sizeof(max), 1, f);
while (!feof(f)) {
fread(¤t, sizeof(int), 1, f);
if (current > max)
max = current;
}
rewind(stdin);
return max;
}
void bin_replace(FILE* f, int max, int amount) {
int current;
int choice;
int kol = 0;
fpos_t cur = 0;
printf("Please,enter a number for change to max one:\n");
while (1) {
rewind(stdin);
if (!scanf("%d", &choice))
printf("Try again\n"); else break;
}
rewind(stdin);
fseek(f, 0, 0);
while (amount > 0) {
fsetpos(f, &cur);
fread(¤t, sizeof(int), 1, f);
if (current == choice) {
fsetpos(f, &cur);
fwrite(&max, sizeof(max), 1, f);
rewind(stdin);
kol++;
}
cur += 4;
amount--;
}
if (kol == 0)
printf("No matches in file for your numbers\n");
}
|
C | #ifndef FUNCIONES_H_INCLUDED
#define FUNCIONES_H_INCLUDED
typedef struct{
char titulo[200];
char genero[200];
int duracion;
char descripcion[300];
int puntaje;
char linkDeImagen[300];
int estado;
}ePelicula;
/** \brief Limpia pantalla.
*/
void fLimpiar();
/** \brief Pide el ingreso y verifica que sea un entero.
*
* \param Mensaje a mostrar.
* \param Mensaje a mostrar si hay un error.
* \param Numero minimo que se puede ingresar.
* \param Numero maximo que se puede ingresar.
* \param Largo maximo que puede llegar a tener el entero ingresado previamente.
* \return Numero ingresado.
*
*/
int getInt(char mensajeamostrar[],char erroramostrar[],int minimo,int maximo,int largoentero);
/** \brief Verifica que lo que se ingrese sea un numero.
*
* \param Dato a validar.
* \param Largo del dato a validar.
* \return Devuelve 1 si el dato es un numero, y 0 si no lo es.
*
*/
int validaNumero(char datoAValidar[],int largoDato);
/** \brief Pide el ingreso y verfica sea de tipo char (sin numeros).
*
* \param Ingreso (dato a validar).
* \param Mensaje a mostrar.
* \param Mensaje a mostrar si hay un error.
* \param Largo maximo que puede llegar a tener el char (sin numeros) ingresado previamente.
*
*/
void getChar(char ingreso[],char mensajeamostrar[],char erroramostrar[],int largoChar);
/** \brief Verifica que lo que se ingrese sea una letra.
*
* \param Dato a validar
* \param Largo del dato a validar.
* \return Devuelve 1 si el dato es una letra, y 0 si no lo es.
*
*/
int validaLetra(char datoAValidar[],int largoDato);
/** \brief Agrega una pelicula en el archivo binario.
*
* \param Pelicula, la estructura a ser agregada en el archivo.
*
*/
void agregarPelicula(ePelicula pelicula);
/** \brief Modifica una pelicula en el archivo binario.
*
* \param Pelicula, la estructura a ser modificada en el archivo.
*
*/
void modificarPelicula(ePelicula pelicula);
/** \brief Elimina una pelicula del archivo binario.
*
* \param Pelicula, la estructura a ser eliminada en el archivo.
*
*/
void borrarPelicula(ePelicula pelicula);
/** \brief Genera el archivo html a partir del archivo binario.
*/
void html();
#endif // FUNCIONES_H_INCLUDED
|
C | #include"Main.h"
void Search_infor1()
{
STU a[10],b,c[10];
int i = 0,n,m=0;//mжǷڸѧ
printf("-------------------\n");
printf("ѧѧ:");
scanf("%s",b.num);
FILE* fp;
fp = fopen("StuInform.txt", "r");
while (1)
{
if (!feof(fp))
{
fread(&a[i], sizeof(STU), 1, fp);
i++;
}
else break;
};
fclose(fp);
fp = fopen("StuInform.txt", "rb");
n = i - 1;
printf(" ༶ ѧ λ \n");
for (int k = 0; k < n; k++)
{
fread(&c[k], sizeof(STU), 1, fp);
if (!strcmp(c[k].num, b.num))
printf("%s %s %s %s %s %d %d\n", c[k].name, c[k].class, c[k].num, c[k].dorm, c[k].bednum, c[k].Report_Repair, c[k].Leave);
break;
m++;
};
if (n == m)
printf("------------------δѧϢ-----------------\n");
fclose(fp);
};
void Search_infor2()
{
STU a[10], b, c[10];
int i = 0, n, m = 0;//mжǷڸѧ
printf("-------------------\n");
printf("ѧ:");
scanf("%s", b.dorm);
FILE* fp;
fp = fopen("StuInform.txt", "r");
while (1)
{
if (!feof(fp))
{
fread(&a[i], sizeof(STU), 1, fp);
i++;
}
else break;
};
fclose(fp);
fp = fopen("StuInform.txt", "rb");
n = i - 1;
printf(" ༶ ѧ λ \n");
for (int k = 0; k < n; k++)
{
fread(&c[k], sizeof(STU), 1, fp);
if (!strcmp(c[k].dorm, b.dorm))
printf("%s %s %s %s %s %d %d\n", c[k].name, c[k].class, c[k].num, c[k].dorm, c[k].bednum, c[k].Report_Repair, c[k].Leave);
else
m++;
};
if (n == m)
printf("------------------δѧϢ-----------------\n");
fclose(fp);
};
void Search_infor3()
{
STU a[10], b, c[10];
int i = 0, n, m = 0;//mжǷڸѧ
printf("-------------------\n");
printf("ѧ༶:");
scanf("%s", b.class);
FILE* fp;
fp = fopen("StuInform.txt", "r");
while (1)
{
if (!feof(fp))
{
fread(&a[i], sizeof(STU), 1, fp);
i++;
}
else break;
};
fclose(fp);
fp = fopen("StuInform.txt", "rb");
n = i - 1;
printf(" ༶ ѧ λ \n");
for (int k = 0; k < n; k++)
{
fread(&c[k], sizeof(STU), 1, fp);
if (!strcmp(c[k].class, b.class))
printf("%s %s %s %s %s %d %d\n", c[k].name, c[k].class, c[k].num, c[k].dorm, c[k].bednum, c[k].Report_Repair, c[k].Leave);
else
m++;
};
if (n == m)
printf("------------------δѧϢ-----------------\n");
fclose(fp);
}; |
C | #include <stdio.h>
int main( void)
{
float a , b , c , max;
printf( "enter 3 sides to know if they can represent a triangle: " );
scanf( "%f%f%f" , &a , &b , &c );
max = a;
if ( b > a ){
max = b;
}
if ( c > max ){
max = c;
}
if ( a + b + c > 2 * max ){
printf( "Yes it can " );
}else{
printf( "No it can't" );
}
}
|
C | #include <stdio.h>
#include <unistd.h>
#include <sys/time.h>
int main() {
struct timeval Arxi;
struct timeval Telos;
gettimeofday(&Arxi, NULL);
gettimeofday(&Telos, NULL);
long int Resta = Telos.tv_usec - Arxi.tv_usec;
printf("%ld\n", resta);
return 0;
}
|
C | #include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <CUnit/Basic.h>
#include "binary_heap.h"
// Useful method to construct and return a node with a given key and name
HeapNode HeapNodeConstructor(int key, char* name)
{
HeapNode hNode;
hNode.key = key;
hNode.item = malloc ((strlen(name) + 1) * sizeof(char));
strcpy(hNode.item, name);
return hNode;
}
void test_create_and_destroy(void)
{
BinaryHeap* bHeap = binary_heap_create(free);
CU_ASSERT_PTR_NOT_NULL(bHeap);
CU_ASSERT_PTR_NULL(bHeap->nodes);
CU_ASSERT(bHeap->size == 0);
binary_heap_destroy(&bHeap);
CU_ASSERT_PTR_NULL(bHeap);
}
void test_heap_manipulation()
{
HeapNode* hNode = NULL;
HeapNode poppedNode;
BinaryHeapCollector collector = free; // use free when deallocating heap items.
BinaryHeap* bHeap = binary_heap_create(collector);
binary_heap_push(&bHeap, HeapNodeConstructor(100, "NodeA")); // 1
binary_heap_push(&bHeap, HeapNodeConstructor(120, "NodeC")); // 2
binary_heap_push(&bHeap, HeapNodeConstructor(90 , "NodeD")); // 3
binary_heap_push(&bHeap, HeapNodeConstructor(95 , "NodeE")); // 4
binary_heap_push(&bHeap, HeapNodeConstructor(110, "NodeF")); // 5
binary_heap_push(&bHeap, HeapNodeConstructor(75 , "NodeG")); // 6
binary_heap_push(&bHeap, HeapNodeConstructor(80 , "NodeH")); // 7
binary_heap_push(&bHeap, HeapNodeConstructor(115, "NodeH")); // 8
binary_heap_push(&bHeap, HeapNodeConstructor(113, "NodeI")); // 9
binary_heap_push(&bHeap, HeapNodeConstructor(116, "NodeJ")); // 10
binary_heap_push(&bHeap, HeapNodeConstructor(60 , "NodeL")); // 11
binary_heap_push(&bHeap, HeapNodeConstructor(74 , "NodeM")); // 12
binary_heap_push(&bHeap, HeapNodeConstructor(73 , "NodeN")); // 13
binary_heap_push(&bHeap, HeapNodeConstructor(70 , "NodeO")); // 14
binary_heap_push(&bHeap, HeapNodeConstructor(130, "NodeP")); // 15
// Assert key/name after push procedures
CU_ASSERT(bHeap->size == 15);
CU_ASSERT(bHeap->nodes[0].key == 130); CU_ASSERT_NSTRING_EQUAL (bHeap->nodes[0].item , "NodeP", strlen("NodeP"));
CU_ASSERT(bHeap->nodes[1].key == 116); CU_ASSERT_NSTRING_EQUAL (bHeap->nodes[1].item , "NodeJ", strlen("NodeJ"));
CU_ASSERT(bHeap->nodes[2].key == 120); CU_ASSERT_NSTRING_EQUAL (bHeap->nodes[2].item , "NodeC", strlen("NodeC"));
CU_ASSERT(bHeap->nodes[3].key == 113); CU_ASSERT_NSTRING_EQUAL (bHeap->nodes[3].item , "NodeI", strlen("NodeI"));
CU_ASSERT(bHeap->nodes[4].key == 115); CU_ASSERT_NSTRING_EQUAL (bHeap->nodes[4].item , "NodeH", strlen("NodeH"));
CU_ASSERT(bHeap->nodes[5].key == 75); CU_ASSERT_NSTRING_EQUAL (bHeap->nodes[5].item , "NodeG", strlen("NodeG"));
CU_ASSERT(bHeap->nodes[6].key == 90); CU_ASSERT_NSTRING_EQUAL (bHeap->nodes[6].item , "NodeD", strlen("NodeD"));
CU_ASSERT(bHeap->nodes[7].key == 95); CU_ASSERT_NSTRING_EQUAL (bHeap->nodes[7].item , "NodeE", strlen("NodeE"));
CU_ASSERT(bHeap->nodes[8].key == 110); CU_ASSERT_NSTRING_EQUAL (bHeap->nodes[8].item , "NodeF", strlen("NodeF"));
CU_ASSERT(bHeap->nodes[9].key == 100); CU_ASSERT_NSTRING_EQUAL (bHeap->nodes[9].item , "NodeA", strlen("NodeA"));
CU_ASSERT(bHeap->nodes[10].key == 60); CU_ASSERT_NSTRING_EQUAL (bHeap->nodes[10].item, "NodeL", strlen("NodeL"));
CU_ASSERT(bHeap->nodes[11].key == 74); CU_ASSERT_NSTRING_EQUAL (bHeap->nodes[11].item, "NodeM", strlen("NodeM"));
CU_ASSERT(bHeap->nodes[12].key == 73); CU_ASSERT_NSTRING_EQUAL (bHeap->nodes[12].item, "NodeN", strlen("NodeN"));
CU_ASSERT(bHeap->nodes[13].key == 70); CU_ASSERT_NSTRING_EQUAL (bHeap->nodes[13].item, "NodeO", strlen("NodeO"));
CU_ASSERT(bHeap->nodes[14].key == 80); CU_ASSERT_NSTRING_EQUAL (bHeap->nodes[14].item, "NodeH", strlen("NodeH"));
// Test peek return
hNode = binary_heap_peek(bHeap);
CU_ASSERT(hNode->key == 130); CU_ASSERT_NSTRING_EQUAL (hNode->item, "NodeP", strlen("NodeP"));
// Test pop return
poppedNode = binary_heap_pop(&bHeap);
CU_ASSERT(poppedNode.key == 130); CU_ASSERT_NSTRING_EQUAL (poppedNode.item, "NodeP", strlen("NodeP"));
// Re-test peek return after pop
hNode = binary_heap_peek(bHeap);
CU_ASSERT(hNode->key == 120); CU_ASSERT_NSTRING_EQUAL (hNode->item, "NodeC", strlen("NodeC"));
// Re-test pop
poppedNode = binary_heap_pop(&bHeap);
CU_ASSERT(poppedNode.key == 120); CU_ASSERT_NSTRING_EQUAL (poppedNode.item, "NodeC", strlen("NodeC"));
for (int i=0; i<4;i++) { // remove 4 element
binary_heap_pop(&bHeap);
}
// Assert key/name after pop procedures
CU_ASSERT(bHeap->size == 9);
CU_ASSERT(bHeap->nodes[0].key == 100); CU_ASSERT_NSTRING_EQUAL (bHeap->nodes[0].item, "NodeA", strlen("NodeA"));
CU_ASSERT(bHeap->nodes[1].key == 95); CU_ASSERT_NSTRING_EQUAL (bHeap->nodes[1].item, "NodeE", strlen("NodeE"));
CU_ASSERT(bHeap->nodes[2].key == 90); CU_ASSERT_NSTRING_EQUAL (bHeap->nodes[2].item, "NodeD", strlen("NodeD"));
CU_ASSERT(bHeap->nodes[3].key == 74); CU_ASSERT_NSTRING_EQUAL (bHeap->nodes[3].item, "NodeM", strlen("NodeM"));
CU_ASSERT(bHeap->nodes[4].key == 70); CU_ASSERT_NSTRING_EQUAL (bHeap->nodes[4].item, "NodeO", strlen("NodeO"));
CU_ASSERT(bHeap->nodes[5].key == 75); CU_ASSERT_NSTRING_EQUAL (bHeap->nodes[5].item, "NodeG", strlen("NodeG"));
CU_ASSERT(bHeap->nodes[6].key == 80); CU_ASSERT_NSTRING_EQUAL (bHeap->nodes[6].item, "NodeH", strlen("NodeH"));
CU_ASSERT(bHeap->nodes[7].key == 60); CU_ASSERT_NSTRING_EQUAL (bHeap->nodes[7].item, "NodeL", strlen("NodeL"));
CU_ASSERT(bHeap->nodes[8].key == 73); CU_ASSERT_NSTRING_EQUAL (bHeap->nodes[8].item, "NodeN", strlen("NodeN"));
for (int i=0; i<8;i++) { // remove 8 element
binary_heap_pop(&bHeap);
}
CU_ASSERT(bHeap->size == 1);
CU_ASSERT(bHeap->nodes[0].key == 60); CU_ASSERT_NSTRING_EQUAL (bHeap->nodes[0].item, "NodeL", strlen("NodeL"));
// Test pop procedure when heap has only 1 element
binary_heap_pop(&bHeap);
CU_ASSERT(bHeap->size == 0);
// Test pop procedure when heap is empty
poppedNode = binary_heap_pop(&bHeap);
CU_ASSERT(bHeap->size == 0);
CU_ASSERT(poppedNode.key == -1);
binary_heap_destroy(&bHeap);
// Test push/peek/size functions with null heap (after destroy being called)
CU_ASSERT(bHeap->size == -1);
CU_ASSERT(binary_heap_push(&bHeap, HeapNodeConstructor(0 , "X")) == -1);
CU_ASSERT_PTR_NULL(binary_heap_peek(bHeap));
}
int main()
{
CU_pSuite pSuite = NULL;
if (CUE_SUCCESS != CU_initialize_registry()) {
return CU_get_error();
}
pSuite = CU_add_suite("BinaryHeap_TestSuite", NULL, NULL);
if (pSuite == NULL)
{
CU_cleanup_registry();
return CU_get_error();
}
if ((CU_add_test(pSuite, "Test binary heap creation and destruction", test_create_and_destroy) == NULL) ||
(CU_add_test(pSuite, "Test binary heap manipulation (pop/push/peek/size)", test_heap_manipulation) == NULL))
{
CU_cleanup_registry();
return CU_get_error();
}
CU_basic_set_mode(CU_BRM_VERBOSE);
CU_basic_run_tests();
CU_cleanup_registry();
return CU_get_error();
}
|
C | #pragma once
bool AND(bool x, bool y) // &
{
return x & y;
}
bool NAND(bool x, bool y) // sheffer, |
{
return !(x & y);
}
bool OR(bool x, bool y) // V
{
return x | y;
}
bool XOR(bool x, bool y) // +
{
return x ^ y;
}
bool NOT(bool x) // ¬, alt + 170
{
return !x;
}
bool NOR(bool x, bool y) // pierce, ↓, alt+25
{
return !(x | y);
}
bool EQ(bool x, bool y) // ~
{
return x == y;
}
bool IMPL(bool x, bool y) // →, alt + 26
{
return x <= y;
}
|
C | #include "mp4.h"
int read_hmhd_box(mp4_bits_t *bs, hmhd_box_t *hmhdbox)
{
hmhdbox->struct_size = hmhdbox->boxheader->struct_size;
hmhdbox->maxPDUsize = mp4_bs_read_u16(bs);
hmhdbox->avgPDUsize = mp4_bs_read_u16(bs);
hmhdbox->maxbitrate = mp4_bs_read_u32(bs);
hmhdbox->avgbitrate = mp4_bs_read_u32(bs);
hmhdbox->reserved = mp4_bs_read_u32(bs);
hmhdbox->struct_size += 16;
return hmhdbox->struct_size;
}
int write_hmhd_box(mp4_bits_t *bs, hmhd_box_t *hmhdbox)
{
uint64_t pos, tail_pos;
pos = mp4_bs_get_position(bs);
hmhdbox->struct_size = write_fullbox_header(bs, hmhdbox->boxheader);
mp4_bs_write_u16(bs, hmhdbox->maxPDUsize);
mp4_bs_write_u16(bs, hmhdbox->avgPDUsize);
mp4_bs_write_u32(bs, hmhdbox->maxbitrate);
mp4_bs_write_u32(bs, hmhdbox->avgbitrate);
mp4_bs_write_u32(bs, hmhdbox->reserved);
hmhdbox->struct_size += 16;
hmhdbox->boxheader->size = hmhdbox->struct_size;
tail_pos = mp4_bs_get_position(bs);
mp4_bs_seek(bs, pos);
mp4_bs_write_u32(bs, hmhdbox->boxheader->size);
mp4_bs_seek(bs, tail_pos);
return hmhdbox->struct_size;
}
int alloc_struct_hmhd_box(hmhd_box_t **hmhdbox)
{
hmhd_box_t * hmhdbox_t = *hmhdbox;
if ((hmhdbox_t = (hmhd_box_t *)calloc(1, sizeof(hmhd_box_t))) == NULL) {
mp4_loge("calloc Failed ");
return 0;
}
alloc_struct_fullbox_header(&(hmhdbox_t->boxheader));
*hmhdbox = hmhdbox_t;
return 1;
}
int free_struct_hmhd_box(hmhd_box_t * hmhdbox)
{
if (hmhdbox) {
if (hmhdbox->boxheader) {
free_struct_fullbox_header(hmhdbox->boxheader);
}
free(hmhdbox);
hmhdbox = NULL;
}
return 1;
}
|
C | #define tipo char
#include "pila.h"
#include <string.h>
typedef long unsigned int size_t;
int main() {
Pila p;
create(&p);
char pala[50];
fgets(pala, 50, stdin);
size_t tam = strlen(pala);
char c;
for(size_t i = 0; i < tam - 1; i++) {
c = pala[i];
//printf("%c %d\n", c, c);
if(c == 40 || c == 91 || c == 123)
push(&p, c);
else {
if(empty(p)) {
c = 0;
break;
}
char aux = front(p);
if(c == 41 && aux == 40)
pop(&p);
else if(c == 93 && aux == 91)
pop(&p);
else if (c == 125 && aux == 123)
pop(&p);
else {
c = 0;
break;
}
}
}
if(!c) {
printf("Cadena no balanceada \n");
return 0;
}
else
printf("Cadena balanceada\n");
return 0;
}
|
C | #include <stdio.h>
int fun(char *restrict x, char *y)
{
char *a = x, *b = y;
*x = 6;
*a = 7;
*y = 8;
*b = 9;
return 0;
}
int main(int argc, char **argv)
{
char a, b;
fun(&a, &b);
fprintf(stdout, "a = %d, a = %d\n", a, b);
return 0;
}
|
C | /* Copyright Statement:
*
*/
#ifndef MP3_WAV_H
#define MP3_WAV_H
#include <stdio.h> /*for FILE pointer*/
/*********************
STRUCTURE
*********************/
struct
{
unsigned char riffheader[4];
unsigned char WAVElen[4];
struct
{
unsigned char fmtheader[8];
unsigned char fmtlen[4];
struct
{
unsigned char FormatTag[2];
unsigned char Channels[2];
unsigned char SamplesPerSec[4];
unsigned char AvgBytesPerSec[4];
unsigned char BlockAlign[2];
unsigned char BitsPerSample[2]; /* format specific for PCM */
} fmt;
struct
{
unsigned char dataheader[4];
unsigned char datalen[4];
/* from here you insert your PCM data */
} data;
} WAVE;
} RIFF =
{ { 'R','I','F','F' } ,{ sizeof(RIFF.WAVE),0,0,0 } ,
{ { 'W','A','V','E','f','m','t',' ' } , { sizeof(RIFF.WAVE.fmt),0,0,0} ,
{ {1,0} , {0,0},{0,0,0,0},{0,0,0,0},{0,0},{16,0} } ,
{ { 'd','a','t','a' } , {0,0,0,0} }
}
};
/*********************
TABLE
*********************/
static int rates[9] = {
44100, 48000, 32000,
22050, 24000, 16000,
11025, 12000, 8000
};
/*********************
SUB_FUNCION
*********************/
static void long2littleendian(long inval,unsigned char *outval,int b)
{
int i;
for(i=0;i<b;i++) {
outval[i] = (inval>>(i*8)) & 0xff;
}
}
int wav_open(int rn, int c, FILE *wavfp)
{
int bps = 16;
long2littleendian(c,RIFF.WAVE.fmt.Channels,sizeof(RIFF.WAVE.fmt.Channels));
long2littleendian(rates[rn],RIFF.WAVE.fmt.SamplesPerSec,sizeof(RIFF.WAVE.fmt.SamplesPerSec));
long2littleendian((int)(c * rates[rn] * bps)>>3, RIFF.WAVE.fmt.AvgBytesPerSec,sizeof(RIFF.WAVE.fmt.AvgBytesPerSec));
long2littleendian((int)(c * bps)>>3, RIFF.WAVE.fmt.BlockAlign,sizeof(RIFF.WAVE.fmt.BlockAlign));
long2littleendian(0,RIFF.WAVE.data.datalen,sizeof(RIFF.WAVE.data.datalen));
long2littleendian(0+sizeof(RIFF.WAVE),RIFF.WAVElen,sizeof(RIFF.WAVElen));
fwrite(&RIFF, sizeof(RIFF),1,wavfp);
return 0;
}
int wav_write(short *buf,int len, FILE *wavfp)
{
int temp;
if(!wavfp)
return 0;
temp = fwrite(buf, 1, len*2, wavfp);
if(temp <= 0)
return 0;
return temp;
}
int wav_close(FILE *wavfp, int datalen)
{
if(!wavfp)
return 0;
if(fseek(wavfp, 0L, SEEK_SET) >= 0) {
long2littleendian(datalen,RIFF.WAVE.data.datalen,sizeof(RIFF.WAVE.data.datalen));
long2littleendian(datalen+sizeof(RIFF.WAVE),RIFF.WAVElen,sizeof(RIFF.WAVElen));
fwrite(&RIFF, sizeof(RIFF),1,wavfp);
}
else {
fprintf(stderr,"Warning can't rewind WAV file. File-format isn't fully conform now.\n");
}
return 0;
}
#endif
|
C | #define _POSIX_C_SOURCE 200112L
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
// esempio di tokenizzazione di stringhe con strtok_r
void tokenizer_r(char *stringa) {
char *tmpstr;
char *token = strtok_r(stringa, " ", &tmpstr);
while (token) {
printf("%s\n", token);
token = strtok_r(NULL, " ", &tmpstr);
}
}
int main(int argc, char *argv[]) {
for(int i=1;i<argc;++i)
tokenizer_r(argv[i]);
return 0;
}
|
C | typedef struct simple_stack {
struct stack_element* top;
} simple_stack;
void stack_init(simple_stack* stack);
void stack_free(simple_stack* stack);
void stack_push(simple_stack* stack, int value);
int stack_pop(simple_stack* stack);
int stack_height(simple_stack* stack);
|
C | //#include <stdio.h>
int twice(int x) {
//fprintf(stderr, "twice(%d)\n", x);
return x * 2;
}
int sum(int x, int y) {
//fprintf(stderr, "sum(%d, %d)\n", x, y);
return x + y;
}
|
C | #include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "redblack-tree.h"
typedef struct
{
long long val;
int num;
int size;
} data_t;
void pushup(redblack_tree_t* tree, redblack_tree_node_t* node)
{
assert(node == tree->nil || ((data_t*)(node->data))->num != 0);
((data_t*)(node->data))->size = ((data_t*)(node->data))->num + ((data_t*)(node->l->data))->size + ((data_t*)(node->r->data))->size;
}
int cmp(const void* a, const void* b)
{
return ((data_t*)a)->val - ((data_t*)b)->val;
}
void Add(long long x, redblack_tree_t* tree)
{
data_t data = { .val = x, .num = 1, .size = 1 };
redblack_tree_node_t* node;
if ((node = rbtree_find(tree, &data)) == tree->nil) {
rbtree_insert(tree, &data);
} else {
((data_t*)(node->data))->num++;
while (node != tree->nil) {
rbtree_node_pushup(tree, node);
node = node->parent;
}
}
}
void Del(long long x, redblack_tree_t* tree)
{
data_t data = { .val = x, .num = 1, .size = 1 };
redblack_tree_node_t *node, *tmp;
node = rbtree_find(tree, &data);
if (((data_t*)(node->data))->num > 1) {
((data_t*)(node->data))->num--;
tmp = node;
while (tmp != tree->nil) {
rbtree_node_pushup(tree, tmp);
tmp = tmp->parent;
}
} else {
rbtree_erase(tree, node);
}
}
int check_tree_size(redblack_tree_t* tree, redblack_tree_node_t* node)
{
if (node == tree->nil)
return 1;
assert(node == tree->nil || node->size == node->l->size + node->r->size + 1);
return check_tree_size(tree, node->l) && check_tree_size(tree, node->r);
}
int check_tree_data(redblack_tree_t* tree, redblack_tree_node_t* node)
{
if (node == tree->nil)
return 1;
assert(((data_t*)(node->data))->size == ((data_t*)(node->data))->num + ((data_t*)(node->l->data))->size + ((data_t*)(node->r->data))->size);
return check_tree_data(tree, node->l) && check_tree_data(tree, node->r);
}
long long Kth(int k, redblack_tree_t* tree)
{
redblack_tree_node_t* now = tree->root;
for (;;) {
if (k <= ((data_t*)(now->l->data))->size) {
now = now->l;
} else {
k -= ((data_t*)(now->l->data))->size;
if (k <= ((data_t*)(now->data))->num) {
return ((data_t*)now->data)->val;
} else {
k -= ((data_t*)(now->data))->num;
now = now->r;
}
}
}
}
int getLessThanNumNode(long long x, redblack_tree_node_t* node, redblack_tree_t* tree)
{
if (node == tree->nil)
return 0;
int ret = 0;
data_t data = { .val = x, .num = 1, .size = 1 };
int flag = tree->cmp(node->data, &data);
if (flag > 0) {
ret = getLessThanNumNode(x, node->l, tree);
} else if (flag < 0) {
ret = ((data_t*)node->l->data)->size + ((data_t*)node->data)->num;
ret += getLessThanNumNode(x, node->r, tree);
} else {
ret = ((data_t*)node->l->data)->size;
}
return ret;
}
int getLessThanNum(long long x, redblack_tree_t* tree)
{
return getLessThanNumNode(x, tree->root, tree);
}
int getGreaterThanNumNode(long long x, redblack_tree_node_t* node, redblack_tree_t* tree)
{
if (node == tree->nil)
return 0;
int ret = 0;
data_t data = { .val = x, .num = 1, .size = 1 };
int flag = tree->cmp(node->data, &data);
if (flag < 0) {
ret = getGreaterThanNumNode(x, node->r, tree);
} else if (flag > 0) {
ret = ((data_t*)node->r->data)->size + ((data_t*)node->data)->num;
ret += getGreaterThanNumNode(x, node->l, tree);
} else {
ret = ((data_t*)node->r->data)->size;
}
return ret;
}
int getGreaterThanNum(long long x, redblack_tree_t* tree)
{
return getGreaterThanNumNode(x, tree->root, tree);
}
long long getMaxLessThan(long long x, redblack_tree_t* tree)
{
data_t data = { .val = x, .num = 1, .size = 1 };
redblack_tree_node_t* node = rbtree_less(tree, &data);
return node == tree->nil ? -1 : ((data_t*)(node->data))->val;
}
long long getMinGreaterThan(long long x, redblack_tree_t* tree)
{
data_t data = { .val = x, .num = 1, .size = 1 };
redblack_tree_node_t* node = rbtree_greater(tree, &data);
return node == tree->nil ? -1 : ((data_t*)(node->data))->val;
}
void dfs_rbtree_node_data_t(redblack_tree_t* tree, redblack_tree_node_t* node)
{
if (node->l != tree->nil) {
assert(node->l->parent == node);
dfs_rbtree_node_data_t(tree, node->l);
}
printf("(%d %lld %d)\n", ((data_t*)(node->data))->num, ((data_t*)(node->data))->val, ((data_t*)(node->data))->size);
if (node->r != tree->nil) {
assert(node->r->parent == node);
dfs_rbtree_node_data_t(tree, node->r);
}
}
int main(void)
{
redblack_tree_t tree = CONSTRUCT_RBTREE(data_t, cmp, pushup);
((data_t*)(tree.nil->data))->size = 0;
((data_t*)(tree.nil->data))->val = 0;
long long n, x, y;
scanf("%lld", &n);
for (int i = 1; i <= n; i++) {
scanf("%lld %lld", &x, &y);
check_tree_size(&tree, tree.root);
check_tree_data(&tree, tree.root);
fprintf(stderr, "[%d] %lld %lld\n", i, x, y);
switch (x) {
case 0:
Add(y, &tree);
break;
case 1:
Del(y, &tree);
break;
case 2:
printf("%lld\n", Kth(y, &tree));
break;
case 3:
printf("%d\n", getLessThanNum(y, &tree));
break;
case 4:
printf("%lld\n", getMaxLessThan(y, &tree));
break;
case 5:
printf("%lld\n", getMinGreaterThan(y, &tree));
break;
}
}
size_t getSiz();
rbtree_free(&tree);
printf("C: %zu\n", getSiz());
return 0;
}
|
C | #define F_CPU 2000000UL
#include <avr/io.h>
#include <util/delay.h>
#include <stdlib.h>
void init(void)
{
// allow power to stabilize
_delay_ms(250);
// port settings
PORTE.DIR = 0xFF;
PORTE.OUT = 0xA5;
return;
}
int main(void)
{
unsigned char c;
init();
// write your code here
while(1)
{
PORTE.OUT = 0xA5 ;
_delay_ms(50);
PORTE.OUT = 0xFF ;
_delay_ms(450);
PORTE.OUT = 0x5A ;
_delay_ms(50);
PORTE.OUT = 0xFF ;
_delay_ms(450);
}
// never die
while(1);
return 0;
}
|
C | /*
* Statemachine2 is table driven.
*/
#include "i2c.h"
#include "mma8541.h"
#include "touchSen.h"
#include <stdio.h>
#include "statemachine1.h"
#include "led.h"
static int Current_state=0;
static int Current_event=0;
typedef enum states2{
sReadXYZ2,
sDisplay2,
sPollSlider2,
sDisconnect2,
nextStatemachine2,
sEnd2
}systemstate;
typedef enum events2{
ePass2,
eFail2,
eDisconnnected2,
eComplete2,
eLeftSlider2,
eRightSlider2,
eTimeout2,
eFinish2
};
void PollSliderHandler(void)
{
Touch_Init();
Init_SysTick();
while(state==sPollSlider)
{
uint16_t touch_val=0;
touch_val=Touch_Scan_LH1();
printf("\nTouch_val has value is %d",touch_val);
if (touch_val>=800 && touch_val<1000)
{
currentevent=eLeftSlider;state=nextStatemachine;Statemachine1();
}
else if(touch_val>1000)
{
currentevent=eRightSlider;state=sEnd;Statemachine1();
}
}
}
typedef void(*functionPointerType)(void);
struct commandStruct{
int *name;
functionPointerType execute;
};
void DisconectHandler(void)
{
state=3;
Statemachine1();
}
void NextSM(void)
{
state=4;
Statemachine1();
}
void EndHandler(void)
{
state=5;
Statemachine1();
}
const struct commandStruct commands[6]= {
{sReadXYZ2, &read_full_xyz},
{sDisplay2, &DisplayXYZ},
{sPollSlider2, &PollSliderHandler},
{sDisconnect2, &DisconectHandler},
{nextStatemachine2, &NextSM},
{sEnd2, &EndHandler},
// {"",0,""} /* End of table indicator */
};
const struct commandStruct *commandPtr = commands;
/* Declare function pointer */
void (*command)(void);
void statemachine2()
{
uint8_t cmdReturn;
for (uint8_t i = 0; i < 6; i++)
{
commandPtr = commands; /* Set ptr back to beginning */
for (uint8_t j = 0; j < 6; j++)
{ /* Iterate through every command */
//if (commandStruct[i].name == commands[j].name)
{
command = commandPtr->execute;
command();
if (cmdReturn)
{ /* error */
Control_RGB_LEDs(1, 0, 0);
} else
{ /* success */
Control_RGB_LEDs(0, 1, 0);
}
}
/* Next pointer element */
commandPtr++;
}
}
}
//systemstate ReadXYZHandler(void)
//{
// printf("inReadXYZ");
// eNewevent=eComplete;
//
// return sDisplay;
//}
//
//systemstate DisplayHandler(void)
//{
// printf("inDisplay");
// eNewevent=eComplete;
// return sPollSlider;
//}
//
//systemstate PollSliderHandler(void)
//{
// printf("inPollSlider");
// return sReadXYZ;
//}
//
//systemstate DisconnectHandler(void)
//{
// printf("inDisconnect");
// return sDisconnect;
//}
//
//systemstate SM1Handler(void)
//{
// printf("inSM!");
// return nextStatemachine;
//}
//
//systemstate EndHandler(void)
//{
// printf("inEnd");
// return sEnd;
//}
//
//void statemachine2(void)
//{
// //printf("\nInside statemachine2");
//
// if(statetable[Current_state][Current_event]==sReadXYZ2)
// { Current_state=sReadXYZ2;
// read_full_xyz();
// printf("\nRead is done");
// Current_state=sDisplay2;
// Current_event=eComplete2;
// statemachine2();
// }
// else if(statetable[Current_state][Current_event]==sDisplay2)
// { Current_state=sDisplay2;
// DisplayXYZ();
// avg_xyz();
// statemachine2();
// }
// else if(statetable[Current_state][Current_event]==sPollSlider2)
// { Current_state=sPollSlider;
// printf("\nPoll Slider");
// statemachine2();
// }
// else if (statetable[Current_state][Current_event]==sEnd2)
// { Current_state=sEnd2;
// state=sEnd; //for statemachine 1
// Statemachine1();
// }
// else if(statetable[Current_state][Current_event]==sDisconnect2)
// {
// Current_state=sDisconnect2;
// state=sDisconnect;
// Statemachine1();
// }
// else
// {
// printf("\nError");
// printf("\nCurrent_State is %d",Current_state);
// printf("\nCurrent_Event is %d",Current_event);
// }
//
//
//}
|
C | #include <stdio.h>
struct stu
{
int num;
char * name;
char sex;
float score;
};
void main()
{
struct stu boy2;
struct stu boy1 = {102, "Zhang Ping", 'M', 78.5};
boy2 = boy1;
printf("Number=%d\nName=%s\n", boy2.num, boy2.name);
printf("Sex=%c\nScore=%.1f\n", boy2.sex, boy2.score);
}
|
C | #include "CD4067.h"
//ʼ
void CD4067Init(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOE, ENABLE);
//DCBA
GPIO_InitStructure.GPIO_Pin = (GPIO_Pin_3|GPIO_Pin_2|GPIO_Pin_1|GPIO_Pin_0);
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(GPIOE, &GPIO_InitStructure);
//INH
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_4;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(GPIOE, &GPIO_InitStructure);
}
//ѡлͨ
//@parameter ch:0-15
void CD4067_SelectChannel(u8 ch)
{
switch (ch)
{
case 0 :GPIO_Write(GPIOE,0x00);break;
case 1 :GPIO_Write(GPIOE,0x01);break;
case 2 :GPIO_Write(GPIOE,0x02);break;
case 3 :GPIO_Write(GPIOE,0x03);break;
case 4 :GPIO_Write(GPIOE,0x04);break;
case 5 :GPIO_Write(GPIOE,0x05);break;
case 6 :GPIO_Write(GPIOE,0x06);break;
case 7 :GPIO_Write(GPIOE,0x07);break;
case 8 :GPIO_Write(GPIOE,0x08);break;
case 9 :GPIO_Write(GPIOE,0x09);break;
case 10:GPIO_Write(GPIOE,0x0a);break;
case 11:GPIO_Write(GPIOE,0x0b);break;
case 12:GPIO_Write(GPIOE,0x0c);break;
case 13:GPIO_Write(GPIOE,0x0d);break;
case 14:GPIO_Write(GPIOE,0x0e);break;
case 15:GPIO_Write(GPIOE,0x0f);break;
default:GPIO_Write(GPIOE,0x10);break;
}
}
//Զлִͨһлһ
void CD4067_AutoRotate(void)
{
static u8 cnt=0;
CD4067_SelectChannel(cnt++);
if(cnt==16)cnt=0;
}
//úûCD4067ײ
extern u16 volatile ADCSample[1];
void CD4067_ADCToBuff(void)
{
static u8 cnt=0;
ADCBuff[cnt++]=ADCSample[0];
// if(cnt==sizeof(ADCBuff))cnt=0;
if(cnt==10)cnt=0;
CD4067_AutoRotate();
}
|
C | #include <unistd.h> //Needed for I2C port
#include <fcntl.h> //Needed for I2C port
#include <sys/ioctl.h> //Needed for I2C port
#include <linux/i2c-dev.h> //Needed for I2C port
#include "smbus.h"
#include "smbus.c"
#include <stdio.h>
#include <stdlib.h>
void main(){
int file;
int adapter_nr = 0; /* probably dynamically determined */
char filename[20];
snprintf(filename, 19, "/dev/i2c-%d", adapter_nr);
file = open(filename, O_RDWR);
if (file < 0) {
/* ERROR HANDLING; you can check errno to see what went wrong */
exit(1);
}
int addr = 0x0c; /* The I2C address */
if (ioctl(file, I2C_SLAVE, addr) < 0) {
/* ERROR HANDLING; you can check errno to see what went wrong */
exit(1);
}
char buf[10];
__u8 st1_reg = 0x10;
__u8 hxl_reg = 0x11;
__u8 hxh_reg = 0x12;
__u8 st2_reg = 0x18;
__u8 cntl2_reg = 0x31;
__u8 cntl3_reg = 0x32;
__u8 st2_res, xl_res, xh_res;
int x_res;
double flux_density;
i2c_smbus_write_byte_data(file, cntl3_reg, 0x01); //write 1 in reset register
i2c_smbus_write_byte_data(file, cntl2_reg, 0x02); //write 2 in control 2 reg, continuous mode
__u8 xl_res_temp = i2c_smbus_read_byte_data(file, hxl_reg);
__u8 xh_res_temp = i2c_smbus_read_byte_data(file, hxh_reg);
printf("All good before the loop sonny\n");
printf("Prelim values for x: 8msb %x 8lsb %x\n", xh_res_temp, xl_res_temp);
while(1){
while( i2c_smbus_read_byte_data(file, st1_reg) != 0x01){
xl_res = i2c_smbus_read_byte_data(file, hxl_reg);
xh_res = i2c_smbus_read_byte_data(file, hxh_reg);
st2_res = i2c_smbus_read_byte_data(file, st2_reg);
if(st2_res == 0b0100){
// //printf("Magnetc sensor overflow (?)\n");
break;
}
if(xl_res != xl_res_temp){
//printf("8msb: %x", xh_res);
//printf(" 8lsb: %x\n", xl_res);
x_res = (xh_res<<8)+xl_res;
if(x_res > 32752){
x_res = x_res-32752;
//printf("reducing negative value\n");
flux_density = -(( (double) x_res/32752)*4912);
}
else{ flux_density = (double) x_res/32752*4912;}
printf("Value being read is %x, flux density of %f\n", x_res, flux_density);
xl_res_temp = xl_res;
xh_res_temp = xh_res;
}
}
}
}
|
C |
int main()
{
int m,n;
int MT[21][21];
int Tx[401],Ty[401],x,y;
int i,j,k=0;
cin>>m>>n;
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)cin>>MT[i][j];
}
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
if(i+1<m && i-1>=0 && j+1<n && j-1>=0)
{
if(MT[i][j]>=MT[i+1][j] && MT[i][j]>=MT[i-1][j] && MT[i][j]>=MT[i][j+1] && MT[i][j]>=MT[i][j-1])
{
Tx[k]=i;
Ty[k]=j;
k++;
}
}
else if(i+1<m && i-1>=0 && j+1<n)
{
if(MT[i][j]>=MT[i+1][j] && MT[i][j]>=MT[i-1][j] && MT[i][j]>=MT[i][j+1])
{
Tx[k]=i;
Ty[k]=j;
k++;
}
}
else if(i+1<m && i-1>=0 && j-1>=0)
{
if(MT[i][j]>=MT[i+1][j] && MT[i][j]>=MT[i-1][j] && MT[i][j]>=MT[i][j-1])
{
Tx[k]=i;
Ty[k]=j;
k++;
}
}
else if(i+1<m && j+1<n && j-1>=0)
{
if(MT[i][j]>=MT[i+1][j] && MT[i][j]>=MT[i][j+1] && MT[i][j]>=MT[i][j-1])
{
Tx[k]=i;
Ty[k]=j;
k++;
}
}
else if(i-1>=0 && j+1<n && j-1>=0)
{
if(MT[i][j]>=MT[i-1][j] && MT[i][j]>=MT[i][j+1] && MT[i][j]>=MT[i][j-1])
{
Tx[k]=i;
Ty[k]=j;
k++;
}
}
else if(i==0 && j==0)
{
if(MT[i][j]>=MT[i+1][j] && MT[i][j]>=MT[i][j+1])
{
Tx[k]=i;
Ty[k]=j;
k++;
}
}
else if(i==0 && j==n-1)
{
if(MT[i][j]>=MT[i+1][j] && MT[i][j]>=MT[i][j-1])
{
Tx[k]=i;
Ty[k]=j;
k++;
}
}
else if(i==m-1 && j==0)
{
if(MT[i][j]>=MT[i-1][j] && MT[i][j]>=MT[i][j+1])
{
Tx[k]=i;
Ty[k]=j;
k++;
}
}
else if(i==m-1 && j==n-1)
{
if(MT[i][j]>=MT[i-1][j] && MT[i][j]>=MT[i][j-1])
{
Tx[k]=i;
Ty[k]=j;
k++;
}
}
}
}
for(i=0;i<k;i++)
{
for(j=0;j<k-i-1;j++)
{
if(Tx[j]>Tx[j+1])
{
x=Tx[j];
Tx[j]=Tx[j+1];
Tx[j+1]=x;
y=Ty[j];
Ty[j]=Ty[j+1];
Ty[j+1]=y;
}
}
}
for(i=0;i<k;i++)
{
for(j=0;j<k-i;j++)
{
if(Tx[j]==Tx[j+1] && Ty[j]>Ty[j+1])
{
y=Ty[j];
Ty[j]=Ty[j+1];
Ty[j+1]=y;
}
}
}
for(i=0;i<k;i++)cout<<Tx[i]<<" "<<Ty[i]<<endl;
return 0;
} |
C |
void rhap(p,n)
int n;
double p[];
{ int i,mm;
double t;
void rsift();
mm=n/2;
for (i=mm-1; i>=0; i--)
rsift(p,i,n-1);
for (i=n-1; i>=1; i--)
{ t=p[0]; p[0]=p[i]; p[i]=t;
rsift(p,0,i-1);
}
return;
}
static void rsift(p,i,n)
int i,n;
double p[];
{ int j;
double t;
t=p[i]; j=2*(i+1)-1;
while (j<=n)
{ if ((j<n)&&(p[j]<p[j+1])) j=j+1;
if (t<p[j])
{ p[i]=p[j]; i=j; j=2*(i+1)-1;}
else j=n+1;
}
p[i]=t;
return;
}
|
C | /*26. If a char is one byte wide, an integer is 2 bytes wide and a long integer is 4 byte wide, then
will the following structure always occupy 7 bytes?*/
struct ex
{
char ch ;
int i ;
long int a ;
}e ;
void main()
{
printf("size of strucure %d",sizeof(e));
}
|
C | #include <stdio.h>
int main(int argc, char *argv[])
{
int v[10], maior_elemento, posicao;
for (int i = 0; i < 10; ++i) {
printf("Digite o %d valor: ", i + 1);
scanf("%d", &v[i]);
}
maior_elemento = v[9];
posicao = 9;
for (int i = 9; i >= 0; --i) {
printf("%d, ", v[i]);
if (maior_elemento < v[i]) {
maior_elemento = v[i];
posicao = i;
}
}
printf("\n");
printf("O maior elemento eh %d na posicao %d\n", maior_elemento, posicao + 1);
return 0;
}
|
C | #include <pthread.h>
#include <stdio.h>
int value = 0;
void *runner(void *param); /* the thread */
int main(int argc, char *argv[])
{
pid t pid;
pthread t tid;
pthread attr t attr;
pid = fork();
if (pid == 0) { /* child process */
pthread attr init(&attr);
pthread create(&tid,&attr,runner,NULL);
pthread join(tid,NULL);
printf("CHILD: value = %d",value); /* LINE C */
}
else if (pid > 0) { /* parent process */
wait(NULL);
printf("PARENT: value = %d",value); /* LINE P */
}
}
void *runner(void *param) {
value = 5;
pthread exit(0);
} |
C | //Own module files
#include "subFunction.h"
#include "CException.h"
#include "OperatorChecker.h"
#include "Token.h"
#include "unity.h"
// Library
#include <string.h>
#include <ctype.h>
#include <stdio.h>
#include <malloc.h>
#define startChar (strO->str[*startColumn])
//#include <assert.h>
//assert( funcName != NULL);
/**
* In the subFunction, the functions there are tool to develop the getToken(...) function.
* Using the createStringObject(...) functions to create a string object element.
* Using the stateTransition(...) functions to identify the tyoe of first character then from initial state go to next state.
* Using the createSubString(...) functions to select the any part of string.
* Eg.
*
* createStringObject(...):
*
* -----------------------
* StringObject ------>|str = "1234"|Index = 0|
* -----------------------
*
* createSubString(...):
* start = 3;
* length = 4
* str = "12312342123"
* ^^^^
* subStr = createSubString(char *str, int start , int length);
* The subStr that contain "1234".
*
* stateTransition(...):
*
* strO->str = "123 1234" strO->str = "ASDSAS"
* ^ ^
*
* currentState ---> integerState; currentState ---> IdentifierState;
*
*
*
* Function:
* StringObject *createStringObject(char *ch);
* char *createSubString(char *str, int start , int length);
* void stateTransition ( StringObject* strO , TokenState *currentState, int* startColumn);
*
* Input:
*
* createStringObject(...):
* ch - store the string from user key in.
*
* createSubString(...):
* str - store the string for user key in.
* start - record the start point for counter of getToken(...) function.
* length - store the length for string that need to form a token
*
* stateTransition(...):
* strO - store the string was typed by user in strO->str.
* - record the transiton times in strO->index.
* - record the start point in strO->startIndex.
* - store the type of newToken when a newToken was created.
* - store a token when a newToken was created.
*
* currentState - record the the current state in getToken(...) function.
* startColumn - record the start point for counter in getToken(...) function.
*
*
* Return:
* createStringObject(...):
* return string object element that has contain the string that typed by user
* createSubString(...):
* return the string that was selected by getToken(...) function.
* stateTransition(...):
* currentState that will be update and change to other state or remain.
*
*/
/***************************createStringObject_Function***************************/
// StringObject *createStringObject(char *str){
// StringObject *strO = malloc(sizeof(StringObject));
// strO->str = str;
// strO->index = 0;
// return strO;
// }
/*****************************stateTransition_Function******************************/
// void stateTransition ( StringObject* strO , TokenState *currentState, int* startColumn){
// if (isdigit(startChar)){
// *currentState = integerState;
// }else if (isalpha(startChar)){
// *currentState = identifierState;
// }else if (startChar == '.'){
// *currentState = decimalPointState;
// }else if (isoperator(startChar)){
// *currentState = operatorState;
// }else if (startChar == '"'){
// *currentState = stringState;
// }else if (startChar == '_' || isalpha(startChar)){
// *currentState = identifierState;
// }else{
// *currentState = unknownState;
// }
// }
/***************************createSubString_Function***************************/
// char *createSubString(char *str, int start , int len){
// char *newStr = malloc(sizeof(char)*(len+1));
// int i = 0;
// int j = start;
// while ( j < (len+start) ){
// newStr[i] = str[j];
// i++;
// j++;
// }
// newStr[i] = 0;
// return newStr;
// }
// 1.throwError("The String Object can't be a NULL\n",ERR_STR_OBJECT_CANNOT_BE_NULL_1);
// 2.throwError("The String can't be a NULL\n",ERR_STR_CANNOT_BE_NULL_1);
// 3.throwError("Can't contain any alphabet\n",ERR_CANNOT_CONTAIN_ALPHA);
// 4.throwError("This is invalid octal integer\n",ERR_INVALID_OCTAL_1);
// 5.throwError("This is invalid Hexdecimal integer\n",ERR_INVALID_HEX_1);
// 6.throwError("End of string without double quote\n",ERR_END_OF_STR_WITHOUT_DOUBLE_QUOTE_1);
// 7.throwError("Can't contain contain two of decimal point in Floating\n",ERR_CANNOT_CONTAIN_TWO_DECIMAL_POINT_IN_A_FLOATING);
// 8.throwError("Behind exponential must be a digit\n",ERR_BEHIND_EXPONENTIAL_MUST_BE_A_DIGIT_1);
// 9.throwError("Can't contain invalid unknown symbol\n",ERR_INVALID_UNKNOWN_SYMBOL);
|
C | #pragma once
#include <cassert>
#include <stdio.h>
#include "Platform.h"
//Include known-size integer files, based on compiler. Some compilers do not have these
//files, so they must be created manually.
#if defined(__GNUC__) || defined(__clang__) || (defined(_MSC_VER) && _MSC_VER >= 1600)
#include <stdint.h>
#elif defined(_MSC_VER)
typedef signed __int8 int8_t;
typedef unsigned __int8 uint8_t;
typedef signed __int16 int16_t;
typedef unsigned __int16 uint16_t;
typedef signed __int32 int32_t;
typedef unsigned __int32 uint32_t;
typedef signed __int64 int64_t;
typedef unsigned __int64 uint64_t;
typedef uint64_t uintptr_t;
typedef int64_t intptr_t;
typedef int16_t wchar_t;
#else
// TODO: Have a better "if all else fails" condition.
//
// Preferably, make all sizes at least big enough for the data size.
// Also, try including C++11 standard types if possible.
//
// List of C++'s standard data sizing rules:
//
// sizeof(char) == 1
// sizeof(char) <= sizeof(short)
// sizeof(short) <= sizeof(int)
// sizeof(int) <= sizeof(long)
// sizeof(long) <= sizeof(long long)
// sizeof(char) * CHAR_BIT >= 8
// sizeof(short) * CHAR_BIT >= 16
// sizeof(int) * CHAR_BIT >= 16
// sizeof(long) * CHAR_BIT >= 32
// sizeof(long long) * CHAR_BIT >= 64
typedef signed char int8_t;
typedef unsigned char uint8_t;
typedef signed short int int16_t;
typedef unsigned short int uint16_t;
typedef signed int int32_t;
typedef unsigned int uint32_t;
typedef long long int64_t;
typedef unsigned long long uint64_t;
typedef uint64_t uintptr_t;
typedef int64_t intptr_t;
typedef int16_t wchar_t;
#endif
typedef uint8_t CHART;
typedef int8_t int8;
typedef int16_t int16;
typedef int32_t int32;
typedef int64_t int64;
typedef uint8_t uint8;
typedef uint16_t uint16;
typedef uint32_t uint32;
typedef uint64_t uint64;
typedef intptr_t intptr;
typedef uintptr_t uintptr;
#ifdef DEBUG
#define assertCheck assert
#else
#define assertCheck (void)
#endif
#ifdef COMPILER_MSVC
#define FORCEINLINE __forceinline
#elif defined(COMPILER_GCC) || defined(COMPILER_CLANG)
#define FORCEINLINE inline __attribute__ ((always_inline))
#else
#define FORCEINLINE inline
#endif
#if __cplusplus < 201103L
#define nullptr NULL
#define CONSTEXPR
#else
#define CONSTEXPR constexpr
#endif
#define NULL_COPY_AND_ASSIGN(T) \
T(const T& other) {(void)other;} \
void operator=(const T& other) { (void)other; }
#define LOG_ERROR "Error"
#define LOG_WARNING "Warning"
#define LOG_TYPE_RENDERER "Renderer"
#define LOG_TYPE_IO "IO"
#define DEBUG_LOG(category, level, message, ...) \
fprintf(stderr, "[%s] ", category); \
fprintf(stderr, "[%s] (%s:%d): ", level, __FILE__, __LINE__); \
fprintf(stderr, message, ##__VA_ARGS__); \
fprintf(stderr, "\n")
#define DEBUG_LOG_TEMP(message, ...) DEBUG_LOG("TEMP", "TEMP", message, ##__VA_ARGS__)
#define DEBUG_LOG_TEMP2(message) DEBUG_LOG("TEMP", "TEMP", "%s", message)
#define ARRAY_SIZE_IN_ELEMENTS(a) (sizeof(a)/sizeof(a[0])) |
C | #include "type.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
symbolTable *initTable(char *token, int line, char *type, node *astPointer){
symbolTable *newnode = (symbolTable *)malloc(sizeof(symbolTable));
newnode->token = (char *)malloc(sizeof(char)*(strlen(token)+1));
strcpy(newnode->token,token);
newnode->line = line;
newnode->type = (char *)malloc(sizeof(char)*(strlen(type)+1));
strcpy(newnode->type,type);
newnode->astPointer = astPointer;
newnode->next = NULL;
return newnode;
}
void insertSymbol(symbolTable *table, char *token, int line, char *type, node *astPointer){
if(table == NULL){
table = initTable(token,line,type,astPointer);
return;
}
symbolTable *aux, *auxNext = table;
while(auxNext != NULL){
aux = auxNext;
auxNext = auxNext->next;
if(auxNext == NULL) break;
}
if(aux == NULL) { printf("ERRO: INSERCAO FALIDA\n"); return;}
symbolTable *newnode = (symbolTable *)malloc(sizeof(symbolTable));
newnode->token = (char *)malloc(sizeof(char)*(strlen(token)+1));
strcpy(newnode->token,token);
newnode->line = line;
newnode->type = (char *)malloc(sizeof(char)*(strlen(type)+1));
strcpy(newnode->type,type);
newnode->astPointer = astPointer;
newnode->next = NULL;
aux->next = newnode;
return;
}
int searchSymbol(symbolTable *table, char *token){
if(table == NULL) return 0;
symbolTable *it,*aux;
while(it != NULL){
if(it == NULL) break;
if(strcmp(it->token,token)){
return 1;
break;
}
it = it->next;
}
return 0;
}
//symbolTable operations end
//symbolTree operations
symbolTree *createScope(char *scope){
symbolTree *newnode = (symbolTree *)malloc(sizeof(symbolTree));
newnode->nChild = 0;
newnode->childs = NULL;
newnode->table = NULL;
return newnode;
}
symbolTree *searchScope(symbolTree *tree, char *scope){
if(tree == NULL) return NULL;
int i;
symbolTree *it, *ret;
ret = NULL;
for(i = 0; i < tree->nChild; i++){
it = &tree->childs[i];
if(strcmp(it->scope,scope)){
ret = it;
}
}
if(ret != NULL) return ret;
for(i = 0; i < tree->nChild; i++){
ret = searchScope(&tree->childs[i],scope);
}
return ret;
}
void insertOnScope(symbolTree *tree,char *scope,char *token, int line, char *type, node *astPointer){
if(tree == NULL){
tree = createScope(scope);
if(token != NULL) insertSymbol(tree->table,token,line,type,astPointer);
return;
}
symbolTree *node = searchScope(tree,scope);
if(node != NULL) insertSymbol(node->table,token,line,type,astPointer);
else{
tree->nChild++;
insertOnScope(&tree->childs[tree->nChild-1],scope,token,line,type,astPointer);
}
return;
}
|
C | #include"stdio.h"
#include"conio.h"
#include"stdlib.h"
#define maxsize 100
typedef char datatype;
typedef struct node
{ datatype data;
int ltag,rtag;
struct node *lchild,*rchild;
}bitree;
bitree *CREATREE(void)
{
datatype ch;
int front,rear;
bitree *root,*s;
bitree *Q[maxsize];
root=NULL;
front=1;rear=0;
ch=getchar();
while(ch!='#')
{
s=NULL;
if(ch!='@')
{
s=malloc(sizeof(bitree));
s->data=ch;s->lchild=NULL;s->rchild=NULL;
}
rear++;Q[rear]=s;
if(rear==1)root=s;
else
{
if(s&&Q[front])
{ if(rear%2==0)Q[front]->lchild=s;
else Q[front]->rchild=s;
}
if(rear%2==1)front++;
}
ch=getchar();
}return root;
}/*CREATREE*/
void in_order(bitree *t,FILE *fp)
{
if(t)
{
in_order(t->lchild,fp);
printf(" %c",t->data);fprintf(fp," %c",t->data);
in_order(t->rchild,fp);
}
}/*in_order*/
void pre_order(bitree *t,FILE *fp)
{ int top;
bitree *s;
bitree *Q[maxsize];
top=0;Q[top]=t;
do
{ fprintf(fp," %c",Q[top]->data);
printf(" %c",Q[top]->data);s=Q[top];top--;
if(s->rchild){top++;Q[top]=s->rchild;}
if(s->lchild){top++;Q[top]=s->lchild;}
}while(top>=0);
}
int big(int a,int b)
{
if(a>b)return a;
return b;
}
int depth_of_tree(bitree *t)
{
int h;
if(!t)h=0;
else {h=big(depth_of_tree(t->lchild),depth_of_tree(t->lchild))+1;}
return h;
}
main()
{
FILE *fp;char ch,preod[20],inod[20];bitree *t,*t_restore;int i=0;
if((fp=fopen("mydata.txt","wt+"))==NULL)
{printf("failed to open file !");getch();exit(1);}
t=CREATREE();
printf("pre_order:");
pre_order(t,fp);
printf("\n in_order:");
fprintf(fp,"\n");
in_order(t,fp);
fprintf(fp,"\n");
printf("\n depth is %d\n",depth_of_tree(t));
rewind(fp);
while((ch=fgetc(fp))!='\n')
{
preod[i]=fgetc(fp);printf(" %c",preod[i]);i++;
}
i=0;
while((ch=fgetc(fp))!='\n')
{
inod[i]=fgetc(fp);printf(" %c",inod[i]);i++;
}
fclose(fp);
getch();
}
|
C | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* links.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: awoimbee <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2019/04/09 19:18:13 by awoimbee #+# #+# */
/* Updated: 2019/05/11 14:46:15 by awoimbee ### ########.fr */
/* */
/* ************************************************************************** */
#include "lem_in.h"
void realloc_links(t_room *hub)
{
uint *new_list;
if (hub->mem_link)
{
hub->mem_link *= REALLOC_COEFF;
if (!(new_list = malloc(sizeof(uint) * hub->mem_link)))
exit_lem_in("Error: malloc in realloc_links\n");
ft_mempcpy(new_list, hub->links, hub->nb_link * sizeof(uint));
free(hub->links);
}
else
{
hub->mem_link = DEFMALLOCMAP;
if (!(new_list = malloc(sizeof(uint) * DEFMALLOCMAP)))
exit_lem_in("Error: malloc in realloc_links\n");
}
hub->links = new_list;
}
void add_link(t_room *hub, const uint linked)
{
if (hub->nb_link == hub->mem_link)
realloc_links(hub);
hub->links[hub->nb_link++] = linked;
}
void display_links(const t_room *hub, const t_graph *g)
{
uint i;
i = 0;
while (i < hub->nb_link)
{
display_room(&g->map.list[hub->links[i++]], g);
}
}
|
C | #include "difference_of_squares.h"
unsigned int sum_of_squares(const unsigned int number)
{
return number * (number + 1) * (2 * number + 1) / 6;
}
unsigned int square_of_sum(const unsigned int number)
{
const unsigned int sumOfNumbersUpToInput = number * (number + 1) / 2;
return sumOfNumbersUpToInput * sumOfNumbersUpToInput;
}
unsigned int difference_of_squares(const unsigned int number)
{
return square_of_sum(number) - sum_of_squares(number);
}
|
C | #include <stdio.h>
int getPairsCount(int arr[], int n, int sum)
{
int i,j,count=0;
for(i=0;i<n;i++)
{
for(j=i+1;j<n;j++)
{
if((arr[i]+arr[j])==sum)
{count++;}
}
}
return count;
}
int main()
{
int i,T, n, k, a[100];
scanf("%d",&T);
while(T--)
{
scanf("%d",&n);
scanf("%d",&k);
for(i=0;i<n;i++)
scanf("%d",&a[i]);
printf("%d\n",getPairsCount(a, n, k));
}
return 0;
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.