language
large_stringclasses 1
value | text
stringlengths 9
2.95M
|
---|---|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define C_OK 0
#define C_NOK -1
#define MAX_STR 64
typedef struct {
char title[MAX_STR];
char author[MAX_STR];
int year;
} BookType;
typedef struct Node {
BookType *book;
struct Node *next;
} NodeType;
typedef struct {
NodeType *head;
NodeType *tail;
} ListType;
int initBook(BookType**);
void initList(ListType*);
void addByTitle(ListType*, BookType*);
void addByYear(ListType*, BookType*);
void copyList(ListType*, ListType*);
void copyByYear(ListType*, ListType*);
void delAuthor(ListType*, char*);
void printList(ListType*);
void cleanupList(ListType*);
void cleanupData(ListType*);
int main(){
ListType booksByTitle;
ListType booksByYear;
ListType tmpList;
BookType *newBook;
char author[MAX_STR];
initList(&booksByTitle);
initList(&booksByYear);
initList(&tmpList);
while (initBook(&newBook) != -1) {
addByTitle(&booksByTitle, newBook);
}
printf("\n*** BOOK LIST BY TITLE ***\nBOOK LIST:\n");
printList(&booksByTitle);
copyList(&booksByTitle, &tmpList);
printf("ENTER BOOK AUTHOR TO DELETE: ");
fgets(author, sizeof(author), stdin);
printf("%s", author);
author[strlen(author)-1] = '\0';
delAuthor(&tmpList, author);
printf("\n*** BOOK LIST BY TITLE (UNALTERED) ***\nBOOK LIST:\n");
printList(&booksByTitle);
printf("\n*** TEMP LIST BY TITLE (ALTERED) ***\nBOOK LIST:\n");
printList(&tmpList);
copyByYear(&booksByTitle, &booksByYear);
printf("\n*** BOOK LIST BY TITLE ***\nBOOK LIST:\n");
printList(&booksByTitle);
printf("\n*** BOOK LIST BY YEAR ***\nBOOK LIST:\n");
printList(&booksByYear);
cleanupData(&booksByTitle);
cleanupList(&booksByTitle);
cleanupList(&tmpList);
cleanupList(&booksByYear);
return C_OK;
}
/*
Function: initBook
Purpose: returns a new book
Parameters:
out: book
return: success or failure
*/
int initBook(BookType **book){
char booktitle[MAX_STR];
char bookauthor[MAX_STR];
char numberstring[MAX_STR];
int bookyear;
printf("Enter book title: ");
fgets(booktitle, sizeof(booktitle), stdin);
booktitle[strlen(booktitle)-1] = '\0';
if (strcmp(booktitle, "end") == 0)
return C_NOK;
printf("Enter book author: ");
fgets(bookauthor, sizeof(bookauthor), stdin);
bookauthor[strlen(bookauthor)-1] = '\0';
printf("Enter book year: ");
fgets(numberstring, sizeof(numberstring), stdin);
numberstring[strlen(numberstring)-1] = '\0';
sscanf(numberstring, "%d", &bookyear);
// If the book year is negative, it is set to year 0.
if(bookyear < 0){
bookyear = 0;
}
*book = malloc(sizeof(BookType));
strcpy((*book)->title, booktitle);
strcpy((*book)->author, bookauthor);
(*book)->year = bookyear;
return C_OK;
}
/*
Function: initList
Purpose: initializes fields of a given list
Parameters:
out: list
return: none
*/
void initList(ListType *list){
list->head = NULL;
list->tail = NULL;
}
/*
Function: addByTitle
Purpose: adds a new book to the list in ascending alphabetical order
Parameters:
inout: list
in: newBook
return: none
*/
void addByTitle(ListType *list, BookType *newBook){
NodeType* tmpNode = malloc(sizeof(NodeType));
NodeType* currNode = list->head;
NodeType* prevNode = NULL;
tmpNode->book = newBook;
tmpNode->next = NULL;
while (currNode != NULL) {
if (strcmp(newBook->title,currNode->book->title) < 0)
break;
prevNode = currNode;
currNode = currNode->next;
}
if (prevNode == NULL) {
list->head = tmpNode;
}
else {
prevNode->next = tmpNode;
}
tmpNode->next = currNode;
if(tmpNode->next == NULL){
list->tail = tmpNode;
}
}
/*
Function: addByYear
Purpose: adds a new book to the list in descending order by year
Parameters:
inout: list
in: newBook
return: none
*/
void addByYear(ListType *list, BookType *newBook){
NodeType* tmpNode = malloc(sizeof(NodeType));
NodeType* currNode = list->head;
NodeType* prevNode = NULL;
tmpNode->book = newBook;
tmpNode->next = NULL;
while (currNode != NULL) {
if (newBook->year > currNode->book->year)
break;
prevNode = currNode;
currNode = currNode->next;
}
if (prevNode == NULL) {
list->head = tmpNode;
}
else {
prevNode->next = tmpNode;
}
tmpNode->next = currNode;
if(tmpNode->next == NULL){
list->tail = tmpNode;
}
}
/*
Function: copyList
Purpose: adds each book in the src list to the dsc list, in ascending order by title
Parameters:
in: src
inout: dest
return: none
*/
void copyList(ListType *src, ListType *dest){
NodeType *sourcenode = src->head;
while(sourcenode != NULL){
addByTitle(dest, sourcenode->book);
sourcenode = sourcenode->next;
}
}
/*
Function: copyByYear
Purpose: adds each book in the src list to the dsc list, in descending order by year
Parameters:
in: src
inout: dest
return: none
*/
void copyByYear(ListType *src, ListType *dest){
NodeType *sourcenode = src->head;
while(sourcenode != NULL){
addByYear(dest, sourcenode->book);
sourcenode = sourcenode->next;
}
}
/*
Function: delAuthor
Purpose: deletes all books by the author specified (name) from list
Parameters:
inout: list
in: name
return: none
*/
void delAuthor(ListType *list, char *name){
NodeType *currNode = list->head;
NodeType *prevNode = NULL;
while(currNode != NULL && (strcmp(currNode->book->author, name) == 0)){
list->head = currNode->next;
free(currNode);
currNode = list->head;
}
while(currNode != NULL){
while(currNode != NULL && (strcmp(currNode->book->author, name) != 0)){
prevNode = currNode;
currNode = currNode->next;
}
if(currNode == NULL)
break;
prevNode->next = currNode->next;
if(prevNode->next == NULL)
list->tail = prevNode;
free(currNode);
currNode = prevNode->next;
}
}
/*
Function: printList
Purpose: prints all the books contained in list and denotes what the head/tail of the list is
Parameters:
out: list
return: none
*/
void printList(ListType *list){
NodeType* currNode = list->head;
if(currNode == NULL){
printf("-- THE BOOK LIST IS EMPTY\n");
printf("HEAD is: -- NULL\n");
printf("TAIL is: -- NULL\n");
}
else{
while(currNode != NULL){
printf("-- %45s by %15s, Yr: %1d\n", currNode->book->title, currNode->book->author, currNode->book->year);
currNode = currNode->next;
}
printf("HEAD is: -- %50s by %15s, Yr: %1d\n", list->head->book->title, list->head->book->author, list->head->book->year);
printf("TAIL is: -- %50s by %15s, Yr: %1d\n", list->tail->book->title, list->tail->book->author, list->tail->book->year);
}
}
/*
Function: cleanupList
Purpose: frees the memory associated with the nodes in the list
Parameters:
out: list
return: none
*/
void cleanupList(ListType *list){
NodeType *currNode, *nextNode;
currNode = list->head;
while (currNode != NULL) {
nextNode = currNode->next;
free(currNode);
currNode = nextNode;
}
}
/*
Function: cleanupData
Purpose: frees the memory associated with the books in the list
Parameters:
out: list
return: none
*/
void cleanupData(ListType* list){
NodeType *currNode = list->head;
while (currNode != NULL) {
free(currNode->book);
currNode = currNode->next;
}
}
|
C
|
/* Created: 2020/09/03 21:35:04 by Preposterone */
/* Updated: 2020/09/03 21:55:10 by Preposterone */
#include "ft_list.h"
void ft_list_clear(t_list *begin_list, void (*free_fct)(void *))
{
t_list *temp;
while (begin_list)
{
temp = begin_list;
begin_list = begin_list->next;
free_fct(temp->data);
free(temp);
}
}
|
C
|
#ifndef __GEOMETRY_H__
#define __GEOMETRY_H__
#define EPSILON (0.00001)
#include <math.h>
/*
* Les couleurs en coordonnées RGB
*/
typedef struct scolor {
unsigned char r, g, b; // traduire unsigned char par entier <= 255
} color;
/*
* Point et vecteur sont deux objets différents mais ils sont tous
* représentables par trois coordonnées dans l'espace
*/
typedef struct spoint {
double x, y, z;
} point, vector;
/*
* Structure représentant une facette
*/
typedef struct sfacet {
point a, b, c;
double k; // coefficient de réflexion
color cp;
vector n;
char* name;
} facet;
/*
* Structure représentant un rayon.
* Le sens du vecteur donne la direction du rayon.
*/
typedef struct sray {
point o;
vector v;
int reflexions;
} ray;
/*
* Ce modèle de scène est celui utilisé par libimgsdl.h.
* Une source de lumière est ponctuelle et possède une couleur propre.
* width et height sont les tailles de l'image rendue.
* nbPoints et nbFacets sont les tailles des vecteur points et facets.
* obs est la position de l'observateur.
* screenA et screenB aident à définir la position et l'orientation de l'écran.
*/
typedef struct ssource {
point p;
color cp;
} source;
typedef struct sscene {
color back;
int width, height, nbPoints, nbFacets;
point obs, screenA, screenB, *points;
facet *facets;
source s;
} scene;
vector crossProduct (vector a, vector b);
double dotProduct (vector a, vector b);
vector normalize (vector v);
vector vSum (vector u, vector v);
vector eDot (double k, vector u);
vector ptsToVect (point a, point b);
void printfPoint (char* name, point a);
float norma (vector v);
int sameSide (facet f, point a, point b);
#endif // __GEOMETRY_H__
|
C
|
#include <stdio.h>
#define MAXLINE 1000
/*
Write the function `strrindex(s,t)` which returns the index position of
the rightmost occurrence of t in s, or -1 if there is none.
*/
/* NOTES
The function `strrindex` is very similar to the books `strindex`. The only
modification needed is to track the last matching index position. So it
really is an additional variable that keeps track of this index, otherwise
its default returns -1.
The rightmost index returned is the index of the first matching letter,
the last match in the string, starting with a 0 index.
*/
int getLine(char s[]);
void reverse(char from[], char to[], int len);
int strrindex(char s[], char t[]);
int main(void) {
int c, i;
char d[MAXLINE]; /* Will hold initial string for `t` */
char s[MAXLINE], t[MAXLINE]; /* `t` will be reversed string */
while (getLine(s) > 0 && getLine(t) > 0) {
// reverse(d, t, c);
i = strrindex(s, t);
printf("Rightmost occurrence: %d\n", i);
}
}
int getLine(char d[]) {
int i, c;
for (i = 0; i < MAXLINE - 1 && (c = getchar()) != EOF && c != '\n'; ++i) {
d[i] = c;
}
/* Don't include newline char */
d[i] = '\0';
return i;
}
/* reverse a string */
void reverse(char from[], char to[], int len) {
int i, j;
for (i = 0, j = len; i < len; i++) {
to[i] = from[--j];
}
to[i] = '\0';
}
int strrindex(char s[], char t[]) {
int idx, i, j, k;
idx = -1;
for (i = 0; s[i] != '\0'; i++) {
for (j = i, k = 0; t[k] != '\0' && s[j] == t[k]; j++, k++)
;
if (k > 0 && t[k] == '\0') {
idx = i;
}
}
return idx;
}
|
C
|
#include <stdio.h>
#define DAY 365 /*매크로 DAY 정의 */
#define TIME 24 /*매크로 TIME정의 */
#define MINUTE 60 /*매크로 MINUTE */
#define SECOND 60 /*매크로 SECOND */
main()
{
long int sec;
/*매크로를 이용해 전처리하면 해당 문자열로 바뀐다, */
sec = DAY*TIME*MINUTE*SECOND;
printf("one year is %1d second\n", sec);
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* cmp.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: gmelisan <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2019/02/19 18:16:48 by gmelisan #+# #+# */
/* Updated: 2019/02/21 17:27:39 by gmelisan ### ########.fr */
/* */
/* ************************************************************************** */
#include "ft_ls.h"
int cmp_lex(const void *a, const void *b)
{
char *str_a;
char *str_b;
str_a = ((t_name *)a)->name;
str_b = ((t_name *)b)->name;
return (ft_strcmp(str_a, str_b));
}
int cmp_rlex(const void *a, const void *b)
{
char *str_a;
char *str_b;
str_a = ((t_name *)a)->name;
str_b = ((t_name *)b)->name;
return (-ft_strcmp(str_a, str_b));
}
int cmp_modtime(const void *a, const void *b)
{
time_t time_a;
time_t time_b;
long res;
time_a = ((t_name *)a)->st.st_mtime;
time_b = ((t_name *)b)->st.st_mtime;
res = time_b - time_a;
if (res > INT_MAX)
res = 1;
else if (res < INT_MIN)
res = -1;
return (res);
}
|
C
|
#include<stdio.h>
#include<conio.h>
void main (void)
{
clrscr();
printf("Hello World\n");
getch();
}
|
C
|
/* Задача 1. Направете две функции и извикайте желаната функция с
указател към функция, съобразно знака, подаден от командния ред: */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int fplus(int a, int b){
return a + b;
}
int fminus(int a, int b){
return a -b;
}
int main(int argc, char *argv[]){
int (*ptr)(int, int) = NULL;
if(argc < 3)
printf("Usage %s +/- arg1 arg2\n", argv[0]);
else if('-' == argv[2][0])
ptr = fminus;
else if('+' == argv[2][0])
ptr = fplus;
(NULL == ptr) ? 0 : printf("\nResult: %d\n",
(*ptr)(atoi(argv[1]), atoi(argv[3])));
return 0;
}
|
C
|
#ifndef PAGEALLOCATOR_H_
#define PAGEALLOCATOR_H_
/*
* Every allocation needs an 8-byte header to store the allocation size while
* staying 8-byte aligned. The address returned by "myMalloc" is the address
* right after this header (i.e. the size occupies the 8 bytes before the
* returned address).
*/
#define HEADER_SIZE 8
/*
* The minimum allocation size is 16 bytes because we have an 8-byte header and
* we need to stay 8-byte aligned.
*/
#define MIN_ALLOC_LOG2 4
#define MIN_ALLOC ((uint64_t)1 << MIN_ALLOC_LOG2)
/*
* The maximum allocation size is currently set to 2gb. This is the total size
* of the heap. It's technically also the maximum allocation size because the
* heap could consist of a single allocation of this size. But of course real
* heaps will have multiple allocations, so the real maximum allocation limit
* is at most 1gb.
*/
#define MAX_ALLOC_LOG2 31
#define MAX_ALLOC ((uint64_t)1 << MAX_ALLOC_LOG2)
/*
* Allocations are done in powers of two starting from MIN_ALLOC and ending at
* MAX_ALLOC inclusive. Each allocation size has a bucket that stores the myFree
* list for that allocation size.
*
* Given a bucket index, the size of the allocations in that bucket can be
* found with "(uint64_t)1 << (MAX_ALLOC_LOG2 - bucket)".
*/
#define BUCKET_COUNT (MAX_ALLOC_LOG2 - MIN_ALLOC_LOG2 + 1)
/*Address for size of ram*/
#define SYSTEM_RAM_ADDRESS 0x1000000
/*
* myFree lists are stored as circular doubly-linked lists. Every possible
* allocation size has an associated myFree list that is threaded through all
* currently myFree blocks of that size. That means MIN_ALLOC must be at least
* "sizeof(list_t)". MIN_ALLOC is currently 16 bytes, so this will be true for
* both 32-bit and 64-bit.
*/
typedef struct list_t {
struct list_t *prev, *next;
} list_t;
static int update_max_ptr(uint8_t *new_value);
static void list_init(list_t *list);
static void list_push(list_t *list, list_t *entry);
static void list_remove(list_t *entry);
static list_t *list_pop(list_t *list);
static uint8_t *ptr_for_node(uint64_t index, uint64_t bucket);
static uint64_t node_for_ptr(uint8_t *ptr, uint64_t bucket);
static int parent_is_split(uint64_t index);
static void flip_parent_is_split(uint64_t index);
static uint64_t bucket_for_request(uint64_t request);
static int lower_bucket_limit(uint64_t bucket);
void *myMalloc(uint64_t request);
void myFree(void *ptr);
#endif
|
C
|
#include "link_list_for_10_and_11.c"
int main(int argc, char const *argv[])
{
int i;
tLink_list *plink_list_A = Creat();
tLink_list *plink_list_B = Creat();
tLink_list *plink_list;
tStudent student;
for (i = 0; i < STD_NUM; ++i)
{
strcpy(student.school_num, SCHOOL_NUM[i]);
strcpy(student.name, NAME[i]);
Append(plink_list_A, student);
}
for (i = 0; i < STD_NUM; ++i)
{
strcpy(student.school_num, SCHOOL_NUM[i + STD_NUM]);
strcpy(student.name, NAME[i + STD_NUM]);
Append(plink_list_B, student);
}
Show(plink_list_A);
Show(plink_list_B);
printf("\n");
plink_list = Combine(plink_list_A, plink_list_B);
Show(plink_list);
printf("\n");
Swap(plink_list, Find_forenode(plink_list, Find_forenode(plink_list, plink_list->ptail)), plink_list->phead);
Swap(plink_list, Find_forenode(plink_list, Find_forenode(plink_list, plink_list->ptail)), Find_forenode(plink_list, plink_list->ptail));
Show(plink_list);
printf("\n");
Sort(plink_list);
Show(plink_list);
return 0;
}
|
C
|
/**
* \file kernel.c
* Various functions and defintions that are common to several parts of the
* kernel.
*/
#include "sys/kernel.h"
#include "sys/pmm.h"
#include "hal/hal.h"
#include "lib/stdio.h" // kprintf
#include "lib/string.h" // memcpy
void panic(const char* msg, const char* file, uint32_t line) {
clear_int();
kprintf(K_FATAL, "PANIC: %s (%s:%i)\n", msg, file, line);
while(1);
}
void print_regs(Registers* regs, uint32_t lev) {
kprintf(lev, "ES: 0x%x | DS: 0x%x | EDI: 0x%x\n", regs->es, regs->ds, regs->edi);
kprintf(lev, "GS: 0x%x | FS: 0x%x\n", regs->gs, regs->fs);
kprintf(lev, "ESI: 0x%x | EBP: 0x%x | t_esp: 0x%x\n", regs->esi, regs->ebp, regs->tampered_esp);
kprintf(lev, "EBX: 0x%x | EDX: 0x%x | ECX: 0x%x\n", regs->ebx, regs->edx, regs->ecx);
kprintf(lev, "EAX: 0x%x | int_no: 0x%x | err_code: 0x%x\n", regs->eax, regs->int_no, regs->err_code);
kprintf(lev, "EIP: 0x%x | CS: 0x%x | EFLAGS: 0x%x\n", regs->eip, regs->cs, regs->eflags);
}
inline uint32_t xchg(volatile uint32_t* addr, uint32_t n_val) {
uint32_t ret;
asm volatile("lock xchgl %0, %1" :
"+m" (*addr), "=a" (ret) :
"1" (n_val) :
"cc");
return ret;
}
void move_stack(uint32_t new_stack, uint32_t sz, uint32_t init_esp) {
uint32_t i;
for(i = new_stack; i >= (new_stack - sz); i -= 4096) {
uint32_t phys = (uint32_t)pmm_alloc_first();
vmm_map_page(phys, i, X86_PAGE_WRITABLE);
}
uint32_t old_stack;
get_esp(old_stack);
uint32_t old_base;
get_ebp(old_base);
uint32_t offset = new_stack - init_esp;
uint32_t new_stack_ptr = old_stack + offset;
uint32_t new_base_ptr = old_base + offset;
memcpy((uint8_t*)new_stack_ptr, (uint8_t*)old_stack, init_esp-old_stack);
// Now we change values to fit with the new stack
for(i = new_stack; i >= (new_stack - sz); i -= 4) {
uint32_t tmp = *(uint32_t*)i;
if( (old_stack < tmp) && (tmp < init_esp) ) {
tmp += offset;
uint32_t* tmp2 = (uint32_t*)i;
*tmp2 = tmp;
}
}
set_esp(new_stack_ptr);
set_ebp(new_base_ptr);
}
// The main body for calculating checksum.
#define checksum_x(sz)\
int i;\
sz ret = 0;\
for(i = 0; i < len; i++) {\
ret += data[i];\
}\
return ret;
uint8_t checksum_8(uint8_t* data, int len) {
checksum_x(uint8_t)
}
uint16_t checksum_16(uint16_t* data, int len) {
checksum_x(uint16_t)
}
uint32_t checksum_32(uint32_t* data, int len) {
checksum_x(uint32_t)
}
uint64_t checksum_64(uint64_t* data, int len) {
checksum_x(uint64_t)
}
void* find_signature(void* data, uint64_t len, int bytes, uint64_t sig, int align) {
uint64_t i;
for(i = 0; i < len; i += align) {
if(bytes == 1) {
if(*((uint8_t*)(data + i)) == (uint8_t)sig) return (data + i);
}
else if(bytes == 2) {
if(*((uint16_t*)(data + i)) == (uint16_t)sig) return (data + i);
}
else if(bytes == 4) {
if(*((uint32_t*)(data + i)) == (uint32_t)sig) return (data + i);
}
else if(bytes == 8) {
if(*((uint64_t*)(data + i)) == (uint64_t)sig) return (data + i);
}
}
return NULL;
}
#ifdef TEST_KERNEL
int kernel_test_checksum() {
#define CHECKSUM_DSZ 10
uint8_t data[CHECKSUM_DSZ];
int i;
for(i = 0; i < CHECKSUM_DSZ; i++) {
data[i] = i;
}
uint8_t res = checksum_8(data, CHECKSUM_DSZ);
if(res != (CHECKSUM_DSZ*(CHECKSUM_DSZ-1))/2) return 1;
for(i = 0; i < CHECKSUM_DSZ; i++) {
data[i] = (0xFF-i);
}
// Result is manually calculated
res = checksum_8(data, CHECKSUM_DSZ);
if(res != 0xC9) return 2;
return 0;
}
bool kernel_generic_unit_test(unit_test* tests, const char* func) {
int res = 0, count = 0;
do {
if( (res = (*tests[count])()) != 0) {
kprintf(K_LOW_INFO, "%s: INDEX: %i FAILED: %i\n", func, count, res);
return false;
}
count++;
} while(tests[count] != NULL);
return true;
}
bool kernel_run_all_tests() {
unit_test tests[2] = {
kernel_test_checksum,
NULL
};
int res = 0, count = 0;
do {
if( (res = (*tests[count])()) != 0) {
kprintf(K_LOW_INFO, "kernel_run_all_tests(): index: %i FAILED: %i\n", count, res);
return false;
}
count++;
} while(tests[count] != NULL);
return true;
}
#endif
|
C
|
#include<assert.h>
#include<stdio.h>
#include<cgenerics/CGAppState.h>
#include"BB_RDParser.h"
CGAppState* appState;
BBScannerRule* startRule = NULL;
void testNewDelete() {
printf("%s... ", __func__);
char* text = "xyz";
BBToken* token = BBToken__new(BBTokenType_identifier, CGString__new(text));
/*
BBScannerNode* node = BBScannerNode__new(BBScannerNodeType_string, "", NULL, BBTokenType_nonTerminal, false);
BBScannerRule* rule = BBScannerRule__new(CGString__new(""), CGArray__newFromInitializerList(BBScannerNode, node, NULL));
*/
BBPhrase* phrase = BBPhrase__new(BBPhraseRepeat_once, NULL);
BBAlternative* alternative = BBAlternative__new(CGArray__newFromInitializerList(BBPhrase, phrase, NULL));
BBSentence* sentence = BBSentence__new(CGString__new("test"), BBTokenType_identifier, CGArray__newFromInitializerList(BBAlternative, alternative, NULL));
BBPhrase_setParts(phrase, CGArray__newFromInitializerList(BBSentence, sentence, NULL));
BB_RDParser* parser = BB_RDParser__new(sentence);
BB_RDParser_delete(parser);
printf("%s ok\n", __func__);
}
void testOneTerminalDefinition() {
/*
identifier ::= 'xyz' ;
*/
printf("%s...\n", __func__);
CGString* text = CGString__new("xyz");
BBToken* token = BBToken__new(BBTokenType_identifier, CGString__new(text));
CGArray(BBToken)* tokenList = CGArray__newFromInitializerList(BBToken, token, NULL);
CGString* sentenceName = CGString__new("identifierSentence");
BBSentence* sentence = BBSentence__new(sentenceName, BBTokenType_identifier, NULL);
BB_RDParser* parser = BB_RDParser__new(sentence);
BBAst* ast = BB_RDParser_parse(parser, tokenList);
assert(ast != NULL);
assert(BBToken_getType(BBAst_getToken(ast)) == BBTokenType_identifier);
assert(!CGString__compare(BBToken_getText(BBAst_getToken(ast)), text));
assert(!CGString__compare(BBSentence_getName(BBAst_getSentence(ast)), sentenceName));
BB_RDParser_delete(parser);
printf("%s ok\n", __func__);
}
/*
definition ::= identifier;
identifier ::= 'xyz';
-->
*/
void testOneAlternativeWithoutRepetition() {
printf("%s...\n", __func__);
CGString* text = CGString__new("xyz");
BBToken* token = BBToken__new(BBTokenType_identifier, CGString__new(text));
CGArray(BBToken)* tokenList = CGArray__newFromInitializerList(BBToken, token, NULL);
BBPhrase* phrase = BBPhrase__new(BBPhraseRepeat_once, NULL);
BBAlternative* alternative = BBAlternative__new(CGArray__newFromInitializerList(BBPhrase, phrase, NULL));
BBSentence* identifierSentence = BBSentence__new(CGString__new("identifierSentence"), BBTokenType_identifier, NULL);
BBPhrase_setParts(phrase, CGArray__newFromInitializerList(BBSentence, identifierSentence, NULL));
BBSentence* definitionSentence = BBSentence__new(CGString__new("definitionSentence"), BBTokenType_definitionSign, CGArray__newFromInitializerList(BBAlternative, alternative, NULL));
BB_RDParser* parser = BB_RDParser__new(definitionSentence);
BB_RDParser_print(parser);
BBAst* ast = BB_RDParser_parse(parser, tokenList);
assert(ast != NULL);
assert(BBToken_getType(BBAst_getToken(ast)) == BBTokenType_definitionSign);
assert(!CGString__compare(BBSentence_getName(BBAst_getSentence(ast)), "definitionSentence"));
CGAppState_THROW(CGAppState__getInstance(), Severity_notice, CGExceptionID_GeneralNonfatalException, "please add tests for sub-sentence");
BBAst_print(ast, 0);
BB_RDParser_delete(parser);
printf("%s ok\n", __func__);
}
/*
definition ::= identifier | semicolon ;
identifier ::= (whatever);
semicolon ::= (whatever);
-->
*/
void testTwoAlternativesWithoutRepetition() {
printf("%s...\n", __func__);
CGString* text = CGString__new("xyz");
BBToken* token = BBToken__new(BBTokenType_semicolon, CGString__new(text));
CGArray(BBToken)* tokenList = CGArray__newFromInitializerList(BBToken, token, NULL);
BBSentence* identifierSentence = BBSentence__new(CGString__new("identifierSentence"), BBTokenType_identifier, NULL);
BBSentence* semicolonSentence = BBSentence__new(CGString__new("semicolonSentence"), BBTokenType_semicolon, NULL);
BBPhrase* identifierPhrase = BBPhrase__new(BBPhraseRepeat_once, NULL);
BBPhrase* semicolonPhrase = BBPhrase__new(BBPhraseRepeat_once, NULL);
BBPhrase_setParts(identifierPhrase, CGArray__newFromInitializerList(BBSentence, identifierSentence, NULL));
BBPhrase_setParts(semicolonPhrase, CGArray__newFromInitializerList(BBSentence, semicolonSentence, NULL));
BBAlternative* identifierAlternative = BBAlternative__new(CGArray__newFromInitializerList(BBPhrase, identifierPhrase, NULL));
BBAlternative* semicolonAlternative = BBAlternative__new(CGArray__newFromInitializerList(BBPhrase, semicolonPhrase, NULL));
BBSentence* definitionSentence = BBSentence__new(CGString__new("definitionSentence"), BBTokenType_definitionSign, CGArray__newFromInitializerList(BBAlternative, identifierAlternative, semicolonAlternative, NULL));
BB_RDParser* parser = BB_RDParser__new(definitionSentence);
BB_RDParser_print(parser);
BBAst* ast = BB_RDParser_parse(parser, tokenList);
assert(ast != NULL);
assert(BBToken_getType(BBAst_getToken(ast)) == BBTokenType_definitionSign);
assert(!CGString__compare(BBSentence_getName(BBAst_getSentence(ast)), "definitionSentence"));
CGAppState_THROW(CGAppState__getInstance(), Severity_notice, CGExceptionID_GeneralNonfatalException, "please add tests for sub-sentence");
BBAst_print(ast, 0);
BB_RDParser_delete(parser);
printf("%s ok\n", __func__);
}
void testUnexpectedEOF() {
printf("%s...\n", __func__);
CGAppState_catchAndDeleteException(CGAppState__getInstance());
CGString* text = CGString__new("xyz");
BBToken* token = BBToken__new(BBTokenType_identifier, CGString__new(text));
CGArray(BBToken)* tokenList = CGArray__newFromInitializerList(BBToken, token, NULL);
BBSentence* identifierSentence = BBSentence__new(CGString__new("identifierSentence"), BBTokenType_identifier, NULL);
BBSentence* semicolonSentence = BBSentence__new(CGString__new("semicolonSentence"), BBTokenType_semicolon, NULL);
BBPhrase* identifierPhrase = BBPhrase__new(BBPhraseRepeat_once, CGArray__newFromInitializerList(BBSentence, identifierSentence, NULL));
CGAppState_catchAndDeleteException(CGAppState__getInstance());
BBPhrase* semicolonPhrase = BBPhrase__new(BBPhraseRepeat_once, CGArray__newFromInitializerList(BBSentence, semicolonSentence, NULL));
BBPhrase* identifierSemicolonPhrase = BBPhrase__new(BBPhraseRepeat_once, CGArray__newFromInitializerList(BBSentence, identifierSentence, semicolonSentence, NULL));
BBAlternative* identifierSemicolonAlternative = BBAlternative__new(CGArray__newFromInitializerList(BBPhrase, identifierSemicolonPhrase, NULL));
BBAlternative* semicolonAlternative = BBAlternative__new(CGArray__newFromInitializerList(BBPhrase, semicolonPhrase, NULL));
BBSentence* definitionSentence = BBSentence__new(CGString__new("definitionSentence"), BBTokenType_definitionSign, CGArray__newFromInitializerList(BBAlternative, identifierSemicolonAlternative, semicolonAlternative, NULL));
BB_RDParser* parser = BB_RDParser__new(definitionSentence);
BBAst* ast = BB_RDParser_parse(parser, tokenList);
assert(ast == NULL);
assert(CGAppState_catchAndDeleteExceptionWithID(CGAppState__getInstance(), BBExceptionID_ScannerError) == true);
BB_RDParser_delete(parser);
printf("%s ok\n", __func__);
}
/*
definition ::= identifier semicolon | semicolon ;
identifier ::= (whatever);
semicolon ::= (whatever);
-->
*/
void testTwoAlternativesAndTwoPhrasesWithoutRepetition() {
printf("%s...\n", __func__);
CGAppState_catchAndDeleteException(CGAppState__getInstance());
CGString* text = CGString__new("ident");
CGString* text2 = CGString__new(";");
BBToken* token = BBToken__new(BBTokenType_identifier, CGString__new(text));
BBToken* token2 = BBToken__new(BBTokenType_semicolon, CGString__new(text2));
CGArray(BBToken)* tokenList = CGArray__newFromInitializerList(BBToken, token, token2, NULL);
BBSentence* identifierSentence = BBSentence__new(CGString__new("identifierSentence"), BBTokenType_identifier, NULL);
BBSentence* semicolonSentence = BBSentence__new(CGString__new("semicolonSentence"), BBTokenType_semicolon, NULL);
BBPhrase* identifierPhrase = BBPhrase__new(BBPhraseRepeat_once, CGArray__newFromInitializerList(BBSentence, identifierSentence, NULL));
CGAppState_catchAndDeleteException(CGAppState__getInstance());
BBPhrase* semicolonPhrase = BBPhrase__new(BBPhraseRepeat_once, CGArray__newFromInitializerList(BBSentence, semicolonSentence, NULL));
BBPhrase* identifierSemicolonPhrase = BBPhrase__new(BBPhraseRepeat_once, CGArray__newFromInitializerList(BBSentence, identifierSentence, semicolonSentence, NULL));
BBAlternative* identifierSemicolonAlternative = BBAlternative__new(CGArray__newFromInitializerList(BBPhrase, identifierSemicolonPhrase, NULL));
BBAlternative* semicolonAlternative = BBAlternative__new(CGArray__newFromInitializerList(BBPhrase, semicolonPhrase, NULL));
BBSentence* definitionSentence = BBSentence__new(CGString__new("definitionSentence"), BBTokenType_definitionSign, CGArray__newFromInitializerList(BBAlternative, identifierSemicolonAlternative, semicolonAlternative, NULL));
BB_RDParser* parser = BB_RDParser__new(definitionSentence);
BB_RDParser_print(parser);
BBAst* ast = BB_RDParser_parse(parser, tokenList);
assert(ast != NULL);
assert(BBToken_getType(BBAst_getToken(ast)) == BBTokenType_definitionSign);
assert(!CGString__compare(BBSentence_getName(BBAst_getSentence(ast)), "definitionSentence"));
CGAppState_THROW(CGAppState__getInstance(), Severity_notice, CGExceptionID_GeneralNonfatalException, "please add tests for sub-sentence");
BBAst_print(ast, 0);
BB_RDParser_delete(parser);
printf("%s ok\n", __func__);
}
/*
definition ::= identifier+ ;
*/
void testRepetition() {
printf("%s...\n", __func__);
CGAppState_catchAndDeleteException(CGAppState__getInstance());
CGString* text = CGString__new("ident1");
CGString* text2 = CGString__new("ident2");
BBToken* token = BBToken__new(BBTokenType_identifier, CGString__new(text));
BBToken* token2 = BBToken__new(BBTokenType_identifier, CGString__new(text2));
CGArray(BBToken)* tokenList = CGArray__newFromInitializerList(BBToken, token, token2, NULL);
BBSentence* identifierSentence = BBSentence__new(CGString__new("identifierSentence"), BBTokenType_identifier, NULL);
BBPhrase* identifierPhrase = BBPhrase__new(BBPhraseRepeat_many, CGArray__newFromInitializerList(BBSentence, identifierSentence, NULL));
BBAlternative* identifierAlternative = BBAlternative__new(CGArray__newFromInitializerList(BBPhrase, identifierPhrase, NULL));
BBSentence* definitionSentence = BBSentence__new(CGString__new("definitionSentence"), BBTokenType_definitionSign, CGArray__newFromInitializerList(BBAlternative, identifierAlternative, NULL));
BB_RDParser* parser = BB_RDParser__new(definitionSentence);
BB_RDParser_print(parser);
BBAst* ast = BB_RDParser_parse(parser, tokenList);
assert(ast != NULL);
assert(BBToken_getType(BBAst_getToken(ast)) == BBTokenType_definitionSign);
assert(!CGString__compare(BBSentence_getName(BBAst_getSentence(ast)), "definitionSentence"));
CGAppState_THROW(CGAppState__getInstance(), Severity_notice, CGExceptionID_GeneralNonfatalException, "please add tests for sub-sentence");
BBAst_print(ast, 0);
BB_RDParser_delete(parser);
printf("%s ok\n", __func__);
}
/*
* start ::= rule1 | rule2 ;
* rule1 ::= identifier semicolon ;
* rule2 ::= identifier definitionSign ;
*/
void testTwoAlternativesWithSameStartKeyword() {
printf("%s...\n", __func__);
CGAppState_reset(CGAppState__getInstance());
CGString* nonterminalName = CGString__new("nonterminal");
CGString* identName = CGString__new("ident");
CGString* semicolonName = CGString__new("semicolon");
CGString* definitionSignName = CGString__new("definitionSign");
BBToken* tokenNonterminal = BBToken__new(BBTokenType_nonTerminal, CGString__new(identName));
BBToken* tokenIdent = BBToken__new(BBTokenType_identifier, CGString__new(identName));
BBToken* tokenSemicolon = BBToken__new(BBTokenType_semicolon, CGString__new(semicolonName));
BBToken* tokenDefinitionSign = BBToken__new(BBTokenType_definitionSign, CGString__new(definitionSignName));
BBSentence* identifierSentence = BBSentence__new(identName, BBTokenType_identifier, NULL);
BBSentence* semicolonSentence = BBSentence__new(semicolonName, BBTokenType_semicolon, NULL);
BBSentence* definitionSignSentence = BBSentence__new(definitionSignName, BBTokenType_definitionSign, NULL);
BBPhrase* rule1Alternative0Phrase0 = BBPhrase__new(BBPhraseRepeat_once, CGArray__newFromInitializerList(BBSentence, identifierSentence, semicolonSentence, NULL));
BBAlternative* rule1Alternative0 = BBAlternative__new(CGArray__newFromInitializerList(BBPhrase, rule1Alternative0Phrase0, NULL));
BBSentence* rule1Sentence = BBSentence__new(CGString__new("rule1"), BBTokenType_nonTerminal, CGArray__newFromInitializerList(BBAlternative, rule1Alternative0, NULL));
BBPhrase* rule2Alternative0Phrase0 = BBPhrase__new(BBPhraseRepeat_once, CGArray__newFromInitializerList(BBSentence, identifierSentence, definitionSignSentence, NULL));
BBAlternative* rule2Alternative0 = BBAlternative__new(CGArray__newFromInitializerList(BBPhrase, rule2Alternative0Phrase0, NULL));
BBSentence* rule2Sentence = BBSentence__new(CGString__new("rule2"), BBTokenType_nonTerminal, CGArray__newFromInitializerList(BBAlternative, rule2Alternative0, NULL));
BBPhrase* startAlternative0Phrase0 = BBPhrase__new(BBPhraseRepeat_once, CGArray__newFromInitializerList(BBSentence, rule1Sentence, NULL));
BBPhrase* startAlternative1Phrase0 = BBPhrase__new(BBPhraseRepeat_once, CGArray__newFromInitializerList(BBSentence, rule2Sentence, NULL));
BBAlternative* startAlternative0 = BBAlternative__new(CGArray__newFromInitializerList(BBPhrase, startAlternative0Phrase0, NULL));
BBAlternative* startAlternative1 = BBAlternative__new(CGArray__newFromInitializerList(BBPhrase, startAlternative1Phrase0, NULL));
BBSentence* startSentence = BBSentence__new(CGString__new("start"), BBTokenType_nonTerminal, CGArray__newFromInitializerList(BBAlternative, startAlternative0, startAlternative1, NULL));
BB_RDParser* parser = BB_RDParser__new(startSentence);
BB_RDParser_print(parser);
/* 1. identifier semicolon */
CGArray(BBToken)* tokenList = CGArray__newFromInitializerList(BBToken, tokenIdent, tokenSemicolon, NULL);
BBAst* ast = BB_RDParser_parse(parser, tokenList);
BBAst_print(ast, 0);
assert(BBAst_getSentence(ast) == startSentence);
BBAst* ruleLeaf = BBAst_getSubAstAt(ast, 0);
assert(BBAst_getSentence(ruleLeaf) == rule1Sentence);
BBAst* identLeaf = BBAst_getSubAstAt(ruleLeaf, 0);
assert(BBAst_getSentence(identLeaf) == identifierSentence);
BBAst* secondLeaf = BBAst_getSubAstAt(ruleLeaf, 1);
assert(BBAst_getSentence(secondLeaf) == semicolonSentence);
/* 1. identifier definitionSign */
tokenList = CGArray__newFromInitializerList(BBToken, tokenIdent, tokenDefinitionSign, NULL);
ast = BB_RDParser_parse(parser, tokenList);
BBAst_print(ast, 0);
assert(BBAst_getSentence(ast) == startSentence);
ruleLeaf = BBAst_getSubAstAt(ast, 0);
assert(BBAst_getSentence(ruleLeaf) == rule2Sentence);
identLeaf = BBAst_getSubAstAt(ruleLeaf, 0);
assert(BBAst_getSentence(identLeaf) == identifierSentence);
secondLeaf = BBAst_getSubAstAt(ruleLeaf, 1);
assert(BBAst_getSentence(secondLeaf) == definitionSignSentence);
BB_RDParser_delete(parser);
printf("%s ok\n", __func__);
}
int main() {
CGAppState__init(__FILE__);
appState = CGAppState__getInstance();
printf("=== %s ===\n", __FILE__);
startRule = BBScannerRuleset__getInstance();
testNewDelete();
testOneTerminalDefinition();
testOneAlternativeWithoutRepetition();
testTwoAlternativesWithoutRepetition();
testTwoAlternativesAndTwoPhrasesWithoutRepetition();
testRepetition();
testTwoAlternativesWithSameStartKeyword();
/* testing errors */
/* testUnexpectedEOF(); */
printf("WARNING: testUnexpectedEOF has been commented-out.\n");
printf("=== %s ok ===\n", __FILE__);
CGAppState__deInit();
return 0;
}
|
C
|
#include "Packet.h"
#include <stdlib.h>
#include <string.h>
#define EGGBEATER_SOF_BYTE 0x55
#define EGGBEATER_EOF_BYTE 0xff
#define COMMAND_VALID(cmd) ( ( ( cmd ) == CtrlCommand_None ) \
|| ( ( cmd ) == CtrlCommand_Echo ) \
|| ( ( cmd ) == CtrlCommand_OpenSession ) \
|| ( ( cmd ) == CtrlCommand_NewSession ) \
|| ( ( cmd ) == CtrlCommand_RefreshSession ) \
|| ( ( cmd ) == CtrlCommand_CloseSession ) \
|| ( ( cmd ) == CtrlCommand_GetFileKey ) \
)
/*
Conditions:
7
Exit points:
8
M = 7 - 8 + 2 = 1
Cyclomatic complexity
1
*/
uint32_t packet_validate(Packet_t* p)
{
PacketHeader_t* header = NULL;
uint16_t specLen, calcLen;
if (p == NULL)
return PacketError_NullArgument;
if (p->Data == NULL)
return PacketError_NullArgument;
if (p->Length < sizeof(PacketHeader_t))
return PacketError_InvalidPacket;
header = (PacketHeader_t*)p->Data;
if (header->MagicNumber != EGGBEATER_SOF_BYTE)
return PacketError_BadSOF;
if (!COMMAND_VALID(header->Command))
return PacketError_BadCommand;
specLen = (header->LengthHigh << 8) | (header->LengthLow);
calcLen = specLen + sizeof(PacketHeader_t);
if (calcLen != p->Length)
return PacketError_BadSize;
if (p->Data[calcLen - 1] != EGGBEATER_EOF_BYTE)
return PacketError_BadEOF;
return 0;
}
/*
Conditions:
3
Exit points:
3
M = 3 - 3 + 2 = 2
Cyclomatic complexity
2
*/
uint32_t packet_get_header(Packet_t* p, PacketHeader_t** h)
{
if (p == NULL)
return PacketError_NullArgument;
if (p->Data == NULL)
return PacketError_NullArgument;
if (h != NULL)
*h = (PacketHeader_t*)p->Data;
return 0;
}
/*
Conditions:
3
Exit points:
3
M = 3 - 3 + 2 = 2
Cyclomatic complexity
2
*/
uint32_t packet_get_data(Packet_t* p, uint8_t** d)
{
if (p == NULL)
return PacketError_NullArgument;
if (p->Data == NULL)
return PacketError_NullArgument;
if (d != NULL)
*d = &(((PacketHeader_t*)(p->Data))->Data0);
return 0;
}
/*
Conditions:
3
Exit points:
3
M = 3 - 3 + 2 = 2
Cyclomatic complexity
2
*/
uint32_t packet_get_data_length(Packet_t* p, uint16_t* l)
{
PacketHeader_t* header;
if (p == NULL)
return PacketError_NullArgument;
if (p->Data == NULL)
return PacketError_NullArgument;
header = (PacketHeader_t*)p->Data;
if (l != NULL)
*l = (header->LengthHigh << 8) | (header->LengthLow);
return 0;
}
/*
Conditions:
7
Exit points:
5
M = 7 - 5 + 2 = 4
Cyclomatic complexity
4
*/
uint32_t packet_create(Packet_t* p, uint8_t cmd, uint8_t* data, uint32_t dataLen)
{
PacketHeader_t* head;
uint8_t* pData;
uint32_t errCode;
if (p == NULL)
return PacketError_NullArgument;
if (data == NULL && dataLen != 0)
return PacketError_NullArgument;
if (p->Data != NULL)
{
free(p->Data);
p->Data = NULL;
p->Length = 0;
}
p->Length = sizeof(PacketHeader_t) + dataLen;
p->Data = malloc(p->Length);
if ((errCode = packet_get_header(p, &head)) != 0)
return errCode;
head->MagicNumber = EGGBEATER_SOF_BYTE;
head->Command = cmd;
head->LengthHigh = (dataLen >> 8) & 0xff;
head->LengthLow = (dataLen) & 0xff;
if ((errCode = packet_get_data(p, &pData)) != 0)
return errCode;
if (dataLen > 0)
memcpy(pData, data, dataLen);
p->Data[p->Length - 1] = EGGBEATER_EOF_BYTE;
return 0;
}
/*
Conditions:
2
Exit points:
2
M = 2 - 2 + 2 = 2
Cyclomatic complexity
2
*/
uint32_t packet_free(Packet_t* p)
{
if (p == NULL)
return PacketError_NullArgument;
if (p->Data != NULL)
{
free(p->Data);
p->Data = NULL;
p->Length = 0;
}
return 0;
}
|
C
|
#include<stdio.h>
main()
{
int n,N=0,s;
scanf("%d",&n);
while(n!=0)
{
N=N*10+n%10;
n=n/10;
}
printf("enter the same number");
scanf("%d",s);
if(N==s)
printf("palindrome");
}
|
C
|
/*
AUTHOR : VISHAL KUMAR GOURAV
PROBLEM : IMPLEMENT EXTENDED EUCLIDEAN ALGORITHM
*/
#include<stdio.h>
int extended(int a,int b,int *x,int *y){
if(a==0){
*x=0;
*y=1;
return b;
}
int x1,y1;
int gcd=extended(b%a,a,&x1,&y1);
*x=y1-(b/a)*x1;
*y=x1;
return gcd;
}
int main(){
int a=35,b=15,x,y;
if(a>b){
a=a+b;
b=a-b;
a=a-b;
}
int gcd=extended(a,b,&x,&y);
printf("\nGCD(%d,%d)=%d, and x=%d and y=%d",a,b,gcd,x,y);
printf("\n");
return 0;
}
|
C
|
#include "parse.h"
#include "meme.h"
#include <ctype.h>
#include <string.h>
#include <stdlib.h>
Pair *parse_list(Lexer *lexer) {
Token *const t = lexer->token;
if (!next_token(lexer)) {
fprintf(stderr, "unterminated list (%s:%d:%d)\n",
lexer->file_name, lexer->line, lexer->col);
return NULL;
}
if (t->type == END) {
node_ref(nil_node);
return nil_node;
}
Node *addr = parse(lexer);
if (!addr) return NULL;
Pair *dec = parse_list(lexer);
if (!dec) {
node_unref(addr);
return NULL;
}
return pair_new(addr, dec);
}
Node *parse_atom(Lexer *lexer) {
Token *const t = lexer->token;
Node *ret = NULL;
if (isdigit(*t->value)) {
// TODO how do i do typeof(IntNode.i) again? ffs
long long i;
if (1 != sscanf(t->value, "%lld", &i)) abort();
ret = int_new(i);
} else if (!strcmp(t->value, "#t")) {
node_ref(true_node);
ret = true_node;
} else if (!strcmp(t->value, "#f")) {
node_ref(false_node);
ret = false_node;
} else {
ret = (Node *)symbol_new(t->value);
}
return ret;
}
static Node *parse_quote(Lexer *lexer) {
next_token(lexer);
Node *quoted = parse(lexer);
if (!quoted) return NULL;
return quote_new(quoted);
}
Node *parse(Lexer *lexer) {
switch (lexer->token->type) {
case ATOM:
return parse_atom(lexer);
case START:
return parse_list(lexer);
case QUOTE:
return parse_quote(lexer);
default:
fprintf(stderr, "syntax error at line %d col %d\n", lexer->token->line, lexer->token->col);
return NULL;
}
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/*USUARIO UVA: paulmartinezuva*/
int main(){
int x, cas, relevancia=0, nro=1;
scanf("%d",&cas);
while(cas--){
char str[100];
int rel=0;
printf("Case #%d:\n");
for(x=0;x<10;x++){
scanf("%s%d",str,rel);
if(rel>=relevancia){
relevancia=rel;
}
}
for(x=0;x<10;x++){
scanf("%s%d",str,rel);
if(rel=relevancia){
printf("%s\n",str);
}
}
nro+=1;
relevancia=0;
}
}
|
C
|
/* Author: Tim Nguyen (adopted from Buttenhof's Pthread book)
* -- workq API Pthread
* Allow to init a workq, destroy, and add tasks. */
#include "workq.h"
#include "cmake-build-debug/errors.h"
#include <stdlib.h>
/* initialize a workqueue:
* - Initialize condition variables
* - Initialize flags and workqueue */
int workq_init(workq_t *wq, int threads, void (*engine)(void*)){
int status;
/* initializing thread's attribute -> set detachable so that exits when complete */
status = pthread_attr_init(&wq->attr);
if (status != 0) return status; // error
status = pthread_attr_setdetachstate(&wq->attr, PTHREAD_CREATE_DETACHED);
if (status != 0) { // cannot set detach state, destroy and return error
pthread_attr_destroy(&wq->attr);
return status;
}
/* initialize condition and mutex variable -- check for errors and deallocate
* if needed */
status = pthread_cond_init(&wq->cv, NULL);
if (status != 0) {
pthread_attr_destroy(&wq->attr);
return status;
}
status = pthread_mutex_init(&wq->mutex, NULL);
if (status != 0){
pthread_attr_destroy(&wq->attr);
pthread_mutex_destroy(&wq->mutex);
return status;
}
/* setup other workqueue attributes */
wq->valid = WORKQ_VALID; // this number is used to check if something is a workq
wq->engine = engine; // engine runs program
wq->quit = 0; // not yet quit
wq->first = wq->last = NULL; // initialize an empty queue
wq->parllelism = threads; // number of threads determine how much to parallelize
wq->idle = 0; // no one is idle yet
wq->counter = 0; // no server thread yet
return 0;
}
// threads perform this function which acts as a handler
// for engines to run --> more efficient for threads.
// it is passed a workqueue which in turns control what it does
/* MAIN FUNCTION THAT THREADS RUN.
* Takes a workq_t element that contains conditional variables, job queue,
* info about other threads, quitting info, and other info require to run.
* TAKE THE FIRST WORK FROM THE QUEUE WHEN THERE ARE WORK
* Otherwise wait and if long enough, exit. Finish work before shutting down. */
static void * workq_server(void* arg){
struct timespec timeout;
workq_t *wq = (workq_t*)arg;
workq_ele_t *we;
int status, timedout;
DPRINTF(("A worker is starting\n"));
// locking mutex to either wait (and terminate) or get a task to work on
// have to modify the main workqueue so lock mutex
status = pthread_mutex_lock(&wq->mutex);
if (status != 0) return NULL;
while(1){
timedout = 0;
DPRINTF(("Worker waiting for work\n"));
clock_gettime(CLOCK_REALTIME, &timeout);
timeout.tv_sec +=2;
// When there's no work and we are not quitting yet... wait for work or if wait long enough
// break and potentially checkout.
while(wq->first == NULL && !wq->quit) {
/* Server threads time out after spending 2 seconds waiting for new work and exit */
status = pthread_cond_timedwait(&wq->cv, &wq->mutex, &timeout);
if (status == ETIMEDOUT) {
DPRINTF(("Worker wait timed out\n"));
timedout = 1; // set flag to timed out (for condition underneath) --> break (still have lock)
break;
} else if (status != 0) { // strange error
DPRINTF(("Worker wait failed, %d (%s)\n", status, strerror(status)));
wq->counter--;
pthread_mutex_unlock(&wq->mutex);
return NULL;
}
}
DPRINTF(("\tWork queue: %#lx, quit: %d\n", wq->first, wq->quit));
we = wq->first;
if (we != NULL){ // IF WE GOT AN ACTUAL WORK
wq->first = wq->first->next; // increment queue
if (wq->last == we) // if there was only one item in the queue
wq->last = NULL;
// finish obtaining work and modifying the queue
// now we unlock the mutex and perform our work
status = pthread_mutex_unlock(&wq->mutex);
// run the engine on the data
wq->engine(we->data);
free(we); // remember to free the work element where we allocate in workq_add
/* WE ARE DONE WITH MAIN WORK. Obtain the lock again and start the loop
* one more time to either wait to terminate or to get a new task */
status = pthread_mutex_lock(&wq->mutex); // obtaining the lock here
// in case something failed we exit
if (status != 0) return NULL;
}
/* before starting another loop, we have to check for some conditions
* to see whether we should quit or terminate or not */
if (wq->first == NULL && wq->quit){ // first we check if there's no more work and need to quit
DPRINTF(("Worker shutting down\n"));
wq->counter--;
// here we signal workq_destroy that we have finished shutting down (it was waiting for threads to shut down)
// hence wq->counter == 0.
if (wq->counter == 0) pthread_cond_broadcast(&wq->cv);
pthread_mutex_unlock(&wq->mutex);
return NULL;
}
// here we timedout most likely came from above. We do this separately
// because there might be a queue added in the meantime so we might do it again
if (wq->first == NULL && timedout){
DPRINTF(("Engine terminating due to timeout.\n"));
wq->counter--;
break;
}
}
// end main while loop for work. We either returned from asking to quit (workq_destroy)
// or we get here due to timedout. Otherwise, we should just keep grabbing work from the queue
pthread_mutex_unlock(&wq->mutex);
DPRINTF(("Worker exiting\n"));
return 0;
}
int workq_add(workq_t *wq, void *element){
workq_ele_t *item;
pthread_t id;
int status;
if (wq->valid != WORKQ_VALID) return EINVAL;
/* Create and initialize a request structure. */
item = (workq_ele_t *)malloc( sizeof( workq_ele_t)); // free in server
if (item == NULL) return ENOMEM; // out of memory cannot allocate
item->data = element;
item->next = NULL;
/* now we add the request to the workqueue */
status = pthread_mutex_lock(&wq->mutex);
if (status != 0) { free(item); return status; }
if (wq->first == NULL) wq->first = item;
else wq->last->next = item;
wq->last = item;
/* Main job is done. Now we can signal idling threads to work or create more threads
* else we just let the fully loaded crew to take tasks from the queue */
if (wq->idle > 0) { // if there are any idling threads, wake them and return
status = pthread_cond_signal(&wq->cv);
if (status != 0){pthread_mutex_unlock(&wq->mutex);return status; }
}
else if (wq->counter < wq->parllelism){ // no idling thread -> we can create new threads if we have
DPRINTF(("Creating new worker\n")); // not reached the maximum number of threads
status = pthread_create(&id, &wq->attr, workq_server, (void*)wq);
if (status != 0 ) {pthread_mutex_unlock(&wq->mutex); return status;}
wq->counter++;
}
pthread_mutex_unlock(&wq->mutex);
return 0;
}
/* will accept a shutdown request at any time but will wait for
* existing engine threads to complete their work and terminate */
int workq_destroy(workq_t *wq){
int status, status1, status2;
if (wq->valid != WORKQ_VALID) return EINVAL;
status = pthread_mutex_lock(&wq->mutex);
if (status != 0) return status;
wq->valid = 0; // prevent any other operations
/* Now we check if there are any active threads. If so, find them and shut down:
* 1. set the quit flag
* 2. broadcast to awake threads
* 3. then wait for thread to quit due to quit flag
* -- no need for join to check thread id */
if (wq->counter > 0 ){ // there are threads still doing stuff
wq->quit = 1; // set the quit flag
if (wq->idle > 0) {
status = pthread_cond_broadcast(&wq->cv);
if (status != 0) {pthread_mutex_unlock(&wq->mutex); return status;}
}
while (wq->counter > 0){ // keep waiting until the last thread signal
status = pthread_cond_wait(&wq->cv, &wq->mutex);
if (status != 0) {pthread_mutex_unlock(&wq->mutex); return status;}
}
}
status = pthread_mutex_unlock(&wq->mutex); // done with quitting threads
if (status != 0) return status;
status = pthread_mutex_destroy(&wq->mutex);
status1 = pthread_cond_destroy(&wq->cv);
status2 = pthread_attr_destroy(&wq->attr);
return (status ? status : (status1 ? status1 : status2));
}
|
C
|
#include "framebuffer.h"
static unsigned char *BitmapFont[256];
/* ============================= Frame buffer ============================== */
SDL_Surface *sdlInit(int width, int height, int bpp, int fullscreen) {
int flags = SDL_SWSURFACE;
SDL_Surface *screen;
if (fullscreen) flags |= SDL_FULLSCREEN;
if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_JOYSTICK) == -1) {
fprintf(stderr, "SDL Init error: %s\n", SDL_GetError());
return NULL;
}
atexit(SDL_Quit);
screen = SDL_SetVideoMode(width,height,bpp,flags);
if (!screen) {
fprintf(stderr, "Can't set the video mode: %s\n", SDL_GetError());
return NULL;
}
/* Unicode support makes dealing with text input in SDL much simpler as
* keys are translated into characters with automatic support for modifiers
* (for instance shift modifier to print capital letters and symbols). */
SDL_EnableUNICODE(SDL_ENABLE);
return screen;
}
frameBuffer *createFrameBuffer(int width, int height, int bpp, int fullscreen) {
frameBuffer *fb = malloc(sizeof(*fb));
fb->width = width;
fb->height = height;
fb->screen = sdlInit(width,height,bpp,fullscreen);
SDL_initFramerate(&fb->fps_mgr);
/* Load the bitmap font */
bfLoadFont((char**)BitmapFont);
gfb = fb;
return fb;
}
void setPixelWithAlpha(frameBuffer *fb, int x, int y, int r, int g, int b, int alpha) {
pixelRGBA(fb->screen, x, fb->height-1-y, r, g, b, alpha);
}
void fillBackground(frameBuffer *fb, int r, int g, int b) {
boxRGBA(fb->screen, 0, 0, fb->width-1, fb->height-1, r, g, b, 255);
}
/* ========================== Drawing primitives ============================ */
void drawHline(frameBuffer *fb, int x1, int x2, int y, int r, int g, int b, int alpha) {
hlineRGBA(fb->screen, x1, x2, fb->height-1-y, r, g, b, alpha);
}
void drawEllipse(frameBuffer *fb, int xc, int yc, int radx, int rady, int r, int g, int b, int alpha, char filled) {
if (filled)
filledEllipseRGBA(fb->screen, xc, fb->height-1-yc, radx, rady, r, g, b, alpha);
else
ellipseRGBA(fb->screen, xc, fb->height-1-yc, radx, rady, r, g, b, alpha);
}
void drawBox(frameBuffer *fb, int x1, int y1, int x2, int y2, int r, int g, int b, int alpha, char filled) {
if (filled)
boxRGBA(fb->screen, x1, fb->height-1-y1, x2, fb->height-1-y2, r, g, b, alpha);
else
rectangleRGBA(fb->screen, x1, fb->height-1-y1, x2, fb->height-1-y2, r, g, b, alpha);
}
void drawTriangle(frameBuffer *fb, int x1, int y1, int x2, int y2, int x3, int y3, int r, int g, int b, int alpha, char filled) {
if (filled)
filledTrigonRGBA(fb->screen, x1, fb->height-1-y1, x2, fb->height-1-y2, x3, fb->height-1-y3, r, g, b, alpha);
else
trigonRGBA(fb->screen, x1, fb->height-1-y1, x2, fb->height-1-y2, x3, fb->height-1-y3, r, g, b, alpha);
}
void drawLine(frameBuffer *fb, int x1, int y1, int x2, int y2, int r, int g, int b, int alpha) {
lineRGBA(fb->screen, x1, fb->height-1-y1, x2, fb->height-1-y2, r, g, b, alpha);
}
void drawPolygon(frameBuffer *fb, Sint16* xv, Sint16* yv, int n, int r, int g, int b, int alpha, char filled) {
int i;
for (i=0; i<n; i++) yv[i] = fb->height-1-yv[i];
if (filled)
filledPolygonRGBA(fb->screen, xv, yv, n, r, g, b, alpha);
else
polygonRGBA(fb->screen, xv, yv, n, r, g, b, alpha);
}
/* ============================= Bitmap font =============================== */
void bfLoadFont(char **c) {
/* Set all the entries to NULL. */
memset(c,0,sizeof(unsigned char*)*256);
/* Now populate the entries we have in our bitmap font description. */
#include "bitfont.h"
}
void bfWriteChar(frameBuffer *fb, int xp, int yp, int c, int r, int g, int b, int alpha) {
int x,y;
unsigned char *bitmap = BitmapFont[c&0xff];
if (!bitmap) bitmap = BitmapFont['?'];
for (y = 0; y < 16; y++) {
for (x = 0; x < 16; x++) {
int byte = (y*16+x)/8;
int bit = x%8;
int set = bitmap[byte] & (0x80>>bit);
if (set) setPixelWithAlpha(fb,xp+x,yp-y+15,r,g,b,alpha);
}
}
}
void bfWriteString(frameBuffer *fb, int xp, int yp, const char *s, int len, int r, int g, int b, int alpha) {
int i;
for (i = 0; i < len; i++)
bfWriteChar(fb,xp-((16-FONT_KERNING)/2)+i*FONT_KERNING,yp,
s[i],r,g,b,alpha);
}
/* ================================ Sprites =================================
* The interface exported is opaque and only uses void pointers, so that a
* different implementation of the framebuffer.c not using SDL can retain
* the same interface with load81.c. */
#define SPRITE_MT "l81.sprite_mt"
/*
void spriteBlit(frameBuffer *fb, sprite *sprite, int x, int y, int angle, int aa) {
SDL_Surface *s = sprite;
if (s == NULL) return;
if (angle) s = rotozoomSurface(s,angle,1,aa);
SDL_Rect dst = {x, fb->height-1-y - s->h, s->w, s->h};
SDL_BlitSurface(s, NULL, fb->screen, &dst);
if (angle) SDL_FreeSurface(s);
}
*/
void spriteBlit(frameBuffer *fb, sprite *sp, int x, int y, int tileNum, int angle, int aa) {
SDL_Surface *s = sp->surf;
if (s == NULL) return;
if (tileNum >= 0) {
SDL_Rect dst = {x, fb->height-1-y - sp->tileH, sp->tileW, sp->tileH};
SDL_Rect src = {(tileNum%sp->tileY) * sp->tileW, (tileNum / sp->tileY) * sp->tileH, sp->tileW, sp->tileH};
if (angle) {
SDL_Surface *temp = SDL_CreateRGBSurface(SDL_SWSURFACE, sp->tileW, sp->tileH, fb->screen->format->BitsPerPixel, 0, 0, 0, 0);
SDL_Surface *tempRot;
SDL_BlitSurface(s, &src, temp, NULL);
tempRot = rotozoomSurface(temp,angle,1,aa);
SDL_BlitSurface(tempRot, NULL, fb->screen, &dst);
SDL_FreeSurface(tempRot);
SDL_FreeSurface(temp);
}
else {
SDL_BlitSurface(s, &src, fb->screen, &dst);
}
}
else {
SDL_Rect dst = {x, fb->height-1-y - s->h, s->w, s->h};
if (angle) s = rotozoomSurface(s,angle,1,aa);
SDL_BlitSurface(s, NULL, fb->screen, &dst);
if (angle) SDL_FreeSurface(s);
}
}
/* Load sprite. Return surface pointer and object on top of stack */
sprite *spriteLoad(lua_State *L, const char *filename) {
sprite *pps;
/* check if image was already loaded and cached */
lua_getglobal(L, "sprites");
lua_getfield(L, -1, filename);
if (lua_isnil(L, -1)) {
/* load image into surface */
sprite ps;
ps.surf = IMG_Load(filename);
if (ps.surf == NULL) {
luaL_error(L, "failed to load sprite %s", filename);
return NULL;
}
ps.w = ps.surf->w;
ps.h = ps.surf->h;
ps.tileX = 0;
ps.tileY = 0;
ps.tileW = ps.w;
ps.tileH = ps.h;
/* box the surface pointer in a userdata */
pps = (sprite*)lua_newuserdata(L, sizeof(sprite));
*pps = ps;
/* set sprite metatable */
luaL_getmetatable(L, SPRITE_MT);
lua_setmetatable(L, -2);
/* cache loaded surface in sprite table */
lua_pushvalue(L, -1);
lua_setfield(L, -4, filename);
} else {
/* unbox surface pointer */
pps = (sprite *)luaL_checkudata(L, -1, SPRITE_MT);
}
return pps;
}
int spriteGC(lua_State *L) {
sprite *pps = (sprite *)luaL_checkudata(L, 1, SPRITE_MT);
if (pps) SDL_FreeSurface(pps->surf);
return 0;
}
int spriteGetHeight(lua_State *L) {
sprite *pps = (sprite *)luaL_checkudata(L, 1, SPRITE_MT);
lua_pushnumber(L, pps->h);
return 1;
}
int spriteGetWidth(lua_State *L) {
sprite *pps = (sprite *)luaL_checkudata(L, 1, SPRITE_MT);
lua_pushnumber(L, pps->w);
return 1;
}
int spriteGetTiles(lua_State *L) {
sprite *pps = (sprite *)luaL_checkudata(L, 1, SPRITE_MT);
lua_pushnumber(L, pps->tileX);
lua_pushnumber(L, pps->tileY);
return 2;
}
int spriteSetTiles(lua_State *L) {
sprite *pps = (sprite *)luaL_checkudata(L, 1, SPRITE_MT);
pps->tileX = lua_tonumber(L, 2);
pps->tileY = lua_tonumber(L, 3);
pps->tileW = pps->w / pps->tileX;
pps->tileH = pps->h / pps->tileY;
return 0;
}
int spriteGetTileSize(lua_State *L) {
sprite *pps = (sprite *)luaL_checkudata(L, 1, SPRITE_MT);
lua_pushnumber(L, pps->tileW);
lua_pushnumber(L, pps->tileH);
return 2;
}
int spriteGetTileNum(lua_State *L) {
sprite *pps = (sprite *)luaL_checkudata(L, 1, SPRITE_MT);
lua_pushnumber(L, pps->tileX * pps->tileY);
return 1;
}
int spriteDrawTile(lua_State *L) {
int x, y, tileNum, angle, antialiasing;
sprite *pps = (sprite *)luaL_checkudata(L, 1, SPRITE_MT);
x = lua_tonumber(L, 2);
y = lua_tonumber(L, 3);
tileNum = lua_tonumber(L,4);
angle = luaL_optnumber(L,5,0);
antialiasing = lua_toboolean(L,6);
spriteBlit(gfb, pps, x, y, tileNum, angle, antialiasing);
return 0;
}
int spriteDraw(lua_State *L) {
int x, y, angle, antialiasing;
sprite *pps = (sprite *)luaL_checkudata(L, 1, SPRITE_MT);
x = lua_tonumber(L, 2);
y = lua_tonumber(L, 3);
angle = luaL_optnumber(L,4,0);
antialiasing = lua_toboolean(L,5);
spriteBlit(gfb, pps, x, y, -1, angle, antialiasing);
return 0;
}
static const struct luaL_Reg sprite_m[] = {
{ "__gc", spriteGC },
{ "getHeight", spriteGetHeight },
{ "getWidth", spriteGetWidth },
{ "getTiles", spriteGetTiles },
{ "setTiles", spriteSetTiles },
{ "getTileSize", spriteGetTileSize },
{ "getTileNum", spriteGetTileNum },
{ "tile", spriteDrawTile },
{ "draw", spriteDraw },
{ NULL, NULL }
};
void initSpriteEngine(lua_State *L) {
luaL_newmetatable(L, SPRITE_MT);
lua_pushvalue(L, -1);
lua_setfield(L, -2, "__index");
luaL_register(L, NULL, sprite_m);
}
|
C
|
/*
COPYRIGHT (c) 2013 Gabriel Perez-Cerezo. <http://gpcf.eu>
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#include "gpio.h"
#include <stdio.h>
void clocked_write(int clockpin, int out, int value) {
gpio_write(out, value);
gpio_write(clockpin, 1);
gpio_write(clockpin, 0);
}
int clocked_read(int clockpin, int in){
gpio_write(clockpin, 1);
gpio_write(clockpin, 0);
return gpio_read(in);
}
void mcp3008_select_chip(int bin[], int inputnum){
bin[0] = 1; bin[1] = 1; //the first two bits have to be 1
int i = 2;
int o[3];
for (i=2; i >= 0; i--) { // converts inputnum to a 3-Bit binary number
o[i] = (inputnum % 2);
inputnum /= 2;
}
int c;
for (c = i-1; c>=0; c--) {
o[c] = 0;
}
c = 2;
for (i = 0; i<3; i++){
bin[c] = o[i];
c++;
}
}
int power_of_2(int exp) {
int output = 1;
int i;
for (i = 1; i<=exp; i++) {
output *= 2;
}
return output;
}
int mcp3008_value(int inputnum, int clock, int in, int out, int cs) {
int i; // "for-loop-integer"
int inputarray[5]; // will contain the input number
int output = 0; // this will be returned
gpio_init(clock, "out");
gpio_init(in, "in");
gpio_init(out, "out");
gpio_init(cs, "out");
if (inputnum < 0 || inputnum > 7) {
return -1; // Those inputs don't exist !
}
gpio_write(cs, 1);
gpio_write(clock, 0);
gpio_write(cs, 0);
mcp3008_select_chip(inputarray, inputnum);
for (i=0; i<5; i++){
clocked_write(clock, out, inputarray[i]); // selects the input on the chip.
}
for (i=12; i>0; i--) {
if (clocked_read(clock, in)) {
output += power_of_2(i);
}
}
gpio_write(cs, 1);
output /=4 ;
return output;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
void print_screen(char* screen, int byte_width, int length) {
int width = byte_width * 8;
int height = length / width;
char* line = malloc( sizeof(char) * width + 2); //number of pixels in one line + '\n\0'
line[width] = '\n';
line[width + 1] = '\0';
int i = 0;
int screen_index = 0;
while( i < height ){
int j = 0;
int line_index=0;
while( j < byte_width ) {
int mask = 1<<7;
while(mask != 0) {
line[line_index] = mask & screen[screen_index] ? '1' : '0';
mask = mask >> 1;
++line_index;
}
printf("%s", line);
++j
++screen_index;
}
++i;
}
free(line);
}
int main(void) {
int width = 2; // * 8 pixels
int height = 16;
int length = width * height;
char screen[2*16] = {0};
print_screen( screen, width, length);
//print_screen( screen, width, length);
exit(0);
}
|
C
|
void Choix_1 (FILE* battements)
{
int *donnees;
int i,sizetab;
sizetab=init_size(battements);
donnees=malloc(sizeof(int)*sizetab);
for(i=0;i<sizetab;i++)
{
fscanf(battements, "%d\n", &donnees[i]);
}
for(i=0;i<sizetab;i++)
{
printf("%d\n", donnees[i]);
}
}
void Choix_2 (FILE* battements)
{
int *donnees;
int i,sizetab;
sizetab=init_size(battements);
donnees=malloc(sizeof(int)*sizetab);
for(i=0;i<sizetab;i++)
{
fscanf(battements, "%d\n", &donnees[i]);
}
croissant(donnees,sizetab);
for(i=0;i<sizetab;i++)
{
printf("%d\n", donnees[i]);
}
}
void Choix_3 (FILE* battements)
{
int *donnees;
int i,sizetab;
sizetab=init_size(battements);
donnees=malloc(sizeof(int)*sizetab);
for(i=0;i<sizetab;i++)
{
fscanf(battements, "%d\n", &donnees[i]);
}
decroissant(donnees,sizetab);
for(i=0;i<sizetab;i++)
{
printf("%d\n", donnees[i]);
}
}
void Choix_4 (FILE* battements)
{
int *donnees;
int i,sizetab;
sizetab=init_size(battements);
donnees=malloc(sizeof(int)*sizetab);
for(i=0;i<4;i++)
{
fscanf(battements, "%d\n", &donnees[i]);
}
unique_search(donnees,sizetab);
}
void Choix_5 (FILE* battements)
{
int *donnees;
int i,sizetab;
sizetab=init_size(battements);
donnees=malloc(sizeof(int)*sizetab);
for(i=0;i<sizetab;i++)
{
fscanf(battements, "%d\n", &donnees[i]);
}
plage_moyenne(donnees,sizetab);
}
void Choix_6 (FILE* battements)
{
printf("%d",init_size(battements));
}
void Choix_7 (FILE* battements)
{
int *donnees;
int i,sizetab;
sizetab=init_size(battements);
donnees=malloc(sizeof(int)*sizetab);
for(i=0;i<sizetab;i++)
{
fscanf(battements, "%d\n", &donnees[i]);
}
min_et_max(donnees,4);
}
int croissant(int *tab, int sizetab)
{
int b, i, c;
do
{
b=sizetab;
for(i=0;i<sizetab;i++)
{
if(tab[i]>tab[i+1]&&i<(sizetab-1))
{
c=tab[i];
tab[i]=tab[i+1];
tab[i+1]=c;
}
else
{
b--;
}
}
}while(b>0);
return *tab;
}
int decroissant(int *tab, int sizetab)
{
int b, i, c;
do
{
b=sizetab;
for(i=0;i<sizetab;i++)
{
if(tab[i]<tab[i+1]&&i<(sizetab-1))
{
c=tab[i];
tab[i]=tab[i+1];
tab[i+1]=c;
}
else
{
b--;
}
}
}while(b>0);
return *tab;
}
int unique_search (int *tab, int sizetab)
{
int temps;
printf("\tA quelle valeur voulez vous votre pouls?\n");
scanf("%d", &temps);
if(temps<sizetab)
{
printf("%d", tab[temps-1]);
}
}
void min_et_max (int *tab, int sizetab)
{
int i, a, b;
int maxi, mini;
mini = tab[1];
maxi = tab [1];
for(i=0;i<sizetab;i++)
{
if (mini>=tab[i])
{
mini = tab[i];
a = i+1;
}
else if (maxi<=tab[i])
{
maxi = tab[i];
b = i+1;
}
}
printf("La valeure mini est %d a la seconde %d\n", mini, a);
printf("La valeure maxi est %d a la seconde %d\n", maxi, b);
}
void plage_moyenne (int *tab, int sizetab)
{
int mini, maxi;
int i, a;
float b;
a = 0;
int *tab2;
printf("Entrez les temps de votre plage de donnees : \n");
printf("Valeure min : ");
scanf("%d",&mini);
printf("Valeure max : ");
scanf("%d",&maxi);
tab2 = malloc(sizeof(int)*(maxi-(mini-1)));
for(i=mini-1; i<maxi; i++)
{
tab2[a]=tab[i];
a++;
}
b = 0;
for (i=0; i<a; i++)
{
b += tab2[i];
}
b = b/(maxi-(mini-1));
printf("La moyenne de pouls de votre plage def est de %.2f", b);
}
|
C
|
//今儿又是活力满满的一天呢~
#define _CRT_SECURE_NO_WARNINGS 1
#include <stdio.h>
unsigned int Gcd(unsigned M, unsigned N)//欧几里得算法 时间复杂度O(logN)
{
unsigned int Rem;
while (N>0)
{
Rem = M%N;
M = N;
N = Rem;
}
return M;
}
int main(void)
{
int a = 50;
int b = 15;
unsigned int ret = Gcd(a, b);
printf("%d ", ret);
return 0;
}
|
C
|
#include <stdio.h>
#include <unistd.h>
#include <stdbool.h>
#include <stdlib.h>
int main(int argc, char* argv[]){
char c;
int opt;
bool lORs = true;
while((opt=getopt(argc, argv, ":ls")) != -1){
switch(opt){
case 'l':
lORs = true;
break;
case 's':
lORs = false;
break;
default:
lORs = true;
break;
}
}
if(lORs){
while(c!='\n'){
c = getc(stdin);
putc(c, stdout);
}
}else{
while(1){
read(0, stdin, 1);
write(1, stdin, 1);
}
}
return 0;
}
|
C
|
#include <stdio.h>
void main()
{
int n;
scanf("%d",&n);
if(n%2==0)
printf("Even\n");
else
printf("Odd\n");
}
|
C
|
#include <stdio.h>
#include "util.h"
int main() {
char c;
char open[100];
int index = 0;
while((c = getchar()) != '\n') {
switch(c) {
case '{':
case '[':
case '(':
open[index++] = c;
break;
case '}':
case ']':
case ')':
open[--index] = NULL;
break;
}
}
if (index) {
printf("You have an unclosed bracket");
} else {
printf("All good");
}
return 0;
}
|
C
|
#include <stdio.h>
/* Excercise 1-14 Write a program to print a histogram of the lengths of words
in its input. It is easy to draw the histogram with the bars horizal; a
vertical orientation is more challenging */
int main() {
// we need to store the lengths in an array from 0 to 20
int length[20];
int c,i,j,alength;
//initialize variables
alength = 0;
for (i=1;i<21;++i){
length[i] = 0;
}
while ((c=getchar()) != EOF) {
if (c == ' ' || c == '\t' || c=='\n'){
++length[alength];
alength = 0;
} else {
++alength;
}
// We now make the histogram
}
for (i=1;i<21;++i){
printf("%d\t|",i);
for (j=0;j<length[i];++j){
putchar('*');
}
putchar('\n');
}
}
|
C
|
/***************************************************
FILE: Transformations.c
AUTHOR: tbl - based on Texture Town, Spring 2010
DATE: 11/04/10
***************************************************/
#include "Transformations.h"
#include "Shapes.h"
/**************************************************
Transformations
**************************************************/
void my_trans(GLfloat x, GLfloat y, GLfloat z) { // translates the camera
my_cam.pos[0] = my_cam.pos[0] + x;
my_cam.pos[1] = my_cam.pos[1] + y;
my_cam.pos[2] = my_cam.pos[2] + z;
my_cam.at[0] += x;
my_cam.at[1] += y;
my_cam.at[2] += z;
}
void real_translation(OBJECT *po, GLfloat x, GLfloat y, GLfloat z) { // translates the shapes
int i, j;
for(i = 0; i <= crt_vs; i++)
{
for(j = 0; j <= crt_rs; j++)
{
po->shape_verts[i][j][0] += x; // translate across x
po->shape_verts[i][j][1] += y; // translates across y
po->shape_verts[i][j][2] += z; // translates across z
}
}
}
void real_scaling(OBJECT *po, GLfloat sx, GLfloat sy, GLfloat sz) { // scales the object
int i, j;
for(i = 0; i <= crt_vs; i++)
{
for(j = 0; j <= crt_rs; j++)
{
po->shape_verts[i][j][0] = po->shape_verts[i][j][0] * sx; // scales x
po->shape_verts[i][j][1] = po->shape_verts[i][j][1] * sy; // scales y
po->shape_verts[i][j][2] = po->shape_verts[i][j][2] * sz; // scales z
po->shape_normals[i][j][0] = po->shape_normals[i][j][0] * sx; // scales x
po->shape_normals[i][j][1] = po->shape_normals[i][j][1] * sy; // scales y
po->shape_normals[i][j][2] = po->shape_normals[i][j][2] * sz; // scales z
}
}
}
void real_rotation(OBJECT *po, GLfloat deg, GLfloat x, GLfloat y, GLfloat z) { // rotates the shapes
GLfloat theta = (deg * M_PI/180); // deg to rotate by
int i, j;
for(i = 0; i <= crt_vs; i++)
{
for(j = 0; j <= crt_rs; j++)
{
GLfloat X = po->shape_verts[i][j][0];
GLfloat Y = po->shape_verts[i][j][1];
GLfloat Z = po->shape_verts[i][j][2];
GLfloat nX = po->shape_normals[i][j][0];
GLfloat nY = po->shape_normals[i][j][1];
GLfloat nZ = po->shape_normals[i][j][2];
if(x == 1) // rotate X
{
po->shape_verts[i][j][1] = Y * cos(theta) - Z * sin(theta);
po->shape_verts[i][j][2] = Z * cos(theta) + Y * sin(theta);
po->shape_normals[i][j][1] = nY * cos(theta) - nZ * sin(theta);
po->shape_normals[i][j][2] = nZ * cos(theta) + nY * sin(theta);
}
else if(y ==1) // rotate Y
{
po->shape_verts[i][j][0] = X * cos(theta) + Z * sin(theta);
po->shape_verts[i][j][2] = Z * cos(theta) - X * sin(theta);
po->shape_normals[i][j][0] = nX * cos(theta) + nZ * sin(theta);
po->shape_normals[i][j][2] = nZ * cos(theta) - nX * sin(theta);
}
else if (z ==1){ // rotate Z
po->shape_verts[i][j][0] = X * cos(theta) - Y * sin(theta);
po->shape_verts[i][j][1] = X * sin(theta) + Y * cos(theta);
po->shape_normals[i][j][0] = nX * cos(theta) - nY * sin(theta);
po->shape_normals[i][j][1] = nX * sin(theta) + nY * cos(theta);
}
}
}
}
void flashlightRotation(GLfloat deg, GLfloat x, GLfloat y, GLfloat z) // rotates the flashlight in place
{
GLfloat theta = (deg * M_PI/180);
GLfloat aX = my_cam.at[0]; // x position
GLfloat aY = my_cam.at[1]; // y position
GLfloat aZ = my_cam.at[2]; // z position
if(x == 1) // rotate X
{
my_cam.at[1] = aY * cos(theta) - aZ * sin(theta);
my_cam.at[2] = aZ * cos(theta) + aY * sin(theta);
}
else if(y ==1) // rotate Y
{
my_cam.at[0] = aX * cos(theta) + aZ * sin(theta);
my_cam.at[2] = aZ * cos(theta) - aX * sin(theta);
}
else if (z ==1){ // rotate Z
my_cam.at[0] = aX * cos(theta) - aY * sin(theta);
my_cam.at[1] = aX * sin(theta) + aY * cos(theta);
}
}
|
C
|
/* Program de sortare a unui vector prin interclasare */
#include <stdio.h>
#include <conio.h>
#define NMAX 100
int a[NMAX]; /* vectorul de sortat */
void afisare(int n)
{ /* afișarea vectorului */
int i;
printf("\n");
for(i=0; i<n; i++)
{
printf("%5d", a[i]);
if(((i+1) % 10)==0) printf("\n");
}
printf("\n");
}
void comb(int inf, int med, int sup)
{ /* interclasarea vectorilor a[inf .. med] și a[med+1 .. sup] */
int i, j, k, l;
int b[NMAX];
i = inf;
j = med+1;
k = inf;
while((i<=med)&(j<=sup))
{
if(a[i]<=a[j])
{
b[k] = a[i];
i++;
}
else
{
b[k] = a[j];
j++;
}
k++;
}
for(l=i; l<=med; l++)
{ /* au ramas elemente in stânga */
b[k] = a[l];
k++;
}
for(l=j;l<=sup;l++)
{ /* au ramas elemente in dreapta */
b[k] = a[l];
k++;
}
/* secvența între inf și sup este sortată */
for(l=inf; l<=sup; l++) a[l] = b[l];
}
void divide_impera(int inf,int sup)
{
int med;
if(inf<sup)
{
med = (inf+sup) / 2;
divide_impera(inf, med);
divide_impera(med+1, sup);
comb(inf, med, sup);
}
}
int main(void)
{
int i, n;
printf("\nIntroduceți numarul de elemente n=");
scanf("%d",&n);
printf("\nIntroduceti elementele vectorului:\n");
for(i=0;i<n;i++)
{
printf("a[%d]=", i);
scanf("%d", &a[i]);
}
printf("\nVECTORUL NESORTAT\n");
afisare(n);
divide_impera(0,n-1);
printf("\nVECTORUL SORTAT\n");
afisare(n);
getch();
return 0;
}
|
C
|
#include <stdio.h>
#include <math.h>
/***********************************************************
*Faça um algoritmo que calcule a área de uma esfera, *
*sendo que o comprimento do raio é informado pelo usuário. *
*A área da esfera é calculada multiplicando-se 4 vezes Pi *
*ao raio ao quadrado. *
************************************************************/
float raio;
float area;
main () {
printf("\ninforme o raio: ");
scanf("%f",&raio);
area = (M_PI*4)*(raio*raio);
printf("\n area e %.2f\n",area);
}
|
C
|
/*++
Copyright (c) 2018 Trent Nelson <[email protected]>
Module Name:
CreateStringArray.c
Abstract:
This module implements the functionality to create a new STRING_ARRAY
structure as part of the steps required to create a new STRING_TABLE
structure. Routines are currently provided for creating an array from a
delimited string.
--*/
#include "stdafx.h"
_Use_decl_annotations_
PSTRING_ARRAY
CreateStringArrayFromDelimitedString_2(
PRTL Rtl,
PALLOCATOR StringTableAllocator,
PALLOCATOR StringArrayAllocator,
PCSTRING String,
CHAR Delimiter,
USHORT StringTablePaddingOffset,
USHORT StringTableStructSize,
PPSTRING_TABLE StringTablePointer
)
/*++
Routine Description:
Creates a new STRING_ARRAY structure that contains entries for each string
in the delimited input String. E.g. if String->Buffer pointed to a string
"foo;bar", then calling this method with a Delimiter of ';' would create a
new STRING_ARRAY with two elements, 'foo' and 'bar'.
If the routine determines the STRING_ARRAY structure can fit within the
trailing padding of a STRING_TABLE structure, it will allocate memory for
the table instead and initialize itself at the relevant location offset,
updating StringTablePointer with the base address of the allocation.
This version differs from version 1 in that the Rtl bitmap routines are
not used for string processing.
Arguments:
Rtl - Supplies a pointer to an initialized RTL structure.
StringTableAllocator - Supplies a pointer to an ALLOCATOR structure which
will be used for creating the STRING_TABLE.
StringArrayAllocator - Supplies a pointer to an ALLOCATOR structure which
may be used to create the STRING_ARRAY if it cannot fit within the
padding of the STRING_TABLE structure. This is kept separate from the
StringTableAllocator due to the stringent alignment requirements of the
string table.
String - Supplies a pointer to a STRING structure that represents the
delimited string to construct the STRING_ARRAY from.
Delimiter - Supplies the character that delimits individual elements of
the String pointer (e.g. ':', ' ').
StringTablePaddingOffset - Supplies a USHORT value indicating the number
of bytes from the STRING_TABLE structure where the padding begins.
This value is used in conjunction with StringTableStructSize below
to determine if the STRING_ARRAY will fit within the table.
StringTableStructSize - Supplies a USHORT value indicating the size of the
STRING_TABLE structure, in bytes. This is used in conjunction with the
StringTablePaddingOffset parameter above.
StringTablePointer - Supplies a pointer to a variable that receives the
address of the STRING_TABLE structure if one could be allocated. If
not, the pointer will be set to NULL.
Return Value:
A pointer to a valid PSTRING_ARRAY structure on success, NULL on failure.
--*/
{
BOOLEAN Final;
BOOLEAN IsSuperfluous;
USHORT Index;
USHORT Count;
USHORT StringLength;
USHORT MinimumLength;
USHORT MaximumLength;
USHORT NumberOfElements;
USHORT AlignedMaxLength;
USHORT AlignedStringTablePaddingOffset;
USHORT StringTableRemainingSpace;
USHORT FinalLength;
ULONG AlignedSize;
ULONG StringBufferAllocSize;
ULONG TotalAllocSize;
ULONG BufferOffset;
ULONG AlignedBufferOffset;
ULONG PaddingSize;
ULONG StringElementsSize;
ULONG_INTEGER Length;
PCHAR Char;
PCHAR Start;
PCHAR FinalStart;
PCHAR PreviousDelimiter;
PCHAR DestBuffer;
PSTRING DestString;
PSTRING_TABLE StringTable = NULL;
PSTRING_ARRAY NewArray = NULL;
//
// Validate arguments.
//
if (!ARGUMENT_PRESENT(Rtl)) {
return NULL;
}
if (!ARGUMENT_PRESENT(StringTableAllocator)) {
return NULL;
}
if (!ARGUMENT_PRESENT(StringArrayAllocator)) {
return NULL;
}
if (!ARGUMENT_PRESENT(String)) {
return NULL;
}
if (String->Length == 0) {
return NULL;
}
if (!ARGUMENT_PRESENT(StringTablePointer)) {
return NULL;
}
//
// Initialize variables before the loop.
//
StringBufferAllocSize = 0;
MinimumLength = (USHORT)-1;
MaximumLength = 0;
Count = 0;
Start = String->Buffer;
PreviousDelimiter = NULL;
Length.LongPart = 0;
//
// Enumerate over the string buffer, looking for delimiters, such that
// individual beginning and end markers for each string can be ascertained.
// Use this information to calculate the total allocation size required to
// store a 16-byte aligned copy of each string.
//
Final = FALSE;
for (Index = 0; Index < String->Length; Index++) {
//
// Resolve the character for this offset.
//
Char = &String->Buffer[Index];
//
// If it's not a delimiter character, continue the search.
//
if (*Char != Delimiter) {
continue;
}
//
// We've found a delimiter character, and need to determine if it's
// depicting the valid end point of string, or if it's superfluous.
// A superfluous delimiter is one that is at the very start of the
// string, or one that immediately follows a previous delimiter (i.e.
// "foo;;bar").
//
IsSuperfluous = (
Char == Start || (
PreviousDelimiter &&
(Char - sizeof(*Char)) == PreviousDelimiter
)
);
if (IsSuperfluous) {
//
// The delimiter is superfluous. Mark it as our previous delimiter
// and continue the loop.
//
PreviousDelimiter = Char;
continue;
}
//
// We've found a seemingly valid delimiter. We need to determine where
// the string started, which we can ascertain from either the start of
// the string (e.g. String->Buffer) if the previous delimiter is null,
// or previous delimiter + sizeof(*Char) if it is not null.
//
if (!PreviousDelimiter) {
//
// We initialize Start to String->Buffer prior to entering the loop,
// so we do not need to do anything here.
//
NOTHING;
} else {
//
// Otherwise, assume the start is the character after the last
// delimiter we saw.
//
Start = PreviousDelimiter + sizeof(*Char);
}
//
// Calculate the length for this string element.
//
Length.LongPart = (ULONG)((ULONG_PTR)Char - (ULONG_PTR)Start);
//
// Sanity check the size.
//
ASSERT(!Length.HighPart);
//
// Calculate the aligned size, then add to our running count.
//
AlignedSize = ALIGN_UP(Length.LowPart, 16);
StringBufferAllocSize += AlignedSize;
//
// Update minimum and maximum length if applicable.
//
if (Length.LowPart < MinimumLength) {
MinimumLength = Length.LowPart;
}
if (Length.LowPart > MaximumLength) {
MaximumLength = Length.LowPart;
}
//
// Increment our counter.
//
Count++;
//
// Update the previous delimiter to point at this delimiter.
//
PreviousDelimiter = Char;
}
//
// We've finished enumerating all the characters in the string buffer. The
// delimited input string is not required to terminate the final string
// element with a delimiter, thus, we need to check if there's a final
// string here.
//
// There's a final string if any of the following conditions hold true:
//
// - If previous delimiter is null (i.e. no delimiters seen).
// - Else, if previous delimiter was not final character of string.
//
Final = FALSE;
if (!PreviousDelimiter) {
//
// No delimiter was seen, so the "delimited string" passed to us on
// input was simply a single string. If this is the case, then there's
// an invariant that count should be 0 at this point. Assert this now.
//
ASSERT(Count == 0);
//
// Toggle the final flag to true. Start will already be set to the
// value of String->Buffer. Assert this now.
//
Final = TRUE;
ASSERT(Start == String->Buffer);
} else if (Char != PreviousDelimiter) {
//
// The string didn't end with a delimiter, which means a final string
// will be present, e.g. the "bar" string in "foo;bar". Toggle the
// final flag to true and set the start pointer to the character after
// the previous delimiter.
//
Final = TRUE;
Start = PreviousDelimiter + sizeof(*Char);
}
//
// Check to see if the final flag was set and process accordingly.
//
if (Final) {
//
// N.B. The remaining logic is identical to how a match is handled in
// the loop above.
//
//
// Calculate the length for this string element.
//
Length.LongPart = (ULONG)(
((ULONG_PTR)(String->Buffer + String->Length)) -
((ULONG_PTR)Start)
);
//
// Sanity check the size.
//
ASSERT(!Length.HighPart);
//
// Calculate the aligned size, then add to our running count.
//
AlignedSize = ALIGN_UP(Length.LowPart, 16);
StringBufferAllocSize += AlignedSize;
//
// Update minimum and maximum length if applicable.
//
if (Length.LowPart < MinimumLength) {
MinimumLength = Length.LowPart;
}
if (Length.LowPart > MaximumLength) {
MaximumLength = Length.LowPart;
}
//
// Update our counter.
//
Count++;
//
// Update the final start pointer and length, simplifying our life
// later in the routine.
//
FinalStart = Start;
FinalLength = Length.LowPart;
}
//
// We've finished the initial pre-processing of the string, identifying the
// number of underlying elements and the required allocation sizes. Verify
// the count; if it's 0, the user has failed to provide a valid input
// string (e.g. ";;;;;;;;;").
//
if (!Count) {
goto End;
}
//
// Capture the number of elements we processed.
//
NumberOfElements = Count;
//
// Calculate the size required for the STRING elements, minus 1 to account
// for the fact that STRING_ARRAY includes a single STRING struct at the
// end of it via the ANYSIZE_ARRAY size specifier.
//
StringElementsSize = (NumberOfElements - 1) * sizeof(STRING);
//
// Calculate the offset where the first string buffer will reside, and the
// aligned value of the offset. Make sure the final buffer offset is
// 16-bytes aligned, adjusting padding as necessary.
//
BufferOffset = sizeof(STRING_ARRAY) + StringElementsSize;
AlignedBufferOffset = ALIGN_UP(BufferOffset, 16);
PaddingSize = (AlignedBufferOffset - BufferOffset);
//
// Calculate the final size.
//
TotalAllocSize = (
//
// Account for the STRING_ARRAY structure.
//
sizeof(STRING_ARRAY) +
//
// Account for the array of STRING structures, minus 1.
//
StringElementsSize +
//
// Account for any alignment padding we needed to do.
//
PaddingSize +
//
// Account for the backing buffer sizes.
//
StringBufferAllocSize
);
//
// Check to see if we can fit our entire allocation within the remaining
// space of the string table.
//
AlignedStringTablePaddingOffset = (
ALIGN_UP_POINTER(StringTablePaddingOffset)
);
StringTableRemainingSpace = (
StringTableStructSize -
AlignedStringTablePaddingOffset
);
if (StringTableRemainingSpace >= TotalAllocSize) {
//
// We can fit our copy of the STRING_ARRAY within the trailing padding
// bytes of the STRING_TABLE, so, allocate sufficient space for that
// struct, then carve out our table pointer.
//
StringTable = (PSTRING_TABLE)(
StringTableAllocator->AlignedCalloc(
StringTableAllocator->Context,
1,
StringTableStructSize,
STRING_TABLE_ALIGNMENT
)
);
if (!StringTable) {
//
// If we couldn't allocate 512-bytes for the table, I don't think
// there is much point trying to allocate <= 512-bytes for just
// the array if memory is that tight.
//
goto Error;
}
//
// Allocation was successful, carve out the pointer to the NewArray.
// (We use RtlOffsetToPointer() here instead of StringTable->StringArray
// as the former will be done against the aligned padding size and isn't
// dependent upon knowing anything about the STRING_TABLE struct other
// than the offset and struct size parameters passed in as arguments.)
//
NewArray = (PSTRING_ARRAY)(
RtlOffsetToPointer(
StringTable,
AlignedStringTablePaddingOffset
)
);
} else {
//
// We can't embed ourselves within the trailing STRING_TABLE padding.
// Clear the pointer to make it clear no StringTable was allocated,
// and then try allocating sufficient space just for the STRING_ARRAY.
//
StringTable = NULL;
NewArray = (PSTRING_ARRAY)(
StringArrayAllocator->Calloc(
StringArrayAllocator->Context,
1,
TotalAllocSize
)
);
}
//
// Ensure we allocated sufficient space.
//
if (!NewArray) {
goto Error;
}
//
// Initialize the scalar fields.
//
NewArray->SizeInQuadwords = (USHORT)(TotalAllocSize >> 3);
NewArray->NumberOfElements = NumberOfElements;
NewArray->MinimumLength = MinimumLength;
NewArray->MaximumLength = MaximumLength;
//
// Initialize the StringTable field; if it's NULL at this point, that's ok.
//
NewArray->StringTable = StringTable;
//
// Initialize destination string pointer. As the STRING structures are
// contiguous, we can just bump this pointer (e.g. DestString++) to advance
// to the next record whilst carving out individual string elements.
//
DestString = NewArray->Strings;
//
// Initialize the destination buffer to the point after the new STRING_ARRAY
// struct and trailing array of actual STRING structs. We then carve out
// new buffer pointers for the destination strings as we loop through the
// source string array and copy strings over.
//
DestBuffer = (PCHAR)(RtlOffsetToPointer(NewArray, BufferOffset));
//
// Reset the count. We can perform an invariant test at the end of this
// loop to ensure we carved out the number of strings we were expecting to.
//
Count = 0;
//
// Reset other variables prior to loop entry.
//
Start = String->Buffer;
PreviousDelimiter = NULL;
Length.LongPart = 0;
//
// Enumerate over the string buffer for a second time, carving out the
// relevant STRING structures as we detect delimiters. The general logic
// here for identifying each string element is identical to the first loop.
//
for (Index = 0; Index < String->Length; Index++) {
//
// Resolve the character for this offset.
//
Char = &String->Buffer[Index];
//
// If it's not a delimiter character, continue the search.
//
if (*Char != Delimiter) {
continue;
}
//
// We've found a delimiter character, and need to determine if it's
// depicting the valid end point of string, or if it's superfluous.
// A superfluous delimiter is one that is at the very start of the
// string, or one that immediately follows a previous delimiter (i.e.
// "foo;;bar").
//
IsSuperfluous = (
Char == Start || (
PreviousDelimiter &&
(Char - sizeof(*Char)) == PreviousDelimiter
)
);
if (IsSuperfluous) {
//
// The delimiter is superfluous. Mark it as our previous delimiter
// and continue the loop.
//
PreviousDelimiter = Char;
continue;
}
//
// We've found a seemingly valid delimiter. We need to determine where
// the string started, which we can ascertain from either the start of
// the string (e.g. String->Buffer) if the previous delimiter is null,
// or previous delimiter + sizeof(*Char) if it is not null.
//
if (!PreviousDelimiter) {
//
// We initialize Start to String->Buffer prior to entering the loop,
// so we do not need to do anything here.
//
NOTHING;
} else {
//
// Otherwise, assume the start is the character after the last
// delimiter we saw.
//
Start = PreviousDelimiter + sizeof(*Char);
}
//
// Calculate the length for this string element.
//
StringLength = (USHORT)((ULONG_PTR)Char - (ULONG_PTR)Start);
//
// Calculate the aligned length.
//
AlignedMaxLength = ALIGN_UP(StringLength, 16);
//
// Fill out the destination string details.
//
DestString->Length = StringLength;
DestString->MaximumLength = AlignedMaxLength;
DestString->Buffer = DestBuffer;
//
// Copy the source string over.
//
CopyMemory(DestString->Buffer, Start, StringLength);
//
// Carve out the next destination buffer.
//
DestBuffer += AlignedMaxLength;
//
// Compute the CRC32 checksum and store in the hash field.
//
DestString->Hash = ComputeCrc32ForString(DestString);
//
// Increment our count and advance our DestString pointer.
//
Count++;
DestString++;
//
// Update the previous delimiter to point at this delimiter.
//
PreviousDelimiter = Char;
}
//
// Check to see if the final flag was set and process accordingly.
//
if (Final) {
//
// N.B. We can use the values we saved earlier for this final string
//
Start = FinalStart;
StringLength = FinalLength;
//
// N.B. Remaining logic is identical to how a match is handled in
// the loop above.
//
//
// Calculate the aligned length.
//
AlignedMaxLength = ALIGN_UP(StringLength, 16);
//
// Fill out the destination string details.
//
DestString->Length = StringLength;
DestString->MaximumLength = AlignedMaxLength;
DestString->Buffer = DestBuffer;
//
// Copy the source string over.
//
CopyMemory(DestString->Buffer, Start, StringLength);
//
// Compute the CRC32 checksum and store in the hash field.
//
DestString->Hash = ComputeCrc32ForString(DestString);
//
// Increment our count.
//
Count++;
}
//
// Invariant check: our count should equal the number of elements we
// captured earlier.
//
ASSERT(Count == NumberOfElements);
//
// We're done.
//
goto End;
Error:
if (NewArray) {
PVOID Address;
//
// If StringTable has a value here, it is the address that should be
// freed, not NewArray.
//
Address = (PVOID)StringTable;
if (Address) {
StringTableAllocator->AlignedFree(StringTableAllocator->Context,
Address);
} else {
Address = (PVOID)NewArray;
StringArrayAllocator->Free(StringArrayAllocator->Context, Address);
}
//
// Clear both pointers.
//
StringTable = NULL;
NewArray = NULL;
}
//
// Intentional follow-on.
//
End:
//
// Update the caller's StringTablePointer (which may be NULL if we didn't
// allocate a StringTable or encountered an error).
//
*StringTablePointer = StringTable;
//
// Return the new string array.
//
return NewArray;
}
// vim:set ts=8 sw=4 sts=4 tw=80 expandtab :
|
C
|
#include <stdio.h>
#include <stdio.h>
void swap(int *x, int *y)
{
int c = *x;
*x = *y;
*y = c;
}
int main (void)
{
int x = 2;
int y = 3;
printf ("%d %d\n", x, y);
swap(&x,&y);
printf ("%d %d\n",x, y);
int *xp = &x;
int *yp = &y;
printf ("%p %p\n", &x, &y);
}
|
C
|
#include "JackTokenizer.h"
#include <string.h>
#include <dirent.h>
#include <errno.h>
#define JACK_FILENAME_MAX_LENGTH 255
#define XML_FILENAME_MAX_LENGTH JACK_FILENAME_MAX_LENGTH // length('.jack') - length('T.xml') = 0
#define JACK_DIRNAME_MAX_LENGTH 255
int analyzeByJackDir(DIR *dpJack, char *jackDirName);
int analyzeByJackFile(char *jackFileName);
int analyze(char *xmlFilePath, char *jackFilePath);
bool isJackFileName(char *jackFileName);
void createJackFilePath(char *jackDirName, char *jackFileName, char *jackFilePath);
void createXmlFilePathFromDirName(char *jackDirName, char *jackFileName, char *xmlFilePath);
void createXmlFilePathFromJackFileName(char *jackFileName, char *xmlFilePath);
void writeTokens(FILE *fp, JackTokenizer tokenizer);
void writeToken(FILE *fp, JackTokenizer tokenizer);
void writeKeyword(FILE *fp, JackTokenizer tokenizer);
void writeSymbol(FILE *fp, JackTokenizer tokenizer);
void writeIdentifier(FILE *fp, JackTokenizer tokenizer);
void writeIntegerConstant(FILE *fp, JackTokenizer tokenizer);
void writeStringConstant(FILE *fp, JackTokenizer tokenizer);
int main(int argc, char *argv[])
{
char *jackFileOrDirName;
DIR *dpJack;
if (argc != 2) {
fprintf(stderr, "Usage: JackAnalyzer source\n");
return 1;
}
jackFileOrDirName = argv[1];
if (strstr(jackFileOrDirName, "/") != NULL) {
fprintf(stderr, "Error: Jack dirname or filename is invalid. '/' can't be included. (%s)\n", jackFileOrDirName);
return 1;
}
dpJack = opendir(jackFileOrDirName);
if (dpJack != NULL) {
int exitNo = analyzeByJackDir(dpJack, jackFileOrDirName);
closedir(dpJack);
return exitNo;
} else if (errno == ENOTDIR) {
return analyzeByJackFile(jackFileOrDirName);
} else {
fprintf(stderr, "Error: Jack dirname or filename is not found. (%s)\n", jackFileOrDirName);
return 1;
}
return 0;
}
int analyzeByJackDir(DIR *dpJack, char *jackDirName)
{
struct dirent *dEntry;
char xmlFilePath[JACK_DIRNAME_MAX_LENGTH + XML_FILENAME_MAX_LENGTH + 1];
char jackFilePath[JACK_DIRNAME_MAX_LENGTH + JACK_FILENAME_MAX_LENGTH + 1];
if (strlen(jackDirName) > JACK_DIRNAME_MAX_LENGTH) {
fprintf(
stderr,
"Error: Jack dirname max size is invalid. Max size is %d. (%s) is %lu\n",
JACK_DIRNAME_MAX_LENGTH,
jackDirName,
strlen(jackDirName)
);
return 1;
}
while ((dEntry = readdir(dpJack)) != NULL) {
char *jackFileName = dEntry->d_name;
if (dEntry->d_type != DT_REG) { // not file
continue;
}
if (! isJackFileName(jackFileName)) {
continue;
}
if (strlen(jackFileName) > JACK_FILENAME_MAX_LENGTH) {
fprintf(
stderr,
"Skip: Jack filename max size is invalid. Max size is %d. (%s) is %lu\n",
JACK_FILENAME_MAX_LENGTH,
jackFileName,
strlen(jackFileName)
);
continue;
}
createJackFilePath(jackDirName, jackFileName, jackFilePath);
createXmlFilePathFromDirName(jackDirName, jackFileName, xmlFilePath);
if (analyze(xmlFilePath, jackFilePath) != 0) {
return 0;
}
}
return 0;
}
int analyzeByJackFile(char *jackFileName)
{
char xmlFilePath[XML_FILENAME_MAX_LENGTH];
if (! isJackFileName(jackFileName)) {
fprintf(stderr, "Error: Jack filename extension(.jack) is invalid. (%s)\n", jackFileName);
return 1;
}
if (strlen(jackFileName) > JACK_FILENAME_MAX_LENGTH) {
fprintf(
stderr,
"Error: Jack filename max size is invalid. Max size is %d. (%s) is %lu\n",
JACK_FILENAME_MAX_LENGTH,
jackFileName,
strlen(jackFileName)
);
return 1;
}
createXmlFilePathFromJackFileName(jackFileName, xmlFilePath);
return analyze(xmlFilePath, jackFileName);
}
int analyze(char *xmlFilePath, char *jackFilePath)
{
FILE *fpJack, *fpXml;
JackTokenizer tokenizer;
if ((fpJack = fopen(jackFilePath, "r")) == NULL) {
fprintf(stderr, "Error: jack file not found (%s)\n", jackFilePath);
return 1;
}
if ((fpXml = fopen(xmlFilePath, "w")) == NULL) {
fprintf(stderr, "Error: xml file not open (%s)\n", xmlFilePath);
fclose(fpJack);
return 1;
}
tokenizer = JackTokenizer_init(fpJack);
writeTokens(fpXml, tokenizer);
fclose(fpXml);
fclose(fpJack);
return 0;
}
bool isJackFileName(char *jackFileName)
{
size_t jackFileNameLength = strlen(jackFileName);
char *jackExtention = ".jack";
size_t jackExtentionLength = strlen(jackExtention);
if (jackFileNameLength <= jackExtentionLength) {
return false;
}
// jack filename is Xxx.jack
if (strcmp(jackFileName + jackFileNameLength - jackExtentionLength, jackExtention) != 0) {
return false;
}
return true;
}
void createJackFilePath(char *jackDirName, char *jackFileName, char *jackFilePath)
{
// jackFilePath is {jackDirName}/{jackFileName}
strcpy(jackFilePath, jackDirName);
strcat(jackFilePath, "/");
strcat(jackFilePath, jackFileName);
}
void createXmlFilePathFromDirName(char *jackDirName, char *jackFileName, char *xmlFilePath)
{
// xmlFilePath is {jackDirName}/{jackFileName} - ".jack" + "T.xml"
strcpy(xmlFilePath, jackDirName);
strcat(xmlFilePath, "/");
strncat(xmlFilePath, jackFileName, strlen(jackFileName) - strlen(".jack"));
strcat(xmlFilePath, "T.xml");
}
void createXmlFilePathFromJackFileName(char *jackFileName, char *xmlFilePath)
{
// XmlFilePath is {jackFileName} - ".jack" + "T.xml"
size_t xmlFileNamePrefixLength = strlen(jackFileName) - strlen(".jack");
strncpy(xmlFilePath, jackFileName, xmlFileNamePrefixLength);
xmlFilePath[xmlFileNamePrefixLength] = '\0';
strcat(xmlFilePath, "T.xml");
}
void writeTokens(FILE *fp, JackTokenizer tokenizer)
{
fprintf(fp, "<tokens>\n");
while (JackTokenizer_hasMoreTokens(tokenizer)) {
JackTokenizer_advance(tokenizer);
writeToken(fp, tokenizer);
}
fprintf(fp, "</tokens>\n");
}
void writeToken(FILE *fp, JackTokenizer tokenizer)
{
switch (JackTokenizer_tokenType(tokenizer))
{
case JACK_TOKENIZER_TOKEN_TYPE_KEYWORD:
writeKeyword(fp, tokenizer);
break;
case JACK_TOKENIZER_TOKEN_TYPE_SYMBOL:
writeSymbol(fp, tokenizer);
break;
case JACK_TOKENIZER_TOKEN_TYPE_IDENTIFIER:
writeIdentifier(fp, tokenizer);
break;
case JACK_TOKENIZER_TOKEN_TYPE_INT_CONST:
writeIntegerConstant(fp, tokenizer);
break;
case JACK_TOKENIZER_TOKEN_TYPE_STRING_CONST:
writeStringConstant(fp, tokenizer);
break;
default:
break;
}
}
void writeKeyword(FILE *fp, JackTokenizer tokenizer)
{
struct keyword {
JackTokenizer_Keyword id;
char *string;
};
struct keyword keywords[] = {
{ JACK_TOKENIZER_KEYWORD_CLASS, "class" },
{ JACK_TOKENIZER_KEYWORD_METHOD, "method" },
{ JACK_TOKENIZER_KEYWORD_FUNCTION, "function" },
{ JACK_TOKENIZER_KEYWORD_CONSTRUCTION, "constructor" },
{ JACK_TOKENIZER_KEYWORD_INT, "int" },
{ JACK_TOKENIZER_KEYWORD_BOOLEAN, "boolean" },
{ JACK_TOKENIZER_KEYWORD_CHAR, "char" },
{ JACK_TOKENIZER_KEYWORD_VOID, "void" },
{ JACK_TOKENIZER_KEYWORD_VAR, "var" },
{ JACK_TOKENIZER_KEYWORD_STATIC, "static" },
{ JACK_TOKENIZER_KEYWORD_FIELD, "field" },
{ JACK_TOKENIZER_KEYWORD_LET, "let" },
{ JACK_TOKENIZER_KEYWORD_DO, "do" },
{ JACK_TOKENIZER_KEYWORD_IF, "if" },
{ JACK_TOKENIZER_KEYWORD_ELSE, "else" },
{ JACK_TOKENIZER_KEYWORD_WHILE, "while" },
{ JACK_TOKENIZER_KEYWORD_RETURN, "return" },
{ JACK_TOKENIZER_KEYWORD_TRUE, "true" },
{ JACK_TOKENIZER_KEYWORD_FALSE, "false" },
{ JACK_TOKENIZER_KEYWORD_NULL, "null" },
{ JACK_TOKENIZER_KEYWORD_THIS, "this" },
};
JackTokenizer_Keyword id = JackTokenizer_keyword(tokenizer);
fprintf(fp, "<keyword> ");
for (size_t i = 0; i < sizeof(keywords) / sizeof(keywords[0]); i++) {
if (id == keywords[i].id) {
fprintf(fp, "%s", keywords[i].string);
break;
}
}
fprintf(fp, " </keyword>\n");
}
void writeSymbol(FILE *fp, JackTokenizer tokenizer)
{
char token[JACK_TOKEN_SIZE];
JackTokenizer_symbol(tokenizer, token);
fprintf(fp, "<symbol> ");
if (strcmp(token, "<") == 0) {
fprintf(fp, "<");
} else if (strcmp(token, ">") == 0) {
fprintf(fp, ">");
} else if (strcmp(token, "&") == 0) {
fprintf(fp, "&");
} else {
fprintf(fp, "%s", token);
}
fprintf(fp, " </symbol>\n");
}
void writeIdentifier(FILE *fp, JackTokenizer tokenizer)
{
char token[JACK_TOKEN_SIZE];
JackTokenizer_identifier(tokenizer, token);
fprintf(fp, "<identifier> %s </identifier>\n", token);
}
void writeIntegerConstant(FILE *fp, JackTokenizer tokenizer)
{
int intVal;
JackTokenizer_intVal(tokenizer, &intVal);
fprintf(fp, "<integerConstant> %d </integerConstant>\n", intVal);
}
void writeStringConstant(FILE *fp, JackTokenizer tokenizer)
{
char token[JACK_TOKEN_SIZE];
JackTokenizer_stringVal(tokenizer, token);
fprintf(fp, "<stringConstant> %s </stringConstant>\n", token);
}
|
C
|
#include<stdio.h>
int main()
{
int x;
printf("enter the weekday number");
scanf("%d",x);
switch(x)
{
case 1:printf("monday");
break;
case 2:printf("tuesday");
break;
case 3:printf("wednesday");
break;
case 4:printf("thursday");
break;
case 5:printf("friday");
break;
case 6:printf("saturday");
break;
case 7:printf("sunday");
break;
default :printf("its not your day");
}
return 0;
}
|
C
|
#include "holberton.h"
#include <stdio.h>
/**
* _strspn - dfgddf
* @s: ffdsfds
* @accept: fdsds
*
* Return: dsfd
*/
unsigned int _strspn(char *s, char *accept)
{
char c, *p, *str;
for (str = s, c = *str; c != 0; str++, c = *str)
{
for (p = accept; *p != 0; p++)
{
if (c == *p)
{
goto next;
}
}
break;
next:;
}
return (str - s);
}
|
C
|
///
/// main source https://steemit.com/utopian-io/@cuthamza/steps-to-create-animated-text-in-c-programming-language
///
#include <stdio.h>
#include <unistd.h>
#include "c-columns.h"
#include "c-tekswarna.h"
#include "c-teksgerak.h"
#include "c-cursorback.h"
#include "c-gtkwindow.h"
#include "c-gtkhelloworld.h"
#include "c-gtk3demo-assistant.h"
#include "c-gtksimple.h"
#include "c-gtk-borderless.h"
///
/// Program utama
///
int main()
{
/// 1. Program columns mengecek jumlah kolom dan baris di terminal
/// 2. Program tekswarna menampilkan huruf berwarna
/// 3. Program teksgerak menampilkan teks yang bergerak per karakter
/// 4. Program cursorback menampilkan pergeseran kursor untuk presentase
/// 5. Program gtkwindow untuk menampilkan jendela kosong
/// 6. Program gtkhelloworld menampilkan tombol hello world
/// 7. Program gtk3demo-assistant mencoba demo bawaan gtk3
/// 8. Program gtksimple menampilkan jumlah klik
/// 9. Program gtk-borderless menampilkan foto yang bisa diketik
main_columns();
main_tekswarna();
main_teksgerak();
main_cursorback();
main_gtkwindow();
main_gtkhelloworld();
main_gtk3demo_assistant();
main_gtksimple();
main_gtk_borderless();
return 0;
}
|
C
|
#include<stdio.h>
int main()
{
double x1,y1,x2,y2,x3,y3,x4,y4;
while(scanf("%lf %lf %lf %lf %lf %lf %lf %lf",&x1,&y1,&x2,&y2,&x3,&y3,&x4,&y4)==8)
{
if(x1==x3 && y1==y3)
printf("%.3lf %.3lf\n",(x2+x4-x3),(y2+y4-y3));
else if(x1==x4 && y1==y4)
printf("%.3lf %.3lf\n",(x2+x3-x4),(y2+y3-y4));
else if(x2==x3 && y2==y3)
printf("%.3lf %.3lf\n",(x1+x4-x3),(y1+y4-y3));
else
printf("%.3lf %.3lf\n",(x1+x3-x4),(y1+y3-y4));
}
return 0;
}
|
C
|
/******************************************************************************
****汾1.0.0
****ƽ̨
****ڣ2020-07-29
****ߣQitas
****Ȩ
*******************************************************************************/
#include "stmflash.h"
#include "iap_config.h"
/*******************************************************************************
**Ϣ
**
**
**
*******************************************************************************/
u16 STMFLASH_ReadHalfWord(u32 faddr)
{
return *(vu16*)faddr;
}
/*******************************************************************************
**Ϣ
**
**
**
*******************************************************************************/
static void STMFLASH_Write_NoCheck(u32 WriteAddr,u16 *pBuffer,u16 NumToWrite)
{
u16 i;
for(i=0;i<NumToWrite;i++)
{
FLASH_ProgramHalfWord(WriteAddr,pBuffer[i]);
WriteAddr+=2;//add addr 2.
}
}
u16 STMFLASH_BUF[PAGE_SIZE / 2];//Up to 2K bytes
/*******************************************************************************
**Ϣ
**
**
**
*******************************************************************************/
void STMFLASH_Write(u32 WriteAddr,u16 *pBuffer,u16 NumToWrite)
{
u32 secpos; //ַ
u16 secoff; //ƫƵַ(16λּ)
u16 secremain; //ʣַ(16λּ)
u16 i;
u32 offaddr; //ȥ0X08000000ĵַ
if((WriteAddr < FLASH_BASE) || (WriteAddr >= FLASH_BASE + 1024 * FLASH_SIZE))return;//Ƿַ
FLASH_Unlock(); //
offaddr = WriteAddr - FLASH_BASE; //ʵƫƵַ.
secpos = offaddr / PAGE_SIZE; //ַ 0~127 for STM32F103RBT6
secoff = (offaddr % PAGE_SIZE) / 2; //ڵƫ(2ֽΪλ.)
secremain = PAGE_SIZE / 2 - secoff; //ʣռС
if(NumToWrite <= secremain)
secremain = NumToWrite;//ڸΧ
while(1)
{
STMFLASH_Read(secpos * PAGE_SIZE + FLASH_BASE, STMFLASH_BUF, PAGE_SIZE / 2);//
for(i = 0; i < secremain; i++)//У
{
if(STMFLASH_BUF[secoff + i] != 0XFFFF)break;//Ҫ
}
if(i < secremain)//Ҫ
{
FLASH_ErasePage(secpos * PAGE_SIZE + FLASH_BASE);//
for(i=0; i < secremain; i++)
{
STMFLASH_BUF[i + secoff] = pBuffer[i];
}
STMFLASH_Write_NoCheck(secpos * PAGE_SIZE + FLASH_BASE, STMFLASH_BUF, PAGE_SIZE / 2);//д
}else
STMFLASH_Write_NoCheck(WriteAddr, pBuffer, secremain);//дѾ˵,ֱдʣ.
if(NumToWrite == secremain)break;//д
else//дδ
{
secpos++; //ַ1
secoff = 0; //ƫλΪ0
pBuffer += secremain; //ָƫ
WriteAddr += secremain; //дַƫ
NumToWrite -= secremain; //ֽ(16λ)ݼ
if(NumToWrite > (PAGE_SIZE / 2)) secremain = PAGE_SIZE / 2;//һд
else secremain = NumToWrite;//һд
}
};
FLASH_Lock();//
}
/*******************************************************************************
**Ϣ
**
**
**
*******************************************************************************/
void STMFLASH_Read(u32 ReadAddr,u16 *pBuffer,u16 NumToRead)
{
u16 i;
for(i=0;i<NumToRead;i++)
{
pBuffer[i]=STMFLASH_ReadHalfWord(ReadAddr);//ȡ2ֽ.
ReadAddr+=2;//ƫ2ֽ.
}
}
|
C
|
/*
CoreSight board registration
Provides an abstract interface to registering boards with the library
Copyright (C) ARM Limited, 2013. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#ifndef _GNU_SOURCE
#define _GNU_SOURCE
#endif
#include "csaccess.h"
#include "csregistration.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/*
This has the CPU type identifier for each core, indexed by Linux core number.
*/
unsigned int cpu_id[LIB_MAX_CPU_DEVICES];
int registration_verbose = 1;
#ifndef BAREMETAL
static const struct board *do_probe_board(const struct board *board_list)
{
const struct board *board = NULL;
FILE *fl = fopen("/proc/cpuinfo", "r");
char *line = NULL;
size_t size = 0;
ssize_t len;
int cpu_number = -1;
if (!fl) {
if (registration_verbose)
printf
("CSREG: Failed to open /proc/cpuinfo - cannot detect the board\n");
return NULL;
}
while ((len = getline(&line, &size, fl)) >= 0) {
if (strncmp(line, "Hardware\t: ", 11) == 0) {
const struct board *b;
unsigned int i;
line[len - 1] = '\0';
for (i = 1; i < len; ++i) {
if (line[i] == '(') {
/* Convert "Myboard (test)" into "Myboard" etc. */
line[i - 1] = '\0';
break;
}
}
for (b = board_list; b->do_registration; b++) {
if (strcmp(line + 11, b->hardware) == 0) {
if (registration_verbose >= 2)
printf("CSREG: Detected '%s' board\n",
b->hardware);
board = b;
break;
}
}
if (!board) {
if (registration_verbose)
printf("CSREG: Board '%s' not known\n", line + 11);
}
} else if (strncmp(line, "processor\t: ", 12) == 0) {
cpu_number = -1;
sscanf(line + 12, "%d", &cpu_number);
} else if (strncmp(line, "CPU part\t: ", 11) == 0) {
unsigned int id;
sscanf(line + 11, "%x", &id);
if (cpu_number >= 0 && cpu_number < LIB_MAX_CPU_DEVICES) {
cpu_id[cpu_number] = id;
}
}
}
free(line);
fclose(fl);
return board;
}
#endif
static int do_registration(const struct board *board,
struct cs_devices_t *devices)
{
/* clear the devices structure */
memset(devices, 0, sizeof(struct cs_devices_t));
if (board->do_registration(devices) != 0) {
if (registration_verbose)
printf("CSREG: Failed to register board '%s'\n",
board->hardware);
return -1;
}
/* No more registrations */
if (cs_registration_complete() != 0) {
if (registration_verbose)
printf
("CSREG: Registration problems on cs_registration_complete()\n");
return -1;
}
if (cs_error_count() > 0) {
if (registration_verbose)
printf("CSREG: Errors recorded during registration\n");
return -1;
}
if (registration_verbose)
printf("CSREG: Registration complete.\n");
return 0;
}
static int initilise_board(const struct board **board,
struct cs_devices_t *devices)
{
if (cs_init() < 0) {
if (registration_verbose)
printf("CSREG: Failed cs_init()\n");
return -1;
}
if (do_registration(*board, devices) < 0) {
if (registration_verbose)
printf("CSREG: Registration failed in setup_board()\n");
return -1;
}
return 0;
}
int setup_board(const struct board **board, struct cs_devices_t *devices,
const struct board *board_list)
{
if (!board || !devices || !board_list) {
if (registration_verbose)
printf("CSREG: Invalid parameters to setup_board()\n");
return -1;
}
#ifndef BAREMETAL
*board = do_probe_board(board_list);
if (!*board) {
if (registration_verbose)
printf("CSREG: Failed to detect the board!\n");
return -1;
}
#else
*board = &board_list[0];
#endif
return initilise_board(board, devices);
}
int setup_named_board(const char *board_name, const struct board **board,
struct cs_devices_t *devices,
const struct board *board_list)
{
const struct board *b = NULL;
if (!board || !devices || !board_list || !board_name) {
if (registration_verbose)
printf("CSREG: Invalid parameters to setup_board()\n");
return -1;
}
*board = NULL;
for (b = board_list; b->do_registration; b++) {
if (strcmp(board_name, b->hardware) == 0) {
if (registration_verbose >= 2)
printf("CSREG: Selected '%s' board\n", b->hardware);
*board = b;
break;
}
}
if (*board == NULL) {
if (registration_verbose)
printf
("CSREG: Unable to find name %s in setup_named_board()\n",
board_name);
return -1;
}
return initilise_board(board, devices);
}
|
C
|
#ifndef GRAPHICS_H
#define GRAPHICS_H
#include <stdint.h>
#include <font.h>
#include <mailbox.h>
#define SCREEN_WIDTH 800
#define SCREEN_HEIGHT 480
#define COLORDEPTH 24
#define PIXEL_BYTES (COLORDEPTH / 8)
typedef struct {
uint8_t red;
uint8_t green;
uint8_t blue;
} color_t;
typedef struct {
uint32_t width;
uint32_t height;
uint32_t virtual_width;
uint32_t virtual_height;
uint32_t pitch;
uint32_t depth;
uint32_t virtual_offset_x;
uint32_t virtual_offset_y;
uint8_t * buff_addr;
uint32_t buff_size;
} fb_info_t;
void framebufferInit();
void clearFrame();
void drawPixel(int x, int y, const color_t * color);
void drawChar(uint32_t x, uint32_t y, const color_t * foreground, const color_t * background, char c);
#endif // GRAPHICS_H
|
C
|
/*
** my_swapstr.c for libmy in /home/arbona/CPool/CPool_infinadd/lib/my
**
** Made by Thomas Arbona
** Login <[email protected]>
**
** Started on Mon Oct 24 14:09:28 2016 Thomas Arbona
** Last update Mon Oct 24 14:10:27 2016 Thomas Arbona
*/
int my_swapstr(char **s1, char **s2)
{
char *tmp;
tmp = *s2;
*s2 = *s1;
*s1 = tmp;
return (0);
}
|
C
|
//Find the minimum depth of a binary tree
int min_depth(struct Node* root, int depth)
{
if (root->left == NULL && root->right == NULL)
return depth;
int x = (root->left != NULL) ? min_depth(root->left, depth+1) : depth;
int y = (root->right != NULL) ? min_depth(root->right, depth+1) : depth;
return (x < y) ? x : y;
}
|
C
|
/*
* Copyright (c) 1994 by Sun Microsystems, Inc.
* All rights reserved.
*/
#pragma ident "@(#)hash.c 1.1 94/12/05 SMI"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <synch.h>
#include <memory.h>
#include <getxby_door.h>
static int hash_string();
hash_t *
make_hash(size)
int size;
{
hash_t *ptr;
ptr = (hash_t *) malloc(sizeof(*ptr));
ptr->size = size;
ptr->table = (hash_entry_t **)
malloc( (unsigned) (sizeof(hash_entry_t *) * size) );
(void)memset((char *) ptr->table, (char) 0, sizeof(hash_entry_t *)*size);
ptr->start = NULL;
ptr->hash_type = String_Key;
return(ptr);
}
hash_t *
make_ihash(size)
int size;
{
hash_t * ptr;
ptr = (hash_t *) malloc(sizeof(*ptr));
ptr->size = size;
ptr->table = (hash_entry_t **) malloc((unsigned)
(sizeof(hash_entry_t *) * size) );
(void)memset((char *) ptr->table, (char) 0,
sizeof(hash_entry_t *)*size);
ptr->start = NULL;
ptr->hash_type = Integer_Key;
return(ptr);
}
char **
get_hash(hash_t *tbl, char *key)
{
int bucket;
hash_entry_t *tmp;
hash_entry_t *new;
if (tbl->hash_type == String_Key) {
tmp = tbl->table[bucket = hash_string(key, tbl->size)];
} else {
tmp = tbl->table[bucket = abs((int)key) % tbl->size];
}
if (tbl->hash_type == String_Key) {
while (tmp != NULL) {
if (strcmp(tmp->key, key) == 0) {
return(&tmp->data);
}
tmp = tmp->next_entry;
}
} else {
while (tmp != NULL) {
if (tmp->key == key) {
return(&tmp->data);
}
tmp = tmp->next_entry;
}
}
/*
* not found....
* insert new entry into bucket...
*/
new = (hash_entry_t *) malloc(sizeof(*new));
new->key = ((tbl->hash_type == String_Key)?strdup(key):key);
/*
* hook into chain from tbl...
*/
new->right_entry = NULL;
new->left_entry = tbl->start;
tbl->start = new;
/*
* hook into bucket chain
*/
new->next_entry = tbl->table[bucket];
tbl->table[bucket] = new;
new->data = NULL; /* so we know that it is new */
return(&new->data);
}
char **
find_hash(hash_t *tbl, char *key)
{
hash_entry_t *tmp;
if (tbl->hash_type == String_Key) {
tmp = tbl->table[hash_string(key, tbl->size)];
for ( ;tmp != NULL; tmp = tmp->next_entry) {
if (!strcmp(tmp->key, key)) {
return(&tmp->data);
}
}
} else {
tmp = tbl->table[abs((int)key) % tbl->size];
for ( ;tmp != NULL; tmp = tmp->next_entry) {
if (tmp->key == key) {
return(&tmp->data);
}
}
}
return(NULL);
}
char *
del_hash(hash_t *tbl, char *key)
{
int bucket;
hash_entry_t * tmp, * prev = NULL;
if (tbl->hash_type == String_Key) {
bucket = hash_string(key, tbl->size);
} else {
bucket = abs((int)key) % tbl->size;
}
if ((tmp = tbl->table[bucket]) == NULL) {
return(NULL);
} else {
if (tbl->hash_type == String_Key) {
while (tmp != NULL) {
if (!strcmp(tmp->key, key)) {
break; /* found item to delete ! */
}
prev = tmp;
tmp = tmp->next_entry;
}
} else {
while (tmp != NULL) {
if (tmp->key == key) {
break;
}
prev = tmp;
tmp = tmp->next_entry;
}
}
if (tmp == NULL) {
return(NULL); /* not found */
}
}
/*
* tmp now points to entry marked for deletion, prev to
* item preceeding in bucket chain or NULL if tmp is first.
* remove from bucket chain first....
*/
if (tbl->hash_type == String_Key) {
free(tmp->key);
}
if (prev!=NULL) {
prev->next_entry = tmp->next_entry;
} else {
tbl->table[bucket] = tmp->next_entry;
}
/*
*now remove from tbl chain....
*/
if (tmp->right_entry != NULL) { /* not first in chain.... */
tmp->right_entry->left_entry = (tmp->left_entry ?
tmp->left_entry->right_entry: NULL);
} else {
tbl->start = (tmp->left_entry ?tmp->left_entry->right_entry:
NULL);
}
return(tmp->data);
}
int
operate_hash(hash_t *tbl, void (*ptr)(), char *usr_arg)
{
hash_entry_t * tmp = tbl->start;
int c = 0;
while (tmp) {
(*ptr)(tmp->data, usr_arg, tmp->key);
tmp = tmp->left_entry;
c++;
}
return(c);
}
int
operate_hash_addr(hash_t *tbl, void (*ptr)(), char *usr_arg)
{
hash_entry_t * tmp = tbl->start;
int c = 0;
while (tmp) {
(*ptr)(&(tmp->data), usr_arg, tmp->key);
tmp = tmp->left_entry;
c++;
}
return(c);
}
void
destroy_hash(hash_t *tbl, int (*ptr)(), char *usr_arg)
{
hash_entry_t * tmp = tbl->start, * prev;
while (tmp) {
if (ptr) {
(*ptr)(tmp->data,usr_arg, tmp->key);
}
if (tbl->hash_type == String_Key) {
free(tmp->key);
}
prev = tmp;
tmp = tmp->left_entry;
free((char *)prev);
}
free((char *)tbl->table);
free(tbl);
}
static int
hash_string(char *s, int modulo)
{
unsigned result = 0;
int i=1;
while (*s != 0) {
result += (*s++ << i++);
}
return(result % modulo);
}
|
C
|
/*ECED3204 Sample - Lab #7. By Colin O'Flynn, released into public domain */
#include <stdio.h>
#include <avr/io.h>
#include <avr/pgmspace.h>
static int uart_putchar(char c, FILE *stream);
static int uart_getchar(FILE *stream);
FILE mystdout = FDEV_SETUP_STREAM(uart_putchar, NULL, _FDEV_SETUP_WRITE);
FILE mystdin = FDEV_SETUP_STREAM(NULL, uart_getchar, _FDEV_SETUP_READ);
static int uart_putchar(char c, FILE *stream)
{
loop_until_bit_is_set(UCSR0A, UDRE0);
UDR0 = c;
return 0;
}
static int uart_getchar(FILE *stream)
{
loop_until_bit_is_set(UCSR0A, RXC0); /* Wait until data exists. */
return UDR0;
}
void init_uart(void)
{
UCSR0B = (1<<RXEN0) | (1<<TXEN0);
UBRR0 = 7;
stdout = &mystdout;
stdin = &mystdin;
}
/* Generic I2C Routines */
void TWI_Start(void)
{
TWCR = (1<<TWINT)|(1<<TWSTA)|(1<<TWEN);
loop_until_bit_is_set(TWCR, TWINT);
}
void TWI_Stop(void)
{
TWCR = (1<<TWINT)|(1<<TWSTO)|(1<<TWEN);
loop_until_bit_is_clear(TWCR, TWSTO);
}
void TWI_sendByte(uint8_t cx)
{
TWDR = cx;
TWCR = (1<<TWINT)|(1<<TWEN);
loop_until_bit_is_set(TWCR, TWINT);
}
uint8_t TWI_readByte(char sendAck)
{
if(sendAck){
TWCR = (1<<TWINT)|(1<<TWEN)|(1<<TWEA);
} else {
TWCR = (1<<TWINT)|(1<<TWEN);
}
loop_until_bit_is_set(TWCR, TWINT);
return TWDR;
}
uint8_t TWI_status(void)
{
return TWSR & 0xF8;
}
/* EEPROM Specific Routines - NO error handling done! */
void writePoll(uint8_t SLA)
{
char busy = 1;
while(busy){
TWI_Start();
TWI_sendByte(SLA);
if(TWI_status() == 0x18){
//OK
busy = 0;
}
}
}
void writeByteEE(uint8_t SLA, uint8_t addr, uint8_t data)
{
TWI_Start();
TWI_sendByte(SLA);
TWI_sendByte(addr);
TWI_sendByte(data);
TWI_Stop();
writePoll(SLA);
}
uint8_t readByteEE(uint8_t SLA, uint8_t addr)
{
uint8_t tmp;
TWI_Start();
TWI_sendByte(SLA);
TWI_sendByte(addr);
TWI_Start();
TWI_sendByte(SLA | 0x01);
tmp = TWI_readByte(0);
TWI_Stop();
return tmp;
}
//You can extend these to have error handling - see http://www.embedds.com/programming-avr-i2c-interface/
//for example
#define EEPROM_ADDR 0xA0
int main(void)
{
init_uart();
printf_P(PSTR("System Booted, built %s on %s\n"), __TIME__, __DATE__);
//~50 kHz I2C frequency (slower than normal)
TWBR = 132;
TWCR = 1<<TWEN;
TWSR = 0;
uint16_t addr = 105;
printf("Read address 0x%02x = %02x\n", addr, readByteEE(EEPROM_ADDR, addr));
}
|
C
|
#define _POSIX_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <errno.h>
#include <inttypes.h>
#include <limits.h>
#include <pthread.h>
#include <signal.h>
#include <time.h>
#include <netdb.h>
#define THREAD_LISTEN_PORT 8989 //port where the thread listens to KILL_SIGNAL itself
#define KILL_SIGNAL 0xBD
/* function that runs in a separate thread to listen for kill signal */
void *signal_listener(void *v);
int main(int argc, char **argv){
pthread_t *listener_thread; /* thread that listens for kill signal*/
uintptr_t v = 0; /* To elimiate the pointer warning during pthread_create() */
/*some variables for performance measurement*/
uint32_t performance_a = 4294967295;
uint32_t performance_d = 0;
int performance_b = 9;
int performance_c = 0;
int one = 1;
clock_t start;
clock_t finish;
/* Socket Variables */
struct addrinfo socket_address;
struct addrinfo *result, *rp;
int socket_fd;
int s;
int test_port = 0;
unsigned char test[9];
uint32_t res = 0;
int red = 0;
buf_size = 9;
unsigned char buf[9] = {0};
char hostname[255];
char port[255];
/* Range values */
uint32_t min = 0;
uint32_t max = 0;
uint32_t sum = 0;
/* User argument variables */
char *endpt;
char *str;
if(argc != 3 || strcmp(argv[1], "--help") == 0){ /* Check to see if the user needs help */
printf("Usage: %s hostname port\n", argv[0]);
exit(EXIT_FAILURE);
}
strcpy(hostname, argv[1]);
errno = 0;
str = argv[2];
test_port = strtoumax(str, &endpt, 10);
if ((errno == ERANGE && (test_port == INT_MAX || test_port == INT_MIN))
|| (errno != 0 && test_port == 0) || endpt == str || test_port < 1024) {
printf("Invalid Port.\nTerminating Client.\n");
exit(EXIT_FAILURE);
}
/* fill the char array with the port input */
strcpy(port, argv[2]);
listener_thread = (pthread_t *) malloc (sizeof(pthread_t));
if(listener_thread == NULL){
printf("failed to allocate threads!\n");
exit(EXIT_FAILURE);
}
if(pthread_create(listener_thread, NULL, signal_listener, (void *)v)){
printf("failed to create listener thread!\n");
exit(EXIT_FAILURE);
}
/* measure performance*/
start = clock();
while ((finish = clock())<(1*CLOCKS_PER_SEC)){
performance_c=(performance_a%performance_b) >> one;
++performance_d;
}
/* Obtain address(es) matching host/port */
memset(&socket_address, 0, sizeof(struct addrinfo));
socket_address.ai_family = AF_INET;
socket_address.ai_socktype = SOCK_STREAM;
socket_address.ai_flags = 0;
socket_address.ai_protocol = 0;
printf("Manage host and port values %s:%s\n",hostname, port);
for (;;){
s = getaddrinfo(hostname, port, &socket_address, &result);
if (s != 0) {
printf("Invaid hostname or port.\n");
exit(EXIT_FAILURE);
}
/* getaddrinfo() returns a list of address structures.
Try each address until we successfully connect(2).
If socket(2) (or connect(2)) fails, we (close the socket
and) try the next address. */
for (rp = result; rp != NULL; rp = rp->ai_next) {
socket_fd = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
if (socket_fd == -1)
continue;
if (connect(socket_fd, rp->ai_addr, rp->ai_addrlen) != -1)
break; /* Success */
close(socket_fd);
}
if (rp == NULL) { /* No address succeeded */
printf("Could not connect!\n");
exit(EXIT_FAILURE);
}
freeaddrinfo(result); /* No longer needed */
/* formulate the request msg */
test[0] = 274; /* Message type */
test[1] = performance_d >> 24; /* perf characteristics */
test[2] = performance_d >> 16; /* " " */
test[3] = performance_d >> 8; /* " " */
test[4] = performance_d; /* " " */
test[5] = 0; /* No results */
test[6] = 0; /* " " */
test[7] = 0; /* " " */
test[8] = 0; /* " " */
if (write(socket_fd, test,9) != 9) {
printf("partial/failed write!\n");
exit(EXIT_FAILURE);
}
shutdown(socket_fd, 1);
memset(buf,0,buf_size); /* reset buffer to 0 */
red = read(socket_fd, buf, buf_size);
if (red == -1) {
printf("read failed.\n");
exit(EXIT_FAILURE);
}
shutdown(socket_fd, 0);
close(socket_fd);
min = 0; /* reset min & max */
max = 0;
if (buf[0] == 277){
/* parse the range data */
min = buf[1];
min = (min << 8) | buf[2];
min = (min << 8) | buf[3];
min = (min << 8) | buf[4];
max = buf[5];
max = (max << 8) | buf[6];
max = (max << 8) | buf[7];
max = (max << 8) | buf[8];
if(min == 0 && max == 0){
printf("All done.\nTerminating Client.\n");
KILL_SIGNALl(0,SIGINT);
exit(EXIT_SUCCESS);
}
if(min<6){
min = 6;
}else if(min%2 != 0){
++min;
}
if(max%2 != 0){
--max;
}
for(uint32_t l_min = min; l_min < max; l_min += 2){
for(uint32_t i = 1; i < l_min; ++i){
if(l_min%i==0){
sum += i;
}
}
if (sum == l_min){
res = l_min;
s = getaddrinfo(hostname, port, &socket_address, &result);
if (s != 0) {
printf("Failed to resolve hostname.\n");
exit(EXIT_FAILURE);
}
for (rp = result; rp != NULL; rp = rp->ai_next) {
socket_fd = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
if (socket_fd == -1)
continue;
if (connect(socket_fd, rp->ai_addr, rp->ai_addrlen) != -1)
break; /* Success */
close(socket_fd);
}
if (rp == NULL) { /* No address succeeded */
printf("Connection Failed.\n");
exit(EXIT_FAILURE);
}
freeaddrinfo(result); /* No longer needed */
/* formulate the result message */
test[0] = 274;
test[1] = 0;
test[2] = 0;
test[3] = 0;
test[4] = 0;
test[5] = res >> 24;
test[6] = res >> 16;
test[7] = res >> 8;
test[8] = res;
/*printf("Sending perfect number: %u\n",res);*/
if (write(socket_fd, test, 9) != 9) {
printf("partial/failed write!\n");
exit(EXIT_FAILURE);
}
close(socket_fd);
}
sum = 0;
}
close(socket_fd);
}
}
if(pthread_join(*listener_thread, NULL)){
printf("Failed to join listener thread.\n");
exit(EXIT_FAILURE);
}
printf("Terminiating Client.\n");
pthread_exit(NULL);
}
void *signal_listener (void *v){
int listener_fd; //fd for listening socket
int incoming_fd; //fd for new connection
int buf_size = 1;
int num_read = 0;
int yes = 1;
char buf[buf_size];
socklen_t addrlen;
struct sockaddr_storage claddr;
struct sockaddr_in serveraddr;
if((listener_fd = socket(AF_INET, SOCK_STREAM, 0)) == -1){
printf("Socket initialization failed.\n");
exit(EXIT_FAILURE);
}
if(setsockopt(listener_fd, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(int)) == -1) {
perror("Socket config failed.");
exit(EXIT_FAILURE);
}
// setting up
serveraddr.sin_family = AF_INET;
serveraddr.sin_addr.s_addr = INADDR_ANY;
serveraddr.sin_port = htons(THREAD_LISTEN_PORT);
memset(&(serveraddr.sin_zero), '\0', 8);
/* bind the socket fd with this sockaddr_in struct */
if(bind(listener_fd, (struct sockaddr *)&serveraddr, sizeof(serveraddr)) == -1){
printf("Socket bind failed.\n");
exit(EXIT_FAILURE);
}
/* listen-set the socket/fd to be passive */
if(listen(listener_fd, 10) == -1){
printf("Listen failed.\n");
exit(EXIT_FAILURE);
}
for(;;){
addrlen = sizeof(struct sockaddr_storage);
incoming_fd = accept(listener_fd, (struct sockaddr *) &claddr, &addrlen);
if (incoming_fd == -1) {
printf("Incoming connection failed.\n");
continue;
}
num_read = read(incoming_fd,buf,buf_size);
if(num_read != -1){
if((buf[0] & KILL_SIGNAL) == KILL_SIGNAL){
printf("Terminiating Client.\n");
KILL_SIGNALl(0,SIGINT);
}
}
close(incoming_fd);
}
pthread_exit(NULL);
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* input_check.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: atyczyns <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2020/01/23 15:34:31 by atyczyns #+# #+# */
/* Updated: 2020/02/19 15:20:43 by atyczyns ### ########.fr */
/* */
/* ************************************************************************** */
#include "../includes/wolf3d.h"
int get_nbr_per_line(char *str)
{
int nbr_per_line;
nbr_per_line = 0;
while (str && *str)
{
if (*str != ' ')
{
if (ft_isdigit(*str))
{
if (*str < '0' || *str > '8')
return (0);
str++;
nbr_per_line++;
}
else
return (0);
}
else
str++;
}
return (nbr_per_line);
}
int get_dimensions(t_wolf *wolf)
{
char *line;
int i;
int ret[2];
i = 0;
while (++i && (ret[0] = get_next_line(wolf->fd, &line) > 0))
{
ret[1] = get_nbr_per_line(line);
ft_strdel(&line);
if (i == 1 && ret[1])
wolf->width = ret[1];
else if (ret[1] != wolf->width || ret[1] == 0)
{
close(wolf->fd);
return (0);
}
wolf->height++;
}
if (ret[0] <= 0)
close(wolf->fd);
if (!ret[0] && line)
ft_strdel(&line);
if (ret[0] < 0 || (!ret[0] && !wolf->width && !wolf->height))
return (0);
return (1);
}
void get_line(t_wolf *wolf, char *line, int j)
{
int i;
int k;
i = 0;
k = 0;
while (line && line[k])
{
if (ft_isdigit(line[k]))
{
wolf->map[i][j] = line[k];
i++;
k++;
}
else
k++;
}
}
int get_file(t_wolf *wolf, char **argv)
{
int j;
int ret;
char *line;
if ((wolf->fd = open(argv[1], O_RDONLY)) < 0)
{
ft_putstr("usage error\n");
return (0);
}
j = 0;
while ((ret = get_next_line(wolf->fd, &line)) > 0)
{
get_line(wolf, line, j);
ft_strdel(&line);
j++;
}
close(wolf->fd);
if (j == wolf->height && !ret)
return (1);
return (0);
}
int parse_file(t_wolf *wolf, char **argv)
{
int i;
i = -1;
wolf->height = 0;
wolf->width = 0;
if (!get_dimensions(wolf))
{
ft_putstr("wrong file format\n");
return (0);
}
if (!(wolf->map = (char **)ft_memalloc(wolf->width * sizeof(char *))))
return (0);
while (++i < wolf->width)
{
if (!(wolf->map[i] = ft_strnew(wolf->height)))
return (0);
}
if (get_file(wolf, argv) == 0)
{
ft_putstr("parsing problem\n");
return (0);
}
if (init_player(wolf))
return (1);
return (0);
}
|
C
|
#include <stdio.h>
#include <errno.h>
#include <stdlib.h>
#include <unistd.h>
#include <pcap.h>
#include <string.h>
#include <netinet/if_ether.h>
#include <netinet/ip.h>
#include <netinet/tcp.h>
#include <netinet/udp.h>
#include <arpa/inet.h>
#include <netinet/in.h>
void test_smtp(int, int, int, const u_char*, int, int);
void smtp(int, const u_char*, int, int);
void
test_smtp(int source_port,
int destination_port,
int size,
const u_char *packet,
int taille_du_paquet,
int verbo) {
if ((source_port == 25 || destination_port == 25) ) {
smtp(size, packet, taille_du_paquet, verbo);
}
}
void
smtp(int size, const u_char* packet, int taille_du_paquet, int verbo) {
printf("\n\n--------------- SMTP ----------------\n\n");
printf("/* Les points représentent des caractères spéciaux (ou des points) */\n\n");
while ( size < taille_du_paquet) {
if ( (int)(packet+size)[0]>31 && (int)(packet+size)[0]<127) {
putchar((packet + size)[0]);
}
else if( (int)(packet+size)[0] == 13 ||
(int)(packet+size)[0] == 10 ||
(int)(packet+size)[0] == 11 ) {
putchar((packet+size)[0]);
} else {
putchar('.');
}
size ++;
}
printf("\n\n");
printf(" Taille total du paquet: %i\n", taille_du_paquet);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include "orderBook.h"
struct heap{
int * a;
size_t capacity;
size_t size;
};
struct orderBook{
struct heap * buy_heap;
struct heap * sell_heap;
};
#define INITIAL_SIZE (32)
#define SIZE_MULTIPLIER (2)
// Make a new empty order book.
OrderBook orderBookCreate(void){
OrderBook ob = malloc(sizeof(struct orderBook));
ob->buy_heap = malloc(sizeof(struct heap));
ob->sell_heap = malloc(sizeof(struct heap));
ob->buy_heap->capacity = ob->sell_heap->capacity = INITIAL_SIZE;
ob->buy_heap->size = ob->sell_heap->size = 0;
ob->buy_heap->a = calloc(INITIAL_SIZE, sizeof(int));
ob->sell_heap->a = calloc(INITIAL_SIZE, sizeof(int));
return ob;
}
// Destroy an order book,
// freeing all space
// and discarding all pending orders.
void orderBookDestroy(OrderBook ob){
free(ob->buy_heap->a);
free(ob->sell_heap->a);
free(ob->buy_heap);
free(ob->sell_heap);
free(ob);
}
// Following 5 functions are from heapsort.c, 04-12-2021 lecture
static void
swap(int *x, int *y)
{
int temp = *x;
*x = *y;
*y = temp;
}
static size_t
parent(size_t i)
{
return (i-1)/2;
}
static size_t
child(size_t i, int side)
{
return 2*i + 1 + side;
}
static void
floatDown(size_t i, size_t n, int *a)
{
size_t bigger = child(i,0);
// need to check if bigger >= n
if(bigger < n) {
if(bigger + 1 < n && a[bigger+1] > a[bigger]) {
// right child exists and is bigger
bigger = bigger + 1;
}
// bigger now is index of the bigger child
// is that child bigger than me?
if(a[bigger] > a[i]) {
swap(&a[bigger], &a[i]);
floatDown(bigger, n, a);
}
}
}
static void
floatUp(size_t i, int *a)
{
if(i != 0 && a[parent(i)] < a[i]) {
swap(&a[parent(i)], &a[i]);
floatUp(parent(i), a);
}
}
// removes the max elt from root
// updates heap by moving bottom right most elt to root
// floats down the root until it is greater than larger of children
// need to update the size of heap after called
static void heapDelete(struct heap * h){
h->size--;
h->a[0] = h->a[h->size];
floatDown(0, h->size, h->a);
}
// inserts a new elt into heap
// need to increment size of heap after called
static void heapInsert(struct heap * h, int new){
h->a[h->size] = new;
floatUp(h->size, h->a);
h->size++;
if (h->size >= h->capacity){
h->capacity *= 2;
h->a = realloc(h->a, h->capacity * sizeof(int));
}
}
// returns root if it exists
static int heapPeek(struct heap * h){
if (h->size){
return h->a[0];
} else{
return 0;
}
}
// Enter a new order in the order book.
//
// If price > 0, it represents a buy order.
// Return value will be price p2 of sell order
// maximizing price + p2 > 0, or 0 if there
// is no such sell order.
//
// If price < 0, it represents a sell order.
// Return value will be price p2 of buy order
// maximizing price + p2 > 0, or 0 if there
// is no such buy order.
//
// In either of the above cases, if 0 is returned,
// then price is entered into the order book
// as a pending order available for future matches.
// If a nonzero value is returned, the corresponding
// pending order is removed.
//
// If price == 0, no order is entered and
// return value is 0.
int orderBookInsert(OrderBook ob, int price){
if (price == 0){
return 0;
}
int top;
// buy order
if (price > 0){
// add to buy queue
top = heapPeek(ob->sell_heap);
if (top == 0 || price + top <= 0){
heapInsert(ob->buy_heap, price);
return 0;
}
// there is a sell order that is profitable
else{
heapDelete(ob->sell_heap);
return top;
}
}
// sell order
else{
top = heapPeek(ob->buy_heap);
// add to sell queue
if (top == 0 || price + top <= 0){
heapInsert(ob->sell_heap, price);
return 0;
}
else{
heapDelete(ob->buy_heap);
return top;
}
}
}
|
C
|
#include<stdio.h>
#include<stdlib.h>
#define OFFSET 2
struct RB{
RB * p1;
RB * p2;
unsigned char offset;
unsigned short sec;
};
int main()
{
struct RB * N;
struct RB rb;
printf("struct RB size is %d byte\n",sizeof(struct RB));
printf("struct RB size is %d byte\n",sizeof(rb));
printf("struct RB POINTER size is %d byte\n",sizeof(struct RB *));
printf("struct RB POINTER size is %d byte\n",sizeof(N));
N=(struct RB*)malloc(sizeof(N));
printf("Nַָ------%p\n",N);
printf("Nַ-------%p\n",&N);
void *z= (void *)(N + OFFSET);
printf("Zַָ%p\n",z);
void *s=(void *)(((unsigned char *)N)+ OFFSET);
printf("Sַָ%p\n",s);
return 1;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <malloc.h>
#include <windows.h>
#include <stdbool.h>
#include "GAME_CONST.h"
bool isWon(int result)
{
return result > WINNING_RESULT - 1;
}
int generateDiceValues()
{
return rand() % 5 + 1;
}
void fillRandomDices(int* diceArray, int amountUnusedDice, int(*generateDiceValues)())
{
int i;
if (diceArray != NULL)
{
for (i = 0; i < amountUnusedDice; i++)
{
*(diceArray + i) = generateDiceValues();
}
}
}
void printDices(int* diceArray, int amountUnusedDice)
{
int i;
for (i = 0; i < amountUnusedDice; i++)
{
printf("|%d| ", *(diceArray + i));
}
}
void playerMove(int* amountUsedDice, int* selectedDice)
{
int i, d = -1;
printf("\n\nEnter bone numbers (enter 0 to finish)\n");
for (i = 0; i < INITIAL_AMOUNT_DICE && d != 0; ++i)
{
scanf_s("%d", &d);
*(selectedDice + i) = d;
/* */
if (d != 0)
{
(*amountUsedDice)++;
}
}
}
void botMove(int* amountUsedDice, int* sortedDice)
{
int i;
/* */
for (i = 0; i < 6; i++)
{
if ((i != 0 && i != 4) && sortedDice[i] < 3)
{
sortedDice[i] = 0;
}
*amountUsedDice = *amountUsedDice + sortedDice[i];
}
}
void selectAllDice(int* selectedDice, int amountUnusedDice)
{
int i;
for (i = 0; i < amountUnusedDice; i++)
{
*(selectedDice + i) = i + 1;
}
}
void sortByQuantity(int* selectedDice, int* sortedDice, int* dicesArray)
{
int i;
for (i = 0; i < INITIAL_AMOUNT_DICE; i++)
{
*(sortedDice + i) = 0;
}
/* */
for (i = 0; *(selectedDice + i) != 0 && i < INITIAL_AMOUNT_DICE; ++i)
{
switch (*(dicesArray + *(selectedDice + i) - 1))
{
case 1:
(*(sortedDice + 0))++;
break;
case 2:
(*(sortedDice + 1))++;
break;
case 3:
(*(sortedDice + 2))++;
break;
case 4:
(*(sortedDice + 3))++;
break;
case 5:
(*(sortedDice + 4))++;
break;
case 6:
(*(sortedDice + 5))++;
break;
}
}
}
void calculateTheSum(int* sortedDice, int* sum)
{
int i, dicesCounter = 0;
/* 1 5 */
for (i = 0; i < INITIAL_AMOUNT_DICE; i++)
{
if (i == 0)
{
switch (*sortedDice)
{
case 1:
*sum = *sum + HUNDRED;
break;
case 2:
*sum = *sum + 2 * HUNDRED;
break;
case 3:
*sum = *sum + THOUSAND;
break;
case 4:
*sum = *sum + 2 * THOUSAND;
break;
case 5:
*sum = *sum + 4 * THOUSAND;
break;
case 6:
*sum = *sum + 8 * THOUSAND;
break;
}
}
else if (i == 4)
{
switch (*(sortedDice + 4))
{
case 1:
*sum = *sum + FIFTY;
break;
case 2:
*sum = *sum + 2 * FIFTY;
break;
case 3:
*sum = *sum + (i + 1) * HUNDRED;
break;
case 4:
*sum = *sum + (i + 1) * 2 * HUNDRED;
break;
case 5:
*sum = *sum + (i + 1) * 4 * HUNDRED;
break;
case 6:
*sum = *sum + (i + 1) * 8 * HUNDRED;
break;
}
}
else
{
if (*(sortedDice + i) > 2)
{
switch (*(sortedDice + i))
{
case 3:
*sum = *sum + (i + 1) * HUNDRED;
break;
case 4:
*sum = *sum + (i + 1) * 2 * HUNDRED;
break;
case 5:
*sum = *sum + (i + 1) * 4 * HUNDRED;
break;
case 6:
*sum = *sum + (i + 1) * 8 * HUNDRED;
break;
}
}
/* , */
/* 2,3,4,6*/
else if (*(sortedDice + i) != 0)
{
*sum = -1;
break;
}
}
/* */
dicesCounter = dicesCounter + *(sortedDice + i);
}
/* , */
if (dicesCounter == 0)
{
*sum = -1;
}
}
int playersRoundResult(int* sum, int* amountUsedDice, int* playerResult)
{
int playerDecision;
/* , */
if (*sum == -1)
{
printf("\nThe current result is 0\n\n");
*sum = 0;
*amountUsedDice = 0;
return 0;
}
/* 6 */
else if (*amountUsedDice == 6)
{
printf("\nThe current result is %d\nEnter 0 to save the result, or enter 1 to continue\n", *sum);
scanf_s("%d", &playerDecision);
if (playerDecision == 0)
{
*playerResult = *playerResult + *sum;
*sum = 0;
*amountUsedDice = 0;
}
else
{
*amountUsedDice = 0;
}
return playerDecision;
}
/* 6 */
else
{
printf("\nThe current result is %d\nEnter 0 to save the result, or enter 1 to continue\n", *sum);
scanf_s("%d", &playerDecision);
if (playerDecision == 0)
{
*playerResult = *playerResult + *sum;
*sum = 0;
*amountUsedDice = 0;
}
return playerDecision;
}
}
int botRoundResult(int* sum, int* amountUsedDice, int* botResult)
{
/* , */
if (*sum == -1)
{
printf("\nBot's current result is 0\n\n");
*sum = 0;
*amountUsedDice = 0;
return 0;
}
/* 6 */
else if (*amountUsedDice == 6)
{
printf("\nBot's current result is %d\n\n", *sum);
*amountUsedDice = 0;
return 1;
}
/* 6 */
else
{
printf("\nBot's current result is %d\n\n", *sum);
/* */
if (*amountUsedDice > 3 || (*sum > 300 && *amountUsedDice > 2))
{
*botResult = *botResult + *sum;
*sum = 0;
*amountUsedDice = 0;
return 0;
}
else
{
return 1;
}
}
}
|
C
|
#include <string.h>
#include "cols.h"
struct colors {
int id;
char *name;
char RGB[3];
} COLORS[] = {
{ 0, "black", {0, 0, 0} },
{ 1, "white", {255, 255, 255} },
{ 2, "red", { 255, 0, 0 } },
{ 3, "darkred", { 64, 0, 0 } },
{ 4, "green", { 0, 255, 0 } },
{ 5, "darkgreen", { 0, 64, 0 } },
{ 6, "blue", { 0, 0, 255 } },
{ 7, "darkblue", {0, 0, 64} },
{ 8, "lightred", {192, 64, 0} },
{ 9, "lightgreen", {0, 96, 64} },
{ 10, "lightblue", {96, 144, 255} },
{ 11, "lightyellow", {255, 144, 96} },
{ 12, "darkgrey", { 16, 16, 16 } },
{ -1, NULL, {0, 0, 0} }
};
char *
get_color(char *col)
{
short int i;
int len;
for (i = 0, len = strlen(col); COLORS[i].id != -1; i++) {
if (strncmp(col, COLORS[i].name, len) == 0) {
return COLORS[i].RGB;
}
}
/* No such color, return NULL color (black) */
return COLORS[i].RGB;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <my_global.h>
#include <mysql.h>
#include <signal.h>
#include <fcntl.h>
#include <sys/ioctl.h>
#include <linux/i2c-dev.h>
#include <unistd.h>
#include <string.h>
#include "button.h"
int i2c_fd1;
int i2c_fd2;
#define GPIO4 4
#define GPIO5 5
int pin1 = GPIO4;
int pin2 = GPIO5;
unsigned char Slave_Addr1=0x0F;
unsigned char Slave_Addr2=0x0D;
void ctrl_c(int sig)
{
close(i2c_fd1);
close(i2c_fd1);
exit(-1);
}
void finish_with_error(MYSQL *con)
{
fprintf(stderr, "%s\n", mysql_error(con));
mysql_close(con);
exit(1);
}
int main(int argc, char **argv)
{
MYSQL *con = mysql_init(NULL);
signal(SIGINT, ctrl_c);
int i = 0;
int j = 0;
unsigned char ret1[15], ret2[30];
char ret3[30];
char coordinates[30];
char *strptr1;
char *strptr2;
char latitude[15];
char longitude[15];
char temperatura[15];
int enable;
int is_locked;
int transport_id = 1;
char q[200];
//Setando arquivos e enderecos para uso do i2c
i2c_fd1 = open("/dev/i2c-1", O_RDWR);
ioctl(i2c_fd1, I2C_SLAVE, Slave_Addr1);
i2c_fd2 = open("/dev/i2c-1", O_RDWR);
ioctl(i2c_fd2, I2C_SLAVE, Slave_Addr2);
if (con == NULL)
{
fprintf(stderr, "%s\n", mysql_error(con));
exit(1);
}
if (mysql_real_connect(con, "localhost", "root", "root",
"transorg", 0, NULL, 0) == NULL)
{
finish_with_error(con);
}
if (mysql_query(con, "CREATE TABLE IF NOT EXISTS transorg (Date DATETIME, Latitute TEXT, Longitude TEXT, Temperatura TEXT, Is_Locked INT, Enable INT, Transporte_ID INT)")) {
finish_with_error(con);
}
//sleep para normalizacao dos sistemas
sleep(30);
//Pegando os valores de enable
Button(&enable, pin1);
//Pegando os valores de is_locked
Button(&is_locked, pin2);
//Recebendo dados de temperatura via i2c
read(i2c_fd1, ret1, 15);
printf("Recebido1: %s\n", ret1);
for (i = 0; i < 15; i ++){
if (ret1[i] == 255)
ret1[i] = '\0';}
sleep(1);
//Recebendo dados das Coordenadas
read(i2c_fd2, ret2, 30);
printf("Recebido2: %s\n", ret2);
for (i = 0; i< 30; i++){
if(ret2[i] == 255)
ret2[i] = '\0';
//printf("%d ", ret2[i]);
}
strcpy(ret3, ret2);
strcpy(temperatura, ret1);
printf("%s\n", temperatura);
printf("%s\n", ret2);
printf("%s\n", ret3);
strptr1 = strtok(ret3, " ");
strptr2 = strtok(NULL, " ");
printf("%s\n", strptr1);
printf("%s\n", strptr2);
strcpy(latitude, strptr1);
strcpy(longitude, strptr2);
sprintf(q, "INSERT INTO transorg Values(CURRENT_TIMESTAMP, '%s', '%s', '%s', %d, %d, %d)", latitude, longitude, temperatura, is_locked, enable, transport_id);
if (mysql_query(con, q)) {
finish_with_error(con);
}
close(i2c_fd1);
close(i2c_fd2);
mysql_close(con);
exit(0);
}
|
C
|
#include<stdio.h>
#include<math.h>
int main() {
double g=9.8;
double h,v,z;
printf("enter h,v,z:");
scanf("%lf,%lf,%lf",&h,&v,&z);
double a=(z*22)/(7*180);
double V=sqrt(2*g*h-v*v*(sin(a)*sin(a)));
double t=(V+v)/(2*g);
double D=v*cos(a)*t;
double H=h+(v*v*(sin(a)*sin(a)))/(2*g);
printf("H D V are %lf %lf %lf",H,D,V);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
void display(int *A, int len);
void counting_sort(int *A, int *B, int k, int len);
int main(int argc, const char * argv[]) {
int a[8] = {2, 5, 3, 0, 2, 3, 0, 3};
int b[8] = {0};
display(a, 8);
counting_sort(a, b, 6, 8);
display(b, 8);
return 0;
}
void counting_sort(int *A, int *B, int k, int len) {
int *C = (int *)malloc(sizeof(float) * k);
for (int i = 0; i < k; ++i) {
C[i] = 0;
}
// count
for (int i = 0; i < len; ++i) {
C[A[i]]++;
}
// count index
for (int i = 1; i < k; ++i) {
C[i] = C[i] + C[i-1];
}
for (int i = len - 1; i >= 0; --i) {
B[C[A[i]] - 1] = A[i];
C[A[i]]--;
}
free(C);
}
void display(int *A, int len) {
for (int i = 0; i < len; ++i) {
printf("%d ", A[i]);
}
printf("\n");
}
|
C
|
#include<stdlib.h>
#include<stdio.h>
int main()
{
float **a;
int i=0, imax=3;
int j, jmax=3;
a =(float **)malloc(imax*sizeof(float *));
for(i=0; i<imax; ++i){
a[i] = (float *)malloc(jmax*sizeof(float));
}
for(i=0; i<imax; ++i){
for(j=0; j<jmax; ++j){
a[i][j] = 0.0;
(i == j )? (a[i][j]=1.0) : (a[i][j]=0.0) ;
printf("a[%d][%d] = %f\n", i,j,a[i][j]);
}
}
/*Free memory*/
for(i=0; i<imax; ++i){
free(a[i]);
}
free(a);
}
|
C
|
#include <stdio.h>
int main()
{
int money,note100,note50,note20,note10,note5,note2,note1;
scanf("%d",&money);
printf("%d\n", money);
note100=money/100;
printf("%d nota(s) de R$ 100,00\n", note100);
note50=(money%100)/50;
printf("%d nota(s) de R$ 50,00\n", note50);
note20=((money%100)%50)/20;
printf("%d nota(s) de R$ 20,00\n", note20);
note10=(((money%100)%50)%20)/10;
printf("%d nota(s) de R$ 10,00\n", note10);
note5=((((money%100)%50)%20)%10)/5;
printf("%d nota(s) de R$ 5,00\n", note5);
note2=(((((money%100)%50)%20)%10)%5)/2;
printf("%d nota(s) de R$ 2,00\n", note2);
note1=((((((money%100)%50)%20)%10)%5)%2)/1;
printf("%d nota(s) de R$ 1,00\n", note1);
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include "lists.h"
/**
*delete_dnodeint_at_index - deletes the node at index index of linked list.
*@head: head of the linked list
*@index: index of the node to be deleted
*Return: 1 if it succeeded, -1 if it failed
*/
int delete_dnodeint_at_index(dlistint_t **head, unsigned int index)
{
dlistint_t *tmp = *head, *tmp_del = NULL;
if (*head == NULL)
return (-1);
if (index == 0)
{
tmp_del = tmp;
if ((*tmp).next != NULL)
(*tmp).next->prev = NULL;
*head = (*tmp).next;
free(tmp_del);
return (1);
}
index--;
while (tmp != NULL && index != 0)
{
tmp = (*tmp).next;
index--;
}
if (index == 0)
{
tmp_del = (*tmp).next;
(*tmp).next = ((*tmp).next)->next;
if ((*tmp).next != NULL)
(*tmp).next->prev = tmp;
free(tmp_del);
return (1);
}
else
return (-1);
}
|
C
|
#include <stdio.h>
int R, C;
char cine[500][500];
int vr[300][300], vc[300][300], vp[300][300];
int min(int a, int b) { return a < b ? a : b; }
int vago(char c)
{
if(c == '.') return 1;
else return 0;
}
int count(int ri, int ci, int rf, int cf)
{
if(ri == 0 && ci == 0) return vp[rf][cf];
if(ri == 0) return vp[rf][cf] - vp[rf][ci-1];
if(ci == 0) return vp[rf][cf] - vp[ri-1][cf];
return vp[rf][cf] - vp[rf][ci-1] - vp[ri-1][cf] + vp[ri-1][ci-1];
}
int main()
{
int K, i, j, ini, fim, area;
while(scanf("%d%d%d", &R, &C, &K) && R)
{
area = R * C;
for(i=0;i<R;i++) scanf("%s", cine[i]);
for(i=0;i<R;i++)
{
vr[i][0] = vago(cine[i][0]);
for(j=1;j<C;j++) vr[i][j] = vr[i][j-1] + vago(cine[i][j]);
}
for(j=0;j<C;j++)
{
vc[j][0] = vago(cine[0][j]);
for(i=1;i<R;i++) vc[j][i] = vc[j][i-1] + vago(cine[i][j]);
}
for(j=0;j<C;j++) vp[0][j] = vr[0][j];
for(i=1;i<R;i++) for(j=0;j<C;j++) vp[i][j] = vp[i-1][j] + vr[i][j];
for(i=0;i<R;i++)
{
if(vp[i][C-1] < K) continue;
if(area == K) break;
for(j=0;j<=i;j++)
{
if(count(j, 0, i, C-1) < K) continue;
ini = fim = 0;
while(fim != C)
{
if(count(j, ini, i, fim) >= K)
{
area = min(area, (i-j+1)*(fim-ini+1));
ini++;
}
else fim++;
}
}
}
printf("%d\n", area);
}
return 0;
}
|
C
|
/*
* Example unit test demonstrating how to detect buffer errors.
*
* Author: Mike Bland ([email protected], http://mike-bland.com/)
* Date: 2014-05-13
* License: Creative Commons Attribution 4.0 International (CC By 4.0)
* http://creativecommons.org/licenses/by/4.0/deed.en_US
*
* URL:
* https://code.google.com/p/mike-bland/source/browse/heartbleed/buf_test.c
*
* This is an example unit test demonstrating how to test for potential buffer
* handling issues in general as described in the "Heartbleed: Break It Up,
* Break It Down" section of "Goto Fail, Heartbleed, and Unit Testing
* Culture":
*
* http://martinfowler.com/articles/testing-culture.html
*
* USAGE:
* -----
* To build and execute the test:
* $ cc -g buf_test.c -o buf_test
* $ ./buf_test
*
* All of the test cases should fail; TestNullInput() will segfault if
* uncommented. As an exercise, modify func() to get all the tests to pass.
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef uint8_t buf_size_t;
#define MAX_BUF_SIZE (buf_size_t)-1
uint8_t *func(uint8_t *input, size_t sz) {
buf_size_t buf_sz = sz;
uint8_t *buf = malloc(buf_sz);
memcpy(buf, input, (buf_size_t)(buf_sz + 10));
return buf;
}
/* input and expected must be allocated on the heap */
typedef struct {
const char *test_case_name;
uint8_t *input;
size_t size;
uint8_t *expected;
} FuncFixture;
static FuncFixture SetUp(const char *const test_case_name) {
FuncFixture fixture;
memset(&fixture, 0, sizeof(fixture));
fixture.test_case_name = test_case_name;
return fixture;
}
static void TearDown(FuncFixture fixture) {
free(fixture.input);
free(fixture.expected);
}
static int ExecuteFunc(FuncFixture fixture) {
int result = 0;
uint8_t *buf = func(fixture.input, fixture.size);
if (fixture.expected == NULL) {
if (buf != NULL) {
fprintf(stderr, "%s failed:\n expected: NULL\n"
" received: \"%s\" (length %lu)\n",
fixture.test_case_name, buf, strlen((char*)buf));
result = 1;
}
} else if (buf == NULL) {
fprintf(stderr, "%s failed:\n expected: \"%s\" (length %lu)\n"
" received NULL\n",
fixture.test_case_name, fixture.expected,
strlen((char*)fixture.expected));
result = 1;
} else if (strcmp((char*)buf, (char*)fixture.expected)) {
fprintf(stderr, "%s failed:\n expected: \"%s\" (length %lu)\n"
" received: \"%s\" (length %lu)\n",
fixture.test_case_name, fixture.expected,
strlen((char*)fixture.expected), buf, strlen((char*)buf));
result = 1;
}
free(buf);
TearDown(fixture);
return result;
}
static int TestNullInput() {
FuncFixture fixture = SetUp(__func__);
fixture.input = NULL;
fixture.size = 0;
fixture.expected = NULL;
return ExecuteFunc(fixture);
}
static int TestEmptyInput() {
FuncFixture fixture = SetUp(__func__);
fixture.input = (uint8_t*)strdup("");
fixture.size = 0;
fixture.expected = NULL;
return ExecuteFunc(fixture);
}
static int TestOnlyCopySpecifiedNumberOfCharacters() {
FuncFixture fixture = SetUp(__func__);
fixture.input = (uint8_t*)strdup("This is an OK input");
fixture.expected = (uint8_t*)strdup("This");
fixture.size = strlen((char*)fixture.expected);
return ExecuteFunc(fixture);
}
static int TestMaxInputSize() {
FuncFixture fixture = SetUp(__func__);
fixture.size = MAX_BUF_SIZE;
fixture.input = (uint8_t*)malloc(fixture.size + 1);
memset(fixture.input, '#', fixture.size);
fixture.input[fixture.size] = '\0';
fixture.expected = (uint8_t*)strdup((char*)fixture.input);
return ExecuteFunc(fixture);
}
static int TestOverMaxInputSize() {
FuncFixture fixture = SetUp(__func__);
fixture.size = MAX_BUF_SIZE + 1;
fixture.input = (uint8_t*)malloc(fixture.size + 1);
memset(fixture.input, '#', fixture.size);
fixture.input[fixture.size] = '\0';
fixture.expected = NULL;
return ExecuteFunc(fixture);
}
int main(int argc, char* argv[]) {
int num_failed =
/* Including TestNullInput() will cause a segfault unless func() is
* fixed */
/* TestNullInput() + */
TestEmptyInput() +
TestOnlyCopySpecifiedNumberOfCharacters() +
TestMaxInputSize() +
TestOverMaxInputSize() +
0;
if (num_failed != 0) {
printf("%d test%s failed\n", num_failed, num_failed != 1 ? "s" : "");
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
int main()
{
int i, n, npar = 1;
do
{
printf("Enter a number to calculate its factorial\n");
scanf("%d", &n);
} while ((n <= 0) || (n >= 10));
switch (n)
{
case 0:
npar = 1;
break;
case 1:
npar = 1;
break;
default:
for (i = 2; i <= n; i++)
npar = npar * i;
break;
}
printf("Factorial of %d = %d\n", n, npar);
return 0;
}
|
C
|
#include<stdio.h>
#include<stdlib.h>
struct Node {
int data;
struct Node * link;
};
struct Node * top;
void Push(int x) {
struct Node * temp = (struct Node *)malloc(sizeof(struct Node));
temp->data=x;
temp->link=top;
top=temp;
}
void Pop() {
struct Node * temp;
if(top==NULL) return;
temp=top;
top=top->link;
free(temp);
}
int IsEmpty() {
if(top==NULL)
return 1;
else
return 0;
}
int Top() {
return(top->data);
}
void Print() {
struct Node * temp = top;
if(temp==NULL) {
printf("Hey ! Stack is empty..\n");
return;
}
printf("Stack : \n");
while(temp!=NULL) {
printf("%d\n",temp->data);
temp=temp->link;
}
printf("\n");
}
int main() {
top=NULL;
//Perform some Push() and Pop() operations and Print() the stack contents
Push(2); Push(4); Push(7); Print();
Pop(); Print();
Push(6); Print();
//Check if Stack is empty or not
printf("\nIs stack empty ?\n");
if(IsEmpty())
printf("Yes\n");
else
printf("No\n");
int top_data = Top();
printf("\nData at the top of stack = %d\n",top_data);
return 0;
}
|
C
|
#include <stdio.h>
//int main(void)
//{
// // ü α ⺻ 3 Ʈ ϴ.
//
// // Ʈ ϸ
// // stdin ǥ Է Ʈ
// // stdout ǥ Ʈ
// // stderr ǥ Ʈ
//
// int ch;
//
// while (1)
// {
// ch = fgetc(stdin);
// if (ch == EOF)
// {
// break;
// }
// fputc(ch, stdout);
// }
// system("pause");
// return 0;
//}
// Ŀ ؽƮ ϰ ̳ʸ Ϸ .
// ؽƮ ƽŰ ڵ尪 ̸ ̿ ̳ʸ
int main(void)
{
FILE *fp;
int ary[10] = { 13,10,13,13,10,26,13,10,13,10 };
int i, res;
fp = fopen_s(&fp,"a.txt", "wb");
for (i = 0; i < 10; i++)
{
fputc_s(ary[i], fp);
}
fclose(fp);
fp = fopen_s(&fp,"a.txt", "rt");
while (1)
{
res = fgetc(fp);
if (res == EOF) break;
printf("%4d", res);
}
fclose(fp);
system("pause");
return 0;
}
|
C
|
#ifndef io_k8s_apimachinery_pkg_version_info_TEST
#define io_k8s_apimachinery_pkg_version_info_TEST
// the following is to include only the main from the first c file
#ifndef TEST_MAIN
#define TEST_MAIN
#define io_k8s_apimachinery_pkg_version_info_MAIN
#endif // TEST_MAIN
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <stdbool.h>
#include "../external/cJSON.h"
#include "../model/io_k8s_apimachinery_pkg_version_info.h"
io_k8s_apimachinery_pkg_version_info_t* instantiate_io_k8s_apimachinery_pkg_version_info(int include_optional);
io_k8s_apimachinery_pkg_version_info_t* instantiate_io_k8s_apimachinery_pkg_version_info(int include_optional) {
io_k8s_apimachinery_pkg_version_info_t* io_k8s_apimachinery_pkg_version_info = NULL;
if (include_optional) {
io_k8s_apimachinery_pkg_version_info = io_k8s_apimachinery_pkg_version_info_create(
"0",
"0",
"0",
"0",
"0",
"0",
"0",
"0",
"0"
);
} else {
io_k8s_apimachinery_pkg_version_info = io_k8s_apimachinery_pkg_version_info_create(
"0",
"0",
"0",
"0",
"0",
"0",
"0",
"0",
"0"
);
}
return io_k8s_apimachinery_pkg_version_info;
}
#ifdef io_k8s_apimachinery_pkg_version_info_MAIN
void test_io_k8s_apimachinery_pkg_version_info(int include_optional) {
io_k8s_apimachinery_pkg_version_info_t* io_k8s_apimachinery_pkg_version_info_1 = instantiate_io_k8s_apimachinery_pkg_version_info(include_optional);
cJSON* jsonio_k8s_apimachinery_pkg_version_info_1 = io_k8s_apimachinery_pkg_version_info_convertToJSON(io_k8s_apimachinery_pkg_version_info_1);
printf("io_k8s_apimachinery_pkg_version_info :\n%s\n", cJSON_Print(jsonio_k8s_apimachinery_pkg_version_info_1));
io_k8s_apimachinery_pkg_version_info_t* io_k8s_apimachinery_pkg_version_info_2 = io_k8s_apimachinery_pkg_version_info_parseFromJSON(jsonio_k8s_apimachinery_pkg_version_info_1);
cJSON* jsonio_k8s_apimachinery_pkg_version_info_2 = io_k8s_apimachinery_pkg_version_info_convertToJSON(io_k8s_apimachinery_pkg_version_info_2);
printf("repeating io_k8s_apimachinery_pkg_version_info:\n%s\n", cJSON_Print(jsonio_k8s_apimachinery_pkg_version_info_2));
}
int main() {
test_io_k8s_apimachinery_pkg_version_info(1);
test_io_k8s_apimachinery_pkg_version_info(0);
printf("Hello world \n");
return 0;
}
#endif // io_k8s_apimachinery_pkg_version_info_MAIN
#endif // io_k8s_apimachinery_pkg_version_info_TEST
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "recipe.h"
void print_recipes(Recipe recipes[], int num)
{
int i = 0;
for(i = 0; i < num; i++)
{
printf("%d: ", recipes[i].id);
printf("%s\n", recipes[i].name);
}
}
|
C
|
#ifndef MYTIME_H_INCLUDED
#define MYTIME_H_INCLUDED
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <stdio.h>
#include <stdbool.h>
#include <assert.h>
static int day_in_month[12] = {31,28,31,30,31,30,31,31,30,31,30,31};
typedef struct {
int year;
int month;
int day;
int day_in_year;
}date;
int day_in_year(date sol);
bool is_leap_year(int year);
// the period start date "YYYY-MM-DD"
static date start_date ;
// the period end date "YYYY-MM-DD"
static date end_date;
// the period start time "hh" (0~24)
static int start_time = -1;
// the period end time "hh" (0~24)
static int end_time= -1;
// the timeslot of a real time eg. "15:00" with start time "12:00" return 3;
int convert_to_timeslot(char *ptr);
typedef struct
{
int days_since_base; //the day since the base day
int time_slot; //if not ,-1
} Date;
int getStartTime();
int getEndTime();
void get_start_date(char* buf);
void get_end_date(char* buf);
// the duration data of the period eg."4.1~4.3" return 3;
int getdurationDate();
// the duration time of the period eg."11~15" return 4;
int getdurationtime();
Date* newDate(int days_since_base, int time_slot);
bool delDate(Date* ptr);
//check valid date "YYYY-MM-DD"
bool is_valid_date_format(char *date);
// "YYYY-MM-DD" to store at global char *end_date
bool set_end_date(char* date);
// "YYYY-MM-DD" to store at global char *start_date
bool set_start_date(char* date);
//get date_to_base
int convert_to_base(char* date);
//get date_to_real date
char* convert_to_date(int num,char* target);
//check valid time "hh:00"
bool is_valid_time_format(char *time);
//set hh:00 to start time
bool set_start_time(char* time);
//set hh:00 to end time
bool set_end_time(char* time);
#endif
|
C
|
#include <stdio.h>
#include <string.h>
#define MAXLEN 1024
void reverse(char s[]);
void reverser(char s[], int i, int j);
int main()
{
char s[MAXLEN];
while (fgets(s, MAXLEN, stdin) > 0) {
reverse(s);
printf("%s\n",s);
}
return 0;
}
void reverse(char s[])
{
reverser(s, 0, strlen(s)-1);
}
void reverser(char s[], int i, int j)
{
int c;
if (i < j) {
c = s[i];
s[i] = s[j];
s[j] = c;
reverser(s, i+1, j-1);
}
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_isint.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: user <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2020/08/27 20:28:54 by user #+# #+# */
/* Updated: 2020/09/14 23:05:02 by user ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
/*
** Functions to check string for the content of
** the valid int value
*/
/*
** Check if 0 <= int_value <= MAX_INT
*/
int ft_isposint_str(char *str)
{
int i;
i = 0;
if (str[0] == '-')
return (0);
while (str[i])
if (!ft_isdigit(str[i++]))
return (0);
if (ft_strlen(str) > MAXINT_LEN ||
(ft_strlen(str) == MAXINT_LEN && str[MAXINT_LEN - 1] + '0' > 7))
return (0);
return (1);
}
/*
** Check if MIN_INT <= int_value <= MAX_INT
*/
int ft_isint_str(char *str)
{
int i;
int is_sign;
is_sign = (str[0] == '-') ? 1 : 0;
i = is_sign ? 1 : 0;
while (str[i])
if (!ft_isdigit(str[i++]))
return (0);
if (is_sign)
{
if (ft_strlen(str) > MININT_LEN ||
(ft_strlen(str) == MININT_LEN && str[MININT_LEN - 1] + '0' > 8))
i = 0;
}
else
{
if (ft_strlen(str) > MAXINT_LEN ||
(ft_strlen(str) == MAXINT_LEN && str[MAXINT_LEN - 1] + '0' > 7))
i = 0;
}
return (i ? 1 : 0);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define IADD 0x60
#define ISUB 0x64
#define IMUL 0x68
#define IDIV 0x6C
#define ILOAD 0x10
typedef struct ExprNode{
struct ExprNode *left;
char data[10];
struct ExprNode *right;
}ExprNode;
FILE *fp=0;
void postordertraversal(ExprNode * node)
{
if(node!=0)
{
postordertraversal(node->left);
postordertraversal(node->right);
typedef unsigned char byte;
byte bytecode;
if(strcmp(node->data,"+")==0)
{
bytecode=IADD;
}else if(strcmp(node->data,"*")==0)
{
bytecode = IMUL;
} else if(strcmp(node->data,"-")==0)
{
bytecode=IDIV;
} else if(strcmp(node->data,"/")==0)
{
bytecode=IDIV;
}else if(atoi(node->data)!=0)
{
bytecode=ILOAD;
fwrite(&bytecode,1,1,fp);
bytecode=atoi(node->data);
}fwrite(&bytecode,1,1,fp);
}}
int main(){
ExprNode tree[]={{tree+1,"+",tree+2},{tree+3,"*",tree+4},{tree+5,"/",tree+6},{0,"10",0},{0,"20",0},{0,"30",0},{0,"10",0},
};
fp=fopen("bcode.swebok","wb");
postordertraversal(tree);
fclose(fp);
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_may_pose.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: dfouquet <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2017/03/18 18:01:39 by dfouquet #+# #+# */
/* Updated: 2017/03/19 17:23:14 by dfouquet ### ########.fr */
/* */
/* ************************************************************************** */
int ft_number_line(char **grid, int number, int line)
{
int i;
i = 0;
while (i < 9)
{
if (grid[line][i] == number)
return (0);
i++;
}
return (1);
}
int ft_number_column(char **grid, int number, int col)
{
int i;
i = 0;
while (i < 9)
{
if (grid[i][col] == number)
return (0);
i++;
}
return (1);
}
int ft_number_square(char **grid, int number, int col, int line)
{
int i;
int j;
int k;
int l;
k = 0;
i = line / 3;
j = col / 3;
while (k < 3)
{
l = 0;
while (l < 3)
{
if (grid[i * 3 + l][j * 3 + k] == number)
return (0);
l++;
}
k++;
}
return (1);
}
int ft_may_pose(char **grid, int number, int col, int line)
{
if (ft_number_line(grid, number, line) == 0 ||
ft_number_column(grid, number, col) == 0 ||
ft_number_square(grid, number, col, line) == 0)
return (0);
return (1);
}
|
C
|
#include "stdio.h"
#include "defs.h"
void s_SwitchSingal();
void g_DisplaySingalSwitch();
int SW__getnum();
static void s_TimeEdit(u8 u8singalColor, u8 u8singalTime);
static u8 s_TimeLimitJudge(u8 u8singalColor, s16 s16Time);
struct ColorTime g_ctTimeSet = {120,10, 120};
struct ColorTime g_ctTimeDown = {120,10, 120};
struct ColorTime g_ctTimeInitial = {120,10, 120};
int i=0,b;
int back=0;
int a[]={0,1,2,3,5,6,7,8,9,'*','#',4,10};
void main()
{
s_SwitchSingal();
back=1;
printf(" back=%d back\n",back);
printf("--------------------------------------------\n\n\n");
}
void s_SwitchSingal(void)
{
u8 u8singalColor = CLEAR;
for(;;)
{
g_DisplaySingalSwitch(); /*MI*/
u8singalColor = SW__getnum(); /*L[̓͂M*/
switch(u8singalColor)
{
case S_U8_COLOR_GREEN :
s_TimeEdit(u8singalColor,g_ctTimeSet.m_u8Green); /*F̎ԂҏW*/
break;
case S_U8_COLOR_RED :
s_TimeEdit(u8singalColor,g_ctTimeSet.m_u8Red); /*ԐF̎ԂҏW*/
break;
case S_U8_COLOR_YELLOW :
s_TimeEdit(u8singalColor,g_ctTimeSet.m_u8Yellow); /*F̎ԂҏW*/
break;
case S_U8_COLOR_BACK :
return; /*Cj[֖߂*/
default :
/*ق̃L[Kv܂*/
break;
}
}
}
void g_DisplaySingalSwitch()
{
printf("\n-------------------------------\n");
printf("MI\n");
}
int SW__getnum()
{
b=a[i];
if(i==12)
return;
else
i++;
printf("SW__getnum()\n");
printf("L[̒l=%d",b);
return b;
}
static void s_TimeEdit(u8 u8singalColor, u8 u8singalTime)
{
printf(" s_TimeEdit() ");
printf("ݒu:F=%d,=%d",u8singalColor,u8singalTime);
}
|
C
|
#include <stdio.h>
#include <Windows.h>
int main(void)
{
// pierwszy rzdek
printf_s("%2s|","");
for (char i = 0; i < 16; i++) {
printf_s(" *%X", i);
}
printf_s("\n");
// drugi rzdek
printf_s("%s\n",
"--+------------------------------------------------");
// gwne zadanie
for (char i = 2; i <= 7; i++) {
printf_s("%x*|", i);
for (char j = 0; j < 16; j++)
{
printf("%3c", i * 16 + j);
}
printf_s("\n");
}
system("pause");
}
|
C
|
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <gsl/gsl_rng.h>
#include <gsl/gsl_randist.h>
double loglikelihood(int t, double R, int *data, int *imp, double **omega, int n);
int main(int argc, char *argv[]){
char *seed = NULL;
gsl_rng *gsl;
int *data;
int *imp;
int n;
double **omega;
int i, j, e;
double *shape;
double *rate;
double sigma;
double **R;
double Rtmp;
double loglike, tmploglike;
int nsim;
char *tmp = NULL;
FILE *fp;
if(argc != 6){
fprintf(stderr,"Rt seed nsim sigma Tg data\n");
exit(0);
}
seed = argv[1];
nsim = atoi(argv[2]);
sigma = atof(argv[3]);
if(nsim <= 10000){
fprintf(stderr,"nsim must be >10,000\n");
exit(0);
}
//read time series
fp = fopen(argv[5],"r");
i = 0;
tmp = (char *)malloc(100*sizeof(char));
data = (int *)malloc(sizeof(int));
imp = (int *)malloc(sizeof(int));
while( !feof(fp) ){
fscanf(fp,"%s %d %d", tmp, &data[i], &imp[i]);
i++;
data = (int *)realloc(data, (i+1)*sizeof(int));
imp = (int *)realloc(imp, (i+1)*sizeof(int));
}
n = i-1;
// read Tg
fp = fopen(argv[4],"r");
i = 0;
shape = (double *)malloc(sizeof(double));
rate = (double *)malloc(sizeof(double));
while( !feof(fp) ){
fscanf(fp,"%lf %lf",&shape[i],&rate[i]);
i++;
shape = (double *)realloc(shape, (i+1)*sizeof(double));
rate = (double *)realloc(rate, (i+1)*sizeof(double));
}
if( (i-1) < n ){
fprintf(stderr,"Tg vector cannot be shorter than the length of the time series\n");
exit(0);
}
//initialization of the seed
setenv("GSL_RNG_SEED",seed, 1);
gsl_rng_env_setup();
gsl = gsl_rng_alloc (gsl_rng_default);
//allocation of variables
R = (double **)calloc(n,sizeof(double*));
omega = (double**)calloc(n,sizeof(double*));
for(i=0; i<n; i++){
R[i] = (double *)calloc(nsim,sizeof(double));
omega[i] = (double *)calloc(n,sizeof(double));
}
//definition of the generation time
for(i=0; i<n; i++){
for(j=0; j<n; j++){
omega[i][j] = gsl_ran_gamma_pdf(j, shape[i],1/rate[i]);
}
}
// loop over the time series
for(i=1; i<n; i++){
fprintf(stderr,"Day: %d\n",i);
if( (data[i]-imp[i]) > 0){
R[i][0] = 1.;
loglike = loglikelihood(i,R[i][0],data,imp,omega,n);
}else{
R[i][0] = 0.;
}
// loop over the mcmc iterations
for(e=1; e<nsim; e++){
R[i][e] = R[i][e-1];
if( (data[i]-imp[i]) > 0){
Rtmp = -1.;
while(Rtmp < 0.){
Rtmp = R[i][e-1] + gsl_ran_gaussian(gsl,(1+data[i])*sigma);
}
tmploglike = loglikelihood(i,Rtmp,data,imp,omega,n);
if(gsl_ran_flat(gsl,0,1) < exp(tmploglike-loglike)){
loglike = tmploglike;
R[i][e] = Rtmp;
}
}
}
}
for(e=nsim-10000; e<nsim; e++){
fprintf(stdout,"%f",R[0][e]);
for(i=1; i<n; i++){
fprintf(stdout,"\t%f",R[i][e]);
}
fprintf(stdout,"\n");
}
return 0;
}
double loglikelihood(int t, double R, int *data, int *imp, double **omega, int T){
double loglike;
double lambda;
int s;
double *omega2;
double sumomega;
omega2 = (double *)calloc(T,sizeof(double));
sumomega = 0.;
for(s=1; s<=t; s++){
if(data[t-s] > 0){
sumomega += omega[t-s][s];
}
}
for(s=1; s<=t; s++){
omega2[s] = omega[t-s][s]/sumomega;
}
lambda = 0.;
for(s=1; s<=t; s++){
lambda += data[t-s]*omega2[s];
}
loglike = log(gsl_ran_poisson_pdf(data[t]-imp[t],R*lambda));
free(omega2);
return loglike;
}
|
C
|
/***********************************************************
* Author : M_Kepler
* EMail : [email protected]
* Last modified: 2018-07-01 13:33:56
* Filename : sys9.c
* Description :
* 首先使用fork创建一个子进程,接着为了保证子进程不在父进程调用kill之前退出
* 在子进程中使用raise函数向子进程发送SIGSTOP信号,使子进程暂停
* 接下来,再在父进程中调用kill向子进程发送信号,请使用SIGKIL
**********************************************************/
#include<stdio.h>
#include <signal.h>
#include<stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
int main()
{
pid_t pid;
int ret,status;
pid=fork();
if (pid<0)
{
printf("Fork error\n");
exit(1);
}
else if(pid==0)
{
printf("I am child progress(Pid:%d) I am waiting for signal\n",getpid());
raise(SIGSTOP);
printf("I am child progress (pid:%d) i am killed by (pid:%d) \n",getpid(),getppid());
exit(0);
}
else
{
sleep(2);
if(waitpid(pid,NULL,WNOHANG)==0)
{
if(ret=kill(pid,SIGKILL)==0)
{
printf("I am parent progress (pid:%d),i kill progress (pid:%d)\n",getpid(),pid);
}
}
waitpid(pid, &status, 0);
exit(0);
}
return 0;
}
|
C
|
#include<stdio.h>
int main(){
//Checking positiveOrNegative
int input;
printf("enter a int number:");
scanf("%d",&input);
if(input>0)
printf("%d is positive number.",input);
else if(input<0)
printf("%d is negative number",input);
else
printf("%d is zero",input);
return 0;
}
|
C
|
#include <assert.h>
#include <stdio.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <fcntl.h>
#define _GNU_SOURCE
int main(int argc,char* argv[])
{
if(argc!=2)
{
printf("usage:%s <file>\n",argv[0]);
return 1;
}
int filefd=open(argv[1],O_CREAT|O_WRONLY|O_TRUNC,0666);
assert(filefd>0);
int pipefd_stdout[2];
int ret=pipe(pipefd_stdout);
assert(ret!=-1);
int pipefd_file[2];
ret=pipe(pipefd_file);
assert(ret!=-1);
ret=splice(STDIN_FILENO,NULL,pipefd_stdout[1],NULL,32768,/*SPLICE_F_MORE|SPLICE_F_MOVE*/5);
assert(ret!=-1);
ret=tee(pipefd_stdout[0],pipefd_file[1],32768,/*SPLICE_F_NONBLOCK*/5);
assert(ret!=-1);
ret=splice(pipefd_file[0],NULL,filefd,NULL,32768,/*SPLICE_F_MORE|SPLICE_F_MOVE*/5);
assert(ret!=-1);
ret=splice(pipefd_stdout[0],NULL,STDOUT_FILENO,NULL,328768,/*SPLICE_F_MORE|SPLICE_F_MOVE*/5);
assert(ret!=-1);
close(filefd);
close(pipefd_stdout[0]);
close(pipefd_stdout[1]);
close(pipefd_file[0]);
close(pipefd_file[1]);
return 0;
}
|
C
|
#include <stdlib.h>
#include <stdio.h>
int main(int argc, char **argv) {
int cookie;
char buf[80];
printf("buf: %08x cookie: %08x\n", &buf, &cookie);
gets(buf);
if (cookie == 0x01020005)
printf("you win!\n");
}
|
C
|
// https://cryptopals.com/sets/1/challenges/5
#include "../helper.h"
int main()
{
char *text = "Burning 'em, if you ain't quick and nimble\nI go crazy when I hear a cymbal";
char *answer = "0b3637272a2b2e63622c2e69692a23693a2a3c6324202d623d63343c2a26226324272765272a282b2f20430a652e2c652a3124333a653e2b2027630c692b20283165286326302e27282f";
char *key = "ICE";
unsigned char bytesXOR[strlen(text)];
//Encrypt text using repeating-key XOR (ICE)
for(int i = 0; i < strlen(text); i++)
{
bytesXOR[i] = text[i] ^ key[i % 3];
}
char *hex = bytesToHex(bytesXOR, strlen(text)); //hex string of bytes array
if(strcmp(answer, hex) == 0)
printf("Success!\n");
else
printf("Failure!\n");
free(hex);
}
|
C
|
/*
* Rewrite the temperature conversion program of Section 1.2 to use a function
* for conversion
*/
#include <stdio.h>
/*
* Summary:
* Converts a temperature in Fahrenheit to Celsius
* Parameters:
* fahr (float): temperature in Fahrenheit
* Return Value:
* Celsius value of 'fahr' (float)
* Description:
* Uses the conversion formula for Fahrenheit to Celsius
*/
float fahrToCelsius(float fahr);
int main(void)
{
int lower = 0, upper = 300, step = 20;
float fahr = lower;
puts("Fahrenheit | Celsius");
puts("---------------------");
while (fahr <= upper) {
printf("%10.0f | %6.1f\n", fahr, fahrToCelsius(fahr));
fahr += step;
}
return 0;
}
float fahrToCelsius(float fahr)
{
return (5.0 / 9.0) * (fahr - 32.0);
}
|
C
|
/*
* psutils.c
*/
#include <stdio.h>
#include "psutils.h"
static char psstring[10000];
static FILE *opf;
void ps(char *string)
{
fprintf(opf, "%s\n", string);
}
void psDrawChar(char aChar)
{
switch (aChar) {
case '(':
sprintf(psstring, "(\\50) show");
break;
case ')':
sprintf(psstring, "(\\51) show");
break;
default:
sprintf(psstring, "(%c) show", aChar);
break;
}
ps(psstring);
}
void print_caption(char *caption) {
float size = 10, space = 13, h = 13, v = -28;
int c, len;
len = strlen(caption);
ps("/Times-Roman findfont 10.000 scalefont setfont");
sprintf(psstring, "%f %f moveto", h, v);
ps(psstring);
for (c = 0; c < len; c++)
switch (caption[c]) {
case '\n':
v -= space;
sprintf(psstring, "%f %f moveto", h, v);
ps(psstring);
break;
default:
psDrawChar(caption[c]);
}
}
void set_print_opf(FILE *thefile)
{
opf = thefile;
}
FILE *get_print_opf(void)
{
return (opf);
}
void psline(double x1, double y1, double x2, double y2)
{
fprintf(opf, "n %.2lf %.2lf m %.2lf %.2lf l\n", x1, y1, x2, y2);
}
|
C
|
#include "reverse_aska.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define B32_SIGNATURE "\x05\xe2\x00\xcf\xee\x7f\xf1\x88"
int fetch_b32value(const unsigned char* code, int* pos, int code_bytes)
{
int i;
int offset;
int fetch_bytes;
int ret_value;
if (*pos < 0) return 0;
if (code[*pos] == 0x76) {
offset = 1;
fetch_bytes = 3;
} else if (strncmp(code+*pos, "\xff\xff\xf7\x88", 4) == 0) {
offset = 4;
fetch_bytes = 4;
} else {
*pos = -1;
return 0;
}
// TODO: オーバーフローチェックがない
ret_value = 0;
for (i = 0; i < fetch_bytes; i++) {
ret_value = (ret_value << 8) | code[*pos+offset+i];
}
*pos += offset+fetch_bytes;
return ret_value;
}
int reverse_aska_prepare_code(ReverseAska* raska)
{
int* instruction_index;
int instruction_index_cnt;
int idxcnt;
int pos;
enum InstructionId instid;
int skipcnt;
instruction_index_cnt = 64;
instruction_index = (int*)malloc(sizeof(int) * instruction_index_cnt);
if (!instruction_index) return 0;
idxcnt = 0;
pos = 8;
do {
if (instruction_index_cnt >= idxcnt) {
instruction_index_cnt += 64;
instruction_index = (int*)realloc(instruction_index, sizeof(int) * instruction_index_cnt);
if (!instruction_index) return 0;
}
instruction_index[idxcnt++] = pos;
instid = fetch_b32value(raska->code, &pos, raska->codelen);
if (pos == -1) goto error;
switch (instid) {
case CND:
skipcnt = 1;
break;
case LB:
case PLIMM:
case PCP:
case LIDR:
skipcnt = 2;
break;
case LIMM:
skipcnt = 3;
break;
case OR:
case XOR:
case AND:
case SBX:
case ADD:
case SUB:
case MUL:
case SHL:
case SAR:
case DIV:
case MOD:
skipcnt = 4;
break;
case LMEM:
case SMEM:
case PADD:
case CMPE:
case CMPNE:
case CMPL:
case CMPGE:
case CMPLE:
case CMPG:
case TSTZ:
case TSTNZ:
skipcnt = 5;
break;
case DATA:
{
int typ = fetch_b32value(raska->code, &pos, raska->codelen);
int len = fetch_b32value(raska->code, &pos, raska->codelen);
skipcnt = 0;
pos += len*4;
}
break;
case REM:
{
int uimm = fetch_b32value(raska->code, &pos, raska->codelen);
switch (uimm)
{
case 0x00: skipcnt = 1; break;
case 0x01: skipcnt = 1; break;
case 0x02: skipcnt = 2; break;
case 0x03: skipcnt = 1; break;
case 0x34: skipcnt = 1; break;
case 0x1ff: skipcnt = 1; break;
default: goto error; break;
}
}
break;
default:
goto error;
}
while (skipcnt-- > 0) {
fetch_b32value(raska->code, &pos, raska->codelen);
}
} while (pos < raska->codelen);
raska->instruction_index = instruction_index;
raska->idxcnt = idxcnt;
return 1;
error:
free(instruction_index);
return 0;
}
ReverseAska* reverse_aska_init(const uint8_t* code, int codelen)
{
ReverseAska* raska = NULL;
if (strncmp(code, B32_SIGNATURE, 8) != 0) return NULL;
raska = (ReverseAska*)malloc(sizeof(ReverseAska));
if (!raska) goto error;
memset(raska, 0, sizeof(ReverseAska));
raska->code = (uint8_t*)malloc(codelen);
if (!raska->code) goto error;
memcpy(raska->code, code, codelen);
raska->codelen = codelen;
if (!reverse_aska_prepare_code(raska)) goto error;
return raska;
error:
free(raska->code);
free(raska->instruction_index);
free(raska);
return NULL;
}
void reverse_aska_free(ReverseAska* raska)
{
free(raska->code);
free(raska->instruction_index);
free(raska);
}
struct ReverseAskaInstruction* get_instruction_string(ReverseAska* raska, int num)
{
struct ReverseAskaInstruction* ret_inst = NULL;
int pos;
int instpos = 0, instnum = 0;
enum InstructionId instid;
static const char* operate_inst_name[] = {
"OR", "XOR", "AND", "SBX",
"ADD", "SUB", "MUL",
"SHL", "SAR", "DIV", "MOD",
};
static const char* compare_inst_name[] = {
"CMPE", "CMPNE", "CMPL", "CMPGE",
"CMPLE", "CMPG", "TSTZ", "TSTNZ",
};
if (num < 0 || num >= raska->idxcnt) return NULL;
ret_inst = (struct ReverseAskaInstruction*)malloc(sizeof(struct ReverseAskaInstruction));
if (!ret_inst) return NULL;
// FIXME: めんどくさいのでとりあえずどれも100バイト確保してある
ret_inst->inst_str = (char*)malloc(sizeof(char) * 100);
if (!ret_inst->inst_str) {
free(ret_inst);
return NULL;
}
ret_inst->number = num;
pos = raska->instruction_index[num];
instid = fetch_b32value(raska->code, &pos, raska->codelen);
switch (instid) {
case LB:
{
int uimm = fetch_b32value(raska->code, &pos, raska->codelen);
int opt = fetch_b32value(raska->code, &pos, raska->codelen);
snprintf(ret_inst->inst_str, 100, "LB(opt:%d, uimm:%d);", opt, uimm);
}
break;
case LIMM:
{
int imm = fetch_b32value(raska->code, &pos, raska->codelen);
int r = fetch_b32value(raska->code, &pos, raska->codelen);
int bit = fetch_b32value(raska->code, &pos, raska->codelen);
snprintf(ret_inst->inst_str, 100, "LIMM(bit:%d, r:R%02X, imm:0x%08x);", bit, r, imm);
}
break;
case PLIMM:
{
int uimm = fetch_b32value(raska->code, &pos, raska->codelen);
int p = fetch_b32value(raska->code, &pos, raska->codelen);
snprintf(ret_inst->inst_str, 100, "PLIMM(p:P%02X, uimm:%d);", p, uimm);
}
break;
case CND:
{
int r = fetch_b32value(raska->code, &pos, raska->codelen);
snprintf(ret_inst->inst_str, 100, "CND(r:R%02X);", r);
}
break;
case LMEM:
{
int p = fetch_b32value(raska->code, &pos, raska->codelen);
int typ = fetch_b32value(raska->code, &pos, raska->codelen);
int zero = fetch_b32value(raska->code, &pos, raska->codelen);
int r = fetch_b32value(raska->code, &pos, raska->codelen);
int bit = fetch_b32value(raska->code, &pos, raska->codelen);
snprintf(ret_inst->inst_str, 100, "LMEM(bit:%d, r:R%02X, typ:%d, p:P%02X, %d);", bit, r, typ, p, zero);
}
break;
case SMEM:
{
int r = fetch_b32value(raska->code, &pos, raska->codelen);
int bit = fetch_b32value(raska->code, &pos, raska->codelen);
int p = fetch_b32value(raska->code, &pos, raska->codelen);
int typ = fetch_b32value(raska->code, &pos, raska->codelen);
int zero = fetch_b32value(raska->code, &pos, raska->codelen);
snprintf(ret_inst->inst_str, 100, "SMEM(bit:%d, r:R%02X, typ:%d, p:P%02X, %d);", bit, r, typ, p, zero);
}
break;
case PADD:
{
int p1 = fetch_b32value(raska->code, &pos, raska->codelen);
int typ = fetch_b32value(raska->code, &pos, raska->codelen);
int r = fetch_b32value(raska->code, &pos, raska->codelen);
int bit = fetch_b32value(raska->code, &pos, raska->codelen);
int p0 = fetch_b32value(raska->code, &pos, raska->codelen);
snprintf(ret_inst->inst_str, 100, "PADD(bit:%d, p0]P%02X, typ:%d, p1:P%02X, r:R%02X);", bit, p0, typ, p1, r);
}
break;
case OR:
case XOR:
case AND:
case SBX:
case ADD:
case SUB:
case MUL:
case SHL:
case SAR:
case DIV:
case MOD:
{
int r1 = fetch_b32value(raska->code, &pos, raska->codelen);
int r2 = fetch_b32value(raska->code, &pos, raska->codelen);
int r0 = fetch_b32value(raska->code, &pos, raska->codelen);
int bit = fetch_b32value(raska->code, &pos, raska->codelen);
if (instid == OR && r1 == r2) {
snprintf(ret_inst->inst_str, 100, "CP(r0:R%02X, r1:R%02X);", r0, r1);
} else {
snprintf(ret_inst->inst_str, 100, "%s(bit:%d, r0:R%02X, r1:R%02X, r2:R%02X);", operate_inst_name[instid-OR], bit, r0, r1, r2);
}
}
break;
case CMPE:
case CMPNE:
case CMPL:
case CMPGE:
case CMPLE:
case CMPG:
case TSTZ:
case TSTNZ:
{
int r1 = fetch_b32value(raska->code, &pos, raska->codelen);
int r2 = fetch_b32value(raska->code, &pos, raska->codelen);
int bit1 = fetch_b32value(raska->code, &pos, raska->codelen);
int r0 = fetch_b32value(raska->code, &pos, raska->codelen);
int bit0 = fetch_b32value(raska->code, &pos, raska->codelen);
snprintf(ret_inst->inst_str, 100, "%s(bit0:%d, bit1:%d, r0:R%02X, r1:R%02X, r2:R%02X);", compare_inst_name[instid-CMPE], bit0, bit1, r0, r1, r2);
}
break;
case PCP:
{
int p1 = fetch_b32value(raska->code, &pos, raska->codelen);
int p0 = fetch_b32value(raska->code, &pos, raska->codelen);
snprintf(ret_inst->inst_str, 100, "PCP(p0:P%02X, p1:P%02X);", p0, p1);
}
break;
case DATA:
{
int typ = fetch_b32value(raska->code, &pos, raska->codelen);
int len = fetch_b32value(raska->code, &pos, raska->codelen);
snprintf(ret_inst->inst_str, 100, "data(typ:%d, len:%d);", typ, len);
}
break;
case LIDR:
{
int imm = fetch_b32value(raska->code, &pos, raska->codelen);
int dr = fetch_b32value(raska->code, &pos, raska->codelen);
snprintf(ret_inst->inst_str, 100, "LIDR(dr:D%02X, imm:%d);", dr, imm);
}
break;
case REM:
{
int uimm = fetch_b32value(raska->code, &pos, raska->codelen);
if (uimm == 0x1ff) {
snprintf(ret_inst->inst_str, 100, "REM%02X(...); // breakpoint", uimm);
} else {
snprintf(ret_inst->inst_str, 100, "REM%02X(...);", uimm);
}
}
break;
default:
snprintf(ret_inst->inst_str, 100, "(unknown:%x)", instid);
free(ret_inst->inst_str);
free(ret_inst);
return NULL;
}
return ret_inst;
}
|
C
|
/* $Source$
* $State$
* $Revision$
*/
#include <fcntl.h>
#include "libsys.h"
/*
* Say whether a particular fd is currently open in text or binary mode.
* Assume that the fd is valid. Return O_TEXT or O_BINARY.
*/
int _sys_getmode(int fd)
{
int reqbegfd = fd & ~_FDVECMASK;
struct _fdmodes *p = &_sys_fdmodes;
_fdvec_t mask;
while (p->begfd != reqbegfd)
{
p = p->next;
if (!p)
return O_TEXT;
}
mask = (_fdvec_t)1 << (fd & _FDVECMASK);
return (p->modevec & mask) ? O_BINARY : O_TEXT;
}
|
C
|
#include<stdio.h>
#include<stdlib.h>
int main()
{
int i,*pizza,maximum,curr_slice,curr_type,type,counter;
printf("Maximum number of pizza slices");
scanf("%d",&maximum);
printf("types of pizza");
scanf("%d",&type);
pizza=(int*)malloc(type*sizeof(int));
for(i=0;i<type;i++)
scanf("%d",&pizza[i]);
counter=0;
curr_slice=0;
curr_type=0;
for(i=type-1;i>=0;i--){
if(curr_slice<maximum)
{
curr_slice+=pizza[i];
printf("%d\t",curr_type);
curr_type+=1;
counter+=1;
}
}
printf("%d",counter);
}
|
C
|
#ifndef QUEUE_H
#define QUEUE_H
#include <stdint.h>
#include <stddef.h>
struct queue_item;
struct queue_item
{
struct queue_item* next;
uint32_t v;
};
typedef struct queue_item queue_item_t;
typedef struct
{
queue_item_t* front;
queue_item_t* last;
size_t size;
} queue_t;
void queueInit(queue_t* q);
void queueAdd(queue_t* q, uint32_t v);
uint32_t queueRemove(queue_t* q);
uint32_t queueFront(queue_t* q);
#endif
|
C
|
#include "density_map.h"
#define MAX_PEAKS 100
#define MIN_DENSITY 1500
#define xkl 20
#define ykl 20
#define xcl ( DENSITY_MAP_WIDTH + xkl - 1 )
#define ycl ( DENSITY_MAP_HEIGHT + ykl - 1 )
double xk[] = {1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1};
double yk[] = {1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1};
double xi[DENSITY_MAP_WIDTH];
double yi[DENSITY_MAP_HEIGHT];
double xc[xcl];
double yc[ycl];
int xpn = 0;
int ypn = 0;
int xp[MAX_PEAKS], yp[MAX_PEAKS];
density_peak_t density_peaks[MAX_PEAKS];
void convolve(const double Signal[], size_t SignalLen,
const double Kernel[], size_t KernelLen,
double Result[])
{
size_t n;
int i = 0;
for (n = 0; n < SignalLen + KernelLen - 1; n++)
{
size_t kmin, kmax, k;
Result[n] = 0;
kmin = (n >= KernelLen - 1) ? n - (KernelLen - 1) : 0;
kmax = (n < SignalLen - 1) ? n : SignalLen - 1;
for (k = kmin; k <= kmax; k++)
{
i++;
Result[n] += Signal[k] * Kernel[n - k];
}
}
}
void calculatePeaks( void )
{
int peak = 1;
double prev, diff;
prev = xc[0];
uint16_t i, j;
for (j = 1; j < xcl; j++ )
{
diff = xc[j] - prev;
if ( peak )
{
if ( diff < 0 )
{
peak = 0;
xp[xpn++] = j;
}
prev = xc[j];
if (xpn == MAX_PEAKS) break;
}
else
{
if ( diff > 0 ) peak = 1;
}
}
prev = yc[0];
for (i = 1; i < ycl; i++ )
{
diff = yc[i] - prev;
if ( peak )
{
if ( diff < 0 )
{
peak = 0;
yp[ypn++] = i;
}
prev = yc[i];
if (ypn == MAX_PEAKS) break;
}
else
{
if ( diff > 0 ) peak = 1;
}
}
}
void processDensityMaps( void )
{
convolve(xi, DENSITY_MAP_WIDTH, xk, xkl, xc);
convolve(yi, DENSITY_MAP_HEIGHT, yk, ykl, yc);
calculatePeaks();
int index = 0, i, j;
for(i = 0; i < ypn; i++ )
{
int y = (int)((float)yp[i] * (float)DENSITY_MAP_HEIGHT/(float)ycl);
for(j = 0; j < xpn; j++ )
{
int x = (int)((float)xp[j] * (float)DENSITY_MAP_WIDTH/(float)xcl);
if(( xc[x] + yc[y] ) > MIN_DENSITY )
{
/* Peak height */
density_peaks[index].X = x;
density_peaks[index].Y = y;
density_peaks[index].X = xc[x] + yc[y];
index++;
}
}
}
}
void generateDensityMaps( uint8_t image_line[], uint16_t y )
{
uint16_t x = 0;
while( x < DENSITY_MAP_WIDTH ) // Traverse all columns
{
uint8_t a = image_line[x];
if( a > DENSITY_MAP_THRESH ) // Check if pixel is on
{
xi[x] += 1;
yi[y] += 1;
}
x += DENSITY_MAP_INTERVAL;
}
}
void initDensityMaps( uint16_t width, uint16_t height, uint16_t interval, uint16_t thresh )
{
// DENSITY_MAP_WIDTH = width;
// DENSITY_MAP_HEIGHT = height;
DENSITY_MAP_INTERVAL = interval;
DENSITY_MAP_THRESH = thresh;
}
|
C
|
#include "print_uart.h"
#include <avr/power.h>
#include <avr/io.h>
#include <avr/interrupt.h>
#include <avr/sleep.h>
#include <util/atomic.h>
#include <stdbool.h>
#include <stdlib.h>
volatile bool rxcflag = false;
/* USART Data Register Empty interrupt handler */
ISR(USART_UDRE_vect, ISR_BLOCK)
{
if (('\0' == wrbuff[wrind]) || txcflag) {
/* If nothing to transmit - disable this interrupt and exit */
UCSR0B &= ~(1 << UDRIE0);
txcflag = true;
return;
}
UDR0 = wrbuff[wrind++];
/* Really we don't need this as long as every string ends with '\0' */
if (wrind >= BUFFER_LEN)
wrind = 0;
}
/* USART TX Complete interrupt handler */
ISR(USART_TX_vect, ISR_BLOCK)
{
/* When data register is empty and after the shift register contents */
/* are already transfered, this interrupt is raised */
UCSR0B &= ~(1 << TXCIE0);
}
void uart_init(void)
{
/* To use USART module, we need to power it on first */
power_usart0_enable();
/* Configure prescaler */
UBRR0L = ubrr_val & 0xFF; /* Lower byte */
UBRR0H = (ubrr_val >> 8) & 0xFF; /* Higher byte */
/* Or we could use UBRR0 (16-bit defined) instead */
/* Set operation mode */
/* Asynchronous mode, even parity, 2 stop bits, 8 data bits */
UCSR0C = (1 << UPM01) | (1 << USBS0) | (1 << UCSZ00) | (1 << UCSZ01);
/* Continue setup & enable USART in one operation */
/* RX & TX complete, Data reg empty interrupts enabled */
UCSR0B = (1 << RXCIE0) | (1 << RXEN0) | (1 << TXEN0);
}
void uart_put(char *str)
{
/* If buffer contents have not been transfered yet -- put MCU to sleep */
while(!txcflag)
sleep_cpu();
/* No interrupts can occur while this block is executed */
ATOMIC_BLOCK(ATOMIC_RESTORESTATE) {
for (uint8_t i = 0; i < BUFFER_LEN; i++) {
wrbuff[i] = str[i];
if ('\0' == str[i])
break;
}
wrind = 0;
txcflag = false; /* programmatic transfer complete flag */
/* Enable transmitter interrupts */
UCSR0B |= (1 << TXCIE0) | (1 << UDRIE0);
}
}
bool atomic_str_eq(char *str1, char *str2)
{
bool res = true;
ATOMIC_BLOCK(ATOMIC_RESTORESTATE) {
for (uint8_t i = 0; i < BUFFER_LEN; i++) {
if (str1[i] != str2[i]) {
res = false;
break;
}
if ('\0' == str1[i])
break;
}
}
return res;
}
char* to_string_uint8(uint8_t arg, char* str)
{
str = malloc(3 * sizeof(char) + 1); /* 3 numbers + \0 sumbol */
uint8_t tmp = arg;
uint8_t pos = 0; /* number of symbols in str */
if( arg >= 100 ) {
tmp /= 100;
str[pos] = tmp + '0'; /* watch ASCII table */
arg %= 100;
pos++;
}
else {
str[pos] = ' ';
pos++;
}
tmp = arg;
if( arg >= 10 ) {
tmp /= 10;
str[pos] = tmp + '0'; /* watch ASCII table */
arg %= 10;
pos++;
}
else {
str[pos] = ' ';
pos++;
}
str[pos] = arg + '0'; /* watch ASCII table */
pos++;
str[pos] = '\0';
return str;
}
char* to_string_uint16(uint16_t arg, char* str)
{
str = malloc(5 * sizeof(char) + 10); /* 5 numbers + \0 sumbol */
uint16_t tmp = arg;
uint8_t pos = 0; /* number of symbols in str */
if( arg >= 10000 ) {
tmp /= 10000;
str[pos] = tmp + '0'; /* watch ASCII table */
arg %= 10000;
pos++;
}
else {
str[pos] = ' ';
pos++;
}
tmp = arg;
if( arg >= 1000 ) {
tmp /= 1000;
str[pos] = tmp + '0'; /* watch ASCII table */
arg %= 1000;
pos++;
}
else {
str[pos] = ' ';
pos++;
}
tmp = arg;
if( arg >= 100 ) {
tmp /= 100;
str[pos] = tmp + '0'; /* watch ASCII table */
arg %= 100;
pos++;
}
else {
str[pos] = ' ';
pos++;
}
tmp = arg;
if( arg >= 10 ) {
tmp /= 10;
str[pos] = tmp + '0'; /* watch ASCII table */
arg %= 10;
pos++;
}
else {
str[pos] = ' ';
pos++;
}
str[pos] = arg + '0'; /* watch ASCII table */
pos++;
str[pos] = '\0';
return str;
}
extern void uart_print_str(char *str);
extern void uart_print_uint8(uint8_t arg, char* str);
extern void uart_print_uint16(uint16_t arg, char* str);
|
C
|
#include "expression/ast.h"
#include <stdlib.h>
struct ast_node *ast_make(int type, struct ast_node *left,
struct ast_node *right)
{
struct ast_node *res = malloc(sizeof(struct ast_node));
if (!res)
return NULL;
res->type = type;
res->data = NULL;
res->nb_data = 0;
res->left = left;
res->right = right;
return res;
}
void ast_free(struct ast_node *root, void (*free_fct)(void*))
{
if (!root)
return;
ast_free(root->left, free_fct);
ast_free(root->right, free_fct);
if (free_fct)
free_fct(root->data);
free(root);
}
|
C
|
//http://projecteuler.net/problem=39
//Author - Ashish Kedia, NITK Surathkal
//@ashish1294
#include<stdio.h>
#include<math.h>
int i,j,k,arr[1001]={0},root[10000001],max=9;
int main()
{
for(i=0;i<1000001;i++) root[i]=-1;
for(i=0;i<1001;i++) {arr[i]=0;root[i*i]=i;}
for(i=1;i<500;i++)
{
for(j=i;j<500;j++)
{
if(i+j+sqrt(i*i+j*j)>1000) break;
int r = root[i*i+j*j];
if(r==-1) continue;
//printf("Pyth Trip = %d,%d,%d sum=%d\n",i,j,r,i+j+r);
arr[i+j+r]++;
}
}
for(i=10;i<=1000;i++) if(arr[i]>arr[max]) max=i;
printf("The Perimeter for which the number of solution is maximum: %d",max);
return 0;
}
|
C
|
#include<stdio.h>
unsigned setbits(unsigned x, int p, int n, unsigned y);
int main(){
unsigned int x = 150;
unsigned int y = 25;
printf("test: %d\n", ~(~0<<3)<<2 );
printf("x: %d\n", setbits(x, 4, 3, y));
return 0;
}
unsigned setbits(unsigned x, int p, int n, unsigned y){
return x & ~(~(~0 << n) << (p+1-n)) | (y & ~(~0 << n)) << (p+1-n);
}
|
C
|
/*
* uart_cli.c
*
* Created on: Mar 25, 2021
* Author: Wiktor Lechowicz
*
* This code contain reusable code for usart based command line interface targeted for stm32 MCUs based on HAL drivers.
*
* * HOW TO USE *
* Create struct CLI_field_destrictor array to describe content of memory with tag strings and type specifiers CLI_field_type.
*
* Initialize CLI (CLI_Init()) with just created memory descriptor.
* Example in main.c
*/
/* === exported includes === */
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include "stm32f3xx_hal.h"
/* === exported defines === */
#define CLI_MAX_TAG_LEN 20 // maximum length of memory field tag displayed in CLI.
/* === exported types === */
enum CLI_field_type {
CLI_FIELD_UINT8,
CLI_FIELD_UINT16,
CLI_FIELD_UINT32,
CLI_FIELD_INT8,
CLI_FIELD_INT16,
CLI_FIELD_INT32,
CLI_FIELD_CHAR,
};
struct CLI_field_descriptor {
char cli_tag[CLI_MAX_TAG_LEN]; // string displayed in terminal which describes displayed memory content
enum CLI_field_type type; // field type, enum
uint16_t size; // size of variable in bytes, use sizeof(variable), works as well for arrays as sizeof(array)
uint16_t num_elements; // number of variables in array, 1 for single variables
};
/* === exported functions === */
/** @brief cli initialization function
* @param huart - uart handle
* @param mem_p - pointer to printed out memory content
* @param descriptor - pointer to memory descriptor struct
* @param num_elements - number of variables in printed memory space
* @retval void */
void CLI_Init(UART_HandleTypeDef *huart, void *mem_p, struct CLI_field_descriptor *descriptor, uint16_t num_elements);
#ifndef APP_INC_UART_CLI_C_
#define APP_INC_UART_CLI_C_
#endif /* APP_INC_UART_CLI_C_ */
|
C
|
//
// This file was generated by the Retargetable Decompiler
// Website: https://retdec.com
// Copyright (c) 2015 Retargetable Decompiler <[email protected]>
//
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
/* ------- Float Types Definitions ------ */
typedef float float32_t;
typedef double float64_t;
/* -------- Function Prototypes --------- */
int32_t nejaka_funkce(int32_t aa, int32_t bb, char * str, int32_t cc, int32_t dd, int32_t ee);
int32_t smichana_funkce(int32_t xx, float32_t yy, int32_t zz, float64_t dodo);
int32_t volaci_funkce(void);
/* ------------- Functions -------------- */
// From module: c:\cpp\manyvars\manyvars\windows mobile 6 standard sdk (armv4i)\debug\manyvars.obj
// Address range: 0x11000 - 0x11147
// Line range: 7 - 29
int32_t nejaka_funkce(int32_t aa, int32_t bb, char * str, int32_t cc, int32_t dd, int32_t ee) {
int32_t v1 = aa + 17 + -3 * bb + cc; // 0x1102c
int32_t v2 = rand(); // 0x11034
int32_t v3 = dd + rand(); // 0x11054
if (ee >= 51) {
int32_t v4 = 25 * ee - 1250; // 0x11074
printf("Blabla %d\n", v4);
v3 += v4;
// branch -> 0x11098
}
// 0x11098
if (v1 == 0) {
// 0x110d4
printf("Vyraz je nulovy a retezec je %s (%d)\n", str, v3);
// branch -> 0x110e4
} else {
// 0x110b8
printf("Vyraz je nenulovy %d %d\n", v1, v3 + v1);
// branch -> 0x110e4
}
// 0x110e4
return aa + 23 + bb + v1 + 2 * cc + v2 - v3 + v3 + ee;
}
// From module: c:\cpp\manyvars\manyvars\windows mobile 6 standard sdk (armv4i)\debug\manyvars.obj
// Address range: 0x11148 - 0x11233
// Line range: 32 - 42
int32_t smichana_funkce(int32_t xx, float32_t yy, int32_t zz, float64_t dodo) {
// 0x11148
_stod();
printf("Hodnota floatu jeje %f\n", (float64_t)(int64_t)(int32_t)yy);
printf("Soucet je %d\n", zz + xx);
_muld();
_itod();
_addd();
_dtoi();
return xx;
}
// From module: c:\cpp\manyvars\manyvars\windows mobile 6 standard sdk (armv4i)\debug\manyvars.obj
// Address range: 0x11234 - 0x11327
// Line range: 45 - 53
int32_t volaci_funkce(void) {
int32_t v1 = rand(); // 0x1123c
_itod();
_addd();
_dtos();
_itod();
_addd();
puts("Calling");
return printf("Vysledek je %d\n", smichana_funkce(v1, (float32_t)v1, 46, (float64_t)(float32_t)v1));
}
// Address range: 0x11328 - 0x114bc
int main(int argc, char ** argv) {
int32_t v1 = rand(); // 0x11338
int32_t v2 = rand(); // 0x11348
int32_t v3 = rand(); // 0x11358
int32_t v4 = rand(); // 0x11368
int32_t v5 = rand(); // 0x11378
int32_t v6 = rand() + v1; // 0x11398
int32_t v7 = rand(); // 0x113a0
int32_t v8 = rand(); // 0x113b8
int32_t v9 = rand(); // 0x113d0
int32_t v10 = nejaka_funkce(v2, v6, "Retezec", v7 + v2, v3, v5) + v1; // 0x11418
int32_t result = v4;
if (v4 < 1001) {
int32_t v11 = v3 + v2 + v4 - v5 - v6 + v10; // 0x11460
int32_t v12 = nejaka_funkce(v11, v8 + v3, "Dalsi", v9 + v4, v10, v5); // 0x11488
volaci_funkce();
result = v12 + v11;
// branch -> 0x114ac
}
// 0x114ac
return result;
}
/* --------- External Functions --------- */
// void _addd(void);
// void _dtoi(void);
// void _dtos(void);
// void _itod(void);
// void _muld(void);
// void _stod(void);
// int printf (const char *restrict, ...)
// int puts (const char *)
// int rand ()
/* ---------- Meta-Information ---------- */
// Detected compiler: windows mobile visual c++ 6 standard sdk (armv4i) (visual studio 2008)
// Detected functions: 4 (31 in front-end)
// Decompiler release: jump-table-remove/bd37749-modified (2015-07-19 14:51:18)
// Decompilation date: 2015-06-19 14:51:32
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <signal.h>
#include <errno.h>
#include <sys/wait.h>
#define MAXBUF 1024
void handler2(int sig) {
int olderrno = errno;
while(waitpid(-1, NULL, 0) > 0) {
printf("handler reaped child\n");
}
sleep(1);
errno = olderrno;
}
int main(void) {
int i, n;
char buf[MAXBUF];
if(signal(SIGCHLD, handler2) == SIG_ERR) {
perror("signal error");
}
for(i = 0; i < 3; i++) {
if(fork() == 0) {
printf("Hello from child %d\n", (int)getpid());
exit(0);
}
}
if((n = read(0, buf, sizeof(buf))) < 0) {
perror("read");
}
printf("Parent processing input\n");
while(1) {
;
}
exit(0);
}
|
C
|
#include <sexo.h>
#include <dirs.h>
private mapping clases = ([ ]);
private nosave object * obs_clases = ({ });
int cargar_clase() {
object ob;
string err;
foreach(string clase in keys(clases)) {
err = catch(ob = load_object(clase));
if ((err) || (!ob)) {
write("Error cargando la clase "+clase+"\n");
if (err) write(err+"\n");
return 0;
}
obs_clases += ({ ob });
}
return 1;
}
int clase(string nueva_clase) {
object raza, clase;
string file, err;
nueva_clase = lower_case(nueva_clase);
if (!find_file(nueva_clase)) {
if (!find_file(DIR_CLASES+"/"+nueva_clase+".c")) {
write("Esa clase no existe!\n");
return 0;
}
else nueva_clase = DIR_CLASES+"/"+nueva_clase+".c";
}
if (!(file = TP -> fichero_raza?())) {
write("La ficha debe tener raza antes que clase!\n");
return 0;
}
if ((err = catch(raza = load_object(file))) || (!raza)) {
write("Error cargando la raza "+file+"\n");
if (err) write(err);
return 0;
}
if (!raza -> clase_permitida?(clase)) {
write("Un "+raza->nombre_raza?(VARON)+" no puede pertenecer a esa clase.\n");
return 0;
}
if ((err = catch(clase = load_object(nueva_clase)) || (!clase))) {
write("Error cargando la clase "+nueva_clase+"\n");
if (err) write(err);
return 0;
}
clases[nueva_clase] = 0;
obs_clases += ({ clase });
return 1;
}
string * clase?() {
string * nombres = ({ });
foreach(object clase in obs_clases) {
nombres += ({ clase -> nombre_clase?() });
}
return nombres;
}
string * fichero_clase?() {
return keys(clases);
}
string * skills_favoritas?() {
string * favoritas = ({ }), * cfav = ({ });
foreach(object clase in obs_clases) {
cfav = clase -> skills_favoritas?();
foreach(string skill in cfav) {
if (member_array(skill, favoritas) == -1)
favoritas += ({ skill });
}
}
return favoritas;
}
int skill_favorita?(string skill) {
return (member_array(skill, skills_favoritas?()) == -1 ? 0 : 1);
}
varargs int nivel?(string clase) {
int found, nivel = 0;
string nombre;
if ((!clase) || (clase=="")) {
foreach(string c in keys(clases)) {
nivel += clases[c];
}
return nivel;
}
else {
found = 0;
foreach(object ob_clase in obs_clases) {
nombre = ob_clase -> nombre_clase?();
if (nombre == clase) {
found = 1;
nombre = file_name(ob_clase) + ".c";
break;
}
}
if (found) return clases[nombre];
else return 0;
}
}
protected void avanzar_clase(string avanzar_clase) {
if (!clases[DIR_CLASES+"/"+avanzar_clase+".c"]) {
clase(avanzar_clase);
}
clases[DIR_CLASES+"/"+avanzar_clase+".c"] += 1;
}
int ataque_base?() {
int ab;
foreach(object clase in obs_clases) {
ab += clase -> ataque_base?(clases[file_name(clase)+".c"]);
}
return ab;
}
string * clases?() {
string * clases = ({ });
foreach(string clase in get_dir(DIR_CLASES+"/*.c")) {
clases += ({ explode(clase,".c")[0] });
}
return clases;
}
/* Devuelve una lista de clases compatibles con las que el usuario
* podria multiclasear su ficha
*/
string * clases_compatibles?() {
string * compatibles;
compatibles = clases?();
foreach(object ob in obs_clases) {
compatibles -= ({ ob -> nombre_clase?() });
foreach(string incompatible in ob -> clases_incompatibles?()) {
compatibles -= ({ incompatible });
}
}
return compatibles;
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* fractals_v2.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: jjosephi <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2020/01/20 14:30:44 by jjosephi #+# #+# */
/* Updated: 2020/01/20 15:15:45 by jjosephi ### ########.fr */
/* */
/* ************************************************************************** */
#include "../incl/fractol.h"
#include "../incl/colors.h"
#include <complex.h>
void burningship(double x, double y, t_data *data)
{
int i;
double z_r;
double z_i;
double z_rtmp;
i = 0;
data->c.real = 1.5 * (x - data->w / 2) /
(0.5 * data->zoom * data->w) - data->m_x;
data->c.im = (y - data->w / 2) / (0.5 * data->zoom * data->w) - data->m_y;
z_r = data->c.real;
z_i = data->c.im;
while (i < 100 && (z_r * z_r + z_i * z_i) <= 4)
{
z_rtmp = z_r;
z_r = fabs(z_r * z_r - z_i * z_i + data->c.real);
z_i = fabs(2 * z_rtmp * z_i + data->c.im);
i++;
}
color_pick(i, data->x, data->y, &data);
}
void owo(double x, double y, t_data *data)
{
int i;
double z_r;
double z_i;
double z_rtmp;
i = 0;
z_r = 1.5 * (x - data->w / 2) / (0.5 * data->zoom * data->w) - data->m_x;
z_i = (y - data->w / 2) / (0.5 * data->zoom * data->w) - data->m_y;
while (i < 100 && (z_r * z_r + z_i * z_i) <= 4)
{
z_rtmp = z_r;
z_r = (z_r * z_r - z_i * z_i + data->c.real * 1.5) / 2;
z_i = 2 * z_rtmp * z_i + data->c.im;
i++;
}
color_pick(i, data->x, data->y, &data);
}
void phoenix(double x, double y, t_data *data)
{
int i;
double z_r;
double z_i;
double z_i2;
double z_rtmp;
i = 0;
z_r = 1.5 * (x - data->w / 2) / (0.5 * data->zoom * data->w) - data->m_x;
z_i = (y - data->w / 2) / (0.5 * data->zoom * data->w) - data->m_y;
while (i < 100 && (z_r * z_r + z_i * z_i) <= 4)
{
z_rtmp = z_r;
z_i2 = z_i;
z_r = z_r * z_r - z_i * z_i + data->c.real * z_rtmp;
z_i = 2 * z_rtmp * z_i + data->c.im * z_i2;
i++;
}
color_pick(i, data->x, data->y, &data);
}
void mandelbrot2(double x, double y, t_data *data)
{
int i;
double z_r;
double z_i;
double z_rtmp;
i = 0;
data->c.real = 1.5 * (x - data->w / 2) /
(0.5 * data->zoom * data->w) - data->m_x;
data->c.im = (y - data->w / 2) / (0.5 * data->zoom * data->w) - data->m_y;
z_r = data->c.real;
z_i = data->c.im;
while (i < 100 && (z_r * z_r + z_i * z_i) <= 4)
{
z_rtmp = z_r;
z_r = z_r * z_r - z_i * z_i + z_r + data->c.real;
z_i = 2 * z_rtmp * z_i + z_i + data->c.im;
i++;
}
color_pick(i, data->x, data->y, &data);
}
|
C
|
/**
* Copyright (C) 2019-2020 Tristan
* For conditions of distribution and use, see copyright notice in the COPYING file.
*/
#include "stream.h"
#include <stdio.h>
#include <stdlib.h>
h2stream_list_t *h2stream_list_create(uint32_t max_size) {
h2stream_list_t *list = malloc(sizeof(h2stream_list_t));
if (!list)
return NULL;
list->count = 0;
list->max = max_size;
list->size = STREAM_LIST_STEP_SIZE;
list->streams = malloc(STREAM_LIST_STEP_SIZE * sizeof(h2stream_t *));
if (!list->streams) {
free(list);
return NULL;
}
/* set stream with id 0x0 to "open" */
if (!h2stream_set_state(list, 0x0, H2_STREAM_OPEN)) {
free(list->streams);
free(list);
return NULL;
}
return list;
}
void h2stream_list_destroy(h2stream_list_t *list) {
if (!list)
return;
size_t i;
for (i = 0; i < list->count; i++) {
free(list->streams[i]);
}
free(list->streams);
free(list);
}
h2stream_t *h2stream_get(h2stream_list_t *list, uint32_t id) {
if (!list)
return NULL;
size_t i;
for (i = 0; i < list->count; i++) {
if (list->streams[i] && list->streams[i]->id == id)
return list->streams[i];
}
if (list->count == list->size) {
h2stream_t **streams = realloc(list->streams, (list->size + STREAM_LIST_STEP_SIZE) * sizeof(h2stream_t *));
if (!streams)
return NULL;
list->size += STREAM_LIST_STEP_SIZE;
list->streams = streams;
}
h2stream_t *stream = malloc(sizeof(h2stream_t));
stream->id = id;
/**
* If this the following 'wrong', use h2stream_set_state
* instead, as that function uses this function.
*/
stream->state = H2_STREAM_IDLE;
list->streams[list->count++] = stream;
return stream;
}
h2stream_state_t h2stream_get_state(h2stream_list_t *list, uint32_t id) {
if (!list)
return H2_STREAM_UNKNOWN_STATE;
size_t i;
for (i = 0; i < list->count; i++) {
if (list->streams[i] && list->streams[i]->id == id)
return list->streams[i]->state;
}
return H2_STREAM_IDLE;
}
int h2stream_set_state(h2stream_list_t *list, uint32_t id, h2stream_state_t state) {
h2stream_t *stream = h2stream_get(list, id);
if (!stream)
return 0;
stream->state = state;
return 1;
}
|
C
|
#include <stdio.h>
#include "date.h"
void printDate(const Date *pd)
{
//printf("(%d/%d/%d)\n", (*pd).year, (*pd).month, (*pd).day);
printf("(%d/%d/%d)\n",pd->year, pd->month, pd->day);
}
|
C
|
/**
* NWEN 302 ARP Implementation
* This is where you should implement the functions
*
* Name:Kurtis Fenton
* Student ID:300473865
*/
#include "arp_functions.h"
#include "my_arp.h"
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <net/if.h>
#include <net/if_arp.h>
/*mac address*/
unsigned char my_mac_address[6];
/* IP address*/
uint32_t my_ip_address;
/**
* This function will be called at the start of the program. You can
* use this function to initialize your own data structures, setup timers,
* or do any stuff to initialize your code.
*/
void my_arp_init()
{
printf("init started.\n");
}
/**
* The purpose of this function is to initiate ARP request. This function
* is called whenever a node has a datagram to be sent to @ip_address and
* it has no MAC address of this node.
*
* @param ip_address IPv4 address to be resolved
*/
void my_arp_resolve (uint32_t ip_address)
{
printf("arp resolve function.\n");
char dest_mac_address[] = {0xff, 0xff, 0xff, 0xff, 0xff, 0xff};
printf("Sending broadcast request.\n");
arp_send_query(ip_address, dest_mac_address);
}
/**
* This is a function that you should implement in my_arp.c
* The purpose of this function is to handle ARP request. This function
* is called whenever a node receives an ARP request.
* Hint: This function should create an Ethernet frame containing the ARP reply.
* See the Implementation of arp_send_query() in arp_functions.c to get an idea
* of how to construct a raw Ethernet frame.
*
* @param ip_address IPv4 address to be resolved
* @param src_mac_address Source MAC address. This should be a 48-bit MAC address.
*/
void my_arp_handle_request(uint32_t ip_address, const unsigned char *mac_address)
{
printf("Handle request function.\n");
unsigned char mac_buffer[6];
arp_get_my_macaddr(mac_buffer);
int my_ip_address = arp_get_my_ipaddr();
if(my_ip_address == ip_address){ /* make sure its this hosts ip */
char buffer[1000] = {};
/* eth header */
printf("Constructing eth header.\n");
struct ethhdr *eth = (struct ethhdr *)buffer;
memcpy(eth->h_source, mac_buffer, 6);
memcpy(eth->h_dest, mac_address, 6);
eth->h_proto = htons(ETH_P_ARP);
/* arp header */
printf("Constructing arp header.\n");
struct arphdr *arph = (struct arphdr*)(buffer + sizeof(struct ethhdr));
arph->ar_hrd = htons(ARPHRD_ETHER);
arph->ar_pro = htons(ETH_P_IP);
arph->ar_hln = 6;
arph->ar_pln = 4;
arph->ar_op = htons(ARPOP_REPLY);
/* Fill in rest of the contents */
printf("Filling in arpdata.\n");
struct arpdata *arpd = (struct arpdata*)(buffer + sizeof(struct ethhdr) + sizeof(struct arphdr));
memcpy(arpd->ar_sha, mac_buffer, 6); /*source mac */
memcpy(arpd->ar_tha, mac_address, 6); /* target mac */
arpd->ar_sip = htonl(my_ip_address); /*src ip */
arpd->ar_tip = htonl(ip_address); /* target ip */
printf("Sending ethernet arp frame.\n");
int len = sizeof(struct ethhdr) + sizeof(struct arphdr) + sizeof(struct arpdata);
arp_send_reply(buffer, len);
printf("Sent.\n");
}
}
/**
* The purpose of this function is to handle ARP reply. This function
* is called whenever a node receives an ARP reply.
* Hint: Use this function to trigger the insertion of an appropriate entry
* in the ARP cache.
*
* @param ip_address IPv4 address to be resolved
* @param mac_address MAC address of the interface with @ip_address.
* This should be a 48-bit MAC address.
*/
void my_arp_handle_reply(uint32_t ip_address, const unsigned char *mac_address)
{
/* Insert ip/mac pair into ARP cache */
arp_insert_cache(ip_address, mac_address);
}
/**
* This function is called whenever a frame is transmitted to a node with
* IP address @ip_address and MAC address @mac_address
*
* @param ip_address IPv4 address
* @param mac_address MAC address of the interface with @ip_address.
*/
void my_arp_frame_transmitted(uint32_t ip_address, const unsigned char *mac_address)
{
}
|
C
|
/* Copyright (C) 2019 SCARV project <[email protected]>
*
* Use of this source code is restricted per the MIT license, a copy of which
* can be found at https://opensource.org/licenses/MIT (or should be included
* as LICENSE.txt within the associated archive or repository).
*/
#include "util.h"
int opt_debug = 1;
int opt_trials = 1000;
int opt_data_min = 0;
int opt_data_max = 1024;
int opt_limb_min = 4;
int opt_limb_max = 16;
FILE* prg = NULL;
void opt_parse( int argc, char* argv[] ) {
int opt;
struct option optspec[] = {
{ "help", no_argument, NULL, OPT_HELP },
{ "debug", required_argument, NULL, OPT_DEBUG },
{ "trials", required_argument, NULL, OPT_TRIALS },
{ "data-min", required_argument, NULL, OPT_DATA_MIN },
{ "data-max", required_argument, NULL, OPT_DATA_MAX },
{ "limb-min", required_argument, NULL, OPT_LIMB_MIN },
{ "limb-max", required_argument, NULL, OPT_LIMB_MAX },
{ NULL, 0, NULL, 0 }
};
while( -1 != ( opt = getopt_long( argc, argv, "+", optspec, NULL ) ) ) {
switch( opt ) {
case OPT_HELP : fprintf( stderr, "usage: %s [options] " "\n", argv[ 0 ] );
fprintf( stderr, " " "\n" );
fprintf( stderr, "--help print usage information " "\n" );
fprintf( stderr, " " "\n" );
fprintf( stderr, "--debug <int> verbosity of debug output " "\n" );
fprintf( stderr, "--trials <int> number of (randomised) trials " "\n" );
fprintf( stderr, " " "\n" );
fprintf( stderr, "--data-min <int> minimum bytes of data (where appropriate)" "\n" );
fprintf( stderr, "--data-max <int> maximum bytes of data (where appropriate)" "\n" );
fprintf( stderr, "--limb-min <int> minimum limbs (where appropriate)" "\n" );
fprintf( stderr, "--limb-max <int> maximum limbs (where appropriate)" "\n" );
exit( EXIT_SUCCESS );
break;
case OPT_DEBUG : opt_debug = strtoul( optarg, NULL, 10 );
break;
case OPT_TRIALS : opt_trials = strtoul( optarg, NULL, 10 );
break;
case OPT_DATA_MIN : opt_data_min = strtoul( optarg, NULL, 10 );
break;
case OPT_DATA_MAX : opt_data_max = strtoul( optarg, NULL, 10 );
break;
case OPT_LIMB_MIN : opt_limb_min = strtoul( optarg, NULL, 10 );
break;
case OPT_LIMB_MAX : opt_limb_max = strtoul( optarg, NULL, 10 );
break;
default : exit( EXIT_FAILURE );
break;
}
}
}
void test_dump_seq( uint8_t* x, int l_x, int mode ) {
switch( mode ) {
case DUMP_LSB: for( int i = 0; i <= ( l_x - 1 ); i++ ) {
printf( "%02X", x[ i ] );
}
break;
case DUMP_MSB: for( int i = ( l_x - 1 ); i >= 0; i-- ) {
printf( "%02X", x[ i ] );
}
break;
}
}
int test_rand_seq( uint8_t* x, int l_x_min, int l_x_max, int size ) {
return fread( x, size, ( l_x_min >= l_x_max ) ? ( l_x_min ) : ( ( abs( test_rand_int() ) % ( l_x_max + 1 - l_x_min ) ) + l_x_min ), prg );
}
int test_rand_int() {
int t;
while( !fread( &t, sizeof( int ), 1, prg ) ) {
/* spin */
}
return t;
}
void test_id( char* x, char* y, int i, int n ) {
printf( "id = '%s:%s[%d/%d]'\n", x, y, i, n );
}
void test_init( int argc, char* argv[], char* import ) {
opt_parse( argc, argv );
if( NULL == ( prg = fopen( "/dev/urandom", "rb" ) ) ) {
abort();
}
printf( "import %s\n", import );
}
void test_fini() {
fclose( prg );
}
|
C
|
//27. WAP to find the number of and sum of all integers greater than n1 and less than n2 and divisible by 7, where n1<n2 and n1 & n2 are read from the keyboard.
#include<stdio.h>
void main()
{
int n1,n2,i,sum=0,c=0;
printf("Enter value of n1 and n2:\n");
scanf("%d%d",&n1,&n2);
if(n2>n1)
{
for(i=n1+1;n2>i;i++)
{
if(i%7==0)
{
sum=sum+i;
c=c+1;
}
}
printf("Sum of all integer exactly divisible by 7 is:%d\n",sum);
printf("Number of all integer exactly divisible by 7 is:%d",c);
}
else
{
printf("n1 is less than n2");
}
}
|
C
|
#include <stdio.h>
void swap(int* a, int* b){
int a1 = *a, b1 = *b;
*a = b1;
*b = a1;
}
int main(){
int a, b;
scanf("%i %i", &a, &b);
printf("a = %i, b = %i\n", a, b);
swap(&a, &b);
printf("a = %i, b = %i\n", a, b);
return 0;
}
|
C
|
/* ========================================
*
* Copyright YOUR COMPANY, THE YEAR
* All Rights Reserved
* UNPUBLISHED, LICENSED SOFTWARE.
*
* CONFIDENTIAL AND PROPRIETARY INFORMATION
* WHICH IS THE PROPERTY OF your company.
*
* ========================================
*/
#include "project.h"
#include <stdio.h>
#include "common_functions.h"
void exercise6(void)
{
//Exercise 6
printf("\n\nExercise 6. \n\n");
//declarations
int currentHours = 0;
int currentMinutes = 0;
int sleepHours = 0;
int sleepMinutes = 0;
int wakeUpHours = 0;
int wakeUpMinutes = 0;
int dayDiff = 0;
//enter data
printf("Enter the current time (hh:mm):");
scanf("%d:%d", ¤tHours, ¤tMinutes);
printf("How much time do you wish to sleep? (hh:mm):");
scanf("%d:%d", &sleepHours, &sleepMinutes);
//check if the data is correctly formatted, if not, extrapolate and recalculate
if(sleepMinutes >= 60){
//add extra ours from minute multiples of 60
sleepHours += sleepMinutes / 60;
//keep the remainder minutes as minutes
sleepMinutes = sleepMinutes % 60;
}
//add up minutes with minutes, hours with hours
wakeUpMinutes = currentMinutes + sleepMinutes;
wakeUpHours = currentHours + sleepHours;
//if minutes are 60 or more, add more hours to hours, reduce minutes to below 60
if(wakeUpMinutes >= 60){
wakeUpHours += wakeUpMinutes / 60;
wakeUpMinutes = wakeUpMinutes % 60;
}
//check if hours go into next day (or more days)
if(wakeUpHours >= 24){
dayDiff = wakeUpHours / 24;
wakeUpHours = wakeUpHours % 24;
}
//show the wake up time
printf("If you go to bed now, you must wake up at %02d:%02d", wakeUpHours, wakeUpMinutes);
//show if the time is tomorrow, or n days later
if(dayDiff == 1){
printf(" the next day.\n");
}
else if(dayDiff > 1){
printf(" %d days later.\n", dayDiff);
}
else{
printf(".\n");
}
printf("\nEnd of Exercise 6. \n\n");
return;
}
/* [] END OF FILE */
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.