language
large_stringclasses 1
value | text
stringlengths 9
2.95M
|
---|---|
C | #include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<unistd.h>
#include<arpa/inet.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<netdb.h>
int main(int argc, char **argv)
{
if(argc<2)
{
printf("[host] [puerto]\n");
return 1;
}
int puerto, conexion;
char buffer[200];
/*
* Estructura -> Informacion Conexion
*/
struct sockaddr_in cliente;
/*
* Estructura -> Informacion Host
*/
struct hostent *servidor;
servidor = gethostbyname(argv[1]);
puerto=(atoi(argv[2]));
if(servidor == NULL)
{
printf("Error\n");
return 1;
}
/*
* Asignacion -> socket
*/
conexion = socket(AF_INET, SOCK_STREAM, 0); //Asignación del socket
/*
* Inicializacion -> 0 en todas las variables
*/
bzero((char *)&cliente, sizeof((char *)&cliente));
cliente.sin_family = AF_INET;
cliente.sin_port = htons(puerto);
bcopy((char *)servidor->h_addr, (char *)&cliente.sin_addr.s_addr, sizeof(servidor->h_length));
/*
* Estableciendo Conexion
*/
if(connect(conexion,(struct sockaddr *)&cliente, sizeof(cliente)) < 0)
{
printf("Error\n");
close(conexion);
return 1;
}
char *a;
int n;
a = inet_ntoa(cliente.sin_addr);
printf("Conexion con -> %s:%d\n", a,htons(cliente.sin_port));
while(1){
send(conexion, "hola", 200, 0);
printf("Mensaje envido \n");
n = recv(conexion, buffer, 200, 0);
if(n < 0)
printf("errr\n");
else
buffer[n]='\0';
printf("Mensaje cliente 1: %s \n", buffer);
sleep(10);
}
return 0;
}
|
C | #include <stdio.h>
#include <stdlib.h>
typedef
struct{
int top;
int size;
int a[1000];
}stack_t;
int isFull(stack_t *s){
if(s->size == s->top)
return 1;
else
return 0;
}
int isEmpty(stack_t *s){
if(s->top == 0)
return 1;
else
return 0;
}
void push(stack_t *s, int ele){
if(isFull(s)){
printf("stack is full\n");
}else{
s->a[s->top++] = ele;
}
}
void pop(stack_t *s){
if(isEmpty(s))
printf("Nothing to pop\n");
else{
printf("Element popped from stack: %d\n", s->a[s->top-1]);
s->a[s->top--] == -1;
}
}
void display(stack_t *s){
if(isEmpty(s))
printf("Stack is Empty\n");
else{
for(int i = 0; i < s->top; i++)
printf("%d ", s->a[i]);
printf("\n");
}
}
int main(){
stack_t s = {0, 10, -1};
for(int i = 0; i < 10; i++){
push(&s, i);
}
display(&s);
printf("length of stack: %d\n", s.top);
pop(&s);
display(&s);
return 0;
} |
C | //#include <stdlib.h>
/*
* File: leds.h
* Author: Fabio WD/Felipe Cabral
*
* Created on 12 de Junho de 2017, 08:48
*/
//
#define LED_ONOFF PIN_D0
#define LED_W_P2 PIN_D1
#define LED_W_P1 PIN_D2
#define LED_YELLOW PIN_D3
#define LED_RED PIN_D4
#define LED_GREEN PIN_D5
#define LED_BLUE PIN_D6
/*
* recebe o endereo da cor que sera
* acendida e pisca por um periodo(delay)
*/
void turn_on_led(int16 color)
{
output_high(color);
delay_ms(300);
output_low(color);
delay_ms(300);
}
/*
*apresenta sequencia de cores para o usurio
*/
void show_sequence(int16 sequence[], int size)
{
for(int i = 0; i < size; i++)
{
turn_on_led(sequence[i]);
}
}
/*
*apresenta sequencia de piscar dos leds para
*quando dois jogadores erram na mesma rodada
*/
void turn_on_led_two_losers()
{
for(int i = 0; i < 2; i++)
{
output_high(LED_W_P2);
output_high(LED_W_P1);
output_high(LED_ONOFF);
delay_ms(200);
output_low(LED_W_P1);
output_low(LED_W_P2);
output_low(LED_ONOFF);
delay_ms(200);
}
}
/*
*apresenta sequencia de piscar dos leds para
*quando os dois chegam ao nivel mximo do jogo sem errar
*/
void turn_on_led_two_winners()
{
for(int i = 0; i < 2; i++)
{
output_high(LED_W_P2);
output_high(LED_W_P1);
delay_ms(100);
output_low(LED_W_P1);
output_low(LED_W_P2);
delay_ms(100);
output_high(LED_W_P1);
output_high(LED_W_P2);
delay_ms(50);
output_low(LED_W_P1);
output_low(LED_W_P2);
delay_ms(50);
output_high(LED_W_P1);
output_high(LED_W_P2);
delay_ms(30);
output_low(LED_W_P1);
output_low(LED_W_P2);
delay_ms(30);
}
output_high(LED_W_P1);
output_high(LED_W_P2);
}
/*
*apresenta sequencia de piscar dos leds para
*quando h um vencedor no jogo
*/
void turn_on_led_winner(int16 player)
{
for(int i = 0; i < 2; i++)
{
output_high(player);
delay_ms(100);
output_low(player);
delay_ms(100);
output_high(player);
delay_ms(50);
output_low(player);
delay_ms(50);
output_high(player);
delay_ms(30);
output_low(player);
delay_ms(30);
}
output_high(player);
}
void turn_on_led_onoff()
{
output_high(LED_ONOFF);
}
void turn_off_led_onoff()
{
output_low(LED_ONOFF);
}
|
C | #include<stdio.h>
#include<stdlib.h>
struct tree{
int data;
struct tree *left;
struct tree *right;
};
struct tree* insert(struct tree* node, int data)
{
if(!node){
node=malloc(sizeof(struct tree));
node->data=data;
node->left=node->right=NULL;
return node;
}
else {
if(data>node->data){
node->right= insert(node->right,data);
return node;
}
else{
node->left= insert(node->left,data);
}
return node;
}
}
printtree(struct tree* node)
{
if(node){
printf("%d",node->data);
}
printtree(node->left);
printtree(node->right);
}
main()
{
int i,n;
struct tree *NODE;
NODE= insert(NODE,5);
NODE= insert(NODE,3);
NODE= insert(NODE,8);
printtree(NODE);
}
|
C | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_atoi_base.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: esivre <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/03/18 09:05:40 by esivre #+# #+# */
/* Updated: 2021/03/21 07:33:20 by esivre ### ########.fr */
/* */
/* ************************************************************************** */
#include <stdio.h>
int ft_size(char *base);
int ft_check_base(char *base, int size_base);
int check_isinbase(char a, char *base);
int ft_atoi_base_nb(char *str, char *base, int size_base, int i);
int ft_atoi_base(char *str, char *base)
{
int i;
int size_base;
int sign;
size_base = ft_size(base);
if (ft_check_base(base, size_base) == 1)
{
i = 0;
sign = 1;
while ((str[i] <= '\r' && str[i] >= '\t') || *str == ' ')
i++;
while (str[i] == '+' || str[i] == '-' )
{
if (str[i] == '-')
sign *= -1;
i++;
}
return (sign * ft_atoi_base_nb(str, base, size_base, i));
}
return (0);
}
int ft_atoi_base_nb(char *str, char *base, int size_base, int i)
{
int resultat;
int position;
resultat = 0;
while (str[i])
{
position = check_isinbase(str[i], base);
if (position == size_base)
return (resultat);
resultat = resultat * size_base + position;
i++;
}
return (resultat);
}
int main(int argc, char **argv)
{
if (argc != 2)
return (0);
printf("%d", ft_atoi_base(argv[1], argv[2]));
return (0);
}
int ft_size(char *base)
{
int i;
i = 0;
while(base[i])
i++;
return (i);
}
int ft_check_base(char *base, int size_base)
{
int i;
int j;
if(size_base < 2)
return (0);
i = 0;
while (i < size_base)
{
if (base[i] == '+' || base[i] == '-')
return (0);
j = i + 1;
while (j < size_base)
{
if (base[i] == base[j])
return (0);
j++;
}
i++;
}
return (1);
}
int check_isinbase(char a, char *base)
{
int i;
i = 0;
while (base[i])
{
if (a == base[i])
return (i);
i++;
}
return (i);
}
|
C | /******************************************************************************
cardtest4.c
Sharon Kuo ([email protected])
CS362-400: Assignment 3
Description: Unit testing for the council room card, as implemented in
councilRoomCard(). Draws 4 cards to the player's hand, adds 1 buy, and each
other player draws 1 card.
******************************************************************************/
#include "dominion.h"
#include "dominion_helpers.h"
#include "rngs.h"
#include <string.h>
#include <stdio.h>
void test_councilRoomCard() {
int seed = 1000;
int numPlayer = 2;
int k[10] = {adventurer, council_room, feast, gardens, mine, remodel, smithy,
village, baron, great_hall}; // set kingdom cards
struct gameState game;
printf("************\nTESTING councilRoomCard():\n************\n");
memset(&game, 23, sizeof(struct gameState)); // clear the game state
initializeGame(numPlayer, k, seed, &game); // initialize new game
// set a 2-player game with identical cards in hand, deck, and discard piles
// have one council room card in each player's hands
game.handCount[0] = 3;
game.discardCount[0] = 3;
game.deckCount[0] = 5;
game.hand[0][0] = council_room;
game.hand[0][1] = copper;
game.hand[0][2] = silver;
game.discard[0][0] = copper;
game.discard[0][1] = copper;
game.discard[0][2] = silver;
game.deck[0][0] = silver;
game.deck[0][1] = silver;
game.deck[0][2] = silver;
game.deck[0][3] = silver;
game.deck[0][4] = silver;
game.handCount[1] = 3;
game.discardCount[1] = 3;
game.deckCount[1] = 5;
game.hand[1][0] = council_room;
game.hand[1][1] = copper;
game.hand[1][2] = silver;
game.discard[1][0] = copper;
game.discard[1][1] = copper;
game.discard[1][2] = silver;
game.deck[1][0] = silver;
game.deck[1][1] = silver;
game.deck[1][2] = silver;
game.deck[1][3] = silver;
game.deck[1][4] = silver;
game.whoseTurn = 0; // set to player 0's turn
game.numBuys = 1;
// play the council room card
int turn1 = cardEffect(council_room, 0, 0, 0, &game, 1, 0);
if (turn1)
printf("FAIL: cardEffect(council_room) returned non-zero value\n");
else
printf("PASS: cardEffect(council_room) returned zero value\n");
// check if player 0 has 4 cards drawn, and council room discarded
if (game.handCount[0] != 6)
printf("FAIL: player 0 did not draw 4 cards; actual hand count is %d\n",
game.handCount[0]);
else
printf("PASS: player 0 drew 4 cards\n");
// check for discarded card for player 0
if (game.discardCount[0] != 4)
printf("FAIL: player 0's discard pile count is not 4; actual discard pile "
"count is %d\n", game.discardCount[0]);
else
printf("PASS: player 0 discarded a card\n");
// check for cards drawn from deck for player 0
if (game.deckCount[0] != 1)
printf("FAIL: player 0's deck is not 1; actual deck count is %d\n",
game.deckCount[0]);
else
printf("PASS: player 0 drew 4 cards from their deck\n");
// check for increased actions
if (game.numBuys != 2)
printf("FAIL: player 0's buys were not incremented by 1; actual "
"action count: %d\n", game.numActions);
else
printf("PASS: player 0's actions incremented by 1\n");
// check if player 1 drew a card
if (game.handCount[1] != 4)
printf("FAIL: player 1 did not draw 1 card; actual hand count is %d\n",
game.handCount[1]);
else
printf("PASS: player 1 drew a card into the hand\n");
if (game.discardCount[1] != 3)
printf("FAIL: player 1's discard count changed; actual discards are %d\n",
game.discardCount[1]);
else
printf("PASS: player 1's discard count is unchanged\n");
if (game.deckCount[1] != 4)
printf("FAIL: player 1 did not draw 1 card; actual deck count is %d\n",
game.deckCount[1]);
else
printf("PASS: player 1's drew a card from the deck\n");
}
int main() {
test_councilRoomCard();
return 0;
}
|
C | /*
* calc.h
* Anirudh Tunoori netid: at813
*/
#ifndef calc_h_included
#define calc_h_included
typedef enum id { binary, hexadecimal, octal, decimal,undefined } identity; //enum identity
struct number_ { //number struct
char* numStr;
int sign;
int value;
char initialForm;
enum id identity;
};
typedef struct number_ NumberN;
//Function definitions:
NumberN* NCreate(char * numStr);
void numDestroy(NumberN* num1, NumberN* num2, char* result);
int dec_octal_binary_ToInt(NumberN *numPtr);
int hexToInt(NumberN *numPtr);
int power(int base, int exponent);
int isBinary(char* num);
int isDecimal(char* num);
int isOctal(char* num);
int isHexadecimal(char* num);
int checkInput(char* argv[]);
int reverse(char* sequence);
int add(int first, int second);
int subtract(int first, int second);
int multiply(int first, int second); //Performs multiplication
char* toBinaryDecimalOctal(int solution, char output);
char* toHexadecimal(int solution);
int checkOutput(NumberN* num1, NumberN* num2, char op, int answer);
#endif
|
C | /*#include <stdio.h>
#include<sys/types.h>
#include<unistd.h>
#include<stdlib.h>
int main()
{
pid_t pid;
pid = fork();
switch(pid){
case 0:
while(1) {
printf ("a background process,childpid:%d,parentpid:%d\n",getpid(),getppid());
sleep(3);
}
case -1:
perror("process creation failed\n");
exit(-1);
default:
printf ("i am parent process,my pid is %d\n",getppid());
exit(0);
}
return 0;
}*/
#include<stdio.h>
#include<sys/types.h>
#include<unistd.h>
int main(int argc, char *argv[], char ** environ )
{
int i;
printf("i am a process image\n");
printf("my_pid=%d,paretpid=%d\n",getpid(),getppid());
printf("uid=%d,gid=%d\n",getuid(),getgid());
for(i=0; i<argc; i++)
printf("argv[%d]:%d\n",argv[i]);
}
|
C | #include <stdio.h>
#include <stdlib.h>
void main()
{
int c, number=0;
char op;
FILE *fp;
if((fp=fopen("test.txt","r"))==NULL)
{
perror("FILE open error");
exit(-1);
}
while(!feof(fp))
{
while((c=fgetc(fp))!=EOF && isdigit(c))
number=10*number+c-'0';
if(c=='\n')
continue;
fprintf(stdout,"operand=>%d\n",number);
number=0;
if(c!=EOF)
{
ungetc(c,fp);
op=fgetc(fp);
fprintf(stdout,"poerator=>%c\n",op);
}
}
fclose(fp);
}
|
C | #include <linux/init.h>
#include <linux/module.h>
#include <linux/device.h>
#include <linux/fs.h>
struct class *hello_class;
struct semaphore sem_open;
struct semaphore sem_read;
struct semaphore sem_write;
int hello_open(struct inode *inode, struct file *filp){
//try to get semaphore sem_open
if(down_trylock(&sem_open)){
printk("device can be open only 2 times");
return -EBUSY;
}
printk("success to get semaphore sem_open\n");
return 0;
}
static ssize_t hello_read(struct file *filp, char __user *buf,
size_t count, loff_t *f_pos){
//try to get semaphore sem_read
down_interruptible(&sem_read);
//critical section code
printk("success to get semaphore sem_read\n");
return 0;
}
static ssize_t hello_write(struct file *filp, const char __user *buf,
size_t count, loff_t *f_pos){
if(down_trylock(&sem_write)){
printk("device is waiting for something\n");
return -EBUSY;
}
printk("Success to get semaphore sem_write\n");
return 0;
}
static long hello_ioctl(struct file *filp, unsigned int cmd, unsigned long arg){
up(&sem_read);
up(&sem_write);
return 0;
}
static int hello_release(struct inode *inode, struct file *filp){
up(&sem_open);
return 0;
}
struct file_operations hello_fops = {
.owner = THIS_MODULE,
.open = hello_open,
.read = hello_read,
.write = hello_write,
.unlocked_ioctl = hello_ioctl,
.release = hello_release,
};
static int hello_init(void){
int ret;
ret = register_chrdev(300, "hello", &hello_fops);
if(ret < 0){
printk("unable to register character device \n");
return ret;
}
hello_class = class_create(THIS_MODULE, "hello");
if(IS_ERR(hello_class)){
printk("hello_class create fail\n");
}
device_create(hello_class, NULL, MKDEV(300,0),NULL, "hello");
printk("hello_init\n");
//initialize semaphore varible
sema_init(&sem_open, 2);
sema_init(&sem_read, 1);
sema_init(&sem_write, 1);
return 0;
}
static void hello_exit(void){
device_destroy(hello_class, MKDEV(300,0));
class_destroy(hello_class);
unregister_chrdev(300,"hello");
printk("hello_exit\n");
}
module_init(hello_init);
module_exit(hello_exit);
MODULE_LICENSE("Dual BSD/GPL");
|
C | #include "memory.h"
#include "stdint.h"
#include "print.h"
#include "global.h"
#include "debug.h"
#include "string.h"
#define PG_SIZE 4096
#define K_HEAP_START 0xc0100000
#define MEM_BITMAP_BASE 0xc009a000
#define PDE_IDX(addr) ((addr & 0xffc00000) >> 22)
#define PTE_IDX(addr) ((addr & 0x003ff000) >> 12)
struct pool {
struct bitmap pool_bitmap;
uint32_t phy_addr_start;
uint32_t pool_size;
};
struct pool kernel_pool, user_pool; /* physical address pool */
struct virtual_addr kernel_vaddr; /* kernel virtual address pool */
static void mem_pool_init(uint32_t all_mem)
{
put_str(" mem_pool_init start\n");
uint32_t page_table_size = PG_SIZE * 256; /* for kernel page table */
uint32_t used_mem = page_table_size + 0x100000; /* reserved for kernel code and data */
uint32_t free_mem = all_mem - used_mem;
uint16_t all_free_pages = free_mem / PG_SIZE;
uint16_t kernel_free_pages = all_free_pages / 2;
uint16_t user_free_pages = all_free_pages - kernel_free_pages;
uint32_t kbm_length = kernel_free_pages / 8;
uint32_t ubm_length = user_free_pages / 8;
uint32_t kp_start = used_mem;
uint32_t up_start = kp_start + kernel_free_pages * PG_SIZE;
kernel_pool.phy_addr_start = kp_start;
user_pool.phy_addr_start = up_start;
kernel_pool.pool_size = kernel_free_pages * PG_SIZE;
user_pool.pool_size = user_free_pages * PG_SIZE;
kernel_pool.pool_bitmap.btmp_bytes_len = kbm_length;
user_pool.pool_bitmap.btmp_bytes_len = ubm_length;
kernel_pool.pool_bitmap.bits = (void*)MEM_BITMAP_BASE;
user_pool.pool_bitmap.bits = (void*)(MEM_BITMAP_BASE + kbm_length);
put_str(" kernel_pool_bitmap_start:");put_int((int)kernel_pool.pool_bitmap.bits);
put_str(" kernel_pool_phy_addr_start:");put_int(kernel_pool.phy_addr_start);
put_str("\n");
put_str(" user_pool_bitmap_start:");put_int((int)user_pool.pool_bitmap.bits);
put_str(" user_pool_phy_addr_start:");put_int(user_pool.phy_addr_start);
put_str("\n");
bitmap_init(&kernel_pool.pool_bitmap);
bitmap_init(&user_pool.pool_bitmap);
kernel_vaddr.vaddr_bitmap.btmp_bytes_len = kbm_length;
kernel_vaddr.vaddr_bitmap.bits = (void*)(MEM_BITMAP_BASE + kbm_length + ubm_length);
kernel_vaddr.vaddr_start = K_HEAP_START;
bitmap_init(&kernel_vaddr.vaddr_bitmap);
put_str(" mem_pool_init done\n");
}
void mem_init() {
put_str("mem_init start\n");
uint32_t mem_bytes_total = (*(uint32_t*)(0xb00));
mem_pool_init(mem_bytes_total);
put_str("mem_init done\n");
}
/* alloc virtual address */
static void* vaddr_get(enum pool_flags pf, uint32_t pg_cnt) {
int vaddr_start = 0, bit_idx_start = -1;
uint32_t cnt = 0;
if (pf == PF_KERNEL) {
bit_idx_start = bitmap_scan(&kernel_vaddr.vaddr_bitmap, pg_cnt);
if (bit_idx_start == -1) {
return NULL;
}
while(cnt < pg_cnt) {
bitmap_set(&kernel_vaddr.vaddr_bitmap, bit_idx_start + cnt++, 1);
}
vaddr_start = kernel_vaddr.vaddr_start + bit_idx_start * PG_SIZE;
} else {
/*TODO, add allocate for user space */
ASSERT(0);
}
return (void*)vaddr_start;
}
/* get pet virtual address first, then add pte index to get pte virtual adddress */
uint32_t* pte_ptr(uint32_t vaddr) {
uint32_t* pte = (uint32_t*)(0xffc00000 + ((vaddr & 0xffc00000) >> 10) + PTE_IDX(vaddr) * 4);
return pte;
}
/*get pdt virtual address first, then add pde index to get pde virtual address */
uint32_t* pde_ptr(uint32_t vaddr) {
uint32_t* pde = (uint32_t*)((0xfffff000) + PDE_IDX(vaddr) * 4);
return pde;
}
/* just get a physical page from m_pool */
static void* palloc(struct pool* m_pool) {
int bit_idx = bitmap_scan(&m_pool->pool_bitmap, 1);
if (bit_idx == -1 ) {
return NULL;
}
bitmap_set(&m_pool->pool_bitmap, bit_idx, 1);
uint32_t page_phyaddr = ((bit_idx * PG_SIZE) + m_pool->phy_addr_start);
return (void*)page_phyaddr;
}
/* add memory map */
static void page_table_add(void* _vaddr, void* _page_phyaddr) {
uint32_t vaddr = (uint32_t)_vaddr, page_phyaddr = (uint32_t)_page_phyaddr;
uint32_t* pde = pde_ptr(vaddr);
uint32_t* pte = pte_ptr(vaddr);
/* check if pdt exist first */
if (*pde & 0x00000001) {
/* TODO
* need bug fix here, when we config kernel page table, we forget to clear page table,
* so sometimes this assert will be hit
*/
ASSERT(!(*pte & 0x00000001));
if (!(*pte & 0x00000001)) {
*pte = (page_phyaddr | PG_US_U | PG_RW_W | PG_P_1); // US=1,RW=1,P=1
} else {
PANIC("pte repeat");
}
} else {
/* alloc pet space first */
uint32_t pde_phyaddr = (uint32_t)palloc(&kernel_pool);
*pde = (pde_phyaddr | PG_US_U | PG_RW_W | PG_P_1);
/* you must clear pet to make sure all pte are invalid */
memset((void*)((int)pte & 0xfffff000), 0, PG_SIZE);
ASSERT(!(*pte & 0x00000001));
*pte = (page_phyaddr | PG_US_U | PG_RW_W | PG_P_1); // US=1,RW=1,P=1
}
}
/* alloc servel pages
* two steps:
* 1. alloc virtual address;
* 2. alloc physical address and add map one by one;
*/
void* malloc_page(enum pool_flags pf, uint32_t pg_cnt) {
ASSERT(pg_cnt > 0 && pg_cnt < 3840);
void* vaddr_start = vaddr_get(pf, pg_cnt);
if (vaddr_start == NULL) {
return NULL;
}
uint32_t vaddr = (uint32_t)vaddr_start, cnt = pg_cnt;
struct pool* mem_pool = pf & PF_KERNEL ? &kernel_pool : &user_pool;
while (cnt-- > 0) {
void* page_phyaddr = palloc(mem_pool);
if (page_phyaddr == NULL) {
/* TODO, you must recycle all alloced physical pages if one of them allocate fail */
ASSERT(0);
return NULL;
}
page_table_add((void*)vaddr, page_phyaddr);
vaddr += PG_SIZE;
}
return vaddr_start;
}
void* get_kernel_pages(uint32_t pg_cnt) {
void* vaddr = malloc_page(PF_KERNEL, pg_cnt);
if (vaddr != NULL) {
memset(vaddr, 0, pg_cnt * PG_SIZE);
}
return vaddr;
} |
C | /*conversion of Cartesian coordinates to Polar Coordinates */
#include<stdio.h>
#include<math.h>
int main(){
double x_abscissa , y_ordinates;
double r,$;
printf("Enter the X (ABSCISSA) : ");
scanf("%lf",&x_abscissa);
printf("Enter the Y (ORDINATES) : ");
scanf("%lf",&y_ordinates);
r=sqrt(x_abscissa*x_abscissa+y_ordinates*y_ordinates);
$=atan(y_ordinates/x_abscissa);
printf("POLAR CORDINATES ARE (%lf,%lf)",r,$);
return 0;
} |
C | #include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
#include <sys/types.h>
typedef struct process {
int at, bt, tat, ct, wt;
} process;
int n; /// number of processes
void FCFS(process p[]) {
int cur = 0; /// Current time
/// We execute in the given order
for (int i = 0; i < n; i++) {
if (cur < p[i].at) cur = p[i].at;
cur += p[i].bt;
/// Process execution starts at cur. As algo is non-preemptive, it will be completed after p[i].burst_time.
p[i].ct = cur;
p[i].tat = p[i].ct - p[i].at;
p[i].wt = p[i].tat - p[i].bt;
}
}
int main() {
scanf("%d", &n);
process p[n];
for (int i = 0; i < n; i++) {
scanf("%d %d", &p[i].at, &p[i].bt);
}
FCFS(p); /// Scheduler uses First come - First served algorithm for execution of processes
/// Let's print metrics table after all processes completed
puts("ID CT TAT WT");
for (int i = 0; i < n; i++) {
printf("%-4d%-4d%-5d%-4d\n", i, p[i].ct, p[i].tat, p[i].wt);
}
/// Counts Average turnaround and waiting time
double avtat = 0.0, avwt = 0.0;
for (int i = 0; i < n; i++) {
avtat += p[i].tat;
avwt += p[i].wt;
}
printf("Average Turnaround time: %.4lf\nAverage Waiting time: %.4lf\n", avtat / n, avwt / n);
}
|
C | /*Car is traveling at a speed of 80 km/hr and a truck is stationed at a distance of 30 mts.
Truck will start moving exactly after 3 second.
If the car driver applies brake now find out whether car will hit the truck or not.
(distance = ((initial velocity + final velocity )/2 ) * time ).*/
#include<stdio.h>
#define initvelocity 80
#define time 3
#define stadistance 30.0
int main()
{
float initvel,distance,finvelocity= 0.0;
initvel = initvelocity * 0.2777778;
distance = (initvel + finvelocity)/2 *time;
if(stadistance > distance)
{
printf("The Car will not hit the truck.\n");
}
else
{
printf("The Car will hit the truck.\n");
}
}
|
C | #include <stdio.h>
#include <math.h>
#include <stdlib.h>
#include <time.h>
char *lines[]={ "3.25 -0.1 3.55 -0.1 0 start",
"3.4 -0.1 3.4 0.5 0 l01",
"3.4 0.5 3.7 0.8",
"3.5 0.6 5.4 0.6 0 l03",
"3.7 0.8 4.1 1.2",
"4.0 1.1 5.6 1.1 0 l04",
"5.6 0.80 5.6 2.2 0 l09",
"4.1 1.2 4.1 1.6 0 l05" ,
"4.1 1.6 4.2 1.7 0 l06" ,
"4.2 1.7 5.8 1.7 0 l07",
"5.6 2.2 5.7 2.3",
"5.7 2.3 5.7 4.6",
"5.7 4.6 5.5 4.8 ",
"5.5 2.8 5.9 2.8 0 cross",
"1.5 2.2 5.4 2.2 0 l08",
"1.7 2.0 1.7 2.4 0 cross",
"5.5 4.8 3.0 4.8",
"3.5 4.6 3.5 5.0 0 cross",
"3.0 4.8 2.3 4.1 255 ",
"2.3 4.1 2.3 3.5 255 ",
"2.3 3.5 3.0 2.8 255 ",
"3.0 2.8 3.0 2.25 255 ",
""};
char *walls[]={"4.0 4.575 4.0 3.25 0 gatewall",
""};
void box(FILE *f,double x,double y,double dx,double dy);
void garage(FILE * f,double x,double y,double dx,double dy);
void gate(FILE *f,double x, double y, double th);
void box1(FILE * f,double x,double y);
int main(int argc, char ** argv){
FILE *linefile, *wallfile;
int i;
time_t t;
srand((unsigned) time(&t));
linefile=fopen("385linev02","w");
if (linefile){
i=0;
while(lines[i]!=""){
fprintf(linefile,"%s\n",lines[i]);
i++;
}
}
wallfile=fopen("385wallv02","w");
if (wallfile){
double x,y;
x=4.2+rand()/(double)RAND_MAX;
printf("%lf \n",x);
i=0;
while(walls[i]!=""){
fprintf(wallfile,"%s\n",walls[i]);
i++;
}
box(wallfile,x,0.45,0.3,0.3);
box1(wallfile,5.6-0.725,1.45);
box(wallfile,5.6-0.25,1.5,0.5,0.4);
garage(wallfile,0.5,1.9,0.8,0.6);
y=3.45+rand()/(double)RAND_MAX/2.0;
gate(wallfile,5.3,y,90);
gate(wallfile,4.0,4.575,90);
gate(wallfile,4.0,2.8,90);
gate(wallfile,2.475,4.625,-45);
gate(wallfile,2.475,2.975,45);
}
return 0;
}
void box(FILE * f,double x,double y,double dx,double dy){
fprintf(f,"%f %f %f %f %d\n",x,y,x, y+dy,0);
fprintf(f,"%f %f %f %f %d\n",x,y+dy,x+dx, y+dy,0);
fprintf(f,"%f %f %f %f %d\n",x,y,x+dx, y,0);
fprintf(f,"%f %f %f %f %d\n",x+dx,y,x+dx, y+dy,0);
}
void garage(FILE * f,double x,double y,double dx,double dy){
fprintf(f,"%f %f %f %f %d\n",x,y,x, y+dy,0);
fprintf(f,"%f %f %f %f %d\n",x,y+dy,x+dx, y+dy,0);
fprintf(f,"%f %f %f %f %d\n",x,y,x+dx, y,0);
fprintf(f,"%f %f %f %f %d\n",x+dx,y-0.2,x+dx, y+dy,0);
}
void gate(FILE *f, double x, double y, double th){
double v1,v2,x1,y1;
v1=(th+135)/180*M_PI;
v2=(th-135)/180*M_PI;
fprintf(f,"%f %f %f %f %d\n",x,y,x+cos(v1)*0.05, y+sin(v1)*0.05,0);
fprintf(f,"%f %f %f %f %d\n",x,y,x+cos(v2)*0.05, y+sin(v2)*0.05,0);
v1=v1-M_PI;
v2=v2-M_PI;
x=x+cos(th/180*M_PI)*0.45;
y=y+ sin(th/180*M_PI)*0.45;
fprintf(f,"%f %f %f %f %d\n",x,y,x+cos(v1)*0.05, y+sin(v1)*0.05,0);
fprintf(f,"%f %f %f %f %d\n",x,y,x+cos(v2)*0.05, y+sin(v2)*0.05,0);
}
void box1(FILE * f,double x,double y){
fprintf(f,"%f %f %f %f %d\n",x,y,x+0.5, y,0);
fprintf(f,"%f %f %f %f %d\n",x+0.95,y,x+1.45, y,0);
fprintf(f,"%f %f %f %f %d\n",x,y+0.5,x+0.5, y+0.5,0);
fprintf(f,"%f %f %f %f %d\n",x+0.95,y+0.5,x+1.45, y+0.5,0);
}
|
C | #include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include "ft_list.h"
void ft_list_foreach_if(t_list *begin_list, void (*f)(void *),
void *data_ref, int (*cmp)());
void my_f(void *data)
{
printf("%s\n", (char*)data);
}
int ft_strcmp(char *s1, char *s2)
{
int c;
c = 0;
while ((*(s1 + c) != '\0') || (*(s2 + c) != '\0'))
{
if (*(s1 + c) != *(s2 + c))
{
return ((unsigned char)(*(s1 + c)) - (unsigned char)(*(s2 + c)));
}
++c;
}
return (0);
}
t_list *ft_list_push_strs(int size, char **strs)
{
t_list *ret;
t_list *tmp;
int cnt;
cnt = 0;
if (size == 0)
return (NULL);
ret = ft_create_elem(NULL);
while (cnt < size)
{
ret->data = *(strs + cnt);
if (cnt != size - 1)
{
tmp = ft_create_elem(NULL);
tmp->next = ret;
ret = tmp;
}
cnt++;
}
return (ret);
}
//reset to original color
void reset()
{
printf("\033[0m");
}
//green
//printf("\t\t\033[0;32mOK\n\n");
//red
//printf("\t\t\033[1;31mKO\n\n");
int main(void)
{
//////////////////////////////////////////////////////
t_list *lst;
//int flag;
char *strs[] = {"Hello","Vvvvvvvvvvvvvvvvvv","Vnimanie, annekdot!","abcd"};
lst = ft_list_push_strs(4, strs);
ft_list_foreach_if(lst, &my_f, strs[2], &ft_strcmp);
ft_list_foreach_if(lst, &my_f, strs[0], &ft_strcmp);
return (0);
}
|
C | #include "types.h"
#include <stdio.h>
#include <stdlib.h>
s_int pop(stack *S);
void push(stack *S, s_int value);
node_t *new_node(s_int val);
void debug_node(node_t *node);
void debug_msg(const char* msg);
int stack_empty(stack *S);
void append(list *L,s_int value);
int remove_val(list *L,s_int value);
s_int pop(stack *S)
{
s_int ret_val;
node_t *aux_node = NULL;
/*Empty Stack*/
if(*S==NULL) return -1;
else{
ret_val=(*S)->value;
aux_node = *S;
*S = (*S)->next;
free(aux_node);
return ret_val;
}
}
void push(stack* S,s_int value)
{
node_t *aux_node;
if(*S==NULL) *S=new_node(value);
else{
aux_node = new_node(value);
aux_node->next = *S;
*S = aux_node;
}
}
int stack_empty(stack *S)
{
if(*S==NULL) return 1;
else return 0;
}
int in_list(list *L,s_int value)
{
node_t *aux_node;
int ret_val=0;
if(stack_empty(L)) return 0;
else
{
aux_node = *L;
while(aux_node!=NULL)
{
if(aux_node->value == value){
ret_val = 1;
break;
}
else{
aux_node = aux_node->next;
}
}
}
return ret_val;
}
void append(list *L, s_int value)
{
push(L,value);
}
int remove_val(list *L, s_int value)
{
node_t *current_node_ptr=NULL;
node_t *aux_next=NULL;
node_t *last_ptr=NULL;
/*Si el valor no se encuentra en la lista*/
if(!in_list(L,value)) return -1;
else{
/*Comenzar a recorrer la lista hasta encontrar el valor*/
current_node_ptr = *L;
if(current_node_ptr->value==value){
*L = (current_node_ptr->next);
free(current_node_ptr);
}else{
while(current_node_ptr->value!=value){
last_ptr = &(*current_node_ptr);
current_node_ptr = current_node_ptr->next;
}
last_ptr->next = current_node_ptr->next;
free(current_node_ptr);
}
}
return 0;
}
node_t *new_node(s_int val)
{
node_t* new;
new = malloc(sizeof(node_t));
new->next = NULL;
new->value = val;
return new;
}
void debug_node(node_t *node)
{
if(node==NULL) printf("Null ptr");
else{
printf("\nNode value: %hd\n",node->value);
if(node->next!=NULL) printf("Previous: %hd\n", node->next->value);
else printf("Previous: NULL\n");
}
}
void debug_list(list *L){
node_t *aux_node_ptr;
if(*L==NULL){
printf("\n L-> NULL \n");
}else{
printf("\n L-> ");
aux_node_ptr = *L;
while(aux_node_ptr!=NULL){
printf("%hd -> ",aux_node_ptr->value);
aux_node_ptr = aux_node_ptr->next;
}
printf("NULL\n");
}
}
void debug_msg(const char* msg){
printf("\nDEBUG: %s\n",msg);
}
|
C | #include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <getopt.h>
#include <unistd.h>
#include <string.h>
#include "kmeans.h"
#include "log.h"
extern struct kmeans_config *kmeans_config;
/**
* Initialize a new config to hold the run configuration set from the command line
*/
struct kmeans_config *new_kmeans_config()
{
struct kmeans_config *new_config = (struct kmeans_config *)malloc(sizeof(struct kmeans_config));
new_config->in_file = NULL;
new_config->out_file = NULL;
new_config->test_file = NULL;
new_config->metrics_file = NULL;
new_config->label = "no-label";
new_config->max_points = MAX_POINTS;
new_config->num_clusters = NUM_CLUSTERS;
new_config->max_iterations = MAX_ITERATIONS;
new_config->num_processors = 1;
return new_config;
}
/**
* Initialize a new metrics to hold the run performance metrics and settings
*/
struct kmeans_metrics *new_kmeans_metrics(struct kmeans_config *config)
{
struct kmeans_metrics *new_metrics = (struct kmeans_metrics *)malloc(sizeof(struct kmeans_metrics));
new_metrics->label = config->label;
new_metrics->max_iterations = config->max_iterations;
new_metrics->num_clusters = config->num_clusters;
new_metrics->total_seconds = 0;
new_metrics->test_result = 0; // zero = no test performed
return new_metrics;
}
/**
* Initialize a new timing object to hold iteration and total times
*/
struct kmeans_timing *new_kmeans_timing()
{
struct kmeans_timing *new_timing = (struct kmeans_timing *)malloc(sizeof(struct kmeans_timing));
new_timing->main_start_time = 0;
new_timing->main_stop_time = 0;
new_timing->iteration_start = 0;
new_timing->iteration_start_assignment = 0;
new_timing->iteration_stop_assignment = 0;
new_timing->iteration_assignment_seconds = 0;
new_timing->iteration_start_centroids = 0;
new_timing->iteration_stop_centroids = 0;
new_timing->iteration_centroids_seconds = 0;
new_timing->accumulated_assignment_seconds = 0;
new_timing->accumulated_centroids_seconds = 0;
new_timing->max_iteration_seconds = 0;
new_timing->elapsed_total_seconds = 0;
new_timing->used_iterations = 0;
return new_timing;
}
void log_usage()
{
fprintf(stderr, "Output logging options:\n");
fprintf(stderr, " -q --quiet fewer output messages\n");
fprintf(stderr, " -z --silent no output messages only the result for metrics\n");
fprintf(stderr, " -v --verbose lots of output messages including full matrices for debugging\n");
fprintf(stderr, " -d --debug debug messages (includes verbose)\n");
fprintf(stderr, " -h print this help and exit\n");
fprintf(stderr, "\n");
}
void kmeans_usage()
{
fprintf(stderr, "Usage: kmeans_<program> [options]\n");
fprintf(stderr, "Options include:\n");
fprintf(stderr, " -f INFILE.CSV to read data points from a file (REQUIRED)\n");
fprintf(stderr, " -k --clusters NUM number of clusters to create (default: %d)\n", NUM_CLUSTERS);
fprintf(stderr, " -n --max-points NUM maximum number of points to read from the input file (default: %d)\n", MAX_POINTS);
fprintf(stderr, " -i --iterations NUM maximum number of iterations to loop over (default: %d)\n", MAX_ITERATIONS);
fprintf(stderr, " -o OUTFILE.CSV to write the resulting clustered points to a file (default is none)\n");
fprintf(stderr, " -t TEST.CSV compare result with TEST.CSV\n");
fprintf(stderr, " -m METRICS.CSV append metrics to this CSV file (creates it if it does not exist)\n");
fprintf(stderr, " -e --proper-distance measure Euclidean proper distance (slow) (defaults to faster square of distance)\n");
fprintf(stderr, " --info for info level messages\n");
fprintf(stderr, " --verbose for extra detail messages\n");
fprintf(stderr, " --warn to suppress all but warning and error messages\n");
fprintf(stderr, " --error to suppress all error messages\n");
fprintf(stderr, " --debug for debug level messages\n");
fprintf(stderr, " --trace for very fine grained debug messages\n");
log_usage();
fprintf(stderr, "\n");
exit(1);
}
char* valid_file(char opt, char *filename)
{
if (access(filename, F_OK ) == -1 ) {
fprintf(stderr, "Error: The option '%c' expects the name of an existing file (cannot find %s)\n", opt, filename);
kmeans_usage();
}
return filename;
}
int valid_count(char opt, char *arg)
{
int value = atoi(arg);
if (value <= 0) {
fprintf(stderr, "Error: The option '%c' expects a counting number (got %s)\n", opt, arg);
kmeans_usage();
}
return value;
}
void validate_config(struct kmeans_config *config)
{
if (config->in_file == NULL || strlen(config->in_file) == 0) {
fprintf(stderr, "ERROR: You must at least provide an input file with -f\n");
kmeans_usage();
}
const char* distance_type = config->proper_distance ? "proper distance" : "relative distance (d^2)";
const char* loop_order_names[] = {"ijk", "ikj", "jki"};
if (IS_DEBUG) {
printf("Config:\n");
printf("Input file : %-10s\n", config->in_file);
printf("Output file : %-10s\n", config->out_file);
printf("Test file : %-10s\n", config->test_file);
printf("Metrics file : %-10s\n", config->metrics_file);
printf("Clusters (k) : %-10d\n", config->num_clusters);
printf("Max Iterations : %-10d\n", config->max_iterations);
printf("Max Points : %-10d\n", config->max_points);
printf("Distance measure : %s\n", distance_type);
printf("\n");
}
}
/**
* Parse command line args and construct a config object
*/
void parse_kmeans_cli(int argc, char *argv[], struct kmeans_config *new_config, enum log_level_t *new_log_level)
{
int opt;
struct option long_options[] = {
{"input", required_argument, NULL, 'f'},
{"output", required_argument, NULL, 'o'},
{"test", required_argument, NULL, 't'},
{"metrics", required_argument, NULL, 'm'},
{"label", required_argument, NULL, 'l'},
{"clusters", required_argument, NULL, 'k'},
{"iterations", required_argument, NULL, 'i'},
{"max-points", required_argument, NULL, 'n'},
{"proper-distance", required_argument, NULL, 'e'},
{"help", required_argument, NULL, 'h'},
// log options
{"error", no_argument, (int *)new_log_level, error},
{"warn", no_argument, (int *)new_log_level, warn},
{"info", no_argument, (int *)new_log_level, info},
{"verbose", no_argument, (int *)new_log_level, verbose},
{"debug", no_argument, (int *)new_log_level, debug},
{"trace", no_argument, (int *)new_log_level, trace},
{NULL, 0, NULL, 0}
};
int option_index = 0;
while((opt = getopt_long(argc, argv, "-o:f:i:k:n:l:t:m:hqdvze" , long_options, &option_index)) != -1)
{
// fprintf(stderr, "FOUND OPT: [%c]\n", opt);
switch(opt) {
case 0:
/* If this option set a flag, do nothing else: the flag is set */
if (long_options[option_index].flag != 0)
break;
// unexpected for now but maybe useful later
printf("Unexpected option %s\n", long_options[option_index].name);
kmeans_usage();
case 'h':
kmeans_usage();
break;
case 'i':
new_config->max_iterations = valid_count(optopt, optarg);
break;
case 'n':
new_config->max_points = valid_count(optopt, optarg);
break;
case 'k':
new_config->num_clusters = valid_count(optopt, optarg);
break;
case 'f':
new_config->in_file = valid_file('f', optarg);
break;
case 'o':
new_config->out_file = optarg;
break;
case 't':
new_config->test_file = optarg;
break;
case 'm':
new_config->metrics_file = optarg;
break;
case 'e':
new_config->proper_distance = true;
break;
case 'l':
new_config->label = optarg;
break;
case ':':
fprintf(stderr, "ERROR: Option %c needs a value\n", optopt);
kmeans_usage();
break;
case '?':
fprintf(stderr, "ERROR: Unknown option: %c\n", optopt);
kmeans_usage();
break;
default:
fprintf(stderr, "ERROR: Unknown option: %c\n", optopt);
}
}
validate_config(new_config);
} |
C | #include <stdio.h>
int main(){
//char* name
char name[255];
int age;
printf("Hello there, what's your name?:\n");
scanf( "%s" , name);
printf("How old are you %s?\n", name);
scanf("%d", &age);
if (age<18){
printf("I'm sorry %s, you need to be 18+ to enter this website\n", name);
}
else{
printf("Welcome %s, we hope you enjoy our site\n", name);
}
return 0;
}
|
C | #include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <netinet/in.h>
#include <net/if.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <ifaddrs.h>
#include <ctype.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/ioctl.h>
#define AC "\x1b[01;36m"
#define AM "\x1b[01;35m"
#define AR "\x1b[0m"
#define AY "\x1b[01;33m"
#define AB "\x1b[01;5m"
#define NUM "\t\x1b[01;36m%d) \x1b[0m"
#define TAB "\t"
#define SPACER " \x1b[01;35m>\x1b[0m "
#define AION "\x1b[01;36mAion\x1b[01;35m>\x1b[0m "
#define BUFSIZE 64
#define PATH "/etc/"
// Converts the file content into a string
// INPUT: Path to the file folder
// OUTPUT: Converted content
char* file_to_string(char* path)
{
char file_path[BUFSIZE];
sprintf(file_path, "%s/aion.tkn", path);
int fd_owner = open(file_path, O_RDONLY);
if (fd_owner < 0) return "Unknown";
char *buffer = malloc (BUFSIZE);
bzero(buffer, BUFSIZE);
read(fd_owner, buffer, BUFSIZE);
close(fd_owner);
buffer[strlen(buffer)-1] = 0;
return (char*) buffer;
}
// Verifies if the string contains only digits or not
// INPUT: String
// OUTPUT: TRUE / FALSE
int validate_number(char *str) {
while (*str) {
if(!isdigit(*str)) return 0;
str++;
}
return 1;
}
// Verifies if the string respect the IPv4 format
// INPUT: String
// OUTPUT: TRUE / FALSE
int validate_ip(char *ip) {
int i, num, dots = 0;
char *ptr;
if (ip == NULL)
return 0;
ptr = strtok(ip, "."); // String explosion
if (ptr == NULL)
return 0;
while (ptr) {
if (!validate_number(ptr)) return 0;
num = atoi(ptr);
if (num >= 0 && num <= 255) {
ptr = strtok(NULL, ".");
if (ptr != NULL) dots++;
} else return 0;
}
if (dots != 3) return 0;
return 1;
}
int main(int argc, char const **argv)
{
printf(AM "_____"AC "/\\\\\\\\\\\\\\\\\\"AM "______________________________________ \n");
printf(" ___"AC "/\\\\\\\\\\\\\\\\\\\\\\\\\\"AM "____________________________________ \n");
printf(" __"AC "/\\\\\\/////////\\\\\\"AM "__"AC "/\\\\\\"AM "_____________________________ \n");
printf(" _"AC "\\/\\\\\\"AM "_______"AC "\\/\\\\\\"AM "_"AC "\\///"AM "______"AC "/\\\\\\\\\\"AM "_____"AC "/\\\\/\\\\\\\\\\\\"AM "___ \n");
printf(" _"AC "\\/\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\"AM "__"AC "/\\\\\\"AM "___"AC "/\\\\\\///\\\\\\"AM "__"AC "\\/\\\\\\////\\\\\\"AM "__ \n");
printf(" _"AC "\\/\\\\\\/////////\\\\\\"AM "_"AC "\\/\\\\\\"AM "__"AC "/\\\\\\"AM "__"AC "\\//\\\\\\"AM "_"AC "\\/\\\\\\"AM "__"AC "\\//\\\\\\"AM "_ \n");
printf(" _"AC "\\/\\\\\\"AM "_______"AC "\\/\\\\\\"AM "_"AC "\\/\\\\\\"AM "_"AC "\\//\\\\\\"AM "__"AC "/\\\\\\"AM "__"AC "\\/\\\\\\"AM "___"AC "\\/\\\\\\"AM "_ \n");
printf(" _"AC "\\/\\\\\\"AM "_______"AC "\\/\\\\\\"AM "_"AC "\\/\\\\\\"AM "__"AC "\\///\\\\\\\\\\/"AM "___"AC "\\/\\\\\\"AM "___"AC "\\/\\\\\\"AM "_ \n");
printf(" _"AC "\\///"AM "________"AC "\\///"AM "__"AC "\\///"AM "_____"AC "\\/////"AM "_____"AC "\\///"AM "____"AC "\\///"AM "__\n" AR);
printf(AY " v1.0.1\n" AR);
printf("\033[31;1;5mWARNING: This is a vulnerable application!\033[0m\n");
printf("\nThis application is made to speed up the configuration of multiple network hosts \n\n");
printf("\nChoose an option: \n");
printf(NUM "Get hostname" TAB TAB NUM "Get IP address\n", 1, 2);
printf(NUM "Change IP address" TAB NUM "Get interfaces\n", 3, 4);
printf(NUM "Exit from Aion" TAB NUM "Reboot\n", 5, 6);
printf(NUM "Shutdown\n\n\n", 7);
char *eptr;
long result;
char option[sizeof(int)];
char buffer[BUFSIZE];
while (1) {
// User input fetching
printf(AION);
gets(option);
result = strtol(option, &eptr, 10);
switch (result) {
case 1: {
// Get hostname
char hostname[BUFSIZE];
hostname[BUFSIZE-1] = '\0';
gethostname(hostname, BUFSIZE-1);
printf(SPACER AC "Hostname: "AR "%s\n", hostname);
} break;
case 2: {
// Get IP address
printf(SPACER AC "Insert the interface name" AR "\n");
printf(SPACER);
gets(buffer);
struct ifaddrs *ifaddr, *ifa;
int family, s;
char host[NI_MAXHOST];
if (getifaddrs(&ifaddr) == -1)
{
perror("getifaddrs");
exit(EXIT_FAILURE);
}
int found = 0;
for (ifa = ifaddr; ifa != NULL; ifa = ifa->ifa_next)
{
if (ifa->ifa_addr == NULL)
continue;
s=getnameinfo(ifa->ifa_addr,sizeof(struct sockaddr_in),host, NI_MAXHOST, NULL, 0, NI_NUMERICHOST);
if((strcmp(ifa->ifa_name,buffer)==0)&&(ifa->ifa_addr->sa_family==AF_INET))
{
found++;
printf(SPACER AC "Address: "AR "%s\n", host);
}
}
if (!found) printf(SPACER AM "Interface not found"AR "\n");
freeifaddrs(ifaddr);
} break;
case 3: {
// Change IP address
printf(SPACER AC "Insert the new IP address" AR " (xxx.xxx.xxx.xxx)\n");
printf(SPACER);
gets(buffer);
if (!validate_ip(buffer)) {
printf(SPACER AM "IP address not valid"AR "\n");
break;
}
char IPaddr[BUFSIZE];
strcpy(IPaddr, buffer);
printf(SPACER AC "Insert mask" AR " (0-32)\n");
printf(SPACER);
gets(buffer);
int mask = atoi(buffer);
if (mask < 0 || mask > 32) {
printf(SPACER AM "Mask not valid"AR "\n");
break;
}
printf(SPACER AC "Insert the interface" AR "\n");
printf(SPACER);
gets(buffer);
char interface[BUFSIZE];
strcpy(interface, buffer);
printf(SPACER AC "Due to safety reasons, insert the root password to apply the changes:" AR "\n");
char psw_o[15];
strcpy(psw_o, file_to_string(PATH));
char psw[15];
int access = 0;
printf(SPACER);
gets(psw);
if (strcmp(psw, psw_o)) {
printf(SPACER AM "Invalid password"AR "\n");
}else{
printf(SPACER AC "Access gained"AR "\n");
access = 1;
}
if(access) {
char cmd[BUFSIZE*20] = "sudo ip flush dev ";
sprintf(cmd, "ip a flush dev %s", interface);
printf("%s\n", cmd);
system(cmd);
sprintf(cmd, "ip a add %s/%d dev %s", IPaddr, mask, interface);
system(cmd);
}
} break;
case 4: {
// Get interfaces list
printf(SPACER AC "Interfaces list" AR "\n");
struct if_nameindex *if_nidxs, *intf;
if_nidxs = if_nameindex();
if ( if_nidxs != NULL )
{
for (intf = if_nidxs; intf->if_index != 0 || intf->if_name != NULL; intf++)
{
printf(SPACER "- %s\n", intf->if_name);
}
if_freenameindex(if_nidxs);
}
} break;
case 5: {
// Exit from Aion
printf(SPACER "Bye!\n");
exit(0);
} break;
case 6: {
// Reboot
system("reboot");
} break;
case 7: {
// Shutdown
system("shutdown now");
} break;
default:
printf("Invalid option\n");
break;
}
}
return 0;
}
|
C | /*
Ce programme produit une PDU-UDP destination du processus
li au port UDP 6545
intervalle de temps calcul alatoirement
*/
#include <netinet/in.h>
#include <netdb.h>
#include <sys/socket.h>
#define PORT 6545
int main( int argc, char **argv)
{
int socketfd;
struct sockaddr_in SADDR;
struct hostent *temp;
char systeme_distant[100];
char donnee[50] ="123456789 123456789 123456789 123456789 123456789";
int dort,i;
printf("Envoi de donnees par UDP vers %s\n",argv[1]);
/* On recupere l adresse IP du systeme distant */
if( !(temp = gethostbyname(argv[1])) )
{
printf(" gethostbyname - %d\n", h_errno);
exit(-1);
}
/* Preparer la socket de communication */
socketfd = socket( AF_INET, SOCK_DGRAM, 0 );
/* Initialisation des champs de la structure */
SADDR.sin_family = AF_INET;
SADDR.sin_port = htons( PORT );
memcpy( &SADDR.sin_addr, temp->h_addr, 4 );
/* Envoi des donnes */
while(1)
{
dort = random()%10;
/* calcule un delai entre 0 et 9 secondes
affiche des points et une etoile pour montrer le delai */
for (i=0;i<dort-1;i++) printf(".");printf("*"); fflush(0);
/* s'endort pour la dure du delai */
sleep(dort);
/* envoie la PDU */
sendto(socketfd, &donnee, 50, 0, (struct sockaddr *)&SADDR, sizeof(SADDR));
}
}
|
C | #include "try.h"
static int val;
/*
* Fonction try qui permet de simuler un setjump
*/
int try(struct ctx_s *p_ctx, func_t *f, int arg)
{
p_ctx->ctx_magic_number = MAGIC_NUMBER;
asm("movl %%esp, %0\n\t" "movl %%ebp, %1"
:"=r"(p_ctx->ctx_esp), "=r"(p_ctx->ctx_ebp));
return f(arg);
}
/*
* Fonction throw qui permet de simuler un longjump
*/
int throw(struct ctx_s *p_ctx, int r)
{
assert(p_ctx->ctx_magic_number == MAGIC_NUMBER);
val = r;
asm("movl %0, %%esp\n\t" "movl %1, %%ebp"
::"r"(p_ctx->ctx_esp), "r"(p_ctx->ctx_ebp));
return val;
}
|
C | #include <stdint.h>
typedef union unichr
{
uint8_t c[2];
uint16_t u;
struct
{
uint16_t uni_l : 5;
uint16_t multibyte_mark : 3;
uint16_t uni_r : 6;
uint16_t multibyte_continue : 2;
};
} unichr;
void utf8_to_cp1251(char *str)
{
for (char *ptr = str; *ptr; ptr++)
{
if ((*ptr & 0xE0) == 0xC0) // utf-8 multibyte seq flag
{
char c = *ptr;
unichr u = { { c, *++ptr } };
u.u = u.uni_l << 6 | u.uni_r; // letter in 11-bit unicode
if (u.u == 0x0451) // latin letter YO
{
u.u = 0xE5; // make it YE
}
else
{
u.u -= 0x0410; // A in unicode
u.u += 0xC0; // A in cp1251
}
*ptr = u.c[0];
}
*str++ = *ptr;
}
*str = 0;
}
|
C | #include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define RESET "\033[0m"
#define RED "\033[31m" /* Red */
typedef struct {
int *array;
size_t used;
size_t size;
} Array;
typedef struct redblack redblack_t;
typedef struct tree_node {
int key; /* κλειδί αναζήτησης */
struct tree_node *l; /* αριστερό παιδί */
struct tree_node *r; /* δεξιό παιδί */
struct tree_node *parent;
short isRed;
} tree_node_t;
struct redblack {
tree_node_t *root; /* ρίζα*/
int nodes; /* πλήθος κόμβων */
int depth; /* βάθος δέντρου */
};
tree_node_t *new_node(struct redblack *tree, int element) {
tree_node_t *new_n = (tree_node_t *)malloc(sizeof *new_n);
if (new_n == NULL)
return NULL;
new_n->isRed = 0;
new_n->key = element;
new_n->l = new_n->r = NULL;
return new_n;
}
void initRedBlack(struct redblack *t, int element) {
t->root = (tree_node_t *)malloc(sizeof(tree_node_t));
t->root->key = element;
t->root->isRed = 0;
t->root->l = NULL;
t->root->r = NULL;
t->root->parent = NULL;
t->nodes = 1;
}
int searchRedBlack(struct redblack *t, int element) {
tree_node_t *node = t->root;
while (node != NULL) {
if (node->key == element) {
return 0;
} else if (node->key > element) {
node = node->l;
} else if (node->key < element) {
node = node->r;
}
}
return 1;
}
tree_node_t *insertToNodeleft(struct redblack *t, tree_node_t *node,
int element) {
if (node->l == NULL) {
node->l = new_node(t, element);
if (node->l != NULL) {
node->l->isRed = 1;
node->l->parent = node;
t->nodes++;
return node->l;
}
}
return NULL;
}
tree_node_t *insertToNoderight(struct redblack *t, tree_node_t *node,
int element) {
if (node->r == NULL) {
node->r = new_node(t, element);
if (node->r != NULL) {
node->r->isRed = 1;
node->r->parent = node;
t->nodes++;
return node->r;
}
}
return NULL;
}
tree_node_t *insertRedBlack(struct redblack *t, tree_node_t *node,
int element) {
if (node->r == NULL && node->l == NULL)
t->depth++;
if (element > node->key) {
if (node->r == NULL)
return insertToNoderight(t, node, element);
else
return insertRedBlack(t, node->r, element);
} else {
if (node->l == NULL)
return insertToNodeleft(t, node, element);
else
return insertRedBlack(t, node->l, element);
}
}
tree_node_t *RightRotation(struct redblack *t, tree_node_t *node) {
if (node != NULL) {
// printf("RightRotation ston komvo %d\n", node->key);
tree_node_t *R = new_node(t, node->key);
//Ενημέρωση του πατέρα
if (node->parent != NULL) {
if ((node->parent->r != NULL) && (node == node->parent->r)) {
node->parent->r = node->l;
}
if ((node->parent->l != NULL) && (node == node->parent->l)) {
node->parent->l = node->l;
}
node->l->parent = node->parent;
} else {
t->root = node->l;
// printf("New root is %d \n", t->root->key);
t->root->isRed = 0;
}
R->isRed = node->isRed = 1;
R->parent = node->l;
if (node->r != NULL) {
R->r = node->r;
R->r->parent = R;
}
if (node->l->r != NULL) {
R->l = node->l->r;
R->l->parent = R;
} else {
R->l = NULL;
}
node = node->l;
node->r = R;
}
return node;
}
tree_node_t *LeftRotation(struct redblack *t, tree_node_t *node) {
if (node != NULL) {
// printf("LeftRotation ston komvo %d\n", node->key);
tree_node_t *L = new_node(t, node->key);
if (node->parent != NULL) {
if ((node->parent->r != NULL) && (node == node->parent->r)) {
node->parent->r = node->r;
}
if ((node->parent->l != NULL) && (node == node->parent->l)) {
node->parent->l = node->r;
}
node->r->parent = node->parent;
} else {
t->root = node->r;
// printf("New root is %d \n", t->root->key);
t->root->isRed = 0;
}
L->isRed = node->isRed = 1;
L->parent = node->r;
if (node->l != NULL) {
L->l = node->l;
L->l->parent = L;
}
if (node->r->l != NULL) {
L->r = node->r->l;
L->r->parent = L;
} else {
L->r = NULL;
}
node = node->r;
node->l = L;
}
return node;
}
int compare(tree_node_t *a, tree_node_t *b) {
if (a == NULL || b == NULL)
return 0;
else if (a == b)
return 1;
return 0;
}
void printRedBlack(struct redblack *t, tree_node_t *node) {
if (node->l != NULL)
printf("/");
else
printf(" ");
if (node->r != NULL)
printf("\\");
else
printf(" ");
// printf("\n");
if (node->l != NULL) {
if (node->l->isRed)
printf(RED);
printf("%d " RESET, node->l->key);
} else
printf("\n ");
if (node->r != NULL) {
if (node->r->isRed)
printf(RED);
printf("%d " RESET, node->r->key);
} else
printf(" ");
if (node->l != NULL) {
if (node->l->l != NULL || node->l->r != NULL) {
printf("\n");
printRedBlack(t, node->l);
}
}
if (node->r != NULL) {
if (node->r->l != NULL || node->r->r != NULL) {
// printf("e ");
printRedBlack(t, node->r);
}
}
}
void repairTree(struct redblack *t, tree_node_t *node) {
// printf("Repair gia ton komvo %d\n", node->key );
tree_node_t *uncle;
if (node->parent == NULL) {
// case1
node->isRed = 0;
t->root = node;
return;
} else if (!node->parent->isRed) {
// printf("case 2\n");
return;
} else if (node->parent->parent != NULL) {
// printf("gp exist\n");
if ((node->parent->parent->r != NULL) &&
(node->parent->parent->l != NULL)) {
// printf("exei duo paidia\n");
if (node->parent->parent->r != node->parent)
uncle = node->parent->parent->r;
else if (node->parent->parent->l != node->parent)
uncle = node->parent->parent->l;
if (uncle->isRed) {
// case3
// printf("ο θείος είναι κοκκινος\n");
uncle->isRed = 0;
node->parent->isRed = 0;
node->parent->parent->isRed = 1;
repairTree(t, node->parent->parent);
} else {
// printf("ο θείος %d είναι μαύρος\n", uncle->key);
if (node->parent->parent->l != NULL &&
compare(node, node->parent->parent->l->r)) {
// printf("o komvos einai l->r\n");
node = LeftRotation(t, node->parent);
node = node->l;
} else if (node->parent->parent->r != NULL &&
compare(node, node->parent->parent->r->l)) {
// printf("o komvos einai r->l\n");
node = RightRotation(t, node->parent);
node = node->r;
} else if (node->parent->parent->r != NULL &&
compare(node, node->parent->parent->r->r)) {
// printf("o komvos einai r->r\n");
node = LeftRotation(t, node->parent);
node->isRed = 0;
return;
} else if (node->parent->parent->l != NULL &&
compare(node, node->parent->parent->l->l)) {
// printf("o komvos einai l->l\n");
node = RightRotation(t, node->parent->parent);
node->isRed = 0;
return;
}
if (node->parent != NULL) {
// printf("o neos komvos exei patera\n");
if (node->parent->parent != NULL) {
// printf("o neos komvos exei pappou!\n");
if (compare(node, node->parent->l))
node = RightRotation(t, node->parent->parent);
else if (compare(node, node->parent->r))
node = LeftRotation(t, node->parent->parent);
node->isRed = 0;
node->parent->isRed = 1;
}
}
}
} else {
// printf("den exei duo paidia\n");
if (node->parent->parent->l != NULL &&
compare(node, node->parent->parent->l->r)) {
// printf("o komvos einai l->r\n");
node = LeftRotation(t, node->parent);
node = node->l;
} else if (node->parent->parent->r != NULL &&
compare(node, node->parent->parent->r->l)) {
// printf("o komvos einai r->l\n");
node = RightRotation(t, node->parent);
node = node->r;
} else if (node->parent->parent->r != NULL &&
compare(node, node->parent->parent->r->r)) {
// printf("o komvos einai r->r\n");
node = LeftRotation(t, node->parent);
node->isRed = 0;
return;
} else if (node->parent->parent->l != NULL &&
compare(node, node->parent->parent->l->l)) {
// printf("o komvos einai l->l\n");
node = RightRotation(t, node->parent->parent);
node->isRed = 0;
return;
}
if (node->parent != NULL) {
// printf("o neos komvos exei patera\n");
if (node->parent->parent != NULL) {
// printf("else o neos komvos exei pappou\n");
if (compare(node, node->parent->l))
node = RightRotation(t, node->parent->parent);
else if (compare(node, node->parent->r))
node = LeftRotation(t, node->parent->parent);
node->isRed = 0;
node->parent->isRed = 1;
}
}
}
}
}
void printTree(struct redblack *t) {
if (t->root->isRed)
printf(RED);
printf("\n%d\n" RESET, t->root->key);
printRedBlack(t, t->root);
}
// A recursive function to do level order traversal
void inorderHelper(tree_node_t *root) {
if (root == NULL)
return;
inorderHelper(root->l);
printf("%d ", root->key);
inorderHelper(root->r);
}
void addtoRedBlack(struct redblack *t, int element) {
if (searchRedBlack(t, element)) {
// printf("Εισαγωγή του %d\n", element);
tree_node_t *node = insertRedBlack(t, t->root, element);
repairTree(t, node);
repairTree(t, t->root);
// printTree(t);
}
}
void save_ints(const char *file_name, struct redblack *tree) {
FILE *file = fopen(file_name, "r");
int i, x = 0;
fscanf(file, "%d", &i);
// printf(".");
x++;
initRedBlack(tree, i);
do {
fscanf(file, "%d", &i);
// printf(".");
addtoRedBlack(tree, i);
tree->root->isRed = 0;
tree->root->parent = NULL;
x++;
} while (!feof(file));
fclose(file);
}
void initArray(Array *a, size_t initialSize) {
a->array = (int *)malloc(initialSize * sizeof(int));
a->used = 0;
a->size = initialSize;
}
void insertArray(Array *a, int element) {
if (a->used == a->size) {
a->size *= 2;
a->array = (int *)realloc(a->array, a->size * sizeof(int));
}
a->array[a->used++] = element;
}
void freeArray(Array *a) {
free(a->array);
a->array = NULL;
a->used = a->size = 0;
}
void save_ints_toArray(const char *file_name, Array *a) {
FILE *file = fopen(file_name, "r");
int i = 0;
do {
fscanf(file, "%d", &i);
insertArray(a, i);
} while (!feof(file));
fclose(file);
}
void merge(Array *arr, int l, int m, int r) {
int i, j, k;
int n1 = m - l + 1;
int n2 = r - m;
int X[n1], Y[n2];
for (i = 0; i < n1; i++)
X[i] = arr->array[l + i];
for (j = 0; j < n2; j++)
Y[j] = arr->array[m + 1 + j];
i = 0;
j = 0;
k = l;
while (i < n1 && j < n2) {
if (X[i] <= Y[j]) {
arr->array[k] = X[i];
i++;
} else {
arr->array[k] = Y[j];
j++;
}
k++;
}
while (i < n1) {
arr->array[k] = X[i];
i++;
k++;
}
while (j < n2) {
arr->array[k] = Y[j];
j++;
k++;
}
}
void mergeSort(Array *arr, int l, int r) {
if (l < r) {
// Το ίδιο με (l+r)/2 αλλά χωρίς υπερχείλιση για μεγάλα l, r
int m = l + (r - l) / 2;
mergeSort(arr, l, m);
mergeSort(arr, m + 1, r);
merge(arr, l, m, r);
}
}
void linearSearch(Array *a, int searching_el) {
for (int i = 0; i < a->used; i++) {
if (searching_el == a->array[i]) {
// printf("Το %d βρέθηκε επιτυχώς στην θέση %d\n", searching_el, i);
return;
}
}
// printf("Το %d δεν βρέθηκε!\n", searching_el);
}
void binarySearch(Array *a, int searching_el) {
int r = a->used - 1;
int l = 0;
int next = (r + l) / 2;
// printf("%d\n", next);
while (next >= 0) {
if (searching_el == a->array[next]) {
// printf("Το %d βρέθηκε επιτυχώς στην θέση %d\n", searching_el, next);
return;
} else if (searching_el > a->array[next]) {
l = next;
} else {
r = next;
}
if (next == (r + l) / 2)
break;
next = (r + l) / 2;
// printf("%d\n", next);
}
// printf("Το %d δεν βρέθηκε!\n", searching_el);
}
void interpolationSearch(Array *a, int searching_el) {
int r = a->used - 1;
int l = 0;
while ((l <= r) && (searching_el >= a->array[l]) &&
(searching_el <= a->array[r])) {
//Πολύ συμαντικό να γίνει casting με double
int next = l +
((double)r - l) * (searching_el - a->array[l]) /
(a->array[r] - a->array[l]);
if (searching_el > a->array[next])
l = next + 1;
else if (searching_el < a->array[next])
r = next - 1;
else {
// printf("Το %d βρέθηκε επιτυχώς στην θέση %d\n", searching_el, next);
return;
}
// printf("(l,r,next) = (%d,%d,%d)\n", l,r,next);
}
// if (searching_el == a->array[l])
// printf("Το %d βρέθηκε επιτυχώς στην θέση %d\n", searching_el, l);
// else
// printf("Το %d δεν βρέθηκε!\n", searching_el);
}
int main(int argc, char *argv[]) {
Array a;
initArray(&a, 1);
save_ints_toArray("integers.txt", &a);
mergeSort(&a, 0, a.used - 1);
struct timespec start, end;
unsigned long long delta_us;
struct redblack t;
clock_gettime(CLOCK_MONOTONIC_RAW, &start);
save_ints("integers.txt", &t);
clock_gettime(CLOCK_MONOTONIC_RAW, &end);
delta_us = (end.tv_sec - start.tv_sec) * 1000000 +
(end.tv_nsec - start.tv_nsec) / 1000;
printf("\nTime for insertions: %llu usec\n", delta_us);
// int step = 1, from = 10, to = 11;
// int step = 1, from = 500000, to = 500001;
// int step = 1, from = 200, to = 2000;
int step = 4, from = 1000, to = 10000;
printf("From %d to %d with step %d\n", from, to, step);
clock_gettime(CLOCK_MONOTONIC_RAW, &start);
for (int i = from; i < to; i += step){
searchRedBlack(&t, i);
}
clock_gettime(CLOCK_MONOTONIC_RAW, &end);
delta_us = (end.tv_sec - start.tv_sec) * 1000000 +
(end.tv_nsec - start.tv_nsec) / 1000;
printf("Time for search with RedBlack: %llu usec\n", delta_us);
clock_gettime(CLOCK_MONOTONIC_RAW, &start);
for (int i = from; i < to; i += step)
linearSearch(&a, i);
clock_gettime(CLOCK_MONOTONIC_RAW, &end);
delta_us = (end.tv_sec - start.tv_sec) * 1000000 +
(end.tv_nsec - start.tv_nsec) / 1000;
printf("Time for search with linearSearch: %llu usec\n", delta_us);
clock_gettime(CLOCK_MONOTONIC_RAW, &start);
for (int i = from; i < to; i += step)
binarySearch(&a, i);
clock_gettime(CLOCK_MONOTONIC_RAW, &end);
delta_us = (end.tv_sec - start.tv_sec) * 1000000 +
(end.tv_nsec - start.tv_nsec) / 1000;
printf("Time for search with binarySearch: %llu usec\n", delta_us);
clock_gettime(CLOCK_MONOTONIC_RAW, &start);
for (int i = from; i < to; i += step)
interpolationSearch(&a, i);
clock_gettime(CLOCK_MONOTONIC_RAW, &end);
delta_us = (end.tv_sec - start.tv_sec) * 1000000 +
(end.tv_nsec - start.tv_nsec) / 1000;
printf("Time for search with interpolationSearch: %llu usec\n", delta_us);
freeArray(&a);
return 0;
}
|
C | #include <stdio.h>
#include "holberton.h"
/**
* print_to_98 - prints all natural numbers from n to 98
* @n: Integer
* Description: prints all natural numbers from n to 98
*
* Return: 0
*/
void print_to_98(int n)
{
int g = n;
if (n > 98)
{
for ( ; g >= 98; g--)
{
printf("%d", g);
if (g != 98)
printf(", ");
}
}
else if (n < 98)
{
for ( ; g <= 98; g++)
{
printf("%d", g);
if (g != 98)
printf(", ");
}
}
else
printf("%d", g);
printf("\n");
}
|
C | #include <stdio.h>
/*
Ģ : + - * / %
*/
int main(){
// 2 Է
int n1, n2;
int result = 0;
printf(" ΰ Է : ");
scanf_s("%d %d",&n1,&n2);
result = n1 + n2;// result
printf(" : %d\n",result);
//
result = n1 - n2;
printf(" : %d\n",result);
//
result = n1 * n2;
printf(" : %d\n",result);
// -
result = n1 / n2;
printf("() : %d\n",result);
// -
result = n1 % n2;
printf("() : %d\n",result);
return 0;
}
|
C | #include <stdio.h>
#include "header.h"
int main(){
int nr=-1, nc, i,j,n=1,tmp_b,tmp_h,tmp_area, A[MAX_R][MAX_C];
leggiMatrice(A,MAX_R,&nr,&nc);
if(nr==-1)return -1;
for(i=0;i<nr;i++)
for(j=0;j<nc;j++)
if (riconosciRegione(A, nr, nc, i, j, &tmp_b, &tmp_h)){
tmp_area = tmp_b * tmp_h;
printf("Regione %d: estr. sup. SX = <%d,%d> b=%d, h=%d, Area=%d\n", n++, i, j, tmp_b, tmp_h, tmp_area);
}
return 0;
} |
C | #ifndef OCNUMPYTOOLS_H_
// A few helper functions/defines for help for dealing with Numeric
// (Python Numeric)
#include "ocport.h"
OC_BEGIN_NAMESPACE
// Convert from a Val tag to a Python Numeric Tab
inline const char* OCTagToNumPy (char tag, bool supports_cx_int=false)
{
switch (tag) {
case 's': return "int8"; break;
case 'S': return "uint8"; break;
case 'i': return "int16"; break;
case 'I': return "uint16"; break;
case 'l': return "int32"; break;
case 'L': return "uint32"; break;
case 'x': return "int64"; break;
case 'X': return "uint64"; break;
case 'b': return "bool"; break;
case 'f': return "float32"; break;
case 'd': return "float64"; break;
case 'F': return "complex64"; break;
case 'D': return "complex128"; break;
default:
if (supports_cx_int) {
switch (tag) {
case 'c': return "complexint8"; break;
case 'C': return "complexuint8"; break;
case 'e': return "complexint16"; break;
case 'E': return "complexuint16"; break;
case 'g': return "complexint32"; break;
case 'G': return "complexuint32"; break;
case 'h': return "complexint64"; break;
case 'H': return "complexuint64"; break;
default: break;
}
}
throw runtime_error("No corresponding NumPy type for Val type");
}
return 0;
}
// Convert from Numeric tag to OC Tag
inline char NumPyStringToOC (const char* tag, bool supports_cx_int=false)
{
char ret = '*';
if (tag==NULL || tag[0]=='\0') {
throw runtime_error("No corresponding OC tag for NumPy tag");
}
typedef AVLHashT<string, char, 16> TABLE;
static TABLE* lookup = 0;
if (lookup == 0) { // Eh, any thread that reaches here will do a commit
TABLE& temp = *new TABLE();
temp["bool"] = 'b';
temp["int8"] = 's';
temp["uint8"] = 'S';
temp["int16"] = 'i';
temp["uint16"] ='I';
temp["int32"] = 'l';
temp["uint32"] ='L';
temp["int64"] ='x';
temp["uint64"] ='X';
temp["float32"]='f';
temp["float64"]='d';
temp["complex64"]='F';
temp["complex128"]='D';
temp["complexint8"] = 'c';
temp["complexuint8"] = 'C';
temp["complexint16"] = 'e';
temp["complexuint16"] = 'E';
temp["complexint32"] = 'g';
temp["complexuint32"] = 'G';
temp["complexint64"] = 'h';
temp["complexuint64"] = 'H';
lookup = &temp;
}
/// AVLHashTIterator<string, char, 16> it(*lookup);
/// while (it()) {
/// cout << it.key() << ":" << it.value() << endl;
/// }
// If found, return full char, otherwise -1 to inidcate it failed
string tagger = tag;
if (lookup->findValue(tagger, ret)) {
if (supports_cx_int) {
return int_1(ret);
}
// Doesn't support cx int
if (tagger.find("complex") != string::npos &&
tagger.find("int")!=string::npos) {
return -1;
} else {
return int_1(ret);
}
} else {
return -1;
}
}
OC_END_NAMESPACE
#define OCNUMPYTOOLS_H_
#endif // OCNUMPYTOOLS_H_
|
C | /* El lenguaje de programacion C, R&K, (Prentice Hall, 2da. edicion, 1991) */
/* # 3.6 */
/* El siguiente programa muestra el ejemplo de la funcion itoa la cual comvierte un numero entero a una cadena de caracteres */
/* Esta funcion usa tres argumentos: el entero, la cadena para almacenar la conversion, y un ancho minimo de campo */
#include <stdio.h>
#include <string.h>
void itoa(int, char [], int);
void reverse(char []);
main(){
int x = 1345;
char line[' '];
itoa(x,line,10);
printf("Entero %i Cadena = %s\n",x,line);
}
void itoa(int n, char s[' '], int min)
{
int i, signo;
if((signo = n) < 0)
{
n = -n;
}
i=0;
do{
s[i++] = n%10 + '0';
}while((n/=10) > 0);
if (signo < 0)
s[i++]='-';
s[i]='\0';
while(i < min)
s[i++] = ' ';
reverse(s);
}
void reverse(char s[' '])
{
int i,j,k;
for(i=0,j = strlen(s)-1;i<j;i++,j--){
k = s[i];
s[i] = s[j];
s[j] = k;
}
}
|
C | // C program to connect to the socket opened by php module
// written by -- kartik
#include<stdio.h>
#include<sys/socket.h>
#include<arpa/inet.h>
#include<stdlib.h>
#include<unistd.h>
#include<string.h>
#include<sys/types.h>
#include<malloc.h>
#include"myfunc.h"
//#include<conio.h>
//max buffer size
#define buffer_size 100
// main function
// takes port number as argument
int main(int argc , char *argv[])
{
if(argc<2)
{
printf("Error : pass the argument <address> <port number>\n");
exit(EXIT_FAILURE);
}
int listenfd=0,connfd=0;
struct sockaddr_in serv_addr; // creating variable of data type 'struct sockaddr_in'
// create a memory buffer
char buffer[buffer_size];
char *send_ack="your message received\n";
// create socket
listenfd=socket(AF_INET, SOCK_STREAM,0);
if(!listenfd)
{
printf("Error : Scoket failed\n");
exit(EXIT_FAILURE);
}
memset(&serv_addr, '0', sizeof(serv_addr));
memset(buffer, '0', sizeof(buffer));
serv_addr.sin_family=AF_INET;
//server address
serv_addr.sin_addr.s_addr = htonl(INADDR_ANY); //listen to any internal address
// set port number
int port=atoi(argv[1]);
serv_addr.sin_port=htons(port);
//bind address
if(bind(listenfd,(struct sockaddr*)&serv_addr, sizeof(serv_addr))<0)
{
printf("Error : Binding failed\n");
// free(buffer);
exit(EXIT_FAILURE);
}
//listen to 1 php script
listen(listenfd,1);
while(1)
{
printf("Server started\n");
connfd=accept(listenfd,(struct sockaddr *)NULL,NULL);
//get the input data from php
int byteRead=read(connfd,buffer,buffer_size);
//trim the garbage value
buffer[byteRead]='\0';
//check received data is exit ? if yes , shutdown the server
if((strcmp(buffer,"exit"))==0)
{
write(connfd,"server close",sizeof("server close"));
printf("Server shutdown\n");
close(connfd);
exit(EXIT_SUCCESS);
}
printf("Call to myfunction\n");
//call to user-defined function present in myfunc.h
myfunc(buffer);
printf("return from myfunction\n\n");
//write the computed data back to php
write(connfd,send_ack,strlen(send_ack));
close(connfd); // close the connection
sleep(1);
}
exit(EXIT_SUCCESS);
}
|
C | #include "strings.h"
#include <stdio.h>
int main(void)
{
char string[] = {'h', 'e', 'l', 'l', 'o', 0x00};
int number = 0xf00d;
printf("%d as string is %s\n", number, int_to_ascii(10, number));
printf("%d as string is %s\n", -number, int_to_ascii(10, -number));
printf("%d as string is %s\n", number, int_to_ascii(2, number));
printf("%d as string is %s\n", number, int_to_ascii(16, number));
puts("BEFORE");
printf("%s\n", string);
puts("AFTER");
printf("%s\n", string_reverse(string));
if (strings_match("hello", "hello"))
puts("OK!");
else
puts("FAIL!");
if (string_contains("hello", "llo"))
puts("OK!");
else
puts("FAIL");
}
|
C | #include "usart.h"
u8 USART_RX_BUF=0;
u16 USART_RX_STA=0;
void uart_init(u32 bound){
//GPIO˿
GPIO_InitTypeDef GPIO_InitStructure;
USART_InitTypeDef USART_InitStructure;
NVIC_InitTypeDef NVIC_InitStructure;
RCC_APB2PeriphClockCmd(RCC_APB2Periph_USART1|RCC_APB2Periph_GPIOA, ENABLE); //ʹUSART1GPIOAʱ
//USART1_TX PA.9
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_9; //PA.9
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP; //
GPIO_Init(GPIOA, &GPIO_InitStructure);
//USART1_RX PA.10
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_10;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING;//
GPIO_Init(GPIOA, &GPIO_InitStructure);
//Usart1 NVIC
NVIC_InitStructure.NVIC_IRQChannel = USART1_IRQn;
NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority=3 ;//ռȼ3
NVIC_InitStructure.NVIC_IRQChannelSubPriority = 3; //ȼ3
NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE; //IRQͨʹ
NVIC_Init(&NVIC_InitStructure); //ָIJʼVICĴ
//USART ʼ
USART_InitStructure.USART_BaudRate = bound;//һΪ9600;
USART_InitStructure.USART_WordLength = USART_WordLength_8b;//ֳΪ8λݸʽ
USART_InitStructure.USART_StopBits = USART_StopBits_1;//һֹͣλ
USART_InitStructure.USART_Parity = USART_Parity_No;//żУλ
USART_InitStructure.USART_HardwareFlowControl = USART_HardwareFlowControl_None;//Ӳ
USART_InitStructure.USART_Mode = USART_Mode_Rx | USART_Mode_Tx; //շģʽ
USART_Init(USART1, &USART_InitStructure); //ʼ
USART_ITConfig(USART1, USART_IT_RXNE, ENABLE);//ж
USART_Cmd(USART1, ENABLE); //ʹܴ
}
void USART1_IRQHandler(void){
u8 Res;
if(USART_GetITStatus(USART1, USART_IT_RXNE) != RESET) {
Res = USART_ReceiveData(USART1);
if(USART_RX_STA==0 || USART_RX_STA==0xff){
if(Res==0xAA)USART_RX_STA=1;
}else if(USART_RX_STA==1){
if(Res==0xBB)
USART_RX_STA=2;
else
USART_RX_STA=0;
}else if(USART_RX_STA==2){
USART_RX_BUF = Res;
USART_RX_STA = 0xFF;
if(USART_RX_BUF)
SysState.SysFlag.bit.UsartFlag = 1;
else
SysState.SysFlag.bit.UsartFlag = 0;
}
}
}
void send_once(void){
u8 i;
u8 num;
while(USART_GetFlagStatus(USART1,USART_FLAG_TC)!=SET);//ȴͽ
USART_SendData(USART1,0xBB);//1
while(USART_GetFlagStatus(USART1,USART_FLAG_TC)!=SET);//ȴͽ
USART_SendData(USART1,0xAA);//1
while(USART_GetFlagStatus(USART1,USART_FLAG_TC)!=SET);//ȴͽ
USART_SendData(USART1,65);//1
for(i=0;i<64;i++){
while(USART_GetFlagStatus(USART1,USART_FLAG_TC)!=SET);//ȴͽ
USART_SendData(USART1,PriData[7-i/8][i%8]&0xff);//1
num+=PriData[7-i/8][i%8]&0xff;
while(USART_GetFlagStatus(USART1,USART_FLAG_TC)!=SET);//ȴͽ
USART_SendData(USART1,(PriData[7-i/8][i%8]>>8)&0xff);//1
num+=(PriData[7-i/8][i%8]>>8)&0xff;
}
while(USART_GetFlagStatus(USART1,USART_FLAG_TC)!=SET);//ȴͽ
USART_SendData(USART1,num&0xff);//1
}
void printtime(void){ //
while(USART_GetFlagStatus(USART1,USART_FLAG_TC)!=SET);//ȴͽ
USART_SendData(USART1,(((KeyState.Key3.HoldTime-60)/60)>>8)&0xff);//1
while(USART_GetFlagStatus(USART1,USART_FLAG_TC)!=SET);//ȴͽ
USART_SendData(USART1,((KeyState.Key3.HoldTime-60)/60)&0xff);//1
}
|
C | void merge(int arr[], int beg, int mid, int end)
{
int i=beg, j=mid+1, k=beg, temp[end+1],l;
while((i<=mid) && (j<=end))
{
if(arr[i] <= arr[j])
{
temp[k] = arr[i];
i++;
}
else
{
temp[k] = arr[j];
j++;
}
k++;
}
while(j<=end)
{
temp[k] = arr[j];
j++;
k++;
}
while(i<=mid)
{
temp[k] = arr[i];
i++;
k++;
}
for(l=beg;l<k;l++)
arr[l] = temp[l];
}
void merge_sort(int arr[], int beg, int end)
{
int mid;
if(beg<end)
{
mid = (beg+end)/2;
merge_sort(arr,beg, mid);
merge_sort(arr, mid+1, end);
merge(arr, beg, mid, end);
}
}
|
C | /* $Header: array.c,v 2.0 88/06/05 00:08:17 root Exp $
*
* $Log: array.c,v $
* Revision 2.0 88/06/05 00:08:17 root
* Baseline version 2.0.
*
*/
#include "EXTERN.h"
#include "perl.h"
STR *
afetch(ar,key)
register ARRAY *ar;
int key;
{
if (key < 0 || key > ar->ary_fill)
return Nullstr;
return ar->ary_array[key];
}
bool
astore(ar,key,val)
register ARRAY *ar;
int key;
STR *val;
{
bool retval;
if (key < 0)
return FALSE;
if (key > ar->ary_max) {
int newmax = key + ar->ary_max / 5;
ar->ary_array = (STR**)saferealloc((char*)ar->ary_array,
(newmax+1) * sizeof(STR*));
bzero((char*)&ar->ary_array[ar->ary_max+1],
(newmax - ar->ary_max) * sizeof(STR*));
ar->ary_max = newmax;
}
while (ar->ary_fill < key) {
if (++ar->ary_fill < key && ar->ary_array[ar->ary_fill] != Nullstr) {
str_free(ar->ary_array[ar->ary_fill]);
ar->ary_array[ar->ary_fill] = Nullstr;
}
}
retval = (ar->ary_array[key] != Nullstr);
if (retval)
str_free(ar->ary_array[key]);
ar->ary_array[key] = val;
return retval;
}
bool
adelete(ar,key)
register ARRAY *ar;
int key;
{
if (key < 0 || key > ar->ary_max)
return FALSE;
if (ar->ary_array[key]) {
str_free(ar->ary_array[key]);
ar->ary_array[key] = Nullstr;
return TRUE;
}
return FALSE;
}
ARRAY *
anew(stab)
STAB *stab;
{
register ARRAY *ar = (ARRAY*)safemalloc(sizeof(ARRAY));
ar->ary_array = (STR**) safemalloc(5 * sizeof(STR*));
ar->ary_magic = str_new(0);
ar->ary_magic->str_link.str_magic = stab;
ar->ary_fill = -1;
ar->ary_index = -1;
ar->ary_max = 4;
bzero((char*)ar->ary_array, 5 * sizeof(STR*));
return ar;
}
void
aclear(ar)
register ARRAY *ar;
{
register int key;
if (!ar)
return;
for (key = 0; key <= ar->ary_max; key++)
str_free(ar->ary_array[key]);
ar->ary_fill = -1;
bzero((char*)ar->ary_array, (ar->ary_max+1) * sizeof(STR*));
}
void
afree(ar)
register ARRAY *ar;
{
register int key;
if (!ar)
return;
for (key = 0; key <= ar->ary_max; key++)
str_free(ar->ary_array[key]);
str_free(ar->ary_magic);
safefree((char*)ar->ary_array);
safefree((char*)ar);
}
bool
apush(ar,val)
register ARRAY *ar;
STR *val;
{
return astore(ar,++(ar->ary_fill),val);
}
STR *
apop(ar)
register ARRAY *ar;
{
STR *retval;
if (ar->ary_fill < 0)
return Nullstr;
retval = ar->ary_array[ar->ary_fill];
ar->ary_array[ar->ary_fill--] = Nullstr;
return retval;
}
aunshift(ar,num)
register ARRAY *ar;
register int num;
{
register int i;
register STR **sstr,**dstr;
if (num <= 0)
return;
astore(ar,ar->ary_fill+num,(STR*)0); /* maybe extend array */
dstr = ar->ary_array + ar->ary_fill;
sstr = dstr - num;
for (i = ar->ary_fill; i >= 0; i--) {
*dstr-- = *sstr--;
}
bzero((char*)(ar->ary_array), num * sizeof(STR*));
}
STR *
ashift(ar)
register ARRAY *ar;
{
STR *retval;
if (ar->ary_fill < 0)
return Nullstr;
retval = ar->ary_array[0];
bcopy((char*)(ar->ary_array+1),(char*)ar->ary_array,
ar->ary_fill * sizeof(STR*));
ar->ary_array[ar->ary_fill--] = Nullstr;
return retval;
}
int
alen(ar)
register ARRAY *ar;
{
return ar->ary_fill;
}
afill(ar, fill)
register ARRAY *ar;
int fill;
{
if (fill < 0)
fill = -1;
if (fill <= ar->ary_max)
ar->ary_fill = fill;
else
astore(ar,fill,Nullstr);
}
void
ajoin(ar,delim,str)
register ARRAY *ar;
char *delim;
register STR *str;
{
register int i;
register int len;
register int dlen;
if (ar->ary_fill < 0) {
str_set(str,"");
STABSET(str);
return;
}
dlen = strlen(delim);
len = ar->ary_fill * dlen; /* account for delimiters */
for (i = ar->ary_fill; i >= 0; i--)
len += str_len(ar->ary_array[i]);
str_grow(str,len); /* preallocate for efficiency */
str_sset(str,ar->ary_array[0]);
for (i = 1; i <= ar->ary_fill; i++) {
str_ncat(str,delim,dlen);
str_scat(str,ar->ary_array[i]);
}
STABSET(str);
}
|
C | /* Chapter 12 Exercise 9 */
#include <stdio.h>
#define NUM 5
double inner_product(const double *a, const double *b, int n);
int main(void)
{
double *a, *b, arr_a[NUM], arr_b[NUM];
printf("\nEnter %d numbers: ", NUM);
for (a = arr_a; a < arr_a + NUM; a++) {
scanf(" %lf", a);
}
printf("\nEnter %d numbers: ", NUM);
for (b = arr_b; b < arr_b + NUM; b++) {
scanf(" %lf", b);
}
printf("Inner Product: %0.3lf\n", inner_product(arr_a, arr_b, NUM));
return 0;
}
double inner_product(const double *a, const double *b, int n) {
double total = 0;
const double *ptr_a = a, *ptr_b = b;
for ( ;ptr_a < a + n && ptr_b < b + n; ptr_a++, ptr_b++) {
total += *ptr_a * *ptr_b;
printf("%f * %f = %f\n", *ptr_a, *ptr_b, *ptr_a * *ptr_b);
}
return total;
}
|
C | #include<unistd.h>
#include<stdlib.h>
#include<stdio.h>
#include<string.h>
#include<sys/shm.h>
#define TEXT_SZ 2048
struct shared_use_st
{
int written_by_you;
char some_text[TEXT_SZ];
};
int main()
{
int running = 1;
void *shared_memory = (void *)0;
struct shared_use_st *shared_stuff;
int shmid;
srand( (unsigned int)getpid() );
shmid = shmget( (key_t)1234,
sizeof(struct shared_use_st),
0666 |IPC_CREAT );
if (shmid == -1)
{
fprintf(stderr, "shmget failed\n");
exit(EXIT_FAILURE);
}
shared_memory = shmat(shmid,(void *)0, 0);
if (shared_memory == (void *)-1)
{
fprintf(stderr, "shmat failed\n");
exit(EXIT_FAILURE);
}
printf("Memory Attached at %x\n",
(int)shared_memory);
shared_stuff = (struct shared_use_st *)
shared_memory;
shared_stuff->written_by_you = 0;
while(running)
{
if(shared_stuff->written_by_you)
{
printf("You Wrote: %s",
shared_stuff->some_text);
sleep( rand() %4 );
shared_stuff->written_by_you = 0;
if (strncmp(shared_stuff->some_text,
"end", 3)== 0)
{
running = 0;
}
}
}
if (shmdt(shared_memory) == -1)
{
fprintf(stderr, "shmdt failed\n");
exit(EXIT_FAILURE);
}
if (shmctl(shmid, IPC_RMID, 0) == -1)
{
fprintf(stderr, "failed to delete\n");
exit(EXIT_FAILURE);
}
exit(EXIT_SUCCESS);
} |
C | #include <stdio.h>
#include <stdlib.h>
void main () {
char name[100], link[100];
printf("Welcome to hacktoberfest 2021!\n");
printf("Visit this link for join: https://hacktoberfest.digitalocean.com\n");
// Input your name
printf("\nEnter your name: ");
scanf(" %s", &name);
// Input your github link
printf("Enter your github link: ");
scanf(" %s", &link);
// Recap your data
printf("\n\n================\n");
printf("Your name: %s", name);
printf("\nYour github link: %s\n\n", link);
printf("Happy hacking mate!\n\n");
}
|
C | #include "matriz.h"
void imprimirMatriz(matriz *M) {
int i, k;
if (M != 0) {
for (i = 0; i < M->filas; i++) {
for (k = 0; k < M->columnas; k++)
printf("%f ", *((M->datos) + i * M->columnas + k));
//printf("%f ", *((M->datos) + i * M->filas + k));
printf("\n");
}
printf("\n");
} else
printf("La matriz no existe\n");
}
|
C | /* See LICENSE file for copyright and license details. */
#include <arpa/inet.h>
#include <errno.h>
#include <inttypes.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "arg.h"
#include "util.h"
static void
usage(void)
{
die("usage: %s [-b colour]", argv0);
}
int
main(int argc, char *argv[])
{
size_t rowlen, rowoutlen;
uint64_t a;
uint32_t width, height, i, j, k, l;
uint16_t *row, mask[3] = { 0xffff, 0xffff, 0xffff };
uint8_t *rowout;
/* arguments */
ARGBEGIN {
case 'b':
if (parse_mask(EARGF(usage()), mask)) {
usage();
}
break;
default:
usage();
} ARGEND
if (argc) {
usage();
}
/* prepare */
ff_read_header(&width, &height);
row = ereallocarray(NULL, width, (sizeof("RGBA") - 1) * sizeof(uint16_t));
rowout = ereallocarray(NULL, width, (sizeof("RGB") - 1) * sizeof(uint8_t));
rowlen = width * (sizeof("RGBA") - 1);
rowoutlen = width * (sizeof("RGB") - 1);
/* write data */
printf("P6\n%" PRIu32 " %" PRIu32 "\n255\n", width, height);
for (i = 0; i < height; ++i) {
efread(row, sizeof(uint16_t), rowlen, stdin);
for (j = 0, k = 0; j < rowlen; j += 4, k += 3) {
a = ntohs(row[j + 3]);
for (l = 0; l < 3; l++) {
/* alpha blending and 8-bit-reduction */
rowout[k + l] = (a * ntohs(row[j + l]) +
(UINT16_MAX - a) * mask[l]) /
(UINT16_MAX *
(UINT16_MAX / UINT8_MAX));
}
}
efwrite(rowout, sizeof(uint8_t), rowoutlen, stdout);
}
return fshut(stdout, "<stdout>");
}
|
C | #include<stdio.h>
#include<string.h>
//#include<stdbool.h>
_Bool backspaceCompare(char* s,char* t);
void processStr(char* str);
int main()
{
char s[10];
char t[10];
printf("Enter string S:");
scanf("%s",s);
printf("Enter string T:");
scanf("%s",t);
if(backspaceCompare(s,t))
printf("S and T are equal.");
}
_Bool backspaceCompare(char* s,char* t)
{
/* str: "ab#c###de#"
i: ^ read
j: ^ write ]read,û|Qwrite(i >= j)ҥHiHΦP@Ӱ}Cק
newStr: a */
processStr(s);
processStr(t);
return strcmp(s,t) == 0;
}
void processStr(char* str)
{
int j= -1;
for(int i=0;i < strlen(str);i++)
{
if(str[i] != '#')
{
j++;
str[j] = str[i];
}
else if(j >= 0)
{
j--;
}
}
str[j+1] = '\0';
printf("%s\n",str);
} |
C | #include "shell.h"
typedef int (*func_t)(char **argv);
typedef struct {
const char *name;
func_t func;
} command_t;
static int do_quit(__unused char **argv) {
shutdownjobs();
exit(EXIT_SUCCESS);
}
static char pathbuf[4096];
static int do_chdir(char **argv) {
char *path = argv[0];
if (path == NULL)
path = getenv("HOME");
memset(pathbuf, 0, 4096);
if (0 == strncmp(path, "~/", 2)) {
strcat(pathbuf, getenv("HOME"));
strcat(pathbuf, "/");
strcat(pathbuf, path + 2);
path = pathbuf;
}
int rc = chdir(path);
if (rc < 0) {
msg("cd: %s: %s\n", strerror(errno), path);
return 1;
}
return 0;
}
static int do_jobs(__unused char **argv) {
watchjobs(ALL);
return 0;
}
static int do_fg(char **argv) {
int j = argv[0] ? atoi(argv[0]) : -1;
sigset_t mask;
sigprocmask(SIG_BLOCK, &sigchld_mask, &mask);
if (!resumejob(j, FG, &mask))
msg("fg: job not found: %s\n", argv[0]);
sigprocmask(SIG_SETMASK, &mask, NULL);
return 0;
}
static int do_bg(char **argv) {
int j = argv[0] ? atoi(argv[0]) : -1;
sigset_t mask;
sigprocmask(SIG_BLOCK, &sigchld_mask, &mask);
if (!resumejob(j, BG, &mask))
msg("bg: job not found: %s\n", argv[0]);
sigprocmask(SIG_SETMASK, &mask, NULL);
return 0;
}
static int do_kill(char **argv) {
if (!argv[0])
return -1;
if (*argv[0] != '%')
return -1;
int j = atoi(argv[0] + 1);
sigset_t mask;
sigprocmask(SIG_BLOCK, &sigchld_mask, &mask);
if (!killjob(j))
msg("kill: job not found: %s\n", argv[0]);
sigprocmask(SIG_SETMASK, &mask, NULL);
return 0;
}
static command_t builtins[] = {
{"quit", do_quit}, {"cd", do_chdir}, {"jobs", do_jobs}, {"fg", do_fg},
{"bg", do_bg}, {"kill", do_kill}, {NULL, NULL},
};
int builtin_command(char **argv) {
for (command_t *cmd = builtins; cmd->name; cmd++) {
if (strcmp(argv[0], cmd->name))
continue;
return cmd->func(&argv[1]);
}
errno = ENOENT;
return -1;
}
noreturn void external_command(char **argv) {
const char *path = getenv("PATH");
if (!index(argv[0], '/') && path) {
size_t n = strlen(path);
for (const char *colon = path; colon < path + n;) {
size_t offset = strcspn(colon, ":");
char *cmd = strndup(colon, offset);
strapp(&cmd, "/");
strapp(&cmd, argv[0]);
(void)execve(cmd, argv, environ);
free(cmd);
colon += offset + 1;
}
} else {
(void)execve(argv[0], argv, environ);
}
msg("%s: %s\n", argv[0], strerror(errno));
exit(EXIT_FAILURE);
}
|
C | #include "bookorder.h"
void
bookorder(char * clientdbfilename, char * orderinputfilename, char * categoriesfilename)
{
FILE * clients = NULL;
FILE * orders = NULL;
FILE * categories = NULL;
//calculate lengths of files for buffers
int client_bufferlen = filelengthwrapper(clientdbfilename);
int order_bufferlen = filelengthwrapper(orderinputfilename);
int category_bufferlen = filelengthwrapper(categoriesfilename);
//create buffers
char * client_buffer = malloc(sizeof(char)*client_bufferlen);
char * order_buffer = malloc(sizeof(char)*order_bufferlen);
char * category_buffer = malloc(sizeof(char)*category_bufferlen);
//copy data from files into buffers
populate_buffer(client_buffer,clientdbfilename);
populate_buffer(order_buffer, orderinputfilename);
populate_buffer(category_buffer, categoriesfilename);
//copy data from buffers into structures
// ... filetostructure_ ...
// ... filetostructure_ ...
// ... filetostructure_ ...
printf("bookorder()\n");
}
orders *
filetostructure_order(char * buffer)
{
orders * myorders = malloc(sizeof(orders));
int index = 0;
char temp = buffer[index];
//order layout:
//<doublequote> <book title> <doublequote> <verticalbar> <double:value> <verticalbar> <integer:userIDnumber> <verticalbar> <category> <newline>
//"I Could Pee on This: And Other Poems by Cats"|7.49|1|HOUSING01
//loop until newline or end of file
return myorders;
}
clients *
filetostructure_clientdatabase(char * buffer)
{
clients * myclients = malloc(sizeof(clients));
return myclients;
}
categories *
filetostructure_categories(char * buffer)
{
categories * mycategories = malloc(sizeof(categories));
return mycategories;
}
|
C | #include <stdio.h>
#include <stdlib.h>
// definicion y prototipos funciones
//variables y constantes
// implementacion de funciones
int main(int argc, char** argv) {
float a, b, c, d;
scanf("%f",&a);
scanf("%f",&b);
scanf("%f",&c);
scanf("%f",&d);
if(a>b && a>c && a>d){
printf("A es mayor");
}
else{
if (b>a && b>c && b>d){
printf("B es mayor");
}
else{
if(c>a && c>b && c>d){
printf("C es mayor");
}
else{
printf("D es mayor");
}
}
}
return (0);
}
|
C | #include <stdio.h>
#include <stdlib.h>
#include <signal.h>
#include <sys/time.h>
int reads = 0;
void close_signal_handler(int sig)
{
printf("Completed %d reads in 5 seconds\n", reads);
exit(0);
}
int main(int argc, char const *argv[])
{
FILE *fp = fopen(argv[1], "rb");
int last_int = sizeof(int) * (100 - 1);
struct itimerval timer;
int n;
timer.it_value.tv_sec = 5;
timer.it_value.tv_usec = 0;
signal(SIGVTALRM, close_signal_handler);
signal(SIGALRM, close_signal_handler);
setitimer(ITIMER_VIRTUAL, &timer, NULL);
sigset_t waiting_mask;
while (++reads) {
fseek(fp, rand() % last_int, SEEK_SET);
fread(&n, 1, sizeof(int), fp);
}
fclose(fp);
return 0;
}
|
C | #include <daos.h>
#include <file_table.h>
#include <files.h>
#include <logger.h>
#include <definitions.h>
#include <macro_utils.h>
#include <app_errors.h>
#include <request_response_definitions.h>
#include <limits.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <dirent.h>
#include <errno.h>
#include <sys/stat.h>
#include <fcntl.h>
//
// Constants
//
#define DAOS_DIRECTORY_LENGTH 2048
#define DAOS_FILE_PREFIX_LENGTH 64
#define DAOS_FILE_EXTENSION_LENGTH 8
#define DAOS_MAX_DIRECTORY_DEPTH 100
#define DAOS_MAX_DIRECTORY_COUNT 10000
//
// Types
//
typedef
struct
{
char directory[DAOS_DIRECTORY_LENGTH + 1];
char filePrefix[DAOS_FILE_PREFIX_LENGTH + 1];
char fileExtension[DAOS_FILE_EXTENSION_LENGTH + 1];
uint8_t numIdDigits;
DaosCount_t numItemsPerFile;
uint32_t dirCount;
uint32_t dirDepth;
DaosItemFunctions_t itemFunctions;
} DaosData_t;
//
// Local prototypes
//
static int saveItemToNewFile(const char* filename, DaosData_t* daosData, const void* item);
static int saveItemToExistingFile(const char* filename, FILE* existingFile,
DaosData_t* daosData, const void* item, bool* newItem);
static void generateFilename(DaosData_t* data, DaosId_t id, char* filename, size_t filenameLength);
static FILE* createTempFile(const char* directory, const char* filePrefix,
char* filename, size_t filenameLength);
//
// External interface
//
Daos_t daos_init(const char* directory, uint32_t dirDepth, uint32_t dirCount, const char* filePrefix, const char* fileExtension,
uint8_t numIdDigits, DaosCount_t numItemsPerFile, DaosItemFunctions_t* itemFunctions)
{
Daos_t daos = Daos_NULL;
if (directory == NULL)
{
LOG_MESSAGE(CRITICAL_LOG_MSG, "Critical error: Invalid NULL value for directory.");
return daos;
}
if (filePrefix == NULL)
{
LOG_MESSAGE(CRITICAL_LOG_MSG, "Critical error: Invalid NULL value for filePrefix.");
return daos;
}
if (fileExtension == NULL)
{
LOG_MESSAGE(CRITICAL_LOG_MSG, "Critical error: Invalid NULL value for fileExtension.");
return daos;
}
if (itemFunctions == NULL)
{
LOG_MESSAGE(CRITICAL_LOG_MSG, "Critical error: Invalid NULL value for itemFunctions.");
return daos;
}
if (strnlen(directory, MAX_STRING_LEN) > DAOS_DIRECTORY_LENGTH)
{
LOG_MESSAGE(CRITICAL_LOG_MSG, "Critical error: Directory's (\"%s\") length is greater"
" than maximum (%zu).", directory, DAOS_DIRECTORY_LENGTH);
return daos;
}
if (strnlen(filePrefix, MAX_STRING_LEN) > DAOS_FILE_PREFIX_LENGTH)
{
LOG_MESSAGE(CRITICAL_LOG_MSG, "Critical error: filePrefix's (\"%s\") length is"
" greater than maximum (%zu).", filePrefix, DAOS_FILE_PREFIX_LENGTH);
return daos;
}
if (strnlen(fileExtension, MAX_STRING_LEN) > DAOS_FILE_EXTENSION_LENGTH)
{
LOG_MESSAGE(CRITICAL_LOG_MSG, "Critical error: fileExtension's (\"%s\") length is "
"greater than maximum (%zu).", fileExtension, DAOS_FILE_EXTENSION_LENGTH);
return daos;
}
if (numIdDigits == 0)
{
LOG_MESSAGE(CRITICAL_LOG_MSG, "Critical error: Invalid 0 value for numIdDigits.");
return daos;
}
if (numItemsPerFile == 0)
{
LOG_MESSAGE(CRITICAL_LOG_MSG, "Critical error: Invalid 0 value for numItemsPerFile.");
return daos;
}
if (dirDepth > DAOS_MAX_DIRECTORY_DEPTH)
{
LOG_MESSAGE(CRITICAL_LOG_MSG, "Critical error: Invalid 0 value for dirDepth.");
return daos;
}
if (dirCount > DAOS_MAX_DIRECTORY_COUNT)
{
LOG_MESSAGE(CRITICAL_LOG_MSG, "Critical error: Invalid 0 value for dirCount.");
return daos;
}
DIR* dir = opendir(directory);
if (dir == NULL)
{
LOG_MESSAGE(CRITICAL_LOG_MSG, "Critical error: opendir(%s) failed. errno = %d"
" (\"%s\").", directory, errno, strerror(errno));
return daos;
}
closedir(dir);
DaosData_t* data = (DaosData_t*)malloc(sizeof(DaosData_t));
if (data == NULL)
{
LOG_MESSAGE(CRITICAL_LOG_MSG, "Critical error: malloc(size = %zu) failed.",
sizeof(DaosData_t));
return daos;
}
strcpy(data->directory, directory);
strcpy(data->filePrefix, filePrefix);
strcpy(data->fileExtension, fileExtension);
data->numIdDigits = numIdDigits;
data->numItemsPerFile = numItemsPerFile;
data->itemFunctions = *itemFunctions;
data->dirCount = dirCount;
data->dirDepth = dirDepth;
daos.d = data;
return daos;
}
void daos_free(Daos_t daos)
{
DaosData_t* data = (DaosData_t*)daos.d;
if (data == NULL) { return; }
free(data);
}
bool daos_isNull(Daos_t daos)
{
return daos.d == NULL;
}
// create a file for "item" without header or any additional data.
static int daos_getItemFlatFile(Daos_t daos, DaosId_t id, void** itemBinary, void** item, uint32_t* itemDataSize)
{
DaosData_t* data = (DaosData_t*)daos.d;
char filename[PATH_MAX];
generateFilename(data, id, filename, ARRAY_COUNT(filename));
FILE* fp;
fp = fopen(filename, "rb");
if (fp == NULL)
{
LOG_MESSAGE(ATTENTION_LOG_MSG, "Error: (id = %lu) - fopen(%s) failed. errno = %d (\"%s\").",
id, filename, errno, strerror(errno));
return ERR_FS_FAILED_TO_OPEN_FILE_FOR_READ;
}
// get the file size
fseek(fp, 0, SEEK_END);
*itemDataSize = ftell(fp);
fseek(fp, 0, SEEK_SET);
// allocate storage for the file content
*itemBinary = malloc(*itemDataSize);
if (*itemBinary == NULL)
{
LOG_MESSAGE(CRITICAL_LOG_MSG, "Critical error: malloc(size = %zu) failed.",
*itemDataSize);
fclose(fp);
return ERR_FS_MEMORY_ALLOC_FAILED;
}
// read the whole file
size_t bytesRead = fread(*itemBinary, 1, *itemDataSize, fp);
fclose(fp);
if (bytesRead != *itemDataSize)
{
LOG_DEFAULT_APP_ERROR(ERR_FS_FILE_READ_FAILED);
return ERR_FS_FILE_READ_FAILED;
}
// item that will be used by caller
*item = *itemBinary;
return ERR_FS_NO_ERROR;
}
// save the buffer as is into a file
static int daos_saveItemFlatFile(Daos_t daos, int id, const void* item, uint32_t itemSize)
{
DaosData_t* data = (DaosData_t*)daos.d;
char filename[PATH_MAX];
generateFilename(data, id, filename, ARRAY_COUNT(filename));
FILE* file = fopen(filename, "wb");
if (file == NULL)
{
LOG_MESSAGE(ATTENTION_LOG_MSG, "Error: (id = %lu) - opendir(%s) failed. errno = %d"
" (\"%s\").", id, filename, errno, strerror(errno));
return ERR_FS_FAILED_TO_OPEN_FILE_FOR_WRITE;
}
size_t bytesWritten = fwrite(item, 1, itemSize, file);
fclose(file);
if(bytesWritten != itemSize)
{
LOG_DEFAULT_APP_ERROR(ERR_FS_FILE_WRITE_NOT_COMPLETED);
return ERR_FS_FILE_WRITE_NOT_COMPLETED;
}
return ERR_FS_NO_ERROR;
}
int daos_getItem(Daos_t daos, DaosId_t id, void** itemBinary, void** item, uint32_t* itemDataSize)
{
DaosData_t* data = (DaosData_t*)daos.d;
if (data == NULL)
{
LOG_MESSAGE(CRITICAL_LOG_MSG, "Critical error: Invalid NULL argument for daos.");
return ERR_FS_PARAM_DAO_NULL;
}
if (data->numItemsPerFile <= 1)
{
return daos_getItemFlatFile(daos, id, itemBinary, item, itemDataSize);
}
char filename[PATH_MAX] = { 0 };
generateFilename(data, id, filename, ARRAY_COUNT(filename));
FILE* file = fopen(filename, "rb");
if (file == NULL)
{
LOG_MESSAGE(ATTENTION_LOG_MSG, "Error: (id = %lu) - fopen(%s) failed. errno = %d (\"%s\").",
id, filename, errno, strerror(errno));
return ERR_FS_FAILED_TO_OPEN_FILE_FOR_READ;
}
DaosOffset_t itemOffset = 0;
DaosSize_t itemSize = 0;
int ret = getFileTableEntry(file, id, &itemOffset, &itemSize);
if (ret != ERR_FS_NO_ERROR)
{
LOG_MESSAGE(ATTENTION_LOG_MSG, "Error: (id = %lu) - getFileTableEntry(file = %s)"
" returned %d.", id, filename, ret);
fclose(file);
return ret;
}
*itemBinary = (uint8_t*)malloc(itemSize);
if (*itemBinary == NULL)
{
LOG_MESSAGE(CRITICAL_LOG_MSG, "Critical error: malloc(size = %zu) failed.",
itemSize);
fclose(file);
return ERR_FS_MEMORY_ALLOC_FAILED;
}
ret = readItemFromFile(file, itemOffset, itemSize, *itemBinary);
fclose(file);
if (ret != 0)
{
LOG_MESSAGE(ATTENTION_LOG_MSG, "Error: (id = %lu) - readItemFromFile(file = %s)"
" returned %d.", id, filename, ret);
return 4;
}
ret = processItemRead(file, *itemBinary, itemSize, NULL, item, itemDataSize);
if (ret != ERR_FS_NO_ERROR)
{
LOG_MESSAGE(ATTENTION_LOG_MSG, "Error: (id = %lu) - processItemRead(file = %s)"
" returned %d.", id, filename, ret);
return ret;
}
return ERR_FS_NO_ERROR;
}
int daos_saveItem(Daos_t daos, const void* item, uint32_t itemSize)
{
DaosData_t* data = (DaosData_t*)daos.d;
if (data == NULL)
{
LOG_MESSAGE(CRITICAL_LOG_MSG, "Critical error: Invalid NULL argument for daos.");
return 1;
}
DaosId_t id = data->itemFunctions.getPersistentItemId(item);
if (data->numItemsPerFile <= 1)
{
return daos_saveItemFlatFile(daos, id, item, itemSize);
}
char filename[PATH_MAX] = { 0 };
generateFilename(data, id, filename, ARRAY_COUNT(filename));
FILE* file = fopen(filename, "r+b");
if (file == NULL)
{
if (errno != ENOENT)
{
LOG_MESSAGE(ATTENTION_LOG_MSG, "Error: (id = %lu) - opendir(%s) failed. errno = %d"
" (\"%s\").", id, filename, errno, strerror(errno));
return ERR_FS_FAILED_TO_OPEN_FILE_FOR_READ;
}
int ret = saveItemToNewFile(filename, data, item);
if (ret != ERR_FS_NO_ERROR)
{
LOG_MESSAGE(ATTENTION_LOG_MSG, "Error: (id = %lu) - saveItemToNewFile(file = %s)"
" returned %d.", id, filename, ret);
return ret;
}
}
else
{
bool newItem;
int ret = saveItemToExistingFile(filename, file, data, item, &newItem);
if (ret != ERR_FS_NO_ERROR)
{
LOG_MESSAGE(ATTENTION_LOG_MSG, "Error: (id = %lu) - saveItemToExistingFile(file = %s)"
" returned %d.", id, filename, ret);
return ret;
}
}
return ERR_FS_NO_ERROR;
}
int daos_getFileVersion(Daos_t daos, const char* filename, DaosFileVersion_t* libraryVersion,
DaosFileVersion_t* fileVersion)
{
FILE* file = fopen(filename, "rb");
if (file == NULL)
{
LOG_MESSAGE(ATTENTION_LOG_MSG, "Error: fopen(%s) failed. errno = %d (\"%s\").",
filename, errno, strerror(errno));
return ERR_FS_FAILED_TO_OPEN_FILE_FOR_READ;
}
int ret = getFileTableVersion(file, libraryVersion, fileVersion);
if (ret != ERR_FS_NO_ERROR)
{
LOG_MESSAGE(ATTENTION_LOG_MSG, "Error: getFileTableVersion(file = %s) returned %d.",
filename, ret);
fclose(file);
return ret;
}
fclose(file);
return ERR_FS_NO_ERROR;
}
int daos_getFileTable(Daos_t daos, const char* filename, DaosFileVersion_t* fileVersion,
DaosCount_t* capacity, DaosCount_t* numItemsInFile, FileTableEntry_t** fileTable)
{
FILE* file = fopen(filename, "rb");
if (file == NULL)
{
LOG_MESSAGE(ATTENTION_LOG_MSG, "Error: fopen(%s) failed. errno = %d (\"%s\").",
filename, errno, strerror(errno));
return ERR_FS_FAILED_TO_OPEN_FILE_FOR_READ;
}
int ret = getFileTable(file, fileVersion, capacity, numItemsInFile, fileTable);
if (ret != ERR_FS_NO_ERROR)
{
LOG_MESSAGE(ATTENTION_LOG_MSG, "Error: (file = %s) returned %d.", filename, ret);
fclose(file);
return ret;
}
fclose(file);
return ERR_FS_NO_ERROR;
}
//
// Local functions
//
static int saveItemToNewFile(const char* filename, DaosData_t* daosData, const void* item)
{
FILE* file = fopen(filename, "w+b");
if (file == NULL)
{
LOG_MESSAGE(ATTENTION_LOG_MSG, "Error: fopen(%s) failed. errno = %d (\"%s\").",
filename, errno, strerror(errno));
return ERR_FS_FAILED_TO_OPEN_FILE_FOR_WRITE;
}
int ret = writeInitialFileTableToFile(file, daosData->numItemsPerFile);
if (ret != ERR_FS_NO_ERROR)
{
LOG_MESSAGE(ATTENTION_LOG_MSG, "Error: writeInitialFileTableToFile(file = %s, capacity = %lu)"
" returned %d.", filename, daosData->numItemsPerFile, ret);
fclose(file);
return ret;
}
DaosId_t id = daosData->itemFunctions.getPersistentItemId(item);
DaosSize_t itemSize = 0;
ret = writeItemToNewFile(file, daosData->directory, daosData->numItemsPerFile,
&daosData->itemFunctions, item, &itemSize);
if (ret != ERR_FS_NO_ERROR)
{
LOG_MESSAGE(ATTENTION_LOG_MSG, "Error: writeItemToNewFile(file = %s, directory = %s, capacity = %lu,"
" id = %lu) returned %d.", filename, daosData->directory, daosData->numItemsPerFile, id, ret);
fclose(file);
return ret;
}
ret = updateFileTableInFile(file, id, itemSize);
if (ret != ERR_FS_NO_ERROR)
{
LOG_MESSAGE(ATTENTION_LOG_MSG, "Error: updateFileTableInFile(file = %s, id = %lu,"
" item size = %lu) returned %d.", filename, id, itemSize, ret);
fclose(file);
return ret;
}
fclose(file);
return ERR_FS_NO_ERROR;
}
static int saveItemToExistingFile(const char* filename, FILE* existingFile,
DaosData_t* daosData, const void* item, bool* newItem)
{
char tempFilename[PATH_MAX] = { 0 };
FILE* tempFile = createTempFile(daosData->directory, daosData->filePrefix, tempFilename,
ARRAY_COUNT(tempFilename));
if (tempFile == NULL)
{
LOG_MESSAGE(ATTENTION_LOG_MSG, "Error: createTempFile() failed.");
fclose(existingFile);
return ERR_FS_FAILED_TO_OPEN_FILE_FOR_WRITE;
}
DaosId_t id = daosData->itemFunctions.getPersistentItemId(item);
DaosOffset_t existingItemOffset = 0;
DaosSize_t existingItemSize = 0;
int ret = getFileTableEntry(existingFile, id, &existingItemOffset, &existingItemSize);
if (ret != ERR_FS_NO_ERROR)
{
LOG_MESSAGE(ATTENTION_LOG_MSG, "Error: getFileTableEntry(file = %s, id = %lu) returned %d.",
filename, id, ret);
fclose(existingFile);
fclose(tempFile);
remove(tempFilename);
return ret;
}
DaosSize_t itemSize = 0;
ret = writeItemToExistingFile(tempFile, existingFile, existingItemOffset,
existingItemSize, &daosData->itemFunctions, item, &itemSize, newItem);
if (ret != ERR_FS_NO_ERROR)
{
LOG_MESSAGE(ATTENTION_LOG_MSG, "Error: writeItemToExistingFile(tempFile = %s, existingFile"
" = %s, id = %lu) returned %d.", tempFilename, filename, id, ret);
fclose(existingFile);
fclose(tempFile);
remove(tempFilename);
return ret;
}
fclose(existingFile);
ret = updateFileTableInFile(tempFile, id, itemSize);
if (ret != ERR_FS_NO_ERROR)
{
LOG_MESSAGE(ATTENTION_LOG_MSG, "Error: updateFileTableInFile(file = %s, id = %s,"
" item size = %lu) returned %d.", filename, id, itemSize, ret);
fclose(tempFile);
remove(tempFilename);
return ret;
}
fclose(tempFile);
if (rename(tempFilename, filename) != 0)
{
LOG_MESSAGE(ATTENTION_LOG_MSG, "Error: rename(old = %s, new = %s) failed. errno = %d"
" (\"%s\").", tempFilename, filename, errno, strerror(errno));
remove(tempFilename);
return ERR_FS_FILE_RENAME_FAILED;
}
return ERR_FS_NO_ERROR;
}
static void generateFilename(DaosData_t* data, DaosId_t id, char* filename, size_t filenameLength)
{
if (data->dirDepth > 1 && data->dirCount > 1)
{
int dirNameVect[DAOS_MAX_DIRECTORY_DEPTH];
int fileName = id / data->numItemsPerFile; // we could store the file in root folder without collision
id /= data->dirCount; // number of files in the last directory
for (size_t i = 0; i < data->dirDepth - 1; i++)
{
dirNameVect[i] = id % data->dirCount;
id = id / data->dirCount;
}
dirNameVect[data->dirDepth - 1] = id;
int bytesWritten = 0;
bytesWritten += snprintf(&filename[bytesWritten], filenameLength - bytesWritten, "%s", data->directory);
for (ssize_t i = data->dirDepth - 1; i >= 0; i--)
{
bytesWritten += snprintf(&filename[bytesWritten], filenameLength - bytesWritten, "/%d", dirNameVect[i]);
mkdir(filename, 0755);
}
snprintf(&filename[bytesWritten], filenameLength - bytesWritten, "/%d", fileName);
}
else
{
DaosId_t group = id / data->numItemsPerFile;
snprintf(filename, filenameLength, "%s/%d", data->directory, group);
}
}
static FILE* createTempFile(const char* directory, const char* filePrefix,
char* filename, size_t filenameLength)
{
snprintf(filename, filenameLength, "%s/temp_%sXXXXXX", directory, filePrefix);
int fd = mkstemp(filename);
if (fd < 0)
{
LOG_MESSAGE(ATTENTION_LOG_MSG, "Error: mkstemp(%s) failed. errno = %d (\"%s\").",
filename, errno, strerror(errno));
return NULL;
}
FILE* file = fdopen(fd, "w+b");
if (file == NULL)
{
LOG_MESSAGE(ATTENTION_LOG_MSG, "Error: fdopen(%s) failed. errno = %d (\"%s\").",
filename, errno, strerror(errno));
close(fd);
return NULL;
}
return file;
}
|
C | //ROI Image Convolution by 3x3 Mask ---> To be modified!
void MyFrame::OnROIConvolve3x3Image(wxCommandEvent & event){
printf("ROI Convolving3x3...");
free(loadedImage);
loadedImage = new wxImage(bitmap.ConvertToImage());
loadedImage2 = new wxImage(bitmap.ConvertToImage());
//mask3 matrix formation
int mask3[3][3];
int weight;
for(int i=0;i<3;i++)
{
for(int j=0;j<3;j++)
{
mask3[i][j]= 1;
}
}
//declare mask matrix values and mask weight here
mask3[0][0]=-1; mask3[0][1]=-2; mask3[0][2]=-1;
mask3[1][0]=0; mask3[1][1]=0; mask3[1][2]=0;
mask3[2][0]=1; mask3[2][1]=2; mask3[2][2]=1;
weight=1;
//mask3 values declared
//creating ROI (Region of Interest)
int newimgWidth = 3*imgWidth/5;
int newimgHeight = 3*imgHeight/5;
int widthcnt = 2*imgWidth/5;
int heightcnt = 2*imgHeight/5;
//making a new image to put masked values in
double RedMaskImage[newimgWidth][newimgHeight];
double GreenMaskImage[newimgWidth][newimgHeight];
double BlueMaskImage[newimgWidth][newimgHeight];
for(int i= widthcnt;i< newimgWidth;i++)
{
for(int j= heightcnt;j<newimgHeight;j++)
{
double sumRed =0; double sumGreen =0; double sumBlue= 0;
sumRed = sumRed + ( mask3[0][0]*loadedImage->GetRed(i-1,j-1) +mask3[0][1]*loadedImage->GetRed(i-1,j) +mask3[0][2]*loadedImage->GetRed(i-1,j+1)
+mask3[1][0]*loadedImage->GetRed(i,j-1) +mask3[1][1]*loadedImage->GetRed(i,j) +mask3[1][2]*loadedImage->GetRed(i,j+1)
+mask3[2][0]*loadedImage->GetRed(i+1,j-1) +mask3[2][1]*loadedImage->GetRed(i+1,j) +mask3[2][2]*loadedImage->GetRed(i+1,j+1) );
sumGreen = sumGreen + ( mask3[0][0]*loadedImage->GetGreen(i-1,j-1) +mask3[0][1]*loadedImage->GetGreen(i-1,j) +mask3[0][2]*loadedImage->GetGreen(i-1,j+1)
+mask3[1][0]*loadedImage->GetGreen(i,j-1) +mask3[1][1]*loadedImage->GetGreen(i,j) +mask3[1][2]*loadedImage->GetGreen(i,j+1)
+mask3[2][0]*loadedImage->GetGreen(i+1,j-1) +mask3[2][1]*loadedImage->GetGreen(i+1,j) +mask3[2][2]*loadedImage->GetGreen(i+1,j+1) );
sumBlue = sumBlue + ( mask3[0][0]*loadedImage->GetBlue(i-1,j-1) +mask3[0][1]*loadedImage->GetBlue(i-1,j) +mask3[0][2]*loadedImage->GetBlue(i-1,j+1)
+mask3[1][0]*loadedImage->GetBlue(i,j-1) +mask3[1][1]*loadedImage->GetBlue(i,j) +mask3[1][2]*loadedImage->GetBlue(i,j+1)
+mask3[2][0]*loadedImage->GetBlue(i+1,j-1) +mask3[2][1]*loadedImage->GetBlue(i+1,j) +mask3[2][2]*loadedImage->GetBlue(i+1,j+1) );
//int averageRed = abs(round(sumRed/weight));
//int averageRed = round(sumRed/weight);
double averageRed = (sumRed/weight);
//int averageGreen = abs(round(sumGreen/weight));
//int averageGreen = round(sumGreen/weight);
double averageGreen = (sumGreen/weight);
//int averageBlue = abs(round(sumBlue/weight));
//int averageBlue = round(sumBlue/weight);
double averageBlue = (sumBlue/weight);
//loadedImage->SetRGB(i,j,averageRed,averageGreen,averageBlue);
RedMaskImage[i][j] = averageRed;
GreenMaskImage[i][j] = averageGreen;
BlueMaskImage[i][j] = averageBlue;
}
}
//Making sure all the pixel values lie between 0-255
/* if(loadedImage->GetRed(i,j) <0){loadedImage->SetRGB(i,j,0,loadedImage->GetGreen(i,j),loadedImage->GetBlue(i,j));}
if(loadedImage->GetRed(i,j)> 255){loadedImage->SetRGB(i,j,255,loadedImage->GetGreen(i,j),loadedImage->GetBlue(i,j));}
if(loadedImage->GetGreen(i,j)<0){loadedImage->SetRGB(i,j,loadedImage->GetRed(i,j),0,loadedImage->GetBlue(i,j));}
if(loadedImage->GetGreen(i,j)>255){loadedImage->SetRGB(i,j,loadedImage->GetRed(i,j),255,loadedImage->GetBlue(i,j));}
if(loadedImage->GetBlue(i,j)<0){loadedImage->SetRGB(i,j,loadedImage->GetRed(i,j),loadedImage->GetGreen(i,j),0);}
if(loadedImage->GetBlue(i,j) >255){loadedImage->SetRGB(i,j,loadedImage->GetRed(i,j),loadedImage->GetGreen(i,j),255);}
//End of making 0-255
*/
//finding min and max of image for absolute value conversion
double minIMGR=RedMaskImage[0][0]; double maxIMGR=RedMaskImage[0][0];
double minIMGG=GreenMaskImage[0][0]; double maxIMGG=GreenMaskImage[0][0];
double minIMGB=BlueMaskImage[0][0]; double maxIMGB=BlueMaskImage[0][0];
for(int i=widthcnt;i<newimgWidth;i++)
{
for(int j=heightcnt;j<newimgHeight;j++)
{
if(RedMaskImage[i][j] < minIMGR)
{
minIMGR=RedMaskImage[i][j];
}
if(RedMaskImage[i][j] > maxIMGR)
{
maxIMGR=RedMaskImage[i][j];
}
if(GreenMaskImage[i][j] < minIMGG)
{
minIMGG=GreenMaskImage[i][j];
}
if(GreenMaskImage[i][j] > maxIMGG)
{
maxIMGG=GreenMaskImage[i][j];
}
if(BlueMaskImage[i][j] < minIMGB)
{
minIMGB=BlueMaskImage[i][j];
}
if(BlueMaskImage[i][j] > maxIMGB)
{
maxIMGB=BlueMaskImage[i][j];
}
}
}
for(int i=widthcnt;i<newimgWidth;i++)
{
for(int j=heightcnt;j<newimgHeight;j++)
{
RedMaskImage[i][j] = round((RedMaskImage[i][j] - minIMGR) * (255) / (maxIMGR - minIMGR));
GreenMaskImage[i][j] = round((GreenMaskImage[i][j] - minIMGG) * (255) / (maxIMGG - minIMGG));
BlueMaskImage[i][j] = round((BlueMaskImage[i][j] - minIMGB) * (255) / (maxIMGB - minIMGB));
}
}
for(int i= widthcnt;i< newimgWidth;i++)
{
for(int j=heightcnt;j<newimgHeight;j++)
{
loadedImage->SetRGB(i,j,RedMaskImage[i][j],GreenMaskImage[i][j],BlueMaskImage[i][j]);
}
}
printf(" Finished ROI Convolving3x3\n");
Refresh();
} //END
|
C | //Arif Burak Demiray
//This code is compiled with C99
#ifndef PRODUCT_H //include guard
#define PRODUCT_H
typedef struct product
{
char product_name[30]; // (phone, tshirt, coke etc.)
char product_type[30]; //(electronicDevice, clothing, market etc.)
int price; // (can be integer between 1-1000)
} product;
/**
* This function compares two products
* If their name and type equals returns 1
* If one of them not equals returns 0
* This function uses strcmp two compare two char arrays
*/
int equals(product *source, product *destination);
/**
* This function compares a product's type with given type char array
* If they are equals returns 1 otherwise 0
*/
int type_equals(product *src, char *type);
//This function prints string value of a product
void to_string(product *product);
/**
* This function creates a product with given attributes
* name is the name of the product
* type is the type of the product
* price is the price of the product
*/
product Product(char *name, char *type, int price);
/**
* This function free a list of products
*/
void free_product_list(product *products, int size);
#endif /*PRODUCT_H*/ |
C | #include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
/*
Project Euler: Problem 2
December 19th, 2015
Clay Gardner
https://projecteuler.net/problem=2
Solved the above problem.
Input: 1 4000000
Output: 4613732
Time: sys 0m0.003s
https://www.hackerrank.com/contests/projecteuler/challenges/euler002
Solved for full points.
*/
//Simple dynamic programming iterative approach
//to solving fibonacci and then summing all even numbers
unsigned long sumEvenFibonacci(long number){
long f0=1;
long f1=2;
unsigned long evens=0;
while (f1 < number) {
if (f1%2==0)
evens+=f1;
f1 = f1+f0;
f0 = f1-f0;
}
return evens;
}
int main() {
int count, i;
scanf("%d\n", &count);
for (i = 0; i < count; i++){
unsigned long n;
unsigned long total;
scanf("%ld\n", &n);
total = sumEvenFibonacci(n);
printf("%lu\n", total);
}
return 0;
} |
C | #include "oo_stack.h"
#include "stdio.h"
#include <sys/time.h>
int main()
{
/*
int i;
Stack* stack = stack_new();
for (i = 0; i < 100000; i++)
{
struct Point p = {i, i+1};
stack->push(stack, i);
}
while (!stack->empty(stack))
{
struct Point p = stack->top(stack);
printf("%i %i\n", p.x, p.y);
stack->pop(stack);
}
stack_delete(stack);
*/
struct timeval startv, endv;
gettimeofday(&startv, NULL);
int i;
Stack* stack = stack_new();
for (i = 0; i < 10000000; i++)
stack->push(stack, i);
while (!stack->empty(stack))
stack->pop(stack);
stack_delete(stack);
gettimeofday(&endv, NULL);
printf("%lu\n", endv.tv_usec - startv.tv_usec);
}
|
C | #include <stdio.h>
#include <stdlib.h>
#include "gotoxy.h"
#include "colores.h"
#include <conio.h>
void menu();
void dibujar_marco();
int main(int argc, char *argv[]) {
system("portada.exe");
system("cls");
system("color 7");
color(1,7);
dibujar_marco();
color(0,15);
menu();
getch();
return 0;
}
void menu()
{
int opc;
gotoxy(50,14);printf("Elige una opcion:");
gotoxy(50,16);printf("1.- Supermercado");
gotoxy(50,18);printf("2.- Sistema Operativo");
gotoxy(50,20);printf("3.- Banco");
gotoxy(50,22);scanf("%d",&opc);
system("cls");
switch(opc)
{
case 1:
system("supermercado.exe");
break;
case 2:
system("");
break;
case 3:
system("");
break;
default:
gotoxy(50,24);printf("No seleccionaste una opcion valida");
exit(1);
}
}
void dibujar_marco()
{
int i,j;
for(i=0;i<120;i++)
{
if(i==0)
{
for(j=1;j<31;j++)
{
gotoxy(i,j);printf("%c",177);
}
}
else
{
if(i==119)
{
for(j=1;j<31;j++)
{
gotoxy(i,j);printf("%c",177);
}
}
else
{
gotoxy(i,1);printf("%c",177);
gotoxy(i,30);printf("%c",177);
}
}
}
}
|
C | bool args_parse(ARGUMENTS* args, int argc, char** argv){
int i,c;
for(i=0;i<argc;i++){
if(argv[i][0]=='-'){
switch(argv[i][1]){
case 'v':
for(c=1;argv[i][c]=='v';c++){
args->verbosity=c;
}
break;
case 'f':
if(i>=argc-1){
fprintf(stderr, "Missing config file name\n");
return false;
}
args->cfgfile=argv[++i];
break;
default:
return false;
}
}
else{
fprintf(stderr, "Stray argument %s\n", argv[i]);
return false;
}
}
return true;
}
|
C | // Leonardo Costa
// Vilmar Rangel
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <pthread.h>
#include <time.h>
void* ThreadSoma(int* args) {
int soma = args[0] + args[1];
int tempoSleep = args[2];
printf("Eu sou a thread SOMA (%d) e irei dormir por %d segundos\n", soma, tempoSleep);
sleep(tempoSleep);
printf("Eu sou a Thread SOMA (%d). Ja se passaram %d segundos, entao terminei!\n", soma, tempoSleep);
return NULL;
}
void* ThreadMultiplica(int* args) {
int multiplicacao = args[0] * args[1];
int tempoSleep = args[2];
printf("Eu sou a thread MULTIPLICA (%d) e irei dormir por %d segundos\n", multiplicacao, tempoSleep);
sleep(tempoSleep);
printf("Eu sou a Thread MULTIPLICA (%d). Ja se passaram %d segundos, entao terminei!\n", multiplicacao, tempoSleep);
return NULL;
}
void* ThreadDivide(int* args) {
int divisao = args[0] / args[1];
int tempoSleep = args[2];
printf("Eu sou a thread DIVISAO (%d) e irei dormir por %d segundos\n", divisao, tempoSleep);
sleep(tempoSleep);
printf("Eu sou a Thread DIVISAO (%d). Ja se passaram %d segundos, entao terminei!\n", divisao, tempoSleep);
return NULL;
}
void* ThreadSubtrai(int* args) {
int subtracao = args[0] - args[1];
int tempoSleep = args[2];
printf("Eu sou a thread SUBTRACAO (%d) e irei dormir por %d segundos\n", subtracao, tempoSleep);
sleep(tempoSleep);
printf("Eu sou a Thread SUBTRACAO (%d). Ja se passaram %d segundos, entao terminei!\n", subtracao, tempoSleep);
return NULL;
}
int main() {
srand(time(0));
int numeros[3];
printf("Digite um numero inteiro > 0:");
scanf("%d", &numeros[0]);
printf("Digite um numero inteiro > 0:");
scanf("%d", &numeros[1]);
pthread_t tDivisao, tSoma, tMultiplicacao, tSubtracao;
numeros[2] = rand() % 20 + 1;
printf("\n rand atual: \t %d",numeros[2] );
pthread_create(&(tSoma), NULL, ThreadSoma, numeros);
numeros[2] = rand() % 20 + 1;
pthread_create(&(tMultiplicacao), NULL, ThreadMultiplica, numeros);
numeros[2] = rand() % 20 + 1;
pthread_create(&(tDivisao), NULL, ThreadDivide, numeros);
numeros[2] = rand() % 20 + 1;
pthread_create(&(tSubtracao), NULL, ThreadSubtrai, numeros);
pthread_join(tSoma, NULL);
pthread_join(tMultiplicacao, NULL);
pthread_join(tDivisao, NULL);
pthread_join(tSubtracao, NULL);
return 0;
} |
C | #include "defs.h"
#include "bitmaps.h"
#include "polygon.h"
#include "strings.h"
#define VAR_SCROLL_Y 0xf9
u8 buffer8[4*320*200];
u32 pal32[16];
int done=0;
extern float palette_rgb[48];
void set_palette(u8 *p, u8 v) {
printf("set palette %d", v);
int offset = 32 * v;
for (int i=0; i<16; i++) {
int color = p[offset+i*2] << 8 | p[offset+i*2+1];
int r = (color >> 8) & 15;
int g = (color >> 4) & 15;
int b = color & 15;
r = (r<<4) | r;
g = (g<<4) | g;
b = (b<<4) | b;
pal32[i] = 0xff000000 | (b<<16) | (g<<8) | r;
palette_rgb[i*3] = r/255.0;
palette_rgb[i*3+1] = g/255.0;
palette_rgb[i*3+2] = b/255.0;
}
}
#include "glutils.h"
//#include "glutils4.h"
void *work(void *args);
int main(int argc, char **argv) {
return display_init(argc, argv);
}
typedef struct {
int pc;
int next_pc;
int state;
int next_state;
int paused;
int ticks;
u16 stack[256];
u8 stack_ptr;
} task;
#define NUM_TASKS 64
#define NUM_REGS 256
typedef struct {
int ticks;
task tasks[NUM_TASKS];
u16 vars[NUM_REGS];
} vm;
typedef struct {
u8 *palette;
u8 *bytecode;
u8 *polygons0;
u8 *polygons1;
} data;
void init_vars(vm *v) {
for (u16 i=0; i<256; i++)
v->vars[i] = 0;
v->vars[0xbc]=0x10;
v->vars[0xc6]=0x80;
v->vars[0xf2]=6000;
v->vars[0xdc]=33;
v->vars[0xe4]=20;
}
void init_tasks(vm *v) {
for (int i=0; i<NUM_TASKS; i++) {
v->tasks[i] = (task){ -1, -1, 0, 0, 0, 0, {0}, 0 };
}
v->tasks[0].pc = 0;
}
s16 to_signed(u16 value, u16 bits) {
u16 mask = 1 << (bits - 1);
return value - ((value & mask) << 1);
}
void print_stack(task *t) {
printf("stack: ");
for (int i=t->stack_ptr; i>0; i--) {
printf("%d: 0x%04x ", i-1, t->stack[i]);
}
}
u8 get_page(u8 num) {
switch (num) {
case 0xff: return current_page2; break;
case 0xfe: return current_page1; break;
case 0x0 ... 0x3: return num; break;
default: printf("illegal page\n"); return 0; break;
}
}
void cpy(u32 dst, u32 src, u32 n) {
for (u16 i=0; i<n; i++)
buffer8[dst+i] = buffer8[src+i];
}
void copy_page_f(u8 src, u8 dst, int vscroll) {
dst = get_page(dst);
if (src >= 0xfe) {
src = get_page(src);
cpy(dst*PAGE_SIZE, src*PAGE_SIZE, PAGE_SIZE);
} else {
//if (0 == (src & 0x80)) vscroll = 0;
src = get_page(src & 3);
if (dst == src) return;
u32 dst_offset = dst * PAGE_SIZE;
u32 src_offset = src * PAGE_SIZE;
if (0 == vscroll)
cpy(dst_offset, src_offset, PAGE_SIZE);
else {
if (vscroll > -SCR_W && vscroll< SCR_W) {
u16 h = vscroll * SCR_W;
if (vscroll < 0) cpy(dst_offset, src_offset-h, PAGE_SIZE);
else cpy(dst_offset+h, src_offset, PAGE_SIZE);
}
}
}
}
void fill_page(u8 num, u8 color) {
u8 pg = get_page(num);
fill_buf(buffer8+pg*PAGE_SIZE, PAGE_SIZE, color);
}
#define F8(c, t) ((c)[(t)->pc++])
#define F16(c, t) (F8(c,t) << 8 | F8(c,t))
#define PUSH(t, v) ((t)->stack[(t)->stack_ptr++] = (v))
#define POP(t) ((t)->stack[--((t)->stack_ptr)])
/* jump table */
void *ops[256];
void unk(vm *v, task *t, data *d) { printf("unimplemented\n"); getchar(); gl_ok=0; }
void movi(vm *v, task *t, data *d) {
u8 arg0 = F8(d->bytecode, t);
s16 imm = to_signed(F16(d->bytecode, t), 16);
v->vars[arg0] = imm;
printf("MOVI VAR[0x%02x] = %d", arg0, imm);
}
void call(vm *v, task *t, data *d) {
u16 arg = F16(d->bytecode, t);
printf("call 0x%04x ", arg);
PUSH(t, t->pc);
t->pc = arg;
print_stack(t);
}
void ret(vm *v, task *t, data *d) {
u16 prev_pc = POP(t);
t->pc = prev_pc;
print_stack(t);
}
void yield(vm *v, task *t, data *d) { printf("yield"); t->paused = 1; }
void select_page(vm *v, task *t, data *d) { current_page0 = get_page(F8(d->bytecode, t)); printf("select page %d", current_page0); }
void fillpg(vm *v, task *t, data *d) { printf("fill page"); u8 num = F8(d->bytecode, t); u8 color = F8(d->bytecode, t); fill_page(num, color); }
void update_display(vm *v, task *t, data *d) {
u8 arg0 = F8(d->bytecode, t);
v->vars[0xf7] = 0;
if (0xfe != arg0) {
if (0xff == arg0) {
u8 tmp = current_page1;
current_page1 = current_page2;
current_page2 = tmp;
} else {
current_page1 = get_page(arg0);
}
}
tex_update_needed=1;
//printf("update_display 0x%02x", arg0);
usleep(1000);
}
void install_task(vm *v, task *t, data *d) {
u8 num = F8(d->bytecode, t);
u16 off = F16(d->bytecode, t);
v->tasks[num].next_pc = off;
//printf("install_task %d -> 0x%04x", num, off);
}
void remove_task(vm *v, task *t, data *d) {
t->pc = -1;
t->paused = 1;
printf("remove task");
}
void put_pixel(u8 page, u16 x, u16 y, u8 color) {
u16 offset = page*PAGE_SIZE + (y*SCR_W+x);
buffer8[offset] = color;
}
void draw_bitmap(u8 id) {
printf(", draw bitmap %u ", id);
unsigned char *buf = bitmaps[id];
u32 offset=0;
for (u16 y=0; y<200; ++y) {
for (u16 x=0; x<320; x+=8) {
for (u8 b=0; b<8; ++b) {
s8 mask = 1 << (7-b);
s8 color = 0;
for (u32 p=0; p<4; ++p) {
if (0 != (buf[offset+p*8000] & mask)) {
color |= (1 << p);
}
}
put_pixel(0, x+b, y, color);
}
offset+=1;
}
}
}
void update_res(vm *v, task *t, data *d) {
u16 arg = F16(d->bytecode, t);
if (arg == 18 || arg == 19 || arg == 71)
draw_bitmap(arg);
printf("update res 0x%04x", arg);
/* end of intro */
if (16002 == arg) { done=1; };
/* ... */
}
void play_sound(vm *v, task *t, data *d) {
u16 arg = F16(d->bytecode, t);
u8 arg0 = F8(d->bytecode, t);
u8 arg1 = F8(d->bytecode, t);
u8 arg2 = F8(d->bytecode, t);
printf("play sound num=%04x freq=%02x volume=%02x channel=%02x", arg, arg0, arg1, arg2);
}
void play_music(vm *v, task *t, data *d) {
u16 arg0 = F16(d->bytecode, t);
u16 arg1 = F16(d->bytecode, t);
u8 arg2 = F8(d->bytecode, t);
printf("play music 0x%04x 0x%04x 0x%02x", arg0, arg1, arg2);
}
void mov(vm *v, task *t, data *d) {
u8 dst = F8(d->bytecode, t);
u8 src = F8(d->bytecode, t);
printf("MOV var[%u] = var[%u]", dst, src);
v->vars[dst] = v->vars[src];
}
void add(vm *v, task *t, data *d) {
u8 dst = F8(d->bytecode, t);
u8 src = F8(d->bytecode, t);
printf("ADD var[%u] += var[%u]", dst, src);
v->vars[dst] += v->vars[src];
}
void copy_page(vm *v, task *t, data *d) {
u8 src = F8(d->bytecode, t);
u8 dst = F8(d->bytecode, t);
printf("copy page var[%u] = var[%u]", dst, src);
copy_page_f(src, dst, v->vars[VAR_SCROLL_Y]);
}
void addi(vm *v, task *t, data *d) {
u8 n = F8(d->bytecode, t);
s16 imm = to_signed(F16(d->bytecode, t), 16);
printf("ADDI var[%u] += %d", n, imm);
v->vars[n] += imm;
}
void reset_thr(vm *v, task *t, data *d) {
u8 start = F8(d->bytecode, t);
u8 end = F8(d->bytecode, t);
u8 state = F8(d->bytecode, t);
if (2==state) {
for (int i=start;i<=end;i++) {
v->tasks[i].next_pc = -2;
}
} else {
for (int i=start;i<=end;i++) {
v->tasks[i].next_state = state;
}
}
}
void jmp_nz(vm *v, task *t, data *d) {
u8 n = F8(d->bytecode, t);
v->vars[n] -= 1;
u16 addr = F16(d->bytecode, t);
printf("JMP NZ %u 0x%04x", v->vars[n], addr);
if (0 != v->vars[n]) t->pc = addr;
}
void draw_char(u8 page, char chr, u8 color, int x, int y) {
if (x < (320/8) && y < (200 - 8)) {
for (u8 j=0; j<8; j++) {
u8 mask = font[(chr-32) * 8 + j];
for (u8 i=0; i<8; i++) {
if (0 != (mask & (1 << (7-i)))) {
put_pixel(page, x*8+i, y+j, color);
}
}
}
}
}
void draw_string(vm *v, task *t, data *d) {
u16 num = F16(d->bytecode, t);
u8 x = F8(d->bytecode, t);
u8 y = F8(d->bytecode, t);
u8 color = F8(d->bytecode, t);
const char *s = strings_en[num];
u8 x0 = x;
printf("draw_string 0x%04x, x=%d, y=%d, [%s]", num, x, y, s);
for (int i=0; i<strlen(s); i++) {
char chr = s[i];
if (10 == chr) { y+= 8; x = x0; }
else { draw_char(current_page0, chr, color, x, y);
x+=1;
}
}
}
void jmp_c(vm *v, task *t, data *d) {
u8 op = F8(d->bytecode, t);
u8 b = v->vars[F8(d->bytecode, t)];
u8 a;
if (op & 0x80) a = v->vars[F8(d->bytecode, t)];
else if (op & 0x40) a = to_signed(F16(d->bytecode, t), 16);
else a = F8(d->bytecode, t);
printf("JMP C op=%u b=0x%02x, a=0x%02x", op, b, a);
u16 addr = F16(d->bytecode, t);
switch (op & 7) {
case 0:
if (b == a) t->pc = addr;
break;
case 1:
if (b != a) t->pc = addr;
break;
case 2:
if (b > a) t->pc = addr;
break;
case 3:
if (b >= a) t->pc = addr;
break;
case 4:
if (b > a) t->pc = addr;
break;
case 5:
if (b <= a) t->pc = addr;
break;
default:
break;
}
}
void jmp(vm *v, task *t, data *d) {
u16 off = F16(d->bytecode, t);
t->pc = off;
printf("JMP 0x%04x", off);
}
void set_pal(vm *v, task *t, data *d) {
u16 arg = F16(d->bytecode, t);
set_palette(d->palette, arg >> 8);
}
void init_ops(void(* def)(vm *v, task*, data *d)) {
for (int i=0; i<256; i++) ops[i] = def;
ops[0x00] = &movi;
ops[0x01] = &mov;
ops[0x02] = &add;
ops[0x03] = &addi;
ops[0x04] = &call;
ops[0x05] = &ret;
ops[0x06] = &yield;
ops[0x0d] = &select_page;
ops[0x07] = &jmp;
ops[0x08] = &install_task;
ops[0x09] = &jmp_nz;
ops[0x0a] = &jmp_c;
ops[0x0b] = &set_pal;
ops[0x0c] = &reset_thr;
ops[0x0e] = &fillpg;
ops[0x0f] = ©_page;
ops[0x10] = &update_display;
ops[0x11] = &remove_task;
ops[0x12] = &draw_string;
ops[0x18] = &play_sound;
ops[0x19] = &update_res;
ops[0x1a] = &play_music;
}
void draw_shape(u8 *p, u16 offset, u8 color, u8 zoom, u8 x, u8 y);
void draw_shape_parts(u8 *data, u16 offset, u8 zoom, u8 x, u8 y) {
u8 x0 = x - ( data[offset++] * zoom / 64 );
u8 y0 = y - ( data[offset++] * zoom / 64 );
u8 count = data[offset++];
printf("draw_shape_parts x0=0x%02x, y0=0x%02x, count=0x%02x\n", x0, y0, count);
for (u16 i=0; i<=count; i++) {
u16 addr = ( data[offset] << 8 ) | data[offset+1];
offset += 2;
u16 x1 = x0 + ( data[offset++] * zoom/64 );
u16 y1 = y0 + ( data[offset++] * zoom/64 );
u8 color = 0xff;
if (addr & 0x8000) {
color = data[offset] & 0x7f; offset += 2;
}
draw_shape(data, ((addr<<1) & 0xfffe), color, zoom, x1, y1);
}
}
void draw_shape(u8 *data, u16 offset, u8 color, u8 zoom, u8 x, u8 y) {
printf("draw_shape offset=0x%04x ", offset);
u8 code = data[offset++];
printf("code=0x%04x %02x\n", code, data[0]);
if (code >= 0xc0) {
if (color & 0x80) {
color = code & 0x3f;
}
fill_polygon(data, offset, color, zoom, x, y);
} else {
if (2 == (code & 0x3f)) {
draw_shape_parts(data, offset, zoom, x, y);
}
}
}
void draw_sprite(vm *v, task *t, data *d, u8 op) {
u16 offset = (F16(d->bytecode, t) << 1) & 0xfffe;
u16 x = F8(d->bytecode, t);
if (0 == (op & 0x20)) {
if (0 == (op & 0x10)) {
x = (x<<8) | F8(d->bytecode, t);
} else {
x = v->vars[x];
}
} else {
if (op & 0x10) {
x+=256;
}
}
u16 y = F8(d->bytecode, t);
if (0 == (op & 0x8)) {
if (0 == (op & 0x4)) {
y = (y<<8) | F8(d->bytecode, t);
} else {
y = v->vars[y];
}
}
u8 *polydata = d->polygons0;
u8 zoom = 64;
if (0 == (op & 0x2)) {
if (op & 0x1) {
zoom = v->vars[F8(d->bytecode, t)];
}
} else {
if (op & 0x1) {
polydata = d->polygons1;
} else {
zoom = F8(d->bytecode, t);
}
}
//printf("draw sprite 0x%04x 0x%02x 0x%02x", offset, x, y);
draw_shape(polydata, offset, 0xff, zoom, x, y);
}
void draw_poly_bkgd(vm *v, task *t, data *d, u8 op) {
u16 arg = ((((u16)op) << 8 | F8(d->bytecode, t)) << 1) & 0xfffe;
u8 arg0 = F8(d->bytecode, t);
u8 arg1 = F8(d->bytecode, t);
if ((arg1 - 199) > 0) { arg0 += arg1 - 199; arg0 = 199; }
draw_shape(d->polygons0, arg, 0xff, 64, arg0, arg1);
}
void execute_task(vm *v, int i, data *d) {
task *t = &(v->tasks[i]);
v->tasks[i].ticks = 0;
v->tasks[i].stack_ptr = 0;
while (!v->tasks[i].paused && gl_ok && !done) {
u8 op = d->bytecode[t->pc++];
printf("\n[%12.6f s, ticks %07d] task %2d tick %4d off 0x%04x op 0x%02x | ", get_time() - t0, v->ticks++, i, (t->ticks)++, t->pc-1, op);
switch (op) {
case 0x80 ... 0xff:
draw_poly_bkgd(v, t, d, op);
break;
case 0x40 ... 0x7f:
draw_sprite(v, t, d, op);
break;
default:
((void(*)(vm*, task*, data*))ops[op])(v, t, d);
break;
}
}
}
void run_tasks(vm *v, data *d) {
for (int i=0; i<NUM_TASKS; i++) {
if (-1 != v->tasks[i].next_pc) {
v->tasks[i].pc = v->tasks[i].next_pc == -2 ? -1 : v->tasks[i].next_pc;
v->tasks[i].next_pc = -1;
}
}
for (int i=0; i<NUM_TASKS; i++) {
if (0==v->tasks[i].state)
if (-1 != v->tasks[i].pc) {
v->tasks[i].paused = 0;
execute_task(v, i, d);
}
}
}
void *work(void *args) {
while (!gl_ok) usleep(10);
byte_array palette, bytecode, polygons;
read_array(&palette, "file17");
read_array(&bytecode, "file18");
read_array(&polygons, "./dump/poly19");
init_bitmaps();
int DEFAULT_TICKS = -1;
int MAX_TICKS = args ? strtol((char*)args, NULL, 10) : DEFAULT_TICKS;
printf("MAX_TICKS=%d\n", MAX_TICKS);
vm vm0;
init_tasks(&vm0);
init_vars(&vm0);
init_ops(&unk);
init_strings();
data d = {palette.bytes, bytecode.bytes, polygons.bytes};
int i=0;
while (gl_ok && !done) {
if (1==paused) { if (1!=step) {usleep(1000); continue; } else {step=0;}}
putchar('.'); fflush(stdout);
run_tasks(&vm0, &d);
if (i>=MAX_TICKS && MAX_TICKS>0) paused=1;
i++;
}
free(palette.bytes);
free(bytecode.bytes);
free(polygons.bytes);
return 0;
}
|
C | /* server.c */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/socket.h>
#include <netinet/in.h>
#define MAXLINE 80
#define SERV_PORT 8100
int main(void)
{
struct sockaddr_in servaddr, cliaddr;
socklen_t cliaddr_len;
int listenfd, connfd;
char buf[MAXLINE];
char str[20];
int i, n;
listenfd = socket(AF_INET, SOCK_STREAM, 0);
if(listenfd==-1)
{
printf("listen err\n");
return 0;
}
bzero(&servaddr, sizeof(servaddr));
servaddr.sin_family = AF_INET;
servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
servaddr.sin_port = htons(SERV_PORT);
if(bind(listenfd, (struct sockaddr *)&servaddr, sizeof(servaddr)))
{
printf("bind err\n");
return 0;
}
if(listen(listenfd, 20))
{
printf("bind err\n");
return 0;
}
printf("Accepting connections ...\n");
while (1) {
cliaddr_len = sizeof(cliaddr);
connfd = accept(listenfd,(struct sockaddr *)&cliaddr, &cliaddr_len);
if ( connfd < 0)
{
printf("Server Accept Failed!\n");
return 0;
}
n = recv(connfd, buf, MAXLINE,0);
inet_ntop(AF_INET, (void*)&cliaddr, str, sizeof(str));
printf("received from %s at PORT %d\n",str,ntohs(cliaddr.sin_port));
for (i = 0; i < n; i++)
buf[i] = toupper(buf[i]);
send(connfd, buf, n,0);
send(connfd,"woshiyigebing\n", 20,0);
//close(connfd);
}
close(listenfd);
}
|
C | #include<stdio.h> // header file
main(){
int n,arr[1000],i,temp; //datatypes assigned
scanf("%d",&n); //reading value
for(i=0;i<n;i++){
scanf("%d ",&arr[i]); // reading values and sorring in the array "arr[]"
}
for(i=0;i<n/2;i++){
temp=arr[i]; //swaping array elements
arr[i]=arr[n-i-1];
arr[n-i-1]=temp;
}
for(i=0;i<n;i++){
printf("%d ",arr[i]); //printing values
}
return(0);
}
|
C | /*
* APICommand.c
*
* Created on: Dec 19, 2011
* Author: ParallelsWin7
*/
#include <stdio.h> //not needed in CCS
#include "APICommand.h"
//////////////////////////////////////////////////////////////////////////
//////////// API CONSTRUCTORS //////////////
//////////////////////////////////////////////////////////////////////////
void ApiCmd_ctor(ApiCmd *cmd, Type_enum type, uint8_t channel, Io_enum io, Feature_enum feature, Param_enum param) {
cmd->type = type;
cmd->channel = channel;
cmd->chan_io = io;
cmd->feature = feature;
cmd->param = param;
cmd->retry_count = 0;
}
void ApiRead_ctor(ApiRead *read, uint8_t channel, Io_enum io, Feature_enum feature, Param_enum param) {
ApiCmd_ctor(&read->super, READ, channel, io, feature, param);
(read->super).cmd_count = 64;
}
void ApiWrite_ctor(ApiWrite *write, uint8_t channel, Io_enum io, Feature_enum feature, Param_enum param, float value) {
ApiCmd_ctor(&write->super, WRITE, channel, io, feature, param);
write->value = value;
(write->super).cmd_count = 72;
}
void ApiAck_ctor(ApiAck *ack, uint8_t count, float value) {
//Maybe go fetch the previous instruction record and populate that data here? TODO
ApiCmd_ctor(&ack->super, ACK, 0, INPUT, NOF, NOP);
(ack->super).cmd_count = count;
ack->value = value;
}
void ApiNot_ctor(ApiNot *not, uint8_t channel, Io_enum io, Feature_enum feature, uint8_t message) {
ApiCmd_ctor(¬->super, NOT, channel, io, feature, NOP);
not->message = message;
}
//////////////////////////////////////////////////////////////////////////
//////////// API GETTERS //////////////
//////////////////////////////////////////////////////////////////////////
void* Api_get_callback(ApiCmd *cmd) {
return cmd->callback;
}
uint8_t Api_get_cmd_count(ApiCmd *cmd) {
return cmd->cmd_count;
}
//////////////////////////////////////////////////////////////////////////
//////////// API SETTERS //////////////
//////////////////////////////////////////////////////////////////////////
void Api_set_callback(ApiCmd *cmd, void (*callback)(void*, float)) {
cmd->callback = callback;
}
void Api_set_cmd_count(ApiCmd *cmd, uint8_t cmd_count) {
cmd->cmd_count = cmd_count;
}
void Api_set_retry_count(ApiCmd *cmd, uint8_t retry_count) {
cmd->retry_count = retry_count;
}
void Api_inc_retry_count(ApiCmd *cmd) {
cmd->retry_count = cmd->retry_count + 1;
}
void Api_reset_retry_count(ApiCmd *cmd) {
cmd->retry_count = 0;
}
//////////////////////////////////////////////////////////////////////////
//////////// API FORMATTERS //////////////
//////////////////////////////////////////////////////////////////////////
//Format an ApiRead object into 3 bytes
void ApiRead_frmtr(ApiRead *cmd, char *formatted) {
//first byte contains type, channel #, and i/o status
formatted[0] = Api_common_front(&(cmd->super));
//get the feature and parameter numbers in 8bit integer
uint8_t feat = (int) ((cmd->super).feature);
uint8_t param = (int) ((cmd->super).param);
//shift the feature to the left by 4 and add param to make 2nd char (byte)
formatted[1] = (char) ((feat << 4) + param);
//command count is 3rd char (byte)
formatted[2] = (char) (cmd->super).cmd_count;
}
//Format an ApiWrite object into 7 bytes
void ApiWrite_frmtr(ApiWrite *cmd, char *formatted) {
//first byte contains type, channel #, and i/o status
formatted[0] = Api_common_front(&(cmd->super));
//get the feature and parameter numbers in 8bit integer
uint8_t feat = (int) ((cmd->super).feature);
uint8_t param = (int) ((cmd->super).param);
//shift the feature to the left by 4 and add param to make 2nd char (byte)
formatted[1] = (char) ((feat << 4) + param);
//command count is 3rd char (byte)
formatted[2] = (char) (cmd->super).cmd_count;
volatile CONVERTER Converter;
Converter.value = cmd->value;
//bytes 4-6 contain the value to write (MSB in byte 4, LSB at end of byte 6)
formatted[3] = Converter.stored[3];
formatted[4] = Converter.stored[2];
formatted[5] = Converter.stored[1];
formatted[6] = Converter.stored[0];
}
//Format an ApiAck object into 6 bytes
void ApiAck_frmtr(ApiAck *cmd, char *formatted) {
//first byte contains type, channel #, and i/o status
formatted[0] = 0x80;
//command count is 2nd char (byte)
formatted[1] = (char) (cmd->super).cmd_count;
volatile CONVERTER Converter;
Converter.value = cmd->value;
//bytes 4-6 contain the value to write (MSB in byte 4, LSB at end of byte 6)
formatted[2] = Converter.stored[3];
formatted[3] = Converter.stored[2];
formatted[4] = Converter.stored[1];
formatted[5] = Converter.stored[0];
}
//Format an ApiNot object into 2 bytes
void ApiNot_frmtr(ApiNot *cmd, char *formatted) {
//first byte contains type, channel #, and i/o status
formatted[0] = Api_common_front(&(cmd->super));
//get the feature and parameter numbers in 8bit integer
uint8_t feat = (int) ((cmd->super).feature);
uint8_t message = (int) (cmd->message);
//shift the feature to the left by 4 and add param to make 2nd char (byte)
formatted[1] = (char) ((feat << 4) + message);
}
//////////////////////////////////////////////////////////////////////////
//////////// API RECONSTRUCTORS //////////////
//////////////////////////////////////////////////////////////////////////
//Reconstruct an ApiRead object from 3 bytes
void ApiRead_rector(ApiRead *cmd, char *formatted) {
//use first char to get channel number and io status with Api_decode_x functions
//get feature and param from 2nd byte
Feature_enum feat = (Feature_enum) ((formatted[1] & 0xF0) >> 4);
Param_enum param = (Param_enum) (formatted[1] & 0x0F);
ApiRead_ctor(cmd, Api_decode_channel(formatted[0]), Api_decode_io(formatted[0]), feat, param);
//command count comes from 3rd byte
(cmd->super).cmd_count = formatted[2];
}
//Reconstruct an ApiWrite object from 7 bytes
void ApiWrite_rector(ApiWrite *cmd, char *formatted) {
//use first char to get channel number and io status with Api_decode_x functions
//get feature and param from 2nd byte
Feature_enum feat = (Feature_enum) ((formatted[1] & 0xF0) >> 4);
Param_enum param = (Param_enum) (formatted[1] & 0x0F);
//bytes 3 through 6 contain the floating point value
volatile CONVERTER Converter;
Converter.stored[0] = formatted[6];
Converter.stored[1] = formatted[5];
Converter.stored[2] = formatted[4];
Converter.stored[3] = formatted[3];
ApiWrite_ctor(cmd, Api_decode_channel(formatted[0]), Api_decode_io(formatted[0]), feat, param, Converter.value);
(cmd->super).cmd_count = formatted[2];
}
//Reconstruct an ApiWrite object from 7 bytes
void ApiAck_rector(ApiAck *cmd, char *formatted) {
//bytes 3 through 6 contain the floating point value
volatile CONVERTER Converter;
Converter.stored[0] = formatted[5];
Converter.stored[1] = formatted[4];
Converter.stored[2] = formatted[3];
Converter.stored[3] = formatted[2];
ApiAck_ctor(cmd, formatted[1], Converter.value);
}
//Reconstruct an ApiRead object from 3 bytes
void ApiNot_rector(ApiNot *cmd, char *formatted) {
//use first char to get channel number and io status with Api_decode_x functions
//get feature and param from 2nd byte
Feature_enum feat = (Feature_enum) ((formatted[1] & 0xF0) >> 4);
uint8_t message = formatted[1] & 0x0F;
ApiNot_ctor(cmd, Api_decode_channel(formatted[0]), Api_decode_io(formatted[0]), feat, message);
}
//////////////////////////////////////////////////////////////////////////
//////////// API ENCODERS //////////////
//////////////////////////////////////////////////////////////////////////
//Output a single byte containing Api command type, channel number, and io status
char Api_common_front(ApiCmd *cmd) {
uint8_t type, chan, io;
//get type and shift it 6 digits left
type = ((int) cmd->type) << 6;
//get channel number, subtract one to force binary and shift left by 2
chan = (cmd->channel - 1) << 2;
//shift left io flag. don't care about the 0 carried in.
io = ((int) cmd->chan_io) << 1;
//add it all up and return
return (char) (type+chan+io);
}
///////////////////////////////////////////////////////////////////////////
//////////// API BYTE DECODERS //////////////
//////////////////////////////////////////////////////////////////////////
//Return channel from Api_common_front style byte
uint8_t Api_decode_channel(char x) {
return ((x & 0x3C) >> 2) + 1;;
}
//Return message type from Api_common_front style byte
Type_enum Api_decode_type(char x) {
return (Type_enum) ((x & 0xC0) >> 6);
}
//Return io status from Api_common_front style byte
Io_enum Api_decode_io(char x) {
return (Io_enum) ((x & 0x02) >> 1);
}
Feature_enum Api_decode_feature(char x) {
return (Feature_enum) ((x & 0xF0) >> 4);
}
Param_enum Api_decode_param(char x) {
return (Param_enum) (x & 0x0F);
}
///////////////////////////////////////////////////////////////////////////
//////////// API INSPECTION TOOLS //////////////
///////////////////////////////////////////////////////////////////////////
void ApiCmd_inspect(ApiCmd *cmd) {
printf("type: %d\n", (int) cmd->type);
printf("channel: %d\n", cmd->channel);
printf("channel io:%d \n", (int) cmd->chan_io);
printf("feature: %d\n", (int) cmd->feature);
printf("parameter: %d\n", (int) cmd->param);
printf("cmd_count: %d\n", cmd->cmd_count);
}
void ApiRead_inspect(ApiRead *cmd) {
ApiCmd_inspect(&cmd->super);
printf("\n");
}
void ApiWrite_inspect(ApiWrite *cmd) {
ApiCmd_inspect(&cmd->super);
printf("value: %lf\n\n", cmd->value);
}
void ApiAck_inspect(ApiAck *cmd) {
ApiCmd_inspect(&cmd->super);
printf("value: %lf\n\n", cmd->value);
}
void ApiNot_inspect(ApiNot *cmd) {
ApiCmd_inspect(&cmd->super);
printf("message: %d\n\n", cmd->message);
}
|
C | // Using operator sizeof to determine standard data type size
#include <stdio.h>
int main(int argc, char const *argv[])
{
char c;
short s;
int i;
long l;
long long ll;
float f;
double d;
long double ld;
int array[20];
int *ptr = array;
printf(" sizeof c = %u\tsizeof(char) = %u\n", sizeof c, sizeof(char));
printf(" sizeof s = %u\tsizeof(short) = %u\n", sizeof s, sizeof(short));
printf(" sizeof i = %u\tsizeof(int) = %u\n", sizeof i, sizeof(int));
printf(" sizeof l = %u\tsizeof(long) = %u\n", sizeof l, sizeof(long));
printf(" sizeof ll = %u\tsizeof(long long) = %u\n", sizeof ll, sizeof(long long));
printf(" sizeof f = %u\tsizeof(float) = %u\n", sizeof f, sizeof(float));
printf(" sizeof d = %u\tsizeof(double) = %u\n", sizeof d, sizeof(double));
printf(" sizeof ld = %u\tsizeof(long double) = %u\n", sizeof ld, sizeof(long double));
printf("sizeof array = %u\n", sizeof array);
printf(" sizeof ptr = %u\n", sizeof ptr);
return 0;
} |
C | #include<unistd.h>
void ft_print(char printnumbr)
{
write(1, &printnumbr, 1);
}
void ft_putnbr(int nb)
{
int number;
if (nb == -2147483648)
{
ft_print('-');
ft_print('2');
ft_putnbr(147483648);
return ;
}
if (nb >= 0)
number = nb;
else
{
ft_print('-');
number = nb * -1;
}
if (number >= 10)
{
ft_putnbr(number / 10);
ft_print(number % 10 + 48);
}
else
ft_print(number + 48);
}
|
C | #include<stdio.h>
#include<ctype.h>
int main() {
int count = 0;
char ch;
printf("Enter a sentence: ");
while( (ch = getchar()) != '\n')
{
ch = toupper(ch);
if (ch == 'A' || ch == 'E' || ch == 'I' || ch == 'O' || ch == 'U')
{
/* code */
count += 1;
}
}
printf("Your sentence contains %d vowels\n", count);
} |
C | #include "tort/fiber.h"
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
static tort_fiber_t *fiber_a, *fiber_b;
static tort_fiber_func_DECL(a);
static tort_fiber_func_DECL(b);
static
tort_fiber_func_DECL(a)
{
static int n = 10;
assert(_tort_fiber_ptr->status == RUNNING);
fiber_a = _tort_fiber_ptr;
fprintf(stderr, "fiber_a = @%p\n", fiber_a);
while ( n -- ) {
// fprintf(stderr, "a: fiber = %p\n", _tort_fiber);
assert(_tort_fiber_ptr == fiber_a);
assert(fiber_a->status == RUNNING);
fprintf(stderr, "a(%s) @%p @%p: n = %d\n", (char*) data, _tort_fiber_ptr, &_tort_fiber_ptr, n);
if ( ! fiber_b ) {
__tort_fiber_new(fiber_a, b, "from a()", (size_t) 0);
assert(fiber_b->status == PAUSED);
} else {
assert(fiber_b->status == PAUSED);
__tort_fiber_yield(fiber_a, fiber_b);
assert(fiber_b->status == PAUSED);
}
}
return "a return";
}
static
tort_fiber_func_DECL(b)
{
static int n = 10;
fiber_b = _tort_fiber_ptr;
fprintf(stderr, "fiber_b = @%p\n", fiber_b);
while ( n -- ) {
// fprintf(stderr, "b: fiber = @%p\n", _tort_fiber_ptr);
assert(_tort_fiber_ptr == fiber_b);
assert(fiber_b->status == RUNNING);
fprintf(stderr, "b(%s) @ @%p @%p: n = %d\n", (char*) data, _tort_fiber_ptr, &_tort_fiber_ptr, n);
assert(fiber_a->status == PAUSED);
__tort_fiber_yield(fiber_b, fiber_a);
assert(fiber_a->status == PAUSED);
}
return "b return";
}
int main(int argc, char **argv)
{
void *result;
fprintf(stderr, "main() @%p\n", &argv);
result = __tort_fiber_new(0, a, "from main()", (size_t) 0);
fprintf(stderr, " => %s\n", (char*) result);
assert(fiber_a->status != RUNNING);
assert(fiber_b->status != RUNNING);
return 0;
}
|
C | // Name-Aman Kumar Kanojia
// Roll no.-201851014
#include <stdio.h>
#include <stdlib.h>
int inverse(int a)
{
for(int i = 1; i < 27; ++i)
{
if((a*i)%26 == 1)
return i;
}
return 0;
}
void Encryption(char arr[], int n, int a, int b)
{
printf("The cipher text is- ");
for(int i = 0; i < n; ++i)
{
if(islower(arr[i]))
{
arr[i] = arr[i] - 'a';
arr[i] = (a*arr[i] + b)%26;
arr[i] = arr[i] + 'a';
}
else
{
arr[i] = arr[i] - 'A';
arr[i] = (a*arr[i] + b)%26;
arr[i] = (arr[i] + 'A');
}
printf("%c", arr[i]);
}
printf("\n");
}
void Decryption(char arr[], int n, int a, int b)
{
printf("The decrypted text is- ");
int ainv = inverse(a);
for(int i = 0; i < n; ++i)
{
if(islower(arr[i]))
{
arr[i] = arr[i] - 'a';
arr[i] = (ainv*(arr[i] + 26 - b)) % 26;
arr[i] = arr[i] + 'a';
}
else
{
arr[i] = arr[i] - 'A';
arr[i] = (ainv*(arr[i] + 26 - b)) % 26;
arr[i] = arr[i] + 'A';
}
printf("%c", arr[i]);
}
printf("\n");
}
int main()
{
int n;
printf("Enter the length of string- ");
scanf("%d", &n);
getchar();
char arr[n+1];
printf("Enter the plain text- ");
scanf("%s", arr);
int a, b;
int flag = 0;
while(flag == 0)
{
printf("Enter a and b- ");
scanf("%d %d", &a, &b);
if(inverse(a))
flag = 1;
else
printf("Please choose valid a.\n");
}
Encryption(arr, n, a, b);
Decryption(arr, n, a, b);
}
|
C | // gcc consumer.c -o con.out
// Include header files
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include "shm_com.h" // header file containing the structure of shared memory
// Main function
int main()
{
// User defined flag
int running = 1;
// Null pointer
void *shared_memory = (void *)0;
// Instance of shared datastructure
struct shared_use_st *shared_stuff;
// Variable to store identifier of shared memory
int shmid;
srand((unsigned int)getpid());
// Create the shared memory space
shmid = shmget((key_t)1234, sizeof(struct shared_use_st), 0666 | IPC_CREAT);
// Check the successful creation of the shared memory
if (shmid == -1) {
fprintf(stderr, "shmget failed\n");
exit(EXIT_FAILURE);
}
// Attach the created shared memory
shared_memory = shmat(shmid, (void *)0, 0);
// Check the successful attachment of the shared memory
if (shared_memory == (void *)-1) {
fprintf(stderr, "shmat failed\n");
exit(EXIT_FAILURE);
}
// Initialize the shared memory for usage
printf("Memory attached at %X\n", (int)shared_memory);
shared_stuff = (struct shared_use_st *)shared_memory;
shared_stuff->written_by_you = 0;
// Start reading from the shared memory
while(running) {
if (shared_stuff->written_by_you) {
printf("You wrote: %s", shared_stuff->some_text);
sleep( rand() % 4 ); /* make the other process wait for us ! */
shared_stuff->written_by_you = 0;
// Magic string end to stop the program
if (strncmp(shared_stuff->some_text, "end", 3) == 0) {
running = 0;
}
}
}
// Shared memory is detached and then deleted
if (shmdt(shared_memory) == -1) {
fprintf(stderr, "shmdt failed\n");
exit(EXIT_FAILURE);
}
if (shmctl(shmid, IPC_RMID, 0) == -1) {
fprintf(stderr, "shmctl(IPC_RMID) failed\n");
exit(EXIT_FAILURE);
}
exit(EXIT_SUCCESS);
}
|
C | /*
* key.c
*
* Created on: Apr 3, 2021
* Author: Francis
*/
#include "key.h"
//按键扫描函数
//mode==1时,按键按下亮,松开灭
//mode==0时,按键按下亮,再次按下灭
uint8_t KeyScan(uint8_t mode)
{
static uint8_t key_up = 1;
if(mode == 1){
key_up = 1;
}
if(key_up && (KEY0 == GPIO_PIN_RESET || KEY1 == GPIO_PIN_RESET || KEY2 == GPIO_PIN_RESET || KY_UP == GPIO_PIN_SET)){
HAL_Delay(10);
key_up = 0;
if(KEY0 == GPIO_PIN_RESET){
return KEY0_PRES;
}else if(KEY1 == GPIO_PIN_RESET){
return KEY1_PRES;
}else if(KEY2 == GPIO_PIN_RESET){
return KEY2_PRES;
}else if(KY_UP == GPIO_PIN_SET){
return KY_UP_PRES;
}
}else if(KEY0 == GPIO_PIN_SET && KEY1 == GPIO_PIN_SET && KEY2 == GPIO_PIN_SET && KY_UP == GPIO_PIN_RESET){
key_up = 1;
if(mode)
{
return NO_PRES;
}
}
return 0;
}
|
C | #include <stdio.h>
#include <stdlib.h>
int positivoNegativo();
int maiorNumero();
int calculadora();
int ordemCrescente();
int main() {
int opcao = 1;
while(opcao>0){
printf("\t\t=========== MENU ===========\n");
printf("\t\t1 - Numero Positivo/Negativo\n");
printf("\t\t2 - Maior de 3 numeros\n");
printf("\t\t3 - Calculadora\n");
printf("\t\t4 - Ordem Crescente de 3 numeros reais\n");
printf("\t\t0 - Sair\n");
printf("\t\t============================\n");
printf("\t-->");
scanf("%i", &opcao);
switch(opcao){
case 0:
break;
case 1:
positivoNegativo();
break;
case 2:
maiorNumero();
break;
case 3:
calculadora();
break;
case 4:
ordemCrescente();
break;
default:
printf("\tOPCAO INVALIDA !\n");
system("pause");
break;
}
system("cls");
}
return 0;
}
int positivoNegativo(){
int numero;
numero = 0;
printf("Digite um numero : \n");
printf("\t-->");
scanf("%i",&numero);
if(numero< 0){
printf("Esse numero e negativo !\n");
}else{
printf("Esse numero e positivo!\n");
}
system("pause");
}
int maiorNumero(){
int numero[3];
for(int i = 0;i< 3;i++){
printf("Digite o %i numero: \n",i+1);
printf("\t-->");
scanf("%i",&numero[i]);
}
if(numero[0] > numero[1] && numero[0] > numero[2]){
printf("O NUMERO %i E MAIOR QUE %i E %i\n", numero[0], numero[1], numero[2]);
}else if(numero[1] > numero[0] && numero[1] > numero[2]){
printf("O NUMERO %i E MAIOR QUE %i E %i\n", numero[1], numero[0], numero[2]);
}else if(numero[2] > numero[0] && numero[2] > numero[1]){
printf("O NUMERO %i E MAIOR QUE %i E %i\n", numero[2], numero[0], numero[1]);
}
system("pause");
}
int calculadora(){
//VARIAVEIS
int calculadoraOpcoes = 0; // Numero opcao
float number[2],resultado = 0; // Vetor numero receber os dois numeros e \\
resultado receber valor da operacao.
//LACO DE REPEDICAO I && ENTRADA
do{
//MENU DE OPCOES
printf("\t\t============================\n");
printf("\t\tOPCOES : \n");
printf("\t\tSOMA --> 1 \n\t\tSUBTRACAO --> 2\n\t\tMULTIPLICACAO --> 3\n");
printf("\t\tDIVICAO --> 4 \n");
printf("\t\t============================\n");
printf("\nDIGITE O NUMERO DA OPCAO DESEJADA:\n \t-->"); // Pedir a opcao ao usuario.
scanf("%i",&calculadoraOpcoes); // Ler opcao.
//LACO DE REPEDICAO II
for(int i=0;i < 2;i++){
printf("DIGITE O NUMERO %i (UTILIZE O \".\" NO LUGAR DA \",\"):\n -->",i+1);
scanf("%f",&number[i]); // Ler os numeros.
}
//LACO CONDICIONAL
switch(calculadoraOpcoes){ // Realizar a operacao de acordo com opcao escolhida.
case 1 : // CASO 1 - SOMA
resultado = number[0] + number[1];
break; // SAIR DO ESCOLHA CASO(switch)
case 2 : // CASO 2 - SUBTRACAO
resultado = number[0] - number[1];
break;// SAIR DO ESCOLHA CASO(switch)
case 3 : // CASO 3 - MULTIPLICACAO
resultado = number[0] * number[1];
break;// SAIR DO ESCOLHA CASO(switch)
case 4 : // CASO 4 - DIVICAO
resultado = number[0] / number[1];
break; // SAIR DO ESCOLHA CASO(switch)
}
printf("\nRESULTADO: %.2f\n", resultado); // Exiber o resultado formatado\\
com duas casas decimais
printf("\nDIGITE 5 CASO QUEIRA SAIR OU 0 PARA CONTINUAR: \n -->");
scanf("%d",&calculadoraOpcoes); // Ler opcao do usuario.
}while(calculadoraOpcoes != 5); // Verificar se o usuario quer continuar.
//SAIDA
}
int ordemCrescente(){
//VARIAVEIS
float numero[3]; // Criar um vetor de 3 posicicoes para armazenar 3 numeros digitados.
// LAÇO DE REPEDIÇÃO && ENTRADA
for (int i = 0; i < 3; i++) { // Pedir ao usuario os 3 numeros.
printf("DIGITE O NUMERO %i : \n--> ", i+1); // Pedir ao usuario o numero(imprimi).
scanf("%f", &numero[i]); // Ler e guarda dentro od vetor.
}
//LAÇO CONDICIONAL
if (numero[0] < numero[1] && numero[0] < numero[2]) {// Verificar se primeiro numero digitado e menor
if (numero[1] < numero[2]){ // Verificar o segundo menor numero
printf("%.2f , %.2f , %.2f\n", numero[0], numero[1], numero[2]); // Resultado 1
} else {
printf("%.2f , %.2f , %.2f\n", numero[0], numero[2], numero[1]);// Resultado 2
}
} else if (numero[1] < numero[0] && numero[1] < numero[2]) {// Verificar se segundo numero digitado \\
e menor
if (numero[0] < numero[2]){// Verificar o segundo menor numero
printf("%.2f , %.2f , %.2f\n", numero[1], numero[0], numero[2]); // Resultado 3
} else {
printf("%.2f , %.2f , %.2f\n", numero[1], numero[2], numero[0]); // Resultado 4
}
}else if (numero[2] < numero[0] && numero[2] < numero[1]) {// Verificar se terceiro numero digitado \\
e menor
if (numero[0] < numero[1]) {// Verificar o segundo menor numero
printf("%.2f , %.2f , %.2f\n", numero[2], numero[0], numero[1]); // Resultado 5
} else {
printf("%.2f , %.2f , %.2f\n", numero[2], numero[1], numero[0]); // Resultado 6
}
}
system("pause");
}
|
C | /******************************************************************************
Online C Compiler.
Code, Compile, Run and Debug C program online.
Write your code in this editor and press "Run" button to compile and execute it.
*******************************************************************************/
#include<stdio.h>
union sample{
int * p;
int a;
char x;
};
int main(){
union sample *ptr = 0;
printf("before incriment: %d\n",ptr);
ptr++;
printf("after incriment: %d",ptr);
return 0;
}
//Output:
before incriment: 0
after incriment: 8 |
C | #include<stdio.h>
#include<string.h>
#include<stdlib.h>
void encrypt(char* input, char* output);
int main(int argc, char* argv[]){
if(argc != 3){
printf("USAGE: complement [input file] [output file]\n");
return 1;
}
encrypt(argv[1], argv[2]);
return 0;
}
void encrypt(char* input, char* output){
FILE *fa, *fb;
char ch;
char c = '\n';
fa = fopen(input, "r");
fb = fopen(output, "w");
if((fa == NULL) || (fb == NULL))
printf("Error reading files!\n");
while((ch=getc(fa)) != EOF){
if(ch == '\n')
putc(c, fb);
else
putc(~ch, fb);
}
} |
C | /* עʵǶʽչʽϵn+1еn+1ֱC(n,0),C(n,1),C(n,2)....C(n,n)
ִϹʽ
C(n,0)=1
C(n,k)=(n-k+1)/k*c(n,k-1)*/
#include<stdio.h>
void main()
{
int m,n,cnm,k;
printf("The number of lines:");scanf("%d",&n);
for(k=1;k<=40;k++) printf(" ");
printf("%6d\n",1); //һ
for(m=1;m<=n-1;m++)
{
for(k=1;k<=40-3*m;k++)
printf(" ");
cnm=1;
printf("%6d",cnm);
for(k=1;k<=m;k++)
{
cnm=cnm*(m-k+1)/k;
printf("%6d",cnm);
}
printf("%\n");
}
}
|
C | /*
Student: Joaquin Saldana
Assignment 3
Testing the adventure card
function code:
int adventurerCard(struct gameState *state)
{
int drawntreasure = 0;
int currentPlayer = whoseTurn(state);
int cardDrawn;
int temphand[MAX_HAND];
int z = 0;
while(drawntreasure<2)
{
if (state->deckCount[currentPlayer] <1)
{//if the deck is empty we need to shuffle discard and add to deck
shuffle(currentPlayer, state);
}
drawCard(currentPlayer, state);
cardDrawn = state->hand[currentPlayer][state->handCount[currentPlayer]-1];//top card of hand is most recently drawn card.
// DEBUG removed the "cardDrawn == silver" statement from the if statement below
if (cardDrawn == copper || cardDrawn == gold)
drawntreasure++;
else
{
temphand[z]=cardDrawn;
state->handCount[currentPlayer]--; //this should just remove the top card (the most recently drawn one).
z++;
}
}
while(z-1 >= 0)
{
state->discard[currentPlayer][state->discardCount[currentPlayer]++]=temphand[z-1]; // discard all cards in play that have been drawn
z=z-1;
}
return 0;
}
*/
#include "dominion.h"
#include "dominion_helpers.h"
#include "rngs.h"
#include "assertions.h"
#include <string.h>
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
#include <assert.h>
int main (int argc, char** argv)
{
printf("\n** Card Test 1: Testing function adventureCard() **\n");
int x;
int treas = 0;
int draw;
int i = 0;
int treasure1 = 0;
int treasure2 = 0;
int temp[MAX_HAND];
int seed = 500;
int numPlayers = 2;
struct gameState state;
int k[10] = {minion, mine, adventurer, great_hall, cutpurse,sea_hag, tribute, smithy, council_room, copper};
initializeGame(numPlayers, k, seed, &state);
state.hand[state.whoseTurn][0] = minion;
adventurerCard(&state);
printf("Expected value: %d, Result: %d\n", state.handCount[state.whoseTurn] + 2, state.handCount[state.whoseTurn]);
state.discardCount[state.whoseTurn] = 5;
adventurerCard(&state);
while(treas < 2)
{
drawCard(state.whoseTurn, &state);
draw = state.hand[state.whoseTurn][state.handCount[state.whoseTurn]-1];
if (draw == copper || draw == silver || draw == gold)
{
treas++;
}
else
{
temp[i] = draw;
state.handCount[state.whoseTurn]--;
i++;
}
}
printf("Expected card count: %d, Result: %d\n", state.discardCount[state.whoseTurn] + i, state.discardCount[state.whoseTurn]);
for(x = 0; x < state.handCount[state.whoseTurn]; x++)
{
if (state.hand[state.whoseTurn][x] == copper || state.hand[state.whoseTurn][x] == silver || state.hand[state.whoseTurn][x] == gold)
{
treasure1++;
}
}
for(x = 0; x < state.handCount[state.whoseTurn]; x++)
{
if (state.hand[state.whoseTurn][x] == copper || state.hand[state.whoseTurn][x] == silver || state.hand[state.whoseTurn][x] == gold)
{
treasure2++;
}
}
printf("Final expected treasure count: %d, Result: %d\n", treasure1, treasure2);
printf("\n** End of Card Test 1 **\n");
return 0;
}
|
C |
#include "util.h"
#include <stdarg.h>
/**
* Check if a bit is set in the bit field.
*/
BOOL HvUtilBitIsSet(SIZE_T BitField, SIZE_T BitPosition)
{
return (BitField >> BitPosition) & 1UL;
}
/**
* Set a bit in a bit field.
*/
SIZE_T HvUtilBitSetBit(SIZE_T BitField, SIZE_T BitPosition)
{
return BitField | (1ULL << BitPosition);
}
/*
* Clear a bit in a bit field.
*/
SIZE_T HvUtilBitClearBit(SIZE_T BitField, SIZE_T BitPosition)
{
return BitField & ~(1ULL << BitPosition);
}
/*
* Certain control MSRs in VMX will ask that certain bits always be 0, and some always be 1.
*
* In these MSR formats, the lower 32-bits specify the "must be 1" bits.
* These bits are OR'd to ensure they are always 1, no matter what DesiredValue was set to.
*
* The high 32-bits specify the "must be 0" bits.
* These bits are AND'd to ensure these bits are always 0, no matter what DesiredValue was set to.
*/
SIZE_T HvUtilEncodeMustBeBits(SIZE_T DesiredValue, SIZE_T ControlMSR)
{
LARGE_INTEGER ControlMSRLargeInteger;
// LARGE_INTEGER provides a nice interface to get the top 32 bits of a 64-bit integer
ControlMSRLargeInteger.QuadPart = ControlMSR;
DesiredValue &= ControlMSRLargeInteger.HighPart;
DesiredValue |= ControlMSRLargeInteger.LowPart;
return DesiredValue;
}
/*
* Print a message to the kernel debugger.
*/
VOID HvUtilLog(LPCSTR MessageFormat, ...)
{
va_list ArgumentList;
va_start(ArgumentList, MessageFormat);
vDbgPrintExWithPrefix("[*] ", DPFLTR_IHVDRIVER_ID, DPFLTR_ERROR_LEVEL, MessageFormat, ArgumentList);
va_end(ArgumentList);
}
/*
* Print a debug message to the kernel debugger.
*/
VOID HvUtilLogDebug(LPCSTR MessageFormat, ...)
{
va_list ArgumentList;
va_start(ArgumentList, MessageFormat);
vDbgPrintExWithPrefix("[DEBUG] ", DPFLTR_IHVDRIVER_ID, DPFLTR_ERROR_LEVEL, MessageFormat, ArgumentList);
va_end(ArgumentList);
}
/*
* Print a success message to the kernel debugger.
*/
VOID HvUtilLogSuccess(LPCSTR MessageFormat, ...)
{
va_list ArgumentList;
va_start(ArgumentList, MessageFormat);
vDbgPrintExWithPrefix("[+] ", DPFLTR_IHVDRIVER_ID, DPFLTR_ERROR_LEVEL, MessageFormat, ArgumentList);
va_end(ArgumentList);
}
/*
* Print an error to the kernel debugger with a format.
*/
VOID HvUtilLogError(LPCSTR MessageFormat, ...)
{
va_list ArgumentList;
va_start(ArgumentList, MessageFormat);
vDbgPrintExWithPrefix("[!] ", DPFLTR_IHVDRIVER_ID, DPFLTR_ERROR_LEVEL, MessageFormat, ArgumentList);
va_end(ArgumentList);
} |
C | #include<stdio.h>
#include<stdlib.h>
#include<arpa/inet.h>
#include<sys/time.h>
#include<sys/select.h>
#include<sys/socket.h>
#include<string.h>
#include<unistd.h>
void ErrorHandling(char *message){
fputs(message,stderr);
fputs("\n",stderr);
exit(1);
}
int main(int argc, char* argv[]){
int srvSock, clntSock;
char buff[100];
struct sockaddr_in srvAddr,clntAddr;
socklen_t szAddr;
fd_set reads,cpy_reads;
struct timeval timeout;
int strLen;
int fdMax;
if(argc!=2){
printf("Usage %s <PORT>\n",argv[0]);
exit(1);
}
memset(&srvAddr,0,sizeof(srvAddr));
srvAddr.sin_family=AF_INET;
srvAddr.sin_addr.s_addr=htonl(INADDR_ANY);
srvAddr.sin_port=htons(atoi(argv[1]));
srvSock=socket(PF_INET,SOCK_STREAM,0);
if(bind(srvSock,(struct sockaddr*)&srvAddr,sizeof(srvAddr))==-1)
ErrorHandling("bind() error!");
if(listen(srvSock,5)==-1)
ErrorHandling("listen() error!");
FD_ZERO(&reads);
FD_SET(srvSock,&reads);
fdMax=srvSock;
int fdNum;
int i;
while(1){
cpy_reads=reads;
timeout.tv_sec=5;
timeout.tv_usec=5000;
if((fdNum=select(fdMax+1,&cpy_reads,0,0,&timeout))==-1)//수신된 데이터가 있는지 확인 and 오류시
break;
if(fdNum==0)
continue;
for(i=0; i<fdMax+1; i++){
if(FD_ISSET(i,&cpy_reads)){
if(i==srvSock){//연결 요청이 들어왔을 때
szAddr=sizeof(clntSock);
clntSock=accept(srvSock,(struct sockaddr*)&clntSock,&szAddr);
FD_SET(clntSock,&reads);
if(fdMax<clntSock)
fdMax=clntSock;
printf("connected client: %d \n", clntSock);
}
else{//클라이언트에서 메시지가 날아왔을 때
strLen=read(i,buff,sizeof(buff));
if(strLen==0){//연결 종료
FD_CLR(i,&reads);
close(i);
printf("closed client: %d \n", i);
}
else//echo
{
write(i,buff,strLen);
}
}
}
}
}
close(srvSock);
return 0;
} |
C | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#define TREE_MAX_SIZE 30
struct node {
int data;
struct node *lchild, *rchild;
};
struct node *tree_creat(int *in, int *post, int len);
void tree_destroy(struct node **root);
void tree_level_walk(struct node *root);
struct node *tree_creat(int *in, int *post, int len)
{
int i;
struct node *root = NULL;
if(len > 0) {
if(!(root = malloc(sizeof(struct node))))
exit(ENOMEM);
root->data = post[len - 1];
for(i = 0; i < len && in[i] != post[len - 1]; ++i)
;
root->lchild = tree_creat(in, post, i);
root->rchild = tree_creat(in + i + 1, post + i, len - 1 - i);
}
return root;
}
void tree_destroy(struct node **root)
{
if(*root) {
tree_destroy(&(*root)->lchild);
tree_destroy(&(*root)->rchild);
free(*root);
*root = NULL;
}
}
void tree_level_walk(struct node *root)
{
int front = 0, rear = 0;
struct node *queue[TREE_MAX_SIZE] = {NULL}, *ptr;
queue[rear++] = root;
while(rear != front) {
ptr = queue[front++];
if(ptr->lchild)
queue[rear++] = ptr->lchild;
if(ptr->rchild)
queue[rear++] = ptr->rchild;
printf("%s%d", 1 == front ? "" : " ", ptr->data);
}
printf("\n");
}
int main(int argc, char *argv[])
{
struct node *root;
int i, cnts, in[TREE_MAX_SIZE] = {0}, post[TREE_MAX_SIZE] = {0};
scanf("%d", &cnts);
for(i = 0; i < cnts; ++i)
scanf("%d", &post[i]);
for(i = 0; i < cnts; ++i)
scanf("%d", &in[i]);
root = tree_creat(in, post, cnts);
tree_level_walk(root);
tree_destroy(&root);
return EXIT_SUCCESS;
}
|
C | #include <stdio.h>
#include <stdlib.h>
int main(){
int arr[] = {1,2,3,4,5};
// int N = 0b11100;
int nonDets[5];
for (int i=0;i<5;i++){
nonDets[i] = nondet_int();
__CPROVER_assume(nonDets[i]>=0&&nonDets[i]<5);
}
// __CPROVER_assume(N>0);
int xorEd = 0;
for(int x=0;x<3;x++){
// printf("%d %d\n",(N&(1<<x)),arr[x]);
// if((N&(1<<x))!=0){
// if((N&(1<<x))!=0){
// // if(N%x==0){
// xorEd = (xorEd^arr[x]);
// }
xorEd = xorEd^arr[nonDets[x]];
}
int flag = 0;
if((xorEd)!=10){
flag = 1;
}
assert(flag == 1);
printf("%d\n", xorEd);
}
|
C | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* padding_5.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: ebouther <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2016/02/06 17:45:17 by ebouther #+# #+# */
/* Updated: 2016/02/06 17:54:33 by ebouther ### ########.fr */
/* */
/* ************************************************************************** */
#include "ft_printf.h"
void ft_padding_switch_core(t_padding *p, t_conv *conv, int *offset)
{
if (**(p->ret) == '-' && *(p->i) == 0)
{
*(p->padding) = ft_strjoin_free(*(p->padding), ft_strdup("-"));
*offset = 1;
(*(p->len))++;
}
else if (conv->padding_pos != -1 && conv->precision_pos != -1
&& ft_strlen(conv->precision) > 0
&& ft_atoi(conv->padding) > ft_atoi(conv->precision))
*(p->padding) = ft_strjoin_free(*(p->padding), ft_strdup(" "));
else
*(p->padding) = ft_strjoin_free(*(p->padding), ft_strdup("0"));
}
void ft_padding_switch(t_padding *p, t_conv *conv, int *offset)
{
if ((ft_strchr("oduixXcsSp%", conv->conversion) != NULL)
|| (conv->conversion_pos == -1))
{
if (ft_strchr(conv->flag, '-') != NULL)
{
if (**(p->ret) == '-' && *(p->i) == 0)
{
*(p->padding) = ft_strjoin_free(*(p->padding), ft_strdup("-"));
*offset = 1;
(*(p->len))++;
}
else
*(p->padding) = ft_strjoin_free(ft_strdup(" "), *(p->padding));
}
else if (ft_strchr(conv->flag, '0') != NULL)
ft_padding_switch_core(p, conv, offset);
else
*(p->padding) = ft_strjoin_free(*(p->padding), ft_strdup(" "));
}
else
*(p->padding) = ft_strjoin_free(*(p->padding), ft_strdup(" "));
}
void ft_do_padding_switch_5_1(char **ret,
int offset, char *padding)
{
char *tmp2;
char *tmp;
tmp2 = NULL;
tmp = NULL;
*ret = ft_strjoin(
(tmp2 = *ret) + offset,
tmp = padding);
if ((*ret)[ft_strlen(*ret) - 1] == '-')
{
(*ret)[ft_strlen(*ret) - 1] = '\0';
*ret = ft_strjoin_free(ft_strdup("-"), *ret);
}
ft_strdel(&tmp);
ft_strdel(&tmp2);
}
|
C | #include <stdio.h>
#include <stdlib.h>
#include <time.h>
typedef enum{
OUT, EMPTY,
SECRET,CHARA,
ENEMY, WEAPON,
DEATHENEMY, GDEATHENEMY,
PRISON,EXIT,
GUNS
} squareKind;
typedef enum{
NOWEAPON, HAVEWEAPON,
GUN, FULL,
QUIT
} modeKind;
typedef struct{
int enemy[3][2];
int chara;
squareKind map[7][7];
}cave;
typedef struct{
int hp;
modeKind weapon;
int key;
int killscore;
}chara;
void p(squareKind map[][7]);
void quitGame();
void checkSquare();
void move2Prison();
int m[7][7];
int moveChara();
int makeEnemy();
int battleScene(int);
int stack;
int c; // moveCharaの文字取得
cave d;
chara ch = {30, 0, 0, 0};
squareKind sq;
modeKind mode;
int main(int argc, char *argv[]){
for(int i=0; i<7; i++){
for(int j=0; j<7; j++){
if(i == 0 || i == 6 || j == 0 || j == 6){
d.map[i][j] = OUT;
m[i][j] = OUT;
}else{
d.map[i][j] = SECRET;
m[i][j] = EMPTY;
}
}
}
srand(time(NULL));
int r = rand()%60;
d.chara = 15;
m[1][5] = PRISON; m[3][4] = EXIT; m[1][1] = ENEMY;
m[3][2] = ENEMY; m[5][5] = ENEMY; m[2][4] = WEAPON;
m[2][1] = GUNS;
d.enemy[0][0] = 30+r;
d.enemy[0][1] = 11;
r = rand()%60;
d.enemy[1][0] = 30+r;
d.enemy[1][1] = 32;
d.enemy[2][0] = 30;
d.enemy[2][1] = 55;
p(d.map);
while(1){
if(moveChara() == -1) printf("壁があって進めない…\n");
p(d.map);
checkSquare();
printf("%d %d\n", ch.weapon, ch.hp);
}
return 0;
}
void p(squareKind map[][7]){
for(int i=0; i<7; i++){
for(int j=0; j<7; j++){
if(d.chara/10 == i && d.chara%10 == j) printf("@");
else if(i == 0 || i == 6) printf("-");
else if(j == 0 || j == 6) printf("|");
else if(map[i][j] == SECRET) printf("%c", '?');
else if(map[i][j] == CHARA) printf("%c", '@');
else if(map[i][j] == PRISON) printf("%c", 'H');
else if(map[i][j] == EXIT) printf("%c", 'O');
else if(map[i][j] == EMPTY) printf("%c", ' ');
else if(map[i][j] == ENEMY) printf("%c", 'E');
else if(map[i][j] == DEATHENEMY) printf("%c", 'X');
}
printf("\n");
}
}
int checkError(){
int m = d.chara;
return (m/10 > 5 || m/10 < 1 || m%10 < 1 || m%10 > 5 || m < 10 || m%10 == 0 || m>55);
}
int moveChara(){
scanf("%lc%*c", &c);
fflush(stdin);
if(c == 'q') quitGame();
if(c == 'r') p(d.map);
sq = d.map[d.chara/10][d.chara%10];
stack = d.chara;
int mover;
if(c == 's') mover = 10;
if(c == 'w') mover = -10;
if(c == 'a') mover = -1;
if(c == 'd') mover = 1;
if(c == 'e') mover = 0;
d.chara += mover;
if(checkError()){
d.chara -= mover;
return -1;
}else{
if (m[d.chara/10][d.chara%10] == WEAPON || m[d.chara/10][d.chara%10] == GUNS ){
m[d.chara/10][d.chara%10] = EMPTY;
d.map[d.chara/10][d.chara%10] = EMPTY;
}
d.map[stack/10][stack%10] = m[stack/10][stack%10];
}
fflush(stdin);
//putchar('\n');
}
void checkSquare(){
int mover = 0;
d.chara += mover;
if (m[d.chara/10][d.chara%10] == WEAPON){
ch.weapon = HAVEWEAPON;
printf("小さなナイフを手に入れた\n");
m[d.chara/10][d.chara%10] = EMPTY;
d.map[d.chara/10][d.chara%10] = EMPTY;
}
else if (m[d.chara/10][d.chara%10] == GUNS){
if(ch.weapon == HAVEWEAPON) ch.weapon = FULL;
else ch.weapon = GUN;
printf("フリントロック式の銃だ。\n");
m[d.chara/10][d.chara%10] = EMPTY;
d.map[d.chara/10][d.chara%10] = EMPTY;
}
else if(m[d.chara/10][d.chara%10] == ENEMY){
/*
if(ch.weapon == GUN || ch.weapon == FULL){
if(d.enemy[(d.chara%10)/2] = battleScene(d.enemy[(d.chara%10)/2]) == 0) m[d.chara/10][d.chara%10] = GDEATHENEMY;
}
else{
if(d.enemy[(d.chara%10)/2] = battleScene(d.enemy[(d.chara%10)/2]) == 0) m[d.chara/10][d.chara%10] = DEATHENEMY;
}*/
int cc = battleScene(d.enemy[(d.chara%10)/2][0]);
d.enemy[(d.chara%10)/2][0] = cc;
if(cc == 0){
m[d.chara/10][d.chara%10] = DEATHENEMY;
printf("%d\n", cc);
}
//printf("enemyhp: %d\n",d.enemy[(d.chara%10)/2]);
}
else if(m[d.chara/10][d.chara%10] == DEATHENEMY){
printf("血だまりに男が倒れている。もう動かないだろう\n");
}
else if(m[d.chara/10][d.chara%10] == GDEATHENEMY){
printf("頭から中身がこぼれている…吐き気を催したが、こらえた。\n");
}
d.map[stack/10][stack%10] = m[stack/10][stack%10];
}
void quitGame(){
printf("本当に終了しますか?..y/n\n");
scanf("%lc%*c", &c);
if(c == 'y' || c == 'Y'){
exit(EXIT_SUCCESS);
}
}
int battleScene(int e){
printf("=============================\n");
printf("盗賊を見つけた。\n");
int f = 0;
// 自分の攻撃
if(ch.weapon == HAVEWEAPON){
printf("ナイフもあるし、今なら戦えそう\n");
printf("戦う e/なにもしない q >");
scanf("%lc%*c", &c);
if(c == 'e'){
e -= 15;
if (e > 0)
printf("かなりダメージを与えた\n");
f = 1;
}
}else if(ch.weapon == NOWEAPON){
printf("丸腰だと勝てそうにない…けど…\n");
printf("戦う e/なにもしない q >");
scanf("%lc%*c", &c);
//printf("%d\n", d.enemy[0]);
if(c == 'e'){
e -= 5;
if (e > 0){
printf("少しだけ、傷を負わせた\n");
move2Prison();
printf("「痛い!離して!」...抵抗はむなしく牢屋に戻された。\n");
f = 1;
}
}
}else if(ch.weapon == GUN || ch.weapon == FULL){
printf("こちらに気が付いていない。盗賊の頭に狙いを定めた。\n");
printf("引き金を引く e/なにもしない q >");
scanf("%lc%*c", &c);
if(c == 'e'){
e = 0;
printf("銃弾は脳天を貫き、盗賊は倒れた\n");
ch.weapon -= 2;
f = 1;
}
}
// 敵の攻撃
if(e > 0){
if(ch.hp == 1){
ch.hp -= 1;
if(d.chara == 15) printf("牢に投げられ、頭を強く打った。\n視界がチカチカと点滅し、鼻血が噴き出す。\nうめきながら立とうとするが、脚が震えるばかりで力が入らない。\nニヤニヤ気味の悪い笑みを最後に、意識が途切れた。\n");
else printf("もう動けそうにない…ここまでみたいだ…\n");
printf("GAMEOVER\n");
exit(EXIT_SUCCESS);
}else if(ch.hp == 5){
ch.hp -= 4;
printf("傷が深い…視界がぼんやりしている\n");
}else if(f == 1)
ch.hp -= 5;
}
if (e <= 0){
e = 0; //0下回った時の処理
printf("盗賊は倒れた。手に嫌な感触が残った\n");
}
printf("キャラのHP: %d\n",ch.hp);
return e;
}
void move2Prison(){
d.chara = 15;
}
|
C | /* -- PCF Operating System --
* See [docs\COPYRIGHT.txt] for more info
*/
/** @file system\kernel\fs\read.c
@brief Virtual File System
*/
#include <errno.h>
#include <string.h>
#include <stdio.h>
#include <kernel\console.h>
int VfsRead(int fd, char *buffer, unsigned int len)
{
if(fd == STDIN_FD) {
unsigned int i = len;
while(i > 0) {
unsigned int key = ConsoleReadChar();
if(key == 0) {
*buffer = '\0';
return len-i;
}
memcpy(buffer, &key, 1);
i--;
buffer++;
}
return len;
}
return -ENOTSUP;
}
|
C | #include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/stat.h>
#include "Header.h"
void Files() {
FILE *fh;
FILE *fh2;
printLn2(1,"これからファイル操作を試します",1);
// printf : <stdio.h>
printLn("> カレントディレクトリをホームに変更",1);
chdir(getenv("HOME"));
// chdir : <unistd.h>
// getenv : <stdlib.h>
// ファイル/フォルダ/シンボリックリンクの作成
printLn2(1,"> Emptyという空フォルダを作成",1);
if (mkdir("Empty",0744)==-1) error(); // 成功すれば0,失敗すれば-1
// mkdir : <sys/stat.h>
printLn("> Blankという空ファイルを作成",1);
if ((fh = fopen("Blank","w")) != NULL) fclose(fh);
else error(); // 失敗すれば,NULLが返される
// fopen,fclose : <stdio.h>
printLn("> フォルダEmptyの中にファイルBlankのシンボリックリンクSymlinkを作成",1);
if (symlink("Blank","Empty/Symlink")==-1) error(); // 成功すれば0,失敗すれば-1
// symlink : <unistd.h>
// 書込み
printLn("> Untitled.mdというMarkdownファイルを作成して書込み",1);
if ((fh = fopen("Untitled.md","w")) != NULL) {
fputs("# Header 1",fh);
// fputs : <stdio.h>
fclose(fh);
}
else error();
// 移動/名称変更
printLn2(1,"> フォルダEmptyをPackageに名称変更",1);
if (rename("Empty","Package")!=0) error();
printLn("> Packageフォルダ内のSymlinkファイルをAliasに名称変更",1);
if (rename("Package/Symlink","Package/Alias")!=0) error();
printLn("> Untitled.mdを移動して,名称変更",1);
if (rename("Untitled.md","Package/Headers.md")!=0) error();
// rename : <stdio.h>
// 追記
printLn2(1,"> Markdownファイルに追記",1);
if ((fh = fopen("Package/Headers.md","a")) != NULL) {
fseek(fh,0,SEEK_END); // 書き込みカーソルをファイル末端に移動
fputs("\r\n## Header 2\r\n### Header 3",fh);
fclose(fh);
}
else error();
// 読込み
printLn2(1,"> Markdownファイルを読込み",1);
if ((fh = fopen("Package/Headers.md","r")) != NULL) {
char lines[300];
while (fgets(lines,300,fh)!=NULL) printf("%s",lines);
fclose(fh);
}
else error();
// ファイルの複製
// ...と言っても,ファイルを読み込んで,そのまま別のファイルに書き込んでいるだけ。
printLn2(1,"> Markdownファイルを複製",1);
if ((fh = fopen("Package/Headers.md","r")) != NULL) {
if ((fh2 = fopen("Package/Duplicated.md","w")) != NULL) {
char lines[300];
while (fgets(lines,300,fh)!=NULL) fputs(lines,fh2);
fclose(fh2);
}
else error();
fclose(fh);
}
else error();
// ファイルの削除
printLn2(1,"> ファイルBlankを削除",1);
if (remove("Blank")!=0) error();
printLn("> シンボリックリンクAliasを削除",1);
if (remove("Package/Alias")!=0) error();
printLn("> フォルダModuleを作成した直後に削除",1);
if (mkdir("Package/Module",0744)==-1) error(); // 成功すれば0,失敗すれば-1
if (remove("Package/Module")==-1) error(); // 成功すれば0,失敗すれば-1
// remove : <stdio.h>
}
void error() {
printLn("\t何らかの理由で操作に失敗しました",1);
} |
C | #include <stdio.h>
#define MIN 0
#define MAX 40
#define INTER 2
main()
{
int celsius;
printf("Celsius, Fahr\n");
for (celsius = MIN; celsius <= MAX; celsius = celsius + INTER)
printf("%5d %7.1f\n", celsius, ((9.0 * celsius) / 5.0 +32.0));
}
|
C | /**
Header for HMC5883L ditigal compass driver
Requirements:
1. the main file should include wire.h
Pin layout:
I2C:
ANL 4 -> SDL
ANL 5 -> SCL
*/
#ifndef compass_driver_h
#define compass_driver_h
#include "Arduino.h"
#include <wire.h>
//Define pins you're using for I2C communication
#define SDLPIN 4
#define SCLPIN 5
#define SAMPLE_SIZE 3
#define COMPASS_ADDR 0x1E //0011110b, I2C 7bit address of HMC5883
#define DECLINATION_ANGLE -10.0/180.0*PI //-10.0 for state college, convert to radians
/**
Function: compass_init
Description: setup the connection between the compass and cpu
*/
void compass_init();
/**
Function: compass_get_angle
Descripton: get the angle compared with its original direction
*/
int compass_get_angle();
#endif |
C | #include "memvirt.h"
#include "simpletest.h"
#define WS(a, b, c) \
if (a){ \
isEqual(a->avg_ws, b, c); \
} \
else isNotNull(a, c);
#define PFRATE(a, b, c) \
if (a){ \
isNear(a->total_pf_rate, b, c); \
} \
else isNotNull(a, c);
void tzero1 ()
{
WHEN("eu tenho apenas um processo, 4 frames e um intervalo igual a 20");
struct result *r = memvirt (1, 4, "t01.txt", 20);
THEN("esse único processo vai ter 10 referências");
isEqual(r->refs[0], 10, 1);
THEN("seu número de PF vai ser 4");
isEqual(r->pfs[0], 4, 1);
THEN("sua taxa de PF vai ser 40%");
isEqual(r->pf_rate[0], 0, 1);
THEN("o ws vai ser zero");
isEqual(r->avg_ws, 0, 1);
THEN("a taxa de PF média vai ser 40%");
isEqual(r->total_pf_rate, 0, 1);
free (r);
}
void tzero2 ()
{
WHEN("eu tenho apenas 3 processos, 7 frames e um intervalo igual a 4");
struct result *r = memvirt (3, 7, "t02.txt", 4);
THEN("o primeiro processo irá ter 3 referências");
isEqual(r->refs[0], 3, 1);
THEN("o segundo processo irá ter 2 referências");
isEqual(r->pfs[1], 2, 1);
THEN("o terçeiro processo irá ter 2 referências");
isEqual(r->pfs[2], 2, 1);
THEN("o número de PF do primeiro irá ser");
isEqual(r->pfs[0], 2, 1);
free (r);
}
void tzero3 ()
{
struct result * r;
WHEN ("dois processos, cinco frames e um intervalo igual de quatro");
r = memvirt (2, 5,"t03.txt", 4);
THEN ("o primero processo irá ter 10 referências");
isEqual(r->refs[0], 10, 1);
THEN ("o segundo processo irá ter 2 referências");
isEqual(r->refs[1], 2, 1);
WS(r, 2, 1);
PFRATE(r, .9, 1);
if(r)
free(r);
}
int main (int argc, char const *argv[])
{
DESCRIBE("Testes do simulador de memória virtual");
tzero1 ();
tzero2 ();
tzero3 ();
GRADEME();
if (grade==maxgrade)
return 0;
else return grade;
return 0;
} |
C | #include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
int CPT = 0;
bool FLAG = false;
int main(int argc, char *argv[])
{
// Open memory card (File *f = fopen(filename, "r");)
// Repeat until end of card:
// Read 512 bytes into a buffer (fread(data, size, number, inptr))
// If start of a new JPEG (check the first 4 bytes (0xff - 0xd8 - 0xff - 0xe*))
// If first JPEG
// Open a new JPEG file
// create the name of the JPEG (000.jpeg)
// Write 512 bytes
// Else
// Close previous JPEG
// Open a new file with a new name (###.jpeg)
// ELse
// If already found JPEG
// Write the next 512 bytes in the current JPEG
// Close any remainning files
// Check usage
if (argc != 2)
{
return 1;
}
// Open file
FILE *file = fopen(argv[1], "r");
if (!file)
{
return 1;
}
unsigned char bytes[512];
FILE *img;
char *new_jpeg;
while (fread(bytes, sizeof(char), 512, file) != !EOF)
{
if (bytes[0] == 0xff && bytes[1] == 0xd8 && bytes[2] == 0xff && (bytes[3] & 0xf0) == 0xe0)
{
if (FLAG == true)
{
FLAG = false;
free(new_jpeg);
fclose(img);
}
if (FLAG == false)
{
FLAG = true;
// Memory allocated for the name of the new JPEG
new_jpeg = malloc(7);
// name the new JPEG and increment CPT
sprintf(new_jpeg, "%03i.jpg", CPT++);
img = fopen(new_jpeg, "w");
fwrite(bytes, sizeof(char), 512, img);
}
}
else
{
if (FLAG == true)
{
fwrite(bytes, sizeof(char), 512, img);
}
}
}
// Close file
fclose(file);
}
|
C | /* roman.c */
/* Author: Adam Reid */
/* Number - Roman Numeral Converter */
/*
The program takes in a user entered number, and converts the number to roman numerals.
*NOTE: The program will not convert any decimals, and will convert words to ""
*/
#include "romanTools.h"
int main(int argc, char * argv[])
{
convertToRoman(argc, argv);
return(0);
}
|
C | #include "map.h"
#include <stdio.h>
#include <stdlib.h>
// in binding=rr mode
void mapping(int mycol, int type)
{
char H_Freq[7]={"2500000"};
// char M_Freq[7]={"1800000"};
char L_Freq[6]={"800000"};
FILE *fp;
char *DVFS=L_Freq;
if(type==1) DVFS=H_Freq;
else if(type==0) DVFS=L_Freq;
if(mycol==0)
{
fp = fopen("/sys/devices/system/cpu/cpu0/cpufreq/scaling_setspeed","w");
fwrite(DVFS,6+type,sizeof(char),fp);
fclose(fp);
}
else if(mycol==1)
{
fp = fopen("/sys/devices/system/cpu/cpu1/cpufreq/scaling_setspeed","w");
fwrite(DVFS,6+type,sizeof(char),fp);
fclose(fp);
}
else if(mycol==2)
{
fp = fopen("/sys/devices/system/cpu/cpu2/cpufreq/scaling_setspeed","w");
fwrite(DVFS,6+type,sizeof(char),fp);
fclose(fp);
}
else if(mycol==3)
{
fp = fopen("/sys/devices/system/cpu/cpu3/cpufreq/scaling_setspeed","w");
fwrite(DVFS,6+type,sizeof(char),fp);
fclose(fp);
}
else if(mycol==4)
{
fp = fopen("/sys/devices/system/cpu/cpu4/cpufreq/scaling_setspeed","w");
fwrite(DVFS,6+type,sizeof(char),fp);
fclose(fp);
}
else if(mycol==5)
{
fp = fopen("/sys/devices/system/cpu/cpu5/cpufreq/scaling_setspeed","w");
fwrite(DVFS,6+type,sizeof(char),fp);
fclose(fp);
}
else if(mycol==6)
{
fp = fopen("/sys/devices/system/cpu/cpu6/cpufreq/scaling_setspeed","w");
fwrite(DVFS,6+type,sizeof(char),fp);
fclose(fp);
}
else if(mycol==7)
{
fp = fopen("/sys/devices/system/cpu/cpu7/cpufreq/scaling_setspeed","w");
fwrite(DVFS,6+type,sizeof(char),fp);
fclose(fp);
}
}
void mapping2(int myrow, int mycol, int type)
{
char H_Freq[7]={"2500000"};
// char M_Freq[7]={"1800000"};
char L_Freq[6]={"800000"};
FILE *fp;
char *DVFS=L_Freq;
if(type==1) DVFS=H_Freq;
else if(type==0) DVFS=L_Freq;
if(myrow < 4)
{
mycol=mycol%4;
if(mycol==0)
{
fp = fopen("/sys/devices/system/cpu/cpu0/cpufreq/scaling_setspeed","w");
fwrite(DVFS,6+type,sizeof(char),fp);
fclose(fp);
}
else if(mycol==1)
{
fp = fopen("/sys/devices/system/cpu/cpu1/cpufreq/scaling_setspeed","w");
fwrite(DVFS,6+type,sizeof(char),fp);
fclose(fp);
}
else if(mycol==2)
{
fp = fopen("/sys/devices/system/cpu/cpu2/cpufreq/scaling_setspeed","w");
fwrite(DVFS,6+type,sizeof(char),fp);
fclose(fp);
}
else if(mycol==3)
{
fp = fopen("/sys/devices/system/cpu/cpu3/cpufreq/scaling_setspeed","w");
fwrite(DVFS,6+type,sizeof(char),fp);
fclose(fp);
}
}
else
{
if(mycol < 4)
mycol = mycol + 4;
if(mycol==4)
{
fp = fopen("/sys/devices/system/cpu/cpu4/cpufreq/scaling_setspeed","w");
fwrite(DVFS,6+type,sizeof(char),fp);
fclose(fp);
}
else if(mycol==5)
{
fp = fopen("/sys/devices/system/cpu/cpu5/cpufreq/scaling_setspeed","w");
fwrite(DVFS,6+type,sizeof(char),fp);
fclose(fp);
}
else if(mycol==6)
{
fp = fopen("/sys/devices/system/cpu/cpu6/cpufreq/scaling_setspeed","w");
fwrite(DVFS,6+type,sizeof(char),fp);
fclose(fp);
}
else if(mycol==7)
{
fp = fopen("/sys/devices/system/cpu/cpu7/cpufreq/scaling_setspeed","w");
fwrite(DVFS,6+type,sizeof(char),fp);
fclose(fp);
}
}
}
|
C | /**
* File : main.c
* Author : Ayana, Masa
* Date : Fri 8 Feb 2019
*/
#include <stdio.h>
int vc_find_next_prime(int n)
{
if (n < 2)
{
return 0;
}
for (int i = 2; i < n; i++)
{
if (n % i == 0)
{
return vc_find_next_prime(n+1);
}
}
return n;
}
int main() {
printf("Result is %d\n", vc_find_next_prime(18));
return 0;
} |
C | /*Напишете програма аналог на спортния тотализатор.
Използвайте функции.
Насоки:
1. Давате право на избор на играча да избере тотализатор, в който
ще си пробва късмета: (5 от 35), (6 от 42) или (6 от 49)
2. При всяко завъртане програмата изписва 1 произволно число,
което не е извадено до момента.
3. Програмата вади числата, нужни за избраната игра (5 или 6).*/
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int choose(void);
void game(int numbers, int max);
int main()
{
switch (choose())
{
case 1:
game(5, 35);
break;
case 2:
game(6, 42);
break;
case 3:
game(6, 49);
break;
default:
break;
}
}
int choose(void)
{
int ans = 1;
printf("Please choose on option\n");
printf("For 5/35 press 1.\nFor 6/42 press 2.\nFor 6/49 press 3.");
scanf("%d", &ans);
return ans;
}
void game(int numbers, int max)
{
srand(time(0));
int res[numbers];
for (int i = 0; i < numbers; i++)
{
res[i] = rand() % (max + 1);
}
printf("And the winning numbers are\n");
for (int i = 0; i < numbers; i++)
{
printf("%d\n", res[i]);
}
}
|
C | #ifndef DATOS_H
#define DATOS_H
typedef struct args ARG;
typedef struct type TYP;
typedef struct type_tab TYPTAB;
struct args{
int arg;
ARG *next;
};
typedef struct argum{
ARG *head;
ARG *tail;
int num; // numero de elementos en la lista
}ARGUMS;
typedef struct sym SYM;
struct sym{
char id [33]; // identificador
int dir; // direccion para la variable
int tipo; // tipo como indice a la tabla de tipos
int var; // tipo de variable
ARGUMS *args; // Lista de argumentos
int num; // numero de argumentos
SYM *next; // apuntador al siguiente simbolo
};
typedef struct sym_tab SYMTAB;
struct sym_tab{
SYM *head;
SYM *tail;
int num; //Numero de elementos en la tabla
TYPTAB *tt;
SYMTAB *next; // apuntador a la tabla siguiente
};
typedef struct sym_stack{
SYMTAB *top;
SYMTAB *tail;
}SSTACK;
typedef struct tipobase{
int is_est; // 1: si es estructura 0: si es tipo simple -1: si no tiene tipo base
union{
SYMTAB *SS;
int tipo;
}tipo;
}TB;
//TYP
struct type{
int id;
char nombre[12];
TB tb;
int tam;
TYP *next; //apuntador al siguiente tipo en la tabla de tipos
};
struct type_tab{
TYP *head;
TYP *tail;
int num; //Contador de elementos en la tabla
TYPTAB *next ; //apuntador a la tabla siguiente
};
typedef struct typ_stack{
TYPTAB *top;
TYPTAB *tail;
}TSTACK;
#endif |
C | #ifndef TD_REDBLACKTREE_C
#define TD_REDBLACKTREE_C
#include "../RedBlackTree.h"
#include "../../DynamicArray/DynamicArray.h"
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
char TD_RedBlackTreeComparator( RedBlackTreePayload leftNode, RedBlackTreePayload rightNode )
{
// Return anything but (true or 1) or (false or 0) for equality.
if (leftNode == rightNode) return -1;
return leftNode > rightNode;
}
void TD_RedBlackTreePayloadDeleter( RedBlackTreePayload payload )
{
//free( payload );
}
void TD_RedBlackTreePrint( RedBlackTree* redBlackTree, RedBlackTreeNode* redBlackTreeNode )
{
printf("%d ", (int) redBlackTreeNode->Payload );
}
void TD_Randomizer( DynamicArray* dynamicArray )
{
int count = dynamicArray->Count;
for (int i = 0; i < count; i++)
{
int randIndex = (rand() % (count - i)) + i;
int tmp = (int)dynamicArray->PayloadArr[i];
dynamicArray->PayloadArr[i] = dynamicArray->PayloadArr[randIndex];
dynamicArray->PayloadArr[randIndex] = (DynamicArrayPayload)tmp;
}
}
void TD_RedBlackTreeTestDriver()
{
srand( time(NULL) );
printf( "Creating a new red black tree.\n" );
DynamicArray* dynamicArray = DynamicArray_NewArray( 0, NULL );
int R = 20;
DynamicArray_Resize(dynamicArray, R, 0);
// Perform stress tests.
for (int j = 0; j < 10; j++)
{
RedBlackTree* redBlackTree = RedBlackTree_NewTree(TD_RedBlackTreeComparator, TD_RedBlackTreePayloadDeleter);
for (int i = 0; i < R; i++) dynamicArray->PayloadArr[i] = i;
TD_Randomizer( dynamicArray );
printf( "\nInserting: " );
for ( int i = 0; i < R; i++ )
{
printf( "%d, ", dynamicArray->PayloadArr[i] );
RedBlackTree_Insert(redBlackTree, dynamicArray->PayloadArr[i] );
}
TD_Randomizer( dynamicArray );
printf( "\nDeleting: " );
for ( int i = 0; i < R; i++ )
{
printf("%d, ", dynamicArray->PayloadArr[i] );
RedBlackTree_NodeRemove( redBlackTree, RedBlackTree_NodeFind( redBlackTree, dynamicArray->PayloadArr[i] ) );
RedBlackTree_Assert( redBlackTree, true );
}
RedBlackTree_DeleteTree(redBlackTree);
}
DynamicArray_DeleteArray( dynamicArray );
}
#endif |
C | #include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>
int getLine(char *inpt);
int printSpeciali(char *s, int len);
int xorFun(char *msg, char *key, char *xorred, int len);
int printHex(char *mssgio, int len);
int main(){
// messaggio da cifrare
char msg[128];
printf("Inserisci il messaggio da cifrare [1-128]:\n");
// se l'input non mi soddisfa lo richiedo
while (getLine(msg) != 1){
printf("Reinserisci:\n");
}
printf("\n");
// scelta dell'utente; uso fgets per prendere l'intera linea e strtol per prendere l'intero
char choiceStr[128];
int choiceInt = 0;
// prendo un intero e verifico che sia o 1 o 2, altrimenti lo richiedo
while (1){
printf("Cosa vuoi fare?\n");
printf("1. Fornire una key\n2. Utilizzare una key causale\n");
printf("Inserisci il valore corrispondente:\n");
getLine(choiceStr);
char *end;
choiceInt = strtol(choiceStr, &end, 10);
if (choiceInt == 1 || choiceInt == 2)
break;
else
printf("\nScrivi 1 o 2!\n\n");
}
int len = strlen(msg);
// chiave
char key[128];
// immessa dall'utente
if (choiceInt == 1 ){
printf("\nInserisci la tua key [%d-128]:\n", len);
while (getLine(key) != 1 || (strlen(key) < len)){
if (strlen(key) < len)
printf("\nTroppo corta, scrivi almeno %d caratteri\n", len);
printf("Reinserisci:\n");
}
}
// creata randomicamente
else if (choiceInt == 2){
time_t t;
srand((unsigned) time(&t));
for (int i = 0; i < len; i++){
key[i] = rand() % 127;
}
printf("\nEcco la tua key:\n");
printSpeciali(key, len);
printf("\n");
printHex(key, len);
printf("\n");
}
// array per il messaggio cifrato
char cipher[128];
xorFun(msg, key, cipher, len);
// stampo con speciali e in hex
printf("\nIl tuo messaggio cifrato e'\n");
printSpeciali(cipher, len);
printf("\n");
printHex(cipher, len);
// array per lo xor del messaggio cifrato
char originalXOR[128];
xorFun(cipher, key, originalXOR, len);
printf("\nIl messaggio originale era\n%s\n", originalXOR);
printHex(originalXOR, len);
// controllo se effettivamente lo xor della stringa xor-ata mi ritorna la stringa iniziale
if (strcmp(msg, originalXOR) != 0)
printf("Qualcosa è andato storto...\n");
return 0;
}
// funzione che mi prende una stringa in input con alcuni controlli
int getLine(char *inpt) {
int chr, check;
// controllo che l'input non sia vuoto
if (fgets (inpt, 128, stdin) == NULL){
printf("\nScrivi qualcosa!\n");
return 0;
}
// controllo che almeno 2 caratteri siano stati inseriti in input
int len = strlen(inpt);
if (len < 2){
printf("\nTroppo corto!\n");
return 0;
}
// controllo a fine linea se trovo \n o EOF
// se c'è, 1, altrimenti 0
if (inpt[len - 1] != '\n') {
check = 0;
while (((chr = getchar()) != '\n') && (chr != EOF))
check = 1;
if (check==1){
printf("\nTroppo lungo!\n");
return 0;
}
else
return 1;
}
// termino l'array
inpt[len - 1] = '\0';
return 1;
}
// funzione che stampa i caratteri speciali da 0 a 31 nel formato |%d|
int printSpeciali(char *s, int len){
for(int i = 0; i < len; i++){
if(s[i] > 31 || s[i] == 127){
printf("%c", s[i]);
}else{
printf("|%d|", s[i]);
}
}
return 1;
}
// funzione xor
int xorFun(char *msg, char *key, char *cipher, int len){
int i = 0;
while (i < len){
cipher[i] = msg[i] ^ key[i];
i++;
}
cipher[i] = '\0';
return 1;
}
// funzione che itera l'array e stampa il corrispettivo hex di ogni carattere
int printHex(char *mssgio, int len){
printf("In hex\n");
for (int i = 0; i < len; i++){
printf("%02x", mssgio[i]);
}
printf("\n");
return 1;
}
|
C | #include <stdio.h>
#include <stdlib.h>
#include "ponto.h"
#include "caminho.h"
struct caminho_{
ponto_ST *pontos;
float distanciaCaminho;
float distanciaPontoInicialParaPontoFinal;
};
//Funções locais que não são exportadas para main
float calcularDistanciaDeTodosPontos(ponto_ST * pontos, int quantidadeDePontos);
float calcularDistanciaPontoInicialParaPontoFinal(ponto_ST * pontos, int quantidadeDePontos);
float calcularDistanciaDeTodosPontos(ponto_ST * pontos, int quantidadeDePontos){
float distanciaTotal = 0;
for(int i = 0; i < quantidadeDePontos-1; i++){
distanciaTotal += distanciaEntreDoisPontos(pontos, i, i+1);
}
return distanciaTotal;
}
float calcularDistanciaPontoInicialParaPontoFinal(ponto_ST * pontos, int quantidadeDePontos){
return distanciaEntreDoisPontos(pontos, 0, quantidadeDePontos - 1);
}
//Funções exportadas
caminho_ST * criarCaminho(ponto_ST * pontos, int quantidadeDePontos){
caminho_ST *caminho;
caminho = (caminho_ST *) calloc(1, sizeof(caminho_ST));
caminho->pontos = pontos;
caminho->distanciaCaminho = calcularDistanciaDeTodosPontos(pontos, quantidadeDePontos);
caminho->distanciaPontoInicialParaPontoFinal = calcularDistanciaPontoInicialParaPontoFinal(pontos, quantidadeDePontos);
return caminho;
}
void mostrarCaminhoPercorrido(caminho_ST * caminho){
printf("%.2f\n", caminho->distanciaCaminho);
}
void mostrarDistanciaEntrePontoFinalEInicial(caminho_ST * caminho){
printf("%.2f\n", caminho->distanciaPontoInicialParaPontoFinal);
} |
C | #include <signal.h>
#include <unistd.h>
#include <stdio.h>
#include <errno.h>
#include <stdlib.h>
#include <string.h>
#include "ft_strace.h"
void do_child(int argc, char **argv)
{
char *args [argc+1];
for (int i=0;i<argc;i++)
args[i] = argv[i];
args[argc] = NULL;
kill(getpid(), SIGSTOP);
execvp(args[0], args);
int error = errno;
char *msg = malloc(11 + strlen(args[0]));
sprintf(msg, "Can't stat %s", args[0]);
ft_error(msg, error);
} |
C | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct ListNode {
int val;
struct ListNode *next;
};
struct ListNode *
insert(struct ListNode **head,struct ListNode * tail,struct ListNode *value);
/* return tail node*/
struct ListNode *
insert(struct ListNode **head,struct ListNode * tail,struct ListNode *value){
if(NULL == *head){
value->next = *head;
*head = value;
}else{
value->next = tail->next;
tail->next = value;
}
return value;
}
/*create single list*/
struct ListNode *
create_list(struct ListNode ** head,int num){
int remainder = 0,consult = 0;
struct ListNode * tail = NULL;
struct ListNode * node = NULL;
do{
remainder = num % 10;
node = (struct ListNode *)malloc(sizeof(struct ListNode));
memset(node,0x00,sizeof(node));
node->val = remainder;
tail = insert(head,tail,node);
}while(num = num/10);
}
static inline struct ListNode *
head_insert(struct ListNode* head,struct ListNode* node){
struct ListNode tmp;
memset(&tmp,0x00,sizeof(tmp));
struct ListNode *p = &tmp,*q;
p->next = head;
q = p;
while(p->next){
if(p->next->val > node->val){
node->next = p->next;
p->next = node;
break;
}
p = p->next;
}
if(!p->next){
node->next = p->next;
p->next = node;
}
return q->next;
}
struct ListNode* insertionSortList(struct ListNode* head) {
struct ListNode * p = head,*q = NULL;
struct ListNode * really_head = NULL;
if(!head || !head->next) head;
while(p){
q = p->next;
really_head = head_insert(really_head,p);
p = q;
}
return really_head;
}
/*print list*/
void print_list(struct ListNode * head){
struct ListNode * p = head;
while(p){
printf("%d->",p->val);
p = p->next;
}
printf("\n");
}
int main(int argc,char *argv[])
{
struct ListNode * l1 = NULL, * l2 = NULL,*l3 = NULL;
struct ListNode * tail = NULL;
tail = create_list(&l1,468521);
print_list(l1);
l2 = insertionSortList(NULL);
print_list(l2);
return 0;
}
|
C | /*
* Copyright (C) 2017 by Benedict Paten ([email protected])
*
* Released under the MIT license, see LICENSE.txt
*/
#include <htslib/vcf.h>
#include "htsIntegration.h"
/*
* Functions for reference prior probabilities
*/
stReferencePriorProbs *stReferencePriorProbs_constructEmptyProfile(char *referenceName,
int64_t referenceStart, int64_t length) {
/*
* Creates an empty object, with all the profile probabilities set to 0.
*/
stReferencePriorProbs *referencePriorProbs = st_calloc(1, sizeof(stReferencePriorProbs));
referencePriorProbs->referenceName = stString_copy(referenceName);
referencePriorProbs->refStart = referenceStart;
referencePriorProbs->length = length;
referencePriorProbs->profileProbs = st_calloc(length*ALPHABET_SIZE, sizeof(uint16_t));
referencePriorProbs->referenceSequence = st_calloc(length, sizeof(uint8_t));
referencePriorProbs->baseCounts = st_calloc(length*ALPHABET_SIZE, sizeof(double));
referencePriorProbs->referencePositionsIncluded = st_calloc(length, sizeof(bool));
for(int64_t i=0; i<length; i++) {
referencePriorProbs->referencePositionsIncluded[i] = true;
}
return referencePriorProbs;
}
void stReferencePriorProbs_destruct(stReferencePriorProbs *referencePriorProbs) {
/*
* Destructor for reference prior probs
*/
free(referencePriorProbs->profileProbs);
free(referencePriorProbs->referenceName);
free(referencePriorProbs->referenceSequence);
free(referencePriorProbs->baseCounts);
free(referencePriorProbs->referencePositionsIncluded);
free(referencePriorProbs);
}
static stReferencePriorProbs *getNext(stList *profileSequences, stList *profileSequencesOnReference) {
/*
* Construct an empty stReferencePriorProbs for the next interval of a reference sequence.
*/
assert(stList_length(profileSequences) > 0);
stProfileSeq *pSeq = stList_pop(profileSequences);
char *refName = pSeq->referenceName;
int64_t refStart = pSeq->refStart;
int64_t refEnd = pSeq->refStart + pSeq->length;
// Add to list of profile sequences contained within the reference interval
// being considered
stList_append(profileSequencesOnReference, pSeq);
while(stList_length(profileSequences) > 0) {
stProfileSeq *pSeq = stList_peek(profileSequences);
if(!stString_eq(pSeq->referenceName, refName)) {
break;
}
stList_pop(profileSequences);
stList_append(profileSequencesOnReference, pSeq);
assert(pSeq->refStart <= refStart);
refStart = pSeq->refStart;
refEnd = pSeq->refStart + pSeq->length > refEnd ? pSeq->refStart + pSeq->length : refEnd;
}
return stReferencePriorProbs_constructEmptyProfile(refName, refStart, refEnd-refStart);
}
void setReadBaseCounts(stReferencePriorProbs *rProbs, stList *profileSequences) {
/*
* Set the base counts observed in the set of profile sequences at each reference position.
*/
for(int64_t i=0; i<stList_length(profileSequences); i++) {
stProfileSeq *pSeq = stList_get(profileSequences, i);
assert(stString_eq(rProbs->referenceName, pSeq->referenceName));
for (int64_t j = 0; j < pSeq->length; j++) {
int64_t k = j + pSeq->refStart - rProbs->refStart;
assert(k >= 0 && k < rProbs->length);
for (int64_t l = 0; l < ALPHABET_SIZE; l++) {
rProbs->baseCounts[k*ALPHABET_SIZE + l] += getProb(&(pSeq->profileProbs[j*ALPHABET_SIZE]), l);
}
}
}
}
stHash *createEmptyReferencePriorProbabilities(stList *profileSequences) {
/*
* Create a set of stReferencePriorProbs that cover the reference intervals included in the profile sequences.
* Each has a flat probability over reference positions.
* The return value is encoded as a map from the reference sequence name (as a string)
* to the stReferencePriorProbs.
*/
// Make map from reference sequence names to reference priors
stHash *referenceNamesToReferencePriors = stHash_construct3(stHash_stringKey, stHash_stringEqualKey,
NULL, (void (*)(void *))stReferencePriorProbs_destruct);
// Copy and sort profile sequences in order
profileSequences = stList_copy(profileSequences, NULL);
stList_sort(profileSequences, stRPProfileSeq_cmpFn);
uint16_t flatValue = scaleToLogIntegerSubMatrix(log(1.0/ALPHABET_SIZE));
while(stList_length(profileSequences) > 0) {
// Get next reference prior prob interval
stList *l = stList_construct();
stReferencePriorProbs *rProbs = getNext(profileSequences, l);
// Fill in probability profile
for(int64_t i=0; i<rProbs->length; i++) {
for(int64_t j=0; j<ALPHABET_SIZE; j++) {
rProbs->profileProbs[i*ALPHABET_SIZE + j] = flatValue;
}
}
// Set the counts of each base observed at each reference position
setReadBaseCounts(rProbs, l);
stList_destruct(l);
assert(stHash_search(referenceNamesToReferencePriors, rProbs->referenceName) == NULL);
stHash_insert(referenceNamesToReferencePriors, rProbs->referenceName, rProbs);
}
// Cleanup
stList_destruct(profileSequences);
return referenceNamesToReferencePriors;
}
double *stReferencePriorProbs_estimateReadErrorProbs(stHash *referenceNamesToReferencePriors, stRPHmmParameters *params) {
/*
* Estimate the read error substitution matrix from the alignment of the reads to the reference.
*/
// Make read error substitution matrix
double *readErrorSubModel = getEmptyReadErrorSubstitutionMatrix(params);
stHashIterator *rProbsIt = stHash_getIterator(referenceNamesToReferencePriors);
char *refSeq;
while((refSeq = stHash_getNext(rProbsIt)) != NULL) {
stReferencePriorProbs *rProbs = stHash_search(referenceNamesToReferencePriors, refSeq);
for(int64_t i=0; i<rProbs->length; i++) {
// Reference character
uint8_t refChar = rProbs->referenceSequence[i];
// Now get read bases
double *baseCounts = &rProbs->baseCounts[i*ALPHABET_SIZE];
for(int64_t j=0; j<ALPHABET_SIZE; j++) {
readErrorSubModel[ALPHABET_SIZE*refChar + j] += baseCounts[j];
}
}
}
stHash_destructIterator(rProbsIt);
normaliseSubstitutionMatrix(readErrorSubModel);
return readErrorSubModel;
}
int64_t stReferencePriorProbs_setReferencePositionFilter(stReferencePriorProbs *rProbs, stRPHmmParameters *params) {
/*
* Sets the rProbs->referencePositionsIncluded array to exclude positions likely to be homozygous.
*
* In a column, let x be the number of occurrences of the most frequent non-reference base.
* If x is less than params.minNonReferenceBaseFilter then the column is filtered out.
*/
int64_t filteredPositions = 0;
for(int64_t i=0; i<rProbs->length; i++) {
double *baseCounts = &rProbs->baseCounts[i*ALPHABET_SIZE];
// Get total expected coverage at base and most frequent base in column
double totalCount = baseCounts[0];
int64_t mostFrequentBase = 0;
double mostFrequentBaseCount = totalCount;
for(int64_t j=1; j<ALPHABET_SIZE; j++) {
totalCount += baseCounts[j];
if(baseCounts[j] > mostFrequentBaseCount) {
mostFrequentBase = j;
mostFrequentBaseCount = baseCounts[j];
}
}
// Maximum number of instances of a non-reference base
double secondMostFrequentBaseCount = 0.0;
int64_t secondMostFrequentBase = 0;
for(int64_t j=0; j<ALPHABET_SIZE; j++) {
if(j != mostFrequentBase && baseCounts[j] > secondMostFrequentBaseCount) {
secondMostFrequentBaseCount = baseCounts[j];
secondMostFrequentBase = j;
}
}
// Filter columns with either of two options:
// (1) If the second most frequent character in the column occurs less than
// params->minSecondMostFrequentBaseFilter times; this is
// intentionally a simple and somewhat robust filter
// (2) If the -log probability of observing the second most frequent character as a result
// of independent substitutions from the
// most frequent character is less than params->minSecondMostFrequentBaseLogProbFilter.
// This second options takes
// into account read error substitution probabilities. It can be used to ignore columns with
// larger numbers of gaps, for example, if
// gaps occur frequently, while including columns with rarer apparent substitution patterns
if(secondMostFrequentBaseCount < params->minSecondMostFrequentBaseFilter ||
-*getSubstitutionProbSlow(params->readErrorSubModelSlow, mostFrequentBase, secondMostFrequentBase) * secondMostFrequentBaseCount <
params->minSecondMostFrequentBaseLogProbFilter) {
filteredPositions++;
// Mask the position
assert(rProbs->referencePositionsIncluded[i] == true);
rProbs->referencePositionsIncluded[i] = false;
}
else if(st_getLogLevel() == debug) {
stList *l = stList_construct3(0, free);
for(int64_t k=0; k<ALPHABET_SIZE; k++) {
stList_append(l, stString_print("%f", baseCounts[k]));
}
char *baseCountString = stString_join2(" ", l);
// st_logDebug("Including position: %s %" PRIi64 " with coverage depth: %f and base counts: %s\n",
// rProbs->referenceName, rProbs->refStart + i, totalCount, baseCountString);
stList_destruct(l);
free(baseCountString);
}
}
return filteredPositions;
}
int64_t filterHomozygousReferencePositions(stHash *referenceNamesToReferencePriors, stRPHmmParameters *params, int64_t *totalPositions) {
/*
* Sets a column filter to ignore columns likely to be homozygous reference.
*
* Returns total number of positions filtered out, sets totalPositions to the total number of
* reference positions.
*/
int64_t filteredPositions = 0;
*totalPositions = 0;
stHashIterator *hashIt = stHash_getIterator(referenceNamesToReferencePriors);
char *referenceName;
while((referenceName = stHash_getNext(hashIt)) != NULL) {
stReferencePriorProbs *rProbs = stHash_search(referenceNamesToReferencePriors, referenceName);
filteredPositions += stReferencePriorProbs_setReferencePositionFilter(rProbs, params);
*totalPositions += rProbs->length;
}
// Cleanup
stHash_destructIterator(hashIt);
return filteredPositions;
}
|
C | #include <stddef.h>
#include <stdint.h>
#include <stdbool.h>
#include <stdlib.h>
#include "eeprom.h"
#include "setting_save.h"
#include "console.h"
#include "stdio.h"
bool eepromInited = false;
set_dev_t setting;
uint8_t *settingBuf = NULL;
//callback function
void saveResult(epState_t result)
{
if(result == EEP_READY) {
console_print("s end\r");
}
free(settingBuf);
settingBuf = NULL;
}
bool settingSave(void)
{
bool ret = false;
char tmp[10];
snprintf(tmp, 10, "s=%d\r", setting.set.solder.value);
console_print(tmp);
if (settingBuf == NULL) {//
if (!eepromInited) {
EepromInit(sizeof(setting_t));
eepromInited = true;
}
settingBuf = malloc(sizeof(setting_t));
if (settingBuf) {
uint8_t count = 0;
uint8_t *rcv = (uint8_t*) (&setting.set);
for(; count<sizeof(setting_t); count++) {
*(settingBuf+count) = *(rcv+count);
}
if (EepromStartWrite(settingBuf, saveResult) == EEP_READY) {
ret = true;
} else {// ..
free(settingBuf);
settingBuf = NULL;
}
}
}
return ret;
}
bool settingLoad(void)
{
bool ret = false;
if (settingBuf == NULL) {// ?
if (!eepromInited) {
if (EepromInit(sizeof(setting_t)) == EEP_BAD) {
console_print("no set\r");
return false;
}
}
eepromInited = true;
settingBuf = malloc(sizeof(setting_t));
if (settingBuf) {
ret = EepromRead(settingBuf) == EEP_READY;
if (ret) {
uint8_t count = 0;
uint8_t *rcv = (uint8_t*) (&setting.set);
for(; count<sizeof(setting_t); count++) {
*(rcv+count) = *(settingBuf+count);
}
setting.ready = true;
char tmp[10];
snprintf(tmp, 10, "l=%d\r", setting.set.solder.value);
console_print(tmp);
}
free(settingBuf);
settingBuf = NULL;
}
}
return ret;
}
|
C | /////////////////////////////////////////////
//
// FILE: child.c
// AUTHOR: Ryan Vollmer
// PURPOSE: Child process functons for small shell.
//
/////////////////////////////////////////////
#include "smallsh.h"
/**
* Checks if command is for a background process
* @param {char*} cmd - command to check
* @return {in} - 1 if background (& found), 0 otherswise
*/
int child_bg(char* cmd) {
char* amp = &cmd[(strlen(cmd) -1)];
// remove trailing whitespace
while (amp > cmd && isspace((char)*amp)) amp--;
// check if ampersand (background process) and not in fg only mode
return (*amp == '&' && !g_fg_only);
}
/**
* Checks all background child processes to see if they have completed
*/
void child_check() {
pid_t child;
int signo;
int child_status;
char buffer[MAX_LEN];
// fg child killed in signal, reap and set globals for status
if (g_status_check) {
waitpid(-1, &child_status, 0);
if (WIFSIGNALED(child_status)) {
if (g_status_check) {
g_status_type = STATUS_TERM;
g_status_signo = WTERMSIG(child_status);
}
}
g_status_check = 0;
}
// check background process, dont stop cmd prompt
child = waitpid(-1, &child_status, WNOHANG);
if (child > 0) {
write(STDOUT_FILENO, "Background pid ", 15);
write(STDOUT_FILENO, itoa((long)child, buffer, 10), num_len((long)child));
write(STDOUT_FILENO, " is done: ", 10);
// exited normally, display message with pid, set signal number
if (WIFEXITED(child_status)) {
signo = WEXITSTATUS(child_status);
write(STDOUT_FILENO, "Exit value ", 11);
write(STDOUT_FILENO, itoa((long)signo, buffer, 10), num_len((long)signo));
}
// exited by term signal, display message, set signal number
else if (WIFSIGNALED(child_status)) {
signo = WTERMSIG(child_status);
write(STDOUT_FILENO, "Terminated by signal ", 21);
write(STDOUT_FILENO, itoa((long)signo, buffer, 10), num_len((long)signo));
}
// print signal number
write(STDOUT_FILENO, "\n", 1);
}
}
/**
* Sets up redirects then runs command
* using execvp with list of arguments
* @param {char*} token - main token for space seperated words
* @param {char**} save_ptr - save pointer for main token
* @param {int} bg - process in background if true
*/
void child_new(char *token, char **save_ptr, int bg) {
char *args[MAX_ARGS];
int arg, rd_in_bg, rd_in, rd_out, fd_in, fd_out;
arg = 0;
rd_in = 0;
rd_in_bg = 0;
rd_out = 0;
// go through each space seperated word
while (token) {
char buffer[MAX_CHARS];
// next word will be input redirect file
if(*token == '<') {
rd_in = 1;
}
// input redirect file
else if (rd_in) {
// get pointer to file desc
fd_in = open(token, O_RDONLY);
if (fd_in < 0) print_err();
// set redirect from stdin to file desc
dup2(fd_in, STDIN_FILENO);
close(fd_in);
rd_in = 0;
rd_in_bg = 1;
}
// next word will be out redirect file
else if (*token == '>') {
rd_out = 1;
}
// output redirect file
else if (rd_out) {
// get pointer to file desc
fd_out = creat(token, 0644);
if (fd_out < 0) print_err();
// set redirect from stdout to file desc
dup2(fd_out, STDOUT_FILENO);
close(fd_out);
rd_out = 0;
}
// argument to pass to exec
else {
strcpy(buffer, token);
// expand any $$ to pid
expand_pids(buffer, 0);
// add to array of arguments
args[arg] = malloc(sizeof(buffer));
if (args == NULL) print_err();
strcpy(args[arg], buffer);
arg++;
}
// get next space seperated word
token = strtok_r(NULL, " \n", save_ptr);
}
// redirect if in background and no input
if (bg) {
// redirect output to /dev/null
fd_out = open("/dev/null", O_WRONLY);
if (fd_out < 0) print_err();
dup2(fd_out, STDOUT_FILENO);
close(fd_out);
// if no input file specificied get from /dev/null
if (!rd_in_bg) {
fd_in = open("/dev/null", O_RDONLY);
if (fd_in < 0) print_err();
dup2(fd_in, STDIN_FILENO);
close(fd_in);
}
}
// ignore if background arg (already determined)
if (*args[arg-1] == '&') {
args[arg-1] = NULL;
}
// last arg must be null for execvp
args[arg] = NULL;
// execute the command
execvp(args[0], args);
print_err();
}
|
C | #include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <math.h>
#include <time.h>
#define N 200
#define LEARN_RATE 0.01
#define EPS 1e-11
double input[N], output[N];
void data(){
srand(time(0));
int i;
double atom=M_PI_4/N;
double x=-M_PI_4;
for (i=0; i<N;++i){
x+=atom;
input[i]=x;
output[i]=sin(x)+(rand()%200-100)*0.0001;
}
}
double SQR(double x){return x*x;}
int main(void){
double w1,w2,w3,w4;
double y1,y2,y3,err,deltaW;
double lastErr=1e10;
int i,iter;
w1=1.0;
w2=-1.0;
w3=0.01;
w4=1.0;
data();
puts("Data:");
for (i=0;i<N;++i){
printf("%lf %lf\n",input[i],output[i]);
}
puts("Training...");
for (iter=1;1;iter++){
for (i=0;i<N;++i){
y1=w1*input[i]+w2;
y2=1.0/(1+exp(-y1));
y3=w3*y2+w4;
err=output[i]-y3;
//compute w1
deltaW=err*w3*y2*(1.0-y2)*input[i];
w1+=deltaW*LEARN_RATE;
//compute w2
deltaW=err*w3*y2*(1.0-y2);
w2+=deltaW*LEARN_RATE;
//compute w3
deltaW=err*y2;
w3+=deltaW*LEARN_RATE;
//compute w4
deltaW=err;
w4+=deltaW*LEARN_RATE;
}
err=0;
for (i=0;i<N;++i){
y1=w1*input[i]+w2;
y2=1.0/(1+exp(-y1));
y3=w3*y2+w4;
err+=SQR(y3-output[i]);
}
err/=N;
printf("Iter=%d, w1=%lf, w2=%lf, w3=%lf, w4=%lf, avgError=%.8lf\n",iter,w1,w2,w3,w4,err);
if (lastErr-err<EPS){
break;
}
lastErr=err;
}
puts("Training finished!\nResult:");
printf("w1=%lf, w2=%lf, w3=%lf, w4=%lf, avgError=%.8lf\n",w1,w2,w3,w4,err);
return 0;
}
|
C | #include <stdio.h>
int main()
{
unsigned int binary, divisor = 1, position_divisor = 10, decimal_weight = 1, decimal = 0, position_value;
printf("Введите двоичное число вида 1001011: ");
scanf("%d", &binary);
while (divisor <= binary) {
position_value = binary % position_divisor / divisor;
decimal += position_value * decimal_weight;
position_divisor *= 10;
divisor *= 10;
decimal_weight *= 2;
}
printf("Десятичное число %d\n", decimal);
return 0;
}
|
C | #include <unistd.h>
#include <sys/types.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char **argv) {
// open /etc/passwd + error handling
int fd = open("/etc/passwd", O_RDONLY);
if(fd < 0) {
perror(argv[0]);
exit(1);
}
// lseek to the last ten bytes of the file + error handling
if(lseek(fd, -10, SEEK_END) < 0) {
perror(argv[0]);
exit(1);
}
// buffer to hold last ten bytes
unsigned char buf[10];
// read last ten bytes in a buffer + error handling
if( read(fd, buf, 10) < 0) {
perror(argv[0]);
exit(1);
}
// write the last ten bytes to the screen + error handling
if( write(1, buf, 10) < 0) {
perror(argv[0]);
exit(1);
}
return 0;
}
|
C | /*! \file linkWatchLib.h
\brief Utility library to help ease the watching of link directories
April 2008, [email protected]
*/
#ifndef LINKWATCHLIB_H
#define LINKWATCHLIB_H
// System Includes
#include <time.h>
#include <zlib.h>
#include <stdio.h>
#ifndef __CINT__
#include <dirent.h>
#endif
int setupLinkWatchDir(char *linkDir); //returns -1 for failure otherwise it returns the watch index number
//Returns 1 if there is new data, zero otherwise
int checkLinkDirs(int timeoutSec, int timeOutUSec);
int getNumLinks(int watchNumber); //returns number of links, zero, -1 for failure
char *getFirstLink(int watchNumber); //returns the filename of the first link
char *getLastLink(int watchNumber); //returns the filename of the most recent link (no idea how)
//This is only needed if you've reason to believe that something naughty is happening and someone is deleting the links from under your nose, like naughty Monitord
int refreshLinkDirs();
//Internal function that uses linked list to keep track of the links
void prepLinkList(int watchIndex);
void addLink(int watchIndex, char *linkName);
int getWatchIndex(int watchNumber);
//More internal functions
#ifndef __CINT__
int filterHeaders(const struct dirent *dir);
int filterOnDats(const struct dirent *dir);
int filterOnGzs(const struct dirent *dir);
int getListofLinks(const char *theEventLinkDir, struct dirent ***namelist);
int getListofPurgeFiles(const char *theEventLinkDir,
struct dirent ***namelist);
#endif
#endif /* LINKWATCHLIB_H */
|
C | /*
* 938. Range Sum of BST
* Given the root node of a binary search tree and two integers low and high,
* return the sum of values of all nodes with a value in the inclusive range [low, high].
*
* Example 1:
* Input: root = [10,5,15,3,7,null,18], low = 7, high = 15
* Output: 32
* Explanation: Nodes 7, 10, and 15 are in the range [7, 15]. 7 + 10 + 15 = 32.
*
* Example 2:
* Input: root = [10,5,15,3,7,13,18,1,null,6], low = 6, high = 10
* Output: 23
* Explanation: Nodes 6, 7, and 10 are in the range [6, 10]. 6 + 7 + 10 = 23.
*
* Constraints:
* The number of nodes in the tree is in the range [1, 2 * 10^4].
* 1 <= Node.val <= 10^5
* 1 <= low <= high <= 10^5
* All Node.val are unique.
*/
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
int rangeSumBST(struct TreeNode* root, int low, int high)
{
if (root == NULL)
return 0;
if (root->val > high)
return rangeSumBST(root->left, low, high);
if (root->val < low)
return rangeSumBST(root->right, low, high);
return root->val + rangeSumBST(root->left, low, high) + rangeSumBST(root->right, low, high);
}
/*
* 执行结果:通过
* 执行用时:52 ms, 在所有 C 提交中击败了100.00%的用户
* 内存消耗:41.5 MB, 在所有 C 提交中击败了45.61%的用户
*/ |
C | #include <stdio.h>
#include <string.h>
#include <math.h>
int main(){
int T, i, tam, num;
long long unsigned int N = 0, P = 0;
char NK[30];
scanf(" %d" , &T);
while(T>0){
scanf("%d%s", &num , NK);
tam = strlen(NK);
N=num;
i = 1;
while(((num-(tam*i))>0) ){
P = (num-(tam*i));
N = N*P;
i++;
}
printf("%llu\n" , N );
T--;
}
return 0;
} |
C | /*
Calcular el algoritmo que determine el número de puntos que lleva un
equipo de fútbol en competición de liga en función del número de partidos ganados, perdidos y empatados.
NOTA: un partido ganado son 3 puntos, uno empatado es 1 y uno perdido son 0.
*/
#include <stdio.h>
void main() {
// variables
int partidosGanados;
int partidosEmpatados;
int partidosPerdidos; // OJO! en este caso, es opcional (leer enunciado)
int puntosFinales;
// fase de recoleccion de datos
printf("Introduzca los partidos ganados... \n");
scanf("%d", &partidosGanados);
printf("Introduzca los partidos empatados... \n");
scanf("%d", &partidosEmpatados);
printf("Introduzca los partidos perdidos... \n");
scanf("%d", &partidosPerdidos);
// calculamos los puntos y los mostramos al usuario
puntosFinales = (partidosGanados * 3) + (partidosEmpatados * 1) + (partidosPerdidos * 0);
printf("Puntuacion del equipo: %d \n", puntosFinales);
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.