language
large_stringclasses 1
value | text
stringlengths 9
2.95M
|
|---|---|
C
|
#include <stdio.h>
#include <unistd.h>
#include <TAU.h>
int f1(void)
{
TAU_PROFILE_TIMER(t,"f1()", "", TAU_USER);
TAU_PROFILE_START(t);
sleep(1);
TAU_PROFILE_STOP(t);
return 0;
}
int input(void) {
TAU_PROFILE_TIMER(t,"input", "", TAU_USER);
TAU_PROFILE_START(t);
sleep(1);
TAU_PROFILE_STOP(t);
}
int output(void) {
TAU_PROFILE_TIMER(t,"output", "", TAU_USER);
TAU_PROFILE_START(t);
sleep(1);
TAU_PROFILE_STOP(t);
}
int f2(void)
{
TAU_PROFILE_TIMER(t,"f2()", "", TAU_USER);
TAU_PROFILE_START(t);
TAU_PHASE_CREATE_STATIC(t2,"IO Phase", "", TAU_USER);
TAU_PHASE_START(t2);
input();
output();
TAU_PHASE_STOP(t2);
TAU_PROFILE_STOP(t);
return 0;
}
int f3(int x) {
TAU_PROFILE_TIMER(t,"f3()", "", TAU_USER);
TAU_PROFILE_START(t);
sleep(x);
TAU_PROFILE_STOP(t);
return 0;
}
int f4(void) {
TAU_PROFILE_TIMER(t,"f4()", "", TAU_USER);
TAU_PROFILE_START(t);
sleep(1);
TAU_PROFILE_STOP(t);
return 0;
}
int main(int argc, char **argv) {
int i;
TAU_PROFILE_TIMER(t,"main()", "", TAU_DEFAULT);
TAU_PROFILE_SET_NODE(0);
TAU_PROFILE_START(t);
for (i=0; i<5; i++) {
char buf[32];
sprintf(buf, "Iteration %d", i);
TAU_PHASE_CREATE_DYNAMIC(phase, buf, "", TAU_USER);
TAU_PHASE_START(phase);
// Alternatively, we could use a dynamically name timer, but we would not get phase info
// TAU_PROFILE_TIMER_DYNAMIC(t2, buf, "", TAU_USER);
// TAU_PROFILE_START(t2);
printf("Iteration %d\n", i);
f1();
f2();
f3(i);
// TAU_PROFILE_STOP(t2);
TAU_PHASE_STOP(phase);
}
f1();
f4();
TAU_PROFILE_STOP(t);
}
|
C
|
#include <lib.h>
#include <syscall.h>
static uint64_t state_128plus[2];
static
uint64_t
xorshift128plus(void) {
uint64_t s1 = state_128plus[0];
uint64_t s0 = state_128plus[1];
state_128plus[0] = s0;
s1 ^= s1 << 23; // a
s1 ^= s1 >> 17; // b
s0 ^= s0 >> 26; // c
return (state_128plus[1] = s0 ^ s1) + state_128plus[0];
}
static uint64_t state_1024star[16];
static int p;
static
uint64_t
xorshift1024star(void) {
uint64_t s0 = state_1024star[p];
uint64_t s1 = state_1024star[p = (p + 1) & 0xF];
s1 ^= s1 << 31; // a
s1 ^= s1 >> 11; // b
s0 ^= s0 >> 30; // c
return (state_1024star[p] = s0 ^ s1) * 1181783497276652981LL;
}
uint64_t
random(void) {
return xorshift1024star();
}
void
init_rand(void) {
uint64_t zero = 0, one = 0;
asm volatile ("\trdtsc\n"
"\tmovl %%eax, %0\n"
"\tmovl %%edx, %1\n" : "=r"(zero), "=r"(one));
state_128plus[0] = zero;
state_128plus[1] = one;
while ((xorshift128plus() & 0x3F) != 0);
for (uint8_t i = 0; i < 16; ++i)
state_1024star[i] = xorshift128plus();
while((random() & 0x3F) != 0)
assert(random() != random());
}
|
C
|
#include <math.h>
#include <stdio.h>
#include <omp.h>
#include <stdlib.h>
#include <unistd.h>
#include <time.h>
#define size 100
int arr[size];
void merge(int arr[], int l, int m, int r)
{
int i, j, k;
int n1 = m - l + 1;
int n2 = r - m;
int L[n1], R[n2];
for (i = 0; i < n1; i++)
L[i] = arr[l + i];
for (j = 0; j < n2; j++)
R[j] = arr[m + 1+ j];
i = 0;
j = 0;
k = l;
while (i < n1 && j < n2)
{
if (L[i] <= R[j])
{
arr[k] = L[i];
i++;
}
else
{
arr[k] = R[j];
j++;
}
k++;
}
while (i < n1)
{
arr[k] = L[i];
i++;
k++;
}
while (j < n2)
{
arr[k] = R[j];
j++;
k++;
}
}
void mergeSort(int arr[], int l, int r)
{
if (l < r)
{
int m = l+(r-l)/2;
mergeSort(arr, l, m);
mergeSort(arr, m+1, r);
merge(arr, l, m, r);
}
}
void printArray()
{
printf("after sorting = \n");
int i;
for (i = 0; i < size; i++)
printf("%d ", arr[i]);
printf("\n");
}
int main()
{
int i;
clock_t tStart = clock();
srand(time(NULL));
for(i = 0; i < size; i++)
{
arr[i] = rand() % size;
}
int num=size;
printf("before sorting = \n");
for(i = 0; i < size; i++)
{
printf("%d ", arr[i]);
}
printf("\n");
int up=0,dn=0;
#pragma omp parallel num_threads(2)
{
int a=omp_get_thread_num();
int half=size/2;
if(a==0){
mergeSort(arr,0,half);
up=1;
}
if(a==1){
mergeSort(arr,half,size);
dn=1;
}
}
mergeSort(arr,0,size);
printArray();
printf("Time taken: %.8fs\n", (double)(clock() - tStart)/CLOCKS_PER_SEC);
return 0;
}
|
C
|
#include <stdio.h>
#include <string.h>
#include "account_srv.h"
#include "printChoices.h"
#include "inputMethod.h"
#include "color.h"
#include "account_UI.h"
#include "templates.h"
void noUserLogin();
void uesrLogin();
void login()
{
setBackgroundColor(0);
setFontColor(7);
// Test if it's the first time
while (account_srv_howManyInToto() == 0)
{
noUserLogin();
}
uesrLogin();
}
void noUserLogin()
{
system("cls");
printTitleWithCurrentTime("Welcome", 8);
printMultipleTimes('\n', 5);
printMiddleAddjusted("It looks like it's your first time lauching this APP", 54);
printMultipleTimes('\n', 2);
printMiddleAddjusted("So, let's set up an Administrator account", 43);
printMultipleTimes('\n', 10);
keyToContinue("Enter", 5);
while (account_UI_creatAdmin() == 0)
{
setBackgroundColor(0);
setFontColor(7);
system("cls");
printTitleWithCurrentTime("Welcome", 8);
printMultipleTimes('\n', 5);
printMiddleAddjusted("You have to create an Administrator account", 44);
printf("\n\n");
keyToContinue("Continue", 8);
}
}
void uesrLogin()
{
account_list_t result = NULL;
int toExit = 0;
while (toExit == 0)
{
setBackgroundColor(0);
setFontColor(7);
system("cls");
printTitleWithCurrentTime("Welcome", 8);
printMultipleTimes('\n', 5);
printMiddleAddjusted("Please tell me who you are", 27);
printf("\n\n");
char usernameReceive[30];
char passwordReceive[30];
printMiddleLeft("Username:", 10, 2);
printMultipleTimes(' ', 2);
inputAlnum(usernameReceive, 30, 6);
printf("\n");
printMiddleLeft("Password:", 10, 2);
printMultipleTimes(' ', 2);
inputPassword(passwordReceive, 30, 6);
printf("\n\n");
result = account_srv_findByUsername(usernameReceive);
// varification
int invalid = 0;
if (result == NULL)
{
invalid = 1;
}
else if (strcmp(result->data.password, passwordReceive) != 0)
{
invalid = 1;
}
// If not to login
if (invalid == 1)
{
setFontColor(1);
printMiddleAddjusted("Invalid username or password", 29);
printf("\n\n");
keyToContinue("Continue", 8);
toExit = exitSelect();
}
// If to login
if (invalid == 0)
{
if (result->data.type == USER_ADMIN)
{
extern int administratorLogin(account_list_t theUser);
toExit = administratorLogin(result);
}
else if (result->data.type == USER_MANAGER)
{
extern int managerLogin(account_list_t theUser);
toExit = managerLogin(result);
}
else if (result->data.type == USER_CLERK)
{
extern int clerkLogin(account_list_t theUser);
toExit = clerkLogin(result);
}
}
}
}
|
C
|
#include <stdio.h>
extern char* add_a(char *);
int main (void) {
char str[10]="chush";
printf("%s\n", add_a(str));
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include "cblas.h"
#define BLOC_SIZE 100
/*
* CBLAS_ORDER Order : ordre par ligne ou colonne
* CBLAS_TRANSPOSE TransA (char) : N/n pour normal - T/t - C/c pour la transposée
* CBLAS_TRANSPOSE TransB (char) : N/n pour norlal - T/t - C/c pour la transposée
* M : nombre de lignes de A et C
* N : nombre de colonnes de B et C
* K : nombre de colonnes de A et nombre de lignes de B
* ALPHA : scalaire alpha (1)
* A : matrice A
* lda : décalage entre chaque ligne de A
* B : matrice B
* ldb : décalage entre chaque ligne de B
* BETA : scalaire beta (0)
* C : matrice C
* ldc : décalage entre chaque ligne de C
*
* TransA :
* - CblasNoTrans = (i, j, k) --> size * size * size * 2
* - CblasTrans = (k, i, j) --> size * size * size * 2
* - CblasConjTrans = (j, i, k) --> size * size * size * 2
*/
void cblas_dgemm_scalaire(const enum CBLAS_ORDER Order, const enum CBLAS_TRANSPOSE TransA, const enum CBLAS_TRANSPOSE TransB, const int M, const int N, const int K, const double alpha, const double *A, const int lda, const double *B, const int ldb, const double beta, double *C, const int ldc) {
int n, m, k, val, b_pos, a_pos, c_pos;
if (TransA == CblasNoTrans) {
if (lda == 1) {
for (m = 0 ; m < M ; m++) {
for (n = 0 ; n < N ; n++) {
c_pos = n*ldc + m;
val = C[c_pos];
b_pos = n*ldb;
for (k = 0 ; k < K ; k++) {
val += A[k + m] * B[b_pos + k];
}
if (alpha == 1) {
C[c_pos] = val;
} else {
C[c_pos] = alpha*val;
}
}
}
} else {
for (m = 0 ; m < M ; m++) {
for (n = 0 ; n < N ; n++) {
c_pos = n*ldc + m;
val = C[c_pos];
b_pos = n*ldb;
for (k = 0 ; k < K ; k++) {
val += A[k*lda + m] * B[b_pos + k];
}
if (alpha == 1) {
C[c_pos] = val;
} else {
C[c_pos] = alpha*val;
}
}
}
}
} else if (TransA == CblasTrans) {
if (alpha == 1) {
for (k = 0 ; k < K ; k++) {
for (m = 0 ; m < M ; m++) {
a_pos = k*lda + m;
for (n = 0 ; n < N ; n++) {
C[n*ldc + m] += A[a_pos] * B[n*ldb + k];
}
}
}
} else {
for (k = 0 ; k < K ; k++) {
for (m = 0 ; m < M ; m++) {
a_pos = k*lda + m;
for (n = 0 ; n < N ; n++) {
C[n*ldc + m] += alpha*(A[a_pos] * B[n*ldb + k]);
}
}
}
}
} else {
if (lda == 1) {
for (n = 0 ; n < N ; n++) {
b_pos = n*ldb;
a_pos = n*ldc;
for (m = 0 ; m < M ; m++) {
c_pos = a_pos + m;
val = C[c_pos];
if (alpha == 1) {
for (k = 0 ; k < K ; k++) {
val += A[k + m] * B[b_pos + k];
}
} else {
for (k = 0 ; k < K ; k++) {
val += alpha * A[k + m] * B[b_pos + k];
}
}
C[c_pos] = val;
}
}
} else {
for (n = 0 ; n < N ; n++) {
b_pos = n*ldb;
a_pos = n*ldc;
for (m = 0 ; m < M ; m++) {
c_pos = a_pos + m;
val = C[c_pos];
if (alpha == 1) {
for (k = 0 ; k < K ; k++) {
val += A[k*lda + m] * B[b_pos + k];
}
} else {
for (k = 0 ; k < K ; k++) {
val += alpha * A[k*lda + m] * B[b_pos + k];
}
}
C[c_pos] = val;
}
}
}
}
}
void cblas_dgemm_scalar_opti(const enum CBLAS_ORDER Order, const enum CBLAS_TRANSPOSE TransA, const enum CBLAS_TRANSPOSE TransB, const int M, const int N, const int K, const double alpha, const double *A, const int lda, const double *B, const int ldb, const double beta, double *C, const int ldc) {
int n, m, k, val, b_pos, a_pos, c_pos;
if (alpha == 1) {
for (k = 0 ; k < K ; k++) {
for (m = 0 ; m < M ; m++) {
a_pos = k*lda + m;
for (n = 0 ; n < N ; n++) {
C[n*ldc + m] += A[a_pos] * B[n*ldb + k];
}
}
}
} else {
for (k = 0 ; k < K ; k++) {
for (m = 0 ; m < M ; m++) {
a_pos = k*lda + m;
for (n = 0 ; n < N ; n++) {
C[n*ldc + m] += alpha*(A[a_pos] * B[n*ldb + k]);
}
}
}
}
}
void cblas_dgemm(const enum CBLAS_ORDER Order, const enum CBLAS_TRANSPOSE TransA, const enum CBLAS_TRANSPOSE TransB, const int M, const int N, const int K, const double alpha, const double *A, const int lda, const double *B, const int ldb, const double beta, double *C, const int ldc) {
if (M <= BLOC_SIZE && N <= BLOC_SIZE && K <= BLOC_SIZE) {
cblas_dgemm_scalar_opti(Order, TransA, TransB, M, N, K, alpha, A, lda, B, ldb, beta, C, ldc);
return;
}
int i, j, k;
int i_pos, j_pos, k_pos;
int nb_m_blocks, nb_k_blocks, nb_n_blocks;
int m_size, k_size, n_size;
int last_m_size, last_k_size, last_n_size;
int last_m_block, last_k_block, last_n_block;
int a_index, b_index, c_index;
nb_m_blocks = ceil(M/BLOC_SIZE);
nb_k_blocks = ceil(K/BLOC_SIZE);
nb_n_blocks = ceil(N/BLOC_SIZE);
last_m_size = M - BLOC_SIZE*(nb_m_blocks-1);
last_k_size = K - BLOC_SIZE*(nb_k_blocks-1);
last_n_size = N - BLOC_SIZE*(nb_n_blocks-1);
last_m_block = nb_m_blocks - 1;
last_n_block = nb_n_blocks - 1;
last_k_block = nb_k_blocks - 1;
for (j = 0 ; j < nb_n_blocks ; j++) {
if (j < last_n_block) {
n_size = BLOC_SIZE;
} else {
n_size = last_n_size;
}
j_pos = j*BLOC_SIZE;
for (i = 0 ; i < nb_m_blocks ; i++) {
if (i < last_m_block) {
m_size = BLOC_SIZE;
} else {
m_size = last_m_size;
}
i_pos = i*BLOC_SIZE;
c_index = i_pos + j_pos*M;
for (k = 0 ; k < nb_k_blocks ; k++) {
k_pos = k*BLOC_SIZE;
a_index = i_pos + k_pos*M;
b_index = k_pos + j_pos*K;
if (k < last_k_block) {
k_size = BLOC_SIZE;
} else {
k_size = last_k_size;
}
cblas_dgemm_scalar_opti(Order, TransA, TransB, m_size, n_size, k_size, alpha, &(A[a_index]), lda, &(B[b_index]), ldb, beta, &(C[c_index]), ldc);
}
}
}
}
|
C
|
#include "reciever.h"
void recievePostResponse(int socket,FILE* response){
char* httpResponse = malloc(MAX_HEADER_);
int totalBufferSize = recv(socket, httpResponse, MAX_HEADER_, 0);
if(totalBufferSize < 0){
perror("error receiving packages");
free(httpResponse);
return;
}
fwrite ( httpResponse , 1 , totalBufferSize , response );
}
void recieveGetResponse(int socket,FILE* body,FILE* response){
char* httpResponse = malloc(MAX_HEADER_+MAX_FILE_SIZE_);
/*httpResponse="HTTP/1.1 200 OK\r\n"
"Date: Thu, 19 Feb 2009 12:27:04 GMT\r\n"
"Content-Length: 18\r\n"
"\r\n"
"sdfkjsdnbfkjbsflll";*/
int totalBufferSize = recv(socket, httpResponse, MAX_HEADER_+MAX_FILE_SIZE_, 0);
if(totalBufferSize <= 0){
perror("error receiving packages");
free(httpResponse);
return;
}
fwrite ( httpResponse , 1 , totalBufferSize , response );
char *responseCode=getCode(httpResponse);
if(strcmp(responseCode,"200")!=0){
return;
}
int contentStart;
int contentLength=getContentParam(&contentStart,httpResponse);
if(contentLength <= 0){
perror("Invalid GET RESPONSE As no content exist in the response");
return;
}
int status=totalBufferSize;
//int status = recv(socket, httpResponse, contentStart + contentLength, MSG_PEEK);
char * content=malloc(contentLength+1);
int current_index=0;
// we may not receive all the data content completely if the data content is large.
for(; current_index < status - contentStart; current_index++){
content[current_index] = httpResponse[current_index + contentStart];
}
// continue reading until we finish reading all the content
while(contentLength - current_index > 1){
status = recv(socket, (char *)(content + current_index), contentLength - current_index, 0);
printf("%d\n", status);
current_index += status;
}
fwrite ( content , 1 , contentLength , body );
}
int getContentParam(int *contentStart,char *httpResponse){
char *dest = strstr(httpResponse, "Content-Length");
int pos= dest - httpResponse;
printf("%d\n",pos);
while(httpResponse[pos]<'0'||httpResponse[pos]>'9'){
pos++;
}
char* contentLength = malloc(10);
int j=0;
while(httpResponse[pos]>='0'&&httpResponse[pos]<='9'){
contentLength[j++]=httpResponse[pos++];
}
char *dest1 = strstr(httpResponse, "\r\n\r\n");
pos= dest1 - httpResponse+4;
*contentStart=pos;
return atoi (contentLength);
}
char *getCode(char *httpResponse){
int i=0;
char* line1=malloc(MAXCHAR);
//get first line of response
while(httpResponse[i]!='\r'&&httpResponse[i]!='\n'){
line1[i]=httpResponse[i];
i++;
}
i=0;
//get cursor i to space after protocol version
while(line1[i]!=' '){
i++;
}
while(line1[i]==' '){
i++;
}//get cursor i to first char in response code
char* code = malloc(4);
int j=0;
while(line1[i]>='0'&&line1[i]<='9'){
code[j++]=line1[i++];
}
code[j]='\0';
return code;
}
|
C
|
#include "str_dealing.h"
/*ַȼ*/
uint16_t strLen(pu8 str)
{
int i = 0;
while (*str != 0) {
++i;
++str;
}
return i;
}
/*ַݺͳȱȽ*/
_Bool str_compare(uint8_t * str1,uint8_t * str2)
{
uint16_t str1_len = strLen(str1);
uint16_t str2_len = strLen(str2);
uint16_t num;
if(str1_len == str2_len)
{
for(num = 0;num < str1_len;num++)
{
if(str1[num]!=str2[num])
{
return 0;
}
}
return 1;
}
else
{
return 0;
}
}
/*ַתƺ*/
void strtoarr(uint8_t * str,uint8_t * arr)
{
// uint16_t num;
// for(num = 0;num < sizeof(str);num++)
// {
// arr[num] = str[num];
// }
while(*str)
{
*arr++ = *str++;
}
}
|
C
|
#ifndef _PTI_H_
#define _PTI_H_
#include "include.h"
#define FLY_FREQUENCY 50 // Ƶ
#define PTI_MIN 500 // Сռձ
#define PTI_MAX 1000 // ռձ
#define PTI_CENTER (PTI_MIN+PTI_MAX)/2 // мռձ
#define POWER_MIN 585 // Сֵ
#define POWER_MAX 725 // ֵ
#define POWER_ATTITUDE 710 // һʱĸ߶
#define UNLOCK_DELAY 2000 // ʱ
#define TIMER_PERIOD 10 // ʱ
#define COM_DIRECTION_TIME 5 // ıʱʱ䣨ʱ + ʱ < ʱڣ
#define DIS_DIRECTION_TIME 2 // ıʱʱ䣨ʱ + ʱ < ʱڣ
#define COM_PTI_CHANGE 35 // ıʱİڶΧ
#define DIS_PTI_CHANGE 40 // ıʱİڶΧ
#define FTM_FLY FTM0
#define CH_ROLL FTM_CH0
#define CH_PITCH FTM_CH1
#define CH_ATTITUDE FTM_CH2
#define CH_YAW FTM_CH3
#define CH_SURE_ATTITUDE FTM_CH4
#define CH_SERVO FTM_CH5
/* з */
typedef enum
{
PTI_PITCH_FRONT, // ǰ
PTI_PITCH_BACK, //
PTI_PITCH_CENTER, // ͣ
PTI_ROLL_FRONT, // ǰ
PTI_ROLL_BACK, //
PTI_ROLL_CENTER, // ͣ
PTI_YAW_FRONT, // ƫǰ
PTI_YAW_BACK, // ƫ
PTI_YAW_CENTER, // ƫͣ
PTI_ALL_CENTER, // ͣ
PTI_PFRONT_RFRONT, // ǰǰ
PTI_PFRONT_RBACK, // ǰ
PTI_PBACK_RFRONG, // ˡǰ
PTI_PBACK_RBACK // ˡ
} Direction;
/* */
typedef enum
{
SERVO_OPEN, //
SERVO_CLOSE //
} ServoChange;
void ptiInit(); // PTI ʼ
void unlock(); //
void lock(); //
void controlFly(Direction direction); // Ʒз
void attitudeChange(int value); // ıֵ
void centerFly(); // ͣ
void stop(); // ͣ
void servoChange(ServoChange change); // ı״̬
#endif
|
C
|
#include "shell.h"
/**
* _free_line - free's struct data->line from memory
* @data: data->line pointer to free's
* Return: Nothing
*/
void _free_line(Data_t *data)
{
/*If line exits can free's from memory*/
if (data->line)
free(data->line);
}
/**
* _free_cleanline - free's struct data->cleanline from memory
* @data: data->cleanline pointer to free's
* Return: Nothing
*/
void _free_cleanline(Data_t *data)
{
/*If args exits can free's from memory*/
if (data->cleanline)
free(data->cleanline);
}
/**
* _free_args - free's struct data->args from memory
* @data: data->args pointer to free's
* Return: Nothing
*/
void _free_args(Data_t *data)
{
free(data->args);
}
|
C
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/*
* File: Word Sort.c
* Author: USER
*
* Created on November 27, 2019, 6:24 PM
*/
#include "WordSort Header.h"
int main(int argc, char** argv) {
char word[MAXCHARACTER_PER_WORD]; /*Work space*/
char *w[N]; /*an array of pointers*/
int n; /*number of words to be sorted*/
int i;
printf("Make A Sentence Here: ");
for (i = 0; scanf("%s", word) == 1; ++i) {
if (i >= N)/*Checks if the number of words has exceeded its limit*/
error_exit_too_many_words();
if (strlen(word) >= MAXCHARACTER_PER_WORD)/*Checks if the number of characters per word has exceeded its limit*/
error_exit_words_too_long();
w[i] = calloc(strlen(word) + 1, sizeof (char)); /*Allocates memory for an array with n elements*/
if (w[i] == NULL)/*This checks if the calloc function worked*/
error_exit_calloc_failed();
strcpy(w[i], word); /*Copies whatever is in word to the memory with an address w[i] where i=0,1,2...*/
}
n = i;
sort_words(w, n); /*Sorts the word in an array w lexicographically*/
wrt_words(w, n); /*Prints the words that have sorted lexicographically*/
return (EXIT_SUCCESS);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
void sort(int []);
int noofrect;
int checkinside(int x,int y);
int checkrect(int x1,int y1,int x2,int y2);
int arr[100][4];
int main()
{
FILE *input;
register int i,j;
int lx,ly,ux,uy;
int xmin,xmax,ymin,ymax;
int area,maxarea=0;
input=fopen("data.txt","r");
fscanf(input,"%d",&noofrect);
printf("number = %d ", noofrect);
for(i=0;i<noofrect;i++)
{
fscanf(input,"%d %d %d %d",&lx,&ly,&ux,&uy);
if((lx >= ux) || (ly >= uy))
{
printf("\nThe data entry (%d,%d) (%d,%d) is not a valid rectangle!!!!\nExiting the program!!!!",lx,ly,ux,uy);
fclose(input);
return 0;
}
printf("\nCood = %d %d %d %d\n",lx,ly,ux,uy);
arr[i][0] = lx;
arr[i][1] = ux;
arr[i][2] = ly;
arr[i][3] = uy;
}
for(i=0;i<noofrect;i++)
{
for(j=noofrect-1;j>=0;j--)
{
printf("\nRect checking.... %d %d %d %d",arr[i][0],arr[i][2],arr[j][1],arr[j][3]);
if(checkrect(arr[i][0],arr[i][2],arr[j][1],arr[j][3]))
{
printf("\nRect %d %d %d %d",arr[i][0],arr[i][2],arr[j][1],arr[j][3]);
if((arr[i][0]<arr[j][2])&&(arr[i][1]<arr[i][3]))
{
area = (arr[j][2]-arr[i][0])*(arr[j][3]-arr[i][1]);
if(maxarea < area)
{
maxarea = area;
xmax = arr[i][2];
ymax = arr[i][3];
xmin = arr[i][0];
ymin = arr[i][1];
}
printf("\ncheck area %d %d",maxarea,area);
}
}
}
}
printf("\nArea = %d",maxarea);
fclose(input);
return 0;
}
int checkinside(int x,int y)
{
int i;
for(i=0;i<noofrect;i++)
{
if((arr[i][0]>=x || arr[i][2]<=x)&&(arr[i][1]>=y || arr[i][3]<=y))
return 1;
}
return 0;
}
int checkrect(int x1,int y1,int x2,int y2)
{
int i,j;
for(i=x1;i<=x2;i++)
{
for(j=y1;j<=y2;j++)
{
if(checkinside(i,j)==0)
return 0;
}
}
return 1;
}
|
C
|
#include "chat.h"
#include "global.h"
#include "debug.h"
#include "gui.h"
int sock_chat;
bool chat_ready=false;
char message[MAX_LEN_CHAT+2];
u8 chat_refresh;
/**
Demana al servidor si hi han missatges
*/
void chat_request_update(void) {
char buffer[MAX_LEN_CHAT+2];
if(chat_ready==1) {
snprintf(buffer,MAX_LEN_CHAT,"G\n");
send(sock_chat,buffer,strlen(buffer),0);
}
}
/**
Inicialitza el xat
Es conecta al servidor
i envia petici per rebre els nous missatges
*/
u8 chat_init(void) {
char buffer[MAX_LEN_CHAT+10];
char nickname[30];
strcpy(nickname,(char *)&PA_UserInfo.Name);
if(PA_InitSocket(&sock_chat,CHAT_SERVER,CHAT_PORT,PA_NORMAL_TCP)) {//PA_NONBLOCKING_TCP, PA_NORMAL_TCP
chat_ready=true;
sprintf(buffer,"L %s\n",nickname);
send(sock_chat,buffer,strlen(buffer),0); //Logged
chat_refresh=CHAT_REFRESH;
chat_request_update();
debug("[chat_init] ok\n");
return 1;
}
debug("[chat_init] fail\n");
return 0;
}
/**
Envia un missatge al xat
*/
void chat_send(char *message){
char buffer[MAX_LEN_CHAT+10];
if(chat_ready==1) {
debug("[chat_send] Sending message\n");
sprintf(buffer,"S %s\n",message);
send(sock_chat,buffer,strlen(buffer),0);
}
}
/**
Informa al servidor que hi ha has creat una partida
*/
void chat_newgame(void) {
char buffer[MAX_LEN_CHAT+10];
if(chat_ready==1) {
debug("[chat_newgame]\n");
sprintf(buffer,"M %s\n",ip);
send(sock_chat,buffer,strlen(buffer),0);
}
}
/**
Processa els missatges del servidor i demana rebre els nous missatge
*/
void chat_update(void) {
char buffer[MAX_LEN_CHAT+2];
char lip[20];
char lnick[20];
s16 n;
s32 nmessages;
//albert. si es s32 no da warning, s32 = int -> %d l46
if(chat_ready==1) {
debug("[chat_update] Checking for new messages\n");
recv(sock_chat,&buffer,MAX_LEN_CHAT,0);
//PA_OutputSimpleText(TOP_SCREEN,0,18,buffer);
if(buffer[0]=='R') {
sscanf(buffer,"R %d",&nmessages);
while(nmessages>0) {
n=recv(sock_chat,&buffer,MAX_LEN_CHAT,0);
if(n>0) {
buffer[n]=0;
PA_Print(TOP_SCREEN,buffer);
}
if(sscanf(buffer,"-match %s %s\n",lip,lnick)) {
if(strcmp(lip,ip)!=0) {
last_game=true;
strcpy(last_game_ip,lip);
strcpy(last_game_nick,lnick);
}
}
nmessages--;
}
}
chat_request_update();
}
}
/**
Desconecta del xat
*/
void chat_quit(void) {
closesocket(sock_chat);
chat_ready=false;
debug("[chat_quit] Chat disconected\n");
}
|
C
|
#ifndef MOUSE_H
#define MOUSE_H
#include "drawing.h"
#define INT_MOUSE 0x33
#define MOUSE_RESET 0x00
#define MOUSE_GETPRESS 0x05
#define MOUSE_GETRELEASE 0x06
#define MOUSE_SETSHAPE 0x09
#define MOUSE_GETMOTION 0x0B
#define LEFT_BUTTON 0x00
#define RIGHT_BUTTON 0x01
#define MIDDLE_BUTTON 0x02
#define MOUSE_WIDTH 3
#define MOUSE_HEIGHT 3
#define MOUSE_SIZE (MOUSE_HEIGHT*MOUSE_WIDTH)
typedef short sword;
typedef struct
{
byte on;
byte button1;
byte button2;
byte button3;
int num_buttons;
sword x;
sword y;
} MOUSE;
sword initMouse(MOUSE *mouse);
sword getMousePress(sword button);
sword getMouseRelease(sword button);
void getMouseMotion(sword *dx, sword *dy);
void showMouse(MOUSE *mouse, byte color);
#endif
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include "functii_sudoku.h"
int main()
{
int **matrix,i,j,nr_joc;
char dump_string[100]; // sir de caractere folosit pt a citi din fisier pana ajung
//la sudoku pe care trebuie sa il rezolv
FILE *ModelSudoku=fopen("Modele Sudoku.txt","r"), *RezolvareSudoku=fopen("Rezolvari Sudoku.txt","w");
matrix=calloc(9,sizeof(int));
for (i=0;i<9; i++)
matrix[i]=calloc(9,sizeof(int));
printf("Ce joc doriti sa fie rezolvat? Introduceti un numar in intervalul 1-50: ");
scanf("%d",&nr_joc);
while (nr_joc<1 || nr_joc>50)
{
printf("\nVa rog introduceti un numar de joc din intervalul 1-50: ");
scanf("%d",&nr_joc);
}
for (i=0;i<nr_joc*2+(nr_joc-1)*9+(nr_joc-1);i++)
fgets(dump_string, sizeof(dump_string),ModelSudoku);
for (i=0;i<9;i++)
for (j=0;j<9;j++)
fscanf(ModelSudoku,"%d ",&matrix[i][j]);
solve_sudoku(matrix,0,0);
if (check_square_rows(matrix)==1 && check_square_cols(matrix)==1)
{
//show_matrix(matrix);
show_matrix_file(matrix,RezolvareSudoku);
}
else printf("\n\nModelul de sudoku nu poate fi rezolvat!");
fclose(ModelSudoku);
fclose(RezolvareSudoku);
return 0;
}
|
C
|
#include <stdio.h>
#include <string.h>
main()
{
char a[5][10],t[10];
int i,j;
for(i=0;i<5;i++)
{
printf("%dͬѧ:",i+1);
gets(a[i]);
}
for(i=1;i<5;i++){
for(j=0;j<5-i;j++)
if(strcmp(a[j],a[j+1])>0)
{
strcpy(t,a[j]);
strcpy(a[j],a[j+1]);
strcpy(a[j+1],t);
}
}
for(i=0;i<5;i++)
printf("%s ",a[i]);
}
|
C
|
//ʽ鶨
int MaxDegree = 10;
typedef struct
{
int CoeffArray[MaxDegree + 1];
int HighPower;
} *Polynomial;
//ʽʼΪ0Ĺ
void ZeroPolymial(Polynomial Poly)
{
int i;
for(i=0;i<=MaxDegree;i++)
{
Poly->CoeffArray[i] = 0;
}
Poly->HighPower = 0;
}
//ʽӵĹ
void AddPolynomial(const Polynomial Poly1,const Polynomial Poly2,Polynomial PolySum)
{
int i;
ZeroPolynomial(PolySum);
PolySum->HighPower = Max(Poly1->HighPower,Poly2->HighPower);
for(i=PolySum->HighPower;i>=0;i--)
{
PolySum->CoeffArray[i] = Poly1->CoeffArray[i] +Poly2->CoeffArray[i];
}
}
//ʽ˵Ĺ
void MultPolyNomial(const Polynomial Poly1,const Polynomial Poly2,Polynomial PolyProd)
{
int i,j;
ZeroPolynomial(PolyProd);
PolyProd->HighPower = Poly1->HighPower + Poly2->HighPower;
if(PolyProd->HighPower > MaxDegree)
{
printf("Exceeded arry size!\n");
}else{
for(i=0;i<=Poly1->HighPower;i++)
{
for(j=0;j<=Poly2->HighPower;j++)
{
PolyProd->CoeffArray[i+j] += Poly1->CoeffArray[i] * Poly2->CoeffArray[j];
}
}
}
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int *data;
int *aux;
int N;
void init_array(int n);
void print_array();
void selection_sort();
void insertion_sort();
void bubble_sort();
void shell_sort();
void quick_sort(int l,int r);
void merge_sort(int l,int r);
int main(int argc,char** args){
if(argc < 3)
return -1;
init_array(atoi(args[1]));
print_array();
switch(atoi(args[2])){
case 1:
printf("Using selection sort\n");
selection_sort();
break;
case 2:
printf("Using insertion sort\n");
insertion_sort();
break;
case 3:
printf("Using bubble sort\n");
bubble_sort();
break;
case 4:
printf("Using quick sort\n");
quick_sort(0,N-1);
break;
case 5:
printf("Using merge sort\n");
merge_sort(0,N-1);
break;
case 6:
printf("Using shell sort\n");
shell_sort();
break;
}
print_array();
return 0;
}
void init_array(int n){
int i;
N = n;
data = malloc(sizeof(*data)*n);
aux = malloc(sizeof(*data)*n);
srand(time(NULL));
for(i = 0;i<N;i++)
data[i] = rand()%N;
}
void print_array(){
int i;
for(i = 0;i<N;i++)
printf("%d ",data[i]);
printf("\n");
}
void selection_sort(){
int i,j,min,tmp;
for(i=0;i<N;i++){
min = i;
for(j=i+1;j<N;j++){
if(data[j]<data[min])
min = j;
}
tmp = data[i];
data[i] = data[min];
data[min] = tmp;
}
}
void insertion_sort(){
int i,j,tmp;
for(i = 1;i<N;i++){
for(j=i-1;j>=0;j--){
if(data[j+1]>data[j])
break;
tmp = data[j];
data[j] = data[j+1];
data[j+1] = tmp;
}
}
}
void bubble_sort(){
int i,j,tmp;
for(i=N-1;i>=0;i--){
for(j=0;j<i;j++){
if(data[j]>data[j+1]){
tmp =data[j];
data[j] = data[j+1];
data[j+1] = tmp;
}
}
}
}
void shell_sort();
void quick_sort(int l,int r){
if(l>=r)
return;
int tmp,left,right,pivot;
pivot = l;
left = l+1;
right = r;
while(right>left){
while(data[left]<=data[pivot]){
if(left == right)
break;
left++;
}
while(data[right]>data[pivot]){
if(left == right)
break;
right--;
}
tmp = data[left];
data[left] = data[right];
data[right] = tmp;
}
if(data[left]<=data[pivot]){
tmp = data[pivot];
data[pivot] = data[left];
data[left] = tmp;
pivot = left;
}
else{
tmp = data[pivot];
data[pivot] = data[left-1];
data[left-1] = tmp;
pivot = left-1;
}
quick_sort(l,pivot-1);
quick_sort(pivot+1,r);
}
void merge_sort(int l,int r){
if(l==r)
return;
int m;
int i;
int left,right;
m = (l+r)/2;
merge_sort(l,m);
merge_sort(m+1,r);
left = l;
right = m+1;
for(i = l;i<=r;i++){
if(right>r)
aux[i] = data[left++];
else if(left>m)
aux[i] = data[right++];
else if(data[left]<=data[right])
aux[i] = data[left++];
else if(data[right]<data[left])
aux[i] = data[right++];
}
for(i = l;i<=r;i++)
data[i] = aux[i];
}
void shell_sort(){
int h;
int i,j,k,tmp,min;
for(h = N/2;h>=1;h/=2){
//This 2 fors is for the insertion method along the gapped lists.
for(i=h;i<N;i++){
tmp = data[i];
for(j=i;j>=h && data[j-h]>tmp;j-=h)
data[j] = data[j-h];
data[j] = tmp;
}
}
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct node{
char data;
struct node *left,*right;
}Node;
Node* EXPR();
Node* FACTOR();
Node* makeNode(char data);
void printInfix(Node* root);
Node* root;
char expr[256];
int pos;
int main(){
scanf("%s",expr);
pos = strlen(expr) - 1;
root = EXPR();
printInfix(root);
//printf("\n");
}
Node* EXPR(){ // FACTOR | EXPR OP FACTOR
Node* node,*right;
char temp;
if(pos >= 0){
node = FACTOR(); //FACTOR
if(pos >= 0){
temp = expr[pos--];
if(temp == '|' || temp == '&'){ //EXPR OP FACTOR
right = node;
node = makeNode(temp);
node->right = right;
node->left = EXPR();
}
}
}
return node;
}
Node* FACTOR(){ // ID | (EXPR)
char temp;
Node* node;
if(pos >= 0){
temp = expr[pos--];
if(temp >= 'A' && temp <= 'D'){ //ID
node = makeNode(temp);
}else if(temp == ')'){
node = EXPR();
if(pos >= 0 && expr[pos+1] != '(')printf("WEED\n");
}
}
return node;
}
Node* makeNode(char data){
Node* node = (Node*)malloc(sizeof(Node));
node->left = NULL;
node->right = NULL;
node->data = data;
return node;
}
void printInfix(Node* root){
//left
if(root->left != NULL)printInfix(root->left);
//root
printf("%c",root->data);
//right
if(root->right != NULL){
char right = (root->right)->data;
if(right == '|' || right == '&')printf("(");
printInfix(root->right);
if(right == '|' || right == '&')printf(")");
}
}
|
C
|
#include<stdio.h>
#include<malloc.h>
struct node {
int data;
struct node* next;
};
#define size sizeof(struct node)
struct node* ins( struct node* head, int val) {
struct node* newNode = (struct node* )malloc(size);
newNode->data = val;
newNode->next = NULL;
if (head == NULL) { return newNode; }
struct node* temp = head;
while( temp->next != NULL ) {
temp = temp->next;
}
temp->next = newNode;
return head;
}
void printLinkedList(struct node *head) {
while (head != NULL) {
printf("%d", head->data);
if(head != NULL && head->next!=NULL) { printf("-->"); }
head = head->next;
}
}
void printFromLast(struct node* head, int pos) {
int length = 0;
struct node* temp = head;
while( temp != NULL) {
length++;
temp = temp->next;
}
temp = head;
for (int i = 1; i < length - pos + 1; i++) { temp = temp->next; }
printf("\nData at %d-pos from last node is: %d", pos, temp->data);
}
int main () {
struct node* head = NULL;
head = ins(head, 20);
head = ins(head, 30);
head = ins(head, 40);
head = ins(head, 50);
head = ins(head, 60);
head = ins(head, 70);
printLinkedList(head);
printFromLast(head, 2);
}
|
C
|
#include <stdio.h>
#include <errno.h>
#include <string.h>
#include <sys/epoll.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdlib.h>
#include <netinet/in.h>
#include <sys/types.h> /* See NOTES */
#include <sys/socket.h>
#include <arpa/inet.h>
#include <assert.h>
#include <pthread.h>
#include "Server.h"
#include "HashTable.h"
#define set_nonblocking(fd) do { \
int option = fcntl(fd, F_GETFL); \
fcntl(fd, F_SETFL, option | O_NONBLOCK); \
} while(0);
#define MAX_EVENT_NUMBER 1024
#define BUFF_SIZE 1024
#define DATA_STORAGE_INIT_SIZE 65536
typedef struct accept_client_param {
int server_fd;
int epfd;
} accept_client_param_t;
void * accept_client(void * context) {
accept_client_param_t * param = (accept_client_param_t *)context;
int client_fd;
struct sockaddr_in client_addr;
socklen_t client_addr_len = sizeof(client_addr);
int client_fd_len;
while (client_fd = accept(param->server_fd, (struct sockaddr *)&client_addr, &client_addr_len)) {
struct epoll_event event;
event.data.fd = client_fd;
event.events = EPOLLIN | EPOLLET;
epoll_ctl(param->epfd, EPOLL_CTL_ADD, client_fd, &event);
set_nonblocking(client_fd);
}
}
int main(int argc, char **argv) {
if (argc < 2) {
printf("server [ip]\n");
return 0;
}
HashTable * dataStorage = initHashWithSize(DATA_STORAGE_INIT_SIZE);
Server * server = initServer(dataStorage);
struct sockaddr_in server_address;
server_address.sin_port = ntohs(12345);
server_address.sin_family = AF_INET;
inet_aton(argv[1], &server_address.sin_addr);
int server_fd = socket(AF_INET, SOCK_STREAM, 0);
assert(server_fd >= 0);
int ret = bind(server_fd, (struct sockaddr *)&server_address, sizeof(server_address));
assert(ret >= 0);
ret = listen(server_fd, 5);
assert(ret >= 0);
int epfd = epoll_create(5);
assert(epfd >= 0);
pthread_t handle;
accept_client_param_t param;
param.server_fd = server_fd;
param.epfd = epfd;
ret = pthread_create(&handle, NULL, accept_client, ¶m);
assert(ret == 0);
struct epoll_event events[MAX_EVENT_NUMBER];
char read_buff[BUFF_SIZE];
char * send_buff;
int is_closed = 1;
while(1) {
ret = epoll_wait(epfd, events, MAX_EVENT_NUMBER, -1);
assert(ret >= 0);
int i;
for (i = 0; i < ret; i++) {
int client_fd = events[i].data.fd;
server->fd = client_fd;
if (events[i].events & EPOLLIN) {
while (1) {
memset(read_buff, '\0', BUFF_SIZE);
ret = recv(client_fd, read_buff, BUFF_SIZE - 1, 0);
if (ret < 0) {
if (errno == EAGAIN || errno == EWOULDBLOCK) {
break;
}
// 连接断开
server->clientClose(server);
close(client_fd);
break;
}
if (ret == 0) {
// 连接断开
server->clientClose(server);
close(client_fd);
break;
}
is_closed = 0;
server->appendRecv(server, read_buff, ret);
}
if (is_closed) {
break;
}
send_buff = server->run(server);
send(client_fd, send_buff, strlen(send_buff) + 1, 0);
}
if (events[i].events & EPOLLRDHUP || events[i].events & EPOLLHUP) {
// 连接断开
server->clientClose(server);
close(client_fd);
}
}
}
server->destroy(server);
close(server_fd);
}
|
C
|
#include "parser/parse.h"
Request *
newRequest() {
Request *request = (Request *) malloc(sizeof(Request));
request->header_count=0;
request->content_length = -1;
request->close = 0;
request->headers = 0;
return request;
}
/**
* Given a char buffer returns the parsed request headers
*/
int
parse(Request *request, char *buffer, int size) {
set_parsing_options(buffer, size, request);
int ret;
if ((ret = yyparse()) == PARSELINE) {
return 1;
} else if (ret == PARSEHEADER) {
return 2;
}
return 0;
}
void
addHeader(Request *request, char *name, char *value) {
Request_header *header = malloc(sizeof(Request_header));
strncpy(header->header_name, name, 4096);
strncpy(header->header_value, value, 4096);
header->next = request->headers;
request->headers = header;
request->header_count ++;
if (strcasecmp(name, "connection") == 0) {
if (strcasecmp(value, "close") == 0) {
request->close = 1;
} else {
request->close = 0;
}
return ;
}
if(strcasecmp(name, "content-length") == 0) {
request->content_length = atoi(value);
return;
}
if(strcasecmp(name, "content_length") == 0) {
request->content_length = atoi(value);
return;
}
}
void
freeRequest(Request *request) {
Request_header *h = request->headers, *tmp;
while (h) {
tmp = h;
h = h->next;
free(tmp);
}
if(request)
free(request);
}
Request *
copyRequest(Request *request) {
Request *req = (Request *) malloc(sizeof(Request));
Request_header *h, *p;
req->header_count=request->header_count;
req->content_length = request->content_length;
req->close = request->close;
req->headers = 0;
/*
char http_version[50];
char http_method[50];
char http_uri[4096];
*/
strcpy(req->http_method, request->http_method);
strcpy(req->http_uri, request->http_uri);
strcpy(req->http_version,request->http_version);
for (h=request->headers; h; h=h->next) {
p = (struct Request_header *)malloc(sizeof(struct Request_header));
p->next = req->headers;
strcpy(p->header_name, h->header_name);
strcpy(p->header_value, h->header_value);
req->headers = p;
}
return req;
}
|
C
|
/********************************************
Target MCU & clock speed: ATmega328P @ 8Mhz internal
Name : BlinkLED.c
Author : Insoo Kim (insoo@hotmail.com)
Date : April 18, 2015
Description: Blink LED at PB0 every second.
HEX size[Byte]: 166 out of 32K
Ref:
********************************************/
#include <avr/io.h>
#include <util/delay.h>
#define halfSec 63 // 0.5 second checked by oscilloscope
#define ledPin 0
void initIO();
int main(void)
{
initIO();
while(1)
{
PORTB ^= 1 << ledPin; /* toggle the LED */
_delay_ms(halfSec); /* max is 262.14 ms / F_CPU in MHz */
}
return 0; // never reach here
}//main
//-----------------------------------
void initIO()
{
DDRB |= _BV(ledPin); //output
}//initIO
|
C
|
#include <stdio.h>
int main()
{
int a,b;
printf("Inserire i valori di a e b per trovare il valore di x nell'equazione ax + b = 0\n");
printf("a: ");
scanf("%d",&a);
printf("b: ");
scanf("%d",&b);
b = b*(-1);
printf("x = %d/%d", b,a);
return 0;
}
|
C
|
#include<iostream>
using namespace std;
int checkTwo(int n);
int bye1(int p);
int bye2(int p);
int main()
{
int p;
cout<<"enter the number of players: ";
cin>>p;
bye1(p);
bye2(p);
return 0;
}
int bye1(int p)
{
int a;
for(int i=0;i<p;i++)
{
a=p-i;
a=a/2;
a=a+i;
if(a%2==0)
{
if(checkTwo(a))
{
cout<<"the number players of bye given based on first condition(2^n) is:"<<i<<endl;
return 0;
}
}
}
return 0;
}
int bye2(int p)
{
int c=0,p1=p;
for(int i=0;i<p1;i++)
{
if(checkTwo(p))
{
goto x;
}
if(p%2==0)
{
p=p/2;
continue;
}
else
{
c++;
p=(p/2)+1;
}
}
x:cout<<"the number players of bye given based on second condition(even) is:"<<c<<endl;
return 0;
}
int checkTwo(int n)
{
for(int i=0;n!=1;i++)
{
if(n%2!=0)
{
break;
}
n=n/2;
}
if(n==1)
return 1;
else
return 0;
}
|
C
|
//BOJ 1193 분수찾기
#include <stdio.h>
int main() {
int i = 1, j = 2, k = 1, tmp = 0, cnt = 1, n = 0, m = 0;
scanf("%d", &i);
while (i != 1) {
tmp = k;
k += j;
++j;
++cnt;
if (i <= k) {
break;
}
}
if (i == 1) {
printf("1/1");
return 0;
}
i -= tmp;
if ((cnt % 2) == 1) {
m = cnt - (i - 1);
n = j - m;
printf("%d/%d", m, n);
} else if ((cnt % 2) == 0) {
n = cnt - (i - 1);
m = j - n;
printf("%d/%d", m, n);
}
return 0;
}
|
C
|
main() {
int matriz[10][10];
int i;
int j;
int x;
int y;
for (i=0 ; i<10 ; i++)
for (j=0 ; j<10 ; j++)
matriz[i][j] = 0;
printf("\nEntre com x e y: \n");
scanf("%d%d",&x,&y);
for(i=x-1 ; i<=x+1 ; i++)
for (j=y-1 ; j<=y+1 ; j++)
if (((i!=x)||(j!=y))&&((i>=0)&&(j>=0)&&(i<10)&&(j<10)))
matriz[i][j] = 1;
for (i=0 ; i<10 ; i++){
printf("\n\n");
for (j=0 ; j<10 ; j++){
printf(" %d",matriz[i][j]);
}
}
getch();
}
|
C
|
#include <stdio.h>
#include <fcntl.h>
static int compdata[20000];
static int compindx=0;
void main(int argc, char **argv)
{
int width, height, x, y, i;
long next, last;
if(argc < 3)
return;
width = atoi(argv[1]);
height= atoi(argv[2]);
setmode(1, O_BINARY);
for(y=0; y<height; y++) // compress each line (1-D compression)
{
scanf("%ld,\n", &last); // initialise last pixel value & counter
i = 1;
for(x=1; x<width; x++) // for each pixel value..
{
scanf("%ld,\n", &next);
if(next == last) // if it hasn't changed..
i++; // increment counter
else // otherwise..
{
compdata[compindx++] = i; // store counter & pixel value..
compdata[compindx++] = (int)last;
last = next; // store new pixel value & ..
i = 1; // clear counter.
}
}
if(i) // if we have not done it yet..
{
compdata[compindx++] = i; // store last pixel value
compdata[compindx++] = (int)last;
}
}
write(1, &width, sizeof(int));
write(1, &height, sizeof(int));
write(1, &compindx, sizeof(int));
write(1, compdata, compindx*sizeof(int));
}
|
C
|
#include <math.h>
#include "vector3.h"
float vector3_dot(struct vector3 a, struct vector3 b)
{
return a.x * b.x + a.y * b.y + a.z * b.z;
}
float vector3_length(struct vector3 a)
{
return sqrt(a.x * a.x + a.y * a.y + a.z * a.z);
}
int vector3_cmp(struct vector3 a, struct vector3 b)
{
return a.x == b.x && a.y == b.y && a.z == b.z;
}
int vector3_is_zero(struct vector3 a)
{
return a.x == 0 && a.y == 0 && a.z == 0;
}
|
C
|
#include "Graph.h"
#define WHITE 0
#define GRAY 1
#define BLACK 2
typedef struct edge
{
int id;
struct edge *next;
int weight;
} Edge;
typedef struct vertex
{
int id;
struct vertex *next;
Edge *edges;
int num_edges;
int d; //discovery time
int t; //end time
int visited;
} Vertex;
struct graph
{
Vertex *vertices;
unsigned int num_vertices;
};
static Vertex *create_vertex(int id, Vertex *next, Edge *edges, int num_edges)
{
Vertex *n = (Vertex *)malloc(sizeof(Vertex));
n->id = id;
n->next = next;
n->edges = edges;
n->num_edges = num_edges;
n->d = 0;
n->t = 0;
return n;
}
static Edge *create_edge(int id, Edge *next, int weight)
{
Edge *e = (Edge *)malloc(sizeof(Edge));
e->id = id;
e->next = next;
e->weight = weight;
}
Graph *graph_createEmpty()
{
Graph *g = (Graph *)malloc(sizeof(Graph));
g->vertices = NULL;
g->num_vertices = 0;
return g;
}
Graph *graph_create(int n)
{
Graph *g = (Graph *)malloc(sizeof(Graph));
g->vertices = NULL;
g->num_vertices = n;
if (n >= 1)
{
g->vertices = create_vertex(0, NULL, NULL, 0);
Vertex *it = g->vertices;
for (int i = 1; i < n; i++)
{
it->next = create_vertex(i, NULL, NULL, 0);
it = it->next;
}
}
return g;
}
void graph_addVertex(Graph *g, int v)
{
if (g)
{
Vertex *it = g->vertices;
Vertex *ant = NULL;
int exists = 0;
if (it)
{
while (it && it->id <= v)
{
if (it->id == v)
exists = 1;
ant = it;
it = it->next;
}
if (!exists)
{
Vertex *n;
if (it)
n = create_vertex(v, it, NULL, 0);
else
n = create_vertex(v, NULL, NULL, 0);
if (!ant)
g->vertices = n;
else
ant->next = n;
}
}
else
g->vertices = create_vertex(v, NULL, NULL, 0);
g->num_vertices++;
}
}
void graph_removeVertex(Graph *g, int v)
{
if (g)
{
Vertex *ant_v = NULL;
Vertex *it = g->vertices;
Vertex *temp = NULL;
int clear = 0;
while (it)
{
if (it->id == v)
{
if (ant_v == NULL)
g->vertices = it->next;
else
ant_v->next = it->next;
temp = it;
clear = 1;
g->num_vertices--;
}
else
{
Edge *ed = it->edges;
Edge *ant_ed = NULL;
Edge *temp_e = NULL;
while (ed && ed->id <= v)
{
if (ed->id == v)
{
if (!ant_ed)
{
it->edges = ed->next;
}
else
{
ant_ed->next = ed->next;
}
temp_e = ed;
it->num_edges--;
break;
}
if (temp_e)
{
free(temp_e);
temp_e = NULL;
}
else
ant_ed = ed;
ed = ed->next;
}
}
if (clear)
clear = 0;
else
ant_v = it;
it = it->next;
}
free(temp);
}
}
int graph_hasVertex(Graph *g, int v)
{
if (g)
{
Vertex *it = g->vertices;
while (it)
{
if (it->id == v)
return 1;
else if (it->id > v)
return 0;
it = it->next;
}
}
return 0;
}
int graph_getVertexCount(Graph *g)
{
return (g) ? g->num_vertices : 0;
}
void graph_addEdge(Graph *g, int v1, int v2, int weight)
{
if (g)
{
Vertex *it = g->vertices;
while (it && it->id <= v1)
{
if (it->id == v1)
{
if (graph_hasVertex(g, v2))
{
Edge *e_it = it->edges;
Edge *ant = NULL;
while (e_it && e_it->id <= v2)
{
ant = e_it;
e_it = e_it->next;
if (e_it->id == v2)
{
//updates the weight
e_it->weight = weight;
break;
}
}
if (!ant)
{
it->edges = create_edge(v2, NULL, weight);
it->num_edges++;
}
else
{
Edge *ed = create_edge(v2, ant->next, weight);
ant->next = ed;
it->num_edges++;
}
}
break;
}
it = it->next;
}
}
}
void graph_removeEdge(Graph *g, int v1, int v2)
{
if (g)
{
Vertex *it = g->vertices;
while (it && it->id <= v1)
{
if (it->id == v1)
{
if (graph_hasVertex(g, v2))
{
Edge *ed = it->edges;
Edge *ant_ed = NULL;
Edge *temp_e = NULL;
while (ed)
{
if (ed->id == v2)
{
if (!ant_ed)
{
it->edges = ed->next;
}
else
{
ant_ed->next = ed->next;
}
temp_e = ed;
break;
}
ed = ed->next;
free(temp_e);
}
}
it->num_edges--;
break;
}
it = it->next;
}
}
}
int graph_hasEdge(Graph *g, int v1, int v2)
{
if (g)
{
Vertex *it = g->vertices;
while (it && it->id <= v1)
{
if (it->id == v1)
{
if (graph_hasVertex(g, v2))
{
Edge *ed = it->edges;
while (ed)
{
if (ed->id == v2)
{
return 1;
}
else if (ed->id > v2)
return 0;
}
}
break;
}
it = it->next;
}
}
return 0;
}
int graph_getEdgeWeight(Graph *g, int v1, int v2)
{
if (g)
{
Vertex *it = g->vertices;
while (it && it->id <= v1)
{
if (it->id == v1)
{
if (graph_hasVertex(g, v2))
{
Edge *ed = it->edges;
while (ed)
{
if (ed->id == v2)
{
return ed->weight;
}
else if (ed->id > v2)
return 0;
}
}
break;
}
it = it->next;
}
}
return 0;
}
int graph_getAdjacentVertices(Graph *g, int v, int **a)
{
if (g)
{
Vertex *it = g->vertices;
while (it && it->id <= v)
{
if (it->id == v)
{
if (it->num_edges == 0)
{
(*a) = NULL;
return 0;
}
Edge *ed = it->edges;
(*a) = (int *)malloc(sizeof(int) * it->num_edges);
int ind = 0;
while (ed)
{
(*a)[ind] = (int *)ed->id;
ind++;
ed = ed->next;
}
return it->num_edges;
}
it = it->next;
}
}
(*a) = NULL;
return 0;
}
void graph_print(Graph *g)
{
if (g)
{
Vertex *it = g->vertices;
while (it)
{
fprintf(stdout, "Vertex: %d Edges: ", it->id);
Edge *it_e = it->edges;
while (it_e && it_e->next)
{
fprintf(stdout, "(%d, %d), ", it_e->id, it_e->weight);
it_e = it_e->next;
}
if (it_e)
fprintf(stdout, "(%d, %d)\n", it_e->id, it_e->weight);
else
fprintf(stdout, "\n");
it = it->next;
}
}
}
static void set_dfsDiscoverytime(Graph *g, int id, int time)
{
if (g)
{
int i = 0;
Vertex *it = g->vertices;
while (it->id != id)
{
it = it->next;
}
if (it)
it->d = time;
}
}
static int get_dfsDiscoverytime(Graph *g, int id)
{
if (g)
{
int i = 0;
Vertex *it = g->vertices;
while (it->id != id)
{
it = it->next;
}
if (it)
return it->d;
else
return -1;
}
}
static void set_dfsEndtime(Graph *g, int id, int time)
{
if (g)
{
int i = 0;
Vertex *it = g->vertices;
while (it->id != id)
{
it = it->next;
}
if (it)
it->t = time;
}
}
static int get_dfsEndtime(Graph *g, int id)
{
if (g)
{
int i = 0;
Vertex *it = g->vertices;
while (it->id != id)
{
it = it->next;
}
if (it)
return it->t;
else
return -1;
}
}
static int get_id(Graph *g, int pos)
{
if (!g)
return -1;
if (g->num_vertices < pos)
return -1;
Vertex *it = g->vertices;
int i = 0;
while (it && i < pos)
{
it = it->next;
}
if (it)
return it->id;
}
static int get_pos(Graph *g, int id)
{
if (!g)
return -1;
Vertex *it = g->vertices;
int i = 0;
while (it && it->id != id)
{
it = it->next;
i++;
}
if (it)
return i;
return -1;
}
static int dfs_visit(Graph *g, int u, int total_t, int *color)
{
color[u] = GRAY;
set_dfsDiscoverytime(g, get_id(g, u), ++total_t);
int *arr = NULL;
int n = graph_getAdjacentVertices(g, get_id(g, u), &arr);
if (arr)
{
for (int i = 0; i < n; i++)
{
int v = get_pos(g, arr[i]);
if (color[v] == WHITE)
total_t = dfs_visit(g, v, total_t, color);
}
free(arr);
}
printf("No visitado: %d\n", get_id(g, u));
color[u] = BLACK;
set_dfsEndtime(g, get_id(g, u), ++total_t);
return total_t;
}
void graph_dfs(Graph *g)
{
int total_t = 0;
int num_vertices = graph_getVertexCount(g);
int *color = (int *)malloc(sizeof(int *) * num_vertices);
for (int i = 0; i < num_vertices; i++)
color[i] = WHITE;
for (int u = 0; u < num_vertices; u++)
{
if (color[u] == WHITE)
total_t = dfs_visit(g, u, total_t, color);
}
fprintf(stdout, "Total t: %d\n", total_t);
free(color);
}
static Vertex *get_vertex(Graph *g, int id)
{
if (!g)
return NULL;
Vertex *it = g->vertices;
while (it && it->id != id)
it = it->next;
return it;
}
void graph_dfs_stack(Graph *g)
{
if (!g)
return;
Vertex *it = g->vertices;
while (it)
{
it->visited = 0;
it = it->next;
}
it = g->vertices;
Stack *s = stack_create(g->num_vertices);
while (it)
{
if (!it->visited)
{
stack_push(s, it->id);
while (!stack_empty(s))
{
int *arr = NULL;
int id = 0;
if (!stack_pop(s, &id))
return;
Vertex *temp = get_vertex(g, id);
temp->visited = 1;
int n = graph_getAdjacentVertices(g, id, &arr);
printf("No visitado: %d\n", id);
if (arr)
{
for (int i = 0; i < n; i++)
{
temp = get_vertex(g, arr[i]);
if (temp && !temp->visited)
stack_push(s, arr[i]);
}
free(arr);
}
}
}
it = it->next;
}
}
int graph_checkCicle(Graph *g)
{
if (!g)
return 0;
Vertex *it = g->vertices;
while (it)
{
it->visited = 0;
it = it->next;
}
it = g->vertices;
Stack *s = stack_create(g->num_vertices);
while (it)
{
if (!it->visited)
{
stack_push(s, it->id);
while (!stack_empty(s))
{
int *arr = NULL;
int id = 0;
if (!stack_pop(s, &id))
return 0;
Vertex *temp = get_vertex(g, id);
temp->visited = 1;
int n = graph_getAdjacentVertices(g, id, &arr);
if (arr)
{
for (int i = 0; i < n; i++)
{
temp = get_vertex(g, arr[i]);
if (temp && !temp->visited)
stack_push(s, arr[i]);
else
return 1;
}
free(arr);
}
}
}
it = it->next;
Vertex *it2 = g->vertices;
while (it2)
{
it2->visited = 0;
it2 = it2->next;
}
}
return 0;
}
|
C
|
typedef struct lista {
float info;
lista *prox;
}Lista;
typedef struct pilha {
Lista *topo;
}Pilha;
Pilha *pilha_cria(void){
Pilha *p= (Pilha*) malloc(sizeof(Pilha));
p->topo=NULL;
return p;
}
void pilha_push(Pilha *p, float v){
Lista *n = (Lista*) malloc (sizeof(Lista));
n->info=v;
n->prox =p->topo;
p->topo=n;
}
int pilha_vazia(Pilha *p){
return (p->topo==NULL);
}
float pilha_pop(Pilha *p){
Lista *t;
float v;
t=p->topo;
v=t->info;
p->topo=t->prox;
free(t);
return v;
}
void pilha_mostra(Pilha *p){
Lista *q;
printf("\nPilha\n");
for(q=p->topo;q!=NULL;q=q->prox)
printf("%.0f\n", q->info);
printf("\n");
}
void pilha_libera(Pilha *p){
Lista *q= p->topo;
while (q!=NULL) {
Lista *t=q->prox;
free(q);
q=t;
}
free(p);
}
|
C
|
#include "Chess.h"
/* globals */
int minimax_depth = 1;
//0 for white, 1 for black
int userColor = 0;
//0 for white, 1 for black
int whosTurn = 0;
//1 for two players, 2 for AI
int gameMode = 1;
//current board
int board[BOARD_SIZE][BOARD_SIZE];
//pieces on the board summary
int pieces[6][2];
//first Window in GUI: -1 / settings mode: 0 / game mode: 1
int gameState = 0;
//string builder flag
int stringFlag = 0;
//First cmd Input
char* cmdInput = NULL;
//First cmd GUI
char* cmdGUI = NULL;
//AI Move
move* AIMove = NULL;
//end game flag
int endGameFlag = 0;
int main( int argc, char* args[] ){
if (argc == 2){
// if the argument is "GUI" run the game on GUI mode
if ( (strcmp(args[1], "GUI") == 0) || (strcmp(args[1], "gui") == 0) || (strcmp(args[1], "Gui") == 0) ){
mainGUI();
return 0;
}
}
mainConsole();
return 0;
}
int mainGUI(){
/* GUI Event*/
SDL_Event e;
// input from the player to be executed
cmdInput = (char*) malloc (50*sizeof(char));
if (cmdInput == NULL){
perror("Error: standard function malloc has failed");
quitGUI();
quit();
return 0;
}
cmdInput[0] = '\0';
// the input from the GUI to be parsed into a string command
cmdGUI = (char*) malloc (50*sizeof(char));
if (cmdGUI == NULL){
perror("Error: standard function malloc has failed");
quitGUI();
quit();
return 0;
}
cmdGUI[0] = '\0';
/* initiating the game */
init();
gameState = -1;
while (strcmp(cmdInput, "quit")){
/* game setting area */
if (gameState == -1){
//Draw the window
DrawFirstWindow();
//starting board initialization
init_board(board);
//get Event
while (SDL_PollEvent(&e) != 0) {
//analyze the GUI event
analyzeFirst(e);
strcpy(cmdInput, cmdGUI);
if(strcmp(cmdInput, "continue") != 0) {
//execute command in the game
setFuncs(cmdInput);
}
}
}
/*Settings area*/
else if (gameState == 0){
//Draw
DrawSecondWindow();
//get Event
while (SDL_PollEvent(&e) != 0) {
if(stringFlag==2 && strcmp(cmdInput, "continue") != 0) {
//execute command in the game
exeGUI(setFuncs(cmdInput));
stringFlag=0;
break;
}
if (stringFlag==1){
//analyze the GUI event
analyzeSecond(e);
strcat(cmdInput, cmdGUI);
}
else if (!stringFlag){
//analyze the GUI event
analyzeSecond(e);
strcpy(cmdInput, cmdGUI);
}
}
}
/*game area*/
else if (gameState == 1){
//Draw
DrawThirdWindow();
if (gameMode == 2 && endGameFlag < 3){
//computers turn
if(whosTurn != userColor){
//get move from the minimax
AIMove = minimaxRoot(whosTurn, minimax_depth, INT_MIN, INT_MAX, 0);
//make the given move
movePiece(AIMove, whosTurn, abs(board[AIMove->from.column][AIMove->from.row]) -1, "queen",1);
printf("AI Move:\n");
print_move(AIMove);
//check for tie mate or check
switch (CMT(whosTurn)){
case(0):
exeGUI(1);
whosTurn = 1 - whosTurn;
break;
case (1) :
exeGUI(2);
whosTurn = 1 - whosTurn;
break;
case (2) :
exeGUI(3);
whosTurn = 1 - whosTurn;
break;
case (3) :
exeGUI(4);
gameMode = 1;
break;
}
delMove(AIMove);
AIMove = NULL;
}
}
//Draw
DrawThirdWindow();
//get Event
if (SDL_WaitEvent(&e)) {
if(stringFlag==2 && strcmp(cmdInput, "continue") != 0) {
//execute command in the game
endGameFlag = gameFuncs(cmdInput);
exeGUI(endGameFlag);
stringFlag=0;
}
if (stringFlag==1){
//analyze the GUI event
analyzeThird(e);
strcat(cmdInput, cmdGUI);
}
else if (!stringFlag){
//analyze the GUI event
analyzeThird(e);
strcpy(cmdInput, cmdGUI);
}
}
}
}
quitGUI();
return 0;
}
int mainConsole(){
/* initiating the game */
init_board(board);
print_board(board);
print_message(WELCOME_TO_CHESS);
while (endGameFlag != 3 && endGameFlag != 4 ){
/*game setting mode*/
if (gameState == 0){
print_message(ENTER_SETTINGS);
//get input from the console
cmdInput = scanInput();
if (strcmp(cmdInput, "quit") == 0) {
if(cmdInput != NULL){
free(cmdInput);
}
quit();
} else {
//execute command in the game
setFuncs(cmdInput);
free(cmdInput);
}
}
/*game play area*/
if (gameState == 1){
//player vs player
if (gameMode == 2){
if(whosTurn != userColor){
AIMove = minimaxRoot(whosTurn, minimax_depth, INT_MIN, INT_MAX, 0);
movePiece(AIMove, whosTurn, abs(board[AIMove->from.column][AIMove->from.row]) -1, "queen",1);
printf("AI Move:\n");
print_move(AIMove);
switch (CMT(whosTurn)){
case (1) :
printf ("Check!\n");
break;
case (2) :
printf ("The game ends with a tie\n");
break;
case (3) :
printf ("Mate! %s player wins the game\n", (whosTurn==0) ? "White" : "Black");
break;
}
print_board(board);
whosTurn = 1 - whosTurn;
delMove(AIMove);
AIMove = NULL;
}
}
printf("%s player - enter your move:\n", (whosTurn == 0) ? "White" : "Black");
//get input from the console
cmdInput = scanInput();
if (strcmp(cmdInput, "quit") == 0){
free(cmdInput);
quit();
} else {
//execute command in the game
endGameFlag = gameFuncs(cmdInput);
if(AIMove != NULL){
delMove(AIMove);
AIMove = NULL;
}
free(cmdInput);
}
}
}
quit();
return 0;
}
|
C
|
#include "minishell.h"
void print_input(unsigned char c) {
if (is_ctrl_key(c))
{
ft_putnbr(c);
ft_putstr("\r\n");
}
else
{
ft_putnbr(c);
ft_putstr(" (");
ft_putchar(c);
ft_putstr(")");
ft_putstr("\r\n");
}
}
|
C
|
// Add necessary #include's.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "records.h"
// You may add helper functions. Actually there is a reason you should!
int get_yob(FILE *f, const char *name, short *pyob)
{
fseek(f, 0, SEEK_SET);
record *test = (record *)malloc(sizeof(record));
while(1){
fread(test, sizeof(record), 1, f);
if(feof(f)){
break;
}
char temp[test->name_len];
strncat(temp, test->name, test->name_len);
if (strcmp(temp, name) == 0){
*pyob = test->yob;
return 1;
}
}
return 0;
}
void set_yob(FILE *f, const char *name, short yob)
{
fseek(f, 0, SEEK_SET);
int iterator = 0;
record *test = (record *)malloc(sizeof(record));
while(1){
fread(test, sizeof(record), 1, f);
iterator++;
if(feof(f)){
break;
}
char temp[test->name_len];
strncat(temp, test->name, test->name_len);
if (strcmp(temp, name) == 0){
if(fseek(f, (sizeof(record)*iterator)-2, SEEK_SET) == 0){
fwrite(&yob, sizeof(yob), 1, f);
return;
}
}
}
record *new = (record *)malloc(sizeof(record));
strcpy(new->name, name);
new->yob = yob;
new->name_len = strlen(name);
fwrite(new, sizeof(record), 1, f);
}
|
C
|
void start_game()
{
//Initializes Game
get_word();
word_len = strlen(word);
memset(guessed_letters, 0, sizeof guessed_letters);
attempts = 10;
}
void get_input()
{
//Gets guess from user and checks
//To see if that letter is in the word
int i;
int letter_hit = 0; //Used to tell if the guess letter is in the word
printf("\nYour guess: \n");
scanf(" %c", user_guess);
for(i=0; i < word_len; i++)
{
if(user_guess[0] == word[i])
{
guessed_letters[i] = user_guess[0];
letter_hit ++;
}
}
if(letter_hit > 0)
{
return;
}
else
{
attempts --;
}
}
void print_blanks()
{
/////////////////////////////////////////////////
/// Prints out a number of blanks equal to the
/// Length of the word
/// Then fills the blanks with the guessed letters
/////////////////////////////////////////////////
int i, j;
draw_platform();
for(i=0; i<word_len; i++)
{
printf("%c", guessed_letters[i]);
printf(" ");
}
printf("\n");
for(j=0; j<word_len - 1; j++)
{
printf("%s", blank);
printf(" ");
}
printf("\n");
}
void draw_platform()
{
/////////////////////////////////////////////////
/// Draws a new segment onto
/// The platform every time
/// The user gets a wrong guess
/////////////////////////////////////////////////
char *platform[]={
" ===\n",
" |\n"
" |\n"
" |\n"
" ===\n",
" =====|\n"
" |\n"
" |\n"
" |\n"
" ===\n",
" |=====|\n"
" |\n"
" |\n"
" |\n"
" ===\n",
" |=====|\n"
" O |\n"
" |\n"
" |\n"
" ===\n",
" |=====|\n"
" O |\n"
" | |\n"
" |\n"
" ===\n",
" |=====|\n"
" O |\n"
" |- |\n"
" |\n"
" ===\n",
" |=====|\n"
" O |\n"
" -|- |\n"
" |\n"
" ===\n",
" |=====|\n"
" O |\n"
" -|- |\n"
" | |\n"
" ===\n",
" |=====|\n"
" O |\n"
" -|- |\n"
" // |\n"
" ===\n"
};
switch(attempts)
{
case 9:
printf("\n\n%s\n", platform[0]);
break;
case 8:
printf("\n\n%s\n", platform[1]);
break;
case 7:
printf("\n\n%s\n", platform[2]);
break;
case 6:
printf("\n\n%s\n", platform[3]);
break;
case 5:
printf("\n\n%s\n", platform[4]);
break;
case 4:
printf("\n\n%s\n", platform[5]);
break;
case 3:
printf("\n\n%s\n", platform[6]);
break;
case 2:
printf("\n\n%s\n", platform[7]);
break;
case 1:
printf("\n\n%s\n", platform[8]);
break;
case 0:
printf("\n\n%s\n", platform[9]);
break;
}
}
void get_word()
{
srand(time(NULL));
char word[][16] = {
"green",
"yellow",
"purple",
"windows",
"linux",
"apple"
};
random_number = rand() % 6;
}
|
C
|
//
// Created by xixi2 on 2020/3/21.
//
#include <stdio.h>
#include <pthread.h>
#include <time.h>
#include <stdlib.h>
#include <unistd.h>
#include <semaphore.h>
#define BUFF_SIZE 3 // 缓冲区大小
//#define PRODUCE_THREAD_SIZE 5
#define PRODUCE_THREAD_SIZE 1
typedef struct node {
int data;
struct node *next;
} ListNode;
ListNode *head = NULL;
sem_t lock;
sem_t consume_sem;// 产品个数,消费者需要的资源
sem_t produce_sem;// 空缓冲区个数,生产者需要的资源
void *produce(void *ptr) {
int idx = *(int *) ptr;
while (1) {
try{
ListNode *pnew = (ListNode *) malloc(sizeof(ListNode));
pnew->data = rand() % 1000;
}catch(Exception &e){
e.w
}
sem_wait(&produce_sem);// 限制了生产者并发的数目
sem_wait(&lock); // 对临界区的访问要加锁
pnew->next = head;
head = pnew;
printf("+++++ producer: %lu, %d\n", pthread_self(), pnew->data);
sem_post(&lock);
sem_post(&consume_sem);
printf("producer tip customer, full: %d\n", consume_sem);
sleep(5);
}
return NULL;
}
void *consume(void *ptr) {
while (1) {
sem_wait(&consume_sem);
sem_wait(&lock);
ListNode *pdel = head;
if (pdel == NULL) {
printf("empty linkedlist\n");
} else {
printf("head : %d\n", head->data);
}
head = head->next;
printf("----- customer: %lu custom %d\n", pthread_self(), pdel->data);
pthread_mutex_unlock(&lock);
sem_post(&lock);
sem_post(&produce_sem);
free(pdel);
printf("customer, empty: %d\n", produce_sem);
sleep(5);
}
return NULL;
}
int main(int argc, char *argv[]) {
pthread_t con;
pthread_t pros[PRODUCE_THREAD_SIZE];
sem_init(&lock, 0, 1);
sem_init(&consume_sem, 0, 0);
sem_init(&produce_sem, 0, BUFF_SIZE);
pthread_create(&con, NULL, consume, NULL);
int thread_args[PRODUCE_THREAD_SIZE];
for (int i = 0; i < PRODUCE_THREAD_SIZE; i++) {
thread_args[i] = i + 1;
pthread_create(&pros[i], NULL, produce, (thread_args + i));
}
pthread_join(con, 0);
for (int i = 0; i < PRODUCE_THREAD_SIZE; i++)
pthread_join(pros[i], 0);
sem_destroy(&lock);
sem_destroy(&consume_sem);
sem_destroy(&produce_sem);
return 0;
}
|
C
|
class Solution {
public:
bool isScramble(string s1, string s2) {
string tmp1=s1;
string tmp2=s2;
sort(tmp1.begin(),tmp1.end());
sort(tmp2.begin(),tmp2.end());
if(tmp1!=tmp2){
return false;
}
return isSubScramble(s1,s2);
}
bool isSubScramble(string s1,string s2){
if(s1.size()!=s2.size()){
return false;
}
if(s1==s2){
return true;
}
for(int i=0;i<s1.size()-1;++i){
string s1_left(s1,0,i+1);
string s1_right(s1,i+1,s1.size()-i-1);
string s2_left(s2,0,i+1);
string s2_right(s2,i+1,s2.size()-i-1);
string tmp1l=s1_left;
string tmp1r=s1_right;
string tmp2l=s2_left;
string tmp2r=s2_right;
sort(tmp1l.begin(),tmp1l.end());
sort(tmp1r.begin(),tmp1r.end());
sort(tmp2l.begin(),tmp2l.end());
sort(tmp2r.begin(),tmp2r.end());
if(tmp1l==tmp2l){
if(isSubScramble(s1_left,s2_left) and isSubScramble(s1_right,s2_right)){
return true;
}
}
string s2r(s2,s2.size()-i-1,i+1);
string s2l(s2,0,s2.size()-i-1);
string tmpl=s2l;
string tmpr=s2r;
sort(tmpr.begin(),tmpr.end());
sort(tmpl.begin(),tmpl.end());
if(tmp1l==tmpr){
if(isSubScramble(s1_right,s2l) and isSubScramble(s1_left,s2r)){
return true;
}
}
}
return false;
}
};
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* treat_map.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: mdiallo <mdiallo@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/04/27 19:47:14 by mdiallo #+# #+# */
/* Updated: 2021/04/27 19:47:17 by mdiallo ### ########.fr */
/* */
/* ************************************************************************** */
#include "../../includes/cub3d.h"
static int check_map_norme(t_window *win_infos, char **map)
{
int x;
int y;
if (!*map || !**map)
return (ERROR);
y = 0;
while (y < win_infos->map->height)
{
x = 0;
if (ft_strlen(map[y]) != (size_t)win_infos->map->width)
return (ERROR);
while (x < win_infos->map->width)
{
if ((y == 0 && map[y][x] != '1')
|| (y == win_infos->map->height - 1 && map[y][x] != '1')
|| (x == 0 && map[y][x] != '1')
|| (x == win_infos->map->width - 1 && map[y][x] != '1'))
return (ERROR);
if (map[y][x] != '0' && map[y][x] != '1' && map[y][x] != '2')
return (ERROR);
x++;
}
y++;
}
return (SUCCES);
}
static void get_map_size(char *str, t_window *win_infos)
{
int i;
int j;
int width;
int height;
i = 0;
j = 0;
width = 0;
height = 0;
while (str[i] != '\n')
{
if (!is_whitespace(str[i]))
width++;
i++;
}
win_infos->map->width = width;
while (str[j] != '\0')
{
if (str[j] == '\n')
height++;
j++;
if (str[j] == '\0' && (j > 0 && str[j - 1] != '\n'))
height++;
}
win_infos->map->height = height;
}
static char **malloc_map(t_window *win_infos)
{
int i;
char **map;
map = (char **)malloc(sizeof(char *) * win_infos->map->height);
if (!map)
leave(1, win_infos, "Error\nDuring map malloc");
ft_bzero(map, sizeof(char *) * win_infos->map->height);
i = 0;
while (i < win_infos->map->height)
{
map[i] = (char *)malloc(sizeof(char) * win_infos->map->width);
if (!map[i])
leave(1, win_infos, "Error\nDuring map line malloc");
ft_bzero(map[i], sizeof(char) * win_infos->map->width);
i++;
}
return (map);
}
static char **init_map(char *str, char **map, t_window *win_infos)
{
int cursor;
int u;
int i;
u = 0;
i = 0;
while (u < win_infos->map->height)
{
cursor = 0;
while (str[i] && str[i] != '\n')
{
if (!is_whitespace(str[i]))
map[u][cursor++] = str[i];
if (str[i] == 'N' || str[i] == 'S' || \
str[i] == 'W' || str[i] == 'E')
{
set_start_pos(win_infos, str[i], cursor, u);
map[u][cursor - 1] = '0';
}
i++;
}
map[u++][cursor] = '\0';
i += 1;
}
return (map);
}
char **map_from_string(char *str, t_window *win_infos)
{
char **map;
get_map_size(str, win_infos);
map = malloc_map(win_infos);
map = init_map(str, map, win_infos);
if (!check_map_norme(win_infos, map))
leave(1, win_infos, "Error\nIn map format");
if (win_infos->player->posx == -20.0 || win_infos->player->posy == -20.0
|| win_infos->player->dir_x == -20.0
|| win_infos->player->dir_y == -20.0)
leave(1, win_infos, "Player pos/dir did'nt set");
free(str);
return (map);
}
|
C
|
#include <stdio.h> // printf()
#include <stdlib.h> // calloc(), atoi()
#include <math.h> // pow()
#include "die.h" // die()
#include "queue.h" // Queue, q_node
#define BASE 10
#define NDIGITS 2 * BASE - 1 // How many buckets will we use?
void radixsort(int* nums, int count); // Radixsort an array of ints (LSD variant)
int radix_len(int num); // Returns decimal digit count of a number
/* This function returns a digit on pos position.
* radix_digit(*something*, 1) returns the LSD.
*
* NOTE: Bear in mind that it's capable
* of returning values below 0 for
* negative num arguments.
*/
int radix_digit(int num, int pos);
int main(int argc, char const* argv[])
{
int* nums = calloc(argc - 1, sizeof(int));
for (int i = 0; i < argc - 1; i++) {
nums[i] = atoi(argv[i + 1]);
}
puts("Your arguments:");
for (int i = 0; i < argc - 1; i++)
printf("%d ", nums[i]);
puts("\n");
radixsort(nums, argc - 1);
puts("Your arguments (sorted):");
for (int i = 0; i < argc - 1; i++)
printf("%d ", nums[i]);
free(nums);
return 0;
}
void radixsort(int* nums, int count)
{
int digit, max;
Queue buckets[NDIGITS]; // One index per digit, including negatives
// Don't bother working on one-element and empty array
if (count < 2)
return;
for (int i = 0; i < NDIGITS; i++) { // Nullify each queue
buckets[i].head = NULL;
buckets[i].tail = NULL;
}
// Find the biggest number width
max = radix_len(nums[0]);
for (int i = 1; i < count; i++)
if (radix_len(nums[i]) > max)
max = radix_len(nums[i]);
// Go through each column
for (int i = 1; i <= max; i++) {
// of each element
for (int j = 0; j < count; j++) {
// to get the i-th digit from j-th nums[] element,
digit = radix_digit(nums[j], i) + BASE - 1; // compensate for negative digits
// and enqueue it to the corresponding digit-th bucket.
q_enq(buckets + digit, nums[j]);
}
// Take each element of nums[],
for (int j = 0; j < count; j++)
for (int k = 0; k < NDIGITS; k++) // and fill it with whatever
while (buckets[k].head != NULL) // we find in each non-empty bucket.
nums[j++] = q_deq(buckets + k);
}
}
int radix_len(int num)
{
int i;
// Try %'ing num by powers of BASE until it stops changing num's value
for (i = 1; num % (int)pow(BASE, i) != num; i++)
;
return i;
}
int radix_digit(int num, int pos)
{
if (pos < 1)
die("Requested a digit on an invalid position");
num %= (int)pow(BASE, pos); // Chop the left part off
num /= (int)pow(BASE, pos - 1); // Chop the right part off
return num;
}
|
C
|
#include <stdio.h>
void main()
{
int num = 156;
int digit, sum = 0;
while(num > 0)
{
digit = num % 10; // take rightmost digit
// printf("%d",digit);
sum += digit;
num /= 10; // remove rightmost digit
}
printf("%d", sum);
}
|
C
|
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main()
{
int n, m, i, j;
int linha=0,coluna=0;
int vet[10][10];
scanf("%d %d", &n, &m);
for(i=1;i<=n;i++)
{
for(j=1;j<=m;j++)
{
scanf("%d%d", &vet[i][j], &vet[i][j]);
if(vet[i][j] == 1)
{
if(j>coluna)
{
coluna = j;
}
if(i>linha)
{
linha = i;
}
}
}
}
printf("%dx%d\n", coluna, linha);
return 0;
}
|
C
|
#include "draw.h"
extern Display *display;
extern Window window;
extern GC gc;
void drawBrightnessIcon() {
// get window attributes for width and height
XWindowAttributes win_attr;
XGetWindowAttributes(display, window, &win_attr);
// extract window width and height
int width = win_attr.width;
int height = win_attr.height;
XSetForeground(display, gc, strtoul(BG_COLOR, 0, 16));
XFillRectangle(display, window, gc, 0, 0, width, height);
XSetForeground(display, gc, strtoul(FG_COLOR, 0, 16));
for (int i=0; i < 12; i++) {
XFillArc(
display, window, gc,
60, 60,
80, 80,
30 * i * 64, 5 * 64);
}
XSetForeground(display, gc, strtoul(BG_COLOR, 0, 16));
XFillArc(
display, window, gc,
75, 75,
50, 50,
0 * 64, 360 * 64);
XSetForeground(display, gc, strtoul(FG_COLOR, 0, 16));
XFillArc(
display, window, gc,
85, 85,
30, 30,
0 * 64, 360 * 64);
}
void drawVolumeIcon() {
// get window attributes for width and height
XWindowAttributes win_attr;
XGetWindowAttributes(display, window, &win_attr);
// extract window width and height
int width = win_attr.width;
int height = win_attr.height;
XSetForeground(display, gc, strtoul(BG_COLOR, 0, 16));
XFillRectangle(display, window, gc, 0, 0, width, height);
XSetForeground(display, gc, strtoul(FG_COLOR, 0, 16));
XFillArc(
display, window, gc,
50, 50,
100, 100,
-45 * 64, 90 * 64);
XSetForeground(display, gc, strtoul(BG_COLOR, 0, 16));
XFillArc(
display, window, gc,
55, 55,
90, 90,
-45 * 64, 90 * 64);
XSetForeground(display, gc, strtoul(FG_COLOR, 0, 16));
XFillArc(
display, window, gc,
60, 60,
80, 80,
-45 * 64, 90 * 64);
XSetForeground(display, gc, strtoul(BG_COLOR, 0, 16));
XFillArc(
display, window, gc,
65, 65,
70, 70,
-45 * 64, 90 * 64);
XSetForeground(display, gc, strtoul(FG_COLOR, 0, 16));
XFillArc(
display, window, gc,
70, 70,
60, 60,
-45 * 64, 90 * 64);
XSetForeground(display, gc, strtoul(BG_COLOR, 0, 16));
XFillArc(
display, window, gc,
75, 75,
50, 50,
-45 * 64, 90 * 64);
XSetForeground(display, gc, strtoul(FG_COLOR, 0, 16));
XFillRectangle(display, window, gc, 55, 75, 50, 50);
XSetForeground(display, gc, strtoul(BG_COLOR, 0, 16));
XFillArc(
display, window, gc,
50, 60,
60, 60,
45 * 64, 135 * 64);
XFillArc(
display, window, gc,
50, 80,
60, 60,
180 * 64, 135 * 64);
}
void drawVolumeIconMuted() {
// get window attributes for width and height
XWindowAttributes win_attr;
XGetWindowAttributes(display, window, &win_attr);
// extract window width and height
int width = win_attr.width;
int height = win_attr.height;
XSetForeground(display, gc, strtoul(BG_COLOR, 0, 16));
XFillRectangle(display, window, gc, 0, 0, width, height);
XSetForeground(display, gc, strtoul(FG_MUTED, 0, 16));
XFillRectangle(display, window, gc, 55, 75, 50, 50);
XSetForeground(display, gc, strtoul(BG_COLOR, 0, 16));
XFillArc(
display, window, gc,
50, 60,
60, 60,
45 * 64, 135 * 64);
XFillArc(
display, window, gc,
50, 80,
60, 60,
180 * 64, 135 * 64);
}
|
C
|
#include<stdio.h>
float phuongtrinh ( int x )
{
if (x==0)
return 1;
else return ( 2*phuongtrinh(x-1)+3/4);
}
void main ()
{
printf("%f", phuongtrinh(5));
}
|
C
|
#include<stdio.h>
#include<conio.h>
#include<graphics.h>
main()
{
int a,b,i,j;
clrscr();
printf("entert he number");
a=1;
for(i=1;i<=5;i++)
{
printf("\n");
for(j=i;j<5;j++)
{
printf("%d ",j);
}
for(a=1;a<=i;a++)
{
printf("%d ",5);
}
}
getch();
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
typedef void const* (*PTRFUN)(void);
typedef enum {false, true} bool;
/* ==============================================
RAZRED Unary_Function
============================================== */
typedef struct{
PTRFUN *vtable;
int lower_bound;
int upper_bound;
} Unary_Function;
typedef double (*funptrDFD)(Unary_Function*, double);
double negative_value_at(Unary_Function* obj, double x){
funptrDFD pfun = (funptrDFD)obj->vtable[0];
return -pfun(obj, x);
}
void tabulate(Unary_Function *obj){
int x = obj->lower_bound;
funptrDFD pfun = (funptrDFD)obj->vtable[0];
for(x; x <= obj->upper_bound; x++){
printf("f(%d)=%lf\n", x, pfun(obj, x));
}
}
bool same_functions_for_ints(Unary_Function* f1, Unary_Function* f2, double tolerance){
if(f1->lower_bound != f2->lower_bound){
return false;
}
if(f1->upper_bound != f2->upper_bound){
return false;
}
int x = f1->lower_bound;
funptrDFD pfun1 = (funptrDFD)f1->vtable[0];
funptrDFD pfun2 = (funptrDFD)f2->vtable[0];
for(x; x <= f1->upper_bound; x++){
double delta = pfun1(f1, x) - pfun2(f2,x);
if(delta < 0){
delta = -delta;
}
if(delta > tolerance){
return false;
}
}
return true;
}
PTRFUN UnaryVT[2]={
(funptrDFD)NULL,
(funptrDFD)negative_value_at
};
Unary_Function* createUnary(int lb, int ub){
Unary_Function* obj = (Unary_Function*)malloc(sizeof(Unary_Function));
obj->vtable = UnaryVT;
obj->lower_bound = lb;
obj->upper_bound =ub;
return obj;
}
/* ==============================================
RAZRED Square
============================================== */
typedef struct{
PTRFUN *vtable;
int lower_bound;
int upper_bound;
} Square;
double Square_value_at(Square* obj, double x){
return x*x;
}
PTRFUN SquareVT[2]={
(funptrDFD)Square_value_at,
(funptrDFD)negative_value_at
};
Square* createSquare(int lb, int ub){
Square* obj = (Square*)malloc(sizeof(Square));
obj->vtable = SquareVT;
obj->lower_bound = lb;
obj->upper_bound =ub;
return obj;
}
/* ==============================================
RAZRED Linear
============================================== */
typedef struct{
PTRFUN *vtable;
int lower_bound;
int upper_bound;
double a;
double b;
} Linear;
double Linear_value_at(Linear* obj, double x){
printf("LIN");
return (obj->a)*x + obj->b;
}
PTRFUN LinearVT[2]={
(funptrDFD)Linear_value_at,
(funptrDFD)negative_value_at
};
Linear* createLinear(int lb, int ub, double a_coef, double b_coef){
Linear* obj = (Linear*)malloc(sizeof(Linear));
obj->vtable = LinearVT;
obj->lower_bound = lb;
obj->upper_bound = ub;
obj->a = a_coef;
obj->b = b_coef;
return obj;
}
/* ==============================================
RAZRED Main
============================================== */
int main(){
Unary_Function* f1 = createSquare(-2, 2);
tabulate(f1);
Unary_Function* f2 = createLinear(-2, 2, 5, -2);
tabulate(f2);
printf("f1==f2: %s\n", same_functions_for_ints(f1, f2, 1E-6) ? "DA" : "NE");
funptrDFD pfun = (funptrDFD)f2->vtable[1];
printf("neg_val f2(1) = %lf\n", pfun(f2,1.0));
free(f1);
free (f2);
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include "lists.h"
#define CHAR_PT_SIZE 256*sizeof(char)
int get_next_event(Event * prev_ev, User * user_list, char * user_name);
/*
* Return a pointer to the struct calendar with name cal_name
* or NULL if no calendar with this name exists in the cal_list
*/
Calendar *find_calendar(Calendar *cal_list, char *cal_name) {
Calendar *cal = cal_list;
while (cal != NULL) {
if (strcmp(cal->name, cal_name) == 0) {
return cal;
}
cal = cal->next;
}
return NULL;
}
/*
* Return a pointer to the user with name username or NULL
* if no such user exists in user_list
*/
User *find_user(User *user_list, char *username) {
User *usr = user_list;
while (usr != NULL) {
if (strcmp(usr->name, username) == 0) {
return usr;
}
usr = usr->next;
}
return NULL;
}
/*
* If a calendar with name cal_name does not exist, create a new
* calendar by this name and insert it at the front of the calendar list.
* Return values:
* 0 if successful
* -1 if a calendar by cal_name already exists
*/
int add_calendar(Calendar **cal_list_ptr, char *cal_name) {
Calendar * cal;
if ((cal = malloc(sizeof(Calendar))) == NULL) {
perror("malloc");
exit(1);
}
cal = *cal_list_ptr;
if (cal == NULL) {
//If there are currently no calendars, initialize the cal_list.
if ((*cal_list_ptr = malloc(sizeof(Calendar))) == NULL) {
perror("malloc");
exit(1);
}
if (((*cal_list_ptr)->name = malloc(CHAR_PT_SIZE)) == NULL) {
perror("malloc");
exit(1);
}
strcpy((*cal_list_ptr)->name, cal_name);
return 0;
}
while (cal != NULL) {
//Check that there is no calendar with the given name.
if (strcmp(cal->name, cal_name) == 0) {
return -1;
}
cal = cal->next;
}
//Return to the beginning of the list, because that is where to put
//a new calendar.
cal = *cal_list_ptr;
Calendar * new_cal_ptr;
if ((new_cal_ptr = malloc(sizeof(Calendar))) == NULL) {
perror("malloc");
exit(1);
}
if ((new_cal_ptr->name = malloc(CHAR_PT_SIZE)) == NULL) {
perror("malloc");
exit(1);
}
strcpy(new_cal_ptr->name, cal_name);
if ((new_cal_ptr->next = malloc(sizeof(Calendar))) == NULL) {
perror("malloc");
exit(1);
}
new_cal_ptr->next = cal;
*cal_list_ptr = new_cal_ptr;
return 0;
}
/*
* Print to stdout a list of all current calendar names (one per line)
*/
void list_calendars(Calendar *cal_list) {
Calendar * cal = cal_list;
while (cal != NULL) {
printf("%s\n", cal->name);
cal = cal->next;
}
}
/*
* If a user with name username does not exist, create a new
* user by this name and insert it at the end of the user list.
* Return values:
* 0 if successful
* -1 if username already exists
*/
int add_user(User **user_list_ptr, char *username) {
User * usr;
if ((usr = malloc(sizeof(User))) == NULL) {
perror("malloc");
exit(1);
}
usr = *user_list_ptr;
if (usr == NULL) {
//If there are currently no users, initialize the user_list.
if ((*user_list_ptr = malloc(sizeof(User))) == NULL) {
perror("malloc");
exit(1);
}
if (((*user_list_ptr)->name = malloc(CHAR_PT_SIZE)) == NULL) {
perror("malloc");
exit(1);
}
strcpy((*user_list_ptr)->name, username);
if (((*user_list_ptr)->subscriptions = malloc(sizeof(Subscription))) == NULL) {
perror("malloc");
exit(1);
}
(*user_list_ptr)->subscriptions = NULL;
if (((*user_list_ptr)->next = malloc(sizeof(User))) == NULL) {
perror("malloc");
exit(1);
}
(*user_list_ptr)->next = NULL;
return 0;
}
while (usr->next != NULL) {
//Check that there is no user with the given name.
if (strcmp(usr->name, username) == 0) {
return -1;
}
usr = usr->next;
}
//I decided to add new users to the end of the user list, and so I do not
//want to actually leave the list by going to null, or I would not be able to append
//the new user. The while loop reaches the last user, and the next if
//statement checks that that user does not have the given name.
if (strcmp(usr->name, username) == 0) {
return -1;
}
User * new_usr_ptr;
if ((new_usr_ptr = malloc(sizeof(User))) == NULL) {
perror("malloc");
exit(1);
}
if ((new_usr_ptr->name = malloc(CHAR_PT_SIZE)) == NULL) {
perror("malloc");
exit(1);
}
strcpy(new_usr_ptr->name, username);
if ((new_usr_ptr->next = malloc(sizeof(User))) == NULL) {
perror("malloc");
exit(1);
}
new_usr_ptr->next = NULL;
if ((new_usr_ptr->subscriptions = malloc(sizeof(Subscription))) == NULL) {
perror("malloc");
exit(1);
}
new_usr_ptr->subscriptions = NULL;
usr->next = new_usr_ptr;
return 0;
}
/*
* Print to stdout a list of usernames one per line
*/
void list_users(User *user_list) {
User * usr = user_list;
while (usr != NULL) {
printf("%s\n", usr->name);
usr = usr->next;
}
}
/*
* Subscribe the user username to calendar cal_name
* Return:
* 0 if successful
* -1 if no user exists by this name
* -2 if no calendar exists by this name
* -3 if this user is already subscribed to this calendar
*/
int subscribe(User *user_list, Calendar *cal_list, char *username, char *cal_name) {
User * usr = find_user(user_list, username);
if (usr == NULL) {
return -1;
}
Calendar * cal = find_calendar(cal_list, cal_name);
if (cal == NULL) {
return -2;
}
Subscription * sub = usr->subscriptions;
if (sub == NULL) {
//If this user has no subscriptions, initialize their subscriptions.
Subscription * sub_ptr;
if ((sub_ptr = malloc(sizeof(Subscription))) == NULL) {
perror("malloc");
exit(1);
}
if ((sub_ptr->calendar = malloc(sizeof(Calendar))) == NULL) {
perror("malloc");
exit(1);
}
sub_ptr->calendar = cal;
usr->subscriptions = sub_ptr;
return 0;
}
while (sub->next != NULL) {
if (strcmp((sub->calendar)->name, cal_name) == 0) {
return -3;
}
sub = sub->next;
}
//I decided to add new subscriptions to the end of the subscription list, and so I do not
//want to actually leave the list by going to null, or I would not be able to append
//the new subscription. The while loop reaches the last subscription, and the next if
//statement checks that that subscription's calendar is not the one to be added.
if (strcmp((sub->calendar)->name, cal_name) == 0) {
return -3;
}
Subscription * new_sub_ptr;
if ((new_sub_ptr = malloc(sizeof(Subscription))) == NULL) {
perror("malloc");
exit(1);
}
if ((new_sub_ptr->calendar = malloc(sizeof(Calendar))) == NULL) {
perror("malloc");
exit(1);
}
new_sub_ptr->calendar = cal;
if ((new_sub_ptr->next = malloc(sizeof(Calendar))) == NULL) {
perror("malloc");
exit(1);
}
new_sub_ptr->next = NULL;
sub->next = new_sub_ptr;
return 0;
}
/*
* Add an event with this name and date to the calender with name cal_name
* Return:
* 0 for success
* -1 for calendar does not exist by this name
*/
int add_event(Calendar *cal_list, char *cal_name, char *event_name, time_t time) {
Calendar * cal;
if ((cal = malloc(sizeof(Calendar))) == NULL) {
perror("malloc");
exit(1);
}
cal = find_calendar(cal_list, cal_name);
if (cal == NULL) {
return -1;
}
//If this calendar has no events, initialize its events.
if (cal->events == NULL) {
if ((cal->events = malloc(sizeof(Event))) == NULL) {
perror("malloc");
exit(1);
}
if (((cal->events)->description = malloc(CHAR_PT_SIZE)) == NULL) {
perror("malloc");
exit(1);
}
strcpy((cal->events)->description, event_name);
(cal->events)->time = time;
}
else {
Event * evs;
if ((evs = malloc(sizeof(Event))) == NULL) {
perror("malloc");
exit(1);
}
evs = cal->events;
//Check if the first event is later than the new event;
//if it is, put the new event at the beginning of the calendar's
//events; else, search through the list for where to put it.
if (difftime(time, evs->time) < difftime(time, time)) {
Event * new_ev_ptr;
if ((new_ev_ptr = malloc(sizeof (Event))) == NULL) {
perror("malloc");
exit(1);
}
if ((new_ev_ptr->description = malloc(CHAR_PT_SIZE)) == NULL) {
perror("malloc");
exit(1);
}
new_ev_ptr->time = time;
strcpy(new_ev_ptr->description, event_name);
if ((new_ev_ptr->next = malloc(sizeof(Calendar))) == NULL) {
perror("malloc");
exit(1);
}
new_ev_ptr->next = cal->events;
cal->events = new_ev_ptr;
return 0;
}
while (evs->next != NULL && difftime(time, (evs->next)->time) > difftime(time, time)) {
evs = evs->next;
}
Event * new_ev_ptr;
if ((new_ev_ptr = malloc(sizeof(Event))) == NULL) {
perror("malloc");
exit(1);
}
if ((new_ev_ptr->description = malloc(CHAR_PT_SIZE)) == NULL) {
perror("malloc");
exit(1);
}
new_ev_ptr->time = time;
strcpy(new_ev_ptr->description, event_name);
if ((new_ev_ptr->next = malloc(sizeof(Calendar))) == NULL) {
perror("malloc");
exit(1);
}
new_ev_ptr->next = evs->next;
evs->next = new_ev_ptr;
//End of the else block.
}
return 0;
}
/*
* Print to stdout a list of the events in this calendar ordered by time
* Return:
* 0 if successful
* -1 if no calendar exists by this name
*/
int list_events(Calendar *cal_list, char *cal_name) {
Calendar *cal = cal_list;
while (cal != NULL) {
if (strcmp(cal->name, cal_name) == 0) {
Event * evs = cal->events;
//Because events are already ordered by time, simply going through and printing
//the first event, then the enxt event, etc. will accomplish the task.
while (evs != NULL) {
printf("%s: %s", evs->description, asctime(localtime(&(evs->time))));
evs = evs->next;
}
return 0;
}
cal = cal->next;
}
return -1;
}
/*
* Print to stdout, the description and time of the next event for
* user user_name
* Return:
* 0 on success
* -1 if this user_name does not exist or has no events
*/
int print_next_event(Calendar *cal_list, User * user_list, char *user_name) {
Event * early_event;
if ((early_event = malloc(sizeof(Event))) == NULL) {
perror("malloc");
exit(1);
}
User * usr = find_user(user_list, user_name);
if (usr == NULL) {
return -1;
}
Subscription * sub = usr->subscriptions;
if (sub == NULL) {
return -1;
}
//Setting the first event to be compared to as the first event in
//the first subscriptions's calendar.
early_event = (sub->calendar)->events;
//Setting an arbitrary time (the time of the variable's creation) to comapre event times.
time_t arb_time = time(NULL);
while (sub != NULL) {
//Next line is equivalent to "if the currently considered event is earlier than the earliest
//event found so far". Note that only teh first events in each subscription's calendar are
//considered, because theya re all sorted chronologically.
if (difftime(arb_time, ((sub->calendar)->events)->time) > difftime(arb_time, early_event->time)) {
early_event = (sub->calendar)->events;
}
sub = sub->next;
}
printf("%s: %s", early_event->description, asctime(localtime(&(early_event->time))));
return 0;
}
/*
* Print to stdout a time-ordered list of all events in any calendars
* subscribed to by this user
*
* Do not change the calendar data-structure.
* Return -1 if this user doesn't exist.
*
* Returns
*/
int print_all_events(Calendar *cal_list, User * user_list, char *user_name) {
User * usr_ptr = find_user(user_list, user_name);
if (usr_ptr == NULL) {
return -1;
}
Event * rec_event;
if ((rec_event = malloc(sizeof(Event))) == NULL) {
perror("malloc");
exit(1);
}
rec_event->description = NULL;
//Because rec_event->description is currently NULL, need to have one
//call of the function get_next_event out of the while loop.
get_next_event(rec_event, user_list, user_name);
while (rec_event->description != NULL) {
printf("%s: %s", rec_event->description, asctime(localtime(&(rec_event->time))));
get_next_event(rec_event, user_list, user_name);
}
return 0;
}
/*
* Changes the decription and time of the passed in event to the description
* and time of the next event (chronologically) in all of the user's subscribed
* calendars. If there are no events after the passed in event, the description
* is set to NULL.
*
* Returns:
* -1 if there is no such user
* 0 if event->description and event-> time are chanegd to a new event's description and time
* 1 if there were no more events after the passed in event and event->description was changed to NULL
*/
int get_next_event(Event * prev_ev, User * user_list, char * user_name) {
User * usr_ptr = find_user(user_list, user_name);
if (usr_ptr == NULL) {
return -1;
}
Subscription * sub = usr_ptr->subscriptions;
Event * ev;
Event * ret_ev;
if ((ret_ev = malloc(sizeof(Event))) == NULL) {
perror("malloc");
exit(1);
}
ret_ev->description = NULL;
time_t arb_time = time(NULL);
//Outer while loop goes through all of teh user's subscriptions;
//inner while loop goes through all of the subscription's calendar's events.
while (sub != NULL) {
ev = (sub->calendar)->events;
while (ev != NULL) {
//If prev_ev->description is NULL, whatever the earliest event is is the one
//to be returned. If it isn't NULL, the earliest event after it is returned.
if (prev_ev->description == NULL) {
if (ret_ev->description == NULL) {
ret_ev->description = ev->description;
ret_ev->time = ev->time;
}
else if (difftime(arb_time, ev->time) > difftime(arb_time, ret_ev->time)) {
ret_ev->description = ev->description;
ret_ev->time = ev->time;
}
}
else if (difftime(arb_time, ev->time) < difftime(arb_time, prev_ev->time)) {
if (ret_ev->description == NULL) {
ret_ev->description = ev->description;
ret_ev->time = ev->time;
}
else if (difftime(arb_time, ev->time) > difftime(arb_time, ret_ev->time)) {
ret_ev->description = ev->description;
ret_ev->time = ev->time;
}
}
ev = ev->next;
}
sub = sub->next;
}
prev_ev->description = ret_ev->description;
prev_ev->time = ret_ev->time;
if (ret_ev->description == NULL) {
return 1;
} else {
return 0;
}
}
|
C
|
#include <stdlib.h>
#include "lists.h"
/**
* free_listint_safe - Free a list.
* @h : first element of the list.
* Return: Voidnumber of element in the list.
*/
size_t free_listint_safe(listint_t **h)
{
listint_t *l;
size_t i = 0;
l = *h;
while (l)
{
if (l <= l->next)
{
free(l);
*h = NULL;
i++;
break;
}
*h = l->next;
free(l);
l = *h;
i++;
}
return (i);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>
#include "gestion_juego.h"
#include "pantalla.h"
#define gotoxy(x,y) printf("\x1b[%d;%dH",(y),(x))
void asteriscos(int n, int l, char c)
{
system("clear"); //Limpiamos la pantalla para evitar problemas con gotoxy
srand(time(NULL));
int a,k,ca,cm; //Rand para conseguir tener los colores de forma aleatoria, este valor se lo sumamos a 29 para tener los valores de
do{ //los colores
ca=29+rand()%7;
cm=29+rand()%7;
}while(ca==cm); //Rellenamos con asteriscos y utilizamos usleep para dar dinamismo a la aparición de filas de asteriscos
for(a=0;a<n;a++){
for(k=0;k<l;k++)
printf("%c[%d;%dm%c%c[%dm",27,4,ca,c,27,0);
printf("\n");
usleep(300000);
}
if((l%2!=0)&&(l>13))printf("%c[%d;%dm%c%c[%dm",27,4,ca,c,27,0);
for(a=0;a<l/2-7;a++) printf("%c[%d;%dm%c%c[%dm",27,4,ca,c,27,0);
printf("%c[%d;%dm %c[%dm",27,1,32,27,0);
for(a=0;a<=l/2-7;a++)printf("%c[%d;%dm%c%c[%dm",27,4,ca,c,27,0);
printf("\n");
usleep(300000);
for(a=0;a<n;a++){
for(k=0;k<l;k++)
printf("%c[%d;%dm%c%c[%dm",27,4,ca,c,27,0);
printf("\n");
usleep(300000);
}
usleep(500000);
gotoxy(35, 4);printf("%c[%d;%dmMASTER MIND%c[%dm",27,1,cm,27,0); //Para imprimir MASTER MIND en la posición deseada
gotoxy(0,7);
return;
}
int confirmar(int idioma,int jop)
{
char res[5];
int i;
do{
if(jop==0){ //En caso de seleccionar salir con partida sin guardar
if(idioma==1)printf("\nHay una partida sin guardar, ¿está seguro de que desea salir? (s/n)?\n");
if(idioma==2)printf("\nHai unha partida sen gardar, está seguro de que desexa saír? (s/n)?\n");
if(idioma==3)printf("\nThere is an unsaved game, are you sure you want to quit? (s/n)?\n");
}
if(jop==1){ //En caso de seleccionar jugar partida con una ya existente sin guardar
if(idioma==1)printf("\nHay una partida sin guardar, ¿descartarla? (s/n)?\n");
if(idioma==2)printf("\nHay unha partida sen gardar, descartala? (s/n)?\n");
if(idioma==3)printf("\nThere is an unsaaved game, discard it? (s/n)?\n");
}
scanf("%s",res); //Comprobamos si el valor introducido se corresponde con una sola posición en el string, sino el switch devolverá -1 y se volverá a
if(strlen(res)!=1)res[0]='t'; //pedir una respuesta válida
switch(res[0]){
case 's':case 'S': return 1;
case 'n':case 'N': return 0;
default: i=-1;
}
}while(i==-1);
return 0;
}
|
C
|
#include <as/private_.h>
/* Public API */
void as_free(void* ptr)
{
if(!ptr)
return;
ulong* mem = &((ulong*) ptr)[-1];
as_anonmunmap(mem, *mem);
}
void* as_malloc(ulong size)
{
if(size == 0)
return NULL;
size = ALIGN(size + sizeof(ulong), as_getpagesize());
ulong* mem = (ulong*) as_anonmmap(size);
*mem = size;
return (void*) &mem[1];
}
void* as_memcpy(void* dst, const void* src, ulong len)
{
if(dst == src)
return dst;
char* cdst = (char*) dst;
const char* csrc = (const char*) src;
while(len-- && (*cdst++ = *csrc++));
return dst;
}
void* as_memset(void* s, int c, ulong len)
{
char* cs = (char*) s;
while(len-- && (*cs++ = (char) c));
return s;
}
void* as_memmove(void* dst, const void* src, ulong len)
{
if(dst <= src)
return as_memcpy(dst, src, len);
char* cdst = (char*) dst + len;
const char* csrc = (const char*) src + len;
while(len-- && (*--cdst = *--csrc));
return dst;
}
|
C
|
#include <stdio.h>
#include <dirent.h>
#include <dirent.h>
#include <sys/stat.h>
/**
* Main
*/
int main(int argc, char **argv)
{
// inituit
char *dirname;
// Parse command line
if(argc == 1){
// set directory to looking to '.'
dirname = '.'
} else if (argc ==2 ){
dirname = argv[1];
} else {
fprintf(stderr, "usage: lsls [dirname]\n");
exit(1);
}
// Open directory
DIR * d = opendir(dirname);
if (d == NULL){
fprintf(stderr, "lsls: cannot open direcory %s\n", idrname);
exit(2);
}
// Repeatly read and print entries
struct direct *entry;
while((entry = reddir(d)) !=NULL){
//stat the entry
char fullpath[8192];
//format before path
snprintf(fullpath, sizeof(fullpath), "%s/%s", dirname, entry->d_name);
struct stat stat_buf;
if (stat(fullpath, &stat_buf) < 0){
fprintf(stderr, "lsls: failed to stat file %s\n", fullpath);
exit(3);
}
if (S_ISREG(stat_buf.st_mode)){
printf("%lld %s\n", stat_buf.st_size, entry-<d_name);
} else if (S_ISDIR(stat_buf.st_mode)){
printf("<DIR> %s\n", entry->d_name);
} else {
printf("%s %s\n", "", entry->d_name);
}
//stat_buf->st_size == (*stat_buf).st_size
printf("%lld %s\n", stat_buf->st_size, entry->d_name);
}
// Close directory
closedir(d);
return 0;
}
|
C
|
#include<stdio.h>
#include<conio.h>
void main()
{
int n,reversedInteger=0,remainder,originalInteger;
scanf("%d",&n);
originalInteger=n;
while(n!=0)
{
remainder=n%10;
reverseInteger=reverseInteger*10+remainder;
n=n/10;
}
if(originalInteger==reversedInteger)
printf("palindrome");
else
printf("not a palindrome");
getch();
}
|
C
|
/*
* Copyright (C) 2009-2023 Alex Smith
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
/**
* @file
* @brief Port address space helpers.
*/
#include <net/port.h>
#include <assert.h>
#include <status.h>
/** Looks up a port in a space, with the lock held.
* @param space Space to look up in (must be locked).
* @param num Port number to look up.
* @return Port found, or NULL if no port bound. */
net_port_t *net_port_lookup_unsafe(net_port_space_t *space, uint16_t num) {
// TODO: Really needs a hash table...
list_foreach(&space->ports, iter) {
net_port_t *port = list_entry(iter, net_port_t, link);
if (port->num == num)
return port;
}
return NULL;
}
/** Allocates a port from a port space.
* @param space Space to allocate from.
* @param port Port to allocate for.
* @param num Port number to allocate.
* @return STATUS_SUCCESS if successful.
* STATUS_ADDR_IN_USE if port is already allocated. */
status_t net_port_alloc(net_port_space_t *space, net_port_t *port, uint16_t num) {
assert(list_empty(&port->link));
assert(port->num == 0);
rwlock_write_lock(&space->lock);
if (!net_port_lookup_unsafe(space, num)) {
port->num = num;
list_append(&space->ports, &port->link);
}
rwlock_unlock(&space->lock);
return (port->num != 0) ? STATUS_SUCCESS : STATUS_ADDR_IN_USE;
}
/** Allocates an ephemeral port from a port space.
* @param space Space to allocate from.
* @param port Port to allocate for.
* @return STATUS_SUCCESS if successful.
* STATUS_TRY_AGAIN if no ports are currently available. */
status_t net_port_alloc_ephemeral(net_port_space_t *space, net_port_t *port) {
assert(list_empty(&port->link));
assert(port->num == 0);
rwlock_write_lock(&space->lock);
/* Round-robin allocation of port numbers. */
uint16_t start = space->next_ephemeral_port;
do {
if (!net_port_lookup_unsafe(space, space->next_ephemeral_port)) {
port->num = space->next_ephemeral_port;
list_append(&space->ports, &port->link);
}
if (space->next_ephemeral_port == IP_EPHEMERAL_PORT_LAST) {
space->next_ephemeral_port = IP_EPHEMERAL_PORT_FIRST;
} else {
space->next_ephemeral_port++;
}
} while (port->num == 0 && space->next_ephemeral_port != start);
rwlock_unlock(&space->lock);
return (port->num != 0) ? STATUS_SUCCESS : STATUS_TRY_AGAIN;
}
/** Frees an allocated port.
* @param space Space the port is allocated from.
* @param port Port to free. */
void net_port_free(net_port_space_t *space, net_port_t *port) {
if (port->num != 0) {
assert(!list_empty(&port->link));
rwlock_write_lock(&space->lock);
list_remove(&port->link);
rwlock_unlock(&space->lock);
port->num = 0;
}
}
|
C
|
/*
============================================================================
Name : genWords.c
============================================================================
*/
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
// ------------------------------------------------------------------
// liefert zufaelligen int-Wert zwischen von und bis einschliesslich.
// ------------------------------------------------------------------
int getZufallsZahl(int von, int bis)
{
if(von >= bis || bis > RAND_MAX)
{
puts("getZufallsZahl meldet: von >= bis || bis > RAND_MAX");
exit(EXIT_FAILURE);
}
return rand() % (bis - von + 1) + von;
}
// ------------------------------------------------------------------
void printKleinenZufallsBuchstaben()
{
printf("%c", getZufallsZahl((int)'a', (int)'z'));
}
// ------------------------------------------------------------------
void printGrossenZufallsBuchstaben()
{
printf("%c", getZufallsZahl((int)'A', (int)'Z'));
}
// ------------------------------------------------------------------
void printKleinenOderGrossenZufallsBuchstaben()
{
if(rand() % 2)
printKleinenZufallsBuchstaben();
else
printGrossenZufallsBuchstaben();
}
// ------------------------------------------------------------------
void printZufallsWort(int minLaenge, int maxLaenge)
{
int laenge = getZufallsZahl(minLaenge, maxLaenge);
printKleinenOderGrossenZufallsBuchstaben();
int i;
for(i = 2; i <= laenge; i++)
printKleinenZufallsBuchstaben();
}
// ------------------------------------------------------------------
int main(void)
{
int i;
time_t t;
int anzahlWoerter = 100;
int minWortLaenge100 = 2;
int maxWortLaenge100 = 50;
srand((unsigned) time(&t));
for (i = 1; i <= anzahlWoerter; i++)
{
printZufallsWort(minWortLaenge100, maxWortLaenge100);
printf("\n");
}
return 0;
}
|
C
|
/*
6. [10 marks]
Write a C program to look at all files under the current directory, recursively, and look for a file named "squid".
If it finds one, it outputs either the path name relative to the current directory, or how many subdirectories deep it is, whichever you find easiest.
If no such file name is found, it outputs "not found".
*/
#include <stdio.h>
#include <stdlib.h>
int main(void) {
return 0;
}
|
C
|
struct high_pass_filter_options_int {
int factor;
};
struct high_pass_filter_options_afp {
int factor;
};
struct high_pass_filter_options_float {
float factor;
};
int64_t high_pass_filter_acc_int = 0;
int64_t high_pass_filter_acc_afp = 0;
float high_pass_filter_acc_float = 0;
void high_pass_filter_int(struct high_pass_filter_options_int *options, int *in, int *out) {
high_pass_filter_acc_int *= 0xF000;
high_pass_filter_acc_int += ((int64_t)(*in) * 0x1000);
high_pass_filter_acc_int = high_pass_filter_acc_int >> 32;
*out = *in - (int)high_pass_filter_acc_int;
}
void high_pass_filter_afp(struct high_pass_filter_options_afp *options, int *in, int *out) {
high_pass_filter_acc_afp *= 0xF000;
high_pass_filter_acc_afp += ((int64_t)(*in) * 0x1000);
high_pass_filter_acc_afp = high_pass_filter_acc_afp >> 32;
*out = *in - (int)high_pass_filter_acc_afp;
}
void high_pass_filter_float(struct high_pass_filter_options_float *options, float *in, float *out) {
high_pass_filter_acc_float *= 0.9375;
high_pass_filter_acc_float += *in * 0.0625;
*out = *in - high_pass_filter_acc_float;
}
|
C
|
/*
* Cell.h
*
* Created on: Jul 21, 2012
* Author: barry
*/
#ifndef CELL_H_
#define CELL_H_
#include "Segment.h"
#include "SegmentUpdateInfo.h"
typedef struct CellType {
struct RegionType* region;
struct ColumnType* column;
int index;
int id;
/**
* The predictionSteps is the fewest number of time steps until this Cell
* believes it will becomes active. The last prediction steps value
* represents the fewest number of time steps this Cell believes it will
* becomes active in. This value will often be a count down that approaches
* zero as time steps move forward and the Cell gets closer to becoming
* activated. If the Cell is not currently in a predicting state this value
* should be ignored.
*/
int predictionSteps;
bool isActive;
bool wasActive;
bool isPredicting;
bool wasPredicted;
bool isLearning;
bool wasLearning;
Segment* segments;
int numSegments;
int allocatedSegments;
SegmentUpdateInfo* segmentUpdates;
int numSegUpdates;
int allocatedSegUpdates;
} Cell;
void initCell(Cell* cell, struct ColumnType* column, int index);
void initInputCell(Cell* cell, struct RegionType* region, int index);
void deleteCell(Cell* cell);
void setCellPredicting(Cell* cell, bool predicting);
int numCellSegments(Cell* cell, int predictionSteps);
void nextCellTimeStep(Cell* cell);
#pragma acc routine
Segment* createCellSegment(Cell* cell);
Segment* getPreviousActiveSegment(Cell* cell);
SegmentUpdateInfo* updateSegmentActiveSynapses(Cell* cell, bool previous,
int segmentID, bool newSynapses);
#pragma acc routine
void applyCellSegmentUpdates(Cell* cell, bool positiveReinforcement);
Segment* getBestMatchingPreviousSegment(Cell* cell, int* segmentID);
Segment* getBestMatchingSegment(Cell* cell, int numPredictionSteps,
bool previous, int* segmentID);
#endif /* CELL_H_ */
|
C
|
/***************************************************************************
Matrix multiplication seq program
****************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
double C[N][N];
double A[N][N], B[N][N];
double wall_clock();
main(argc, argv)
int argc;
char **argv[];
{
char host[128];
int i, j, k;
double t0, t1;
FILE *fd;
int log = 0;
gethostname(host, sizeof(host));
if (argc > 1) log = 1;
for (i=0; i < N ; i++)
{
for (j=0; j < N; j++)
{
C[i][j] = 0;
B[i][j] = (double) i * j ;
A[i][j] = (double) i * j ;
}
}
t0 = wall_clock();
/* Switch j and k can give better results */
for (i=0; i < N; i++)
for (k=0; k < N; k++)
for (j=0; j < N; j++)
C[i][j] += A[i][k]*B[k][j];
t1 = wall_clock() - t0;
printf ("%f\n", t1);
/*
if (log) {
for (i=0; i<N; i++)
{
for (j=0; j<N; j++) fprintf(fd, "%8.1f ",C[i][j]);
fprintf(fd,"\n");
}
}
fclose(fd);
*/
exit (1);
}
/* Wall_clock() */
/* Author: Wenhai Jiang */
/* Date: October 1994 */
#include <sys/time.h>
#include <sys/resource.h>
double wall_clock()
{
struct timeval tp;
struct timezone tzp;
double t;
gettimeofday(&tp, &tzp);
t = (tzp.tz_minuteswest*60 + tp.tv_sec)*1.0e6 + (tp.tv_usec)*1.0;
return t;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
int add (int x, int y) {
int result;
printf("Requisicao de adicao para %d e %d\n", x, y);
result = x + y;
return(result);
} /* fim funcao add */
int sub (int x, int y) {
int result;
printf("Requisicao de subtracao para %d e %d\n", x, y);
result = x - y;
return(result);
} /* fim funcao sub */
int main( int argc, char *argv[]) {
int x,y;
if (argc!=3) {
fprintf(stderr,"Uso correto: %s num1 num2\n",argv[0]);
exit(0);
}
/* Recupera os 2 operandos passados como argumento */
x = atoi(argv[1]); y = atoi(argv[2]);
printf("%d + %d = %d\n",x,y, add(x,y));
printf("%d - %d = %d\n",x,y, sub(x,y));
return(0);
} /* fim main */
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void print_site_matrix_row(long *site_matrix_row, int width, char base) {
int con_count_index;
printf("%c: [", base);
for (con_count_index = 0; con_count_index < width; con_count_index++){
printf(" %ld ", site_matrix_row[con_count_index]);
}
printf("]\n");
}
void print_site_matrix (long *consensus_count_a,
long *consensus_count_t,
long *consensus_count_c,
long *consensus_count_g,
int width){
print_site_matrix_row(consensus_count_a, width, 'A');
print_site_matrix_row(consensus_count_t, width, 'T');
print_site_matrix_row(consensus_count_c, width, 'C');
print_site_matrix_row(consensus_count_g, width, 'G');
}
void print_consensus(long *consensus_count_a,
long *consensus_count_t,
long *consensus_count_c,
long *consensus_count_g,
int width) {
int site_index;
for (site_index = 0; site_index < width; site_index++) {
const int aCount = consensus_count_a[site_index];
const int tCount = consensus_count_t[site_index];
const int cCount = consensus_count_c[site_index];
const int gCount = consensus_count_g[site_index];
if (aCount > tCount && aCount > cCount && aCount > gCount) {
printf("A");
} else if (tCount > aCount && tCount > cCount && tCount > gCount) {
printf("T");
} else if (cCount > aCount && cCount > tCount && cCount > gCount) {
printf("C");
} else if (gCount > aCount && gCount > tCount && gCount > cCount) {
printf("G");
} else if (aCount == 0 && tCount == 0 && cCount == 0 && gCount == 0) {
printf(" ");
//exit(1);
} else {
printf("?");
}
}
printf("\n");
}
int main(int argc, char* argv[])
{
char const* const file_name = argv[1];
if (file_name == 0) {
printf("A file must be passed into this program\n");
return 0;
}
char const* const widthString = argv[2];
if (widthString == 0) {
printf("A width must be passed into this program\n");
return 0;
}
long width = strtol(widthString, NULL, 10);
long consensus_count_a[width];
long consensus_count_t[width];
long consensus_count_c[width];
long consensus_count_g[width];
int con_count_index = 0;
for (con_count_index = 0; con_count_index < width; con_count_index++) {
consensus_count_a[con_count_index] = 0;
consensus_count_t[con_count_index] = 0;
consensus_count_c[con_count_index] = 0;
consensus_count_g[con_count_index] = 0;
}
char read[width+1];
FILE* file = fopen(file_name, "r");
while (!feof(file)) {
int numberOfItemsMatched = fscanf(file, "%[^\n]%*c", read);
//int numberOfItemsMatched = fscanf(file, "%s\r", read);
//printf("%s\n", read);
int site_index = 0;
//printf("%c %s\n", read[site_index], read);
while(read[site_index] != '\0') {
//printf("%d\n", read[site_index] != '\0');
char site = read[site_index];
//printf("%d\n", site_index);
if (site == 'A' || site == 'a') {
consensus_count_a[site_index]++;
} else if (site == 'T' || site == 't'){
consensus_count_t[site_index]++;
} else if (site == 'C' || site == 'c') {
consensus_count_c[site_index]++;
} else if (site == 'G' || site == 'g') {
consensus_count_g[site_index]++;
} else if (site == ' ') {
// Do nothing
} else if (site == 'N' || site == 'n') {
// Do Nothing
} else {
printf("We saw an unexpected character: '%c' %d\n", site, site);
exit(1);
}
site_index++;
}
}
print_consensus(consensus_count_a, consensus_count_t, consensus_count_c, consensus_count_g, width);
//print_site_matrix(consensus_count_a, consensus_count_t, consensus_count_c, consensus_count_g, width);
return 0;
}
|
C
|
#include <avr/io.h> // The necessary header file required for avr atmega 16/32
#include <util/delay.h> // Header file required for Delay
#include<compat/deprecated.h> // Used for the commands like sbi,cbi,bit_is_clear etc..
#include<stdlib.h>
#ifndef multiutil_H
#define multiutil_H
#define LCD_PORT PORTA // PortA as LCD command port
#define LCD_DDR DDRA
#define rs 0 // connect RS pin to LCD_C_PORT ie PA0 // connect RW pin to LCD_C_PORT ie PA6
#define en 1 // connect EN pin to LCD_C_PORT ie PA1
void lcd_init(void); // Function to init lcd ie to start display ,4 bit mode, cursor ON, etc
void write_command(unsigned char comm); // Function to write command in lcd
void write_data(unsigned char lcd_data); // Fuction to write data in lcd
void ilabs_lcd_prints(char *print_str); // Function to print String On LCD
void lcd_printi(int num);
void lcd_clrscr(void);
void lcd_goto(uint8_t,uint8_t);
void lcd_printc(char);
void init_usart(void);
void transmit_char(char);
void transmit_string(char *);
void init_pwm(int mode);
void init_adc(void);
int read_adc(char adc);
void start_i2c(void);
void stop_i2c(void);
void init_i2c(void);
void write_i2c(char);
char read_i2c(char);
#endif
//LCD
void lcd_init(void)
{
_delay_ms(300);
LCD_DDR=0b11110011; //Initialize the LCD port first
write_command(0x80); //initial address of DDRAM for first line
write_command(0x28); //To select 4 bit data
write_command(0x0e); //Command to on the display & cursor blink/blink off
write_command(0x01); //Command to clear LCD display
write_command(0x06); //Command for character entry mode
}
void write_command(unsigned char comm)
{
_delay_ms(2);
LCD_PORT=((comm & 0xF0)|(1<<en)); //Sending 4 MSB bits of command, & Enable=1,RW=0,RS=0;
cbi(LCD_PORT,en);
LCD_PORT=((comm<<4)|(1<<en)); //Sending 4 LSB bits of command
cbi(LCD_PORT,en);
}
void write_data(unsigned char lcd_data)
{
_delay_ms(2);
LCD_PORT=((lcd_data & 0xF0)|(1<<en)|(1<<rs)); //Sending 4 MSB bits of command, & Enable=1,RW=0,RS=1;
cbi(LCD_PORT,en);
LCD_PORT=((lcd_data<<4)|(1<<en)|(1<<rs)); //Sending 4 LSB bits of command
cbi(LCD_PORT,en);
}
void lcd_prints(char *print_str)
{
while(*print_str)
{
if(*print_str=='\0')
break;
write_data(*print_str);
print_str++;
}
}
void lcd_printi(int num)
{
char buff[]={'0','0','0','0','0'};
itoa(num,buff,10);
lcd_prints(buff);
}
void lcd_printc(char data)
{
if(data=='\n')
lcd_goto(0,2);
write_data(data);
}
void lcd_goto(uint8_t x,uint8_t y)
{
if(y==1)
write_command(0x80|x);
else if(y==2)
write_command(0xC0|x);
}
void lcd_clrscr(void)
{
write_command(0x01);
_delay_ms(3);
write_command(0x80);
}
//USART
void init_usart()
{
//Communication protocol set
//with 1 stop bit & 8 data bits
UCSRC=(1<<UCSZ1)|(1<<UCSZ0)|(1<<URSEL);
//Reception & transmission is enabled
//Reception of data will occur on interrupt
UCSRB=(1<<RXEN)|(1<<TXEN)|(1<<RXCIE);
//Baud rate = 9600
UBRRH=0x00;
UBRRL=103;
}
void transmit_char(char data)
{
loop_until_bit_is_set(UCSRA,UDRE);
UDR=data;
}
void transmit_string(char *data)
{
while(*data)
{
transmit_char(*data);
data++;
}
}
//PWM
void init_pwm(int mode)
{
DDRD|=(1<<PD4)|(1<<PD5);
TCCR1A|=(1<<COM1A1)|(1<<COM1B1);
TCCR1B|=(1<<CS10)|(1<<CS11);
switch(mode)
{
case 8:TCCR1A|=(1<<WGM10); TCCR1B|=(1<<WGM12);break;
case 9:TCCR1A|=(1<<WGM11); TCCR1B|=(1<<WGM12);break;
case 10:TCCR1A|=(1<<WGM10)|(1<<WGM11); TCCR1B|=(1<<WGM12);break;
default:TCCR1A|=(1<<WGM10); TCCR1B|=(1<<WGM12);break;
}
}
//ADC
void init_adc(void)
{
ADMUX=(1<<REFS0);
ADCSRA=(1<<ADPS0)|(1<<ADPS1)|(1<<ADPS2)|(1<<ADEN);
}
int read_adc(char adc)
{
ADMUX&=(0b11100000);
ADMUX|=(adc);
//`ADMUX=0b01
ADCSRA|=(1<<ADEN)|(1<<ADSC);
while((ADCSRA&(1<<ADIF))==0);
return ADC;
}
//I2C
void init_i2c(void)
{
PORTC |= _BV(0)|_BV(1);
TWBR=0x47;
}
void start_i2c(void)
{
TWCR|=(1<<TWINT)|(1<<TWSTA)|(1<<TWEN);
while((TWCR&(1<<TWINT))==0);
}
void stop_i2c(void)
{
TWCR|=(1<<TWINT)|(1<<TWSTO)|(1<<TWEN);
}
void write_i2c(char data)
{
TWDR=data;
TWCR=(1<<TWINT)|(1<<TWEN);
while((TWCR&(1<<TWINT))==0);
}
char read_i2c(char last)
{
if(last==0)
TWCR=(1<<TWINT)|(1<<TWEN)|(1<<TWEA);
else
{
TWCR=(1<<TWINT)|(1<<TWEN);
}
while((TWCR&(1<<TWINT))==0);
return TWDR;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// 缱
typedef unsigned int UINT;
// #define UINT unsigned int; // ó ص
// BUT ó ϴ ܼ ġȯ
// typedef ¥ ڷ
//
// 0, 1, 2 ̷ ǵ
// ij Ÿ
enum ACTION {MOVE, JUMP, ACTION};
// + 缱
// Ʒ 100, 101, 102 ڵ
typedef enum COLOR {RED=100, GREEN, BLUE} COLOR;
int main(void) {
// ̷ 3
// 缱 =
// 缱 ʿ ΰ..?
// ü or ؼ
// ⺻ 缱Ѵ? ̰Ŵ ...ض. ūϳ.
// UINT nData; ̷ 'unsigned int' ؼ
// ڵ ߸. Ȯ ʿϴϱ.
// LPARAM param; << ̰ ? windows αֿ ִ ǵ, long ̷ -_-
// 밡 ǥ ms
// ̸ '뵵' 巯 ϶!
// nData n int...
// '' 巯 ̷ٺ... ڷ LPARAM ̷ ..
// α ڷ ;; µ...
// ڵ
// Ÿ ̵带 ϴ° .
// ü ȹ Ͽ .
//
// ƿ ̰
// .
enum ACTION act = MOVE;
printf("ACTION : %d\n", act); // 0
COLOR color = GREEN;
printf("GREEN : %d\n", color); // 101
// ̷ ϴ. ּ ſ !
switch (act) {
case MOVE:
printf("\n");
break;
case JUMP:
printf("\n");
break;
case ACTION:
printf("!\n");
break;
}
return 0;
}
|
C
|
// 2. Reverse null-terminated char* str
void reverse(char* str){
if (str){
char * end = str;
while(*end){
end++;
}
end--;
char temp;
while (str < end){
temp = *str;
*str++ = *end;
*end-- = temp;
}
}
}
int main(){
// char * str = "abc";
char* str = "abcd";
reverse(str);
// cout << str << '\n
}
|
C
|
// 201611523_1_2.c
// 1. 1 α Ͻÿ.
/* 1: (Logic Error)-α ̳߰ ʾ ٸ
:(nF-32) ʾұ 꿡 error Ͽ */
// 2. ùٸ µǵ α ۼϽÿ
// 2:
#include<stdio.h>
int main(void)
{
int nC, nF;
printf("ȭµ Էϼ\n");
scanf("%d",&nF);
nC = (nF-32)*5/9;
printf("ȭ %d %dԴϴ\n", nF, nC);
return 0;
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_print_other.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: tkeynes <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2018/02/07 14:46:15 by tkeynes #+# #+# */
/* Updated: 2018/02/07 14:46:33 by tkeynes ### ########.fr */
/* */
/* ************************************************************************** */
#include "../include/ft_printf.h"
int ft_print_int_max(intmax_t arg, t_flags conv)
{
if (conv.conv == CONV_HEXA)
return (ft_print_hexa_long_long((unsigned long long)arg, conv));
if (conv.conv == CONV_OCTAL)
return (ft_print_octal_long_long((unsigned long long)arg, conv));
if (conv.conv == CONV_INT)
return (ft_print_long_long_int((unsigned long long int)arg, conv));
return (ft_print_long_long_int_unsigned((unsigned long long int)arg, conv));
}
int ft_print_sizet(size_t arg, t_flags conv)
{
if (conv.conv == CONV_HEXA)
return (ft_print_hexa_long_long((unsigned long long)arg, conv));
if (conv.conv == CONV_OCTAL)
return (ft_print_octal_long_long((unsigned long long)arg, conv));
if (conv.conv == CONV_INT)
return (ft_print_long_long_int((unsigned long long int)arg, conv));
return (ft_print_long_long_int_unsigned((unsigned long long int)arg, conv));
}
int ft_print_none(t_flags conv)
{
int count;
count = 0;
if (!conv.options[OPTION_LESS])
{
if (conv.options[OPTION_ZERO])
count += ft_print_zero(conv.width - 1);
else
count += ft_print_space(conv.width - 1);
}
count += ft_putchar('%');
if (conv.options[OPTION_LESS])
count += ft_print_space(conv.width - 1);
return (count);
}
|
C
|
/********************************************************/
/****************** AUTHOR LUOYU ************************/
/********************************************************/
#include "uio.h"
#include "bsdsys.h"
#include "libkern.h"
#include "kin.h"
#include "bsdip.h"
#include "ip_icmp.h"
#include "socket.h"
#include "sockio.h"
#include "bsdif.h"
#include "if_dl.h"
#include "ethernet.h"
#include "kroute.h"
#include "if_arp.h"
#include "if_ether.h"
//from Windows
#include <process.h>
//#include "ips_config.h"
extern int errno;
unsigned long strtoul(const char *cp, char **endp, unsigned int base)
{
unsigned long result = 0, value;
if (!base)
{
base = 10;
if (*cp == '0')
{
base = 8;
cp++;
if ((bsd_tolower(*cp) == 'x') && bsd_isxdigit(cp[1]))
{
cp++;
base = 16;
}
}
}
else if (base == 16)
{
if (cp[0] == '0' && bsd_tolower(cp[1]) == 'x')
cp += 2;
}
while (bsd_isxdigit(*cp) &&
(value = bsd_isdigit(*cp) ? *cp - '0' : bsd_tolower(*cp) - 'a' + 10) < base)
{
result = result * base + value;
cp++;
}
if (endp)
*endp = (char *)cp;
return result;
}
/*
* Check whether "cp" is a valid ascii representation
* of an Internet address and convert to a binary address.
* Returns 1 if the address is valid, 0 if not.
* This replaces inet_addr, the return value from which
* cannot distinguish between failure and a local broadcast address.
*/
//#define _LIBC
in_addr_t
__inet_aton(const char *cp, struct in_addr *addr)
{
static const in_addr_t max[4] = { 0xffffffff, 0xffffff, 0xffff, 0xff };
in_addr_t val;
#ifndef _LIBC
int base;
#endif
char c;
union iaddr
{
uint8_t bytes[4];
uint32_t word;
} res;
uint8_t *pp = res.bytes;
int digit;
#ifdef _LIBC
int saved_errno = errno;
#endif
res.word = 0;
c = *cp;
for (;;)
{
/*
* Collect number up to ``.''.
* Values are specified as for C:
* 0x=hex, 0=octal, isdigit=decimal.
*/
if (!bsd_isdigit(c))
goto ret_0;
{
char *endp;
unsigned long ul;
ul = strtoul (cp, (char **) &endp, 0);
if (ul == ULONG_MAX && errno == ERANGE)
goto ret_0;
if (ul > 0xfffffffful)
goto ret_0;
val = ul;
digit = cp != endp;
cp = endp;
}
c = *cp;
if (c == '.')
{
/*
* Internet format:
* a.b.c.d
* a.b.c (with c treated as 16 bits)
* a.b (with b treated as 24 bits)
*/
if (pp > res.bytes + 2 || val > 0xff)
goto ret_0;
*pp++ = val;
c = *++cp;
}
else
break;
}
/*
* Check for trailing characters.
*/
if (c != '\0' && (!bsd_isascii(c) || !bsd_isspace(c)))
goto ret_0;
/*
* Did we get a valid digit?
*/
if (!digit)
goto ret_0;
/* Check whether the last part is in its limits depending on
the number of parts in total. */
if (val > max[pp - res.bytes])
goto ret_0;
if (addr != NULL)
addr->s_addr = res.word | htonl (val);
return (1);
ret_0:
return (0);
}
/*
* Ascii internet address interpretation routine.
* The value returned is in network order.
*/
in_addr_t
bsd_inet_addr(const char *cp)
{
struct in_addr val;
if (__inet_aton(cp, &val))
return (val.s_addr);
return (INADDR_NONE);
}
/*
* Check whether "cp" is a valid ascii representation
* of an Internet address and convert to a binary address.
* Returns 1 if the address is valid, 0 if not.
* This replaces inet_addr, the return value from which
* cannot distinguish between failure and a local broadcast address.
*/
int
bsd_inet_aton(const char *cp, struct in_addr *addr)
{
register u_int32_t val;
register int base, n;
register char c;
unsigned int parts[4];
register unsigned int *pp = parts;
c = *cp;
for (;;)
{
/*
* Collect number up to ``.''.
* Values are specified as for C:
* 0x=hex, 0=octal, isdigit=decimal.
*/
if (!bsd_isdigit(c))
return (0);
val = 0;
base = 10;
if (c == '0')
{
c = *++cp;
if (c == 'x' || c == 'X')
base = 16, c = *++cp;
else
base = 8;
}
for (;;)
{
if (bsd_isascii(c) && bsd_isdigit(c))
{
val = (val * base) + (c - '0');
c = *++cp;
}
else if (base == 16 && bsd_isascii(c) && bsd_isxdigit(c))
{
val = (val << 4) |
(c + 10 - (bsd_islower(c) ? 'a' : 'A'));
c = *++cp;
}
else
break;
}
if (c == '.')
{
/*
* Internet format:
* a.b.c.d
* a.b.c (with c treated as 16 bits)
* a.b (with b treated as 24 bits)
*/
if (pp >= parts + 3)
return (0);
*pp++ = val;
c = *++cp;
}
else
break;
}
//printf("%s %d\n", __FUNCTION__, __LINE__);
/*
* Check for trailing characters.
*/
if (c != '\0' && (!bsd_isascii(c) || !bsd_isspace(c)))
return (0);
/*
* Concoct the address according to
* the number of parts specified.
*/
n = pp - parts + 1;
switch (n)
{
case 0:
return (0); /* initial nondigit */
case 1: /* a -- 32 bits */
break;
case 2: /* a.b -- 8.24 bits */
if ((val > 0xffffff) || (parts[0] > 0xff))
return (0);
val |= parts[0] << 24;
break;
case 3: /* a.b.c -- 8.8.16 bits */
if ((val > 0xffff) || (parts[0] > 0xff) || (parts[1] > 0xff))
return (0);
val |= (parts[0] << 24) | (parts[1] << 16);
break;
case 4: /* a.b.c.d -- 8.8.8.8 bits */
if ((val > 0xff) || (parts[0] > 0xff) || (parts[1] > 0xff) || (parts[2] > 0xff))
return (0);
val |= (parts[0] << 24) | (parts[1] << 16) | (parts[2] << 8);
break;
}
if (addr)
addr->s_addr = htonl(val);
return (1);
}
char *bsd_strchr(const char *s, int c)
{
for (; *s != (char)c; ++s)
if (*s == '\0')
return NULL;
return (char *)s;
}
|
C
|
#include "motor.h"
#include "global.h"
/*
*****************************************************************************
* Motor_SetPWM()
* Description :
*****************************************************************************
*/
void Motor_SetPWM(CTRL_DataType *control_data, MOTOR_DataType *motor)
{
float w1, w2, w3, w4; /* rotation speed */
w1 = Constraint_f(control_data->Thrust + control_data->Mx - control_data->My - control_data->Mz, 0, 1);
w2 = Constraint_f(control_data->Thrust + control_data->Mx + control_data->My + control_data->Mz, 0, 1);
w3 = Constraint_f(control_data->Thrust - control_data->Mx + control_data->My - control_data->Mz, 0, 1);
w4 = Constraint_f(control_data->Thrust - control_data->Mx - control_data->My + control_data->Mz, 0, 1);
motor->motor1 = (uint16_t)(w1 * PWM_WIDTH + PWM_LOWEST + 0.5f);
motor->motor2 = (uint16_t)(w2 * PWM_WIDTH + PWM_LOWEST + 0.5f);
motor->motor3 = (uint16_t)(w3 * PWM_WIDTH + PWM_LOWEST + 0.5f);
motor->motor4 = (uint16_t)(w4 * PWM_WIDTH + PWM_LOWEST + 0.5f);
//Motor_Smooth(motor);
Motor_Constraint(motor);
BSP_PWM_Set(motor->motor1, motor->motor2, motor->motor3, motor->motor4);
}
/*
*****************************************************************************
* Motor_MinThrust()
* Description :
*****************************************************************************
*/
void Motor_MinThrust(MOTOR_DataType *motor)
{
motor->motor1 = PWM_LOWEST;
motor->motor2 = PWM_LOWEST;
motor->motor3 = PWM_LOWEST;
motor->motor4 = PWM_LOWEST;
BSP_PWM_Set(motor->motor1, motor->motor2, motor->motor3, motor->motor4);
}
/*
*****************************************************************************
* Motor_MaxThrust()
* Description :
*****************************************************************************
*/
void Motor_MaxThrust(MOTOR_DataType *motor)
{
motor->motor1 = PWM_HIGHEST;
motor->motor2 = PWM_HIGHEST;
motor->motor3 = PWM_HIGHEST;
motor->motor4 = PWM_HIGHEST;
BSP_PWM_Set(motor->motor1, motor->motor2, motor->motor3, motor->motor4);
}
/*
*****************************************************************************
* MotorConstraint()
* Description :
*****************************************************************************
*/
void Motor_Constraint(MOTOR_DataType *motor)
{
motor->motor1 = (uint16_t)Constraint_int(motor->motor1, PWM_LOWEST, PWM_HIGHEST);
motor->motor2 = (uint16_t)Constraint_int(motor->motor2, PWM_LOWEST, PWM_HIGHEST);
motor->motor3 = (uint16_t)Constraint_int(motor->motor3, PWM_LOWEST, PWM_HIGHEST);
motor->motor4 = (uint16_t)Constraint_int(motor->motor4, PWM_LOWEST, PWM_HIGHEST);
}
/*
****************************************************************************
* MotorSmooth()
* Description : compensate the motor mechanics effect
****************************************************************************
*/
void Motor_Smooth(MOTOR_DataType *motor)
{
static uint16_t last_motor1 = PWM_LOWEST;
static uint16_t last_motor2 = PWM_LOWEST;
static uint16_t last_motor3 = PWM_LOWEST;
static uint16_t last_motor4 = PWM_LOWEST;
if ((motor->motor1) > last_motor1)
motor->motor1 = (last_motor1 + 1 * (motor->motor1)) / 2;
else
motor->motor1 = (motor->motor1) - (last_motor1 - (motor->motor1)) * 1;
if ((motor->motor2) > last_motor2)
motor->motor2 = (last_motor2 + 1 * (motor->motor2)) / 2;
else
motor->motor2 = (motor->motor2) - (last_motor2 - (motor->motor2)) * 1;
if ((motor->motor3) > last_motor3)
motor->motor3 = (last_motor3 + 1 * (motor->motor3)) / 2;
else
motor->motor3 = (motor->motor3) - (last_motor3 - (motor->motor3)) * 1;
if ((motor->motor4) > last_motor4)
motor->motor4 = (last_motor4 + 1 * (motor->motor4)) / 2;
else
motor->motor4 = (motor->motor4) - (last_motor4 - (motor->motor4)) * 1;
last_motor1 = (motor->motor1);
last_motor2 = (motor->motor2);
last_motor3 = (motor->motor3);
last_motor4 = (motor->motor4);
}
|
C
|
#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <limits.h>
void prim(int vertex, int graph[][vertex]);
void readData();
void createEdge(int vertex, int graph[vertex][vertex], int src, int dest, int weight);
void initializeMatrix(int vertex, int graph[vertex][vertex]);
int main(){
readData();
return 0;
}
void prim(int vertex, int graph[][vertex]){
int distancia[vertex], precedente[vertex], visitas[vertex], vertice[vertex], x = 0, z = 0, dist_min = INT_MAX;
for(int v = 0; v < vertex; v++){
distancia[v] = INT_MAX/2;
precedente[v] = -1;
visitas[v] = 0;
vertice[v] = v;
}
distancia[0] = 0;
for(int xi = 0; xi < vertex; xi++){
for(int k=0; k< vertex; k++){
if(graph[x][k] != -1 && distancia[k] > graph[x][k] && visitas[k] == 0){
precedente[k] = x;
distancia[k] = graph[x][k];
}
}
visitas[x] = 1;
z = 0;
dist_min = INT_MAX;
while (z < vertex){
if(dist_min > distancia[z] && visitas[z] == 0){
dist_min = distancia[z];
x = z;
}
z++;
}
}
int y = 1, cont = 0, aux, aux2;
z = 1;
for(int i = 1; i < vertex; i++)
{
if(vertice[i] > precedente[i])
{
aux = vertice[i];
vertice[i] = precedente[i];
precedente[i] = aux;
}
}
for(int j=5; j>=1; j--){
for(int i=0; i<j; i++){
if(vertice[i]>vertice[i+1]){
aux=precedente[i];
precedente[i]=precedente[i+1];
precedente[i+1]=aux;
aux2 = vertice[i];
vertice[i] = vertice[i+1];
vertice[i+1] = aux2;
}
}
}
int agm = 0;
for(int i = 1; i < vertex; i++){
printf("(%d, %d) ", vertice[i]+1, precedente[i]+1);
agm += graph[vertice[i]][precedente[i]];
}
printf("\nCUSTO AGM: %d \n", agm);
}
void initializeMatrix(int vertex, int graph[vertex][vertex]){
for(int x = 0; x< vertex; x++){
for(int k=0; k< vertex; k++)
graph[x][k] = -1;
}
}
void readData(){
FILE *data;
int vertex=0, edges=0, src=0, dest=0, weight=0, i=0;
data = fopen("prim_input.input", "r");
if (data==NULL){
fputs("Cannot open source file\n", stderr);
exit(EXIT_FAILURE);
}else{
size_t maxLen = 6;
char *line= malloc(6*sizeof(char));
vertex = fgetc(data) - '0';
// printf("%d\n", vertex);
int graph[vertex][vertex];
initializeMatrix(vertex, graph);
while (getline(&line, &maxLen, data) > 0)
{
if (i != 0)
{
if (line[0])
src = line[0] - '0';
if (line[2])
dest = line[2] - '0';
if (line[4])
weight = line[4] - '0';
else
weight = 1;
createEdge(vertex, graph, src-1, dest-1, weight);
}
i++;
}
printf("\n");
// para printar a matrix
// for(int x = 0; x < vertex; x++){
// for(int k=0; k< vertex; k++)
// printf("%d ", graph[x][k]);
// printf("\n");
// }
prim(vertex, graph);
if (line)
free(line);
fclose(data);
exit(EXIT_SUCCESS);
}
}
void createEdge(int vertex, int graph[vertex][vertex], int src, int dest, int weight){
graph[src][dest] = weight;
graph[dest][src] = weight;
}
|
C
|
/*
* bankaccount.c
* Authors: Emmannuel Baah
* Yuk Yan
*/
#include "bankaccount.h"
#include <string.h>
#define errormessage(x) errormessage_(x, __FILE__, __LINE__)
/*
* Create an account given a name and balance.
* insession is initialized to 0.
*/
Account *
accountcreate( char * name )
{
Account * account;
if ( (account = (Account *)malloc(sizeof(Account))) == NULL )
{
errormessage("Not enough memory for Account");
}
else
{
strncpy(account->accountname, name, 100);
account->currentbalance = 0;
account->insession = 0;
}
return account;
}
/*
* Destroy and free the memory of a given account.
*/
void
accountdestroy( Account * account )
{
free(account);
}
/*
* Prints the information regarding the account.
*/
void
accountprint( Account * account )
{
char * insession;
if ( account == NULL )
{
errormessage("NULL Account");
return;
}
else
{
if ( account->insession)
{
insession = "IN SERVICE";
}
else
{
insession = "NOT IN SERVICE";
}
printf("-----------------------------------------------------\n");
printf("Account name -- %s\n", account->accountname);
printf("Current balance -- %.2f\n", account->currentbalance);
printf("Session status -- %s\n", insession);
printf("-----------------------------------------------------\n");
}
}
|
C
|
/*
* MC68HC11 specific processing
*/
#include "do.h"
#include "globals.h"
#include "as.h"
#include "util.h"
#include "eval.h"
#define PAGE1 0x00
#define PAGE2 0x18
#define PAGE3 0x1A
#define PAGE4 0xCD
/* addressing modes */
#define IMMED 0
#define INDX 1
#define INDY 2
#define LIMMED 3 /* long immediate */
#define OTHER 4
static int bitop(int op, int mode, int class);
static void do_gen(int op, int mode, int pnorm,int px,int py);
static void do_indexed(int op);
static void epage(int p);
int yflag = 0; /* YNOIMM, YLIMM, and CPD flag */
/*
* localinit --- machine specific initialization
*/
void localinit(void)
{
}
/*
* do_op --- process mnemonic
*
* Called with the base opcode and it's class. Optr points to
* the beginning of the operand field.
*/
void do_op(int opcode /* base opcode */, int class /* mnemonic class */)
{
int dist; /* relative branch distance */
int amode; /* indicated addressing mode */
char *peek;
/* guess at addressing mode */
peek = Optr;
amode = OTHER;
while( !delim(*peek) && *peek != EOS) /* check for comma in operand field */
if( *peek++ == ',' ){
if( mapdn(*peek) == 'y' )
amode = INDY;
else
amode = INDX;
break;
}
if( *Optr == '#' ) amode = IMMED;
yflag = 0;
switch(class){
case P2INH:
emit(PAGE2);
case INH: /* inherent addressing */
emit(opcode);
return;
case REL: /* relative branches */
eval();
dist = Result - (Pc+2);
emit(opcode);
if( (dist >127 || dist <-128) && Pass==2){
error("Branch out of Range");
emit(lobyte(-2));
return;
}
emit(lobyte(dist));
return;
case LONGIMM:
if( amode == IMMED )
amode = LIMMED;
case NOIMM:
if( amode == IMMED ){
error("Immediate Addressing Illegal");
return;
}
case GEN: /* general addressing */
do_gen(opcode,amode,PAGE1,PAGE1,PAGE2);
return;
case GRP2:
if( amode == INDY ){
Cycles++;
emit(PAGE2);
amode = INDX;
}
if( amode == INDX )
do_indexed(opcode);
else{ /* extended addressing */
eval();
emit(opcode+0x10);
eword(Result);
}
return;
case CPD: /* cmpd */
if( amode == IMMED )
amode = LIMMED;
if( amode == INDY )
yflag=1;
do_gen(opcode,amode,PAGE3,PAGE3,PAGE4);
return;
case XNOIMM: /* stx */
if( amode == IMMED ){
error("Immediate Addressing Illegal");
return;
}
case XLIMM: /* cpx, ldx */
if( amode == IMMED )
amode = LIMMED;
do_gen(opcode,amode,PAGE1,PAGE1,PAGE4);
return;
case YNOIMM: /* sty */
if( amode == IMMED ){
error("Immediate Addressing Illegal");
return;
}
case YLIMM: /* cpy, ldy */
if(amode == INDY)
yflag=1;
if( amode == IMMED )
amode = LIMMED;
do_gen(opcode,amode,PAGE2,PAGE3,PAGE2);
return;
case BTB: /* bset, bclr */
case SETCLR: /* brset, brclr */
opcode = bitop(opcode,amode,class);
if (amode == INDX)
Cycles++;
if( amode == INDY ){
Cycles+=2;
emit(PAGE2);
amode = INDX;
}
emit(opcode);
eval();
emit(lobyte(Result)); /* address */
if( amode == INDX )
Optr += 2; /* skip ,x or ,y */
Optr = skip_white(Optr);
eval();
emit(lobyte(Result)); /* mask */
if( class == SETCLR )
return;
Optr = skip_white(Optr);
eval();
dist = Result - (Pc+1);
if( (dist >127 || dist <-128) && Pass==2){
error("Branch out of Range");
dist = Old_pc - (Pc+1);
}
emit(lobyte(dist));
return;
default:
fatal("Error in Mnemonic table");
}
}
/*
* bitop --- adjust opcode on bit manipulation instructions
*/
static int bitop(int op, int mode, int class)
{
if( mode == INDX || mode == INDY )
return(op);
if( class == SETCLR )
return(op-8);
else if(class==BTB)
return(op-12);
else
fatal("bitop");
}
/*
* do_gen --- process general addressing modes
*/
static void do_gen(int op /* base opcode */,
int mode /* addressing mode */,
int pnorm /* page for normal addressing modes: IMM,DIR,EXT */,
int px /* page for INDX addressing */,
int py /* page for INDY addressing */)
{
switch(mode)
{
case LIMMED:
Optr++;
epage(pnorm);
emit(op);
eval();
eword(Result);
break;
case IMMED:
Optr++;
epage(pnorm);
emit(op);
eval();
emit(lobyte(Result));
break;
case INDY:
if(yflag)
Cycles += 2;
else
Cycles += 3;
epage(py);
do_indexed(op+0x20);
break;
case INDX:
Cycles+=2;
epage(px);
do_indexed(op+0x20);
break;
case OTHER:
eval();
epage(pnorm);
if(Force_word){
emit(op+0x30);
eword(Result);
Cycles+=2;
break;
}
if(Force_byte){
emit(op+0x10);
emit(lobyte(Result));
Cycles++;
break;
}
if(Result>=0 && Result <=0xFF){
emit(op+0x10);
emit(lobyte(Result));
Cycles++;
break;
}
else {
emit(op+0x30);
eword(Result);
Cycles+=2;
break;
}
break;
default:
error("Unknown Addressing Mode");
}
}
/*
* do_indexed --- handle all wierd stuff for indexed addressing
*/
static void do_indexed(int op)
{
char c;
emit(op);
eval();
if( *Optr++ != ',' )
error("Syntax");
c = mapdn(*Optr++);
if( c != 'x' && c != 'y')
warn("Indexed Addressing Assumed");
if( Result < 0 || Result > 255)
warn("Value Truncated");
emit(lobyte(Result));
}
/*
* epage --- emit page prebyte
*/
static void epage(int p)
{
if( p != PAGE1 ) /* PAGE1 means no prebyte */
emit(p);
}
|
C
|
#include "capture.h"
void de_init(){
enum v4l2_buf_type type;
unsigned int i;
camera.capturing=FALSE;
//stopping the capture
printf("Stop capturing\n\n");
type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
if (xioctl (camera.fd, VIDIOC_STREAMOFF, &type) == -1)
errno_exit("VIDIOC_STREAMOFF");
//reseting buffer
printf("Reseting the buffers\n\n");
for (i = 0; i < camera.i_buffers; i++) {
struct v4l2_buffer buf;
CLEAR(buf);
buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
buf.memory = V4L2_MEMORY_MMAP;
buf.index = i;
if (xioctl (camera.fd, VIDIOC_QUERYBUF, &buf) == -1)
errno_exit("VIDIOC_QUERYBUF");
munmap (camera.buffers[i].start, camera.buffers[i].length);
}
printf("Closing the device\n\n");
close(camera.fd);
exit(1);
}
|
C
|
#include <stdio.h>
int main()
{
int i,j,ii,jj,n;
int count=0, max_count=0, start_index=0, temp_start_index=0;
int data[100] ;
printf("Input Array n : ");
scanf("%d",&n);
printf("\n");
for(int i=0;i<n;i++)
{
scanf("%d",&data[i]);
}
printf("%d ",data[0]);
printf("\n");
for(int i=0; i < n+1; ++i)
{
for (j=n;j>=0;--j)
{
for (ii=i,jj=j;;++ii,--jj)
{
if (data[ii]==data[jj])
{
if (count==0)
{
temp_start_index=ii;
}
++count;
if (ii==jj)
{
count=count*2-1;
break;
}
else{
if (ii>jj)
{
--count;
count=count*2;
break;
}
}
}
else
{
count=0;
break;
}
}
if (count>max_count)
{
max_count=count;
start_index=temp_start_index;
count=0;
temp_start_index=0;
}
}
}
printf("Subarray palindrom\n");
for (i=start_index;i<start_index+max_count;++i)
{
printf("%d ",data[i]);
}
return 0;
}
|
C
|
/*第五章复习题 第四题*/
#include<stdio.h>
int main(void)
{
int i = 1;
float n;
printf("Watch out! Here come a bunch of fractions!\n");
while(i < 30) {
n = 1.0 / i;
printf(" %f", n);
i++;
}
printf("\nThat's all, folks!\n");
return 0;
}
|
C
|
/*
* Sooyeon E. Chough (A92093139)
* Yue Jiang (A92095681)
*/
/**
* ALL IMPLEMENTATIONS AND HELPER FUNCTIONS FOR DECODER WILL BE IN THIS FILE.
*/
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include "common.h"
#include "decoder.h"
/**
* Takes a char c and int index as input.
* Extracts the bit at the input index from the char c. The 0 index
* refers to the LSB, so for example, index 2 should extract the 3rd
* least significant bit.
*
* @param c the char to extract a bit from
* @param index the index of the bit to extract
* @returns the value of the bit at index in c
*/
int extractBit(char c, int index)
{
// Initializing necessary variables
int ch, i = 0;
// Getting the binary version of the char
ch = (int) c;
// Shifting ch as necessary to get wanted index
ch = ch >> index;
// Getting wanted bit
i = ch & 0x01;
// Returning the bit
return i;
}
/**
* Takes a 6 character array b as input and returns the corresponding
* char from MAPPING that is indexed by the binary ASCII string b.
* For example, if b = "010101", then the char that is mapped to it is
* in MAPPING, index 1*16 + 1*4 + 1*1 = 21.
*
* @param b a pointer to a 6 character array, with ASCII '1's and '0's
* @returns the corresponding character from MAPPING
*/
char decodeChar(char *b)
{
// Initializing necessary variables
char *temp = NULL;
int i, total = 0;
// Going through each char of the given array
for( i = 0; i < 6; i++ )
{
// Getting value and multiplying by corresponding power of 2
temp = (char*) malloc( sizeof(char) );
*temp = b[ i ];
if( *temp == '1' )
{
total = total + ( 32 >> i );
}
free( temp );
}
// Returning char from MAPPING array
return MAPPING[ total ];
}
/**
* Takes a FILE handle in as input (corresponding to
* an encoded file) and reads the file, char by char. The
* bit at the input index of each char is extracted (by calling
* extractBit). The least significant bit is in index 0.
*
* For each character, if the extracted bit is 0, output ASCII '0' to
* the output file. If the extracted bit is 1, output ASCII
* '1' to the output file.
*
* @param in the input file handle to read from
* @param out the output file to write the extracted ASCII binary into
* @param index the index of the bit to extract from each char
*/
void codeToBinary(FILE *in, FILE *out, int index)
{
// Initializing necessary variables
int bit = 0;
char ch = ' ';
char *ptr = NULL;
// Getting first char
ch = fgetc( in );
while( ch != EOF )
{
// Getting bit
bit = extractBit( ch, index );
// Allocating memory
ptr = (char*) malloc( sizeof(char) );
// Getting necessary char '0' or '1'
if( bit == 0 )
{
*ptr = '0';
}
else
{
*ptr = '1';
}
// Writing to output file
fwrite( ptr, sizeof(char), 1, out );
// Freeing memory
free( ptr );
// Getting next char
ch = fgetc( in );
}
// End of file
return;
}
/**
* Takes a FILE handle in as input (corresponding to a
* "binary" decoded file) and reads the file, 6 chars at a
* time. Each 6 chars (all ASCII 0's and 1's) should be read into a
* char array and decoded into its corresponding char (by calling
* decodeChar). The resulting chars would be output to the FILE handle
* pointed to by out.
*
* @param in the input file, encoded as ASCII '1's and '0's
* @Param out the decoded output file (ASCII)
*/
void binaryToText(FILE *in, FILE *out)
{
// Initializing necessary variables
char c = ' ';
char *bin = NULL;
int i = 0;
// Reading file
c = fgetc( in );
// Going through file
while( c != EOF )
{
// Allocating memory
bin = (char*) malloc( sizeof(char)*6 );
// Making the 6-char array
for( i = 0; i < 6; i++ )
{
bin[ i ] = c;
c = fgetc( in );
}
// Getting resulting char
*bin = decodeChar( bin );
// Writing onto file
fwrite( bin, sizeof(char), 1, out );
// Freeing memory
free( bin );
}
}
/**
* Reads in a file from the specified input path and outputs a a binary decoding to
* specified bin path and a fully decoded version to specified output path.
* This should simply open the necessary files, call the above helper functions
* in the correct sequence, and close the necessary files.
*
* @param input the path to the input file
* @param bin the path to the decoded ASCII binary output file
* @param output the path to the decoded output file
* @param index The index of the bit from which binary values should be extracted
*/
void decodeFile(char* input, char* bin, char* output, int index)
{
// Initializing necessary variables
FILE *in, *out, *ascii;
// Opening files
in = fopen( input, "r" );
out = fopen( output, "w" );
ascii = fopen( bin, "w" );
// Writing first time
codeToBinary( in, ascii, index );
// Changing permissions
fclose( ascii );
fopen( bin, "r" );
// Writing second time
binaryToText( ascii, out );
// Closing files
fclose( in );
fclose( out );
fclose( ascii );
// End of method
return;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main ()
{
float a,b,l;
printf("Digite um numero e a base, respectivamente: ");
scanf("%f%f",&a,&b);
l=(log(a))/(log(b));
printf("O log vale: %f\n",l);
return 0;
}
|
C
|
#ifndef OS_PROCESS_H
#define OS_PROCESS_H
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_PROCESS 512
#define MAX_QUEUE 256
typedef struct Process
{
int process_id; // 프로세스 번호
int arrival_time; // 도착 시간
int burst_duration; // 수행 시간
int deadline_time; // 데드라인 (실시간)
} Process;
typedef struct Queue_Node
{
int process_id; // 프로세스 번호
int arrival_time; // 도착 시간
int remained_time; // 수행 후 남아있는 시간
int deadline_time; // 데드라인 (실시간)
} Queue_Node;
typedef struct TimeItem
{
int time; // 시간
int pid; // PID
} TimeItem;
Process g_process[MAX_PROCESS];
#endif
|
C
|
#include<stdio.h>
#include<stdlib.h>
#include<locale.h>
int main(){
setlocale(LC_ALL, "Portuguese");
int a = 1;
char b = 'x';
//Cdigo de exemplo com if
if (a == 1){
printf ("\nOpo escolhida: 1");
}else if (a == 2){
printf ("\nOpo escolhida: 2");
}else if (a == 3){
printf ("\nOpo escolhida: 3");
}else{
printf ("\nOpo invlida");
}
//O mesmo cdido de cima, adaptado ao switch
switch(a){
case 1:
printf ("\nOpo escolhida: 1");
break;
case 2:
printf ("\nOpo escolhida: 2");
break;
case 3:
printf ("\nOpo escolhida: 3");
break;
default:
printf("\nOpo invlida");
break;
}
//Switch com char
switch(b){
case 'x':
printf("\nA letra x");
break;
default:
printf ("\nA letra no x");
}
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* main_ft_isdigit.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: jfranchi <jfranchi@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/05/31 13:40:03 by jfranchi #+# #+# */
/* Updated: 2021/05/31 21:21:44 by jfranchi ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
#include "../headers/main_libft.h"
int main_ft_isdigit(int ch)
{
int function;
int ft_function;
function = isdigit(ch);
ft_function = ft_isdigit(ch);
if (function == ft_function)
printf("function = %d and ft_function = %d - OK\n", \
function, ft_function);
else
printf("function = %d and ft_function = %d - KO\n", \
function, ft_function);
return (ch);
}
|
C
|
#include "hw_config.h"
#include "pressure.h"
/*
Init SPI for operate MCP6S21 Opertional amplifier
*/
void PressureInit(void)
{
GPIO_InitTypeDef GPIO_InitStruct;
SPI_InitTypeDef SPI_InitStruct;
// enable clock for used IO pins
RCC_AHBPeriphClockCmd(RCC_AHBPeriph_GPIOB, ENABLE);
/* configure pins used by SPI1
* PB3 = SCK
* PB5 = MOSI
* PB4 = MISO
*/
GPIO_InitStruct.GPIO_Pin = GPIO_Pin_3 | GPIO_Pin_4 | GPIO_Pin_5;
GPIO_InitStruct.GPIO_Mode = GPIO_Mode_AF;
GPIO_InitStruct.GPIO_OType = GPIO_OType_PP;
GPIO_InitStruct.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_InitStruct.GPIO_PuPd = GPIO_PuPd_NOPULL;
GPIO_Init(GPIOB, &GPIO_InitStruct);
// connect SPI1 pins to SPI alternate function
GPIO_PinAFConfig(GPIOB, GPIO_PinSource3, GPIO_AF_5);
GPIO_PinAFConfig(GPIOB, GPIO_PinSource4, GPIO_AF_5);
GPIO_PinAFConfig(GPIOB, GPIO_PinSource5, GPIO_AF_5);
// enable clock for used IO pins
RCC_AHBPeriphClockCmd(RCC_AHBPeriph_GPIOD, ENABLE);
/*
PB6 - CS
*/
GPIO_InitStruct.GPIO_Pin = GPIO_Pin_6;
GPIO_InitStruct.GPIO_Mode = GPIO_Mode_OUT;
GPIO_InitStruct.GPIO_OType = GPIO_OType_PP;
GPIO_InitStruct.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_InitStruct.GPIO_PuPd = GPIO_PuPd_UP;
GPIO_Init(GPIOB, &GPIO_InitStruct);
GPIO_SetBits(GPIOB, GPIO_Pin_6);
// enable peripheral clock
RCC_APB2PeriphClockCmd(RCC_APB2Periph_SPI1, ENABLE);
/* configure SPI1 in Mode 0
* CPOL = 0 --> clock is low when idle
* CPHA = 0 --> data is sampled at the first edge
*/
SPI_InitStruct.SPI_Direction = SPI_Direction_2Lines_FullDuplex;
SPI_InitStruct.SPI_Mode = SPI_Mode_Master;
SPI_InitStruct.SPI_DataSize = SPI_DataSize_16b;
SPI_InitStruct.SPI_CPOL = SPI_CPOL_Low;
SPI_InitStruct.SPI_CPHA = SPI_CPHA_1Edge;
SPI_InitStruct.SPI_NSS = SPI_NSS_Soft | SPI_NSSInternalSoft_Set;
SPI_InitStruct.SPI_BaudRatePrescaler = SPI_BaudRatePrescaler_256;
SPI_InitStruct.SPI_FirstBit = SPI_FirstBit_MSB;
SPI_Init(SPI1, &SPI_InitStruct);
SPI_Cmd(SPI1, ENABLE);
}
static uint16_t SPI1_send(uint16_t data)
{
SPI1->DR = data; // write data to be transmitted to the SPI data register
while( !(SPI1->SR & SPI_I2S_FLAG_TXE) ); // wait until transmit complete
while( !(SPI1->SR & SPI_I2S_FLAG_RXNE) ); // wait until receive complete
while( SPI1->SR & SPI_I2S_FLAG_BSY ); // wait until SPI is not busy anymore
return SPI1->DR; // return received data from SPI data register
}
uint16_t PressureSend(uint16_t data)
{
GPIO_ResetBits(GPIOB, GPIO_Pin_6);
uint16_t out = SPI1_send(data);
GPIO_SetBits(GPIOB, GPIO_Pin_6);
return out;
}
uint16_t PressureRead(uint8_t reg)
{
uint16_t data = reg;
data = (data<<8)|0x8000;
return PressureSend(data)&0xFF;
}
void PressureWrite(uint8_t reg, uint8_t value)
{
uint16_t data = reg;
data = (data<<8)|value;
PressureSend(data);
}
int16_t PressureReadTemp()
{
uint16_t temp_lo = PressureRead(0x2B);
uint16_t temp_hi = PressureRead(0x2C);
return ((int16_t)((temp_hi<<8)|temp_lo))/48+425;
}
uint16_t PressureReadPressure()
{
uint32_t p_xl = PressureRead(0x28);
uint32_t p_l = PressureRead(0x29);
uint32_t p_h = PressureRead(0x2A);
uint32_t p = (p_h<<16)|(p_l<<8)|(p_xl);
return p/4096;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#define TRUE 1
#define FALSE 0
#define ll long long int
#define ull unsigned long long int
/*
|
|
3 2 1
|
|
--------4----------------0-------
|
|
5 6 7
|
|
*/
typedef struct {
int idx;
int x, y;
float m;
} Pair;
Pair hero;
int getQuad(ll x, ll y) {
// if (x > 0 && y == 0) return 0;
if (x > 0 && y > 0) return 1;
if (x == 0 && y > 0) return 2;
if (x < 0 && y > 0) return 3;
// if (x < 0 && y == 0) return 4;
// if (x < 0 && y < 0) return 5;
// if (x == 0 && y < 0) return 6;
// if (x < 0 && y > 0) return 7;
}
// Return < 0: a < b, == 0: a == b, > 0: a > b
int cmpfunc(const void* a, const void* b) {
Pair p = *(Pair*)a, q = *(Pair*)b;
return (q.m - p.m) > 0 ? 1 : -1;
}
int main() {
int n;
scanf("%d", &n);
n = n - 1;
Pair points[n];
int minY = 1e6, minYIdx = -1;
for (int i = 0; i < n; ++i) {
scanf("%d %d %d", &points[i].idx, &points[i].x, &points[i].y);
if (points[i].y < minY) {
minYIdx = i;
minY = points[i].y;
}
}
scanf("%d %d %d", &hero.idx, &hero.x, &hero.y);
if (hero.y > minY) {
Pair temp = hero;
hero = points[minYIdx];
points[minYIdx] = temp;
}
// printf("Hero: [%d] %d %d\n\n", hero.idx, hero.x, hero.y);
// Translating to reference frame with hero as origin
for (int i = 0; i < n; i++) {
points[i].x -= hero.x;
points[i].y -= hero.y;
points[i].m = (float)points[i].x / (float)points[i].y;
}
qsort(points, n, sizeof(Pair), cmpfunc);
for (int i = 0; i < n; i++) {
printf("%d ", points[i].idx);
// printf("[%d]: (%.3f) (%d, %d)\n", points[i].idx, points[i].m, points[i].x, points[i].y);
}
return 0;
}
|
C
|
#include <stdio.h>
void posortujWektor(float tablica[], int n);
void wypiszWektor(float tablica[], int n);
int main(int argc, char** argv) {
// max 20 liczb
int ileLiczb;
printf("Ile liczb chcesz posortowac ?: ");
scanf("%d",&ileLiczb);
if(ileLiczb <= 0) {
printf("Ilosc liczb do posortowania nie moze byc mniejsze niz 0!\n");
return 1;
}
if(ileLiczb > 20) {
printf("Maksymalnie mozesz posortowac 20 liczb.\n");
return 1;
}
float tablicaLiczb[ileLiczb];
int tmp = 0;
printf("Podaj te liczby wpisujac liczba + enter lub liczba + spacja\n");
while(tmp < ileLiczb) {
scanf("%f", &tablicaLiczb[tmp]);
tmp++;
}
printf("Wektor do posortowania: ");
wypiszWektor(tablicaLiczb, ileLiczb);
posortujWektor(tablicaLiczb, ileLiczb);
printf("Wektor posortowany: ");
wypiszWektor(tablicaLiczb, ileLiczb);
return 0;
}
void posortujWektor(float tablica[], int n) {
int i,j;
for(i=0 ; i < n ; i++) {
for(j=1 ; j < n-i ; j++) {
if(tablica[j-1] > tablica[j]) {
float tmp = tablica[j-1];
tablica[j-1] = tablica[j];
tablica[j] = tmp;
}
}
}
}
void wypiszWektor(float tablica[], int n) {
int i=0;
printf("[ ");
while(i < n){
printf("%.2f ", tablica[i]);
i++;
}
printf(" ]\n");
}
|
C
|
/* Author : Chaitaly Kundu
Date: 13-03-2021 *?
/* Write a program to find the factorial value of any number entered through keyboard */
#include<stdio.h>
int main()
{
int n,i,factorial=1;
printf("Enter the number: ");
scanf("%d",&n);
for(i=1;i<=n;i++)
{
factorial = factorial*i;
}
printf("%d",factorial);
return 0;
}
|
C
|
#include <stdio.h>
int x, y, z;
int gcd(int x, int y) {
int i, q, r;
if(x > y) {
// printf("x is bigger\n");
for(i=(y-1);i>1;i--) {
q = x % i;
r = y % i;
if (!q & !r) {
printf("%d and %d are not coprimes with GCD %d\n", x, y, i);
return 0;}
}
}
else {
// printf("y is bigger\n");
for(i=(x-1);i>1;i--) {
q = x % i;
r = y % i;
if (!q & !r) {
printf("%d and %d are not coprimes with GCD %d\n", x, y, i);
return 0;}
}
}
printf("%d and %d are coprimes!\n", x, y);
return 1;
}
|
C
|
#include <stdio.h>
int main()
{
char str1[50], str2[50],a,b;
printf("\nEnter first string: ");
scanf("%s",str1);
printf("\nEnter second string: ");
scanf("%s",str2);
for(a=0; str1[a]!='\0'; ++a);
for(b=0; str2[b]!='\0'; ++b, ++a)
{
str1[a]=str2[b];
}
str1[a]='\0';
printf("\nOutput: %s",str1);
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <string.h>
#include <ctype.h>
#include "hashmap.h"
#include "list.h"
typedef struct{
char nombre[60];
char marca[25];
char tipo[20];
int stock;
int precio;
}Producto;
typedef struct{
List * lista;
char nombre[30];
}Carro;
char * minuscula (char * str){
for(int i = 0; str[i]; i++){
str[i] = tolower(str[i]);
}
return str;
}
char *get_csv_field (char * tmp, int k) {
int open_mark = 0;
char* ret=(char*) malloc (100*sizeof(char));
int ini_i=0, i=0;
int j=0;
while(tmp[i+1]!='\0'){
if(tmp[i]== '\"'){
open_mark = 1-open_mark;
if(open_mark) ini_i = i+1;
i++;
continue;
}
if(open_mark || tmp[i]!= ','){
if(k==j) ret[i-ini_i] = tmp[i];
i++;
continue;
}
if(tmp[i]== ','){
if(k==j) {
ret[i-ini_i] = 0;
return ret;
}
j++; ini_i = i+1;
}
i++;
}
if(k==j) {
ret[i-ini_i] = 0;
return ret;
}
return NULL;
}
void importarArchivo(HashMap * mapaNombre, HashMap * mapaMarca, HashMap * mapaTipo, FILE * archivo){
char csv[50];
printf(" Ingrese el nombre del archivo: \n ");
gets(csv);
archivo=fopen(csv,"r");
if (archivo==NULL){
printf(" El archivo de nombre %s no se puede abrir.\n",csv);
return;
}
char * linea = (char*)malloc(1024*sizeof(char));
while(fgets(linea,1023,archivo) != NULL){
Producto * new = (Producto *)malloc(sizeof(Producto));
strcpy(new->nombre, minuscula(get_csv_field(linea,0)));
strcpy(new->marca, minuscula(get_csv_field(linea,1)));
strcpy(new->tipo, minuscula(get_csv_field(linea,2)));
new->stock = atoi(get_csv_field(linea,3));
new->precio = atoi(get_csv_field(linea,4));
insertMap(mapaNombre, strdup(new->nombre), new);
if(searchMap(mapaMarca, new->marca)==NULL){
HashMap * mapaAux = createMap(20);
insertMap(mapaAux, strdup(new->nombre), new);
insertMap(mapaMarca, new->marca, mapaAux);
}else{
HashMap * mapa = searchMap(mapaMarca, new->marca);
insertMap(mapa, strdup(new->nombre), new);
}
if(searchMap(mapaTipo, new->tipo)==NULL){
HashMap * mapaAux = createMap(20);
insertMap(mapaAux, strdup(new->nombre), new);
insertMap(mapaTipo, new->tipo, mapaAux);
}else{
HashMap * mapa = searchMap(mapaTipo, new->tipo);
insertMap(mapa, strdup(new->nombre), new);
}
}
printf("Archivo importado correctamente \n");
}
void exportarArchivo(HashMap * mapaNombre){
FILE * archivo = fopen("listaProductos.csv", "r+");
fseek(archivo, -1, SEEK_END);
Producto * prod = firstMap(mapaNombre);
while(prod != NULL){
fprintf(archivo, "%s, ",prod->nombre);
fprintf(archivo, "%s, ",prod->marca);
fprintf(archivo, "%s, ",prod->tipo);
fprintf(archivo, "%i, ",prod->stock);
fprintf(archivo, "%i, \n",prod->precio);
prod = nextMap(mapaNombre);
}
printf("archivo exportado correctamente\n");
fclose(archivo);
}
void agregarProducto(HashMap * mapaNombre, HashMap * mapaMarca, HashMap * mapaTipo){
Producto * new = (Producto *)malloc(sizeof(Producto));
printf("ingrese el nombre del producto a agregar\n");
gets(new->nombre);
minuscula(new->nombre);
printf("ingrese la marca del producto a agregar\n");
gets(new->marca);
minuscula(new->marca);
printf("ingrese el tipo de producto a agregar\n");
gets(new->tipo);
minuscula(new->tipo);
printf("ingrese el stock del producto a agregar\n");
scanf("%i", &new->stock);
printf("ingrese el precio del producto a agregar\n");
scanf("%i", &new->precio);
Producto * buscado = searchMap(mapaNombre, new->nombre);
if(buscado == NULL){
insertMap(mapaNombre, strdup(new->nombre), new);
if(searchMap(mapaMarca, new->marca)==NULL){
HashMap * mapaAux = createMap(20);
insertMap(mapaAux, strdup(new->nombre), new);
insertMap(mapaMarca, new->marca, mapaAux);
}else{
HashMap * mapa = searchMap(mapaMarca, new->marca);
insertMap(mapa, strdup(new->nombre), new);
}
if(searchMap(mapaTipo, new->tipo)==NULL){
HashMap * mapaAux = createMap(20);
insertMap(mapaAux, strdup(new->nombre), new);
insertMap(mapaTipo, new->tipo, mapaAux);
}else{
HashMap * mapa = searchMap(mapaTipo, new->tipo);
insertMap(mapa, strdup(new->nombre), new);
}
printf("Producto agregado correctamente\n");
}
if(buscado != NULL){
buscado->stock = (buscado->stock) + (new->stock);
printf("Stock aumentado correctamente\n");
}
}
void buscarNombre(HashMap * mapaNombre){
char buscado[60];
printf("Ingrese el nombre del producto\n");
gets(buscado);
minuscula(buscado);
Producto * produc = searchMap(mapaNombre, buscado);
if(produc == NULL) printf("No se encuentra el producto\n");
else printf("%s %s %s %i %i\n", produc->nombre, produc->marca, produc->tipo, produc->stock, produc->precio);
}
void buscarTipo(HashMap * mapaTipo){
char buscado[20];
printf("Ingrese el tipo del producto\n");
gets(buscado);
minuscula(buscado);
HashMap * map = searchMap(mapaTipo, buscado);
if(map == NULL) printf("No se encuentra el tipo\n");
else{
Producto * produc = firstMap(map);
while(produc != NULL){
printf("%s %s %s %i %i\n", produc->nombre, produc->marca, produc->tipo, produc->stock, produc->precio);
produc = nextMap(map);
}
}
}
void buscarMarca(HashMap * mapaMarca){
char buscado[25];
printf("Ingrese la marca del producto\n");
gets(buscado);
minuscula(buscado);
HashMap * map = searchMap(mapaMarca, buscado);
if(map == NULL) printf("No se encuentra la marca\n");
else{
Producto * produc = firstMap(map);
while(produc != NULL){
printf("%s %s %s %i %i\n", produc->nombre, produc->marca, produc->tipo, produc->stock, produc->precio);
produc = nextMap(map);
}
}
}
void mostrarProductos(HashMap * mapaNombre){
Producto * produc = firstMap(mapaNombre);
while(produc != NULL){
printf("%s %s %s %i %i\n", produc->nombre, produc->marca, produc->tipo, produc->stock, produc->precio);
produc = nextMap(mapaNombre);
}
}
void agregarCarro(HashMap * mapaNombre, List * listaGral){
char buscado[60];
char carrito[30];
int cant;
printf("Ingrese el nombre del producto\n");
gets(buscado);
minuscula(buscado);
Producto * prod = searchMap(mapaNombre,buscado);
printf("Ingrese cuantos va a comprar \n");
scanf("%i", &cant);
printf("Ingrese el nombre del carrito\n");
gets(carrito);
minuscula(carrito);
if(first(listaGral) != NULL){
Carro * nuevo = (Carro *)malloc(sizeof(Carro));
strcpy(nuevo->nombre, carrito);
pushFront(nuevo->lista,prod->nombre);
printf("Carrito %s creado con exito\n", carrito);
}else{
Carro * primero = first(listaGral);
int flag = 0;
while(primero != NULL){
if(strcmp(carrito,primero->nombre) == 0){
pushBack(primero->lista, prod->nombre);
flag = 1;
printf("Producto agregado\n");
}
primero = next(listaGral);
}
if(flag == 0){
Carro * nuevo = (Carro *)malloc(sizeof(Carro));
strcpy(nuevo->nombre, carrito);
pushFront(nuevo->lista,prod->nombre);
printf("Producto agregado correctamente\n");
}
}
}
void pagarCarro(HashMap * mapaNombre, List * listaGral){
printf("Ingrese el nombre del carrito que quiera pagar\n");
char carrito[30];
gets(carrito);
minuscula(carrito);
Carro * primero = first(listaGral);
int flag = 0;
while(primero != NULL){
int suma;
if(strcmp(primero->nombre, carrito) == 0){
flag = 1;
char nombre[60];
strcpy(nombre, first(primero->lista));
while(nombre != NULL){
Producto * buscado = searchMap(mapaNombre, nombre);
suma = suma + buscado->precio;
printf("%s %i\n", buscado->nombre, buscado->precio);
strcpy(nombre, next(primero->lista));
}
printf("El precio a pagar es %d\n", suma);
popCurrent(listaGral);
}
primero = next(listaGral);
}
if(flag == 0)printf("El carrito no existe\n");
}
|
C
|
#include "header.h"
/**
* malloc_error - prints error message and exits when malloc fails
* @name: the name of our compiled program
*/
void malloc_error(char **name)
{
/* Error message from malloc man page, exit status from ENOMEM */
char *string = "ENOMEM Out of memory.";
free((*name));
write(STDERR, string, _strlen(string));
exit(12);
}
/**
* malloc_error2 - prints error message and exits when malloc fails
*/
void malloc_error2(void)
{
/*Error message from malloc man page, exit status from ENOMEM */
char *string = "ENOMEM Out of memory.";
write(STDERR, string, _strlen(string));
}
/**
* getline_error - prints error message and exits when getline fails
* @name: name of currently running shell program
*/
void getline_error(char **name)
{
/*Error message from getline man page, exit status from EINVAL */
free(name);
perror("EINVAL Bad arguments\n");
exit(22);
}
/**
* write_error - a fucntion to wrtie and error if write fails.
*/
void write_error(void)
{
/* Error message from any function with a write() for if the write fails */
perror("ERROR: write failed.\n");
exit(450);
}
|
C
|
#include<stdio.h>
void main()
{
float num1, num2;
char op,n;
float result;
printf("Enter the statement\n");
scanf("%f%c%f",&num1,&op,&num2);
switch (op)
{
case '-':
result = num1 - num2;
printf("Result=%f", result);
break;
case'+':
result = num1 + num2;
printf("Result=%f", result);
break;
case'*':
result = num1 * num2;
printf("Result=%f", result);
break;
case'/':
result = num1 / num2;
printf("Result=%f", result);
break;
default:
printf("The operator is not valid");
}
printf("\nDo you want to continue write 'y' if yes: ");
scanf(" %c", &n);
if (n == 'y')
main();
else
printf("-----------------------------------------");
}
|
C
|
struct Student {
int age;
char name[30];
char schoolYear[20]; // Either "Freshman", "Sophomore", "Junior", "Senior", or "Graduate"
int creditHours;
};
void swap (int *a, int *b);
int maximumElement(int *arr, int size);
void reverseString(char *str);
int evenOddDiff(int *arr, int size);
int seniorStudents(struct Student *students, int size);
int strComp(char *str1, char *str2);
char hasPlayerWon (char board[3][3]);
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "moto.h"
#include "type.h"
#include "color.h"
#include "service.h"
#include "work.h"
#include "informs.h"
#include "menu.h"
#include "extras.h"
#include "validations.h"
void inform(eMoto motorcycles[], int sizeMotorcycles, eType types[], int sizeTypes, eColor colors[], int sizeColors, eService services[], int sizeServices, eWork works[], int sizeWorks)
{
char cont = 's';
system("cls");
printf("\n *** INFORMES ***************************************************************************");
do
{
switch(menu_inform())
{
case 1:
inform_motoXcolor(motorcycles, sizeMotorcycles, types, sizeTypes, colors, sizeColors);
break;
case 2:
inform_motoXtype(motorcycles, sizeMotorcycles, types, sizeTypes, colors, sizeColors);
break;
case 3:
inform_motoWithHigherCilindrada(motorcycles, sizeMotorcycles, types, sizeTypes, colors, sizeColors);
break;
case 4:
inform_motoXAllTypes(motorcycles, sizeMotorcycles, types, sizeTypes, colors, sizeColors);
break;
case 5:
inform_motoCountByColorAndType(motorcycles, sizeMotorcycles, types, sizeTypes, colors, sizeColors);
break;
case 6:
inform_motoAndWorks(motorcycles, sizeMotorcycles, types, sizeTypes, colors, sizeColors, works, sizeWorks, services, sizeServices);
break;
case 7:
inform_sumOfAmountsOfWorks(motorcycles, sizeMotorcycles, types, sizeTypes, colors, sizeColors, works, sizeWorks, services, sizeServices);
break;
case 8:
inform_serviceAndMotos(motorcycles, sizeMotorcycles, types, sizeTypes, colors, sizeColors, works, sizeWorks, services, sizeServices);
break;
case 9:
inform_serviceXdate(motorcycles, sizeMotorcycles, types, sizeTypes, colors, sizeColors, works, sizeWorks, services, sizeServices);
break;
case 10:
cont = 'n';
break;
}
}
while(cont == 'y');
}
void inform_motoXcolor(eMoto motorcycles[], int sizeMotorcycles, eType types[], int sizeTypes, eColor colors[], int sizeColors)
{
int flag = 0;
int idColor;
system("cls");
printf("\n *** MOTOS POR COLOR *****************************************************************************\n\n");
color_show(colors, sizeColors);
validations_getUnsignedInt(&idColor,"\n\tIngrese ID del color: ", "\n\t(!) Error. Ingrese un valor numerico entero.\n",1,100000,10000,100000,4);
for(int i=0; i<sizeMotorcycles; i++)
{
if(motorcycles[i].state == 1 && motorcycles[i].idColor == idColor)
{
printf("\n\t\t _____________________________________________________________________________\n");
printf("\n\t\t ID MARCA TIPO COLOR CILINDRADA ");
printf("\n\t\t _____________________________________________________________________________\n");
moto_showOne(motorcycles[i], types, sizeTypes, colors, sizeColors);
flag = 1;
}
}
if(flag == 0)
{
printf("\n\t\t>>> No hay motos de ese color <<<\n");
}
}
void inform_motoXtype(eMoto motorcycles[], int sizeMotorcycles, eType types[], int sizeTypes, eColor colors[], int sizeColors)
{
int flag = 0;
int idType;
system("cls");
printf("\n *** MOTOS POR TIPO *****************************************************************************\n\n");
type_show(types, sizeTypes);
validations_getUnsignedInt(&idType,"\n\tIngrese ID del tipo: ", "\n\t(!) Error. Ingrese un valor numerico entero a partir de 1000\n",1,10000,1000,10000,4);
for(int i=0; i<sizeMotorcycles; i++)
{
if(motorcycles[i].state == 1 && motorcycles[i].idType == idType)
{
printf("\n\t\t _____________________________________________________________________________\n");
printf("\n\t\t ID MARCA TIPO COLOR CILINDRADA ");
printf("\n\t\t _____________________________________________________________________________\n");
moto_showOne(motorcycles[i], types, sizeTypes, colors, sizeColors);
flag = 1;
}
}
if(flag == 0)
{
printf("\n\t\t>>> No hay motos de ese tipo <<<\n");
}
}
void inform_motoWithHigherCilindrada(eMoto motorcycles[], int sizeMotorcycles, eType types[], int sizeTypes, eColor colors[], int sizeColors)
{
int higherCilindrada = 0;
system("cls");
printf("\n *** MAYOR CILINDRADA *********************************************\n\n");
for(int i=0; i<sizeMotorcycles; i++)
{
if(motorcycles[i].state == 1)
{
if(motorcycles[i].cilindrada > higherCilindrada)
{
higherCilindrada = motorcycles[i].cilindrada;
}
}
}
printf("\nLa mayor cilindrada es %d y la/s motos son: ", higherCilindrada);
printf("\n\t\t _____________________________________________________________________________\n");
printf("\n\t\t ID MARCA TIPO COLOR CILINDRADA ");
printf("\n\t\t _____________________________________________________________________________\n");
for(int i=0; i<sizeMotorcycles; i++)
{
if(motorcycles[i].cilindrada == higherCilindrada)
{
moto_showOne(motorcycles[i], types, sizeTypes, colors, sizeColors);
}
}
}
void inform_motoXAllTypes(eMoto motorcycles[], int sizeMotorcycles, eType types[], int sizeTypes, eColor colors[], int sizeColors)
{
system("cls");
printf("\n *** MOTOS DE TODOS LOS TIPOS *********************************************\n\n");
for(int i=0; i<sizeTypes; i++)
{
printf("\n\n\n\n\nTipo: %s", types[i].description);
for(int j=0; j<sizeMotorcycles; j++)
{
if(motorcycles[j].state == 1 && motorcycles[j].idType == types[i].id)
{
printf("\n\t\t _____________________________________________________________________________\n");
printf("\n\t\t ID MARCA TIPO COLOR CILINDRADA ");
printf("\n\t\t _____________________________________________________________________________\n");
moto_showOne(motorcycles[j], types, sizeTypes, colors, sizeColors);
}
}
}
}
void inform_motoCountByColorAndType(eMoto motorcycles[], int sizeMotorcycles, eType types[], int sizeTypes, eColor colors[], int sizeColors)
{
int flag = 0;
int idColor;
int idType;
int indexColor;
int indexType;
int counter = 0;
system("cls");
printf("\n *** CONTADOR DE MOTOS POR COLOR Y TIPO *****************************************************************************\n\n");
color_show(colors, sizeColors);
validations_getUnsignedInt(&idColor,"\n\tIngrese ID del color: ", "\n\t(!) Error. Ingrese un valor numerico entero.\n",1,100000,10000,100000,4);
type_show(types, sizeTypes);
validations_getUnsignedInt(&idType,"\n\tIngrese ID del tipo: ", "\n\t(!) Error. Ingrese un valor numerico entero.\n",1,10000,1000,10000,4);
indexColor = color_findOne(idColor, colors, sizeColors);
indexType = type_findOne(idType, types, sizeTypes);
for(int i=0; i<sizeMotorcycles; i++)
{
if(motorcycles[i].state == 1 && motorcycles[i].idColor == idColor && motorcycles[i].idType == idType)
{
counter++;
flag = 1;
}
}
if(flag == 0)
{
printf("\n\n\t\t>>> No hay motos de ese color y tipo <<<\n");
}
else
{
printf("\n\n\t\t>>> Hay %d motos del color %s y del tipo %s <<<\n", counter, colors[indexColor].colorName, types[indexType].description);
system("pause");
}
}
void inform_motoAndWorks(eMoto motorcycles[], int sizeMotorcycles, eType types[], int sizeTypes, eColor colors[], int sizeColors, eWork works[], int sizeWorks, eService services[], int sizeService)
{
int flag = 0;
int idMoto;
system("cls");
printf("\n *** TODOS LOS TRABAJOS DE UNA MOTO *****************************************************************************\n\n");
moto_show(motorcycles, sizeMotorcycles, types, sizeTypes, colors, sizeColors);
validations_getUnsignedInt(&idMoto,"\n\tIngrese ID de la moto: ", "\n\t(!) Error. Ingrese un valor numerico entero a partir de 1000\n",1,10000,1000,10000,4);
for(int i=0; i<sizeWorks; i++)
{
if(works[i].state == 1 && works[i].idMoto == idMoto)
{
printf("\n\t\t ________________________________________________________________________\n");
printf("\n\t\t ID MARCA SERVICIO FECHA ");
printf("\n\t\t ________________________________________________________________________\n");
work_showOne(works[i],motorcycles,sizeMotorcycles,services,sizeService);
flag = 1;
}
}
if(flag == 0)
{
printf("\n\t\t>>> No hay trabajos realizados en esta moto <<<\n");
}
}
void inform_sumOfAmountsOfWorks(eMoto motorcycles[], int sizeMotorcycles, eType types[], int sizeTypes, eColor colors[], int sizeColors, eWork works[], int sizeWorks, eService services[], int sizeServices)
{
int flag = 0;
int idMoto;
float sum;
system("cls");
printf("\n *** SUMA DE IMPORTES DE LOS SERVICIOS *****************************************************************************\n\n");
moto_show(motorcycles, sizeMotorcycles, types, sizeTypes, colors, sizeColors);
validations_getUnsignedInt(&idMoto,"\n\tIngrese ID de la moto: ", "\n\t(!) Error. Ingrese un valor numerico entero a partir de 1000\n",1,10000,1000,10000,4);
for(int i=0; i<sizeWorks; i++)
{
if(works[i].state == 1 && works[i].idMoto == idMoto)
{
sum += services[works[i].idService-20000].price;
flag = 1;
}
}
printf("\n\t\tLa suma de los importes de la moto seleccionada es: %.2f", sum);
if(flag == 0)
{
printf("\n\t\t>>> No hay servicios realizados en esta moto <<<\n");
}
}
void inform_serviceAndMotos(eMoto motorcycles[], int sizeMotorcycles, eType types[], int sizeTypes, eColor colors[], int sizeColors,eWork works[], int sizeWorks, eService services[], int sizeServices)
{
int flag = 0;
int idService;
system("cls");
printf("\n *** MOTOS CON SERVICIOS REALIZADOS *****************************************************************************\n\n");
service_show(services,sizeServices);
validations_getUnsignedInt(&idService,"\n\tIngrese ID del servicio: ", "\n\t(!) Error. Ingrese un valor numerico entero a partir de 20000\n",1,30000,20000,30000,4);
for(int i=0; i<sizeWorks; i++)
{
if(works[i].state == 1 && works[i].idService == idService)
{
work_showOne(works[i],motorcycles,sizeMotorcycles,services,sizeServices);
flag = 1;
}
}
if(flag == 0)
{
printf("\n\t\t>>> No hay motos a las que se les haya realizado ese servicio <<<\n");
}
}
void inform_serviceXdate(eMoto motorcycles[], int sizeMotorcycles, eType types[], int sizeTypes, eColor colors[], int sizeColors, eWork works[], int sizeWorks, eService services[], int sizeServices)
{
int flag = 0;
eWork auxWork;
system("cls");
printf("\n *** SERVICIOS POR FECHA *****************************************************************************\n\n");
validations_getUnsignedInt(&auxWork.date.day,"\n\tIngrese dia: ", "\n\t(!) Error. Ingrese un valor numerico entero. Dia inexistente.\n",1,31,1,31,4);
validations_getUnsignedInt(&auxWork.date.month,"\n\tIngrese mes: ", "\n\t(!) Error. Ingrese un valor numerico entero. Mes inexistente.\n",1,12,1,12,4);
validations_getUnsignedInt(&auxWork.date.year,"\n\tIngrese anio: ", "\n\t(!) Error. Ingrese un valor numerico entero. El anio debe ser entre 1990 y 2020.\n",1,2020,1,2020,4);
while(validations_getDate(auxWork.date.day, auxWork.date.month, auxWork.date.year, 1990, 2020)==0)
{
printf("\n\t(!) Error. Fecha no valida. \n");
validations_getUnsignedInt(&auxWork.date.day,"\n\n\tIngrese dia: ", "\n\t(!) Error. Ingrese un valor numerico entero.\n",1,31,1,31,4);
validations_getUnsignedInt(&auxWork.date.month,"\n\tIngrese mes: ", "\n\t(!) Error. Ingrese un valor numerico entero.\n",1,12,1,12,4);
validations_getUnsignedInt(&auxWork.date.year,"\n\tIngrese anio: ", "\n\t(!) Error. Ingrese un valor numerico entero entre 1990 y 2020.\n",1,2020,1,2020,4);
}
for(int i=0; i<sizeWorks; i++)
{
if(works[i].state == 1 && (works[i].date.day == auxWork.date.day) && (works[i].date.month == auxWork.date.month) && (works[i].date.year == auxWork.date.year))
{
work_showOne(works[i], motorcycles, sizeMotorcycles, services, sizeServices);
flag = 1;
}
}
if(flag == 0)
{
printf("\n\t\t>>> No se realizaron servicios en esa fecha <<<\n");
}
}
|
C
|
#ifndef TRUE
#define TRUE 1
#define FALSE 0
#endif
#define X 400
#define Y 400
#define BG GetNamedColor("black")
#define WORK GetNamedColor("white")
#define S GetNamedColor("cyan")
#define C GetNamedColor("green")
#define POLY GetNamedColor("red")
#include <stdbool.h>
enum SIDE{UNCLEAR,IN,OUT,ON};
typedef struct _node
{
int x, y;
struct _node *next;
struct _node *prev;
struct _node *nextPoly; /* pointer to the next polygon */
struct _node *neighbor; /* the coresponding intersection point */
int intersect; /* 1 if an intersection point, 0 otherwise */
int entry; /* 1 if an entry point, 0 otherwise */
int visited; /* 1 if the node has been visited, 0 otherwise */
float alpha; /* intersection point placemet */
SIDE side;
_node()
{
entry = 1;
side = UNCLEAR;
}
} node;
|
C
|
#include <stdio.h>
#include <sqlite3.h>
int main(int argc, char **argv) {
sqlite3 *conn;
sqlite3_stmt *res;
int err = 0, cnt = 0;
const char *err_msg;
const char *tail;
err = sqlite3_open("ship.sqlite3", &conn);
if (err) {
printf("Can not open database\n");
return 1;
}
err = sqlite3_exec(conn,
"update ship set name=\'NCC-1701-D\' where id=3",
0, 0, 0);
err = sqlite3_prepare_v2(conn,
"select id,name from ship order by id",
1000, &res, &tail);
if (err != SQLITE_OK) {
printf("Select failed");
return 1;
}
while (sqlite3_step(res) == SQLITE_ROW) {
printf("%u ", sqlite3_column_int(res, 0));
printf("%s\n", sqlite3_column_text(res, 1));
cnt++;
}
sqlite3_finalize(res);
sqlite3_close(conn);
return 0;
}
|
C
|
/*
* timer0System.c
*
* Created: 2016-03-03 7:26:30 PM
* Author: take-iwiw
* Note: Timer0 is fixed for system timer (1 msec)
*/
#include <avr/io.h>
#include <avr/interrupt.h>
#include "../myCommon.h"
#include "timer0System.h"
/*** Internal Const Values ***/
/*** Internal Static Variables ***/
// over flow happens every 65.536 sec
static volatile uint16_t s_cntTimer0_1ms = 0;
static void (*s_callback)();
/*** Internal Function Declarations ***/
/*** External Function Defines ***/
void timer0SystemInit()
{
// CTC Mode without compare output
TCCR0A = (0<<COM0A0) | (0<<COM0B0) | (2<<WGM00);
// Div = 1/64
TCCR0B = 0x03;
// Compare match every 1 msec (1/ (64/16M) / 1000)
OCR0A = F_CPU / 64 / 1000;
// Enable Compare Match A Interrupt
TIMSK0 = (1<<OCIE0A);
}
RET timer0SetCallback(void (*func)())
{
if(s_callback == 0){
s_callback = func;
return RET_OK;
}
return RET_ERR_REGISTER;
}
RET timer0ClearCallback(void (*func)())
{
if(s_callback == func){
s_callback = 0;
return RET_OK;
}
return RET_ERR_REGISTER;
}
// over flow happens every 65.536 sec
uint8_t timer0SystemGetTimeMS()
{
return s_cntTimer0_1ms;
}
/*** Internal Function Definitions ***/
ISR(TIMER0_COMPA_vect)
{
s_cntTimer0_1ms++;
if(s_callback != 0) s_callback();
return;
}
|
C
|
#include <std.h>
inherit ROOM;
void create()
{
::create();
set_property("indoors",1);
set_travel(PAVED_ROAD);
set_terrain(STONE_BUILDING);
set_property("no teleport",1);
set_property("light",3);
set_short("%^BOLD%^Paladin's Hall%^RESET%^");
set_long(
"You are standing within the paladin guild hall in the Antioch palace."+
" A %^BOLD%^%^BLUE%^royal blue%^RESET%^ rug stretches down the hallway."+
" Oil lamps gilded with %^BOLD%^white gold%^RESET%^ line the walls,"+
" shedding light on the area. There are a few statues on pedestals placed"+
" at intervals along the length of the hallway here. To the west is the"+
" rest of the palace, and to the north the guild hall continues."
);
set_smell("default","The faint scent of vanilla is in the air.");
set_listen("default","A respectful silence cloaks the room.");
set_items(([
"floor" : "The floor is covered in a fine rug that is %^BOLD%^%^BLUE%^"+
" royal blue%^RESET%^ trimmed with %^BOLD%^white%^RESET%^.",
({"rug","blue rug","royal blue rug"}) : "%^BOLD%^%^BLUE%^The rug is a"+
" rich royal blue with %^WHITE%^white%^BLUE%^ edges, it stretches down"+
" the entire hallway.%^RESET%^",
({"oil lamps","lamps"}) : "%^BOLD%^%^WHITE%^The oil lamps are gilded"+
" in white gold, they give off a steady light and a faint scent of vanilla.%^RESET%^",
({"wall","walls"}) : "Oil lamps and pedestals line the walls here.",
"pedestals" : "%^BOLD%^Pedestals made of white marble are set up at"+
" equal intervals along the hallways here, they have statues on top"+
" of them.%^RESET%^",
"statues" : "%^BOLD%^Porcelain statues stand atop pedestals along the"+
" walls here. There appear to be a total of nine of them.",
({"statue 1","helm statue","statue"}) : "%^BOLD%^The first statue is the symbol of Helm,"+
" Guardian of Antioch. It is an open eye with a %^BLUE%^blue pupil%^WHITE%^"+
" painted on the palm of a left-hand war gauntlet.",
({"statue 2","tyr statue"}) : "%^BOLD%^There is a statue of a balanced set"+
" of scales standing upon the head of an upright war hammer.",
({"statue 3","torm statue"}) : "%^BOLD%^There is a righ-handed gauntlet"+
" standing up right with the palm open, holding a %^RESET%^gray metal"+
" shield%^BOLD%^ with three %^BLACK%^black arrows%^WHITE%^ embedded in the"+
" shield.",
({"statue 4","tempus statue"}) : "%^BOLD%^There is a porcelain sword that"+
" is blazing with a silver light and has a %^RED%^red%^WHITE%^ aura"+
" surrounding it.",
({"statue 5","kelemvor statue"}) : "%^BOLD%^A skeletal arm holds"+
" %^YELLOW%^golden scales%^WHITE%^ of justice that are evenly balanced.",
({"statue 6","eldath statue"}) : "%^BOLD%^A disk surrounded by a"+
" %^CYAN%^sky blue%^WHITE%^ aura is fringed with"+
" %^RESET%^%^GREEN%^green%^WHITE%^%^BOLD%^ ferns.",
({"statue 7","mielikki statue"}) : "%^BOLD%^There is a white unicorn"+
" rearing on a field with a %^GREEN%^green%^WHITE%^ aura.",
({"statue 8","lathander statue"}) : "%^BOLD%^Along the end of the hallway"+
" there is a porcelain disk that is glowing a %^MAGENTA%^rosy"+
" pink%^WHITE%^ shade.",
({"statue 9","mystra statue"}) : "%^BOLD%^There are two"+
" %^RESET%^%^BLUE%^dark%^BOLD%^%^WHITE%^ female eyes carved into the"+
" center of one of the far statues, surrounded by seven white stars.",
({"statue 9","grumbar statue"}) : "%^BOLD%^The very last statue is a set"+
" of mountains that are glowing a soft %^GREEN%^green%^WHITE%^ and have an"+
" aura of %^RESET%^%^MAGENTA%^purple%^BOLD%^%^WHITE%^ surrounding them.",
]));
set_exits(([
"west" : "/d/antioch/cguilds/paladin/hall1",
"north" : "/d/antioch/cguilds/paladin/hall3",
]));
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
void main()
{
int codigo;
int VT = 65;
char turno;
float salario, desconto, descontado;
float INSS = 0.15;
printf("Codigo: ");
scanf("%d", &codigo);
printf("Turno (m/t): ");
fflush(stdin);
scanf("%c", &turno);
printf("Salario: R$");
scanf("%f", &salario);
desconto = ((INSS * salario) + VT);
printf("Desconto: R$%f\n", desconto);
descontado = (salario - desconto);
printf("Valor a receber: R$%f", descontado);
}
|
C
|
#include <stdio.h>
int main()
{
int n, soma=0, aux=1;
printf("\n Informe um numero \n");
scanf("%d", & n);
while (aux<n)
{
if (n % aux == 0)
{
soma = soma+aux;
}
aux=aux+1;
}
if (soma == n)
{
printf("\n O numero %d e um numero perfeito \n", n);
}
else
{
printf("\n O numero %d nao e um numero perfeito \n", n);
}
return 0;
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_strsplit.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: cquillet <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2016/11/06 16:25:01 by cquillet #+# #+# */
/* Updated: 2017/10/30 17:35:11 by cquillet ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
static size_t get_nb_words(char const *s, char c, size_t *start)
{
size_t nb_words;
size_t i;
if (s == NULL)
return (0);
nb_words = 0;
i = 0;
while (s[i] && s[i] == c)
i++;
*start = i;
while (s[i])
{
while (s[i] && s[i] != c)
i++;
nb_words++;
while (s[i] && s[i] == c)
i++;
}
return (nb_words);
}
char **ft_strsplit(char const *s, char c)
{
char **split;
size_t nb_words;
size_t len_word;
size_t i;
nb_words = get_nb_words(s, c, &i);
if (!(split = (char **)malloc((nb_words + 1) * sizeof(char *))))
return (NULL);
split[nb_words] = 0;
if (nb_words == 0)
return (split);
nb_words = 0;
while (s[i])
{
len_word = 0;
while (s[i + len_word] && s[i + len_word] != c)
len_word++;
split[nb_words] = ft_strsub(s, i, len_word);
nb_words++;
i += len_word;
while (s[i] && s[i] == c)
i++;
}
return (split);
}
|
C
|
#include <setjmp.h>
#include <avr/io.h>
#include <avr/interrupt.h>
#include <avr/signal.h>
#include "tinythreads.h"
#define NULL 0
#define DISABLE() cli()
#define ENABLE() sei()
#define STACKSIZE 80
#define NTHREADS 4
#define SETSTACK(buf,a) *((unsigned int *)(buf)+8) = (unsigned int)(a) + STACKSIZE - 4; \
*((unsigned int *)(buf)+9) = (unsigned int)(a) + STACKSIZE - 4
struct thread_block {
void (*function)(int); // code to run
int arg; // argument to the above
thread next; // for use in linked lists
jmp_buf context; // machine state
char stack[STACKSIZE]; // execution stack space
};
struct thread_block threads[NTHREADS];
struct thread_block initp;
thread freeQ = threads;
thread readyQ = NULL;
thread current = &initp;
int initialized = 0;
static void initialize(void) {
int i;
PORTB = 0x80;
EIMSK = 0x80;
PCMSK1 = 0x80;
TCNT1 = 0;
TCCR1B = 0x04;
OCR1A = 0x3D09; ;//change the time slicing
/*TCCR1B = 0x1D;
ICR1 = 0x0186;*/
// initialize of timer
TIMSK2 = 0x00;
ASSR = 0x08;
TCNT2 = 0x00;
OCR2A = 50;
TCCR2A = 0x0B;
while(0x07 & ASSR);
TIFR2 = 0x00;
TIMSK2 = 0x02;
LCDCRA = 0x80;
LCDCRB = 0xB7;
for (i=0; i<NTHREADS-1; i++)
threads[i].next = &threads[i+1];
threads[NTHREADS-1].next = NULL;
initialized = 1;
}
static void enqueue(thread p, thread *queue) {
p->next = NULL;
if (*queue == NULL) {
*queue = p;
} else {
thread q = *queue;
while (q->next)
q = q->next;
q->next = p;
}
}
static thread dequeue(thread *queue) {
thread p = *queue;
if (*queue) {
*queue = (*queue)->next;
} else {
// Empty queue, kernel panic!!!
while (1) ; // not much else to do...
}
return p;
}
static void dispatch(thread next) {
if (setjmp(current->context) == 0) {
current = next;
longjmp(next->context,1);
}
}
void spawn(void (* function)(int), int arg) {
thread newp;
DISABLE();
if (!initialized) initialize();
newp = dequeue(&freeQ);
newp->function = function;
newp->arg = arg;
newp->next = NULL;
if (setjmp(newp->context) == 1) {
ENABLE();
current->function(current->arg);
DISABLE();
enqueue(current, &freeQ);
dispatch(dequeue(&readyQ));
}
SETSTACK(&newp->context, &newp->stack);
enqueue(newp, &readyQ);
ENABLE();
}
ISR(SIG_PIN_CHANGE1){
if ((PINB&PORTB)!=PORTB)
{
yield();
}
}
ISR(SIG_OUTPUT_COMPARE2){
yield();
}
void yield(void) {
enqueue(current, &readyQ);
dispatch(dequeue(&readyQ));
}
void lock(mutex *m)
{
}
void unlock(mutex *m)
{
}
|
C
|
/*
-----------------------------------------
How many bottles of water you use while taking a shower
-----------------------------------------
Write a program which askes user for the duration of their shower
and then spits out the number of bottles of water used.
Assume that 1 minute of shower = 12 bottles of water.
*/
#include <cs50.h>
#include <stdio.h>
int getBottles(time)
{
return time * 12;
}
int main(void)
{
printf("minutes: ");
int time = GetInt();
// printf("bottles: %i\n", time * 12); // Calculate direclty in the printf
printf("bottles: %i\n", getBottles(time)); // or call a function that return the result
}
|
C
|
#include "types.h"
#include "stat.h"
#include "user.h"
char store[512];
void tail(int linesToPrint, int filedes, char* fname) {
int numberOfLines;
int lineStop;
int i = 0;
int n = 0;
int skipCheck = 0;
numberOfLines = 0;
lineStop = 0;
while((n = read(filedes, store, sizeof(store))) > 0) {
for(i = 0; i < n; i++) {
if(store[i] == '\n') {
numberOfLines++;
}
}
}
if(n < 0){
printf(1, "error reading file\n");
exit();
}
close(filedes);
int beginRead = numberOfLines - linesToPrint;
if((filedes = open(fname, 0)) < 0){
printf(1, "error cannot open file\n");
exit();
}
while((n = read(filedes, store, sizeof(store))) > 0) {
for(i = 0; i < n; i++) {
if(lineStop >= beginRead) {
if(store[i] == '\n' && skipCheck == 0) {
skipCheck = 1;
printf(1,"%c",store[i]);
}
else if(store[i] != '\n' && skipCheck == 1) {
skipCheck = 0;
printf(1,"%c",store[i]);
}
else if(store[i] != '\n' && skipCheck == 0) {
printf(1,"%c",store[i]);
}
}
else {
if(store[i] == '\n') {
lineStop++;
}
}
}
}
}
int main(int argc, char* argv[]) {
int filedes, i, linesToPrint;
char* num;
if(argc <= 2 || argc%2 == 0) {
filedes = open(argv[1],0);
tail(10,filedes,argv[1]);
exit();
}
for(i = 1; i < argc; i+=2){
if((filedes = open(argv[i+1], 0)) < 0){
printf(1, "error unable to open file\n");
exit();
}
num = argv[i];
if(num[0] != '-') {
linesToPrint = 10;
}
else {
num++;
linesToPrint = atoi(num);
}
tail(linesToPrint, filedes, argv[i+1]);
close(filedes);
}
exit();
}
|
C
|
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <errno.h>
#include "shell.h"
#include "node.h"
#include "parser.h"
// create new node and set type field
struct node_s *new_node(enum node_type_e type)
{
struct node_s *node = malloc(sizeof(struct node_s));
if(!node)
{
return NULL;
}
memset(node, 0, sizeof(struct node_s));
node->type = type;
return node;
}
// add child node and modify number of children field
void add_child_node(struct node_s *parent, struct node_s *child)
{
if(!parent || !child)
{
return;
}
// if first child already exists, add to end of child list (doubly linked list)
if(!parent->first_child)
{
parent->first_child = child;
}
else
{
struct node_s *sibling = parent->first_child;
while(sibling->next_sibling)
{
sibling = sibling->next_sibling;
}
sibling->next_sibling = child;
child->prev_sibling = sibling;
}
parent->children++;
}
// set node value to given string
void set_node_val_str(struct node_s *node, char *val)
{
node->val_type = VAL_STR;
if(!val)
{
node->val.str = NULL;
}
else
{
char *val2 = malloc(strlen(val)+1);
if(!val2)
{
node->val.str = NULL;
}
else
{
strcpy(val2, val);
node->val.str = val2;
}
}
}
// free memory used by structure. call recursively on children if present
void free_node_tree(struct node_s *node)
{
if(!node)
{
return;
}
struct node_s *child = node->first_child;
while(child)
{
struct node_s *next = child->next_sibling;
free_node_tree(child);
child = next;
}
if(node->val_type == VAL_STR)
{
if(node->val.str)
{
free(node->val.str);
}
}
free(node);
}
|
C
|
#include<stdio.h>
int add(int, int);
int sub(int, int);
long int mul(int, int);
float div(int, int);
int res1=-1;
long int res2 = -1;
float res3 = -1;
int main()
{
int a=20,b=10,q;
res1=add(a,b);
printf("sum=%d",res1);
res1=sub(a,b);
printf("difference=%d",res1);
res2=mul(a,b);
printf("product=%ld",res2);
res3=div(a,b);
printf("quotient=%f",res3);
printf("enter a number to exit\n");
scanf_s("%d",&q);
return 0;
}
int add(int a,int b)
{
extern int res1;
res1=a+b;
return res1;
}
int sub(int a,int b)
{
extern int res1;
res1=a-b;
return res1;
}
long int mul(int a,int b)
{
extern int res2;
res2=a*b;
return res2;
}
float div(int a,int b)
{
extern int res3;
res3=a/b;
return res3;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.