language
large_stringclasses 1
value | text
stringlengths 9
2.95M
|
---|---|
C
|
#include "RCC.h"
typedef struct
{
volatile u32 CR; /* Clock control register, offset = 0x00*/
volatile u32 CFGR; /* Clock configuration register, offset = 0x04 */
volatile u32 CIR; /* Clock interrupt register, offset = 0x08 */
volatile u32 APB2RSTR; /* APB2 peripheral reset register, offset = 0x0C */
volatile u32 APB1RSTR; /* APB1 peripheral reset register, offset = 0x10 */
volatile u32 AHBENR; /* AHB peripheral clock enable register, offset = 0x14 */
volatile u32 APB2ENR; /* APB2 peripheral clock enable register, offset = 0x18 */
volatile u32 APB1ENR; /* APB1 peripheral clock enable register, offset = 0x1C */
volatile u32 BDCR; /* Backup domain control register, offset = 0x20 */
volatile u32 CSR; /* Control/status register, offset = 0x24 */
}RCC_t;
/* This is a pointer to a block that corresponds to RCC memory map */
volatile RCC_t* const RCC = (RCC_t*)0x40021000;
/*note add the PLL multiplier*/
extern STD_STATUS RCC_u8ControlClks(u32 Copy_u32ClkSelectionMask, STATE Copy_u8Status)
{
STD_STATUS local_u8ErrorStatus = STATUS_NOT_OK;
u32 Local_u32RegisterCopy = 0;
if(IS_RCC_CLK_MASK_VALID(Copy_u32ClkSelectionMask))
{
switch(Copy_u8Status)
{
case OFF:
Local_u32RegisterCopy = RCC->CR;
Local_u32RegisterCopy &= ~Copy_u32ClkSelectionMask;
RCC->CR = Local_u32RegisterCopy;
local_u8ErrorStatus = STATUS_OK;
break;
case ON:
Local_u32RegisterCopy = RCC->CR;
Local_u32RegisterCopy |= Copy_u32ClkSelectionMask;
RCC->CR = Local_u32RegisterCopy;
local_u8ErrorStatus = STATUS_OK;
break;
default:
local_u8ErrorStatus = STATUS_NOT_OK;
break;
}
}
else
{
local_u8ErrorStatus = STATUS_NOT_OK;
}
return local_u8ErrorStatus;
}
extern STD_STATUS RCC_u8SelectSysClk(u32 Copy_u32SysClkSelectionMask)
{
STD_STATUS local_u8ErrorStatus = STATUS_NOT_OK;
u32 Local_u32RegisterCopy = 0;
if(IS_RCC_SYS_CLK_MASK_VALID(Copy_u32SysClkSelectionMask))
{
Local_u32RegisterCopy = RCC->CFGR;
Local_u32RegisterCopy &= RCC_CFGR_SW_CLR_MASK;
Local_u32RegisterCopy |= Copy_u32SysClkSelectionMask;
RCC->CFGR = Local_u32RegisterCopy;
}
else
{
local_u8ErrorStatus = STATUS_NOT_OK;
}
return local_u8ErrorStatus;
}
extern STD_STATUS RCC_u8ControlPeripherals(BUS Copy_u8Bus, u32 Copy_u32PeripheralMask, STATE Copy_u8Status)
{
STD_STATUS local_u8ErrorStatus = STATUS_NOT_OK;
u32 Local_u32RegisterCopy = 0;
switch(Copy_u8Bus)
{
case AHB:
switch(Copy_u8Status)
{
case OFF:
Local_u32RegisterCopy = RCC->AHBENR;
Local_u32RegisterCopy &= ~Copy_u32PeripheralMask;
RCC->AHBENR = Local_u32RegisterCopy;
break;
case ON:
Local_u32RegisterCopy = RCC->AHBENR;
Local_u32RegisterCopy |= Copy_u32PeripheralMask;
RCC->AHBENR = Local_u32RegisterCopy;
break;
default:
local_u8ErrorStatus = STATUS_NOT_OK;
break;
}
break;
case APB2:
switch(Copy_u8Status)
{
case OFF:
Local_u32RegisterCopy = RCC->APB2ENR;
Local_u32RegisterCopy &= ~Copy_u32PeripheralMask;
RCC->APB2ENR = Local_u32RegisterCopy;
break;
case ON:
Local_u32RegisterCopy = RCC->APB2ENR;
Local_u32RegisterCopy |= Copy_u32PeripheralMask;
RCC->APB2ENR = Local_u32RegisterCopy;
break;
default:
local_u8ErrorStatus = STATUS_NOT_OK;
break;
}
break;
case APB1:
switch(Copy_u8Status)
{
case OFF:
Local_u32RegisterCopy = RCC->APB1ENR;
Local_u32RegisterCopy &= ~Copy_u32PeripheralMask;
RCC->APB1ENR = Local_u32RegisterCopy;
break;
case ON:
Local_u32RegisterCopy = RCC->APB1ENR;
Local_u32RegisterCopy |= Copy_u32PeripheralMask;
RCC->APB1ENR = Local_u32RegisterCopy;
break;
default:
local_u8ErrorStatus = STATUS_NOT_OK;
break;
}
break;
default:
local_u8ErrorStatus = STATUS_NOT_OK;
break;
}
return local_u8ErrorStatus;
}
|
C
|
#include<stdio.h>
void printCombinations(int a[], int data[], int start, int end, int index, int r, int d[], int l)
{
if(index==r)
{
int j;
for(j=0;j<r;j++) //print the combination from collosus' set
{
printf("%d ", data[j]);
}
for(j=0;j<l;j++) //print the set minus which is always required
{
if(d[j]!=999) printf("%d ",d[j]);
}
printf("\n");
}
else
{ int i;
for(i=start;(i<=end)&&(end-i+1>=r-index);i++)
{
data[index]= a[i];
printCombinations(a,data,i+1,end,index+1,r,d,l);
}
}
}
int main()
{
int n,k,l; //sizes of universal set, collosus' set and required set respectively
scanf("%d", &n);
int u[n]; //universal skillset
int i;
for(i=0;i<n;i++)
{
scanf("%d", &u[i]);
}
scanf("%d", &k);
int c[k]; //collossus' skillset
for(i=0;i<k;i++)
{
scanf("%d", &c[i]);
}
scanf("%d",&l);
int r[l]; //required skillset
int d[l]; //duplicate copy of r
for(i=0;i<l;i++)
{
scanf("%d", &r[i]);
d[i]=r[i];
}
for(i=0;i<k;i++) //index of collosus' set
{
int j; //here we are doing d - c ie r - c
for(j=0;j<l;j++) //index of duplicate ie required set
{
if(c[i]==d[j]) {d[j]=999; break;}
}
}
int data[k];
printf("***************\n");
for(i=0;i<l;i++)
{
if(d[i]!=999) printf("%d ",d[i]);
}
printf("\n");
for(i=1;i<=k;i++)
{
printCombinations(c,data,0,k-1,0,i,d,l);
}
return 0;
}
|
C
|
#include "game.h"
#include "timer.h"
#include "kbd.h"
#include "level.h"
Game* initGame() {
Game* game = (Game*) malloc(sizeof(Game));
game->result = PLAYING;
game->score = 0;
game->currLevel = 0;
game->timePerPlay = TIMEPERPLAY;
initLevels(game);
game->fundo = loadBitmap(
"/home/lcom/lcom1718-t6g08/prisonBreaker/res/fundo.bmp");
game->square = initSquare();
game->timeBar = loadBitmap(
"/home/lcom/lcom1718-t6g08/prisonBreaker/res/barra.bmp");
game->scoreNumbers = initScoreNumbers();
return game;
}
ScoreNumbers* initScoreNumbers() {
ScoreNumbers* scoreNumbers = (ScoreNumbers*) malloc(sizeof(ScoreNumbers));
scoreNumbers->numberOfNumbers = 10;
scoreNumbers->scoreNumbers = (Bitmap **) malloc(
sizeof(Bitmap*) * scoreNumbers->numberOfNumbers);
scoreNumbers->scoreNumbers[0] = loadBitmap(
"/home/lcom/lcom1718-t6g08/prisonBreaker/res/0.bmp");
scoreNumbers->scoreNumbers[1] = loadBitmap(
"/home/lcom/lcom1718-t6g08/prisonBreaker/res/1.bmp");
scoreNumbers->scoreNumbers[2] = loadBitmap(
"/home/lcom/lcom1718-t6g08/prisonBreaker/res/2.bmp");
scoreNumbers->scoreNumbers[3] = loadBitmap(
"/home/lcom/lcom1718-t6g08/prisonBreaker/res/3.bmp");
scoreNumbers->scoreNumbers[4] = loadBitmap(
"/home/lcom/lcom1718-t6g08/prisonBreaker/res/4.bmp");
scoreNumbers->scoreNumbers[5] = loadBitmap(
"/home/lcom/lcom1718-t6g08/prisonBreaker/res/5.bmp");
scoreNumbers->scoreNumbers[6] = loadBitmap(
"/home/lcom/lcom1718-t6g08/prisonBreaker/res/6.bmp");
scoreNumbers->scoreNumbers[7] = loadBitmap(
"/home/lcom/lcom1718-t6g08/prisonBreaker/res/7.bmp");
scoreNumbers->scoreNumbers[8] = loadBitmap(
"/home/lcom/lcom1718-t6g08/prisonBreaker/res/8.bmp");
scoreNumbers->scoreNumbers[9] = loadBitmap(
"/home/lcom/lcom1718-t6g08/prisonBreaker/res/9.bmp");
return scoreNumbers;
}
void initLevels(Game* game) {
game->levels = (Level**) malloc(NUMBEROFLEVELS * sizeof(Level*));
initBeginnerLevels(game);
initNormalLevels(game);
initAdvancedLevels(game);
initExpertLevels(game);
}
void initBeginnerLevels(Game* game) {
/***********************
* Level 1 - UP *
***********************/
Level * level1 = (Level*) malloc(sizeof(Level));
level1->levelID = 1;
level1->instruction = UP;
level1->numAcceptedDirections = 1;
level1->acceptedDirections = (short *) malloc(
sizeof(short) * level1->numAcceptedDirections);
level1->acceptedDirections[0] = UP_DIR;
level1->instructionBitmap = loadBitmap(
"/home/lcom/lcom1718-t6g08/prisonBreaker/res/up.bmp");
game->levels[0] = level1;
/***********************
* Level 2 - DOWN *
***********************/
Level * level2 = (Level*) malloc(sizeof(Level));
level2->levelID = 2;
level2->instruction = DOWN;
level2->numAcceptedDirections = 1;
level2->acceptedDirections = (short *) malloc(
sizeof(short) * level2->numAcceptedDirections);
level2->acceptedDirections[0] = DOWN_DIR;
level2->instructionBitmap = loadBitmap(
"/home/lcom/lcom1718-t6g08/prisonBreaker/res/down.bmp");
game->levels[1] = level2;
/***********************
* Level 3 - LEFT *
***********************/
Level * level3 = (Level*) malloc(sizeof(Level));
level3->levelID = 3;
level3->instruction = LEFT;
level3->numAcceptedDirections = 1;
level3->acceptedDirections = (short *) malloc(
sizeof(short) * level3->numAcceptedDirections);
level3->acceptedDirections[0] = LEFT_DIR;
level3->instructionBitmap = loadBitmap(
"/home/lcom/lcom1718-t6g08/prisonBreaker/res/left.bmp");
game->levels[2] = level3;
/*********************
* Level 4 - RIGHT *
*********************/
Level * level4 = (Level*) malloc(sizeof(Level));
level4->levelID = 4;
level4->instruction = RIGHT;
level4->numAcceptedDirections = 1;
level4->acceptedDirections = (short *) malloc(
sizeof(short) * level4->numAcceptedDirections);
level4->acceptedDirections[0] = RIGHT_DIR;
level4->instructionBitmap = loadBitmap(
"/home/lcom/lcom1718-t6g08/prisonBreaker/res/right.bmp");
game->levels[3] = level4;
}
void initNormalLevels(Game* game) {
/*************************
* Level 5 - NOT UP *
*************************/
Level * level5 = (Level*) malloc(sizeof(Level));
level5->levelID = 5;
level5->instruction = NOT_UP;
level5->numAcceptedDirections = 3;
level5->acceptedDirections = (short *) malloc(
sizeof(short) * level5->numAcceptedDirections);
level5->acceptedDirections[0] = DOWN_DIR;
level5->acceptedDirections[1] = LEFT_DIR;
level5->acceptedDirections[2] = RIGHT_DIR;
level5->instructionBitmap = loadBitmap(
"/home/lcom/lcom1718-t6g08/prisonBreaker/res/notup.bmp");
game->levels[4] = level5;
/*************************
* Level 6 - NOT DOWN *
*************************/
Level * level6 = (Level*) malloc(sizeof(Level));
level6->levelID = 6;
level6->instruction = NOT_DOWN;
level6->numAcceptedDirections = 3;
level6->acceptedDirections = (short *) malloc(
sizeof(short) * level6->numAcceptedDirections);
level6->acceptedDirections[0] = UP_DIR;
level6->acceptedDirections[1] = LEFT_DIR;
level6->acceptedDirections[2] = RIGHT_DIR;
level6->instructionBitmap = loadBitmap(
"/home/lcom/lcom1718-t6g08/prisonBreaker/res/notdown.bmp");
game->levels[5] = level6;
/***********************
* Level 7 - NOT LEFT *
***********************/
Level * level7 = (Level*) malloc(sizeof(Level));
level7->levelID = 7;
level7->instruction = NOT_LEFT;
level7->numAcceptedDirections = 3;
level7->acceptedDirections = (short *) malloc(
sizeof(short) * level7->numAcceptedDirections);
level7->acceptedDirections[0] = UP_DIR;
level7->acceptedDirections[1] = DOWN_DIR;
level7->acceptedDirections[2] = RIGHT_DIR;
level7->instructionBitmap = loadBitmap(
"/home/lcom/lcom1718-t6g08/prisonBreaker/res/notleft.bmp");
game->levels[6] = level7;
/***********************
* Level 8 - NOT RIGHT *
***********************/
Level * level8 = (Level*) malloc(sizeof(Level));
level8->levelID = 8;
level8->instruction = NOT_RIGHT;
level8->numAcceptedDirections = 3;
level8->acceptedDirections = (short *) malloc(
sizeof(short) * level8->numAcceptedDirections);
level8->acceptedDirections[0] = UP_DIR;
level8->acceptedDirections[1] = DOWN_DIR;
level8->acceptedDirections[2] = LEFT_DIR;
level8->instructionBitmap = loadBitmap(
"/home/lcom/lcom1718-t6g08/prisonBreaker/res/notright.bmp");
game->levels[7] = level8;
}
void initAdvancedLevels(Game* game) {
/*************************
* Level 9 - NOT NOT UP *
*************************/
Level * level9 = (Level*) malloc(sizeof(Level));
level9->levelID = 9;
level9->instruction = NOT_NOT_UP;
level9->numAcceptedDirections = 1;
level9->acceptedDirections = (short *) malloc(
sizeof(short) * level9->numAcceptedDirections);
level9->acceptedDirections[0] = UP_DIR;
level9->instructionBitmap = loadBitmap(
"/home/lcom/lcom1718-t6g08/prisonBreaker/res/notnotup.bmp");
game->levels[8] = level9;
/***************************
* Level 10 - NOT NOT DOWN *
***************************/
Level * level10 = (Level*) malloc(sizeof(Level));
level10->levelID = 10;
level10->instruction = NOT_NOT_DOWN;
level10->numAcceptedDirections = 1;
level10->acceptedDirections = (short *) malloc(
sizeof(short) * level10->numAcceptedDirections);
level10->acceptedDirections[0] = DOWN_DIR;
level10->instructionBitmap = loadBitmap(
"/home/lcom/lcom1718-t6g08/prisonBreaker/res/notnotdown.bmp");
game->levels[9] = level10;
/***************************
* Level 11 - NOT NOT LEFT *
***************************/
Level * level11 = (Level*) malloc(sizeof(Level));
level11->levelID = 11;
level11->instruction = NOT_NOT_LEFT;
level11->numAcceptedDirections = 1;
level11->acceptedDirections = (short *) malloc(
sizeof(short) * level11->numAcceptedDirections);
level11->acceptedDirections[0] = LEFT_DIR;
level11->instructionBitmap = loadBitmap(
"/home/lcom/lcom1718-t6g08/prisonBreaker/res/notnotleft.bmp");
game->levels[10] = level11;
/****************************
* Level 12 - NOT NOT RIGHT *
***************************/
Level * level12 = (Level*) malloc(sizeof(Level));
level12->levelID = 12;
level12->instruction = NOT_NOT_RIGHT;
level12->numAcceptedDirections = 1;
level12->acceptedDirections = (short *) malloc(
sizeof(short) * level12->numAcceptedDirections);
level12->acceptedDirections[0] = RIGHT_DIR;
level12->instructionBitmap = loadBitmap(
"/home/lcom/lcom1718-t6g08/prisonBreaker/res/notnotright.bmp");
game->levels[11] = level12;
}
void initExpertLevels(Game* game) {
/************************
* Level 13 - NOTHING *
***********************/
Level * level13 = (Level*) malloc(sizeof(Level));
level13->levelID = 13;
level13->instruction = NOTHING;
level13->numAcceptedDirections = 1;
level13->acceptedDirections = (short *) malloc(
sizeof(short) * level13->numAcceptedDirections);
level13->acceptedDirections[0] = NOTHING_DIR;
level13->instructionBitmap = loadBitmap(
"/home/lcom/lcom1718-t6g08/prisonBreaker/res/nothing.bmp");
game->levels[12] = level13;
/***************************
* Level 14 - NOT NOTHING *
**************************/
Level * level14 = (Level*) malloc(sizeof(Level));
level14->levelID = 14;
level14->instruction = NOT_NOTHING;
level14->numAcceptedDirections = 4;
level14->acceptedDirections = (short *) malloc(
sizeof(short) * level14->numAcceptedDirections);
level14->acceptedDirections[0] = UP_DIR;
level14->acceptedDirections[1] = DOWN_DIR;
level14->acceptedDirections[2] = LEFT_DIR;
level14->acceptedDirections[3] = RIGHT_DIR;
level14->instructionBitmap = loadBitmap(
"/home/lcom/lcom1718-t6g08/prisonBreaker/res/notnothing.bmp");
game->levels[13] = level14;
/*******************************
* Level 15 - NOT NOT NOTHING *
******************************/
Level * level15 = (Level*) malloc(sizeof(Level));
level15->levelID = 15;
level15->instruction = NOT_NOT_NOTHING;
level15->numAcceptedDirections = 1;
level15->acceptedDirections = (short *) malloc(
sizeof(short) * level15->numAcceptedDirections);
level15->acceptedDirections[0] = NOTHING_DIR;
level15->instructionBitmap = loadBitmap(
"/home/lcom/lcom1718-t6g08/prisonBreaker/res/notnotnothing.bmp");
game->levels[14] = level15;
}
void gameUpdate(Game* game, Timer* timer, Mouse* mouse) {
switch (game->result) {
case PLAYING:
if (timer->counter == game->timePerPlay) {
Level* currentLevel = game->levels[game->currLevel];
if (!isAcceptedDirection(currentLevel, NOTHING_DIR)) {
game->result = LOSE;
} else {
selectNextLevel(game);
resetMouse(mouse);
resetTimer(timer);
}
}
break;
case WAITING:
updateSquare(game->square);
if (hasFinishedMovement(game->square)) {
selectNextLevel(game);
resetMouse(mouse);
resetTimer(timer);
}
break;
case LOSE:
break;
}
}
void gameUpdateKeyboard(Game* game, unsigned long scancode) {
Level* currentLevel = game->levels[game->currLevel];
short dir = getDirectionFromKey(scancode);
if (dir == INVALID_DIR)
return;
if (game->result == PLAYING) {
if (isAcceptedDirection(currentLevel, dir)) {
game->result = WAITING;
game->square->direction = dir;
} else
game->result = LOSE;
}
}
void gameUpdateMouse(Game* game, Mouse* mouse) {
Level* currentLevel = game->levels[game->currLevel];
short dir = getDirectionFromMouse(mouse);
if (dir == INVALID_DIR)
return;
if (game->result == PLAYING) {
if (isAcceptedDirection(currentLevel, dir)) {
game->result = WAITING;
game->square->direction = dir;
} else
game->result = LOSE;
}
}
void displayGame(Game* game, Timer* timer) {
drawBitmap(game->fundo, 0, 0, ALIGN_LEFT);
displayLevel(game->levels[game->currLevel]);
displaySquare(game->square);
displayTimeBar(game, timer);
}
void displayTimeBar(Game* game, Timer* timer) {
long currTicks = timer->ticks;
if (currTicks > game->timePerPlay * 60) {
drawBitmap(game->timeBar, BAR_X_COORD_END, BAR_Y_COORD, ALIGN_LEFT);
return;
}
long XCoordBar = currTicks * (BAR_X_COORD_END - BAR_X_COORD_START)
/ (game->timePerPlay * 60.0) + BAR_X_COORD_START;
drawBitmap(game->timeBar, XCoordBar, BAR_Y_COORD, ALIGN_LEFT);
}
void displayScore(Game* game) {
short gameFinalScore = game->score;
short deltax = 0;
short deltay = 0;
if (gameFinalScore == 0)
drawBitmap(game->scoreNumbers->scoreNumbers[0], SCORE_X_COORD_START,
SCORE_Y_COORD_START, ALIGN_LEFT);
while (gameFinalScore) {
short bitmapToPrint = gameFinalScore % 10;
drawBitmap(game->scoreNumbers->scoreNumbers[bitmapToPrint],
SCORE_X_COORD_START + deltax, SCORE_Y_COORD_START + deltay, ALIGN_LEFT);
gameFinalScore /= 10;
deltax -= SCORE_DELTAX;
deltay -= SCORE_DELTAY;
}
}
void selectNextLevel(Game* game) {
//generates Random Number [0 - NUMBEROFLEVELS-1]
int nextLevel = rand() % NUMBEROFLEVELS;
game->score++;
game->currLevel = nextLevel;
game->result = PLAYING;
}
void resetGame(Game* game) {
game->result = PLAYING;
game->score = 0;
game->currLevel = 0;
}
short getDirectionFromKey(unsigned long scancode) {
if (scancode == KEY_TO_MOVE_LEFT)
return LEFT_DIR;
if (scancode == KEY_TO_MOVE_RIGHT)
return RIGHT_DIR;
if (scancode == KEY_TO_MOVE_UP)
return UP_DIR;
if (scancode == KEY_TO_MOVE_DOWN)
return DOWN_DIR;
return INVALID_DIR;
}
short getDirectionFromMouse(Mouse* mouse) {
if (mouse->deltaX > MIN_MOUSE_MOVEMENT)
return RIGHT_DIR;
if (mouse->deltaX < -MIN_MOUSE_MOVEMENT)
return LEFT_DIR;
if (mouse->deltaY > MIN_MOUSE_MOVEMENT)
return UP_DIR;
if (mouse->deltaY < -MIN_MOUSE_MOVEMENT)
return DOWN_DIR;
return INVALID_DIR;
}
void freeGameLevels(Game* game) {
int i;
for (i = 0; i < NUMBEROFLEVELS; i++) {
freeLevel(game->levels[i]);
}
free(game->levels);
}
void freeScoreNumbers(ScoreNumbers* scoreNumbers) {
int i;
for (i = 0; i < scoreNumbers->numberOfNumbers; i++) {
deleteBitmap(scoreNumbers->scoreNumbers[i]);
}
free(scoreNumbers);
}
void freeGame(Game* game) {
freeGameLevels(game);
freeSquare(game->square);
deleteBitmap(game->fundo);
deleteBitmap(game->timeBar);
freeScoreNumbers(game->scoreNumbers);
free(game);
}
|
C
|
/*Scrieti un program pentru scaderea a 2 numere reale. Numarul de cifre -
pana la 1000 de ambele parti ale virgulei
Write a program for the division of 2 real numbers. Number of digits -
up to 1000 on both sides of the comma*/
#include <stddef.h>
#include <stdio.h>
#include <stdlib.h>
int my_strlen (char *str) {
int len = 0;
while (*str != '\0') {
str++;
len++;
}
return len;
}
// Multiplies str1 and str2, and prints result.
char* multiply(char* num1, char* num2)
{
int len1 = my_strlen(num1);
int len2 = my_strlen(num2);
if (len1 == 0 || len2 == 0)
return "0";
// will keep the result number in vector
// in reverse order
char* result = malloc(sizeof(char) * (len1 + len2));
for(int i=0; i < len1 + len2; i++)
result[i] = '0';
// Below two indexes are used to find positions
// in result.
int i_n1 = 0;
int i_n2 = 0;
// Go from right to left in num1
for (int i=len1-1; i>=0; i--)
{
int carry = 0;
int n1 = num1[i] - '0';
// To shift position to left after every
// multiplication of a digit in num2
i_n2 = 0;
// Go from right to left in num2
for (int j=len2-1; j>=0; j--)
{
// Take current digit of second number
int n2 = num2[j] - '0';
// Multiply with current digit of first number
// and add result to previously stored result
// at current position.
int sum = n1*n2 + atoi(&result[i_n1 + i_n2]) + carry;
// Carry for next iteration
carry = sum/10;
// Store result
char c =(sum % 10) + '0';
result[i_n1 + i_n2] = c ;
i_n2++;
}
// store carry in next cell
if (carry > 0){
int temp = atoi(&result[i_n1 + i_n2]);
temp = temp + carry;
result[i_n1 + i_n2] = temp + '0';
}
// To shift position to left after every
// multiplication of a digit in num1.
i_n1++;
}
// ignore '0's from the right
int i = my_strlen(result) - 1;
while (i>=0 && atoi(&result[i]) == 0)
i--;
// If all were '0's - means either both or
// one of num1 or num2 were '0'
if (i == -1)
return "0";
// generate the result string
char* s = malloc(sizeof(char) * len1 + len1);
int len_str = 0;
while (i >= 0){
s[len_str] = result[i--];
len_str++;
}
return s;
}
int main()
{
char* str1;
char* str2;
int n;
char c;
int first_comma_position;
int second_comma_position;
int final_comma;
printf("Dati dimeanisunea la numar \n");
scanf("%d", &n);
str1 = malloc( sizeof(char) * n);
for(int i=0; i < n; i++){
scanf(" %c", &c);
if(c == '.'){
first_comma_position = i;
scanf(" %c", &c);
}
str1[i] = c;
}
first_comma_position = n - first_comma_position;
printf("Dati dimeanisunea la numar \n");
scanf("%d", &n);
str2 = malloc( sizeof(char) * n);
printf("Dati numarul\n");
for(int i=0; i < n; i++){
scanf(" %c", &c);
if(c == '.'){
second_comma_position = i;
scanf(" %c", &c);
}
str2[i] = c;
}
second_comma_position = n - second_comma_position;
final_comma = first_comma_position + second_comma_position;
char *result = multiply(str1, str2);
int len = my_strlen(result);
final_comma = len - final_comma;
for(int i=0; i < len; i++){
if( i == final_comma){
printf(".");
}
printf("%c", result[i]);
}
return 0;
}
|
C
|
#include <stdio.h>
float C;
void C_to_F(float C);
int main(){
printf("Her skal vi regne om celsius til farenheit\n");
printf("Hvor mange grader celsius vil du gjøre om til farenheit?\n");
scanf("%f",&C);
C_to_F(C);
return 0;
}
void C_to_F(float C){
float F;
F = ((9.0/5.0)*C+32.0);
printf("%.2f celsius er %.2f farenheit\n",C,F);
}
|
C
|
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
int main() {
int qtd, i, soma=0;
scanf("%d", &qtd);
int num[qtd];
for(i=0; i<qtd; i++){
scanf("%d", &num[i]);
if(num[i]%2 == 0){
num[i] = +1;
} else {
num[i]= -1;
}
soma = soma + num[i];
}
printf("%d", soma);
return 0;
}
|
C
|
#pragma once
#include <stdint.h>
typedef struct display display_t;
typedef struct display {
void (*draw_line)(display_t *this, uint8_t *line);
void (*show)(display_t *this);
void (*delete)(display_t *this);
} display_t ;
|
C
|
# 1 "MAP/SAFE-exbench/DAGGER-efm.tmp.c"
# 1 "<command-line>"
# 1 "MAP/SAFE-exbench/DAGGER-efm.tmp.c"
# 18 "MAP/SAFE-exbench/DAGGER-efm.tmp.c"
int nondet() {int i; return i;}
int X1;
int X2;
int X3;
int X4;
int X5;
int X6;
void main()
{
/*
int X1;
int X2;
int X3;
int X4;
int X5;
int X6;
*/
if (! (X1>=1)) return;
if (! (X2==0)) return;
if (! (X3==0)) return;
if (! (X4==1)) return;
if (! (X5==0)) return;
if (! (X6==0)) return;
while(nondet())
{
if (nondet())
{
if (! (X1 >= 1)) return;
if (! (X4 >= 1)) return;
X1=X1-1;
X4=X4-1;
X2=X2+1;
X5=X5+1;
}
else
{
if (nondet())
{
if (! (X2 >= 1)) return;
if (! (X6 >= 1)) return;
X2=X2-1;
X3=X3+1;
}
else
{
if (nondet())
{
if (! (X4 >= 1)) return;
if (! (X3 >= 1)) return;
X3=X3-1;
X2=X2+1;
}
else
{
if (nondet())
{
if (! (X3>=1)) return;
X3=X3-1;
X1=X1+1;
X6=X6+X5;
X5=0;
}
else
{
if (! (X2 >= 1)) return;
X2 = X2 - 1;
X1 = X1 + 1;
X4 = X4 + X6;
X6 = 0;
}
}
}
}
}
__VERIFIER_assert( X4 + X5 + X6 -1 >= 0 );
__VERIFIER_assert( X4 + X5 + X6 -1 <= 0 );
__VERIFIER_assert( X4 + X5 <= 1 );
__VERIFIER_assert( X5 >= 0 );
__VERIFIER_assert( X4 >= 0 );
__VERIFIER_assert( X3 >= 0 );
__VERIFIER_assert( X2 >= 0 );
__VERIFIER_assert( X1 + X5 >= 1 );
__VERIFIER_assert( X1 + X2 >= X4 + X5 );
__VERIFIER_assert( X1 + X2 + X3 >= 1 );
}
|
C
|
void ft_swap(int *a, int *b)
{
int x;
x = *a;
*a = *b;
*b = x;
}
|
C
|
#include <stdio.h>
int main ()
{
float basetriangulo, alturatriangulo, areatriangulo;
printf("entre com a base do triangulo: ");
scanf("%f", &basetriangulo);
printf(" entre com a altura do triangulo: ");
scanf("%f", &alturatriangulo);
areatriangulo= (basetriangulo *alturatriangulo)/2;
printf(" a area do triangulo eh: %f", areatriangulo);
return 0;
}
|
C
|
/*
A web client with the following command line usage
webclient url
Invoke the program with
./webclient http://localhost/
which sends a HTTP request “GET URL HTTP/1.0” to the specified URL (e.g., the local Apache http server), where URL is the command line
argument. The web client then calls shutdown(), prints (to stdout) the entire HTTP response (header and body), and then exits.
• The HTTP request does not have headers nor body.
• The client looks up the server info by calling getaddrinfo(3), before the client calls socket(2).
• To simplify the code, the client only handles http on port 80. Note the URL is limited to any URL based on http (without port).
• Make sure HTTP response status is 200 or 3XX, not 4XX or 5XX.
*/
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netinet/ip.h>
#include <unistd.h>
#include <string.h>
#include <arpa/inet.h>
#include <errno.h>
#include <netdb.h>
#define PRINT
int main (int argc, char* argv[])
{
int success = 0;
char path[20];
char host[20];
if (sscanf(argv[1], "http://%99[^/]/%199[^\n]", host, path) == 2)
{
success = 1;/* http://hostname/page*/
}
else if (sscanf(argv[1], "http://%99[^/]/[^\n]", host) == 1)
{
success = 1; /* http://hostname/ */
}
else if (sscanf(argv[1], "http://%99[^\n]", host) == 1)
{
success =1; /* http://hostname */
}
PRINT("\nHost is %s ", host);
struct addrinfo hints;
struct addrinfo *result, *rp;
int sfd, s;
char *service = "http";
memset(&hints, 0, sizeof(struct addrinfo));
hints.ai_family = AF_INET;
hints.ai_socktype = SOCK_STREAM ;
hints.ai_flags = 0;
hints.ai_protocol = 0; /* Any protocol */
s = getaddrinfo(host,service , &hints, &result);
if (s != 0)
{
fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(s));
exit(EXIT_FAILURE);
}
for (rp = result; rp != NULL; rp = rp->ai_next)
{
sfd = socket(rp->ai_family, rp->ai_socktype,rp->ai_protocol);
if (sfd == -1)
continue;
PRINT("socket created");
if (connect(sfd, rp->ai_addr, rp->ai_addrlen) != -1)
{
PRINT("\nConnection is established ");
break;
} /* Success */
close(sfd);
}
if (rp == NULL) /* No address succeeded */
{
fprintf(stderr, "Could not connect\n");
exit(EXIT_FAILURE);
}
freeaddrinfo(result); /* No longer needed */
char *url1="GET ";
char *url2= argv[1];
char *url3= " HTTP/1.0\r\n";
char *url4= "\r\n";
char *url = malloc( strlen(url1)+ strlen (url2) + strlen (url3) + strlen(url4) + 1);
strcpy(url ,url1);
strcat(url, url2);
strcat(url, url3);
strcat(url, url4);
int w,r,c;
w = write(sfd, url, strlen(url));
if (w == -1)
{
perror("error");
return -1;
}
PRINT("\nHTTP request is %s",url);
shutdown(sfd, SHUT_WR);
PRINT("\nWrite half is closed\n");
int len = 15000;
char *buffer = malloc(sizeof(char) * len);
char *final = buffer;
while((r = read (sfd, buffer,len))>0)
{
buffer += r;
len -= r;
}
buffer++;
*buffer = '\0';
printf(" \n\n%s\n", final);
c = close(sfd);
if (w == -1)
{
perror("error");
return -1;
}
PRINT("\nClosed\n");
return 0;
}
|
C
|
/*
* Application.c
* Facebook username : ahmed mohamed
* Full name : ahmed mohamed mohamed
* Created on: Dec 7, 2019
* Author: Ahmed badra
*/
#include<avr/io.h>
#include<avr/interrupt.h>
#include<util/delay.h>
/*global time variables*/
unsigned char Seconds;
unsigned char Minutes;
unsigned char Hours;
/*timer1
*FOC1A & FOC1B set to one
*init TCNT1
*set value in ICR1 to compare
*WGM13 & WGM12 set to 1 for CTC mode
*CS10 & CS11 set to 1 for prescaler 64
*Fcpu = 1 Mhz
*for 1 sec need to interrupt at 15625 count
*in TIMSK -> OCIE1A set to 1 to enable Timer1 compare match interrupt A
*enable Global interrupt
*voila timer1 is counting and waiting for flag to interrupt it in 1 sec
*/
void Timer1_CTC_init(void)
{
/*function definition*/
TCCR1A = (1<<FOC1A) | (1<<FOC1B);
TCCR1B |= (1<<WGM13) | (1<<WGM12) | (1<<CS10) | (1<<CS11);
TIMSK |= (1<<OCIE1A);
TCNT1 = 0;
/*counting for 15624 for 1 sec delay*/
ICR1 = 15624;
}
/*
* Timer0
* CTC Mode operation
* OCR0 = 78 for 5 msec count
* at Fcpu = 1 Mhz
* TCNT0 = 0
* FOC0 set to 1 for non-PWM
* WGM01 ar TCCR0 set to 1 for CTC
* CS00 & CS01 both are 1's for 64 prescaler
* at TIMSK -> OCIE0 set to 1 for compare match interrupt enable
*/
void Timer0_CTC_init(void)
{
/*function definition*/
TCCR0 = (1<<FOC0) | (1<<WGM01) | (1<<CS00) | (1<<CS01);
TIMSK = (1<<OCIE0);
TCNT0 = 0;
OCR0 = 78;
}
void INT0_init(void)
{
/*function definition*/
GICR |= (1<<6);
MCUCR |= (1<<ISC01);
DDRD &=~(1<<2);
PORTD |= (1<<2);
}
void INT1_init(void)
{
/*function definition*/
GICR |= (1<<7);
MCUCR |= (1<<ISC11);
DDRD &=~(1<<3);
PORTD |= (1<<3);
}
void INT2_init(void)
{
/*function definition*/
GICR |= (1<<5);
MCUCSR |= (1<<ISC2);
DDRB &=~(1<<2);
PORTB |= (1<<2);
}
int main(void)
{
/*initilization code*/
/*setting PA0 to PA5 & PC0 to PC3 o\p pins*/
DDRA |= 0x3F;
DDRC |= 0x1F;
/*init the pins*/
PORTC &=0xF0;
PORTC |=(1<<PC4);
PORTA &=0xC0;
INT0_init();
INT1_init();
INT2_init();
Timer0_CTC_init();
Timer1_CTC_init();
/*global interrupt enable*/
SREG |= (1<<7);
/*starting incrementing timer0 for seconds , minutes , hours*/
TCCR1B |= (1<<CS10) | (1<<CS11);
/*start with variables ((((((((((((edit here)))))))))))*/
Seconds = 0;
Minutes = 0;
Hours = 0;
/*------------------------------------------------*/
/*super loop*/
while(1)
{
/*Application code*/
}
}
//--------------------------------------------------
/*interrupt service routines*/
//--------------------------------------------------
ISR(INT2_vect)
{
/*interrupt service routine of external INT0*/
/* continue the counting */
TCCR1B |= (1<<CS10) | (1<<CS11);
}
ISR(INT1_vect)
{
/*interrupt service routine of external INT0*/
/*stopping the counting */
TCCR1B &= ~((1<<CS10) | (1<<CS11));
}
ISR(INT0_vect)
{
/*interrupt service routine of external INT0*/
/*initiate the clock */
Seconds = 0;
Minutes = 0;
Hours = 0;
}
ISR(TIMER0_COMP_vect)
{
/*interrupt service routine for timer0 interrupt*/
/*each 5 msec Timer0 display current time variables for 3 milliseconds*/
for(int i =0 ; i<6 ; i++)
{
/*enabling the displaying 7-segment*/
PORTA = (PORTA &0xC0) | (1<<i);
if(i == 0) PORTC = ((Seconds % 10)&0x0F) | (PORTC &0xF0);
if(i == 1) PORTC = ((Seconds / 10)&0x0F) | (PORTC &0xF0);
if(i == 2) PORTC = ((Minutes % 10)&0x0F) | (PORTC &0xF0);
if(i == 3) PORTC = ((Minutes / 10)&0x0F) | (PORTC &0xF0);
if(i == 4) PORTC = ((Hours % 10)&0x0F) | (PORTC &0xF0);
if(i == 5) PORTC = ((Hours / 10)&0x0F) | (PORTC &0xF0);
/*delay to be able to see the display*/
_delay_ms(3);
}
}
ISR(TIMER1_COMPA_vect)
{
/*interrupt servive routine of TIMER1 interrupt*/
/*each 1 Sec TIMER1 update time Variables*/
if(Seconds == 59)
{
Seconds = 0;
if(Minutes == 59)
{
Minutes = 0;
if(Hours == 23)
{
Hours = 0;
}
else
{
Hours++;
}
}
else
{
Minutes++;
}
}
else
{
Seconds++;
}
}
|
C
|
#include <fsal/fsal.h>
#include <fsal/dir.h>
#include <core/filesrv.h>
#include <core/fstype.h>
#include <stdio.h>
#include <stddef.h>
#include <drivers/disk.h>
static int __open(void *path, int flags)
{
if (path == NULL)
return -1;
fsal_path_t *fpath = fsal_path_find(path, 1);
if (fpath == NULL) {
printf("path %s not found!\n", path);
return -1;
}
/* 查找对应的文件系统 */
fsal_t *fsal = fpath->fsal;
if (fsal == NULL) {
printf("path %s fsal error!\n", path);
return -1;
}
/* 转换路径 */
char new_path[MAX_PATH] = {0};
if (fsal_path_switch(fpath, new_path, path) < 0)
return -1;
//srvprint("open path:%s\n", new_path);
/* 执行打开 */
return fsal->open(new_path, flags);
}
static int __close(int idx)
{
if (ISBAD_FSAL_FIDX(idx))
return -1;
/* 查找对应的文件系统 */
fsal_file_t *fp = FSAL_I2F(idx);
fsal_t *fsal = fp->fsal;
if (fsal == NULL)
return -1;
return fsal->close(idx);
}
static int __ftruncate(int idx, off_t offset)
{
if (ISBAD_FSAL_FIDX(idx))
return -1;
/* 查找对应的文件系统 */
fsal_file_t *fp = FSAL_I2F(idx);
fsal_t *fsal = fp->fsal;
if (fsal == NULL)
return -1;
return fsal->ftruncate(idx, offset);
}
static int __read(int idx, void *buf, size_t size)
{
if (ISBAD_FSAL_FIDX(idx))
return -1;
/* 查找对应的文件系统 */
fsal_file_t *fp = FSAL_I2F(idx);
fsal_t *fsal = fp->fsal;
if (fsal == NULL)
return -1;
return fsal->read(idx, buf, size);
}
static int __write(int idx, void *buf, size_t size)
{
if (ISBAD_FSAL_FIDX(idx))
return -1;
/* 查找对应的文件系统 */
fsal_file_t *fp = FSAL_I2F(idx);
fsal_t *fsal = fp->fsal;
if (fsal == NULL)
return -1;
return fsal->write(idx, buf, size);
}
static int __lseek(int idx, off_t off, int whence)
{
if (ISBAD_FSAL_FIDX(idx))
return -1;
/* 查找对应的文件系统 */
fsal_file_t *fp = FSAL_I2F(idx);
fsal_t *fsal = fp->fsal;
if (fsal == NULL)
return -1;
return fsal->lseek(idx, off, whence);
}
static int __fsync(int idx)
{
if (ISBAD_FSAL_FIDX(idx))
return -1;
/* 查找对应的文件系统 */
fsal_file_t *fp = FSAL_I2F(idx);
fsal_t *fsal = fp->fsal;
if (fsal == NULL)
return -1;
return fsal->fsync(idx);
}
static int __opendir(char *path)
{
if (path == NULL)
return -1;
fsal_path_t *fpath = fsal_path_find(path, 1);
if (fpath == NULL) {
printf("path %s not found!\n", path);
return -1;
}
/* 查找对应的文件系统 */
fsal_t *fsal = fpath->fsal;
if (fsal == NULL) {
printf("path %s fsal error!\n", path);
return -1;
}
/* 转换路径 */
char new_path[MAX_PATH] = {0};
if (fsal_path_switch(fpath, new_path, path) < 0) {
printf("path %s switch error!\n", path);
return -1;
}
/* 执行打开 */
return fsal->opendir(new_path);
}
static int __closedir(int idx)
{
if (ISBAD_FSAL_DIDX(idx))
return -1;
/* 查找对应的文件系统 */
fsal_dir_t *pdir = FSAL_I2D(idx);
fsal_t *fsal = pdir->fsal;
if (fsal == NULL)
return -1;
return fsal->closedir(idx);
}
static int __readdir(int idx, void *buf)
{
if (ISBAD_FSAL_DIDX(idx))
return -1;
/* 查找对应的文件系统 */
fsal_dir_t *pdir = FSAL_I2D(idx);
fsal_t *fsal = pdir->fsal;
if (fsal == NULL)
return -1;
return fsal->readdir(idx, buf);
}
static int __mkdir(char *path, mode_t mode)
{
if (path == NULL)
return -1;
fsal_path_t *fpath = fsal_path_find(path, 1);
if (fpath == NULL) {
printf("path %s not found!\n", path);
return -1;
}
/* 查找对应的文件系统 */
fsal_t *fsal = fpath->fsal;
if (fsal == NULL) {
printf("path %s fsal error!\n", path);
return -1;
}
/* 转换路径 */
char new_path[MAX_PATH] = {0};
if (fsal_path_switch(fpath, new_path, path) < 0)
return -1;
/* 执行打开 */
return fsal->mkdir(new_path, mode);
}
static int __unlink(char *path)
{
if (path == NULL)
return -1;
fsal_path_t *fpath = fsal_path_find(path, 1);
if (fpath == NULL) {
printf("path %s not found!\n", path);
return -1;
}
/* 查找对应的文件系统 */
fsal_t *fsal = fpath->fsal;
if (fsal == NULL) {
printf("path %s fsal error!\n", path);
return -1;
}
/* 转换路径 */
char new_path[MAX_PATH] = {0};
if (fsal_path_switch(fpath, new_path, path) < 0)
return -1;
/* 执行打开 */
return fsal->unlink(new_path);
}
static int __rename(char *old_path, char *new_path)
{
if (old_path == NULL || new_path == NULL)
return -1;
fsal_path_t *fpath = fsal_path_find(old_path, 1);
if (fpath == NULL) {
printf("path %s not found!\n", old_path);
return -1;
}
/* 查找对应的文件系统 */
fsal_t *fsal = fpath->fsal;
if (fsal == NULL) {
printf("path %s fsal error!\n", old_path);
return -1;
}
/* 转换路径 */
char old_path2[MAX_PATH] = {0};
if (fsal_path_switch(fpath, old_path2, old_path) < 0)
return -1;
char new_path2[MAX_PATH] = {0};
if (fsal_path_switch(fpath, new_path2, new_path) < 0)
return -1;
/* 执行打开 */
return fsal->rename(old_path2, new_path2);
}
static int __state(char *path, void *buf)
{
if (path == NULL)
return -1;
fsal_path_t *fpath = fsal_path_find(path, 1);
if (fpath == NULL) {
printf("path %s not found!\n", path);
return -1;
}
/* 查找对应的文件系统 */
fsal_t *fsal = fpath->fsal;
if (fsal == NULL) {
printf("path %s fsal error!\n", path);
return -1;
}
/* 转换路径 */
char new_path[MAX_PATH] = {0};
if (fsal_path_switch(fpath, new_path, path) < 0)
return -1;
/* 执行打开 */
return fsal->state(new_path, buf);
}
static int __fstat(int idx, void *buf)
{
if (ISBAD_FSAL_DIDX(idx))
return -1;
/* 查找对应的文件系统 */
fsal_dir_t *pdir = FSAL_I2D(idx);
fsal_t *fsal = pdir->fsal;
if (fsal == NULL)
return -1;
return fsal->fstat(idx, buf);
}
static int __chmod(char *path, mode_t mode)
{
if (path == NULL)
return -1;
fsal_path_t *fpath = fsal_path_find(path, 1);
if (fpath == NULL) {
printf("path %s not found!\n", path);
return -1;
}
/* 查找对应的文件系统 */
fsal_t *fsal = fpath->fsal;
if (fsal == NULL) {
printf("path %s fsal error!\n", path);
return -1;
}
/* 转换路径 */
char new_path[MAX_PATH] = {0};
if (fsal_path_switch(fpath, new_path, path) < 0)
return -1;
/* 执行打开 */
return fsal->chmod(new_path, mode);
}
static int __fchmod(int idx, mode_t mode)
{
if (ISBAD_FSAL_DIDX(idx))
return -1;
/* 查找对应的文件系统 */
fsal_dir_t *pdir = FSAL_I2D(idx);
fsal_t *fsal = pdir->fsal;
if (fsal == NULL)
return -1;
return fsal->fchmod(idx, mode);
}
static int __utime(char *path, time_t actime, time_t modtime)
{
if (path == NULL)
return -1;
fsal_path_t *fpath = fsal_path_find(path, 1);
if (fpath == NULL) {
printf("path %s not found!\n", path);
return -1;
}
/* 查找对应的文件系统 */
fsal_t *fsal = fpath->fsal;
if (fsal == NULL) {
printf("path %s fsal error!\n", path);
return -1;
}
/* 转换路径 */
char new_path[MAX_PATH] = {0};
if (fsal_path_switch(fpath, new_path, path) < 0)
return -1;
/* 执行打开 */
return fsal->utime(new_path, actime, modtime);
}
static int __feof(int idx)
{
if (ISBAD_FSAL_FIDX(idx))
return -1;
/* 查找对应的文件系统 */
fsal_file_t *fp = FSAL_I2F(idx);
fsal_t *fsal = fp->fsal;
if (fsal == NULL)
return -1;
return fsal->feof(idx);
}
static int __ferror(int idx)
{
if (ISBAD_FSAL_FIDX(idx))
return -1;
/* 查找对应的文件系统 */
fsal_file_t *fp = FSAL_I2F(idx);
fsal_t *fsal = fp->fsal;
if (fsal == NULL)
return -1;
return fsal->ferror(idx);
}
static off_t __ftell(int idx)
{
if (ISBAD_FSAL_FIDX(idx))
return -1;
/* 查找对应的文件系统 */
fsal_file_t *fp = FSAL_I2F(idx);
fsal_t *fsal = fp->fsal;
if (fsal == NULL)
return -1;
return fsal->ftell(idx);
}
static size_t __fsize(int idx)
{
if (ISBAD_FSAL_FIDX(idx))
return -1;
/* 查找对应的文件系统 */
fsal_file_t *fp = FSAL_I2F(idx);
fsal_t *fsal = fp->fsal;
if (fsal == NULL)
return -1;
return fsal->fsize(idx);
}
static int __rewind(int idx)
{
if (ISBAD_FSAL_FIDX(idx))
return -1;
/* 查找对应的文件系统 */
fsal_file_t *fp = FSAL_I2F(idx);
fsal_t *fsal = fp->fsal;
if (fsal == NULL)
return -1;
return fsal->rewind(idx);
}
static int __rewinddir(int idx)
{
if (ISBAD_FSAL_DIDX(idx))
return -1;
/* 查找对应的文件系统 */
fsal_dir_t *fp = FSAL_I2D(idx);
fsal_t *fsal = fp->fsal;
if (fsal == NULL)
return -1;
return fsal->rewinddir(idx);
}
static int __rmdir(char *path)
{
if (path == NULL)
return -1;
fsal_path_t *fpath = fsal_path_find(path, 1);
if (fpath == NULL) {
printf("path %s not found!\n", path);
return -1;
}
/* 查找对应的文件系统 */
fsal_t *fsal = fpath->fsal;
if (fsal == NULL) {
printf("path %s fsal error!\n", path);
return -1;
}
/* 转换路径 */
char new_path[MAX_PATH] = {0};
if (fsal_path_switch(fpath, new_path, path) < 0)
return -1;
/* 执行打开 */
return fsal->rmdir(new_path);
}
static int __chdir(char *path)
{
if (path == NULL)
return -1;
fsal_path_t *fpath = fsal_path_find(path, 1);
if (fpath == NULL) {
printf("path %s not found!\n", path);
return -1;
}
/* 查找对应的文件系统 */
fsal_t *fsal = fpath->fsal;
if (fsal == NULL) {
printf("path %s fsal error!\n", path);
return -1;
}
/* 转换路径 */
char new_path[MAX_PATH] = {0};
if (fsal_path_switch(fpath, new_path, path) < 0)
return -1;
/* 执行打开 */
return fsal->chdir(new_path);
}
static int __ioctl(int idx, int cmd, unsigned long arg)
{
if (ISBAD_FSAL_FIDX(idx))
return -1;
/* 查找对应的文件系统 */
fsal_file_t *fp = FSAL_I2F(idx);
fsal_t *fsal = fp->fsal;
if (fsal == NULL)
return -1;
return fsal->ioctl(idx, cmd, arg);
}
static int __fcntl(int idx, int cmd, long arg)
{
if (ISBAD_FSAL_FIDX(idx))
return -1;
/* 查找对应的文件系统 */
fsal_file_t *fp = FSAL_I2F(idx);
fsal_t *fsal = fp->fsal;
if (fsal == NULL)
return -1;
return fsal->fcntl(idx, cmd, arg);
}
/* 挂载文件系统 */
int __mount(
char *source, /* 需要挂载的资源 */
char *target, /* 挂载到的目标位置 */
char *fstype, /* 文件系统类型 */
unsigned long mountflags /* 挂载标志 */
) {
if (source == NULL || target == NULL || fstype == NULL)
return -1;
/* 查找要挂载的资源 */
if (disk_res_find((char *) source) < 0) {
printf("[%s] %s: source %s not found!\n", SRV_NAME, __func__, source);
return -1;
}
/* 查看目标位置是否可用 */
if (fsal_path_find((void *) target, 0) != NULL) {
printf("[%s] %s: target %s had mounted!\n", SRV_NAME, __func__, target);
return -1;
}
/* 查找文件系统类型 */
fsal_t *fsal = fstype_find((char *)fstype);
if (fsal == NULL) {
printf("[%s] %s: filesystem type %s not found!\n", SRV_NAME, __func__, fstype);
return -1;
}
printf("[%s] %s: will mount fs source %s target %s fstype %s.\n",
SRV_NAME, __func__, source, target, fstype);
/* 执行对应类型文件系统的挂载 */
int retval = fsal->mount(source, target, fstype, mountflags);
if (retval < 0) {
printf("[%s] %s: mount fs source %s target %s fstype %s failed!\n",
SRV_NAME, __func__, source, target, fstype);
return -1;
}
return 0;
}
static int __unmount(char *path, unsigned long flags)
{
if (path == NULL)
return -1;
fsal_path_t *fpath = fsal_path_find(path, 0);
if (fpath == NULL) {
printf("path %s not found!\n", path);
return -1;
}
/* 查找对应的文件系统 */
fsal_t *fsal = fpath->fsal;
if (fsal == NULL) {
printf("path %s fsal error!\n", path);
return -1;
}
/* 转换路径 */
char new_path[MAX_PATH] = {0};
if (fsal_path_switch(fpath, new_path, path) < 0)
return -1;
/* 执行打开 */
return fsal->unmount(new_path, flags);
}
/* 创建文件系统 */
int __mkfs(
char *source, /* 需要创建FS的设备 */
char *fstype, /* 文件系统类型 */
unsigned long flags /* 标志 */
) {
if (source == NULL || fstype == NULL)
return -1;
/* 查找要挂载的资源 */
if (disk_res_find(source) < 0) {
printf("[%s] %s: source %s not found!\n", SRV_NAME, __func__, source);
return -1;
}
/* 查找文件系统类型 */
fsal_t *fsal = fstype_find((char *)fstype);
if (fsal == NULL) {
printf("[%s] %s: filesystem type %s not found!\n", SRV_NAME, __func__, fstype);
return -1;
}
printf("[%s] %s: will make fs on source %s fstype %s.\n",
SRV_NAME, __func__, source, fstype);
/* 执行对应类型文件系统的挂载 */
int retval = fsal->mkfs(source, fstype, flags);
if (retval < 0) {
printf("[%s] %s: make fs source %s fstype %s failed!\n",
SRV_NAME, __func__, source, fstype);
return -1;
}
return 0;
}
fsal_t fsif = {
.mkfs = __mkfs,
.mount = __mount,
.unmount = __unmount,
.open = __open,
.close = __close,
.read = __read,
.write = __write,
.lseek = __lseek,
.opendir = __opendir,
.closedir = __closedir,
.readdir = __readdir,
.mkdir = __mkdir,
.unlink = __unlink,
.rename = __rename,
.ftruncate = __ftruncate,
.fsync = __fsync,
.state = __state,
.chmod = __chmod,
.fchmod = __fchmod,
.utime = __utime,
.feof = __feof,
.ferror = __ferror,
.ftell = __ftell,
.fsize = __fsize,
.rewind = __rewind,
.rewinddir = __rewinddir,
.rmdir = __rmdir,
.chdir = __chdir,
.ioctl = __ioctl,
.fcntl = __fcntl,
.fstat = __fstat,
};
|
C
|
#include "at89x52.H"
#include "UART.h"
#include "my_type.h"
#include "config.h"
/********************************************************************
ܣڳʼ
ڲޡ
أޡ
עޡ
********************************************************************/
void init_uart(void)
{
EA=0;
TMOD&=0x0F;
TMOD|=0x20; //ʱ1ģʽ2
SCON=0x50; //ڹģʽ1
TCON=0x05;
TH1=256-Fclk/(BitRate*12*16);
TL1=256-Fclk/(BitRate*12*16);
PCON=0x80; //ڲʼӱ
ES=1; //ж
TR1=1; //ʱ1
REN=1; //
EA=1; //ж
}
////////////////////////End of function//////////////////////////////
/********************************************************************
ܣжϴ
ڲޡ
أޡ
עޡ
********************************************************************/
void UartISR(void) interrupt 4
{
if(RI) //յ
{
RI=0; //ж
SBUF=SBUF;
}
else //һֽ
{
TI=0;
}
}
////////////////////////End of function//////////////////////////////
/********************************************************************
ܣڷһֽݡ
ڲd: Ҫ͵ֽݡ
أޡ
עޡ
********************************************************************/
void uart_putchar(uint8 d)
{
ES=0;
SBUF=d;
while(TI!=1);
TI=0;
ES=1;
}
////////////////////////End of function//////////////////////////////
/********************************************************************
ܣһַ
ڲpdҪ͵ַָ롣
أޡ
עޡ
********************************************************************/
void print_str(uint8 * pd)
{
while((*pd)!='\0')
{
uart_putchar(*pd);
pd++;
}
}
////////////////////////End of function//////////////////////////////
/********************************************************************
ܣתʮַ͡
ڲxʾ
أޡ
עޡ
********************************************************************/
void print_longint(uint32 x)
{
int8 i;
uint8 display_buffer[10];
for(i=9;i>=0;i--)
{
display_buffer[i]='0'+x%10;
x/=10;
}
for(i=0;i<9;i++)
{
if(display_buffer[i]!='0')
{
break;
}
}
for(;i<10;i++)
{
uart_putchar(display_buffer[i]);
}
}
////////////////////////End of function//////////////////////////////
code uint8 HexTable[]={'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};
/********************************************************************
ܣʮƷ͡
ڲ͵
أޡ
עޡ
********************************************************************/
void print_16hex(uint16 x)
{
uint8 i;
uint8 display_buffer[7];
display_buffer[6]=0;
display_buffer[0]='0';
display_buffer[1]='x';
for(i=5;i>=2;i--)
{
display_buffer[i]=HexTable[(x&0xf)];
x>>=4;
}
print_str(display_buffer);
}
////////////////////////End of function//////////////////////////////
/********************************************************************
ܣʮƷ͡
ڲ͵
أޡ
עޡ
********************************************************************/
void print_32hex(uint32 x) //
{
uint8 i;
uint8 display_buffer[11];
display_buffer[10]=0;
display_buffer[0]='0';
display_buffer[1]='x';
for(i=9;i>=2;i--)
{
display_buffer[i]=HexTable[(x&0xf)];
x>>=4;
}
print_str(display_buffer);
}
////////////////////////End of function//////////////////////////////
/********************************************************************
ܣһbyteݡ
ڲ͵ݡ
أޡ
עޡ
********************************************************************/
////////////////////////End of function//////////////////////////////
/********************************************************************
ܣHEXʽһbyteݡ
ڲ͵
أޡ
עޡ
********************************************************************/
void print_hex(uint8 x)
{
uart_putchar('0');
uart_putchar('x');
uart_putchar(HexTable[x>>4]);
uart_putchar(HexTable[x&0xf]);
uart_putchar(' ');
}
////////////////////////End of function//////////////////////////////
|
C
|
#include <math.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include "UTF8.h"
enum state_tag
{
NUMBER,
X,
POWER,
ADD,
SUB,
MUL,
DIV,
NUL
};
struct var
{
double x1;
double x2;
double constant;
};
struct ans
{
double x1;
double x2;
int flag;
};
struct var *parse();
struct ans *solve(struct var *variables);
int state_change(enum state_tag *current, enum state_tag new, UTF8_String *string_buffer, double *temp, struct var *variables, char ch);
double eval(char *str);
enum state_tag store = NUL;
int flag = 1;
int main()
{
struct var *variables;
struct ans *answer;
for (;;)
{
flag = 1;
store = NUL;
printf(">>> ");
variables = parse();
// printf("x1 -> %lf\n", variables->x1);
// printf("x2 -> %lf\n", variables->x2);
// printf("constant -> %lf\n", variables->constant);
answer = solve(variables);
if (answer->flag == 0)
printf("%lf\n", variables->constant);
else if (answer->flag == 1)
printf("The root of the function x = %lf\n", answer->x1);
else if(answer->flag == 2)
{
printf("The first root of the function x1 = %lf\n", answer->x1);
printf("The second root of the function x2 = %lf\n", answer->x2);
}
free(variables);
variables = NULL;
free(answer);
answer = NULL;
}
return 0;
}
struct var *parse()
{
struct var *new = (struct var*)calloc(1, sizeof(struct var));
double temp = 0;
enum state_tag state = NUL;
char ch = 0;
UTF8_String *string_buffer = utf8_string_new();
for (;;)
{
ch = getchar();
if (ch == EOF)
{
free(new);
string_buffer = utf8_string_delete(&string_buffer);
exit(0);
}
else if (ch == ' ')
continue;
else if (ch == '\n')
{
state_change(&state, NUL, string_buffer, &temp, new, ch);
break;
}
else if (ch == 'e' || ch == 'q')
{
free(new);
string_buffer = utf8_string_delete(&string_buffer);
exit(0);
}
else
{
if (ch >= '0' && ch <= '9' || ch == '.')
state_change(&state, NUMBER, string_buffer, &temp, new, ch);
switch (ch)
{
case '=':
state_change(&state, NUL, string_buffer, &temp, new, ch);
flag = -1;
break;
case '^':
state_change(&state, POWER, string_buffer, &temp, new, ch);
break;
case '+':
state_change(&state, ADD, string_buffer, &temp, new, ch);
break;
case '-':
state_change(&state, SUB, string_buffer, &temp, new, ch);
break;
case '*':
state_change(&state, NUMBER, string_buffer, &temp, new, ch);
break;
case '/':
state_change(&state, NUMBER, string_buffer, &temp, new, ch);
break;
case 'x':
state_change(&state, X, string_buffer, &temp, new, ch);
}
}
}
string_buffer = utf8_string_delete(&string_buffer);
return new;
}
struct ans *solve(struct var *variables)
{
struct ans *answer = (struct ans*)calloc(1, sizeof(struct ans));
if (variables->x1 == 0 && variables->x2 == 0)
{
answer->flag = 0;
return answer;
}
else if (variables->x2 == 0)
{
answer->flag = 1;
answer->x1 = -variables->constant / variables->x1;
}
else
{
double a = variables->x2;
double b = variables->x1;
double c = variables->constant;
answer->flag = 2;
answer->x1 = (-b + sqrt(pow(b, 2) - (4 * a * c))) / (2 * a);
answer->x2 = (-b - sqrt(pow(b, 2) - (4 * a * c))) / (2 * a);
}
return answer;
}
int state_change(enum state_tag *current, enum state_tag new, UTF8_String *string_buffer, double *temp, struct var *variables, char ch)
{
int f = 1;
switch (new)
{
case NUMBER:
if (*current != POWER)
utf8_string_append_char(string_buffer, ch);
else
return 0;
break;
case X:
break;
case POWER:
break;
default:
if (store == SUB)
f = -1;
switch (*current)
{
case NUMBER:
variables->constant += eval(utf8_string_get_value(string_buffer)) * flag * f;
utf8_string_reassign(string_buffer, "");
break;
case X:
if (strlen(utf8_string_get_value(string_buffer)))
{
variables->x1 += eval(utf8_string_get_value(string_buffer)) * flag * f;
utf8_string_reassign(string_buffer, "");
}
else
variables->x1 += 1 * flag * f;
break;
case POWER:
if (strlen(utf8_string_get_value(string_buffer)))
{
variables->x2 += eval(utf8_string_get_value(string_buffer)) * flag * f;
utf8_string_reassign(string_buffer, "");
}
else
variables->x2 += 1 * flag * f;
break;
}
break;
}
if (new == ADD || new == SUB || new == NUL)
store = new;
*current = new;
}
double eval(char *str)
{
enum state_tag state = NUL;
double temp;
char *endptr;
for (;;)
{
switch (state)
{
case MUL:
temp *= strtof(str, &endptr);
break;
case DIV:
temp /= strtof(str, &endptr);
break;
default:
temp = strtof(str, &endptr);
break;
}
if (strlen(endptr))
{
switch(endptr[0])
{
case '*':
state = MUL;
break;
case '/':
state = DIV;
break;
}
str = endptr + 1;
continue;
}
break;
}
return temp;
}
|
C
|
#define IHC_IMPL
#include "IHC.h"
#include <stdio.h>
#include <stdlib.h>
static MagickWand *wand;
static MagickWand *staining_wands[NUM_CHANNELS];
int ProcessImageFiles(const char *input_fname,
const char *color_deconvolution_matrix_fname,
const char **output_fnames)
{
MagickBooleanType magick_status;
double color_deconvolution_matrix[NUM_CHANNELS][NUM_CHANNELS];
int status, i;
/* Initialize the MagickWand environment. */
MagickWandGenesis();
wand = NewMagickWand();
for (i = 0; i < NUM_CHANNELS; i++)
{
staining_wands[i] = NewMagickWand();
}
/* Read an image. */
magick_status = MagickReadImage(wand, input_fname);
if (magick_status == MagickFalse)
{
ThrowWandException();
}
status = ReadColorDeconvolutionMatrix(color_deconvolution_matrix_fname,
color_deconvolution_matrix);
if (status == 1)
{
perror(color_deconvolution_matrix_fname);
exit(1);
}
else if (status == 2)
{
fprintf(stderr, "%s: Failed to parse input\n",
color_deconvolution_matrix_fname);
exit(1);
}
double *staining_amounts[NUM_CHANNELS];
SeparateStains(color_deconvolution_matrix, staining_amounts);
size_t width = MagickGetImageWidth(wand);
size_t height = MagickGetImageHeight(wand);
for (i = 0; i < NUM_CHANNELS; i++)
{
magick_status = MagickConstituteImage(staining_wands[i],
width, height, "I", DoublePixel,
staining_amounts[i]);
if (magick_status == MagickFalse)
ThrowWandException();
/* Write the image and then destroy it. */
magick_status = MagickWriteImage(staining_wands[i], output_fnames[i]);
if (magick_status == MagickFalse)
ThrowWandException();
free(staining_amounts[i]);
staining_wands[i] = DestroyMagickWand(staining_wands[i]);
}
/* Deallocate resources and destroy the MagickWand environment. */
wand = DestroyMagickWand(wand);
MagickWandTerminus();
return 1;
}
int SeparateStains(double (*color_deconvolution_matrix)[NUM_CHANNELS],
double *staining_amounts[])
{
size_t width = MagickGetImageWidth(wand);
size_t height = MagickGetImageHeight(wand);
size_t x, y;
int i;
PixelIterator *iterator = NewPixelIterator(wand);
if (iterator == (PixelIterator *) NULL)
{
ThrowWandException();
}
for (i = 0; i < NUM_CHANNELS; i++)
{
staining_amounts[i] = (double *) calloc(width * height, sizeof(double));
}
for (y = 0; y < height; y++)
{
PixelWand **row_pixels = PixelGetNextIteratorRow(iterator, &width);
if (row_pixels == (PixelWand **) NULL)
break;
for (x = 0; x < width; x++)
{
PixelInfo color;
PixelGetMagickColor(row_pixels[x], &color);
double pixel_staining_amounts[NUM_CHANNELS];
ColorDeconvolve(color_deconvolution_matrix,
&color, pixel_staining_amounts);
for (i = 0; i < NUM_CHANNELS; i++)
{
staining_amounts[i][x + y * width] = pixel_staining_amounts[i];
}
}
PixelSyncIterator(iterator);
}
iterator = DestroyPixelIterator(iterator);
return 1;
}
int ReadColorDeconvolutionMatrix(
const char *filepath,
double (*color_deconvolution_matrix)[NUM_CHANNELS])
{
FILE *f = fopen(filepath, "r");
if (f == NULL)
return 1;
for (int i = 0; i < NUM_CHANNELS; i++)
{
for (int j = 0; j < NUM_CHANNELS; j++)
{
int status = fscanf(f, "%lf", &color_deconvolution_matrix[i][j]);
if (status != 1)
{
fclose(f);
return 2;
}
}
}
fclose(f);
return 0;
}
void ColorDeconvolve(double (*color_deconvolution_matrix)[NUM_CHANNELS],
const PixelInfo *color,
double *pixel_staining_amounts)
{
/* This is basically matrix multiplication. */
int j;
for (j = 0; j < NUM_CHANNELS; j++)
{
pixel_staining_amounts[j]
= color->red * color_deconvolution_matrix[0][j]
+ color->green * color_deconvolution_matrix[1][j]
+ color->blue * color_deconvolution_matrix[2][j];
pixel_staining_amounts[j] /= QuantumRange; /* Clamp to [0, 1] */
}
}
void ThrowWandException()
{
ExceptionType severity;
int i;
char *description = MagickGetException(wand, &severity);
fprintf(stderr, "%s %s %lu %s\n", GetMagickModule(), description);
description = (char *) MagickRelinquishMemory(description);
for (i = 0; i < NUM_CHANNELS; i++)
{
staining_wands[i] = DestroyMagickWand(staining_wands[i]);
}
wand = DestroyMagickWand(wand);
MagickWandTerminus();
exit(1);
}
|
C
|
#include<stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <sys/utsname.h>
#include <limits.h>
#include <unistd.h>
#include <string.h>
#include<ctype.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <dirent.h>
#include<fcntl.h>
#include <pwd.h>
#include <grp.h>
#include <time.h>
#include <memory.h>
#include<sys/wait.h>
void cd(char *path,int noofw,char *fwd)
{
if(noofw>2)
{
printf("incorrect no of arguments for cd\n");
}
else if(noofw==1)
{
if(chdir(fwd)!=0)
{
perror("cd failed");
}
}
else
{
if(path[0]=='~')
{
path+=1;
char *temp=(char *)malloc(1000);
strcpy(temp,fwd);
strcat(temp,path);
if(chdir(temp)!=0)
{
perror("cd failed");
}
}
else
{
if(chdir(path)!=0)
{
perror("cd failed");
}
}
}
}
|
C
|
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main(void)
{
int num1, num2;
int year;
if (!0)
{
printf("hello!\n");
}
printf("please input year : ");
scanf("%d", &year);
if (!(year >= 1000 && year < 10000))
{
printf("year format error!\n");
return -1;
}
if (year % 400 == 0 || year % 4 == 0 && year % 100 != 0)
{
printf("yes!\n");
}
else
{
printf("no!\n");
}
printf("===============\n");
//2016
if (!(year % 400))// year % 400 == 0
{
printf("yes");
}
else
{
if (!(year % 4))
{
if (year % 100)
{
printf("yes!\n");
}
else
{
printf("no!\n");
}
}
else
{
printf("no!\n");
}
}
printf("please input two number : ");
scanf("%d%d", &num1, &num2);
/*
*if (num > 10);
*{
* printf("大于10!\n");
* printf("hello!\n");
*}
*/
if (num1 > num2)
{
printf("max = %d\n", num1);
;
}
else
{
printf("max = %d\n", num2);
}
return 0;
}
|
C
|
#include <stdio.h>
#include <string.h>
void appendLetter(char msg[64])
{
char finalLetter[2];
if (strlen(msg) % 2 != 0)
{
finalLetter[0] = msg[strlen(msg) - 1] != 'X' ? 'X' : 'Y';
strcat(msg, finalLetter);
}
}
void formatMessage(char message[64])
{
for (int i = 0; i < strlen(message); i += 2)
{
if (message[i + 1] == message[i])
{
message[i + 1] = 'X';
}
}
}
int letterPosition(const char playfairSquare[5][5], char letter)
{
int letterPosition;
for (int i = 0; i < 5; i++)
{
for (int j = 0; j < 5; j++)
{
if (playfairSquare[i][j] == letter)
{
letterPosition = i * 5 + j;
}
}
}
return letterPosition;
}
void encodeMessage(char playfairSquare[5][5], char msg[64])
{
removeNoLettersCharacters(msg);
toUpperCase(msg);
printf("Message purge : %s\n", msg);
replaceJIntoI(msg);
formatMessage(msg);
appendLetter(msg);
printf("Message prepare : %s\n", msg);
for (int i = 0; i < strlen(msg); i += 2)
{
int positionFirstLetter = letterPosition(playfairSquare, msg[i]);
int positionSecondLetter = letterPosition(playfairSquare, msg[i + 1]);
if (positionFirstLetter / 5 == positionSecondLetter / 5)
{
msg[i] = positionFirstLetter % 5 != 4 ? playfairSquare[positionFirstLetter / 5][(positionFirstLetter % 5) + 1] : playfairSquare[positionFirstLetter / 5][0];
msg[i + 1] = positionSecondLetter % 5 != 4 ? playfairSquare[positionSecondLetter / 5][(positionSecondLetter % 5) + 1] : playfairSquare[positionSecondLetter / 5][0];
}
else if (positionFirstLetter % 5 == positionSecondLetter % 5)
{
msg[i] = positionFirstLetter / 5 != 4 ? playfairSquare[(positionFirstLetter / 5) + 1][positionFirstLetter % 5] : playfairSquare[0][positionFirstLetter % 5];
msg[i + 1] = positionSecondLetter / 5 != 4 ? playfairSquare[(positionSecondLetter / 5) + 1][positionSecondLetter % 5] : playfairSquare[0][positionSecondLetter % 5];
}
else
{
msg[i] = playfairSquare[positionFirstLetter / 5][positionSecondLetter % 5];
msg[i + 1] = playfairSquare[positionSecondLetter / 5][positionFirstLetter % 5];
}
}
}
void printMessage(char message[64])
{
printf("Message crypte : ");
for (int i = 0; i < strlen(message); i += 2)
{
printf("%c%c ", message[i], message[i + 1]);
}
}
// cle : radio londre
// msg : Les chants les plus desesperes sont les chants les plus beaux
|
C
|
#include <stdio.h>
#include <string.h>
void
find_placeof_word( char word[], char characters[][250], int len_column, int cordinate[] );
int
find_placeof_horizontal_word( char word[], char characters[][250], int len_column, int cordinate[] );
int
find_placeof_vertical_word( char word[], char characters[][250], int len_column, int cordinate[] );
int
find_max_row_len( char characters[][250] );
void
take_vertical_word( char word[], char characters[][250], char compare[], int row, int column );
int
main(void)
{
char get_row[250];
char characters[100][250]; //input.txt dosyasından okunan karakterlerin yazıldığı arraydir.
int row = 0, number_of_rows = 0, i, column; //number_of_rows characters array'inin kaç satırdan oluştuğunu saklar.
char *word1 = "Xanthos";
char *word2 = "Patara";
char *word3 = "Myra";
char *word4 = "Arycanda";
char *word5 = "Phaselis";
int cordinate[2];
FILE *fp;
fp = fopen("input.txt","r");
for( row = 0; row < 100; row++ ) //Buradaki for döngüleri ile characters array'inin tüm elemanları null karakteri ile dolduruldu.
{
for( column = 0; column < 250; column++ )
{
characters[row][column] = 0;
}
}
row = 0;
number_of_rows = 0;
while( fscanf( fp, "%s", get_row ) == 1 ) //input.txt dosyasında boşluk ve newline karakteri ile ayrılmış tüm ardışık karakterler
{ //characters array'ine satırlar halinde yazıldı.
strcpy( *(characters +row) , get_row );
row += 1;
number_of_rows += 1;
}
find_placeof_word( word1, characters, number_of_rows, cordinate );
find_placeof_word( word2, characters, number_of_rows, cordinate );
find_placeof_word( word3, characters, number_of_rows, cordinate );
find_placeof_word( word4, characters, number_of_rows, cordinate );
find_placeof_word( word5, characters, number_of_rows, cordinate );
}
void
find_placeof_word( char word[], char characters[][250], int number_of_rows, int cordinate[] ) //bu fonksiyon aranacak kelimeyi önce yatayda arar.Aradığı kelimeyi bulursa kelimeyi ve kelimenin ilk karakterinin konumunu ekrana basar.Aradığı kelimeyi yatayda bulamazsa dikeyde arar.Dikeyde bulursa bulduğu kelimeyi ve kelimenin ilk karakterinin konumunu ekrana basar.
{
if ( find_placeof_horizontal_word( word, characters, number_of_rows, cordinate ) == 1 )
{
printf("%s (%d,%d) Horizontal\n", word, cordinate[0], cordinate[1] );
}
else if(find_placeof_vertical_word( word, characters, number_of_rows, cordinate ) == 1 )
{
printf( "%s (%d,%d) Vertical\n", word, cordinate[0], cordinate[1] );
}
}
int
find_placeof_horizontal_word( char word[], char characters[][250], int number_of_rows, int cordinate[] ) //bu fonksiyon verilen kelimeyi characters array'inde yatay olarak sağdan sola doğru arar.Eğer aradığı kelimeyi bulursa bulduğu kelimenin ilk karakterinin konumunu cordinate array'ine kaydeder.
{
int row, column;
char compare[9];
/* Buradaki for döngüsü ile satırın en başından başlanarak satırdan karşılaştırılacak kelime uzunluğu kadar kelime campare arry'ine kopyalaır. Compare array'i karşılaştırılmak istenen kelimeyle kıyaslanır. Compare arry'i ile aranan kelimenin eşit olduğu durumda döngüden çıkılır. */
for( row = 0; row < number_of_rows; row++ )
{
for( column = 0; column <= ( strlen(*(characters + row)) - strlen(word) ); column++ )
{
memcpy( compare, (*( characters + row ))+column, strlen( word ) );
compare[ strlen( word ) ] = '\0';
cordinate[0] = row + 1; //Cordinate array'inin ilk elemanı bulunacak kelimenin ilk karakterinin satır sırsını saklar.
cordinate[1] = column + 1; //Cordinate array'inin ikinci elemanı bulunacak kelimenin ilk karakterinin sütun sırsını saklar.
if( strcmp( word, compare ) == 0 ) return 1;
}
}
return 0;
}
int
find_placeof_vertical_word( char word[], char characters[][250], int number_of_rows, int cordinate[] ) //bu fonksiyon verilen kelimeyi characters array'inde dikey olarak yukarıdan aşağıya doğru arar.Eğer aradığı kelimeyi bulursa bulduğu kelimenin ilk karakterinin konumunu cordinate array'ine kaydeder.
{
int row, column;
char compare[9];
int max_row_len = find_max_row_len( characters );
/*buradaki for döngüleri characters array'indeki sütunların başından başlayarak aşağıya doğru sırayla take_vertikal_word fonksiyonuna koum verir. */
for( column = 0; column < max_row_len; column++ )
{
for( row = 0; row <= number_of_rows - strlen( word ); row++ )
{
take_vertical_word( word, characters ,compare, row, column );
if( strcmp( compare, word ) == 0 )
{
cordinate[0] = row +1; //Cordinate array'inin ilk elemanı bulunacak kelimenin ilk karakterinin satır sırsını saklar.
cordinate[1] = column +1; //Cordinate array'inin ikinci elemanı bulunacak kelimenin ilk karakterinin sütun sırsını saklar.
return 1;
}
}
}
return 0;
}
int
find_max_row_len( char characters[][250] ) //bu fonksiyon characters array'indeki en uzun satırın uzunluğunu bularak max_row_len değişkenine yazar.
{
int row;
int max_row_len; //characters array'indeki en uzun satırın uzunluğunu saklar.
max_row_len = strlen( *characters );
for(row = 1; row < 100; row++ )
{
if( strlen( *(characters + row) ) > max_row_len )
{
max_row_len = strlen( *(characters + row) );
}
}
return max_row_len;
}
void
take_vertical_word( char word[], char characters[][250], char compare[], int row, int column ) //bu fonksiyon characters arrayi'nin verilen kordinatlarından başlayarak paramtre olarak verilen kelime uzunluğunda karakterleri yukarıdan aşağıya olarak alır.Aldığı keimeleri compare array'ine kaydeder.
{
int i;
int len_word = strlen( word );
for( i = 0; i < len_word; i++ )
{
compare[i] = characters[ row + i ][column];
}
compare[ len_word ] = '\0';
}
|
C
|
/*
* ADAT mixer driver
*
* Copyright (c) 2013 Daniel Lopez-Arozena <[email protected]>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License.
*
* Cross-compile with cross-gcc -I/path/to/cross-kernel/include
*/
#include <stdint.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <getopt.h>
#include <fcntl.h>
#include <sys/ioctl.h>
#include <linux/types.h>
#include <linux/spi/spidev.h>
#define ARRAY_SIZE(a) (sizeof(a) / sizeof((a)[0]))
#define SMP64 0x40
#define SMP128 0x80
#define POT_MS 100
#define FS48K 48000
#define FS44K 441000
#define HIGH 1
#define LOW 0
static const char *device = "/dev/spidev1.1";
static uint8_t wdclk = LOW; // Fs Clock. (48KHz, 44.1KHz)
static uint8_t bclk = LOW; // Data Clock (64 * Fs = 3072KHz, 2822.4KHz)
static uint8_t resolution = 16; // sample data resolution (16, 24 bits)
static uint8_t sampling = SMP64; // Number of samples buffer (64, 128)
static uint16_t fs = FS48K; // Sampling Frequency (Fs) in Hz (48000KHz, 44.1KHz)
static void configure_shit(void)
{
// wake_up_interruptible(&short_queue); /* awake any reading process */
return;
}
static void wait_wdclk_rise(void)
{
if (wdclk == LOW)
wait_event_interruptible(wdclk_queue, wdclk == HIGH);
return;
}
static void wait_wdclk_fall(void)
{
if (wdclk == HIGH)
wait_event_interruptible(wdclk_queue, wdclk == LOW);
return;
}
static void wait_bclk_rise(void)
{
if (bclk == LOW)
wait_event_interruptible(bclk_queue, bclk == HIGH);
bclk = LOW;
return;
}
static void adat_rx_tx_odd(uint8_t bit)
{
return;
}
static void adat_rx_tx_even(uint8_t bit)
{
return;
}
static void mix_odd()
{
return;
}
static void mix_even()
{
return;
}
static void read_pots(void)
{
return;
}
static void adat_io(sampling, resolution)
{
unsigned short n = 0;
unsigned short bit = 0;
for (n = 0 ; n < sampling ; ++n)
{
wait_wdclk_rise(); // odd channels
for (bit = 0 ; bit < resolution ; ++bit)
{
wait_bclk_rise();
adat_rx_tx_odd(bit);
}
/*
Time to mix = (32 - resolution)/(fs*64)
For 16 and 48000 Hz, T = 5,2 us
For 16 and 44100 Hz, T = 5,6 us
*/
wait_wdclk_fall(); // even channels
for (bit = 0 ; bit < resolution ; ++bit)
{
wait_bclk_rise();
adat_rx_tx_even(bit);
}
}
}
int main(int argc, char *argv[])
{
unsigned short t = 1;
unsigned short n = 0;
unsigned short bit = 0;
unsigned short potPeriod = fs * POT_MS / 1000;
configure_shit();
wait_wdclk_fall(); // to sync
while(1)
{
if (read_pots(&t))
t = potPeriod;
adat_io(sampling, resolution);
mix_data(); // Launch thread to mix. Takes sampling time?
}
return 0;
}
|
C
|
// Useful math functions
int inline abs(int val) {
return val > 0 ? val : val * -1;
}
|
C
|
#include "holberton.h"
#include <stdio.h>
#include <stdlib.h>
/**
* argstostr - cat all the args
* @ac: integer
* @av: character
* Return: yes
*/
char *argstostr(int ac, char **av)
{
int i, j;
int buffer = 0;
int length = 0;
char *ptr;
if (ac == 0)
return (NULL);
if (av == NULL)
return (NULL);
for (i = 0; av[i]; i++)
for (j = 0; av[i][j]; j++)
length++;
ptr = (char *)malloc(length * sizeof(char) + ac + 1);
if (!ptr)
return (NULL);
for (i = 0; av[i]; i++)
{
for (j = 0; av[i][j]; j++, buffer++)
ptr[buffer] = av[i][j];
ptr[buffer] = '\n';
buffer++;
}
ptr[buffer] = '\0';
return (ptr);
}
|
C
|
#include<stdio.h>
int main(void){
int a, b, c;
c = a + b;
printf("sum is %d", c);
c = a * b;
printf("product is %d", c);
c = a / b;
printf("quotient is %d", c);
c = a % b;
printf("remainder is %d", c);
return 0;
}
|
C
|
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <locale.h>
#include "listaAdjacencia.h"
int main()
{
printf("A localidade corrente agora � %s \n", setlocale(LC_ALL, ""));
system("cls");
grafoBairros *grafo = lerArquivo("MatrizBairros.csv");
grafo = lerArquivoDistancias(grafo, "MatrizBairros.csv");
int op = -1;
int valor;
while (op != 0)
{
printf("1 - grafo conexo\n"
"2 - grafo completo\n"
"3 - grafo regular\n"
"4 - caminho hamiltoniano\n"
"0 - Sair\n");
scanf("%d", &op);
switch (op)
{
case 1:
{
system("cls");
if (verifica_conexo == 1)
printf("\n GRAFO CONEXO \n\n");
else
printf("\n GRAFO NAO CONEXO \n\n");
system("pause");
system("cls");
break;
}
case 2:
{
system("cls");
if (verifica_completo == 1)
printf("\n GRAFO COMPLETO \n\n");
else
printf("\n GRAFO NAO COMPLETO \n\n");
system("pause");
system("cls");
break;
}
case 3:
{
system("cls");
if (verifica_regular == 1)
printf("\n GRAFO REGULAR \n\n");
else
printf("\n GRAFO NAO REGULAR \n\n");
system("pause");
system("cls");
break;
}
case 4:
{
system("cls");
if (verifica_hamiltoniano == 1)
printf("\n GRAFO COM CAMINHO HAMILTONIANO \n\n");
else
printf("\n GRAFO SEM CAMINHO HAMILTONIANO \n\n");
system("pause");
system("cls");
break;
}
case 5:
{
system("cls");
system("pause");
system("cls");
break;
}
case 6:
{
system("cls");
system("pause");
system("cls");
break;
}
}
}
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* max_byte_main.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: cjosue <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2020/01/25 13:16:42 by cjosue #+# #+# */
/* Updated: 2020/01/25 13:16:44 by cjosue ### ########.fr */
/* */
/* ************************************************************************** */
#include "../includes/asm.h"
void ft_print_byte(char *buf)
{
int i;
unsigned char b;
i = 7;
while (i >= 0)
{
if (*buf & (1U << i))
ft_putchar('1');
else
ft_putchar('0');
i--;
}
}
int main(int ac, char **av)
{
char *tmp;
char buf[1];
int fd;
int i;
fd = open(av[1] , O_RDONLY);
while((i = get_next_line(fd, &tmp)) > 0)
{
printf("%d\n", i);
free(tmp);
lseek(fd, -1, SEEK_CUR);
read(fd, buf, 1);
// if (*buf != '\n')
printf("{%c}\n", *buf);
}
// unsigned char *res;
// char *str = "0abf11a0";
// char *tmp;
// int byte;
//
// byte = 4;
// res = (unsigned char*)malloc(sizeof(unsigned char) * byte);
// tmp = str;
// while (*tmp)
// {
// *res = 0;
// if (*tmp >= '0' && *tmp <='9')
// *res |= ((*tmp - '0') << 4);
// else
// *res |= ((*tmp - 'a' + 10) << 4);
// tmp++;
// if (*tmp >= '0' && *tmp <='9')
// *res |= *tmp - '0';
// else
// *res |= *tmp - 'a' + 10;
// tmp++;
// res++;
//
// }
// int fd;
// fd = open(av[1], O_WRONLY);
// write(fd, res - byte, byte);
// int i;
// unsigned int tmp;
// i = 19;
// tmp = (unsigned int)i;
// ft_print_byte((char*)&tmp);
return (0);
}
|
C
|
/**
* @file functions.c
* @author Federico Peccia
* @brief Example functions which will be tested
* @version 0.1
* @date 2019-08-20
*
* @copyright Copyright (c) 2019
*
*/
/**
* @brief Simple addition function
*
* @param a
* @param b
* @return int
*/
int sum(int a,int b )
{
return a+b;
}
/**
* @brief Simple substraction function
*
* @param a
* @param b
* @return int
*/
int sub(int a, int b )
{
return a - b;
}
|
C
|
#include "../src/calc.h"
#include "../thirdparty/ctest.h"
#include "../src/input.h"
#include "../test/calculation.h"
#include <gtk/gtk.h>
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
double Calc(char* str, int launch, int end);
char* input;
CTEST(plus, CALCULATION)
{
const double exp1 = 18;
const double exp2 = 21;
const double exp3 = 1304;
const double exp4 = 203;
input = malloc(10);
strcpy(input, "18");
int s1 = strlen(input);
double c1 = Calc(input, 0, s1 - 1);
strcpy(input, "13+8");
int s2 = strlen(input);
double c2 = Calc(input, 0, s2 - 1);
strcpy(input, "1245+51+8");
int s3 = strlen(input);
double c3 = Calc(input, 0, s3 - 1);
strcpy(input, "74+129");
int s4 = strlen(input);
double c4 = Calc(input, 0, s4 - 1);
ASSERT_EQUAL(exp1, c1);
ASSERT_EQUAL(exp2, c2);
ASSERT_EQUAL(exp3, c3);
ASSERT_EQUAL(exp4, c4);
}
CTEST(minus, CALCULATION)
{
const double exp1 = 11;
const double exp2 = 129;
const double exp3 = 1773;
const double exp4 = 93;
input = malloc(10);
strcpy(input, "16-5");
int s1 = strlen(input);
double c1 = Calc(input, 0, s1 - 1);
strcpy(input, "154-25");
int s2 = strlen(input);
double c2 = Calc(input, 0, s2 - 1);
strcpy(input, "1842-61-8");
int s3 = strlen(input);
double c3 = Calc(input, 0, s3 - 1);
strcpy(input, "194-101");
int s4 = strlen(input);
double c4 = Calc(input, 0, s4 - 1);
ASSERT_EQUAL(exp1, c1);
ASSERT_EQUAL(exp2, c2);
ASSERT_EQUAL(exp3, c3);
ASSERT_EQUAL(exp4, c4);
}
CTEST(multiply, CALCULATION1)
{
const double exp1 = 75;
const double exp2 = 198;
const double exp3 = 1887;
const double exp4 = -58;
input = malloc(10);
strcpy(input, "15*5");
int s1 = strlen(input);
double c1 = Calc(input, 0, s1 - 1);
strcpy(input, "18*11");
int s2 = strlen(input);
double c2 = Calc(input, 0, s2 - 1);
strcpy(input, "1258*1.5");
int s3 = strlen(input);
double c3 = Calc(input, 0, s3 - 1);
strcpy(input, "58*(-1)");
int s4 = strlen(input);
double c4 = Calc(input, 0, s4 - 1);
ASSERT_EQUAL(exp1, c1);
ASSERT_EQUAL(exp2, c2);
ASSERT_EQUAL(exp3, c3);
ASSERT_EQUAL(exp4, c4);
}
CTEST(divide, CALCULATION)
{
const double exp1 = 9;
const double exp2 = 30;
const double exp3 = 466.25;
const double exp4 = -14.4;
input = malloc(10);
strcpy(input, "18/2");
int s1 = strlen(input);
double c1 = Calc(input, 0, s1 - 1);
strcpy(input, "15/(0.5)");
int s2 = strlen(input);
double c2 = Calc(input, 0, s2 - 1);
strcpy(input, "1865/4");
int s3 = strlen(input);
double c3 = Calc(input, 0, s3 - 1);
strcpy(input, "72/(-5)");
int s4 = strlen(input);
double c4 = Calc(input, 0, s4 - 1);
ASSERT_EQUAL(exp1, c1);
ASSERT_EQUAL(exp2, c2);
ASSERT_EQUAL(exp3, c3);
ASSERT_EQUAL(exp4, c4);
}
CTEST(pow, CALCULATION)
{
const double exp1 = 169;
const double exp2 = 16105100000;
const double exp3 = 7770.573760;
const double exp4 = 0.0135;
input = malloc(10);
strcpy(input, "13^2");
int s1 = strlen(input);
double c1 = Calc(input, 0, s1 - 1);
strcpy(input, "110^5");
int s2 = strlen(input);
double c2 = Calc(input, 0, s2 - 1);
strcpy(input, "1746^(1.2)");
int s3 = strlen(input);
double c3 = Calc(input, 0, s3 - 1);
strcpy(input, "74^(-1)");
int s4 = strlen(input);
double c4 = Calc(input, 0, s4 - 1);
ASSERT_EQUAL(exp1, c1);
ASSERT_EQUAL(exp2, c2);
ASSERT_EQUAL(exp3, c3);
ASSERT_EQUAL(exp4, c4);
}
CTEST(sqrt, CALCULATION)
{
const double exp1 = 5;
const double exp2 = 7;
const double exp3 = 3.605551;
const double exp4 = 8.602325;
input = malloc(10);
strcpy(input, "25^(0.5)");
int s1 = strlen(input);
double c1 = Calc(input, 0, s1 - 1);
strcpy(input, "49^(0.5)");
int s2 = strlen(input);
double c2 = Calc(input, 0, s2 - 1);
strcpy(input, "13^(0.5)");
int s3 = strlen(input);
double c3 = Calc(input, 0, s3 - 1);
strcpy(input, "74^(0.5)");
int s4 = strlen(input);
double c4 = Calc(input, 0, s4 - 1);
ASSERT_EQUAL(exp1, c1);
ASSERT_EQUAL(exp2, c2);
ASSERT_EQUAL(exp3, c3);
ASSERT_EQUAL(exp4, c4);
}
|
C
|
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/wait.h>
#define NSTACK 100
volatile int waiting_pid;
pid_t pid_stack[NSTACK];
int count=0;
void sig_ign(struct sigaction* act){
act->sa_sigaction = NULL;
act->sa_handler = SIG_IGN;
sigset_t sigset;
int sigem;
if((sigem=sigemptyset(&sigset))<0){perror("sigemptyset error");exit(1);}
act->sa_mask= sigset;
act->sa_flags=0;
act->sa_restorer=NULL;
}
void sig_ign_drop(struct sigaction* act){
act->sa_sigaction = NULL;
act->sa_handler = SIG_DFL;
sigset_t sigset;
int sigem;
if((sigem=sigemptyset(&sigset))<0){perror("sigemptyset error");exit(1);}
act->sa_mask=sigset;
act->sa_flags=0;
act->sa_restorer=NULL;
}
void wait_child(int signal,siginfo_t* info,void* ctx){
if(info->si_code==CLD_STOPPED){
pid_stack[count] = info->si_pid;
count++;
}
if(info->si_code != CLD_CONTINUED){
int wstatus;
if ((waiting_pid = waitpid(info->si_pid,&wstatus, WUNTRACED))<0){perror("waitchild error");}
}
//printf("accepted"); //For debug(NOT RECOMMENDED)
}
void sig_wait_child(struct sigaction*act){
act->sa_handler = NULL;
act->sa_sigaction = wait_child;
sigset_t sigset;
int sigem;
if((sigem=sigemptyset(&sigset))<0){perror("sigemptyset error");exit(1);}
act->sa_mask=sigset;
act->sa_flags = SA_SIGINFO;
act->sa_restorer = NULL;
}
|
C
|
#include <stdlib.h>
#include <stdio.h>
#include <pcap.h>
#include <Winsock2.h>
void bin_prnt_byte(int x)
{
int n;
for(n=0; n < 8; n++)
{
if((x & 0x80) !=0)
{
printf("1");
}
else
{
printf("0");
}
x = x<<1;
}
}
void debug_print_packet_data(const u_char *pkt_data)
{
const u_char *datagramme;
int i, j;
int packet_size;
unsigned char c;
// Header ethernet => 14 Bytes
// Header IPV4 => 20 bytes
// Header UDP => 8 bytes
datagramme = pkt_data + 14 + 20 + 8;
// Client or sever ?
char direction;
int src_port = ntohs(*(u_short *)(datagramme - 8));
int dest_port = ntohs(*(u_short *)(datagramme - 6));
if (src_port == 11677)
direction = '<';
else if (dest_port == 11677)
direction = '>';
else
direction = '?';
// Get the datagramme size from the UDP header
packet_size = ntohs(*(u_short *)(datagramme - 4)) - 8;
if (packet_size <= 4)
return;
printf("Packet. Size: %d\n", packet_size);
datagramme = pkt_data + 14 + 20 + 8;
for (i = 0; i < packet_size; i += 16) {
// Hexadecimal data
printf("%c ", direction);
for (j = 0; j < 16; j++)
{
if (i + j < packet_size)
{
c = *(datagramme + i + j);
printf("%.2X ", c);
}
else
{
printf(" ");
}
}
printf(" ");
// Printable characters
for (j = 0; j < 16 && i + j < packet_size; j++)
{
c = *(datagramme + i + j);
if (c < 32 || c > 126)
{
c = '.';
}
printf("%c", c);
}
printf("\n");
}
// Print the 3 first bytes in binary format
for (i = 0; i < 3; i++)
{
c = *(datagramme + i);
bin_prnt_byte(c);
printf(" ");
}
printf("\n\n");
}
int main()
{
pcap_t *fp;
char errbuf[PCAP_ERRBUF_SIZE];
char *source = NULL;
char *filter = NULL;
struct bpf_program fcode;
bpf_u_int32 NetMask;
int res;
struct pcap_pkthdr *header;
const u_char *pkt_data;
pcap_if_t *alldevs;
/* Retrieve the device list */
if(pcap_findalldevs(&alldevs, errbuf) == -1)
{
fprintf(stderr,"Error in pcap_findalldevs: %s\n", errbuf);
return (-1);
}
if(!alldevs || !(alldevs->name))
{
fprintf(stderr, "No device capture found!");
return (-1);
}
// Select the first device capture as source
source = alldevs->name;
// open a capture from the network
if ((fp = pcap_open_live(source, // name of the device
65536, // portion of the packet to capture.
// 65536 grants that the whole packet will be captured on all the MACs.
1, // promiscuous mode (nonzero means promiscuous)
1000, // read timeout
errbuf // error buffer
)) == NULL)
{
fprintf(stderr,"\nUnable to open the adapter.\n");
return -2;
}
// Capture the packets on UDP port 11677 (T4C)
filter = "udp and port 11677";
// We should loop through the adapters returned by the pcap_findalldevs_ex()
// in order to locate the correct one.
//
// Let's do things simpler: we suppose to be in a C class network ;-)
NetMask=0xffffff;
//compile the filter
if(pcap_compile(fp, &fcode, filter, 1, NetMask) < 0)
{
fprintf(stderr,"\nError compiling filter: wrong syntax.\n");
pcap_close(fp);
return -3;
}
//set the filter
if(pcap_setfilter(fp, &fcode)<0)
{
fprintf(stderr,"\nError setting the filter\n");
pcap_close(fp);
return -4;
}
//start the capture
while((res = pcap_next_ex(fp, &header, &pkt_data)) >= 0)
{
if (res == 0)
continue;
debug_print_packet_data(pkt_data);
}
pcap_close(fp);
return 0;
}
|
C
|
/**
* @file gost89_mac.c
* @brief GOST 28147-89 emplementation.
* @author Gerasimov A.S.
*/
#include "typedef.h"
#include "crypto/gost89.h"
#include "memory/memory.h"
/**
* @brief
* Calculate MAC summ by GOST algorithm.
*
* @param ctx : [in] point to GOST context.
* @param dst : [out] buffer for output block.
* @param src : [in] address of input block.
*/
void gost89_mac_update ( gost89_ctx_t *ctx, const uint32 *pdata, size_t len )
{
register uint32 c0;
uint32 accumul[2];
uint32 n1 = ctx->seed[0];
uint32 n2 = ctx->seed[1];
for( c0 = len >> 3; c0; c0-- )
{
n1 ^= *pdata++;
n2 ^= *pdata++;
__GOST_STEP_DIRECT( ctx->key, n1, n2 );
__GOST_STEP_DIRECT( ctx->key, n1, n2 );
}
if( len & 0x00000007 )
{
accumul[0] = 0;
accumul[1] = 0;
memcpy( accumul, pdata, len & 0x00000007 );
n1 ^= accumul[0];
n2 ^= accumul[1];
__GOST_STEP_DIRECT( ctx->key, n1, n2 );
__GOST_STEP_DIRECT( ctx->key, n1, n2 );
}
ctx->seed[0] = n1;
ctx->seed[1] = n2;
}
/**
* @brief
* Store MAC result.
*
* @param ctx : [in] point to GOST context.
* @param dst : [out] buffer address to store MAC.
*/
void gost89_mac_final ( gost89_ctx_t *ctx, uint32 *mac )
{
*mac = ctx->seed[0];
}
|
C
|
#include"../tree.h"
void options_av(tree *t)
{
do{
printf("\n MENU : ");
printf("\n 1: Balance Factor ");
printf("\n 2: Inorder ");
printf("\n 3: Search ");
printf("\n 4: Insert ");
printf("\n 5: Delete in AVL ");
printf("\n 6: Other Displays ");
printf("\n 7: Lowest Common Ancestor ");
printf("\n 0: Back ");
scanf(" %d",&c);
system("clear");
switch(c)
{
case 1: balance(t); end; break;
case 2: end; inor(t); end; break;
case 3: searchbst(t); break;
case 4: {
printf("\n What do you want to insert ? ");
scanf("%d",&k);
t=insavl(t,k);
} break;
case 5: t=delavl(t); break;
case 6: display_bt(t); break;
case 7: { int a1,a2;
end; inor(t); end;
printf("\n Enter First key : "); scanf("%d",&a1);
printf("\n Enter Second key : "); scanf("%d",&a2); end; end;
printf("\n The ancestor is found out to be : \n\n%d ",lca(t,a1,a2)->data);
system("sleep 2");
system("clear");
} break;
case 0: {
printf("\n Are you sure to go back : ");
scanf(" %d",&z);
if(z==1)
{
system("clear");
printf("\n\n Returning from the AVL Tree menu ");
printf("\n (Expected wait time - 2 secs) \n");
system("sleep 2");
return;
}
else options_av(t);
}
}
}
while(c!=0);
}
|
C
|
#include "common.h"
//// io ports
#define DATA_BITS_8 3
#define STOP_BITS_1 0
#define DATA_REG(n) (n)
#define INT_ENABLE_REG(n) ((n) + 1)
#define FIFO_CTRL_REG(n) ((n) + 2)
#define DIVISOR_LO_REG(n) (n)
#define DIVISOR_HI_REG(n) ((n) + 1)
#define LINE_CTRL_REG(n) ((n) + 3)
#define MODEM_CTRL_REG(n) ((n) + 4)
#define LINE_STAT_REG(n) ((n) + 5)
#define MODEM_STAT_REG(n) ((n) + 6)
#define SCRATCH_REG(n) ((n) + 7)
#define SERIAL_PORT 0x3F8
static void serial_input_handler(registers_t regs)
{
unsigned char c;
c=inb(DATA_REG(SERIAL_PORT));
ar_addInputKey(c);
// ut_printf(" Received the char from serial %x %c \n",c,c);
outb(INT_ENABLE_REG(SERIAL_PORT), 0x01); // Issue an interrupt when input buffer is full.
}
void init_serial()
{
int portno = SERIAL_PORT ;
int reg;
outb(INT_ENABLE_REG(portno), 0x00); // Disable all interrupts
outb(LINE_CTRL_REG(portno), 0x80); // Enable DLAB (set baud rate divisor)
outb(DIVISOR_LO_REG(portno), 1 & 0xff); // Set divisor to (lo byte)
outb(DIVISOR_HI_REG(portno), 1 >> 8); // (hi byte)
// calculate line control register
reg =
(DATA_BITS_8 & 3) |
(STOP_BITS_1 ? 4 : 0) |
(0 ? 8 : 0) |
(0 ? 16 : 0) |
(0 ? 32 : 0) |
(0 ? 64 : 0);
outb(LINE_CTRL_REG(portno), reg);
outb(FIFO_CTRL_REG(portno), 0x47); // Enable FIFO, clear them, with 4-byte threshold
outb(MODEM_CTRL_REG(portno), 0x0B); // No modem support
outb(INT_ENABLE_REG(portno), 0x01); // Issue an interrupt when input buffer is full.
ar_registerInterrupt(36,serial_input_handler,"serial");
}
static spinlock_t serial_lock = SPIN_LOCK_UNLOCKED;
int dr_serialWrite( char *buf , int len)
{
int i;
unsigned long flags;
spin_lock_irqsave(&serial_lock, flags);
for (i=0; i<len; i++)
{
outb(DATA_REG(SERIAL_PORT), buf[i]);
}
spin_unlock_irqrestore(&serial_lock, flags);
}
|
C
|
/// start
#include "print.h"
#include "itoa.c"
// For memory IO
void print_char(const char c)
{
char *p = (char*)OUT_MEM;
*p = c;
return;
}
void print_string(const char *str)
{
const char *p;
for (p = str; *p != '\0'; p++)
print_char(*p);
print_char(*p);
print_char('\n');
return;
}
// For memory IO
void print_integer(int x)
{
char *str;
str = itoa(x);
print_string(str);
return;
}
|
C
|
/* Partner 1 Name & E-mail: Andrew Cruz [email protected]
* Partner 2 Name & E-mail: Jonathan Kaneshiro [email protected]
* Lab Section: 24
* Assignment: Lab #4 Exercise #3
* Exercise Description: [optional - include for your own benefit]
* A household has a digital combination deadbolt lock system on the doorway.
* The system has buttons on a keypad. Button 'X' connects to PA0, 'Y' to PA1,
* and '#' to PA2. Pressing and releasing '#', then pressing 'Y', should unlock the door by setting PB0 to 1.
* Any other sequence fails to unlock. Pressing a button from inside the house (PA7) locks the door (PB0=0).
* For debugging purposes, give each state a number, and always write the current state to PORTC (consider using the enum state variable).
* Also, be sure to check that only one button is pressed at a time.
*
* I acknowledge all content contained herein, excluding template or example
* code, is my own original work.
*/
#include <avr/io.h>
#define locked 0x00;
#define unlocked 0x01;
enum Lock_States {Lock, One, Two, Three, Four, Five} Lock_State;
void SM_Door_Lock() {
unsigned char PA_0 = PINA & 0x01;
unsigned char PA_1 = PINA & 0x02;
unsigned char PA_2 = PINA & 0x04;
unsigned char PA_7= PINA & 0x80;
switch(Lock_State) {
case Lock: { //Start State and locking state
Lock_State = One;
}
case One: {
if( (!PA_0 && !PA_1) && (PA_2 && !PA_7) ) { //Move to Next State if Pressing only '#'(PA_2) and door is not being locked from inside(PA_7)
Lock_State = Two;
} else if(PA_7) { //If PA_7 is pressed go to lock state
Lock_State = Lock;
} else { //Any other combination will bring you back to start state(One)
Lock_State = One;
}
break;
}
case Two: { //'#' pressed state
if( (!PA_0 && !PA_1) && (PA_2 && !PA_7) ) { //Stay in stat if still holding '#'(PA_2) down and door is not being locked from inside(PA_7)
Lock_State = Two;
} else if(PA_7) { //If PA_7 is pressed go to lock state
Lock_State = Lock;
} else if( (!PA_0 && !PA_1) && (!PA_2 && !PA_7) ) { //Move to Next State if nothing is being held down
Lock_State = Three;
} else { //Any other combination will bring you back to start state(One)
Lock_State = One;
}
break;
}
case Three: { //'#' release state
if( (!PA_0 && !PA_1) && (!PA_2 && !PA_7) ) { //Stay in stat if still not holding anything down
Lock_State = Three;
} else if(PA_7) { //If PA_7 is pressed go to lock state
Lock_State = Lock;
} else if( (!PA_0 && PA_1) && (!PA_2 && !PA_7) ) { //Move to Next State if 'Y'(PA_1) is held down and door is not being locked from inside(PA_7)
Lock_State = Four;
} else { //Any other combination will bring you back to start state(One)
Lock_State = One;
}
break;
}
case Four: { //Y pressed but not released state
if( (!PA_0 && PA_1) && (!PA_2 && !PA_7) ) { //Stay in state if still 'Y'(PA_1) is held down and door is not being locked from inside(PA_7)
Lock_State = Four;
} else if(PA_7) { //If PA_7 is pressed go to lock state
Lock_State = Lock;
} else if( (!PA_0 && !PA_1) && (!PA_2 && !PA_7) ) { //Move to Next State if nothing is being held down
Lock_State = Five;
} else { //Any other combination will bring you back to start state(One)
Lock_State = One;
}
break;
}
case Five: { //Unlock State
if( PA_7 ) { //If door is locked from inside(PA_7) then go to lock state(One)
Lock_State = One;
} else if(PA_7) { //If PA_7 is pressed go to lock state
Lock_State = Lock;
} else if( (!PA_0 && !PA_1) && (PA_2 && !PA_7) ) { //Pressing '#' will continue to State 2 to check sequence
Lock_State = Two;
} else { //Anything other than door being locked from inside(PA_7) will keep door unlocked
Lock_State = Five;
}
break;
}
default: { //Any error brings us back to Lock State
Lock_State = Lock;
break;
}
} //Transitions
//Stores where door is locked or unlocked
unsigned char tempB;
//Stores what state we are in
unsigned char tempC;
unsigned char previousB = PORTB & 0x01;
switch(Lock_State) {
case Lock: {
tempB = locked;
tempC = 0x00;
break;
}
case One: { //State One door is locked
tempB = previousB;
tempC = 0x01;
break;
}
case Two: { //State Two door is locked
tempB = previousB;
tempC = 0x02;
break;
}
case Three: { //State Three door is locked
tempB = previousB;
tempC = 0x03;
break;
}
case Four: { //State Four door is locked
tempB = previousB;
tempC = 0x04;
break;
}
case Five: { //State Five door is unlocked
tempB = (previousB) ? locked : unlocked;
tempC = 0x05;
break;
}
default: {
tempB = locked;
tempC = 0x01;
break;
}
} //Actions
//Set PORTB and PORTC to values
PORTB = tempB;
PORTC = tempC;
}
int main(void)
{
//Init SM to first state
Lock_State = Lock;
while (1)
{
SM_Door_Lock();
}
}
|
C
|
#include "rtos_hal.h"
#include "stdio.h"
#include "plp_math.h"
#include "data.h"
#include "defines.h"
void cluster_entry_i32(void* args) {
printf("Cluster entered. Compute for i32.\n\n");
int32_t result=0;
// We also count the number of cycles taken to compute it.
// This structure will hold the configuration and also the results in the
// cumulative mode
rt_perf_t perf;
// It must be initiliazed at least once, this will set all values in the
// structure to zero.
rt_perf_init(&perf);
// Activate specified events
rt_perf_conf(&perf, (1<<RT_PERF_CYCLES) | (1<<RT_PERF_INSTR)); // Note: on gvsoc you can activate as many counters as you want, while when you run on board, there is only one HW counter.
#ifdef SLOW
// Reset HW counters now and start and stop counters so that we benchmark
// only around the printf
rt_perf_reset(&perf);
rt_perf_start(&perf);
plp_dot_prod_i32s_xpulpv2(a, b, VLEN, &result);
rt_perf_stop(&perf);
printf("The true result is %d, the calculated result is %d.\n", res, result);
printf("Total cycles: %d\n", rt_perf_read(RT_PERF_CYCLES));
printf("Instructions: %d\n", rt_perf_read(RT_PERF_INSTR));
printf("\nThe number of cycles is extremely high! What is happening?\n\n");
#endif //SLOW
#ifdef L2DATA
printf("\nBy default the data is stored in L2 memory in the SoC, the access from the cluster to L2 memory takes many cycles. Let's now store the vectors in L1 memory.\n\n");
// Reset HW counters now and start and stop counters so that we benchmark
// only around the printf
rt_perf_reset(&perf);
rt_perf_start(&perf);
plp_dot_prod_i32s_xpulpv2(a_cl, b_cl, VLEN, &result);
rt_perf_stop(&perf);
printf("The true result is %d, the calculated result is %d.\n", res, result);
printf("Total cycles: %d\n", rt_perf_read(RT_PERF_CYCLES));
printf("Instructions: %d\n", rt_perf_read(RT_PERF_INSTR));
printf("\nThe number of cycles is significantly reduced.\n\n");
#endif //L2DATA
return;
}
|
C
|
/*32. Find out the value of a.
a = b > c ? c > d ? 12 : d > e ? 13 : 14 : 15
for
1. b=5;c=15;d=e=8;
2. b=15;c=10;d=e=8;
3. b=5;c=15;d=e=20;
4. b=c=9;d=20;e=19; */
#include<stdio.h>
int main()
{
int a,b=5,c=15,d=8,e=8;
a = (b>c) ? ( (c>d) ? 12 : ( d>e ? 13:14)) : 15 ;
printf("a=%d\n",a);
return 0;
}
/*here if b>c false it jumps to 15
if we give b<c which is true it enters c>d and give 12
if we give c<d which is false it enters d>e and gives 14 */
|
C
|
/**
* @file command_module_util.c
* @author Alex Amellal ([email protected])
* @brief Utility functions for the command module
* @version 0.1
* @date 2021-11-19
*
* @copyright Dalhousie Space Systems Lab (c) 2021
*
*/
#include "command_module_util.h"
int cmd_parse(char* cmd, size_t cmd_len) {
// Get args
int argc = ipc_get_n_args(cmd, cmd_len);
char argv[argc][MAX_ARG_LEN];
OK(ipc_get_args(cmd, cmd_len, argv, argc));
// Check commands
if (ipc_check_cmd(CMD_TAKE_PICTURE_GPS)) {
return CMD_TAKE_PICTURE_GPS_ID;
} else if (ipc_check_cmd(CMD_TAKE_PICTURE_TIME)) {
return CMD_TAKE_PICTURE_TIME_ID;
} else if (ipc_check_cmd(CMD_TAKE_PICTURE)) {
return CMD_TAKE_PICTURE_ID;
}
// done, no command identified
return 0;
}
/**
* @brief Parses and executes requirements for provided command.
*
* @param cmd String containing command to parse.
* @param cmd_len Length of cmd.
* @return 0 = OK, -1 = ERROR
*/
int cmd_handle(char* cmd, size_t cmd_len) {
// Parse command
int cmd_id = cmd_parse(cmd, cmd_len);
// Check if GPS condition provided
if (cmd_id == CMD_TAKE_PICTURE_GPS_ID) {
// Get args
int argc = ipc_get_n_args(cmd, strlen(cmd));
char args[argc][MAX_ARG_LEN];
OK(ipc_get_args(cmd, strlen(cmd), args, argc));
// Check argc
if (argc != 6) {
moderr("Invalid number of arguments. SKIPPING\n");
return -1;
}
// Get coordinate floats
float gps_min[2], gps_max[2];
gps_min[0] = atof(args[2]);
gps_min[1] = atof(args[3]);
gps_max[0] = atof(args[4]);
gps_max[1] = atof(args[5]);
modprintf(
"About to ask mission to take picture at coordinates (min) %f, %f, "
"(max) %f, %f\n",
gps_min[0], gps_min[1], gps_max[0], gps_max[1]);
// Forward command to the mission module
OK(ipc_send_cmd(ipc.core.msn.name, "%s %s %s %f %f %f %f",
ipc.core.msn.cmd.qmsn, "gps", ipc.pay.cmd.take_pic,
gps_min[0], gps_min[1], gps_max[0], gps_max[1]));
// Check if time condition provided
} else if (cmd_id == CMD_TAKE_PICTURE_TIME_ID) {
// Get args
int argc = ipc_get_n_args(cmd, strlen(cmd));
char args[argc][MAX_ARG_LEN];
OK(ipc_get_args(cmd, strlen(cmd), args, argc));
// Check argc
if (argc != 3) {
moderr("Invalid number of arguments. SKIPPING\n");
return -1;
}
// Get time
time_t t = atol(args[2]);
modprintf("About to ask mission to take picture at time %ld\n", t);
// Forward to mission module
OK(ipc_send_cmd(ipc.core.msn.name, "%s %s %s %ld", ipc.core.msn.cmd.qmsn,
"time", ipc.pay.cmd.take_pic, t));
// Check for commands for other subsystems
} else if (cmd_id == CMD_TAKE_PICTURE) {
// Send message to payload
OK(ipc_send_cmd(ipc.pay.name, ipc.pay.cmd.take_pic));
}
}
|
C
|
/*
** incantation.c for zappy in /home/guilbo_m/rendu/PSU/PSU_2016_zappy
**
** Made by Mathis Guilbon
** Login <[email protected]>
**
** Started on Sun Jun 24 14:10:14 2017 Mathis Guilbon
** Last update Sun Jul 2 00:06:59 2017 Baptiste Veyssiere
*/
#include <unistd.h>
#include "server.h"
bool incant_underway(t_data *data, t_player *player)
{
t_player *tmp;
tmp = data->players_root;
if (pic_init(data, player) == -1)
return (false);
while (tmp != NULL)
{
if (tmp->pos->x == player->pos->x &&
tmp->pos->y == player->pos->y &&
tmp->level == player->level &&
(socket_write(tmp->fd, "Elevation underway\n") == -1 ||
(tmp != player && pic(data, tmp) == -1) ||
add_to_ilist(player, tmp) == -1))
return (false);
tmp = tmp->next;
}
if (pic_end(data) == -1)
return (false);
return (true);
}
bool enough_people(t_data *data, t_player *player,
unsigned int needed)
{
t_player *tmp;
unsigned int count;
tmp = data->players_root;
count = 0;
while (tmp != NULL)
{
if (tmp->pos->x == player->pos->x &&
tmp->pos->y == player->pos->y &&
tmp->level == player->level)
++count;
tmp = tmp->next;
}
return (count == needed);
}
bool upgrade_to_lvl2(t_data *data, t_player *player)
{
t_items *items;
items = &data->map[player->pos->y][player->pos->x];
if (items->players == 1 && items->item[LINEMATE] == 1 &&
items->item[DERAUMERE] == 0 && items->item[SIBUR] == 0 &&
items->item[MENDIANE] == 0 && items->item[PHIRAS] == 0 &&
items->item[THYSTAME] == 0)
return (true);
return (false);
}
bool upgrade_to_lvl3(t_data *data, t_player *player)
{
t_items *items;
items = &data->map[player->pos->y][player->pos->x];
if (items->players == 2 && enough_people(data, player, 2) &&
items->item[LINEMATE] == 1 && items->item[DERAUMERE] == 1 &&
items->item[SIBUR] == 1 && items->item[MENDIANE] == 0 &&
items->item[PHIRAS] == 0 && items->item[THYSTAME] == 0)
return (true);
return (false);
}
bool upgrade_to_lvl4(t_data *data, t_player *player)
{
t_items *items;
items = &data->map[player->pos->y][player->pos->x];
if (items->players == 2 && enough_people(data, player, 2) &&
items->item[LINEMATE] == 2 && items->item[DERAUMERE] == 0 &&
items->item[SIBUR] == 1 && items->item[MENDIANE] == 0 &&
items->item[PHIRAS] == 2 && items->item[THYSTAME] == 0)
return (true);
return (false);
}
|
C
|
#include "ensemble.h"
//limitações: Esse algoritmo só funciona bem quando todos os ensembles tem o mesmo número de agrupamentos, que é igual ao número de agrupamentos alvo.
unsigned int *normalize_clusters(unsigned int *cluster,unsigned int Nelements){
unsigned int *taken = CALLOC(unsigned int,NCLUSTERSMAX);
unsigned int *newCluster = MALLOC(unsigned int,Nelements);
unsigned int Nclusters = 0;
for(unsigned int i=0;i<Nelements;i++){
if( taken[cluster[i]] == 0 ){
newCluster[i] = taken[cluster[i]] = ++Nclusters;
}
else{
newCluster[i] = taken[cluster[i]];
}
}
return newCluster;
}
void Copy(unsigned int *clusterCenter,unsigned int *clusterPoint,int Nclusters){
for(int i=0;i<Nclusters;i++)
clusterCenter[i] = clusterPoint[i];
}
int Hamming(unsigned int *clusterCenter,unsigned int *clusterPoint,int Nclusters){
int dist = 0;
for(int i=0;i<Nclusters;i++)
if(clusterCenter[i] != clusterPoint[i])
dist++;
return dist;
}
int Reassign(unsigned int **clusterCenters,unsigned int **clusterPoints,unsigned int *finalClustering,int Nelements,int Nclusters,int NclustersFinal){
int hammingSum = 0;
for(int i=0;i<Nelements;i++){
int newCluster = 0;
int minDist = Hamming(clusterCenters[0],clusterPoints[i],Nclusters);
for(int j=1;j<NclustersFinal;j++){
if(Hamming(clusterCenters[j],clusterPoints[i],Nclusters) < minDist){
minDist = Hamming(clusterCenters[j],clusterPoints[i],Nclusters);
newCluster = j;
}
}
finalClustering[i] = newCluster;
hammingSum += minDist;
}
return hammingSum;
}
void RecalculateCenters(unsigned int **clusterCenters,unsigned int **clusterPoints,unsigned int *finalClustering,int Nelements,int Nclusters,int NclustersFinal){
int ***frequency = MALLOC(int**,NclustersFinal);
for(int i=0;i<NclustersFinal;i++){
frequency[i] = MALLOC(int*,Nclusters);
for(int j=0;j<Nclusters;j++)
frequency[i][j] = MALLOC(int,NCLUSTERSMAX);
}
//int frequency[NclustersFinal][Nclusters][NCLUSTERSMAX];
for(int i=0;i<NclustersFinal;i++)
for(int j=0;j<Nclusters;j++)
for(int k=0;k<NCLUSTERSMAX;k++)
frequency[i][j][k]=0;
for(int i=0;i<Nelements;i++){
for(int j=0;j<Nclusters;j++){
frequency[finalClustering[i]][j][clusterPoints[i][j]]++;
}
}
for(int i=0;i<NclustersFinal;i++)
for(int j=0;j<Nclusters;j++){
int freq = 0;
for(int k=0;k<NCLUSTERSMAX;k++)
if(freq < frequency[i][j][k]){
freq = frequency[i][j][k];
clusterCenters[i][j] = k;
}
}
}
unsigned int *IVC(unsigned int **ensemble,int Nclusters,int Nelements,int NclustersFinal){
unsigned int **clusterCenters = MALLOC(unsigned int*,NclustersFinal);
for(int i=0;i<NclustersFinal;i++)
clusterCenters[i] = MALLOC(unsigned int,Nclusters);
unsigned int **clusterPoints = MALLOC(unsigned int*,Nelements);
for(int i=0;i<Nelements;i++)
clusterPoints[i] = MALLOC(unsigned int,Nclusters);
for(int i=0;i<Nelements;i++)
for(int j=0;j<Nclusters;j++)
clusterPoints[i][j] = ensemble[j][i];
int initialCentroids[NclustersFinal];
int Nselected = 0;
int *selected = CALLOC(int,Nelements);
while(Nselected < NclustersFinal){
int candidate = rand()%Nelements;
if(!selected[candidate]){
selected[candidate] = 1;
initialCentroids[Nselected++] = candidate;
}
}
for(int i=0;i<NclustersFinal;i++)
Copy(clusterCenters[i],clusterPoints[initialCentroids[i]],Nclusters);
unsigned int *finalClustering = MALLOC(unsigned int,Nelements);
int hammingSum = Reassign(clusterCenters,clusterPoints,finalClustering,Nelements,Nclusters,NclustersFinal);
int previousHammingSum = hammingSum + 1;
while(hammingSum < previousHammingSum){
previousHammingSum = hammingSum;
RecalculateCenters(clusterCenters,clusterPoints,finalClustering,Nelements,Nclusters,NclustersFinal);
hammingSum = Reassign(clusterCenters,clusterPoints,finalClustering,Nelements,Nclusters,NclustersFinal);
}
return finalClustering;
}
int main(int agrc,char **argv){
clock_t start = clock();
srand(time(NULL));
int Nelements,Nclusters;
scanf("%d%d",&Nelements,&Nclusters);
unsigned int **ensemble = MALLOC(unsigned int*,Nclusters);
for(int i=0;i<Nclusters;i++)
ensemble[i] = MALLOC(unsigned int,Nelements);
for(int i=0;i<Nclusters;i++)
for(int j=0;j<Nelements;j++)
scanf("%d",&ensemble[i][j]);
for(int i=0;i<Nclusters;i++)
ensemble[i] = normalize_clusters(ensemble[i],Nelements);
int NclustersFinal = atoi(argv[1]);
unsigned int *finalClustering = IVC(ensemble,Nclusters,Nelements,NclustersFinal);
finalClustering = normalize_clusters(finalClustering,Nelements);
clock_t end = clock();
char output[100];
strcpy(output,argv[2]);
strcat(output,"_IVC");
FILE *fileOutput = fopen(output,"w");
if(fileOutput){
for(int i=0;i<Nelements;i++)
fprintf(fileOutput,"%d ",finalClustering[i]);
fprintf(fileOutput,"\nTempo usado: %lf",(double)(end-start)/CLOCKS_PER_SEC);
}
else{
printf("nao foi possivel salver o resultado do IVC\n");
}
return 0;
}
|
C
|
#include <stdio.h>
#include <netdb.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <string.h>
#include <unistd.h>
#include <pthread.h>
#include <stdlib.h>
#include "client.h"
#include "calcul.h"
void *client(void *pt)
{
ClientArgs *args = (ClientArgs *)pt;
struct sockaddr_in adr;
adr.sin_family = PF_INET;
adr.sin_addr.s_addr = inet_addr(args->host);
while (1)
{
/* Reçois la taille du port et le port */
/*********************************/
PipeClient dataClient[1];
read(args->pipeEnvoi, dataClient, sizeof(dataClient));
adr.sin_port = htons(dataClient->port);
/* Creation de la socket */
/*************************/
int descripteurDeSocket = socket(AF_INET, SOCK_STREAM, 0);
if (descripteurDeSocket < 0)
{
printf("Problemes pour creer la socket");
exit(1);
}
/* Connect de la socket */
/*************************/
if (connect(descripteurDeSocket, (struct sockaddr *)&adr, sizeof(adr)) < 0)
{
printf("Client : Problemes pour se connecter au serveur\n");
exit(1);
}
DataSocket toSend[1];
toSend->type = dataClient->type;
switch (dataClient->type)
{
case 0: //Message
{
strcpy(toSend->message, dataClient->message);
break;
}
case 1: //Request
toSend->pid = dataClient->pid;
toSend->horloge = dataClient->horloge;
toSend->RequestPort = dataClient->RequestPort;
break;
}
send(descripteurDeSocket, toSend, sizeof(toSend), 0);
close(descripteurDeSocket);
}
}
|
C
|
#include"../header/header.h"
int hashValue(char *string)
{
// printf("\n in hashfun \n");
int count = 0;
int total = 0;
int i, res;
count = strlen(string);
for( i = 0; i < count; i++)
{
total += *(string + i);
}
res = total % 10;
return res;
//printf("\n total is =%d \n", total);
}
|
C
|
/**
* PLATOTerm64 - A PLATO Terminal for the Commodore 64
* Based on Steve Peltz's PAD
*
* Author: Thomas Cherryhomes <thom.cherryhomes at gmail dot com>
*
* terminal.c - Terminal state functions
*/
#include <stdbool.h>
#include <string.h>
#include "../include/terminal.h"
#include "../include/screen.h"
#define true 1
#define false 0
/**
* ASCII Features to return in Features
*/
#define ASC_ZFGT 0x01
#define ASC_ZPCKEYS 0x02
#define ASC_ZKERMIT 0x04
#define ASC_ZWINDOW 0x08
/**
* protocol.c externals
*/
extern CharMem CurMem;
extern padBool TTY;
extern padBool ModeBold;
extern padBool Rotate;
extern padBool Reverse;
extern DispMode CurMode;
extern padBool FlowControl;
/**
* screen.c externals
*/
extern unsigned char CharWide;
extern unsigned char CharHigh;
extern padPt TTYLoc;
extern unsigned char already_started;
/**
* terminal_init()
* Initialize terminal state
*/
void terminal_init(void)
{
terminal_set_tty();
}
/**
* terminal_initial_position()
* Set terminal initial position after splash screen.
*/
void terminal_initial_position(void)
{
TTYLoc.x=0;
TTYLoc.y=256; // Right under splashscreen.
}
/**
* terminal_set_tty(void) - Switch to TTY mode
*/
void terminal_set_tty(void)
{
if (already_started)
screen_clear();
TTY=true;
ModeBold=padF;
Rotate=padF;
Reverse=padF;
CurMem=M0;
/* CurMode=ModeRewrite; */
CurMode=ModeWrite; /* For speed reasons. */
CharWide=8;
CharHigh=16;
TTYLoc.x = 0; // leftmost coordinate on screen
TTYLoc.y = 495; // Top of screen - one character height
}
/**
* terminal_set_plato(void) - Switch to PLATO mode
*/
void terminal_set_plato(void)
{
TTY=false;
screen_clear();
}
/**
* terminal_get_features(void) - Inquire about terminal ASCII features
*/
unsigned char terminal_get_features(void)
{
return ASC_ZFGT; /* This terminal can do Fine Grained Touch (FGT) */
}
/**
* terminal_get_type(void) - Return the appropriate terminal type
*/
unsigned char terminal_get_type(void)
{
return 12; /* ASCII terminal type */
}
/**
* terminal_get_subtype(void) - Return the appropriate terminal subtype
*/
unsigned char terminal_get_subtype(void)
{
return 1; /* ASCII terminal subtype IST-III */
}
/**
* terminal_get_load_file(void) - Return the appropriate terminal loadfile (should just be 0)
*/
unsigned char terminal_get_load_file(void)
{
return 0; /* This terminal does not load its resident from the PLATO system. */
}
/**
* terminal_get_configuration(void) - Return the terminal configuration
*/
unsigned char terminal_get_configuration(void)
{
return 0x40; /* Touch panel is present. */
}
/**
* terminal_get_char_address(void) - Return the base address of the character set.
*/
unsigned short terminal_get_char_address(void)
{
return 0x3000; /* What the? Shouldn't this be 0x3800? */
}
/**
* terminal_mem_read - Read a byte of program memory.
* not needed for our terminal, but must
* be decoded.
*/
padByte terminal_mem_read(padWord addr)
{
return (0xFF);
}
/**
* terminal_mem_load - Write a byte to non-character memory.
* not needed for our terminal, but must be decoded.
*/
void terminal_mem_load(padWord addr, padWord value)
{
/* Not Implemented */
}
/**
* Mode5, 6, and 7 are basically stubbed.
*/
void terminal_mode_5(padWord value)
{
}
void terminal_mode_6(padWord value)
{
}
void terminal_mode_7(padWord value)
{
}
/**
* terminal_ext_allow - External Input allowed. Not implemented.
*/
void terminal_ext_allow(padBool allow)
{
/* Not Implemented */
}
/**
* terminal_set_ext_in - Set which device to get input from.
* Not implemented
*/
void terminal_set_ext_in(padWord device)
{
}
/**
* terminal_set_ext_out - Set which device to send external data to.
* Not implemented
*/
void terminal_set_ext_out(padWord device)
{
}
/**
* terminal_ext_in - get an external input from selected device.
* Not implemented.
*/
padByte terminal_ext_in(void)
{
return 0;
}
/**
* terminal_ext_out - Send an external output to selected device
* Not implemented.
*/
void terminal_ext_out(padByte value)
{
}
// Temporary PLATO character data, 8x16 matrix
static unsigned char char_data[]={0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00};
static unsigned char BTAB[]={0x80,0x40,0x20,0x10,0x08,0x04,0x02,0x01}; // flip one bit on (OR)
static unsigned char BTAB_5[]={0x08,0x10,0x10,0x20,0x20,0x40,0x80,0x80}; // flip one bit on for the 5x6 matrix (OR)
static unsigned char TAB_0_5[]={0x05,0x05,0x05,0x04,0x04,0x04,0x03,0x03,0x02,0x02,0x01,0x01,0x01,0x00,0x00,0x00};
static unsigned char TAB_0_5i[]={0x00,0x00,0x00,0x01,0x01,0x01,0x02,0x02,0x03,0x03,0x04,0x04,0x04,0x05,0x05,0x05};
static unsigned char TAB_0_4[]={0x00,0x00,0x01,0x02,0x02,0x03,0x03,0x04}; // return 0..4 given index 0 to 7
static unsigned char PIX_THRESH[]={0x03,0x02,0x03,0x03,0x02, // Pixel threshold table.
0x03,0x02,0x03,0x03,0x02,
0x02,0x01,0x02,0x02,0x01,
0x02,0x01,0x02,0x02,0x01,
0x03,0x02,0x03,0x03,0x02,
0x03,0x02,0x03,0x03,0x02};
static unsigned char PIX_WEIGHTS[]={0x00,0x00,0x00,0x00,0x00, // Pixel weights
0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00};
static unsigned char TAB_0_25[]={0,5,10,15,20,25}; // Given index 0 of 5, return multiple of 5.
static unsigned char pix_cnt; // total # of pixels
static unsigned char curr_word; // current word
static unsigned char u,v; // loop counters
extern unsigned char fontm23[768];
extern unsigned short fontptr[160];
/**
* terminal_char_load - Store a character into the user definable
* character set.
*/
void terminal_char_load(padWord charnum, charData theChar)
{
// Clear char data.
memset(char_data,0,sizeof(char_data));
memset(PIX_WEIGHTS,0,sizeof(PIX_WEIGHTS));
memset(&fontm23[fontptr[charnum]],0,6);
pix_cnt=0;
// Transpose character data.
for (curr_word=0;curr_word<8;curr_word++)
{
for (u=16; u-->0; )
{
if (theChar[curr_word] & 1<<u)
{
pix_cnt++;
PIX_WEIGHTS[TAB_0_25[TAB_0_5[u]]+TAB_0_4[curr_word]]++;
char_data[u^0x0F&0x0F]|=BTAB[curr_word];
}
}
}
// Determine algorithm to use for number of pixels.
// Algorithm A is used when roughly half of the # of pixels are set.
// Algorithm B is used either when the image is densely or sparsely populated (based on pix_cnt).
if ((54 <= pix_cnt) && (pix_cnt < 85))
{
// Algorithm A - approx Half of pixels are set
for (u=6; u-->0; )
{
for (v=5; v-->0; )
{
if (PIX_WEIGHTS[TAB_0_25[u]+v] >= PIX_THRESH[TAB_0_25[u]+v])
fontm23[fontptr[charnum]+u]|=BTAB[v];
}
}
}
else if ((pix_cnt < 54) || (pix_cnt >= 85))
{
// Algorithm B - Sparsely or heavily populated bitmaps
for (u=16; u-->0; )
{
if (pix_cnt >= 85)
char_data[u]^=0xFF;
for (v=8; v-->0; )
{
if (char_data[u] & (1<<v))
{
fontm23[fontptr[charnum]+TAB_0_5i[u]]|=BTAB_5[v];
}
}
}
if (pix_cnt >= 85)
{
for (u=6; u-->0; )
{
fontm23[fontptr[charnum]+u]^=0xFF;
fontm23[fontptr[charnum]+u]&=0xF8;
}
}
}
}
/**
* terminal_ready() - Show ready
*/
void terminal_ready(void)
{
TTYLoc.x=TTYLoc.y=0;
ShowPLATO("PLATOTerm 1.2 Ready. EXTEND 9 - Print. EXTEND 0 - Help",54);
}
|
C
|
#include "main.h"
#include "utils.h"
#include "irc.h"
int strpos(char *needle, char *haystack) {
char *dest = strstr(haystack, needle);
return (dest - haystack) + 1;
}
int instr(const char *h, const char *n) {
return (strstr(h,n)!=NULL);
}
int instrf(const char *h, const char *n, ...) {
va_list args;
va_start(args, n);
char s[DEFAULT_BUFLEN];
vsprintf(s,n,args);
va_end(args);
return instr(h,s);
}
int str_isspace(char *str) {
int i;
for(i=0;i<strlen(str);i++){
if (!isspace(str[i]))
return 0;
}
return 1;
}
char *strtrim_l(const char *string, int trim, char *dest) {
int len=strlen(string);
strncpy(dest,string+trim,len);
dest[len]='\0';
return dest;
}
//Function adatpted from: http://stackoverflow.com/a/780024/883015
char *StrReplaceAll(char const * const original, char const * const pattern, char const * const replacement) {
size_t const replen = strlen(replacement);
size_t const patlen = strlen(pattern);
size_t const orilen = strlen(original);
size_t patcnt = 0;
const char * oriptr;
const char * patloc;
// find how many times the pattern occurs in the original string
for (oriptr = original; patloc = strstr(oriptr, pattern); oriptr = patloc + patlen)
{
patcnt++;
}
{
// allocate memory for the new string
size_t const retlen = orilen + patcnt * (replen - patlen);
char * const returned = (char *) malloc( sizeof(char) * (retlen + 1) );
if (returned != NULL)
{
// copy the original string,
// replacing all the instances of the pattern
char * retptr = returned;
for (oriptr = original; patloc = strstr(oriptr, pattern); oriptr = patloc + patlen)
{
size_t const skplen = patloc - oriptr;
// copy the section until the occurence of the pattern
strncpy(retptr, oriptr, skplen);
retptr += skplen;
// copy the replacement
strncpy(retptr, replacement, replen);
retptr += replen;
}
// copy the rest of the string.
strcpy(retptr, oriptr);
}
return returned;
}
}
void arr_zero(char a[], int len) {
int i;
for(i=0;i<len;i++)
a[i]=0;
}
void half_arr_zero(char a[], int len) {
int i;
for(i=0;i<(len/2);i++)
a[i+1]=0;
}
char *url_encode(char *str) {
return StrReplaceAll(StrReplaceAll(str," ","%20"),"&","%26");
}
void irc_getuser(char *buf, char u[]) {
sscanf(buf,":%s!",u);
int n=strpos("!",u);
if (n>0)
u[n-1]=0;
}
void irc_getmsg(char *buf, char m[]) {
char *p;
char *cbuf = strtok(buf,"\r\n");
if ((p=strpbrk(cbuf+1,":"))!=NULL)
{
int k = (p-cbuf+1);
int q = strlen(cbuf)-k;
strncpy(m,cbuf+k,q);
m[q]=0;
}
else
m[0]=0;
}
int irc_connected(char *recvbuf) {
if (instrf(recvbuf," %d ",RplMotdEnd) || instrf(recvbuf," %d ",ErrNoMotd))
return 1;
else
return 0;
}
int irc_identified(char *recvbuf) {
if (instr(recvbuf,"You are now identified"))
return 1;
if (instrf(recvbuf," %d ",ErrUserOnChannel))
return -1;
if (instrf(recvbuf," %d ",ErrNickNameInUse))
return -1;
if (instr(recvbuf,"Invalid password"))
return -1;
if (instr(recvbuf,"Nick/channel is temporarily unavailable"))
return -1;
return 0;
}
int irc_joined(char *recvbuf) {
if (instr(recvbuf,":End of /NAMES list"))
return 1;
return 0;
}
int irc_sender(char *r, const char *u) {
int i;
int ul = strlen(u);
int rl = strlen(r);
if ((rl > ul) && (r[0]==':') && (r[ul+1]=='!')) {
for(i=1;i<ul+1;i++) {
//printf("\n%c =vs= %c\n",r[i],u[i-1]);
if (r[i]!=u[i-1])
return 0;
}
return 1;
}
return 0;
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* errors.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: snicolet <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2016/05/03 21:14:07 by snicolet #+# #+# */
/* Updated: 2016/05/05 17:19:00 by snicolet ### ########.fr */
/* */
/* ************************************************************************** */
#include "minishell.h"
#include "libft.h"
#include <stdlib.h>
#include <unistd.h>
static const char *minishell_error_str(int errorn)
{
const char *str;
if (errorn == ERR_NOTFOUND)
str = "command not found";
else if (errorn == ERR_PERMS)
str = "permission denied";
else if (errorn == ERR_NOPATH)
str = "no PATH environement variable found";
else if (errorn == ERR_EXEC)
str = "child process has returned an error";
else if (errorn == ERR_ENVPARSE_UNKNOW)
str = "env: unknow argument";
else
str = "unknow error";
return (str);
}
int minishell_error(int errorn, char *suffix, int delsuffix)
{
const char *str = minishell_error_str(errorn);
ft_putstr_fd("minishell: ", 2);
ft_putstr_fd(str, 2);
if (suffix)
{
ft_putstr_fd(": ", 2);
ft_putstr_fd(suffix, 2);
}
write(2, "\n", 1);
if (delsuffix)
free(suffix);
return (errorn);
}
|
C
|
#include<stdio.h>
#include <unistd.h>
unsigned char swap_bits(unsigned char octet)
{
unsigned char rev;
int i = 0;
rev = 0;
while (i < 8)
{
rev |= octet & 1;
rev <<= 1;
octet >>= 1;
i++;
}
return (rev);
}
int main(void)
{
printf("%c\n", swap_bits(0b11110000));
return (0);
}
|
C
|
/**
Copyright 2014 Simon Zolin
*/
#include <test/tests.h>
#include <FFOS/test.h>
#define x FFTEST_BOOL
static int state;
static void test_conn_onconnect(void *userptr, int result);
static ssize_t test_conn_getvar(void *obj, const char *name, size_t namelen, void *dst, size_t cap);
static const fsv_connect_cb test_conn_cb = {
&test_conn_onconnect, &test_conn_getvar
};
static void test_conn_connectok(tester *t)
{
ffskt sk;
t->conn->getvar(t->conn_id, FFSTR("socket_fd"), &sk, sizeof(ffskt));
fsv_dbglog(t->logctx, FSV_LOG_DBGNET, "TEST", NULL, "socket: %L", sk);
t->conn->fin(t->conn_id, FSV_CONN_KEEPALIVE);
t->conn_id = NULL;
}
static void test_conn_connectnext(tester *t)
{
fsv_conn_new cn = {0};
cn.userptr = t;
t->conn->getserv(t->conctx, &cn, 0);
t->conn_id = cn.con;
t->conn->connect(t->conn_id, 0);
}
enum {
CONN_OK
, CONN_DNS
, CONN_ADDR
, CONN_KA_OK
, CONN_KA_EXPIRED
};
static void test_conn_katimer(void *param)
{
tester *t = param;
FFTEST_FUNC;
test_conn_connectnext(t);
}
static void test_conn_onconnect(void *userptr, int result)
{
tester *t = userptr;
FFTEST_FUNC;
switch (state++) {
case CONN_OK:
x(result == FSV_CONN_OK);
test_conn_connectok(t);
test_conn_connectnext(t);
break;
case CONN_DNS:
//failed to connect to a server. The server is now marked as down.
x(result == FSV_CONN_EDNS);
t->conn->fin(t->conn_id, 0);
t->conn_id = NULL;
test_conn_connectnext(t);
break;
case CONN_ADDR:
x(result == FSV_CONN_ENOADDR);
t->conn->fin(t->conn_id, 0);
t->conn_id = NULL;
test_conn_connectnext(t);
//getting connection with www.google.com from keep-alive cache...
break;
case CONN_KA_OK:
//keep-alive connection is ok
x(result == FSV_CONN_OK);
test_conn_connectok(t);
{
fsv_conn_new cn = {0};
cn.userptr = t;
cn.con = t->conn_id;
t->conn->getserv(t->conctx, &cn, 0);
// we have google.com again, because both srv1 and srv2 are down.
x(ffstr_eqcz(&cn.url, "http://www.google.com/some/path"));
t->conn->fin(cn.con, FSV_CONN_KEEPALIVE);
}
t->srv->timer(&t->tmr, -2 * 1000, &test_conn_katimer, t); //wait 2 seconds to test keepalive_cache.expiry
break;
case CONN_KA_EXPIRED:
//keep-alive connection expired, we established a new connection
x(result == FSV_CONN_OK);
testm_runnext(t);
break;
}
}
static ssize_t test_conn_getvar(void *obj, const char *name, size_t namelen, void *dst, size_t cap)
{
FFTEST_FUNC;
if (ffs_eqcz(name, namelen, "my_var")) {
ffstr s;
if (obj == NULL)
ffstr_setcz(&s, "server3");
else
ffstr_setcz(&s, "www.google.com");
*(char**)dst = s.ptr;
return s.len;
}
return 0;
}
static void test_round_robin_balancer(tester *t)
{
const fsv_connect *conn = t->conn;
fsv_conn_new cn = {0};
conn->getserv(t->conctx, &cn, 0);
x(ffstr_eqcz(&cn.url, "http://server1"));
conn->fin(cn.con, 0);
cn.con = NULL;
conn->getserv(t->conctx, &cn, 0);
x(ffstr_eqcz(&cn.url, "http://127.0.0.1:64000"));
conn->fin(cn.con, 0);
cn.con = NULL;
conn->getserv(t->conctx, &cn, 0);
x(ffstr_eqcz(&cn.url, "http://127.0.0.1:64000")); //"weight" worked
conn->fin(cn.con, 0);
cn.con = NULL;
conn->getserv(t->conctx, &cn, 0);
x(ffstr_eqcz(&cn.url, "http://server3/some/path"));
conn->fin(cn.con, 0);
cn.con = NULL;
// iterate through servers
conn->getserv(t->conctx, &cn, 0);
x(ffstr_eqcz(&cn.url, "http://server1"));
conn->getserv(t->conctx, &cn, 0);
x(ffstr_eqcz(&cn.url, "http://127.0.0.1:64000"));
conn->getserv(t->conctx, &cn, 0);
x(ffstr_eqcz(&cn.url, "http://server3/some/path"));
x(FSV_CONN_ENOSERV == conn->getserv(t->conctx, &cn, 0));
x(cn.con == NULL);
}
int test_connect(tester *t)
{
const fsv_connect *conn = t->conn;
fsv_conn_new cn = {0};
if (t->conn == NULL) {
testm_runnext(t);
return 0;
}
FFTEST_FUNC;
test_round_robin_balancer(t);
//rotate to the 3rd server
conn->getserv(t->conctx, &cn, 0); //srv2 weight 1
conn->fin(cn.con, 0);
cn.con = NULL;
conn->getserv(t->conctx, &cn, 0); //srv2 weight 2
conn->fin(cn.con, 0);
cn.con = NULL;
// connect
cn.userptr = t;
conn->getserv(t->conctx, &cn, 0); //get www.google.com
t->conn_id = cn.con;
conn->connect(t->conn_id, 0);
return 0;
}
int testm_conf_connect(ffparser_schem *ps, tester *t, ffpars_ctx *a)
{
const ffstr *name = &ps->vals[0];
const fsv_modinfo *m = t->srv->findmod(name->ptr, name->len);
if (m == NULL)
return FFPARS_EBADVAL;
t->conn = m->f->iface("connect");
if (t->conn == NULL)
return FFPARS_EBADVAL;
t->conctx = t->conn->newctx(a, &test_conn_cb);
if (t->conctx == NULL)
return FFPARS_EBADVAL;
return 0;
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* parse.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: rretta <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2020/03/06 17:35:22 by erodd #+# #+# */
/* Updated: 2020/03/11 18:17:18 by rretta ### ########.fr */
/* */
/* ************************************************************************** */
#include "../includes/lem_in.h"
char **ft_file_parse(char **split)
{
char tmp[4097];
char *str;
char *str2;
int i;
str = "";
str2 = "";
ft_memset(tmp, '\0', 4096);
while ((read(STDIN_FILENO, tmp, 4096)) > 0)
{
tmp[4096] = '\0';
str2 = ft_strjoin(str, tmp);
if (*str != '\0')
free(str);
str = str2;
ft_memset(tmp, '\0', 4096);
}
if (ft_intstrstr(str2, "\n\n") == 1)
{
perror("ERROR: EMPTY LINE");
exit (EXIT_FAILURE);
}
split = ft_strsplit(str2, '\n');
ft_strdel(&str2);
return (split);
}
int ft_file_checker(char **split)
{
ft_val_ant(split[0]);
ft_putstr("start\n");
ft_val_bond(split);
ft_putstr("bond\n");
ft_val_room(split);
ft_putstr("val_room\n");
return(0);
}
int ft_val_ant(char *split)
{
int ant_num;
int i;
i = 0;
while (ft_isdigit(split[i]))
i++;
if (split[i])
{
perror("ERROR: INCORRECT INPUT OF ANTS\n");
exit (1);
}
ant_num = ft_atoi(split);
if (ant_num < 1 || ant_num > INT32_MAX)
{
perror("ERROR: INCORRECT QUANTITY OF ANTS\n");
exit (1);
}
ft_putnbr(ant_num);
ft_putchar('\n');
return (1);
}
int ft_val_bond(char **split)
{
int start;
int end;
start = 0;
end = 0;
while (*split != 0)
{
if (ft_strstr(*split, "##start\0") != 0)
start++;
if (ft_strstr(*split, "##end\0") != 0)
end++;
split++;
}
if (start == 1 && end == 1)
return (EXIT_SUCCESS);
else
{
perror("ERROR: THERE SHOULD BE ONLY ONE ENTERANCE AND EXIT");
exit (EXIT_FAILURE);
}
}
int ft_val_room(char **split)
{
char **str;
int i;
int room_num;
i = 1;
room_num = 0;
int j = 0;
ft_putstr("init\n");
while ((ft_word_counter(split[i], ' ') != 1 && ft_word_counter(split[i], '-') != 2) || split[i][0] == '#')
{
if ((ft_word_counter(split[i], ' ') == 3 || split[i][0] == '#') && split[i][0] != '\n')
{
if (split[i][0] == 'L')
{
perror("ERROR: SHITTY ROOM NAME");
exit (EXIT_FAILURE);
}
else if (split[i][0] == '#')
i++;
else
{
i++;
room_num++;
}
}
else
{
perror("ERROR: SHITTY ROOM INPUT");
exit (EXIT_FAILURE);
}
// ft_arrclr(str);
// i++;
}
ft_putnbr(room_num);
ft_putchar('\n');
ft_val_links(split, i); //TO MOVE TO FT_FILE_CHECKER FUNC (MAYBE)
return (room_num);
}
int ft_val_links(char **split, int i)
{
int links_num;
links_num = 0;
while (split[i])
{
if (ft_word_counter(split[i], ' ') == 1 && ft_word_counter(split[i], '-') == 2 )
{
links_num++;
i++;
}
else if (split[i][0] == '#')
i++;
else
{
perror("ERROR: SHITTY LINK INPUT");
exit (EXIT_FAILURE);
}
}
ft_putnbr(links_num);
ft_putchar('\n');
return (0);
}
// int ants_parse(t_lemin *lem)
// {
// char *line;
// get_next_line(0, &line);
// tmp = line;
// while (ft_isdigit(*tmp))
// tmp++;
// if (*tmp)
// {
// ft_putstr("ERROR: NEED MORE ANTS TO PROCEED\n");
// exit (1);
// }
// lem->ants = ft_atoi(line);
// free(line);
// // rooms_parse(lem);
// ft_putnbr(lem->ants);
// return (1);
// }
// int rooms_parse(t_lemin *lem)
// {
// char *line;
// char **tmp;
// while (get_next_line(0, &line))
// {
// tmp = ft_strsplit(line, ' ');
// if (tmp[1] != NULL || tmp[0][0] == '#' && tmp[0][1] == '#')
// {
// lem->rooms->name = tmp[0];
// }
// while ((tmp[2] = ft_strsplit(line, 32)) != 0)
// {
// ft_putstr(line);
// ft_putchar('\n');
// }
// }
// return (1);
// }
|
C
|
// Reading from a file
#include<stdio.h>
int main()
{
FILE *fptr;
int c, stock;
char buffer[200],item[10];
float price;
/* myfile.txt : Inventory \n 100
Widget 0.29 \n End of List */
fptr = fopen("myfile.txt","r");
fgets(buffer,20,fptr); /* read a line */
printf("%s\n",buffer);
fscanf(fptr,"%d %s %f",&stock,item,&price); /* read data */
printf("%d %s %4.2f \n",stock,item,price);
while((c = getc(fptr))!=EOF) /* read the rest of the file */
printf("%c",c);
fclose(fptr);
return 0;
}
|
C
|
#include<stdio.h>
#include<stdlib.h>
#define start 0
#define end 199
FILE *fout;
void display(int ar[25],int n){//function for calculating head movement
int i,cnt=0,t;
for(i=0;i<n-1;i++){
//printf("\t%d",order[i]);
t=ar[i]-ar[i+1];
cnt+=t<0?t*-1:t;
}
printf("Total head movement:%d\n\n",cnt);
fprintf(fout,"Total head movement:%d\n\n",cnt);
}
void swap(int *xp, int *yp)
{
int temp = *xp;
*xp = *yp;
*yp = temp;
}
// A function to implement bubble sort
void bubbleSort(int arr[], int n)
{
int i, j;
for (i = 0; i < n-1; i++)
// Last i elements are already in place
for (j = 0; j < n-i-1; j++)
if (arr[j] > arr[j+1])
swap(&arr[j], &arr[j+1]);
}
void printArray(int arr[], int size)
{
int i;
for (i=0; i < size; i++)
printf("%d ", arr[i]);
printf("\n");
}
void fcfs(int ar[20],int n,int head){//function for fcfs disc sheduling
int i,order[25];
order[0]=head;
for ( i=0; i < n; i++)
{
order[i+1]=ar[i];
}
printf("FCFS:\n");
fprintf(fout,"FCFS:\n");
display(order,n+1);
}
void scan(int ar[20],int n,int head){//function for scan disc sheduling
int i,order[25], dir,ord[25];
order[0]=head;
printf("Enter direction: 1.Larger 0.Smaller:");
scanf("%d",&dir);
for ( i=0; i < n; i++)
{
order[i+1]=ar[i];
}
order[++i]=start;
order[++i]=end;
n+=3;
bubbleSort(order,n);
int j=0,k;
if(dir){
for(i=0;i<n && 1;i++){
if(order[i]==head){
k=i;
ord[j]=order[i];j++;
}
else if(order[i]>head)
{
ord[j]=order[i];j++;
}
}
i=k-1;
while (i>0)
{
ord[j]=order[i];j++;
i--;
}
}else{
for(i=n-1;i>=0;i--){
if(order[i]==head){
k=i;
ord[j]=order[i];j++;
}
else if(order[i]<head)
{
ord[j]=order[i];j++;
}
}
i=k+1;
while (i<n-1)
{
ord[j]=order[i];j++;
i++;
}
}
//display(ord,n-1);
printArray(ord,n);
//printArray(order,n+3);
// printf("FCFS:\n");
// fprintf(fout,"FCFS:\n");
// display(order,n+1);
}
void cscan(int ar[20],int n,int head){//function for scan disc sheduling
int i,order[25], dir,ord[25];
order[0]=head;
printf("Enter direction: 1.Larger 0.Smaller:");
scanf("%d",&dir);
for ( i=0; i < n; i++)
{
order[i+1]=ar[i];
}
order[++i]=start;
order[++i]=end;
n+=3;
bubbleSort(order,n);
int j=0,k;
if(dir){
for(i=0;i<n && 1;i++){
if(order[i]==head){
k=i;
ord[j]=order[i];j++;
}
else if(order[i]>head)
{
ord[j]=order[i];j++;
}
}
i=0;
while (i<k)
{
ord[j]=order[i];j++;
i++;
}
}else{
for(i=n-1;i>=0;i--){
if(order[i]==head){
k=i;
ord[j]=order[i];j++;
}
else if(order[i]<head)
{
ord[j]=order[i];j++;
}
}
i=n-1;
while (i>k)
{
ord[j]=order[i];j++;
i--;
}
}
display(ord,n);
//printArray(ord,n);
//printArray(order,n+3);
// printf("FCFS:\n");
// fprintf(fout,"FCFS:\n");
// display(order,n+1);
}
void main(){
FILE *fptr;
int i=0,ar[20],a,head;
//opening input and output files
if ((fout = fopen("output.txt", "w")) == NULL) {
printf("Error! opening file");
exit(1);
}
if ((fptr = fopen("input.txt", "r")) == NULL) {
printf("Error! opening file");
exit(1);
}
printf("------------------------------------------\n");
fprintf(fout,"------------------------------------------\n");
fprintf(fout,"Input\n");
printf("Input\n");
if(!feof(fptr)){
fscanf(fptr,"%d",&head);//head pointer
fprintf(fout,"Current head position :%d\n",head);
printf("Current head position : %d\n",head);
}
printf("Sectors numbered from : %d to %d\n",start,end);
fprintf(fout,"Sectors numbered from : %d to %d\n",start,end);
printf("Requests are:");//inputing requests
fprintf(fout,"Requests are:");
i=0;
while (!feof(fptr)){
fscanf(fptr,"%d",&a);
ar[i]=a;
fprintf(fout,"\t%d",ar[i]);
printf("\t%d",ar[i]);i++;
}
printf("\n------------------------------------------\n");
fprintf(fout,"\n------------------------------------------\n");
fprintf(fout,"Output\n");//showing output
printf("Output\n");
// fcfs(ar,i,head);
cscan(ar,i,head);
printf("------------------------------------------\n");
fprintf(fout,"------------------------------------------\n");
}
|
C
|
/*Задача 5.
Дефинирайте и инициализирайте int променлива = 34 и
пойнтер към нея.
Опитайте да ги разместите, като поредност (първо да е
пойнтерът, после променливата).*/
#include <stdio.h>
int main(){
int *p;/*=&a не работи защото я декларираме след пойнтера*/
int a=34;
p=&a;
printf("%d value %d address\n",*p,p);
return 0;
}
|
C
|
#ifndef CHAR_STACK_H
#define CHAR_STACK_H
#include "minimax.h"
#define CAPACITY (3*(BOARD_SIZE))
struct CharStack {
char a[CAPACITY];
int head;
};
void
empty_stack(struct CharStack *s);
int
is_empty_stack(struct CharStack const *s);
void
push_stack(struct CharStack *s, char c);
char
peek_stack(struct CharStack const *s);
char
pop_stack(struct CharStack *s);
#endif //CHAR_STACK_H
|
C
|
/*
* Serial port setup
*/
#include <string.h>
#include "stm32f1xx_hal.h"
#include "stm32_hal_legacy.h"
#include "serial.h"
static USART_HandleTypeDef husart2;
static GPIO_InitTypeDef usart2_pins;
/* Private prototypes */
void init_usart2_pins(void);
void init_usart2_pins(void)
{
// Enable GPIOA Clock
__HAL_RCC_GPIOA_CLK_ENABLE();
//USART2_TX - PA2
usart2_pins.Pin = GPIO_PIN_2;
usart2_pins.Speed = GPIO_SPEED_FREQ_HIGH;
usart2_pins.Pull = GPIO_NOPULL;
usart2_pins.Mode = GPIO_MODE_AF_PP;
HAL_GPIO_Init(GPIOA , &usart2_pins);
//USART2_RX - PA3
usart2_pins.Pin = GPIO_PIN_3;
usart2_pins.Speed = GPIO_SPEED_FREQ_HIGH;
usart2_pins.Pull = GPIO_NOPULL;
usart2_pins.Mode = GPIO_MODE_INPUT;
HAL_GPIO_Init(GPIOA , &usart2_pins);
}
uint8_t USART2_Init(void)
{
init_usart2_pins();
// Enable USART2 clock (Rx and Tx pins)
__HAL_RCC_USART2_CLK_ENABLE();
husart2.Instance = USART2;
husart2.Init.BaudRate = BAUD_RATE;
husart2.Init.WordLength = USART_WORDLENGTH_8B;
husart2.Init.StopBits = USART_STOPBITS_1;
husart2.Init.Parity = USART_PARITY_NONE;
husart2.Init.Mode = USART_MODE_TX_RX;
uint8_t ret = HAL_USART_Init(&husart2);
return ret;
}
void transmit_USART2(char *msgBuffer)
{
uint16_t buf_size = strlen(msgBuffer);
HAL_USART_Transmit(&husart2, (uint8_t*)msgBuffer, buf_size, HAL_MAX_DELAY);
}
|
C
|
#include <netinet/in.h> /* sockaddr_in6 */
#include <stdlib.h> /* malloc() */
#include <string.h> /* memset() */
#include "message.h"
#include "server.h"
#define COAP_MSG_MIN_SIZE 4
/* RFC 7252 - Section 4.6 */
#define COAP_MSG_MAX_SIZE 1152
#define COAP_DEFAULT_PORT 5683
void
server_run ()
{
int sockfd;
struct sockaddr_in6 addr;
socklen_t addrlen;
struct message *msg;
int ret;
pthread_t thread_id;
sockfd = socket (AF_INET6, SOCK_DGRAM, 0);
if (sockfd == -1)
system_error ("socket");
memset (&addr, 0, sizeof (addr));
addr.sin6_family = AF_INET6;
addr.sin6_port = htons (COAP_DEFAULT_PORT);
addr.sin6_addr = in6addr_any;
if (bind (sockfd, (struct sockaddr *) &addr, sizeof (addr)) == -1)
system_error ("bind");
addrlen = sizeof(struct sockaddr_in6);
while (1)
{
msg = coap_message_new ();
/* Blocking until a new messsage is received */
msg->len = recvfrom (sockfd, msg->data, COAP_MSG_MAX_SIZE, 0,
(struct sockaddr *) &msg->src, &addrlen);
if (msg->len > 0)
{
if (msg->len < COAP_MSG_MIN_SIZE)
{
/* Should be at least 4-byte long */
warning ("message too short");
coap_message_free (msg);
}
else
{
/* Need to balance the cost of message pre-processing vs. the one of starting a new thread */
/* It should always take about the same time to parse the fixed-sized header whereas the whole message processing could vary greatly */
/* Validate the fixed-size header */
ret = coap_header_parse (msg);
if (ret < 0)
{
warning("invalid message header");
coap_message_free (msg);
}
/* Hand message over to a processsing thread */
thread_id = pthread_create (&thread_id, NULL,
&coap_message_process, (void *)msg);
}
}
else
system_error ("recvfrom");
}
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
#include "input_functions.h"
#include "meta_commands.h"
#include "virtual_machine.h"
#include "definitions/row_definition.h"
#include "definitions/table_definition.h"
int main(int argc, char* argv[])
{
Table* table = db_open(argc < 2 ? "defaultdb.db" : argv[1]);
InputBuffer* input_buffer = new_input_buffer();
while(true)
{
print_prompt();
read_input(input_buffer);
if (is_meta_command(input_buffer))
{
// `do_meta_command` may run the function `exit` if the input_buffer is ".exit"
switch(do_meta_command(input_buffer, table))
{
case (META_COMMAND_SUCCESS):
continue;
case (META_COMMAND_UNRECOGNIZED_COMMAND):
printf("Unrecognized command '%s'.\n", input_buffer->buffer);
continue;
}
}
Statement statement;
StatementResult statement_result = prepare_statement(input_buffer, &statement);
switch (statement_result.prepare_result)
{
case (PREPARE_SUCCESS):
break;
case (PREPARE_SYNTAX_ERROR):
if (statement_result.message != NULL) {
printf("%s", statement_result.message);
} else {
printf("Couldn't execute statement: '%s'.\n", input_buffer->buffer);
}
continue;
case (PREPARE_UNRECOGNIZED_STATEMENT):
printf("Unrecognized keyword at start of '%s'.\n", input_buffer->buffer);
continue;
}
switch (execute_statement(&statement, table))
{
case (EXECUTE_SUCCESS):
printf("Executed.\n");
break;
case (EXECUTE_DUPLICATE_KEY):
printf("Error: Duplicate key.\n");
break;
case (EXECUTE_TABLE_FULL):
printf("Error: Table full.\n");
break;
}
}
}
|
C
|
#include <stdio.h>
int main(int argc, char *argv[])
{
int i = 0;
int j = 0;
int n_check[10];
for (i=1; i<10; i++){
n_check[i] = 0;
}
for (i=1; i<argc; i++){
n_check[atoi(argv[i])]++;
}
for (i=1; i<10; i++){
if (n_check[i]>0){
printf("%d, ", i);
}
}
printf("\n");
return 0;
}
|
C
|
/*******************************************************************************
Algoritmos bsicos de manipulao de uma rvore de Adelson-Velskii Landis.
Os ns da rvore so decompostos e armazenam elementos do tipo TELEM.
*******************************************************************************/
#include <stdlib.h>
typedef struct noavl *PtNoAVL;
struct noavl
{
PtNoAVL PtEsq; /* ponteiro para o n esquerdo da rvore AVL */
PtNoAVL PtDir; /* ponteiro para o n direito da rvore AVL */
TELEM *PtEle; /* ponteiro para o elemento da rvore AVL */
unsigned int Altura; /* altura do n */
};
/******************************************************************************/
PtNoAVL CriarNoAVL (TELEM pelem) /* alocao do n decomposto */
{
PtNoAVL NoAVL;
...
return NoAVL;
}
/******************************************************************************/
void DestruirNoAVL (PtNoAVL *pptelem) /* libertao do n decomposto */
{
...
*pptelem = NULL; /* colocar o ponteiro a nulo */
}
/******************************************************************************/
unsigned int AlturaAVL (PtNoAVL praiz)
{
if (praiz == NULL) return 0;
else return praiz->Altura;
}
/******************************************************************************/
void RotacaoSimplesDireita (PtNoAVL *pno)
{
unsigned int AltEsq, AltDir;
PtNoAVL No = (*pno)->PtEsq;
(*pno)->PtEsq = No->PtDir; No->PtDir = *pno;
/* actualizar a altura dos ns envolvidos na rotao */
AltEsq = AlturaAVL ((*pno)->PtEsq);
AltDir = AlturaAVL ((*pno)->PtDir);
(*pno)->Alt = AltEsq > AltDir ? AltEsq + 1 : AltDir + 1;
AltEsq = AlturaAVL (No->PtEsq);
AltDir = (*pno)->Alt;
No->Alt = AltEsq > AltDir ? AltEsq + 1 : AltDir + 1;
*pno = No;
}
/******************************************************************************/
void RotacaoSimplesEsquerda (PtNoAVL *pno)
{
unsigned int AltEsq, AltDir;
PtNoAVL No = (*pno)->PtDir;
(*pno)->PtDir = No->PtEsq; No->PtEsq = *pno;
/* actualizar a altura dos ns envolvidos na rotao */
AltEsq = AlturaAVL ((*pno)->PtEsq);
AltDir = AlturaAVL ((*pno)->PtDir);
(*pno)->Alt = AltEsq > AltDir ? AltEsq + 1 : AltDir + 1;
AltEsq = (*pno)->Alt;
AltDir = AlturaAVL (No->PtDir);
No->Alt = AltEsq > AltDir ? AltEsq + 1 : AltDir + 1;
*pno = No;
}
/******************************************************************************/
void RotacaoDuplaDireitaEsquerda (PtNoAVL *pno)
{
RotacaoSimplesDireita (&(*pno)->PtDir);
RotacaoSimplesEsquerda (pno);
}
/******************************************************************************/
void RotacaoDuplaEsquerdaDireita (PtNoAVL *pno)
{
RotacaoSimplesEsquerda (&(*pno)->PtEsq);
RotacaoSimplesDireita (pno);
}
/******************************************************************************/
void EquilibrarAVL (PtNoAVL *praiz)
{
unsigned int AltEsq, AltDir;
if (*praiz == NULL) return;
/* clculo da altura das subrvores esquerda e direita */
AltEsq = AlturaAVL ((*praiz)->PtEsq);
AltDir = AlturaAVL ((*praiz)->PtDir);
if (AltEsq - AltDir == 2) /* subrvore esquerda desiquilibrada? */
{
AltEsq = AlturaAVL ((*praiz)->PtEsq->PtEsq);
AltDir = AlturaAVL ((*praiz)->PtEsq->PtDir);
if (AltEsq >= AltDir) RotacaoSimplesDireita (praiz);
else RotacaoDuplaEsquerdaDireita (praiz);
}
else if (AltDir - AltEsq == 2) /* subrvore direita desiquilibrada? */
{
AltDir = AlturaAVL ((*praiz)->PtDir->PtDir);
AltEsq = AlturaAVL ((*praiz)->PtDir->PtEsq);
if (AltDir >= AltEsq) RotacaoSimplesEsquerda (praiz);
else RotacaoDuplaDireitaEsquerda (praiz);
}
else (*praiz)->Alt = AltEsq > AltDir ? AltEsq + 1 : AltDir + 1;
/* actualizar a altura do n */
}
/******************************************************************************/
void InserirElementoNaAVL (PtNoAVL *praiz, TELEM pelem)
{
if (*praiz == NULL)
{ /* inserir o elemento - criao do elemento com altura 1 */
if ((*praiz = CriarNoAVL (pelem)) == NULL) return;
}
else if (*(*praiz)->PtEle > pelem) /* inserir na subrvore esquerda */
InserirElementoNaAVL (&(*praiz)->PtEsq, pelem);
else if (*(*praiz)->PtEle < pelem) /* inserir na subrvore direita */
InserirElementoNaAVL (&(*praiz)->PtDir, pelem);
else return; /* o elemento j existe */
EquilibrarAVL (praiz); /* reequilibrar a rvore */
}
/******************************************************************************/
void RemoverElementoDaAVL (PtNoAVL *praiz, TELEM *pelem)
{
/* a rvore est vazia ou o elemento no existe */
if (*praiz == NULL) return;
if (*(*praiz)->PtEle > *pelem)
RemoverElementoDaAVL (&(*praiz)->PtEsq, pelem);
else if (*(*praiz)->PtEle < *pelem)
RemoverElementoDaAVL (&(*praiz)->PtDir, pelem);
else
{
*pelem = *(*praiz)->PtEle; /* copiar o elemento */
RemoverNoAVL (praiz); /* eliminar o elemento */
}
EquilibrarAVL (praiz); /* reequilibrar a rvore */
}
void RemoverNoAVL (PtNoAVL *praiz)
{
PtNoAVL NoTmp = *praiz;
if ((*praiz)->PtEsq == NULL && (*praiz)->PtDir == NULL)
DestruirNoAVL (praiz); /* n folha - eliminar o elemento */
else if ((*praiz)->PtEsq == NULL) /* com subrvore direita */
{
*praiz = (*praiz)->PtDir; /* ligar direita */
DestruirNoAVL (&NoTmp); /* eliminar o elemento */
}
else if ((*praiz)->PtDir == NULL) /* com subrvore esquerda */
{
*praiz = (*praiz)->PtEsq; /* ligar esquerda */
DestruirNoAVL (&NoTmp); /* eliminar o elemento */
}
else SubstituirNoMinAVL (&(*praiz)->PtDir, (*praiz)->PtEle);
/* com subrvores direita e esquerda, substituir pelo menor elemento da subrvore direita */
}
void SubstituirNoMinAVL (PtNoAVL *praiz, TELEM *pelem)
{
PtNoAVL NoTmp = *praiz;
if ((*praiz)->PtEsq == NULL)
{
*pelem = *(*praiz)->PtEle; /* copiar o elemento */
*praiz = (*praiz)->PtDir; /* ajustar a subrvore direita */
DestruirNoAVL (&NoTmp); /* eliminar o elemento */
}
else SubstituirNoMinAVL (&(*praiz)->PtEsq, pelem);
EquilibrarAVL (praiz); /* reequilibrar a rvore */
}
/******************************************************************************/
|
C
|
/*$$$ SUBPROGRAM DOCUMENTATION BLOCK
C
C SUBPROGRAM: NUMMTB
C PRGMMR: ATOR ORG: NP12 DATE: 2009-03-23
C
C ABSTRACT: THIS ROUTINE SEARCHES FOR AN ENTRY CORRESPONDING TO IDN
C IN THE BUFR MASTER TABLE (EITHER 'B' OR 'D', DEPENDING ON THE VALUE
C OF IDN). THE SEARCH USES BINARY SEARCH LOGIC, SO ALL OF THE ENTRIES
C IN THE TABLE MUST BE SORTED IN ASCENDING ORDER (BY FXY NUMBER) IN
C ORDER FOR THIS ROUTINE TO WORK PROPERLY.
C
C PROGRAM HISTORY LOG:
C 2009-03-23 J. ATOR -- ORIGINAL AUTHOR
C
C USAGE: CALL NUMMTB( IDN, TAB, IPT )
C INPUT ARGUMENT LIST:
C IDN - INTEGER: BIT-WISE REPRESENTATION OF FXY VALUE TO BE
C SEARCHED FOR
C
C OUTPUT ARGUMENT LIST:
C TAB - CHARACTER: TABLE IN WHICH IDN WAS FOUND ('B' OR 'D')
C IPT - INTEGER: INDEX OF ENTRY FOR IDN IN MASTER TABLE TAB
C
C REMARKS:
C THIS ROUTINE CALLS: BORT CADN30 CMPIA
C THIS ROUTINE IS CALLED BY: STSEQ
C Normally not called by any application
C programs.
C
C ATTRIBUTES:
C LANGUAGE: C
C MACHINE: PORTABLE TO ALL PLATFORMS
C
C$$$*/
#include "bufrlib.h"
#include "mstabs.h"
void nummtb( f77int *idn, char *tab, f77int *ipt )
{
f77int *pifxyn, *pbs, nmt;
char adn[7], errstr[129];
if ( *idn >= ifxy( "300000", 6 ) ) {
*tab = 'D';
pifxyn = &MSTABS_BASE(idfxyn)[0];
nmt = MSTABS_BASE(nmtd);
}
else {
*tab = 'B';
pifxyn = &MSTABS_BASE(ibfxyn)[0];
nmt = MSTABS_BASE(nmtb);
}
pbs = ( f77int * ) bsearch( idn, pifxyn, ( size_t ) nmt, sizeof( f77int ),
( int (*) ( const void *, const void * ) ) cmpia );
if ( pbs == NULL ) {
cadn30( idn, adn, sizeof( adn ) );
adn[6] = '\0';
sprintf( errstr, "BUFRLIB: NUMMTB - COULD NOT FIND DESCRIPTOR "
"%s IN MASTER TABLE %c", adn, *tab );
bort( errstr, ( f77int ) strlen( errstr ) );
}
*ipt = pbs - pifxyn;
return;
}
|
C
|
/*
this source code is for returing the days of given month
*/
#include <stdio.h>
int month_day[] = {0, 31, 28, 31, 30, 31 ,30, 31, 31, 30, 31, 30, 31};
// 0 1 2 3 4 5 6 7 8 9 0 1 2
int isLeapYear(int year)
{
return year % 4 == 0 && year % 100 != 0 || year % 400 == 0;
}
int getdays(int year, int month)
{
if(month == 2 && isLeapYear(year))
return month_day[month] + 1;
return month_day[month];
}
int main()
{
int year, month;
printf("please input the year and the month:(use blank)\n");
scanf("%d %d", &year, &month);
printf("days:%d", getdays(year, month));
return 0;
}
|
C
|
// p_2.c
#include <stdio.h>
void hoge(int i) {
printf("%p\n", &i);
}
int main() {
int i = 100;
printf("%p\n", &i);
hoge(i);
return 0;
}
|
C
|
#include <assert.h>
int solution(int number) {
int total = 0;
for(int i=3; i<number; i = i+3) {
total += i;
}
for(int i=5; i<number; i = i+5) {
if (i % 3 != 0)
total += i;
}
return total;
}
// Test Code
int main (int argc, char *argv[]) {
assert(solution(10) == 23);
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
int add(int x, int y);
int sub(int x, int y);
int main() {
int a = 10;
int b = 20;
// Calculate sum
int sum = add(a, b);
printf("The sum of %d and %d is %d.\n", a, b, sum);
// Calculate difference
printf("The difference of %d and %d is %d.\n", a, b, sub(a,b));
return EXIT_SUCCESS;
}
int add(int x, int y) {
int result = x + y;
return result;
}
int sub(int x, int y) {
int result = x - y;
return result;
}
|
C
|
#include<stdio.h>
int main()
{
int dn,kn,i,j,m;
printf("enter the no of bits in message");
scanf("%d",&dn);
char data[dn+1];
printf("enter the data");
scanf("%s",&data);
printf("enter no of bits in key");
scanf("%d",&kn);
printf("enter the key");
char key[kn+1];
scanf("%s",&key);
char data1[dn+kn-1];
for(i=0;i<dn;i++)
data1[i]=data[i];
for(j=1;j<kn;j++)
{
data1[i]='0';
i++;
}
for(i=0;i<dn;i++)
{
if(data1[i]=='0')
continue;
else
{
for(j=1;j<kn;j++)
{
if(data1[i+j]!=key[j])
data1[i+j]='1';
else
data1[i+j]='0';
}
}
}
printf("crc is \n");
/*for(i=0;i<dn;i++)
printf("%c",data[i]);*/
for(i=dn;i<dn+kn-1;i++)
printf("%c",data1[i]);
return 0;
}
|
C
|
#include<stdio.h>
#include<con
#include<process.h>
#define size 8
int main()
{
int arr[size],r=-1,f=0,nc=0,c,x,p;
for(;;)
{
system("cls");
printf("1. Insert Rear\n");
printf("2. Delete Front\n");
printf("3. Display\n");
printf("4. Exit\n");
printf("Enter Choice : ");
scanf("%d",&c);
switch(c)
{
case 1:
if(nc==size)
{
printf("queue is full");
getch();
}
else
{
r=(r+1)%size;
printf("enter no ");
scanf("%d",&arr[r]);
nc=nc+1;
}
break;
case 2:
if(nc==0)
{
printf("queue is empty");
getch();
}
else
{
printf("deleted no=%d",arr[f]);
f=(f+1)%size;
nc=nc-1;
getch();
}
break;
case 3:
if(nc==0)
{
printf("queue is empty cannot display");
getch();
}
else
{
p=f;
for(x=1;x<=nc;x++)
{
printf("%d ",arr[p]);
p=(p+1)%size;
}
getch();
}
break;
case 4:
exit(0);
default:
printf("wrong choice");
getch();
}
}
}
|
C
|
// ksr.c, 159
//need to include spede.h, const-type.h, ext-data.h, tools.h
#include "spede.h"
#include "const-type.h"
#include "ext-data.h"
#include "tools.h"
#include "ksr.h"
#include "proc.h"
// to create a process: alloc PID, PCB, and process stack
// build trapframe, initialize PCB, record PID to ready_que
void SpawnSR(func_p_t p) { // arg: where process code starts
int pid;
/*use a tool function to check if available queue is empty:
a. cons_printf("Panic: out of PID!\n");
b. and go into GDB*/
if(QueEmpty(&avail_que))
{
cons_printf("Panic: out of PID!\n");
breakpoint(); //Calling breakpoint(); to enter GDB
}
//get 'pid' initialized by dequeuing the available queue
pid = DeQue(&avail_que); //Fill this function with the available que
//use a tool function to clear the content of PCB of process 'pid'
Bzero((char *) &pcb[pid], sizeof(pcb_t));
//set the state of the process 'pid' to READY
pcb[pid].state = READY;
//if 'pid' is not IDLE, use a tool function to enqueue it to the ready queue
if(pid != IDLE)
{
EnQue(pid, &ready_que);
}
//use a tool function to copy from 'p' to DRAM_START, for STACK_MAX bytes
MemCpy((char *) DRAM_START, (char *) p, STACK_MAX);
/*create trapframe for process 'pid:'
1st position trapframe pointer in its PCB to the end of the stack*/
pcb[pid].tf_p = (tf_t *)(DRAM_START + STACK_MAX - sizeof(tf_t));
pcb[pid].tf_p->efl = EF_DEFAULT_VALUE | EF_INTR; //set efl in trapframe to EF_DEFAULT_VALUE|EF_INTR // handle intr
pcb[pid].tf_p->cs = get_cs(); //set cs in trapframe to return of calling get_cs() // duplicate from CPU
pcb[pid].tf_p->eip = DRAM_START; //set eip in trapframe to DRAM_START // where code copied
}
// count run time and switch if hitting time limit
void TimerSR(void)
{
outportb(PIC_CONT_REG, TIMER_SERVED_VAL); //1st notify PIC control register that timer event is now served
sys_time_count++; //increment system time count by 1
pcb[run_pid].time_count++; //increment the time count of the process currently running by 1
pcb[run_pid].total_time++; //increment the life span count of the process currently running by 1
/*if the time count of the process is reaching maximum allowed runtime
move the process back to the ready queue
alter its state to indicate it is not running but ...
reset the PID of the process in run to NONE*/
if(pcb[run_pid].time_count == TIME_MAX)
{
EnQue(run_pid, &ready_que);
pcb[run_pid].state = READY;
run_pid = NONE;
}
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_printf.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: gtresa <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2020/12/19 13:33:04 by gtresa #+# #+# */
/* Updated: 2020/12/25 12:03:03 by gtresa ### ########.fr */
/* */
/* ************************************************************************** */
#include "libftprintf.h"
t_prf *init_struct(void)
{
t_prf *prf;
prf = (t_prf*)malloc(sizeof(t_prf));
if (prf != NULL)
{
prf->flag = 2;
prf->width = 0;
prf->prec = -1;
prf->type = 0;
prf->len = 0;
prf->pref = 0;
}
return (prf);
}
static void start_struct(t_prf *prf, char *format)
{
prf->flag = 2;
prf->width = 0;
prf->prec = -1;
prf->type = 0;
prf->pref = 0;
output_start(&(*format), prf);
}
static int free_data(char *format, t_prf *prf)
{
int res;
res = prf->len;
if (format != NULL)
free(format);
if (prf != NULL)
{
res = prf->len;
free(prf);
}
return (res);
}
int ft_printf(const char *str, ...)
{
va_list ap;
t_prf *prf;
char *format;
if ((prf = init_struct()) == NULL)
return (-1);
format = ft_strdup(str);
va_start(ap, str);
while (format)
{
start_struct(prf, &(*format));
if (check_format(&(*format), prf, ap) == -1)
return (free_data(format, prf));
if (prf->type == 99 || prf->type == 115 || prf->type == 37)
output_str(prf, ap);
if (prf->type == 100 || prf->type == 105 || prf->type == 117)
output_nbr(prf, ap);
if (prf->type == 120 || prf->type == 88 || prf->type == 112)
output_hex(prf, ap);
}
write(1, &"\0", 1);
va_end(ap);
return (free_data(format, prf));
}
|
C
|
#include <inttypes.h>
#include <stdbool.h>
/*
* USAGE:
* char ipadddress_buffer[PREFIX_LENGTH]; // (16)
* memset(ip_address_buffer, 0, PREFIX_LENGTH);
* char *ip_address = "192.168.2.10";
* char mask = 20;
* get_broadcast_address(ip_address, mask, ip_address_buffer);
* printf("Broadcast address = %s\n", ip_address_buffer);
* EX: 192.168.1.1, 24 -> 192.168.1.255
* EX: 10.1.23.10, 20 -> 10.1.31.255
*/
void get_broadcast_address(const char *ip_address, uint8_t mask, char *output_buffer);
/*
* USAGE:
* char *ip_address = "192.168.2.10";
* unsigned int integer_ip = get_ip_integer_equivalent(ip_address);
* printf("Integer equivalent for %s is %u\n", ip_address, integer_ip);
* EX: 192.168.2.10 -> 3_232_236_042
* EX: 10.1.23.10 -> 167_843_594
*/
uint_fast32_t get_ip_integer_equivalent(const char *ip_address);
/*
* USAGE:
* unsigned int int_ip = 2058138165;
* char ip_address_buffer[PREFIX_LENGTH];
* memset(ip_address_buffer, 0, PREFIX_LENGTH);
* get_dot_ip_format(int_ip, ip_address_buffer);
* printf("IP address in A.B.C.D format is %s\n", ip_address_buffer);
* EX: 2058138165 -> 122.172.178.53
*/
void get_dot_ip_format(const uint_fast32_t ip_address, char *output_buffer);
/*
* USAGE:
* char network_id_buffer[PREFIX_LENGTH];
* memset(ip_address_buffer, 0, PREFIX_LENGTH);
* char *ip_address = "192.168.2.10";
* uint8_t mask = 20;
* get_network_id(ip_address, mask, network_id_buffer);
* printf("Network id is %s\n");
* EX: 192.168.1.1 24 -> 129.168.0.0
* EX: 10.1.23.10 20 -> 10.1.16.0
*/
void get_network_id(const char *ip_address, const uint8_t mask, char *output_buffer);
/*
* USAGE:
* unsigned char mask = 24;
* printf("Subnet cardinality for mask = %u is %u\n", mask, get_subnet_cardinality(mask));
* EX: 24 -> 254
* EX: 30 -> 2
*/
uint_fast32_t get_subnet_cardinality(const uint8_t mask);
/*
* USAGE:
* char *network_id = "192.168.0.0";
* char mask = 24;
* char *check_ip = "192.168.0.13"
* bool is_in_subnet = is_ip_in_subnet(network_id, mask, check_ip);
* char* conditional = (is_in_subnet) ? "" : " not";
* printf("IP address %s is%s a member of subnet %s/%u\n", check_ip, conditional, network_id, mask);
* EX: 192.168.0.0 24 192.168.0.13 -> true
* EX: 192.168.0.0 24 192.169.0.13 -> false
*/
bool is_ip_in_subnet(const char *network_id, const uint8_t mask, const char* ip_address);
|
C
|
#include "included.h"
#include "stdio.h"
int plusOne(int x)
{
return factorial(x + 1) + 1;
}
int main()
{
int c;
scanf("%d", &c);
printf("%d", plusOne(c));
return 0;
}
|
C
|
//
// keygen.c
// Description: Creates a one-time pad keyfile of specific length, determined by user input
// Characters used as key include the 26 English alphabet, and the space character.
// Created by Brian Sia on 8/4/16.
//
//
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
//main()
//intializes random seed, checks for valid user input, and then generate the ASCII to integer conversion
//for the key. then add trailing newspace to end the file.
//Preconditions: length of key supplied as an argument
//Postconditions: generates a one-time pad key made up of the 26 English alphabet and the space character
int main(int argc, char **argv){
//random num gen seed
srand(time(NULL));
if(argc !=2){
fprintf(stderr, "Usage: %s keylength", argv[0]);
exit(1);
}
int randChar, index, keylength = atoi(argv[1]);
//A to Z lies between decimal 65-90 in ASCII. 91 corresponds to [ character
//which will be converted to the space character if encountered
for(index = 0; index < keylength; index++){
randChar = rand()%27 + 'A';
if (randChar == 26 + 'A')// '[' character encounted
{
randChar = 32; //ASCII for space
}
fprintf(stdout, "%c", randChar);
}
//newline ending the keygen file
fprintf(stdout, "\n");
return 0;
}
|
C
|
#include "stm32l4xx.h" // Device header
int period;
float freq;
int main(void)
{
int last_value =0;
int current_value=0;
RCC->AHB2ENR |=1;
GPIOA->MODER &=~0xc00;
GPIOA->MODER |=0x800;
GPIOA->AFR[0] |=0x00100000;
//configuring TIM2
RCC->APB1ENR1 |=1;
TIM2->PSC = 1600-1;
TIM2->ARR = 10000;
TIM2->CCMR1 =0x30; //set output toggle on match
TIM2->CCR1 =0; //set match mode
TIM2->CCER |=1; //Enable channel1 compare mode
TIM2->CNT =0; //clear counter
TIM2->CR1 =1; //Enable TIM2
//config PA6
RCC->AHB2ENR |=1; //Enabling clock for PA6
GPIOA->MODER &=~0x3000;
GPIOA->MODER |=0x2000; //setting PA6 mode to AF
GPIOA->AFR[0] |=0x2000000; //Setting PA6 to AF2 which is TIM3 CH 1
//config TIM3
RCC->APB1ENR1 |=2; //Enable clock for TIM3
TIM3->PSC = 16000-1;
TIM3->CCMR1 =0x41; //set channel 1 to capture at every edge at frequency dts/2
TIM3->CCER |=0x0B; //Enable capture mode and capture at both edges
TIM3->CR1 =1; //Enable TIM3
while(1){
while(!(TIM3->SR &2)){} //Status register bit1 set when input captured
current_value = TIM3->CCR1;
period = current_value-last_value; //time period calculation
last_value = current_value;
freq = 1000.0f/period ; //frequency calculation
}
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// Includes for process control
#include <unistd.h>
#include <signal.h>
#include <sys/wait.h>
#include <sys/types.h>
// Add custom linked list library
#include "linkedList.h"
// User input constants
#define MAX_INPUT_SIZE 9999
void manageProcessStatus(pid_t pid, node** list, char* signal){
if(findElement(list, pid, 0))
{
int retValue = 0;
// Check what signal should be sent to existing process
if(strncmp(signal, "TERM", 4) == 0)
{
retValue = kill(pid, SIGTERM);
}
else if(strncmp(signal, "STOP", 4) == 0)
{
retValue = kill(pid, SIGSTOP);
}
else if (strncmp(signal, "CONT", 4) == 0)
{
retValue = kill(pid, SIGCONT);
}
else
{
printf("Error: Invalid signal.\n");
return;
}
if(retValue == -1)
{
printf("Error: kill() failed.\n");
}
}
else
{
printf("Error: Process %d does not exist.\n", pid);
}
}
void createProcess(node** list, char** parameters){
pid_t pid;
pid = fork();
if(pid == 0)
{
// Execute program in child process
if (execvp(parameters[0], parameters) < 0)
{
// On failure terminate
printf("Error: execvp failed.\n");
exit(-1);
}
}
else if(pid > 0)
{
// Track process
addTaskToTheList(list, createNode(pid, parameters[0]));
}
else
{
printf("Error: Fork failed.\n");
}
}
void pstat(pid_t pid, node* list){
node* searchResult = findElement(&list, pid, 0);
if(searchResult)
{
// Variables used for file processing
char line[MAX_INPUT_SIZE];
char* data[MAX_INPUT_SIZE];
char path[1024];
// Open /proc/[pid]/stat
sprintf (path, "/proc/%d/stat", pid);
FILE *fptr = fopen(path,"r");
if (fptr == NULL)
{
printf("Error: Failed to open file %s.\n", path);
}
else
{
fgets(line, MAX_INPUT_SIZE, fptr);
// Parse the line by spaces and save it to be accessed later
int index = 0;
char* token;
token = strtok(line, " ");
while (token != NULL)
{
data[index] = token;
token = strtok(NULL, " ");
index++;
}
// Print the needed file contents
printf("comm: %s\n", data[1]);
printf("state: %s\n", data[2]);
// Divide usage cycles by system clock to obtain time
char *ptr;
printf("utime: %f\n", (float)strtoul(data[13], &ptr, 10)/(float)sysconf(_SC_CLK_TCK));
printf("stime: %f\n", (float)strtoul(data[14], &ptr, 10)/(float)sysconf(_SC_CLK_TCK));
printf("rss: %s\n", data[23]);
fclose(fptr);
}
// Open /proc/[pid]/status
sprintf(path, "/proc/%d/status", pid);
fptr = fopen(path,"r");
if (fptr == NULL)
{
printf("\nError: Failed to open file %s.\nPMan: > ", path);
}
else
{
// Data is seperated by a newline character
// Iterate through data and print last two items for context switch information
int index = 0;
while (fgets(line, MAX_INPUT_SIZE, fptr) != NULL)
{
index++;
if(index == 54)
{
printf("%s", line);
}
}
printf("%s", line);
fclose(fptr);
}
}
else
{
printf("Error: Process %d does not exist.\n", pid);
}
}
void checkZombieProcess(node** list){
int status;
while (1)
{
// No processes to check
if(list == NULL)
{
return;
}
// Allow process status to change prior to checking status
usleep(1500);
// Wait for any child process whose process group ID is equal to the absolute value of pid
// Options used:
// WCONTINUED: return if a stopped child has been resumed by delivery of SIGCONT
// WNOHANG: return immediately if no child has exited.
// WUNTRACED: return if a child has stopped
pid_t retPid = waitpid(-1, &status, WCONTINUED | WNOHANG | WUNTRACED);
if (retPid > 0)
{
// Find the pid node and update it's status or remove it from the list
node* searchResult = findElement(list, retPid, 0);
if (WIFSTOPPED(status) && searchResult != NULL)
{
printf("Process %d was stopped.\n", retPid);
searchResult->active = 0;
}
else if (WIFCONTINUED(status) && searchResult != NULL)
{
printf("Process %d was started.\n", retPid);
searchResult->active = 1;
}
else if (WIFSIGNALED(status))
{
printf("Process %d was killed.\n", retPid);
findElement(list, retPid, 1);
}
else if (WIFEXITED(status))
{
printf("Process %d terminated.\n", retPid);
findElement(list, retPid, 1);
}
}
else
{
break;
}
}
}
int main(){
// Storage variables
node* listHead = NULL;
char* userInput = auto_malloc(MAX_INPUT_SIZE);
char command[8];
// Variables used during parsing
pid_t pid;
char *token;
// User input flags used to process commands
int twoArgumentsProvided = 0;
int validPid = 0;
while(1){
// Reset storage variables
memset(userInput, '\0', MAX_INPUT_SIZE);
memset(command, '\0', 8);
// Reset flags
twoArgumentsProvided = 0;
validPid = 0;
// Prompt user for input
printf("PMan: > ");
// Read users input
// Ignores newline character, tabs, and space
// Returns once a newline character is encountered
while(scanf(" %[^\n\t]", userInput) == 0);
checkZombieProcess(&listHead);
// Copy input so original input exists untokenized
token = strtok(userInput, " ");
// Acceptable commands only have a length of 7 so no need to copy more characters
strncpy(command, token, 7);
// Parse the remianing parameters
char* parameters[MAX_INPUT_SIZE];
// Used to indicate the number of parameters
parameters[0] = NULL;
parameters[1] = NULL;
int index = 0;
while(token != NULL)
{
token = strtok(NULL, " ");
parameters[index] = token;
index++;
}
// Check if second argument could be possibly a pid
if(parameters[1] == NULL && parameters[0] != NULL)
{
pid = atoi(parameters[0]);
// Check validity of pid
// Max pid found using
// cat /proc/sys/kernel/pid_max
// Max pid is 32768
if( 0 < pid && pid <= 4194304)
{
validPid = 1;
}
// Set flag to indicate a parameter was entered
twoArgumentsProvided = 1;
}
// Compare the input to acceptable commands
if(strncmp(command, "bg", 8) == 0 && parameters[0] != NULL)
{
createProcess(&listHead, parameters);
}
else if(strncmp(command, "bglist", 8) == 0)
{
if(parameters[0] != NULL){
printf("PMan: > %s: too many arguments\n", command);
continue;
}
printList(listHead);
}
else if(strncmp(command, "bgkill", 8) == 0 && twoArgumentsProvided && validPid)
{
manageProcessStatus(pid, &listHead, "TERM");
}
else if(strncmp(command, "bgstop", 8) == 0 && twoArgumentsProvided && validPid)
{
manageProcessStatus(pid, &listHead, "STOP");
}
else if(strncmp(command, "bgstart", 8) == 0 && twoArgumentsProvided && validPid)
{
manageProcessStatus(pid, &listHead, "CONT");
}
else if(strncmp(command, "pstat", 8) == 0 && twoArgumentsProvided && validPid)
{
pstat(pid, listHead);
}
else if(strncmp(command, "bg" , 8) == 0 ||
strncmp(command, "bgkill" , 8) == 0 ||
strncmp(command, "bgstop" , 8) == 0 ||
strncmp(command, "bgstart" , 8) == 0 ||
strncmp(command, "pstat" , 8) == 0)
{
// Correct command but command was used incorrectly, alert the user
if(!twoArgumentsProvided)
{
printf("PMan: > %s: too few or too many arguments\n", command);
}
else if(!validPid)
{
printf("PMan: > %d: invalid pid, pid must be greater than 0 and less than 4194305\n", pid);
}
}
else
{
printf("PMan: > %s: command not found\n", userInput);
}
checkZombieProcess(&listHead);
}
freeList(listHead);
free(userInput);
}
|
C
|
#include<stdio.h>
#include<stdlib.h>
void ex1_3()
{
short sum, s = 32767;
sum = s + 1;
printf("s+1=%d\n", sum);
sum = s + 2;
printf("s+2=%d\n", sum);
}
|
C
|
#include <stdio.h>
int main(int argc, char* argv[]) {
FILE* f = NULL;
f = fopen("Exo5.c", "r"); /* On ouvre le fichier source du code */
int c = 0;
if (f!=NULL) { /* Si le fichier est trouvé */
c = fgetc(f); /* On récupère les caractères un par un */
while (c!=EOF) { /* Tant qu'on ne tombe pas sur la fin du fichier, on continue de le lire */
printf("%c", c); /* On affiche caractère par caractère */
c = fgetc(f);
}
} else {
printf("Erreur : Impossible de trouver le code source !\n");
}
fclose(f);
return 0;
}
|
C
|
/*
* licence kaneton licence
*
* project kaneton
*
* file /home/buckman/kaneton/libs/libia32/task/tss.c
*
* created renaud voltz [mon apr 10 01:01:34 2006]
* updated matthieu bucchianeri [sun sep 10 12:57:09 2006]
*/
/*
* ---------- information -----------------------------------------------------
*
* an event handler is always executed in kernel land.
* also when an event occurs in user land, the ia32 architecture automaticaly
* performs a task switch, replacing the cpl3-stack by the cpl0-stack of the
* thread. information needed to perform this task switch are contained into
* the current TSS whose descriptor is pointed by the TR register.
* thus, whatever the design chosen for the context switch implementation, ia32
* architecture always needs at least one TSS.
*/
/*
* ---------- includes --------------------------------------------------------
*/
#include <kaneton.h>
#include <architecture/architecture.h>
/*
* ---------- functions -------------------------------------------------------
*/
/*
* update the given tss.
*/
t_status ia32_tss_load(t_ia32_tss* tss,
t_uint16 ss,
t_uint32 esp,
t_uint32 io)
{
assert(tss != NULL);
tss->ss0 = ss;
tss->esp0 = esp;
tss->io = io;
tss->io_end = 0xFF;
return STATUS_OK;
}
/*
* set the given tss as current.
*
* steps:
*
* 1) fill the tss descriptor and add it into the gdt.
* 2) get the segment selector for this descriptor.
* 3) load the task register with this segment selector.
*/
t_status ia32_tss_init(t_ia32_tss* tss)
{
t_uint16 segment;
t_uint16 selector;
t_ia32_segment descriptor;
assert(tss != NULL);
/*
* 1)
*/
descriptor.base = (t_uint32)tss;
descriptor.limit = sizeof (t_ia32_tss);
descriptor.privilege = IA32_PRIV_RING0;
descriptor.is_system = 1;
descriptor.type.sys = IA32_SEG_TYPE_TSS;
if (ia32_gdt_reserve_segment(IA32_GDT_CURRENT, descriptor,
&segment) != STATUS_OK)
return STATUS_UNKNOWN_ERROR;
/*
* 2)
*/
if (ia32_gdt_build_selector(segment, descriptor.privilege, &selector)
!= STATUS_OK)
return STATUS_UNKNOWN_ERROR;
/*
* 3)
*/
LTR(selector);
return STATUS_OK;
}
|
C
|
/*
创建一个函数,对元素个数为n的int型数组v进行倒序排列。
void rev_intary{int v[],int n)
*/
#include <stdio.h>
void diaohuan(int a,int b){
int c = 0;
c = a;
a = b;
b = c;
}
void rev_intary(int v[],int n){
int c = 0;
// for(int i=0;i<n;i++){
// // diaohuan(v[i],v[n-(i+1)]);
// // c = v[i];
// // v[i] = v[n-(i+1)];
// // v[n-(i+1)] = c;
// // printf("%d",v[i]);
// // printf("%d",v[n-(i+1)]);
// // printf(" %d",v[i]);
// }
putchar('{');
for(int i=0;i<n;i++){
printf(" %d",v[n-(i+1)]);
}
putchar('}');
}
int main(){
int shu[10] = {1,2,3,4,5,6,7,8,9,10};
printf("元素为10的数组倒序输出为:");
rev_intary(shu,10);
}
|
C
|
#include <stdio.h>
#include <math.h>
int main()
{
double a, b, c, discriminant, root1, root2, realPart, imaginaryPart;
scanf("%lf %lf %lf",&a, &b, &c);
discriminant = b*b-4*a*c;
// condition for real and different roots
if (discriminant > 0)
{
// sqrt() function returns square root
root1 = (-b+sqrt(discriminant))/(2*a);
root2 = (-b-sqrt(discriminant))/(2*a);
if(root1<root2)
printf("%lf %lf\n",root1 , root2);
else printf("%lf %lf\n", root2, root1);
}
//condition for real and equal roots
else if (discriminant == 0)
{
root1 = root2 = -b/(2*a);
if(root1<root2)
printf("%lf %lf\n",root1 , root2);
else printf("%lf %lf\n", root2, root1);
}
// if roots are not real
else
{
root1 = -b/(2*a);
root2 = sqrt(-discriminant)/(2*a);
if(root1<root2)
printf("%lf %2lf\n",root1 , root2);
else printf("%lf %lf\n", root2, root1);
}
return 0;
}
|
C
|
#include "stdio.h"
#include "stdlib.h"
#include "math.h"
#define RAND 200
#define POINTS 200
#define TRUE 1
#define FALSE 0
#define TOP 1
#define BOTTOM -1
#define IGNORE 0
// data structures
typedef struct Point
{
int x;
int y;
} Point;
// signatures
Point newPoint(int x, int y);
void printPoint(Point pt);
int pointEquals(Point p1, Point p2);
void printPointArray(Point* ptArray, int len);
Point* getPointArray(int* lenPtr);
Point* getStaticPointArray(int* lenPtr);
Point* copyPointArray(Point* ptArray, int len);
void removeIndexFromPointArray(Point* ptArray, int* length, int index);
int determineOrientation(Point lp1, Point lp2, Point p);
Point createVector(Point p1, Point p2);
int crossProduct(Point p1, Point p2);
float distanceLineToPoint(Point lpt1, Point lpt2, Point dPt);
int isPointInTriangle(Point trLeft, Point trRight, Point trTop, Point p);
float getTriangleArea(Point p1, Point p2, Point p3);
int getMaxDistancePointFromLine(Point leftMost, Point rightMost, Point* pointArray, int length);
void bubbleSort(Point* ptArray, int len);
|
C
|
#include<stdio.h>
#include<string.h>
int main()
{
char s[20]="abcdecf";
char s1[20];
int i,j=0;
for(i=0;s[i]!='\0';i++)
{
if(s[i]!='c')
{
s1[j]=s[i];
j++;
}
}
s1[j]='\0';
printf("%s",s1);
}
/*#include<stdio.h>
#include<conio.h>
#include<string.h>
void del(char str[], char ch);
void main() {
char str[10];
char ch;
printf("\nEnter the string : ");
gets(str);
printf("\nEnter character which you want to delete : ");
scanf("%ch", &ch);
del(str, ch);
getch();
}
void del(char str[], char ch) {
int i, j = 0;
int size;
char ch1;
char str1[10];
size = strlen(str);
for (i = 0; i < size; i++) {
if (str[i] != ch) {
str1[j] = str[i];
//= ch1;
j++;
}
}
str1[j] = '\0';
printf("\ncorrected string is : %s", str1);
}*/
|
C
|
// SPDX-License-Identifier: Apache-2.0
// Copyright 2019 Charles University
#include "../theap.h"
#include <ktest.h>
#include <mm/heap.h>
/*
* Tests that kmalloc() returns a valid address. We assume
* there would be always enough free memory to allocate 8 bytes
* when the kernel starts.
*/
void kernel_test(void) {
ktest_start("heap/basic");
void* ptr1 = kmalloc(16);
void* ptr2 = kmalloc(16);
size_t sizeT= (size_t)ptr2;
void* ptr3 = kmalloc(16);
kfree(ptr2);
void* ptr4 = kmalloc(8);
void* ptr5 = kmalloc(8);
printk("Ptr1: %u\n",(size_t)ptr1);
printk("Ptr4: %u\n",(size_t)ptr4);
printk("Ptr5: %u\n",(size_t)ptr5);
printk("Ptr3: %u\n",(size_t)ptr3);
printk("sizeT + 8: %u\n", sizeT + 8);
printk("sizeT: %u\n", sizeT);
ktest_assert((size_t)ptr4 == sizeT, "Wrong fit");
ktest_assert(ptr1 != NULL, "no memory available");
ktest_assert(ptr3 != NULL, "no memory available");
ktest_check_kmalloc_result(ptr1, 16);
ktest_check_kmalloc_result(ptr3, 16);
ktest_passed();
}
|
C
|
/*
** EPITECH PROJECT, 2019
** My_revstr
** File description:
** [file description here]
*/
int my_strlen(char const *str);
void my_swap_char(char *a, char *b);
char *my_revstr(char *str)
{
int nb_char;
int i;
i = 0;
nb_char = my_strlen(str) - 1;
while (i <= (nb_char / 2)){
my_swap_char(str + i, str + nb_char - i);
i++;
}
return (str);
}
|
C
|
// Praktikum EL2208 Pemecahan Masalah dengan C
// Modul : 8
// Percobaan : 2
// Tanggal : 11 Maret 2016
// Nama (NIM) : Ngakan Putu Ariastu Krisnadi Rata (13214137)
// Nama File : problem2.c
// Deskripsi : menghitung BMI user dengan inputan tinggi dan berat badanya , lalu menentukan status tubuhnya (overweight dll)
#include <stdio.h>
// Deklarasi Fungsi
float BMIcalc (float w, float h);
int main(){
float height,weight; //deklarasi variable
float z;
//ALGORITMA
printf("Kalkulator Berat Badan Ideal BMI\n");
printf("Masukkan tinggi badan anda ( Meter ):\n"); //meminta input tinggi
scanf("%f",&height);
printf("Masukkan berat badan anda ( Kilogram ):\n"); //meminta input berat
scanf("%f",&weight);
z=BMIcalc(weight,height); //proses BMI dengan pemanggilan fungsi disimpan di z
if (z < 18){ //percabangan sesuai hasil perhitungan BMI (Z)
printf("BMI = %.2f, Under Weight\n",z);
}
if ((z < 26)&&(z >= 18)){
printf("BMI = %.2f, Normal Weight\n",z);
}
if ((z < 28)&&(z >= 25)){
printf("BMI = %.2f, Over Weight\n",z);
}
if (z >= 28){
printf("BMI = %.2f, Obese\n",z);
}
return 0;
}
// Deklarasi
float BMIcalc (float w, float h){ //fungsi dengan input tinggi dan berat
float R;
R = w/(h*h); //proses
return R; //mengembalikan nilai R dari proses
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* convert_length.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: abungert <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2016/01/15 16:58:51 by antoinebungert #+# #+# */
/* Updated: 2016/01/26 16:55:45 by abungert ### ########.fr */
/* */
/* ************************************************************************** */
#include "ft_printf.h"
uintmax_t get_unsigned_length(uintmax_t nbr, t_tag *tag)
{
if (tag->length == 1)
nbr = (unsigned short int)nbr;
else if (tag->length == 2)
nbr = (unsigned char)nbr;
else if (tag->length == 3)
nbr = (unsigned long int)nbr;
else if (tag->length == 4)
nbr = (unsigned long long int)nbr;
else if (tag->length == 5)
nbr = (uintmax_t)nbr;
else if (tag->length == 6)
nbr = (size_t)nbr;
else
nbr = (unsigned int)nbr;
return (nbr);
}
intmax_t get_signed_length(intmax_t nbr, t_tag *tag)
{
if (tag->length == 1)
nbr = (short int)nbr;
else if (tag->length == 2)
nbr = (char)nbr;
else if (tag->length == 3)
nbr = (long int)nbr;
else if (tag->length == 4)
nbr = (long long int)nbr;
else if (tag->length == 5)
nbr = (intmax_t)nbr;
else if (tag->length == 6)
nbr = (size_t)nbr;
else
nbr = (int)nbr;
return (nbr);
}
|
C
|
#ifndef THREADSMANAGING_THREADS_MANAGER_H_
#define THREADSMANAGING_THREADS_MANAGER_H_
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>
#include <sys/types.h>
#include <string.h>
#include <errno.h>
/**
* Status = 0 -> Thread da eliminare; = 1 -> Thread attivo;
*
*/
struct _thread_list_elem {
pthread_t thread_id;
int status;
void* thread_info;
struct _thread_list_elem* next;
};
typedef struct _thread_list_elem Thread_List_Elem;
Thread_List_Elem* threads_list;
pthread_mutex_t mtx_getseq;
pthread_cond_t cond_read_seq_global;
short int read_seq_global;
pthread_mutex_t mtx_wrtfile;
pthread_cond_t cond_write_file_global;
short int write_file_global;
int insert_threadInList(Thread_List_Elem** list_head, Thread_List_Elem** last_inList, Thread_List_Elem* new_thread);
Thread_List_Elem* remove_thread(Thread_List_Elem** list_head, pthread_t t_id);
int pt_m_lock (pthread_mutex_t *mtx);
int pt_m_unlock (pthread_mutex_t *mtx);
void check_Thread_Error(int error_code);
#endif /* THREADSMANAGING_THREADS_MANAGER_H_ */
|
C
|
/*
============================================================================
Name : twr-lib-tester.c
Author : Digital Logic
Description : Tester for twr-comm library
Tester for easy SN/ID
============================================================================
*/
#include "../lib/include/twr-comm.h"
//-----------------------------
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
//-----------------------------
// OS specific
#include <windows.h>
//-----------------------------
static int polling = TRUE;
// UID for stop polling - exit from application
u8 stop_uid[4] = { 0x16, 0x78, 0x58, 0x56 };
int fCB_UID(c_string sn, u8 uid[], int uid_len, int control_info)
{
TWR_STATUS e;
int i;
puts("");
puts("Application CB_OK is called ...");
printf("Arrived packet from TWR SN=[%8s] with UID[len: %d]=", sn, uid_len);
// hex to string
for (i = 0; i < uid_len; ++i)
printf("%02X:", uid[i]);
printf(" | control_info= %d\n\n", control_info);
puts("Application send ACK...");
int r_status = 0; // OK
e = TWR_Packet_Ack(sn, uid, uid_len, control_info, r_status);
printf("TWR_Packet_Ack() : %s\n", TWR_Status2Str(e));
puts("");
puts("");
//--------------------------------------------------------------
// stop polling on specific UID
if (!memcmp(uid, stop_uid, sizeof(stop_uid)))
{
puts("--> STOP POLLING UID detected <--");
polling = FALSE;
}
//--------------------------------------------------------------
return 0;
}
int fCB_Error(int err_id, const char *err_msg)
{
printf("ERROR happens: id= %d | msg= %s\n", err_id, err_msg);
return 0;
}
int main(void)
{
TWR_STATUS e;
printf("Tester for TWR-comm library version: ");
puts(TWR_GetLibraryVersionStr());
e = TWR_registerCB_Error(fCB_Error);
printf("TWR_registerCB_Error(fCB_Error) : %s\n", TWR_Status2Str(e));
e = TWR_registerCB_UID(fCB_UID);
printf("TWR_registerCB_OK(fCB_UID) : %s\n", TWR_Status2Str(e));
//---
puts("Wait for SN/UID events...");
puts("");
while (polling)
{
e = TWR_Manager();
if (e)
{
printf("TWR_Manager() : %s\n", TWR_Status2Str(e));
break;
}
Sleep(1);
fflush(stdout);
}
puts("Done.");
puts("Tester exit!");
return EXIT_SUCCESS;
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* msh_helpers1.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: jbeall <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2019/03/18 10:04:24 by jbeall #+# #+# */
/* Updated: 2019/03/18 10:06:15 by jbeall ### ########.fr */
/* */
/* ************************************************************************** */
#include "minishell.h"
void free_str_split(char **str_arr)
{
int i;
i = 0;
while (str_arr[i])
free(str_arr[i++]);
free(str_arr);
}
char **dup_str_arr(char **ar)
{
char **new;
int count;
count = 0;
while (ar[count])
count++;
new = (char**)ft_memalloc(sizeof(char*) * (count + 1));
while (count)
{
new[count - 1] = ft_strdup(ar[count - 1]);
count--;
}
return (new);
}
void print_command(t_command *cmd)
{
int i;
ft_printf("CMD: %s\n", cmd->name);
i = 1;
ft_printf("ARGS:\n");
while (cmd->argv[i])
{
ft_printf("%s\n", cmd->argv[i]);
i++;
}
}
int has_non_trailing_slash(char *str)
{
int i;
int count;
i = 0;
count = ft_strlen(str);
while (i < count - 1)
{
if (str[i] == '/')
return (1);
i++;
}
return (0);
}
void free_cmd(t_command *cmd)
{
free_str_split(cmd->argv);
free(cmd);
}
|
C
|
/*
** EPITECH PROJECT, 2017
** MY_STRNCAT.C (FOR LIB)
** File description:
** For lib: function for concatenate two strings with n caractere
*/
#include <stdlib.h>
#include "my.h"
char *my_strncat(char *dest, char const *src, int nb)
{
int i = 0;
int j = 0;
int cpt = my_strlen(dest) + nb;
char *save = malloc(sizeof(char) * (cpt + 1));
if (save == NULL)
return (NULL);
i = my_strlen(dest);
for (; j < nb; ++j)
dest[i + j] = src[j];
dest[i + j] = '\0';
return (dest);
}
|
C
|
/* devuelve la cantidad de caracteres en cadena sin contar el '\0' */
int largo_cadena(char cadena[])
{
int largo=0
while (cadena[largo]!='\0') largo++;
return largo;
}
|
C
|
#include<stdio.h>
int main()
{
int t,n,temp,k,arr[100],i,sum;
scanf("%d",&t);
while(t--)
{
scanf("%d",&n);
for(i=0;i<n;i++)
scanf("%d",&arr[i]);
scanf("%d",&k);
sum=0;
for(i=0;i<k;i++)
{
scanf("%d",&temp);
sum+=arr[temp-1];
}
printf("%d\n",sum);
}
return 0;
}
|
C
|
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
#include "mpi.h"
#define SlaveSize 100
#define MasterSIze 100000
long int globalSum(int* vector, int size) {
long int sum = 0;
for (int i = 0; i < size; i++) {
sum += vector[i];
}
return sum;
}
int ElementsSum(int vector[], int size) {
int sum = 0;
for (int i = 0; i < size; i++) {
sum += vector[i];
}
return sum;
}
int main(int argc, char** argv[]) {
srand(time(NULL));
int MainVector[MasterSIze], vector2[SlaveSize];
int i, j, rank, size;
int root = 0;
int counter = 0;
MPI_Init(&argc, &argv);
MPI_Request req1, req2;
MPI_Status status1, status2;
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
MPI_Comm_size(MPI_COMM_WORLD, &size);
for (int i = 0; i < SlaveSize; i++)
{
vector2[i] = 0;
}
if (rank == 0) {
int MainSum = 0;
int slaveSum = 0;
int VectorSum[MasterSIze / SlaveSize];
int TotalSum[MasterSIze / SlaveSize];
for (i = 0; i < MasterSIze; i++) {
MainVector[i] = rand() % 10001;
if ((i + 1)% SlaveSize == 0) {
MPI_Isend(&MainVector[i +1 - SlaveSize], SlaveSize, MPI_INT,
counter % (size - 1) + 1, 0, MPI_COMM_WORLD, &req1);
MainSum = ElementsSum(&MainVector[i +1- SlaveSize], SlaveSize);
TotalSum[counter] = MainSum;
printf("\nGlobal Sum: %d\n", MainSum);
MPI_Wait(&req1, &status1);
MPI_Irecv(&VectorSum[counter], 1, MPI_INT, counter % (size - 1) + 1, 0, MPI_COMM_WORLD, &req2);
MPI_Wait(&req2, &status2);
printf("Sum of rank %d is: %d\n", counter % size + 1, VectorSum[counter]);
counter++;
}
}
printf("\n\nGlobal Sum: %d\n", globalSum(TotalSum, counter));
printf("Slave Sum: %d\n\n", globalSum(VectorSum, counter));
}
else {
long int partialSum = 0;
for (i = rank; i <= MasterSIze/SlaveSize; i += size - 1) {
MPI_Irecv(&vector2[0], SlaveSize, MPI_INT, 0, 0, MPI_COMM_WORLD, &req1);
MPI_Wait(&req1, &status1);
partialSum = ElementsSum(vector2, SlaveSize);
MPI_Isend(&partialSum, 1, MPI_INT, 0, 0, MPI_COMM_WORLD, &req2);
MPI_Wait(&req2, &status2);
}
}
MPI_Finalize();
return 0;
}
|
C
|
/*
Luke Manzitto
11/23/2020
Lab8 - Step1
Creates a file with random numbers between 0-19.
*/
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[]) {
FILE *fp;
char buffer [sizeof(int)];
int i;
fp = fopen("testInput.txt", "w");
for (i=0; i<100; i++){
sprintf(buffer, "%d\n", rand()%20);
fputs(buffer, fp);
}
fclose(fp);
return 0;
}
|
C
|
#include <vector>
#include <string>
#include <iostream>
#include <sstream>
#include <fstream>
#include "classAnalyzer.h"
using namespace std;
mushroomAnalyzer::mushroomAnalyzer(){}
/*
* The detailed initializer of mushrronAnalyzer; using the input
* to fill-in:
* DLStat, the 3-dimensional array that stores how
* one single property influences the mushroom's edibility.
* DLIndex, the int array that will store the ordering of all
* properties by comparing the majority rate of each property.
* The algorithm applied here does not strictly stick to the
* information gain method but is also more optimal than just
* random selection.
*/
void
mushroomAnalyzer::init(){
ifstream inputF;
/* 0-fill all the DLStat and DLIndex arrays. */
for (int i = 0; i < numOfProperty; i++){
DLIndex[i] = 0;
for (int j = 0; j < 127; j++){
DLStat[i][j][0] = 0;
DLStat[i][j][1] = 0;
}
}
/* Open the file for input. */
inputF.open(inputStream);
/* Check if successfully opened. */
/* Read the data one line at a time. Split the line delimited
* by ',' and if this line indicates an edbile mushroom,
* increase 1 for the first slot in every DLStat element that
* corresponds to a property of this mushroom.
* e.g.: the line read in is:
* e,x,s,y,t,a,f,c,b,k,e,c,s,s,w,w,p,w,o,p,n,n,h
* because its 1st property is 'x'(120) and it is edible,
* DLStat[0][120][0] should increase by 1, meaning that
* there exists at least one datum whose first property
* is x and is edible.
* Applying this operation to all the data, we will get an
* array containing the info apopos how one single property
* influences the edibility.
*/
if(inputF.is_open()){
for (int i = 0; i < DEFAULT_DATA_LENGTH; i++){
string nextLine;
getline(inputF, nextLine);
char edibility = nextLine[0];
int count = 1;
for (int j = 1; j < nextLine.length(); j++){
if (nextLine[j] != ','){
if (edibility == 'e'){
DLStat[count-1][nextLine[j]][0] ++;
}
else{
DLStat[count-1][nextLine[j]][1] ++;
}
count ++;
}
}
}
/* With DLStat filled-in, the program goes on to decide the order
* by which it splits the properties.
* To achieve this, the program calculates the majority rate for
* each property.
* e.g.: DLStat[0][120][0] is 100 and DLStat[0][120][1] is 0.
* The majority rate for x in the first property is then:
* MAX(DLStat[0][120][0], DLStat[0][120][1]) / (DLStat[0][120][0]
* + DLStat[0][120][1])
* Therefore this value is added into DLIndex[0] and the count is
* increased by 1.
* When the first property has been exhausted, divide DLIndex[0]
* with count will get the averge majority rate for the 1st property.
*/
for (int i = 0; i < numOfProperty; i++){
int count = 0;
for (int j = 0; j < 127; j++){
if (DLStat[i][j][0] || DLStat[i][j][1]){
count ++;
double rate = 2 - 2 * (DLStat[i][j][0] > DLStat[i][j][1]
? DLStat[i][j][0] : DLStat[i][j][1] + 0.0) /
(DLStat[i][j][0] + DLStat[i][j][1]);
DLIndex[i] += rate;
}
}
DLIndex[i] = DLIndex[i] / count;
}
inputF.close();
root = new propertyNode(this);
}
else{
cout << "Error opening file!" << endl;
}
}
/* Accessor method for mushroonAnalyzer that returns DLIndex*/
array<double, numOfProperty>
mushroomAnalyzer::getDLOrder(){
return DLIndex;
}
/* Acessor method for mushroomAnalyzer that returns DLStat */
array<array<array<int, 2>, 127>, numOfProperty>
mushroomAnalyzer::getDLCont(){
return DLStat;
}
/* The method that makes the prediction by recursively calling
* proceed to matching propertyNodes and contNodes. */
char
mushroomAnalyzer::match(string toMatch){
return (root -> proceed(toMatch));
}
/* Constructo for root propertyNode.
* The operations consist of:
* set the source using from
* set the forward array using the DLIndex in source
* delete the first element in forward array in order
* set the id
* build its children, which is a list of contNodes
*/
propertyNode::propertyNode(mushroomAnalyzer* from){
source = from;
forward = source -> getDLOrder();
int min = 0;
for (int i = 0; i < numOfProperty; i++){
if (forward[i] < forward[min]){
min = i;
}
}
forward[min] = 100;
id = min;
//cout << id << " start building propertyNode" << endl;
build();
}
/*
* Constructor for child propertyNode.
* The operations consist of:
* set parent
* set forward
* set source
* set backtrace
* build its children
*/
propertyNode::propertyNode(contNode* from, array<double, numOfProperty> fw, int id){
parent = from;
forward = fw;
source = parent -> getSource();
backtrace = parent -> getDLOrder();
this -> id = id;
//cout << id << " start building propertyNode" << endl;
this -> build();
//cout << id << " propertyNode build complete" << endl;
}
/*
* The method that interconnects between levels of propertyNodes
* and contNodes.
* One propertyNode has many contNodes as children since one
* property can have many contents for it.
* Construct a child node for each possible content by pushing
* and then popping different pair of <int, char> into backtrace.
* The forward array can be left unchanged because this build step
* does not go to the next property in the tree.
*/
void propertyNode::build(){
array<array<array<int, 2>, 127>, numOfProperty> DLStat = source -> getDLCont();
vector<pair<int, char>> copy = backtrace;
for(int i = 0; i < 127; i++){
if (DLStat[id][i][0] || DLStat[id][i][1]){
pair<int, char> toAdd(id, i);
copy.push_back(toAdd);
serial.push_back(i);
//cout << "continue to next" << endl;
contNode* toPush = new contNode(this, copy);
children.push_back(toPush);
copy.pop_back();
}
}
}
/*
* Accessor method for propertyNode that returns the ID
*/
int propertyNode::getID(){
return id;
}
/*
* Accessor method for propertyNode that returns the
* forward array
*/
array<double, numOfProperty> propertyNode::getDLOrder(){
return forward;
}
/*
* Accessor method for propertyNode that returns the
* source pointer to the mushroomAnalyzer
*/
mushroomAnalyzer* propertyNode::getSource(){
return source;
}
/*
* Looks like the reverse of build, search through
* all possible content of this property and find the
* one that matches the given string, call proceed
* method on that one contNode child.
*/
char propertyNode::proceed(string match){
char toComp = match[id*2+2];
for (int i = 0; i < children.size(); i++){
if (serial[i] == toComp){
return (children[i] -> proceed(match));
break;
}
}
return 'E';
}
/*
* Constructor for contNode
* The operations consist of:
* set the backtrace
* set the parent
* set the forward
* set the source
* initialize finality with true
* build its child
*/
contNode::contNode(propertyNode* from, vector<pair<int, char>> bt){
backtrace = bt;
parent = from;
forward = from -> getDLOrder();
source = parent -> getSource();
finality = true;
build();
}
/*
* Accessor method for contNode that returns backtrace
*/
vector<pair<int, char>> contNode::getDLOrder(){
return backtrace;
}
/*
* Accessor method for contNode that returns source
*/
mushroomAnalyzer* contNode::getSource(){
return source;
}
/*
* The build method for contNode.
* Check through the database and match each data with
* this -> backtrace; if the result does not vary
* throughout the whole match process, then terminate
* and return because this trace is final by reaching
* this node. If the result varies at some point,
* terminate and go on to the next property, because
* this trace is not final up to this node.
* If one trace exhausted the properties and still
* did not reach a final trace, set finality as true
* but result as 'E' and return.
*/
void contNode::build(){
ifstream inputF;
inputF.open(inputStream);
if (inputF.is_open()){
char res;
for (int i = 0; i < DEFAULT_DATA_LENGTH; i++){
int ini = 1; int right = 1;
string nextLine;
getline(inputF, nextLine);
for (int j = 0; j < backtrace.size(); j ++){
int index = (backtrace[j].first) * 2 + 2;
char match = backtrace[j].second;
if (nextLine[index] != match){
right = 0;
break;
}
}
if (right){
if (ini){
res = nextLine[0];
ini = 0;
}
else{
if (res != nextLine[0]){
finality = false;
break;
}
}
}
}
inputF.close();
if (!finality){
//cout << parent -> getID() << " contNode build complete" << endl;
int min = 0; int count = 0;
for (int i = 0; i < numOfProperty; i++){
if (forward[i] < forward[min]){
min = i;
}
if (forward[i] == 100){
count ++;
}
}
if (count != numOfProperty){
forward[min] = 100;
//cout << "continue to next" << endl;
child = new propertyNode(this, forward, min);
}
else{
finality = true;
result = 'E';
}
}
else{
result = res;
//cout << parent -> getID() << " contNode build complete" << endl;
return;
}
}
else{
cout << "Error opening file" << endl;
}
}
/*
* The proceed method for contNode.
* If this node is final, return its result.
* If this node is not final, go to next property.
*/
char contNode::proceed(string match){
if (finality){
return result;
}
else{
return (child -> proceed(match));
}
}
/*
* Tester for the Decision Tree structure.
*/
int main(){
cout << "Start building DT..." << endl;
/* Create and initialize the object to test with */
mushroomAnalyzer test;
test.init();
cout << "DT building complete. Now running auto test with 4000 sets of data..." << endl;
/* Create connect to the database */
ifstream inputF;
inputF.open(inputStream);
/* Create the file that saves the output */
ofstream outputF;
outputF.open("ACCURACY");
/* Run the Decision Tree on 4000 sets of test data */
int countR = 0; int countW = 0;
for (int i = 0; i < 8000; i++){
if (i >= 4000){
string nextLine;
getline(inputF, nextLine);
char res = test.match(nextLine);
if (res != nextLine[0]){
outputF << "Wrong prediction on test " << i
<< ": should be " << nextLine[0]
<< ", but was " << res << endl;
countW++;
}
else{
outputF << res << " is the correct prediction on " << i << endl;
countR++;
}
}
}
inputF.close();
outputF << "Out of " << (countR + countW) << " predictions, "
<< countR << " are right, standing at a "
<< (countR + 0.0) / (countR + countW) * 100 << "% rate of accuracy." << endl;
cout << "Out of " << (countR + countW) << " predictions, "
<< countR << " are right, standing at a "
<< (countR + 0.0) / (countR + countW) * 100 << "% rate of accuracy." << endl;
/* Start the manual test */
string inputS;
cout << "The auto test has been completed and the result is in ACCURACY file," << endl
<< "now you can manually test this DT." << endl;
cout << "Please type in data in the form of ?,x,s,n,t,p,f,c,n,k,e,e,s,s,w,w,p,w,o,p,k,s,u."
<< endl << "Then press enter, the program will first predict its edibility and then search through"
<< "the data for actual match and compare both." <<endl;
cout << "To quit, type in quit and enter." << endl << "Please type in mushroom description." << endl;
cin >> inputS;
while (inputS != "quit"){
char res = test.match(inputS);
inputS[0] = res;
string wrong = inputS;
if (res == 'e'){
cout << "According to the DT, this mushroom is edible." << endl;
cout << "Checking for match in database." << endl;
wrong[0] = 'p';
}
else{
cout << "According to the DT, this mushroom is poisonous." << endl;
cout << "Checking for match in database." << endl;
wrong[0] = 'e';
}
inputF.open(inputStream);
bool correctness = true;
for (int i = 0; i < 8000; i++){
string nextLine;
getline(inputF, nextLine);
if (nextLine == inputS){
cout << "Prediction is correct." << endl;
correctness = false;
break;
}
if (nextLine == wrong){
cout << "Prediction is wrong." << endl;
correctness = false;
break;
}
}
if (correctness){
cout << "Not match found." << endl;
}
cout << "Please type in mushroom description." << endl << "To quit, type in quit and enter." << endl;
cin >> inputS;
}
}
|
C
|
/**************************************************************************
** stackapp.c
** Author: Chris Kearns
** Stack application for validating balanced [{()}] in input
** string. See algorithm at bottom of file.
** Call from command line: prog '[{()}]'
** Requires #include dynArray.h (Implementation of stack and bag with
** underlying array.)
**************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include "dynArray.h"
/****************************************************************
Using stack to check for unbalanced parentheses.
******************************************************************/
/* Returns the next character of the string, once reaches end return '0' (zero)
param: s pointer to a string
pre: s is not null
*/
char nextChar(char* s) {
static int i = -1;
char c;
++i;
c = *(s+i);
if ( c == '\0' )
return '\0';
else
return c;
}
/* Checks whether the (), {}, and [] are balanced or not
param: s pointer to a string.
pre: s is not null.
post: Stack is deleted and we return res.
ret: int 1 for true, 0 for false.
*/
int isBalanced(char* s) {
DynArr *dyn;
dyn = newDynArr(12); /* arbitrarily selected array size. */
char r;
int res = 0;
do {
r = nextChar(s);
if (r == '{' || r == '(' || r == '[') {
if (r == '{') r = '}';
if (r == '[') r = ']';
if (r == '(') r = ')';
pushDynArr(dyn, r);
}
else if (r == '}' || r == ']' || r == ')') {
if (isEmptyDynArr(dyn)) {
res = 0;
deleteDynArr(dyn);
return res;
}
else if(topDynArr(dyn) == r) {
popDynArr(dyn);
}
}
} while (r != '\0');
if (isEmptyDynArr(dyn)) {
res = 1;
}
deleteDynArr(dyn);
return res;
}
int main(int argc, char* argv[]){
if (argv[1] != NULL) {
char* s = argv[1];
int res;
printf("Assignment 2\n");
res = isBalanced(s);
if (res)
printf("The string %s is balanced\n",s);
else
printf("The string %s is not balanced\n",s);
}
else {
printf("\"prog\" needs an argument such as prog '' or prog '[{()}]'\n");
}
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
int main(void) {
int n,cont=0;
printf("informe o numero de entradas");
scanf("%d",&n);
int *v=malloc(n*sizeof(int));
int w[n/2];
for (int i=0;i<n;i++){
scanf("%d",&v[i]);
}
int k=0,f=0;
for (int i=0;i<n;i++){
for(int j=i;j<n-1;j++){
if(v[i]==v[j+1]){
for(int m=0;m<k;m++){
if(v[i]==w[m]){
f++;
}
}
if(f==0){
w[k]=v[i];
k++;
cont++;
break;
}
}
}
}
printf("%d pares",cont);
printf("(");
for(int i=0;i<cont;i++){
printf(" tamanho %d ",w[i]);
}
printf(")");
free(v);
return 0;
}
|
C
|
/************************************************************************|
| Simulação de Escalonamento de Processos com Gerenciamento de Memória |
| |---------------------------| |
| | Integrantes: | |
| | João Marcos Rosa | |
| | Jonatan Rodrigues | |
| | Mateus Matinato | |
| | Vinicius de Freitas | |
| |---------------------------| |
| Disciplina: laboratório de Estrutura de Dados II |
| Professor: Leandro Neves Data: 12/09/2017 |
|************************************************************************/
#include <locale.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h> //Usada para gerar numeros aleatórios e tempos
#include <windows.h> //Usada para configurar tamanho da janela
#include <conio.h> //Usada para kbhit
#include "funcoesGeren.h"
#define quantum 1 //Define o quantum do processador
#define velocidade 2.5 //Define a velocidade do programa (0 -> muito rapido / 5 -> muito devagar)
void main(){
setlocale(LC_ALL,"Portuguese");
system("mode con:cols=210 lines=70");
int idDisponivel[1000];
int i;
for(i=0;i<1000;i++){
idDisponivel[i] = 1;
}
MEM *memoria = criaMemoria();
memoria->tamanho = 512;
memoria->posicao = 0;
srand(time(NULL));
//Cria as filas necessárias
FILA *jobs = criaFila();
FILA *pronto = criaFila();
FILA *dispositivo = criaFila();
FILA *tabela = criaFila();
int flag = 0;
int contadorprocessos = 0;
//Inicio do Programa
printf("|============================================|\n");
printf("| Simulação de Escalonamento de Processos |\n");
printf("|--------------------------------------------|\n");
printf("| Simular Manualmente (1) |\n");
printf("| Simular Automaticamente (2) |\n");
printf("| Simular Pressionando Enter (3) |\n");
printf("|============================================|\n");
printf("Digite sua opção -> ");
int opc;
scanf("%d",&opc);
system("cls");
//Loop que gerará aleatoriedades
int aleatorio = -1;
int fez;
int tecla = 13;
while(opc == 1 || (opc == 2 && !_kbhit()) || (opc == 3 && tecla == 13) ){
aleatorio = randomInteger(1,110);
fez = 1;
if(opc == 1){
printf("\n|=================================================|\n");
printf("| MENU MANUAL |\n");
printf("|-------------------------------------------------|\n");
printf("| Gerar um Processo Aleatório (1) |\n");
printf("| Processar com Round Robin (1 ciclo) (2) |\n");
printf("| Liberar um Processo em Dispositivo (3) |\n");
printf("| Informações Sobre Processo/PCB (4) |\n");
printf("| Sair (0) |\n");
printf("|=================================================|\n");
printf("Digite sua opção -> ");
int opc2;
scanf("%d",&opc2);
switch(opc2){
case 1: aleatorio = 20; break;
case 2:{
if(filaVazia(pronto)){
printf("--> Não existem processos na fila de Pronto <--\n");
tempo(velocidade);
}
aleatorio = 60;
break;
}
case 3:{
if(filaVazia(dispositivo)){
printf("--> Não existem processos na fila de Dispositivo <--\n");
tempo(velocidade);
}
aleatorio = 100;
break;
}
case 4:{
printf("Digite o número do processo: ");
int numprocesso;
scanf("%d",&numprocesso);
procuraMemoria(memoria,numprocesso);
char continuar = 13;
do{
fflush(stdin);
printf("\nAperte enter para continuar...\n");
continuar = getch();
}while(continuar != 13);
aleatorio = 150;
break;
}
case 0:{
//Caso for 0 não entra em nenhum if e sai do loop
aleatorio = 150;
opc = 0;
break;
}
}
}
else if((opc == 2 || opc == 3) && flag == 0){
barraProgresso(1);
flag = 1;
if(opc == 3){
printf("Aperte ENTER para gerar aleatoriedades...");
}
}
mostraFilas(memoria,pronto,dispositivo);
//Começo dos casos de aleatoriedade
int inseriu = 0;
if(aleatorio <= 40){
//Gera um processo na hora
PROCESSO *p1 = criaProcesso(idDisponivel);
if(p1 == NULL){
printf("Número máximo de processos atingido.\n");
tempo(2);
aleatorio = 60;
break;
}
clock_t inicio = clock();
double valor = 0;
memoria = insereMemoria(memoria,p1,&inseriu);
tempo(velocidade);
if(inseriu){
//Caso tiver sido inserido na memória -> passa pra fila de pronto
p1->pcb.id = p1->id;
p1->pcb.estado = 0;
p1->pcb.contador = rand()%10+1;
p1->pcb.tempoCPU = ((float)rand()/(float)RAND_MAX) * (rand()%1000+20);
insereFila(tabela,*p1); //Insere na tabela de PCB o processo
insereFila(pronto,*p1); //Insere na fila de pronto o processo
printf("\nO Processo %d (Quantum -> %d)foi inserido na fila pronto.\n",p1->id, p1->pcb.contador);
tempo(velocidade);
mostraFilas(memoria,pronto,dispositivo);
}
else{
printf("\nO Processo %d não foi inserido na fila de pronto por falta de memória.\n",p1->id);
tempo(velocidade);
}
}
else if(aleatorio > 40 && aleatorio <= 80){
//Faz o escalonamento e diminui os quantuns
if(filaVazia(pronto)) fez = 0;
int i;
int tamanhoPronto = tamanhoFila(pronto);
for(i = 0; i < tamanhoPronto; i++){
PROCESSO executando = removeFila(pronto);
removeFila(tabela);
if(executando.pcb.contador > 0){ //Caso o quantum for positivo, subtrai o quantum do processador
executando.pcb.estado = 1; //Em execução
printf("\nProcesso %d em execução...\n",executando.id);
int device = rand()%10+1;
if(device == 1 || device == 2){
//Caso o inteiro device for 1 ou 2-> necessita de E/S
executando.pcb.estado = 3;
insereFila(dispositivo,executando);
printf("---> O Processo %d foi INTERROMPIDO e movido para a fila de dispositivos <---\n",executando.id);
tempo(velocidade+1.0);
mostraFilas(memoria,pronto,dispositivo);
}
else if(executando.pcb.contador < quantum){ //Isso serve para esperar x segundos de processamento
tempo(executando.pcb.contador);
executando.pcb.contador -= quantum; //Diminui o quantum do processo
}
else if(executando.pcb.contador >= quantum){ //isso serve para esperar "quantum" segundos de processamento
tempo(quantum);
executando.pcb.contador -= quantum; //Diminui o quantum do processo
}
//Depois de executar e esperar o tempo ele reinsere na fila
if(executando.pcb.contador > 0 && executando.pcb.estado != 3){ //Caso ainda houver quantum
printf("---> ID: %d foi processado e resta(m) %d segundo(s) de processamento <---\n",executando.id, executando.pcb.contador);
executando.pcb.estado = 1;
tempo(velocidade);
insereFila(pronto,executando); //Joga o processo pra tabela auxiliar
mostraFilas(memoria,pronto,dispositivo);
}
if(executando.pcb.contador <=0 && executando.pcb.estado != 3){ //Caso o quantum for 0 ou negativo, muda o estado para 2 e remove das filas
executando.pcb.estado = 2; //Altera estado para finalizado
printf("---> O Processo %d foi FINALIZADO <---\n",executando.id);
removeMemoria(memoria,&executando);
tempo(velocidade);
mostraFilas(memoria,pronto,dispositivo);
contadorprocessos++;
}
}
}
}
else if(aleatorio > 80 && aleatorio <=110){
//Retirará um processo da fila de dispositivo
if(!filaVazia(dispositivo)){
PROCESSO disp = removeFila(dispositivo);
insereFila(pronto,disp);
printf("\n---> O Processo %d foi TRANSFERIDO de Dispositivo para Pronto(Posição %d) <---\n",disp.id,tamanhoFila(pronto));
tempo(velocidade);
mostraFilas(memoria,pronto,dispositivo);
}
else fez = 0;
}
if(opc == 3 && fez == 1){
fflush(stdin);
printf("\nAperte ENTER para continuar ou ESC para sair.\n");
tecla = getch();
}
}
system("cls");
printf("\n\n\t\t--> SIMULAÇÃO FINALIZADA <--\n\t\t%d PROCESSOS FINALIZADOS\n",contadorprocessos);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <strings.h>
#include <fcntl.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <sys/time.h>
#include <arpa/inet.h>
#include <unistd.h>
#define MAXLINE 1000
#define NAME_LEN 20
char *EXIT_STRING = "exit";
int tcp_connect(int af,char *servip,unsigned short port);
void errquit(char *mesg){perror(mesg);exit(1);}
int main(int argc , char *argv[]){
char bufall[MAXLINE+NAME_LEN], *bufmsg;
int maxfdp1;
int s;
int namelen;
fd_set read_fds;
if(argc != 4){
printf("사용법 : %s server_ip port name \n",argv[0]);
exit(0);
}
sprintf(bufall,"[%s]:",argv[3]);
namelen = strlen(bufall);
bufmsg = bufall+namelen;
s= tcp_connect(AF_INET,argv[1],atoi(argv[2]));
if(s==-1)
errquit("tcp_connect fail");
puts("서버에 접속되었습니다.");
maxfdp1 = s+1;
FD_ZERO(&read_fds);
while(1){
FD_SET(0,&read_fds);
FD_SET(s,&read_fds);
if(select(maxfdp1, &read_fds,NULL,NULL,NULL)<0)
errquit("select fail");
if(FD_ISSET(s,&read_fds)){
int nbyte;
if((nbyte = recv(s,bufmsg,MAXLINE,0))>0){
bufmsg[nbyte] = 0;
printf("%s \n",bufmsg);
}
}
if(FD_ISSET(0,&read_fds)){
if(fgets(bufmsg, MAXLINE,stdin)){
if(send(s,bufall,namelen+strlen(bufmsg),0)<0)
puts("Error : Write error on socket");
if(strstr(bufmsg, EXIT_STRING)!=NULL){
puts("Good Bye");
close(s);
exit(0);
}
}
}
}//while
return 0;
}
int tcp_connect(int af,char *servip,unsigned short port){
struct sockaddr_in servaddr;
int s;
if((s= socket(af,SOCK_STREAM,0))<0)
return 1;
bzero((char*)&servaddr,sizeof(servaddr));
servaddr.sin_family = af;
inet_pton(AF_INET,servip,&servaddr.sin_addr);
servaddr.sin_port = htons(port);
if(connect(s,(struct sockaddr *)&servaddr,sizeof(servaddr))<0)
return -1;
return s;
}
|
C
|
#include "dataModel.h"
//Struct
struct stParam{
char adv_name[3+1];
char val_1[6+1];
char val_2[6+1];
char val_3[6+1];
};
//struct stParam mParam[3];
//static const int mMaxDat=3;
struct stParam mParam[10];
static const int mMaxDat=10;
static const int mAdvNamesize=3;
static const int mOK_CODE =1;
static const int mNG_CODE =0;
//
void dataModel_set_advName(int iNum, char *adv_name ){
strcpy(mParam[iNum].adv_name , adv_name);
}
//
void dataModel_debug_printDat(){
for(int i= 0; i< mMaxDat; i++){
// printf("dat.i=%d, name=%s , value=%s \n", i , mParam[i].adv_name, mParam[i].val_1 );
printf("dat.i=%d, name=%s , value1=%s, value2=%s , value3=%s\n", i , mParam[i].adv_name, mParam[i].val_1, mParam[i].val_2, mParam[i].val_3 );
}
}
//
void dataModel_init_proc(){
printf("# init_proc \n");
// strcpy(mParam[0].adv_name, adv_name1 );
// strcpy(mParam[1].adv_name, adv_name2 );
// strcpy(mParam[2].adv_name, adv_name3 );
}
//
void dataModel_set_datByAdvname(char *adv_name, char *value, int field ){
// printf("val-1=%s\n" , mParam[0].val_1);
for(int i=0; i< mMaxDat; i++){
if(strcmp(adv_name, mParam[i].adv_name )== 0){
if(field==1){
strcpy(mParam[i].val_1 , value);
}else if(field==2){
strcpy(mParam[i].val_2 , value);
}else if(field==3){
strcpy(mParam[i].val_3 , value);
}
}
}
}
//
void dataModel_get_datByAdvname(char *adv_name, int field ,char *cValue){
//static char cRet[3+1];
for(int i=0; i< mMaxDat; i++){
if(strcmp(adv_name, mParam[i].adv_name )== 0){
if(field==1){
// strcpy(cRet , mParam[i].val_1);
strcpy(cValue , mParam[i].val_1);
}else if(field==2){
strcpy(cValue , mParam[i].val_2);
}else if(field==3){
strcpy(cValue , mParam[i].val_3);
}
}
}
}
/*
char *dataModel_get_datByAdvname(char *adv_name, int field ){
static char cRet[3+1];
for(int i=0; i< mMaxDat; i++){
if(strcmp(adv_name, mParam[i].adv_name )== 0){
if(field==1){
strcpy(cRet , mParam[i].val_1);
}else if(field==2){
strcpy(cRet , mParam[i].val_1);
}else if(field==3){
strcpy(cRet , mParam[i].val_1);
}
}
}
return cRet;
}
*/
int dataModel_recvCount(){
int ret= mNG_CODE;
int iCount=0;
int iCount2=0;
for(int j=0; j< mMaxDat; j++){
if(strlen( mParam[j].adv_name ) > 0 ){
iCount=iCount +1;
}
}
printf("iCount=%d\n",iCount );
if(iCount < 1){
return ret;
}
for(int i=0; i< iCount; i++){
// if(strlen( mParam[i].val_1 ) < 1 ){
if( (strlen( mParam[i].adv_name ) > 0 ) && (strlen( mParam[i].val_1 ) > 0 ) ){
iCount2= iCount2+1;
// return ret;
}
}
printf("iCount2=%d\n", iCount2 );
if(iCount2 > 0){ ret= mOK_CODE;}
return ret;
}
//
int dataModel_validAdvName(char *advname ){
int ret= mNG_CODE;
for(int i=0; i< mMaxDat; i++){
if(strncmp(advname , mParam[i].adv_name ,mAdvNamesize )== 0){
ret= mOK_CODE;
return ret;
}
}
return ret;
}
//
int dataModel_isComplete(){
int ret= mNG_CODE;
int iCount=0;
for(int j=0; j< mMaxDat; j++){
if(strlen( mParam[j].adv_name ) > 0 ){
iCount=iCount +1;
}
}
printf("iCount=%d\n",iCount );
// if(iCount < mMaxDat ){
if(iCount < 1){
return ret;
}
for(int i=0; i< iCount; i++){
// if(strlen( mParam[i].val_1 ) < 1 ){
if( (strlen( mParam[i].adv_name ) > 0 ) && (strlen( mParam[i].val_1 ) < 1) ){
return ret;
}
}
ret =mOK_CODE;
return ret;
}
//
void dataModel_clear(){
for(int i=0; i< mMaxDat; i++){
mParam[i].val_1[0]= '\0';
mParam[i].val_2[0]= '\0';
mParam[i].val_3[0]= '\0';
}
}
|
C
|
/* needs stdint.h */
#ifndef UTF8_TO_UTF32_H
#define UTF8_TO_UTF32_H
static int
utf8_to_utf32(const uint8_t *utf8, uint32_t *utf32, int max)
{
unsigned int c;
int i = 0;
--max;
while (*utf8) {
if (i >= max)
return 0;
if (!(*utf8 & 0x80)) {
utf32[i++] = *utf8++;
} else if ((*utf8 & 0xe0) == 0xc0) {
c = (*utf8++ & 0x1f) << 6;
if ((*utf8 & 0xc0) != 0x80) return 0;
utf32[i++] = c + (*utf8++ & 0x3f);
} else if ((*utf8 & 0xf0) == 0xe0) {
c = (*utf8++ & 0x0f) << 12;
if ((*utf8 & 0xc0) != 0x80) return 0;
c += (*utf8++ & 0x3f) << 6;
if ((*utf8 & 0xc0) != 0x80) return 0;
utf32[i++] = c + (*utf8++ & 0x3f);
} else if ((*utf8 & 0xf8) == 0xf0) {
c = (*utf8++ & 0x07) << 18;
if ((*utf8 & 0xc0) != 0x80) return 0;
c += (*utf8++ & 0x3f) << 12;
if ((*utf8 & 0xc0) != 0x80) return 0;
c += (*utf8++ & 0x3f) << 6;
if ((*utf8 & 0xc0) != 0x80) return 0;
c += (*utf8++ & 0x3f);
if ((c & 0xFFFFF800) == 0xD800) return 0;
if (c >= 0x10000) {
c -= 0x10000;
if (i + 2 > max) return 0;
utf32[i++] = 0xD800 | (0x3ff & (c >> 10));
utf32[i++] = 0xDC00 | (0x3ff & (c ));
}
} else return 0;
}
utf32[i] = 0;
return i;
}
#endif
|
C
|
#include <stdio.h>
#include <stdint.h>
uint8_t and_gate(uint8_t a, uint8_t b){
return ((a >> 0) & 0x01) & ((b >> 0) & 0x01);
}
uint8_t xor_gate(uint8_t a, uint8_t b){
return ((a >> 0) & 0x01) ^ ((b >> 0) & 0x01);
}
uint8_t or_gate(uint8_t a, uint8_t b){
return ((a >> 0) & 0x01) | ((b >> 0) & 0x01);
}
uint8_t ha(uint8_t a, uint8_t b){
uint8_t ha_out = 0;
uint8_t ha_xor0 = 0;
uint8_t ha_and0 = 0;
ha_xor0 = xor_gate(((a >> 0) & 0x01), ((b >> 0) & 0x01));
ha_and0 = and_gate(((a >> 0) & 0x01), ((b >> 0) & 0x01));
ha_out |= ((ha_xor0 >> 0) & 0x01ull) << 0;
ha_out |= ((ha_and0 >> 0) & 0x01ull) << 1;
return ha_out;
}
uint8_t fa(uint8_t a, uint8_t b, uint8_t cin){
uint8_t fa_out = 0;
uint8_t fa_xor0 = 0;
uint8_t fa_and0 = 0;
uint8_t fa_xor1 = 0;
uint8_t fa_and1 = 0;
uint8_t fa_or0 = 0;
fa_xor0 = xor_gate(((a >> 0) & 0x01), ((b >> 0) & 0x01));
fa_and0 = and_gate(((a >> 0) & 0x01), ((b >> 0) & 0x01));
fa_xor1 = xor_gate(((fa_xor0 >> 0) & 0x01), ((cin >> 0) & 0x01));
fa_and1 = and_gate(((fa_xor0 >> 0) & 0x01), ((cin >> 0) & 0x01));
fa_or0 = or_gate(((fa_and0 >> 0) & 0x01), ((fa_and1 >> 0) & 0x01));
fa_out |= ((fa_xor1 >> 0) & 0x01ull) << 0;
fa_out |= ((fa_or0 >> 0) & 0x01ull) << 1;
return fa_out;
}
uint64_t u_rca8(uint64_t a, uint64_t b){
uint64_t u_rca8_out = 0;
uint8_t u_rca8_ha_xor0 = 0;
uint8_t u_rca8_ha_and0 = 0;
uint8_t u_rca8_fa1_xor1 = 0;
uint8_t u_rca8_fa1_or0 = 0;
uint8_t u_rca8_fa2_xor1 = 0;
uint8_t u_rca8_fa2_or0 = 0;
uint8_t u_rca8_fa3_xor1 = 0;
uint8_t u_rca8_fa3_or0 = 0;
uint8_t u_rca8_fa4_xor1 = 0;
uint8_t u_rca8_fa4_or0 = 0;
uint8_t u_rca8_fa5_xor1 = 0;
uint8_t u_rca8_fa5_or0 = 0;
uint8_t u_rca8_fa6_xor1 = 0;
uint8_t u_rca8_fa6_or0 = 0;
uint8_t u_rca8_fa7_xor1 = 0;
uint8_t u_rca8_fa7_or0 = 0;
u_rca8_ha_xor0 = (ha(((a >> 0) & 0x01), ((b >> 0) & 0x01)) >> 0) & 0x01;
u_rca8_ha_and0 = (ha(((a >> 0) & 0x01), ((b >> 0) & 0x01)) >> 1) & 0x01;
u_rca8_fa1_xor1 = (fa(((a >> 1) & 0x01), ((b >> 1) & 0x01), ((u_rca8_ha_and0 >> 0) & 0x01)) >> 0) & 0x01;
u_rca8_fa1_or0 = (fa(((a >> 1) & 0x01), ((b >> 1) & 0x01), ((u_rca8_ha_and0 >> 0) & 0x01)) >> 1) & 0x01;
u_rca8_fa2_xor1 = (fa(((a >> 2) & 0x01), ((b >> 2) & 0x01), ((u_rca8_fa1_or0 >> 0) & 0x01)) >> 0) & 0x01;
u_rca8_fa2_or0 = (fa(((a >> 2) & 0x01), ((b >> 2) & 0x01), ((u_rca8_fa1_or0 >> 0) & 0x01)) >> 1) & 0x01;
u_rca8_fa3_xor1 = (fa(((a >> 3) & 0x01), ((b >> 3) & 0x01), ((u_rca8_fa2_or0 >> 0) & 0x01)) >> 0) & 0x01;
u_rca8_fa3_or0 = (fa(((a >> 3) & 0x01), ((b >> 3) & 0x01), ((u_rca8_fa2_or0 >> 0) & 0x01)) >> 1) & 0x01;
u_rca8_fa4_xor1 = (fa(((a >> 4) & 0x01), ((b >> 4) & 0x01), ((u_rca8_fa3_or0 >> 0) & 0x01)) >> 0) & 0x01;
u_rca8_fa4_or0 = (fa(((a >> 4) & 0x01), ((b >> 4) & 0x01), ((u_rca8_fa3_or0 >> 0) & 0x01)) >> 1) & 0x01;
u_rca8_fa5_xor1 = (fa(((a >> 5) & 0x01), ((b >> 5) & 0x01), ((u_rca8_fa4_or0 >> 0) & 0x01)) >> 0) & 0x01;
u_rca8_fa5_or0 = (fa(((a >> 5) & 0x01), ((b >> 5) & 0x01), ((u_rca8_fa4_or0 >> 0) & 0x01)) >> 1) & 0x01;
u_rca8_fa6_xor1 = (fa(((a >> 6) & 0x01), ((b >> 6) & 0x01), ((u_rca8_fa5_or0 >> 0) & 0x01)) >> 0) & 0x01;
u_rca8_fa6_or0 = (fa(((a >> 6) & 0x01), ((b >> 6) & 0x01), ((u_rca8_fa5_or0 >> 0) & 0x01)) >> 1) & 0x01;
u_rca8_fa7_xor1 = (fa(((a >> 7) & 0x01), ((b >> 7) & 0x01), ((u_rca8_fa6_or0 >> 0) & 0x01)) >> 0) & 0x01;
u_rca8_fa7_or0 = (fa(((a >> 7) & 0x01), ((b >> 7) & 0x01), ((u_rca8_fa6_or0 >> 0) & 0x01)) >> 1) & 0x01;
u_rca8_out |= ((u_rca8_ha_xor0 >> 0) & 0x01ull) << 0;
u_rca8_out |= ((u_rca8_fa1_xor1 >> 0) & 0x01ull) << 1;
u_rca8_out |= ((u_rca8_fa2_xor1 >> 0) & 0x01ull) << 2;
u_rca8_out |= ((u_rca8_fa3_xor1 >> 0) & 0x01ull) << 3;
u_rca8_out |= ((u_rca8_fa4_xor1 >> 0) & 0x01ull) << 4;
u_rca8_out |= ((u_rca8_fa5_xor1 >> 0) & 0x01ull) << 5;
u_rca8_out |= ((u_rca8_fa6_xor1 >> 0) & 0x01ull) << 6;
u_rca8_out |= ((u_rca8_fa7_xor1 >> 0) & 0x01ull) << 7;
u_rca8_out |= ((u_rca8_fa7_or0 >> 0) & 0x01ull) << 8;
return u_rca8_out;
}
uint64_t h_u_csabam8_rca_h1_v4(uint64_t a, uint64_t b){
uint64_t h_u_csabam8_rca_h1_v4_out = 0;
uint8_t h_u_csabam8_rca_h1_v4_and3_1 = 0;
uint8_t h_u_csabam8_rca_h1_v4_and4_1 = 0;
uint8_t h_u_csabam8_rca_h1_v4_and5_1 = 0;
uint8_t h_u_csabam8_rca_h1_v4_and6_1 = 0;
uint8_t h_u_csabam8_rca_h1_v4_and7_1 = 0;
uint8_t h_u_csabam8_rca_h1_v4_and2_2 = 0;
uint8_t h_u_csabam8_rca_h1_v4_ha2_2_xor0 = 0;
uint8_t h_u_csabam8_rca_h1_v4_ha2_2_and0 = 0;
uint8_t h_u_csabam8_rca_h1_v4_and3_2 = 0;
uint8_t h_u_csabam8_rca_h1_v4_ha3_2_xor0 = 0;
uint8_t h_u_csabam8_rca_h1_v4_ha3_2_and0 = 0;
uint8_t h_u_csabam8_rca_h1_v4_and4_2 = 0;
uint8_t h_u_csabam8_rca_h1_v4_ha4_2_xor0 = 0;
uint8_t h_u_csabam8_rca_h1_v4_ha4_2_and0 = 0;
uint8_t h_u_csabam8_rca_h1_v4_and5_2 = 0;
uint8_t h_u_csabam8_rca_h1_v4_ha5_2_xor0 = 0;
uint8_t h_u_csabam8_rca_h1_v4_ha5_2_and0 = 0;
uint8_t h_u_csabam8_rca_h1_v4_and6_2 = 0;
uint8_t h_u_csabam8_rca_h1_v4_ha6_2_xor0 = 0;
uint8_t h_u_csabam8_rca_h1_v4_ha6_2_and0 = 0;
uint8_t h_u_csabam8_rca_h1_v4_and7_2 = 0;
uint8_t h_u_csabam8_rca_h1_v4_and1_3 = 0;
uint8_t h_u_csabam8_rca_h1_v4_ha1_3_xor0 = 0;
uint8_t h_u_csabam8_rca_h1_v4_ha1_3_and0 = 0;
uint8_t h_u_csabam8_rca_h1_v4_and2_3 = 0;
uint8_t h_u_csabam8_rca_h1_v4_fa2_3_xor1 = 0;
uint8_t h_u_csabam8_rca_h1_v4_fa2_3_or0 = 0;
uint8_t h_u_csabam8_rca_h1_v4_and3_3 = 0;
uint8_t h_u_csabam8_rca_h1_v4_fa3_3_xor1 = 0;
uint8_t h_u_csabam8_rca_h1_v4_fa3_3_or0 = 0;
uint8_t h_u_csabam8_rca_h1_v4_and4_3 = 0;
uint8_t h_u_csabam8_rca_h1_v4_fa4_3_xor1 = 0;
uint8_t h_u_csabam8_rca_h1_v4_fa4_3_or0 = 0;
uint8_t h_u_csabam8_rca_h1_v4_and5_3 = 0;
uint8_t h_u_csabam8_rca_h1_v4_fa5_3_xor1 = 0;
uint8_t h_u_csabam8_rca_h1_v4_fa5_3_or0 = 0;
uint8_t h_u_csabam8_rca_h1_v4_and6_3 = 0;
uint8_t h_u_csabam8_rca_h1_v4_fa6_3_xor1 = 0;
uint8_t h_u_csabam8_rca_h1_v4_fa6_3_or0 = 0;
uint8_t h_u_csabam8_rca_h1_v4_and7_3 = 0;
uint8_t h_u_csabam8_rca_h1_v4_and0_4 = 0;
uint8_t h_u_csabam8_rca_h1_v4_ha0_4_xor0 = 0;
uint8_t h_u_csabam8_rca_h1_v4_ha0_4_and0 = 0;
uint8_t h_u_csabam8_rca_h1_v4_and1_4 = 0;
uint8_t h_u_csabam8_rca_h1_v4_fa1_4_xor1 = 0;
uint8_t h_u_csabam8_rca_h1_v4_fa1_4_or0 = 0;
uint8_t h_u_csabam8_rca_h1_v4_and2_4 = 0;
uint8_t h_u_csabam8_rca_h1_v4_fa2_4_xor1 = 0;
uint8_t h_u_csabam8_rca_h1_v4_fa2_4_or0 = 0;
uint8_t h_u_csabam8_rca_h1_v4_and3_4 = 0;
uint8_t h_u_csabam8_rca_h1_v4_fa3_4_xor1 = 0;
uint8_t h_u_csabam8_rca_h1_v4_fa3_4_or0 = 0;
uint8_t h_u_csabam8_rca_h1_v4_and4_4 = 0;
uint8_t h_u_csabam8_rca_h1_v4_fa4_4_xor1 = 0;
uint8_t h_u_csabam8_rca_h1_v4_fa4_4_or0 = 0;
uint8_t h_u_csabam8_rca_h1_v4_and5_4 = 0;
uint8_t h_u_csabam8_rca_h1_v4_fa5_4_xor1 = 0;
uint8_t h_u_csabam8_rca_h1_v4_fa5_4_or0 = 0;
uint8_t h_u_csabam8_rca_h1_v4_and6_4 = 0;
uint8_t h_u_csabam8_rca_h1_v4_fa6_4_xor1 = 0;
uint8_t h_u_csabam8_rca_h1_v4_fa6_4_or0 = 0;
uint8_t h_u_csabam8_rca_h1_v4_and7_4 = 0;
uint8_t h_u_csabam8_rca_h1_v4_and0_5 = 0;
uint8_t h_u_csabam8_rca_h1_v4_fa0_5_xor1 = 0;
uint8_t h_u_csabam8_rca_h1_v4_fa0_5_or0 = 0;
uint8_t h_u_csabam8_rca_h1_v4_and1_5 = 0;
uint8_t h_u_csabam8_rca_h1_v4_fa1_5_xor1 = 0;
uint8_t h_u_csabam8_rca_h1_v4_fa1_5_or0 = 0;
uint8_t h_u_csabam8_rca_h1_v4_and2_5 = 0;
uint8_t h_u_csabam8_rca_h1_v4_fa2_5_xor1 = 0;
uint8_t h_u_csabam8_rca_h1_v4_fa2_5_or0 = 0;
uint8_t h_u_csabam8_rca_h1_v4_and3_5 = 0;
uint8_t h_u_csabam8_rca_h1_v4_fa3_5_xor1 = 0;
uint8_t h_u_csabam8_rca_h1_v4_fa3_5_or0 = 0;
uint8_t h_u_csabam8_rca_h1_v4_and4_5 = 0;
uint8_t h_u_csabam8_rca_h1_v4_fa4_5_xor1 = 0;
uint8_t h_u_csabam8_rca_h1_v4_fa4_5_or0 = 0;
uint8_t h_u_csabam8_rca_h1_v4_and5_5 = 0;
uint8_t h_u_csabam8_rca_h1_v4_fa5_5_xor1 = 0;
uint8_t h_u_csabam8_rca_h1_v4_fa5_5_or0 = 0;
uint8_t h_u_csabam8_rca_h1_v4_and6_5 = 0;
uint8_t h_u_csabam8_rca_h1_v4_fa6_5_xor1 = 0;
uint8_t h_u_csabam8_rca_h1_v4_fa6_5_or0 = 0;
uint8_t h_u_csabam8_rca_h1_v4_and7_5 = 0;
uint8_t h_u_csabam8_rca_h1_v4_and0_6 = 0;
uint8_t h_u_csabam8_rca_h1_v4_fa0_6_xor1 = 0;
uint8_t h_u_csabam8_rca_h1_v4_fa0_6_or0 = 0;
uint8_t h_u_csabam8_rca_h1_v4_and1_6 = 0;
uint8_t h_u_csabam8_rca_h1_v4_fa1_6_xor1 = 0;
uint8_t h_u_csabam8_rca_h1_v4_fa1_6_or0 = 0;
uint8_t h_u_csabam8_rca_h1_v4_and2_6 = 0;
uint8_t h_u_csabam8_rca_h1_v4_fa2_6_xor1 = 0;
uint8_t h_u_csabam8_rca_h1_v4_fa2_6_or0 = 0;
uint8_t h_u_csabam8_rca_h1_v4_and3_6 = 0;
uint8_t h_u_csabam8_rca_h1_v4_fa3_6_xor1 = 0;
uint8_t h_u_csabam8_rca_h1_v4_fa3_6_or0 = 0;
uint8_t h_u_csabam8_rca_h1_v4_and4_6 = 0;
uint8_t h_u_csabam8_rca_h1_v4_fa4_6_xor1 = 0;
uint8_t h_u_csabam8_rca_h1_v4_fa4_6_or0 = 0;
uint8_t h_u_csabam8_rca_h1_v4_and5_6 = 0;
uint8_t h_u_csabam8_rca_h1_v4_fa5_6_xor1 = 0;
uint8_t h_u_csabam8_rca_h1_v4_fa5_6_or0 = 0;
uint8_t h_u_csabam8_rca_h1_v4_and6_6 = 0;
uint8_t h_u_csabam8_rca_h1_v4_fa6_6_xor1 = 0;
uint8_t h_u_csabam8_rca_h1_v4_fa6_6_or0 = 0;
uint8_t h_u_csabam8_rca_h1_v4_and7_6 = 0;
uint8_t h_u_csabam8_rca_h1_v4_and0_7 = 0;
uint8_t h_u_csabam8_rca_h1_v4_fa0_7_xor1 = 0;
uint8_t h_u_csabam8_rca_h1_v4_fa0_7_or0 = 0;
uint8_t h_u_csabam8_rca_h1_v4_and1_7 = 0;
uint8_t h_u_csabam8_rca_h1_v4_fa1_7_xor1 = 0;
uint8_t h_u_csabam8_rca_h1_v4_fa1_7_or0 = 0;
uint8_t h_u_csabam8_rca_h1_v4_and2_7 = 0;
uint8_t h_u_csabam8_rca_h1_v4_fa2_7_xor1 = 0;
uint8_t h_u_csabam8_rca_h1_v4_fa2_7_or0 = 0;
uint8_t h_u_csabam8_rca_h1_v4_and3_7 = 0;
uint8_t h_u_csabam8_rca_h1_v4_fa3_7_xor1 = 0;
uint8_t h_u_csabam8_rca_h1_v4_fa3_7_or0 = 0;
uint8_t h_u_csabam8_rca_h1_v4_and4_7 = 0;
uint8_t h_u_csabam8_rca_h1_v4_fa4_7_xor1 = 0;
uint8_t h_u_csabam8_rca_h1_v4_fa4_7_or0 = 0;
uint8_t h_u_csabam8_rca_h1_v4_and5_7 = 0;
uint8_t h_u_csabam8_rca_h1_v4_fa5_7_xor1 = 0;
uint8_t h_u_csabam8_rca_h1_v4_fa5_7_or0 = 0;
uint8_t h_u_csabam8_rca_h1_v4_and6_7 = 0;
uint8_t h_u_csabam8_rca_h1_v4_fa6_7_xor1 = 0;
uint8_t h_u_csabam8_rca_h1_v4_fa6_7_or0 = 0;
uint8_t h_u_csabam8_rca_h1_v4_and7_7 = 0;
uint64_t h_u_csabam8_rca_h1_v4_u_rca8_a = 0;
uint64_t h_u_csabam8_rca_h1_v4_u_rca8_b = 0;
uint64_t h_u_csabam8_rca_h1_v4_u_rca8_out = 0;
h_u_csabam8_rca_h1_v4_and3_1 = and_gate(((a >> 3) & 0x01), ((b >> 1) & 0x01));
h_u_csabam8_rca_h1_v4_and4_1 = and_gate(((a >> 4) & 0x01), ((b >> 1) & 0x01));
h_u_csabam8_rca_h1_v4_and5_1 = and_gate(((a >> 5) & 0x01), ((b >> 1) & 0x01));
h_u_csabam8_rca_h1_v4_and6_1 = and_gate(((a >> 6) & 0x01), ((b >> 1) & 0x01));
h_u_csabam8_rca_h1_v4_and7_1 = and_gate(((a >> 7) & 0x01), ((b >> 1) & 0x01));
h_u_csabam8_rca_h1_v4_and2_2 = and_gate(((a >> 2) & 0x01), ((b >> 2) & 0x01));
h_u_csabam8_rca_h1_v4_ha2_2_xor0 = (ha(((h_u_csabam8_rca_h1_v4_and2_2 >> 0) & 0x01), ((h_u_csabam8_rca_h1_v4_and3_1 >> 0) & 0x01)) >> 0) & 0x01;
h_u_csabam8_rca_h1_v4_ha2_2_and0 = (ha(((h_u_csabam8_rca_h1_v4_and2_2 >> 0) & 0x01), ((h_u_csabam8_rca_h1_v4_and3_1 >> 0) & 0x01)) >> 1) & 0x01;
h_u_csabam8_rca_h1_v4_and3_2 = and_gate(((a >> 3) & 0x01), ((b >> 2) & 0x01));
h_u_csabam8_rca_h1_v4_ha3_2_xor0 = (ha(((h_u_csabam8_rca_h1_v4_and3_2 >> 0) & 0x01), ((h_u_csabam8_rca_h1_v4_and4_1 >> 0) & 0x01)) >> 0) & 0x01;
h_u_csabam8_rca_h1_v4_ha3_2_and0 = (ha(((h_u_csabam8_rca_h1_v4_and3_2 >> 0) & 0x01), ((h_u_csabam8_rca_h1_v4_and4_1 >> 0) & 0x01)) >> 1) & 0x01;
h_u_csabam8_rca_h1_v4_and4_2 = and_gate(((a >> 4) & 0x01), ((b >> 2) & 0x01));
h_u_csabam8_rca_h1_v4_ha4_2_xor0 = (ha(((h_u_csabam8_rca_h1_v4_and4_2 >> 0) & 0x01), ((h_u_csabam8_rca_h1_v4_and5_1 >> 0) & 0x01)) >> 0) & 0x01;
h_u_csabam8_rca_h1_v4_ha4_2_and0 = (ha(((h_u_csabam8_rca_h1_v4_and4_2 >> 0) & 0x01), ((h_u_csabam8_rca_h1_v4_and5_1 >> 0) & 0x01)) >> 1) & 0x01;
h_u_csabam8_rca_h1_v4_and5_2 = and_gate(((a >> 5) & 0x01), ((b >> 2) & 0x01));
h_u_csabam8_rca_h1_v4_ha5_2_xor0 = (ha(((h_u_csabam8_rca_h1_v4_and5_2 >> 0) & 0x01), ((h_u_csabam8_rca_h1_v4_and6_1 >> 0) & 0x01)) >> 0) & 0x01;
h_u_csabam8_rca_h1_v4_ha5_2_and0 = (ha(((h_u_csabam8_rca_h1_v4_and5_2 >> 0) & 0x01), ((h_u_csabam8_rca_h1_v4_and6_1 >> 0) & 0x01)) >> 1) & 0x01;
h_u_csabam8_rca_h1_v4_and6_2 = and_gate(((a >> 6) & 0x01), ((b >> 2) & 0x01));
h_u_csabam8_rca_h1_v4_ha6_2_xor0 = (ha(((h_u_csabam8_rca_h1_v4_and6_2 >> 0) & 0x01), ((h_u_csabam8_rca_h1_v4_and7_1 >> 0) & 0x01)) >> 0) & 0x01;
h_u_csabam8_rca_h1_v4_ha6_2_and0 = (ha(((h_u_csabam8_rca_h1_v4_and6_2 >> 0) & 0x01), ((h_u_csabam8_rca_h1_v4_and7_1 >> 0) & 0x01)) >> 1) & 0x01;
h_u_csabam8_rca_h1_v4_and7_2 = and_gate(((a >> 7) & 0x01), ((b >> 2) & 0x01));
h_u_csabam8_rca_h1_v4_and1_3 = and_gate(((a >> 1) & 0x01), ((b >> 3) & 0x01));
h_u_csabam8_rca_h1_v4_ha1_3_xor0 = (ha(((h_u_csabam8_rca_h1_v4_and1_3 >> 0) & 0x01), ((h_u_csabam8_rca_h1_v4_ha2_2_xor0 >> 0) & 0x01)) >> 0) & 0x01;
h_u_csabam8_rca_h1_v4_ha1_3_and0 = (ha(((h_u_csabam8_rca_h1_v4_and1_3 >> 0) & 0x01), ((h_u_csabam8_rca_h1_v4_ha2_2_xor0 >> 0) & 0x01)) >> 1) & 0x01;
h_u_csabam8_rca_h1_v4_and2_3 = and_gate(((a >> 2) & 0x01), ((b >> 3) & 0x01));
h_u_csabam8_rca_h1_v4_fa2_3_xor1 = (fa(((h_u_csabam8_rca_h1_v4_and2_3 >> 0) & 0x01), ((h_u_csabam8_rca_h1_v4_ha3_2_xor0 >> 0) & 0x01), ((h_u_csabam8_rca_h1_v4_ha2_2_and0 >> 0) & 0x01)) >> 0) & 0x01;
h_u_csabam8_rca_h1_v4_fa2_3_or0 = (fa(((h_u_csabam8_rca_h1_v4_and2_3 >> 0) & 0x01), ((h_u_csabam8_rca_h1_v4_ha3_2_xor0 >> 0) & 0x01), ((h_u_csabam8_rca_h1_v4_ha2_2_and0 >> 0) & 0x01)) >> 1) & 0x01;
h_u_csabam8_rca_h1_v4_and3_3 = and_gate(((a >> 3) & 0x01), ((b >> 3) & 0x01));
h_u_csabam8_rca_h1_v4_fa3_3_xor1 = (fa(((h_u_csabam8_rca_h1_v4_and3_3 >> 0) & 0x01), ((h_u_csabam8_rca_h1_v4_ha4_2_xor0 >> 0) & 0x01), ((h_u_csabam8_rca_h1_v4_ha3_2_and0 >> 0) & 0x01)) >> 0) & 0x01;
h_u_csabam8_rca_h1_v4_fa3_3_or0 = (fa(((h_u_csabam8_rca_h1_v4_and3_3 >> 0) & 0x01), ((h_u_csabam8_rca_h1_v4_ha4_2_xor0 >> 0) & 0x01), ((h_u_csabam8_rca_h1_v4_ha3_2_and0 >> 0) & 0x01)) >> 1) & 0x01;
h_u_csabam8_rca_h1_v4_and4_3 = and_gate(((a >> 4) & 0x01), ((b >> 3) & 0x01));
h_u_csabam8_rca_h1_v4_fa4_3_xor1 = (fa(((h_u_csabam8_rca_h1_v4_and4_3 >> 0) & 0x01), ((h_u_csabam8_rca_h1_v4_ha5_2_xor0 >> 0) & 0x01), ((h_u_csabam8_rca_h1_v4_ha4_2_and0 >> 0) & 0x01)) >> 0) & 0x01;
h_u_csabam8_rca_h1_v4_fa4_3_or0 = (fa(((h_u_csabam8_rca_h1_v4_and4_3 >> 0) & 0x01), ((h_u_csabam8_rca_h1_v4_ha5_2_xor0 >> 0) & 0x01), ((h_u_csabam8_rca_h1_v4_ha4_2_and0 >> 0) & 0x01)) >> 1) & 0x01;
h_u_csabam8_rca_h1_v4_and5_3 = and_gate(((a >> 5) & 0x01), ((b >> 3) & 0x01));
h_u_csabam8_rca_h1_v4_fa5_3_xor1 = (fa(((h_u_csabam8_rca_h1_v4_and5_3 >> 0) & 0x01), ((h_u_csabam8_rca_h1_v4_ha6_2_xor0 >> 0) & 0x01), ((h_u_csabam8_rca_h1_v4_ha5_2_and0 >> 0) & 0x01)) >> 0) & 0x01;
h_u_csabam8_rca_h1_v4_fa5_3_or0 = (fa(((h_u_csabam8_rca_h1_v4_and5_3 >> 0) & 0x01), ((h_u_csabam8_rca_h1_v4_ha6_2_xor0 >> 0) & 0x01), ((h_u_csabam8_rca_h1_v4_ha5_2_and0 >> 0) & 0x01)) >> 1) & 0x01;
h_u_csabam8_rca_h1_v4_and6_3 = and_gate(((a >> 6) & 0x01), ((b >> 3) & 0x01));
h_u_csabam8_rca_h1_v4_fa6_3_xor1 = (fa(((h_u_csabam8_rca_h1_v4_and6_3 >> 0) & 0x01), ((h_u_csabam8_rca_h1_v4_and7_2 >> 0) & 0x01), ((h_u_csabam8_rca_h1_v4_ha6_2_and0 >> 0) & 0x01)) >> 0) & 0x01;
h_u_csabam8_rca_h1_v4_fa6_3_or0 = (fa(((h_u_csabam8_rca_h1_v4_and6_3 >> 0) & 0x01), ((h_u_csabam8_rca_h1_v4_and7_2 >> 0) & 0x01), ((h_u_csabam8_rca_h1_v4_ha6_2_and0 >> 0) & 0x01)) >> 1) & 0x01;
h_u_csabam8_rca_h1_v4_and7_3 = and_gate(((a >> 7) & 0x01), ((b >> 3) & 0x01));
h_u_csabam8_rca_h1_v4_and0_4 = and_gate(((a >> 0) & 0x01), ((b >> 4) & 0x01));
h_u_csabam8_rca_h1_v4_ha0_4_xor0 = (ha(((h_u_csabam8_rca_h1_v4_and0_4 >> 0) & 0x01), ((h_u_csabam8_rca_h1_v4_ha1_3_xor0 >> 0) & 0x01)) >> 0) & 0x01;
h_u_csabam8_rca_h1_v4_ha0_4_and0 = (ha(((h_u_csabam8_rca_h1_v4_and0_4 >> 0) & 0x01), ((h_u_csabam8_rca_h1_v4_ha1_3_xor0 >> 0) & 0x01)) >> 1) & 0x01;
h_u_csabam8_rca_h1_v4_and1_4 = and_gate(((a >> 1) & 0x01), ((b >> 4) & 0x01));
h_u_csabam8_rca_h1_v4_fa1_4_xor1 = (fa(((h_u_csabam8_rca_h1_v4_and1_4 >> 0) & 0x01), ((h_u_csabam8_rca_h1_v4_fa2_3_xor1 >> 0) & 0x01), ((h_u_csabam8_rca_h1_v4_ha1_3_and0 >> 0) & 0x01)) >> 0) & 0x01;
h_u_csabam8_rca_h1_v4_fa1_4_or0 = (fa(((h_u_csabam8_rca_h1_v4_and1_4 >> 0) & 0x01), ((h_u_csabam8_rca_h1_v4_fa2_3_xor1 >> 0) & 0x01), ((h_u_csabam8_rca_h1_v4_ha1_3_and0 >> 0) & 0x01)) >> 1) & 0x01;
h_u_csabam8_rca_h1_v4_and2_4 = and_gate(((a >> 2) & 0x01), ((b >> 4) & 0x01));
h_u_csabam8_rca_h1_v4_fa2_4_xor1 = (fa(((h_u_csabam8_rca_h1_v4_and2_4 >> 0) & 0x01), ((h_u_csabam8_rca_h1_v4_fa3_3_xor1 >> 0) & 0x01), ((h_u_csabam8_rca_h1_v4_fa2_3_or0 >> 0) & 0x01)) >> 0) & 0x01;
h_u_csabam8_rca_h1_v4_fa2_4_or0 = (fa(((h_u_csabam8_rca_h1_v4_and2_4 >> 0) & 0x01), ((h_u_csabam8_rca_h1_v4_fa3_3_xor1 >> 0) & 0x01), ((h_u_csabam8_rca_h1_v4_fa2_3_or0 >> 0) & 0x01)) >> 1) & 0x01;
h_u_csabam8_rca_h1_v4_and3_4 = and_gate(((a >> 3) & 0x01), ((b >> 4) & 0x01));
h_u_csabam8_rca_h1_v4_fa3_4_xor1 = (fa(((h_u_csabam8_rca_h1_v4_and3_4 >> 0) & 0x01), ((h_u_csabam8_rca_h1_v4_fa4_3_xor1 >> 0) & 0x01), ((h_u_csabam8_rca_h1_v4_fa3_3_or0 >> 0) & 0x01)) >> 0) & 0x01;
h_u_csabam8_rca_h1_v4_fa3_4_or0 = (fa(((h_u_csabam8_rca_h1_v4_and3_4 >> 0) & 0x01), ((h_u_csabam8_rca_h1_v4_fa4_3_xor1 >> 0) & 0x01), ((h_u_csabam8_rca_h1_v4_fa3_3_or0 >> 0) & 0x01)) >> 1) & 0x01;
h_u_csabam8_rca_h1_v4_and4_4 = and_gate(((a >> 4) & 0x01), ((b >> 4) & 0x01));
h_u_csabam8_rca_h1_v4_fa4_4_xor1 = (fa(((h_u_csabam8_rca_h1_v4_and4_4 >> 0) & 0x01), ((h_u_csabam8_rca_h1_v4_fa5_3_xor1 >> 0) & 0x01), ((h_u_csabam8_rca_h1_v4_fa4_3_or0 >> 0) & 0x01)) >> 0) & 0x01;
h_u_csabam8_rca_h1_v4_fa4_4_or0 = (fa(((h_u_csabam8_rca_h1_v4_and4_4 >> 0) & 0x01), ((h_u_csabam8_rca_h1_v4_fa5_3_xor1 >> 0) & 0x01), ((h_u_csabam8_rca_h1_v4_fa4_3_or0 >> 0) & 0x01)) >> 1) & 0x01;
h_u_csabam8_rca_h1_v4_and5_4 = and_gate(((a >> 5) & 0x01), ((b >> 4) & 0x01));
h_u_csabam8_rca_h1_v4_fa5_4_xor1 = (fa(((h_u_csabam8_rca_h1_v4_and5_4 >> 0) & 0x01), ((h_u_csabam8_rca_h1_v4_fa6_3_xor1 >> 0) & 0x01), ((h_u_csabam8_rca_h1_v4_fa5_3_or0 >> 0) & 0x01)) >> 0) & 0x01;
h_u_csabam8_rca_h1_v4_fa5_4_or0 = (fa(((h_u_csabam8_rca_h1_v4_and5_4 >> 0) & 0x01), ((h_u_csabam8_rca_h1_v4_fa6_3_xor1 >> 0) & 0x01), ((h_u_csabam8_rca_h1_v4_fa5_3_or0 >> 0) & 0x01)) >> 1) & 0x01;
h_u_csabam8_rca_h1_v4_and6_4 = and_gate(((a >> 6) & 0x01), ((b >> 4) & 0x01));
h_u_csabam8_rca_h1_v4_fa6_4_xor1 = (fa(((h_u_csabam8_rca_h1_v4_and6_4 >> 0) & 0x01), ((h_u_csabam8_rca_h1_v4_and7_3 >> 0) & 0x01), ((h_u_csabam8_rca_h1_v4_fa6_3_or0 >> 0) & 0x01)) >> 0) & 0x01;
h_u_csabam8_rca_h1_v4_fa6_4_or0 = (fa(((h_u_csabam8_rca_h1_v4_and6_4 >> 0) & 0x01), ((h_u_csabam8_rca_h1_v4_and7_3 >> 0) & 0x01), ((h_u_csabam8_rca_h1_v4_fa6_3_or0 >> 0) & 0x01)) >> 1) & 0x01;
h_u_csabam8_rca_h1_v4_and7_4 = and_gate(((a >> 7) & 0x01), ((b >> 4) & 0x01));
h_u_csabam8_rca_h1_v4_and0_5 = and_gate(((a >> 0) & 0x01), ((b >> 5) & 0x01));
h_u_csabam8_rca_h1_v4_fa0_5_xor1 = (fa(((h_u_csabam8_rca_h1_v4_and0_5 >> 0) & 0x01), ((h_u_csabam8_rca_h1_v4_fa1_4_xor1 >> 0) & 0x01), ((h_u_csabam8_rca_h1_v4_ha0_4_and0 >> 0) & 0x01)) >> 0) & 0x01;
h_u_csabam8_rca_h1_v4_fa0_5_or0 = (fa(((h_u_csabam8_rca_h1_v4_and0_5 >> 0) & 0x01), ((h_u_csabam8_rca_h1_v4_fa1_4_xor1 >> 0) & 0x01), ((h_u_csabam8_rca_h1_v4_ha0_4_and0 >> 0) & 0x01)) >> 1) & 0x01;
h_u_csabam8_rca_h1_v4_and1_5 = and_gate(((a >> 1) & 0x01), ((b >> 5) & 0x01));
h_u_csabam8_rca_h1_v4_fa1_5_xor1 = (fa(((h_u_csabam8_rca_h1_v4_and1_5 >> 0) & 0x01), ((h_u_csabam8_rca_h1_v4_fa2_4_xor1 >> 0) & 0x01), ((h_u_csabam8_rca_h1_v4_fa1_4_or0 >> 0) & 0x01)) >> 0) & 0x01;
h_u_csabam8_rca_h1_v4_fa1_5_or0 = (fa(((h_u_csabam8_rca_h1_v4_and1_5 >> 0) & 0x01), ((h_u_csabam8_rca_h1_v4_fa2_4_xor1 >> 0) & 0x01), ((h_u_csabam8_rca_h1_v4_fa1_4_or0 >> 0) & 0x01)) >> 1) & 0x01;
h_u_csabam8_rca_h1_v4_and2_5 = and_gate(((a >> 2) & 0x01), ((b >> 5) & 0x01));
h_u_csabam8_rca_h1_v4_fa2_5_xor1 = (fa(((h_u_csabam8_rca_h1_v4_and2_5 >> 0) & 0x01), ((h_u_csabam8_rca_h1_v4_fa3_4_xor1 >> 0) & 0x01), ((h_u_csabam8_rca_h1_v4_fa2_4_or0 >> 0) & 0x01)) >> 0) & 0x01;
h_u_csabam8_rca_h1_v4_fa2_5_or0 = (fa(((h_u_csabam8_rca_h1_v4_and2_5 >> 0) & 0x01), ((h_u_csabam8_rca_h1_v4_fa3_4_xor1 >> 0) & 0x01), ((h_u_csabam8_rca_h1_v4_fa2_4_or0 >> 0) & 0x01)) >> 1) & 0x01;
h_u_csabam8_rca_h1_v4_and3_5 = and_gate(((a >> 3) & 0x01), ((b >> 5) & 0x01));
h_u_csabam8_rca_h1_v4_fa3_5_xor1 = (fa(((h_u_csabam8_rca_h1_v4_and3_5 >> 0) & 0x01), ((h_u_csabam8_rca_h1_v4_fa4_4_xor1 >> 0) & 0x01), ((h_u_csabam8_rca_h1_v4_fa3_4_or0 >> 0) & 0x01)) >> 0) & 0x01;
h_u_csabam8_rca_h1_v4_fa3_5_or0 = (fa(((h_u_csabam8_rca_h1_v4_and3_5 >> 0) & 0x01), ((h_u_csabam8_rca_h1_v4_fa4_4_xor1 >> 0) & 0x01), ((h_u_csabam8_rca_h1_v4_fa3_4_or0 >> 0) & 0x01)) >> 1) & 0x01;
h_u_csabam8_rca_h1_v4_and4_5 = and_gate(((a >> 4) & 0x01), ((b >> 5) & 0x01));
h_u_csabam8_rca_h1_v4_fa4_5_xor1 = (fa(((h_u_csabam8_rca_h1_v4_and4_5 >> 0) & 0x01), ((h_u_csabam8_rca_h1_v4_fa5_4_xor1 >> 0) & 0x01), ((h_u_csabam8_rca_h1_v4_fa4_4_or0 >> 0) & 0x01)) >> 0) & 0x01;
h_u_csabam8_rca_h1_v4_fa4_5_or0 = (fa(((h_u_csabam8_rca_h1_v4_and4_5 >> 0) & 0x01), ((h_u_csabam8_rca_h1_v4_fa5_4_xor1 >> 0) & 0x01), ((h_u_csabam8_rca_h1_v4_fa4_4_or0 >> 0) & 0x01)) >> 1) & 0x01;
h_u_csabam8_rca_h1_v4_and5_5 = and_gate(((a >> 5) & 0x01), ((b >> 5) & 0x01));
h_u_csabam8_rca_h1_v4_fa5_5_xor1 = (fa(((h_u_csabam8_rca_h1_v4_and5_5 >> 0) & 0x01), ((h_u_csabam8_rca_h1_v4_fa6_4_xor1 >> 0) & 0x01), ((h_u_csabam8_rca_h1_v4_fa5_4_or0 >> 0) & 0x01)) >> 0) & 0x01;
h_u_csabam8_rca_h1_v4_fa5_5_or0 = (fa(((h_u_csabam8_rca_h1_v4_and5_5 >> 0) & 0x01), ((h_u_csabam8_rca_h1_v4_fa6_4_xor1 >> 0) & 0x01), ((h_u_csabam8_rca_h1_v4_fa5_4_or0 >> 0) & 0x01)) >> 1) & 0x01;
h_u_csabam8_rca_h1_v4_and6_5 = and_gate(((a >> 6) & 0x01), ((b >> 5) & 0x01));
h_u_csabam8_rca_h1_v4_fa6_5_xor1 = (fa(((h_u_csabam8_rca_h1_v4_and6_5 >> 0) & 0x01), ((h_u_csabam8_rca_h1_v4_and7_4 >> 0) & 0x01), ((h_u_csabam8_rca_h1_v4_fa6_4_or0 >> 0) & 0x01)) >> 0) & 0x01;
h_u_csabam8_rca_h1_v4_fa6_5_or0 = (fa(((h_u_csabam8_rca_h1_v4_and6_5 >> 0) & 0x01), ((h_u_csabam8_rca_h1_v4_and7_4 >> 0) & 0x01), ((h_u_csabam8_rca_h1_v4_fa6_4_or0 >> 0) & 0x01)) >> 1) & 0x01;
h_u_csabam8_rca_h1_v4_and7_5 = and_gate(((a >> 7) & 0x01), ((b >> 5) & 0x01));
h_u_csabam8_rca_h1_v4_and0_6 = and_gate(((a >> 0) & 0x01), ((b >> 6) & 0x01));
h_u_csabam8_rca_h1_v4_fa0_6_xor1 = (fa(((h_u_csabam8_rca_h1_v4_and0_6 >> 0) & 0x01), ((h_u_csabam8_rca_h1_v4_fa1_5_xor1 >> 0) & 0x01), ((h_u_csabam8_rca_h1_v4_fa0_5_or0 >> 0) & 0x01)) >> 0) & 0x01;
h_u_csabam8_rca_h1_v4_fa0_6_or0 = (fa(((h_u_csabam8_rca_h1_v4_and0_6 >> 0) & 0x01), ((h_u_csabam8_rca_h1_v4_fa1_5_xor1 >> 0) & 0x01), ((h_u_csabam8_rca_h1_v4_fa0_5_or0 >> 0) & 0x01)) >> 1) & 0x01;
h_u_csabam8_rca_h1_v4_and1_6 = and_gate(((a >> 1) & 0x01), ((b >> 6) & 0x01));
h_u_csabam8_rca_h1_v4_fa1_6_xor1 = (fa(((h_u_csabam8_rca_h1_v4_and1_6 >> 0) & 0x01), ((h_u_csabam8_rca_h1_v4_fa2_5_xor1 >> 0) & 0x01), ((h_u_csabam8_rca_h1_v4_fa1_5_or0 >> 0) & 0x01)) >> 0) & 0x01;
h_u_csabam8_rca_h1_v4_fa1_6_or0 = (fa(((h_u_csabam8_rca_h1_v4_and1_6 >> 0) & 0x01), ((h_u_csabam8_rca_h1_v4_fa2_5_xor1 >> 0) & 0x01), ((h_u_csabam8_rca_h1_v4_fa1_5_or0 >> 0) & 0x01)) >> 1) & 0x01;
h_u_csabam8_rca_h1_v4_and2_6 = and_gate(((a >> 2) & 0x01), ((b >> 6) & 0x01));
h_u_csabam8_rca_h1_v4_fa2_6_xor1 = (fa(((h_u_csabam8_rca_h1_v4_and2_6 >> 0) & 0x01), ((h_u_csabam8_rca_h1_v4_fa3_5_xor1 >> 0) & 0x01), ((h_u_csabam8_rca_h1_v4_fa2_5_or0 >> 0) & 0x01)) >> 0) & 0x01;
h_u_csabam8_rca_h1_v4_fa2_6_or0 = (fa(((h_u_csabam8_rca_h1_v4_and2_6 >> 0) & 0x01), ((h_u_csabam8_rca_h1_v4_fa3_5_xor1 >> 0) & 0x01), ((h_u_csabam8_rca_h1_v4_fa2_5_or0 >> 0) & 0x01)) >> 1) & 0x01;
h_u_csabam8_rca_h1_v4_and3_6 = and_gate(((a >> 3) & 0x01), ((b >> 6) & 0x01));
h_u_csabam8_rca_h1_v4_fa3_6_xor1 = (fa(((h_u_csabam8_rca_h1_v4_and3_6 >> 0) & 0x01), ((h_u_csabam8_rca_h1_v4_fa4_5_xor1 >> 0) & 0x01), ((h_u_csabam8_rca_h1_v4_fa3_5_or0 >> 0) & 0x01)) >> 0) & 0x01;
h_u_csabam8_rca_h1_v4_fa3_6_or0 = (fa(((h_u_csabam8_rca_h1_v4_and3_6 >> 0) & 0x01), ((h_u_csabam8_rca_h1_v4_fa4_5_xor1 >> 0) & 0x01), ((h_u_csabam8_rca_h1_v4_fa3_5_or0 >> 0) & 0x01)) >> 1) & 0x01;
h_u_csabam8_rca_h1_v4_and4_6 = and_gate(((a >> 4) & 0x01), ((b >> 6) & 0x01));
h_u_csabam8_rca_h1_v4_fa4_6_xor1 = (fa(((h_u_csabam8_rca_h1_v4_and4_6 >> 0) & 0x01), ((h_u_csabam8_rca_h1_v4_fa5_5_xor1 >> 0) & 0x01), ((h_u_csabam8_rca_h1_v4_fa4_5_or0 >> 0) & 0x01)) >> 0) & 0x01;
h_u_csabam8_rca_h1_v4_fa4_6_or0 = (fa(((h_u_csabam8_rca_h1_v4_and4_6 >> 0) & 0x01), ((h_u_csabam8_rca_h1_v4_fa5_5_xor1 >> 0) & 0x01), ((h_u_csabam8_rca_h1_v4_fa4_5_or0 >> 0) & 0x01)) >> 1) & 0x01;
h_u_csabam8_rca_h1_v4_and5_6 = and_gate(((a >> 5) & 0x01), ((b >> 6) & 0x01));
h_u_csabam8_rca_h1_v4_fa5_6_xor1 = (fa(((h_u_csabam8_rca_h1_v4_and5_6 >> 0) & 0x01), ((h_u_csabam8_rca_h1_v4_fa6_5_xor1 >> 0) & 0x01), ((h_u_csabam8_rca_h1_v4_fa5_5_or0 >> 0) & 0x01)) >> 0) & 0x01;
h_u_csabam8_rca_h1_v4_fa5_6_or0 = (fa(((h_u_csabam8_rca_h1_v4_and5_6 >> 0) & 0x01), ((h_u_csabam8_rca_h1_v4_fa6_5_xor1 >> 0) & 0x01), ((h_u_csabam8_rca_h1_v4_fa5_5_or0 >> 0) & 0x01)) >> 1) & 0x01;
h_u_csabam8_rca_h1_v4_and6_6 = and_gate(((a >> 6) & 0x01), ((b >> 6) & 0x01));
h_u_csabam8_rca_h1_v4_fa6_6_xor1 = (fa(((h_u_csabam8_rca_h1_v4_and6_6 >> 0) & 0x01), ((h_u_csabam8_rca_h1_v4_and7_5 >> 0) & 0x01), ((h_u_csabam8_rca_h1_v4_fa6_5_or0 >> 0) & 0x01)) >> 0) & 0x01;
h_u_csabam8_rca_h1_v4_fa6_6_or0 = (fa(((h_u_csabam8_rca_h1_v4_and6_6 >> 0) & 0x01), ((h_u_csabam8_rca_h1_v4_and7_5 >> 0) & 0x01), ((h_u_csabam8_rca_h1_v4_fa6_5_or0 >> 0) & 0x01)) >> 1) & 0x01;
h_u_csabam8_rca_h1_v4_and7_6 = and_gate(((a >> 7) & 0x01), ((b >> 6) & 0x01));
h_u_csabam8_rca_h1_v4_and0_7 = and_gate(((a >> 0) & 0x01), ((b >> 7) & 0x01));
h_u_csabam8_rca_h1_v4_fa0_7_xor1 = (fa(((h_u_csabam8_rca_h1_v4_and0_7 >> 0) & 0x01), ((h_u_csabam8_rca_h1_v4_fa1_6_xor1 >> 0) & 0x01), ((h_u_csabam8_rca_h1_v4_fa0_6_or0 >> 0) & 0x01)) >> 0) & 0x01;
h_u_csabam8_rca_h1_v4_fa0_7_or0 = (fa(((h_u_csabam8_rca_h1_v4_and0_7 >> 0) & 0x01), ((h_u_csabam8_rca_h1_v4_fa1_6_xor1 >> 0) & 0x01), ((h_u_csabam8_rca_h1_v4_fa0_6_or0 >> 0) & 0x01)) >> 1) & 0x01;
h_u_csabam8_rca_h1_v4_and1_7 = and_gate(((a >> 1) & 0x01), ((b >> 7) & 0x01));
h_u_csabam8_rca_h1_v4_fa1_7_xor1 = (fa(((h_u_csabam8_rca_h1_v4_and1_7 >> 0) & 0x01), ((h_u_csabam8_rca_h1_v4_fa2_6_xor1 >> 0) & 0x01), ((h_u_csabam8_rca_h1_v4_fa1_6_or0 >> 0) & 0x01)) >> 0) & 0x01;
h_u_csabam8_rca_h1_v4_fa1_7_or0 = (fa(((h_u_csabam8_rca_h1_v4_and1_7 >> 0) & 0x01), ((h_u_csabam8_rca_h1_v4_fa2_6_xor1 >> 0) & 0x01), ((h_u_csabam8_rca_h1_v4_fa1_6_or0 >> 0) & 0x01)) >> 1) & 0x01;
h_u_csabam8_rca_h1_v4_and2_7 = and_gate(((a >> 2) & 0x01), ((b >> 7) & 0x01));
h_u_csabam8_rca_h1_v4_fa2_7_xor1 = (fa(((h_u_csabam8_rca_h1_v4_and2_7 >> 0) & 0x01), ((h_u_csabam8_rca_h1_v4_fa3_6_xor1 >> 0) & 0x01), ((h_u_csabam8_rca_h1_v4_fa2_6_or0 >> 0) & 0x01)) >> 0) & 0x01;
h_u_csabam8_rca_h1_v4_fa2_7_or0 = (fa(((h_u_csabam8_rca_h1_v4_and2_7 >> 0) & 0x01), ((h_u_csabam8_rca_h1_v4_fa3_6_xor1 >> 0) & 0x01), ((h_u_csabam8_rca_h1_v4_fa2_6_or0 >> 0) & 0x01)) >> 1) & 0x01;
h_u_csabam8_rca_h1_v4_and3_7 = and_gate(((a >> 3) & 0x01), ((b >> 7) & 0x01));
h_u_csabam8_rca_h1_v4_fa3_7_xor1 = (fa(((h_u_csabam8_rca_h1_v4_and3_7 >> 0) & 0x01), ((h_u_csabam8_rca_h1_v4_fa4_6_xor1 >> 0) & 0x01), ((h_u_csabam8_rca_h1_v4_fa3_6_or0 >> 0) & 0x01)) >> 0) & 0x01;
h_u_csabam8_rca_h1_v4_fa3_7_or0 = (fa(((h_u_csabam8_rca_h1_v4_and3_7 >> 0) & 0x01), ((h_u_csabam8_rca_h1_v4_fa4_6_xor1 >> 0) & 0x01), ((h_u_csabam8_rca_h1_v4_fa3_6_or0 >> 0) & 0x01)) >> 1) & 0x01;
h_u_csabam8_rca_h1_v4_and4_7 = and_gate(((a >> 4) & 0x01), ((b >> 7) & 0x01));
h_u_csabam8_rca_h1_v4_fa4_7_xor1 = (fa(((h_u_csabam8_rca_h1_v4_and4_7 >> 0) & 0x01), ((h_u_csabam8_rca_h1_v4_fa5_6_xor1 >> 0) & 0x01), ((h_u_csabam8_rca_h1_v4_fa4_6_or0 >> 0) & 0x01)) >> 0) & 0x01;
h_u_csabam8_rca_h1_v4_fa4_7_or0 = (fa(((h_u_csabam8_rca_h1_v4_and4_7 >> 0) & 0x01), ((h_u_csabam8_rca_h1_v4_fa5_6_xor1 >> 0) & 0x01), ((h_u_csabam8_rca_h1_v4_fa4_6_or0 >> 0) & 0x01)) >> 1) & 0x01;
h_u_csabam8_rca_h1_v4_and5_7 = and_gate(((a >> 5) & 0x01), ((b >> 7) & 0x01));
h_u_csabam8_rca_h1_v4_fa5_7_xor1 = (fa(((h_u_csabam8_rca_h1_v4_and5_7 >> 0) & 0x01), ((h_u_csabam8_rca_h1_v4_fa6_6_xor1 >> 0) & 0x01), ((h_u_csabam8_rca_h1_v4_fa5_6_or0 >> 0) & 0x01)) >> 0) & 0x01;
h_u_csabam8_rca_h1_v4_fa5_7_or0 = (fa(((h_u_csabam8_rca_h1_v4_and5_7 >> 0) & 0x01), ((h_u_csabam8_rca_h1_v4_fa6_6_xor1 >> 0) & 0x01), ((h_u_csabam8_rca_h1_v4_fa5_6_or0 >> 0) & 0x01)) >> 1) & 0x01;
h_u_csabam8_rca_h1_v4_and6_7 = and_gate(((a >> 6) & 0x01), ((b >> 7) & 0x01));
h_u_csabam8_rca_h1_v4_fa6_7_xor1 = (fa(((h_u_csabam8_rca_h1_v4_and6_7 >> 0) & 0x01), ((h_u_csabam8_rca_h1_v4_and7_6 >> 0) & 0x01), ((h_u_csabam8_rca_h1_v4_fa6_6_or0 >> 0) & 0x01)) >> 0) & 0x01;
h_u_csabam8_rca_h1_v4_fa6_7_or0 = (fa(((h_u_csabam8_rca_h1_v4_and6_7 >> 0) & 0x01), ((h_u_csabam8_rca_h1_v4_and7_6 >> 0) & 0x01), ((h_u_csabam8_rca_h1_v4_fa6_6_or0 >> 0) & 0x01)) >> 1) & 0x01;
h_u_csabam8_rca_h1_v4_and7_7 = and_gate(((a >> 7) & 0x01), ((b >> 7) & 0x01));
h_u_csabam8_rca_h1_v4_u_rca8_a |= ((h_u_csabam8_rca_h1_v4_fa1_7_xor1 >> 0) & 0x01ull) << 0;
h_u_csabam8_rca_h1_v4_u_rca8_a |= ((h_u_csabam8_rca_h1_v4_fa2_7_xor1 >> 0) & 0x01ull) << 1;
h_u_csabam8_rca_h1_v4_u_rca8_a |= ((h_u_csabam8_rca_h1_v4_fa3_7_xor1 >> 0) & 0x01ull) << 2;
h_u_csabam8_rca_h1_v4_u_rca8_a |= ((h_u_csabam8_rca_h1_v4_fa4_7_xor1 >> 0) & 0x01ull) << 3;
h_u_csabam8_rca_h1_v4_u_rca8_a |= ((h_u_csabam8_rca_h1_v4_fa5_7_xor1 >> 0) & 0x01ull) << 4;
h_u_csabam8_rca_h1_v4_u_rca8_a |= ((h_u_csabam8_rca_h1_v4_fa6_7_xor1 >> 0) & 0x01ull) << 5;
h_u_csabam8_rca_h1_v4_u_rca8_a |= ((h_u_csabam8_rca_h1_v4_and7_7 >> 0) & 0x01ull) << 6;
h_u_csabam8_rca_h1_v4_u_rca8_a |= (0x00) << 7;
h_u_csabam8_rca_h1_v4_u_rca8_b |= ((h_u_csabam8_rca_h1_v4_fa0_7_or0 >> 0) & 0x01ull) << 0;
h_u_csabam8_rca_h1_v4_u_rca8_b |= ((h_u_csabam8_rca_h1_v4_fa1_7_or0 >> 0) & 0x01ull) << 1;
h_u_csabam8_rca_h1_v4_u_rca8_b |= ((h_u_csabam8_rca_h1_v4_fa2_7_or0 >> 0) & 0x01ull) << 2;
h_u_csabam8_rca_h1_v4_u_rca8_b |= ((h_u_csabam8_rca_h1_v4_fa3_7_or0 >> 0) & 0x01ull) << 3;
h_u_csabam8_rca_h1_v4_u_rca8_b |= ((h_u_csabam8_rca_h1_v4_fa4_7_or0 >> 0) & 0x01ull) << 4;
h_u_csabam8_rca_h1_v4_u_rca8_b |= ((h_u_csabam8_rca_h1_v4_fa5_7_or0 >> 0) & 0x01ull) << 5;
h_u_csabam8_rca_h1_v4_u_rca8_b |= ((h_u_csabam8_rca_h1_v4_fa6_7_or0 >> 0) & 0x01ull) << 6;
h_u_csabam8_rca_h1_v4_u_rca8_b |= (0x00) << 7;
h_u_csabam8_rca_h1_v4_u_rca8_out = u_rca8(h_u_csabam8_rca_h1_v4_u_rca8_a, h_u_csabam8_rca_h1_v4_u_rca8_b);
h_u_csabam8_rca_h1_v4_out |= (0x00) << 0;
h_u_csabam8_rca_h1_v4_out |= (0x00) << 1;
h_u_csabam8_rca_h1_v4_out |= (0x00) << 2;
h_u_csabam8_rca_h1_v4_out |= (0x00) << 3;
h_u_csabam8_rca_h1_v4_out |= ((h_u_csabam8_rca_h1_v4_ha0_4_xor0 >> 0) & 0x01ull) << 4;
h_u_csabam8_rca_h1_v4_out |= ((h_u_csabam8_rca_h1_v4_fa0_5_xor1 >> 0) & 0x01ull) << 5;
h_u_csabam8_rca_h1_v4_out |= ((h_u_csabam8_rca_h1_v4_fa0_6_xor1 >> 0) & 0x01ull) << 6;
h_u_csabam8_rca_h1_v4_out |= ((h_u_csabam8_rca_h1_v4_fa0_7_xor1 >> 0) & 0x01ull) << 7;
h_u_csabam8_rca_h1_v4_out |= ((h_u_csabam8_rca_h1_v4_u_rca8_out >> 0) & 0x01ull) << 8;
h_u_csabam8_rca_h1_v4_out |= ((h_u_csabam8_rca_h1_v4_u_rca8_out >> 1) & 0x01ull) << 9;
h_u_csabam8_rca_h1_v4_out |= ((h_u_csabam8_rca_h1_v4_u_rca8_out >> 2) & 0x01ull) << 10;
h_u_csabam8_rca_h1_v4_out |= ((h_u_csabam8_rca_h1_v4_u_rca8_out >> 3) & 0x01ull) << 11;
h_u_csabam8_rca_h1_v4_out |= ((h_u_csabam8_rca_h1_v4_u_rca8_out >> 4) & 0x01ull) << 12;
h_u_csabam8_rca_h1_v4_out |= ((h_u_csabam8_rca_h1_v4_u_rca8_out >> 5) & 0x01ull) << 13;
h_u_csabam8_rca_h1_v4_out |= ((h_u_csabam8_rca_h1_v4_u_rca8_out >> 6) & 0x01ull) << 14;
h_u_csabam8_rca_h1_v4_out |= ((h_u_csabam8_rca_h1_v4_u_rca8_out >> 7) & 0x01ull) << 15;
return h_u_csabam8_rca_h1_v4_out;
}
|
C
|
/************************************************** INFO **************************************************/
/**
* \brief OpenMP implementation of a 3D version of the Game of Life by John Conway
* for the Parallel and Distributed Computing course at IST 16/17 2nd Semester
* taught by Professor José Monteiro and Professor Luís Guerra e Silva
*
* \author Group #25
* \author André Mendes #66943
* \author Nuno Venturinha #67682
* \author Daniel Sousa #79129
* \version 1.0
* \date 07/04/2017
*/
/************************************************** INCLUDE **************************************************/
#include <omp.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/************************************************** DEFINE **************************************************/
/************************************************** CONSTANTS **************************************************/
#define ALIVE 1 /** \def Macro to differentiate alive from dead cells */
#define BUFFER_SIZE 200 /** \def Size of the file reading buffer */
#define DEAD 0 /** \def Macro to differentiate alive from dead cells */
#define NEIGHBOR 1 /** \def Macro to differentiate neighbor from new cells */
#define NEW 0 /** \def Macro to differentiate neighbor from new cells */
/************************************************** OPERATORS **************************************************/
#define MOD(a, b) (((a) < 0) ? ((a) % (b) + (b)) : ((a) % (b)))
/************************************************** PROTOTYPES **************************************************/
struct node;
void alloc_check (void *ptr);
struct node *** cube_create (int size);
void cube_destroy (struct node ***cube, int size);
void cube_print (struct node ***cube, int size);
void cube_purge (struct node ***cube, int size);
void determine_next_generation (struct node ***cube, int size);
void mark_neighbors (struct node ***cube, int size);
void node_add (struct node **head, short mode, short status, int z);
struct node * node_create (short status, int z);
void read_arguments (int argc, char *argv[], char **input_filename, int *iterations);
void read_coordinates (FILE *input_fd, struct node ***cube);
int read_size (FILE *input_fd);
/************************************************** STRUCT NODE **************************************************/
/** \struct
* Structure that represents the cells used in the cube.
* Holds the information related to a given cell and a pointer
* to another one with the same [x][y] coordinates
*/
struct node
{
short alive_neighbors; /**< Number of alive neighbors this cell has */
short status; /**< Whether this cell is alive or dead */
short z; /**< z-coordinate of this cell */
struct node *next; /**< Pointer to another cell with the same [x][y] coordinates */
};
/************************************************** ALLOC_CHECK **************************************************/
/**
* Checks if a given memory allocation was successful
*
* @param ptr Pointer to the memory that was allocated
*/
void alloc_check(void *ptr)
{
if(ptr == NULL)
{
fprintf(stderr, "Error with memory allocation\n");
abort();
}
}
/************************************************** CUBE_CREATE **************************************************/
/**
* Creates a 2D size by size "cube" of pointers to nodes and returns it
*
* @param size Size of the sides of the cube
* @return "Cube"
*/
struct node *** cube_create(int size)
{
struct node ***cube = NULL;
struct node **cube_mem = NULL;
int x = 0;
cube = (struct node ***) calloc(size, sizeof(struct node **));
cube_mem = (struct node **) calloc(size * size, sizeof(struct node *));
alloc_check(cube);
alloc_check(cube_mem);
for(x = 0; x < size; x++)
{
cube[x] = &cube_mem[size * x];
}
return cube;
}
/************************************************** CUBE_DESTROY **************************************************/
/**
* Frees the memory allocated for the structure required for the problem
*
* @param cube Structure that contains the cells
* @param size Size of the sides of the cube
*/
void cube_destroy(struct node ***cube, int size)
{
struct node *aux = NULL; /**< Auxilliary pointer */
int x = 0; /**< x-Coordinate */
int y = 0; /**< y-Coordinate */
for(x = 0; x < size; x++)
{
for(y = 0; y < size; y++)
{
while(cube[x][y] != NULL)
{
aux = cube[x][y];
cube[x][y] = cube[x][y]->next;
free(aux);
}
}
}
free(cube[0]);
free(cube);
}
/************************************************** CUBE_PRINT **************************************************/
/**
* Prints the solution of the problem to stdout
*
* @param cube Structure that contains the cells
* @param size Size of the sides of the cube
*/
void cube_print(struct node ***cube, int size)
{
struct node *aux = NULL; /**< Auxilliary pointer */
int x = 0; /**< x-Coordinate */
int y = 0; /**< y-Coordinate */
for(x = 0; x < size; x++)
{
for(y = 0; y < size; y++)
{
aux = cube[x][y];
while(aux != NULL)
{
if(aux->status == ALIVE)
{
fprintf(stdout, "%d %d %d\n", x, y, aux->z);
}
aux = aux->next;
}
}
}
}
/************************************************** CUBE_PURGE **************************************************/
/**
* Clean up routine to remove dead cells from the already processed
* structure as a way to speed up the next iteration
*
* @param cube Structure that contains the cells
* @param size Size of the sides of the cube
*/
void cube_purge(struct node ***cube, int size)
{
struct node **ptr = NULL; /**< Dereferencing pointer */
struct node *aux = NULL; /**< Auxilliary pointer */
int x = 0; /**< x-Coordinate */
int y = 0; /**< y-Coordinate */
for(x = 0; x < size; x++)
{
for(y = 0; y < size; y++)
{
ptr = &cube[x][y];
aux = *ptr;
while(aux != NULL)
{
if(aux->status == DEAD)
{
*ptr = aux->next;
free(aux);
}
else
{
ptr = &aux->next;
}
aux = *ptr;
}
}
}
}
/************************************************** DETERMINE_NEXT_GENERATION **************************************************/
/**
* Iterates through all the cells in the cube and determines whether
* they live or die in the next generation
*
* @param cube Structure that contains the cells
* @param size Size of the sides of the cube
*/
void determine_next_generation(struct node ***cube, int size)
{
struct node *aux = NULL; /**< Auxilliary pointer */
int x = 0; /**< x-Coordinate */
int y = 0; /**< y-Coordinate */
#pragma omp for schedule(static)
for(x = 0; x < size; x++)
{
for(y = 0; y < size; y++)
{
aux = cube[x][y];
while(aux != NULL)
{
/* If the cell is alive and has less than 2 or more than 4 neighbors it dies */
if(aux->status == ALIVE)
{
if(aux->alive_neighbors < 2 || aux->alive_neighbors > 4)
{
aux->status = DEAD;
}
}
/* If the cell is dead and has either 2 or 3 neighbors it comes to life */
else
{
if(aux->alive_neighbors == 2 || aux->alive_neighbors == 3)
{
aux->status = ALIVE;
}
}
/* Reset the number of neighbors of all processed cells */
aux->alive_neighbors = 0;
aux = aux->next;
}
}
}
}
/************************************************** LOCKS_CREATE **************************************************/
/**
* Creates and initializes a 2D size by size matrix of locks and returns it
*
* @param size Size of the sides of the matrix
* @return Locks
*/
omp_lock_t ** locks_create(int size)
{
omp_lock_t **locks = NULL;
omp_lock_t *locks_mem = NULL;
int x = 0;
int y = 0;
locks = (omp_lock_t **) calloc(size, sizeof(omp_lock_t *));
locks_mem = (omp_lock_t *) calloc(size * size, sizeof(omp_lock_t));
alloc_check(locks);
alloc_check(locks_mem);
for(x = 0; x < size; x++)
{
locks[x] = &locks_mem[size * x];
for(y = 0; y < size; y++)
{
omp_init_lock(&(locks[x][y]));
}
}
return locks;
}
/************************************************** LOCKS_DESTROY **************************************************/
/**
* Destroys and frees the memory allocated for the locks required for the problem
*
* @param locks Structure that contains the locks
* @param size Size of the sides of the matrix of locks
*/
void locks_destroy(omp_lock_t **locks, int size)
{
int x = 0; /**< x-Coordinate */
int y = 0; /**< y-Coordinate */
for(x = 0; x < size; x++)
{
for(y = 0; y < size; y++)
{
omp_destroy_lock(&(locks[x][y]));
}
}
free(locks[0]);
free(locks);
}
/************************************************** MARK_NEIGHBORS **************************************************/
/**
* Increments the alive neighbors count of all the neighbors of all
* alive cells in the current generation
*
* @param locks OpenMP locks to guarantee synchronization between all
* threads acessing the same list
* @param cube Structure that contains the cells
* @param size Size of the sides of the cube
*/
void mark_neighbors(omp_lock_t **locks, struct node ***cube, int size)
{
struct node *aux = NULL; /**< Auxilliary pointer */
int tmp = 0; /**< Temporary variable to avoid computing the modulo multiple times */
int x = 0; /**< x-Coordinate */
int y = 0; /**< y-Coordinate */
int z = 0; /**< z-Coordinate */
#pragma omp for schedule(static)
for(x = 0; x < size; x++)
{
for(y = 0; y < size; y++)
{
aux = cube[x][y];
while(aux != NULL)
{
/* For every alive cell, add each of its 6 neighbors to the cube and/or increment their neighbor count */
if(aux->status == ALIVE)
{
z = aux->z;
/* Compute the modulo just once to avoid having to do it once for each of the following 3 operations */
tmp = MOD((x+1), size);
/* Set the lock corresponding to that list on the cube and unset it after the operation is done */
omp_set_lock(&(locks[tmp][y]));
add_node(&(cube[tmp][y]), NEIGHBOR, DEAD, z);
omp_unset_lock(&(locks[tmp][y]));
tmp = MOD((x-1), size);
omp_set_lock(&(locks[tmp][y]));
add_node(&(cube[tmp][y]), NEIGHBOR, DEAD, z);
omp_unset_lock(&(locks[tmp][y]));
tmp = MOD((y+1), size);
omp_set_lock(&(locks[x][tmp]));
add_node(&(cube[x][tmp]), NEIGHBOR, DEAD, z);
omp_unset_lock(&(locks[x][tmp]));
tmp = MOD((y-1), size);
omp_set_lock(&(locks[x][tmp]));
add_node(&(cube[x][tmp]), NEIGHBOR, DEAD, z);
omp_unset_lock(&(locks[x][tmp]));
tmp = MOD((z+1), size);
omp_set_lock(&(locks[x][y]));
add_node(&(cube[x][y]), NEIGHBOR, DEAD, tmp);
omp_unset_lock(&(locks[x][y]));
tmp = MOD((z-1), size);
omp_set_lock(&(locks[x][y]));
add_node(&(cube[x][y]), NEIGHBOR, DEAD, tmp);
omp_unset_lock(&(locks[x][y]));
}
aux = aux->next;
}
}
}
}
/************************************************** NODE_ADD **************************************************/
/**
* Adds a node to the given list
*
* @param head Head of the list where to insert the node
* @param mode A way to differentiate whether we're adding neighbors of alive cells or alive cells themselves.
* It could be suppressed by creating an almost identical function for each case
* @param status Status of the cell to add
* @param z z-coordinate of the cell to add
*/
void node_add(struct node **head, short mode, short status, int z)
{
struct node *aux = NULL; /**< Auxilliary pointer */
struct node *new = NULL; /**< Pointer to a new node */
/* Add the node at the start of the list if its either empty or if it has the smallest z-coordinate */
if(((*head) == NULL) || ((*head)->z > z))
{
new = node_create(status, z);
new->alive_neighbors += mode;
new->next = (*head);
(*head) = new;
}
/* If we're adding a neighbor and the z-coordinate matches one already existing, increment the neighbor count */
else if((*head)->z == z)
{
(*head)->alive_neighbors += mode;
}
/* Remaining cases */
else
{
aux = (*head);
/* Go through the list until it either ends or we find a node with a greater z-coordinate */
while((aux->next != NULL) && (aux->next->z <= z))
{
aux = aux->next;
}
/* Increment the neighbor count if the node we are inserting already exists */
if(aux->z == z)
{
aux->alive_neighbors += mode;
}
/* Otherwise add the node */
else
{
new = node_create(status, z);
new->alive_neighbors += mode;
new->next = aux->next;
aux->next = new;
}
}
}
/************************************************** NODE_CREATE **************************************************/
/**
* Creates a node that represent a cell in the game
*
* @param status Status of the cell to create
* @param z z-coordinate of the cell to create
* @return Pointer to the cell created
*/
struct node * node_create(short status, int z)
{
struct node *new = NULL; /**< Pointer to the new node */
new = (struct node *) calloc(1, sizeof(struct node));
alloc_check(new);
new->alive_neighbors = 0;
new->status = status;
new->z = z;
new->next = NULL;
return new;
}
/************************************************** READ_ARGUMENTS **************************************************/
/**
* Checks if the command line arguments verify the specifications
*
* @param argc Command line argument count
* @param argv Command line arguments
* @param input_filename Name of the file specified in the arguments
* @param iterations Number of iterations specified in the arguments
*/
void read_arguments(int argc, char *argv[], char **input_filename, int *iterations)
{
FILE *input_fd = NULL;
if(argc != 3)
{
fprintf(stderr, "Program is run with ./life3d [name-of-input-file] [number-of-iterations]\n");
exit(-1);
}
(*input_filename) = argv[1];
input_fd = fopen((*input_filename), "r");
if(input_fd == NULL)
{
fprintf(stderr, "Error opening given file\n");
exit(-1);
}
fclose(input_fd);
(*iterations) = atoi(argv[2]);
if((*iterations) <= 0)
{
fprintf(stderr, "The number of iterations must be >= 1\n");
exit(-1);
}
}
/************************************************** READ_COORDINATES **************************************************/
/**
* Reads the input file and stores the given cells in the cube
*
* @param cube Structure that contains the cells
* @param input_filename Name of the input file
* @param size Size of the sides of the cube
*/
void read_coordinates(FILE *input_fd, struct node ***cube)
{
char buffer[BUFFER_SIZE] = {0};
int x = 0;
int y = 0;
int z = 0;
while(fgets(buffer, BUFFER_SIZE, input_fd) != NULL)
{
if((sscanf(buffer,"%d %d %d", &x, &y, &z)) != 3)
{
fprintf(stderr, "Input file does not match specifications\n");
exit(-1);
}
node_add(&(cube[x][y]), NEW, ALIVE, z);
}
}
/************************************************** READ_SIZE **************************************************/
/**
* Reads the input file and returns the declared size of the sides of the cube
*
* @param input_fd File descriptor for the input file
* @return size Size of the sides of the cube
*/
int read_size(FILE *input_fd)
{
char buffer[BUFFER_SIZE] = {0};
int size = 0;
fgets(buffer, BUFFER_SIZE, input_fd);
if((sscanf(buffer, "%d", &size)) != 1)
{
fprintf(stderr, "Input file does not match specifications\n");
exit(-1);
}
return size;
}
/************************************************** MAIN **************************************************/
int main(int argc, char *argv[])
{
FILE *input_fd = NULL; /**< File descriptor for the input file */
omp_lock_t **locks = NULL; /**< OpenMP locks, one for each [x][y] pair */
struct node ***cube = NULL; /**< Structure that contains the cells */
char *input_filename = NULL; /**< Name of the input file */
int iterations = 0; /**< Number of iterations to run the problem */
int size = 0; /**< Size of the sides of the cube */
/* Read the arguments given to the program */
read_arguments(argc, argv, &input_filename, &iterations);
/* Read the size of the problem */
input_fd = fopen(input_filename, "r");
size = read_size(input_fd);
/* Create the data structure */
cube = cube_create(size);
/* Create the locks */
locks = locks_create(size);
/* Reads the input file and stores the given cells in the cube */
read_coordinates(input_fd, cube);
fclose(input_fd);
/* Process the given problem */
#pragma omp parallel
{
while(iterations > 0)
{
/* Mark the neighbors of the currently alive cells */
mark_neighbors(locks, cube, size);
/* Go over all the cells and check which ones are alive in the next generation */
determine_next_generation(cube, size);
/* Go over all the cells and remove the dead ones */
cube_purge(cube, size);
/* Make sure that only one of the threads decreases the number of iterations */
#pragma omp single
iterations--;
}
}
/* Print the solution to stdout */
cube_print(cube, size);
/* Destroy the data structures */
cube_destroy(cube, size);
locks_destroy(locks, size);
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
int sigma(int);
int main(void)
{
int m ;
printf("Enter an integer:\n");
scanf("%i",&m);
int answer = sigma(m);
printf("%i \n",answer);
}
int sigma(int n)
{
if(n == 0) return 0 ;
if(n == 1) return 1 ;
else return (n + sigma(n-1));
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.