language
large_stringclasses 1
value | text
stringlengths 9
2.95M
|
---|---|
C
|
/**
* @file spi.h
* @brief Driver for interfacing with SPI.
*/
#ifndef SPI_H_
#define SPI_H_
#include <stdio.h>
/**
* @brief Sets up pins for MOSI, SCK, SS and MISO and specifies that the ATSam is master in of
* the SPI.
*/
void spi_init(void);
/**
* @brief Transmits @p data on the SPI.
*/
void spi_write(uint8_t data);
/**
* @brief Reads data from the SPI.
*/
uint8_t spi_read(void);
/**
* @brief Sets the slave select pin to high.
*/
void spi_slave_select(void);
/**
* @brief Sets the slave select pin to low.
*/
void spi_slave_deselect(void);
#endif
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <errno.h>
#include <unistd.h>
int main(int argc, char* argv[]){
ssize_t rd, wr, wr1;
ssize_t numread, numread1;
char buffer[100];
char buffer1[50];
//check vaild input
if(argc != 4 || argv[1] == "--help")
{
printf("Invaild input!\nUsage: cpcmd source_file destination_file\n");
return 1;
}
rd = open(argv[1], O_RDONLY | O_CREAT);
if(rd == -1)
{
printf("\nError opening source file!\n");
perror("open");
return 1;
}
wr = open(argv[2], O_CREAT|O_WRONLY, S_IWUSR | S_IRUSR);
if(wr == -1)
{
printf("\nError opening first destination file!\n");
perror("open");
return 1;
}
wr1 = open(argv[3], O_WRONLY | O_CREAT, S_IWUSR | S_IRUSR);
if(wr == -1)
{
printf("\nError opening second destination file!\n");
perror("open");
return 1;
}
//using lseek system call to check the size of the source file
int size = lseek(rd,0L,SEEK_END);
//printf("size of the file:%d\n", size);// output the size for testing purpose
lseek(rd,0L,SEEK_SET);
while (size > 0)
{
//replace the next 100 bytes with 1->A && adding XYZ
if (size >= 150)
{
numread = read(rd, buffer, sizeof(buffer) + 1);
for (int i = 0; i < 100; i++)
if (buffer[i] == '1') buffer[i] = 'A';
write(wr,buffer,numread);
size = size - 100;
numread1 = read(rd, buffer1, sizeof(buffer1) + 1);
for (int j = 0; j < 50; j++)
if(buffer1[j] == '2') buffer1[j] = 'B';
write(wr1,buffer1,numread1);
size = size - 50;
}
//the last step with less than 100 bytes, change 1->A ONLY
else if (size < 150 && size >= 100) // 100 <= size <= 150
{
numread = read(rd, buffer, sizeof(buffer) + 1);
for (int i = 0; i < 100; i++)
if (buffer[i] == '1') buffer[i] = 'A';
write(wr,buffer,numread);
size = size - 100;
numread1 = read(rd, buffer1, size);
for (int j = 0; j < size; j++)
if(buffer1[j] == '2') buffer1[j] = 'B';
write(wr1,buffer1,numread1);
size = 0;
}
else //size < 100
{
numread = read(rd, buffer, size);
for (int i=0; i<size; i++)
if (buffer[i] == '1') buffer[i] = 'A';
write(wr,buffer,numread);
size = 0;
}
}
close(rd);
close(wr);
close(wr1);
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <math.h>
struct tree {
int data;
struct tree *left;
struct tree *right;
};
struct tree *newNode(int data) {
struct tree *ptr = malloc(sizeof(struct tree));
ptr->data = data;
ptr->left = NULL;
ptr->right = NULL;
return ptr;
}
int max (int a, int b) {
return a > b ? a : b;
}
int height(struct tree *root) {
if (root == NULL)
return 0;
return 1+max(height(root->left), height(root->right));
}
bool isBalanced(struct tree *root) {
if (root == NULL)
return 1;
int lh = height(root->left);
int rh = height(root->right);
if ((abs(lh - rh) <= 1) && isBalanced(root->left) && isBalanced(root->right))
return 1;
return 0;
}
int main() {
struct tree *root = NULL;
root = newNode(1);
root->left = newNode(2);
root->right = newNode(3);
root->left->left = newNode(4);
root->left->left->left = newNode(5);
root->right->right = newNode(6);
printf("%s",isBalanced(root)?"True":"False");
printf("\n");
return 0;
}
|
C
|
/**
https://zhuethan.github.io/2020-08-03-MallocLab-In-CSAPP/. Implement a malloc strategy on empty heap space.
*/
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <stdint.h>
#include "mm.h"
#include "memlib.h"
/* If you want debugging output, use the following macro. When you hand
* in, remove the #define DEBUG line. */
#define DEBUG
#ifdef DEBUG
# define dbg_printf(...) printf(__VA_ARGS__)
#else
# define dbg_printf(...)
#endif
/**
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
|-----------------------------------------------------------------------------------------------------------------------------------
| ptr1 | ptr2 | ptr3 | ptr4 | ptr5 | ptr6 | ptr7 | ptr8 | ptr9 | ptr10 | ptr11 | ptr12 | ptr13 | ptr14 | ptr15 | ptr16
| ptr17 | ptr18 | ptr19 | ptr20 | ptr21| ptr22 | ptr23 | ptr24 | empty | prologue | hdr | data ....
... | ftr | hdr | data ....
|
|
|
...
...
|
|
|
|
|
| | ftr |
*/
//#define checkheap(lineno) mm_checkheap(lineno)
#define checkheap(lineno)
/* do not change the following! */
#ifdef DRIVER
/* create aliases for driver tests */
#define malloc mm_malloc
#define free mm_free
#define realloc mm_realloc
#define calloc mm_calloc
#endif /* def DRIVER */
/* single word (4) or double word (8) alignment */
#define ALIGNMENT 8
/* rounds up to the nearest multiple of ALIGNMENT */
#define ALIGN(size) (((size) + (ALIGNMENT-1)) & ~0x7)
#define SIZE_T_SIZE (ALIGN(sizeof(size_t)))
#define SIZE_PTR(p) ((size_t*)(((char*)(p)) - SIZE_T_SIZE))
#define WSIZE 4
#define DSIZE 8
#define CHUNKSIZE (1 << 9)
#define MAX(x, y) ((x) > (y) ? (x) : (y))
#define PACK(size, alloc, prev_alloc) ((size) | (alloc) | (prev_alloc << 1))
#define GET(p) (*(unsigned int*)(p))
#define PUT(p, val) (*(unsigned int*)(p) = (val))
#define GET_NEXT_POINTER(p) ((void*)((int64_t)(*(unsigned int*)(p) == 0 ? 0 : (*(unsigned int*)(p)+0x800000000))))
#define GET_PREV_POINTER(p) ((void*)((int64_t)(*(unsigned int*)((char*)p + WSIZE) == 0 ? 0 : (*(unsigned int*)((char*)p + WSIZE) + 0x800000000))))
#define PUT_NEXT_POINTER(p, add) (*(unsigned int*)(p) = (uintptr_t)(add == NULL ? 0 : add-0x800000000))
#define PUT_PREV_POINTER(p, add) (*(unsigned int*)((char*)p + WSIZE) = (uintptr_t)(add == NULL ? 0 : add-0x800000000))
// Given pointer to
#define GET_SIZE(p) (GET(p) & ~0x7)
#define GET_ALLOC(p) (GET(p) & 0x1)
#define GET_PREV_ALLOC(p) ((GET(p) & 0x2) >> 1)
// Given block ptr bp, compute address of its header and footer
#define HDRP(bp) ((char*)(bp) - WSIZE)
#define FTRP(bp) ((char*)(bp) + GET_SIZE(HDRP(bp)) - DSIZE)
// Given block ptr bp, compute address of next and pre blocks
#define NEXT_BLKP(bp) ((char*)(bp) + GET_SIZE(((char*)(bp) - WSIZE)))
#define PREV_BLKP(bp) ((char*)(bp) - GET_SIZE(((char*)(bp) - DSIZE)))
#define NEXT_FREE_BLKP(bp) (GET(bp))
#define SEG_LIMIT 24
static char* heap_listp = 0;
static void** seg_list = 0;
#ifdef NEXT_FIT
static char* rover;
#endif
static void *extend_heap(size_t words);
static void place(void *bp, size_t asize);
static void *find_fit(size_t asize);
static void *coalesce(void *bp);
static void printblock(void *bp);
static void print_free_list();
static void checkblock(void *bp, int lineno);
static inline int get_seglist_bucket(size_t size) {
int words = size / WSIZE;
int i = 0;
while (words > 1) {
words >>= 1;
i += 1;
}
return i;
}
static inline void* get_seglist_root(int seglist_bucket) {
unsigned int offset = *(unsigned int*)((char*)seg_list + WSIZE*seglist_bucket);
return (void*)(offset == 0 ? 0 : offset + 0x800000000);
}
static inline void set_seglist_root(int id, void* ptr) {
*(unsigned int*)((char*)seg_list + WSIZE*id) = (uintptr_t)(ptr == NULL ? 0 : ptr-0x800000000);
}
/*
* mm_init - Called when a new trace starts.
*/
int mm_init(void) {
heap_listp = 0;
seg_list = 0;
if ((seg_list = mem_sbrk(SEG_LIMIT * WSIZE)) == (void*)-1) {
return -1;
}
memset(seg_list, 0, SEG_LIMIT*WSIZE);
if ((heap_listp = mem_sbrk(4 * WSIZE)) == (void*)-1) {
return -1;
}
PUT(heap_listp, PACK(0, 1, 1)); // why?
PUT(heap_listp+WSIZE, PACK(DSIZE, 1, 1)); // prologue header
PUT(heap_listp+2*WSIZE, PACK(DSIZE, 1, 1)); // prologue footer
PUT(heap_listp+3*WSIZE, PACK(0, 1, 1)); // epilogue header
heap_listp += 2*WSIZE;
if (extend_heap(CHUNKSIZE/WSIZE) == NULL) {
return -1;
}
return 0;
}
// Return pointer referring to new free heap starting point;
static void *extend_heap(size_t words) {
void* bp;
size_t size = ((words & 1) ? (words+1) : words) * WSIZE;
if ((bp = mem_sbrk(size)) == (void*)-1) {
return NULL;
}
size_t prev_alloc = GET_PREV_ALLOC(HDRP(bp));
if (prev_alloc) {
PUT(HDRP(bp), PACK(size, 0, 1));
PUT(FTRP(bp), PACK(size, 0, 1));
PUT(HDRP(NEXT_BLKP(bp)), PACK(0, 1, 0));
} else {
PUT(HDRP(bp), PACK(size, 0, 0));
PUT(FTRP(bp), PACK(size, 0, 0));
PUT(HDRP(NEXT_BLKP(bp)), PACK(0, 1, 0));
}
return coalesce(bp);
}
static void remove_block(void* bp) {
/*
1. both prev and next are existing.
2. prev is NULL and next is existing.
3. prev is NULL and next is null.
4. prev is existing and next is null.
*/
void* prev_node = GET_PREV_POINTER(bp);
void* next_node = GET_NEXT_POINTER(bp);
int seglist_bucket = get_seglist_bucket(GET_SIZE(HDRP(bp)));
if (prev_node == NULL && next_node == NULL) {
set_seglist_root(seglist_bucket, NULL);
} else if (prev_node != NULL && next_node == NULL) {
PUT_NEXT_POINTER(prev_node, NULL);
} else if (prev_node == NULL && next_node != NULL) {
set_seglist_root(seglist_bucket, next_node);
PUT_PREV_POINTER(next_node, NULL);
} else {
PUT_PREV_POINTER(next_node, prev_node);
PUT_NEXT_POINTER(prev_node, next_node);
}
}
static void insert_head(void* bp, size_t size) {
/*
1. seglist_root is NULL
2. seglist_root points to some blocks.
*/
int seg_list_bucket = get_seglist_bucket(size);
void* seglist_root = get_seglist_root(seg_list_bucket);
if (seglist_root == NULL) {
set_seglist_root(seg_list_bucket, bp);
PUT_NEXT_POINTER(bp, NULL);
PUT_PREV_POINTER(bp, NULL);
} else {
PUT_NEXT_POINTER(bp, seglist_root);
PUT_PREV_POINTER(seglist_root, bp);
PUT_PREV_POINTER(bp, NULL);
set_seglist_root(seg_list_bucket, bp);
}
}
static void *coalesce(void* bp) {
size_t prev_alloc = GET_PREV_ALLOC(HDRP(bp));
size_t next_alloc = GET_ALLOC(HDRP(NEXT_BLKP(bp)));
size_t next_size = GET_SIZE(HDRP(NEXT_BLKP(bp)));
size_t cur_size = GET_SIZE(HDRP(bp));
size_t prev_size;
if (prev_alloc && next_alloc) {
insert_head(bp, cur_size);
checkheap(__LINE__);
return bp;
} else if (prev_alloc && !next_alloc) {
remove_block(NEXT_BLKP(bp));
size_t asize = cur_size + next_size;
PUT(HDRP(bp), PACK(asize, 0, 1));
PUT(FTRP(bp), PACK(asize, 0, 1));
insert_head(bp, asize);
checkheap(__LINE__);
return bp;
} else if (!prev_alloc && next_alloc) {
void* prev_bp = PREV_BLKP(bp);
remove_block(prev_bp);
prev_size = GET_SIZE(HDRP(PREV_BLKP(bp)));
size_t asize = cur_size + prev_size;
PUT(HDRP(PREV_BLKP(bp)), PACK(asize, 0, 1));
PUT(FTRP(PREV_BLKP(bp)), PACK(asize, 0, 1));
insert_head(prev_bp, asize);
checkheap(__LINE__);
return PREV_BLKP(bp);
} else {
void* prev_bp = PREV_BLKP(bp);
void* next_bp = NEXT_BLKP(bp);
remove_block(prev_bp);
remove_block(next_bp);
prev_size = GET_SIZE(HDRP(PREV_BLKP(bp)));
size_t asize = cur_size + prev_size + next_size;
PUT(HDRP(PREV_BLKP(bp)), PACK(asize, 0, 1));
PUT(FTRP(PREV_BLKP(bp)), PACK(asize, 0, 1));
insert_head(prev_bp, asize);
checkheap(__LINE__);
return PREV_BLKP(bp);
}
}
static void* find_fit(size_t asize) {
for (int bucket = get_seglist_bucket(asize); bucket < SEG_LIMIT; bucket++) {
void* root = get_seglist_root(bucket);
for (void* cur = root; cur != NULL; cur = GET_NEXT_POINTER(cur)) {
size_t hsize = GET_SIZE(HDRP(cur));
if (hsize >= asize) {
return cur;
}
}
}
return NULL;
}
/*
* malloc - Allocate a block by incrementing the brk pointer.
* Always allocate a block whose size is a multiple of the alignment.
*/
void *malloc(size_t size) {
/*int newsize = ALIGN(size + SIZE_T_SIZE);
unsigned char *p = mem_sbrk(newsize);
//dbg_printf("malloc %u => %p\n", size, p);
if ((long)p < 0)
return NULL;
else {
p += SIZE_T_SIZE;
*SIZE_PTR(p) = size;
return p;
}*/
if (heap_listp == 0) {
mm_init();
}
size_t asize;
void* ptr;
size_t words = MAX(4, ((size + WSIZE + (WSIZE-1)) / WSIZE));
asize = (words & 1 ? (words+1) : words) * WSIZE;
if ((ptr = find_fit(asize)) == NULL) {
if ((ptr = extend_heap(MAX(asize / WSIZE, CHUNKSIZE / WSIZE))) == NULL) {
return NULL;
}
}
place(ptr, asize);
checkheap(__LINE__);
return ptr;
}
static void place(void *bp, size_t asize) {
size_t o_size = GET_SIZE(HDRP(bp));
remove_block(bp);
if (o_size-asize >= 4*WSIZE) {
PUT(HDRP(bp), PACK(asize, 1, 1));
size_t new_size = o_size-asize;
PUT(HDRP(NEXT_BLKP(bp)), PACK(new_size, 0, 1));
PUT(FTRP(NEXT_BLKP(bp)), PACK(new_size, 0, 1));
insert_head(NEXT_BLKP(bp), new_size);
} else {
size_t n_size = GET_SIZE(HDRP(NEXT_BLKP(bp)));
size_t n_alloc = GET_ALLOC(HDRP(NEXT_BLKP(bp)));
PUT(HDRP(bp), PACK(o_size, 1, 1));
PUT(HDRP(NEXT_BLKP(bp)), PACK(n_size, n_alloc, 1));
if (!n_alloc) {
PUT(FTRP(NEXT_BLKP(bp)), PACK(n_size, n_alloc, 1));
}
}
}
/*
* free - We don't know how to free a block. So we ignore this call.
* Computers have big memories; surely it won't be a problem.
*/
void free(void *ptr) {
if (ptr == 0)
return;
size_t size = GET_SIZE(HDRP(ptr));
if (heap_listp == 0) {
mm_init();
}
size_t prev_alloc = GET_PREV_ALLOC(HDRP(ptr));
size_t next_size = GET_SIZE(HDRP(NEXT_BLKP(ptr)));
size_t next_alloc = GET_ALLOC(HDRP(NEXT_BLKP(ptr)));
PUT(HDRP(ptr), PACK(size, 0, prev_alloc));
PUT(FTRP(ptr), PACK(size, 0, prev_alloc));
PUT(HDRP(NEXT_BLKP(ptr)), PACK(next_size, next_alloc, 0));
if (!next_alloc) {
PUT(FTRP(NEXT_BLKP(ptr)), PACK(next_size, next_alloc, 0));
}
coalesce(ptr);
checkheap(__LINE__);
}
/*
* realloc - Change the size of the block by mallocing a new block,
* copying its data, and freeing the old block. I'm too lazy
* to do better.
*/
void *realloc(void *oldptr, size_t size) {
size_t oldsize;
void* newptr;
if (size == 0) {
free(oldptr);
return NULL;
}
if (oldptr == NULL) {
return malloc(size);
}
newptr = malloc(size);
if (newptr == NULL) {
return 0;
}
oldsize = GET_SIZE(HDRP(oldptr));
if (size < oldsize) {
oldsize = size;
}
memcpy(newptr, oldptr, oldsize);
free(oldptr);
return newptr;
}
/*
* calloc - Allocate the block and set it to zero.
*/
void *calloc (size_t nmemb, size_t size)
{
size_t bytes = nmemb * size;
void *newptr;
newptr = malloc(bytes);
size_t asize = GET_SIZE(HDRP(newptr));
memset(newptr, 0, asize);
return newptr;
}
void printblock(void *bp) {
void* header = HDRP(bp);
void* footer = FTRP(bp);
printf("location: %p | hsize:%d, hallocated:%d, pallocated: %d |", bp, GET_SIZE(header), GET_ALLOC(header), GET_PREV_ALLOC(header));
printf(" data:");
if (!GET_ALLOC(header)) {
printf("next: %p, prev: %p", GET_NEXT_POINTER(bp), GET_PREV_POINTER(bp));
}
if (!GET_ALLOC(header)) {
printf(" | fsize:%d, fallocated:%d, pallocated: %d", GET_SIZE(footer), GET_ALLOC(footer), GET_PREV_ALLOC(footer));
}
printf("\n");
}
void checkblock(void* ptr, int lineno) {
if (!GET_ALLOC(HDRP(ptr)) && GET_SIZE(HDRP(ptr)) != GET_SIZE(FTRP(ptr))) {
printblock(ptr);
printf("size is not matched [%d]\n", lineno);
exit(1);
}
if (GET_SIZE(HDRP(ptr)) < 8) {
printblock(ptr);
printf("size too small [%d]\n", lineno);
exit(1);
}
if ((unsigned long)ptr & 0x7) {
printblock(ptr);
printf("alignment is not correct for header [%d]\n", lineno);
exit(1);
}
if (!GET_ALLOC(HDRP(ptr)) && (unsigned long)FTRP(ptr) & 0x7) {
printblock(ptr);
printf("alignemtn is not correct for footer address %lx in line [%d]\n", (unsigned long)(FTRP(ptr)+WSIZE), lineno);
exit(1);
}
if (!GET_ALLOC(HDRP(ptr)) && GET_ALLOC(HDRP(ptr)) != GET_ALLOC(FTRP(ptr))) {
printblock(ptr);
printf("alloc is not matched for address %lx in line [%d]\n", (unsigned long)ptr, lineno);
exit(1);
}
if (!GET_ALLOC(HDRP(ptr))) {
void* prev_ptr = GET_PREV_POINTER(ptr);
void* next_ptr = GET_NEXT_POINTER(ptr);
if (prev_ptr != NULL) {
if (GET_NEXT_POINTER(prev_ptr) != ptr) {
printf("prev and next are not matched:\n");
printf("ptr %p | next: %p | prev: %p \n", ptr, next_ptr, prev_ptr);
printf("ptr->prev: %p | next: %p | prev: %p \n", prev_ptr, GET_NEXT_POINTER(prev_ptr), GET_PREV_POINTER(prev_ptr));
exit(1);
}
}
}
}
/*
* mm_checkheap - There are no bugs in my code, so I don't need to check,
* so nah!
*/
void mm_checkheap(int lineno) {
/*Get gcc to be quiet. */
//verbose = verbose;
// check epilogue and prolague blocks:
if (GET(HDRP(heap_listp)) != PACK(DSIZE, 1, 1) || GET(FTRP(heap_listp)) != PACK(DSIZE, 1, 1)) {
printf("%d\n", GET(heap_listp + WSIZE));
printf("prologue error [%d]\n", lineno);
exit(1);
}
// check block's address alignment
int prev_alloc = 1;
void* prev_ptr = NULL;
int free_blocks = 0;
for (void* ptr = heap_listp; GET_SIZE(HDRP(ptr)) != 0; ptr = NEXT_BLKP(ptr)) {
if (!GET_ALLOC(HDRP(ptr))) {
free_blocks += 1;
}
checkblock(ptr, lineno);
if (prev_alloc == 0 && GET_ALLOC(HDRP(ptr)) == 0) {
printf("\nthe prev block: \n");
printblock(PREV_BLKP(ptr));
printf("\nthe current block\n");
printblock(ptr);
printf("two consecutive blocks [%d]\n", lineno);
exit(1);
}
if (!prev_alloc && prev_ptr != NULL) {
if (PREV_BLKP(ptr) != prev_ptr) {
printblock(ptr);
printf("prev [%p] pointers refers to wrong place [%p] at line [%d]", PREV_BLKP(ptr), prev_ptr, lineno);
exit(1);
}
}
if (ptr < mem_heap_lo() || ptr > mem_heap_hi()) {
printblock(ptr);
printf("list pointers points beyond heap limits [%p] for ptr [%p] at line [%d]\n", mem_heap_hi(), ptr, lineno);
exit(1);
}
if (ptr == prev_ptr) {
printblock(ptr);
printf("pointer doesn't move [%d]\n", lineno);
exit(1);
}
prev_ptr = ptr;
prev_alloc = GET_ALLOC(HDRP(ptr));
}
if (free_blocks != 0) {
printf("not allocated list\n");
for (void* ptr = heap_listp; GET_SIZE(HDRP(ptr)) != 0; ptr = NEXT_BLKP(ptr)) {
if (!GET_ALLOC(HDRP(ptr))) {
printf("%p -> ", ptr);
}
}
print_free_list();
printf("\nfree blocks number is not matched %d from line %d\n", free_blocks, lineno);
exit(1);
}
}
static void print_free_list() {
printf("\nfree list");
for (int i = 0; i < SEG_LIMIT; i++) {
void* cur = *((void**)seg_list+i);
if (cur != NULL) printf("\nindex %d : \n", i);
for (; cur != NULL; cur = GET_NEXT_POINTER(cur)) {
printf("%p -> ", cur);
}
if (cur != NULL) printf("\n");
}
printf("\n");
}
|
C
|
#include "joystick.h"
s16 joystick[4]={0,0,0,0};
s16 joystick_reader_counter=0;
void joystick_setup() {
joystick[0]=0;
joystick[1]=0;
joystick[2]=0;
joystick[3]=0;
}
void joystick_capture()
{
static u8 n=0;
static u16 time_previous = 0;
static u16 joystick_[6] = {0,0,0,0,0,0};
u16 time, time_delta;
u8 i;
time = READ_TIMER_1;
joystick_reader_counter++; // para saber si se perdi la comunicacin con el joystick
if(time_previous < time) {
time_delta = time - time_previous;
} else {
time_delta = 60000 - (time_previous - time);
}
if(n == 0) {
if(time_delta>15000) {
n=1;
}
} else if(n != 0) {
if(1700 < time_delta && time_delta < 4300)
joystick_[n-1]=time_delta;
else {
n=0;
}
n++;
if(n>6) {
if(2700 < joystick_[4] && joystick_[4] < 2799 && 2700 < joystick_[5] && joystick_[5] < 2799) {
for(i=0; i<4; i++) {
switch(i) {
case 0:
joystick[0] = joystick_[0];
joystick[0] = 200*((s16)joystick_[0]-2707)/(3458-1907);
break;
case 1:
joystick[1] = joystick_[1];
joystick[1] = 200*((s16)joystick_[1]-2750)/(3465-1993);
break;
case 2:
joystick[2] = joystick_[2];
joystick[2] = 100*((s16)joystick_[2]-2118)/(4090-2118);
break;
case 3:
joystick[3] = joystick_[3];
joystick[3] = 200*((s16)joystick_[3]-3407)/(4099-2639);
break;
}
}
}
n=0;
}
}
time_previous = time;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct list_s list_t;
struct list_s{
list_t *next;
char* word;
};
list_t *nodealloc(char *,list_t *);
list_t * stringsplit(char *);
int main()
{ list_t *ptr=NULL;
ptr=stringsplit("a.b.cccc.ddd.ccc.ddd.sss.sss");
while(ptr!=NULL){
printf("%s\n",ptr->word);
ptr=ptr->next;
}
return 0;
}
list_t * stringsplit(char *str){
int i,j=0;
char mystr[100];
list_t *head=NULL;
for(i=0;str[i]!='\0';i++){
if(str[i]=='.' || str[i]=='\0'){
mystr[j]='\0';
head=nodealloc(mystr,head) ;
j=0;
}
else{
mystr[j] =str[i];
j++;
}
}
mystr[j]='\0';
head=nodealloc(mystr,head) ;
return head;
}
list_t *nodealloc(char *mystr,list_t *head){
list_t *ptr,*tmp;
ptr=malloc(sizeof(list_t));
ptr->word=malloc(sizeof(strlen(mystr)+1));
strcpy(ptr->word,mystr);
ptr->next=NULL;
if(head==NULL){
return ptr;
}
else{
tmp=head;
while(tmp->next!=NULL)
tmp=tmp->next;
tmp->next=ptr;
return head;
}
}
|
C
|
#include "utilities.h"
#include <inttypes.h>
#include <stdlib.h>
#include <stdio.h>
int main(int argc, char **argv) {
struct timespec start_time;
struct timespec wait_time;
struct timespec now;
uint64_t argv_start_time;
uint64_t argv_start_milliseconds;
char *argv_command;
if (argc != 4) {
printf("Usage: %s <start time in unix time (seconds)> <milliseconds> <command>\n", argv[0]);
exit(1);
}
sscanf(argv[1], "%" SCNu64, &argv_start_time);
sscanf(argv[2], "%" SCNu64, &argv_start_milliseconds);
start_time.tv_sec = argv_start_time;
start_time.tv_nsec = argv_start_milliseconds * 1000000;
printf("%lld %lu\n", (long long int)start_time.tv_sec, argv_start_milliseconds);
argv_command = argv[3];
timespec_get(&now, TIME_UTC);
timespec_diff(&now, &start_time, &wait_time);
nanosleep(&wait_time, 0);
return system(argv_command);
}
|
C
|
#include<stdio.h>
int main()
{
char ch;
printf("빮 Է:");
scanf("%c",&ch);
//빮 'A' ƽŰڵ尪 65 B ƽŰڵ尪 66
//ҹ 'a' ƽŰڵ尪 97 ι ̴ 32
printf("%c ҹڴ %cԴϴ.",ch, ch+32);
return 0;
}
|
C
|
#define NULL ((void*)0)
typedef unsigned long size_t; // Customize by platform.
typedef long intptr_t; typedef unsigned long uintptr_t;
typedef long scalar_t__; // Either arithmetic or pointer type.
/* By default, we understand bool (as a convenience). */
typedef int bool;
#define false 0
#define true 1
/* Forward declarations */
/* Type definitions */
/* Variables and functions */
int parse_signature (char const*,unsigned long) ;
char* strchrnul (char const*,char) ;
unsigned long strlen (char const*) ;
__attribute__((used)) static void find_subpos(const char *buf,
const char **sub, unsigned long *sublen,
const char **body, unsigned long *bodylen,
unsigned long *nonsiglen,
const char **sig, unsigned long *siglen)
{
const char *eol;
/* skip past header until we hit empty line */
while (*buf && *buf != '\n') {
eol = strchrnul(buf, '\n');
if (*eol)
eol++;
buf = eol;
}
/* skip any empty lines */
while (*buf == '\n')
buf++;
/* parse signature first; we might not even have a subject line */
*sig = buf + parse_signature(buf, strlen(buf));
*siglen = strlen(*sig);
/* subject is first non-empty line */
*sub = buf;
/* subject goes to first empty line */
while (buf < *sig && *buf && *buf != '\n') {
eol = strchrnul(buf, '\n');
if (*eol)
eol++;
buf = eol;
}
*sublen = buf - *sub;
/* drop trailing newline, if present */
if (*sublen && (*sub)[*sublen - 1] == '\n')
*sublen -= 1;
/* skip any empty lines */
while (*buf == '\n')
buf++;
*body = buf;
*bodylen = strlen(buf);
*nonsiglen = *sig - buf;
}
|
C
|
#include "List.h"
#include "List.c"
#include "queue.h"
#include "queue.c"
#include <stdio.h>
void main()
{
int choice;
queue *q1 = queue_new();
queue *q2 = queue_new();
int queueinuse = 1;
int ele, size;
printf("Press -1 to exit, 1 to push, 2 to pop, 3 to get size, 4 to print stack : ");
scanf("%d", &choice);
while(choice != -1)
{
switch(choice)
{
case 1: scanf("%d", &ele);
if(queueinuse == 1)
{
enqueue(q2, ele);
while(!queue_is_empty(q1))
{
ele = dequeue(q1);
enqueue(q2, ele);
}
queueinuse = 2;
}
else
{
enqueue(q1, ele);
while(!queue_is_empty(q2))
{
ele = dequeue(q2);
enqueue(q1, ele);
}
queueinuse = 1;
}
break;
case 2: if(queueinuse == 1)
ele = dequeue(q1);
else
ele = dequeue(q2);
printf("%d popped\n", ele);
break;
case 3: if(queueinuse == 1)
size = queue_size(q1);
else
size = queue_size(q2);
printf("Size : %d\n", size);
break;
case 4: if(queueinuse == 1)
queue_print(q1);
else
queue_print(q2);
printf("\n");
break;
case -1: break;
default : printf("Invalid Choice");
break;
}
printf("Press -1 to exit, 1 to push, 2 to pop, 3 to print, 4 to get size of stack : ");
scanf("%d", &choice);
}
}
|
C
|
#include <stdio.h>
//Function Prototypes
float checkBalance(int acctNum);
float getBalance(int acctNum);
/* checkBalance: return the balance of the specified account */
float checkBalance(int acctNum)
{
float bal;
bal = getBalance(acctNum);
return bal;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
void * my_memmove(void *dst,const void * src,size_t num)
{
void * ret = dst;
if (src <= dst && dst < (char *)src + num)
{
dst = (char *)dst + num - 1;
src = (char *)src + num - 1;
while (num--)
{
*(char *)dst = *(char *)src;
dst = (char *)dst - 1;
src = (char *)src - 1;
}
}
else{
while (num--)
{
*(char *)dst = *(char *)src;
dst = (char *)dst + 1;
src = (char *)src + 1;
}
}
return ret;
}
int main()
{
char str[] = "abcd";
my_memmove(str + 1, str, 4);
system("pause");
return 0;
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* exec2.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: darugula <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2020/01/01 12:26:24 by darugula #+# #+# */
/* Updated: 2020/01/01 12:26:25 by darugula ### ########.fr */
/* */
/* ************************************************************************** */
#include "minishell.h"
static pid_t built_in_or_external(char **replaced_args, int c)
{
pid_t pid;
pid = 0;
if (!built_in_processed(replaced_args, c))
{
pid = exec2((const char**)replaced_args);
}
ft_free_array((void**)replaced_args, c);
return (pid);
}
static pid_t exec3(int c, char **args)
{
char *replaced_args[c + 1];
replaced_args[c] = NULL;
env_replace_vars(replaced_args, (const char**)args);
ft_free_null_term_array((void**)args);
replace_back(replaced_args);
debug_printf("after replace\n");
debug_print_zt_array((const char**)replaced_args);
return (built_in_or_external(replaced_args, c));
}
pid_t exec(char *str)
{
char **args;
int c;
args = ft_split3(str, " \t");
free(str);
c = ft_count_null_term_array((void*)args);
return (exec3(c, args));
}
|
C
|
#ifndef MAIN_H
#define MAIN_H
// Program version (as reported by -v)
#define VERSION "1.2"
// Allowed ROM size limits
#define MIN_ROM_SIZE 0x200
#define MAX_ROM_SIZE 0x400000
// Location of relevant header fields
#define HEADER_COPYRIGHT 0x113 // Copyright code
#define HEADER_DATE 0x118 // Build date
#define HEADER_TITLE1 0x120 // Domestic title
#define HEADER_TITLE2 0x150 // Overseas title
#define HEADER_CHECKSUM 0x18E // Checksum
#define HEADER_SERIALNO 0x183 // Serial number
#define HEADER_REVISION 0x18C // Revision
#define HEADER_ROMSTART 0x1A0 // ROM start address
#define HEADER_ROMEND 0x1A4 // ROM end address
#define HEADER_RAMSTART 0x1A8 // RAM start address
#define HEADER_RAMEND 0x1AC // RAM end address
#define PROGRAM_START 0x200 // Where game code proper starts
// Other limits
#define DATE_LEN 8 // Length of build date field
#define TITLE_LEN 48 // Length of title fields
#define COPYRIGHT_LEN 4 // Length of copyright code
#define SERIALNO_LEN 8 // Length of serial number
typedef struct {
size_t size; // Size in bytes
uint8_t blob[MAX_ROM_SIZE]; // Where ROM is stored
} Rom;
// ROM padding modes
typedef enum {
PADDING_QUIET, // Just pad
PADDING_VERBOSE, // Pad and report sizes
} PadMode;
#endif
|
C
|
/////////////////////////////////////////////////////////////////////////////////
/// DS1307.C ///
/// ///
/// ds1307_init() -Habilita o relógio sem alterar o estado dos registradores ///
/// -Saída de onda quadrada desativada por padrão ///
/// ///
/// ds1307_set_date_time(dia,mes,ano,hor,min,seg) ///
/// -Altera data e hora ///
/// Exemplo: (24/07/2012 08:16:05) ///
/// ds1307_set_date_time(24,07,12,8,16,5); ///
/// ///
/// ds1307_get_date() ///
/// -Obtém a data e o dia da semana ///
/// ///
/// ds1307_get_time() ///
/// -Obtém a hora ///
/// ///
/////////////////////////////////////////////////////////////////////////////////
/// ///
/// 2012 - Guilherme Mazoni ///
/// ///
/////////////////////////////////////////////////////////////////////////////////
#use i2c(MASTER, SLOW, sda=RTC_SDA, scl=RTC_SCL)
BYTE seg, min, hor, dds, dia, mes, ano;
BYTE bin2bcd(BYTE bin);
BYTE bcd2bin(BYTE bcd);
int8 calc_dds(int8 _dia, int8 _mes, int16 _ano);
void ds1307_init(void)
{
BYTE segs = 0;
i2c_start();
i2c_write(0xD0);
i2c_write(0x00);
i2c_stop();
i2c_start();
i2c_write(0xD1);
segs = bcd2bin(i2c_read(0));
delay_us(3);
i2c_stop();
segs &= 0x7F;
delay_us(3);
i2c_start();
i2c_write(0xD0);
i2c_write(0x00);
i2c_write(bin2bcd(segs));
i2c_stop();
i2c_start();
i2c_write(0xD0);
i2c_write(0x07);
i2c_write(0x80); //Desabilita a saída de onda quadrada
i2c_stop();
}
void ds1307_set_date_time(BYTE dia, BYTE mes, BYTE ano, BYTE hora, BYTE min, BYTE seg)
{
BYTE dds;
dds = calc_dds(dia,mes,ano);
seg &= 0x7F;
hora &= 0x3F;
i2c_start();
i2c_write(0xD0);
i2c_write(0x00);
i2c_write(bin2bcd(seg)); // REG 0
i2c_write(bin2bcd(min)); // REG 1
i2c_write(bin2bcd(hora)); // REG 2
i2c_write(bin2bcd(dds)); // REG 3 - Dia da semana
i2c_write(bin2bcd(dia)); // REG 4
i2c_write(bin2bcd(mes)); // REG 5
i2c_write(bin2bcd(ano)); // REG 6
i2c_write(0x80); // REG 7 - Desabilita a saída de onda quadrada
i2c_stop();
}
void ds1307_get_date()
{
i2c_start();
i2c_write(0xD0);
i2c_write(0x03);
i2c_start();
i2c_write(0xD1);
dds = bcd2bin(i2c_read() & 0x7f); // REG 3
dia = bcd2bin(i2c_read() & 0x3f); // REG 4
mes = bcd2bin(i2c_read() & 0x1f); // REG 5
ano = bcd2bin(i2c_read(0)); // REG 6
i2c_stop();
}
void ds1307_get_time()
{
i2c_start();
i2c_write(0xD0);
i2c_write(0x00);
i2c_start();
i2c_write(0xD1);
seg = bcd2bin(i2c_read() & 0x7f);
min = bcd2bin(i2c_read() & 0x7f);
hor = bcd2bin(i2c_read(0) & 0x3f);
i2c_stop();
}
BYTE bin2bcd(BYTE bin)
{
BYTE temp;
BYTE aux;
temp = bin;
aux = 0;
while(1)
{
if(temp >= 10)
{
temp -= 10;
aux += 0x10;
}
else
{
aux += temp;
break;
}
}
return(aux);
}
BYTE bcd2bin(BYTE bcd) // Margem de 00 a 99.
{
BYTE temp;
temp = bcd;
temp >>= 1;
temp &= 0x78;
return(temp + (temp >> 2) + (bcd & 0x0f));
}
int8 calc_dds(int8 _dia, int8 _mes, int16 _ano)
{
int8 ix, tx, vx;
_ano = _ano + 2000;
switch(_mes)
{
case 2 :
case 6 : vx = 0; break;
case 8 : vx = 4; break;
case 10 : vx = 8; break;
case 9 :
case 12 : vx = 12; break;
case 3 :
case 11 : vx = 16; break;
case 1 :
case 5 : vx = 20; break;
case 4 :
case 7 : vx = 24; break;
}
if (_ano > 1900) _ano -= 1900;
ix = (int16)((_ano - 21) % 28) + vx + (_mes > 2);
tx = (ix + (ix / 4)) % 7 + _dia;
return ((tx % 7) + 1);
}
|
C
|
#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
#include<assert.h>
#include<stdlib.h>
#include<string.h>
//void qsort(void*base, num, width, int(*compare)(const void*, const void*));
// Ҫָ Ԫظ ԪشС ȽԪشСĺ
typedef struct STU
{
char name[20];
int age;
}STU;
void Swap(char*p1,char* p2,int width)
{
int i = 0;
for (i = 0; i < width; i++)
{
char tmp = *p1;
*p1 = *p2;
*p2 = tmp;
p1++;
p2++;
}
}
void Bubble_sort(void*base, int sz, int width,int(*cmp)( void *e1, void*e2))
{
int i = 0;
for (i = 0; i < sz - 1; i++)
{
int j = 0;
for (j = 0; j < sz - 1 - i; j++)
{
if (cmp((char*)base + j*width, (char*)base + (j + 1)*width) > 0)
{
Swap((char*)base + j*width, (char*)base + (j + 1)*width,width);//
}
}
}
}
int cmp_int(const void* e1, const void* e2)
{
return *(int*)e1 - *(int*)e2;
}
int cmp_float(const void*e1, const void*e2)
{
if (*(float*)e1 > *(float*)e2)
return 1;
else if (*(float*)e1 == *(float*)e2)
return 0;
else
return -1;
}
int cmp_STU_by_age(const void*e1, const void*e2)
{
return (*(STU*)e1).age - (*(STU*)e2).age;//((STU*)e1)->age-((STU*)e1)->age
}
int cmp_STU_by_name(const void*e1, const void*e2)
{
return strcmp((*(STU*)e1).name,((STU*)e1)->name);
}
void test1()
{
int arr[] = { 1, 3, 5, 7, 9, 2, 4, 6, 8, 10 };
int sz = sizeof(arr) / sizeof(arr[0]);
qsort(arr, sz, sizeof(arr[0]), cmp_int);
int i = 0;
for (;i<sz;i++)
printf("%d ", arr[i]);
system("pause");
}
void test2()
{
float arr[] = { 1.0, 3.0, 5.0, 7.0, 9.0, 2.0, 4.0, 6.0, 8.0 };
int sz = sizeof(arr) / sizeof(arr[0]);
qsort(arr, sz, sizeof(arr[0]), cmp_float);
int i = 0;
for (; i<sz; i++)
printf("%f ", arr[i]);
system("pause");
}
void test3()
{
STU s[3] = { { "Tom", 12 }, { "Cow", 31 }, { "Fat", 26 } };
int sz = sizeof(s) / sizeof(s[0]);
//qsort(s, sz, sizeof(s[0]), cmp_STU_by_age);
qsort(s, sz, sizeof(s[0]), cmp_STU_by_name);
int i = 0;
for (; i < sz; i++)
{
printf("%s ", s[i].name);
printf("%d ", s[i].age);
printf("\n");
}
}
void test4()
{
int arr[] = { 1, 3, 5, 7, 9, 2, 4, 6, 8, 10 };
int sz = sizeof(arr) / sizeof(arr[0]);
Bubble_sort(arr, sz, sizeof(arr[0]), cmp_int);
int i = 0;
for (; i<sz; i++)
printf("%d ", arr[i]);
system("pause");
}
void test5()
{
STU s[3] = { { "Tom", 12 }, { "Cow", 31 }, { "Fat", 26 } };
int sz = sizeof(s) / sizeof(s[0]);
//qsort(s, sz, sizeof(s[0]), cmp_STU_by_age);
//qsort(s, sz, sizeof(s[0]), cmp_STU_by_name);
//Bubble_sort(s, sz, sizeof(s[0]), cmp_STU_by_age);
Bubble_sort(s, sz, sizeof(s[0]), cmp_STU_by_age);
int i = 0;
for (; i < sz; i++)
{
printf("%s ", s[i].name);
printf("%d ", s[i].age);
printf("\n");
}
}
int main()
{
//test1();
//test2();
//test3();
//test4();
test5();
return 0;
}
//char* my_strcpy1(char* arr, const char* str)
//{
// char* ret = arr;
// assert(arr != NULL);
// assert(str != NULL);
// while (*arr++ =*str++)
// {
// ;
// }
// return ret;
//}
//char* my_strcpy2(char* arr, const char* str)
//{
// char* ret = arr;
// assert(arr != NULL);
// assert(str != NULL);
// while (*arr++ = *str++)
// {
// ;
// }
// return ret;
//}char* my_strcpy3(char* arr, const char* str)
//{
// char* ret = arr;
// assert(arr != NULL);
// assert(str != NULL);
// while (*arr++ = *str++)
// {
// ;
// }
// return ret;
//}char* my_strcpy4(char* arr, const char* str)
//{
// char* ret = arr;
// assert(arr != NULL);
// assert(str != NULL);
// while (*arr++ = *str++)
// {
// ;
// }
// return ret;
//}
//
//
//int main()
//{
// char arr1[] = "************";
// char arr2[] = "little";
// char*(*pf)(char*, const char*)=my_strcpy1;
// char*(*pfarr[4])(char*, const char*) = { my_strcpy1, my_strcpy2, my_strcpy3, my_strcpy4 };
// printf("%s\n", pfarr[2](arr1,arr2));
// system("pause");
// return 0;
//}
|
C
|
/*CS1010 AY2019/20 Semester 1 Lab6 Ex2
* driver.c
* This program calculate the possible routes given an array of gas stations available within distance.
* <LIU YIFENG>
* <C06>
*/
#include <stdio.h>
#define MAX_STATIONS 20
//function prototypes
void readStations(int [], int [], int *, int *);
void printStations(int [], int [], int, int);
int calcPossibleRoutes(int, int [], int [], int, int);
int main(void) {
//declare variables
int distances[MAX_STATIONS];
int fuels[MAX_STATIONS];
int totalDist, numStation;
int possibleRoute;
//calling functions
readStations(distances, fuels, &totalDist, &numStation);
printStations(distances, fuels, totalDist, numStation);
possibleRoute = calcPossibleRoutes(100, distances, fuels, numStation, totalDist);
//initial gasAvail is 100
printf("Possible number of routes = %d\n", possibleRoute);
return 0;
}
// Read the gas stations' distances and available fuel
// and return the total distance and number of gas stations read.
// Note: Do not change this function
void readStations(int distances[], int fuels[], int *totalDistPtr, int *numStationPtr) {
int i;
printf("Enter total distance: ");
scanf("%d", totalDistPtr);//non-negative integers
printf("Enter number of gas stations: ");
scanf("%d", numStationPtr);//non-negative integers
printf("Enter distance and amount of fuel for each gas station:\n");
// gasStation Array will store in such way [dist0, fuel0, dist1, fuel1, dist2, fuel2, ...]
for (i = 0; i < *numStationPtr; i++) {
scanf("%d %d", &distances[i], &fuels[i]);//distances are integers in increasing order
//fuels are integers
}
}
// Print total distance and gas stations' distances and fuel
// Note: Do not change this function
void printStations(int distances[], int fuels[], int totalDist, int numStation) {
int i;
printf("Total distance = %d\n", totalDist);
printf("Number of gas stations = %d\n", numStation);
printf("Gas stations' distances: ");
for (i = 0; i < numStation; i++) {
printf("%4d ", distances[i]);
}
printf("\n");
printf("Gas stations' fuel amt : ");
for (i = 0; i < numStation; i++) {
printf("%4d ", fuels[i]);
}
printf("\n");
}
//return the number of possible routes
int calcPossibleRoutes(int gasAvail, int distances[], int fuels[], int numStation, int totalDist) {
if(numStation == 0) {//if there is no station
if(totalDist > gasAvail)//and if the totalDist is more than the gasAvail
return 0;//impossible to finish - 0 possible routes
else//if gasAvail is enough for toatalDist
return 1;//only 1 possible route to finish, no station for choice of refill
}
else if(numStation == 1) {//last station before destination
if(gasAvail >= totalDist)//gas is enough even if does not refill
return 2;//refill or dont refill, 2 possibilities
else if(gasAvail + fuels[0] < totalDist)
//gas is not enough even if refilled
return 0;
else
//gas is enough iff refil
return 1;
}
else {
if(gasAvail >= distances[1])//gas is enough to reach the next station
return calcPossibleRoutes(gasAvail+fuels[0], distances+1, fuels+1, numStation-1, totalDist)
+ calcPossibleRoutes(gasAvail, distances+1, fuels+1, numStation-1, totalDist);
//can either refill or not, number of possible routes is the sum refilling and not refilling
else if(gasAvail < distances[0])//gas is not enough to reach the first station
return 0;//impossible to finish
else//can reach the next station iff refill
return calcPossibleRoutes(gasAvail+fuels[0], distances+1, fuels+1, numStation-1, totalDist);
}
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
void g(int x, int * y) {
printf("In g, x = %d, *y = %d\n", x, *y);
x++;
*y = *y - x;
y = &x;
}
void f(int * a, int b) {
printf("In f, *a = %d, b = %d\n", *a, b);
*a += b;
b *= 2;
g(*a, &b);
printf("Back in f, *a = %d, b = %d\n", *a, b);
}
int main(void) {
int x = 3;
int y = 4;
f(&x, y);
printf("In main: x = %d, y = %d\n", x, y);
return EXIT_SUCCESS;
}
/*
output
In f, *a = 3, b = 4
In g, x = 7, y = 8
Back in f, *a = 7, b = 0
In main, x = 7, y = 4
*/
|
C
|
#include "common.h"
#include "log.h"
#include "branch_layer.h"
#include <memory.h>
static void branch_layer_prepare(layer_t *l)
{
LOG("branch_layer: in %d\n", l->in.size);
}
static void branch_layer_forward(layer_t *l)
{
int i = 0, b = 0;
branch_layer_t *me = (branch_layer_t *)l;
for (i = 0; i < me->num; ++i)
{
layer_t *branch = me->branch[i].n->layer[0];
for (b = 0; b < l->n->batch; ++b)
memcpy(&branch->in.val[b * branch->in.size], &l->in.val[b * l->in.size + me->branch[i].offset],
branch->in.size * sizeof(data_val_t));
net_forward(me->branch[i].n);
}
}
static void branch_layer_backward(layer_t *l)
{
int i = 0, j = 0, b = 0;
branch_layer_t *me = (branch_layer_t *)l;
memset(l->in.grad, 0, l->n->batch * l->in.size * sizeof(data_val_t));
for (i = 0; i < me->num; ++i)
{
layer_t *branch = me->branch[i].n->layer[0];
for (b = 0; b < l->n->batch; ++b)
for (j = 0; j < branch->in.size; ++j)
l->in.grad[b * l->in.size + me->branch[i].offset + j] += branch->in.grad[b * branch->in.size + j];
}
}
static const layer_func_t branch_func = {
branch_layer_prepare,
branch_layer_forward,
branch_layer_backward};
layer_t *branch_layer(int in, net_t *n, int offset, ...)
{
int num = 1;
va_list branches;
va_start(branches, offset);
for (net_t *_n = NULL; _n = va_arg(branches, net_t *); ++num)
{
va_arg(branches, int);
}
va_end(branches);
branch_layer_t *me = (branch_layer_t *)alloc(1, sizeof(branch_layer_t) + num * sizeof(branch_t));
me->l.in.size = in;
me->l.func = &branch_func;
me->num = 1;
me->branch = (branch_t *)(me + 1);
me->branch[0].n = n;
me->branch[0].offset = offset;
va_start(branches, offset);
for (net_t *_n = NULL; _n = va_arg(branches, net_t *); ++(me->num))
{
me->branch[me->num].n = _n;
me->branch[me->num].offset = va_arg(branches, int);
}
va_end(branches);
return (layer_t *)me;
}
int is_branch_layer(layer_t *l)
{
return l->func == &branch_func;
}
|
C
|
#include <stdio.h>
int main(void)
{
int n;
int p;
printf("Enter value for n and p followed by 'Enter': ");
scanf("%d %d", &n, &p);
printf("n value is: %d\np value is: %d\n", n, p);
return(0);
}
|
C
|
#include <stdlib.h>
#include <wordexp.h>
#include <dirent.h>
#include <errno.h>
#include <sys/stat.h>
#include "tc-directory.h"
#include "tc-task.h"
const char * _tc_getHomePath(){
const char * homePath;
/* Determine the home directory */
homePath = getenv("HOME");
if ( homePath == NULL ) {
/* Determine the home directory a different way */
wordexp_t exp_result;
wordexp("~", &exp_result, 0);
homePath = (exp_result.we_wordv[0]);
}
return homePath;
}
void _tc_getTasksDir(char * tasksDir){
const char * home;
home = _tc_getHomePath();
sprintf(tasksDir,"%s/.tc/%s",home,TC_TASK_DIR);
}
void _tc_getCurrentTaskPath(char * currentTaskPath){
const char * home;
home = _tc_getHomePath();
sprintf(currentTaskPath,"%s/.tc/%s",home,TC_CURRENT_TASK);
}
int _tc_directoryExists(char * directoryToCheck){
DIR * dir;
int success;
dir = opendir(directoryToCheck);
if ( dir ) {
closedir(dir);
success = TRUE;
} else if ( ENOENT == errno )
success = FALSE; /* The directory doesn't exist */
else
success = -1;/* Something went wrong with opening it */
return success;
}
int _tc_file_exists(const char * filename){
/* Security Concern: If you check for a file's existence and then open the
* file, between the time of access checking and creation of a file someone
* can create a symlink or something and cause your open to fail or open
* something that shouldn't be opened. That being said... I'm not concerned.
*/
struct stat buffer;
return(stat (filename, &buffer) == 0);
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_path_add.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: grass-kw <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2016/02/26 13:31:43 by grass-kw #+# #+# */
/* Updated: 2016/02/26 13:46:12 by grass-kw ### ########.fr */
/* */
/* ************************************************************************** */
#include "ft_ls.h"
void determine_position(t_path **begin_path, t_path *new_elem,
t_env *e, int *i)
{
if (flag_is_active(TIME, e->flags))
*i = insertion_sort(begin_path, new_elem, compare_date_path, e);
else if (flag_is_active(BIRTH_DATE, e->flags))
*i = insertion_sort(begin_path, new_elem, compare_birth_path, e);
else
*i = insertion_sort(begin_path, new_elem, compare_name_path, e);
}
static void if_zero(t_path **begin_path, t_path *new_elem, t_path *cursor)
{
new_elem->next = cursor;
*begin_path = new_elem;
}
void ft_path_add(t_path **begin_path, t_path *new_elem, t_env *e)
{
t_path *cursor;
unsigned int size;
int i;
determine_position(begin_path, new_elem, e, &i);
size = ft_path_size(begin_path);
cursor = *begin_path;
if (i == 0 && size == 0)
*begin_path = new_elem;
else if (i == 0 && size != 0)
if_zero(begin_path, new_elem, cursor);
else
{
while ((i-- - 1))
cursor = cursor->next;
if (cursor == NULL)
cursor->next = new_elem;
else
{
new_elem->next = cursor->next;
cursor->next = new_elem;
}
}
}
|
C
|
#include "libft.h"
char *ft_strnew(size_t size)
{
char *res;
if ((res = malloc(sizeof(char) * (size + 1))) == NULL)
return (NULL);
res[size] = '\0';
while (size--)
res[size] = '\0';
return (res);
}
|
C
|
#include "multiboot.h"
#include "print.h"
void gdt_done();
void mem(struct multiboot_info* mbt)
{
char *clear_screen = " ";
int len = (int)mbt->mmap_length;
unsigned long x = 0, mem=0;
char *welcome = "Welcome to FIFOS: The System memory is: ";
char *mb=" MB";
memory_map_t* mmap = (memory_map_t*)mbt->mmap_addr;
while(mmap <(mbt->mmap_addr + len))
{
if(mmap->type == 1)
{
x = mmap->length_low;
mem = mem + x;
}
mmap = (memory_map_t*) ( (unsigned int)mmap + mmap->size + sizeof(unsigned int) );
}
mem = mem>>20;
pos_x=0;
pos_y=0;
//clearing the screen before writing on it
while(1)
{
WriteCharacter(clear_screen);
if(pos_y>25)
break;
}
//resetting the cursor value
pos_x=0;
pos_y=0;
//printing the welcome message
WriteCharacter(welcome);
//printing the amount of free memory
print_num (mem);
//printing the unit of the free system memory
WriteCharacter(mb);
pos_y ++;
pos_x = 0;
return;
}
void gdt_done()
{
char *gdt = "GDT initialised...";
WriteCharacter(gdt);
return;
}
|
C
|
#include <string.h>
#include <stdio.h>
int main(void) {
int a = 0b1111;
int b = 0b0011;
int status;
status = memcmp(&a, &b, 4);
if (status == 0) {
printf("Same bytes\n");
}
else if (status < 0) {
printf()
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#include "../common/constants.h"
#include "../topology/topology.h"
#include "routingtable.h"
//makehash()是由路由表使用的哈希函数.
//它将输入的目的节点ID作为哈希键,并返回针对这个目的节点ID的槽号作为哈希值.
int makehash(int node)
{
return node % MAX_ROUTINGTABLE_SLOTS;
}
//这个函数动态创建路由表.表中的所有条目都被初始化为NULL指针.
//然后对有直接链路的邻居,使用邻居本身作为下一跳节点创建路由条目,并插入到路由表中.
//该函数返回动态创建的路由表结构.
routingtable_t* routingtable_create()
{
routingtable_t * my_route = (routingtable_t *)malloc(sizeof(routingtable_t));
int i = 0;
for(i=0; i<MAX_ROUTINGTABLE_SLOTS; i++) {
my_route->hash[i] = NULL;
}
int nbrnum = topology_getNbrNum();
int *nbrlist = topology_getNbrArray();
int j;
for( j=0; j<nbrnum; j++) {
routingtable_setnextnode(my_route, nbrlist[j], nbrlist[j]);
}
return my_route;
}
//这个函数删除路由表.
//所有为路由表动态分配的数据结构将被释放.
void routingtable_destroy(routingtable_t* routingtable)
{
int i = 0;
for(i=0; i<MAX_ROUTINGTABLE_SLOTS; i++) {
routingtable_entry_t *slot = routingtable->hash[i];
while(slot!=NULL) {
routingtable_entry_t *next = slot->next;
free(slot);
slot = next;
}
}
free(routingtable);
return;
}
//这个函数使用给定的目的节点ID和下一跳节点ID更新路由表.
//如果给定目的节点的路由条目已经存在, 就更新已存在的路由条目.如果不存在, 就添加一条.
//路由表中的每个槽包含一个路由条目链表, 这是因为可能有冲突的哈希值存在(不同的哈希键, 即目的节点ID不同, 可能有相同的哈希值, 即槽号相同).
//为在哈希表中添加一个路由条目:
//首先使用哈希函数makehash()获得这个路由条目应被保存的槽号.
//然后将路由条目附加到该槽的链表中.
void routingtable_setnextnode(routingtable_t* routingtable, int destNodeID, int nextNodeID)
{
int pos = makehash(destNodeID);
routingtable_entry_t *table;
if(routingtable->hash[pos] == NULL) { //add
routingtable->hash[pos] = (routingtable_entry_t *)malloc(sizeof(routingtable_entry_t));
table = routingtable->hash[pos];
table->destNodeID = destNodeID;
table->nextNodeID = nextNodeID;
table->next = NULL;
return;
}
else { //update!
table = routingtable->hash[pos];
while(table!= NULL) {
if(table->destNodeID == destNodeID) {
table->nextNodeID = nextNodeID;
return;
}
table = table->next;
}
table = (routingtable_entry_t*)malloc(sizeof(routingtable_entry_t));
table->next = routingtable->hash[pos];
routingtable->hash[pos] = table;
}
return;
}
//这个函数在路由表中查找指定的目标节点ID.
//为找到一个目的节点的路由条目, 你应该首先使用哈希函数makehash()获得槽号,
//然后遍历该槽中的链表以搜索路由条目.如果发现destNodeID, 就返回针对这个目的节点的下一跳节点ID, 否则返回-1.
int routingtable_getnextnode(routingtable_t* routingtable, int destNodeID)
{
int pos = makehash(destNodeID);
routingtable_entry_t *table;
if(routingtable->hash[pos] == NULL) {
return -1;
}
else {
table = routingtable->hash[pos];
while(table != NULL) {
if(table->destNodeID == destNodeID) {
return table->nextNodeID;
}
table = table->next;
}
}
return -1;
}
//这个函数打印路由表的内容
void routingtable_print(routingtable_t* routingtable)
{
printf("================== ROUTING TABLE ==================\n");
int i=0;
for(i=0; i<MAX_ROUTINGTABLE_SLOTS; i++) {
if(routingtable->hash[i]!=NULL) {
routingtable_entry_t* item = routingtable->hash[i];
printf("SLOT %d\n", i+1);
while(item != NULL) {
printf("destNodeID: %d\tnextNodeID: %d\n", item->destNodeID, item->nextNodeID);
item = item->next;
}
}
}
return;
}
|
C
|
/**
* This program demonstrates invocation of the rmdir
* system call (40) using the syscall function.
*/
#include <linux/types.h>
#include <linux/unistd.h>
#include <string.h>
int main(int argc, char *argv[]) {
// We demonstrate the use of command-line arguments here.
// But note the non-existent error handling (all the better
// to illustrate the error code below).
// JD: ^^^^ I think this is copy-paste leftover.
int result = syscall(40, argv[1]);
// A result of -1 means that something went wrong. Otherwise,
// check for your new directory!
if (result == 0) {
// Don't use this error message in "real" programs. O_o
char *successMessage = "You are Successful\n";
syscall(4, 2, successMessage, strlen(successMessage));
} if (result == -1) {
// Don't use this error message in "real" programs. O_o
char *errorMessage = "Herp derp mkderp\n";
syscall(4, 2, errorMessage, strlen(errorMessage));
}
}
|
C
|
//
// main.c
// 2-1
//
// Created by 下田将斉 on 2016/07/04.
// Copyright © 2016年 Masakiyo Shimoda. All rights reserved.
//
#include <stdio.h>
#include <time.h>
void printtime(long totalsec){
int sec, min, hour, day;
day = totalsec / (24 * 60 * 60);
hour = totalsec / (60 * 60) - (day * 24);
min = totalsec / (60) - (day * 24 * 60) - (hour * 60);
sec = totalsec % 60;
printf("%dd %02d:%02d:%02d\n",day, hour, min, sec);
}
int main(int argc, const char * argv[]) {
puts("7265秒は:");
printtime(7265);
puts("200000は:");
printtime(200000);
puts("1970年1月1日から現在までの経過時間は:");
time_t current;
current = time(NULL);
printtime((long)current);
return 0;
}
|
C
|
#include <math.h>
#include <stdio.h>
#include <ctype.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include "svm.h"
#define Malloc(type,n) (type *)malloc((n)*sizeof(type))
// yes, this was not the best idea..
typedef signed char schar;
typedef float Qfloat;
#ifndef min
template <class T> static inline T min(T x,T y) { return (x<y)?x:y; }
#endif
#ifndef max
template <class T> static inline T max(T x,T y) { return (x>y)?x:y; }
#endif
template <class T> static inline void swap(T& x, T& y) { T t=x; x=y; y=t; }
template <class S, class T> static inline void clone(T*& dst, S* src, int n)
{
dst = new T[n];
memcpy((void *)dst,(void *)src,sizeof(T)*n);
}
static inline double powi(double base, int times)
{
double tmp = base, ret = 1.0;
for(int t=times; t>0; t/=2)
{
if(t%2==1) ret*=tmp;
tmp = tmp * tmp;
}
return ret;
}
#define INF HUGE_VAL
#define TAU 1e-12
//
// Kernel Cache
//
// l is the number of total data items
// size is the cache size limit in bytes
//
class Cache
{
public:
Cache(int l,long int size);
~Cache();
// request data [0,len)
// return some position p where [p,len) need to be filled
// (p >= len if nothing needs to be filled)
int get_data(const int index, Qfloat **data, int len);
void swap_index(int i, int j);
private:
int l;
long int size;
struct head_t
{
head_t *prev, *next; // a circular list
Qfloat *data;
int len; // data[0,len) is cached in this entry
};
head_t *head;
head_t lru_head;
void lru_delete(head_t *h);
void lru_insert(head_t *h);
};
//
// Kernel evaluation
//
// the static method k_function is for doing single kernel evaluation
// the constructor of Kernel prepares to calculate the l*l kernel matrix
// the member function get_Q is for getting one column from the Q Matrix
//
class QMatrix {
public:
virtual Qfloat *get_Q(int column, int len) const = 0;
virtual double *get_QD() const = 0;
virtual void swap_index(int i, int j) const = 0;
virtual ~QMatrix() {}
virtual const svm_node * get_x(int i) const = 0;
};
class Kernel: public QMatrix {
public:
Kernel(int l, svm_node * const * x, const svm_parameter& param);
virtual ~Kernel();
static double k_function(const svm_node *x, const svm_node *y,
const svm_parameter& param);
virtual Qfloat *get_Q(int column, int len) const = 0;
virtual double *get_QD() const = 0;
virtual void swap_index(int i, int j) const // no so const...
{
swap(x[i],x[j]);
if(x_square) swap(x_square[i],x_square[j]);
}
virtual const svm_node * get_x(int i) const
{ return x[i]; }
protected:
double (Kernel::*kernel_function)(int i, int j) const;
private:
const svm_node **x;
double *x_square;
// svm_parameter
const int kernel_type;
const int degree;
const double gamma;
const double coef0;
static double dot(const svm_node *px, const svm_node *py);
double kernel_linear(int i, int j) const
{
return dot(x[i],x[j]);
}
double kernel_poly(int i, int j) const
{
return powi(gamma*dot(x[i],x[j])+coef0,degree);
}
double kernel_rbf(int i, int j) const
{
return exp(-gamma*(x_square[i]+x_square[j]-2*dot(x[i],x[j])));
}
double kernel_sigmoid(int i, int j) const
{
return tanh(gamma*dot(x[i],x[j])+coef0);
}
double kernel_precomputed(int i, int j) const
{
return x[i][(int)(x[j][0].value)].value;
}
};
int print_null(const char *s,...) {return 0;}
static int (*info)(const char *fmt,...) = &printf;
struct svm_node *x;
int max_nr_attr = 64;
struct svm_model* model;
int predict_probability=0;
static char *line = NULL;
static int max_line_len;
struct svm_problem prob; // set by read_problem
struct svm_node *x_space;
//struct svm_parameter param; // set by parse_command_line
const char* trainfile = NULL;
static char* readline(FILE *input)
{
int len;
if(fgets(line,max_line_len,input) == NULL)
return NULL;
while(strrchr(line,'\n') == NULL)
{
max_line_len *= 2;
line = (char *) realloc(line,max_line_len);
len = (int) strlen(line);
if(fgets(line+len,max_line_len-len,input) == NULL)
break;
}
return line;
}
void exit_input_error(int line_num)
{
fprintf(stderr,"Wrong input format at line %d\n", line_num);
exit(1);
}
void predict(FILE *input, FILE *output)
{
int correct = 0;
int total = 0;
double error = 0;
double sump = 0, sumt = 0, sumpp = 0, sumtt = 0, sumpt = 0;
int svm_type=svm_get_svm_type(model);
int nr_class=svm_get_nr_class(model);
double *prob_estimates=NULL;
int j;
if(predict_probability)
{
if (svm_type==NU_SVR || svm_type==EPSILON_SVR)
info("Prob. model for test data: target value = predicted value + z,\nz: Laplace distribution e^(-|z|/sigma)/(2sigma),sigma=%g\n",svm_get_svr_probability(model));
else
{
int *labels=(int *) malloc(nr_class*sizeof(int));
svm_get_labels(model,labels);
prob_estimates = (double *) malloc(nr_class*sizeof(double));
fprintf(output,"labels");
for(j=0;j<nr_class;j++)
fprintf(output," %d",labels[j]);
fprintf(output,"\n");
free(labels);
}
}
// --- extra computations
if (trainfile != NULL)
{
printf("Computing extra values..\n");
// some stupid things to initialize..
int l = model->l;
schar *y = new schar[l];
int i;
printf("Having %d SVs\n", l);
for(i=0;i<l;i++)
{
y[i] = -1;
if (model->sv_coef[0][i] > 0)
y[i] = +1;
}
printf("Obtained cost C: %f\n", model->param.C);
printf("Obtained gamma g: %f\n", model->param.gamma);
double Cp = model->param.C;
// compute hinge loss
printf("Current rho: [%f]\n", model->rho[0]);
double hingeLoss = 0.0;
for (int i = 0; i < prob.l; i++)
{
// predict value
{
double currentLoss = 0.0;
svm_predict_values(model, prob.x[i], ¤tLoss);
currentLoss = 1.0 - double(prob.y[i]) * currentLoss;
if (currentLoss > 0)
hingeLoss += currentLoss;
}
}
printf("Current hingeLoss: [%f]\n", hingeLoss);
// first term
double primal = Cp * hingeLoss;
// compute weight squared
double weight = 0;
for(int i=0;i<l;i++)
{
for(int j=i;j<l;j++)
{
double k = Kernel::k_function(model->SV[i], model->SV[j], model->param);
k = model->sv_coef[0][i] * k * model->sv_coef[0][j];
weight += k;
if (j != i)
weight += k;
}
}
weight = weight/2.0;
printf("Current weight: [%f]\n", sqrt(2*weight));
// second term
primal += weight;
// compute dual
double dual = -weight;
for (int j=0; j<l; j++)
{
dual += model->sv_coef[0][j] * y[j];
}
// do not count computation of primal to the save times
printf("Computed primal value: [%f]\n", primal);
printf("Computed dual value: [%f]\n", dual);
fflush(stdout);
// FREE ALPHAS, minus_ones , y
}
// ---
max_line_len = 1024;
line = (char *)malloc(max_line_len*sizeof(char));
while(readline(input) != NULL)
{
int i = 0;
double target_label, predict_label;
char *idx, *val, *label, *endptr;
int inst_max_index = -1; // strtol gives 0 if wrong format, and precomputed kernel has <index> start from 0
label = strtok(line," \t\n");
if(label == NULL) // empty line
exit_input_error(total+1);
target_label = strtod(label,&endptr);
if(endptr == label || *endptr != '\0')
exit_input_error(total+1);
while(1)
{
if(i>=max_nr_attr-1) // need one more for index = -1
{
max_nr_attr *= 2;
x = (struct svm_node *) realloc(x,max_nr_attr*sizeof(struct svm_node));
}
idx = strtok(NULL,":");
val = strtok(NULL," \t");
if(val == NULL)
break;
errno = 0;
x[i].index = (int) strtol(idx,&endptr,10);
if(endptr == idx || errno != 0 || *endptr != '\0' || x[i].index <= inst_max_index)
exit_input_error(total+1);
else
inst_max_index = x[i].index;
errno = 0;
x[i].value = strtod(val,&endptr);
if(endptr == val || errno != 0 || (*endptr != '\0' && !isspace(*endptr)))
exit_input_error(total+1);
++i;
}
x[i].index = -1;
if (predict_probability && (svm_type==C_SVC || svm_type==NU_SVC))
{
predict_label = svm_predict_probability(model,x,prob_estimates);
fprintf(output,"%g",predict_label);
for(j=0;j<nr_class;j++)
fprintf(output," %g",prob_estimates[j]);
fprintf(output,"\n");
}
else
{
predict_label = svm_predict(model,x);
fprintf(output,"%g\n",predict_label);
}
if(predict_label == target_label)
++correct;
error += (predict_label-target_label)*(predict_label-target_label);
sump += predict_label;
sumt += target_label;
sumpp += predict_label*predict_label;
sumtt += target_label*target_label;
sumpt += predict_label*target_label;
++total;
}
if (svm_type==NU_SVR || svm_type==EPSILON_SVR)
{
info("Mean squared error = %g (regression)\n",error/total);
info("Squared correlation coefficient = %g (regression)\n",
((total*sumpt-sump*sumt)*(total*sumpt-sump*sumt))/
((total*sumpp-sump*sump)*(total*sumtt-sumt*sumt))
);
}
else
info("Accuracy = %g%% (%d/%d) (classification)\n",
(double)correct/total*100,correct,total);
if(predict_probability)
free(prob_estimates);
}
void exit_with_help()
{
printf(
"Usage: svm-predict [options] test_file model_file output_file\n"
"options:\n"
"-o train_file : if specified some derivates like primal value, dual value etc will be computed\n"
"-b probability_estimates: whether to predict probability estimates, 0 or 1 (default 0); for one-class SVM only 0 is supported\n"
"-q : quiet mode (no outputs)\n"
);
exit(1);
}
// read in a problem (in svmlight format)
void read_problem(const char *filename)
{
int elements, max_index, inst_max_index, i, j;
FILE *fp = fopen(filename,"r");
char *endptr;
char *idx, *val, *label;
if(fp == NULL)
{
fprintf(stderr,"can't open input file %s\n",filename);
exit(1);
}
prob.l = 0;
elements = 0;
max_line_len = 1024;
line = Malloc(char,max_line_len);
while(readline(fp)!=NULL)
{
char *p = strtok(line," \t"); // label
// features
while(1)
{
p = strtok(NULL," \t");
if(p == NULL || *p == '\n') // check '\n' as ' ' may be after the last feature
break;
++elements;
}
++elements;
++prob.l;
}
rewind(fp);
if (prob.l == 0)
{
fprintf (stderr, "Trainfile has no data?!\n");
exit_input_error(-17);
}
prob.y = Malloc(double,prob.l);
prob.x = Malloc(struct svm_node *,prob.l);
x_space = Malloc(struct svm_node,elements);
max_index = 0;
j=0;
for(i=0;i<prob.l;i++)
{
inst_max_index = -1; // strtol gives 0 if wrong format, and precomputed kernel has <index> start from 0
readline(fp);
prob.x[i] = &x_space[j];
label = strtok(line," \t\n");
if(label == NULL) // empty line
exit_input_error(i+1);
prob.y[i] = strtod(label,&endptr);
if(endptr == label || *endptr != '\0')
exit_input_error(i+1);
while(1)
{
idx = strtok(NULL,":");
val = strtok(NULL," \t");
if(val == NULL)
break;
errno = 0;
x_space[j].index = (int) strtol(idx,&endptr,10);
if(endptr == idx || errno != 0 || *endptr != '\0' || x_space[j].index <= inst_max_index)
exit_input_error(i+1);
else
inst_max_index = x_space[j].index;
errno = 0;
x_space[j].value = strtod(val,&endptr);
if(endptr == val || errno != 0 || (*endptr != '\0' && !isspace(*endptr)))
exit_input_error(i+1);
++j;
}
if(inst_max_index > max_index)
max_index = inst_max_index;
x_space[j++].index = -1;
}
if(model->param.gamma == 0 && max_index > 0)
{
model->param.gamma = 1.0/max_index;
}
if(model->param.kernel_type == PRECOMPUTED)
for(i=0;i<prob.l;i++)
{
if (prob.x[i][0].index != 0)
{
fprintf(stderr,"Wrong input format: first column must be 0:sample_serial_number\n");
exit(1);
}
if ((int)prob.x[i][0].value <= 0 || (int)prob.x[i][0].value > max_index)
{
fprintf(stderr,"Wrong input format: sample_serial_number out of range\n");
exit(1);
}
}
fclose(fp);
}
int main(int argc, char **argv)
{
FILE *input, *output;
int i;
double Cparam = -1.41;
// parse options
for(i=1;i<argc;i++)
{
if(argv[i][0] != '-') break;
++i;
switch(argv[i-1][1])
{
case 'o':
trainfile = argv[i];
break;
case 'c':
Cparam = atof(argv[i]);
break;
case 'b':
predict_probability = atoi(argv[i]);
break;
case 'q':
info = &print_null;
i--;
break;
default:
fprintf(stderr,"Unknown option: -%c\n", argv[i-1][1]);
exit_with_help();
}
}
if ((trainfile != NULL) && (Cparam == -1.41))
{
fprintf(stderr, "Need to specify the cost, if trainfile option is used.");
exit_with_help();
}
if(i>=argc-2)
exit_with_help();
input = fopen(argv[i],"r");
if(input == NULL)
{
fprintf(stderr,"can't open input file %s\n",argv[i]);
exit(1);
}
output = fopen(argv[i+2],"w");
if(output == NULL)
{
fprintf(stderr,"can't open output file %s\n",argv[i+2]);
exit(1);
}
if((model=svm_load_model(argv[i+1]))==0)
{
fprintf(stderr,"can't open model file %s\n",argv[i+1]);
exit(1);
}
model->param.C = Cparam;
// if we specified a train file, we need to read it
if (trainfile != NULL)
{
printf("Reading training file..\n");
read_problem(trainfile);
}
x = (struct svm_node *) malloc(max_nr_attr*sizeof(struct svm_node));
if(predict_probability)
{
if(svm_check_probability_model(model)==0)
{
fprintf(stderr,"Model does not support probabiliy estimates\n");
exit(1);
}
}
else
{
if(svm_check_probability_model(model)!=0)
info("Model supports probability estimates, but disabled in prediction.\n");
}
printf("Predicting..\n");
predict(input,output);
svm_free_and_destroy_model(&model);
free(x);
free(line);
fclose(input);
fclose(output);
return 0;
}
|
C
|
//print all natural no. b/w n & 1 using while loop
#include<stdio.h>
int main()
{
int n,i=1;
printf("\nEnter no. till you want natural no. to be printed : ");
scanf("%d",&n);
i=n;
printf("\nNatural nos b/w %d and 1 are : ",n);
while(i>=1)
{
printf(" %d ",i);
i--;
}
printf("\n");
return 0;
}
|
C
|
#include<signal.h>
#include <stdio.h>
#include <stdlib.h>
#include<unistd.h>
void sigcb(int signo){
}
int mysleep(int nsec){
signal(SIGALRM,sigcb);
alarm(nsec);
pause();//永久阻塞但是被信号打断了
}
int main(){
mysleep(2);
printf("-----");
}
|
C
|
/*
* bit_manipulation.c
*
* Created on: Feb 4, 2020
* Author: Alex
*/
#include <stdio.h>
#include "bit_manipulation.h"
void check_bit(unsigned char x, unsigned char pos)
{
x &= 1U << pos;
if(x)
{
printf("Bit is SET\n");
}
else
{
printf("Bit is UNSET\n");
}
}
void set_bit(unsigned char * x, unsigned char pos)
{
*x |= 1U << pos;
}
void unset_bit(unsigned char * x, unsigned char pos)
{
*x &= ~(1U << pos);
}
void toggle_bit(unsigned char * x, unsigned char pos)
{
*x ^= 1U << pos;
}
|
C
|
#include "my_misc.h"
#include "stdint.h"
long map(long x, long in_min, long in_max, long out_min, long out_max)
{
return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min;
}
int intToString(char* str, int n,int radix) //将整数表达成字符形态
{
int i = 0, j = 0, remain = 0;
int len = 0;
char tmp = 0;
char isNegative = 0;
if (n < 0)
{
isNegative = 1;
n = -n;
}
do
{
remain = n % radix;
if (remain > 9)
str[i] = remain - 10 + 'A'; //为了十六进制,10将表示成A
else
str[i] = remain + '0'; //将整数+'0' = 整数对应的ASCII码
i++;
} while (n /= radix);
if (isNegative == 1)
str[i++] = '-';
str[i] = '\0';
len = i;
for (i--, j = 0; j <= i; j++, i--) //25%10 = 5,25/10 = 2,2%10 = 2,2/10 = 0,所以str中结果是倒置的,翻转一下
{
tmp = str[j];
str[j] = str[i];
str[i] = tmp;
}
return len;
}
const uint32_t POW_10[] = {
1, 10,100, 1000, 10000, 100000, 1000000, 10000000,
100000000, 1000000000
};
int my_vsprintf(char *buf, const char *fmt, my_va_list args)
{
char* p;
my_va_list p_next_arg = args;
uint8_t bit_width[2] = {0, 6};
uint8_t bit_sel = 0;
for (p=buf; *fmt; fmt++)
{
if (*fmt != '%')
{
*p++ = *fmt;
continue;
}
bit_width[0] = 0;
bit_width[1] = 6;
bit_sel = 0;
repeat:
fmt++;
if (*fmt >= '0' && *fmt <= '9' && bit_sel < 2)
{
bit_width[bit_sel] = *fmt - '0';
goto repeat;
}
switch (*fmt)
{
case 'd': //十进制整数
{
int n = my_va_arg(p_next_arg, int);
p += intToString(p, n, 10);
break;
}
case 'x': //十六进制整数
{
int n = my_va_arg(p_next_arg, int);
p += intToString(p, n, 16);
break;
}
case 'f': //浮点数
{
if((unsigned long)p_next_arg & 0x7) //可变参 浮点数默认是double类型 保证内存8字节对齐
{
p_next_arg = (my_va_list)((unsigned long)p_next_arg + 0x7);
p_next_arg = (my_va_list)((unsigned long)p_next_arg & 0xFFFFFFF8);
}
double f = my_va_arg(p_next_arg, double); //%f,输出浮点数
int n = (int)f;
p += intToString(p, n, 10);
*p++ = '.';
double d = ABS(f - n) + 0.5/MIN(1000000, POW_10[bit_width[1]]);
for(int i=0; i < MIN(6, bit_width[1]); i++)
{
d *= 10;
*p++ = (((int)d) % 10) + '0';
}
break;
}
case 'c': //单个 ASCII 字符
{
*p++ = my_va_arg(p_next_arg, int);
break;
}
case 's': //字符串
{
char *str = my_va_arg(p_next_arg, char *);
for (; *str != 0; )
{
*p++ = *str++;
}
break;
}
case '%': //
{
*p++ = '%';
break;
}
case '.':
{
bit_sel++;
goto repeat;
}
default:
{
break;
}
}
}
*p++ = 0;
return (p - buf);
}
void my_sprintf(char *buf, const char *fmt, ...)
{
my_va_list ap;
my_va_start(ap, fmt);
my_vsprintf(buf, fmt, ap);
my_va_end(ap);
}
|
C
|
#include <stdio.h>
#include <inttypes.h>
#include <ctype.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
#include <unistd.h>
#include <fcntl.h>
#include "../include/libfts.h"
#define TRUE 1
#define FALSE 0
#define DEBUG FALSE
#define FT_DEBUG(in_context, ...) \
do { \
if (DEBUG == TRUE) { \
(void) printf ("DEBUG:%s:%" PRIu64 ":%s: " in_context "\n", \
__FILE__, (uint64_t)__LINE__, __func__, \
__VA_ARGS__); \
} \
} while (0)
#define TEST_BZERO TRUE
#define TEST_CAT FALSE
#define TEST_IS TRUE
#define TEST_MEM TRUE
#define TEST_PUTS FALSE
#define TEST_STR TRUE
#define TEST_TO TRUE
#define READ_ENTRY TRUE
#define SCAN_MIN (-100)
#define SCAN_MAX (+300)
#define STRING "Ceci est une chaine a tester..."
#define STRING_LEN (int)(strlen(STRING))
#define STRINGL "Ceci est aussi une chaine a tester... Sauf qu'elle est bien plus longue que la premiere, vraiment... Je ne sais pas trop pourquoi, mais il doit y avoir une raison... Je la trouverai peut etre qui sais... Avec le temps..."
#define STRINGL_LEN (int)(strlen(STRINGL))
#define TAB_LEN 100
char *string = NULL;
static void handle_segv(int sig)
{
(void)sig;
if (DEBUG)
printf ("\033[38;5;2m%s : Segmentation fault\033[0m\033[0m\n", string);
signal(SIGSEGV, SIG_DFL);
}
static void test_bzero_crash(void)
{
pid_t child;
int status;
signal(SIGSEGV, &handle_segv);
if ((child = fork()) == -1)
return ;
if (child == 0)
{
string = "UNIX";
bzero(NULL, 10);
if (DEBUG)
printf ("\033[38;5;1m%s : La fonction n'a pas crash\033[0m\033[0m\n", string);
exit(1);
}
waitpid(child, &status, 0);
signal(SIGSEGV, &handle_segv);
if ((child = fork()) == -1)
return ;
if (child == 0)
{
string = "FT ";
ft_bzero(NULL, 10);
if (DEBUG)
printf ("\033[38;5;1m%s : La fonction n'a pas crash\033[0m\033[0m\n", string);
exit(1);
}
waitpid(child, &status, 0);
}
static int test_bzero(void)
{
char *s1;
char *s2;
s1 = strdup(STRING);
s2 = strdup(STRING);
bzero(s1 + 10, 5);
ft_bzero(s2 + 10, 5);
if (memcmp(s1, s2, STRING_LEN) != 0)
{
FT_DEBUG("UNIX {%.*s}", TAB_LEN, s1);
FT_DEBUG("FT {%.*s}", TAB_LEN, s2);
return (FALSE);
}
free(s1);
free(s2);
test_bzero_crash();
return (TRUE);
}
static int test_cat(void)
{
int fd;
printf("\033[38;5;214m*** Verification visuelle ***\033[0m\033[0m\n");
printf("\033[38;5;69m=== TEST 1 ===\033[0m\033[0m\n(fd = -1)\n");
fd = -1;
ft_cat(fd);
printf("\n\033[38;5;69m=== TEST 2 ===\033[0m\033[0m\n(fd = 42)\n");
fd = 42;
ft_cat(fd);
printf("\n\033[38;5;69m=== TEST 3 ===\033[0m\033[0m\n(fd = open(\"./Makefile\", O_RDONLY))\n");
fd = open("./Makefile", O_RDONLY);
ft_cat(fd);
if (READ_ENTRY == TRUE)
{
printf("\n\033[38;5;69m=== TEST 4 ===\033[0m\033[0m\n(fd = 0)\n");
fd = 0;
ft_cat(fd);
}
printf("\033[38;5;2m*** Fin de Verification visuelle ***\033[0m\033[0m\n");
return (TRUE);
}
static int test_is(void)
{
for (int n = SCAN_MIN ; n < SCAN_MAX ; ++ n)
if (ft_isalnum(n) != isalnum(n))
return (FALSE);
for (int n = SCAN_MIN ; n < SCAN_MAX ; ++ n)
if (ft_isalpha(n) != isalpha(n))
return (FALSE);
for (int n = SCAN_MIN ; n < SCAN_MAX ; ++ n)
if (ft_isascii(n) != isascii(n))
return (FALSE);
for (int n = SCAN_MIN ; n < SCAN_MAX ; ++ n)
if (ft_isdigit(n) != isdigit(n))
return (FALSE);
for (int n = SCAN_MIN ; n < SCAN_MAX ; ++ n)
if (ft_islower(n) != islower(n))
return (FALSE);
for (int n = SCAN_MIN ; n < SCAN_MAX ; ++ n)
if (ft_isprint(n) != isprint(n))
return (FALSE);
for (int n = SCAN_MIN ; n < SCAN_MAX ; ++ n)
if (ft_isupper(n) != isupper(n))
return (FALSE);
return (TRUE);
}
static void test_mem_crash(void)
{
pid_t child;
int status;
signal(SIGSEGV, &handle_segv);
if ((child = fork()) == -1)
return ;
if (child == 0)
{
string = "UNIX";
memset(NULL, 'A', 10);
if (DEBUG)
printf ("\033[38;5;1m%s : La fonction n'a pas crash\033[0m\033[0m\n", string);
exit(1);
}
waitpid(child, &status, 0);
signal(SIGSEGV, &handle_segv);
if ((child = fork()) == -1)
return ;
if (child == 0)
{
string = "FT ";
ft_memset(NULL, 'A', 10);
if (DEBUG)
printf ("\033[38;5;1m%s : La fonction n'a pas crash\033[0m\033[0m\n", string);
exit(1);
}
waitpid(child, &status, 0);
signal(SIGSEGV, &handle_segv);
if ((child = fork()) == -1)
return ;
if (child == 0)
{
string = "UNIX";
memcpy(NULL, STRING, STRING_LEN);
if (DEBUG)
printf ("\033[38;5;1m%s : La fonction n'a pas crash\033[0m\033[0m\n", string);
exit(1);
}
waitpid(child, &status, 0);
signal(SIGSEGV, &handle_segv);
if ((child = fork()) == -1)
return ;
if (child == 0)
{
string = "FT ";
ft_memcpy(NULL, STRING, STRING_LEN);
if (DEBUG)
printf ("\033[38;5;1m%s : La fonction n'a pas crash\033[0m\033[0m\n", string);
exit(1);
}
waitpid(child, &status, 0);
signal(SIGSEGV, &handle_segv);
if ((child = fork()) == -1)
return ;
if (child == 0)
{
string = "UNIX";
memcpy(STRING, NULL, STRING_LEN);
if (DEBUG)
printf ("\033[38;5;1m%s : La fonction n'a pas crash\033[0m\033[0m\n", string);
exit(1);
}
waitpid(child, &status, 0);
signal(SIGSEGV, &handle_segv);
if ((child = fork()) == -1)
return ;
if (child == 0)
{
string = "FT ";
ft_memcpy(STRING, NULL, STRING_LEN);
if (DEBUG)
printf ("\033[38;5;1m%s : La fonction n'a pas crash\033[0m\033[0m\n", string);
exit(1);
}
waitpid(child, &status, 0);
}
static int test_mem(void)
{
char s1[TAB_LEN];
char s2[TAB_LEN];
int d1;
int d2;
bzero(s1, TAB_LEN);
bzero(s2, TAB_LEN);
memset(s1, 'A', TAB_LEN / 3);
ft_memset(s2, 'A', TAB_LEN / 3);
if (memcmp(s1, s2, TAB_LEN) != 0)
{
FT_DEBUG("UNIX {%.*s}", TAB_LEN, s1);
FT_DEBUG("FT {%.*s}", TAB_LEN, s2);
return (FALSE);
}
memset(s1 + 13, '0', TAB_LEN / 5);
ft_memset(s2 + 13, '0', TAB_LEN / 5);
if (memcmp(s1, s2, TAB_LEN) != 0)
{
FT_DEBUG("UNIX {%.*s}", TAB_LEN, s1);
FT_DEBUG("FT {%.*s}", TAB_LEN, s2);
return (FALSE);
}
memcpy(s1, STRING, STRING_LEN - 7);
ft_memcpy(s2, STRING, STRING_LEN - 7);
if (memcmp(s1, s2, TAB_LEN) != 0)
{
FT_DEBUG("UNIX {%.*s}", TAB_LEN, s1);
FT_DEBUG("FT {%.*s}", TAB_LEN, s2);
return (FALSE);
}
d1 = memcmp(STRING, STRING, STRING_LEN - 1);
d2 = ft_memcmp(STRING, STRING, STRING_LEN - 1);
if (d1 != d2)
{
FT_DEBUG("UNIX %d", d1);
FT_DEBUG("FT %d", d2);
return (FALSE);
}
d1 = memcmp(STRING, STRINGL, STRINGL_LEN - 1);
d2 = ft_memcmp(STRING, STRINGL, STRINGL_LEN - 1);
if (d1 != d2)
{
FT_DEBUG("UNIX %d", d1);
FT_DEBUG("FT %d", d2);
return (FALSE);
}
test_mem_crash();
return (TRUE);
}
static int test_puts(void)
{
char *str;
printf("\033[38;5;214m*** Verification visuelle ***\033[0m\033[0m\n");
str = strdup(STRINGL);
printf("\033[38;5;69m*** TEST PUTS ***\033[0m\033[0m\n");
printf("\033[38;5;69m=== TEST 1 ===\033[0m\033[0m\n");
puts(str);
ft_puts(str);
memset(str + 25, '\0', 2);
printf("\n\033[38;5;69m=== TEST 2 ===\033[0m\033[0m\n");
puts(str);
ft_puts(str);
printf("\n\033[38;5;69m=== TEST 3 ===\033[0m\033[0m\n");
puts(str + 26);
ft_puts(str + 26);
printf("\n\033[38;5;69m=== TEST 4 ===\033[0m\033[0m\n");
puts(str + 30);
ft_puts(str + 30);
printf("\n\033[38;5;69m=== TEST 5 ===\033[0m\033[0m\n");
puts(NULL);
ft_puts(NULL);
printf("\033[38;5;69m*** TEST PUTSTR ***\033[0m\033[0m\n");
free(str);
str = strdup(STRINGL);
printf("\033[38;5;69m=== TEST 1 ===\033[0m\033[0m\n");
ft_putstr(str);
memset(str + 25, '\0', 2);
printf("\n\033[38;5;69m=== TEST 2 ===\033[0m\033[0m\n");
ft_putstr(str);
printf("\n\033[38;5;69m=== TEST 3 ===\033[0m\033[0m\n");
ft_putstr(str + 26);
printf("\n\033[38;5;69m=== TEST 4 ===\033[0m\033[0m\n");
ft_putstr(str + 30);
printf("\n\033[38;5;69m=== TEST 5 ===\033[0m\033[0m\n");
ft_putstr(NULL);
free(str);
printf("\n\033[38;5;2m*** Fin de Verification visuelle ***\033[0m\033[0m\n");
return (TRUE);
}
static void test_str_crash(void)
{
pid_t child;
int status;
signal(SIGSEGV, &handle_segv);
if ((child = fork()) == -1)
return ;
if (child == 0)
{
string = "UNIX";
strdup(NULL);
if (DEBUG)
printf ("\033[38;5;1m%s : La fonction n'a pas crash\033[0m\033[0m\n", string);
exit(1);
}
waitpid(child, &status, 0);
signal(SIGSEGV, &handle_segv);
if ((child = fork()) == -1)
return ;
if (child == 0)
{
string = "FT ";
ft_strdup(NULL);
if (DEBUG)
printf ("\033[38;5;1m%s : La fonction n'a pas crash\033[0m\033[0m\n", string);
exit(1);
}
waitpid(child, &status, 0);
signal(SIGSEGV, &handle_segv);
if ((child = fork()) == -1)
return ;
if (child == 0)
{
string = "UNIX";
strlen(NULL);
if (DEBUG)
printf ("\033[38;5;1m%s : La fonction n'a pas crash\033[0m\033[0m\n", string);
exit(1);
}
waitpid(child, &status, 0);
signal(SIGSEGV, &handle_segv);
if ((child = fork()) == -1)
return ;
if (child == 0)
{
string = "FT ";
ft_strlen(NULL);
if (DEBUG)
printf ("\033[38;5;1m%s : La fonction n'a pas crash\033[0m\033[0m\n", string);
exit(1);
}
waitpid(child, &status, 0);
signal(SIGSEGV, &handle_segv);
if ((child = fork()) == -1)
return ;
if (child == 0)
{
string = "UNIX";
strcat(NULL, STRING);
if (DEBUG)
printf ("\033[38;5;1m%s : La fonction n'a pas crash\033[0m\033[0m\n", string);
exit(1);
}
waitpid(child, &status, 0);
signal(SIGSEGV, &handle_segv);
if ((child = fork()) == -1)
return ;
if (child == 0)
{
string = "FT ";
ft_strcat(NULL, STRING);
if (DEBUG)
printf ("\033[38;5;1m%s : La fonction n'a pas crash\033[0m\033[0m\n", string);
exit(1);
}
waitpid(child, &status, 0);
signal(SIGSEGV, &handle_segv);
if ((child = fork()) == -1)
return ;
if (child == 0)
{
string = "UNIX";
strcat(STRING, NULL);
if (DEBUG)
printf ("\033[38;5;1m%s : La fonction n'a pas crash\033[0m\033[0m\n", string);
exit(1);
}
waitpid(child, &status, 0);
signal(SIGSEGV, &handle_segv);
if ((child = fork()) == -1)
return ;
if (child == 0)
{
string = "FT ";
ft_strcat(STRING, NULL);
if (DEBUG)
printf ("\033[38;5;1m%s : La fonction n'a pas crash\033[0m\033[0m\n", string);
exit(1);
}
waitpid(child, &status, 0);
}
static int test_str(void)
{
char *s1;
char *s2;
s1 = strdup(STRINGL);
s2 = ft_strdup(STRINGL);
if (memcmp(s1, s2, STRINGL_LEN) != 0)
{
FT_DEBUG("UNIX {%.*s}", STRINGL_LEN, s1);
FT_DEBUG("FT {%.*s}", STRINGL_LEN, s2);
return (FALSE);
}
if (strlen(s1) != ft_strlen(s1))
{
FT_DEBUG("UNIX [%zu]", strlen(s1));
FT_DEBUG("FT [%zu]", ft_strlen(s1));
return (FALSE);
}
memset(s1 + 20, '\0', 1);
memset(s2 + 20, '\0', 1);
if (strlen(s1) != ft_strlen(s1))
{
FT_DEBUG("UNIX [%zu]", strlen(s1));
FT_DEBUG("FT [%zu]", ft_strlen(s1));
return (FALSE);
}
s1 = strcat(s1, STRING);
s2 = ft_strcat(s2, STRING);
if (memcmp(s1, s2, STRINGL_LEN) != 0)
{
FT_DEBUG("UNIX {%.*s}", STRINGL_LEN, s1);
FT_DEBUG("FT {%.*s}", STRINGL_LEN, s2);
for (int n = 0 ; n < STRINGL_LEN ; ++ n)
{
FT_DEBUG("FUNCTION RETURN %d N %d VALUE {%.*s}", memcmp(s1 + n, s2 + n, STRINGL_LEN - n), n, STRINGL_LEN - n, s1 + n);
FT_DEBUG("FUNCTION RETURN %d N %d VALUE {%.*s}", memcmp(s1 + n, s2 + n, STRINGL_LEN - n), n, STRINGL_LEN - n, s2 + n);
}
return (FALSE);
}
if (strlen(s1) != ft_strlen(s1))
{
FT_DEBUG("UNIX [%zu]", strlen(s1));
FT_DEBUG("FT [%zu]", ft_strlen(s1));
return (FALSE);
}
test_str_crash();
return (TRUE);
}
static int test_to(void)
{
for (int n = SCAN_MIN ; n < SCAN_MAX ; ++ n)
if (ft_tolower(n) != tolower(n))
return (FALSE);
for (int n = SCAN_MIN ; n < SCAN_MAX ; ++ n)
if (ft_toupper(n) != toupper(n))
return (FALSE);
return (TRUE);
}
int main()
{
printf("%s tests de la fonction ft_bzero\n", (!TEST_BZERO) ? "\033[38;5;214m~\033[0m\033[0m" : ((test_bzero() == TRUE) ? "\033[38;5;2m✓\033[0m\033[0m" : "\033[38;5;1m✗\033[0m\033[0m"));
printf("%s tests de la fonction ft_cat\n", (!TEST_CAT) ? "\033[38;5;214m~\033[0m\033[0m" : ((test_cat() == TRUE) ? "\033[38;5;2m✓\033[0m\033[0m" : "\033[38;5;1m✗\033[0m\033[0m"));
printf("%s tests des fonctions ft_is\n", (!TEST_IS) ? "\033[38;5;214m~\033[0m\033[0m" : ((test_is() == TRUE) ? "\033[38;5;2m✓\033[0m\033[0m" : "\033[38;5;1m✗\033[0m\033[0m"));
printf("%s tests des fonctions ft_mem\n", (!TEST_MEM) ? "\033[38;5;214m~\033[0m\033[0m" : ((test_mem() == TRUE) ? "\033[38;5;2m✓\033[0m\033[0m" : "\033[38;5;1m✗\033[0m\033[0m"));
printf("%s tests de la fonction ft_puts\n", (!TEST_PUTS) ? "\033[38;5;214m~\033[0m\033[0m" : ((test_puts() == TRUE) ? "\033[38;5;2m✓\033[0m\033[0m" : "\033[38;5;1m✗\033[0m\033[0m"));
printf("%s tests des fonctions ft_str\n", (!TEST_STR) ? "\033[38;5;214m~\033[0m\033[0m" : ((test_str() == TRUE) ? "\033[38;5;2m✓\033[0m\033[0m" : "\033[38;5;1m✗\033[0m\033[0m"));
printf("%s tests des fonctions ft_to\n", (!TEST_TO) ? "\033[38;5;214m~\033[0m\033[0m" : ((test_to() == TRUE) ? "\033[38;5;2m✓\033[0m\033[0m" : "\033[38;5;1m✗\033[0m\033[0m"));
return (0);
}
|
C
|
#ifndef CBUF_H
#define CBUF_H
#define CBUF_SIZE 1024
typedef struct cbuf {
int size;
char data[CBUF_SIZE];
int start;
int end;
} cbuf;
void cbuf_new(cbuf *buf);
void cbuf_push(cbuf *buf, char c);
char cbuf_pop(cbuf *buf);
char cbuf_peek(cbuf *buf);
void cbuf_unpop(cbuf *buf, char c);
char cbuf_unpush(cbuf *buf);
int cbuf_empty(cbuf *buf);
int cbuf_read(cbuf *buf, char *out, int length);
int cbuf_write(cbuf *buf, char *data, int length);
void cbuf_flush(cbuf *buf);
#endif
|
C
|
#include "holberton.h"
/**
* _strstr - locate a substring
* @haystack: string to search
* @needle: substring to search for
*
* Description: Find the first occurrence of the substring needle in the
* string haystack. The terminating null bytes ('\0') are not compared.
*
* Return: a pointer to the beginning of the located substring, or
* NULL if the substring is not found.
*/
char *_strstr(char *haystack, char *needle)
{
char *h_pos, *n_pos;
do {
h_pos = haystack;
n_pos = needle;
do {
if (!*n_pos)
return (haystack);
if (!*h_pos)
return (NULL);
} while (*h_pos++ == *n_pos++);
++haystack;
} while (*haystack);
return (NULL);
}
|
C
|
//PEPIN Thibaut
//PAXENT Laurent
#include "cesar.h"
int nombre_ligne(char* path)
{
int fd = open(path,O_RDONLY);
int res=0;char c;
while(read(fd,&c,sizeof(char)) != 0)
{
if(c == '\n') res++;
}
close(fd);
return res;
}
instruction* recup_inst(char* nom_fic,int nbr_ligne)
{
int fd = open(nom_fic,O_RDONLY);
int i=0;
char c;
int taille,signe;
instruction* inst = malloc((nbr_ligne)*sizeof(instruction));
for(i=0;i<nbr_ligne;i++)
{
inst[i].decalage = 0;
taille = 0;
signe = 1;
while((read(fd,&c,sizeof(char)) != 0) && (c != ';'))taille++;
inst[i].path = malloc((taille+1)*sizeof(char));
lseek(fd,-(taille+1)*sizeof(char),SEEK_CUR);
read(fd,inst[i].path,taille);
lseek(fd,sizeof(char),SEEK_CUR);
while((read(fd,&c,sizeof(char)) != 0) && (c != ';'))
{
if(c == '-') signe = -1;
else inst[i].decalage = (inst[i].decalage*10) + (c - '0');
}
inst[i].decalage %= ('Z'-'A'+1);
inst[i].decalage *= signe;
read(fd,&(inst[i].sens),sizeof(char));
while((read(fd,&c,sizeof(char)) != 0) && (c != '\n'));
}
close(fd);
return inst;
}
void* decalage_mot(void* argument)
{
arg* a = (arg*)argument;
int i,c,d;
for(i=a->deb;i <= a->fin;i++)
{
c = a->chaine[i];
d = a->decalage;
a->chaine[i] = ((c>='A')&&(c<='Z'))?
((c-'A'+d >= 0)?c+d:c-'A'+d+'Z')
:(((c>='a')&&(c<='z'))?
((c-'a'+d >= 0)?c+d:c-'a'+d+'z')
:c);
}
return NULL;
}
void insertion_debut(thread_liste* liste)
{
thread_elem* d = malloc(sizeof(thread_elem));
d->addr = *liste;
*liste = d;
}
void suppression_debut(thread_liste* liste)
{
thread_elem* d = *liste;
*liste = (*liste)->addr;
free(d);
}
int main(int argc, char** argv)
{
if(argc == 1)exit(0);
int nbr_ligne = nombre_ligne(argv[1]),i,j,reste;
pid_t pid[nbr_ligne];
instruction* inst = recup_inst(argv[1],nbr_ligne);
int pipes[nbr_ligne][2];
char buf[tmax];
for(i=0;i<nbr_ligne;i++)
{
pipe(pipes[i]);
pid[i] = fork();
if(pid[i] == 0) goto fin_boucle;
}
free(inst);
fin_boucle:
if(i == nbr_ligne) //parent
{
for(i=0;i<nbr_ligne;i++)
{
close(pipes[i][1]);
}
for(j=0;j<nbr_ligne;j++)
{
waitpid(pid[j],NULL,0);
while((reste = read(pipes[j][0],buf,tmax)) != 0)
{
write(STDOUT_FILENO,buf,reste);
}
}
for(i=0;i<nbr_ligne;i++)
{
close(pipes[0][1]);
}
}
else //fils
{
for(j=0;j<i;j++)
{
close(pipes[j][1]);
close(pipes[j][0]);
}
close(pipes[i][0]);
int fd = open(inst[i].path,O_RDONLY),taille_chaine = tmax+1, pos = 0, j, k = 0;
while((reste = read(fd,buf,tmax)) != 0)taille_chaine += reste;
char* chaine = malloc(taille_chaine*sizeof(char));
lseek(fd,0,SEEK_SET);
while((reste = read(fd,&chaine[pos],tmax)) != 0)pos += reste;
thread_liste liste = NULL;
for(j=0;j<=pos;j++)
{
if(!(((chaine[j] >= 65)&&(chaine[j] <=90)) || ((chaine[j] >= 97)&&(chaine[j] <=122))))
{
insertion_debut(&liste);
(liste->argument).deb = k;
(liste->argument).fin = j;
(liste->argument).chaine = chaine;
(liste->argument).decalage = inst[i].decalage;
pthread_create(&(liste->tid),NULL,decalage_mot,&(liste->argument));
k=j+1;
}
}
while(liste != NULL)
{
pthread_join(liste->tid,NULL);
suppression_debut(&liste);
}
if(inst[i].sens == 'c')
{
char n_path[strlen(inst[i].path) + 7];
strcpy(n_path,inst[i].path);
strcpy(&n_path[strlen(inst[i].path)],"_cypher");
int fd2 = open(n_path,O_CREAT|O_WRONLY,0700);
write(fd2,chaine,strlen(chaine)*sizeof(char));
close(fd2);
//"le fichier : " = 13
//" a bien ete crypte.\n" = 20
// total = 33 caractères
char msg[strlen(inst[i].path)+33];
strcpy(msg,"le fichier : ");
strcat(msg,inst[i].path);
strcat(msg," a bien ete crypte.\n");
write(pipes[i][1],msg,strlen(msg));
}
else if(inst[i].sens == 'd')
{
write(pipes[i][1],chaine,strlen(chaine)+1);
}
free(chaine);
free(inst);
close(fd);
close(pipes[i][1]);
}
exit(0);
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_graph_shortestpath.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: bduron <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2017/03/07 18:01:03 by bduron #+# #+# */
/* Updated: 2017/03/09 18:03:09 by bduron ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
void find_path_rec(int start, int end, int *parents)
{
if ((start == end) || (end == -1))
ft_printf("\n%d", start);
else
{
find_path_rec(start, parents[end], parents);
ft_printf(" %d", end);
}
}
t_list *find_path_bfs(int start, int end, int *parents)
{
int v;
t_list *stack;
if (!parents || parents[end] == -1)
return (NULL);
v = end;
stack = ft_lstnew(&v, sizeof(int));
while (parents[v] != start)
{
v = parents[v];
ft_lstpush(&stack, ft_lstnew(&v, sizeof(int)));
}
ft_lstpush(&stack, ft_lstnew(&start, sizeof(int)));
return (stack);
}
|
C
|
#include <string.h>
#include <stdlib.h>
#include "memory.h"
#include "parse.h"
#include "errors.h"
// Operators functions
int isAllowedAfter(const char *op)
{
if (
strcmp(op, "-o") == 0
|| strcmp(op, "-a") == 0
|| ((op[0] != '-' && op[0] != '!')
&& (op[0] != '-' && op[0] != '('))
)
return 0;
return 1;
}
struct token parse_and(char *argv[], int *cursor)
{
if (*cursor == 1)
{
error_exit(
INV_ARG,
"you have used a binary operator '-a' with nothing before it."
);
}
if (argv[*cursor + 1] == NULL || !isAllowedAfter(argv[*cursor + 1]))
error_exit(PATH, argv[*cursor]);
struct token token = { AND, OPERATOR, NULL };
return token;
}
struct token parse_or(char *argv[], int *cursor)
{
if (*cursor == 1)
{
error_exit(
INV_ARG,
"you have used a binary operator '-o' with nothing before it."
);
}
if (argv[*cursor + 1] == NULL || !isAllowedAfter(argv[*cursor + 1]))
error_exit(PATH, argv[*cursor]);
struct token token = { OR, OPERATOR, NULL };
return token;
}
struct token parse_oparen(char *argv[], int *cursor)
{
if (argv[*cursor + 1][0] == ')' || !isAllowedAfter(argv[*cursor + 1]))
error_exit(MISS_ARG, "(");
struct token token = { PAREN_O, OPERATOR, NULL };
return token;
}
struct token parse_cparen(char *argv[], int *cursor)
{
if (argv[*cursor - 1][0] == '(')
error_exit(MISS_ARG, ")");
struct token token = { PAREN_C, OPERATOR, NULL };
return token;
}
struct token parse_not(char *argv[], int *cursor)
{
if (argv[*cursor + 1] == NULL)
error_exit(MISS_ARG, argv[*cursor]);
struct token token = { NOT, OPERATOR, NULL };
return token;
}
|
C
|
#ifdef CS333_P2
#include "types.h"
#include "user.h"
//Allows user interaction with the system calls that
//both set and get UIDs and GIDs
int
main(void)
{
uint ppid;
int validTest = 32768;
int invalidTest = -10;
//UID testing
printf(2, "\n\nreturn code for setuid(%d) is: %d\n",validTest, setuid(validTest));
if(setuid(validTest) == -1)
{
printf(2, "setuid(%d) failed: Out of bounds\n", validTest);
}
else
{
printf(2, "setuid(%d) successful!, UID is now: %d\n", validTest, getuid());
}
printf(2, "return code for setuid(%d) is: %d\n",invalidTest, setuid(invalidTest));
if(setuid(invalidTest) == -1)
{
printf(2, "setuid(%d) failed: Out of bounds\n", invalidTest);
}
else
{
printf(2, "setuid(%d) successful!, UID is now: %d\n", invalidTest, getuid());
}
//GID testing
printf(2, "return code for setgid(%d) is: %d\n",validTest, setgid(validTest));
if(setgid(validTest) == -1)
{
printf(2, "setgid(%d) failed: Out of bounds\n", validTest);
}
else
{
printf(2, "setgid(%d) successful!, GID is now: %d\n", validTest, getgid());
}
printf(2, "return code for setgid(%d) is: %d\n",invalidTest, setgid(invalidTest));
if(setgid(invalidTest) == -1)
{
printf(2, "setgid(%d) failed: Out of bounds\n", invalidTest);
}
else
{
printf(2, "setgid(%d) successful!, GID is now: %d\n", invalidTest, getgid());
}
//PPID testing
ppid = getppid();
printf(2, "My parent process is: %d\n", ppid);
printf(2, "Done!\n");
exit();
}
#endif
|
C
|
#include "stdio.h"
#include "math.h"
#define N 501
#define max(a,b) ((a) < (b) ? (b) : (a))
#define min(a,b) ((a) < (b) ? (a) : (b))
int n, r[N];
double x[N];
int main()
{
int i, j;
while (scanf (" %d", &n) != EOF){
for (i = 0; i < n; i++) scanf (" %d", r + i);
for (i = 0; i < n; i++){
x[i] = r[i];
for (j = 0; j < i; j++)
x[i] = max (x[i], x[j] + 2 * sqrt (r[i] * r[j]));
}
double ans = 0.0;
for (i = 0; i < n; i++)
ans = max (ans, x[i] + r[i]);
printf ("%.20lf\n", ans);
}
}
|
C
|
//8.4
#include <stdio.h>
#include <locale.h>
#include <math.h>
#include <stdlib.h>
int main()
{
setlocale(LC_ALL, "Rus");
int A,t;
printf("Введите двузначное число\n");
scanf("%d",&A);
t=A%10;
A=A/10;
printf("%d",t*10+A);
return 0;
}
|
C
|
/*
** key_shift.c for in /home/januar_m/delivery/PSU/PSU_2016_42sh
**
** Made by Martin Januario
** Login <[email protected]>
**
** Started on Thu May 18 19:44:16 2017 Martin Januario
** Last update Fri May 19 14:53:11 2017 Martin Januario
*/
#include <curses.h>
#include <term.h>
#include "edit.h"
static void move_cursor(t_key *keys, char *str, int i)
{
printf(tgetstr(str, NULL));
keys->idx += i;
fflush(stdout);
}
void key_sleft_(t_key *keys, __attribute__ ((unused)) char *str,
char **line)
{
unsigned int check;
unsigned int save;
unsigned int cpt;
check = 0;
save = 0;
cpt = 0;
while (*line && keys->idx > 0)
{
if ((*line)[keys->idx] != ' ' && cpt != 0)
{
if (save == cpt)
save = 0;
check += 1;
}
else
save += 1;
if (check >= 1 && save >= 1)
{
move_cursor(keys, "nd", 1);
return ;
}
move_cursor(keys, "le", -1);
cpt++;
}
}
void key_sright_(t_key *keys, __attribute__ ((unused)) char *str,
char **line)
{
unsigned int check;
unsigned int save;
unsigned int cpt;
check = 0;
save = 0;
cpt = 0;
while (*line && (*line)[keys->idx] != '\0')
{
if ((*line)[keys->idx] != ' ' && cpt != 0)
{
if (save == cpt)
save = 0;
check += 1;
}
else
save += 1;
if (check >= 1 && save >= 1)
return ;
printf(tgetstr("nd", NULL));
fflush(stdout);
keys->idx++;
cpt++;
}
}
|
C
|
/*
The header for robust i/o functions
The functions are analogous to the ones from the book "Computer Systems: A Programmer's Perspective"
by Randal Bryant and David O'Hallaron
*/
#ifndef ROBUST_IO_H
#define ROBUST_IO_H
#include <stdio.h>
#define RIO_BUFSIZE 8192
typedef struct
{
int rioFd; //Descriptor for this internal buffer
int rioCnt; //Unread bytes in internal buffer
char *rioBufPtr; //Next unread byte in internal buffer
char rioBuf[RIO_BUFSIZE]; //Internal buffer
} rioT;
//returns number of bytes transferred, 0 on EOF, −1 on error
ssize_t rioReadn(int fd, void *userbuf, size_t n);
//returns number of bytes transferred, 0 on EOF, −1 on error
ssize_t rioWriten(int fd, void *userbuf, size_t n);
//returns number of bytes transferred, 0 on EOF, −1 on error
void rioReadInitb(rioT *rp, int fd);
//returns number of bytes transferred, 0 on EOF, −1 on error
ssize_t rioReadLineb(rioT *rp, void *usrbuf, size_t maxlen);
//returns number of bytes transferred, 0 on EOF, −1 on error
ssize_t rioReadnb(rioT *rp, void *usrbuf, size_t n);
//returns number of bytes transferred, 0 on EOF, −1 on error
static ssize_t rioRead(rioT *rp, char *usrbuf, size_t n);
#endif
|
C
|
#include <stdlib.h>
#include <stdio.h>
typedef struct celula {
int dado;
struct celula *prox;
} celula;
celula *enfileira(celula *f, int x){
celula *novo = malloc(sizeof(celula));
if(novo == NULL)
return NULL;
else{
novo->prox = f->prox;
f->prox = novo;
f->dado = x;
return novo;
}
}
int main (){
celula *umOuMenosUm = malloc(sizeof(celula));
int nEventos;
scanf("%d", &nEventos);
for (int i = 0; i <= nEventos; i++)
{
int num;
scanf("%d", &num);
enfileira(umOuMenosUm, num);
}
while ()
{
/* code */
}
return 0;
}
|
C
|
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/types.h>
int main ( int argc, char * argv[] )
{
pid_t pid;
int i=0;
pid = fork();
if ( pid > 0 ) {
printf("PARENT PROCESS %d\n",getpid());
printf("CHILD PROCESS IS EXITED \n");
//wait(NULL);
}
else if ( pid == 0 )
{
printf("CHILD PROCESS %d\n",getpid());
execvp(argv[0],argv);
printf("CHILD PROCESS AFTER EXECV");
}
else
printf("FORK IS FAILED\n");
printf("this is main process");
getchar();
return 0;
}
|
C
|
#include <stdio.h>
#include <errno.h>
#if 0
void perror(const char *s);
#endif // 0
int main(int argc, char *argv[]) {
errno = 1;
perror("errno = 1");
errno = EAGAIN;
perror("errno = EAGAIN");
return 0;
}
|
C
|
#include <stdio.h>
//Escreva um algoritmo que leia um conjunto de 100 nmeros inteiros positivos e determine o maior deles.
int main(){
int n1=0, nf=0, i;
for (i=0;i<100; i++){
printf("Digite um numero: ");
scanf("%d", &n1);
if(nf<n1){
nf=n1;
}
}
printf("O maior numero eh: %d", nf);
return 0;
}
|
C
|
#ifndef __F1_HELPER_H__
#define __F1_HELPER_H__
#define _BSD_SOURCE
#define _XOPEN_SOURCE 500
#include <stdio.h>
#include <sys/ioctl.h>
#include <unistd.h>
#include <string.h>
#include <time.h>
#include <stdlib.h>
#include <bsg_manycore_driver.h>
#include <bsg_manycore_loader.h>
#include <bsg_manycore_mem.h>
#include <bsg_manycore_errno.h>
#include <bsg_manycore_elf.h>
typedef enum transfer_type {
deviceToHost = 0,
hostToDevice
} transfer_type_t;
void printReqPkt(hb_mc_request_packet_t *pkt) {
uint32_t addr = hb_mc_request_packet_get_addr(pkt);
uint32_t data = hb_mc_request_packet_get_data(pkt);
uint32_t x_src = hb_mc_request_packet_get_x_src(pkt);
uint32_t y_src = hb_mc_request_packet_get_y_src(pkt);
uint32_t x_dst = hb_mc_request_packet_get_x_dst(pkt);
uint32_t y_dst = hb_mc_request_packet_get_y_dst(pkt);
uint32_t op = hb_mc_request_packet_get_op(pkt);
printf("Manycore request packet: Address 0x%x at coordinates (0x%x, 0x%x) from (0x%x, 0x%x). Operation: 0x%x, Data: 0x%x\n", addr, x_dst, y_dst, x_src, y_src, op, data);
}
void printRespPkt(hb_mc_response_packet_t *pkt) {
uint32_t data = hb_mc_response_packet_get_data(pkt);
uint32_t load_id = hb_mc_response_packet_get_load_id(pkt);
uint32_t x_dst = hb_mc_response_packet_get_x_dst(pkt);
uint32_t y_dst = hb_mc_response_packet_get_y_dst(pkt);
uint32_t op = hb_mc_response_packet_get_op(pkt);
printf("Manycore response packet: To coordinates (0x%x, 0x%x). Operation: 0x%x, Load_id: 0x%x, Data: 0x%x\n", x_dst, y_dst, op, load_id, data);
}
// emulate cudaMemcpy semantics
// userPtr should already be allocated
// on hammerblade virtual and physical addresses are the same (i.e. only physical addresses)
void hammaMemcpy(uint8_t fd, uint32_t x, uint32_t y, uint32_t virtualAddr, void *userPtr, uint32_t numBytes, transfer_type_t transferType) {
// calculate the number of packets we're going to need. each packets sends 4 bytes
int numPackets = numBytes / 4;
if (transferType == deviceToHost) {
hb_mc_response_packet_t *buf = (hb_mc_response_packet_t*)malloc(sizeof(hb_mc_response_packet_t) * numPackets);
// context, ptr to write to, x, y, virtual address, number of words (how many uint32 / 4 bytes)
// for some reason need to shift the address by 2 ( / 4. To reflect that fact that it's word addressable not byte addressable!
int read = hb_mc_copy_from_epa(fd, buf, x, y, virtualAddr >> 2, numPackets);
if (read == HB_MC_SUCCESS) {
// we're going to collect all of the data in a uint32_t buffer and then cast it to void
// this should be find b/c every type is <=32-bits.
// If over 64 bits this could result in flipping the first and second halves
// store data from the packets in the provided memory
// the data is in bytes [9,6].
for (int i = 0; i < numPackets; i++) {
// printRespPkt(&(buf[i]));
uint32_t data = hb_mc_response_packet_get_data(&(buf[i]));
// put the data into the container
// printf("data: %x\n", data);
((uint32_t*)userPtr)[i] = data;
}
}
else {
printf("read from tile failed %x.\n", virtualAddr);
assert(0);
}
// free memory
free(buf);
}
else if (transferType == hostToDevice) {
uint32_t *data = (uint32_t *) calloc(numPackets, sizeof(uint32_t));
for (int i = 0; i < numPackets; i++) {
data[i] = ((uint32_t*)userPtr)[i];
//printf("sent packet %d: 0x%x\n", i, data[i]);
}
// store data in tile
int write = hb_mc_copy_to_epa(fd, x, y, virtualAddr >> 2, data, numPackets);
free(data);
if (write != HB_MC_SUCCESS) {
printf("writing data to tile (%d, %d)'s DMEM failed.\n", x, y);
assert(0);
}
}
else {
assert(0);
}
}
// **********************************************************************
// cherry-pick unexposed methods from bsg_manycore_mem.cpp
// **********************************************************************
/*!
* returns HB_MC_SUCCESS if eva is a DRAM address and HB_MC_FAIL if not.
*/
int hb_mc_eva_is_dram (eva_t eva) {
if (hb_mc_get_bits(eva, 31, 1) == 0x1)
return HB_MC_SUCCESS;
else
return HB_MC_FAIL;
}
/*
* returns x coordinate of a DRAM address.
*/
uint32_t hb_mc_dram_get_x (eva_t eva) {
return hb_mc_get_bits(eva, 29, 2); /* TODO: hardcoded */
}
/*
* returns y coordinate of a DRAM address.
*/
uint32_t hb_mc_dram_get_y (eva_t eva) {
return hb_mc_get_manycore_dimension_y() + 1;
}
// memcpy to/from given symbol name
void hammaSymbolMemcpy(uint8_t fd, uint32_t x, uint32_t y, const char *exeName, const char *symName, void *userPtr, uint32_t numBytes, transfer_type_t transferType) {
// get the device address of relevant variables
eva_t addr = 0;
symbol_to_eva(exeName, symName, &addr);
printf("Memop with addr: 0x%x\n", addr);
// check if this is a dram address. if so, we need to mod the x,y coords
if (hb_mc_eva_is_dram(addr) == HB_MC_SUCCESS) {
x = hb_mc_dram_get_x(addr);
y = hb_mc_dram_get_y(addr);
}
hammaMemcpy(fd, x, y, addr, userPtr, numBytes, transferType);
}
void waitForKernel(uint8_t fd, int numTiles) {
for (int i = 0; i < numTiles; i++) {
hb_mc_request_packet_t manycore_finish;
hb_mc_fifo_receive(fd, 1, (hb_mc_packet_t *) &manycore_finish);
printReqPkt(&manycore_finish);
}
}
// load kernels onto multiple cores on the hammerblade in (but don't run)
void hammaLoadMultiple(uint8_t fd, char *manycore_program, int x1, int y1, int x2, int y2) {
int origin_x = x1;
int origin_y = y1;
for (uint8_t y = y1; y < y2; y++) {
for (uint8_t x = x1; x < x2; x++) {
if (y == 0) {
printf("trying to load kernel to io core (%d, %d)\n", x, y);
assert(0);
}
// start kernel with origin
hb_mc_tile_freeze(fd, x, y);
hb_mc_tile_set_group_origin(fd, x, y, origin_x, origin_y);
hb_mc_load_binary(fd, manycore_program, &x, &y, 1);
}
}
}
// run all of the current kernels of multiple tiles
void hammaRunMultiple(uint8_t fd, int x1, int y1, int x2, int y2) {
// start all of the tiles
for (int y = y1; y < y2; y++) {
for (int x = x1; x < x2; x++) {
hb_mc_tile_unfreeze(fd, x, y);
}
}
int num_tiles = (x2 - x1) * (y2 - y1);
// recv a packet from each tile marking their completion
waitForKernel(fd, num_tiles);
}
// initalize the hammerblade instance
void hammaInit(uint8_t *fd) {
if (hb_mc_fifo_init(fd) != HB_MC_SUCCESS) {
printf("failed to initialize host.\n");
assert(0);
}
}
#endif
|
C
|
#include <stdlib.h>
#include <stdio.h>
#include "../__RVC_IsNull_Monitor.h"
int main(void) {
int* v[5], i, sum = 0;
fprintf(stdout, "Test 2\n");
fprintf(stderr, "Test 2\n");
v[0] = (int *)malloc(sizeof(int)); *(v[0]) = 1;
v[1] = (int *)malloc(sizeof(int)); *(v[1]) = 2;
v[2] = NULL;
v[3] = (int *)malloc(sizeof(int)); *(v[3]) = 4;
v[4] = (int *)malloc(sizeof(int)); *(v[4]) = 8;
for (i = 0; i < 5; i++) {
if (v[i]) {
__RVC_IsNull_isNull();
__RVC_IsNull_deref();
sum += *(v[i]);
} else {
__RVC_IsNull_isNull();
}
}
printf("sum: %d\n", sum);
}
|
C
|
// chatClient.c
// the main function of your chatServer
#include <stdio.h>
#include <signal.h>
#include <errno.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include "Socket.h"
#include "Thread.h"
#include "Packet.h"
#include "socketStruct.h"
const int MAX_MESSAGE = 1024;
// The function of the chatClient is to read input from standard
// input, typically the keyboard and write it to the server
// it connected to. At the same time the application is reading from
// the connection to the server and writes whatever is read from the
// network to standard output.
// The passed in parameter is the result of createClientSocket.
void *networkReader (void *param)
{
// Add code and declarations here to read information the socket
// connected to the server and write it to standard output. Upon
// getting and EOF from the server terminate the application.
struct Socket *soc = (struct Socket *) param;
char message_receive[MAX_MESSAGE];
int bytes_received = 0;
for ( ; ; )
{
message_receive [0] = '\0';
if (soc && (soc->sType == ACTIVE_SOCKET))
{
bytes_received = socketRecv (soc, message_receive, MAX_MESSAGE);
if (bytes_received < 0)
{
bytes_received = socketClose (soc);
if (bytes_received <= 0)
{
printf ("Client: close error.\n");
return (void*) bytes_received;
} // if statement
printf ("Client: receive error.\n");
return (void*) bytes_received;
} // if statement
if (bytes_received == 0)
{
printf ("Client: Server shut down!\n");
return (void*) -1;
} // if statement
message_receive[bytes_received] = '\0';
printf ("^Message: %s\n", message_receive);
} // if statement
else
{
printf ("Client: connection failed\n");
} // else statement
} // for loop
free (soc);
soc = NULL;
return NULL;
} // networkReader
// This program takes 3 command line arguments in the following order:
// 1) An string that this client is to be known by (this is
// not used for this part of the assignment)
// 2) The machine the server is on. This name can be in DNS
// or dotted IP (i.e. 127.8.9.131) format.
// 3) The port the server is running on
// A sample command line might look like these:
// chatClient CS213 remote.ugrad.cs.ubc.ca 3678
// chatClient DA 127.0.0.1 4589
//
int main (int argc, char *argv[])
{
// handle SIGPIPE
if (signal (SIGPIPE, SIG_IGN) == SIG_ERR)
{
perror ("sigHandle, SIGPIPE cannot be handled.");
exit (-1);
} // if statement
printf ("SIGPIPE set to ignore.%d\n", SIGPIPE);
// Create a client socket connected to the server. Add the code and
// declarations below here.
char message_send[MAX_MESSAGE];
char *hostname;
int port;
int bytes_sent;
if (argc != 3)
{
printf ("Usage: testClient <hostname> <port>");
return -1;
} // if statement
hostname = argv[1];
port = atoi (argv[2]);
printf ("Client: Calling createClientSocket(\"%s\", %d)\n", hostname, port);
struct Socket *soc = createClientSocket (hostname, port);
if (soc == NULL)
{
printf ("Client: could not construct socket\n");
return 0;
} // if statement
// Create and start a thread running the networkReader code to
// handle the input coming across the network. Add the code and
// declarations below here.
void *thread = createThread (networkReader, soc);
runThread (thread, NULL);
detachThread (thread);
// Once the thread is running have this execution stream loop reading
// information from standard input and writing it to the server connection.
// You may assume a maximum read size of 128 bytes from standard
// input. Add the code and declarations below here.
for ( ; ; )
{
if (soc && (soc->sType == ACTIVE_SOCKET))
{
gets (message_send);
bytes_sent = socketSend (soc, message_send, strlen (message_send));
if (bytes_sent < 0)
{
perror ("Client: send error.\n");
return bytes_sent;
} // inner if statement
} // outter if statement
else
{
printf ("Client: connection failed\n");
} // else statement
} // for loop
return 0;
} // main
|
C
|
/*
* index3.c
*
* Created on: Dec 12, 2019
* Author: isel
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "index.h"
static void tInsert(Tnode **rp, Word word);
static Word* tFind(Tnode **rp, Word word);
static Word* privateIndexFindWord(char *data);
static int cmpWordByValue(const void * elem1, const void * elem2);
static Tnode* treeToSortedList(Tnode *r, Tnode *link);
static Tnode* sortedListToBalancedTree(Tnode **listRoot, int n);
Index idx;
int shouldOrder;
int wordCount = 0;
void indexStart( void ){
idx = (Index) { NULL };
shouldOrder = 1;
}
void indexAddOccur( Word *w, int fileIdx, int line, long offset ){
Occurence occur = { fileIdx, line, offset };
int add = 1;
int i;
for(i = 0; i < w->count; i++){
if(w->occur[i].fileIdx == occur.fileIdx && w->occur[i].line == occur.line) add = 0;
}
if(add == 1){
w->count++;
w->occur = realloc(w->occur, w->count * sizeof(Occurence));
w->occur[w->count - 1] = occur;
}
}
static Word * privateIndexFindWord( char *data ){
Word word = { data, 0, malloc(0) };
return tFind(&(idx.root), word);
}
Word * indexFindWord( char *data ){
if(shouldOrder == 1){
Tnode * t1 = treeToSortedList(idx.root, NULL);
idx.root = sortedListToBalancedTree(&t1, wordCount);
shouldOrder = 0;
}
return privateIndexFindWord(data);
}
void indexAddWord( char *data, int fileIdx, int line, long offset ){
Word* w = privateIndexFindWord(data);
if(w != NULL) {
indexAddOccur(w, fileIdx, line, offset);
}
else {
char* newData = malloc(strlen(data));
strcpy(newData, data);
Occurence occur = { fileIdx, line, offset };
Occurence * occurarr = malloc(sizeof(Occurence));
occurarr[0] = occur;
Word newWord = { newData, 1, occurarr };
tInsert(&idx.root, newWord);
}
}
static void auxClearSpace(Tnode *link){
if(link != NULL){
free(link->word.occur);
auxClearSpace(link->left);
auxClearSpace(link->right);
free(link);
}
}
void indexEnd( void ){
auxClearSpace(idx.root);
}
static void tInsert(Tnode **rp, Word word){
if(*rp == NULL){
Tnode * newNode = malloc(sizeof(Tnode));
*newNode = (Tnode) { word, NULL, NULL };
*rp = newNode;
} else if(cmpWordByValue((const void*) &word, (const void*) &(*rp)->word) < 0){
tInsert(&(*rp)->left, word);
} else {
tInsert(&(*rp)->right, word);
}
}
static Word* tFind(Tnode **rp, Word word){
if(*rp == NULL) return NULL;
int i = cmpWordByValue((const void*) &word, (const void*) &(*rp)->word);
if(i == 0) return &(*rp)->word;
else if(i > 0) return tFind(&(*rp)->right, word);
else return tFind(&(*rp)->left, word);
}
static int cmpWordByValue(const void * elem1, const void * elem2){
return strcmp(((Word *) elem1)->word, ((Word *) elem2)->word);
}
static Tnode *treeToSortedList( Tnode *r, Tnode *link ){
Tnode * p;
if( r == NULL ) return link;
wordCount++;
p = treeToSortedList( r->left, r );
r->left = NULL;
r->right = treeToSortedList( r->right, link );
return p;
}
static Tnode* sortedListToBalancedTree( Tnode **listRoot, int n ) {
if( n == 0 )
return NULL;
Tnode *leftChild = sortedListToBalancedTree( listRoot, n/2 );
Tnode *parent = *listRoot;
parent->left = leftChild;
*listRoot = (*listRoot)->right;
parent->right = sortedListToBalancedTree( listRoot, n - ( n / 2 + 1 ) );
return parent;
}
|
C
|
//#include "my_malloc.h"
//#include "my_pthread_t.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#define SIZE (4096 * 4096)
#define PAGE_SIZE 4096
int main()
{
char *swap="swapper";
int fd = open(swap,O_CREAT | O_RDWR | O_TRUNC, S_IRUSR | S_IWUSR);
lseek(fd,0,SEEK_SET);
static unsigned char swapFile[SIZE];
bzero(swapFile,SIZE);
write(fd,swapFile,SIZE);
unsigned char page[PAGE_SIZE];
unsigned char page2[PAGE_SIZE];
unsigned char page3[PAGE_SIZE];
bzero(page,PAGE_SIZE);
bzero(page2,PAGE_SIZE);
bzero(page3,PAGE_SIZE);
page[0] = 0xff;
page[1] = 0xff;
memcpy(page2,page,PAGE_SIZE);
lseek(fd,PAGE_SIZE*2,SEEK_SET);
write(fd,page2,PAGE_SIZE);
lseek(fd,0,SEEK_SET);
lseek(fd,PAGE_SIZE*2,SEEK_SET);
read(fd,page3,PAGE_SIZE);
int result = (page3[0] << 8) | page3[1];
printf("Please work ~ Int: %d\t,Hex: 0x%04x\n",result,result);
return 0;
}
|
C
|
#include"utils.h"
#include"maths.h"
static void tmp_mod_light(t_light_list *curr,
t_coords *base,
t_coords *decal,
int max)
{
int off;
int semi;
t_coords *cdecal;
off = curr->soft_val;
semi = off / 2;
cdecal = &(curr->rndm[(int)decal->y * max + (int)decal->x]);
curr->pos->x = base->x + cdecal->x + (rand() % off - semi) / 2;
curr->pos->y = base->y + cdecal->y + (rand() % off - semi) / 2;
curr->pos->z = base->z + cdecal->z + (rand() % off - semi) / 2;
}
static double ratio_mid(double datas[], int max)
{
double total;
int x;
int y;
total = 0;
x = 0;
while (x < max)
{
y = 0;
while (y < max)
{
total += datas[y * max + x];
++y;
}
++x;
}
total /= (double)(max * max);
if (total >= 1.0)
return (1.0);
if (total <= 0.0)
return (0.0);
return (total);
}
double soft_listing(t_rt *this,
t_light_list *curr,
t_coords *it)
{
double datas[256];
t_coords saved;
t_coords i;
if (this->cam->light_sampling == 1
|| curr->type != LIGHT_NOR
|| curr->soft_val <= 1)
return (list_transparency(this, curr, it, 1.0f));
copy_coords(&saved, curr->pos);
i.x = 0;
while (i.x < this->cam->light_sampling)
{
i.y = 0;
while (i.y < this->cam->light_sampling)
{
tmp_mod_light(curr, &saved, &i, this->cam->light_sampling);
datas[(int)i.y * this->cam->light_sampling + (int)i.x] =
list_transparency(this, curr, it, 1.0f);
i.y++;
}
i.x++;
}
copy_coords(curr->pos, &saved);
return (ratio_mid(datas, this->cam->light_sampling));
}
|
C
|
void init (LInt *l){
LInt current = *l;
if ((*l)->prox == NULL){
free(*l);
*l = NULL;
return;
}
LInt prev;
while (current -> prox != NULL){
prev = current;
current = current -> prox;
}
prev -> prox = NULL;
free(current);
}
|
C
|
#include <string.h>
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include "../include/sstring.h"
bool string_valid(const char *str, const size_t length){
if(length==0) //check to make sure there is a valid length
return false;
if(str==NULL) //check for null string
return false;
int i;
for(i=0; i<=length; i++){ //iterate through string until null terminator to test valid string
if(str[i] == '\0')
return true;
}
return false;
}
char *string_duplicate(const char *str, const size_t length){
if(str==NULL) //check for no null string
return false;
if(length==0) //check for a valid length
return false;
char* hold=malloc(sizeof(char)*length); //alloc string to be duplicated into
int i;
for(i=0; i<length; i++){ //iterate through length of string
hold[i]=str[i]; //assign str index to hold
}
return hold;
}
bool string_equal(const char *str_a, const char *str_b, const size_t length){
if(str_a ==NULL || str_b==NULL) //error check for null strings
return false;
if(length==0) //ensure a valid length
return false;
int i;
for(i=0; i<length; i++){ //iterate through length of strings
if(str_a[i]!=str_b[i]) //compare values of string indices to check for valid
return false;
}
return true;
}
int string_length(const char *str, const size_t length){
if(length==0) //error check for valid length
return -1;
if(str==NULL) //error check string to ensure it's not null
return -1;
int count=strlen(str);
return count;
}
int string_tokenize(const char *str, const char *delims, const size_t str_length, char **tokens, const size_t max_token_length, const size_t requested_tokens){
if(str==NULL || delims==NULL || tokens==NULL) //error check that pointers aren't null
return 0;
if(str_length==0 || max_token_length==0 || requested_tokens==0) //error check to ensure valid lengths and tokens requested
return 0;
int i, count=0;
for(i=0; i<requested_tokens; i++){ //loop through the number of requested tokens
if(tokens[i]==NULL) //error check for pointer at tokens[i] to not be null
return -1;
}
i=0;
char* hold=string_duplicate(str, str_length); //duplicate str into char* hold because strtok doesn't take const
tokens[i]=strtok(hold, delims); //tokenize the first token
//i++;
//count++;
while(tokens[i]!=NULL){ //iterate until null pointer at tokens[i]
tokens[i]=strtok(NULL, delims); //tokenize the next token from null pointer
i++; //iterate i
count++; //iterate count
}
return count; //return number of tokens
}
bool string_to_int(const char *str, int *converted_value){
if(str==NULL || converted_value==NULL) //error check for null pointers
return false;
int i;
for(i=0; i<strlen(str); i++){ //iterate until end of string
if(str[i]-'0'<0 || str[i]-'0' >9) //error check to make sure that str[i] is actually an integer
break;
if(*converted_value > 32767 || *converted_value < -32767){ //ensure that the converted value does not exceed the int range
*converted_value=0;
return false;
}
*converted_value *=10; //multiple the converted value by 10 for number of place values
*converted_value+=( str[i] -'0'); //add the newly read integer from str[i] to the other numbers
}
//converted_value[i]=hold;
return true;
}
|
C
|
#include <stdio.h>
#define MAX 1000
void escape(char s[], char t[]);
void esc(char s[], char t[]);
int main()
{
int c;
char s[MAX];
char t[] = "li\nnu\tx";
char o[] = "li\\nnu\\tx";
escape(s, t);
printf("result: %s\n", s);
esc(s, o);
printf("result: %s\n", s);
c = getchar();
return 0;
}
void escape(char s[], char t[])
{
int i, j;
for (i=j=0; t[i]!='\0'; i++)
{
switch (t[i]) {
case '\n':
s[j++] = '\\';
s[j++] = 'n';
break;
case '\t':
s[j++] = '\\';
s[j++] = 't';
break;
default:
s[j++] = t[i];
break;
}
}
}
void esc(char s[], char t[])
{
int i, j;
for (i=j=0; t[i]!='\0'; i++)
{
if (t[i] == '\\')
{
switch (t[++i]) {
case 'n':
s[j++] = '\n';
break;
case 't':
s[j++] = '\t';
break;
default:
break;
}
}
else
s[j++] = t[i];
}
}
|
C
|
/* , , EOF. . . , . ( ispunct() ctype.h.)*/
#include <stdio.h>
#include <ctype.h>
int main(void)
{
int letters=0;
int char_number=0;
int j,i=0;
int letters_count[1000];
int average=0;
int symbols_count=0;
char ch;
while(scanf("%c",&ch)!=EOF)
{
if(ch==' ')
{
if (i==0)
symbols_count=char_number;
else
symbols_count=char_number-symbols_count-1;
average+=symbols_count;
char_number=symbols_count;
if (symbols_count>0)
{
i++;
printf(" %d: %d \n",i,symbols_count);
}
}
if(ispunct(ch)==0)
char_number++;
}
symbols_count=char_number-symbols_count-1;
average+=symbols_count;
printf(" %d: %d \n",i+1,symbols_count);
printf(" : %d",average/(i+1));
return 0;
}
|
C
|
#include <cs50.h>
#include <stdio.h>
#include <string.h>
int main(){
string num0 = get_string("");
string num1 = get_string("");
char temp;
int number1 = strlen(num0);
int number2 = strlen(num1);
for (int i=0; i < number1; i++){
for (int j=0; j < number1 - i - 1; j++ ){
if (num0[j] > num0[j+1]){
temp = num0[j];
num0[j] = num0[j+1];
num0[j+1] = temp;
}
}
}
for (int i=0; i < number2; i++){
for (int j=0; j < number2 - i - 1; j++ ){
if (num1[j] > num1[j+1]){
temp = num1[j];
num1[j] = num1[j+1];
num1[j+1] = temp;
}
}
}
if(strcmp(num0, num1) == 0){
printf("출력값 : True\n");
}
else printf("출력값 : False\n");
}
|
C
|
/***********************************************************************************************************
*执行用时:4 ms, 在所有 Go 提交中击败了84.73%的用户
*内存消耗:5.7 MB, 在所有 Go 提交中击败了79.74%的用户
************************************************************************************************************
*/
/***********************************************************************************************************
给你一个链表和一个特定值 x ,请你对链表进行分隔,使得所有小于 x 的节点都出现在大于或等于 x 的节点之前。
你应当保留两个分区中每个节点的初始相对位置。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/partition-list
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
************************************************************************************************************
*/
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* partition(struct ListNode* head, int x) {
if(head == NULL || head->next == NULL){
return head;
}
int flag = 0;
struct ListNode *x_ptr = NULL;
struct ListNode *p1 = NULL;
struct ListNode *p2 = NULL;
struct ListNode *p3 = NULL;
struct ListNode *big_head = (struct ListNode*)malloc(sizeof(struct ListNode));
struct ListNode *small_head = (struct ListNode*)malloc(sizeof(struct ListNode));
small_head->next = NULL;
big_head->next = NULL;
p1 = big_head;
p2 = small_head;
p3 = head;
while(p3 != NULL){
if(p3->val < x){
p2->next = p3;
p3 = p3->next;
p2 = p2->next;
p2->next = NULL;
}
else{
p1->next = p3;
p3 = p3->next;
p1 = p1->next;
p1->next = NULL;
}
}
p2->next = big_head->next;
return small_head->next;
}
|
C
|
/*
* Moisture_sensors.c
*
* Created: 11/9/2019 3:13:54 PM
* Author : steph
*/
#include <avr/io.h>
//#include <timer.h>
void ADC_init() {
ADCSRA |= (1 << ADEN) | (1 << ADSC) | (1 << ADATE);
// ADEN: setting this bit enables analog-to-digital conversion.
// ADSC: setting this bit starts the first conversion.
// ADATE: setting this bit enables auto-triggering. Since we are
// in Free Running Mode, a new conversion will trigger whenever
// the previous conversion completes.
}
/*
void ADC_on(){
}
void ADC_off(){
}
void ADC_read(){
}
*/
int main(){
//Initialize DDRX and PORTX
DDRA = 0x00; PORTA = 0xFF;
DDRB = 0xFF; PORTB = 0x00;
DDRD = 0xFF; PORTD = 0x00;
//LED variables
unsigned short x = 0xABCD;
//unsigned char my_char = (char)my_short; // my_char = 0xCD
//my_char = (char)(my_short >> 4); // my_char = 0xBC
ADC_init();
//ADC_on();
//ADC_off();
//x = ADC;
while(1){
x = ADC;
PORTB = (char)x;
PORTD = (((char)(x >> 2)) & 0xC0);
}
return 0;
}
/*
//----------Find GCD function ------------------------------------------------//
unsigned long int findGCD(unsigned long int a, unsigned long int b){
unsigned long int c;
while(1){
c = a%b;
if(c==0){return b;}
a = b;
b = c;
}
return 0;
}
//----------End find gcd function --------------------------------------------//
//---------------Task scheduler data structure ------------------------------//
// Struct for Tasks represent a running process in our simple real-time operating system.
typedef struct _task{
Tasks a should have members that include: state, period,
a measurement of elapsed time, and a function pointer
signed char state; //Task's current state
unsigned long int period; // Task period
unsigned long int elapsedTime; // Time elapsed since last task tick
int (*TickFct)(int); // Task tick function
}task;
// --------------End Task scheduler data structure
//Tick Function #1: Button Logic
enum SM1_States{Release, Press};
int SM1Tick(int state){
static unsigned char flag = 0;
//Transitions
switch(state){
case Release:
if(PINA == 0xFE){flag = flag ? 1:0;
state = Press;}
else{state = Release;}
break;
case Press:
if(PINA == 0xFE){state = Press;}
else{
PORTB = flag ? 0x01:0x00;
state = Release;
}
break;
default: break;
}
//Actions
switch(state){
case Release:
break;
case Press:
break;
default: break;
}
return state;
};
int main(void)
{
//Ports and DDRX
DDRA = 0x00; PORTA = 0xFF;
DDRB = 0xFF; PORTB = 0x00;
// Period for the tasks
unsigned long int SMTick1_calc = 50;
// Calculating GCD
unsigned long int tmpGCD = 1;
tmpGCD = findGCD(SMTick1_calc, tmpGCD);
// Recalculate GCD periods for scheduler
unsigned long int SMTick1_period = SMTick1_calc/tmpGCD;
//Tasks code
static task task1;
task *tasks[] = {&task1};
const unsigned short numTasks = sizeof(tasks)/sizeof(task*);
//Task #1
task1.state = -1; // Task initial state
task1.period = SMTick1_period; //Task period
task1.elapsedTime = SMTick1_period; //Task current elapsed time
task1.TickFct = &SM1Tick; //Function pointer for the tick
TimerSet(tmpGCD);
TimerOn();
//unsigned char sensorReading = 0;
//unsigned char sensorOn = 0;
unsigned char i = 0;
while (1)
{
//Scheduler code
for(i = 0; i < numTasks; i++){
// Task is ready to tick
if(tasks[i]->elapsedTime == tasks[i]->period){
//Setting next state for task
tasks[i]->state = tasks[i]->TickFct(tasks[i]->state);
//Reset the elapsed time for next tick.
tasks[i]->elapsedTime = 0;
}
tasks[i]->elapsedTime +=1;
}
while(!TimerFlag);
TimerFlag = 0;
}
return 0;
}
*/
|
C
|
/*
** initbcg1.c for initbcg1 in /home/marrie_h/rendu/PSU/PSU_2015_tetris
**
** Made by hugo marrien
** Login <[email protected]>
**
** Started on Tue Feb 23 10:33:36 2016 hugo marrien
** Last update Wed Mar 16 12:20:14 2016 nguyen kevin
*/
#include "header.h"
void init_colorbcg1()
{
init_pair(0, 0, 7);
init_pair(1, 1, 1);
init_pair(2, 2, 2);
init_pair(3, 3, 3);
init_pair(4, 4, 4);
init_pair(5, 5, 5);
init_pair(6, 6, 6);
init_pair(7, 7, 7);
}
void init_title1()
{
attron(COLOR_PAIR(4));
mvprintw(1, 1, " ");
mvprintw(2, 3, " ");
mvprintw(3, 3, " ");
mvprintw(4, 3, " ");
mvprintw(5, 3, " ");
mvprintw(6, 3, " ");
mvprintw(7, 3, " ");
attroff(COLOR_PAIR(4));
attron(COLOR_PAIR(3));
mvprintw(3, 5, " ");
mvprintw(4, 5, " ");
mvprintw(5, 5, " ");
mvprintw(6, 5, " ");
mvprintw(7, 5, " ");
attroff(COLOR_PAIR(3));
attron(COLOR_PAIR(1));
mvprintw(3, 9, " ");
mvprintw(4, 10, " ");
mvprintw(5, 10, " ");
mvprintw(6, 10, " ");
mvprintw(7, 10, " ");
attroff(COLOR_PAIR(1));
attron(COLOR_PAIR(2));
}
void init_title2()
{
mvprintw(3, 13, " ");
mvprintw(4, 13, " ");
mvprintw(4, 15, " ");
mvprintw(5, 13, " ");
mvprintw(6, 13, " ");
mvprintw(6, 15, " ");
mvprintw(7, 13, " ");
mvprintw(7, 15, " ");
attroff(COLOR_PAIR(2));
attron(COLOR_PAIR(6));
mvprintw(3, 17, " ");
mvprintw(4, 17, " ");
mvprintw(5, 17, " ");
mvprintw(6, 17, " ");
mvprintw(7, 17, " ");
attroff(COLOR_PAIR(6));
attron(COLOR_PAIR(5));
mvprintw(3, 19, " ");
mvprintw(4, 19, " ");
mvprintw(5, 19, " ");
mvprintw(6, 21, " ");
mvprintw(7, 19, " ");
attroff(COLOR_PAIR(5));
}
void init_next()
{
attron(COLOR_PAIR(0));
mvprintw(10, 21, " NEXT: ");
mvprintw(11, 20, " ");
mvprintw(11, 26, " ");
mvprintw(12, 20, " ");
mvprintw(12, 26, " ");
mvprintw(13, 20, " ");
mvprintw(13, 26, " ");
mvprintw(14, 20, " ");
mvprintw(14, 26, " ");
mvprintw(15, 20, " ");
attroff(COLOR_PAIR(0));
}
void fillwhite()
{
int l;
int c;
l = 0;
attron(COLOR_PAIR(7));
while (l != LINES)
{
c = 0;
while (c != COLS)
{
mvprintw(l, c, " ");
c = c + 1;
}
l = l + 1;
}
attroff(COLOR_PAIR(7));
}
int init_bcg()
{
init_colorbcg1();
/* fillwhite(); */
init_title1();
init_title2();
init_next();
init_score();
return (0);
}
|
C
|
#ifndef INPUTS_H_
#define INPUTS_H_
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
/// @fn unsigned long long PedirCUIL_CUIT(char[], char[])
/// @brief
///
/// @param mensaje
/// @param mensajeError
double PedirCUIL_CUIT(char mensaje[], char mensajeError[]);
/// @fn void PedirCadena(char[], int, char[], char[])
/// @brief Realiza la carga de un vector char
///
/// @param vector Vector donde se hara la carga
/// @param largoVector Largo del vector donde se hara la carga
/// @param mensaje Mensaje que se solicita al hacer la carga
/// @param mensajeError Mensaje de error en caso de que la carga se exceda de la capacidad del vector
void PedirCadena(char vector[], int largoVector, char mensaje[],
char mensajeError[]);
/// @fn int PedirEntero(char[])
/// @brief Pide y valida que el valor ingresado sea un valor valido para int
///
/// @param mensaje Mensaje que se muestra al solicitar el numero
/// @param mensajeError Mensaje que se muestra en caso de ingresar un caracter invalido
/// @return Numero int validado
int PedirEntero(char mensaje[], char mensajeError[]);
/// @fn int PedirEnteroEnRango(char[], int, int)
/// @brief Pide y valida que el valor ingresado sea un valor valido para int y ademas que este dentro de un rango especifico
///
/// @param mensaje Mensaje que se muestra al solicitar el numero
/// @param mensajeError Mensaje que se muestra en caso de ingresar un caracter invalido o valor fuera de rango
/// @param min Valor minimo del rango permitido
/// @param max Valor maximo del rango permitido
/// @return Numero int validado
int PedirEnteroEnRango(char mensaje[], char mensajeError[], int min, int max);
/// @fn int PedirEnteroExcluyendo(char[], int)
/// @brief Pide y valida que el valor ingresado sea un valor valido para int y ademas excluye un valor
///
/// @param mensaje Mensaje que se muestra al solicitar el numero
/// @param valorAExcluir Numero que no se permite en el ingreso
/// @return Numero int validado
int PedirEnteroExcluyendo(char mensaje[],char mensajeError[], int valorAExcluir);
/// @fn int PedirEnteroPositivo(char[], char[])
/// @brief
///
/// @param mensaje
/// @param mensajeError
/// @return
int PedirEnteroPositivo(char mensaje[], char mensajeError[]);
/// @fn float PedirFlotante(char[])
/// @brief Pide y valida que el valor ingresado sea un valor valido para float
///
/// @param mensaje Mensaje que se muestra al solicitar el numero
/// @return Numero float validado
float PedirFlotante(char mensaje[], char mensajeError[]);
/// @fn float PedirFlotanteEnRango(char[], float, float)
/// @brief Pide y valida que el valor ingresado sea un valor valido para float y ademas que este dentro de un rango especifico
///
/// @param mensaje Mensaje que se muestra al solicitar el numero
/// @param min Valor minimo del rango permitido
/// @param max Valor maximo del rango permitido
/// @return Numero float validado
float PedirFlotanteEnRango(char mensaje[],char mensajeError[], float min, float max);
/// @fn float PedirFlotantePositivo(char[], char[])
/// @brief
///
/// @param mensaje Mensaje que se muestra al solicitar el numero flotante
/// @param mensajeError Mensaje en caso de ingresar un caracter invalido o un valor negativo
/// @return Numero flotante validado
float PedirFlotantePositivo(char mensaje[],char mensajeError[]);
/// @fn int myGets(char*, int)
/// @brief
///
/// @param cadena
/// @param longitud
/// @return
int myGets(char * cadena, int longitud);
/// @fn int PedirSN(char[])
/// @brief Pide ingresar S para continuar o N para no hacerlo, indistinto si se usan mayus o minus y se valida.
///
/// @param mensaje El mensaje a mostrar al pedir el caracter
/// @param mensajeError El mensaje a mostrar luego de ingresar un caracter no valido
/// @return 1 en caso de S y 0 en caso de N
int PedirSN(char mensaje[], char mensajeError[]);
#endif
|
C
|
#include "MirrorInitiator.h"
void client_assistant(int sock, int argPos, char** argv)
{
int i = 0, size, end = true, filesTransferred, bytesTransferred;
char buffer[256];
char** StrTable;
content_num = 0; // Global variable
StrTable = analyze(argv[argPos], ",", strlen(argv[argPos]));
/* Send how much contentServers exists */
if( write(sock, &content_num, sizeof(content_num)) < 0 ) { perror("Write"); exit(1); }
/* Send data to server */
while( StrTable[i] != NULL )
{
/* Sent the size of data that server has to read */
size = strlen(StrTable[i])+1;
if( write(sock, &size, sizeof(size)) < 0 ) { perror("Write"); exit(1); }
/* write all the data to MirrorManager */
write_all(sock, StrTable[i], strlen(StrTable[i])+1);
i++; // Take next string
}
/* -------------------- */
free_table(StrTable);
while( strcmp(buffer, "yes") != 0 && strcmp(buffer, "no") != 0)
{
printf("Do you want to shut down MirrorServer? [yes/no]\n");
scanf("%s",buffer);
if( strcmp(buffer, "yes") == 0 )
{
if( write(sock, &end, sizeof(end)) < 0 ) { perror("Write"); exit(1); }
for(i = 0; i < content_num; i++)
{
if( read(sock, &bytesTransferred, sizeof(bytesTransferred)) < 0 ) { perror("Read"); exit(1); }
if( read(sock, &filesTransferred, sizeof(filesTransferred)) < 0 ) { perror("Read"); exit(1); }
printf("Total files that transferred are: %d.\n",filesTransferred);
printf("Total bytes that transferred are: %d.\n",bytesTransferred);
}
}
}
}
|
C
|
#include "pebble.h"
Window *s_main_window;
TextLayer *s_data_layer;
int boundsShift = 0;
void setLayerBounds(TextLayer *subject, int16_t new_bounds)
{
APP_LOG(APP_LOG_LEVEL_INFO, "In setter with %d", new_bounds);
GRect bounds;
bounds = layer_get_bounds((Layer *)subject);
bounds.origin.x = new_bounds; // Move the x origin
layer_set_bounds((Layer *)subject, bounds);
};
void up_click_handler(ClickRecognizerRef recognizer, void *context) {
setLayerBounds(s_data_layer, ++boundsShift);
}
void down_click_handler(ClickRecognizerRef recognizer, void *context) {
setLayerBounds(s_data_layer, --boundsShift);
}
static void main_window_load(Window *window) {
s_data_layer = text_layer_create(GRect(73, 91, 144, 51));
layer_set_frame((Layer *) s_data_layer, GRect(73, 91, 71, 51));
text_layer_set_background_color(s_data_layer, GColorClear);
text_layer_set_text_color(s_data_layer, GColorWhite);
layer_add_child(window_get_root_layer(s_main_window), (Layer *)s_data_layer);
text_layer_set_font(s_data_layer, fonts_get_system_font(FONT_KEY_BITHAM_42_MEDIUM_NUMBERS));
text_layer_set_text(s_data_layer, "89056");
}
static void main_window_unload(Window *window) {
text_layer_destroy(s_data_layer);
}
static void click_config_provider(void *context) {
window_single_click_subscribe(BUTTON_ID_UP, up_click_handler);
window_single_click_subscribe(BUTTON_ID_DOWN, down_click_handler);
}
static void init() {
s_main_window = window_create();
window_set_background_color(s_main_window, GColorBlack);
window_set_click_config_provider(s_main_window, click_config_provider);
window_set_window_handlers(s_main_window, (WindowHandlers) {
.load = main_window_load,
.unload = main_window_unload
});
window_stack_push(s_main_window, true);
}
static void deinit() {
window_destroy(s_main_window);
}
int main(void) {
init();
app_event_loop();
deinit();
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
static int compare(char *s1, char *s2)
{
for (int i = 0; i < 50; i += 1) {
if (s1[i] != s2[i]) {
return 0;
}
}
return 1;
}
int main(int ac, char **av)
{
const char charset[] = "IHaveNoIdeaWtfImDoingRightNow";
const int len = strlen(charset);
char res[51] = {};
if (ac != 2) {
printf("Gimme pass bro!\n");
return (-1);
}
if (strlen(av[1]) != 50) {
printf("Not even correct length!\n");
return (-1);
}
for (int i = 0; i < 50; i++) {
res[i] = charset[((i % strlen(strchr(charset, (charset[i % (len)])))) + i) % len];
}
res[50] = '\0';
if (compare(av[1], res)) {
printf("PoC{%s}\n", av[1]);
return 0;
}
dprintf(2, "N0pe!\n");
return 1;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include "automatecellulaire.h"
//GENERATION
//PURPOSE : Iteration of a single generation of the game of life.
//INPUT : Buffer and number of generations
//OUTPUT : Edited text file with info on the current generation
void generation(enum cell buffer[SIZE][SIZE],enum cell grid[SIZE][SIZE],int nGen)
{
int i,j;
int env;
int nLiveCells;
for(i=0;i<SIZE;i++)
{
for(j=0;j<SIZE;j++)
{
env=environmentinfo(buffer,i,j);
if((buffer[i][j]==1)||(buffer[i][j]==3))
{
if ((env<2)||(env>3))
{
death(grid,env,i,j);
}
else
{
stasis(grid,env,i,j);
}
}
else if (env==3)
{
birth(grid,env,i,j);
}
}
}
nLiveCells=cellcount(grid);
editfile(nLiveCells,nGen);
}
//BIRTH
//PURPOSE : Give birth to a cell
//INPUT : Plane, number of surrounding cells, position
//OUTPUT :
void birth(enum cell grid[SIZE][SIZE],int nSurroundingLiveCells,int nI, int nJ)
{
grid[nI][nJ]=alive;
}
//STASIS
//PURPOSE :
//INPUT :
//OUTPUT :
void stasis(enum cell grid[SIZE][SIZE],int nSurroundingLiveCells,int nI, int nJ)
{
grid[nI][nJ]=alive;
}
//DEATH
//PURPOSE : KILLING A CELL WHEN THE CONDITIONS ARE MET
//INPUT : PLANE, NUMBER OF SURROUNDING CELLS, POSITION OF CELL
//OUTPUT : MODIFIED PLANE
void death(enum cell grid[SIZE][SIZE],int nSurroundingLiveCells,int nI, int nJ)
{
grid[nI][nJ]=dead;
}
//EDITFILE
//PURPOSE : Editing the text file with generation info
//INPUT : Total living cells and number of generations
//OUTPUT : Edited text file
void editfile(int nLiveCells,int nGen)
{
FILE * pData;
pData=fopen("gendata.txt","a");
fprintf(pData,"\nGENERATION NUMBER %d : %d living cells\n",nGen,nLiveCells);
fclose(pData);
}
//EMPTYFILE
//PURPOSE : Empty the file before a new game
//INPUT : -
//OUTPUT : Emptied text file
void emptyfile()
{
FILE * pData;
pData=fopen("gendata.txt","w");
fclose(pData);
}
//COPYARRAY
//PURPOSE : Copy an array into another
//INPUT : Buffer & grid
//OUTPUT : Reassigned buffer
void copyarray(enum cell grid[SIZE][SIZE],enum cell buffer[SIZE][SIZE])
{
int i,j;//Incrementation
for(i=0;i<SIZE;i++)
{
for(j=0;j<SIZE;j++)
{
buffer[i][j]=grid[i][j];
}
}
}
|
C
|
/*
*
* This code implements the sum of two vectors in parallel using a shared memory approach, implemented with OpenMP
* The parallelization is inplicit because the loop is autmatically divided among the threads by the OpenMP work scharing construct
* The pre-defined size of the vectors N is not expected to be a submultiple of the number of threads spwaned at runtime.
*
* Every element of the two vectors a and b is initialized with the threadId of the thread working on the element.
* resulting vector c is obtained by the parallel sum of the two vectors a
*
* Compile with:
* $icc -qopenmp vector_parallel_work_sharing_loop.c
*
* Run with:
* $export OMP_NUM_THREADS=[NUMBER OF THREADS]; ./a.out
*
*/
#include <stdlib.h>
#include <stdio.h>
// Header file for compiling code including OpenMP APIs
#include <omp.h>
#define N 8
int main( int argc, char * argv[] ){
int thread_id = 0.0;
int * a, * b, * c;
int i = 0;
a = (int * )malloc( N * sizeof(int) );
b = (int * )malloc( N * sizeof(int) );
c = (int * )malloc( N * sizeof(int) );
#pragma omp parallel private( thread_id, i )
{
int n_threads = omp_get_num_threads();
thread_id = omp_get_thread_num();
#pragma omp for
for( i = 0; i < N; i++ ){
a[ i ] = b[ i ] = thread_id;
c[ i ] = a[ i ] + b[ i ];
}
}
for( i = 0; i < N; i++ ){
fprintf( stdout, "\nc[ %d ] = a[ %d ] + b[ %d ] = %d \n", i, i, i, c[ i ] );
}
free( a );
free( b );
free( c );
return 0;
}
|
C
|
#include <string.h>
#include <stdlib.h>
#include "urgan.h"
int main(void){
char line[SIZE];
char *rssis;
const char *id;
int i,j;
int closest[4];
FILE *f=fopen("/dev/ttyUSB0","r+");
if(f == NULL){
printf("erreur ouverture fichier USB0\n");
exit(0);
}
Marker* dist=malloc(N_BALISES*sizeof(Marker));
if(dist ==NULL){
printf("erreur allocation 1\n");
exit(0);
}
Coordinates *area=malloc(5*sizeof(Coordinates));
if(area==NULL){
printf("erreur allocation tableau de coordonnees\n");
exit(0);
}
//matrice qui memorisera pour chaque badge les distances calculees a partir des rssis recus
float avg_badge[N_BADGE][N_BALISES];
for(i=0;i<N_BADGE;i++){
for(j=0;j<N_BALISES;j++)
avg_badge[i][j]=0.0;
}
//tableau qui memorisera l'indice de la derniere distance recuperee pour chaque badge
int cpt_badge[N_BADGE];
//tableau qui memorisera si c'est le premier echantillonage du badge. si oui, on prend dix echantillons avant d'effectuer la moyenne,
//sinon, on applique la fenetre glissante.
int first_sampling[N_BADGE];
for(i=0;i<N_BADGE;i++){
cpt_badge[i]=0;
first_sampling[i]=1;
}
//initialisation des structures 'marker' correspondants aux balises
printf("Reading configuration file ...\n");
init_markers(dist);
printf("-->Configuration saved\n");
// print_markers(dist,N_BALISES);
//On recupere en continu la ligne inscrite par la rfduino sur le port USB0.
//On incrementera la somme des rssis, pour le badge concerne, jusqu'a atteindre
//10 echantillons, avant d'effectuer la premiere moyenne, puis faire une fenetre glissante ensuite.
printf("calculating positions ...\n");
while(1){
fgets(line,SIZE*sizeof(char),f);
id=strtok(line,";");
// printf("id badge : %s\n",id);
rssis=strtok(NULL,"\n");
// printf("%s\n",rssis);
sscanf(rssis,"%d %d %d %d %d %d %d %d\n",&dist[0].rssi,&dist[1].rssi,&dist[2].rssi,&dist[3].rssi,&dist[4].rssi,&dist[5].rssi,&dist[6].rssi,&dist[7].rssi);
// print_markers(dist,N_BALISES);
rssi_to_distance(dist);
//on incremente la valeur totale de rssis recu pour le badge id
avg_badge[id[0]-97][cpt_badge[id[0]-97]]=avg_badge[id[0]-97][cpt_badge[id[0]-97]]+dist[cpt_badge[id[0]-97]].dist;
cpt_badge[id[0]-97]++;
// printf("rssi to distance conversion : \n\n");
// print_markers(dist,N_BALISES);
//Une fois qu'on a 10 echantillons, on calcule la distance moyenne de chaque balise avec le badge
if((cpt_badge[id[0]-97] == NB_CYCLES)||(first_sampling[id[0]-97]==0)){
for(i=0;i<N_BALISES;i++){
avg_badge[id[0]-97][i]=avg_badge[id[0]-97][i]/NB_CYCLES;
// printf("balise %d => moyenne : %f\n",i,avg_badge[id[0]-97][i]);
dist[i].dist=avg_badge[id[0]-97][i];
}
//on modifie dist pour qu'elle comporte les 4 balises les plus proches en première position et pour effectuer la trilateration sur ces dernieres.
for(i=0;i<4;i++){
devices_sorted(dist,closest,i);
// printf("min[%d] = %d\n",i,closest[i]);
}
// print_markers(dist,N_BALISES);
trilateration(dist,&area[0],&area[1],&area[2],&area[3],&area[4]);
// printf("\nArea of the badge : (%f,%f) | (%f,%f) | (%f,%f) | (%f,%f) | (%f,%f) \n",area[0].x,area[0].y,area[1].x,area[1].y,area[2].x,area[2].y,area[3].x,area[3].y,area[4].x,area[4].y);
int n=5;
//On verifie que les coordonnees ne sont pas negatives, infinies, ou hors de la page. Sinon on les annule et on calcule le barycentre sur les n-i restantes (i=nb de coordonnees neg ou inf)
for(i=0;i<5;i++){
if((isfinite(area[i].x) == 0) || (isfinite(area[i].y) == 0) || area[i].x <0 || area[i].y <0 || area[i].x>2000 || area[i].y>1000){
area[i].x = 0;
area[i].y = 0;
n--;
}
}
// printf("n = %d\n", n);
// printf("\nNew area of the badge : (%f,%f) | (%f,%f) | (%f,%f) | (%f,%f) | (%f,%f) \n",area[0].x,area[0].y,area[1].x,area[1].y,area[2].x,area[2].y,area[3].x,area[3].y,area[4].x,area[4].y);
//On calcule le barycentre a partir des coordonnees que la trilateration nous renvoit
area[0].x=(area[0].x+area[1].x+area[2].x+area[3].x+area[4].x)/n;
area[0].y=(area[0].y+area[1].y+area[2].y+area[3].y+area[4].y)/n;
// printf("barycenter : (%f,%f)\n",area[0].x,area[0].y);
FILE *f2;
//On test l'id pour savoir dans quel fichier ecrire les coordonnees finales
if(strcmp(id,"a") == 0){
f2=fopen(BADGE_A,"w");
}else if(strcmp(id,"b") == 0){
f2=fopen(BADGE_B,"w");
}
//....refaire autant de 'else if' qu'il y a de badges en plus
if(f2 == NULL){
printf("erreur ouverture fichier de badge\n");
exit(0);
}
//On ecrit ensuite les coordonnees finales dans le fichier du badge concerne
fprintf(f2,"%f,%f\n",area[0].x,area[0].y);
fclose(f2);
cpt_badge[id[0]-97]=0;
printf("badge %s : (%f,%f)\n",id,area[0].x,area[0].y);
}
my_delay(1);
}
free(dist);
free(area);
fclose(f);
return 0;
}
|
C
|
#include <stdlib.h>
#include <string.h>
#include "hiredis/hiredis.h"
#include "player_state.h"
const char *KEY_STATE = "player-state";
const char *HKEY_ALBUM = "album";
const char *HKEY_TRACK = "track";
const char *HKEY_SONG_TIME_ELAPSED = "song-time-elapsed";
int player_state_store(const char *album, int track, double song_time_elapsed) {
redisContext *r = redisConnect("127.0.0.1", 6379);
if (r == NULL) {
return -1;
} else if (r->err) {
redisFree(r);
return -1;
}
redisReply *reply = NULL;
reply = redisCommand(r, "HSET %s %s %s", KEY_STATE, HKEY_ALBUM, album);
freeReplyObject(reply);
reply = redisCommand(r, "HSET %s %s %d", KEY_STATE, HKEY_TRACK, track);
freeReplyObject(reply);
reply = redisCommand(r, "HSET %s %s %f", KEY_STATE, HKEY_SONG_TIME_ELAPSED, song_time_elapsed);
freeReplyObject(reply);
return 0;
}
int player_state_clear() {
redisContext *r = redisConnect("127.0.0.1", 6379);
if (r == NULL) {
return -1;
} else if (r->err) {
redisFree(r);
return -1;
}
redisReply *reply = redisCommand(r, "DEL %s", KEY_STATE);
freeReplyObject(reply);
redisFree(r);
return 0;
}
int player_state_restore(char **album, int *track, double *song_time_elapsed) {
redisContext *r = redisConnect("127.0.0.1", 6379);
if (r == NULL) {
return -1;
} else if (r->err) {
redisFree(r);
return -1;
}
int rc = 0;
redisReply *reply = redisCommand(r, "HGETALL %s", KEY_STATE);
if (reply) {
if (reply->type == REDIS_REPLY_ARRAY && reply->elements == 6) {
for(int i=0; i<reply->elements; i++) {
char *p = reply->element[i]->str;
if (! strcmp(HKEY_ALBUM, p)) {
*album = calloc(strlen(reply->element[i+1]->str)+1, sizeof(char));
strcpy(*album, reply->element[++i]->str);
} else if (! strcmp(HKEY_TRACK, p)) {
*track = atoi(reply->element[++i]->str);
} else if (! strcmp(HKEY_SONG_TIME_ELAPSED, p)) {
*song_time_elapsed = atof(reply->element[++i]->str);
}
}
}
rc = -1;
freeReplyObject(reply);
redisFree(r);
} else {
rc = -1;
}
return rc;
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_printf_width_1.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: iiasceri <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2018/03/22 15:27:45 by iiasceri #+# #+# */
/* Updated: 2018/03/22 15:27:46 by iiasceri ### ########.fr */
/* */
/* ************************************************************************** */
#include "libftprintf.h"
/*
** pre print width
*/
void ft_pre_print_width(t_com **com)
{
intmax_t width;
size_t len;
size_t new_width;
char *spaces;
char *result;
if ((*com)->width)
{
width = ft_atoi((*com)->width);
if (width < 0)
{
new_width = (size_t)-width;
len = (*com)->len;
spaces = ft_strnew_char_filled(new_width - len, ' ');
result = ft_strjoin((*com)->scroll, spaces);
free((*com)->scroll);
free(spaces);
(*com)->scroll = result;
if (new_width > len)
(*com)->len = (size_t)new_width;
}
else
ft_mod_add_spaces(*&com);
}
}
|
C
|
#include <stdio.h>
#include <cs50.h>
int main(void){
int numStudents = get_int("Number of students: ");
int numAssignments = get_int("Number of Assignments for each student: ");
int gradebook[numStudents][numAssignments];
string students[numStudents];
int averages [numStudents];
for(int i=0; i<numStudents; i++){
students[i] = get_string("Name of student %i: ",i);
printf("%s",students[i]);
}
int entry = get_int("Enter Grade: ");
printf("grade is: %i\n",entry);
} // end of main
|
C
|
#pragma once
#include "Vector3f.h"
/**
* This structure defines a vertex data.
*/
struct Vertex {
float position[3];
float color[3];
float normal[3];
float texCoord[3];
Vertex() {}
Vertex(Vector3f pos, Vector3f c, Vector3f n, Vector3f tex) {
position[0]=pos.x();
position[1]=pos.y();
position[2]=pos.z();
color[0]=c.x();
color[1]=c.y();
color[2]=c.z();
normal[0]=n.x();
normal[1]=n.y();
normal[2]=n.z();
texCoord[0]=tex.x();
texCoord[1]=tex.y();
texCoord[2]=tex.z();
}
};
|
C
|
#include <stdio.h>
#include <stdarg.h> //可变参数头文件
void change(int *num);
//可变参数函数
double avg(int num, ...);
int main()
{
int num = 9;
change(&num);
printf("%d\n", num);
printf("%.2lf", avg(4, 2,3,4,5));
return 0;
}
void change(int *num)
{
(*num)++;
}
double avg(int num, ...)
{
va_list vaList;
double sum = 0.0;
/* 为 num 个参数初始化 valist */
va_start(vaList, num);
/* 访问所有赋给 valist 的参数 */
for (int i = 0; i < num; ++i) {
sum += va_arg(vaList, int);
}
/* 清理为 valist 保留的内存 */
va_end(vaList);
return sum/num;
}
|
C
|
import java.util.*;
import java.lang.*;
public class roman{
public static void main(String aa[]){
int sum=0;
String s;
int b=0;
int pp=0;
int count=0;
int c[]=new int[100];
Scanner ss=new Scanner(System.in);
s=ss.next();
char a[]=s.toCharArray();
int l=s.length();
for(int i=0;i<l;i++){
switch(a[i]){
case'I':
b=1;
break;
case'V':
b=5;
break;
case'X':
b=10;
break;
}
c[pp]=b;
pp++;
count++;
}
pp=0;
int f=c[pp];
int ll=c[count-1];
if(f>ll||f==ll){
for(int i=0;i<count;i++){
sum=sum+c[i];
}
System.out.println(sum);
}
else{
for(int i=count-1;i>=0;i--){
sum=(-sum)-c[i];
}
System.out.println(sum);
}
}
}
|
C
|
//Find duplicate letters in a string
#include<stdio.h>
int main()
{
char a[100];
int i,j,count;
printf("Enter a string=");
scanf("%s",&a);
for(i=0;a[i+1]!='\0';i++)
{
if(a[i]!=-1)
{
count=1;
for(j=i+1;a[j]!='\0';j++)
{
if(a[i]==a[j])
{
count++;
a[j]=-1;
}
}
if(count>1)
printf("%c is appearing %d times\n",a[i],count);
}
}
return 0;
}
|
C
|
#include <stdio.h>
#include <string.h>
int main()
{
char str[1002] = {'\0'};
while (fgets(str, 1000, stdin)){
char *p = "poi";
char *q = str;
int count = 0;
q = strstr(str, p);
for (int i = 0; i < 334; i++){
if (q == NULL){
break;
}else{
q = strstr(q + 1, p);
count++;
}
}
printf("%d\n", count);
memset(str, 1002, '\0');
}
return 0;
}
|
C
|
#include <Python.h>
#include <SDL/SDL.h>
#include <SDL/SDL_opengl.h>
#define SCREEN_WIDTH 800
#define SCREEN_HEIGHT 600
#define SCREEN_BPP 32
#define NUM_QUADS 1
typedef struct point {
float x, y;
} point;
typedef struct rgb_color {
float r,g,b;
} rgb_color;
typedef struct quad {
point *center;
point *bottom_left;
point *top_right;
rgb_color *color;
} quad;
int initGL() {
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(0.0, SCREEN_WIDTH, SCREEN_HEIGHT, 0.0, 1.0, -1.0);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
GLenum error = glGetError();
if (error != GL_NO_ERROR) {
printf("Error initializing OpenGL: %s", gluErrorString(error));
return 1;
}
return 0;
}
void render(quad *quads, int size) {
glClear(GL_COLOR_BUFFER_BIT);
glLoadIdentity();
printf("Render called: %d\n", sizeof(quads));
int i;
for (i = 0; i < size; i++) {
printf("Render: %d\n", i);
// loop over the given quads and render each one
float cen_x = quads[i].center->x;
float cen_y = quads[i].center->y;
float left = quads[i].bottom_left->x;
float bot = quads[i].bottom_left->y;
float right = quads[i].top_right->x;
float top = quads[i].top_right->y;
rgb_color *color = quads[i].color;
glTranslatef(cen_x, cen_y, 0.0f);
// draw the quad
glBegin(GL_QUADS);
glColor3f(color->r, color->g, color->b);
glVertex2f(left, top);
glVertex2f(right, top);
glVertex2f(right, bot);
glVertex2f(left, bot);
glEnd();
}
printf("Done rendering\n");
SDL_GL_SwapBuffers();
}
int translate_quads(quad **quads, PyObject *pyobj) {
printf("Translating quads\n");
if (PySequence_Check(pyobj) == 0) {
// pass
}
int i;
int num_quads = PySequence_Size(pyobj);
*quads = malloc(sizeof(quad) * num_quads);
printf("Memory allocated: %d\n", sizeof(quad)*num_quads);
printf("Number of quads: %d\n", num_quads);
for (i = 0; i < num_quads; i++) {
printf("Parsing quad\n");
PyObject *py_quad = PySequence_GetItem(pyobj, i);
PyObject *py_center = PyObject_GetAttrString(py_quad, "center");
PyObject *py_bottom_left = PyObject_GetAttrString(py_quad, "bottom_left");
PyObject *py_top_right = PyObject_GetAttrString(py_quad, "top_right");
PyObject *py_color = PyObject_GetAttrString(py_quad, "color");
point *center, *bottom_left, *top_right;
rgb_color *color;
center = malloc(sizeof(point));
bottom_left = malloc(sizeof(point));
top_right = malloc(sizeof(point));
color = malloc(sizeof(rgb_color));
float *x1, *y1, *x2, *y2, *x3, *y3, *r, *g, *b;
PyArg_ParseTuple(py_center, "ff", &(center->x), &(center->y));
PyArg_ParseTuple(py_bottom_left, "ff", &(bottom_left->x), &(bottom_left->y));
PyArg_ParseTuple(py_top_right, "ff", &(top_right->x), &(top_right->y));
PyArg_ParseTuple(py_color, "fff", &(color->r), &(color->g), &(color->b));
printf("Stuff parsed\n");
printf("Center: %f %f\n", center->x, center->y);
quads[i]->center = center;
quads[i]->bottom_left = bottom_left;
quads[i]->top_right = top_right;
quads[i]->color = color;
}
printf("quad: %d\n", *quads);
return num_quads;
}
int main(int argc, char* argv[]) {
if (SDL_Init(SDL_INIT_EVERYTHING) < 0) {
printf("Failed to init SDL\n");
return 1;
}
if (SDL_SetVideoMode(SCREEN_WIDTH, SCREEN_HEIGHT, SCREEN_BPP, SDL_OPENGL) == NULL) {
printf("Failed to set video mode\n");
return 1;
}
if (initGL() == 1) {
printf("Failed to init OpenGL\n");
return 1;
}
SDL_WM_SetCaption("Exciting Things", NULL);
// set up the quads we will be rendering
/*quad quads[NUM_QUADS];
int i = 0;
point q1_center, q1_bl, q1_tr,
q2_center, q2_bl, q2_tr,
q3_center, q3_bl, q3_tr;
rgb_color color;
q1_center.x = 200; q1_center.y = 200;
q1_bl.x = -50.0f; q1_bl.y = -50.0f;
q1_tr.x = 50.0f; q1_tr.y = 50.0f;
color.r = 1.0f; color.g = 0.0f; color.b = 0.0f;
quads[0].center = q1_center;
quads[0].bottom_left = q1_bl;
quads[0].top_right = q1_tr;
quads[0].color = color;*/
// objects for running a python script
PyObject *script_module, *ret_obj, *mod_func, *args;
// pointer for array we will dump script results in
quad *quads;
int num_quads;
printf("Initializing Python\n");
Py_Initialize();
PySys_SetPath(".");
printf("Importing modules\n");
script_module = PyImport_ImportModule("scripts");
mod_func = PyObject_GetAttrString(script_module, "create_quads");
// this is where we call the python script
ret_obj = PyEval_CallObject(mod_func, NULL);
// translate and store quad objects
if (ret_obj == NULL) {
printf("Failed to retrieve quads\n");
return 1;
}
num_quads = translate_quads(&quads, ret_obj);
// run the main loop
int running = 1;
SDL_Event event;
while(running) {
while(SDL_PollEvent(&event)) {
if (event.type == SDL_QUIT) {
running = 0;
} else if (event.type == SDL_KEYDOWN) {
//pass
}
}
render(quads, num_quads);
}
free(quads);
Py_Finalize();
return 0;
}
|
C
|
//
#include <stdio.h>
int main (void)
{
int a,b;
printf ("input 2 whole numbers");
scanf("%d%d", &a,&b);
printf("a+b=%d+%d=",a,b,a+b);
printf("a+b=%d+%d=",a,b,a-b);
printf("a+b=%d+%d=",a,b,a*b);
}
|
C
|
#include <stdio.h>
/*
10. Um investidor está preocupado com o cambio
do dólar e necessita de um programa que o auxilie
a calcular a variação cambial entre dois dias consecutivos.
Implemente um programa que solicite dois valores de dólar
(preço) e informe a diferença absoluta e a diferença relativa entre eles.
dif_absoluta = val_ontem - val_hoje
dif_relativa = (dif_absoluta * 100) / val_ontem
*/
int main(){
float dolar_hoje, dolar_ontem, dif_absoluta, dif_relativa;
printf("Informe o valor do dolar no dia anterior: ");
scanf("%f", &dolar_ontem);
if(dolar_ontem == 0){
printf("Dolar do dia anterior precisa ser diferente de 0");
return 1;
}
printf("Informe o valor do dolar hoje: ");
scanf("%f", &dolar_hoje);
dif_absoluta = dolar_ontem - dolar_hoje;
dif_relativa = (dif_absoluta*100) / dolar_ontem;
printf("\nDiferenca absoluta: %f", dif_absoluta);
printf("\nDiferenca relativa: %f", dif_relativa);
printf("\nPressione qualquer tecla para sair do programa.");
scanf("%f", &dolar_hoje);
}
|
C
|
/**
* \fn void strupr(char *cadena)
* \brief Reemplaza los caracteres minuscula por mayusculas.
* \author Pose, Fernando Ezequiel.
* \date 2010.06.11
* \param Entrada de la palabra.
* \return No retorna.
*/
void strupr(char *cadena){
int i, len;
len = my_strlen(cadena);
for(i=0; i< len; i++){
if( *(cadena + i)>= 'a' && *(cadena + i) <= 'z') *(cadena + i ) -= 'a' - 'A';
}
}
|
C
|
/**
* \file Edge.h
*
* Contains all the instruction to operate with edges
*
* Created on: Dec 22, 2016
* Author: koldar
*/
#ifndef EDGE_H_
#define EDGE_H_
#include "hashtable.h"
#include "list.h"
#include <stdbool.h>
struct Node;
struct PredSuccGraph;
/**
* Represents a direct edge
*
* \dotfile edge01.dot
*/
typedef struct Edge {
struct Node* source;
struct Node* sink;
void* payload;
} Edge;
typedef list EdgeList;
typedef HT EdgeHT;
/**
* Creates an edge
*
* @param[in] source the source of the edge
* @param[in] sink the sink of the edge
* @param[in] label the label of the edge
* @return an edge in the heap. Be sure to clear it out with ::destroyEdge when not needed anymore
*/
Edge* initEdge(const struct Node* restrict source, const struct Node* restrict sink, const void* payload);
/**
* Clone an edge. Payload is copied by referend though.
*
* If you want to clone the payload as well, please use ::cloneEdgeWithPayload
* \note
* ::Edge::source, ::Edge::sink and ::Edge::payload are not cloned; only copied by reference
*
* @param[in] e the edge to clone
* @return a new copy of the edge
*/
Edge* cloneEdge(const Edge* e);
/**
* Clone an edge. Payload included
*
* \note
* ::Edge::source, ::Edge::sink are not cloned; only copied by reference
*
* @param[in] e the edge to clone
* @param[in] payloadCloner the function to use to clone the edge payload
* @return a new copy of the edge
*/
Edge* cloneEdgeWithPayload(const Edge* e, cloner payloadCloner);
/**
* Destroy an edge
*
* \warning
* The function <b>won't free</b> the memory for the soource nor the sink of the edges. It will simply remove the edge itself
*
* @param[in] e the edge to remove
*/
void destroyEdge(Edge* e);
/**
* Destroy an edge with the associated payload
*
* \warning
* The function <b>won't free</b> the memory for the source nor the sink of the edges. It will simply remove the edge itself
*
* @param[in] e the edge to remove
* @param[in] payloadDesturctor the function to use to destroy the payload
*/
void destroyEdgeWithPayload(Edge* e, destructor payloadDestructor);
/**
* \note
* Hash does not take into account payload at all
*
* @param[in] e the edge involved
* @return an hash representation of the edge \c e
*/
int getHashOfEdge(const Edge* e);
/**
* \note
* note that the edge will check only the source and the sink of the 2 edges, not the ::Edge::label!
*
* The function **won't check** the payload content, only the source and the sink of the edges.
* If you want to also check the payload, please use ::getEdgeCmpWithPayload
*
* @param[in] e1 the first edge. Can be NULL
* @param[in] e2 the second edge. Can be NULL
* @return
* \li true if the edges are equals;
* \li false otherwise
*/
bool getEdgeCmp(const Edge* e1, const Edge* e2);
/**
* Check that 2 edges are the same **and** with the same payload
*
* @param[in] e1 the first edge. Can be NULL
* @param[in] e2 the second edge. Can be NULL
* @param[in] payloadComparator the function to use to compare 2 payload edges
* @return
* \li true if the edges are equals (and with the same payload);
* \li false otherwise
*/
bool getEdgeCmpWithPayload(const Edge* e1, const Edge* e2, comparator payloadComparator);
/**
*
* Be sure to call ::free function to avoid memoty leak on the resutl!
*
* @param[in] e the edge to analyze
* @param[in] payloadStringify the function to use to print a string of the payload
* @return a newly allocated string representing the edge inside the heap.
*/
const char* getStringOfEdge(const Edge* e, stringify payloadStringigy);
/**
* retrieve the buffer popolated by the string representation of \c e
*
* @param[in] e the edge whose string representation we're interested in
* @param[inout] buffer the buffer that will accept the representation
* @return the number of characters we have consumed in the buffer (or pointer to '\0')
*/
int getBufferStringOfEdge(const Edge* e, char* buffer);
void storeEdgeInFile(FILE* f, const Edge* e, object_serializer payload);
Edge* loadEdgeFromFile(FILE* f, struct PredSuccGraph* g, object_deserializer edgeDeserializer);
/**
* Get the payload of the edge already casted
*
* @param[in] edge a point of ::Edge
* @param[in] type the type of the payload. example may be \c int, \c Foo
*/
#define getEdgePayloadAs(edge, type) ((type)(edge)->payload)
#endif /* EDGE_H_ */
|
C
|
#include <fcntl.h>
#include <gpiod.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#define COUNT 1000000
const char *NAME = "logger";
int main(int argc, char *argv[])
{
struct gpiod_chip *chip;
struct gpiod_line_bulk lines;
int dump_file;
unsigned int offsets[2] = {19, 20};
unsigned int values[2];
size_t iteration = 0;
char buf[COUNT];
int ret;
dump_file = open("/tmp/signal.dump", O_CREAT|O_WRONLY|O_TRUNC, 0666);
if (dump_file < 0) {
printf("Cant dump\n");
return -1;
}
chip = gpiod_chip_open("/dev/gpiochip0");
if (!chip) {
printf("GPIO not opened\n");
return -1;
}
ret = gpiod_chip_get_lines(chip, &offsets[0], 2, &lines);
if (ret < 0) {
printf("Lines not opened\n");
return -1;
}
gpiod_line_request_input(lines.lines[0], NAME);
gpiod_line_request_input(lines.lines[1], NAME);
gpiod_line_set_flags(lines.lines[0], GPIOD_LINE_REQUEST_FLAG_ACTIVE_LOW | GPIOD_LINE_REQUEST_FLAG_OPEN_DRAIN);
gpiod_line_set_flags(lines.lines[1], GPIOD_LINE_REQUEST_FLAG_ACTIVE_LOW | GPIOD_LINE_REQUEST_FLAG_OPEN_DRAIN);
while (true) {
ret = gpiod_line_get_value_bulk(&lines, values);
//values[0] = gpiod_line_get_value(lines.lines[0]);
//values[1] = gpiod_line_get_value(lines.lines[1]);
if (ret < 0) {
printf("Failed to get values\n");
return -1;
}
buf[iteration] = (values[0]) | (values[1]) << 1;
iteration++;
if (iteration == COUNT) {
break;
}
}
if (write(dump_file, &buf[0], COUNT) != COUNT) {
printf("Not all written\n");
}
return 0;
}
|
C
|
#include <stdio.h>
#include <unistd.h>
#include <sys/time.h>
#include "IPCServer.h"
extern int ultra_val[3];
char motor_pin[4];
void delay(int tt){
char tmpbuf[4];
sprintf(tmpbuf,"%d",tt);
strcat(motor_pin,",");
strcat(motor_pin,tmpbuf);
char *p;
p = strtok(motor_pin, ",");
*motor_pin=*p;
IPCServer(motor_pin);
strncpy(motor_pin, "", 3);
long pause;
clock_t now,then;
pause = tt*(CLOCKS_PER_SEC/1000);
now = then = clock();
while( (now-then) < pause )
now = clock();
}
void usercode(void)
{
int cnt;
while(1){
cnt+=1;
delay(1);
printf("--usercode--%d\n",cnt);
if (ultra_val[1]<10) {
motor_pin[0]='1';
motor_pin[1]='1';
motor_pin[2]='1';
motor_pin[3]='0';
}else if (ultra_val[1]>20)
{
motor_pin[0]='1';
motor_pin[1]='0';
motor_pin[2]='0';
motor_pin[3]='0';
delay(600);
}
}
}
|
C
|
#include<stdio.h>
long int fatorial();
int main(int argc, char const *argv[]){
int num = 20;
long int fat = 0;
fat = fatorial(num);
printf("%ld\n", fat);
return 0;
}
long int fatorial(int n){
long int f;
if (n==0)
return 1;
else
f = n * fatorial(n-1);
return f;
}
|
C
|
#ifndef _VEC3_H_
#define _VEC3_H_
typedef struct vec3 {
float x, y, z;
} vec3;
/**
* @brief Creates a new vec3 struct, populated with the given values. This
* function allocates space for the new vec3. If space cannot be allocated for
* this vec3, this function will immediately terminate the program.
*
* @param x the x component of this vec3.
* @param y the y component of this vec3.
* @param z the z component of this vec3.
* @return vec3* a pointer to the newly allocated vec3 struct.
*/
vec3 vec3_new(float x, float y, float z);
/**
* @brief Return the length of the given vec3.
*
* @param v a pointer to the vec3 struct whose length is desired.
* @return float the length of the given vec3.
*/
float vec3_length(vec3 v);
/**
* @brief Perform a scalar multiplication of the given vec3 and scalar value.
* The result of the scalar multiplication is stored in the vec3* result.
*
* @param result a pointer to a vec3 struct where the result of the scalar
* multiplication is stored. The vec3 struct must already be initialized.
* An uninitialized vec3 struct will result in undefined behavior.
* @param v a pointer to the vec3 struct to perform the scalar multiplication
* upon. This struct is not modified.
* @param scale a float scalar to multiply the given vec3 by.
* @return vec3* a pointer to the resultant struct. This is always the same
* pointer given as the parameter for result.
*/
vec3 vec3_scale(vec3 v, float scale);
/**
* @brief create a new vector with the same direction, scaled down so that
* vec3_length(v) returns 1.0.
*
* @param result a pointer to a vec3 struct where the result of the
* normalization is stored. The vec3 struct must already be initialized.
* An uninitialized vec3 struct will result in undefined behavior.
* @param v a pointer to the vec3 struct to normalize. This struct is not
* modified.
* @return vec3* a pointer to the resultant struct. This is always the same
* pointer given as the parameter for result.
*/
vec3 vec3_normalize(vec3 v);
/**
* @brief add two vec3 structs.
*
* @param result a pointer to a vec3 struct which contins the result of the
* addition. The vec3 struct must already be initialized. An
* uninitialized vec3 struct will result in undefined behavior.
* @param v1 a pointer to the left operand vec3 struct. This struct is not
* modified.
* @param v2 a pointer to the right operand vec3 struct. This struct is not
* modified.
* @return vec3* a pointer to the resultant struct. This is always the same
* pointer given as the parameter for result.
*/
vec3 vec3_add(vec3 v1, vec3 v2);
/**
* @brief subtract two vec3 structs.
*
* @param result a pointer to a vec3 struct which contins the result of the
* subtraction. The vec3 struct must already be initialized. An
* uninitialized vec3 struct will result in undefined behavior.
* @param v1 a pointer to the left operand vec3 struct. This struct is not
* modified.
* @param v2 a pointer to the right operand vec3 struct. This struct is not
* modified.
* @return vec3* a pointer to the resultant struct. This is always the same
* pointer given as the parameter for result.
*/
vec3 vec3_sub(vec3 v1, vec3 v2);
/**
* @brief Return the dot product of two vectors.
*
* @param v1 a vec3 struct pointer for the left side operand of the dot product.
* This struct is not modified.
* @param v2 a vec3 struct pointer for the right side operand of the dot product.
* This struct is not modified.
* @return float the result of the dot product of the two vec3 structs.
*/
float vec3_dot(vec3 v1, vec3 v2);
/**
* @brief Returns a random vec3 with a length of 1.0 or less. Each component
* of the vec3 is in the range [-1, 1], as long as the length of the vec3
* is 1.0 or less.
*
* @return vec3* a random vec3 with a length of 1.0 or less.
*/
vec3 vec3_random_in_unit_sphere();
/**
* @brief Returns a vec3 with each component taken to the power of gamma.
*
* @return vec3* a vec3 with each component taken to the power of gamma.
*/
vec3 vec3_gamma_correct(vec3 color, float gamma);
/**
* @brief Calculates the vec3 that would be reflected from a given ray and
* normal.
*
*/
vec3 vec3_reflect(vec3 v, vec3 normal);
#endif
|
C
|
#include <stdio.h>
int main(int argc, char** argv)
{
if (argc!=2) {
printf("Not 1 argument!");
return 0;
}
char* str=argv[1];
int length=0;
int x=0;
int a=1;
while(a==1)
{
if(str[x]=='\0')
a=2;
else{
length++;
}
x++;
}
int frequency=0;
int i=0;
while(i<length)
{
if(str[i]=='a')
frequency++;
i++;
}
printf("%d\n",frequency);
return 0;
}
|
C
|
#include <stdio.h>
main()
{
int c, sp;
sp = 0;
while ((c = getchar()) != EOF ){
if (c != ' '){
putchar(c);
sp = 0;
}
if (c == ' '){
if (sp == 0)
putchar(c);
sp = 1;
}
}
return 0;
}
|
C
|
#include <stdio.h>
int main(void)
{
char a[10] = "senthil";
char b[10] = "entslihk";
char ch;
unsigned int xor = 0;
int i = 0;
// Since XOR is cumulative. 2^3^2==3. So XOR the whole string and XOR it again to nullify then the remaining char is the extra one
while (ch = a[i++]) {
xor ^= ch;
}
i = 0;
while (ch = b[i++])
xor ^= ch;
printf("%c \n", xor);
}
|
C
|
#include <stdio.h>
#include <math.h>
#define s scanf
void p(){
unsigned char x=0;
float e;short c;signed char n,i; float u=0;
s("%f",&e);
if(e==0) return;
s("%hhu",&n);
for(i=0;i<n;i++){
s("%hi",&c);
u+=c;
}
printf("%.0f\n",ceil(u/e));
p();
}
int main() {
p();
return 0;
}
|
C
|
/* pqueue.c
* Implementation of a priority queue.
* Homework assigned 2/8/17
*/
#include "pqueue.h"
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <math.h>
#define INITIALCAPACITY 100
#define min(a, b) ((a < b) ? a : b)
Data makeData(Vertex *v, int weight) {
Data data = {v, weight};
return data;
}
// Your code here:
void swap(Data *a, Data *b) {
Data x = *a;
*a = *b;
*b = x;
}
typedef struct pqueue {
Data *data;
int length;
int capacity;
} pqueue;
int getDepth(PQueue q, int index) {
return log2(index) + 1;
}
int getLeftChild(Data *d, int length, int index) {
int value = index * 2 + 1;
if (value >= length) {
return -1;
} else {
return value;
}
}
int getRightChild(Data *d, int length, int index) {
int value = index * 2 + 2;
if (value >= length) {
return -1;
} else {
return value;
}
}
int getParent(PQueue q, int index) {
if (index == 0) {
return -1;
} else {
return (index - 1) / 2;
}
}
// Returns a newly allocated empty priority queue.
PQueue makeEmptyPQueue() {
PQueue newPQueue= (PQueue) malloc(sizeof(pqueue));
newPQueue->data = (Data*) malloc(sizeof(Data) * INITIALCAPACITY);
newPQueue->length = 0;
newPQueue->capacity = INITIALCAPACITY;
return newPQueue;
}
// Determines whether the priority queue is empty.
bool isEmpty(PQueue q) {
return q->length == 0;
}
void siftUp(PQueue q, int index) {
int parentIndex = getParent(q, index);
if (parentIndex != -1) {
if (q->data[parentIndex].weight > q->data[index].weight) {
swap(&q->data[parentIndex], &q->data[index]);
}
} else {
return;
}
siftUp(q, parentIndex);
}
// Adds an element to the priority queue.
void addToPQueue(PQueue q, Data d) {
if (q->length == q->capacity) {
// to be implemented: expanding arrays.
fprintf(stderr, "Attempted to add elements beyond capacity\n");
exit(1);
}
q->data[q->length] = d;
siftUp(q, q->length);
q->length += 1;
}
// Decreases the priority of a Data element of the priority queue.
void decreasePriority(PQueue q, Data d) {
for (int i = 0; i < q->length; i++) {
if (q->data[i].v == d.v) {
q->data[i] = d;
siftUp(q, i);
}
}
}
void siftDown(Data* data, int length, int index) {
int leftChildIndex = getLeftChild(data, length, index);
int rightChildIndex = getRightChild(data, length, index);
if (leftChildIndex == -1 && rightChildIndex == -1) {
return;
} else if (rightChildIndex == -1) {
if (data[0].weight > data[leftChildIndex].weight) {
swap(&data[0], &data[leftChildIndex]);
siftDown(data, length, leftChildIndex);
}
} else {
int minValueIndex = min(leftChildIndex, rightChildIndex);
if (data[0].weight > data[minValueIndex].weight) {
swap(&data[0], &data[minValueIndex]);
siftDown(data, length, minValueIndex);
}
}
}
// Returns min-weight element.
Data peekMin(PQueue q) {
return q->data[0];
}
// Removes and returns min-weight element.
Data removeMin(PQueue q) {
Data firstElem = q->data[0];
Data lastElem = q->data[q->length - 1];
q->data[0] = lastElem;
q->data[q->length - 1] = firstElem;
q->length -= 1;
siftDown(q->data, q->length, 0);
return firstElem;
}
// Returns the number of elements in the priority queue.
int pqLength(PQueue q) {
return q->length;
}
void freePQueue(PQueue q) {
free(q->data);
free(q);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <ctype.h>
#include <assert.h>
#include "linkedl.h"
#include "basecase.h"
#include "tokenize.h"
void helper_main(char cmd[]);
int
main(int argc, char** argv)
{
if (argc > 2) {
// return invalid inputs
printf("\n\ninvalid arguments to ./nush\n");
printf("usage: pass a script to run or give command line inputs\n");
exit(1);
}
char cmd[256];
char* line;
if (argc == 2) { // SCRIPT
FILE* script = fopen(argv[1], "r");
if (!script) {
printf("\n\nfopen of script failed!\n\n");
exit(0);
}
line = fgets(cmd, 256, script);
while(line) {
helper_main(line);
line = fgets(cmd, 256, script);
}
//printf("no lines left\n");
fclose(script);
}
// PROMPT
else {
while (1) {
printf("nush$ ");
fflush(stdout);
line = fgets(cmd, 256, stdin);
if(!line){
printf("\nuser indicated eof\n");
exit(0);
}
helper_main(line);
}
}
//printf("\nmade it to end of main \n");
return 0;
}
// execute
void helper_main(char line[]) {
assert(line);
// print_order(tokenize(cmd);
linkedl* tokens = reverse_and_free(tokenize(line));
char *args[length(tokens)];
// linkedl -> arr char pointers
int i = 0;
for (; tokens; tokens= tokens->rest) {
args[i] = malloc(strlen(tokens->head));
strcpy(args[i], tokens->head);
++i;
}
args[i] = NULL; // null terminate
base_case(args);
//for (long j = 0; j < length(tokens); ++j) {
// free(args[j]);
//}
free_linkedl(tokens);
}
|
C
|
#include <stdio.h>
#include <malloc.h>
#include <string.h>
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>
#define BUF_SIZE 80
#define SLEEP_TIME 5000
#define BUFFER_SIZE 256
#define STANDART_OUTPUT 1
#define CHECK_ERROR(status, mes)\
if (status != 0) {\
char buf[BUF_SIZE] = { 0 };\
strerror_r(status, buf, sizeof(buf));\
fprintf(stderr, "%s: %s\n", mes, buf);\
pthread_exit(NULL);\
}
typedef struct node{
char *string;
struct node *next;
pthread_mutex_t mutex;
} Node;
typedef struct list{
Node* head;
int size;
pthread_mutex_t mutex;
} List;
void swap(Node *a, Node *b){
char *tmp = a->string;
a->string = b->string;
b->string = tmp;
}
void sort(List* list){
Node* cur;
int i;
int status;
int flag = 1;
while(flag){
flag = 0;
cur = list->head;
while(cur->next != NULL){
status = pthread_mutex_lock(&(cur->mutex));
CHECK_ERROR(status, "pthread_mutex_lock");
status = pthread_mutex_lock(&(cur->next->mutex));
CHECK_ERROR(status, "pthread_mutex_lock");
if(strcmp(cur->string, cur->next->string) > 0){
swap(cur, cur->next);
flag = 1;
}
status = pthread_mutex_unlock(&(cur->next->mutex));
CHECK_ERROR(status, "pthread_mutex_unlock");
status = pthread_mutex_unlock(&(cur->mutex));
CHECK_ERROR(status, "pthread_mutex_unlock");
cur = cur->next;
}
}
}
void* func(void* param){
int status;
List* list = (List* )param;
while(1){
/* First way to avoid segmentation fault - see next comment why */
if (list->size > 0){
usleep(6000000);
sort(list);
}
/* Second way */
/* If we dont do this long usleep - get the segmentation fault in case of trying to acces non-allocated list->head->next */
// usleep(6000000);
// sort(list);
}
}
void add(List* list, char* str){
int status;
char *tmpStr = (char *)malloc(strlen(str) + 1);
if(tmpStr == NULL){
fprintf(stderr, "ERROR in malloc\n");
exit(1);
}
strcpy(tmpStr, str);
Node* newHead = (Node *)malloc(sizeof(Node));
if(newHead == NULL){
fprintf(stderr, "ERROR in malloc\n");
exit(1);
}
if(list->size > 0){
status = pthread_mutex_lock(&(list->head->mutex));
CHECK_ERROR(status, "pthread_mutex_lock");
}
status = pthread_mutex_init(&(newHead->mutex), NULL);
CHECK_ERROR(status, "pthread_mutex_init");
newHead->string = tmpStr;
newHead->next = list->head;
list->head = newHead;
list->size++;
if(list->size > 1){
status = pthread_mutex_unlock(&(list->head->next->mutex));
CHECK_ERROR(status, "pthread_mutex_unlock");
}
}
void output(List *list){
char* msg = "Entered strings:\n";
Node* cur = list->head;
write(STANDART_OUTPUT, msg, strlen(msg));
while(cur != NULL){
write(STANDART_OUTPUT, cur->string, strlen(cur->string));
cur = cur->next;
}
}
List* create_list(){
List* list = (List *)malloc(sizeof(List));
if(list == NULL){
fprintf(stderr, "ERROR in malloc\n");
exit(1);
}
list->head = NULL;
list->size = 0;
return list;
}
void free_list(List* list) {
Node* tmp = list->head;
Node* prev = NULL;
if (NULL == tmp) {
return;
}
while (tmp->next) {
prev = tmp;
tmp = tmp->next;
free(prev->string);
free(prev);
}
free(tmp->string);
free(tmp);
}
int main(int argc, char** argv) {
pthread_t thread;
int code;
char* msg = "Enter strings:\n";
char cur_symbol = '\n';
int i;
int threads_number;
if (argc != 2){
printf("Usage: [prog_name] [threads_number] \n");
return -1;
}
if ((threads_number = atoi(argv[1])) < 0){
printf("Invalid threads number \n");
return -1;
}
pthread_t* threads = (pthread_t *)malloc(threads_number * sizeof(pthread_t));
List* list = create_list();
code = pthread_mutex_init(&(list->mutex), NULL);
CHECK_ERROR(code, "pthread_mutex_init");
for (i = 0; i < threads_number; i++){
code = pthread_create(&threads[i], NULL, func, (void *)list);
CHECK_ERROR(code, "pthread_create");
}
write(STANDART_OUTPUT, msg, strlen(msg));
char buf[BUF_SIZE] = { 0 };
while(1){
if(fgets(buf, BUF_SIZE, stdin) == NULL){
fprintf(stderr, "fgets failed\n");
return -1;
}
if((buf[0] == '\n') && (cur_symbol == '\n')){
output(list);
continue;
}
cur_symbol = buf[strlen(buf) - 1];
add(list, buf);
}
free_list(list);
return 0;
}
/*
Сделать несколько сортирующих потоков
*/
|
C
|
/*
ID: lizhita1
LANG: C
TASK: cowtour
*/
#include <stdio.h>
#include <string.h>
#include <math.h>
#define MAXN 150
#define sqr(a) ((a)*(a))
int n, adj[MAXN][MAXN];
double loca[MAXN][2];
double dist[MAXN][MAXN];
int main() {
FILE *fin = fopen("cowtour.in", "r");
fscanf(fin, "%d", &n);
for (int i=0; i<n; ++i)
fscanf(fin, "%lf%lf", &loca[i][0], &loca[i][1]);
char ch;
fscanf(fin, "%c", &ch);
for (int i=0; i<n; ++i) {
for (int j=0; j<n; ++j) {
fscanf(fin, "%c", &ch);
adj[i][j] = (ch=='1');
if (adj[i][j])
dist[i][j] = sqrt(sqr(loca[i][0]-loca[j][0])+sqr(loca[i][1]-loca[j][1]));
else
dist[i][j] = -1;
}
fscanf(fin, "%c", &ch);
}
fclose(fin);
for (int k=0; k<n; ++k)
for (int i=0; i<n; ++i)
if (dist[i][k]>0)
for (int j=0; j<n; ++j)
if (i!=j && dist[k][j]>0 && (dist[i][j]<0 || dist[i][k]+dist[k][j]<dist[i][j]))
dist[i][j] = dist[i][k]+dist[k][j];
/*
for (int i=0; i<n; ++i) {
for (int j=0; j<n; ++j)
printf("%.6f ", dist[i][j]);
printf("\n");
}
*/
double ans = -1;
for (int i=0; i<n; ++i)
for (int j=0; j<n; ++j)
if (i!=j && dist[i][j]<0) {
double max1 = 0;
for (int k=0; k<n; ++k)
if (dist[i][k]>0 && dist[i][k]>max1)
max1 = dist[i][k];
double max2 = 0;
for (int k=0; k<n; ++k)
if (dist[k][j]>0 && dist[k][j]>max2)
max2 = dist[k][j];
double line = sqrt(sqr(loca[i][0]-loca[j][0])+sqr(loca[i][1]-loca[j][1]));
if (ans<0 || line+max1+max2<ans)
ans = line+max1+max2;
}
for (int i=0; i<n; ++i)
for (int j=0; j<n; ++j)
if (i!=j && dist[i][j]>0 && dist[i][j]>ans)
ans = dist[i][j];
FILE *fout = fopen("cowtour.out", "w");
fprintf(fout, "%.6f\n", ans);
fclose(fout);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <sys/types.h>
#include <dirent.h>
#include "tiny-AES-c/aes.h"
#ifdef AES256
#define AESBYTES 32
#elif defined(AES192)
#define AESBYTES 24
#elif defined(AES128)
#define AESBYTES 16
#else
#error Must define AES SIZE MACRO
#endif
#define ARRAY_SIZE(array) (sizeof(array)/sizeof(array[0]))
#define PRINT_TITLE(title) \
printf("\n%s %s %s\n",\
&"::::::::::::::::::::::::::::::::::::::::"[(strlen(title)/2)],\
title,\
&"::::::::::::::::::::::::::::::::::::::::"[(strlen(title)/2)])
#define TERMINATE_EX(error_msg, subject) { \
fprintf(stderr, "CENC FATAL: LINE %d :: %s :: %s\n", __LINE__, subject, error_msg); \
exit(EXIT_FAILURE); \
}
#define TERMINATE(error_msg) TERMINATE_EX(error_msg, "STRERROR")
struct file_array {
char** paths;
int cnt;
};
struct pack {
unsigned char* buffer;
long size;
};
static void parse_files(const char* const path_arg,
void(* const clbk)(const char*, const char*, void*),
void* const user_data)
{
int path_len = strlen(path_arg);
char path[path_len + 1];
strcpy(path, path_arg);
if (path[path_len - 1] == '/')
path[--path_len] = '\0';
DIR* const dirp = opendir(path);
if (dirp == NULL) {
FILE* const file = fopen(path, "rb");
if (file != NULL) {
fclose(file);
char tmp[path_len + 1];
strcpy(tmp, path);
char* const slashaddr = strrchr(tmp, '/');
if (slashaddr != NULL) {
*slashaddr = '\0';
clbk(tmp, slashaddr + 1, user_data);
} else {
clbk(".", tmp, user_data);
}
return;
} else {
TERMINATE_EX(strerror(errno), path);
}
}
struct dirent* direntp;
while ((direntp = readdir(dirp)) != NULL) {
if (direntp->d_type == DT_REG) {
clbk(path, direntp->d_name, user_data);
} else if (direntp->d_type == DT_DIR &&
(strcmp(direntp->d_name, ".") != 0) &&
(strcmp(direntp->d_name, "..") != 0)) {
char subdir[strlen(path) + strlen(direntp->d_name) + 2];
sprintf(subdir, "%s/%s", path, direntp->d_name);
parse_files(subdir, clbk, user_data);
}
}
closedir(dirp);
}
static void get_files_clbk(const char* const dirpath,
const char* const filename,
void* const user_data)
{
struct file_array* const fa = (struct file_array*)user_data;
const int idx = fa->cnt++;
fa->paths = realloc(fa->paths, sizeof(char*) * fa->cnt);
if (fa->paths == NULL)
TERMINATE(strerror(errno));
/* / */
const int pathlen = strlen(dirpath) + 1 + strlen(filename);
fa->paths[idx] = malloc(pathlen + 1);
if (fa->paths[idx] == NULL)
TERMINATE(strerror(errno));
sprintf(fa->paths[idx], "%s/%s", dirpath, filename);
fa->paths[idx][pathlen] = '\0';
}
static void init_file_array(const char* const* const paths,
const int npaths,
struct file_array* const fa)
{
fa->cnt = 0;
fa->paths = NULL;
PRINT_TITLE("FILE ARRAY");
printf("Fetching files... ");
fflush(stdout);
for (int i = 0; i < npaths; ++i)
parse_files(paths[i], get_files_clbk, fa);
printf("%d files fetched!\n", fa->cnt);
}
static void terminate_file_array(struct file_array* const fa)
{
for (int i = 0; i < fa->cnt; ++i)
free(fa->paths[i]);
free(fa->paths);
}
static long get_file_size(FILE* const file)
{
fseek(file, 0, SEEK_END);
long size = ftell(file);
fseek(file, 0, SEEK_SET);
return size;
}
static void init_pack(const struct file_array* const fa,
struct pack* const pack)
{
PRINT_TITLE("BINARY PACKAGE");
pack->size = 0;
pack->buffer = NULL;
printf("Copying files content to package buffer / Creating cenc_map.c... ");
fflush(stdout);
FILE* const cencmapfile = fopen("cenc_map.c", "w");
fprintf(cencmapfile,
"#include \"cenc_map.h\"\n\n"
"const struct cenc_map cenc_map[%d] = {\n", fa->cnt);
for (int i = 0; i < fa->cnt; ++i) {
FILE* const file = fopen(fa->paths[i], "rb");
if (file == NULL)
TERMINATE_EX(strerror(errno), fa->paths[i]);
const long size = get_file_size(file);
pack->buffer = realloc(pack->buffer, pack->size + size);
if (pack->buffer == NULL)
TERMINATE(strerror(errno));
fprintf(cencmapfile, "\t{ \"%s\", %ld, %ld },\n",
fa->paths[i], pack->size, size);
pack->size += fread(&pack->buffer[pack->size], 1, size, file);
fclose(file);
}
fprintf(cencmapfile, "};");
fclose(cencmapfile);
printf("Done!\n");
printf("Unencrypted package size: %ld bytes\n", pack->size);
}
static void terminate_pack(struct pack* const pack)
{
free(pack->buffer);
}
static void write_pack_to_file(const struct pack* const pack,
const char* const filename)
{
FILE* const file = fopen(filename, "wb");
if (file == NULL)
TERMINATE(strerror(errno));
printf("Writing file: %s... ", filename);
fflush(stdout);
fwrite(pack->buffer, sizeof(unsigned char), pack->size, file);
printf("Done!\n");
fclose(file);
}
static void get_aes_keys(unsigned char* const key, unsigned char* const iv)
{
FILE* const aes_keys_file = fopen("aes_keys.txt", "rt");
if (!aes_keys_file)
TERMINATE_EX(strerror(errno), "aes_keys.txt");
int size = 0;
char c;
printf("AES Key: ");
while (size < 33 && (c = fgetc(aes_keys_file)) != '\n') {
printf("%.2X ", (unsigned char)c);
key[size++] = c;
}
printf("\n");
if (size != AESBYTES) {
fprintf(stderr, "AES Key incompatible size: %d bytes\n", size);
TERMINATE("Couldnt get AES Keys");
}
printf("AES Key size: %d\n", size);
size = 0;
printf("IV Key: ");
while (size < 17 && (c = fgetc(aes_keys_file)) != '\n') {
printf("%.2X ", (unsigned char)c);
iv[size++] = c;
}
printf("\n");
if (size != 16) {
fprintf(stderr, "AES Key incompatible size: %d bytes\n", size);
TERMINATE("Couldn`t get AES Keys");
}
printf("IV Key size: %d\n", size);
fclose(aes_keys_file);
}
static void encrypt_pack(struct pack* const pack)
{
PRINT_TITLE("Encrypting data pack");
unsigned char key[32];
unsigned char iv[16];
printf("Fetching AES Keys...\n");
get_aes_keys(key, iv);
struct AES_ctx ctx;
AES_init_ctx_iv(&ctx, key, iv);
AES_CTR_xcrypt_buffer(&ctx, pack->buffer, pack->size);
}
int main(const int argc, const char* const* const argv)
{
PRINT_TITLE("CENC - C FILE ENCRYPTER VERSION 0.1 BY RAFAEL MOURA (DHUSTKODER)");
if (argc < 2) {
printf("Usage: %s <files and directories to encrypt>\n", argv[0]);
return EXIT_SUCCESS;
}
struct file_array fa;
struct pack pack;
init_file_array(argv + 1, argc - 1, &fa);
init_pack(&fa, &pack);
terminate_file_array(&fa);
write_pack_to_file(&pack, "unencrypted.bin");
encrypt_pack(&pack);
write_pack_to_file(&pack, "encrypted.bin");
terminate_pack(&pack);
return EXIT_SUCCESS;
}
|
C
|
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <glib.h>
#include "server/clients.h"
#include "proto/proto.h"
GSList *clients;
pthread_mutex_t clients_lock;
pthread_mutexattr_t lock_attr;
void _broadcast_message(char *message)
{
GString *msg_term = g_string_new(message);
g_string_append(msg_term, STR_MESSAGE_END);
pthread_mutex_lock(&clients_lock);
GSList *curr = clients;
while (curr != NULL) {
ChatClient *participant = curr->data;
int sent = 0;
int to_send = strlen(msg_term->str);
char *marker = msg_term->str;
while (to_send > 0 && ((sent = write(participant->sock, marker, to_send)) > 0)) {
to_send -= sent;
marker += sent;
}
curr = g_slist_next(curr);
}
pthread_mutex_unlock(&clients_lock);
g_string_free(msg_term, TRUE);
}
void
clients_init(void)
{
// initialise recursive mutex
pthread_mutexattr_init(&lock_attr);
pthread_mutexattr_settype(&lock_attr, PTHREAD_MUTEX_RECURSIVE);
pthread_mutex_init(&clients_lock, &lock_attr);
}
ChatClient*
clients_new(struct sockaddr_in client_addr, int socket)
{
ChatClient *client = malloc(sizeof(ChatClient));
client->ip = strdup(inet_ntoa(client_addr.sin_addr));
client->port = ntohs(client_addr.sin_port);
client->sock = socket;
client->nickname = NULL;
return client;
}
void
clients_add(ChatClient *client)
{
pthread_mutex_lock(&clients_lock);
clients = g_slist_append(clients, client);
pthread_mutex_unlock(&clients_lock);
}
void
clients_print_total(void)
{
pthread_mutex_lock(&clients_lock);
printf("Connected clients: %d\n", g_slist_length(clients));
pthread_mutex_unlock(&clients_lock);
}
void
clients_register(ChatClient *client, char *nickname)
{
client->nickname = strdup(nickname);
GString *msg = g_string_new("--> ");
g_string_append(msg, nickname);
g_string_append(msg, " has joined the conversation.");
_broadcast_message(msg->str);
g_string_free(msg, TRUE);
}
void
clients_broadcast_message(char *from, char *message)
{
GString *msg = g_string_new(from);
g_string_append_printf(msg, ": %s", message);
_broadcast_message(msg->str);
g_string_free(msg, TRUE);
}
void
clients_end_session(ChatClient *client)
{
// send to all clients
GString *msg = g_string_new("<-- ");
g_string_append(msg, client->nickname);
g_string_append(msg, " has left the conversation.");
_broadcast_message(msg->str);
g_string_free(msg, TRUE);
pthread_mutex_lock(&clients_lock);
GSList *curr = clients;
while (curr != NULL) {
if (curr->data == client) {
clients = g_slist_remove_link(clients, curr);
free(client->ip);
free(client->nickname);
close(client->sock);
free(client);
break;
}
curr = g_slist_next(curr);
}
pthread_mutex_unlock(&clients_lock);
clients_print_total();
}
|
C
|
#include "oled.h"
#include "s3c24xx.h"
#include "gpio_spi.h"
#include "oledfont.h"
static void OLED_Set_DC(unsigned char val)
{
if (val)
GPGDAT |= (1<<4);
else
GPGDAT &= ~(1<<4);
}
static void OLED_Set_CS(unsigned char val)
{
if (val)
GPFDAT |= (1<<1);
else
GPFDAT &= ~(1<<1);
}
static void OLED_Write_Cmd(unsigned char cmd)
{
OLED_Set_DC(0); // Send Command
OLED_Set_CS(0); // Chip Selection the OLED
SPI_Send_Byte(cmd);
OLED_Set_CS(1); // Un-Selection the OLED
OLED_Set_DC(1); // Send
}
static void OLED_Write_Data(unsigned char data)
{
OLED_Set_DC(1); // Send data
OLED_Set_CS(0); // Chip Selection the OLED
SPI_Send_Byte(data);
OLED_Set_CS(1); // Un-Selection the OLED
OLED_Set_DC(1); // Send
}
static void OLED_Set_Page_Addr_Mode(void)
{
OLED_Write_Cmd(0x20);
OLED_Write_Cmd(0x02);
}
static void OLED_Clear(void)
{
int page, col, i;
for (page = 0; page < 8; page++)
{
OLED_Set_Pos (page, 0);
for (i = 0; i < 128; i++)
OLED_Write_Data (0);
}
}
void OLED_Init(void)
{
/* Send Command to Oled, Let it init */
OLED_Write_Cmd (0xAE); /*display off*/
OLED_Write_Cmd (0x00); /*set lower column address*/
OLED_Write_Cmd (0x10); /*set higher column address*/
OLED_Write_Cmd (0x40); /*set display start line*/
OLED_Write_Cmd (0xB0); /*set page address*/
OLED_Write_Cmd (0x81); /*contract control*/
OLED_Write_Cmd (0x66); /*128*/
OLED_Write_Cmd (0xA1); /*set segment remap*/
OLED_Write_Cmd (0xA6); /*normal / reverse*/
OLED_Write_Cmd (0xA8); /*multiplex ratio*/
OLED_Write_Cmd (0x3F); /*duty = 1/64*/
OLED_Write_Cmd (0xC8); /*Com scan direction*/
OLED_Write_Cmd (0xD3); /*set display offset*/
OLED_Write_Cmd (0x00);
OLED_Write_Cmd (0xD5); /*set osc division*/
OLED_Write_Cmd (0x80);
OLED_Write_Cmd (0xD9); /*set pre-charge period*/
OLED_Write_Cmd (0x1f);
OLED_Write_Cmd (0xDA); /*set COM pins*/
OLED_Write_Cmd (0x12);
OLED_Write_Cmd (0xdb); /*set vcomh*/
OLED_Write_Cmd (0x30);
OLED_Write_Cmd (0x8d); /*set charge pump enable*/
OLED_Write_Cmd (0x14);
OLED_Set_Page_Addr_Mode();
OLED_Clear();
OLED_Write_Cmd (0xAF); /*display ON*/
}
void OLED_Set_Pos(int page, int col)
{
OLED_Write_Cmd (0xB0 + page); // Set Page Start Address for Page Addressing Mode
OLED_Write_Cmd (col & 0xf); // Set Lower Column Start Address for Page Addressing Mode
OLED_Write_Cmd (0x10 + (col >> 4)); // Set Higher Column Start Address for Page Addressing Mode
}
void OLED_Put_char(int page, int col, char c)
{
int i;
// Get Matrix
const unsigned char *dots = oled_asc2_8x16[c - ' '];
// Send to OLED
OLED_Set_Pos(page, col);
for (i = 0; i < 8; i++)
OLED_Write_Data(dots[i]);
OLED_Set_Pos(page + 1, col);
for (i = 0; i < 8; i++)
OLED_Write_Data(dots[i + 8]);
}
/*
* page --- 0 ~ 7
* col --- 0 ~ 127
* str --- 8 x 16 pixels
*/
void OLED_Print(int page, int col, char *str)
{
int i = 0;
while (str[i])
{
OLED_Put_char(page, col, str[i]);
col += 8;
if (col > 127) {
col = 0;
page += 2;
}
i++;
}
}
void OLED_Clear_Page(int page)
{
int i;
OLED_Set_Pos (page, 0);
for (i = 0; i < 128; i++)
OLED_Write_Data (0);
OLED_Set_Pos (page + 1, 0);
for (i = 0; i < 128; i++)
OLED_Write_Data (0);
}
|
C
|
/*
Name: find-largest-word.c
Date: July 6, 2020
Description: Find the smallest and largest words
the way you'd find them in the dictionary
*/
#include <stdio.h>
#include <string.h>
#include <stdlib.h> // malloc
#include <stdbool.h> // bool
#include <ctype.h> // isalpha
#define MAX_WORD_LENGTH ((size_t)20 + 1)
void remove_new_line(char *word) {
char *p = strchr(word, '\n');
if (p != NULL) {
*p = '\0';
}
}
bool is_word_alpha(const char *word) {
for (int i = 0; i < strlen(word); i++) {
if (!isalpha(word[i]))
return false;
}
return true;
}
int main(int argc, char *argv[]) {
char smallest_word[MAX_WORD_LENGTH], largest_word[MAX_WORD_LENGTH];
char *word = malloc(MAX_WORD_LENGTH); // heap
// OR *word[MAX_WORD_LENGTH] // stack
if (word == NULL) {
perror(argv[0]); // argv[0] = file name
exit(EXIT_FAILURE); // 1
}
// Get a word (1st run)
printf("Enter a word: ");
fgets(word, MAX_WORD_LENGTH, stdin);
remove_new_line(word);
// copy word into smallest_word and largest_word
strcpy(smallest_word, word);
strcpy(largest_word, word);
do {
// Get the word (continues)
printf("Enter a word: ");
if (fgets(word, MAX_WORD_LENGTH, stdin) == NULL) {
if (ferror(stdin)) {
perror(argv[0]);
}
exit(ferror(stdin) ? EXIT_FAILURE : EXIT_SUCCESS);
}
remove_new_line(word);
// if word is smaller than smallest_word
if (strcmp(word, smallest_word) < 0 && is_word_alpha(word)) {
strcpy(smallest_word, word);
}
// if word is bigger than largest_word
else if (strcmp(word, largest_word) > 0 && is_word_alpha(word)) {
strcpy(largest_word, word);
}
} while (strlen(word) != 4 + 1); //+1 for \0
printf("\nSmallest word: %s", smallest_word);
printf("Largest word: %s", largest_word);
free(word); // free the malloc
return 0;
}
|
C
|
/** @file demo.c
@author Ollie Chick (och26) and Leo Lloyd (lll28)
@brief Demo module - used to display information before the game starts.
*/
#include <stdbool.h>
#include "system.h"
#include "pio.h"
#include "pacer.h"
#include "tinygl.h"
#include "button.h"
#include "../fonts/font5x7_1.h"
#include "display_bitmap.h"
/* Time in seconds before the arrow is displayed. */
#define TIME_BEFORE_ARROW 15
/* Bitmap of the arrow pointing to the button. */
static const uint8_t arrow[] =
{
4, 14, 21, 4, 4
// |631 |
// |4268421|
// |....@..|
// |...@@@.|
// |..@.@.@|
// |....@..|
// |....@..|
};
/** Plays the demo and returns when the button is pressed. */
void play_demo (void)
{
pacer_init (PACER_RATE);
tinygl_text("Tic-tac-toe! ");
uint16_t ticks_before_scene_change = (PACER_RATE * TIME_BEFORE_ARROW);
uint16_t ticker = 0;
while (1) {
pacer_wait();
button_update(); //poll button
tinygl_update(); //refresh screen
/* If button is pushed, return (skip the demo). */
if(button_push_event_p (BUTTON1))
{
tinygl_clear();
tinygl_update();
return;
}
/* After the preset time, display the arrow. */
if (ticker == ticks_before_scene_change) {
tinygl_clear();
set_display(arrow);
}
ticker++;
}
}
|
C
|
#include<stdio.h>
int main(){
int arr[3][5];
int value = 0;
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 5; j++) {
arr[i][j] = i * 10 + j;
}
}
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 5; j++) {
printf("arr[%d][%d] = %d\n", i, j, arr[i][j]);
}
}
return 0;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.