language
large_stringclasses 1
value | text
stringlengths 9
2.95M
|
---|---|
C | #include<stdio.h>
#include<string.h>
main()
{
char a1[1000],a2[1000];
printf("\n ENTER THE FIRST STRING : \n\n");
gets(a1);
printf("\n ENTER THE SECOND STRING : \n\n");
gets(a2);
if(strcmp(a1,a2)==0)
{
printf("\n THE STRINFGS ARE EQUAL : \n\n%s\n\n%s\n",a1,a2);
}
else
{
printf("\n THE STRINFGS ARE NOT EQUAL : \n\n%s\n\n%s\n",a1,a2);
}
}
|
C | /**
* Return an array of size *returnSize.
* Note: The returned array must be malloced, assume caller calls free().
*/
#include <stdlib.h>
#include <string.h>
const int TRUE = 1;
const int FALSE = 0;
int isDigit(char c) {
if ('0' <= c && c <= '9') {
return TRUE;
}
return FALSE;
}
// 0: letter-log
// 1: digit-log
int classifyLog(char* log) {
int i = 0;
while(log[i] != ' ') {
i++;
}
if (isDigit(log[i + 1])) {
return 1;
} else {
return 0;
}
}
// return 1: a <= b
// return 0: a > b
int compareIdentifier(char* a, char* b) {
int idx = 0;
while(a[idx] != ' ' && b[idx] != ' ') {
if (a[idx] < b[idx]) {
return 1;
}
if (a[idx] > b[idx]) {
return 0;
}
idx++;
}
if (a[idx] == ' ' && b[idx] != ' ') {
return 1;
}
if (a[idx] == ' ') {
return 1;
} else {
return 0;
}
}
// return 1: a < b
// return 0: a == b
// return -1: a > b
int compareStr(char* a, char* b) {
int aLen = strlen(a);
int bLen = strlen(b);
int smallest = aLen < bLen ? aLen : bLen;
for(int i=0;i<smallest;i++) {
if(a[i] < b[i]) {
return 1;
}
if(a[i] > b[i]) {
return -1;
}
}
if(aLen == bLen) {
return 0;
}
if(aLen < bLen) {
return 1;
} else {
return -1;
}
}
// return 1: a < b
// return -1: a > b
int compareLetterLog(char* a, char* b) {
int nonIDIdxA = 0;
int nonIDIdxB = 0;
for(int i=0;i<strlen(a);i++) {
if(a[i] == ' ') {
nonIDIdxA = i + 1;
break;
}
}
for(int i=0;i<strlen(b);i++) {
if(b[i] == ' ') {
nonIDIdxB = i + 1;
break;
}
}
int val = compareStr(a + nonIDIdxA, b + nonIDIdxB);
if(val == 1) {
return 1;
}
if(val == -1) {
return -1;
}
val = compareIdentifier(a, b);
if (val == 1) {
return 1;
} else {
return -1;
}
}
void sortLetterLogs(char** logs, int len) {
for(int i=0;i<len;i++) {
for(int j=i+1;j<len;j++) {
if (compareLetterLog(logs[i], logs[j]) != 1) {
char* tmp = logs[i];
logs[i] = logs[j];
logs[j] = tmp;
}
}
}
}
char** reorderLogFiles(char** logs, int logsSize, int* returnSize) {
char* digitLogs[100];
char* letterLogs[100];
int digitLogsLen = 0;
int letterLogsLen = 0;
for(int i=0;i<logsSize;i++) {
if (classifyLog(logs[i]) == 1) {
digitLogs[digitLogsLen++] = logs[i];
} else {
letterLogs[letterLogsLen++] = logs[i];
}
}
sortLetterLogs(letterLogs, letterLogsLen);
char** ret = (char**)malloc(sizeof(char*) * logsSize);
*returnSize = logsSize;
int retIdx = 0;
for(int i=0;i<letterLogsLen;i++) {
ret[retIdx++] = letterLogs[i];
}
for(int i=0;i<digitLogsLen;i++) {
ret[retIdx++] = digitLogs[i];
}
return ret;
}
|
C | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* draw_map.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: rnureeva <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2019/11/11 16:57:41 by rnureeva #+# #+# */
/* Updated: 2019/11/16 12:41:57 by rnureeva ### ########.fr */
/* */
/* ************************************************************************** */
#include "fdf.h"
void help(t_fdf *map)
{
mlx_string_put(map->mlx_ptr, map->win_ptr, 10, 10, 0x247d58,
"To change brightness use + ");
mlx_string_put(map->mlx_ptr, map->win_ptr, 10, 30, 0x247d58,
"To change zoom use + or -");
mlx_string_put(map->mlx_ptr, map->win_ptr, 10, 50, 0x247d58,
"To move use arrow buttons");
mlx_string_put(map->mlx_ptr, map->win_ptr, 10, 70, 0x247d58,
"To change colors use first letter of color or click the mouse");
mlx_string_put(map->mlx_ptr, map->win_ptr, 10, 90, 0x247d58,
"To change type of projection use 2 or 3");
mlx_string_put(map->mlx_ptr, map->win_ptr, 10, 80, 0x247d58,
"To change altitude use ( or )");
}
void draw(t_fdf *map)
{
if (map->info == 1)
help(map);
map->y = 0;
while (map->y < map->y_coordinate)
{
map->x = 0;
while (map->x < map->x_coordinate)
{
if (map->x < map->x_coordinate - 1)
{
map->x1 = map->x + 1;
map->y1 = map->y;
painter(*map);
}
if (map->y < map->y_coordinate - 1)
{
map->x1 = map->x;
map->y1 = map->y + 1;
painter(*map);
}
map->x++;
}
map->y++;
}
}
|
C | #include <stdio.h>
int main(void)
{
//Function prototypes
void PrintBinaryFormOfNumber(unsigned int);
//Variable declarations
unsigned int a;
unsigned int b;
unsigned int right_shift_A, right_shift_B;
unsigned int left_shift_A, left_shift_B;
unsigned int result;
//code
printf("\n\n");
printf("Enter An Integer = ");
scanf("%u", &a);
printf("\n\n");
printf("Enter Another Integer = ");
scanf("%u", &b);
printf("\n\n");
printf("By How Many Bits Do You Want To Shift A = %d To The Right ? ", a);
scanf("%u", &right_shift_A);
printf("\n\n");
printf("By How Many Bits Do You Want To Shift B = %d To The Right ? ", b);
scanf("%u", &right_shift_B);
printf("\n\n");
printf("By How Many Bits Do You Want To Shift A = %d To The Left ? ", a);
scanf("%u", &left_shift_A);
printf("\n\n");
printf("By How Many Bits Do You Want To Shift B = %d To The Left ? ", b);
scanf("%u", &left_shift_B);
printf("\n\n\n\n");
result = a & b;
printf("Bitwise AND-ing Of \nA = %d (Decimal), %o (Octal), %X (Hexadecimal) and \nB = %d (Decimal), %o (Octal), %X (Hexadecimal) \nGives The Result = %d (Decimal), %o (Octal), %X (Hexadecimal).\n\n", a, a, a, b, b, b, result, result, result);
PrintBinaryFormOfNumber(a);
PrintBinaryFormOfNumber(b);
PrintBinaryFormOfNumber(result);
printf("\n\n\n\n");
result = a | b;
printf("Bitwise OR-ing Of \nA = %d (Decimal), %o (Octal), %X (Hexadecimal) and \nB = %d (Decimal), %o (Octal), %X (Hexadecimal) Gives The \nResult = %d (Decimal), %o (Octal), %X (Hexadecimal).\n\n", a, a, a, b, b, b, result, result, result);
PrintBinaryFormOfNumber(a);
PrintBinaryFormOfNumber(b);
PrintBinaryFormOfNumber(result);
printf("\n\n\n\n");
result = a ^ b;
printf("Bitwise XOR-ing Of \nA = %d (Decimal), %o (Octal), %X (Hexadecimal) and \nB = %d (Decimal), %o (Octal), %X (Hexadecimal) Gives The \nResult = %d (Decimal), %o (Octal), %X (Hexadecimal).\n\n", a, a, a, b, b, b, result, result, result);
PrintBinaryFormOfNumber(a);
PrintBinaryFormOfNumber(b);
PrintBinaryFormOfNumber(result);
printf("\n\n\n\n");
result = ~a;
printf("Bitwise COMPLEMENT Of \nA = %d (Decimal), %o (Octal), %X (Hexadecimal) \nGives The \nResult = %d (Decimal), %o (Octal), %X (Hexadecimal).\n\n", a, a, a, result, result, result);
PrintBinaryFormOfNumber(a);
PrintBinaryFormOfNumber(result);
printf("\n\n\n\n");
result = ~b;
printf("Bitwise COMPLEMENT Of \nB = %d (Decimal), %o (Octal), %X (Hexadecimal) \nGives The \nResult = %d (Decimal), %o (Octal), %X (Hexadecimal).\n\n", b, b, b, result, result, result);
PrintBinaryFormOfNumber(b);
PrintBinaryFormOfNumber(result);
printf("\n\n\n\n");
result = a >> right_shift_A;
printf("Bitwise RIGHT-SHIFT By %d Bits Of \nA = %d (Decimal), %o (Octal), %X (Hexadecimal) \nGives The \nResult = %d (Decimal), %o (Octal), %X (Hexadecimal).\n\n", right_shift_A, a, a, a, result, result, result);
PrintBinaryFormOfNumber(a);
PrintBinaryFormOfNumber(result);
printf("\n\n\n\n");
result = b >> right_shift_B;
printf("Bitwise RIGHT-SHIFT By %d Bits Of \nB = %d (Decimal), %o (Octal), %X (Hexadecimal) \nGives The \nResult = %d (Decimal), %o (Octal), %X (Hexadecimal).\n\n", right_shift_B, b, b, b, result, result, result);
PrintBinaryFormOfNumber(b);
PrintBinaryFormOfNumber(result);
printf("\n\n\n\n");
result = a << left_shift_A;
printf("Bitwise LEFT-SHIFT By %d Bits Of \nA = %d (Decimal), %o (Octal), %X (Hexadecimal) \nGives The \nResult = %d (Decimal), %o (Octal), %X (Hexadecimal).\n\n", left_shift_A, a, a, a, result, result, result);
PrintBinaryFormOfNumber(a);
PrintBinaryFormOfNumber(result);
printf("\n\n\n\n");
result = b << left_shift_B;
printf("Bitwise LEFT-SHIFT By %d Bits Of \nB = %d (Decimal), %o (Octal), %X (Hexadecimal) \nGives The \nResult = %d (Decimal), %o (Octal), %X (Hexadecimal).\n\n", left_shift_B, b, b, b, result, result, result);
PrintBinaryFormOfNumber(b);
PrintBinaryFormOfNumber(result);
return(0);
}
// ****** BEGINNERS TO C PROGRAMMING LANGUAGE : PLEASE IGNORE THE CODE OF THE FOLLOWING FUNCTION SNIPPET 'PrintBinaryFormOfNumber()' ******
// ****** YOU MAY COME BACK TO THIS CODE AND WILL UNDERSTAND IT MUCH BETTER AFTER YOU HAVE COVERED : ARRAYS, LOOPS AND FUNCTIONS ******
// ****** THE ONLY OBJECTIVE OF WRITING THIS FUNCTION WAS TO OBTAIN THE BINARY REPRESENTATION OF DECIMAL INTEGERS SO THAT BIT-WISE AND-ing, OR-ing, COMPLEMENT AND BIT-SHIFTING COULD BE UNDERSTOOD WITH GREAT EASE ******
void PrintBinaryFormOfNumber(unsigned int decimal_number)
{
//variable declarations
unsigned int quotient, remainder;
unsigned int num;
unsigned int binary_array[8];
int i;
//code
for (i = 0; i < 8; i++)
binary_array[i] = 0;
printf("The Binary Form Of The Decimal Integer %d Is\t=\t", decimal_number);
num = decimal_number;
i = 7;
while (num != 0)
{
quotient = num / 2;
remainder = num % 2;
binary_array[i] = remainder;
num = quotient;
i--;
}
for (i = 0; i < 8; i++)
printf("%u", binary_array[i]);
printf("\n\n");
}
|
C | #include <stdio.h>
int main()
{
long nc;
while(getchar() != '\n') {
++nc;
}
printf("%ld\n", nc);
} |
C | #include "stm32f10x.h"
#include "LED.H"
/*******************************************************************************
* : LED_Init
* : LEDʼ
* :
* :
*******************************************************************************/
void LED_Init()
{
GPIO_InitTypeDef GPIO_InitStructure;//ṹ
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOC, ENABLE);
GPIO_InitStructure.GPIO_Pin= LED_PIN; //ѡҪõIO
GPIO_InitStructure.GPIO_Mode=GPIO_Mode_Out_PP; //ģʽ
GPIO_InitStructure.GPIO_Speed=GPIO_Speed_50MHz; //ô
GPIO_Init(GPIOC, &GPIO_InitStructure); /* ʼGPIO */
GPIO_SetBits(GPIOC, LED_PIN); //LED˿ߣϨLED
return;
}
void led_toggle_0(void)
{
GPIO_WriteBit(GPIOC, GPIO_Pin_0, (BitAction)(1 - GPIO_ReadInputDataBit(GPIOC, GPIO_Pin_0)));
return;
}
void led_toggle_1(void)
{
GPIO_WriteBit(GPIOC, GPIO_Pin_1, (BitAction)(1 - GPIO_ReadInputDataBit(GPIOC, GPIO_Pin_1)));
return;
}
|
C | #include "loop.h"
#include <string.h>
#include "loop_heap.h"
loop_container_t* init_loop(){
loop_container_t* temp = NULL;
if((temp = (loop_container_t*)malloc(sizeof(loop_container_t))) == NULL){
return NULL;
}
else{ //if memory allocation for loops` container did not fail
if((temp->arr = (loop_t*) malloc(sizeof(loop_t))) == NULL){
return NULL;
}
else{ //and if memory allocation for an array of loops did not fail
temp->quantity = 0;
temp->max_size = 1;
return temp;
}
}
}
int loop_full(const loop_container_t* container){ //check if loop container is full
return container->quantity == container->max_size;
}
int loop_empty(const loop_container_t* container){ //check if loop container is empty
return container->quantity == 0;
}
void add_loop_element(loop_container_t* container, const loop_t* el){
loop_t* temp = NULL;
if(loop_full(container)){ //if container is full, realloc memory
if((temp = (loop_t*)realloc(container->arr, ++container->max_size * sizeof(loop_t))) == NULL){
exit_w_code(LOOP_PROCESSING_ERR); //if memory reallocation failed
}
else{
container->arr = temp;
}
}
temp = &(container->arr[container->quantity++]); //and copy data
strcpy(temp->loop_et, el->loop_et);
copy_list(&temp->task_list, el->task_list);
}
loop_t* search_loop(const loop_container_t* loop, const char* et, unsigned left, unsigned right){ //assuming structure is sorted by DESC
if(left <= right){ //search loop by it`s label (binary search)
unsigned mid = (left + right)/2;
int result = strcmp(et, loop->arr[mid].loop_et);
return(
result == 0? &loop->arr[mid] : (
result > 0? search_loop(loop, et, left, mid - 1) : search_loop(loop, et, mid + 1, right)
)
);
}
return NULL;
} |
C | #include "holberton.h"
/**
* print_square - Print a square of lengh n
* @n : number of lines
* Return: Always 0.
*/
void print_square(int n)
{
int c;
int d = n;
if (n < 1)
{
_putchar('\n');
}
while (d > 0)
{
c = 1;
while (c <= n)
{
_putchar(35);
c++;
}
d--;
_putchar('\n');
}
}
|
C | #include<stdio.h>
void main()
{
int a[10],i,great;
printf("Enter a values:");
for (i=0;i<10;i++)
{
scanf("%d", &a[i]);
}
great=a[0];
for(i=0;i<10;i++)
{
if(a[i]>great)
{
great=a[i];
}
}
printf("greatest number %d",great);
return 0;
}
|
C | void strcpy(char*, char*);
//string copy function
bool strcomp(char*, char*);
//string compares returns true or false
void strcat(char*, char*);
//appends second string onto end of first
int strlen(char*);
//returns the length of the string
|
C | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "reversi.h"
#define _DEBUG
Point p_add(Point a, Point b)
{
Point res;
res = a;
res.x += b.x;
res.y += b.y;
return res;
}
Point p_sub(Point a, Point b)
{
Point res;
res = a;
res.x -= b.x;
res.y -= b.y;
return res;
}
Point p_set(int x, int y)
{
Point res;
res.x = x;
res.y = y;
return res;
}
int p_cmp(const Point* a, const Point* b) {
if (memcmp(a, b, sizeof(Point)) == 0) return 1;
return 0;
}
void r_init(Reversi* r)
{
memset(r->board_, 0, sizeof(r->board_[0][0]) * 64);
memset(r->canSet_, 0, sizeof(r->canSet_));
r->current_ = Black;
r->countTurn = 1;
r->board_[3][3] = White;
r->board_[4][3] = Black;
r->board_[3][4] = Black;
r->board_[4][4] = White;
r->countBlack = 2;
r->countWhite = 2;
r_scan(r);
}
void r_dump(const Reversi* r)
{
int x, y, i;
char overlay[8][8] = {0};
for (i = 0; i < r->countCanSet; i++) {
overlay[r->canSet_[i].x][r->canSet_[i].y] = 1;
}
printf("===== Turn %2d =====\n", r->countTurn);
printf(" %c ", r->current_ == Black ? 'B' : 'W');
for (i = 0; i < 8; i++) {
printf("%d ", i);
}
printf("\n");
for (y = 0; y < 8; y++) {
printf(" %d ", y);
for (x = 0; x < 8; x++) {
switch (r->board_[x][y]) {
case None:
if (overlay[x][y] == 1) {
printf("* ");
} else {
printf(". ");
}
break;
case Black:
printf("B ");
break;
case White:
printf("W ");
break;
}
}
printf("\n");
}
printf("=== B %2d / W %2d ===\n", r->countBlack, r->countWhite);
printf("\n");
}
int r_scan(Reversi* r)
{
const Point dir[8] = {{0, 1}, {1, 1}, {1, 0}, {1, -1}, {0, -1}, { -1, -1}, { -1, 0}, { -1, 1}};
int count = 0, x, y, i, flag, bench = 0;
Point cur;
r->countBlack = (r->countWhite = 0);
for (y = 0; y < 8; y++) {
for (x = 0; x < 8; x++) {
bench++;
if (r->board_[x][y] == Black) {
r->countBlack++;
continue;
} else if (r->board_[x][y] == White) {
r->countWhite++;
continue;
}
for (i = 0; i < 8; i++) {
cur = p_set(x, y);
flag = 0;
for (;;) {
bench++;
cur = p_add(cur, dir[i]);
if (cur.x < 0 || cur.y < 0 || cur.x >= 8 || cur.y >= 8) {
break; // Out of bounds.
}
if (r->board_[cur.x][cur.y] == None) {
break; // Free
}
if (!flag && r->board_[cur.x][cur.y] == r->current_) {
break; // LoL
}
if (flag && r->board_[cur.x][cur.y] == r->current_) {
r->canSet_[count] = p_set(x, y);
count++;
flag = -1;
break;
}
if (r->board_[cur.x][cur.y] == (r->current_ == Black ? White : Black)) {
flag++;
}
}
if (flag == -1) {
break;
}
}
}
}
r->countCanSet = count;
#ifdef _BENCHMARK
printf("\t\t\t\t\t\t\tr_scan() count = %d / bench = %d\n", count, bench);
#endif
return count;
}
void r_flip(Reversi* r, int x, int y)
{
const Point dir[8] = {{0, 1}, {1, 1}, {1, 0}, {1, -1}, {0, -1}, { -1, -1}, { -1, 0}, { -1, 1}};
int i, flag, bench = 0;
Point cur;
for (i = 0; i < 8; i++) {
cur = p_set(x, y);
flag = 0;
for (;;) {
bench++;
cur = p_add(cur, dir[i]);
if (cur.x < 0 || cur.y < 0 || cur.x >= 8 || cur.y >= 8) {
break; // Out of bounds.
}
if (r->board_[cur.x][cur.y] == None) {
break; // Free
}
if (!flag && r->board_[cur.x][cur.y] == r->current_) {
break; // LoL
}
if (flag && r->board_[cur.x][cur.y] == r->current_) {
cur = p_sub(cur, dir[i]);
do {
r->board_[cur.x][cur.y] = r->current_;
cur = p_sub(cur, dir[i]);
bench++;
} while (r->board_[cur.x][cur.y] != r->current_);
break;
}
if (r->board_[cur.x][cur.y] == (r->current_ == Black ? White : Black)) {
flag++;
}
}
}
#ifdef _BENCHMARK
printf("\t\t\t\t\t\t\tr_flip() bench = %d\n", bench);
#endif
}
int r_set(Reversi* r, Disk d, int x, int y)
{
int i = 0;
if (r->current_ != d) {
#ifdef _DEBUG
printf("r_set : It's not your turn.\n");
exit(EXIT_FAILURE);
#endif
return -1;
}
if (r->board_[x][y] != None) {
#ifdef _DEBUG
printf("r_set : It seems like that (%d,%d) is already using.\n", x, y);
exit(EXIT_FAILURE);
#endif
return -1;
}
for (i = 0; i < r->countCanSet; i++) {
if (r->canSet_[i].x == x && r->canSet_[i].y == y) {
r->board_[x][y] = r->current_;
r_flip(r, x, y);
r->current_ = (r->current_ == Black ? White : Black);
if (r_scan(r) == 0) { // Skip?
r->current_ = (r->current_ == Black ? White : Black);
if (r_scan(r) == 0) { // Game Over
r->current_ = None;
return 1;
}
}
r->countTurn++;
return 1;
}
}
#ifdef _DEBUG
printf("r_set : (%d,%d) can't be set.\n", x, y);
exit(EXIT_FAILURE);
#endif
return -1;
} |
C | #include<stdio.h>
#include<stdlib.h>
struct node
{
int data;
struct node* left;
struct node* right;
};
struct node* newnode(int data)
{
struct node* nn=(struct node*)malloc(sizeof(struct node));
nn->data=data;
nn->left=NULL;
nn->right=NULL;
return nn;
}
struct stack
{
struct stack* next;
struct node* tt;
};
void push(struct stack** nn,struct node* curr)
{
struct stack* ss=(struct stack*)malloc(sizeof(struct stack));
ss->tt=curr;
ss->next=(*nn);
(*nn)=ss;
}
struct node* pop(struct stack** ss)
{
struct stack* t;
t=*ss;
struct node* nn;
nn=t->tt;
(*ss)=t->next;
free(t);
return nn;
}
struct node* peek(struct stack* ss)
{
return ss->tt;
}
int empty(struct stack* s1)
{
if(s1==NULL)
{
return 1;
}
else
{
return 0;
}
}
void inorder(struct node* root)
{
struct node* curr=root;
struct stack* stk=NULL;
int t=1;
while(1)
{
if(curr!=NULL)
{
push(&stk,curr);
curr=curr->left;
}
else
{
if(empty(stk))
break;
struct node* temp=pop(&stk);
printf("%d ",temp->data);
if(temp->right)
{
curr=temp->right;
}
}
}
}
void preorder(struct node* root)
{
struct node* curr=root;
struct stack* stk=NULL;
while(1)
{
if(curr!=NULL)
{
printf("%d ",curr->data);
push(&stk,curr);
curr=curr->left;
}
else
{
if(empty(stk))
break;
struct node* temp=pop(&stk);
if(temp->right)
{
curr=temp->right;
}
}
}
}
void postorder(struct node* root)
{
struct node* curr=root;
struct stack* stk1=NULL;
while(!empty(stk1)||curr)
{
if(curr!=NULL)
{
push(&stk1,curr);
curr=curr->left;
}
else
{
struct node* temp=peek(stk1)->right;
if(temp == NULL)
{
temp=pop(&stk1);
printf("%d ",temp->data);
while(!empty(stk1) && temp==peek(stk1)->right)
{
temp=pop(&stk1);
printf("%d ",temp->data);
}
}
else
{
curr=temp;
}
}
}
}
int height(struct node* root)
{
if(root == NULL)
return;
else
{
int lheight=height(root->left);
int rheight=height(root->right);
if(lheight>rheight)
{
return lheight+1;
}
else
{
return rheight+1;
}
}
}
int max(int a,int b)
{
return a>b?a:b;
}
int diameter(struct node* root)
{
if(root == NULL)
return;
else
{
int l=height(root->left);
int r=height(root->right);
int c=l+r+1;
int x=diameter(root->left);
int y=diameter(root->right);
return max(c,max(x,y));
}
}
struct node* constructTree(int in[],int pre[],int low,int high)
{
static int t=0;
if(high<low)
{
return NULL;
}
else
{
struct node* nn=newnode(pre[(t)]);
int i;
for(i=low;i<high;i++)
{
if(pre[(t)]==in[i])
{
break;
}
}
(t)++;
nn->left=constructTree(in,pre,low,i-1);
nn->right=constructTree(in,pre,i+1,high);
return nn;
}
}
struct node* constructTree1(int in[],int post[],int low,int high)
{
static int t=6;
if(high<low)
{
return NULL;
}
else
{
struct node* nn=newnode(post[(t)]);
int i;
for(i=low;i<high;i++)
{
if(post[(t)]==in[i])
{
break;
}
}
(t)--;
nn->right=constructTree(in,post,i+1,high);
nn->left=constructTree(in,post,low,i-1);
return nn;
}
}
void MorrisInorder(struct node* root)
{
struct node* curr=root;
struct node* temp;
while(curr!=NULL)
{
if(!curr->left)
{
printf("%d ",curr->data);
curr=curr->right;
}
else
{
temp=curr->left;
while(temp->right!=NULL&&temp->right!=curr)
{
temp=temp->right;
}
if(temp == NULL)
{
// printf("%d ",curr->data);
temp->right=curr;
curr=curr->left;
}
else
{
temp->right=NULL;
printf("%d ",curr->data);
curr=curr->right;
}
}
}
}
void MorrisPreorder(struct node* root)
{
struct node* curr=root;
struct node* temp;
while(curr!=NULL)
{
if(!curr->left)
{
printf("%d ",curr->data);
curr=curr->right;
}
else
{
temp=curr->left;
while(temp->right!=NULL&&temp->right!=curr)
{
temp=temp->right;
}
if(temp == NULL)
{
printf("%d ",curr->data);
temp->right=curr;
curr=curr->left;
}
else
{
temp->right=NULL;
// printf("%d ",curr->data);
curr=curr->right;
}
}
}
}
int main()
{
int in[]={4,2,5,1,6,3,7};
int pre[]={1,2,4,5,3,6,7};
int post[]={4,5,2,6,7,3,1};
struct node* root=newnode(1);
root->left=newnode(2);
root->right=newnode(3);
root->left->left=newnode(4);
root->left->right=newnode(5);
root->right->left=newnode(6);
root->right->right=newnode(7);
inorder(root);
printf("\n");
preorder(root);
printf("\n");
postorder(root);
printf("\n");
int x=height(root);
printf("%d ",x);
printf("\n");
int y=diameter(root);
printf("%d ",y);
printf("\n");
int t=0;
struct node* nn1=constructTree(in,pre,0,7);
inorder(nn1);
printf("\n");
struct node* nn2=constructTree1(in,post,0,7);
inorder(nn1);
printf("\n");
MorrisInorder(root);
printf("\n");
MorrisPreorder(root);
}
|
C | #include<stdlib.h>
#include<stdio.h>
#define MAX 10000000
/*
void quick_sort(long int s[], int l, int r)
{
if (l < r)
{
//Swap(s[l], s[(l + r) / 2]); //м͵һ μע1
int i = l, j = r, x = s[l];
while (i < j)
{
while(i < j && s[j] >= x) // ҵһСx
j--;
if(i < j)
s[i++] = s[j];
while(i < j && s[i] < x) // ҵһڵx
i++;
if(i < j)
s[j--] = s[i];
}
s[i] = x;
quick_sort(s, l, i - 1); // ݹ
quick_sort(s, i + 1, r);
}
}
*/
int main()
{ int f[1000],n,m,v[1000],w[1000],p[1000];
int i,j,k;
scanf("%d%d",&m,&n);//mʾnʾ
for(i=0;i<n;++i)
{
scanf("%d%d",&w[i],&p[i]);//w=, p=Ҫ
v[i]=w[i]*p[i];
// scanf("%d%d",&v,&w);//v=ֵw=
}
//quick_sort(p,0,n)
for(i=0;i<n;++i)
{
for(j=m;j>=w[i];--j)
//for(j=w;j<=m;++j)
if(f[j]<f[j-w[i]]+v[i])
f[j]=f[j-w[i]]+v[i];
}
printf("%d\n",f[m]);
//return 0;
system("pause");
}
//C++CӦöɡ ˳һ䣬ҪŵĻ
//for(int j=m;j>=w;--j)һfor(int j=w;j<=m;++j)ˡ
/*
#include<stdlib.h>
#define MAX 1111
int f[MAX],n,m,v,w;
int main(){
int i,j;
scanf("%d%d",&n,&m);//nʾmʾ
for(i=1;i<=n;++i){
scanf("%d%d",&v,&w);//v=ֵw=
for(j=m;j>=w;--j)
if(f[j]<f[j-w]+v)
f[j]=f[j-w]+v;
}
printf("%d\n",f[m]);
return 0;
}
*/
|
C | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#define PORT 8080
int main(){
char client_message[2000];
char buffer[1024];
int serverSocket,newSocket;
struct sockaddr_in serverAddr;
struct sockaddr_storage serverStorage;
socklen_t addr_size;
//creating socket
serverSocket=socket(AF_INET,SOCK_STREAM,0);
//configure settings of server sockaddr struct
serverAddr.sin_family=AF_INET;
serverAddr.sin_port=htons(PORT);
if(inet_pton(AF_INET, "127.0.0.1", &serverAddr.sin_addr)<=0)
{
printf("\nInvalid address/ Address not supported \n");
return -1;
}
//setting all bits of padding field to 0
memset(serverAddr.sin_zero,'\0',sizeof(serverAddr.sin_zero));
//Binding
bind(serverSocket,(struct sockaddr *)&serverAddr,sizeof(serverAddr));
//Listen
if(listen(serverSocket,3)==0)
{
printf("Listening......\n");
}
else
{
printf("Error.......\n");
}
//Accept
addr_size=sizeof(serverStorage);
while(1)
{
newSocket = accept(serverSocket, (struct sockaddr*)&serverStorage, &addr_size);
fork();
close(serverSocket);
while(1)
{
recv(newSocket, buffer, 1024, 0);
printf("Client Message: %s\n", buffer);
printf("Enter the message:\n");
fgets(client_message,1000,stdin);
send(newSocket,client_message, 1000, 0);
}
}
close(newSocket);
return 0;
}
|
C | #include<stdio.h>
#include<stdlib.h>
int main(){
int number;
scanf("%d",&number);
int test=number;
int sum=0,inter;
while (test>0)
{
inter=test%10;
test=test/10;
sum=sum+(inter*inter*inter);
}
if (sum==number)
{
printf("Its Armstrong!");
}else
{
printf("Its not");
}
} |
C | #include <string.h>
char * __cdecl strrev(char * string)
{
char *start = string;
char *left = string;
char ch;
while (*string++) /* find end of string */
;
string -= 2;
while (left < string)
{
ch = *left;
*left++ = *string;
*string-- = ch;
}
return(start);
}
|
C | /**
* @file mod_pulsgen.h
*
* @brief pulses generator module header
*
* This module implements an API
* to make real-time pulses generation using GPIO
*/
#ifndef _MOD_PULSGEN_H
#define _MOD_PULSGEN_H
#include <stdint.h>
#include "mod_msg.h"
#include "mod_timer.h"
#define PULSGEN_CH_CNT 32 ///< maximum number of pulse generator channels
#define PULSGEN_FIFO_SIZE 4 ///< size of channel's fifo buffer
/// a channel parameters
struct pulsgen_ch_t
{
uint32_t port; // GPIO port number
uint32_t pin_mask; // GPIO pin mask
uint32_t pin_mask_not; // GPIO pin ~mask
uint32_t pin_inverted; // same as `pin_mask` or 0
uint8_t task; // 0 = "channel disabled"
uint8_t task_infinite; // 0 = "make task_toggles and disable the channel"
uint32_t task_toggles; // pin toggles for this task
uint32_t task_toggles_todo; // pin toggles left to do for this task
uint32_t tasks_done; // total number of tasks done
uint8_t toggles_dir; // 0 = cnt++, !0 = cnt--
int32_t cnt; // total number of pin toggles
uint32_t setup_ticks; // number of CPU ticks to prepare pin toggle
uint32_t hold_ticks; // number of CPU ticks to hold pin state
uint8_t abort_on_setup;
uint8_t abort_on_hold;
uint64_t todo_tick; // timestamp (in CPU ticks) to change pin state
};
struct pulsgen_fifo_item_t
{
uint8_t used;
uint8_t toggles_dir;
uint32_t toggles;
uint32_t pin_setup_time;
uint32_t pin_hold_time;
uint32_t start_delay;
};
/// messages types
enum
{
PULSGEN_MSG_PIN_SETUP = 0x20,
PULSGEN_MSG_TASK_ADD,
PULSGEN_MSG_ABORT,
PULSGEN_MSG_STATE_GET,
PULSGEN_MSG_TASK_TOGGLES_GET,
PULSGEN_MSG_CNT_GET,
PULSGEN_MSG_CNT_SET,
PULSGEN_MSG_TASKS_DONE_GET,
PULSGEN_MSG_TASKS_DONE_SET,
PULSGEN_MSG_WATCHDOG_SETUP,
PULSGEN_MSG_CNT
};
/// the message data sizes
#define PULSGEN_MSG_BUF_LEN MSG_LEN
// export public methods
void pulsgen_module_init();
void pulsgen_module_base_thread();
void pulsgen_pin_setup(uint8_t c, uint8_t port, uint8_t pin, uint8_t inverted);
void pulsgen_task_add(uint32_t c, uint32_t toggles_dir, uint32_t toggles, uint32_t pin_setup_time, uint32_t pin_hold_time, uint32_t start_delay);
void pulsgen_abort(uint8_t c, uint8_t on_hold);
uint8_t pulsgen_state_get(uint8_t c);
uint32_t pulsgen_task_toggles_get(uint8_t c);
int32_t pulsgen_cnt_get(uint8_t c);
void pulsgen_cnt_set(uint8_t c, int32_t value);
uint32_t pulsgen_tasks_done_get(uint8_t c);
void pulsgen_tasks_done_set(uint8_t c, uint32_t tasks);
int8_t volatile pulsgen_msg_recv(uint8_t type, uint8_t * msg, uint8_t length);
void pulsgen_watchdog_setup(uint8_t enable, uint32_t time);
#endif
|
C | #include "localized_pokemon.h"
#include <commons/string.h>
t_localized_pokemon* localized_pokemon_create(char* nombre, t_list* posiciones){
t_localized_pokemon* localized_pokemon = malloc( sizeof(t_localized_pokemon) );
localized_pokemon->nombre = string_from_format("%s",nombre);
localized_pokemon->tamanio_nombre = strlen(nombre);
localized_pokemon->posiciones = posiciones;
localized_pokemon->cantidadPos = (uint32_t)list_size(posiciones);
return localized_pokemon;
}
op_code localized_pokemon_codigo(t_localized_pokemon* localized_pokemon){
return LOCALIZED_POKEMON;
}
t_buffer* localized_pokemon_to_buffer(t_localized_pokemon* localized_pokemon){
t_buffer* buffer = malloc( sizeof(t_buffer) );
//tam_nombre y cant posiciones, nombre, posiciones
buffer->size = sizeof(uint32_t) * 2
+ localized_pokemon->tamanio_nombre
+ (sizeof(uint32_t) * 2) * localized_pokemon->cantidadPos;
buffer->stream = localized_pokemon_to_stream(localized_pokemon);
return buffer;
}
t_localized_pokemon* localized_pokemon_from_buffer(t_buffer* buffer){
return localized_pokemon_from_stream(buffer->stream);
}
void localized_pokemon_mostrar(t_localized_pokemon* localized_pokemon){
printf("Mensaje - Localized Pokemon:\n");
printf("Nombre: %s\n",localized_pokemon->nombre);
printf("Tamanio de nombre: %d\n",localized_pokemon->tamanio_nombre);
printf("Cantidad de posiciones: %d\n",localized_pokemon->cantidadPos);
printf("Posiciones: \n");
for(int i=0; i<localized_pokemon->cantidadPos; i++){
uint32_t x = posiciones_get_X(localized_pokemon->posiciones,i);
uint32_t y = posiciones_get_Y(localized_pokemon->posiciones,i);
printf("Posicion numero %d: x = %d , y = %d \n",i+1,x,y);
}
puts("------------");
}
char* localized_pokemon_to_string(t_localized_pokemon* localized_pokemon){
char* mensaje = string_from_format("Tipo = LOCALIZED_POKEMON | Contenido = Pokemon: %s | Cantidad de posiciones: %d | Posiciones (x,y): ",localized_pokemon->nombre,localized_pokemon->cantidadPos);
for(int i=0; i<localized_pokemon->cantidadPos; i++){
uint32_t x = posiciones_get_X(localized_pokemon->posiciones,i);
uint32_t y = posiciones_get_Y(localized_pokemon->posiciones,i);
char* posicion = string_from_format("(%d,%d) ",x,y);
string_append(&mensaje,posicion);
free(posicion);
}
return mensaje;
}
void localized_pokemon_destroy(t_localized_pokemon* localized_pokemon){
free(localized_pokemon->nombre);
posiciones_destroy(localized_pokemon->posiciones);
free(localized_pokemon);
}
int localized_pokemon_size(t_localized_pokemon* localized){
return sizeof(localized->tamanio_nombre) + localized->tamanio_nombre + sizeof(localized->cantidadPos) + (sizeof(uint32_t)*2)*localized->cantidadPos;
}
t_list* localized_pokemon_get_list(t_localized_pokemon* localized_pokemon){
t_list* pokemons = list_create();
for(int i = 0 ; i < localized_pokemon->cantidadPos ; i++){
t_pokemon* pokemon = pokemon_create(localized_pokemon->nombre,*((t_posicion*)list_get(localized_pokemon->posiciones, i)));
list_add(pokemons, pokemon);
}
return pokemons;
}
void* localized_pokemon_to_stream(t_localized_pokemon* localized_pokemon){
//tam_nombre y cant posiciones, nombre, posiciones
int size = sizeof(uint32_t) * 2
+ localized_pokemon->tamanio_nombre
+ (sizeof(uint32_t) * 2) * localized_pokemon->cantidadPos;
void* stream = malloc(size);
int offset = 0;
memcpy(stream + offset, &(localized_pokemon->tamanio_nombre), sizeof(uint32_t));
offset += sizeof(uint32_t);
memcpy(stream + offset, localized_pokemon->nombre, localized_pokemon->tamanio_nombre);
offset += localized_pokemon->tamanio_nombre;
memcpy(stream + offset, &(localized_pokemon->cantidadPos), sizeof(uint32_t));
offset += sizeof(uint32_t);
//Por cada posicion segun la cantidad, hago memcpy de x e y.
for(int i = 0 ; i < localized_pokemon->cantidadPos ; i++){
uint32_t x = posiciones_get_X(localized_pokemon->posiciones,i);
memcpy(stream + offset, &(x), sizeof(uint32_t));
offset += sizeof(uint32_t);
uint32_t y = posiciones_get_Y(localized_pokemon->posiciones,i);
memcpy(stream + offset, &(y), sizeof(uint32_t));
offset += sizeof(uint32_t);
}
return stream;
}
t_localized_pokemon* localized_pokemon_from_stream(void* stream){
t_localized_pokemon* localized_pokemon = malloc( sizeof(t_localized_pokemon) );
memcpy(&(localized_pokemon->tamanio_nombre), stream, sizeof(uint32_t));
stream += sizeof(uint32_t);
localized_pokemon->nombre = malloc(localized_pokemon->tamanio_nombre + 1);
memcpy(localized_pokemon->nombre, stream, localized_pokemon->tamanio_nombre);
localized_pokemon->nombre[localized_pokemon->tamanio_nombre] = '\0';
stream += localized_pokemon->tamanio_nombre;
memcpy(&(localized_pokemon->cantidadPos), stream, sizeof(uint32_t));
stream += sizeof(uint32_t);
localized_pokemon->posiciones = posiciones_create();
for(int i = 0 ; i < localized_pokemon->cantidadPos ; i++){
t_posicion* posicion = malloc(sizeof(t_posicion));
memcpy(&(posicion->posicionX), stream, sizeof(uint32_t));
stream += sizeof(uint32_t);
memcpy(&(posicion->posicionY), stream, sizeof(uint32_t));
stream += sizeof(uint32_t);
list_add(localized_pokemon->posiciones,posicion);
}
return localized_pokemon;
}
|
C | /* 5-8.c
#include <stdio.h>
#define OUTPUT1(a, b) a + b // ũ Լ
#define OUTPUT2(a, b) #a "+" #b // ũ Լ
int main(void)
{
printf(" %d \n", OUTPUT1(11, 22)); // 10
printf(" %s \n", OUTPUT2(11, 22)); // ڿ ġ
return 0;
}
*/ |
C | #include<stdio.h>
char atoupper(char c)
{
char d='c'-32;
return d;
}
main()
{
char c='s';
char d=atoupper(c);
printf("%c \n",d);
}
|
C | #include <stdio.h>
#define OK 0
#define ERROR 1
#define MAX_LEN 10
#define MIN_LEN 1
#define TRUE 1
#define FALSE 0
int sum_even(const int *arr, const int n);
int scanf_arr(int *arr, int n);
int check(const int *arr, const int n);
int main(void)
{
int n;
int rc = scanf("%d", &n);
if (rc != 1 || n < MIN_LEN || n > MAX_LEN)
{
printf("Некорректные данные\n");
return ERROR;
}
int arr[n];
rc = scanf_arr(arr, n);
if (rc != n)
{
printf("Некорректные данные\n");
return ERROR;
}
if (check(arr, n))
{
printf("Нет чётных элементов");
return ERROR;
}
printf("\n Сумма чётных элементов массива: %d", sum_even(arr, n));
return OK;
}
int sum_even(const int *arr, const int n)
{
int summ = 0;
for (int i = 0; i < n; i++)
summ += arr[i] % 2 == 0 ? arr[i] : 0;
return summ;
}
int check(const int *arr, const int n)
{
int flag = FALSE;
for (int i = 0; i < n; i++)
{
if (arr[i] % 2 == 0)
{
flag = TRUE;
break;
}
}
if (!flag)
return ERROR;
return OK;
}
int scanf_arr(int *arr, int n)
{
int rc = 0;
printf("Введите элементы массива: \n");
for (int i = 0; i < n; i++)
rc += scanf("%d", &arr[i]);
return rc;
}
|
C | #include <stdio.h>
int main()
{
int n;
printf("Enter sum \n");
scanf("%d",&n);
printf("No of 100 notes: %d \n",(n/100));
n%=100;
printf("No of 50 notes: %d \n",(n/50));
n%=50;
printf("No of 10 notes: %d \n" ,(n/10));
n%=10;
}
|
C | #include "TLC2543.h"
/*
Ȩ:https://github.com/MisakaMikoto128/TLC2543_STM32
ߣԸ
*/
void TLC2543_Init()
{
GPIO_InitTypeDef GPIO_InitStructure;
RCC_APB2PeriphClockCmd( RCC_APB2Periph_GPIOB, ENABLE );//PORTBʱʹ
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_12; // PB12
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP; //
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(GPIOB, &GPIO_InitStructure);
GPIO_SetBits(GPIOB,GPIO_Pin_12);
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_11;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING; //
GPIO_Init(GPIOB, &GPIO_InitStructure);
SPI2_Init(); //ʼSPI
SPI2_SetSpeed(SPI_BaudRatePrescaler_256);//Ϊ18Mʱ,ģʽ
}
unsigned int TLC2543_ReadWirte(unsigned int ctrlcode)
{
unsigned int rev = 0;
ctrlcode |= OUT16BIT;
ctrlcode <<=8;//ڸֽ
CS=0; //ʹ
while(SPI_I2S_GetFlagStatus(SPI2, SPI_I2S_FLAG_TXE)==RESET);
SPI_I2S_SendData(SPI2,ctrlcode); //дһݣͨݸʽ
while(SPI_I2S_GetFlagStatus(SPI2, SPI_I2S_FLAG_RXNE)==RESET);
rev = SPI_I2S_ReceiveData(SPI2); //Ͷȡ
CS=1;
return rev;
}
unsigned int TLC2543_Read(unsigned int channel)
{
unsigned int adcvalue = 0;
adcvalue = TLC2543_ReadWirte(channel)>>4;
while(!EOC);
return adcvalue;
}
unsigned int TLC2543_Set(unsigned int ctrlcode)
{
return TLC2543_ReadWirte(ctrlcode);
}
float TLC2543_Calvot(unsigned int ADCValue,int maxout)
{
return ADCValue*RF_VOT/maxout;
}
/*
˳ȡָĿֵͨpdata,len-ͨpdata-ָ룬Ĭ16bit,֤pdataָС>=2*len
*/
int TLC2543_readAll(unsigned short *pdata,int len)
{
len = (len <= TLC2543_CHANNELNUM)?len:TLC2543_CHANNELNUM;//Χ
for(int i = 0; i < len; i++)
{
pdata[i] = (unsigned short)TLC2543_Read(AIN0 + ((unsigned char)i << 4));
}
return len;
}
|
C | //hash-open addressing
// open addressing is a method for handling collisions. In Open Addressing,
//all elements are stored in the hash table itself.
//So at any point, the size of the table must be greater than
// or equal to the total number of keys
#include<stdio.h>
#include<stdlib.h>
int count;
#define maxsize 10
int insert_hash(int arr[],int num)
{
int key=num%maxsize;
while(arr[key]!=-1 && count!=maxsize)
{
key=(key+1)%maxsize;
count++;
}
if(count<maxsize)
arr[key]=num;
return 1;
}
int search(int arr[],int num)
{
int count=0;
int key=num%maxsize;
while(arr[key]!=num && count!=maxsize)
{
key=key+1%maxsize;
count++;
}
if(count<maxsize)
return 1;
else
return 0;
}
void display(int arr[])
{
for(int i=0;i<maxsize;i++)
printf("\n%d",arr[i]);
}
void delete(int arr[],int num)
{
int count=0;
int key=num%maxsize;
while(arr[key]!=num && count!=maxsize)
{
key=key+1%(maxsize);
count++;
}
if(count<maxsize)
arr[key]=-1;
}
int main()
{
int arr[maxsize];
int flag=0;
int num;
int ch;
for(int i=0;i<maxsize;i++)
arr[i]=-1;
while(1)
{
printf("\n enter option 1.inserthash 2.display 3.search 4.delete 5.exit");
scanf("%d",&ch);
switch(ch)
{
case 1:count=0;
printf("enter record no");
scanf("%d",&num);
flag=insert_hash(arr,num);
if(flag==0)
printf("\n hash table full");
break;
case 2:
display(arr);
break;
case 3:
printf("enter key to search");
scanf("%d",&num);
int s_flag=search(arr,num);
if(s_flag==1)
printf("key found");
else
printf("key not found");
break;
case 4:
printf("enter key to search");
scanf("%d",&num);
delete(arr,num);
break;
case 5:
exit(1);
}
}
} |
C | //NAME: Yunjing Zheng
//EMAIL: [email protected]
//ID: 304806663
#include <errno.h>
#include <pthread.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <time.h>
#include "utilities.h"
const int PROGRAM_TYPE=ADD_TYPE;
// can adjust using process arguments
int DEBUG_FLAG, YIELD_FLAG, NUM_THREADS=1, NUM_ITERATIONS=1;
long long COUNTER;
char* SYNC_TYPE="none";
int SPIN_LOCK;
pthread_mutex_t MUTEX = PTHREAD_MUTEX_INITIALIZER;
void add(long long *pointer, long long value) {
lock();
long long sum = *pointer + value;
if (YIELD_FLAG) sched_yield();
*pointer = sum;
unlock();
}
void add_c(long long *pointer, long long value) {
/*
atomic instruction __sync_val_compare_and_swap
long long __sync_val_compare_and_swap(long long *ptr, long long prev, long long new){
long long old=*ptr;
if(*ptr==prev)*ptr=new;
return old;
}
*/
long long old,new;
do {
old=*pointer;
new=old+value;
if (YIELD_FLAG) sched_yield();
}
while(__sync_val_compare_and_swap(pointer,old,new)!=old);
}
void* thread_task(void* func){
void (*add_func)(long long*, long long)=func;
int index_iteration;
for(index_iteration=0; index_iteration< NUM_ITERATIONS; index_iteration++){
add_func(&COUNTER,1);
}
for(index_iteration=0; index_iteration< NUM_ITERATIONS; index_iteration++){
add_func(&COUNTER,-1);
}
return NULL;
}
long long thread_spawner(){
void (*func)(long long*, long long);
if(strcmp(SYNC_TYPE,"c")==0) func=add_c;
else func=add;
pthread_t* my_threads=(pthread_t*) calloc(NUM_THREADS, sizeof(pthread_t));
start_timer();
int index_thread;
for(index_thread=0; index_thread< NUM_THREADS; index_thread++){
if(pthread_create(my_threads+index_thread, NULL, thread_task, (void*)func)) {
perror("Error: failed to create pthread");
close_and_exit_program(1);
}
}
for(index_thread=0; index_thread< NUM_THREADS; index_thread++){
/* wait for threads to finish*/
if(pthread_join(my_threads[index_thread], NULL)) {
perror("Error: failed to join pthread");
close_and_exit_program(1);
}
}
long long elapsed_time=end_timer();
free(my_threads);
return elapsed_time;
}
//this function checks for arguments
void process_args(int argc, char **argv){
static struct option long_options_list[] =
{
{"threads", required_argument, 0, 't'},
{"iterations", required_argument, 0, 'i'},
{"sync", required_argument, 0, 's'},
{"yield", optional_argument, 0, 'y'},
{"debug", no_argument, 0, 'd'},
{0, 0, 0, 0}
};
int c=0;
while ((c = getopt_long(argc, argv, "t:i:s:y:d:", long_options_list, NULL)) != -1){
//no argument, break
if (c == -1) break;
switch (c)
{
case 't':
NUM_THREADS=atoi(optarg);
if(NUM_THREADS<1) {
fprintf(stderr,"Error: number of threads must be greater than 0.\n");
close_and_exit_program(1);
}
break;
case 'i':
NUM_ITERATIONS=atoi(optarg);
if(NUM_ITERATIONS<1) {
fprintf(stderr,"Error: number of iterations must be greater than 0.\n");
close_and_exit_program(1);
}
break;
case 's':
if(strcmp(optarg,"none")!=0 && strcmp(optarg,"s")!=0 && strcmp(optarg,"m")!=0 &&
(PROGRAM_TYPE==LIST_TYPE || strcmp(optarg,"c")!=0)){
if(PROGRAM_TYPE==ADD_TYPE) fprintf(stderr,"Error: sync type must be s, c, or m.\n");
else fprintf(stderr,"Error: sync type must be s or m.\n");
close_and_exit_program(1);
}
SYNC_TYPE=optarg;
break;
case 'y':
if(PROGRAM_TYPE==LIST_TYPE) {
if(!optarg){
fprintf(stderr, "Error: yield requires an argument.\n");
close_and_exit_program(1);
}
if((strcmp(optarg,"none")==0)){
YIELD_FLAG=0;
}
else{
int c;
for(c=0; c<strlen(optarg); c++){
switch (optarg[c]){
case 'i':YIELD_FLAG |= INSERT_YIELD;
break;
case 'd':YIELD_FLAG |= DELETE_YIELD;
break;
case 'l':YIELD_FLAG |= LOOKUP_YIELD;
break;
default: fprintf(stderr,"Error: yield argument must be a combition of i, d, and l.\n");
close_and_exit_program(1);
}
}
}
}
else{
if(optarg){
fprintf(stderr, "Error: yield takes no argument.\n");
close_and_exit_program(1);
}
YIELD_FLAG=1;
}
break;
case 'd':
DEBUG_FLAG=1;
break;
case '?':
print_usage();
close_and_exit_program(1);
default:
// should never get here.
if(DEBUG_FLAG) printf("Error: Unexpected case.\n");
close_and_exit_program(1);
}
}
}
int main (int argc, char **argv)
{
process_args(argc, argv);
long long elapsed_time=thread_spawner();
long long operations=NUM_THREADS*NUM_ITERATIONS*2;
print_arguments_description();
fprintf(stdout, "%lld, %lld, %lld,%lld\n", operations, elapsed_time, elapsed_time/operations, COUNTER);
close_and_exit_program(0);
return 0;
} |
C |
#include "stdio.h"
int main(){
int pasc[11];
int n = 11;
int x, i, j;
int cam;
x = 0;
printf("INGRESE UN NUMERO:");
scanf("%d",&cam);
printf("\n");
printf("INGRESE EL NUMERO DE FILAS: ");
scanf("%d",&n);
for (i=1; i<=n ; i++)
{
//Construimos el triangulo de pascal
for (j=x; j>=0; j--)
{
if(j==x || j==0)
{
pasc[j] = cam;
}
else
{
pasc[j] = pasc[j] + pasc[j-1];
}
}
x++;
printf("\n");
//Truco para imprimir el triangulo
for (j=1; j<=n-i; j++)
printf(" ");
for(j=0; j<x; j++)
{
printf("%3d ", pasc[j]);
}
}
return 0;
}
|
C | #include<stdio.h>
int main()
{
int g;
printf("Enter your grade :");
scanf("%d",&g);
g=g/10;
switch(g)
{
case 10 :
case 9 :
printf("\nYour grade is A.");
break;
case 8 :
printf("\nYour grade is B.");
break;
case 7 :
printf("\nYour grade is C.");
break;
case 6 :
printf("\nYour grade is D.");
break;
default :
printf("\nYour grade is F.");
break;
}
return 0;
}
|
C | #incluide <studio.h>
int main []
[
int numero;
printf ( " \ n introduce un numero " );
scanf ( " % d , & numero " );
si (numero% 2 es 0 )
[
printf ( " \ n El numero es PAR " );
]
demás
[
printf ( " \ n El numero es IMPAR " );
]
return 0 ;
] |
C | #include "window.h"
static SDL_Surface *window;
static size_t window_width, window_height;
/* buffer used for window bar text */
#define TITLEBUFFER 40
#define BLACK SDL_MapRGB(window->format, 0x00, 0x00, 0x00)
#define WHITE SDL_MapRGB(window->format, 0xFF, 0xFF, 0xFF)
#define GREEN SDL_MapRGB(window->format, 0x00, 0xBB, 0x00)
#define BLUE SDL_MapRGB(window->format, 0x00, 0xAA, 0xDD)
#define GOLD SDL_MapRGB(window->format, 0xFF, 0xCC, 0x00)
#define RED SDL_MapRGB(window->format, 0xFF, 0x00, 0x00)
void draw_field(Game *game)
{
char title[TITLEBUFFER];
if (game->paused) {
sprintf(title, "%s — paused", TITLE);
} else if (game->players > 1) {
sprintf(title, "%s — multiplayer", TITLE);
} else if (game->level > 0) {
sprintf(title, "%s — level %d — score: %d/%d",
TITLE,
game->level,
game->total_score + game->p1->score,
game->total_score + TARGET_SCORE);
} else {
sprintf(title, "%s — score: %d",
TITLE, game->p1->score);
}
SDL_WM_SetCaption(title, NULL);
/* go over the 2D array to draw and draw the appropriate block */
for (int i = 0; i < game->width; ++i) {
for (int j = 0; j < game->height; ++j) {
SDL_Rect block = { 1 + i * BLOCK_SIZE
, 1 + j * BLOCK_SIZE
, BLOCK_SIZE - 2
, BLOCK_SIZE - 2
};
Uint32 color;
switch (game->field[i][j]) {
case '1': /* player 1's snake */
SDL_FillRect(window, &block, GREEN);
break;
case '2' /* player 2's snake */:
SDL_FillRect(window, &block, BLUE);
break;
case 'f': /* food */
SDL_FillRect(window, &block, RED);
break;
case 't': /* treat */
SDL_FillRect(window, &block, GOLD);
break;
case 'w': /* wall */
SDL_FillRect(window, &block, BLACK);
break;
default: /* empty */
SDL_FillRect(window, &block, WHITE);
break;
}
}
}
SDL_Flip(window);
}
void clear_screen()
{
SDL_FillRect(window, NULL, WHITE);
}
/* show highscores
* returns 1 to start a new game
* returns 0 to quit the game */
int score_screen()
{
HighScore *hs = get_scores();
SDL_FillRect(window, NULL, BLACK);
TTF_Font *font = TTF_OpenFont(FONTFILE, BLOCK_SIZE * 2 / 3);
SDL_Color black = { 0, 0, 0 };
SDL_Surface *score_fg;
char score[] = " Highscores ";
int text_width;
TTF_SizeText(font, score, &text_width, NULL);
int text_x_position = window_width / 2 - text_width / 2;
score_fg = TTF_RenderText_Blended(font, score, black);
SDL_Rect score_bg = { text_x_position
, 1
, text_width
, BLOCK_SIZE - 2
};
SDL_FillRect(window, &score_bg, WHITE);
SDL_BlitSurface(score_fg, NULL, window, &score_bg);
for (int i = 0; i < NR_OF_SCORES; ++i) {
sprintf(score, " <%02d> %5d %s ", i + 1, hs[i].score, hs[i].name);
score_fg = TTF_RenderText_Blended(font, score, black);
SDL_Rect score_bg = { text_x_position
, 1 + (i + 1) * BLOCK_SIZE
, text_width
, BLOCK_SIZE - 2
};
SDL_FillRect(window, &score_bg, WHITE);
SDL_BlitSurface(score_fg, NULL, window, &score_bg);
}
free(hs);
TTF_CloseFont(font);
SDL_FreeSurface(score_fg);
SDL_Flip(window);
SDL_Event event;
while (1) {
while (SDL_PollEvent(&event)) {
if (event.type == SDL_QUIT) {
return 0;
} else if (event.type == SDL_KEYDOWN) {
switch (event.key.keysym.sym) {
case SDLK_ESCAPE:
return 0;
case SDLK_SPACE:
case SDLK_RETURN:
case SDLK_KP_ENTER:
return 1;
default:
break;
}
}
}
}
}
/* get the player's name to add to the high score file
* part of this would fit better in io.c, but right now
* that'd just add unnecessary complexity
* will return NULL when player hit quit */
char *get_name()
{
TTF_Font *font = TTF_OpenFont(FONTFILE, BLOCK_SIZE * 2 / 3);
char *name = calloc(4, sizeof(char)); /* limited to 3 letters */
strcpy(name, "___");
char box[sizeof(" NAME: ___ ")];
sprintf(box, " NAME: %s ", name);
/* get width in pixels when drawn with the loaded font */
int box_width;
TTF_SizeText(font, box, &box_width, NULL);
SDL_Color font_color = { 0xFF, 0xFF, 0xFF };
SDL_Rect bg = { window_width / 2 - box_width / 2
, window_height / 2
, box_width
, BLOCK_SIZE - 2
};
SDL_Event event;
int i = 0, entering_text = 1;
while (entering_text) {
sprintf(box, " NAME: %s ", name);
SDL_Surface *fg = TTF_RenderText_Blended(font, box, font_color);
SDL_FillRect(window, &bg, BLACK);
SDL_BlitSurface(fg, NULL, window, &bg);
SDL_FreeSurface(fg);
SDL_Flip(window);
SDL_Delay(20);
while (SDL_PollEvent(&event)) {
if (event.type == SDL_KEYDOWN) {
int key = event.key.keysym.sym;
if (key == SDLK_RETURN || key == SDLK_KP_ENTER) {
entering_text = 0;
} else if (key == SDLK_BACKSPACE && i > 0) {
name[--i] = '_';
} else if (key >= SDLK_a && key <= SDLK_z && i < 3) {
name[i++] = (char) key ^ 32; /* switches to uppercase */
} else if (key >= SDLK_0 && key <= SDLK_9 && i < 3) {
name[i++] = (char) key;
}
} else if (event.type == SDL_QUIT) {
free(name);
name = NULL;
entering_text = 0;
}
}
}
TTF_CloseFont(font);
return name;
}
/* check who won in multiplayer game
* assumes player 1 has a green snake
* and player 2 has a blue snake
* returns 0 when player hit quit */
int show_winner(int player_nr)
{
TTF_Font *font = TTF_OpenFont(FONTFILE, BLOCK_SIZE * 2 / 3);
char winner[sizeof(" IT'S A TIE! ")];
if (player_nr == 1) {
strcpy(winner, " GREEN WINS! ");
} else if (player_nr == 2) {
strcpy(winner, " BLUE WINS! ");
} else {
strcpy(winner, " IT'S A TIE! ");
}
int text_width;
TTF_SizeText(font, winner, &text_width, NULL);
SDL_Color font_color = { 0xFF, 0xFF, 0xFF };
SDL_Rect bg = { window_width / 2 - text_width / 2
, window_height / 2
, text_width
, BLOCK_SIZE - 2
};
SDL_Surface *fg = TTF_RenderText_Blended(font, winner, font_color);
SDL_FillRect(window, &bg, BLACK);
SDL_BlitSurface(fg, NULL, window, &bg);
SDL_Flip(window);
SDL_FreeSurface(fg);
TTF_CloseFont(font);
SDL_Event event;
while (1) {
while(SDL_PollEvent(&event)) {
switch (event.type) {
case SDL_QUIT:
return 0;
case SDL_KEYDOWN:
switch (event.key.keysym.sym) {
case SDLK_SPACE:
case SDLK_RETURN:
case SDLK_ESCAPE:
return 1;
default:
break;
}
default:
SDL_Delay(20);
}
}
}
}
void window_quit()
{
puts("freeing window");
SDL_FreeSurface(window);
puts("quitting TTF");
TTF_Quit();
puts("quitting SDL");
SDL_Quit();
}
void window_init(size_t field_width, size_t field_height)
{
window_width = field_width * BLOCK_SIZE;
window_height = field_height * BLOCK_SIZE;
if (SDL_Init(SDL_INIT_VIDEO < 0)) {
fprintf(stderr, "Could not initialize SDL: %s\n", SDL_GetError());
exit(1);
}
window = SDL_SetVideoMode(window_width, window_height, 0,
SDL_HWPALETTE | SDL_DOUBLEBUF);
if (window == NULL) {
fprintf(stderr, "Failed to create window: %s\n", SDL_GetError());
exit(1);
}
if (TTF_Init() < 0) {
fprintf(stderr, "Could not initialize SDL_ttf: %s\n", TTF_GetError());
exit(1);
}
sound_init();
SDL_WM_SetCaption(TITLE, NULL);
clear_screen();
atexit(window_quit);
}
/* resizes window when loading a level with different dimensions
* for some reason also seems to relocate the window on Linux
* which would require using SDL2 to fix */
void window_resize(size_t field_width, size_t field_height)
{
SDL_FreeSurface(window);
window_width = field_width * BLOCK_SIZE;
window_height = field_height * BLOCK_SIZE;
window = SDL_SetVideoMode(window_width, window_height, 0,
SDL_HWPALETTE | SDL_DOUBLEBUF);
}
void window_pause()
{
char title[TITLEBUFFER];
sprintf(title, "%s — Paused", TITLE);
SDL_WM_SetCaption(title, NULL);
}
/* wraps SDL's delay function to make switching frameworks easier */
void delay(int n)
{
SDL_Delay(n);
}
|
C | #include "ctype.h"
#include "stdio.h"
#include "string.h"
void swap_chars(char *sentence, int char_closer_to_word_beginning_index, int char_closer_to_word_ending_index) {
char tmp = sentence[char_closer_to_word_ending_index];
sentence[char_closer_to_word_ending_index] = sentence[char_closer_to_word_beginning_index];
sentence[char_closer_to_word_beginning_index] = tmp;
}
void reverse_word_recursively(char *sentence, int word_beginning_index, int word_ending_index) {
if (word_beginning_index < word_ending_index) {
swap_chars(sentence, word_beginning_index, word_ending_index);
reverse_word_recursively(sentence, word_beginning_index + 1, word_ending_index - 1);
}
}
int is_not_last_char_in_word_yet(char *sentence, int index) {
return index > 0 && isspace(sentence[index]) ? 1 : 0;
}
int is_first_char_in_word(char *sentence, int index) {
return index == 0 || isspace(sentence[index-1]);
}
/**
* Reverse last word in given sentence recursively.
* 1. Looking for the beginning and the ending of the last word in a sentence.
* 2. When found - reversing the last world in the given char array by mutating this array
* @param sentence - sentence last word of which should be reversed
* @param potentially_first_char_in_word_index - index of the char which might be the first char in the last word
* @param potentially_last_char_in_word_index - index of the char which might be the last char in the last word
*/
void reverse_last_word_of_sentence_recursively(
char *sentence,
int potentially_first_char_in_word_index,
int potentially_last_char_in_word_index) {
// Nothing to reverse
if (potentially_last_char_in_word_index <= 0) {
return;
}
// Skip whitespaces in the end of the sentence
if (is_not_last_char_in_word_yet(sentence, potentially_first_char_in_word_index)) {
reverse_last_word_of_sentence_recursively(sentence, potentially_first_char_in_word_index - 1,
potentially_last_char_in_word_index - 1);
return;
}
if (is_first_char_in_word(sentence, potentially_first_char_in_word_index)) {
// Found the word beginning - reverse the last word
reverse_word_recursively(sentence, potentially_first_char_in_word_index, potentially_last_char_in_word_index);
return;
} else {
// Proceed looking for the word beginning
reverse_last_word_of_sentence_recursively(sentence, potentially_first_char_in_word_index - 1,
potentially_last_char_in_word_index);
}
}
/**
* Reverse last word in given sentence using cycle.
* 1. Looking for the beginning and the ending of the last word in a sentence.
* 2. When found - reversing the last world in the given char array by mutating this array
* @param sentence - sentence last word of which should be reversed
* @param length - length of the given sentence
*/
void reverse_last_word_with_cycle(char *sentence, int length) {
// Nothing to reverse
if (length <= 0) {
return;
}
int last_word_char_index = length;
for ( ; is_not_last_char_in_word_yet(sentence, last_word_char_index); last_word_char_index--);
// Word either doesn't exist or has just one char
if (last_word_char_index <= 0) {
return;
}
int first_word_char_index = last_word_char_index-1;
for ( ; !is_first_char_in_word(sentence, first_word_char_index); first_word_char_index--);
for( ; first_word_char_index < last_word_char_index; first_word_char_index++, last_word_char_index--) {
swap_chars(sentence, first_word_char_index, last_word_char_index);
}
}
int main() {
int max_input_size = 100;
char input[max_input_size];
printf("Print sentence\n");
fgets(input, max_input_size, stdin);
int length = (int) strlen(input)-1;
reverse_last_word_with_cycle(input, length);
printf("Reversed with a cycle:\n");
printf("%s\n", input);
reverse_last_word_of_sentence_recursively(input, length, length);
printf("Reversed back recursively:\n");
printf("%s\n", input);
return 0;
} |
C | /*
Lossy Block Reduction Filter.
Goal: Reduce the number of distinct pixel blocks such that subsequent compression of DXT output will compress better.
This is done as an image pre-filter rather than as part of the block-encoding process mostly to generalize over some of the subsequent encoding steps.
Note: May write over the edges or past the end of the image if it is not evenly divisible by the block size.
This estimates the block similarily mostly via MSE (Mean Square Error).
Tests show that this will introduce blocky artifacts with gradients.
*/
#include <bgbbtj.h>
// #define BLKSZ 8
// #define BLKSZ 2
#define BLKSZ 4
#define BLKSZ2 (BLKSZ*BLKSZ)
int *filtlbr_block_vals;
int *filtlbr_block_yval;
byte *filtlbr_block_cvals;
short *filtlbr_block_cyval;
short *filtlbr_block_ychain;
int *filtlbr_block_cnt;
int *filtlbr_block_ucnt;
int filtlbr_n_blocks;
int filtlbr_chains[1024];
int filtlbr_xs;
int filtlbr_ys;
void BGBBTJ_FiltLBR_GetIndexBlock(int idx, byte *buf)
{
// int i, n;
memcpy(buf, filtlbr_block_cvals+(idx*(BLKSZ2*4)), BLKSZ2*4);
}
int BGBBTJ_FiltLBR_GetIndexBlockY(int idx)
{
return(filtlbr_block_cyval[idx]);
}
void BGBBTJ_FiltLBR_AddIndexBlock(int idx, byte *buf)
{
int i, j, n;
i=BGBBTJ_FiltLBR_CalcBlockY(buf);
filtlbr_block_yval[idx]+=i;
for(i=0; i<(BLKSZ2*4); i++)
{
filtlbr_block_vals[idx*(BLKSZ2*4)+i]+=buf[i];
}
filtlbr_block_cnt[idx]++;
n=filtlbr_block_cnt[idx];
j=filtlbr_block_yval[idx]/n;
filtlbr_block_cyval[idx]=j;
for(i=0; i<(BLKSZ2*4); i++)
{
j=filtlbr_block_vals[idx*(BLKSZ2*4)+i]/n;
if(j<0)j=0;
if(j>255)j=255;
filtlbr_block_cvals[idx*(BLKSZ2*4)+i]=j;
}
#if 0
j=BGBBTJ_FiltLBR_CalcBlockY(filtlbr_block_cvals+(idx*(BLKSZ2*4)));
filtlbr_block_cyval[idx]=j;
#endif
}
int BGBBTJ_FiltLBR_CalcBlockY(byte *buf)
{
int i, j, k;
k=0;
for(i=0; i<BLKSZ2; i++)
{
// j=buf[i*4+0]+2*buf[i*4+1]+buf[i*4+2]+(buf[i*4+3]>>1);
j=(buf[i*4+0]+2*buf[i*4+1]+buf[i*4+2])>>2;
// j=(19595*buf[i*4+0] + 38470*buf[i*4+1] + 7471*buf[i*4+2])>>16;
k+=j;
}
return(k/BLKSZ2);
}
#if 0
int BGBBTJ_FiltLBR_CompareBlock(byte *blka, byte *blkb)
{
int ya, ua, va, aa;
int yb, ub, vb, ab;
int yc, yd;
int cr, cg, cb, ca;
int cra, cga, cba, caa;
int crb, cgb, cbb, cab;
int dr, dg, db, da;
int dy, du, dv;
int i, j, k, n;
#if 0
n=0;
for(i=0; i<BLKSZ2; i++)
{
cra=blka[i*4+0]; cga=blka[i*4+1];
cba=blka[i*4+2]; caa=blka[i*4+3];
crb=blkb[i*4+0]; cgb=blkb[i*4+1];
cbb=blkb[i*4+2]; cab=blkb[i*4+3];
dr=cra-crb; dr=dr*dr;
dg=cga-cgb; dg=dg*dg;
db=cba-cbb; db=db*db;
da=caa-cab; da=da*da;
dy=(dr+2*dg+db)>>2;
j=dr+dg+db+dy+(da>>2);
n+=j;
// n+=j*j;
}
return(n/(BLKSZ2*2));
#endif
#if 1
n=0;
for(i=0; i<BLKSZ2; i++)
{
cr=blka[i*4+0]; cg=blka[i*4+1];
cb=blka[i*4+2]; ca=blka[i*4+3];
ya=(cr+2*cg+cb)>>2;
// ua=((cb-cg)>>1)+128;
// va=((cr-cg)>>1)+128;
ua=(cb-cg)+128;
va=(cr-cg)+128;
aa=((ca-128)>>1)+128;
cr=blkb[i*4+0]; cg=blkb[i*4+1];
cb=blkb[i*4+2]; ca=blkb[i*4+3];
yb=(cr+2*cg+cb)>>2;
// ub=((cb-cg)>>1)+128;
// vb=((cr-cg)>>1)+128;
ub=(cb-cg)+128;
vb=(cr-cg)+128;
ab=((ca-128)>>1)+128;
dy=ya-yb;
du=ua-ub;
dv=va-vb;
da=aa-ab;
j=(dy*dy)+(du*du)+(dv*dv)+(da*da);
n+=j;
// n+=j*j;
}
return(n/(BLKSZ2*2));
#endif
#if 0
n=0;
for(i=0; i<BLKSZ; i++)
for(j=0; j<BLKSZ; j++)
{
k=i*4+j;
cr=blka[k*4+0]; cg=blka[k*4+1];
cb=blka[k*4+2]; ca=blka[k*4+3];
ya=(cr+2*cg+cb)>>2;
// ua=((cb-cg)>>1)+128;
// va=((cr-cg)>>1)+128;
ua=(cb-cg)+128;
va=(cr-cg)+128;
aa=((ca-128)>>1)+128;
cr=blkb[k*4+0]; cg=blkb[k*4+1];
cb=blkb[k*4+2]; ca=blkb[k*4+3];
yb=(cr+2*cg+cb)>>2;
// ub=((cb-cg)>>1)+128;
// vb=((cr-cg)>>1)+128;
ub=(cb-cg)+128;
vb=(cr-cg)+128;
ab=((ca-128)>>1)+128;
dy=ya-yb;
du=ua-ub;
dv=va-vb;
da=aa-ab;
// k=(dy*dy)+(da*da);
k=(dy*dy)+(du*du)+(dv*dv)+(da*da);
n+=k;
#if 1
if((j+1)<BLKSZ)
{
k=i*4+j+1;
cr=blka[k*4+0]; cg=blka[k*4+1]; cb=blka[k*4+2];
yc=(cr+2*cg+cb)>>2;
cr=blkb[k*4+0]; cg=blkb[k*4+1]; cb=blkb[k*4+2];
yd=(cr+2*cg+cb)>>2;
du=yc-ya;
dv=yd-yb;
dy=dv-du;
n+=(dy*dy)>>2;
}
if((i+1)<BLKSZ)
{
k=(i+1)*4+j;
cr=blka[k*4+0]; cg=blka[k*4+1]; cb=blka[k*4+2];
yc=(cr+2*cg+cb)>>2;
cr=blkb[k*4+0]; cg=blkb[k*4+1]; cb=blkb[k*4+2];
yd=(cr+2*cg+cb)>>2;
du=yc-ya;
dv=yd-yb;
dy=dv-du;
n+=(dy*dy)>>2;
}
#endif
// n+=j*j;
}
return(n/(BLKSZ2*2));
#endif
#if 0
n=0;
for(i=0; i<(BLKSZ2*4); i++)
{
j=blka[i]-blkb[i];
n+=j*j;
}
return(n/(BLKSZ2*4));
#endif
}
#endif
#if 1
int BGBBTJ_FiltLBR_CompareBlock(byte *blka, byte *blkb)
{
int ya, ua, va, aa;
int yb, ub, vb, ab;
int yc, yd;
int cr, cg, cb, ca;
int cra, cga, cba, caa;
int crb, cgb, cbb, cab;
int dr, dg, db, da;
int dy, du, dv;
int er, eg, eb, ea;
int i, j, k, n;
#if 1
n=0; er=0; eg=0; eb=0; ea=0;
for(i=0; i<BLKSZ2; i++)
{
cra=blka[i*4+0]; cga=blka[i*4+1];
cba=blka[i*4+2]; caa=blka[i*4+3];
crb=blkb[i*4+0]; cgb=blkb[i*4+1];
cbb=blkb[i*4+2]; cab=blkb[i*4+3];
dr=cra-crb; dr=dr*dr;
dg=cga-cgb; dg=dg*dg;
db=cba-cbb; db=db*db;
da=caa-cab; da=da*da;
j=(caa>cab)?caa:cab;
er+=(dr*j)>>8;
eg+=(dg*j)>>8;
eb+=(db*j)>>8;
ea+=(da*j)>>8;
// er+=dr;
// eg+=dg;
// eb+=db;
// ea+=da;
// dy=(dr+2*dg+db)>>2;
// j=dr+dg+db+dy+(da>>2);
// n+=j;
// n+=j*j;
}
// n=(19595*er + 38470*eg + 7471*eb + ea*4096 + 32768)>>16;
// n=(19595*er + 38470*eg + 7471*eb + ea*4096)>>16;
n=(19595LL*er + 38470LL*eg + 7471LL*eb + ea*4096LL)>>16;
// if(n<0)n=(1<<31)-1;
return(n/BLKSZ2);
#endif
}
#endif
int BGBBTJ_FiltLBR_GetImageBlock(
byte *img, int xstride, int ystride,
byte *block)
{
int i, j;
for(i=0; i<BLKSZ; i++)
for(j=0; j<BLKSZ; j++)
{
block[(i*BLKSZ+j)*4+0]=img[(i*ystride)+(j*xstride)+0];
block[(i*BLKSZ+j)*4+1]=img[(i*ystride)+(j*xstride)+1];
block[(i*BLKSZ+j)*4+2]=img[(i*ystride)+(j*xstride)+2];
block[(i*BLKSZ+j)*4+3]=img[(i*ystride)+(j*xstride)+3];
}
return(0);
}
int BGBBTJ_FiltLBR_SetImageBlock(
byte *img, int xstride, int ystride,
byte *block)
{
int i, j;
for(i=0; i<BLKSZ; i++)
for(j=0; j<BLKSZ; j++)
{
img[(i*ystride)+(j*xstride)+0]=block[(i*BLKSZ+j)*4+0];
img[(i*ystride)+(j*xstride)+1]=block[(i*BLKSZ+j)*4+1];
img[(i*ystride)+(j*xstride)+2]=block[(i*BLKSZ+j)*4+2];
img[(i*ystride)+(j*xstride)+3]=block[(i*BLKSZ+j)*4+3];
}
return(0);
}
int BGBBTJ_FiltLBR_YChainIdx(int yv, int mmse)
{
// return(yv/(mmse+1));
// return((yv+mmse)/(2*mmse+1));
return((yv+(mmse>>1))/(mmse+1));
}
int BGBBTJ_FiltLBR_LookupMatchIndexBlockSkip(byte *blk,
int immse, int mmse, int skip)
{
byte tblk[BLKSZ2*4];
int bi, be;
int i, j, yv;
yv=BGBBTJ_FiltLBR_CalcBlockY(blk);
#if 0
bi=-1; be=mmse;
for(i=0; i<filtlbr_n_blocks; i++)
{
j=BGBBTJ_FiltLBR_GetIndexBlockY(i);
j=j-yv; j=j*j;
if(j>be)continue;
BGBBTJ_FiltLBR_GetIndexBlock(i, tblk);
j=BGBBTJ_FiltLBR_CompareBlock(tblk, blk);
if(j<be) { bi=i; be=j; }
}
#endif
#if 1
bi=-1; be=mmse; i=filtlbr_chains[BGBBTJ_FiltLBR_YChainIdx(yv, immse)];
// for(i=0; i<filtlbr_n_blocks; i++)
while(i>=0)
{
#if 1
j=BGBBTJ_FiltLBR_GetIndexBlockY(i);
j=j-yv; j=j*j;
if(j>be)
{
i=filtlbr_block_ychain[i];
continue;
}
#endif
if(skip>=0)
{
if(i==skip)
{ i=filtlbr_block_ychain[i]; continue; }
// if(filtlbr_block_ucnt[i]<16)
// if(filtlbr_block_ucnt[i]<8)
if(filtlbr_block_ucnt[i]<4)
{ i=filtlbr_block_ychain[i]; continue; }
}
BGBBTJ_FiltLBR_GetIndexBlock(i, tblk);
j=BGBBTJ_FiltLBR_CompareBlock(tblk, blk);
if(j<be) { bi=i; be=j; }
i=filtlbr_block_ychain[i];
}
#endif
return(bi);
}
int BGBBTJ_FiltLBR_LookupMatchIndexBlock(byte *blk, int mmse)
{
return(BGBBTJ_FiltLBR_LookupMatchIndexBlockSkip(
blk, mmse, mmse, -1));
}
int BGBBTJ_FiltLBR_GetMatchIndexBlock(byte *blk, int mmse)
{
int i, j, k;
i=BGBBTJ_FiltLBR_LookupMatchIndexBlock(blk, mmse);
if(i>=0)return(i);
i=filtlbr_n_blocks++;
BGBBTJ_FiltLBR_AddIndexBlock(i, blk);
#if 1
j=BGBBTJ_FiltLBR_YChainIdx(
BGBBTJ_FiltLBR_GetIndexBlockY(i), mmse);
filtlbr_block_ychain[i]=filtlbr_chains[j];
filtlbr_chains[j]=i;
#endif
return(i);
}
BGBBTJ_API void BGBBTJ_FiltLBR_CheckSetupImage(
int xs, int ys, int qf)
{
int xs2, ys2;
xs2=(xs+BLKSZ-1)/BLKSZ;
ys2=(ys+BLKSZ-1)/BLKSZ;
if((xs!=filtlbr_xs) || (ys!=filtlbr_ys) || !filtlbr_block_vals)
{
if(filtlbr_block_vals)
{
free(filtlbr_block_vals);
free(filtlbr_block_yval);
free(filtlbr_block_cnt);
free(filtlbr_block_cvals);
free(filtlbr_block_cyval);
free(filtlbr_block_ychain);
}
filtlbr_block_vals=malloc(2*xs2*ys2*(BLKSZ2*4)*sizeof(int));
filtlbr_block_yval=malloc(2*xs2*ys2*sizeof(int));
filtlbr_block_cnt=malloc(2*xs2*ys2*sizeof(int));
filtlbr_block_ucnt=malloc(2*xs2*ys2*sizeof(int));
filtlbr_block_cvals=malloc(2*xs2*ys2*(BLKSZ2*4));
filtlbr_block_cyval=malloc(2*xs2*ys2*sizeof(short));
filtlbr_block_ychain=malloc(2*xs2*ys2*sizeof(short));
filtlbr_n_blocks=0;
filtlbr_xs=xs;
filtlbr_ys=ys;
}
}
BGBBTJ_API void BGBBTJ_FiltLBR_SetupImage(
int xs, int ys, int qf)
{
int xs2, ys2;
int i;
BGBBTJ_FiltLBR_CheckSetupImage(xs, ys, qf);
xs2=(xs+BLKSZ-1)/BLKSZ;
ys2=(ys+BLKSZ-1)/BLKSZ;
filtlbr_n_blocks=0;
memset(filtlbr_block_vals, 0, 2*xs2*ys2*(BLKSZ2*4)*sizeof(int));
memset(filtlbr_block_yval, 0, 2*xs2*ys2*sizeof(int));
memset(filtlbr_block_cnt, 0, 2*xs2*ys2*sizeof(int));
memset(filtlbr_block_ucnt, 0, 2*xs2*ys2*sizeof(int));
// memset(filtlbr_chains, 0, 256*sizeof(int));
for(i=0; i<1024; i++)
filtlbr_chains[i]=-1;
}
/**
* Filter image, where irgba and orgba give the input and output images.
* xs and ys give the size, and qf gives the quality (low 8 bits, 0-100).
*/
BGBBTJ_API void BGBBTJ_FiltLBR_FilterImageB(
byte *orgba, byte *irgba, int xs, int ys, int qf)
{
byte tblk[BLKSZ2*4];
int *bidx, *uidx;
int x, y, xs2, ys2, xstr, ystr;
int idx, idx1, mmse;
int i, j, k;
if((qf&255)>=100)
{
if(!orgba)return;
memcpy(orgba, irgba, xs*ys*4);
return;
}
printf("BGBBTJ_FiltLBR_FilterImage: Begin\n");
BGBBTJ_FiltLBR_SetupImage(xs, ys, qf);
xs2=(xs+BLKSZ-1)/BLKSZ;
ys2=(ys+BLKSZ-1)/BLKSZ;
bidx=malloc(xs2*ys2*sizeof(int));
// uidx=malloc(xs2*ys2*sizeof(int));
uidx=filtlbr_block_ucnt;
memset(uidx, 0, xs2*ys2*sizeof(int));
xstr=4; ystr=xs*4;
// mmse=95-(qf&255);
// mmse=90-(qf&255);
// mmse=100-(qf&255);
// mmse=256-(qf&255);
// mmse=1.0+10.0*(pow(100.0/(qf&255), 2)-1.0);
mmse=1.0+10.0*((100.0/(qf&255))-1.0);
// mmse=1.0+20.0*((100.0/(qf&255))-1.0);
if(mmse<0)mmse=0;
mmse=mmse*mmse;
for(y=0; y<ys2; y++)
{
printf("BGBBTJ_FiltLBR_FilterImage: %d/%d %d/%d\r",
y, ys2, filtlbr_n_blocks, y*xs2);
for(x=0; x<xs2; x++)
{
BGBBTJ_FiltLBR_GetImageBlock(irgba+(y*BLKSZ*ystr)+(x*BLKSZ*xstr),
xstr, ystr, tblk);
idx=BGBBTJ_FiltLBR_GetMatchIndexBlock(tblk, mmse);
// BGBBTJ_FiltLBR_AddIndexBlock(idx, tblk);
bidx[y*xs2+x]=idx;
uidx[idx]++;
}
printf("BGBBTJ_FiltLBR_FilterImage: %d/%d %d/%d\r",
y, ys2, filtlbr_n_blocks, y*xs2);
}
printf("\n");
#if 1
for(y=0; y<ys2; y++)
{
for(x=0; x<xs2; x++)
{
idx=bidx[y*xs2+x];
// if(uidx[idx]<16)
if(uidx[idx]<8)
{
BGBBTJ_FiltLBR_GetImageBlock(
irgba+(y*BLKSZ*ystr)+(x*BLKSZ*xstr),
xstr, ystr, tblk);
// k=mmse+((mmse*(32-uidx[idx]))>>1);
// k=mmse+((mmse*(16-uidx[idx]))>>1);
// k=mmse+((mmse*(16-uidx[idx]))>>2);
k=mmse+((mmse*(8-uidx[idx]))>>2);
// k=mmse+(mmse*(16-uidx[idx]));
i=BGBBTJ_FiltLBR_LookupMatchIndexBlockSkip(
tblk, mmse, k, idx);
if(i>0)
{
bidx[y*xs2+x]=i;
}
}
// BGBBTJ_FiltLBR_AddIndexBlock(idx, tblk);
// bidx[y*xs2+x]=idx;
}
}
#endif
#if 1
for(y=0; y<ys2; y++)
{
// printf("BGBBTJ_FiltLBR_FilterImage: %d/%d %d/%d\r",
// y, ys2, filtlbr_n_blocks, y*xs2);
for(x=0; x<xs2; x++)
{
BGBBTJ_FiltLBR_GetImageBlock(irgba+(y*BLKSZ*ystr)+(x*BLKSZ*xstr),
xstr, ystr, tblk);
// idx=BGBBTJ_FiltLBR_GetMatchIndexBlock(tblk, mmse);
idx=bidx[y*xs2+x];
BGBBTJ_FiltLBR_AddIndexBlock(idx, tblk);
// bidx[y*xs2+x]=idx;
}
// printf("BGBBTJ_FiltLBR_FilterImage: %d/%d %d/%d\r",
// y, ys2, filtlbr_n_blocks, y*xs2);
}
// printf("\n");
#endif
if(!orgba)return;
for(y=0; y<ys2; y++)
for(x=0; x<xs2; x++)
{
idx=bidx[y*xs2+x];
#if 0
printf("BGBBTJ_FiltLBR_FilterImage: %d/%d %d/%d\r",
y, ys2, filtlbr_n_blocks, y*xs2);
BGBBTJ_FiltLBR_GetImageBlock(irgba+(y*BLKSZ*ystr)+(x*BLKSZ*xstr),
xstr, ystr, tblk);
// idx1=BGBBTJ_FiltLBR_LookupMatchIndexBlock(tblk, mmse);
idx1=BGBBTJ_FiltLBR_GetMatchIndexBlock(tblk, mmse);
if(idx1>=0)idx=idx1;
#endif
BGBBTJ_FiltLBR_GetIndexBlock(idx, tblk);
BGBBTJ_FiltLBR_SetImageBlock(orgba+(y*BLKSZ*ystr)+(x*BLKSZ*xstr),
xstr, ystr, tblk);
}
// printf("\n");
free(bidx);
// free(filtlbr_block_vals);
// free(filtlbr_block_yval);
// free(filtlbr_block_cvals);
// free(filtlbr_block_cyval);
// free(filtlbr_block_cnt);
printf("BGBBTJ_FiltLBR_FilterImage: Done\n");
}
/**
* Filter patch image, where irgba and orgba give the input and output images.
* xs and ys give the size, and qf gives the quality (low 8 bits, 0-100).
* Patch images will try to reuse blocks from a prior image.
*/
BGBBTJ_API void BGBBTJ_FiltLBR_FilterPatchImageB(
byte *orgba, byte *irgba, int xs, int ys, int qf)
{
byte tblk[BLKSZ2*4];
int onchn[1024];
int *bidx;
int x, y, xs2, ys2, xstr, ystr;
int idx, idx1, mmse, onb;
int i;
if((qf&255)>=100)
{
memcpy(orgba, irgba, xs*ys*4);
return;
}
printf("BGBBTJ_FiltLBR_FilterImage: Begin\n");
onb=filtlbr_n_blocks;
for(i=0; i<1024; i++)
onchn[i]=filtlbr_chains[i];
BGBBTJ_FiltLBR_CheckSetupImage(xs, ys, qf);
xs2=(xs+BLKSZ-1)/BLKSZ;
ys2=(ys+BLKSZ-1)/BLKSZ;
bidx=malloc(xs2*ys2*sizeof(int));
xstr=4; ystr=xs*4;
// mmse=95-(qf&255);
// mmse=90-(qf&255);
// mmse=100-(qf&255);
// mmse=256-(qf&255);
// mmse=1.0+10.0*(pow(100.0/(qf&255), 2)-1.0);
mmse=1.0+10.0*((100.0/(qf&255))-1.0);
// mmse=1.0+20.0*((100.0/(qf&255))-1.0);
if(mmse<0)mmse=0;
mmse=mmse*mmse;
for(y=0; y<ys2; y++)
{
printf("BGBBTJ_FiltLBR_FilterImage: %d/%d %d/%d\r",
y, ys2, filtlbr_n_blocks, y*xs2);
for(x=0; x<xs2; x++)
{
BGBBTJ_FiltLBR_GetImageBlock(irgba+(y*BLKSZ*ystr)+(x*BLKSZ*xstr),
xstr, ystr, tblk);
idx=BGBBTJ_FiltLBR_GetMatchIndexBlock(tblk, mmse);
bidx[y*xs2+x]=idx;
}
printf("BGBBTJ_FiltLBR_FilterImage: %d/%d %d/%d\r",
y, ys2, filtlbr_n_blocks, y*xs2);
}
printf("\n");
#if 1
for(y=0; y<ys2; y++)
{
for(x=0; x<xs2; x++)
{
BGBBTJ_FiltLBR_GetImageBlock(irgba+(y*BLKSZ*ystr)+(x*BLKSZ*xstr),
xstr, ystr, tblk);
idx=bidx[y*xs2+x];
if(idx<onb)continue;
BGBBTJ_FiltLBR_AddIndexBlock(idx, tblk);
}
}
#endif
for(y=0; y<ys2; y++)
for(x=0; x<xs2; x++)
{
idx=bidx[y*xs2+x];
BGBBTJ_FiltLBR_GetIndexBlock(idx, tblk);
BGBBTJ_FiltLBR_SetImageBlock(orgba+(y*BLKSZ*ystr)+(x*BLKSZ*xstr),
xstr, ystr, tblk);
}
//restore prior state
filtlbr_n_blocks=onb;
for(i=0; i<1024; i++)
filtlbr_chains[i]=onchn[i];
free(bidx);
printf("BGBBTJ_FiltLBR_FilterImage: Done\n");
}
BGBBTJ_API void BGBBTJ_FiltLBR_PreFilterImage_Reduce(
byte *rgba, int xs, int ys, int qf)
{
byte tblk[BLKSZ2*4], tblk2[BLKSZ2*4];
byte tdblk[16];
int x, y, xs2, ys2, xstr, ystr;
int pxa, pxb, pxc, pxd;
int cr, cg, cb, ca;
int idx, idx1, mmse, onb;
int i, j;
xs2=(xs+BLKSZ-1)/BLKSZ;
ys2=(ys+BLKSZ-1)/BLKSZ;
xstr=4;
ystr=xs*xstr;
mmse=1.0+10.0*((100.0/(qf&255))-1.0);
// mmse=1.0+20.0*((100.0/(qf&255))-1.0);
if(mmse<0)mmse=0;
mmse=mmse*mmse;
for(y=0; y<ys2; y++)
{
for(x=0; x<xs2; x++)
{
BGBBTJ_FiltLBR_GetImageBlock(rgba+(y*BLKSZ*ystr)+(x*BLKSZ*xstr),
xstr, ystr, tblk);
// idx=BGBBTJ_FiltLBR_GetMatchIndexBlock(tblk, mmse);
// bidx[y*xs2+x]=idx;
for(i=0; i<2; i++)
for(j=0; j<2; j++)
{
pxa=((i*2+0)*4+j*2+0)*4; pxb=((i*2+0)*4+j*2+1)*4;
pxc=((i*2+1)*4+j*2+0)*4; pxd=((i*2+1)*4+j*2+1)*4;
cr=(tblk[pxa+0]+tblk[pxb+0]+tblk[pxc+0]+tblk[pxd+0])>>2;
cg=(tblk[pxa+1]+tblk[pxb+1]+tblk[pxc+1]+tblk[pxd+1])>>2;
cb=(tblk[pxa+2]+tblk[pxb+2]+tblk[pxc+2]+tblk[pxd+2])>>2;
ca=(tblk[pxa+3]+tblk[pxb+3]+tblk[pxc+3]+tblk[pxd+3])>>2;
tblk2[pxa+0]=cr; tblk2[pxb+0]=cr;
tblk2[pxc+0]=cr; tblk2[pxd+0]=cr;
tblk2[pxa+1]=cg; tblk2[pxb+1]=cg;
tblk2[pxc+1]=cg; tblk2[pxd+1]=cg;
tblk2[pxa+2]=cb; tblk2[pxb+2]=cb;
tblk2[pxc+2]=cb; tblk2[pxd+2]=cb;
tblk2[pxa+3]=ca; tblk2[pxb+3]=ca;
tblk2[pxc+3]=ca; tblk2[pxd+3]=ca;
}
i=BGBBTJ_FiltLBR_CompareBlock(tblk2, tblk);
if((i*i)<=mmse)
{
BGBBTJ_FiltLBR_SetImageBlock(
rgba+(y*BLKSZ*ystr)+(x*BLKSZ*xstr),
xstr, ystr, tblk2);
memcpy(tblk, tblk2, BLKSZ2*4);
}
#if 0
BGBBTJ_BCn_EncodeBlockDXT1F(
tdblk, tblk, 4, 4*4, 3);
BGBBTJ_BCn_DecodeBlockDXT1(tdblk, tblk2, 4, 4*4, 3);
i=BGBBTJ_FiltLBR_CompareBlock(tblk2, tblk);
if((i*i)<=mmse)
{
BGBBTJ_FiltLBR_SetImageBlock(
rgba+(y*BLKSZ*ystr)+(x*BLKSZ*xstr),
xstr, ystr, tblk2);
memcpy(tblk, tblk2, BLKSZ2*4);
}
#endif
}
}
}
BGBBTJ_API void BGBBTJ_FiltLBR_FilterImage(
byte *orgba, byte *irgba, int xs, int ys, int qf)
{
byte *trgba, *tblk;
int fmt;
if((qf&255)>90)
{
BGBBTJ_FiltLBR_FilterImageB(orgba, irgba, xs, ys, qf);
return;
}
trgba=malloc(xs*ys*4);
tblk=malloc(((xs+3)/4)*((ys+3)/4)*16);
fmt=BGBBTJ_JPG_BC3;
// if(fmt<75)
// { fmt=BGBBTJ_JPG_BC3F; }
// if(fmt<50)
// { fmt=BGBBTJ_JPG_BC1A; }
BGBBTJ_BCn_EncodeImageDXTn(tblk, irgba, xs, ys, 4, fmt);
BGBBTJ_BCn_DecodeImageDXTn(tblk, trgba, xs, ys, 4, fmt);
BGBBTJ_FiltLBR_ColorQuantizeImage(trgba, trgba, xs, ys, qf);
// BGBBTJ_FiltLBR_PreFilterImage_Reduce(trgba, xs, ys, qf);
BGBBTJ_FiltLBR_FilterImageB(orgba, trgba, xs, ys, qf);
// BGBBTJ_FiltLBR_PreFilterImage_Reduce(orgba, xs, ys, qf);
// BGBBTJ_FiltLBR_ColorQuantizeImage(orgba, orgba, xs, ys, qf);
free(trgba);
free(tblk);
// BGBBTJ_FiltLBR_StatImageBlocks(orgba, xs, ys, qf);
// BGBBTJ_FiltLBR_StatImageBlocks(irgba, xs, ys, qf);
}
BGBBTJ_API void BGBBTJ_FiltLBR_FilterPatchImage(
byte *orgba, byte *irgba, int xs, int ys, int qf)
{
byte *trgba, *tblk;
if((qf&255)>90)
{
BGBBTJ_FiltLBR_FilterPatchImageB(orgba, irgba, xs, ys, qf);
return;
}
trgba=malloc(xs*ys*4);
tblk=malloc(((xs+3)/4)*((ys+3)/4)*16);
BGBBTJ_BCn_EncodeImageDXTn(tblk, irgba, xs, ys, 4, BGBBTJ_JPG_BC3);
BGBBTJ_BCn_DecodeImageDXTn(tblk, trgba, xs, ys, 4, BGBBTJ_JPG_BC3);
BGBBTJ_FiltLBR_FilterPatchImageB(orgba, trgba, xs, ys, qf);
// BGBBTJ_FiltLBR_ColorQuantizeImage(orgba, orgba, xs, ys, qf);
#if 0
BGBBTJ_BCn_EncodeImageDXTn(tblk, orgba, xs, ys, 4, BGBBTJ_JPG_BC3);
#endif
free(trgba);
free(tblk);
}
BGBBTJ_API void BGBBTJ_FiltLBR_ColorQuantizeImage(
byte *orgba, byte *irgba, int xs, int ys, int qf)
{
int cr, cg, cb, ca;
int cy, cu, cv;
int i, j, k, n;
// return;
if((qf&255)>50)
{
if(orgba!=irgba)
{ memcpy(orgba, irgba, xs*ys*4); }
return;
}
n=xs*ys;
for(i=0; i<n; i++)
{
cr=irgba[i*4+0];
cg=irgba[i*4+1];
cb=irgba[i*4+2];
ca=irgba[i*4+3];
#if 0
cr=((cr+21)/43)*43;
cg=((cg+21)/43)*43;
cb=((cb+21)/43)*43;
cr=(cr<0)?0:((cr>255)?255:cr);
cg=(cg<0)?0:((cg>255)?255:cg);
cb=(cb<0)?0:((cb>255)?255:cb);
#endif
#if 1
cy=(cr+2*cg+cb)>>2;
cu=(cb-cg)+128;
cv=(cr-cg)+128;
// cu=((cb-cg)/2)+128;
// cv=((cr-cg)/2)+128;
cu=((cu-128)*1.5)+128;
cv=((cv-128)*1.5)+128;
#if 1
// cy=(cy*10+128)>>8;
// cu=(cu*5+128)>>8;
// cv=(cv*5+128)>>8;
// cy=(cy*10+127)>>8;
// cu=(cu*5+127)>>8;
// cv=(cv*5+127)>>8;
cy=(cy*10+128)>>8;
cu=(((cu-128)*5+128)>>8)+2;
cv=(((cv-128)*5+128)>>8)+2;
// cy=(cy*10)>>8;
// cu=(cu*5)>>8;
// cv=(cv*5)>>8;
// ca=ca>>4;
cy=(cy<0)?0:((cy>9)?9:cy);
cu=(cu<0)?0:((cu>4)?4:cu);
cv=(cv<0)?0:((cv>4)?4:cv);
// cy=(cy* 6554+128)>>8;
// cu=(cu*13107+128)>>8;
// cv=(cv*13107+128)>>8;
// cy=(((cy-2)* 6554+128)>>8)+128;
cy=(cy* 6554+128)>>8;
cu=(((cu-2)*13107+128)>>8)+128;
cv=(((cv-2)*13107+128)>>8)+128;
// ca=ca<<4;
#endif
// cu-=128; cv-=128;
// cu=(cu-128)*2; cv=(cv-128)*2;
cu=(cu-128)*0.67; cv=(cv-128)*0.67;
cg=cy-((cu+cv)>>2);
cb=cg+cu;
cr=cg+cv;
cr=(cr<0)?0:((cr>255)?255:cr);
cg=(cg<0)?0:((cg>255)?255:cg);
cb=(cb<0)?0:((cb>255)?255:cb);
#endif
orgba[i*4+0]=cr;
orgba[i*4+1]=cg;
orgba[i*4+2]=cb;
orgba[i*4+3]=ca;
}
}
#if 0
BGBBTJ_API void BGBBTJ_FiltLBR_StatImageBlocks(
byte *rgba, int xs, int ys, int qf)
{
int *colors;
int *bpat;
byte *tbuf, *tcda;
byte *tblk, *sb;
int cr, cg, cb;
int cya, cua, cva, cyb, cub, cvb;
int i, j, k, l, n, nc, np;
int stm, stn, sta;
n=((xs+3)/4)*((ys+3)/4);
colors=malloc(65536*sizeof(int));
memset(colors, 0, 65536*sizeof(int));
bpat=malloc(n*sizeof(int));
tbuf=malloc(1<<22);
tblk=malloc(n*16);
BGBBTJ_BCn_EncodeImageDXTn(tblk, rgba, xs, ys, 4, BGBBTJ_JPG_BC3);
tcda=malloc(n*6);
printf("BGBBTJ_FiltLBR_StatImageBlocks:\n");
np=0;
for(i=0; i<n; i++)
{
sb=tblk+i*16+8;
colors[sb[0]|(sb[1]<<8)]++;
colors[sb[2]|(sb[3]<<8)]++;
#if 1
// k=sb[4]|(sb[5]<<8)|(sb[6]<<16)|(sb[7]<<24);
#if 1
k=(sb[4]&15)|((sb[5]&15)<<4);
j=((sb[4]>>4)&15)|(((sb[5]>>4)&15)<<4);
k|=j<<8;
j=(sb[6]&15)|((sb[7]&15)<<4);
k|=j<<16;
j=((sb[6]>>4)&15)|(((sb[7]>>4)&15)<<4);
k|=j<<24;
#endif
for(j=0; j<np; j++)
if(bpat[j]==k)
break;
if(j>=np)
{
j=np++;
bpat[j]=k;
tcda[j*4+0]=sb[0];
tcda[j*4+1]=sb[1];
tcda[j*4+2]=sb[2];
tcda[j*4+3]=sb[3];
if(j)
{
// k=sb[0]|(sb[1]<<8)|(sb[2]<<16)|(sb[3]<<24);
// l=sb[0-16]|(sb[1-16]<<8)|(sb[2-16]<<16)|(sb[3-16]<<24);
k=sb[0]|(sb[1]<<8);
l=sb[0-16]|(sb[1-16]<<8);
k=k-l;
tcda[j*4+0]=k;
tcda[j*4+1]=k>>8;
// tcda[j*4+2]=k>>16;
// tcda[j*4+3]=k>>24;
k=sb[2]|(sb[3]<<8);
l=sb[2-16]|(sb[3-16]<<8);
k=k-l;
tcda[j*4+2]=k;
tcda[j*4+3]=k>>8;
// tcda[j*4+0]=sb[0]-sb[-16];
// tcda[j*4+1]=sb[1]-sb[-15];
// tcda[j*4+2]=sb[2]-sb[-14];
// tcda[j*4+3]=sb[3]-sb[-13];
// tcda[j*4+0]=sb[0]-tcda[(j-1)*4+0];
// tcda[j*4+1]=sb[1]-tcda[(j-1)*4+1];
// tcda[j*4+2]=sb[2]-tcda[(j-1)*4+2];
// tcda[j*4+3]=sb[3]-tcda[(j-1)*4+3];
}
#if 0
k=sb[0]|(sb[1]<<8);
cb=(k&0x001F)<<3;
cg=(k&0x07E0)>>3;
cr=(k&0xF800)>>8;
// tcda[j*6+0]=(cr+2*cg+cb)>>2;
// tcda[j*6+1]=cb-cg;
// tcda[j*6+2]=cr-cg;
cya=(cr+2*cg+cb)>>2;
cua=cb-cg; cva=cr-cg;
k=sb[2]|(sb[3]<<8);
cb=(k&0x001F)<<3;
cg=(k&0x07E0)>>3;
cr=(k&0xF800)>>8;
// tcda[j*6+3]=(cr+2*cg+cb)>>2;
// tcda[j*6+4]=cb-cg;
// tcda[j*6+5]=cr-cg;
cyb=(cr+2*cg+cb)>>2;
cub=cb-cg; cvb=cr-cg;
tcda[j*6+0]=cya;
tcda[j*6+1]=cua;
tcda[j*6+2]=cva;
tcda[j*6+3]=cyb-cya;
tcda[j*6+4]=cub-cua;
tcda[j*6+5]=cvb-cva;
#endif
}
#endif
}
nc=0; stm=99999; stn=0; sta=0;
for(i=0; i<65536; i++)
{
if(colors[i])
{
if(colors[i]<stm)
stm=colors[i];
if(colors[i]>stn)
stn=colors[i];
sta+=colors[i];
nc++;
}
}
sta/=nc;
printf("BGBBTJ_FiltLBR_NumColors: Nc=%d Stm=%d Stn=%d Sta=%d\n",
nc, stm, stn, sta);
printf("BGBBTJ_FiltLBR_NumPatterns: %d\n", np);
i=PDZ2_EncodeStreamLvl(bpat, tbuf, np*4, 1<<22, 9);
printf("BGBBTJ_FiltLBR_BPatSz: %d -> %d\n", np*4, i);
// i=PDZ2_EncodeStreamLvl(tcda, tbuf, np*6, 1<<22, 9);
// printf("BGBBTJ_FiltLBR_TcdaSz: %d -> %d, R=%d\n", np*6, i, np*4);
i=PDZ2_EncodeStreamLvl(tcda, tbuf, np*4, 1<<22, 9);
printf("BGBBTJ_FiltLBR_TcdaSz: %d -> %d, R=%d\n", np*4, i, np*4);
printf("BGBBTJ_FiltLBR_StatImageBlocks: OK\n");
}
#endif
#if 1
BGBBTJ_API void BGBBTJ_FiltLBR_StatImageBlocks(
byte *rgba, int xs, int ys, int qf)
{
int stats[1024];
byte *tbuf, *lbuf, *tlcbuf, *tlpbuf;
byte *tpbuf, *tplbuf;
byte *tzbuf, *tzlbuf;
byte *tblk, *sb;
u64 li, lj;
int cr, cg, cb;
int cya, cua, cva, cyb, cub, cvb;
int i, j, k, l, n, nc, np;
int stm, stn, sta, sz, szlb, szp, szplb;
n=((xs+3)/4)*((ys+3)/4);
tbuf=malloc(1<<22);
lbuf=malloc(1<<22);
tblk=malloc(2*n*16);
BGBBTJ_BCn_EncodeImageDXTn(tblk, rgba, xs, ys, 4, BGBBTJ_JPG_BC3);
BGBBTJ_BCn_EncodeImageDXTn(tblk+n*16, rgba, xs, ys, 4, BGBBTJ_JPG_BC3);
sz=BGBBTJ_PackBCn_EncodeBlocks2DXT5(
tbuf, lbuf, tblk, n, ((xs+3)/4), &szlb);
tpbuf=malloc(1<<22);
tplbuf=malloc(1<<22);
szp=BGBBTJ_PackBCn_EncodePatchBlocks2DXT5(
tpbuf, tplbuf, tblk, n, ((xs+3)/4), &szplb);
printf("BGBBTJ_FiltLBR_StatImageBlocks: Sz=%d, SzLb=%d\n", sz, szlb);
printf("BGBBTJ_FiltLBR_StatImageBlocks: SzP=%d, SzLbP=%d\n", szp, szplb);
for(i=0; i<1024; i++)stats[i]=0;
// BGBBTJ_PackBCn_StatBlockArray2(tbuf, stats, 2*n, ((xs+3)/4));
BGBBTJ_PackBCn_StatBlockArray2(tpbuf, stats, 2*n, ((xs+3)/4));
for(i=0; i<32; i++)
{
printf("B%3d: ", i*8);
for(j=0; j<8; j++)
{
printf("%5d ", stats[i*8+j]);
}
printf("\n");
}
for(i=0; i<32; i++)
{
printf("I%3d: ", i*8);
for(j=0; j<8; j++)
{
printf("%5d ", stats[256+i*8+j]);
}
printf("\n");
}
for(i=0; i<32; i++)
{
printf("L%3d: ", i*8);
for(j=0; j<8; j++)
{
printf("%5d ", stats[512+i*8+j]);
}
printf("\n");
}
tzbuf=malloc(1<<22);
tzlbuf=malloc(1<<22);
tlcbuf=malloc(1<<22);
tlpbuf=malloc(1<<22);
lj=0;
for(i=0; i<(szlb/8); i++)
{
li=*(u64 *)(lbuf+(i*8));
// *(u32 *)(lbuf+(i*8))=li^lj;
// lj=li;
j=*(u32 *)(lbuf+(i*8+0));
*(u32 *)(tlcbuf+i*4)=j;
j=*(u32 *)(lbuf+(i*8+4));
*(u32 *)(tlpbuf+i*4)=j;
}
i=PDZ2_EncodeStreamLvl(tbuf, tzbuf, sz, 1<<22, 9);
printf("BGBBTJ_FiltLBR_StatImageBlocks: TzBuf %d -> %d\n", sz, i);
j=PDZ2_EncodeStreamLvl(lbuf, tzlbuf, szlb, 1<<22, 9);
printf("BGBBTJ_FiltLBR_StatImageBlocks: TzlBuf %d -> %d\n", szlb, j);
printf("BGBBTJ_FiltLBR_StatImageBlocks: TotBuf %d -> %d\n", sz+szlb, i+j);
j=PDZ2_EncodeStreamLvl(tlcbuf, tzlbuf, szlb/2, 1<<22, 9);
printf("BGBBTJ_FiltLBR_StatImageBlocks: TzlcBuf %d -> %d\n", szlb/2, j);
k=PDZ2_EncodeStreamLvl(tlpbuf, tzlbuf, szlb/2, 1<<22, 9);
printf("BGBBTJ_FiltLBR_StatImageBlocks: TzlpBuf %d -> %d\n", szlb/2, k);
printf("BGBBTJ_FiltLBR_StatImageBlocks: TotBufB %d -> %d\n",
sz+szlb, i+j+k);
}
#endif
|
C | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_printf.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: fgracefo <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2020/07/13 14:24:33 by fgracefo #+# #+# */
/* Updated: 2020/08/14 16:50:42 by fgracefo ### ########.fr */
/* */
/* ************************************************************************** */
#include "../header/ft_printf.h"
t_flag ft_parse_len(const char *format, size_t *i, va_list list, t_flag flag)
{
if (format[*i] == 'l' && format[(*i) + 1] == 'l')
{
flag.length.ll = 1;
(*i)++;
}
else if (format[*i] == 'l')
flag.length.l = 1;
else if (format[*i] == 'L')
flag.length.lll = 1;
else if (format[*i] == 'z')
flag.length.l = 'z';
else if (format[*i] == 'j')
flag.length.l = 'j';
else if (format[*i] == 'h' && format[(*i) + 1] == 'h')
{
flag.length.hh = 1;
(*i)++;
}
else if (format[*i] == 'h')
flag.length.h = 1;
flag.size.star = ft_count_size(format, i, list);
(*i)++;
return (flag);
}
t_flag ft_parse_flag(const char *format, size_t *i, va_list list, t_flag flag)
{
while (!(ft_strrchr("cspdiuxoXfegUZ%", format[*i])) && format[*i])
{
if (format[*i] == '0')
flag = ft_parse_zero(format, i, list, flag);
else if ((format[*i] >= '1' && format[*i] <= '9')
|| format[*i] == '-' || format[*i] == '*')
flag = ft_parse_minus(format, i, list, flag);
else if (format[*i] == '+')
flag = ft_parse_plus(format, i, list, flag);
else if (format[*i] == ' ')
flag = ft_parse_space(format, i, list, flag);
else if (format[*i] == '.')
flag = ft_parse_dot(format, i, list, flag);
else if (format[*i] == '#')
{
flag.hash = 1;
(*i)++;
}
else if (format[*i] == 'l' || format[*i] == 'h'
|| format[*i] == 'L' || format[*i] == 'j' || format[*i] == 'z')
flag = ft_parse_len(format, i, list, flag);
else
(*i)++;
}
return (flag);
}
int ft_parser(const char *format, size_t *i, va_list list)
{
t_flag flag;
flag = (t_flag){ 0, 0, 0, 0, 0, 0, 0, 0,
{ 0, 0, 0, 0, 0, 1}, { 0, 0, 0, 0, 0 } };
flag = ft_parse_flag(format, i, list, flag);
return (print_type(format, i, list, flag));
}
int ft_sprintf(const char *format, va_list list)
{
size_t i;
int len;
len = 0;
i = 0;
while (format[i])
{
while (format[i] && format[i] != '%')
{
write(1, &format[i], 1);
i++;
len++;
}
if (format[i] == '%' && format[i + 1])
{
i++;
len += ft_parser(format, &i, list);
}
else if (format[i + 1] == '\0')
i++;
}
return (len);
}
int ft_printf(const char *format, ...)
{
int len;
va_list list;
len = 0;
va_start(list, format);
len = ft_sprintf(format, list);
va_end(list);
return (len);
}
|
C | #include <stdio.h>
int n;
int sqrt(int n, int a)
{
int ret = 1;
while (a--) {
ret *= n;
}
return ret;
}
int main(void)
{
//freopen("input.txt", "r", stdin);
int a, b;
while (scanf("%d", &n) != EOF) {
int div = sqrt(10, n / 2);
for (int i = 0; i < sqrt(10, n); i++) {
a = i / div;
b = i % div;
if ((a + b) * (a + b) == i) {
if (n == 2)
printf("%02d\n", i);
else if (n == 4)
printf("%04d\n", i);
else if (n == 6)
printf("%06d\n", i);
else if (n == 8)
printf("%08d\n", i);
}
}
}
return 0;
}
|
C | #include "src.h"
void my_printf_o(va_list listarg)
{
int fd;
fd = va_arg(listarg, int);
my_putnbr_base(fd, "01234567");
}
void my_printf_u(va_list listarg)
{
unsigned int fd;
fd = va_arg(listarg, unsigned long int);
my_putnbr_base(my_put_nbr_unsigned(fd), "0123456789");
}
void my_printf_x(va_list listarg)
{
int fd;
fd = va_arg(listarg, int);
my_putnbr_base(fd, "0123456789abcdef");
}
void my_printf_X(va_list listarg)
{
int fd;
fd = va_arg(listarg, int);
my_putnbr_base(fd, "0123456789ABCDEF");
}
void my_printf_b(va_list listarg)
{
int fd;
fd = va_arg(listarg, int);
my_putnbr_base(fd, "01");
} |
C | #include <stdio.h>
#include <stdlib.h>
void swap(int *a, int *b){
int temp = *a;
*a = *b;
*b = temp;
}
/* Questa funzione partiziona l'array A in 3 parti:
1) A[sx..i] contiene tutti gli elementi minori del pivot;
2) A[i+1..j-1] contiene tutti gli elementi uguali al pivot;
3) A[j..dx] contiene tutti gli elementi maggiori del pivot. */
void distribuzione(int A[], int sx, int dx, int* i, int* j) {
// Variabile per scorrere l'array
int s = sx;
// Prendo come pivot l'ultimo elemento dell'array
int pivot = A[dx];
while (s <= dx)
{
if (A[s]<pivot)
swap(&A[sx++], &A[s++]);
else if (A[s]==pivot)
s++;
else if (A[s]>pivot)
swap(&A[s], &A[dx--]);
}
// Aggiorno i e j
*i = sx-1;
*j = s;
}
// Quick Sort basato su 3-way partition
void quicksort(int A[], int sx, int dx) {
// Caso base con 1 o 0 elementi
if(sx>=dx)
return;
int i, j;
// NB: i e j passati per riferimento!
distribuzione(A, sx, dx, &i, &j);
//printf("perno1: %d", i);
//printf("perno2: %d", j);
// Ricorsione su elementi minori del pivot
quicksort(A, sx, i);
// Ricorsione su elementi maggiori del pivot
quicksort(A, j, dx);
}
void stampaArray(int A[], int n) {
for (int i = 0; i < n; ++i)
printf("%d ", A[i]);
printf("\n");
}
int main(void){
int N;
scanf("%i", &N);
int *A = malloc(N*sizeof(int));
for(int i = 0; i < N; i++)
{
scanf("%i", &A[i]);
}
quicksort(A, 0, N-1);
stampaArray(A, N);
return 0;
} |
C | /* Given an interface name and a packet length (optional), prints to stdout
* the maximum number of packets (each within that length) that fits in the
* currently available TX slots. If the packet length is not specified, it
* is assumed that any packet to be transmitted fits within a single netmap
* slot, hence printing the number of available TX slots.
* On error, "-1" is printed.
* Arguments:
* $1 -> interface name
* $2 -> packet length
*/
#include <inttypes.h>
#include <math.h>
#include <net/if.h>
#include <net/netmap.h>
#define NETMAP_WITH_LIBS
#include <net/netmap_user.h>
uint64_t
slots_per_packet(struct netmap_ring *ring, unsigned pkt_len)
{
return (uint64_t)(ceil((double)pkt_len / (double)ring->nr_buf_size));
}
uint64_t
ring_avail_tx_packets(struct netmap_ring *ring, unsigned pkt_len)
{
if (pkt_len == 0) {
return nm_ring_space(ring);
}
return nm_ring_space(ring) / slots_per_packet(ring, pkt_len);
}
uint64_t
nmport_avail_tx_packets(struct nm_desc *nmd, unsigned pkt_len)
{
uint64_t total = 0;
unsigned int i;
for (i = nmd->first_tx_ring; i <= nmd->last_tx_ring; i++) {
struct netmap_ring *ring = NETMAP_TXRING(nmd->nifp, i);
total += ring_avail_tx_packets(ring, pkt_len);
}
return total;
}
int
main(int argc, char **argv)
{
uint64_t avail_tx_packets;
struct nm_desc *nmd;
const char *if_name;
uint64_t pkt_len;
if (argc == 2) {
pkt_len = 0;
} else if (argc == 3) {
pkt_len = atoi(argv[2]);
if (pkt_len == 0) {
printf("-1");
exit(EXIT_FAILURE);
}
} else {
printf("-1");
exit(EXIT_FAILURE);
}
fclose(stderr);
if_name = argv[1];
nmd = nm_open(if_name, NULL, 0, NULL);
if (nmd == NULL) {
printf("-1");
exit(EXIT_FAILURE);
}
avail_tx_packets = nmport_avail_tx_packets(nmd, pkt_len);
printf("%" PRId64, avail_tx_packets);
return 0;
}
|
C | /*!
\file
\brief Various functions for transfering data to/from slave/master memory
\date Started 6/3/2013
\author George
*/
#include "common.h"
/* the working directory; initialized during init */
static char xfer_wdir[BDMPI_WDIR_LEN];
/* disk I/O will be done in chunks of this number of bytes */
#define BDMPI_DISK_CHUNK 131072
/*************************************************************************/
/*! Sets the static working directory. */
/*************************************************************************/
void xfer_setwdir(char *wdir)
{
strcpy(xfer_wdir, wdir);
}
/*************************************************************************/
/*! Returns a globally unique file number. */
/*************************************************************************/
ssize_t xfer_getfnum()
{
static ssize_t nextfnum=1;
nextfnum++;
return ((ssize_t)getpid())*10000000 + nextfnum;
}
/*************************************************************************/
/*! Unlinks the file associated with fnum. */
/*************************************************************************/
void xfer_unlink(ssize_t fnum)
{
//char *fname;
char fname[BDMPI_WDIR_LEN+20];
if (sprintf(fname, "%s/%zd", xfer_wdir, fnum) == -1)
errexit("xfer_unlink: Failed to create filename.\n");
//if (asprintf(&fname, "%s/%zd", xfer_wdir, fnum) == -1)
// errexit("xfer_unlink: Failed to create filename.\n");
unlink(fname);
//free(fname);
return;
}
/*************************************************************************/
/*! Copies data into remote buffer space via scb. */
/*************************************************************************/
void xfer_out_scb(bdscb_t *scb, void *vbuf, size_t count, BDMPI_Datatype datatype)
{
size_t i, dtsize, chunk, len;
char *buf = (char *)vbuf;
dtsize = bdmp_sizeof(datatype);
chunk = scb->size/dtsize;
/* get into a loop copying and storing the data */
for (i=0; i<count; i+=chunk) {
len = (i+chunk < count ? chunk : count - i);
bdscb_wait_empty(scb);
//bdprintf("out_scb: %zd bytes from %p [%zu %zu]\n", len*dtsize, buf+i*dtsize, count, i);
memcpy(scb->buf, buf+i*dtsize, len*dtsize);
bdscb_post_full(scb);
}
return;
}
/*************************************************************************/
/*! Copies data into local buffer space via scb. */
/*************************************************************************/
void xfer_in_scb(bdscb_t *scb, void *vbuf, size_t count, BDMPI_Datatype datatype)
{
size_t i, dtsize, chunk, len;
char *buf = (char *)vbuf;
dtsize = bdmp_sizeof(datatype);
chunk = scb->size/dtsize;
/* get into a loop copying and storing the data */
for (i=0; i<count; i+=chunk) {
len = (i+chunk < count ? chunk : count - i);
bdscb_wait_full(scb);
//bdprintf("in_scb: %zd bytes from %p [%zu %zu]\n", len*dtsize, buf+i*dtsize, count, i);
memcpy(buf+i*dtsize, scb->buf, len*dtsize);
bdscb_post_empty(scb);
}
return;
}
/*************************************************************************/
/*! Copies data into the specified file. */
/*************************************************************************/
void xfer_out_disk(ssize_t fnum, char *buf, size_t count, BDMPI_Datatype datatype)
{
//char *fname;
int fd;
size_t len, size = bdmp_msize(count, datatype);
ssize_t ret;
char fname[BDMPI_WDIR_LEN+20];
if (sprintf(fname, "%s/%zd", xfer_wdir, fnum) == -1)
errexit("xfer_out_disk: Failed to create filename.\n");
//if (asprintf(&fname, "%s/%zd", xfer_wdir, fnum) == -1)
// errexit("xfer_out_disk: Failed to create filename.\n");
if ((fd = open(fname, O_CREAT|O_WRONLY|O_TRUNC, S_IRUSR|S_IWUSR)) == -1)
errexit("xfer_out_disk: Failed to open file %s: %s\n", fname, strerror(errno));
//bdprintf("out_disk: %zu bytes from %p [%zu %zu] %s\n", size, buf, size,
// fnum, fname);
do {
len = (size > BDMPI_DISK_CHUNK ? BDMPI_DISK_CHUNK : size);
ret = gk_write(fd, buf, len);
if (-1 == ret) {
if (EIO != errno && EINTR != errno) {
errexit("[%5d] xfer_out_disk: Write failed: %s (%zd, %zu) (%d) %p\n", \
(int)getpid(), strerror(errno), ret, len, errno, buf);
}
}
else {
buf += ret;
size -= ret;
}
} while (size > 0);
close(fd);
//free(fname);
return;
}
/*************************************************************************/
/*! Copies data from the specified file. */
/*************************************************************************/
void xfer_in_disk(ssize_t fnum, char *buf, size_t count, BDMPI_Datatype datatype,
int rmfile)
{
//char *fname;
int fd;
size_t len, rsize, size = bdmp_msize(count, datatype);
ssize_t ret;
char fname[BDMPI_WDIR_LEN+20];
if (sprintf(fname, "%s/%zd", xfer_wdir, fnum) == -1)
errexit("xfer_in_disk: Failed to create filename.\n");
//if (asprintf(&fname, "%s/%zd", xfer_wdir, fnum) == -1)
// errexit("xfer_in_disk: Failed to create filename.\n");
if ((rsize = gk_getfsize(fname)) == -1)
errexit("[%5d] xfer_in_disk: Error with file: %s [%s]\n", (int)getpid(),
fname, strerror(errno));
if (rsize > size)
errexit("xfer_in_disk: Size of file %s is larger than supplied buffer space: [%zu %zu]\n",
fname, rsize, size);
if ((fd = open(fname, O_RDONLY)) == -1)
errexit("xfer_in_disk: Failed to open file %s: %s\n", fname, strerror(errno));
//bdprintf("in_disk: %zu bytes from %p [%zu %zu]\n", rsize, buf, size, fnum);
size = rsize;
do {
len = (size > BDMPI_DISK_CHUNK ? BDMPI_DISK_CHUNK : size);
ret = gk_read(fd, buf, len);
if (-1 == ret) {
if (EIO != errno && EINTR != errno) {
errexit("[%5d] xfer_in_disk: Read failed: %s (%zd, %zu) (%d) %p\n", \
(int)getpid(), strerror(errno), ret, len, errno, buf);
}
}
else {
buf += ret;
size -= ret;
}
} while (size > 0);
close(fd);
if (rmfile)
unlink(fname);
//free(fname);
return;
}
|
C | #include <stdio.h>
#include <sys/epoll.h>
#include <fcntl.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <unistd.h>
#include <pthread.h>
#include "my_socket.h"
#include "my_err.h"
struct heihei{
char send_name[20];
char recv_name[20];
char mes[1024];
int send_fd;
int recv_fd;
};
struct haha{
int type;
struct heihei data;
};
void *deal(void *hei)
{
int i;
struct haha *p;
p = (struct haha*)hei;
printf("%s\n", p->data.mes);
}
int main()
{
int i;
int ret;
int socklen;
int sock_fd;
int conn_fd;
int nfds;
int kdpfd;
int curfds;
int acceptcont = 0;
struct sockaddr_in seve;
struct sockaddr_in cli;
struct epoll_event ev;
struct epoll_event events[1024];
struct haha hen;
struct haha *hei;
socklen = sizeof(struct sockaddr_in);
sock_fd = my_accept_seve();
kdpfd = epoll_create(1024);
ev.events = EPOLLIN | EPOLLET;
ev.data.fd = sock_fd;
if(epoll_ctl(kdpfd, EPOLL_CTL_ADD, sock_fd, &ev) < 0){
my_err("epoll_ctl", __LINE__);
}
curfds = 1;
while(1){
if((nfds = epoll_wait(kdpfd, events, curfds, -1)) < 0){
my_err("epoll_wait", __LINE__);
}
for(i = 0; i < nfds; i++){
if(events[i].data.fd == sock_fd){
if((conn_fd = accept(sock_fd, (struct sockaddr*)&cli, &socklen)) < 0){
my_err("accept", __LINE__);
}
printf("连接成功\n");
acceptcont++;
if(curfds >= 1024){
fprintf(stderr, "太多的连接了\n");
close(conn_fd);
continue;
}
ev.events = EPOLLIN | EPOLLET;
ev.data.fd = conn_fd;
if(epoll_ctl(kdpfd, EPOLL_CTL_ADD, conn_fd, &ev) < 0){
my_err("epoll_ctl", __LINE__);
}
curfds++;
continue;
}
else if(events[i].events & EPOLLIN){
ret = recv(events[i].data.fd, &hen, sizeof(struct haha), 0);
if(ret < 0){
close(events[i].data.fd);
perror("recv");
continue;
}
hei = (struct haha*)malloc(sizeof(struct haha));
memcpy(hei, &hen, sizeof(struct haha));
pthread_t pid;
pthread_create(&pid, NULL, deal, (void*)hei);
}
}
}
}
|
C | /*
* Operating System Interface
*
* This provides access to useful OS routines for the sandbox architecture.
* They are kept in a separate file so we can include system headers.
*
* Copyright (c) 2011 The Chromium OS Authors.
* SPDX-License-Identifier: GPL-2.0+
*/
#ifndef __OS_H__
#define __OS_H__
#include <linux/types.h>
struct sandbox_state;
/**
* Access to the OS read() system call
*
* \param fd File descriptor as returned by os_open()
* \param buf Buffer to place data
* \param count Number of bytes to read
* \return number of bytes read, or -1 on error
*/
ssize_t os_read(int fd, void *buf, size_t count);
/**
* Access to the OS read() system call with non-blocking access
*
* \param fd File descriptor as returned by os_open()
* \param buf Buffer to place data
* \param count Number of bytes to read
* \return number of bytes read, or -1 on error
*/
ssize_t os_read_no_block(int fd, void *buf, size_t count);
/**
* Access to the OS write() system call
*
* \param fd File descriptor as returned by os_open()
* \param buf Buffer containing data to write
* \param count Number of bytes to write
* \return number of bytes written, or -1 on error
*/
ssize_t os_write(int fd, const void *buf, size_t count);
/**
* Access to the OS lseek() system call
*
* \param fd File descriptor as returned by os_open()
* \param offset File offset (based on whence)
* \param whence Position offset is relative to (see below)
* \return new file offset
*/
off_t os_lseek(int fd, off_t offset, int whence);
/* Defines for "whence" in os_lseek() */
#define OS_SEEK_SET 0
#define OS_SEEK_CUR 1
#define OS_SEEK_END 2
/**
* Access to the OS open() system call
*
* \param pathname Pathname of file to open
* \param flags Flags, like O_RDONLY, O_RDWR
* \return file descriptor, or -1 on error
*/
int os_open(const char *pathname, int flags);
#define OS_O_RDONLY 0
#define OS_O_WRONLY 1
#define OS_O_RDWR 2
#define OS_O_MASK 3 /* Mask for read/write flags */
#define OS_O_CREAT 0100
/**
* Access to the OS close() system call
*
* \param fd File descriptor to close
* \return 0 on success, -1 on error
*/
int os_close(int fd);
/**
* Access to the OS unlink() system call
*
* \param pathname Path of file to delete
* \return 0 for success, other for error
*/
int os_unlink(const char *pathname);
/**
* Access to the OS exit() system call
*
* This exits with the supplied return code, which should be 0 to indicate
* success.
*
* @param exit_code exit code for U-Boot
*/
void os_exit(int exit_code) __attribute__((noreturn));
/**
* Put tty into raw mode to mimic serial console better
*
* @param fd File descriptor of stdin (normally 0)
* @param allow_sigs Allow Ctrl-C, Ctrl-Z to generate signals rather than
* be handled by U-Boot
*/
void os_tty_raw(int fd, bool allow_sigs);
/**
* Acquires some memory from the underlying os.
*
* \param length Number of bytes to be allocated
* \return Pointer to length bytes or NULL on error
*/
void *os_malloc(size_t length);
/**
* Free memory previous allocated with os_malloc()/os_realloc()
*
* This returns the memory to the OS.
*
* \param ptr Pointer to memory block to free
*/
void os_free(void *ptr);
/**
* Reallocate previously-allocated memory to increase/decrease space
*
* This works in a similar way to the C library realloc() function. If
* length is 0, then ptr is freed. Otherwise the space used by ptr is
* expanded or reduced depending on whether length is larger or smaller
* than before.
*
* If ptr is NULL, then this is similar to calling os_malloc().
*
* This function may need to move the memory block to make room for any
* extra space, in which case the new pointer is returned.
*
* \param ptr Pointer to memory block to reallocate
* \param length New length for memory block
* \return pointer to new memory block, or NULL on failure or if length
* is 0.
*/
void *os_realloc(void *ptr, size_t length);
/**
* Access to the usleep function of the os
*
* \param usec Time to sleep in micro seconds
*/
void os_usleep(unsigned long usec);
/**
* Gets a monotonic increasing number of nano seconds from the OS
*
* \return A monotonic increasing time scaled in nano seconds
*/
uint64_t os_get_nsec(void);
/**
* Parse arguments and update sandbox state.
*
* @param state Sandbox state to update
* @param argc Argument count
* @param argv Argument vector
* @return 0 if ok, and program should continue;
* 1 if ok, but program should stop;
* -1 on error: program should terminate.
*/
int os_parse_args(struct sandbox_state *state, int argc, char *argv[]);
/*
* Types of directory entry that we support. See also os_dirent_typename in
* the C file.
*/
enum os_dirent_t {
OS_FILET_REG, /* Regular file */
OS_FILET_LNK, /* Symbolic link */
OS_FILET_DIR, /* Directory */
OS_FILET_UNKNOWN, /* Something else */
OS_FILET_COUNT,
};
/** A directory entry node, containing information about a single dirent */
struct os_dirent_node {
struct os_dirent_node *next; /* Pointer to next node, or NULL */
ulong size; /* Size of file in bytes */
enum os_dirent_t type; /* Type of entry */
char name[0]; /* Name of entry */
};
/**
* Get a directionry listing
*
* This allocates and returns a linked list containing the directory listing.
*
* @param dirname Directory to examine
* @param headp Returns pointer to head of linked list, or NULL if none
* @return 0 if ok, -ve on error
*/
int os_dirent_ls(const char *dirname, struct os_dirent_node **headp);
/**
* Get the name of a directory entry type
*
* @param type Type to cehck
* @return string containing the name of that type, or "???" if none/invalid
*/
const char *os_dirent_get_typename(enum os_dirent_t type);
/**
* Get the size of a file
*
* @param fname Filename to check
* @return size of file, or -1 if an error ocurred
*/
ssize_t os_get_filesize(const char *fname);
/**
* Write a character to the controlling OS terminal
*
* This bypasses the U-Boot console support and writes directly to the OS
* stdout file descriptor.
*
* @param ch Character to write
*/
void os_putc(int ch);
/**
* Write a string to the controlling OS terminal
*
* This bypasses the U-Boot console support and writes directly to the OS
* stdout file descriptor.
*
* @param str String to write (note that \n is not appended)
*/
void os_puts(const char *str);
/**
* Write the sandbox RAM buffer to a existing file
*
* @param fname Filename to write memory to (simple binary format)
* @return 0 if OK, -ve on error
*/
int os_write_ram_buf(const char *fname);
/**
* Read the sandbox RAM buffer from an existing file
*
* @param fname Filename containing memory (simple binary format)
* @return 0 if OK, -ve on error
*/
int os_read_ram_buf(const char *fname);
/**
* Jump to a new executable image
*
* This uses exec() to run a new executable image, after putting it in a
* temporary file. The same arguments and environment are passed to this
* new image, with the addition of:
*
* -j <filename> Specifies the filename the image was written to. The
* calling image may want to delete this at some point.
* -m <filename> Specifies the file containing the sandbox memory
* (ram_buf) from this image, so that the new image can
* have access to this. It also means that the original
* memory filename passed to U-Boot will be left intact.
*
* @param dest Buffer containing executable image
* @param size Size of buffer
*/
int os_jump_to_image(const void *dest, int size);
#endif
|
C | // Module for interfacing with file system
#include "c_string.h"
#include "c_types.h"
#include "flash_fs.h"
#include "lauxlib.h"
#include "lualib.h"
#include "modules.h"
#include "platform.h"
#include "vfs.h"
static volatile int file_fd = FS_OPEN_OK - 1;
// Lua: open(filename, mode)
static int file_open(lua_State *L)
{
size_t len;
if (file_fd)
{
vfs_close(file_fd);
file_fd = 0;
}
const char *fname = luaL_checklstring(L, 1, &len);
const char *basename = vfs_basename(fname);
luaL_argcheck(L, strlen(basename) <= 32 && strlen(fname) == len, 1, "filename invalid");
const char *mode = luaL_optstring(L, 2, "r");
file_fd = vfs_open(fname, mode);
if (!file_fd)
{
lua_pushnil(L);
}
else
{
lua_pushboolean(L, 1);
}
return 1;
}
// Lua: close()
static int file_close(lua_State *L)
{
if (file_fd)
{
vfs_close(file_fd);
file_fd = 0;
NODE_DBG("file close successfully\n");
}
return 0;
}
// Lua: format()
static int file_format(lua_State *L)
{
file_close(L);
if (!vfs_format())
{
NODE_ERR("\n*** ERROR ***: unable to format. FS might be compromised.\n");
NODE_ERR("It is advised to re-flash the NodeMCU image.\n");
luaL_error(L, "Failed to format file system");
}
else
{
NODE_ERR("format done.\n");
}
return 0;
}
// Lua: list()
static int file_list(lua_State *L)
{
vfs_dir *dir;
vfs_item *item;
if ((dir = vfs_opendir("")))
{
lua_newtable(L);
while ((item = vfs_readdir(dir)))
{
lua_pushinteger(L, vfs_item_size(item));
lua_setfield(L, -2, vfs_item_name(item));
vfs_closeitem(item);
}
vfs_closedir(dir);
return 1;
}
return 0;
}
static int file_seek(lua_State *L)
{
static const int mode[] = {VFS_SEEK_SET, VFS_SEEK_CUR, VFS_SEEK_END};
static const char *const modenames[] = {"set", "cur", "end", NULL};
if (!file_fd)
return luaL_error(L, "open a file first");
int op = luaL_checkoption(L, 1, "cur", modenames);
long offset = luaL_optlong(L, 2, 0);
op = vfs_lseek(file_fd, offset, mode[op]);
if (op < 0)
lua_pushnil(L); /* error */
else
lua_pushinteger(L, vfs_tell(file_fd));
return 1;
}
// Lua: remove(filename)
static int file_remove(lua_State *L)
{
size_t len;
const char *fname = luaL_checklstring(L, 1, &len);
const char *basename = vfs_basename(fname);
luaL_argcheck(L, strlen(basename) <= 32 && strlen(fname) == len, 1, "filename invalid");
file_close(L);
vfs_remove((char *)fname);
return 0;
}
// Lua: flush()
static int file_flush(lua_State *L)
{
if (!file_fd)
return luaL_error(L, "open a file first");
if (vfs_flush(file_fd) == 0)
lua_pushboolean(L, 1);
else
lua_pushnil(L);
return 1;
}
#if 0
// Lua: check()
static int file_check( lua_State* L )
{
file_close(L);
lua_pushinteger(L, fs_check());
return 1;
}
#endif
// Lua: rename("oldname", "newname")
static int file_rename(lua_State *L)
{
size_t len;
if (file_fd)
{
vfs_close(file_fd);
file_fd = 0;
}
const char *oldname = luaL_checklstring(L, 1, &len);
const char *basename = vfs_basename(oldname);
luaL_argcheck(L, strlen(basename) <= 32 && strlen(oldname) == len, 1, "filename invalid");
const char *newname = luaL_checklstring(L, 2, &len);
basename = vfs_basename(newname);
luaL_argcheck(L, strlen(basename) <= 32 && strlen(newname) == len, 2, "filename invalid");
if (0 <= vfs_rename(oldname, newname))
{
lua_pushboolean(L, 1);
}
else
{
lua_pushboolean(L, 0);
}
return 1;
}
// Lua: fsinfo()
static int file_fsinfo(lua_State *L)
{
u32_t total, used;
if (vfs_fsinfo("", &total, &used))
{
return luaL_error(L, "file system failed");
}
NODE_DBG("total: %d, used:%d\n", total, used);
if (total > 0x7FFFFFFF || used > 0x7FFFFFFF || used > total)
{
return luaL_error(L, "file system error");
}
lua_pushinteger(L, total - used);
lua_pushinteger(L, used);
lua_pushinteger(L, total);
return 3;
}
// g_read()
static int file_g_read(lua_State *L, int n, int16_t end_char)
{
if (n <= 0 || n > LUAL_BUFFERSIZE)
n = LUAL_BUFFERSIZE;
if (end_char < 0 || end_char > 255)
end_char = EOF;
luaL_Buffer b;
if (!file_fd)
return luaL_error(L, "open a file first");
luaL_buffinit(L, &b);
char *p = luaL_prepbuffer(&b);
int i;
n = vfs_read(file_fd, p, n);
for (i = 0; i < n; ++i)
if (p[i] == end_char)
{
++i;
break;
}
if (i == 0)
{
luaL_pushresult(&b); /* close buffer */
return (lua_objlen(L, -1) > 0); /* check whether read something */
}
vfs_lseek(file_fd, -(n - i), VFS_SEEK_CUR);
luaL_addsize(&b, i);
luaL_pushresult(&b); /* close buffer */
return 1; /* read at least an `eol' */
}
// Lua: read()
// file.read() will read all byte in file
// file.read(10) will read 10 byte from file, or EOF is reached.
// file.read('q') will read until 'q' or EOF is reached.
static int file_read(lua_State *L)
{
unsigned need_len = LUAL_BUFFERSIZE;
int16_t end_char = EOF;
size_t el;
if (lua_type(L, 1) == LUA_TNUMBER)
{
need_len = (unsigned)luaL_checkinteger(L, 1);
if (need_len > LUAL_BUFFERSIZE)
{
need_len = LUAL_BUFFERSIZE;
}
}
else if (lua_isstring(L, 1))
{
const char *end = luaL_checklstring(L, 1, &el);
if (el != 1)
{
return luaL_error(L, "wrong arg range");
}
end_char = (int16_t)end[0];
}
return file_g_read(L, need_len, end_char);
}
// Lua: readline()
static int file_readline(lua_State *L) { return file_g_read(L, LUAL_BUFFERSIZE, '\n'); }
// Lua: write("string")
static int file_write(lua_State *L)
{
if (!file_fd)
return luaL_error(L, "open a file first");
size_t l, rl;
const char *s = luaL_checklstring(L, 1, &l);
rl = vfs_write(file_fd, s, l);
if (rl == l)
lua_pushboolean(L, 1);
else
lua_pushnil(L);
return 1;
}
// Lua: writeline("string")
static int file_writeline(lua_State *L)
{
if (!file_fd)
return luaL_error(L, "open a file first");
size_t l, rl;
const char *s = luaL_checklstring(L, 1, &l);
rl = vfs_write(file_fd, s, l);
if (rl == l)
{
rl = vfs_write(file_fd, "\n", 1);
if (rl == 1)
lua_pushboolean(L, 1);
else
lua_pushnil(L);
}
else
{
lua_pushnil(L);
}
return 1;
}
// Module function map
const LUA_REG_TYPE file_map[] = {{LSTRKEY("list"), LFUNCVAL(file_list)},
{LSTRKEY("open"), LFUNCVAL(file_open)},
{LSTRKEY("close"), LFUNCVAL(file_close)},
{LSTRKEY("write"), LFUNCVAL(file_write)},
{LSTRKEY("writeline"), LFUNCVAL(file_writeline)},
{LSTRKEY("read"), LFUNCVAL(file_read)},
{LSTRKEY("readline"), LFUNCVAL(file_readline)},
{LSTRKEY("format"), LFUNCVAL(file_format)},
#if defined(BUILD_SPIFFS) && !defined(BUILD_WOFS)
{LSTRKEY("remove"), LFUNCVAL(file_remove)},
{LSTRKEY("seek"), LFUNCVAL(file_seek)},
{LSTRKEY("flush"), LFUNCVAL(file_flush)},
//{ LSTRKEY( "check" ), LFUNCVAL( file_check ) },
{LSTRKEY("rename"), LFUNCVAL(file_rename)},
{LSTRKEY("fsinfo"), LFUNCVAL(file_fsinfo)},
#endif
{LNILKEY, LNILVAL}};
LUALIB_API int luaopen_file(lua_State *L)
{
#if LUA_OPTIMIZE_MEMORY > 0
return 0;
#else
luaL_register(L, LUA_FILELIBNAME, file_map);
return 1;
#endif
}
|
C | //Adds access to libraries sdio and cs50 for certain features
#include <stdio.h>
#include <cs50.h>
//helps start off any program
int main(void)
//Start of program
{
//Allows assignment of a custom name by the user as the variable equal to answer
string answer = get_string("What is your name? ");
//displays output with custom variable for the name as user inputs previously
printf("hello, %s\n", answer);
//End of program
}
|
C | /*
output.txt should have:
foo:s,w,y,x
*/
void main()
{
int z = 12;//1
int x;//2
int y;//3
int w;//4
int r = 0, s;//5 6
// "x" should be printed
printf( "%d\n", x == 1 ? 12 : 13 );//7
// "y" should be printed:
printf( "%d\n", z == 12 ? y : 13 );//8
// "w" and "s" should be printed:
printf( "%d\n", z == 12 ? (w * 12 + 43) : (r + s) );//9
}
|
C | #pragma once
#include<stdio.h>
#include<stdlib.h>
#include <string.h>
#include<assert.h>
#define MAX 50
typedef struct node
{
int adj;
}node;
typedef struct grap
{
char vertex[MAX];
node arr[MAX][MAX];
int vexnum;
int arcnum;
}grap;
typedef struct Queue
{
char a[MAX];
int front;
int rear;
int size;
}Queue;
//ʼ
void InitGrap(grap* pg);
//
void ScanfGrap(grap* pg);
//
void PrintfGrap(grap* pg);
//DFS
void FindStartDFS(grap* pg);
//BFS
void FindStartBFS(grap* pg);
void InitQueue(Queue* pq);
void EnterQueue(Queue* pq,char x);
char DeleteQueue(Queue* pq);
|
C | /**
* @file
* @brief Tests if System Timer's IRQ are handling when thread is running.
*
* @details There was a problme on STM32 platform:
* when after context switch timers, interrupts become disabled
* inside the next thread.
*
* @date 06.06.18
* @author Alex Kalmuk
*/
#include <errno.h>
#include <unistd.h>
#include <embox/test.h>
#include <util/err.h>
#include <kernel/thread.h>
#include <hal/clock.h>
#define DELAY 1000000
#define ITERS 10
EMBOX_TEST_SUITE("test for systimer irq handling when thread is running");
static int thread_res[2];
static int delay_spinning(int volatile delay) {
clock_t start = clock_sys_ticks();
while (delay--)
;
return clock_sys_ticks() - start;
}
static void *thread_hnd(void *arg) {
int val;
int i = 0;
for (i = 0; i < ITERS; i++) {
val = delay_spinning(DELAY);
if (!val) {
break;
}
}
*(int *) arg = val;
return NULL;
}
TEST_CASE("System timer interrupts must not be disabled after thread_switch") {
struct thread *t1, *t2;
int val;
/* Check first if clocks are updating during time */
val = delay_spinning(DELAY);
test_assert_not_equal(val, 0);
t1 = thread_create(0, thread_hnd, &thread_res[0]);
test_assert_zero(err(t1));
t2 = thread_create(0, thread_hnd, &thread_res[1]);
test_assert_zero(err(t2));
test_assert_zero(thread_join(t1, NULL));
test_assert_not_equal(thread_res[0], 0);
test_assert_zero(thread_join(t2, NULL));
test_assert_not_equal(thread_res[1], 0);
}
|
C | int climbStairs(int n){
if (n == 1) return 1;
int* dp = (int*)malloc(sizeof(int) * (n + 1));
dp[1] = 1;
dp[2] = 2;
for (int i = 3; i < n + 1; ++i) {
dp[i] = dp[i - 1] + dp[i - 2];
}
int sum = dp[n];
free(dp);
return sum;
}
|
C | /*************************************************************************
> File Name: getHostname.c
> Author:wuhonglei
> Mail:[email protected]
> Created Time: Sat 31 Oct 2015 10:35:33 AM CST
> Description:virConnectGetHostname 获得主机(Dom0)的名字
************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <libvirt/libvirt.h>
int main(int argc, char *argv[])
{
virConnectPtr conn;
char *host;
conn = virConnectOpen("xen:///");
if (conn == NULL) {
fprintf(stderr, "Failed to open connection to xen:///\n");
return 1;
}
host = virConnectGetHostname(conn);
fprintf(stdout, "Hostname:%s\n", host);
free(host);
virConnectClose(conn);
return 0;
}
|
C | #include<string.h>
#include<stdio.h>
#define fbuf(c) while((c=getchar())!='\n' && c!=' ' && c!='#')
void* fsearch(void*a,void*b,int ele_size,int n);
int main()
{
int str1[256]={0,},str2[256]={0,};
printf("Get two string_>");
char c=0;
int i=0,j=0;
scanf("%s",str1);
fbuf(c);
scanf("%s",str2+j);
fbuf(c);
//fgets(str1,256,stdin);
//str1[strlen(str1)-1]=0;
//fgets(str2,256,stdin);
//str2[strlen(str2)-1]=0;
int* chr=(int*)fsearch(str1,str2,sizeof(int),1+j);
if(chr!=NULL)
printf("find:%d\n",*chr);
else
printf("NULL\n");
return 0;
}
void* fsearch(void* a, void* b, int ele_size, int n)
{
void*buf;
for(int i=0;i<n;i++)
{
buf=(char*)b+i*ele_size;
if(memcmp(buf,a,ele_size)==0)
return buf;
}
return NULL;
}
|
C | #include<stdio.h>
#include<conio.h>
main(){
char name[1005], school[1005], tel[1005];
int age;
printf("Enter your name:\n");
gets(name);
printf("Enter your age:\n");
scanf("%d",&age);
printf("Enter your school:\n");
scanf(" %s", &school);
printf("Enter your telephone number:\n");
scanf(" %s", &tel);
printf("Your name is %s.\n", name);
printf("You are %d years old.\n", age);
printf("The school you attend is %s.\n", school);
printf("Your telephone number is %s.\n", tel);
getch();
}
|
C | //
// Created by Shahak on 06/06/2017.
//
#include "company.h"
#include "utility.h"
#include <stdlib.h>
#include <assert.h>
#include <string.h>
#define INVALID_PARAMETER -1
struct Company_t {
char *email;
TechnionFaculty FacultyOfCompany;
Set company_rooms;
};
Company companyCreate(char *company_email, TechnionFaculty Faculty,
CompanyErrorCode *CompanyError) {
assert(NULL != company_email);
if (NULL == company_email || !isEmailValid(company_email) ||
!isFacultyValid(Faculty)) {
*CompanyError = COMPANY_INVALID_PARAMETER;
return NULL;
}
Company company = malloc((size_t) sizeof(*company));
if (NULL == company) {
*CompanyError = COMPANY_OUT_OF_MEMORY;
return NULL;
}
company->email = malloc((size_t) sizeof(char) * strlen(company_email));
if (NULL == company->email) {
free(company);
*CompanyError = COMPANY_OUT_OF_MEMORY;
return NULL;
}
strcpy(company->email, company_email);
company->FacultyOfCompany = Faculty;
company->company_rooms = setCreate(roomCopyElement, roomFreeElement,
roomCompareElements);
*CompanyError = COMPANY_SUCCESS;
return company;
}
CompanyErrorCode companyDestroy(Company company) {
if (NULL == company) {
return COMPANY_INVALID_PARAMETER;
}
setDestroy(company->company_rooms);
free(company->email);
free(company);
return COMPANY_SUCCESS;
}
CompanyErrorCode companyAddRoom(Company company, char *company_email,
int room_id, int price, int num_ppl,
int opening_time, int closing_time,
int difficulty) {
assert(NULL != company && NULL != company_email && NULL != working_hrs);
RoomErrorCode RoomError;
Room room = roomCreate(company_email, room_id, price, num_ppl, opening_time,
closing_time, difficulty, &RoomError);
if (RoomError == ROOM_INVALID_PARAMETER) {
return COMPANY_INVALID_PARAMETER;
} else if (RoomError == ROOM_OUT_OF_MEMORY) {
return COMPANY_OUT_OF_MEMORY;
}
SetResult AddResult = setAdd(company->company_rooms, room);
if (AddResult == SET_NULL_ARGUMENT) {
roomDestroy(room);
return COMPANY_INVALID_PARAMETER;
} else if (AddResult == SET_ITEM_ALREADY_EXISTS) {
roomDestroy(room);
return COMPANY_ROOM_ALREADY_EXISTS;
} else if (AddResult == SET_OUT_OF_MEMORY) {
roomDestroy(room);
return COMPANY_OUT_OF_MEMORY;
}
return COMPANY_SUCCESS;
}
CompanyErrorCode companyRemoveRoom(Company company, Room room) {
if (NULL == company || NULL == room) {
return COMPANY_INVALID_PARAMETER;
}
SetResult RemoveResult = setRemove(company->company_rooms, room);
if (RemoveResult == SET_NULL_ARGUMENT) {
return COMPANY_INVALID_PARAMETER;
}
return COMPANY_SUCCESS;
}
int companyCompareElements(SetElement company_1, SetElement company_2) {
if (NULL == company_1 || NULL == company_2) {
return INVALID_PARAMETER;
//TODO gotta make sure that -1 won't be a problem
}
Company ptr1 = company_1, ptr2 = company_2;
return (strcmp(ptr1->email, ptr2->email) );
}
void companyFreeElement(SetElement company) {
if (NULL == company) {
return;
}
companyDestroy(company);
}
SetElement companyCopyElement(SetElement src_company) {
if (NULL == src_company) {
return NULL;
}
Company ptr = src_company; //to make the code clearer
CompanyErrorCode CopyResult;
Company company = companyCreate(ptr->email, ptr->FacultyOfCompany,
&CopyResult);
if (CopyResult == COMPANY_OUT_OF_MEMORY ||
CopyResult == COMPANY_INVALID_PARAMETER) {
return NULL;
}
return company;
}
char* companyGetEmail (Company company, CompanyErrorCode *CompanyError) {
if (NULL == company) {
*CompanyError = COMPANY_INVALID_PARAMETER;
return NULL;
}
char *output = malloc((size_t) sizeof(char) * strlen(company->email));
if (NULL == output) {
*CompanyError = COMPANY_OUT_OF_MEMORY;
return NULL;
}
strcpy(output, company->email);
*CompanyError = COMPANY_SUCCESS;
return output;
}
TechnionFaculty companyGetFaculty(Company company,
CompanyErrorCode *CompanyError) {
if (NULL == company) {
*CompanyError = COMPANY_INVALID_PARAMETER;
return UNKNOWN;
}
*CompanyError = COMPANY_SUCCESS;
return company->FacultyOfCompany;
}
Room companyFindRoom(Company company, int room_id,
CompanyErrorCode *CompanyError) {
if (NULL == company || room_id <= 0) {
*CompanyError = COMPANY_INVALID_PARAMETER;
return NULL;
}
Room room_iterator = setGetFirst(company->company_rooms);
//TODO should we check NULL?
while (NULL != room_iterator) {
RoomErrorCode RoomError;
bool isEqual = isRoomID(room_iterator, room_id, &RoomError);
if (RoomError == ROOM_INVALID_PARAMETER) {
*CompanyError = COMPANY_INVALID_PARAMETER;
return NULL;
}
if (isEqual) {
*CompanyError = COMPANY_SUCCESS;
return room_iterator;
}
room_iterator = setGetNext(company->company_rooms);
}
*CompanyError = COMPANY_ROOM_DOES_NOT_EXIST;
return NULL;
}
bool isCompanyEmailEqual(Company company, char *email,
CompanyErrorCode *CompanyError) {
if (NULL == company || NULL == email) {
*CompanyError = COMPANY_INVALID_PARAMETER;
return false;
}
*CompanyError = COMPANY_SUCCESS;
if (strcmp(company->email, email) == 0) {
return true;
}
return false;
}
|
C | #include <stdio.h>
int main ()
{
double k,total,result;
double i = 1;
printf("Digite um valor para k\n");
scanf("%lf",&k);
while(1)
{
total = 1/i;
result += total;
//printf("%lf\n",result);
if (result >= k)
{
printf("%.2lf\n",i);
break;
}
i ++;
}
return 0;
} |
C | #include <stdio.h>
int main(void) {
char *s = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz+/0123456789";
char *str = "pqrst";
int l=5;
int j=0;
int t;
int n;
int n1;
if(l%3 == 0)
{
while(str[j]!='\0')
{
if(j%3==0)
{
t=2;
n=(int)str[j];
printf("%c ",s[n>>t]);
}
else if(j%3==1)
{
t=4;
n=(int)str[j];
n1=(int)str[j-1];
printf("%c ",(s[((n>>t)|(n1<<t))&63]));
n1=(int)str[j+1];
printf("%c ",(s[((n<<2)|(n1>>6))&63]));
}
else if(j%3==2)
{
n=(int)str[j];
printf("%c ",s[(n&63)]);
}
j++;
}
}
else if(l%3==1)
{
while(str[j]!='\0')
{
if(j%3==0)
{
t=2;
n=(int)str[j];
printf("%c ",s[n>>t]);
}
else if(j%3==1)
{
t=4;
n=(int)str[j];
n1=(int)str[j-1];
printf("%c ",(s[((n>>t)|(n1<<t))&63]));
n1=(int)str[j+1];
printf("%c ",(s[((n<<2)|(n1>>6))&63]));
}
else if(j%3==2)
{
n=(int)str[j];
printf("%c ",s[(n&63)]);
}
if(str[j+1]=='\0')
{
n=(int)str[j];
printf("%c ",s[(n<<4)&63]);
}
j++;
}
printf(" = = ");
}
else if(l%3==2)
{
while(str[j]!='\0')
{
if(j%3==0)
{
t=2;
n=(int)str[j];
printf("%c ",s[n>>t]);
}
else if(j%3==1)
{
t=4;
n=(int)str[j];
n1=(int)str[j-1];
printf("%c ",(s[((n>>t)|(n1<<t))&63]));
n1=(int)str[j+1];
printf("%c ",(s[((n<<2)|(n1>>6))&63]));
}
else if(j%3==2)
{
n=(int)str[j];
printf("%c ",s[(n&63)]);
}
j++;
}
printf("= ");
}
return 0;
}
|
C | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <unistd.h>
#include "structure.h"
#include "utilities.h"
#include "lyrics_io.h"
//Contains functions pertaining to file i/o
void readLinesToStructure(structure *s, char *filename, int numLines){ //reads untagged lines from file into structure object
FILE *fp;
numLines = getNumLines(filename);
fp = fopen(filename,"r");
fprintf(stderr,"Now parsing '%s'\n",filename);
char *inputLine = malloc(sizeof(char)*256);
while(fgets(inputLine,512,fp) != NULL){
char *temp = malloc(sizeof(char)*512);
strcpy(temp,inputLine);
addLine(s,newLine(temp));
}
fclose(fp);
}
void parseLines(structure *s, char *filename, int numLines){ //tags untagged lines in structure object by feeding them into Parsey McParseFace
FILE *fp;
char *inputLine = malloc(sizeof(char)*512);
int currLine = 1;
for(int i = 0;i<s->lineCount;i++){
if(s->lines[i]->words[0] != '\n'){
char *parsed = makeParseable(toLower(s->lines[i]->words));
fprintf(stderr,"Parsing line %d of %d...\n",currLine,numLines);
currLine++;
system(parsed);
fp = fopen("tmp/output.txt","r"); //if you change the location or name in this file, make sure to also change the corresponding
char *temp = malloc(sizeof(char)*512); //entry in models/syntaxnet/syntaxnet/models/parsey_mcparseface/context.pbtxt
fgets(inputLine,512,fp);
strcpy(temp,inputLine);
s->lines[i]->pos = temp;
fclose(fp);
}
}
}
void writeStructToFile(structure *s, char *filename, int numLines, char ***words, char ***rhymes){ //writes structure to .txt file in madlyrics/structs/
char *path = malloc(sizeof(char)*128);
strcpy(path,"structs/");
filename += 8; //removes first 8 chars from filename, which is always "corpora/"
strcat(path,filename);
FILE *outputFile = fopen(path,"w");
char *temp = malloc(sizeof(char)*128);
char *str = malloc(sizeof(char)*128); //holds data for each word that will be printed to outfile
int i = 0;
while(s->lines[i] != NULL){
char **curr = malloc(sizeof(char *)*64);
strToArr(s->lines[i]->pos,curr);
strcpy(str,"");
int j = 0;
while(curr[j] != NULL){
removeNewlines(curr[j]);
if(!ispunct(getPosFromTaggedString(curr[j])[0])){
sprintf(temp,"%s_%d_%s ",getPosFromTaggedString(curr[j]),
isInCharArr(*words,getWordFromTaggedString(curr[j])),
(*rhymes)[isInCharArr(*words,getWordFromTaggedString(curr[j]))]
); // format: POS_WORDID_RHYMEID
strcat(str,temp);
}
else{
strcat(str,(curr[j]));
strcat(str," ");
}
j++;
}
removeNewlines(str);
fprintf(outputFile,"%s\n",str);
i++;
}
fprintf(stderr,"Saved structure to structs/%s.\n",filename);
fclose(outputFile);
}
int updatePosLists(structure *s){ //checks if each word/POS combination is present in POS lists found in madlyrics/lists, updates corresponding list
// if not present. Returns number of new entries added to lists (int).
char *path = malloc(sizeof(char)*128);
char **wordsArr = malloc(sizeof(char *)*64);
char *word = malloc(sizeof(char )*256);
FILE *dest;
int i = 0;
int newEntries = 0;
while(s->lines[i] != NULL){
strToArr(removeUnderscores(s->lines[i]->pos),wordsArr); // evenly sized array with format (word) (pos)
int l = 0;
while(wordsArr[l] != NULL){
strcpy(word,wordsArr[l]);
if(isAlnum(word)){
strcpy(path,"lists/");
strcat(path,cleanStr(wordsArr[l+1]));
strcat(path,".txt");
if(!isInFile(word,path)){
dest = fopen(path,"a");
fprintf(dest,"%s\n",word);
fclose(dest);
newEntries++;
}
}
l+=2;
}
i++;
}
return newEntries;
}
void findRhymeScheme(structure *s, char *filename,int numLines){
char **currentLine = malloc(sizeof(char *)*256);
char **wordsArr = malloc(sizeof(char *)*256);
int size = 0;
int capacity = 256;
int i = 0;
while(s-> lines[i] != NULL){
strToArr(removeUnderscores(s->lines[i]->pos),currentLine);
int j = 0;
while(currentLine[j] != NULL){
if(isInCharArr(wordsArr,currentLine[j]) == -1 && !ispunct(currentLine[j][strlen(currentLine[j])-1])){
wordsArr[size] = malloc(sizeof(char)*256);
strcpy(wordsArr[size],currentLine[j]);
size++;
}
if(size == capacity){
wordsArr = realloc(wordsArr,sizeof(char *)*(capacity *2));
capacity *= 2;
}
j += 2;
}
i++;
}
char **rhymeArr = malloc(sizeof(char *) * 256);
char *curr = malloc(sizeof(char)*256);
int k = 0;
while(wordsArr[k] != NULL){
rhymeArr[k] = malloc(sizeof(char)*256);
strcpy(curr,getRhymeId(wordsArr[k]));
if(strcmp(curr,"?") == 0 || isInCharArr(rhymeArr,curr) == -1 ){
strcpy(rhymeArr[k],curr);
}
else{
sprintf(curr, "%d", isInCharArr(rhymeArr,curr));
strcpy(rhymeArr[k],curr);
}
removeSpaces(wordsArr[k]);
k++;
}
int z = 0;
while(rhymeArr[z] != NULL){
if(!isNumber(rhymeArr[z])){
sprintf(rhymeArr[z],"%d",z); //if it's the first occurence of a rhyme, replace rhyme ID with index
}
removeSpaces(rhymeArr[z]);
z++;
}
writeStructToFile(s,filename,numLines,&wordsArr,&rhymeArr);
}
char *getRhymeId(char *str){ //gets rhyme ID from madlyrics/dicts/editedRhymeDict.csv that corresponds to given word
FILE *fp = fopen("dicts/editedRhymeDict.csv","r");
char **results = malloc(sizeof(char *)*32);
int size = 0;
char *temp = malloc(sizeof(char)*256);
char *curr = malloc(sizeof(char)*256);
while(fgets(temp, 128,fp) != NULL){
if(strstr(temp,toUpper(str)) != NULL){ // if match is found
strcpy(curr,getWordFromDictEntry(temp));
if(strcmp(toUpper(str),curr) == 0){ //if word entry matches str exactly
results[size] = malloc(sizeof(char)*256);
strcpy(results[size],getRhymeIdFromDictEntry(temp));
size++;
}
}
}
fclose(fp);
//printCharArr(results);
if(results[0] != NULL){
return results[rand() % (sizeof(results) / sizeof(results[0]))]; //returns random entry in array
}
else{
return "?";
}
}
|
C | #define _GNU_SOURCE
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <pthread.h>
#include <dirent.h>
#include <regex.h>
pthread_mutex_t print_mutex;
pthread_mutex_t running_threads_mutex;
pthread_cond_t running_threads_cond;
int max_thread_num; // Constant during program
int running_threads = 1; // To indicate how many call to the file_grep func are running
// (Starts with 1 representing the inital thread that runs main())
regex_t g_pattern; // REGEX pattern to search
// Find occurences of the global pattern in a file
void *file_grep(void *thread_arg)
{
char *path = (char *) thread_arg;
// Variable inicialization
FILE *file = fopen(path, "r");
int total_line_num = 0;
ssize_t line_lenght = 0;
int c;
// Check number of lines in FILE
while ((c = fgetc(file)) != -1)
{
if (c == '\n')
total_line_num++;
}
// Array representing lines where the patter occurs
int regex_lines[total_line_num];
rewind(file);
int curr_line = 0;
int i = 0;
// Searching for patterns in each line and storing lines that have pattern
while (line_lenght != -1)
{
char *line;
size_t n = 0;
line_lenght = getline(&line, &n, file);
int regex_exec = regexec(&g_pattern, line, 0, 0, 0);
free(line);
// We just need to know if line has a match
if (regex_exec != 0)
{
curr_line++;
continue;
}
regex_lines[i] = curr_line;
curr_line++;
i++;
}
// Printing in order
pthread_mutex_lock(&print_mutex);
for (int j = 0; j < i; j++)
printf("%s: %d\n", path, regex_lines[j]);
pthread_mutex_unlock(&print_mutex);
pthread_mutex_lock(&running_threads_mutex);
running_threads--;
// Maybe put a if test here? (to check if number of thread is greater than 1 or less than maximum)
pthread_cond_signal(&running_threads_cond);
pthread_mutex_unlock(&running_threads_mutex);
fclose(file);
free(path);
pthread_exit(NULL);
}
// Store in new_path the concatenation of a string old_path with a '/' and an append, given its size
void concat_path (char *new_path, char const *old_path, char *append, int append_real_size)
{
char shorter_append[append_real_size + 1];
strncpy(shorter_append, append, append_real_size);
shorter_append[append_real_size] = '\0';
strcpy(new_path, old_path);
strcat(new_path, "/");
strcat(new_path, shorter_append);
}
// Search recursevily into a folder and finds archives to analise
int rec_search (char const *dir_name)
{
DIR *direc = opendir(dir_name);
if (!direc)
{
printf("Error: couldn't open directory %s\n", dir_name);
closedir(direc);
return 0;
}
struct dirent *curr_file;
// Until end of folder is reached
while (curr_file = readdir(direc))
{
// Ignore the '.' and '..' folders
if (strcmp(curr_file->d_name, ".") == 0 || strcmp(curr_file->d_name, "..") == 0)
continue;
struct stat buf;
// Formats path string to current directory
int i = 0;
while (curr_file->d_name[i] != '\0')
i++;
char format_file_name[strlen(dir_name) + i + 5];
concat_path(format_file_name, dir_name, curr_file->d_name, i);
if (stat(format_file_name, &buf) == -1)
{
printf("Error: Couldn't check statistics of file %s\n", curr_file->d_name);
continue;
}
// Checks if file is a regular one
if (S_ISREG(buf.st_mode))
{
// Need to dinamically allocate path string to the file_grep function. It is
// then responsible form dealocating it when finished
char *allocated_file_path = malloc(strlen(format_file_name) + 2);
strcpy(allocated_file_path, format_file_name);
pthread_t file_thread;
// Var running_threads is added when thread is created and subtracted when is destroyed
// Since the recursive search is linear, when the main thread return to the main() function,
// we need that all threads end before we proceed to eliminate glocal mutex and conditional
// variables
pthread_mutex_lock(&running_threads_mutex);
// Waiting for thread number to be below the maximum (as in the program argumment)
while (running_threads >= max_thread_num)
pthread_cond_wait(&running_threads_cond, &running_threads_mutex);
int r = pthread_create(&file_thread, NULL, file_grep, (void *) allocated_file_path);
if (!r)
running_threads++;
pthread_mutex_unlock(&running_threads_mutex);
}
else if (S_ISDIR(buf.st_mode))
rec_search(format_file_name);
else
{
printf("Error: File %s\n is not a directory nor a regular file", curr_file->d_name);
continue;
}
}
closedir(direc);
return 1;
}
int main(int argc, char const *argv[])
{
if (argc < 4)
{
printf("Error: insufficient number of arguments\n");
return 0;
}
int max_thread_arg = atoi(argv[1]);
if (max_thread_arg < 2)
{
printf("Error: minimum number of threads is 2\n");
return 0;
}
const char *string_pattern = argv[2];
char const *path = argv[3];
int pat_res = regcomp(&g_pattern, string_pattern, 0);
if (pat_res != 0)
{
printf("Error: couldn't recognize patter %s\n", string_pattern);
return 0;
}
max_thread_num = max_thread_arg;
// Inicializing pthreads variables
pthread_mutex_init(&print_mutex, NULL);
pthread_mutex_init(&running_threads_mutex, NULL);
pthread_cond_init(&running_threads_cond, NULL);
int search_val = rec_search(path);
// Preventing pthread variables to be destoyed before termination of all adjacent threads
pthread_mutex_lock(&running_threads_mutex);
while (running_threads > 1)
pthread_cond_wait(&running_threads_cond, &running_threads_mutex);
pthread_mutex_unlock(&running_threads_mutex);
// Destroying pthreads variables (after no more file threads are executing)
pthread_mutex_destroy(&print_mutex);
pthread_mutex_destroy(&running_threads_mutex);
pthread_cond_destroy(&running_threads_cond);
running_threads--;
regfree(&g_pattern);
return 1;
}
|
C | #include "spi.h"
void SPI1_Init(void); //ʼSPI
void SPI1_SetSpeed(u8 SPI_BaudRatePrescaler); //SPIٶ
u8 SPI1_ReadWriteByte(u8 TxData);//SPI߶дһֽ
SPI_InitTypeDef SPI_InitStructure;//ǰõSPIԾ涨
void SPI1_Init(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA|RCC_APB2Periph_SPI1, ENABLE);
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_5 |GPIO_Pin_6| GPIO_Pin_7;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;//50MHz
GPIO_Init(GPIOA, &GPIO_InitStructure);
SPI_InitStructure.SPI_Direction = SPI_Direction_2Lines_FullDuplex; //SPI˫ģʽ:SPIΪ˫˫ȫ˫
SPI_InitStructure.SPI_Mode = SPI_Mode_Master; //SPIģʽ:ΪSPI
SPI_InitStructure.SPI_DataSize = SPI_DataSize_8b; //SPIݴС:SPIͽ8λ֡ṹ
SPI_InitStructure.SPI_CPOL = SPI_CPOL_High; //ѡ˴ʱӵ̬:ʱո
SPI_InitStructure.SPI_CPHA = SPI_CPHA_2Edge; //ݲڵڶʱ
SPI_InitStructure.SPI_NSS = SPI_NSS_Soft; //NSSźӲNSSܽţʹSSIλ:ڲNSSźSSIλ
SPI_InitStructure.SPI_BaudRatePrescaler = SPI_BaudRatePrescaler_256; //岨ԤƵֵ:ԤƵֵΪ256
SPI_InitStructure.SPI_FirstBit = SPI_FirstBit_MSB; //ָݴMSBλLSBλʼ:ݴMSBλʼ
SPI_InitStructure.SPI_CRCPolynomial = 7; //CRCֵĶʽ
SPI_Init(SPI1, &SPI_InitStructure); //SPI_InitStructָIJʼSPIxĴ
SPI_Cmd(SPI1, ENABLE); //ʹSPI
/*ǿЩд
SPI1_ReadWriteByte(0xff);
ӲӶνġ
*/
}
//SPI ٶú
//SpeedSet:
//SPI_BaudRatePrescaler_2 2Ƶ (SPI 36M@sys 72M)
//SPI_BaudRatePrescaler_8 8Ƶ (SPI 9M@sys 72M)
//SPI_BaudRatePrescaler_16 16Ƶ (SPI 4.5M@sys 72M)
//SPI_BaudRatePrescaler_256 256Ƶ (SPI 281.25K@sys 72M)
void SPI1_SetSpeed(u8 SPI_BaudRatePrescaler)
{
assert_param(IS_SPI_BAUDRATE_PRESCALER(SPI_BaudRatePrescaler));//жЧ
SPI1->CR1&=0XFFC7;//λ3-5㣬ò
SPI1->CR1|=SPI_BaudRatePrescaler; //SPI1ٶ
SPI_Cmd(SPI1,ENABLE); //ʹSPI1
}
//SPIx дһֽ
//TxData:Ҫдֽ
//ֵ:ȡֽ
u8 SPI1_ReadWriteByte(u8 TxData)
{
while (SPI_I2S_GetFlagStatus(SPI1, SPI_I2S_FLAG_TXE) == RESET){}//ȴ
SPI_I2S_SendData(SPI1, TxData); //ͨSPIxһbyte
while (SPI_I2S_GetFlagStatus(SPI1, SPI_I2S_FLAG_RXNE) == RESET){} //ȴһbyte
return SPI_I2S_ReceiveData(SPI1); //ͨSPIxյ
}
|
C | #include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include <ctype.h>
//Zad.1_1
int isNumber(const char *s)
{
int i=1;
if(s[0]=='-' || isdigit(s[0]))
{
}else
{
return 0;
}
for(i;i<strlen(s);i++)
{
if(! isdigit(s[i]))
{
return 0;
}
}
return 1;
}
//Zad.1_2
char *trim(char *s){
int i=0;
for(i;i<strlen(s);i++)
{
if(!isspace(s[i]))
break;
}
int j=strlen(s)-1;
for(j;j>0;j--)
{
if(!isspace(s[j]))
break;
}
int newSize = j-i;
char *result = malloc(newSize+1);
int index=0;
for(i;i<=j;i++)
{
result[index]=s[i];
index++;
}
result[index]='\0';
return result;
}
//Zad 1.3
int getOperator(char *op,const char *s)
{
int i=0;
for(i;i<strlen(s);i++)
{
if(!isdigit(s[i]))
{
break;
}
}
if(s[i]=='-' || s[i]=='+' || s[i]=='*' || s[i]=='/' || s[i]==':')
{
op[0]=s[i];
op[1]='\0';
return 1;
}
return 0;
}
struct Fraction {
int num, den;
};
//Zad 1.4
int getFraction(struct Fraction *x, const char *s)
{
int i=0;
for(i;i<strlen(s);i++)
{
if(!isdigit(s[i]))
{
break;
}
}
if(s[i]=='/')
{
char *licznik = malloc(i+1);
char *mianownik = malloc(strlen(s)-i+1);
int j=0;
for(j;j<i;j++)
{
licznik[j]=s[j];
}
licznik[j]='\0';
int k=i+1;
int index=0;
for(k;k<strlen(s);k++)
{
mianownik[index]=s[k];
index++;
}
mianownik[index]='\0';
x->den = atoi(mianownik);
x->num = atoi(licznik);
//jest ułamkiem
return 1;
}
else
{
//nie jest ułamkiem
//sprawdz czy jest liczba caly
if(i==strlen(s))
{
x->num=atoi(s);
x->den=1;
return 1;
}
return 0;
}
}
/*
a/b + c/d = (a*d + c*b) / (b*d)
*/
struct Fraction sum(struct Fraction x, struct Fraction y) {
int a = x.num;
int b = x.den;
int c = y.num;
int d = y.den;
struct Fraction z;
z.num = a*d + c*b;
z.den = b*d;
return z;
}
/*
a/b - c/d = (a*d - c*b) / (b*d)
*/
struct Fraction subtract(struct Fraction x, struct Fraction y) {
int a = x.num;
int b = x.den;
int c = y.num;
int d = y.den;
struct Fraction z;
z.num = a*d - c*b;
z.den = b*d;
return z;
}
/*
a/b * c/d = (a*c) / (b*d)
*/
struct Fraction multiplicate(struct Fraction x, struct Fraction y) {
int a = x.num;
int b = x.den;
int c = y.num;
int d = y.den;
struct Fraction z;
z.num = a*c;
z.den = b*d;
return z;
}
/*
a/b : c/d = (a*d) / (b*c)
*/
struct Fraction division(struct Fraction x, struct Fraction y) {
int a = x.num;
int b = x.den;
int c = y.num;
int d = y.den;
struct Fraction z;
z.num = a*d;
z.den = b*c;
return z;
}
struct Fraction doMagic(struct Fraction x)
{
struct Fraction y;
y.num = x.num;
y.den = x.den;
int a = y.num;
int b = y.den;
//jezeli mian < 0 a licznik > 0 to odwroc znaki
if(a>0)
{
if(b<0)
{
a=-a;
b=-b;
}
}
//jezeli mian jest podzielny przez licznik podziel
if(a!=-1)
if(b%a==0)
{
b=b/a;
a=1;
}
if(a%b==0)
{
a=a/b;
b=1;
}
y.num=a;
y.den=b;
return y;
}
void printFraction(struct Fraction x){
int a = x.num;
int b = x.den;
if(b==0)
{
printf("(struct Fraction){%d,%d} -> NaN\n",a,b);
return;
}
if(a==0)
{
printf("(struct Fraction){%d,%d} -> 0\n",a,b);
return;
}
struct Fraction y = doMagic(x);
if(y.den==1)
{
printf("(struct Fraction){%d,%d} -> %d\n",a,b,y.num);
return;
}
if(abs(y.num)>y.den)
{
int whole = y.num/y.den;
int c=y.num;
int d=y.den;
if(c<0)
{
c+=abs(whole)*d;
}else
{
c-=abs(whole)*d;
}
printf("(struct Fraction){%d,%d} -> %d %d/%d\n",a,b,whole,abs(c),abs(d));
return;
}
printf("(struct Fraction){%d,%d} -> %d/%d\n",a,b,y.num,y.den);
return;
}
int poprawnyOperator(char *op)
{
if(op[0]=='+' || op[0]=='-' || op[0]=='*' || op[0]=='/')
return 1;
return 0;
}
void print(struct Fraction x,struct Fraction y, const char op)
{
struct Fraction solution;
if(op == '+')
solution = sum(x,y);
else if(op == '-')
solution = subtract(x,y);
else if(op == '*')
solution = multiplicate(x,y);
else if(op == '/' || op == ':')
solution = division(x,y);
else
{
printf("%c - nieznane dzialanie",op);
return;
}
printf("%d/%d %c %d/%d = %d/%d\n",x.num,x.den,op,y.num,y.den,solution.num,solution.den);
}
char *safeReadFromConsole()
{
unsigned int len_max = 128;
unsigned int currentSize = 0;
char *data = malloc(len_max);
currentSize = len_max;
if(data != NULL)
{
int c;
unsigned int i=0;
//accept user input until hit enter or new line
while ((c = getchar()) != '\n')
{
data[i++]=(char)c;
//if max size realocate
if (i==currentSize)
{
currentSize = i+len_max;
data = realloc(data,currentSize);
}
}
data[i] = '\0';
return data;
}
return data;
}
//Zad.1.5
void odczytTerminal(){
int MAX_LEN =20;
// char *ulamek1=malloc(sizeof(char)*MAX_LEN);
printf("podaj a/b =");
char *ulamek1 = safeReadFromConsole();
// fgets(ulamek1, MAX_LEN, stdin);
struct Fraction *ul1Pointer,ul1;
ul1Pointer=&ul1;
while (getFraction(ul1Pointer,ulamek1)==0)
{
printf("podano nieprawidlowe dane.\n");
printf("podaj a/b =");
fgets(ulamek1, MAX_LEN, stdin);
}
printf("podaj c/d =");
char *ulamek2 = safeReadFromConsole();
struct Fraction *ul2Pointer,ul2;
ul2Pointer = &ul2;
while (getFraction(ul2Pointer,ulamek2)==0)
{
printf("podano nieprawidlowe dane.\n");
printf("podaj c/d =");
fgets(ulamek2, MAX_LEN, stdin);
}
char *opPointer=malloc(2);
printf("podaj operator = ");
fgets(opPointer, 2, stdin);
while (poprawnyOperator(opPointer)==0)
{
printf("podano bledny operator\n");
printf("podaj operator = ");
fgets(opPointer, 1, stdin);
}
print(ul1,ul2,opPointer[0]);
}
void main()
{
// printf("%d - isNumber\n",isNumber("XD elo 213"));
// printf("%d - isNumber\n",isNumber("213"));
// printf("%d - isNumber\n",isNumber("-213"));
// printf("%s - trim",trim(" elo elo "));
// char *op=malloc(2);
// printf("%d - getOperator = %s\n",getOperator(op,"5/2"),op);
// struct Fraction *solutionPointer,solution;
// solutionPointer=&solution;
// printf("%d - ulamek\n",getFraction(solutionPointer,"52"));
// printf("%d - ulamek\n",getFraction(solutionPointer,"2/3"));
// printf("%d - ulamek\n",getFraction(solutionPointer,"dsa/dsa"));
// printFraction(solution);
odczytTerminal();
// char *xd = saveReadFromConsole();
// printf("%s - string",xd);
} |
C | /** \brief La funcion toma dos parametros tipo flotantes, y vivide uno por el otro.
*
* \param parametro A flotante.
* \param parametro B flotante.
* \return Retorna un flotante resultante de una divicion.
*
*/
float divicion (float , float );
/** \brief La funcion toma un numero, y mediante un for calcula su factorial, el cual retorna como flotante.
*
* \param 'a' es un parametro enviado desde main.c, de tipo flotante.
* \return retorna un flotante.
*
*/
float factorial(float );
/** \brief La funcion toma dos flotantes y los resta.
*
* \param parametro A: flotante.
* \param parametro B: flotante.
* \return Retorna el resto de una resta en flotante.
*
*/
float resta (float , float );
/** \brief Suma dos numeros.
*
* \param parametro A: flotante
* \param parametro B: flotante
* \return retorna el resultado de la suma de los dos parametros en float.
*
*/
float suma (float , float );
|
C | #include <stdlib.h>
#include <string.h>
typedef struct {
void* base;
int front;
int rear;
int queueCapacity;
int typeSize;
} CircularQueue;
typedef char String[256];
CircularQueue* create(int typeSize,int queueCapacity);
int enQueue(CircularQueue* cQueue,void* element);
int isFull(CircularQueue* cQueue);
void* deQueue(CircularQueue* cQueue);
int isEmpty(CircularQueue* cQueue); |
C | /*
* Copyright (C) 2017 Niko Rosvall <[email protected]>
*/
#define _XOPEN_SOURCE 700
/* Make only POSIX.2 regexp functions available */
#define _POSIX_C_SOURCE 200112L
#include <stdio.h>
#include <regex.h>
#include "entry.h"
#include "regexfind.h"
void regex_find(Entry_t *head, const char *search, int show_password)
{
regex_t regex;
int retval;
if(regcomp(®ex, search, REG_NOSUB) != 0)
{
fprintf(stderr, "Invalid regular expression.\n");
return;
}
/* Currently regex only searches for the title field */
while(head != NULL)
{
retval = regexec(®ex, head->title, 0, NULL, 0);
if(retval == 0)
{
/* We have a match */
fprintf(stdout, "=====================================================================\n");
fprintf(stdout, "ID: %d\n", head->id);
fprintf(stdout, "Title: %s\n", head->title);
fprintf(stdout, "User: %s\n", head->user);
fprintf(stdout, "Url: %s\n", head->url);
if(show_password == 1)
fprintf(stdout, "Password: %s\n", head->password);
else
fprintf(stdout, "Password: **********\n");
fprintf(stdout, "Notes: %s\n", head->notes);
fprintf(stdout, "Modified: %s\n", head->stamp);
fprintf(stdout, "=====================================================================\n");
}
head = head->next;
}
regfree(®ex);
}
|
C | #include <stdio.h>
#include <stdlib.h>
typedef struct bstNode{
int data;
struct bstNode *left;
struct bstNode *right;
}bstNode;
bstNode* insert(int data, bstNode* root)
{
//printf("Hey");
if(root == NULL){
//printf("I am null\n");
bstNode *node = (bstNode *)malloc(sizeof(bstNode));
node->data = data;
node->left = NULL;
node->right = NULL;
return node;
}
if(data < root->data){
root->left = insert(data, root->left);
}else if(data > root->data){
root->right = insert(data, root->right);
}
return root;
}
void inorder(bstNode *root)
{
if(root == NULL) return;
inorder(root->left);
printf("%d\t", root->data);
inorder(root->right);
}
void freeUp(bstNode *root)
{
if(root != NULL){
freeUp(root->left);
freeUp(root->right);
free(root);
}
}
int main(int argc, char* argv[])
{
FILE* textReader = fopen(argv[1], "r");
if(textReader == NULL){
printf("error\n");
return 0;
}
bstNode *root = NULL;
char c = '\0';
int num = 0;
while(fscanf(textReader, "%c\t%d\n", &c, &num) != EOF){
if(c == 'i'){
root = insert(num, root);
}
}
fclose(textReader);
/*
root = insert(50, root);
//printf("Hello\n");
root = insert(60, root);
root = insert(30, root);
root = insert(20, root);
root = insert(10, root);
root = insert(0, root);
root = insert(15, root);
root = insert(25, root);
*/
inorder(root);
freeUp(root);
return 0;
}
|
C | #include<stdio.h>
#include<fcntl.h>
#include<unistd.h>
#include<errno.h>
void cpy(int instd , int outstd)
{
char buf[BUFSIZ]={0};
int n=0;
while((n=read(instd,buf,BUFSIZ))>0)
write(outstd,buf,n);
return;
}
int main(int argc , char* argv[])
{
int f=0;
if( argc < 3 || argc > 4) return 1;
if(argc == 4 && strcmp(argv[1],"-f")==0)
{
f=1;
}
int instd;
if(( instd = open(argv[f+1],O_RDONLY))<0)
{
perror(argv[f+1]);
return 1;
}
int outstd;
if(f && (outstd=creat(argv[f+2],0600))<0)
{
perror(argv[f+2]);
return 1;
}
else if(!f && (outstd=open(argv[f+2],O_WRONLY|O_CREAT|O_EXCL,0600))<0)
{
perror(argv[f+2]);
return 1;
}
dup2(instd,0);
dup2(outstd,1);
close(instd);
close(outstd);
cpy(0,1);
return 0;
}
|
C | #ifndef BLOCKGETANDSET_DEFINED
#define BLOCKGETANDSET_DEFINED
//ubNuAׂ
void SetBlock(MAP_DATA, BINDATA, int, int, int);
BINDATA GetBlock(MAP_DATA, int, int, int);
//T
int mapfind(MAP_DATA, int, int);
//\[g̍ޗƂȂ̒lvZ
int64 calc(MAP_DATA, int, int);
//ubNu
void SetBlock(MAP_DATA Mdata, BINDATA block, int x, int y, int h)
{
int p;
p = mapfind(Mdata, x, y);
if (p != -1 && h >= -128 && h < 128)
Mdata.value[p].data[h + MAP_ZERO] = block;
}
//ubN擾
BINDATA GetBlock(MAP_DATA Mdata, int x, int y, int h)
{
int p;
p = mapfind(Mdata, x, y);
if (p != -1 && h >= -128 && h < 128)
return Mdata.value[p].data[h + MAP_ZERO];
else
return B_ERROR;
}
//w肵WiʍWj̃f[^
//T@Ŏs
int mapfind(MAP_DATA Mdata, int x, int y)
{
int low = 0, high = Mdata.youso - 1, mid;
int64 keyxy = calc(Mdata, x, y);
int64 midxy;
while (low <= high)
{
mid = (low + high) / 2;
midxy = calc(Mdata, Mdata.value[mid].x, Mdata.value[mid].y);
if (keyxy<midxy) high = mid - 1;
else if (keyxy>midxy) low = mid + 1;
else break;
}
if (Mdata.youso > 0 && x == Mdata.value[mid].x && y == Mdata.value[mid].y) return mid;
else return -1;
}
//------------------------------------------------------------
//\[g邽߂̍ޗiljvZ
int64 calc(MAP_DATA MData, int x, int y)
{
int xt = x - MData.pxmin;//pxmin;
int yt = y - MData.pymin;//pymin;
int xm = MData.pxmax - MData.pxmin + 1;//pxmax - pxmin + 1;
return yt*xm + xt;
}
//------------------------------------------------------------
#endif |
C | #include "holberton.h"
/**
* mul - check the code for Holberton School students.
* @a: init value
* @b: init value
* Return: Always 0.
*/
int mul(int a, int b)
{
int resultado;
resultado = a * b;
return (resultado);
}
|
C | /**
* Author: Gavin Christie
* Date Created: November 11th 2017
* Version: 1.0
* Main function for spell check program
**/
#include "DictionaryFunctions.h"
int main( int argc, char **argv)
{
/* Check that correct number of arguments are entering through terminal */
if ( argc < 2 || argc > 2 ) {
printf( "Please try again with only file name.\n" );
return 0;
}
/* Enter the command loop */
commandLoop ( argv[1] );
return 0;
}
/* Last modified: November 14th 2017 */ |
C | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* test2.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: mbryan <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2014/12/02 09:57:50 by mbryan #+# #+# */
/* Updated: 2014/12/02 16:18:10 by mbryan ### ########.fr */
/* */
/* ************************************************************************** */
#include "ft_ls.h"
#include "stdio.h"
int option_a = 0;
int option_l = 0;
int option_r = 0;
int option_r_caps = 0;
int option_t = 0;
// prend les argument passer en parametre puis les met dans une list t1
argument *take_argument(int argc, char const *argv[])
{
argument *t1;
int x;
x = 1;
t1 = NULL;
t1 = initiaze_list(t1);
while(x != argc)
{
t1 = addone2(t1, argv[x]);
x++;
}
return (t1);
}
// lit l interieur des argument (pour l instant dossier uniquement)
argument *take_inside(int argc, char const *argv[])
{
argument *test1;
DIR *ret;
struct dirent *ret2;
int x;
test1 = NULL;
test1 = initiaze_list(test1);
x = 1;
(void)argv;
if (argc == 1)
{
x++;
ret = opendir(".");
while((ret2 = readdir(ret)) != NULL)
test1 = addone(test1, ret2->d_name);
}
if (argc > 1)
{
while(argv[x])
{
if ((ret = opendir(argv[x])) == NULL)
{
ft_putstr_fd("ft_ls: ", 2);
perror(argv[x]);
}
else
{
while((ret2 = readdir(ret)) != NULL)
{
test1 = addone(test1, ret2->d_name);
}
}
x++;
}
}
return (test1);
}
int main(int argc, char const *argv[])
{
argument *t1;
argument *test1;
int trye;
test1 = take_inside(argc, argv);
t1 = take_argument(argc, argv);
trye = check_option(t1);
printf("%d\n", trye);
read_list(test1);
ft_putendl("\n----------------\n");
read_list(t1);
return 0;
} |
C | typedef long unsigned int size_t;
extern int printf (const char *__restrict __format, ...);
extern int scanf (const char *__restrict __format, ...) ;
extern int getchar (void);
extern int putchar (int __c);
int nextInt(){int f=0;char s=0;char c=getchar();while((c<48)||(57<c)){if(c==45){s=1;c=getchar();break;}c=getchar();}while((48<=c)&&(c<=57)){f=f*10+(c-48);c=getchar();}return s?-f:f;}
char nextChar(){char f=0;char s=0;char c=getchar();while((c<48)||(57<c)){if(c==45){s=1;c=getchar();break;}c=getchar();}while((48<=c)&&(c<=57)){f=f*10+(c-48);c=getchar();}return s?-f:f;}
short int nextShort(){short f=0;char s=0;char c=getchar();while((c<48)||(57<c)){if(c==45){s=1;c=getchar();break;}c=getchar();}while((48<=c)&&(c<=57)){f=f*10+(c-48);c=getchar();}return s?-f:f;}
long long int nextLong(){long long int f=0;char s=0;char c=getchar();while((c<48)||(57<c)){if(c==45){s=1;c=getchar();break;}c=getchar();}while((48<=c)&&(c<=57)){f=f*10+(c-48);c=getchar();}return s?-f:f;}
void println(){putchar(10);}
void print(char *f){while(*f){putchar(*f);f++;}}
void printInt(int f){char c[10];if(!f){putchar(48);return;}if(f<0){f=-f;putchar(45);}char i=0;while(f){c[++i]=(f%10)+48;f/=10;}while(i){putchar(c[i--]);}}
void printLong(long long int f){char c[19];if(!f){putchar(48);return;}if(f<0){f=-f;putchar(45);}char i=0;while(f){c[++i]=(f%10)+48;f/=10;}while(i){putchar(c[i--]);}}
int min(int a, int b){return a>b?b:a;}
int d, i;
int g, p[11], c[11];
int n, a;
int ans;
int s1, need;
int main(){
d=nextInt();
g=nextInt();
for(i = 0; i < d; ++i){
p[i]=nextInt();
c[i]=nextInt();
}
ans = 1e9;
n = 1<<d;
for(a=0; a<n; a++){
int s = 0, num = 0, rest_max = -1;
for(i=0; i<d; i++){
if(a>>i&1){
s += 100 * (i+1) * p[i] + c[i];
num += p[i];
}else{
rest_max = i;
}
}
if(s<g){
s1 = 100 * (rest_max + 1);
need = (g - s + s1 - 1) / s1;
if(need >= p[rest_max]){
continue;
}
num += need;
}
ans = min(ans, num);
}
printInt(ans);
println();
} |
C | #include <stdlib.h>
#include "transceivercom.h"
#include "packages.h"
const int maxPackages = 20;
void initPackages() {
allPackages.first = NULL;
}
void insertPackage(unsigned short moduleid, unsigned short macaddress, unsigned short nodeid, unsigned char * data) {
struct packageList * module = allPackages.first;
struct packageList * packModule = NULL;
struct package * pack = NULL;
while (module) {
if (module->moduleid == moduleid) {
if (module->packCount == maxPackages)
pack = module->last;
packModule = module;
break;
}
module = module->next;
}
if (packModule != NULL) {
// Aloca o novo pacote
struct package * newPackage = (struct package *) malloc(sizeof(struct package));
newPackage->address = macaddress;
newPackage->nodeid = nodeid;
newPackage->data = data;
// Lista vazia
if (module->first == NULL) {
module->first = newPackage;
module->last = newPackage;
newPackage->next = NULL;
newPackage->prev = NULL;
module->packCount = 1;
} else {
newPackage->next = module->first;
newPackage->prev = NULL;
module->first->prev = newPackage;
module->first = newPackage;
// Lista cheia, remove o ultimo
if (pack != NULL) {
module->last->prev->next = NULL;
module->last = module->last->prev;
free(pack);
} else {
module->packCount++;
}
}
}
}
unsigned char * readData(unsigned short moduleid) {
struct packageList * module = allPackages.first;
struct package * last;
unsigned char * data = NULL;
while (module) {
if (module->moduleid == moduleid) {
if (module->packCount > 0) {
last = module->last;
data = last->data;
if (last->prev != NULL) {
last->prev->next = NULL;
} else {
module->first = NULL;
}
module->last = last->prev;
free(last);
module->packCount--;
}
break;
}
module = module->next;
}
return data;
}
void insertModule(unsigned short module) {
struct packageList * newModule = allPackages.first;
int found = 0;
while (newModule) {
if (newModule->moduleid == module) {
found = 1;
break;
}
newModule = newModule->next;
}
if (found == 0) {
newModule = (struct packageList *) malloc(sizeof(struct packageList));
newModule->moduleid = module;
newModule->first = NULL;
newModule->last = NULL;
newModule->packCount = 0;
newModule->next = allPackages.first;
allPackages.first = newModule;
}
}
|
C | #include "../ecs/components.h"
#include "grammer_parser.h"
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
// File example:
//
// s => sl
// s => sr # comment support
// s => sf
// l => l1
//
enum TokenType {
TOKENTYPE_ID, // ([a-zA-Z0-9])
TOKENTYPE_REPLACE, // ([a-zA-Z0-9]+)
TOKENTYPE_ARROW, // \=\>
TOKENTYPE_COMMENT, // \#.*$
TOKENTYPE_NEWLINE, // \n
TOKENTYPE_END_OF_FILE, // EOF
TOKENTYPE_UNKNOWN
};
struct Token {
enum TokenType type;
char *data;
int line_number;
int col;
};
static struct Token scanner( FILE* fd ) {
struct Token tk;
tk.type = TOKENTYPE_UNKNOWN;
char buffer[100];
beginning:
switch (fgetc(fd)) {
case ' ': goto beginning;
case '\t': goto beginning;
case '\n':
tk.type = TOKENTYPE_NEWLINE;
return tk;
case '#': {
int tmp = fgetc(fd);
while(tmp != '\n' && tmp != EOF)
tmp = fgetc(fd);
tk.type = TOKENTYPE_COMMENT;
return tk;
}
case EOF:
tk.type = TOKENTYPE_END_OF_FILE;
return tk;
default: fseek(fd, -1, SEEK_CUR);
}
int ret = fscanf( fd, " %[a-zA-Z0-9]", buffer);
if(ret == 1) {
if(strlen(buffer) == 1) {
tk.type = TOKENTYPE_ID;
tk.data = calloc(2, sizeof(char));
tk.data[0] = buffer[0];
return tk;
}
else if(strlen(buffer) > 1) {
tk.type = TOKENTYPE_REPLACE;
tk.data = calloc((size_t)ret + 1, sizeof(char));
strncpy(tk.data, buffer, ret+1);
return tk;
}
}
char *c = calloc(sizeof(char), 3);
// todo: need to check the return code of fscanf
// bpaf: do you want to remove the line 72 todo and ignore fscanf? I think you can even pass NULL instead of c and avoid alloc
ret = fscanf( fd, " %2c", c );
ret = strcmp("=>", c );
free(c);
if(ret == 0) {
tk.type = TOKENTYPE_ARROW;
return tk;
}
return tk;
}
// LEVEL => RULE LEVEL
// | COMMENT? NEWLINE
// | EOF
//
// RULE => ID ARROW REPLACE COMMENT? NEWLINE
// Rewrite a struct that also have the length of the array
struct Rules parse_rule(struct Token cur, FILE* fd);
static struct RulesWrapper parse_level(FILE* fd) {
struct Token cur;
const int max_rules = 10;
struct Rules* rules = calloc(sizeof(struct Rules), max_rules);
int number_of_rules = 0;
cur = scanner(fd);
while(cur.type != TOKENTYPE_END_OF_FILE) {
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wswitch-enum"
switch(cur.type) {
case TOKENTYPE_COMMENT:
case TOKENTYPE_NEWLINE:
break;
default:
rules[number_of_rules] = parse_rule(cur, fd);
number_of_rules++;
if(number_of_rules > 10) {
fprintf(stderr, "More than 10 rules\n");
break;
}
}
#pragma GCC diagnostic pop
cur = scanner(fd);
}
struct RulesWrapper rw = {
.rules = rules,
.number_of_rules = number_of_rules
};
return rw;
}
static char * token_descriptor(enum TokenType type) {
switch(type) {
case TOKENTYPE_ID:
return "TOKENTYPE_ID";
case TOKENTYPE_ARROW:
return "TOKENTYPE_ARROW";
case TOKENTYPE_REPLACE:
return "TOKENTYPE_REPLACE";
case TOKENTYPE_COMMENT:
return "TOKENTYPE_COMMENT";
case TOKENTYPE_NEWLINE:
return "TOKENTYPE_NEWLINE";
case TOKENTYPE_END_OF_FILE:
return "TOKENTYPE_END_OF_FILE";
case TOKENTYPE_UNKNOWN:
return "TOKENTYPE_UNKNOWN";
}
return "UNKNOWN_TOKEN";
}
static struct Token expected_token(
struct Token cur,
enum TokenType type,
enum TokenType type2)
{
if(cur.type == type || cur.type == type2)
return cur;
char *got = token_descriptor(cur.type);
char *expected1 = token_descriptor(type);
char *expected2 = token_descriptor(type2);
fprintf(
stderr,
"Unexpected token, got %s but expected %s or %s\n",
got,
expected1,
expected2
);
exit(SOMETHING_BROKE);
}
struct Rules parse_rule(struct Token cur, FILE* fd) {
struct Rules rule;
expected_token(cur, TOKENTYPE_ID, TOKENTYPE_ID);
rule.id = *cur.data;
free(cur.data);
expected_token(scanner(fd), TOKENTYPE_ARROW, TOKENTYPE_ARROW);
cur = expected_token(scanner(fd), TOKENTYPE_REPLACE, TOKENTYPE_ID);
rule.replace = cur.data;
return rule;
}
struct RulesWrapper parser( FILE* fd ) {
return parse_level(fd);
}
|
C | #include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main(){
int n, m;
scanf("%d%d", &n, &m);
int i, comp, out = 0;
for(i = 7; i > 1; i--){
comp = (m%(int)pow(10, i) - m%(int)pow(10, i-2)) / pow(10, i-2);
if(n == comp){
out++;
}
}
printf("%d\n", out);
return 0;
}
|
C | #include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include "fteik/fteik.h"
void solver2d_c(const double *slow,
double *tt,
const int nz, const int nx,
const double zsrc, const double xsrc,
const double dz, const double dx,
const int nsrc);
int create2DLayeredVelocityModel(const int nlayer, const int nz, const int nx,
double dz,
const double interface[], const double v1d[],
double **vmod);
/*!
* @brief 2D layer over halfspace problem.
*/
int main( )
{
int nlayer = 3; // Number of layers in model.
double dx = 10.0; // Grid spacing (m) in x.
double dz = 10.0; // Grid spacing (m) in z.
double x0 = 0.0; // x model origin (m).
double x1 = 2000.0; // x model extent (m).
double z0 = 0.0; // z model origin (m); e.g., free surface
double z1 = 800.0; // z model extent (m).
double v1d[3] = {3500.0, 4200.0, 5500.0}; // Velocity (m/s) in layers; z+ down
double interface[2] = {100.0, 250.0}; // Interface depth (m); z+ down
// Source info
int nsrc = 1; // Number of sources
double zsrc[1] = {z0+(z1-z0)*0.5 + 3.0}; // z source depth (m)
double xsrc[1] = {x0+(x1-x0)*0.5 + 3.0}; // x source offset (m).
// Solver parameters
int nsweep = 2; // Number of Gauss-Seidel iterations.
double eps = 5.0; // Number of grid points around source to
// use spherical approximation.
double convTol = 1.e-10; // Convergence tolerance for Gauss-Seidel
// Other parameters
const char *archiveFile = "loh.h5";
const char *modelName = "vpLayerOverHalfSpaceModel";
const char *travelTimeName = "vpLayerOverHalfSpaceTravelTimes";
double *vel, *ttimes, xwidth, zwidth;
int ierr, ncell, nx, nz;
xwidth = fabs(x1 - x0);
zwidth = fabs(z1 - z0);
nx = (int) (round(xwidth/dx)) + 1;
nz = (int) (round(zwidth/dz)) + 1;
// Some checks
if (dx <= 0.0 || dz <= 0.0)
{
fprintf(stderr, "%s: Invalid grid spacing\n", __func__);
return EXIT_FAILURE;
}
printf("%d %d\n", nx, nz);
if (nx < 3 || nz < 3)
{
fprintf(stderr, "%s: Insufficient number of grid points: %d %d\n",
__func__, nx, nz);
return EXIT_FAILURE;
}
// Create a 1D velocity model in the solver coordinate system
ierr = create2DLayeredVelocityModel(nlayer, nz, nx, dz,
interface, v1d, &vel);
if (ierr != 0)
{
fprintf(stderr, "%s: Failed to make velocity model\n", __func__);
return EXIT_FAILURE;
}
// Initialize the solver
fprintf(stdout, "%s: Initializing solver...\n", __func__);
fteik_solver2d_initialize(nz, nx,
z0, x0,
dz, dx,
nsweep, eps,
convTol, 0,
&ierr);
if (ierr != 0)
{
fprintf(stderr, "%s: Error initializing solver\n", __func__);
return EXIT_FAILURE;
}
// Set the velocity model
fprintf(stdout, "%s: Setting the velocity model...\n", __func__);
ncell = (nz - 1)*(nx - 1);
fteik_solver2d_setVelocityModel64f(ncell, vel, &ierr);
if (ierr != 0)
{
fprintf(stderr, "%s: Error setting velocity model\n", __func__);
return EXIT_FAILURE;
}
fprintf(stdout, "%s: Setting the source locations...\n", __func__);
fteik_solver2d_setSources64f(nsrc, zsrc, xsrc, &ierr);
ttimes = (double *) calloc((size_t) (nz*nx), sizeof(double));
double *slow = (double *) calloc((size_t) ((nz-1)*(nx-1)), sizeof(double));
for (int k=0; k<(nz-1)*(nx-1); k++){slow[k] = 1.0/vel[k];}
/*
printf("calling ref\n");
solver2d_c(slow, ttimes, nz, nx, zsrc[0], xsrc[0], dz, dx, nsweep);
fprintf(stdout, "%s: Calling debug solver...\n", __func__);
*/
fteik_solver2d_solveSourceFSM(1, &ierr);
printf("calling lsm\n");
fprintf(stdout, "%s: Calling solver...\n", __func__);
fteik_solver2d_solveSourceLSM(1, &ierr);
if (ierr != 0)
{
fprintf(stderr, "%s: Error calling solver\n", __func__);
return EXIT_FAILURE;
}
// Initialize the output
fprintf(stdout, "%s: Writing results...\n", __func__);
fteik_h5io_initializeF(archiveFile);
fteik_h5io_writeVelocityModelF(modelName);
fteik_h5io_writeTravelTimesF(travelTimeName);
fteik_h5io_finalizeF();
fprintf(stdout, "%s: Finalizing solver...\n", __func__);
fteik_solver2d_free();
// Free resources
free(vel);
free(ttimes);
return EXIT_SUCCESS;
}
//============================================================================//
int create2DLayeredVelocityModel(const int nlayer, const int nz, const int nx,
double dz,
const double interface[], const double v1d[],
double **vmod)
{
double *vel = NULL;
double v, z;
int ix, iz, k, ncellx, ncellz;
*vmod = NULL;
if (nlayer < 1)
{
fprintf(stderr, "%s: Error no layers\n", __func__);
return EXIT_FAILURE;
}
ncellz = nz - 1;
ncellx = nx - 1;
vel = (double *) calloc((size_t) (ncellz*ncellx), sizeof(double));
for (iz=0; iz<ncellz; iz++)
{
z = (double) iz*dz;
//for (k=0; k<nlayer; k++){ix*ncellz + iz;}
v = v1d[0];
for (k=0; k<nlayer-1; k++)
{
if (z >= interface[k] - 1.e-10){v = v1d[k+1];}
}
printf("%d %f\n", iz, v);
//printf("%f %f\n", z, v);
// Copy velocity for all x locations
#pragma omp simd
for (ix=0; ix<ncellx; ix++)
{
vel[ix*ncellz + iz] = v; //ix*ncellz + iz + 2; //v;
}
}
// Ensure that I got all points
for (k=0; k<ncellx*ncellz; k++)
{
if (vel[k] <= 0.0)
{
fprintf(stderr, "%s: Index %d has invalid velocity\n", __func__, k);
free(vel);
return EXIT_FAILURE;
}
}
*vmod = vel;
return EXIT_SUCCESS;
}
|
C | #pragma once
//ͨCSPʵļAES_128ӽܹ
#include "stdafx.h"
#include <windows.h>
#include <wincrypt.h>
#define BLOCK_SIZE 1024
#define ALG_SYM_ALGO CALG_3DES
/*****************************************************
*EncryptFile
* ܣļ
* ΣPCHAR szSource, ܵļ
PCHAR szDestination, ܺļ
PCHAR passwd); ܿ
* Σ
*ֵBOOLTRUΪܳɹFALSEΪʧ
******************************************************/
BOOL EncryptFile(PCHAR szSource, PCHAR szDestination, PCHAR passwd);
/*****************************************************
*DecryptFile
* ܣļ
* ΣPCHAR szSource, ܵļ
PCHAR szDestination, ܺļ
PCHAR passwd); ܿ
* Σ
*ֵBOOLTRUΪܳɹFALSEΪʧ
******************************************************/
BOOL DecryptFile(PCHAR szSource, PCHAR szDestination, PCHAR passwd);
int example_three()
{
CHAR szEncSource[] = "E:\\vs2017project\\EncryptAndDecrypt\\Debug\\test.txt";
CHAR szEncDes[] = "test_enc.txt";
CHAR szDecSource[] = "test_enc.txt";
CHAR szDecDes[] = "test_dec.txt";
CHAR * passwd = "123456";
BOOL bRet = EncryptFile(szEncSource, szEncDes, passwd);
if (bRet)
printf("EncryptFile success!\n");
bRet = DecryptFile(szDecSource, szDecDes, passwd);
if (bRet)
printf("DecryptFile success!\n");
getchar();
return 0;
}
BOOL EncryptFile(PCHAR szSource, PCHAR szDestination, PCHAR passwd)
{
//
FILE* fSource = NULL;
FILE* fDestination = NULL;
if ((fSource = fopen(szSource, "rb")) == NULL)
{
return FALSE;
}
if ((fDestination = fopen(szDestination, "wb")) == NULL)
{
return FALSE;
}
//һһCSP
HCRYPTPROV hCryptProv;
BOOL bRet = CryptAcquireContext(
&hCryptProv,
NULL, //ԿNULLʾʹĬ
NULL, //CSP_NAME
PROV_RSA_AES,
0
);
if (!bRet)
{
bRet = CryptAcquireContext(&hCryptProv, NULL, NULL, PROV_RSA_AES, CRYPT_NEWKEYSET);
if (!bRet)
{
printf("CryptAcquireContext fail!");
return FALSE;
}
}
//һỰԿsession keyỰԿҲжԳԿ
// һSessionָӵúCryptAcquireContextúCryptReleaseContext ڼĽΡ
//ỰԿֻܴһỰ
HCRYPTHASH hCryptHash;
//hash
bRet = CryptCreateHash(hCryptProv, CALG_MD5, 0, 0, &hCryptHash);
if (!bRet)
{
printf("CryptCreateHash fail!");
return FALSE;
}
//ϡɢ
bRet = CryptHashData(hCryptHash, (BYTE*)passwd, strlen(passwd), 0);
if (!bRet)
{
printf("CryptHashData fail!");
return FALSE;
}
//ùϡɢɻỰԿ
HCRYPTKEY hCryptKey;
bRet = CryptDeriveKey(hCryptProv, ALG_SYM_ALGO, hCryptHash, CRYPT_EXPORTABLE, &hCryptKey);
CryptDestroyHash(hCryptHash);
if (!bRet)
{
printf("CryptDeriveKey fail!");
return FALSE;
}
//ļм,hCryptKeyѾ㷨CALG_AES_128
while (TRUE)
{
//ܣС1024
CHAR buf[BLOCK_SIZE] = { 0 };
DWORD nReadLen = fread(buf, 1, BLOCK_SIZE, fSource);
if (nReadLen <= 0)
break;
CryptEncrypt(hCryptKey,
NULL,//ͬʱɢкͼܣﴫһɢж
feof(fSource),//һΪTRUE
0,
(BYTE*)buf,//뱻ܵݣ
&nReadLen,//ݳȣܺݳ
BLOCK_SIZE//bufĴС
);
fwrite(buf, 1, nReadLen, fDestination);
}
//ɣͷ
fclose(fSource);
fclose(fDestination);
if (hCryptKey)
CryptDestroyKey(hCryptKey);
if (hCryptHash)
CryptDestroyHash(hCryptHash);
if (hCryptProv)
CryptReleaseContext(hCryptProv, 0);
return TRUE;
}
BOOL DecryptFile(PCHAR szSource,
PCHAR szDestination,
PCHAR passwd)
{
//
FILE* fSource = NULL;
FILE* fDestination = NULL;
if ((fSource = fopen(szSource, "rb")) == NULL)
{
return FALSE;
}
if ((fDestination = fopen(szDestination, "wb")) == NULL)
{
return FALSE;
}
//һһCSP
HCRYPTPROV hCryptProv;
BOOL bRet = CryptAcquireContext(&hCryptProv, NULL, NULL, PROV_RSA_AES, 0);
if (!bRet)
{
bRet = CryptAcquireContext(
&hCryptProv,
NULL, //ԿNULLʾʹĬ
NULL, //û¼
PROV_RSA_AES,
CRYPT_NEWKEYSET //Կ
);
if (!bRet)
{
printf("CryptAcquireContext fail!");
return FALSE;
}
}
//һỰԿsession keyỰԿҲжԳԿ
// һSessionָӵúCryptAcquireContextúCryptReleaseContext ڼĽΡ
//ỰԿֻܴһỰ
HCRYPTHASH hCryptHash;
//hash
bRet = CryptCreateHash(hCryptProv, CALG_MD5, 0, 0, &hCryptHash);
if (!bRet)
{
printf("CryptCreateHash fail!");
return FALSE;
}
//ϡɢ
bRet = CryptHashData(hCryptHash, (BYTE*)passwd, strlen(passwd), 0);
if (!bRet)
{
printf("CryptHashData fail!");
return FALSE;
}
//ùϡɢɻỰԿ
HCRYPTKEY hCryptKey;
bRet = CryptDeriveKey(hCryptProv, ALG_SYM_ALGO, hCryptHash, CRYPT_EXPORTABLE, &hCryptKey);
if (!bRet)
{
printf("CryptDeriveKey fail!");
return FALSE;
}
//ļн,hCryptKeyѾ㷨CALG_AES_128
while (TRUE)
{
//ܣС1024
CHAR buf[BLOCK_SIZE] = { 0 };
DWORD nReadLen = fread(buf, 1, BLOCK_SIZE, fSource);
if (nReadLen <= 0)
break;
CryptDecrypt(hCryptKey,
NULL,//ͬʱɢкͼܣﴫһɢж
feof(fSource),//һΪTRUE
0,
(BYTE*)buf,//뱻ܵݣ
&nReadLen//ݳȣܺݳ
);
fwrite(buf, 1, nReadLen, fDestination);
}
//ɣͷ
fclose(fSource);
fclose(fDestination);
if (hCryptKey)
CryptDestroyKey(hCryptKey);
if (hCryptHash)
CryptDestroyHash(hCryptHash);
if (hCryptProv)
CryptReleaseContext(hCryptProv, 0);
return TRUE;
} |
C | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* args_check.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: vlegros <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2019/06/27 16:31:18 by vlegros #+# #+# */
/* Updated: 2019/06/27 16:31:18 by vlegros ### ########.fr */
/* */
/* ************************************************************************** */
#include "push_swap.h"
int search_through(t_ivec *vec, int value)
{
int i;
i = -1;
while ((size_t)++i < vec->length)
if (vec->data[i] == value)
return (1);
return (0);
}
static void check_new_value(t_ivec **vec, char **temp, char **save_ptr)
{
long value;
while (**temp)
{
value = ft_atoi_move(temp);
if (value > INT_MAX || value < INT_MIN || search_through(*vec, value))
{
ft_int_vec_del(vec);
ft_memdel((void**)save_ptr);
finish_him(INPUT_ERROR);
}
ft_int_vec_pushback(*vec, value);
}
ft_memdel((void**)save_ptr);
}
int check_integers(int from, int argc, char **argv)
{
char *temp;
char *save_ptr;
t_ivec *vec;
int flag;
if (!(vec = ft_int_vec_init()))
finish_him(MALLOC_ERROR);
flag = 0;
while (from < argc)
{
if (!(temp = ft_strtrim(argv[from])))
{
ft_int_vec_del(&vec);
finish_him(MALLOC_ERROR);
}
save_ptr = temp;
check_new_value(&vec, &temp, &save_ptr);
from++;
flag = 1;
}
ft_int_vec_del(&vec);
return (flag);
}
|
C | #include <stdio.h>
#include <stdlib.h> /* exit(0); */
/*
Ǻθ Լ recursive function
: ڱ ڽŸ Ǻθ Լ
Լ θ ̰ ڵѴ.
*/
int main()
{
int a;
while(1)
{
printf("\n ϰ ϴ ԷϽÿ.");
printf("\nԷ ϰ, 0 ԷϽÿ.");
printf("\n\nԷ : ");
scanf("%d",&a);
if(a==0) /* Էµ 0̸ α . */
exit(0);
printf("%d! =",a);
printf("1 = %d",fac(a));
}
return 0;
}
fac(int data)
{
int fact;
if(data==0)
fact=1;
else
{
printf(" %d * ",data);
fact = data*fac(data-1);
}
return(fact);
}
|
C | #include <stdio.h>
int main(void) {
int n;
scanf("%d", &n);
int i, prev, curCount = 1, maxCount = 1;
if (n == 1) {
printf("1");
return 0;
}
scanf("%d", &prev);
for (i = 1; i < n; i++) {
int cur;
scanf("%d", &cur);
if (cur > prev) curCount++;
else {
if (curCount > maxCount) maxCount = curCount;
curCount = 1;
}
prev = cur;
}
printf("%d", maxCount > curCount ? maxCount : curCount);
return 0;
}
|
C | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <signal.h>
#include <errno.h>
#include <sys/wait.h>
#include <sys/socket.h>
#include <unistd.h>
#define PORT "3490"
#define BACKLOG 10 //how many pending connections in queue
void sigchld_handler(int s)
{
int saved_errno = errno;
while(waitpid(-1,NULL,WNOHANG) > 0);
errno = saved_errno;
}
void *get_in_addr(struct sockaddr *sa)
{
if(sa->sa_family == AF_INET){
return &(((struct sockaddr_in*)sa)->sin_addr);
}
return &(((struct sockaddr_in6*)sa)->sin6_addr);
}
int main(int argc, char*argv[])
{
int status;
int yes = 1;
int sockfd,new_fd; //listen on sock_fd,new connection on new_fd
struct addrinfo hints,*servinfo,*p;
struct sigaction sa;
char s[INET6_ADDRSTRLEN];
memset(&hints,0,sizeof hints);
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
hints.ai_flags = AI_PASSIVE; // use my IP
if((status = getaddrinfo(NULL,PORT,&hints,&servinfo))!=0){
fprintf(stderr,"getaddrinfo: %s\n",gai_strerror(status));
return 1;
}
for(p = servinfo;p!=NULL;p = p->ai_next){
if((sockfd = socket(p->ai_family,p->ai_socktype,p->ai_protocol)) == -1){
perror("server:socket");
continue;
}
if(setsockopt(sockfd,SOL_SOCKET,SO_REUSEADDR,&yes,sizeof(int)) == -1){
perror("setsockopt");
exit(1);
}
if(bind(sockfd,p->ai_addr,p->ai_addrlen) == -1){
close(sockfd);
perror("server:bind");
continue;
}
break;
}
freeaddrinfo(servinfo);
if(p == NULL){
fprintf(stderr,"server: failed to bind\n");
exit(1);
}
if(listen(sockfd,BACKLOG) == -1){
perror("listen");
exit(1);
}
sa.sa_handler = sigchld_handler;
sigemptyset(&sa.sa_mask);
sa.sa_flags = SA_RESTART;
if(sigaction(SIGCHLD,&sa,NULL) == -1){
perror("sigaction");
exit(1);
}
printf("server: waiting for connections...\n");
while(1){
socklen_t sin_size;
struct sockaddr_storage their_addr;
sin_size = sizeof their_addr;
new_fd = accept(sockfd,(struct sockaddr *)&their_addr,&sin_size);
if(new_fd == -1){
perror("accept");
continue;
}
inet_ntop(their_addr.ss_family,get_in_addr((struct sockaddr*)&their_addr),s,sizeof s);
printf("server: got connection from %s\n",s);
if(!fork()){
close(sockfd);
if(send(new_fd,"Hello, world",13,0) == -1){
perror("send");
}
close(new_fd);
exit(0);
}
close(new_fd);
}
return 0;
} |
C | /*
û
û
*/
#include "user.h"
struct machine_structure Machine_Structure; //ṹ
struct input_structure Input_Structure ={120,0}; //ṹ
struct led_struct{
u16 timer;
u8 flag; //b1=1,˸;b1=0ֹͣ˸,b2=1ÿ2˸һ
u8 Blue_LED_on;
} LED_Struct;
/*
void User_Timer1S(void)
û1붨ʱ붨ʱ
*/
void User_Timer1s(void)
{
Input_Structure.Timer++;
LED_Struct.timer++;
// if((LED_Struct.timer % 2) == 0)
// {
// if(LED_Struct.flag & b2)
// {
// LED_Struct.flag &= ~b2;
// }
// else
// {
// LED_Struct.flag |= b2;
// }
// }
}
/*
void User_Timer1SClear(void)
û붨ʱʱ
*/
void User_Timer1sClear(void)
{
Input_Structure.Timer=0;
}
/*
u32 User_GetTimer1sValue(void)
οģʱλ
*/
u32 User_GetTimer1sValue(void)
{
return Input_Structure.Timer;
}
void User_SetTimer1sValue(u32 buf)
{
Input_Structure.Timer=buf;
}
//ָʾƿ
void LED_main(void)
{
if(LED_Struct.Blue_LED_on & 1)
{
//
if(LED_Struct.flag & b1)
{
GPIO_ResetBits(OUTPUT4);
}
else if(LED_Struct.flag &b2)
{
GPIO_SetBits(OUTPUT4);
}
if(User_GetTimer1sValue() > 300 && LED_Struct.timer > 300)
{//ûпģֹͣ˸
LED_Struct.timer=0;
LED_Struct.Blue_LED_on = 0;
GPIO_SetBits(OUTPUT4);
}
}
}
//ָʾ˸
void LED_ON(void)
{
LED_Struct.flag &= ~b2;
LED_Struct.flag |= b1;
LED_Struct.Blue_LED_on =1;
}
//ָʾֹͣ˸
void LED_OFF(void)
{
LED_Struct.flag &= ~b1;
LED_Struct.flag |= b2;
}
/*
void Communictae_Check(void)
úڼ̫ͨѶǷ̫ͨͨģ飬ע⣬Ϊ˵ȴ̫
ģģҪ3SԺ
㷨̫˿ݷͺʼʱ3Ȼûյ
·ݣ3ûյλصݣΪ̫ģ⣬
̫ģ飬3ΣΪǰϣҪ˹Ԥ
*/
struct Communicate_struct
{
u8 flag; //b1(ݷ),b2(ǰͨѶ״̬,01쳣),b3(ģ5S)
u16 timer;
u32 timer1;
u8 count1; //·ݴ
u8 count2; //
u8 TxBuffer[255]; //ڱҪ͵
u8 TxLen; //ڱ浱ǰݵij
} comm_str;
u32 Ethernet_Time_Count;
extern u8 USART3_TxBuffer[255];
extern u8 USART3_TxLen;
u8 Ethernet_Reset_Count;
void Communictae_Check(void)
{
if(comm_str.flag & b3)
{//ģѾ
if(comm_str.timer >=12000)
{//ճʱ
comm_str.timer=0;
comm_str.count1++;
if((comm_str.count1>=3) && (Ethernet_Time_Count>3600)) //1Сʱûյظڵ3Σ
{//ģ
//ģ
// printf("̫ģ\r\n");
comm_str.flag=0;
Ethernet_Time_Count=0;
comm_str.count1=0;
comm_str.timer=0;
comm_str.TxLen=0;
Ethernet_Reset_Count++; //ͳ
GPIO_SetBits(OUTPUT8); //ģ
// GPIO_ResetBits(RESET_PIN); //ģ
}
else if(comm_str.count1>=3)
{
// printf("6\r\n");
// printf("timer1=%u\r\n",Ethernet_Time_Count);
Communicate_SetOff();
}
else
{//ûյأһη͵
u8 i;
for(i=0;i<comm_str.TxLen;i++)
{
USART3_TxBuffer[i]=comm_str.TxBuffer[i];
}
USART3_TxLen=comm_str.TxLen;
USART3_SendDW();
// printf("timer1=%u\r\n",Ethernet_Time_Count);
}
}
}
else if(comm_str.timer >=3000)
{//̫
Communicate_SetOff();
comm_str.flag |= b3; //ģ
if(comm_str.TxLen>0)
{
u8 i;
for(i=0;i<comm_str.TxLen;i++)
{
USART3_TxBuffer[i]=comm_str.TxBuffer[i];
}
USART3_TxLen=comm_str.TxLen;
USART3_SendDW();
}
}
else if(comm_str.timer >=500)
{//̫ģ
GPIO_ResetBits(OUTPUT8);
// GPIO_SetBits(RESET_PIN);
}
}
/*
void Communicate_timer(void)
ͨѶⶨʱú1msʱ
̫ģʱҪȴ3S
*/
void Communicate_timer(void)
{
if((comm_str.flag & b3) == 0)
{//ģԼ
comm_str.timer++;
}
else if(comm_str.flag & b1)
{//ݷͣʱ
comm_str.timer++;
}
}
/*
void Communicate_SetIn(void)
comm_str.flagb1λʱ,ʱ
*/
void Communicate_SetOn(void)
{
comm_str.flag |= b1;
comm_str.timer=0;
}
/*
δյݼʱ
*/
void Clera_Timer1(void)
{
Ethernet_Time_Count=0;
}
/*
void Communicate_SetIn(void)
comm_str.flagb1λֹͣʱͬʱǰļ
*/
void Communicate_SetOff(void)
{
comm_str.flag &= ~(b1 | b2);
comm_str.timer=0;
comm_str.count1=0;
comm_str.count2=0;
}
/*
void Communicate_SaveData(void)
浱ǰҪ͵
룺 u8 *p(Ҫݵַ),u8 len(Ҫݵij)
*/
void Communicate_SaveData(u8 *p,u8 len)
{
u8 i;
for(i=0;i<len;i++)
{
comm_str.TxBuffer[i]=*p++;
}
comm_str.TxLen=len;
}
/*
void Communicate_Star(void)
ʱãʱʱ3SȻټԱ̫ģ
*/
void Communicate_Star(void)
{
GPIO_ResetBits(OUTPUT8);
// GPIO_SetBits(RESET_PIN);
while(comm_str.timer<1500);
comm_str.timer=0;
}
void Communicate_StarON(void)
{
while(comm_str.timer<1000);
comm_str.timer=0;
comm_str.flag =0;
comm_str.flag |= b3; //ģ
comm_str.TxLen=0;
}
|
C | /*Задача 18:
Направете сериализация и десериализация на структурата
typedef struct Person{
char name[20];
int age;
char gender;
}t_person;
в XML формат по показания в лекцията начин.*/
#include <stdio.h>
#define SIZE 20
static const char *FORMAT_PERSON_IN = "(%[^,], %d, %c)\n";
static const char *FORMAT_PERSON_OUT = "(%s, %d, %c)\n";
typedef struct Person{
char name[SIZE];
int age;
char gender;
}t_person;
int main(void){
t_person m ={
.name = "Boni",
.age = 22,
.gender = 'F'
};
t_person dm;
FILE *fp;
fp = fopen("20210308_18people.xml", "w+" );
if(NULL == fp)
return 1;
fprintf(fp, FORMAT_PERSON_OUT, m.name, m.age, m.gender);
fseek(fp, 0, SEEK_SET);
fscanf(fp, FORMAT_PERSON_IN, dm.name, &dm.age, &dm.gender);
printf(FORMAT_PERSON_OUT, dm.name, dm.age, dm.gender);
fclose(fp);
return 0;
} |
C | #include <stdio.h>
int main(){
int *p;
int num = 12345;
p = #
printf("num is = %d\n", num);
printf("num address is = %p\n", &num);
printf("pointer value is = %p\n", p);
printf("pointer indicates value %d\n", *p);
*p = 23456;
printf("num is = %d\n", num);
printf("num address is = %p\n", &num);
printf("pointer value is = %p\n", p);
printf("pointer indicates value %d\n", *p);
return 0;
} |
C |
int reverse(int,int);
int main(int argc, char* argv[])
{
int sz[5][5],n,m,i,j,e[5];
for(i=0;i<5;i++){
for(j=0;j<5;j++){
scanf("%d",&sz[i][j]);
}
}
scanf("%d%d",&m,&n);
if(reverse(n,m)==0){
printf("error\n");
}else{
for(j=0;j<5;j++){
e[j]=sz[n][j];
sz[n][j]=sz[m][j];
sz[m][j]=e[j];
}
for(i=0;i<5;i++){
for(j=0;j<4;j++){
printf("%d ",sz[i][j]);
}
if(j==4){
printf("%d",sz[i][j]);
}
printf("\n");
}
}
return 0;
}
int reverse(int n,int m){
if(n>=0&&n<5&&m>=0&&m<5){
return 1;
}else{
return 0;
}
} |
C | #include <stdio.h>
#include <string.h>
int main ()
{
FILE *origin;
FILE *result;
char c;
result = fopen("escribir.txt", "e");
origen = fopen("leer.txt", "l");
if ( origin == NULL){
printf("Error\n");
return 1;
}
while((c=getc(origin)) != EOF)
{
if (c == '/')
{
if ( c == '*')
{
c=getc(origin);
bookmark:while( c != '*')
{
c=getc(origin);
}
c=getc(origin);
if (c!= '/')
goto bookmark;
}
else if(c == '/')
{
c=getc(origin);
while (c != '\n')
{
c=getc(origin);
}
}
else
{
putc(c,result);
}
}
putc(c,result);
}
fclose(origin);
fclose(result);
printf("NUevo archivo\n");
return 0;
} |
C | //1. Write a program in C to display the first 10 natural numbers.
#include<stdio.h>
#include<conio.h>
int main()
{
int i;
printf("The first ten natural numbers are:");
for(i=1;i<=10;i++)
{
printf("\n%d",i);
}
getch();
}
|
C | #include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
pthread_mutex_t mutex = PTHREA_MUTEX_INITIALIZER;
pthread_cond_t cond = PTHREA_COND_INITIALIZER;
void *thread1( void * );
void *thread2( void * );
int i = 1;
int main( int argc, char *argv[] )
{
pthread_t t_a, t_b;
pthread_create( &t_a, NULL, thread1, ( void *)NULL );
pthread_create( &t_b, NULL, thread2, ( void *)NULL );
pthread_join( t_a, NULL );
pthread_join( t_b, NULL );
pthread_mutex_destroy( &mutex );
pthread_cond_destroy( &cond );
exit( 0 );
}
void *thread1( void *junk )
{
for( i = 0; i <= 6; i++ )
{
pthread_mutex_lock( &mutex );
printf( "thread1: lock %d\n", __LINE__ );
if( i % 3 == 0){
printf( "thread1: signal 1 %d\n", __LINE__ );
pthread_cond_signal( &cond );
printf( "thread1: signal 2 %d\n", __LINE__ );
sleep( 1 );
}
pthread_mutex_unlock( mutex );
printf( "thread1: unlock %d\n", __LINE__ );
sleep( 1 );
}
}
void *thread2( void *junk )
{
while( i < 6 )
{
pthread_mutex_lock( &mutex );
printf( "thread2: lock %d\n", __LINE__ );
if( i % 3 != 0 ){
printf( "thread2: wait 1 %d\n", __LINE__ );
pthread_cond_wait( &cond, &mutex );
printf( "thread2: wait 2 %d\n", __LINE__ );
}
pthread_mutex_unlock( &mutex );
printf( "thread2: unlock %d\n", __LINE__ );
sleep( 1 );
}
}
|
C | #include<stdio.h>
int main()
{
int x=13,y;
y= x++ + x++;
printf("%d\n",y);
printf("%d\n",x);
return 0;
} |
C | /*@A (C) 1992 Allen I. Holub */
#include <stdio.h>
#include <tools/debug.h>
#include <tools/set.h>
#include <tools/hash.h>
#include <tools/compiler.h>
#include <tools/l.h>
#include "parser.h"
/* FIRST.C Compute FIRST sets for all productions in a symbol table.
*-------------------------------------------------------------------------
*/
void first_closure P(( SYMBOL *lhs )); /* local */
void first P(( void )); /* public */
int first_rhs P(( SET *dest, SYMBOL **rhs, int len ));
PRIVATE int Did_something;
/*----------------------------------------------------------------------*/
PUBLIC void first( )
{
/* Construct FIRST sets for all nonterminal symbols in the symbol table. */
D( printf("Finding FIRST sets\n"); )
do
{
Did_something = 0;
ptab( Symtab, (ptab_t) first_closure, NULL, 0 );
} while( Did_something );
}
/*----------------------------------------------------------------------*/
PRIVATE void first_closure( lhs )
SYMBOL *lhs; /* Current left-hand side */
{
/* Called for every element in the FIRST sets. Adds elements to the first
* sets. The following rules are used:
*
* 1) given lhs->...Y... where Y is a terminal symbol preceded by any number
* (including 0) of nullable nonterminal symbols or actions, add Y to
* FIRST(x).
*
* 2) given lhs->...y... where y is a nonterminal symbol preceded by any
* number (including 0) of nullable nonterminal symbols or actions, add
* FIRST(y) to FIRST(lhs).
*/
PRODUCTION *prod; /* Pointer to one production side */
SYMBOL **y; /* Pointer to one element of production */
static SET *set = NULL; /* Scratch-space set. */
int i;
if( !ISNONTERM(lhs) ) /* Ignore entries for terminal symbols */
return;
if( !set ) /* Do this once. The set isn't free()d */
set = newset();
ASSIGN( set, lhs->first );
for( prod = lhs->productions; prod ; prod = prod->next )
{
if( prod->non_acts <= 0 ) /* No non-action symbols */
{ /* add epsilon to first set */
ADD( set, EPSILON );
continue;
}
for( y = prod->rhs, i = prod->rhs_len; --i >= 0; y++ )
{
if( ISACT( *y ) ) /* pretend acts don't exist */
continue;
if( ISTERM( *y ) )
ADD( set, (*y)->val );
else if( *y ) /* it's a nonterminal */
UNION( set, (*y)->first );
if( !NULLABLE( *y )) /* it's not a nullable nonterminal */
break;
}
}
if( !IS_EQUIVALENT(set, lhs->first) )
{
ASSIGN( lhs->first, set );
Did_something = 1;
}
}
/*----------------------------------------------------------------------*/
PUBLIC int first_rhs( dest, rhs, len )
SET *dest; /* Target set */
SYMBOL **rhs; /* A right-hand side */
int len; /* # of objects in rhs */
{
/* Fill the destination set with FIRST(rhs) where rhs is the right-hand side
* of a production represented as an array of pointers to symbol-table
* elements. Return 1 if the entire right-hand side is nullable, otherwise
* return 0.
*/
if( len <= 0 )
{
ADD( dest, EPSILON );
return 1;
}
for(; --len >= 0 ; ++rhs )
{
if( ISACT( rhs[0] ) )
continue;
if( ISTERM( rhs[0] ) )
ADD( dest, rhs[0]->val );
else
UNION( dest, rhs[0]->first );
if( !NULLABLE( rhs[0] ) )
break;
}
return( len < 0 );
}
|
C | #ifndef __TYPES__
#define __TYPES__
#include <stdint.h>
typedef uint8_t u8; /* Unsigned types of an exact size */
typedef uint16_t u16;
typedef uint32_t u32;
typedef uint64_t u64;
typedef int8_t s8; /* Signed types of an exact size */
typedef int16_t s16;
typedef int32_t s32;
typedef int64_t s64;
typedef u16 le16;
typedef u32 le32;
typedef u64 le64;
typedef u16 be16;
typedef u32 be32;
typedef u64 be64;
#endif
|
C | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* raycasting.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: sreicher <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2020/11/02 14:05:47 by sreicher #+# #+# */
/* Updated: 2020/11/04 16:40:15 by sreicher ### ########.fr */
/* */
/* ************************************************************************** */
#include "wolf3d.h"
void put_color_to_pixel(t_env *e, int x, int y, int color)
{
int pixel;
pixel = (x + y * e->win->x_win);
e->img.data[pixel] = color;
}
void verline(int x, t_env *e)
{
while (e->rc->drawstart < e->rc->drawend)
{
put_color_to_pixel(e, x, e->rc->drawstart, e->rc->color);
e->rc->drawstart++;
}
}
void raycasting(t_env *e, int x)
{
mlx_clear_window(e->win->mlx_ptr, e->win->win_ptr);
while (x < e->win->x_win)
{
e->plr->camera_x = 2 * x / (double)e->win->x_win - 1;
e->plr->ray_pos_x = e->plr->pos_x;
e->plr->ray_pos_y = e->plr->pos_y;
e->plr->ray_dir_x = e->plr->dir_x + e->plr->plane_x * e->plr->camera_x;
e->plr->ray_dir_y = e->plr->dir_y + e->plr->plane_y * e->plr->camera_x;
e->rc->mapx = (int)e->plr->ray_pos_x;
e->rc->mapy = (int)e->plr->ray_pos_y;
e->rc->deltadistx = sqrt(1 + (e->plr->ray_dir_y * e->plr->ray_dir_y)
/ (e->plr->ray_dir_x * e->plr->ray_dir_x));
e->rc->deltadisty = sqrt(1 + (e->plr->ray_dir_x * e->plr->ray_dir_x)
/ (e->plr->ray_dir_y * e->plr->ray_dir_y));
e->rc->hit = 0;
e->rc->side = 0;
raycasting2(e);
if (e->rc->side == 1)
{
e->rc->color = e->rc->color / 2;
}
verline(x, e);
x++;
}
}
void raycasting2(t_env *e)
{
if (e->plr->ray_dir_x < 0)
{
e->rc->stepx = -1;
e->rc->sidedistx = (e->plr->ray_pos_x - e->rc->mapx)
* e->rc->deltadistx;
}
else
{
e->rc->stepx = 1;
e->rc->sidedistx = (e->rc->mapx + 1.0 - e->plr->ray_pos_x)
* e->rc->deltadistx;
}
if (e->plr->ray_dir_y < 0)
{
e->rc->stepy = -1;
e->rc->sidedisty = (e->plr->ray_pos_y - e->rc->mapy)
* e->rc->deltadisty;
}
else
{
e->rc->stepy = 1;
e->rc->sidedisty = (e->rc->mapy + 1.0 - e->plr->ray_pos_y)
* e->rc->deltadisty;
}
raycasting3(e);
}
void raycasting3(t_env *e)
{
while (e->rc->hit == 0)
{
if (e->rc->sidedistx < e->rc->sidedisty)
{
e->rc->sidedistx += e->rc->deltadistx;
e->rc->mapx += e->rc->stepx;
e->rc->side = 0;
}
else
{
e->rc->sidedisty += e->rc->deltadisty;
e->rc->mapy += e->rc->stepy;
e->rc->side = 1;
}
if (e->map->vertices2[e->rc->mapy][e->rc->mapx].z > 0)
e->rc->hit = 1;
}
if (e->rc->side == 0)
e->rc->perpwalldist = (e->rc->mapx - e->plr->ray_pos_x
+ (1 - e->rc->stepx) / 2) / e->plr->ray_dir_x;
else
e->rc->perpwalldist = (e->rc->mapy - e->plr->ray_pos_y
+ (1 - e->rc->stepy) / 2) / e->plr->ray_dir_y;
raycasting4(e);
}
|
C | #include <stdio.h>
#include <string.h>
#include <strings.h>
#include <ctype.h>
#include <stdlib.h>
#include <cs50.h>
int main(int argc, string argv[])
{
//checks if a letter repeats in string from command line argument
// Take one letter
for (int i = 0; i < strlen(argv[1]); i++)
{
// Compare that letter with every letter in the string
for (int j = i + 1; j < strlen(argv[1]); j++)
{
if (tolower(argv[1][i]) == tolower(argv[1][j]))
{
printf("There is a repeat, ignoring case.\n");
return 1;
}
}
}
printf("No repeats.\n");
return 0;
} |
C | #include <stdio.h>
#include <string.h>
#include <stdlib.h>
typedef enum {
INTEGER = 0, REAL, NAN
}Type;
typedef struct __Number {
Type t;
union {
int i;
double r;
}data;
}Number;
typedef enum {
ADD = 0, SUB, MUL, DIV
}Operation;
Number calculate(Number n1, Number n2, Operation op)
{
Number result;
switch (op)
{
case ADD:
if (n1.t == INTEGER && n2.t == INTEGER)
{
result.t = INTEGER;
result.data.i = n1.data.i + n2.data.i;
}
else if(n1.t == INTEGER && n2.t == REAL)
{
result.t = REAL;
result.data.r = n1.data.i + n2.data.r;
}
else if (n1.t == REAL && n2.t == INTEGER)
{
result.t = REAL;
result.data.r = n1.data.r + n2.data.i;
}
else
{
result.t = REAL;
result.data.r = n1.data.r + n2.data.r;
}
break;
case SUB:
if (n1.t == INTEGER && n2.t == INTEGER)
{
result.t = INTEGER;
result.data.i = n1.data.i - n2.data.i;
}
else if (n1.t == INTEGER && n2.t == REAL)
{
result.t = REAL;
result.data.r = n1.data.i - n2.data.r;
}
else if (n1.t == REAL && n2.t == INTEGER)
{
result.t = REAL;
result.data.r = n1.data.r - n2.data.i;
}
else
{
result.t = REAL;
result.data.r = n1.data.r - n2.data.r;
}
break;
case MUL:
if (n1.t == INTEGER && n2.t == INTEGER)
{
result.t = INTEGER;
result.data.i = n1.data.i * n2.data.i;
}
else if (n1.t == INTEGER && n2.t == REAL)
{
result.t = REAL;
result.data.r = n1.data.i * n2.data.r;
}
else if (n1.t == REAL && n2.t == INTEGER)
{
result.t = REAL;
result.data.r = n1.data.r * n2.data.i;
}
else
{
result.t = REAL;
result.data.r = n1.data.r * n2.data.r;
}
break;
case DIV:
if (n2.data.i == 0 || n2.data.r == 0)
result.t = NAN;
else if (n1.t == INTEGER && n2.t == INTEGER)
{
result.t = REAL;
result.data.r = n1.data.i / n2.data.i;
}
else if (n1.t == INTEGER && n2.t == REAL)
{
result.t = REAL;
result.data.r = n1.data.i / n2.data.r;
}
else if (n1.t == REAL && n2.t == INTEGER)
{
result.t = REAL;
result.data.r = n1.data.r / n2.data.i;
}
else
{
result.t = REAL;
result.data.r = n1.data.r / n2.data.r;
}
break;
default:
break;
}
return result;
}
int main()
{
Number n1, n2, result;
char num1[30], num2[30];
scanf("%s %s", num1, num2);
int i;
for (i = 0; i < strlen(num1); i++)
{
if (num1[i] == '.') break;
}
if (i == strlen(num1))
{
n1.t = INTEGER;
n1.data.i = atoi(num1);
}
else
{
n1.t = REAL;
n1.data.r = atof(num1);
}
for (i = 0; i < strlen(num2); i++)
{
if (num2[i] == '.') break;
}
if (i == strlen(num2))
{
n2.t = INTEGER;
n2.data.i = atoi(num2);
}
else
{
n2.t = REAL;
n2.data.r = atof(num2);
}
result = calculate(n1, n2, ADD);
if (result.t == INTEGER)
printf("ADD %d INTEGER\n", result.data.i);
else
printf("ADD %f REAL\n", result.data.r);
result = calculate(n1, n2, SUB);
if (result.t == INTEGER)
printf("SUB %d INTEGER\n", result.data.i);
else
printf("SUB %f REAL\n", result.data.r);
result = calculate(n1, n2, MUL);
if (result.t == INTEGER)
printf("MUL %d INTEGER\n", result.data.i);
else
printf("MUL %f REAL\n", result.data.r);
result = calculate(n1, n2, DIV);
if (result.t == REAL)
printf("DIV %f REAL\n", result.data.r);
else
printf("DIV NAN");
return 0;
} |
C | #include <stdio.h>
#include "ChainedList.h"
int main() {
ChainedList* list = chndlstEmpty();
printf("%d\n", chndlstLength(list));
chndlstDisplay(list);
chndlstAddValueAtEnd(list, 18);
printf("%d\n", chndlstLength(list));
chndlstDisplay(list);
chndlstAddValueAtEnd(list, 19);
printf("%d\n", chndlstLength(list));
chndlstDisplay(list);
chndlstRemoveValue(getFirst(list));
printf("%d\n", chndlstLength(list));
chndlstDisplay(list);
chndlstAddValueAtBeginning(list, 80);
printf("%d\n", chndlstLength(list));
chndlstDisplay(list);
chndlstRemoveFirst(list);
printf("%d\n", chndlstLength(list));
chndlstDisplay(list);
return 0;
}
|
C | #include <iostream>
#include <fstream>
#include <stdlib.h>
#include <iomanip>
using namespace std;
const char* sortName = "quickSort";
const int MIN = 10;
const int MAX = 100000;
const int FILE_SIZE = 100;
const char* executionTime = "Nguyen_Hung_timeOfExecution.txt";
void generateFile(){
cout << "Randomly generating input files:" << endl;
system("./generateFile");
}
void runQuickSort(const string& inputFile, const string& outputFile){
string cmd = "./" + string(sortName) + " " + inputFile + " " + outputFile;
system(cmd.data());
}
int main(){
generateFile();
cout << "Sorting input files:" << endl;
ofstream out;
out.open(executionTime);
out << setw(10) << "Input Size " << setw(15) << "Execution Time" << endl;
out.close();
for(int i = MIN; i <= MAX; i*=10){
for(int j = 1; j<= FILE_SIZE; ++j){
string inputFile = "inputfiles/" + to_string(i) + "_" + to_string(j);
string outputFile = "outputfiles/" + to_string(i) + "_" + to_string(j);
runQuickSort(inputFile, outputFile);
}
}
cout << "All Done!" << endl;
}
|
C | #ifndef CHTBL_H
#define CHTBL_H
#include <stdlib.h>
#include <List/list.h>
//定义链式哈希表(chained hash tables)结构体
//@buckets 表示坑位
//@函数指针h 指定哈希函数,为了尽可能的散列
//@table 是哈希表本身
typedef struct CHTbl_{
int buckets;
int (*h)(const void *key);
int (*match)(const void *key1, const void *key2);
void (*destroy)(void *data);
int size;
List *table;
}CHTbl;
//初始化链式哈希表
int chtbl_init(CHTbl *htbl, int buckets, int (*h)(const void *key),
int (*match)(const void *key1, const void *key2), void (*destroy)(void *data));
//销毁哈希表
void chtbl_destroy(CHTbl *htbl);
//插入表元素
int chtbl_insert(CHTbl *htbl, const void *data);
//移除表元素
int chtbl_remove(CHTbl *htbl, void **data);
//查找表元素
int chtbl_lookup(const CHTbl *htbl, void **data);
#define chtbl_size(htbl) ((htbl)->size)
#endif
|
C | int min (int num1, int num2) {
return (num1 < num2) ? (num1) : (num2);
}
int minimumDistances(int a_count, int* a) {
int ref = 100000;
int res = ref;
for (int i = 0; i < a_count; i++) {
for (int j = (i + 1); j < a_count; j++) {
if (a[i] == a[j]) {
res = min(res, abs(j - i));
}
}
}
if (res == ref) res = -1;
return res;
} |
C | #include<stdio.h>
void main(){
int a;
printf("Size of integer before assignment is %d\n",sizeof(a));
a = 6636;
printf("Size of integer after assignment is %d\n",sizeof(a));
}
//memory occupied by integer does not depend on whether its assigned a value or not
|
C | #include "stdio.h"
/*
Write a program that, given a date, three ints (for example, 11 27 1997),
will print the number of that day within its year:
i.e. Jan 1st is always 1, Dec 31st is either 365 or 366.
The months of the year have lengths according to the following rules:
- The odd months up to and including month 7 have 31 days.
- The even months from 8 upwards, have 31 days.
- Month 2 has 28 days except in a leap year when it has 29 days.
- The rest of the months have 30 days.
*/
int IsLeapYear (int year);
int main()
{
// variables to hold days-related value
int day, month, year, is_leap_year, num_of_days;
// variable to hold loop counter
int i;
// Initialize days_lookup with number of days in each month, assuming non leap year.
int days_lookup[12]={31,28,31,30,31,30,31,31,30,31,30,31};
// Read date
printf("Program to get a date's day of the year.\n");
printf("Please input the date (dd MM yyyy)");
scanf("%d %d %d",&day, &month, &year);
// Set February to have 29 days in case of leap year
is_leap_year = IsLeapYear(year);
if (is_leap_year)
days_lookup[1]=29;
// Start counting until MM-1
num_of_days = 0;
for (i=0; i<month-1; ++i){
num_of_days += days_lookup[i];
}
// Add the number of days in month M specified in the input date
num_of_days += day;
printf("%d-%d-%d is a day number %d in that year.\n", day,month,year,num_of_days);
return 0;
}
int IsLeapYear (int year){
int is_leap = 0;
// Check leap year from the least restrictive condition
if (year % 4 == 0) // least restrictive
is_leap = 1;
if (year % 100 == 0) // a bit restrictive
is_leap = 0;
if (year % 400 == 0) // more restrictive
is_leap = 1;
if (year < 1752) // the most restrictive
is_leap = 0;
return is_leap;
}
|
C | #include "set.h"
#include <stdio.h>
#include <stdlib.h>
typedef struct NodeS {
setElementT data;
struct NodeS *next;
} Node;
struct setCDT {
Node *head;
int size;
};
setADT setNew()
{
/* Allocate A */
setADT A;
A = (setADT) malloc(sizeof(struct setCDT));
if (A == NULL)
return NULL;
A->size = 0;
A->head = NULL;
return A;
}
void setFree(setADT A)
{
Node *cp, *prev;
/* For each Node in A, free it */
cp = A->head;
while(cp) {
prev = cp;
cp = cp->next;
free(prev);
}
free(A);
}
int setInsertElementSorted(setADT A, setElementT item)
{
Node *new, *curr, *prev;
curr = prev = NULL;
/* Find position to insert item */
for (curr = A->head; curr; curr = curr->next) {
if (curr->data == item)
return A->size;
if (curr->data > item)
break;
prev = curr;
}
/* Allocate new node*/
new = (Node *) malloc(sizeof(Node));
if (new == NULL) {
printf("ERROR: Out of memory\n Exiting...\n");
exit(-1);
}
new->data = item;
/* Insert item */
if (prev == NULL) {
A->head = new;
} else {
prev->next = new;
}
new->next = curr;
return ++A->size;
}
setADT setUnion(setADT A, setADT B)
{
Node *cpA, *cpB;
setADT C;
C = setNew();
/* For all setElementT x in A, insert x into C */
for (cpA=A->head; cpA; cpA = cpA->next)
setInsertElementSorted(C, cpA->data);
/* For all setElementT x in B, insert x into C */
for (cpB=B->head; cpB; cpB = cpB->next)
setInsertElementSorted(C, cpB->data);
/* Note: this works only because insert ignores duplicate values :D */
return C;
}
setADT setIntersection(setADT A, setADT B)
{
Node *cpA, *cpB;
setADT C;
C = setNew();
/* For all setElementT x in A, insert x into C iff x in B */
for (cpA=A->head; cpA; cpA = cpA->next) {
for (cpB=B->head; cpB; cpB = cpB->next) {
if (cpA->data == cpB->data) {
setInsertElementSorted(C, cpA->data);
break;
}
}
}
return C;
}
setADT setDifference(setADT A, setADT B)
{
int flag=0;
Node *cpA, *cpB;
setADT C;
C = setNew();
/* For each element in A, compare it with each element in B */
for (cpA=A->head; cpA; cpA=cpA->next) {
for (cpB=B->head; cpB; cpB = cpB->next) {
if (cpA->data == cpB->data) {
flag = 1;
break;
}
}
/* If A[i] appeared in B, do not add it to C. Else, add it */
flag? flag=0 : setInsertElementSorted(C, cpA->data);
}
return C;
}
int setCardinality(setADT A)
{
return A->size;
}
void setPrint(setADT A, char *name)
{
/* Special case: |A| = 0 */
if (A->size == 0) {
printf("%s = {}\n", name);
return;
}
/* Print all element in A */
Node *cp;
printf("%s = {", name);
for (cp = A->head; cp; cp = cp->next) {
printf("%d, ", cp->data);
}
/* Remove trailing comma and add lcosing bracket*/
printf("\b\b} \n");
}
|
C | #include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <sys/types.h>
#include <unistd.h>
#include <stdint.h>
#include <inttypes.h>
#include <pthread.h>
int size;
unsigned long **matrix1;
unsigned long **matrix2;
unsigned long **resMatrix;
unsigned long random_int(int min, int max, int seed)
{
srand( seed );
return min + rand() % (max+1 - min);
}
void toString(unsigned long **array)
{
for (int i = 0; i < size; i++)
{
for (int j = 0; j < size; j++)
printf("%lu ", array[i][j]);
printf("\n");
}
}
void *matrixMultiplication()
{
for (int i = 0; i < size; i++)
{
for (int j = 0; j < size; j++)
{
for (int k = 0; k < size; k++)
resMatrix[i][j] += matrix1[i][k]*matrix2[k][j];
}
}
}
int main()
{
struct timespec start, end;
int count;
pthread_t *thread;
printf("Input matrix size: ");
scanf("%d", &size);
matrix1 = malloc(size*sizeof(unsigned long *));
matrix2 = malloc(size*sizeof(unsigned long *));
resMatrix = malloc(size*sizeof(unsigned long *));
for(int i = 0; i < size; i++)
{
matrix1[i] = malloc(size*sizeof(unsigned long));
matrix2[i] = malloc(size*sizeof(unsigned long));
resMatrix[i] = malloc(size*sizeof(unsigned long));
}
//need a seed for random numbers, because C is stupid
for(int i = 0; i < size; i++)
{
for(int j = 0; j < size; j++)
{
matrix1[i][j] = random_int(0,1000, i+3*j+1);
matrix2[i][j] = random_int(0,1000, 3*i+j+3);
}
}
thread = malloc(size*sizeof(pthread_t));
matrixMultiplication();
toString(matrix1);
printf("--------\n");
toString(matrix2);
printf("--------\n");
toString(resMatrix);
clock_gettime(CLOCK_MONOTONIC, &start);
for(int i = 0; i < 50; i++)
{
pthread_create(thread, NULL, matrixMultiplication, NULL);
pthread_join(*thread, NULL);
}
clock_gettime(CLOCK_MONOTONIC, &end);
double seconds = (double)end.tv_sec + 1.0e-9*end.tv_nsec - (double)start.tv_sec + 1.0e-9*start.tv_nsec;
printf("Seconds: %.9f\n",seconds);
printf("Average seconds: %.9f\n", seconds/50);
}
|
C | /*
20设头指针为L的带有表头结点的非循环双向链表,
其每个结点中除有pred(前驱指针)data(数据)和next(后继指针)域外,还有一个访问频度域freq。
在链表被启用前,其值均始化为零。每当在链表中进行一次 Locate(L,x)运算时,令元素值为x的结点中freq域的值增1,
并使此链表中结点保持按访问频度非增(递减)的顺序排列,同时最近访问的结点排在频度相同的结点的前面,以便使频繁访问的结点总是靠近表头。
试编写符合上述要求的 Locate(L,x)运算的算法,该运算为函数过程,返回找到结点的地址,类型为指针型
*/
//思想:在双向链表中查找数据值为x的节点,查到后将节点从链表上摘下,然后再顺着节点的前驱链查找到该节点的插入位置
//频度递减,且排在同频度的第一个,即向前找到第一个比他频度还大的节点,插入位置为该节点之后
DLinkList Locate(DLinkList &L,ElemType x)
{//先查x 查找成功频度加1
//按频度递减插入(同频度最近访问的在前面)
DNode *p=L->next,*q; //p为工作指针 q为p的前驱,用于查找插入位置
while(p&&p->data!=x)
p=p->next;
if(!p)
{
printf("不存在值为x的节点\n");
exit(0);
}
else
{
p->freq++; //值为x的节点频度加1
p->next->pred=p->pred;
p->pred->next=p->next; //p节点摘下
q=p->pred; //查找p的插入位置
while(q!=L && q->freq <= p->freq)
q=q->pred;
p->next=q->next;
q->next->pred=p; //p节点插入 排在同频率的第一个
p->pred=q;
q->next=p;
}
return p
} |
C | #include<stdio.h>
int a[7]={};
FILE *fp;
char c;
int allplus(int x)
{int i;
for (i=1; i<=6; i++)
a[i] += x;
return 0;
}
int check()
{int i;
for (i=1; i<=6; i++)
if (a[i] >= 100)
a[i] = 100;
return 0;
}
int scan()
{int i;
printf("Ҵҹսô(1/0):\n1.ʹë\n0.ë\n");
scanf("%d", &i);
if (i == 1)
allplus(-2);
printf("ս(abcd):\n");
scanf("%s", &c);
if (c == 's'||c == 'S')
{
allplus(1);
a[1] += 3;
}
else if (c == 'a'||c == 'A')
a[1] += 3;
else if (c == 'b'||c == 'B')
{
allplus(-1);
a[1] += 3;
}
else if (c == 'c'||c == 'C')
{
allplus(-2);
a[1] += 3;
}
else
allplus(-3);
printf("MVP:\n");
scanf("%d", &i);
a[i] += 10;
check();
return 0;
}
int kitou()
{int i;
allplus(-15);
for (i=1; i<=6; i++)
{
printf("%d: %d\n", i, a[i]);
if (a[i] <= 60)
printf("%dҪˢ\n", i);
}
return 0;
}
int save()
{int i;
for (i=1; i<=6; i++)
fprintf(fp,"%d\n",a[i]);
return 0;
}
int main()
{int i;
fp = fopen("pilaozhi.txt","w");
for(i=1; i<=6; i++)
{
printf("%d:", i);
scanf("%d", &a[i]);
}
for (;;)
{
scan();
printf("ˣ(1/0):\n1.ˣؼ\n0.\n");
scanf("%d", &i);
if (i == 1)
{
kitou();
printf("沢˳(1/0):\n");
scanf("%d", &i);
if (i == 1)
{
save();
break;
}
}
}
fclose(fp);
return 0;
}
|
C | #include <stdio.h>
int top=-1;
char a[20];
int push(char);
int main(){
int n,i,flag=0;
char c;
scanf("%d",&n);
fflush(stdin);
for (i=0;i<n;i++){
scanf("%c",&c);
if (c=='('||c=='{'||c=='['){
push(c);
}
else if ((c==')'&&a[top]=='(')||(c=='}'&&a[top]=='{')||(c==']'&&a[top]=='[')){
pop();
}
else{
printf("Not Balanced");
flag=1;
break;
}
}
if (flag==0) printf("Balanced");
return 0;
}
int pop(){
top--;
return 0;
}
int push(char x){
a[++top]=x;
return 0;
}
|
C | #include "expr_assert.h"
#include "assignment.h"
int fibo(int numberOfTerms,int *numberNeeded){
int a = -1,b = 1,i,c;
for(i=0;i<numberOfTerms;i++){
c = a + b;
numberNeeded[i] = c;
a = b;
b = c;
}
if(numberNeeded[0] == 0)
return 1;
return 0;
}
int concat(int *array1, int len_of_array1, int *array2, int len_of_array2, int *result_array){
int lenghtOfResultArray = len_of_array1 + len_of_array2, i, j=0;
for(i = 0; i < len_of_array1; i++){
result_array[i] = array1[i];
}
for(i = len_of_array1; i < lenghtOfResultArray; i++){
result_array[i] = array2[j];
j = j+1;
}
return lenghtOfResultArray;
}
int filter(int *array, int length, int threshold, int *result_array){
int i,j=0;
for(i = 0; i < length; i++){
if(array[i] > threshold){
result_array[j] = array[i];
j = j + 1;
}
}
return j;
}
int reverse(int *array, int length, int *result_array){
int j = 0,i;
for(i = length - 1; i >= 0; i--){
result_array[j] = array[i];
j = j + 1;
}
return j;
}
|
C | #include <avr/io.h>
#include "config.h"
#include "light.h"
#include "uart.h"
#include "history.h"
uint8_t handle_light(const char *cmd, char action) {
log_cmd(cmd, action);
int mask = 0;
char c = cmd[1];
// set bits in mask according to pins that should be changed
if (c == '*') {
mask = 0xff;
} else if (c >= '0' && c <= '7') {
uint8_t n = c - '0';
mask = 1 << n;
}
// set or clear pins
if (mask != 0) {
if (cmd[2] < '0' || cmd[2] > '1') {
return 0;
}
uint8_t val = cmd[2] - '0';
#if INVERSE
val = !val;
#endif
if (val) {
LIGHT_PORT |= mask;
} else {
LIGHT_PORT &= ~mask;
}
}
return mask;
}
void handle_light_query(void) {
uint8_t port = LIGHT_PORT;
#if INVERSE
port = ~port;
#endif
uart_putc('l');
uart_putc('=');
uart_putl(port, 1);
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.