language
large_stringclasses 1
value | text
stringlengths 9
2.95M
|
|---|---|
C
|
/* yafft.c
*
* Yet another FFT - A lightweight C library for the Fast Fourier Transform.
*
*/
#include <math.h>
#include "yafft.h"
#define TWO_PI 6.2831853071795862
#define CADD(x, y) ((complex_float) {(x).real + (y).real, \
(x).imag + (y).imag})
#define CSUB(x, y) ((complex_float) {(x).real - (y).real, \
(x).imag - (y).imag})
#define CMUL(x, y) ((complex_float) {(x).real*(y).real - (x).imag*(y).imag, \
(x).real*(y).imag + (x).imag*(y).real})
/*
* Bit Twiddling Hacks
* https://graphics.stanford.edu/~seander/bithacks.html
*
*/
static unsigned int reverse_bits(
unsigned int v,
const unsigned int num_bits
) {
unsigned int r = v; // r will be reversed bits of v
int s = num_bits - 1; // extra shift needed at end
for (v >>= 1; v; v >>= 1) {
r <<= 1;
r |= v & 1;
s--;
}
r <<= s; // shift when v's highest bits are zero
r &= (1 << num_bits) - 1; // mask out non-significant bits
return r;
}
/*
* Generate twiddle factors
*/
static void generate_twiddle_factors(
complex_float* data,
const unsigned int size,
const unsigned int n,
const int sign
) {
double arg;
for (unsigned int k = 0; k < size; k++) {
arg = TWO_PI*k/n;
data[k].real = cos(arg);
data[k].imag = sign*sin(arg);
}
}
/*
* Swap two complex numbers
*/
static inline void swap_complex_numbers(
complex_float* a,
complex_float* b
) {
complex_float c = *a;
*a = *b;
*b = c;
}
/*
* Butterfly
*/
static void butterfly(
complex_float* x,
complex_float* y
) {
complex_float z = *x;
*x = CADD(z, *y);
*y = CSUB(z, *y);
}
/*
* Decimation-in-Time (DIT) Fast Fourier Transform (FFT)
*/
static void fft_radix2_dit(
complex_float* data,
const unsigned int size,
const unsigned int stages,
const complex_float* twiddle_factor
) {
unsigned int i, j;
// Bit reversal
for (i = 0; i < size; i++) {
j = reverse_bits(i, stages);
if (i < j) {
swap_complex_numbers(&data[i], &data[j]);
}
}
// FFT Stages
unsigned int sample_step_size;
unsigned int twiddle_step_size = size >> 1;
for (int m = 1; m <= stages; m++) {
sample_step_size = 1 << m;
unsigned int separator = sample_step_size >> 1;
// N-point FFTs
for (unsigned int offset = 0; offset < size; offset += sample_step_size) {
for (unsigned int k = 0; k < separator; k++) {
// Twiddle factor
complex_float W = twiddle_factor[k*twiddle_step_size];
// Indices
i = offset + k;
j = i + separator;
// Butterfly
data[j] = CMUL(data[j], W);
butterfly(&data[i], &data[j]);
}
}
twiddle_step_size >>= 1;
}
}
/*
* Decimation-in-Frequency (DIF) Fast Fourier Transform (FFT)
*/
static void fft_radix2_dif(
complex_float* data,
const unsigned int size,
const unsigned int stages,
const complex_float* twiddle_factor
) {
unsigned int i, j;
// FFT Stages
unsigned int sample_step_size;
unsigned int twiddle_step_size = 1;
for (int m = stages; m >= 0; m--) {
sample_step_size = 1 << m;
unsigned int separator = sample_step_size >> 1;
// N-point FFTs
for (unsigned int offset = 0; offset < size; offset += sample_step_size) {
for (unsigned int k = 0; k < separator; k++) {
// Twiddle factor
complex_float W = twiddle_factor[k*twiddle_step_size];
// Indices
i = offset + k;
j = i + separator;
// Butterfly
butterfly(&data[i], &data[j]);
data[j] = CMUL(data[j], W);
}
}
twiddle_step_size <<= 1;
}
// Bit reversal
for (i = 0; i < size; i++) {
j = reverse_bits(i, stages);
if (i < j) {
swap_complex_numbers(&data[i], &data[j]);
}
}
}
/**
* Fast Fourier Transform (FFT)
*/
void fft_radix2(
complex_float* data,
const unsigned int size,
const decimation_type decimation
) {
// Number of Stages
const unsigned int stages = log2(size);
// Twiddle factors
complex_float twiddle_factor[size >> 1];
generate_twiddle_factors(twiddle_factor, size >> 1, size, -1);
// FFT
switch (decimation) {
case DECIMATION_IN_TIME:
fft_radix2_dit(data, size, stages, twiddle_factor);
break;
case DECIMATION_IN_FREQUENCY:
fft_radix2_dif(data, size, stages, twiddle_factor);
break;
}
}
/**
* Inverse Fast Fourier Transform (FFT)
*/
void ifft_radix2(
complex_float* data,
const unsigned int size,
const decimation_type decimation
) {
// Number of Stages
const unsigned int stages = log2(size);
// Twiddle factors
complex_float twiddle_factor[size >> 1];
generate_twiddle_factors(twiddle_factor, size >> 1, size, +1);
// FFT
switch (decimation) {
case DECIMATION_IN_TIME:
fft_radix2_dit(data, size, stages, twiddle_factor);
break;
case DECIMATION_IN_FREQUENCY:
fft_radix2_dif(data, size, stages, twiddle_factor);
break;
}
// Scaling
for (unsigned int n = 0; n < size; n++) {
data[n].real /= size;
data[n].imag /= size;
}
}
|
C
|
#include <stdio.h>
int main(void) {
int n;
scanf("%d", &n);
char str[2][101];
scanf("%s%s", str[0], str[1]);
for (int i = 0; i < n; i++)
printf("%c%c", str[0][i], str[1][i]);
putchar('\n');
}
|
C
|
/*
Author: Mhirley Lopes
Purpose: Studying variables
Date: 19.06.2020
*/
#include <stdio.h>
int main()
{
int integerVar = 41;
long int verylongVar = 1232179827419L;
float floatVar = 12.5;
double doubleVar = 1.7e4;
long double longDoubleVar = 13.43e+11L;
bool boolVar = false;
bool anotherBoolean = true;
return 0;
}
|
C
|
#include "buffend.c"
void flush_in(){
int ch;
while( (ch = fgetc(stdin)) != EOF && ch != '\n' ){}
}
int criar_tabelas(){
char *nomeTabela=(char *)malloc(sizeof(char)*TAMANHO_NOME_TABELA);
char *nomeCampo=(char *)malloc(sizeof(char)*TAMANHO_NOME_CAMPO);
int inserir, erro;
char tipoCampo;
int pk;
table *tabela = (table *)malloc(sizeof(table)*1);
int fimCampos = 0, numTabelas, tamanhoCampo, i;
printf("Digite o numero de tabelas a serem inseridas!\n");
scanf("%i",&numTabelas);
for(i = 0; i < numTabelas; i++){
printf("Digite o nome da tabela!\n");
scanf("%s",nomeTabela);
printf("\n%s\n", nomeTabela);
tabela = iniciaTabela(nomeTabela);
if(tabela == ERRO_NOME_TABELA_INVALIDO){
printf("Erro: na função iniciaTabela(). Nome da tabela já existente.\n");
return 0;
}
while(fimCampos == 0){
printf("Digite o nome do campo!\n");
scanf("%s",nomeCampo);
flush_in();
fflush(stdin);
printf("Digite o Tipo do campo!(S-C-I-D)\n");
scanf("%c",&tipoCampo);
fflush(stdin);
if(tipoCampo == 'I')
tamanhoCampo = sizeof(int);
if(tipoCampo == 'C')
tamanhoCampo = sizeof(char);
if(tipoCampo =='D')
tamanhoCampo = sizeof(double);
if(tipoCampo == 'S'){
printf("Digite o Tamanho do campo!\n");
scanf("%d",&tamanhoCampo);
}
printf("O Campo eh Chave Primaria?(Sim 1 - 0 Nao)\n");
scanf("%d",&pk);
tabela = adicionaCampo(tabela, nomeCampo, tipoCampo, tamanhoCampo,pk);
printf("Deseja inserir um novo campo? (Sim 1 - 0 Nao)\n");
scanf("%d",&inserir);
if(inserir == 0){
fimCampos = 1;
erro = finalizaTabela(tabela);
if(erro != SUCCESS){
printf("Erro %d: na função finalizaTabela().\n", erro);
return 0;
}
}
}
}
return 1;
}
int visualizar_tabela(){
char *nomeTabela=(char *)malloc(sizeof(char)*TAMANHO_NOME_TABELA);
struct fs_objects objeto;
printf("Digite o nome da tabela!\n");
scanf("%s",nomeTabela);
objeto=leObjeto(nomeTabela);
leSchema(objeto);
printf("a tabela e:\n %s",objeto.nome);
printf("\n|--------------------------------------------------------------------|\n\n");
return 1;
}
int menu(){
int opcao;
printf("|--------------------------------------------------------------------|\n");
printf("| Menu |\n");
printf("|--------------------------------------------------------------------|\n");
printf(" Para criar tabelas digite 1 \n Para visualizar as tabelas criadas digite 2 \n Para sair digite 3\n");
scanf("%d",&opcao);
printf("|--------------------------------------------------------------------|\n");
return opcao;
}
int main ()
{
//~ tp_buffer *bp = (tp_buffer*)malloc(sizeof(tp_buffer)*PAGES);
//~ bp = initbuffer();
int opcao;
while(opcao!=3)
{
if(opcao==1)
{ //cria as tabelas
printf("|--------------------------------------------------------------------|\n");
printf("| Criar tabelas |\n");
printf("|--------------------------------------------------------------------|\n\n");
criar_tabelas();
}
if(opcao==2)
{ //mostra as tabelas criadas
printf("|--------------------------------------------------------------------|\n");
printf("| Visualizar tabelas |\n");
printf("|--------------------------------------------------------------------|\n\n");
visualizar_tabela();
}
opcao = menu();
}
return 1;
}
|
C
|
/**
* @file Buffer.c
* @brief
*/
/*****************************************************************************/
/* INCLUDES */
/*****************************************************************************/
#include "Buffer.h"
#include "Interface/Os.h"
#include <string.h>
/*****************************************************************************/
/* DEFINED CONSTANTS */
/*****************************************************************************/
/*****************************************************************************/
/* TYPE DEFINITIONS */
/*****************************************************************************/
/*****************************************************************************/
/* MACRO DEFINITIONS */
/*****************************************************************************/
/*****************************************************************************/
/* DEFINITION OF GLOBAL CONSTANTS AND VARIABLES */
/*****************************************************************************/
/*****************************************************************************/
/* DECLARATION OF LOCAL FUNCTIONS */
/*****************************************************************************/
/*****************************************************************************/
/* DEFINITION OF LOCAL FUNCTIONS */
/*****************************************************************************/
/*****************************************************************************/
/* DEFINITION OF GLOBAL FUNCTIONS */
/*****************************************************************************/
void GSM_BufferObjectInit(GSM_Buffer_t *this)
{
OS_LockBuffer();
memset(this, 0, sizeof(*this));
OS_UnlockBuffer();
}
bool GSM_BufferPushChar(GSM_Buffer_t *this, char c)
{
OS_LockBuffer();
if (this->rdindex == this->wrindex) {
this->rdindex = 0;
this->wrindex = 0;
memset(this->buffer, 0, sizeof(this->buffer));
}
bool result = false;
if (this->wrindex < SIM8XX_INPUT_BUFFER_LENGTH) {
this->buffer[this->wrindex] = c;
++this->wrindex;
result = true;
}
OS_StartGuardTimer();
OS_UnlockBuffer();
return result;
}
GSM_BufferData_t GSM_BufferGetData(GSM_Buffer_t *this)
{
GSM_BufferData_t data = {0};
OS_LockBuffer();
if (this->rdindex <= this->wrindex) {
data.data = &this->buffer[this->rdindex];
data.length = this->wrindex - this->rdindex;
}
OS_UnlockBuffer();
return data;
}
bool GSM_BufferPopData(GSM_Buffer_t *this, size_t length)
{
OS_LockBuffer();
bool result = false;
if ((this->rdindex + length) <= this->wrindex) {
this->rdindex += length;
result = true;
}
OS_UnlockBuffer();
return result;
}
size_t GSM_BufferGetLength(GSM_Buffer_t *this)
{
size_t n = 0;
OS_LockBuffer();
if (this->rdindex <= this->wrindex)
n = this->wrindex - this->rdindex;
OS_UnlockBuffer();
return n;
}
/****************************** END OF FILE **********************************/
|
C
|
int count=-1;
int getreg()
{
if(count<19)
{
count++;
return count;
}
else
printf("Out of Registers\n");
}
void freereg()
{
if(count!=-1)
count--;
else
printf("Freeing register error\n");
}
int codegen(struct tnode *t,FILE *fp)
{
int i,j;
if(t->op==NULL)
{
i=getreg();
fprintf(fp,"MOV R%d, %d\n",i,t->val);
return i;
}
switch(*(t->op))
{
case '+':
i=codegen(t->left,fp);
j=codegen(t->right,fp);
fprintf(fp,"ADD R%d, R%d\n",i,j);
freereg();
return i;
break;
case '*':
i=codegen(t->left,fp);
j=codegen(t->right,fp);
fprintf(fp,"MUL R%d, R%d\n",i,j);
freereg();
return i;
break;
case '-':
i=codegen(t->left,fp);
j=codegen(t->right,fp);
fprintf(fp,"SUB R%d, R%d\n",i,j);
freereg();
return i;
break;
case '/':
i=codegen(t->left,fp);
j=codegen(t->right,fp);
fprintf(fp,"DIV R%d, R%d\n",i,j);
freereg();
return i;
break;
}
}
void print(int reg,FILE *fp)
{
fprintf(fp,"MOV SP,4095\n");
int i=getreg();
fprintf(fp,"MOV R%d,5\n",i);
fprintf(fp,"PUSH R%d\n",i);
fprintf(fp,"MOV R%d,-2\n",i);
fprintf(fp,"PUSH R%d\n",i);
fprintf(fp,"MOV R0,R%d\n",reg);
fprintf(fp,"PUSH R0\n");
fprintf(fp,"PUSH R%d\n",i);
fprintf(fp,"PUSH R%d\n",i);
fprintf(fp,"INT 7\n");
fprintf(fp,"POP R0\n");
fprintf(fp,"POP R0\n");
fprintf(fp,"POP R0\n");
fprintf(fp,"POP R0\n");
fprintf(fp,"POP R0\n");
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_room.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: skgatle <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2017/12/12 09:51:10 by skgatle #+# #+# */
/* Updated: 2017/12/12 09:51:12 by skgatle ### ########.fr */
/* */
/* ************************************************************************** */
#include "../includes/header.h"
void ft_add_to_room_end(t_room **start, t_room *new_node)
{
t_room *tmp;
if (*start == NULL)
*start = new_node;
else
{
tmp = *start;
while (tmp->next)
tmp = tmp->next;
tmp->next = new_node;
new_node->next = NULL;
}
}
t_room *new_room(char **input, int start_end, int num_of_ants)
{
t_room *room;
room = (t_room *)malloc(sizeof(t_room));
room->id = input[0];
room->posx = input[1];
room->posy = input[2];
room->next = NULL;
room->is_start = 0;
room->is_end = 0;
room->num_of_ants = 0;
room->connect = NULL;
room->backpack = NULL;
room->routes = NULL;
if (start_end == 1 && (room->is_start = 1))
room->num_of_ants = num_of_ants;
else if (start_end == 2)
room->is_end = 1;
return (room);
}
void start_connections(t_room **room)
{
t_room *tmp;
tmp = *room;
while (tmp)
{
tmp->start_connections = tmp->connect;
tmp = tmp->next;
}
}
|
C
|
/************************************************************************************
* Network Programming Assingment 2
* Ravi Shankar Pandey
* (2012C6PS676P)
* Abhinav Anurag
* (2012C6PS523P)
* Aditi Agarwal
* (2012C6PS510P)
************************************************************************************/
/*includes*/
#include <stdio.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <unistd.h>
#include <strings.h>
#include <pthread.h>
#include <netinet/in.h>
#include <stdlib.h>
#include <string.h>
#include <sys/select.h>
/*user data stucture*/
struct user_data
{
char name[50];
int isReg;
int connfd;
};
/*global variable*/
struct user_data *clients;
int listenfd, nthreads;
socklen_t clilen;
struct sockaddr_in cliaddr, servaddr;
pthread_mutex_t mlock = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t slock = PTHREAD_MUTEX_INITIALIZER;
/*function prototypes*/
void init_clients();
void err4(int connfd);
void err3(int connfd);
void err2(int connfd);
void err1(int connfd);
int uni_msg(int connfd, int index, char *name);
int leave(int connfd, int index);
int broadcast(int connfd, int index, char* msg);
int list(int connfd);
int register_user(int connfd, int index);
int bmsg(int connfd, char* name, int index, char* msg);
struct user_data getData(int connfd);
/*main*/
int main(int argc, char **argv)
{
if(argc != 3)
{
printf("Improper format %s [port] [N].\n",argv[0]);
exit(EXIT_FAILURE);
}
int i;
void sig_int(int), thread_make(int);
nthreads = atoi(argv[2]);
clients = (struct user_data *)malloc(sizeof(struct user_data)*nthreads);
init_clients();
listenfd = socket(AF_INET, SOCK_STREAM, 0);
if(listenfd == -1)
{
perror("listenfd");
exit(EXIT_FAILURE);
}
bzero(&servaddr, sizeof(servaddr));
servaddr.sin_family = AF_INET;
servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
servaddr.sin_port = htons(atoi(argv[1]));
if(bind(listenfd, (struct sockaddr *)&servaddr, sizeof(servaddr)) < 0)
{
perror("bind");
exit(EXIT_FAILURE);
}
if(listen(listenfd, 2*nthreads) < 0)
{
perror("listen");
exit(EXIT_FAILURE);
}
for(i=0; i<nthreads;i++)
thread_make(i);
/*all the work done in thread*/
for(;;)
pause();
}
/*creates thread*/
void thread_make(int i)
{
void *thread_main(void *);
pthread_t thread_tid;
pthread_create(&thread_tid, NULL, &thread_main, (void *)i);
return;
}
/*thread main function*/
void *thread_main(void *arg)
{
int connfd;
void web_client(int, int);
socklen_t clilen;
struct sockaddr_in *cliaddr;
cliaddr = malloc(sizeof(servaddr));
if(cliaddr == NULL)
{
perror("malloc");
exit(EXIT_FAILURE);
}
//printf("thread %d starting\n", (int) arg);
for(;;)
{
clilen = sizeof(cliaddr);
pthread_mutex_lock(&mlock);
connfd = accept(listenfd, (struct sockaddr*)cliaddr, &clilen);
if(connfd < 0)
{
perror("accept");
exit(EXIT_FAILURE);
}
//printf("new client: %s, port %d\n", inet_ntop(AF_INET, cliaddr->sin_addr, 4, NULL), ntohs(cliaddr->sin_port));
pthread_mutex_unlock(&mlock);
web_client(connfd, (int)arg);
close(connfd);
}
}
/*Handles the client requests*/
void web_client(int connfd, int index)
{
char recv_buff[201];
char *reply = "username not registered.\n";
if(register_user(connfd, index))
{
pthread_mutex_lock(&slock);
char * name = clients[index].name;
pthread_mutex_unlock(&slock);
while(1)
{
memset(recv_buff, '\0', 201);
if(read(connfd, recv_buff, 200) < 0)
{
perror("read");
exit(EXIT_FAILURE);
}
int len = strlen(recv_buff);
if(!((int)recv_buff[len-1] == 10 &&
(int) recv_buff[len-2] == 13))
{
err1(connfd);
continue;
}
recv_buff[len-2] = '\0';
if(strncmp("LEAV", recv_buff, 4) == 0)
{
leave(connfd, index);
break;
}
else if(strncmp("JOIN", recv_buff, 4) == 0)
{
err4(connfd);
}
else if(strncmp("LIST", recv_buff, 4) == 0)
{
list(connfd);
}
else if(strncmp("UMSG ", recv_buff, 5) == 0)
{
uni_msg(connfd, index, &recv_buff[5]);
}
else if(strncmp("BMSG ", recv_buff, 5) == 0)
{
broadcast(connfd, index, &recv_buff[5]);
}
else
{
err3(connfd);
}
}
}
shutdown(connfd, 2);
}
/*uincating message*/
int uni_msg(int connfd, int index, char *name)
{
char recv_buff[201];
char send_data[251];
char *err_msg = "ERROR <not online>\n";
struct user_data a = getData(connfd);
memset(recv_buff, 0, 201);
memset(send_data, 0, 251);
if (read(connfd, recv_buff, 200) < 0)
{
err2(connfd);
return 0;
}
int j,flag=0,len = strlen(recv_buff);
recv_buff[len-2] = '\0';
pthread_mutex_lock(&slock);
for(j=0;j<nthreads;j++)
{
if(strncmp(name, clients[j].name, strlen(name)) == 0)
{
sprintf(send_data, "[%s]:- %s\n",clients[index].name, recv_buff);
printf("%s\n",send_data);
if ( write(clients[j].connfd, send_data,
strlen(send_data)) < 0)
{
err2(connfd);
}
flag = 1;
}
if(flag)
break;
}
pthread_mutex_unlock(&slock);
if(!flag)
{
write(connfd, err_msg, strlen(err_msg));
}
}
/*get user details */
struct user_data getData(int connfd)
{
int j;
pthread_mutex_lock(&slock);
for(j=0;j<nthreads;j++)
{
if(connfd == clients[j].connfd)
{
pthread_mutex_unlock(&slock);
return clients[j];
}
}
pthread_mutex_unlock(&slock);
struct user_data a;
a.connfd = -1;
a.isReg = 0;
return a;
}
/*broadcasting message*/
int broadcast(int connfd, int index, char* msg)
{
int j;
char info[300];
pthread_mutex_lock(&slock);
sprintf(info, "[%s]:- %s\n",clients[index].name, msg);
for(j=0;j<nthreads;j++)
{
if(j==index || clients[j].isReg == 0)
{
continue;
}
write(clients[j].connfd, info, strlen(info));
}
pthread_mutex_unlock(&slock);
return 1;
}
/*listing all the connected clients*/
int list(int connfd)
{
char *buffer;
buffer = malloc(20*nthreads*sizeof(char));
int j = 0,temp;
memset(buffer, '\0', 20);
pthread_mutex_lock(&slock);
for(j=0;j<nthreads;j++)
{
if(clients[j].isReg)
{
temp = strlen(buffer);
sprintf(&buffer[temp], "%s\n", clients[j].name);
}
}
temp = strlen(buffer);
sprintf(&buffer[temp], "\n");
pthread_mutex_unlock(&slock);
if(write(connfd, buffer, strlen(buffer)) < 0)
{
err2(connfd);
return 0;
}
free(buffer);
return 1;
}
/*exiting*/
int leave(int connfd, int index)
{
pthread_mutex_lock(&slock);
strcpy(clients[index].name, "");
clients[index].isReg = 0;
clients[index].connfd = -1;
pthread_mutex_unlock(&slock);
char *msg = "user connection terminated.\n";
write(connfd, msg, strlen(msg));
return 1;
}
/*Return 1 on success else 0*/
int register_user(int connfd, int index)
{
char buffer[201];
char * suc_msg = "logged in\n";
char * fail_msg = "invalid command\n";
if(read(connfd, buffer, 200) < 0)
{
perror("read");
return 0;
}
if(strncmp("JOIN", buffer, 4) == 0)
{
if( write(connfd, suc_msg, strlen(suc_msg)) < 0)
{
perror("send");
return 0;
}
pthread_mutex_lock(&slock);
strcpy(clients[index].name, &buffer[5]);
clients[index].name[strlen(clients[index].name) - 2] = '\0';
clients[index].isReg = 1;
clients[index].connfd = connfd;
pthread_mutex_unlock(&slock);
return 1;
}
write(connfd, fail_msg, strlen(fail_msg));
pthread_mutex_lock(&slock);
clients[index].isReg = 0;
pthread_mutex_unlock(&slock);
return 0;
}
/*initializing all the clients array to null*/
void init_clients()
{
int j;
for(j=0;j<nthreads;j++)
{
clients[j].isReg = 0;
clients[j].connfd = -1;
strcpy(clients[j].name, "");
}
}
/*error messages*/
void err4(int connfd)
{
char *err4 = "Cannot have multiple logins.\n";
if(write(connfd, err4, strlen(err4))<0)
{
perror("write");
}
}
void err3(int connfd)
{
char *err3 = "Unknown Command.\n";
if(write(connfd, err3, strlen(err3))<0)
{
perror("write");
}
}
void err2(int connfd)
{
char *err2 = "Unable to process query.\n";
if(write(connfd, err2, strlen(err2))<0)
{
perror("write");
}
}
void err1(int connfd)
{
char *err1 = "Improper format.\n";
if(write(connfd, err1, strlen(err1))<0)
{
perror("write");
}
}
|
C
|
#include<stdio.h>
#include<math.h>
#include<conio.h>
float n,pu,mb,tx,mnet;
void main()
{
printf("donner le nombre de KWH");
scanf("%f",&n);
if(n<100)
pu=0.80;
else
{
if(n<300)
pu=1.20;
else
pu=2;
}
mb=pu*n;
tx=mb*0.17
mn=mb+tx;
printf("le montant brut est",mb);
printf("la taxe est",tx);
printf("le montant net est",mn);
}
|
C
|
#include <stdio.h>
int main(void)
{
int integer1; //]wܼ
int integer2;
int sum;
printf("Enter first integer\n");
scanf("%d",&integer1); //JĤ@ܼ
printf("Enter second integer\n");
scanf("%d",&integer2); //JĤGܼ
sum=integer1+integer2; //NܼƬۥ[
printf("sum is %d\n",sum); //XܼƩM
}
|
C
|
#include "mbed.h"
#include "SDFileSystem.h"
#include "FXOS8700Q.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
//Port Assignments________________________________________________________________________________________________
FXOS8700Q_acc acc( PTE25, PTE24, FXOS8700CQ_SLAVE_ADDR1); // Proper Ports and I2C Address for K64F Freedom board
FXOS8700Q_mag mag( PTE25, PTE24, FXOS8700CQ_SLAVE_ADDR1); // Proper Ports and I2C Address for K64F Freedom board
Serial pc(USBTX, USBRX);
//MotionSensor Data given in terms of gravity
MotionSensorDataUnits mag_data;
MotionSensorDataUnits acc_data;
//MotionSensor Data Raw - Meaning that it gives in non 'Gs'
MotionSensorDataCounts mag_raw;
MotionSensorDataCounts acc_raw;
//SD card initialization "sd" is what the directory is called. to access it is "/sd"
SDFileSystem sd(PTE3, PTE1, PTE2, PTE4, "sd"); // MOSI, MISO, SCK, CS
//File initialization
FILE *fp_raw;
FILE *fp_;
FILE *fp_log;
int main()
{
acc.enable(); //Enable Motion Sensor
//pc.printf("Initializing \n");
mkdir("/sd/test", 0777);
fp_log = fopen("/sd/log.txt", "w");
fp_= fopen("/sd/test/testing.csv", "a+");
fp_raw = fopen("/sd/test/testing_raw.csv", "a+");
if (fp_ == NULL) {
fprintf(fp_log,"Unable to write the file \n");
fclose(fp_log);
} else {
fprintf(fp_,"Begin Here _______________________________________________");
fprintf(fp_raw, "Begin Here _____________________________________________");
fclose(fp_);
fclose(fp_raw);
int count = 0;
while(true){
count =0;
fp_ = fopen("/sd/test/testing.csv", "a+");
fp_raw = fopen("/sd/test/testing_raw.csv","a+");
while (count <100) {
acc.getAxis(acc_data);
mag.getAxis(mag_data);
fprintf(fp_,"%1.5f,%1.5f,%1.5f, ", acc_data.x, acc_data.y, acc_data.z);
fprintf(fp_,"%4.3f, %4.3f, %4.3f\r\n", mag_data.x, mag_data.y, mag_data.z);
acc.getAxis(acc_raw);
mag.getAxis(mag_raw);
fprintf(fp_raw,"%d,%d,%d,", acc_raw.x, acc_raw.y, acc_raw.z);
fprintf(fp_raw,"%d, %d,%d\r\n", mag_raw.x, mag_raw.y, mag_raw.z);
wait(.001);
count = count +1;
}
fclose(fp_);
fclose(fp_raw);
}
}
}
|
C
|
#include "../include/io.h"
void print_promt(){
fprintf(stdout,"$");
fflush(stdout);
}
void get_cmd_line(char* cmd){
char c;
size_t used = 0;
BEGIN_READ();
while (((c = getc(stdin)) != EOF) && (c != '\n')){
cmd[used++] = c;
}
cmd[used] = '\0';
END_READ();
}
void debug_info(const char* info){
if (info != NULL){
fprintf(stdout,"%s\n",info);
}
}
void BEGIN_READ(){
READING = TRUE;
}
void END_READ(){
READING=FALSE;
}
|
C
|
/*
* Shortcut experiment.
* Opens the doors, moves the robot to the start position, ...
* louis-emmanuel.martinet@upmc.fr
*/
#include "protocol.h"
#include "analysebehavior.h"
#include "supervisor.h"
#include <webots/servo.h>
#include <webots/distance_sensor.h>
#include <webots/led.h>
#include <webots/emitter.h>
#include <webots/supervisor.h>
#include <webots/robot.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// Webots devices: servos, sensors and emitter
#define NBSENSORS 1
#define NBSERVOS 4
WbDeviceTag sensors[NBSENSORS];
WbDeviceTag servos[NBSERVOS];
WbDeviceTag emitter;
enum servo_name { short1_start = 0, short1_end = 1,
short2_start = 2, short2_end = 3 };
enum sensor_name { s_goal = 0 };
// output file for protocol observations
FILE * output_protoc = NULL;
enum protocol_type { FREE = 0, BLOC = 1 };
// position of servos (c : close, o : open), and actions
enum servo_position { c = 1, o = -1 };
float orders[NBSERVOS];
// trials informations
int trial = 1;
double trial_time;
int total_step = 1;
// The start & goal points
const char* start_name = "START";
double* start_position;
double* start_rotation;
const char* goal_name = "GOAL";
double* goal_position;
// stuff to create an automaton for the robot
enum robot_states { SEARCHING, GOALFOUND, SLEEPING } robot_state;
int wait = -1;
// shortcut typedef (0 = direct shortcut, 1 = indirect shortcut)
int shortcut;
void message_protocol (enum protocol_type s) {
fprintf(output_protoc, "%d %d %d\n", total_step, trial, s);
fflush(output_protoc);
}
void new_trial_doors(){
if (trial < 7) {
orders[0] = orders[1] = orders[2] = orders[3] = c;
message_protocol (BLOC);
} else if (shortcut == 0) {
// Test period
orders[1] = orders[3] = o;
orders[0] = orders[2] = c;
message_protocol (FREE);
} else if (shortcut == 1) {
// Test period
orders[1] = orders[3] = c;
orders[0] = orders[2] = o;
message_protocol (FREE);
}
}
void init_protocol (int simu_id, int cut) {
char output_path[128];
sprintf (output_path, "../../data/data_raw/%d/protocol.txt", simu_id);
output_protoc = fopen (output_path, "w");
fprintf(output_protoc, "%s format : total_step day trial type\n", "%");
fprintf(output_protoc, "%s type : 0=free ; 1=blocs\n", "%");
// retrieve device handles
int i;
char servo_name[] = "servo0";
for(i = 0; i < NBSERVOS; i++){
servos[i] = wb_robot_get_device (servo_name);
servo_name[5]++;
}
sensors[0] = wb_robot_get_device ("sensor_goal");
wb_distance_sensor_enable (sensors[0], TIME_STEP);
emitter = wb_robot_get_device ("emitter");
// retrieve the start position
WbNodeRef start_point = wb_supervisor_node_get_from_def (start_name);
if (start_point != NULL) {
WbFieldRef t_start = wb_supervisor_node_get_field (start_point, "translation");
WbFieldRef r_start = wb_supervisor_node_get_field (start_point, "rotation");
start_position = (double*) wb_supervisor_field_get_sf_vec3f (t_start);
start_rotation = (double*) wb_supervisor_field_get_sf_rotation (r_start);
//printf("Protocol: %f %f %f\n", start_position[0], start_position[2], start_rotation[3]);
}
else {
printf("Error: node %s not found\n", start_name);
}
// retrieve the goal position
WbNodeRef goal_point = wb_supervisor_node_get_from_def (goal_name);
if (goal_point != NULL) {
WbFieldRef t_goal = wb_supervisor_node_get_field (goal_point, "translation");
goal_position = (double*) wb_supervisor_field_get_sf_vec3f (t_goal);
goal_position[2] += 0.04;
}
else {
printf("Error: node %s not found\n", goal_name);
}
trial_time = 0.0;
shortcut = cut;
new_trial_doors();
wb_robot_step (TIME_STEP);
}
void do_orders () {
int i;
for(i = 0; i < NBSERVOS; i++) {
wb_servo_set_position (servos[i], orders[i]);
}
}
void move_doors () {
int i;
int value[NBSENSORS];
for(i = 0; i < NBSENSORS; i++) {
value[i] = wb_distance_sensor_get_value (sensors[i]);
}
if (robot_state == SEARCHING && value[s_goal] < 900) {
robot_state = GOALFOUND;
wait = 100;
char msg [] = "goal";
wb_emitter_send (emitter, msg, strlen(msg) + 1);
message (GOAL);
}
do_orders();
}
void run_protocol () {
// printing the simulation stats
char score[128];
sprintf(score, "Trial %d : %s", trial, trial >= 7 ? "Test" : "Training");
wb_supervisor_set_label (0, score, 0.01, 0.01, 0.05, 0x0000ff, 0);
sprintf(score, "Time %d s", (int)trial_time);
wb_supervisor_set_label (1, score, 0.01, 0.05, 0.05, 0x0000ff, 0);
// change the doors according to the trial number
move_doors();
trial_time += (float) TIME_STEP / 1000;
total_step++;
// sending the distance of the robot to the goal
const double* translation = wb_supervisor_field_get_sf_vec3f (t_field);
double dist[] = {translation[0] - goal_position[0], translation[2] - goal_position[2]};
char dist_msg[128];
sprintf(dist_msg, "%f", sqrt(dist[0] * dist[0] + dist[1] * dist[1]));
wb_emitter_send (emitter, dist_msg, strlen(dist_msg) + 1);
if (robot_state == SEARCHING && trial_time > 1000) {
// maximum time reached
message (EXCEED);
// we move the animat at the goal position
wb_supervisor_field_set_sf_vec3f (t_field, goal_position);
wb_supervisor_field_set_sf_rotation (r_field, start_rotation);
}
else if (robot_state == GOALFOUND && wait == -1) {
// Reset the maze & robot
wb_supervisor_field_set_sf_vec3f (t_field, start_position);
wb_supervisor_field_set_sf_rotation (r_field, start_rotation);
trial++;
// When all the trials are done, we quit webots
if (trial > 7) {
supervisor_die ();
}
new_trial_doors();
trial_time = 0;
current_way_init ();
robot_state = SEARCHING;
}
if (wait >= 0) {
wait--;
}
}
void die_protocol () {
fflush(output_protoc);
fclose(output_protoc);
}
int get_trial(){
return trial;
}
int get_total_step(){
return total_step;
}
double get_trial_time(){
return trial_time;
}
|
C
|
// Alex Rockhill 3.10.2019
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "plot.h"
#include "network.h"
#include "random.h"
struct network_args parse_args() {
struct network_args nw_args;
FILE *fp = fopen("./bin/args.txt","rb");
char args[SLEN];
while (fgets(args, SLEN, fp) != NULL) {
char *flag = strtok(args, " ");
char *ptr = strtok(NULL, " \n");
if (strcmp(flag, "--seed") == 0) {
nw_args.seed = atoi(ptr);
} else if (strcmp(flag, "--dim") == 0){
nw_args.dim = atoi(ptr);
} else if (strcmp(flag, "--oris") == 0) {
nw_args.oris = atoi(ptr);}
else if (strcmp(flag, "--n_steps") == 0) {
nw_args.n_steps = atoi(ptr);
} else if (strcmp(flag, "--loc_mu") == 0) {
nw_args.loc_mu = strtof(ptr, NULL);
} else if (strcmp(flag, "--lat_mu") == 0) {
nw_args.lat_mu = strtof(ptr, NULL);
} else if (strcmp(flag, "--loc_sig") == 0) {
nw_args.loc_sig = strtof(ptr, NULL);
} else if (strcmp(flag, "--lat_sig") == 0) {
nw_args.lat_sig = strtof(ptr, NULL);
} else if (strcmp(flag, "--leak") == 0) {
nw_args.leak = strtof(ptr, NULL);
} else if (strcmp(flag, "--loc") == 0) {
strcpy(nw_args.loc, ptr);
} else if (strcmp(flag, "--lat") == 0) {
strcpy(nw_args.lat, ptr);
}
}
return nw_args;
}
int main()
{
struct network_args nw_args = parse_args();
struct network nw = make_network(nw_args);
plot_network(nw);
take_down_network(nw);
}
|
C
|
#include "arrays.h"
char *arr_strcat(char dest[], const char src[]) {
// find the null byte on dest
char byte;
int pos = -1;
do {
pos++;
byte = dest[pos];
} while ('\0' != byte);
// write over the dest until we
// reach null byte on src
int src_pos = -1;
do {
src_pos++;
byte = src[src_pos];
dest[pos] = byte;
pos++;
} while ('\0' != byte);
return dest;
}
int ary_strcmp(const char s1[], const char s2[]) {
int index = -1;
char s1_c;
char s2_c;
do {
index++;
s1_c = s1[index];
s2_c = s2[index];
} while (s1_c != '\0' && s2_c != '\0' && s1_c == s2_c);
return s1_c - s2_c;
}
int ary_strncmp(const char s1[], const char s2[], size_t n) {
char s1_c;
char s2_c;
for (int i = 0; i < n; i++) {
s1_c = s1[i];
s2_c = s2[i];
if (s1_c == '\0' || s2_c == '\0' || s1_c != s2_c) {
return s1_c - s2_c;
}
}
return 0;
}
char *ary_strchr(const char s[], int c) {
for (int i = 0;; i++) {
if (s[i] == c) {
return (char *)&s[i];
}
if (s[i] == '\0') {
return NULL;
}
}
}
|
C
|
/*
Given a non-empty array of integers, every element appears twice except for one. Find that single one.
Note:
Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?
Example 1:
Input: [2,2,1]
Output: 1
Example 2:
Input: [4,1,2,1,2]
Output: 4
*/
int singleNumber(int* nums, int numsSize){
int ans;
ans = nums[0];
for(int i=1;i<numsSize;i++)
{
ans = ans ^ nums[i];
}
return ans;
}
|
C
|
/*
* who01.c - a first version of the who program
* open, read UTMP file, and show results
* utmpx.h -- "/usr/include/utmpx.h"
*
*/
#include <stdio.h>
#include <utmpx.h>
#include <fcntl.h>
#include <unistd.h>
#define SHOWHOST /* include remote machine on output */
/*
* show info()
* displays contents of the utmp struct in human readable form
*/
void show_info(struct utmpx *) ;
int main (int argc, char const *argv[])
{
/* code */
struct utmpx current_record; /* read info into here */
int utmpfd ; /* read from this descriptor */
int reclen = sizeof(current_record) ;
if ((utmpfd = open(_PATH_UTMPX, O_RDONLY )) == -1){ //failed
perror(_PATH_UTMPX) ; /* UTMP_FILE is utmp.h */
exit(1) ;
}
while ( read(utmpfd, ¤t_record, reclen ) == reclen)
show_info(¤t_record) ;
close(utmpfd) ;
return 0;
}
void show_info(struct utmpx * utbufp ){
struct utmpx * d=getutxent() ;
printf("%-8.8s", d->ut_user) ; /* the logname */
printf(" ") ;
printf("%-8.8s", d->ut_line) ; /* the tty */
printf(" ") ;
printf("%-10ld", d->ut_tv.tv_sec) ; /* login time */
printf(" ") ;
#ifdef SHOWHOST
printf("(%s)", d->ut_host) ; /* the host */
#endif
printf("\n") ;
}
|
C
|
/* File that contains the information necessary to implement all of the
* commands in the server.
* Author: YOUR NAME HERE */
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
#include <unistd.h>
#include "server.h"
#include "commands.h"
#include "command_utils.h"
#include "server_utils.h"
#include "user_utils.h"
#include "client_server_utils.h"
/* List of commands the server recognizes. */
char* commands[COMMAND_COUNT] = {"exit", "server_exit", "set_nickname", "clear_nickname",
"rename", "mute", "unmute", "show_status", "show_all_statuses"};
/* List of functions to handle each command. Each function is at the same index
* as the command is in the previous list to allow a command name search to
* give easy access to a function with an extended if else. */
void (*command_functions[COMMAND_COUNT]) (char **args, unsigned count, unsigned n) =
{handle_exit, handle_server_exit, handle_set_nickname, handle_clear_nickname, handle_rename,
handle_mute, handle_unmute, handle_show_status, handle_show_all_statuses};
/* Function that takes in a message that is a command sent by user at index
* n and parses the message into a command name and its arguments. It then
* calls the appropriate function to handle a command with that name. */
void parse_command (char *message, unsigned n) {
int i = 0;
while (message[i] != '\\') {
i++;
}
char *name = strtok (message + i + 1, WHITESPACE_SET);
if (!isword (name)) {
int end = 0;
while (isidentifierpart (name[end])) {
end++;
}
name[end] = 0;
if (isknowncommand (name)) {
handle_invalid_arguments (name, n);
return;
} else {
handle_unknown_command (name, n);
return;
}
}
if (!isknowncommand (name)) {
handle_unknown_command (name, n);
} else {
unsigned arg_limit = 3;
char *args[3];
char *arg;
unsigned count = 0;
while (count < arg_limit && (arg = strtok (NULL, WHITESPACE_SET)) != NULL) {
args[count] = arg;
count++;
if (!isword (arg)) {
handle_invalid_arguments (name, n);
return;
}
}
if (count == arg_limit) {
handle_invalid_arguments (name, n);
return;
}
handle_command (name, args, count, n, message);
}
}
/* A function that takes a command name, the arguments, the number of
* arguments, and the index of the user who gave the command and calls
* the appropriate function to handle the command. Needs to also have
* a ptr to original msg to free if it is a server_exit. */
void handle_command (char *name, char **args, unsigned count, unsigned n, char *msg) {
unsigned ctr = 0;
while (ctr < COMMAND_COUNT) {
if (strcmp (name, commands[ctr]) == 0) {
if (strcmp (name, "server_exit") == 0 && count == 0) {
free (msg);
}
command_functions [ctr] (args, count, n);
return;
}
ctr++;
}
handle_unknown_command (name, n);
}
/* Function that handles the exit command. It sends the client back
* a message to exit using the Exit_Message character (see
* client_server_utils.h) at the start of the message. The
* function takes in no arguments. The function is also passed in
* the total number of args the function was called with, count and
* the index of the user who sent the command. */
void handle_exit (char **args, unsigned count, unsigned n) {
if (count != 0) {
handle_invalid_arguments ("exit", n);
} else {
char message [3];
message[0] = Exit_Message;
message[1] = '\n';
message[2] = 0;
reply (message, n);
}
}
/* Function that handles the server_exit command. It closes all of
* the sockets that are currently open, frees all the messages for
* any of the users who were open and cleans up all of the remaining
* users. The function takes in no arguments. The function is also
* passed in the total number of args the function was called with,
* count and the index of the user who sent the command. */
void handle_server_exit (char **args, unsigned count, unsigned n) {
if (count != 0) {
handle_invalid_arguments ("server_exit", n);
} else {
close (sockets[0]);
socket_total--;
free (messages[0]);
int start = 0;
int ctr = 1;
while (start < socket_total) {
if (sockets[ctr] != -1) {
start++;
close (sockets[ctr]);
sockets[ctr] = -1;
free (messages[ctr]);
if (users[ctr] != NULL) {
cleanup_user (users[ctr]);
}
}
ctr++;
}
exit (0);
}
}
/* ***************************READ ME*******************************
* *
* *
* This begins the section you will edit. If you encounter an error*
* be sure and call the handle_invalid_arguments function and then *
* exit the function. See handle_server_exit above for an example *
* of how to use it. Also be sure and check the error conditions *
* on the spec. *
* *
* A few functions you may find userful: *
* - isvalidname (command_utils.h) *
* - find_user (user_utils.h) *
* - has_nickname (user_utils.h) *
* - create_name (user_utils.h) *
* - output_user_status (command_utils.h) *
* *
* ****************************************************************/
/* Function that handles the set_nickname command. The command takes
* exactly 2 arguments, stored in args. The first is a name which
* must be the name of an existing user. The second is word which
* must be a valid choice for a new name. It sets the user whose name
* is given by the first argument's nickname to the second argument.
* Then all messages from that user should display that nickname.
* The function is also passed in the total number of args the function
* was called with, count and the index of the user who sent the command.
* You do not need to check that any args passed in are either too long
* or consist of invalid characters, this has already been checked for you.*/
void handle_set_nickname (char **args, unsigned count, unsigned n) {
/* HANDLE ANY POSSIBLE ERROR CONDITIONS */
/* IMPLEMENT THE CORE FUNCTIONALITY */
struct user_info *user = NULL; /* REPLACE ME */
/* WE HANDLE MESSAGE OUTPUT FOR YOU */
char *other_messages[6];
other_messages[0] = users[n]->name_info->name;
other_messages[1] = " set ";
other_messages[2] = user->name_info->name;
other_messages[3] = "'s nickname to ";
other_messages[4] = args[1];
other_messages[5] = "\n";
char *message = create_message (other_messages, 6);
share_message (message, n, false);
free (message);
other_messages[0] = "You set ";
if (user == users[n]) {
other_messages[1] = "your";
other_messages[2] = " nickname to ";
} else {
other_messages[1] = other_messages[2];
other_messages[2] = other_messages[3];
}
other_messages[3] = other_messages[4];
other_messages[4] = other_messages[5];
message = create_message (other_messages, 5);
reply (message, n);
free (message);
/* ANYTHING ELSE THAT NEEDS TO BE DONE? DOES ANYTHING
* NEED TO BE FREED? */
}
/* Function to handle the clear_nickname command. It takes in one
* argument, a name, which must be the name of an existing user.
* The function removes the nickname of the user if one exists
* and resets it to that user's name.
* The function is also passed in the total number of args the
* function was called with, count and the index of the user who
* sent the command. You do not need to check that any args passed
* in are either too long or consist of invalid characters, this
* has already been checked for you. */
void handle_clear_nickname (char **args, unsigned count, unsigned n) {
/* HANDLE ANY POSSIBLE ERROR CONDITIONS */
/* IMPLEMENT THE CORE FUNCTIONALITY */
struct user_info *user = NULL; /* REPLACE ME */
/* WE HANDLE MESSAGE OUTPUT FOR YOU */
char *other_messages[4];
other_messages[0] = users[n]->name_info->name;
other_messages[1] = " has cleared ";
other_messages[2] = user->name_info->name;
other_messages[3] = "'s nickname\n";
char *message = create_message (other_messages, 4);
share_message (message, n, false);
free (message);
other_messages[0] = "You have cleared ";
if (user == users[n]) {
other_messages[1] = "your";
other_messages[2] = " nickname\n";
} else {
other_messages[1] = other_messages[2];
other_messages[2] = other_messages[3];
}
message = create_message (other_messages, 3);
reply (message, n);
free (message);
/* ANYTHING ELSE THAT NEEDS TO BE DONE? DOES ANYTHING
* NEED TO BE FREED? */
}
/* Function to handle the rename command. It takes one argument which must
* be a valid name. The user who called the command will have their name
* changed to the name passed in. Then any attempts to access that user
* will need to refer to this new name and not the old one. Also if the
* user does not have a nickname this name should be displayed instead
* of the old name. The function is also passed in the total number of args
* the function was called with, count and the index of the user who sent
* the command. You do not need to check that any args passed in are either
* too long or consist of invalid characters, this has already been checked
* for you.*/
void handle_rename (char **args, unsigned count, unsigned n) {
/* HANDLE ANY POSSIBLE ERROR CONDITIONS */
/* USEFUL VARIABLES PRESET FOR MESSAGE OUTPUT */
char *name = args[0];
struct user_info *user = users[n];
char *old_name = user->name_info->name;
/* IMPLEMENT THE CORE FUCNTIONALITY */
/* WE HANDLE MESSAGE OUTPUT FOR YOU */
char *other_messages[4];
other_messages[0] = old_name;
other_messages[1] =" changed their name to ";
other_messages[2] = name;
other_messages[3] = "\n";
char *message = create_message (other_messages, 4);
share_message (message, n, false);
free (message);
other_messages[0] = "You have changed your name to ";
other_messages[1] = name;
other_messages[2] = "\n";
message = create_message (other_messages, 3);
reply (message, n);
free (message);
/* ANYTHING ELSE THAT NEEDS TO BE DONE? DOES ANYTHING
* NEED TO BE FREED? */
}
/* Function to handle the mute command. It takes one argument, a name, which
* must be the name of an existing user. If the user is not already muted
* by the user who called the command, set that user to by muted by for the
* user who called the command. Then all messages sent by the user who's name
* is the first argument should not be received by the user who issued the
* mute command. The function is also passed in the total number of args the
* function was called with, count and the index of the user who sent the
* command. */
void handle_mute (char **args, unsigned count, unsigned n) {
/* HANDLE ERROR CONDITIONS */
/* IMPLEMENT THE CORE FUNCTIONALITY */
/* WE HANDLE MESSAGE OUTPUT FOR YOU */
char *messages[3];
messages[0] = "User ";
messages[1] = args[0];
messages[2] = " is now muted\n";
char *message = create_message (messages, 3);
reply (message, n);
free (message);
/* ANYTHING ELSE THAT NEEDS TO BE DONE? DOES ANYTHING
* NEED TO BE FREED? */
}
/* Function to handle the unmute command. It takes one argument, a name, which
* must be the name of an existing user. If the user is currently muted by the
* user who called the command. Then that user should resume receiving messages
* from that user. The function is also passed in the total number of args the
* function was called with, count and the index of the user who sent the
* command. You do not need to check that any args passed in are either too long
* or consist of invalid characters, this has already been checked for you.*/
void handle_unmute (char **args, unsigned count, unsigned n) {
/* HANDLE ERROR CONDITIONS */
/* IMPLEMENT THE CORE FUNCTIONALITY */
/* WE HANDLE MESSAGE OUTPUT FOR YOU */
char *other_messages[3];
other_messages[0] = "User ";
other_messages[1] = args[0];
other_messages[2] = " is no longer muted\n";
char *message = create_message (other_messages, 3);
reply (message, n);
free (message);
/* ANYTHING ELSE THAT NEEDS TO BE DONE? DOES ANYTHING
* NEED TO BE FREED? */
}
/* Function that handles the show_status command. It takes 1 argument,
* a name, which must be an existing user. It then display the status
* of that user to the user who called the command. The function is
* also passed in the total number of args the function was called with,
* count and the index of the user who sent the command. You may find
* the function output_user_status helpful. You do not need to check
* that any args passed in are either too long or consist of invalid
* characters, this has already been checked for you. */
void handle_show_status (char **args, unsigned count, unsigned n) {
/* HANDLE ERROR CONDITIONS. */
/* IMPLEMENT THE CORE FUNCTIONALITY */
}
/* Function that handles the show_all_statuses command. It returns the status
* information of all connected users in alphabetical order. It takes no arguments.
* The function is also passed in the total number of args the function was called
* with, count and the index of the user who sent the command. You may find the
* functions sort_users and output_user_status (in command_utils.h)
* helpful. You do not need to check that any args passed in are either too long
* or consist of invalid characters, this has already been checked for you. */
void handle_show_all_statuses (char **args, unsigned count, unsigned n) {
if (count != 0) {
handle_invalid_arguments ("show_all_statuses", n);
} else {
sort_users(&n);
for (int i = 1; i < socket_total; i++) {
output_user_status (users[i], n);
}
}
}
/* Function that handles a known command being called with the wrong
* arguments. It replies to the user at index that the command name
* was called with the wrong arguments. */
void handle_invalid_arguments (char *name, unsigned n) {
char *start = "Incorrect arguments for ";
char *end = " command\n";
char *messages[] = {start, name, end};
char *new_message = create_message (messages, 3);
reply (new_message, n);
free (new_message);
}
/* Function that handles a command that is not known. It replies to
* the user at index n that the command name does not exist. */
void handle_unknown_command (char *name, unsigned n) {
char *start = "Unknown command ";
char *end = "\n";
char *messages[] = {start, name, end};
char *new_message = create_message (messages, 3);
reply (new_message, n);
free (new_message);
}
|
C
|
#include "TStopwatch.h"
void SubsetTree(TString fileout, TString treenameout, TString filein, TString treenamein, vector<TString> branches)
{
TStopwatch s;
s.Start();
TFile *f = new TFile(filein);
TTree *t = (TTree *)f->Get(treenamein);
t->SetBranchStatus("*",0);
for (auto b:branches) t->SetBranchStatus(b,1);
TFile *fout = new TFile(fileout,"RECREATE");
TTree *tout = t->CloneTree(-1,"fast");
tout->SetName(treenameout);
tout->Write();
fout->Close();
s.Stop();
cout<<"Finished in "<<s.RealTime()<<" s"<<endl;
//s.Print();
}
void SubsetMultipleTrees(TString fileout, vector<TString> treenameout, TString filein, vector<TString> treenamein, vector<vector<TString> > branches)
{
TStopwatch s;
s.Start();
TFile *f = new TFile(filein);
vector<TTree *>ts;
for (unsigned i=0;i<treenamein.size();i++) {
TTree *t = (TTree *)f->Get(treenamein[i]);
t->SetBranchStatus("*",0);
for (auto b:branches[i]) t->SetBranchStatus(b,1);
ts.push_back(t);
}
TFile *fout = new TFile(fileout,"RECREATE");
for (unsigned i=0;i<ts.size();i++) {
TTree *tout = ts[i]->CloneTree(-1,"fast");
//shows progress, but much slower
// TTree *tout = ts[i]->CloneTree(0,"fast");
// int nentries = ts[i]->GetEntries();
// int oneperc = nentries/100;
// for (int j=0;j<nentries;j++)
// {
// ts[i]->GetEntry(j); tout->Fill();
// if (j % oneperc == 0) cout<<"\r"<<j/oneperc<<"% "<<flush;
// }
// cout<<endl;
tout->SetName(treenameout[i]);
tout->Write();
delete tout;
delete ts[i];
}
fout->Close();
s.Stop();
cout<<"Finished in "<<s.RealTime()<<" s"<<endl;
}
|
C
|
#ifndef __SPICEUSR_H__
#define __SPICEUSR_H__
#include <math.h>
typedef char SpiceChar;
typedef int SpiceInt;
typedef double SpiceDouble;
static void vpack_c(SpiceDouble x, SpiceDouble y, SpiceDouble z, SpiceDouble* vec3) {
vec3[0] = x;
vec3[1] = y;
vec3[2] = z;
return;
}
static void vscl_c(SpiceDouble scalar, SpiceDouble* vec3in, SpiceDouble* vec3out) {
vec3out[0] = vec3in[0] * scalar;
vec3out[1] = vec3in[1] * scalar;
vec3out[2] = vec3in[2] * scalar;
return;
}
static SpiceDouble vdot_c(SpiceDouble* vec3a, SpiceDouble* vec3b) {
return (vec3a[0]*vec3b[0]) + (vec3a[1]*vec3b[1]) + (vec3a[2]*vec3b[2]);
}
static SpiceDouble vnorm_c(SpiceDouble* vec3) {
return sqrt(vdot_c(vec3,vec3));
}
static void vhat_c(SpiceDouble* vec3in, SpiceDouble* uvec3out) {
SpiceDouble vnorm = vnorm_c(vec3in);
vscl_c(vnorm > 0. ? (1./vnorm) : 0.0, vec3in, uvec3out);
return;
}
static void vadd_c(SpiceDouble* vec3a, SpiceDouble* vec3b, SpiceDouble* vec3out) {
vpack_c( vec3a[0]+vec3b[0], vec3a[1]+vec3b[1], vec3a[2]+vec3b[2], vec3out);
return;
}
static void vlcom_c(SpiceDouble scalarA, SpiceDouble* vec3a, SpiceDouble scalarB, SpiceDouble* vec3b, SpiceDouble* vec3out) {
SpiceDouble lclVec3a[3];
SpiceDouble lclVec3b[3];
vscl_c(scalarA,vec3a,lclVec3a);
vscl_c(scalarB,vec3b,lclVec3b);
vadd_c(lclVec3a,lclVec3b,vec3out);
return;
}
static void vlcom3_c(SpiceDouble scalarA, SpiceDouble* vec3a, SpiceDouble scalarB, SpiceDouble* vec3b, SpiceDouble scalarC, SpiceDouble* vec3c, SpiceDouble* vec3out) {
SpiceDouble lclVec3[3];
vlcom_c(scalarA,vec3a,scalarB,vec3b,lclVec3);
vlcom_c(1.0,lclVec3,scalarC,vec3c,vec3out);
return;
}
static void vsub_c(SpiceDouble* v0, SpiceDouble* v1, SpiceDouble* v01) {
vlcom_c(1.,v1,-1.,v0,v01);
return;
}
static void vequ_c(SpiceDouble* vin, SpiceDouble* vout) {
vout[0] = vin[0];
vout[1] = vin[1];
vout[2] = vin[2];
return;
}
static void vcrss_c(SpiceDouble* v0, SpiceDouble* v1, SpiceDouble* v01) {
SpiceDouble lclVec3[3];
lclVec3[0] = v0[1]*v1[2] - v1[1]*v0[2];
lclVec3[1] = v0[2]*v1[0] - v1[2]*v0[0];
lclVec3[2] = v0[0]*v1[1] - v1[0]*v0[1];
vequ_c(lclVec3,v01);
return;
}
static void ucrss_c(SpiceDouble* v0, SpiceDouble* v1, SpiceDouble* uv01) {
vcrss_c(v0,v1,uv01);
vhat_c(uv01,uv01);
return;
}
static void vminus_c(SpiceDouble* vin, SpiceDouble* vout) {
if (vin[0] != 0.0) vout[0] = -vin[0];
if (vin[1] != 0.0) vout[1] = -vin[1];
if (vin[2] != 0.0) vout[2] = -vin[2];
return;
}
#endif /* __SPICEUSR_H__ */
|
C
|
/*
* KPrimitives.c
*
* Created on: 2010-11-18
* Author: abubakar
*/
#include "rtx.h"
//HELPER FUNCTION - to be used with the kernel primitive, not with KB and CRT proccesses
NewPCB * get_PCB (int process_id)
{
if (PCBList->Head==NULL){
return NULL;
}
NewPCB* Temp = PCBList->Head;
if (process_id==Temp->ProcID)
return Temp;
while (process_id !=Temp->ProcID)
{
if (Temp->Kernelpt_Next==NULL)
return NULL;
Temp=Temp->Kernelpt_Next;
}
return Temp;
}
int K_Sort_Envelope_Enqueue (Envelope * msg_env)
{
if (timeout_Q->head==NULL && timeout_Q->free_msg_counter==0) //List contains nothing
{
K_Enqueue_MsgEnv(msg_env,timeout_Q);
timeout_Q->free_msg_counter++;
return 1;
}
else
{
if (timeout_Q->free_msg_counter==1)
{
Envelope* Temp=timeout_Q->head;
if (msg_env->clockticks>=Temp->clockticks) //list contains 1 add to TAIL
{
timeout_Q->tail=msg_env;
Temp->Next=msg_env;
msg_env->Previous=Temp;
timeout_Q->free_msg_counter++;
return 1;
}
else //List contains 1 add to HEAD
{
Temp->Previous=msg_env;
msg_env->Next=Temp;
timeout_Q->head=msg_env;
timeout_Q->tail=Temp;
timeout_Q->free_msg_counter++;
return 1;
}
}
else //List contains more than 1
{
Envelope* A=timeout_Q->head; //1st one
Envelope* B=timeout_Q->head->Next; //2nd one
if (msg_env->clockticks<A->clockticks)
{
A->Previous=msg_env;
msg_env->Next=A;
timeout_Q->head=msg_env;
timeout_Q->free_msg_counter++;
return 1;
}
else if (msg_env->clockticks>timeout_Q->head->clockticks && msg_env->clockticks<timeout_Q->tail->clockticks)
{
int i;
for (i=0;i<timeout_Q->free_msg_counter;i++)
{
if (msg_env->clockticks<B->clockticks && msg_env->clockticks>A->clockticks)
break;
A=A->Next;
B=B->Next;
}
A->Next=msg_env;
msg_env->Next=B;
B->Previous=msg_env;
msg_env->Previous=A;
timeout_Q->free_msg_counter++;
return 1;
}
else if (msg_env->clockticks>timeout_Q->tail->clockticks)
{
Envelope* Last=timeout_Q->tail;
Last->Next=msg_env;
msg_env->Previous=Last;
timeout_Q->tail=msg_env;
timeout_Q->free_msg_counter++;
return 1;
}
}
}
}
int K_Enqueue_PCB (NewPCB* Temp,QueuePCB* List)
{
if (Temp==NULL)
return 0;
if (List->Head==NULL && List->Tail==NULL)
{
// printf("hello\n");
List->Head=Temp;
List->Tail=Temp;
Temp->Next=NULL;
Temp->Previous=NULL;
return 1;
}
else
{
NewPCB *A=List->Tail;
List->Tail = Temp;
Temp->Previous = A;
A->Next = Temp;
return 1;
}
return 0;
}
int K_Enqueue_MsgEnv (Envelope *Temp, msg_env_Q * List) //List=head of the list on which envelope is to be enqueued
{
if (Temp==NULL)
return 0;
else
{
if (List->head!=NULL && List->tail!=NULL)
{
Envelope *A=List->tail;
List->tail->Next=Temp;
Temp->Next=NULL;
Temp->Previous=A;
List->tail=Temp;
return 1;
}
else
{
List->head=Temp;
List->tail=Temp;
Temp->Next=NULL;
Temp->Previous=NULL;
return 1;
}
}
}
Envelope* K_Dequeue_MsgEnv(msg_env_Q* List)
{
if (List->head!= NULL && List->tail!=NULL)
{
Envelope *A=List->head;
if (List->head->Next!=NULL)
{
List->head=List->head->Next;
List->head->Previous=NULL;
A->Next=NULL;
return A;
}
else
{
printf("TEST2\n");
List->head=NULL;
List->tail=NULL;
return A;
}
}
else
return NULL; //ERROR as A will point to NULL
}
NewPCB* K_Search_Dequeue (int PID,QueuePCB * List)
{
if (List->Head!=NULL)
{
NewPCB *A=List->Head;
while (PID!=A->ProcID)
{
if (A->Next==NULL)
return NULL;
A=A->Next;
}
if (A->Next==NULL && A->Previous!=NULL)
{
NewPCB* Temp=A->Previous;
A->Previous=NULL;
Temp->Next=NULL;
return A;
}
else if (A->Previous==NULL && A->Next!=NULL)
{
NewPCB* Temp=A->Next;
Temp->Previous=NULL;
A->Next=NULL;
return A;
}
else if (A->Next==NULL && A->Previous==NULL)
{
List->Head=NULL;
List->Tail=NULL;
return A;
}
else
{
NewPCB* Temp=A->Next;
NewPCB* Temp2=A->Previous;
A->Next=NULL;
A->Previous=NULL;
Temp2->Next=Temp;
Temp->Previous=Temp2;
return A;
}
}
else
return NULL;
}
NewPCB * K_Dequeue_PCB (msg_env_Q* List)
{
if (List->head!=NULL && List->tail!=NULL)
{
printf("Entered If statement\n");
NewPCB *Temp=List->head;
if (List->head->Next==NULL)
{
List->head=NULL;
List->tail=NULL;
return Temp;
}
else
{
List->head=List->head->Next;
List->head->Previous=NULL;
Temp->Next=NULL;
}
return Temp;
}
else
return NULL; //ERROR
}
//CONTEXT SWITCH
void context_switch (jmp_buf *previous, jmp_buf *next) //check parameter ???????????
{
int return_val =setjmp(previous);
if (return_val==0)
longjmp(next,1);
longjmp (previous,return_val);
}
//PROCESS_SWITCH
void process_switch() //NEED RELEASE PROCESSOR ??????????
{
int i;
for (i=0;i<4;i++)
{
if (ReadyQueue[i]->Head!=NULL)
break;
}
NewPCB*NEXT=K_Dequeue_PCB (ReadyQueue[i]);
// context_swtich (current_process->jbContext,NEXT->jbContext);
current_process->State=1;
K_Enqueue_PCB (current_process,ReadyQueue[current_process->Priority]);
current_process=NEXT;
current_process->State=4;
NEXT=NULL;
}
//TRACE ARRAYS
void K_add_to_trace_array (int trace_type, int sender_id, int destination_id, int message_type)
{
// trace_type=1 means SEND and trace_type=0 means recieve
if (trace_type==1)
{
if (Send_Trace_Array_Counter <=15)
{
Send_Trace_Array[Send_Trace_Array_Counter]->SenderID=sender_id;
Send_Trace_Array[Send_Trace_Array_Counter]->DestintionID=destination_id;
// Send_Trace_Array [Send_Trace_Array_Counter][2]=time(NULL); //??????????????
Send_Trace_Array[Send_Trace_Array_Counter]->Msg_Type=message_type;
Send_Trace_Array_Counter++;
}
else
{
Send_Trace_Array_Counter =0;
K_add_to_trace_array (trace_type, sender_id, destination_id, message_type);
}
}
else
{
if (Recieve_Trace_Array_Counter <=15)
{
Recieve_Trace_Array[Recieve_Trace_Array_Counter]->SenderID=sender_id;
Recieve_Trace_Array[Recieve_Trace_Array_Counter]->DestintionID=destination_id;
// Recieve_Trace_Array [Recieve_Trace_Array_Counter][2]=time(NULL); //???????????
Recieve_Trace_Array[Recieve_Trace_Array_Counter]->Msg_Type=message_type;
Recieve_Trace_Array_Counter++;
}
else
{
Recieve_Trace_Array_Counter =0;
K_add_to_trace_array (trace_type, sender_id, destination_id, message_type);
}
}
}
//INTERPROCESS COMMUNICATION
int K_send_message (int destination_pid, Envelope * msg_Envelope)
{
if (msg_Envelope!=NULL)
{
NewPCB *Temp=get_PCB(destination_pid);
if (Temp!=NULL)
{
msg_Envelope->SenderID=current_process->ProcID;
printf("%d\n",msg_Envelope->SenderID);
msg_Envelope->DestinationID=Temp->ProcID;
printf("%d\n",msg_Envelope->DestinationID);
K_add_to_trace_array (1,current_process->ProcID, msg_Envelope->DestinationID,msg_Envelope->Msg_Type); //message_type ??????????
Envelope* AB=K_Dequeue_MsgEnv(current_process->Own);
int A;
A=K_Enqueue_MsgEnv (AB, Temp->recievelist);
printf("sender id %d dest id%d\n",Temp->recievelist->head->SenderID,Temp->recievelist->head->DestinationID);
if (Temp->State==3)
{
Temp->State=1;
int B;
B=K_Enqueue_PCB(Temp, ReadyQueue[Temp->Priority]);
return (A && B);
}
return A;
}
else
return 0; //ERROR
}
else
{
//DISPLAY ERROR
return 0;
}
}
Envelope* K_recieve_message ()
{
// printf("FUCK U SANJITH\n");
if (current_process->recievelist->head!=NULL)
{
Envelope *Temp=K_Dequeue_MsgEnv(current_process->recievelist);
if (Temp!=NULL)
{
K_add_to_trace_array (0,Temp->SenderID, Temp->DestinationID,Temp->Msg_Type); //message_type ?????????
if (current_process->State==3)
{
K_Enqueue_PCB(current_process, ReadyQueue[current_process->Priority]);
current_process->State=1;
}
return Temp;
}
else
return NULL;
}
else
{
current_process->State=3;
K_Enqueue_PCB(current_process,Blocked_On_Resources[current_process->Priority]);
return NULL;
}
}
//MESSAGE MANAGEMENT
Envelope * K_request_msg_env ()
{
if (Free_Env_Queue->head==NULL)
{
// if (current_process->Priority==i-process-PRIORITY) //check for i-process using the PID ????????
// return NULL;
// else
// {
int A;
A=K_Enqueue_PCB (current_process,Blocked_On_Envelope[current_process->Priority]);
// process_switch ();
current_process->State=2;
return NULL;
// }
}
else
{
Envelope* Temp=K_Dequeue_MsgEnv(Free_Env_Queue);
K_Enqueue_MsgEnv(Temp,current_process->Own);
Free_Env_Queue->free_msg_counter--;
if (current_process->State==2)
{
current_process->State=1;
NewPCB* A=K_Dequeue_PCB(Blocked_On_Envelope[current_process->Priority]);
K_Enqueue_PCB(current_process,ReadyQueue[A->Priority]);
}
return Temp;
}
}
int K_release_msg_envelope (Envelope * msg_Envelope)
{
int k,l;
l=-1;
for (k=0;k<4;k++)
{
l=l+1;
if (Blocked_On_Envelope[l]->Head!=NULL)
break;
}
if (Blocked_On_Envelope[l]->Head!=NULL)
{
NewPCB *Temp=K_Dequeue_PCB(Blocked_On_Envelope[l]);
Temp->State=1;
K_Dequeue_MsgEnv(current_process->Own);
int A=K_Enqueue_MsgEnv(msg_Envelope,Temp->Own);
int B=K_Enqueue_PCB(Temp,ReadyQueue[Temp->Priority]);
return (A && B);
}
else
{
int A=K_Enqueue_MsgEnv (msg_Envelope, Free_Env_Queue);
K_Dequeue_MsgEnv(current_process->Own);
Free_Env_Queue->free_msg_counter++;
return A;
}
}
//PROCESSOR MANAGEMENT
int K_release_processor ()
{
current_process->State=1;
int A=K_Enqueue_PCB(current_process,ReadyQueue[current_process->Priority]);
process_switch();
return A;
}
//NULL PROCESS
void null_process()
{
while (1);
{
K_release_processor();
}
}
/*
int K_request_process_status (Envelope * msg_env_ptr)
{
if (msg_env_ptr==NULL)
return 0; //ERROR
else
{
sprintf(Status_Array,"");
int i;
for (i=0;i<3;i++)
{
NewPCB *Temp;
Temp=PCBList->head;
char* tempchar[20];
sprintf(tempchar,"%d %d %d,",Temp->ProcID,Temp->State,Temp->Priority);
strcat(Status_Array,tempchar);
Temp=Temp->Next;
strcpy(msg_env_ptr->Data,Status_Array);
return 1;
}
}
}
*/
//TERMINATE
//CHANGE PRIORITY
int K_change_priority (int new_Priority, int Target_Process_ID)
{
NewPCB *ptr=get_PCB (Target_Process_ID);
if (ptr!=NULL && new_Priority<=3)//&& ptr->ProcID!= ID of i-process && new_Priority <=3)
{
if (ptr->State ==1)
{
NewPCB* Temp=K_Search_Dequeue(ptr->ProcID,ReadyQueue[ptr->Priority]);
printf("%d\n",Temp->Priority);
Temp->Priority=new_Priority;
int A=K_Enqueue_PCB (Temp,ReadyQueue[Temp->Priority]);
return A;
}
else
{
ptr->Priority=new_Priority;
return 1;
}
}
else
{
ptr=NULL;
return 0;
}
}
int K_request_delay (int time_delay, int wakeup_code,Envelope* msg_env)
{
msg_env->Msg_Type=wakeup_code;
msg_env->clockticks=time_delay;
K_send_message(5000,msg_env); //5000=TIMER PROCESS ID
printf("message to requeust delay to timer process sent\n");
return 1;
}
/*
int K_send_console_chars (Envelope * MsgEnv)
{
if (MsgEnv!=NULL)
{
int A=MsgEnv->SenderID;
int B;
B=K_send_message (0011, MsgEnv); //0011 PID of CRT i-process
if (B==1)
{
Envelope * Temp=K_recieve_message();
if (Temp->Msg_Type==6) //CRT_akn=6
{
Temp->Msg_Type=2; //display_acknowledgement
int C=K_send_message (A,Temp);
if (C==1)
return 1;
else
return 0;
}
else
return 0;
}
else
return 0;
}
else
return 0;
}
int K_get_console_chars (Envelope * MsgEnv)
{
if (MsgEnv!=NULL)
{
int return_val=K_send_message (3000,MsgEnv); // 3000=KB i process id???????????????????????/
return return_val;
}
else
return 0; //DISPLAY ERROR ?????????????
}
int K_get_trace_buffers (Envelope* MsgEnv)
{
if (MsgEnv!=NULL)
{
}
else
return 0; //DISPLAY ERROR ????????????????
}
*/
|
C
|
#include "functions.h"
#include <stdio.h>
#include <math.h>
/***********************************/
/* 1 */
/***********************************/
int isFib(unsigned long n)
{
unsigned long curr, next, temp;
int i;
if(n == 0) return 1;
if(n == 1) return 2;
i = 2;
curr = 1;
next = 1;
while(next <= n) {
i++;
if(next == n) return i;
temp = next;
next += curr;
curr = temp;
}
return -1;
}
/***********************************/
/* 2 */
/***********************************/
unsigned int count_units(unsigned int num) {
unsigned int count;
switch(num) {
case 1: /* OnE */
case 3: /* thrEE */
case 4: /* fOUr */
case 5: /* fIvE */
case 7: /* sEvEn */
case 8: /* EIght */
case 9: /* nInE */
count = 2;
break;
case 2: /* twO */
case 6: /* sIx */
count = 1;
break;
default: count = 0; break; /* Impossible case! */
}
return count;
}
unsigned int count_tens(unsigned int num)
{
unsigned int tens, units;
if(num < 10) return count_units(num);
if(num < 20) { /* 10 to 19 */
/* tEn: 1, ElEvEn: 3, twElvE: 2, thIrtEEn: 3, fOUrtEEn: 4, fIftEEn: 3, sIxtEEn: 3, sEvEntEEn: 4, EIghtEEn: 4, nInEtEEn: 4 */
if(num == 10) return 1;
if(num == 12) return 2;
if(num == 11 || num == 13 || num == 15 || num == 16) return 3;
if(num == 14 || num == 17 || num == 18 || num == 19) return 4;
}
/* twEnty: 1, thIrty: 1, fOrty: 1, fIfty: 1, sIxty: 1, sEvEnty: 2, EIghty: 2, nInEty: 2 */
tens = num / 10;
units = num % 10;
if(tens >= 2 && tens <= 6) return 1 + count_units(units);
if(tens > 6 && tens <= 9) return 2 + count_units(units);
/* Should never reach here */
return 0;
}
unsigned int count_hundreds(unsigned int num)
{
return count_units(num/100) + ((num/100 > 0) ? /* hUndrEd */ 2 : 0) + count_tens(num % 100);
}
unsigned int count_millions(unsigned int num)
{
return (num > 0) ? count_hundreds(num) + /* mIllIOn */ 3 : 0;
}
unsigned int count_thousands(unsigned int num)
{
return (num > 0) ? count_hundreds(num) + /* thOUsAnd */ 3 : 0;
}
unsigned int count_vowels(unsigned long num) {
unsigned int remaining, thousands, millions;
/* 1 billion is a special case */
if(num == 1000000000) return 5; /* OnE bIllIOn */
/* Zero is a special case */
if(num == 0) return 2; /* zErO */
thousands = (num / 1000) % 1000;
millions = (num / 1000000) % 1000000;
remaining = num % 1000;
//printf("millions = %u\tthousands = %u\thundreds = %u\ttens = %u\tunits = %u\n", millions, thousands, remaining/100, (remaining %100)/10, remaining%10);
/* printf("Total count = %u\n", count_millions(millions) + count_thousands(thousands) + count_hundreds(hundreds)); */
return count_millions(millions) + count_thousands(thousands) + count_hundreds(remaining);
}
/***********************************/
/* 3 */
/***********************************/
unsigned int count_ones(long num) {
unsigned long n;
unsigned int count;
n = (unsigned long) num;
count = 0;
while(n != 0) {
count += n & 1;
n >>= 1;
}
return count;
}
/***********************************/
/* 4 */
/***********************************/
unsigned char get_byte(unsigned long n, unsigned int byte_num)
{
return (n >> (8 * (byte_num - 1))) & 0xff;
}
unsigned long swap_bytes(unsigned long n)
{
unsigned char b1, b2, b3, b4, b5, b6, b7, b8;
unsigned long res;
b1 = get_byte(n, 1);
b2 = get_byte(n, 2);
b3 = get_byte(n, 3);
b4 = get_byte(n, 4);
b5 = get_byte(n, 5);
b6 = get_byte(n, 6);
b7 = get_byte(n, 7);
b8 = get_byte(n, 8);
res = b7;
res = (res << 8) | b8;
res = (res << 8) | b5;
res = (res << 8) | b6;
res = (res << 8) | b3;
res = (res << 8) | b4;
res = (res << 8) | b1;
res = (res << 8) | b2;
return res;
}
/***********************************/
/* 5 */
/***********************************/
long a4_minus_b4(int a, int b)
{
return pow((double) a, 4) - pow((double) b, 4);
}
void printsqrt(float f){
printf("The square root of %f is %f\n", f, sqrt(f));
}
|
C
|
/*******************************************************************************
* Title : Table Initialization, Build and Maintenance
* Filename : tables.c
* Author : Itai Kimelman
* Version : 1.5.0
*******************************************************************************/
/** \file tables.c
* \brief This module contains function that maintain all the tables necessary to the assembler
* the tables are: the opcode table, the code image table, the data image table, te symbol table, and the external label list.
*/
/******************************************************************************
* Includes
*******************************************************************************/
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include "assembler.h"
/******************************************************************************
* Module Preprocessor Constants
*******************************************************************************/
#define NON_REAL_INDEX -1
/******************************************************************************
* Module Variable Definitions
*******************************************************************************/
/*tables*/
const cmd_info opcode_table[] = {{"add", 0, 1},{"addi", 10, 0},{"and", 0, 3},
{"andi", 12, 0},{"beq", 16, 0},{"bgt", 18, 0},
{"blt", 17, 0},{"bne", 15, 0},{"call", 32, 0},
{"jmp", 30, 0},{"la", 31, 0},{"lb", 19, 0},
{"lh", 23, 0},{"lw", 21, 0},{"move", 1, 1},
{"mvhi", 1, 2},{"mvlo", 1, 3},{"nor", 0, 5},
{"nori", 14, 0},{"or", 0, 4},{"ori", 13, 0},
{"sb", 20, 0},{"sh", 24, 0},{"stop", 63, 0},
{"sub", 0, 2},{"subi", 11, 0},{"sw", 22, 0}};
command_image *code_img;
data_image *data_img;
symbol_node *symbol_table;
ext_node *external_list;
/*other global vars*/
unsigned long code_img_length = 0; /*length of code image table*/
unsigned long data_img_length = 0; /*length of data image table*/
int data_exists =FALSE; /*indicates if there is data*/
extern unsigned long DC; /*current data counter*/
int entries_exist; /*indicates if there are labels that are entry points*/
/******************************************************************************
* Function Prototypes
*******************************************************************************/
void code_r_cmd(char *line, unsigned opcode, unsigned funct, cmd_in_binary *ptr_to_printable);
void code_i_cmd(char *line, unsigned opcode, cmd_in_binary *ptr_to_printable);
void code_j_cmd(char *line, unsigned opcode, cmd_in_binary *ptr_to_printable);
int complete_missing_info_i(unsigned long label_address, unsigned long IC);
int complete_missing_info_j(char *label, unsigned long label_address, unsigned long IC);
void code_db(char *line, int num_args, int pos);
void code_dh(char *line, int num_args, int pos);
void code_asciz(char *line, int pos);
void code_dw(char *line, int num_args, int pos);
/******************************************************************************
* Function Definitions
*******************************************************************************/
/******************************************************************************
* Function : initialize_tables();
*//**
* \section Description: this function initializes all the tables (besides the opcode table) to NULL,
* and all of the flags to FALSE accordingly
*******************************************************************************/
void initialize_tables(){
code_img = NULL;
data_img = NULL;
symbol_table = NULL;
external_list = NULL;
entries_exist = FALSE;
data_exists = FALSE;
}
/******************************************************************************
* Functions For Order Lines
*******************************************************************************/
/******************************************************************************
* Function : get_opcode(char *line);
*//**
* \section Description: gets the opcode for the current order line.
* used only when the assembler knows this line is an order line
* \param line - the current line
*
* \return the opcode for the current order line
*
*******************************************************************************/
unsigned get_opcode(char *line) {
if(order_index(line) == -1) {
return NON_REAL_OPCODE;
}
return opcode_table[order_index(line)].opcode;
}
/******************************************************************************
* Function : get_opcode(char *line);
*//**
* \section Description: gets the opcode for the current order line.
* used only when the assembler knows this line is an order line
* \param opcode - opcode of current order
* \return the expected number of operands for this line
*******************************************************************************/
int num_ops_expected(unsigned opcode) {
if(opcode == 0 || (opcode >=10 && opcode <=18)) {
return 3;
}
if(opcode == 1 || (opcode >=19 && opcode <=24)) {
return 2;
}
if(opcode >=30 && opcode <=32) {
return 1;
}
return 0;
}
/******************************************************************************
* Function : order_index(char *line);
*//**
* \section Description: gets the order info from opcode table by obtaining the correct index for it (see opcode table).
* if the order associated with this line is not in the opcode table,
* the assembler will report an error.
* used only when the assembler knows this line is non other than an order line.
* \param line - the current line
*
* \return the index for the current order line in the opcode table. -1 if order does not exist
*
*******************************************************************************/
int order_index(char *line) {
int i;
char *word = (char *)malloc(MAX_LINE+1);
scan_op(line, word);
for(i = 0; i < NUM_ORDERS; i++) {
if(strcmp(word,opcode_table[i].name)<0) {
fprintf(stderr, "error: order %s does not exist ", word);
free(word);
return NON_REAL_INDEX;
}
if(strcmp(word,opcode_table[i].name)==0) {
free(word);
return i;
}
}
fprintf(stderr, "error: order %s does not exist ", word);
free(word);
return NON_REAL_INDEX;
}
/******************************************************************************
* Function : get_funct(char *line);
*//**
* \section Description: gets the funct for the current order line.
* used only when the assembler knows this line is an order line
* \param line - the current line
*
* \return the funct for the current order line
*
*******************************************************************************/
unsigned get_funct(char *line) {
return opcode_table[order_index(line)].funct;
}
/******************************************************************************
* Function : cmd_to_info(char *line, unsigned IC);
*//**
* \section Description: this function is called only if there are no errors in this order line.
* it code the order line to machine code according to the bit fields
* given in the project instructions. the result will be held in the code image table
* \param line - the current line(points after optional label)
* \param IC - current instruction counter (see project instructions)
*******************************************************************************/
void cmd_to_info(char *line, unsigned IC) {
unsigned type;
unsigned opcode = get_opcode(line);
unsigned funct = get_funct(line);
cmd_in_binary printable;
command_image img;
line+= next_op(line,FALSE);
code_img_length++;
if(opcode<=1) {
type = R_CMD;
} else if(opcode<=24){
type = I_CMD;
} else type = J_CMD;
switch(type) {
case R_CMD:
code_r_cmd(line, opcode, funct, &printable);
break;
case I_CMD:
code_i_cmd(line, opcode, &printable);
break;
case J_CMD:
code_j_cmd(line, opcode, &printable);
break;
}
img.address = IC;
img.machine_code = printable;
code_img = (command_image*) realloc (code_img,(code_img_length)* sizeof(command_image));
alloc_check(code_img);
code_img[code_img_length-1] = img;
}
/******************************************************************************
* Function : code_r_cmd(char *line, unsigned opcode, unsigned funct, cmd_in_binary *ptr_to_printable);
*//**
* \section Description: this function codes R commands into machine code
* \param line - the current line(points after order)
* \param opcode - opcode of this R order
* \param funct - funct of this R order
* \param ptr_to_printable - pointer to a union with a divided word, which allows the assembler to divide orders into bytes later on
*******************************************************************************/
void code_r_cmd(char *line, unsigned opcode, unsigned funct, cmd_in_binary *ptr_to_printable) {
unsigned regs[] = {0,0,0};
int i;
r_command r_cmd;
r_cmd.opcode = opcode;
regs[0] = atoi(++line);
if(opcode == 0) {
for(i=1;i<3;i++) {
if(!empty(line))
line+=next_op(line,TRUE);
regs[i] = atoi(++line);
}
} else {
if(!empty(line))
line+=next_op(line,TRUE);
regs[2] = atoi(++line);
}
r_cmd.rs = regs[0];
r_cmd.rt = regs[1];
r_cmd.rd = regs[2];
r_cmd.funct = funct;
r_cmd.zeros = 0;
ptr_to_printable->r_cmd = r_cmd;
}
/******************************************************************************
* Function : code_i_cmd(char *line, unsigned opcode, cmd_in_binary *ptr_to_printable);
*//**
* \section Description: this function codes I commands into machine code
* \param line - the current line(points after order)
* \param opcode - opcode of this I order
* \param ptr_to_printable - pointer to a union with a divided word, which allows the assembler to divide orders into bytes later on
*******************************************************************************/
void code_i_cmd(char *line, unsigned opcode, cmd_in_binary *ptr_to_printable) {
int can_code_immed;
unsigned regs[] = {0,0,0};
int i;
i_command i_cmd;
i_cmd.opcode = opcode;
if(opcode <= 14 || (opcode>=19 && opcode<=24)) {
can_code_immed = TRUE;
} else can_code_immed = FALSE;
regs[0] = atoi(++line);
for(i=1;i<3;i++) {
line+= next_op(line,TRUE);
if(can_code_immed && i==1) {
i_cmd.immed=atoi(line);
} else regs[i] = atoi(++line);
}
/*happens if the command is an arithmetic or a load/save command:*/
if(regs[2]!=0) regs[1] = regs[2];
i_cmd.rs = regs[0];
i_cmd.rt = regs[1];
ptr_to_printable->i_cmd = i_cmd;
}
/******************************************************************************
* Function : code_j_cmd(char *line, unsigned opcode, cmd_in_binary *ptr_to_printable);
*//**
* \section Description: this function codes I commands into machine code
* \param line - the current line(points after order)
* \param opcode - opcode of this I order
* \param ptr_to_printable - pointer to a union with a divided word, which allows the assembler to divide orders into bytes later on
*******************************************************************************/
void code_j_cmd(char *line, unsigned opcode, cmd_in_binary *ptr_to_printable) {
j_command j_cmd;
j_cmd.opcode = opcode;
if(opcode <= 32) {
if(*line != '$') {
j_cmd.reg = FALSE;
} else {
j_cmd.reg = 1;
j_cmd.address = (unsigned)atoi(++line);
}
}
else {
j_cmd.reg = FALSE;
j_cmd.address = 0;
}
ptr_to_printable->j_cmd = j_cmd;
}
/******************************************************************************
* Function : complete_missing_info(char *label,char order_type, unsigned IC);
*//**
* \section Description: this function the missing info about conditional branch and J orders, where labels can show as operands
* and the assembler does not know their address when passing on the file for the 1st time
* given in the project instructions. the result will be held in the code image table.
*
* \errors: 1. external label is used in conditional branch orders.
* 2. label requested as an operand does not exist.
* 3. address difference in conditional branch orders is out of 16 bit range
* 4. algorithm flaw in assembler
*
* \param label - the label with unknown address
* \param order_type - 'I' or 'J' according to the order type
* \param IC - the current instruction counter
*
* \return TRUE if the info was completed successfully. FALSE if error was found
*******************************************************************************/
int complete_missing_info(char *label, char order_type, unsigned long IC) {
unsigned long label_address;
int i;
symbol_node *curr = symbol_table;
if(order_type == 'J') {
for(i = 0; i < code_img_length; i++) {
/*no info need to be completed. a register has already been coded into the binary image:*/
if(IC == code_img[i].address && code_img[i].machine_code.j_cmd.reg == TRUE)
return TRUE;
}
}
/*pass on the symbol table.*/
while(curr!=NULL) {
if(strcmp(label,curr->symbol) == 0) {
label_address = curr->address;
break;
}
curr = curr->next;
}
if(curr == NULL) {
fprintf(stderr,"error: label used as operand does not exist ");
return FALSE;
}
if(order_type == 'I') {
return complete_missing_info_i(label_address, IC);
}
if(order_type == 'J') {
return complete_missing_info_j(label, label_address, IC);
}
fprintf(stderr,"error: this should not happen (algorithm flaw in assembler) ");
return FALSE;
}
/******************************************************************************
* Function : complete_missing_info_i(unsigned long label_address, unsigned long IC);
*//**
* \section Description: this function completes the missing info about conditional branch orders.
* it has the address of the label that shows up as an operand, and it has the instruction counter
* of this order, so it just searches the array for the right order and completes it with the information it has
* \param label - the label that shows up as an operand in this J order
* \param IC - address of the conditional branch order
* \param label_address - address of the label that shows up as an operand in he order
* \return TRUE if no error was found (see \errors in complete_missing_info)
*******************************************************************************/
int complete_missing_info_i(unsigned long label_address, unsigned long IC) {
int i;
if(!in_lim((long int)(label_address-IC),16)) {
fprintf(stderr,"error: immed value should be in 16 bit limits ");
return FALSE;
}
if(label_address == 0) {
fprintf(stderr,"error: external symbol cannot be used in conditional branch orders ");
return FALSE;
}
for(i = 0; i < code_img_length; i++) {
if(code_img[i].address == IC) {
code_img[i].machine_code.i_cmd.immed = label_address - IC;
return TRUE;
}
}
fprintf(stderr,"error: this should not happen (algorithm flaw in assembler) ");
return FALSE;
}
/******************************************************************************
* Function : complete_missing_info_j(unsigned long label_address);
*//**
* \section Description: this function completes the missing info about J orders that are not "stop".
* it searches the array for this J order and puts the parameter "label_address"
* into the "address" field. if the label is external, it will be added to the external label list
* \param label_address - address of the label that shows up as an operand in he order
* \param IC - address of this J order
* \return TRUE if no error was found (see \errors in complete_missing_info)
*******************************************************************************/
int complete_missing_info_j(char *label, unsigned long label_address, unsigned long IC) {
int i;
if(label_address == 0) { /*external label*/
add_to_ext_list(IC,label);
}
for(i = 0; i < code_img_length; i++) {
if(code_img[i].address == IC) {
code_img[i].machine_code.j_cmd.address = label_address;
return TRUE;
}
}
fprintf(stderr,"error: this should not happen (algorithm flaw in assembler) ");
return FALSE;
}
/******************************************************************************
* Functions For Data Storage Directive Lines
*******************************************************************************/
/******************************************************************************
* Function : data_to_info(char *line);
*//**
* \section Description: this function is called only if there are no errors in this data directive line.
* it code the data directive line to machine code according to the project instructions.
* the result will be held in the data image table
* \param line - the current line(points after optional label)
*******************************************************************************/
void data_to_info(char *line) {
int d = is_data(line);
int len;
int num_args;
int pos = data_img_length; /* we start to update in this position */
if(data_exists == FALSE) {
data_exists = TRUE;
}
line+= next_op(line,FALSE);
if(d==3) {
len = asciz_len(line); /* num characters */
data_img_length += (len+1); /* placeholder for null term */
} else {
num_args = get_num_args(line); /* num numbers */
data_img_length += num_args;
}
data_img = (data_image*) realloc(data_img,data_img_length *(sizeof(data_image)));
alloc_check(data_img);
switch(d) {
case DB:
code_db(line,num_args,pos);
break;
case DH:
code_dh(line,num_args,pos);
break;
case ASCIZ:
code_asciz(line,pos);
break;
case DW:
code_dw(line,num_args,pos);
break;
}
}
/******************************************************************************
* Function : code_db(char *line, int num_args, int pos);
*//**
* \section Description: this function puts the data into the data image table for .db directives
* \param line - pointer to the current line after the directive
* \param num_args - the number of arguments in this line
* \param pos - index of the 1st cell in the data image table that I didnt code the data into
*******************************************************************************/
void code_db(char *line, int num_args, int pos) {
int i;
data_img[pos].machine_code.b = atoi(line);
data_img[pos].address=DC;
data_img[pos].bytes_taken = ONE_BYTE;
DC+=ONE_BYTE;
for(i=1;i< num_args;i++) {
line+=next_op(line,TRUE);
data_img[pos+i].machine_code.b = atoi(line);
data_img[pos+i].address=DC;
data_img[pos+i].bytes_taken = ONE_BYTE;
DC+=ONE_BYTE;
}
}
/******************************************************************************
* Function : code_dh(char *line, int num_args, int pos);
*//**
* \section Description: this function puts the data into the data image table for .dh directives
* \param line - pointer to the current line after the directive
* \param num_args - the number of arguments in this line
* \param pos - index of the the 1st cell in the data image table that I didnt code the data into
*******************************************************************************/
void code_dh(char *line, int num_args, int pos) {
int i;
data_img[pos].machine_code.dh.img = atoi(line);
data_img[pos].address=DC;
data_img[pos].bytes_taken = HALF_WORD;
DC+=HALF_WORD;
for(i=1;i< num_args;i++) {
line+=next_op(line,TRUE);
data_img[pos+i].machine_code.dh.img = atoi(line);
data_img[pos+i].address=DC;
data_img[pos+i].bytes_taken = HALF_WORD;
DC+=HALF_WORD;
}
}
/******************************************************************************
* Function : code_asciz(char *line, int num_args, int pos);
*//**
* \section Description: this function puts the data into the data image table for .asciz directives
* \param line - pointer to the current line after the directive
* \param pos - index of the 1st cell in the data image table that I didnt code the data into
*******************************************************************************/
void code_asciz(char *line, int pos) {
int i;
line++; /*skipping the opening '\"'*/
/*encoding all the chars of the directive to all the cells left but the last one*/
/*last cell in array saved for '\0'*/
for(i=pos;i<(data_img_length-1);i++) {
data_img[i].machine_code.b = (unsigned)(line[i]);
data_img[i].address = DC;
data_img[i].bytes_taken = ONE_BYTE;
DC+=ONE_BYTE;
}
/*adding the null character*/
data_img[i].machine_code.b = 0;
data_img[i].address = DC;
data_img[i].bytes_taken = ONE_BYTE;
DC+=ONE_BYTE;
}
/******************************************************************************
* Function : code_dw(char *line, int num_args, int pos);
*//**
* \section Description: this function puts the data into the data image table for .dw directives
* \param line - pointer to the current line after the directive
* \param num_args - the number of arguments in this line
* \param pos - index of the 1st cell in the data image table that I didnt code the data into
*******************************************************************************/
void code_dw(char *line, int num_args, int pos) {
int i;
data_img[pos].machine_code.dw.img = atol(line);
data_img[pos].address=DC;
data_img[pos].bytes_taken = WORD;
DC+=WORD;
for(i=1;i< num_args;i++) {
line+=next_op(line,TRUE);
data_img[pos+i].machine_code.dw.img = atol(line);
data_img[pos+i].address=DC;
data_img[pos+i].bytes_taken = WORD;
DC+=WORD;
}
}
/******************************************************************************
* Function : update_data_img(unsigned ICF);
*//**
* \section Description: at the end of the 1st pass, to maintain continuity in addresses,
* ICF (see pass_one.c) is added to each address in the data table
* \param ICF - the final value of IC (see pass_one.c)
*******************************************************************************/
void update_data_img(unsigned ICF) {
int i;
for(i=0;i<data_img_length;i++)
data_img[i].address+=ICF;
}
/******************************************************************************
* Function : create_symbol(symbol_node *dest,unsigned address, char *symbol, int attribute, int is_entry);
*//**
* \section Description: this function creates a symbol_node (ready to add to the symbol table)
* with the attributes given. for explanation about each attribute ot the symbol, see assembler.h
* \param dest - pointer to the result. must be allocated memory to it before using this function
*******************************************************************************/
void create_symbol(symbol_node *dest, unsigned address, char *symbol, int attribute, int is_entry) {
dest->next = NULL;
dest->address = address;
dest->attribute = attribute;
strcpy(dest->symbol, symbol);
dest->is_entry = is_entry;
}
/******************************************************************************
* Function : add_symbol(unsigned address, char *symbol, int attribute, int is_entry);
*//**
* \section Description: this function adds the symbol represented by the parameters given to the symbol table.
* for explanation about each attribute ot the symbol, see assembler.h.
* an error will e detected if the assembler will try to add a symbol with an identical name to another symbol in the table
* \return FALSE if error occurs, TRUE if the symbol was added successfully
*******************************************************************************/
int add_symbol(unsigned address, char *symbol, int attribute, int is_entry) {
symbol_node *node;
symbol_node *curr;
node = (symbol_node*)malloc(sizeof(symbol_node));
node->symbol = (char*) malloc (MAX_LABEL+1);
alloc_check(node);
alloc_check(node->symbol);
create_symbol(node, address ,symbol ,attribute ,is_entry);
if (symbol_table == NULL) {
symbol_table = node;
return TRUE;
}
curr = symbol_table;
while(curr!=NULL) {
if(strcmp((node->symbol),(curr->symbol))==0) {
fprintf(stderr, "symbol (%s) already exists, and cannot be used twice ", node->symbol);
free(node->symbol);
free(node);
return FALSE;
}
curr = curr->next;
}
curr = symbol_table;
while(curr->next!=NULL)
curr = curr->next;
curr->next = node;
return TRUE;
}
/******************************************************************************
* Function : add_ent(char *symbol);
*//**
* \section Description: this function is called when an entry point has been detected,
* it sees if the symbol does ont exist, or if it is external. if it is one of thw two,
* the assembler will report an error. otherwise, it will turn on the "is_entry" flag in the correct symbol_node
* in the symbol table.
*
* \param symbol - the name of the symbol
* \return TRUE is the symbol can be an entry, FALSE if an error was found
*******************************************************************************/
int add_ent(char *symbol) {
symbol_node *curr = symbol_table;
if(entries_exist == FALSE)
entries_exist = TRUE;
while(curr!=NULL) {
if(strcmp(curr->symbol,symbol) == 0) {
/*don't need a loop. there is only one attribute*/
if(curr->attribute == EXTERNAL) {
fprintf(stderr,"error: this symbol cannot be an entry and external at the same time ");
return FALSE;
}
curr->is_entry = TRUE;
return TRUE;
}
curr = curr->next;
}
fprintf(stderr,"error: the symbol requested as an entry point does not exist ");
return FALSE;
}
/******************************************************************************
* Function : update_symbol_table(unsigned ICF);
*//**
* \section Description: at the end of the 1st pass, to maintain continuity in addresses,
* ICF (see pass_one.c) is added to each address of a symbol that has the attribute "data"
* in the symbol table.
* \param ICF - the final value of IC (see pass_one.c)
*******************************************************************************/
void update_symbol_table(unsigned long ICF) {
symbol_node *curr = symbol_table;
while(curr != NULL) {
if(curr->attribute == DATA) {
curr->address+=ICF;
}
curr = curr->next;
}
}
/******************************************************************************
* Function : create_ext_node(ext_node *dest,unsigned address, char *label);
*//**
* \section Description: this function creates an ext_node (ready to add to the external label list)
* with the attributes given. for explanation about each attribute ot the external label, see assembler.h
* \param dest - pointer to the result. must be allocated memory to it before using this function
*******************************************************************************/
void create_ext_node(ext_node *dest,unsigned address, char *label) {
dest->address = address;
strcpy(dest->label,label);
dest->next = NULL;
}
/******************************************************************************
* Function : add_to_ext_list(unsigned address, char *label);
*//**
* \section Description: this function adds the external label represented by the parameters given to the external label list.
* for explanation about each attribute ot the external label, see assembler.h
*******************************************************************************/
void add_to_ext_list(unsigned address, char *label) {
ext_node *node;
ext_node *curr = external_list;
node = (ext_node*) malloc(sizeof(ext_node));
node->label = (char*) malloc(MAX_LABEL+1);
alloc_check(node);
alloc_check(node->label);
create_ext_node(node,address,label);
if(external_list == NULL) {
external_list = node;
return;
}
while(curr->next!=NULL)
curr = curr->next;
/*we are on the last node*/
curr->next = node;
}
/*************** END OF FUNCTIONS ***************************************************************************/
|
C
|
/*
**replace strings of blanks with tabs and blanks
*/
#include<stdio.h>
#define TABINC 15 //tab increment size, that means tab character will appear after 8 positions every time
main(){
int c, nb, nt, pos;
nb = 0; //num of blanks necessary
nt = 0; //num of tabs necessary
for(pos = 1;(c = getchar()) != EOF; ++pos){
if(c == ' '){
if(pos % TABINC != 0)
++nb;
else{
nb = 0; //reset num of blanks
++nt; //one more tab
}
}else{
for( ; nt > 0; --nt)
putchar('\t'); //output tabs
if(c == '\t') //forget the blanks
nb = 0;
else //output blanks
for( ; nb > 0; --nb)
putchar(' ');
putchar(c);
if(c == '\n')
pos = 0;
else if(c == '\t')
pos = pos + (TABINC - (pos - 1) % TABINC) - 1;
}
}
}
|
C
|
#include <SDL.h>
#include "camera.h"
void move_camera(struct Camera *cam)
{
static const Uint8 *keyboardStates = NULL;
if (keyboardStates == NULL)
keyboardStates = SDL_GetKeyboardState(NULL);
if (keyboardStates[SDL_SCANCODE_W])
cam->y += 0.04f;
if (keyboardStates[SDL_SCANCODE_S])
cam->y -= 0.04f;
if (keyboardStates[SDL_SCANCODE_D])
cam->x += 0.04f;
if (keyboardStates[SDL_SCANCODE_A])
cam->x -= 0.04f;
if (keyboardStates[SDL_SCANCODE_F])
cam->z += 0.04f;
if (keyboardStates[SDL_SCANCODE_G])
cam->z -= 0.04f;
if (keyboardStates[SDL_SCANCODE_E])
cam->roll += 0.04f;
if (keyboardStates[SDL_SCANCODE_Q])
cam->roll += -0.04f;
if (keyboardStates[SDL_SCANCODE_UP])
cam->pitch -= 0.04f;
if (keyboardStates[SDL_SCANCODE_DOWN])
cam->pitch += 0.04f;
if (keyboardStates[SDL_SCANCODE_LEFT])
cam->rot_y += -0.04f;
if (keyboardStates[SDL_SCANCODE_RIGHT])
cam->rot_y += 0.04f;
}
static void handle_inputs(struct Entity *cube)
{
static const Uint8 *keyboardStates = NULL;
if (keyboardStates == NULL)
keyboardStates = SDL_GetKeyboardState(NULL);
if (keyboardStates[SDL_SCANCODE_UP])
cube->rot_x += -0.04f;
if (keyboardStates[SDL_SCANCODE_DOWN])
cube->rot_x += 0.04f;
if (keyboardStates[SDL_SCANCODE_LEFT])
cube->rot_y += -0.04f;
if (keyboardStates[SDL_SCANCODE_RIGHT])
cube->rot_y += 0.04f;
if (keyboardStates[SDL_SCANCODE_COMMA])
cube->rot_z += 0.04f;
if (keyboardStates[SDL_SCANCODE_PERIOD])
cube->rot_z += -0.04f;
if (keyboardStates[SDL_SCANCODE_EQUALS])
cube->scale += 0.04f;
if (keyboardStates[SDL_SCANCODE_MINUS])
cube->scale += -0.04f;
if (keyboardStates[SDL_SCANCODE_W])
cube->y += 0.04f;
if (keyboardStates[SDL_SCANCODE_S])
cube->y += -0.04f;
if (keyboardStates[SDL_SCANCODE_A])
cube->x += -0.04f;
if (keyboardStates[SDL_SCANCODE_D])
cube->x += 0.04f;
if (keyboardStates[SDL_SCANCODE_F])
cube->z += 0.04f;
if (keyboardStates[SDL_SCANCODE_G])
cube->z += -0.04f;
}
|
C
|
/* Copyright (C) 2004 Free Software Foundation.
Check that logb, logbf, logbl, ilogb, ilogbf and ilogbl
built-in functions compile.
Written by Uros Bizjak, 14th April 2004. */
/* { dg-do compile } */
/* { dg-options "-O2 -ffast-math" } */
extern double logb(double);
extern float logbf(float);
extern long double logbl(long double);
extern int ilogb(double);
extern int ilogbf(float);
extern int ilogbl(long double);
double test1(double x)
{
return logb(x);
}
float test1f(float x)
{
return logbf(x);
}
long double test1l(long double x)
{
return logbl(x);
}
int test2(double x)
{
return ilogb(x);
}
int test2f(float x)
{
return ilogbf(x);
}
int test2l(long double x)
{
return ilogbl(x);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <sys/time.h>
#include "header.h"
double calcMatMulTime(double* A, double* B, double* C, int N, int nRuns) {
double t_sum = 0;
struct timeval start, end;
for (int i = 0; i < nRuns; ++i) {
gettimeofday(&start, NULL);
matmul(A, B, C, N, N, N);
gettimeofday(&end, NULL);
double time = end.tv_sec - start.tv_sec + ((double) (end.tv_usec - start.tv_usec)) / 1000000;
t_sum += time;
}
return t_sum / nRuns;
}
int main() {
int nRuns = 5;
double* A = (double *) malloc(4096 * 4096 * sizeof(double));
double* B = (double *) malloc(4096 * 4096 * sizeof(double));
double* C = (double *) malloc(4096 * 4096 * sizeof(double));
randomArray(A, 4096 * 4096);
randomArray(B, 4096 * 4096);
int Ns[] = {512, 1024, 2048};
FILE* fp= fopen("./runtimes.txt", "w+");
for (int i = 0; i < 3; ++i) {
int N = Ns[i];
double time = calcMatMulTime(A, B, C, N, nRuns);
fprintf(fp, "runtime of %dx%d matmul: %lf seconds\n", N, N, time);
}
fclose(fp);
free(A);
free(B);
free(C);
return 0;
}
|
C
|
#include<stdio.h>
#include<pthread.h>
#include<unistd.h>
/*non blocking semaphore structure */
typedef struct
{
int value;
pthread_mutex_t mutex;
pthread_cond_t cond;
} blocking_semaphore;
typedef struct
{
int val;
int n;
} my_arg;
void initialise_sem(blocking_semaphore *S, int a)
{
pthread_mutex_lock(&(S->mutex));
S->value=a;
pthread_mutex_unlock(&(S->mutex));
}
/*wait() implementation */
void blocking_wait(blocking_semaphore *S)
{
pthread_mutex_lock(&(S->mutex));
while(S->value<=0)
{
pthread_cond_wait(&(S->cond), &(S->mutex));
//temporarily release the mutex lock and make the thread sleep until signalled
}
S->value--;
pthread_mutex_unlock(&(S->mutex));
//mutex lock while decremenenting the value of the semaphore to prevent race conditions
}
void blocking_signal(blocking_semaphore *S)
{
pthread_mutex_lock(&(S->mutex));
S->value++;
pthread_cond_broadcast(&(S->cond));
//waking up all the threads that have been waiting on this semaphore's comditional variable
pthread_mutex_unlock(&(S->mutex));
//mutex lock while incremenenting the value of the semaphore to prevent race conditions
}
blocking_semaphore dining_room;
blocking_semaphore forks[1000];
blocking_semaphore sauce_bowls[2];//all the required semaphores
int diningroom=0; int forkTaken[1000]; int sauceBowlTaken[2]; //all shared variables
void * philosopher(void * num) //this is the function allotted to each philosopher thread
{
int phil=((my_arg *)num)->val;;
int n=((my_arg *)num)->n;
blocking_wait(&dining_room); //try to enter dining room
diningroom++;
printf("\nP%d has entered room",phil);
blocking_wait(&forks[phil]); //try to take i-th fork
forkTaken[phil]++;
printf("\nP%d has received F%d",phil,phil);
blocking_wait(&forks[(phil+1)%n]); //try to take i+1 th fork
forkTaken[(phil+1)%n]++;
printf("\nP%d has received F%d",phil,(phil+1)%n);
blocking_wait(&sauce_bowls[0]); //try to take first bowl
sauceBowlTaken[0]++;
printf("\nP%d has received B%d",phil,1);
sauceBowlTaken[1]++;
blocking_wait(&sauce_bowls[1]); //try to take second bowl
printf("\nP%d has received B%d",phil,2);
sleep(1); //eating
printf("\nP%d has finished eating",phil);
sauceBowlTaken[1]--;
blocking_signal(&sauce_bowls[1]); //release 2nd bowl
printf("\nP%d has released B%d",phil,2);
sauceBowlTaken[0]--;
blocking_signal(&sauce_bowls[0]); //release 1st bowl
printf("\nP%d has released B%d",phil,1 );
forkTaken[(phil+1)%n]--;
blocking_signal(&forks[(phil+1)%n]); //release i+1th fork
printf("\nP%d has released F%d",phil,(phil+1)%n);
forkTaken[phil]--;
blocking_signal(&forks[phil]); //release ith fork
printf("\nP%d has released F%d",phil,phil);
diningroom--;
blocking_signal(&dining_room); //leave dining room
printf("\nP%d has left room",phil);
}
//implementation signal_printVal for debugging
void signal_printVal(blocking_semaphore *S)
{
printf("%d\n",S->value);
}
int main()
{
int n;
printf("Enter number of philosophers(>=2):");
scanf("%d",&n);
//initialse shared variables
diningroom=0; //0 people in dining room
for(int i=0;i<n;i++)
{
forkTaken[i]=0; //fork not taken yet
}
sauceBowlTaken[0]=0; sauceBowlTaken[1]=0; //sauce bowls not taken yet;
//array of philosopher threads, array of my_args to pass n and i
pthread_t philosophers[n]; my_arg a[n];
//initialising all the semaphores
initialise_sem(&dining_room,n-1);
initialise_sem(&sauce_bowls[0],1);
initialise_sem(&sauce_bowls[1],1);
for(int i=0;i<n;i++) {initialise_sem(&forks[i],1); a[i].val=i; a[i].n=n;}
for(int i=0;i<n;i++)pthread_create(&philosophers[i],NULL,philosopher,(void *)&a[i]);
/*int i=0;
while(1)
{
pthread_create(&philosophers[i%n],NULL,philosopher,(void *)&a[i%n]);
i++;
} */
for(int i=0;i<n;i++)pthread_join(philosophers[i],NULL);
return 0;
}
|
C
|
#include "g_hash_table_utils.h"
void g_hash_table_iterate(GHashTable *table, g_hash_table_iterate_cb cb) {
g_assert_nonnull(table);
GHashTableIter iter;
gpointer key, value;
g_hash_table_iter_init(&iter, table);
while (g_hash_table_iter_next(&iter, &key, &value)) {
cb(key, value);
}
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>
typedef struct Tarea {
int TareaID; //Numerado en ciclo iterativo
char *Descripcion; //
int Duracion; // entre 10 – 100
}Tarea;
typedef struct Tnodo{
Tarea tarea;
struct Tnodo *siguiente;
}Tnodo;
Tnodo *crearLista();
Tnodo *CrearNodo(int id);
void CargarLista(Tnodo **cabeza, int tama);
void Mostrar(Tnodo *lista, Tnodo **realizadas, Tnodo **pendientes);
Tnodo *quitarNodo(Tnodo **cab);
void verLista(Tnodo *lista);
int main(){
Tnodo *ListaTareas = crearLista();
Tnodo *realizadas = crearLista();
Tnodo *pendientes = crearLista();
int cant_tareas;
srand(time(NULL));
printf("Ingrese el numero de tareas:\n");
scanf("%d",&cant_tareas);
CargarLista(&ListaTareas,cant_tareas);
Mostrar(ListaTareas,&realizadas,&pendientes);
printf("lista pendiente");
verLista(pendientes);
system("pause");
return 0;
}
Tnodo *crearLista(){
return NULL;
}
Tnodo *CrearNodo(int id){
Tnodo *aux;
char desc[100];
aux = (Tnodo*)malloc(sizeof(Tnodo));
aux->tarea.TareaID = id;
printf("\ningrese una descripcion de la tarea numero %d\n",id);
fflush(stdin);
gets(desc);
fflush(stdin);
//necesito reservar memoria para el putnero descripcion
aux->tarea.Descripcion=(char*)malloc(sizeof(char)* strlen(desc));
strcpy(aux->tarea.Descripcion,desc);
fflush(stdin);
aux->tarea.Duracion = rand() % 90;
aux->siguiente=NULL;
return aux;
}
void CargarLista(Tnodo **cabeza, int tama){//inicia al comiezo de la lista
Tnodo *nuevo;
for (int i = 0; i < tama; i++)
{
//creamos un nodo que apunta a null
nuevo = CrearNodo(i+1);
//insertamos el nodo a la lista
nuevo->siguiente = *cabeza;
*cabeza = nuevo;
}
}
Tnodo *quitarNodo(Tnodo **cab){
Tnodo *anterior=crearLista();
anterior = *cab;
*cab = anterior->siguiente;
anterior->siguiente = NULL;
return anterior;
}
void verLista(Tnodo *lista){
Tnodo *aux = lista;
while (lista!=NULL)
{
/* code */
printf("Id: %d\n",aux->tarea.TareaID);
printf("Descripcion: %s\n",aux->tarea.Descripcion);
printf("Duracion: %d\n",aux->tarea.Duracion);
printf("\n\n");
}
}
void Mostrar(Tnodo *lista, Tnodo **realizadas, Tnodo **pendientes){
Tnodo *actual;
Tnodo *nuevo = crearLista();
int respuesta;
printf("***Contenido de la lista***\n");
for ( actual = lista; actual !=NULL; actual=actual->siguiente)
{
printf("Id: %d\n",actual->tarea.TareaID);
printf("Descripcion: %s\n",actual->tarea.Descripcion);
printf("Duracion: %d\n",actual->tarea.Duracion);
printf("\n\n");
printf("Se realizo esta tarea? 1.(si) 2.(no)");
do
{
scanf("%d",&respuesta);
} while (respuesta!=1 && respuesta!=2);
if (respuesta==1)
{
nuevo = quitarNodo(&lista);
nuevo = *realizadas;
*realizadas = nuevo->siguiente;
}else{
nuevo = quitarNodo(&lista);
*pendientes = (Tnodo*)malloc(sizeof(Tnodo));
nuevo = *pendientes;
*pendientes = nuevo->siguiente;
}
}
}
|
C
|
#include <stdio.h>
int s[1000];
int e[1000];
int main(void)
{
int N;
int i,j;
int box, box1;
int comp = 0;
int count = 1;
int pre;
scanf("%d",&N);
for(i=1; i<= N; i++)
{
scanf("%d %d", &s[i], &e[i]);
}
for(i=1; i<= N; i++){
for(j=1; j<= N; j++){
if(s[i] < s[j])
{
box = s[i];
s[i] = s[j];
s[j] = box;
}
if(e[i] < e[j])
{
box = e[i];
e[i] = e[j];
e[j] = box;
}
}
}
j = 1;
for(i = 1; i <= N; i++ )
{
if(s[i]>e[j])
{
count++;
j++;
while(s[i]>e[j]) j++;
}
}
printf("%d\n", count);
return 0;
}
|
C
|
/*
** EPITECH PROJECT, 2020
** 0
** File description:
** 0
*/
#include "my.h"
int check_walls_up_right(object_t *pos, int i)
{
if (pos->arr[pos->x_pos[i] - 1][pos->x_pos[i + 1]] == '#' &&
pos->arr[pos->x_pos[i]][pos->x_pos[i + 1] + 1] == '#' ||
pos->arr[pos->x_pos[i] - 1][pos->x_pos[i + 1]] == 'X' &&
pos->arr[pos->x_pos[i]][pos->x_pos[i + 1] + 1] == 'X' ||
pos->arr[pos->x_pos[i] - 1][pos->x_pos[i + 1]] == '#' &&
pos->arr[pos->x_pos[i]][pos->x_pos[i + 1] + 1] == 'X' ||
pos->arr[pos->x_pos[i] - 1][pos->x_pos[i + 1]] == 'X' &&
pos->arr[pos->x_pos[i]][pos->x_pos[i + 1] + 1] == '#')
return 1;
}
int check_walls_up_left(object_t *pos, int i)
{
if (pos->arr[pos->x_pos[i] - 1][pos->x_pos[i + 1]] == '#' &&
pos->arr[pos->x_pos[i]][pos->x_pos[i + 1] - 1] == '#' ||
pos->arr[pos->x_pos[i] - 1][pos->x_pos[i + 1]] == 'X' &&
pos->arr[pos->x_pos[i]][pos->x_pos[i + 1] - 1] == 'X' ||
pos->arr[pos->x_pos[i] - 1][pos->x_pos[i + 1]] == '#' &&
pos->arr[pos->x_pos[i]][pos->x_pos[i + 1] - 1] == 'X' ||
pos->arr[pos->x_pos[i] - 1][pos->x_pos[i + 1]] == 'X' &&
pos->arr[pos->x_pos[i]][pos->x_pos[i + 1] - 1] == '#')
return 1;
}
int check_walls_down_right(object_t *pos, int i)
{
if (pos->arr[pos->x_pos[i] + 1][pos->x_pos[i + 1]] == '#' &&
pos->arr[pos->x_pos[i]][pos->x_pos[i + 1] + 1] == '#' ||
pos->arr[pos->x_pos[i] + 1][pos->x_pos[i + 1]] == 'X' &&
pos->arr[pos->x_pos[i]][pos->x_pos[i + 1] + 1] == 'X' ||
pos->arr[pos->x_pos[i] + 1][pos->x_pos[i + 1]] == '#' &&
pos->arr[pos->x_pos[i]][pos->x_pos[i + 1] + 1] == 'X' ||
pos->arr[pos->x_pos[i] + 1][pos->x_pos[i + 1]] == 'X' &&
pos->arr[pos->x_pos[i]][pos->x_pos[i + 1] + 1] == '#')
return 1;
}
int check_walls_down_left(object_t *pos, int i)
{
if (pos->arr[pos->x_pos[i] + 1][pos->x_pos[i + 1]] == '#' &&
pos->arr[pos->x_pos[i]][pos->x_pos[i + 1] - 1] == '#' ||
pos->arr[pos->x_pos[i] + 1][pos->x_pos[i + 1]] == 'X' &&
pos->arr[pos->x_pos[i]][pos->x_pos[i + 1] - 1] == 'X' ||
pos->arr[pos->x_pos[i] + 1][pos->x_pos[i + 1]] == '#' &&
pos->arr[pos->x_pos[i]][pos->x_pos[i + 1] - 1] == 'X' ||
pos->arr[pos->x_pos[i] + 1][pos->x_pos[i + 1]] == 'X' &&
pos->arr[pos->x_pos[i]][pos->x_pos[i + 1] - 1] == '#')
return 1;
}
int check_all_walls(object_t *pos)
{
int k = 0;
for (int i = 0; pos->x_pos[i] != -1; i += 2)
{
if (check_walls_up_right(pos, i) == 1 ||
check_walls_up_left(pos, i) == 1 ||
check_walls_down_left(pos, i) == 1 ||
check_walls_down_right(pos, i) == 1)
k++;
}
return k;
}
|
C
|
#include <stdio.h>
void main()
{
int x,y,z,a;
while(1){
printf("enter 1 to continue or 0 to exit to window:!\n");
printf("enter your choice!\n");
scanf("%d",&a);
switch(a){
case 1:
printf("enter first integer!\n");
scanf("%d",&x);
printf("enter second integer!\n");
scanf("%d",&y);
z=x+y;
printf("Addition is: %d \n", z);
break;
case 0:
exit(0);
default:
printf("enter correctly \n");
}
}
}
|
C
|
#include <stdio.h>
// 数组的传递不可能通过拷贝的方式传递。在传递的时候,数组名仅充当地址使用。
// 数组三要素: 起始地址,步长,范围
// 数组名是一个指针,包含起始地址和步长
// 数组传递的时候要传数组名和范围
void disArray(int arr[], int n);
int main()
{
int arr[] = {0, 2, 4, 6, 8, 10};
printf("main sizeof(arr) = %d\n", sizeof (arr));
disArray(arr, sizeof (arr) / sizeof (*arr)); // *arr == arr[0]
return 0;
}
void disArray(int arr[], int n)
{
printf("disArray sizeof(arr) = %d\n", sizeof(arr));
for (int i = 0; i < n; i++) {
printf("%d\t", *arr++); // *arr++ == *(arr++) == arr[i]
}
putchar(10);
}
|
C
|
/* Jason Black, Feb 22 1992
Input can come from stdin, from '-' or from a file named on the command line:
Flags: -dvi for use with dvitps PostScript files.
Usage:
ps2txt [-dvi] [-] [input_file.ps]
ps2txt.c extracts strings from a PostScript file. This version has been
modified to correctly deal with the oddities of PostScript files generated by
dvi-to-PostScript converters, so if you keep this and the original program
around, you might want to rename one of them.
VERSION: 1.1 Fixed bug dealing with comments.
1.2 By popular demand: put spaces between strings.
2.0 Fixed most problems of extraneous spaces and newlines
between strings.
added support for the ligatures ff, fi, fl, ffi, & ffl.
re-designed the control structures, and otherwise cleaned
up the code.
2.1 Put Qazi's original algorithm back in, and added -dvi flag to
use my more specific algorithm. Also by popular demand.
Re-wrote the command line parsing yet again.
History: Modified Qazi's program on Feb. 18 1992 so that it could do dvitps
files well. Posted to alt.sources. Got feedback requesting support
for regular PostScript files as well. Retrieved Qazi's original
source code, and put it back in on Feb. 22 1992. While the original
program concept and source code is from Iqbal Qazi, this version
has had enough modifications that I am claiming it as my own. Qazi's
sections are well marked if you want to see them.
Comments/suggestions to cloister@u.washington.edu
*/
#include <stdio.h>
#define Putc(x) putchar(x); /* makes some lines not exceed 80 chars. */
#define TRUE 1
#define FALSE 0
void dviparse(); /* function prototypes */
void psparse();
void main(argc, argv)
int argc;
char *argv[];
{
int i, /* everybody's favorite counter */
known_flag, /* used during command line parsing */
dvi_file = FALSE; /* true if -dvi option found on command line */
FILE *file, *source; /* input stream */
source = stdin; /* default input source */
for(i=1; i<argc; i++) /* parse command line args */
{
known_flag = FALSE;
if (strcmp(argv[i],"-dvi") == 0) /* is it a dvitps PostScript file? */
{
dvi_file = TRUE;
known_flag = TRUE;
}
if (strcmp(argv[i],"-") == 0) /* weirdo-user explicitly wants stdin */
{
source = stdin;
known_flag = TRUE;
}
if (!known_flag) /* must be the input file name */
{
if ((file=fopen(argv[i],"r")) != NULL )
source=file;
else
{
fprintf(stderr,"ps2txt: error opening file %s\n",argv[i]);
fprintf(stderr,"usage: ps2txt [-dvi] [-] [input_file.ps]\n");
exit(1);
}
}
}
if (dvi_file)
dviparse(source); /* use my algorithm */
else
psparse(source); /* use Iqbal's algorithm */
}
void dviparse(source)
FILE *source;
{
int ch, /* current character */
prev_ch = '\n', /* previously read character */
in_paren = FALSE, /* inside or outside of parentheses? */
b_flag = FALSE, /* true if previous character was ')' */
b_space = TRUE; /* true if a 'b' should produce a space */
char junk[80]; /* place to throw away comment lines */
while ((ch = fgetc(source)) != EOF)
{
if (ch == '\n') ch = fgetc(source); /* ignore newlines in input! */
if (in_paren) /* strings to print come inside parentheses */
switch(ch)
{
case ')' : in_paren--; b_flag=1; break; /* not in paren's anymore */
case '\n' : Putc(' '); break; /* <cr> = ' ' in parens */
case '\\' :
switch(ch=fgetc(source))
{
case '(' :
case ')' : Putc(ch); break; /* from \? */
case 't' : Putc('\t'); break; /* write a tab */
case 'n' : Putc('\n'); break; /* write a <cr> */
case '\\': Putc('"'); break; /* open quotes */
case '0' : switch(ch=fgetc(source))
{
case '1': switch(ch=fgetc(source))
{
case '3' : fputs("ff",stdout); break; /* from \01? */
case '4' : fputs("fi",stdout); break;
case '5' : fputs("fl",stdout); break;
case '6' : fputs("ffi",stdout); break;
case '7' : fputs("ffl",stdout); break;
default: fputs("\\01",stdout); Putc(ch); /* unknown code */
} break; /* from \0? */
default: fputs("\\0",stdout); Putc(ch); /* unknown code */
} break;
case '1' : case '2' : case '3' : case '4' :
case '5' : case '6' : case '7' : Putc('\\'); /* unknown code */
default: Putc(ch);
} break; /* from original switch */
default: Putc(ch);
}
else /* not in paren's */
switch(ch)
{
case '%' : fgets(junk, 80, source); break; /* toss out comments */
case '\n' : break; /* skip <cr>'s outside of parens */
case '-' : if (b_flag)
{
b_flag = 0; /* because now prev. char != ')' */
b_space = 0; /* but the number after ')' is negative, so no */
/* space in case the letter code is 'b'. */
/* the default is b_space = 1 */
} break;
case '(' : in_paren++; /* back in parens again */
switch(prev_ch) /* check prev char to see if we need a space */
{
case 'l' : case 'm' : case 'n' : case 'o' : /* not for these 8 */
case 'q' : case 'r' : case 's' : case 't' :
break;
case 'y' : Putc('\n'); break; /* need a newline */
case 'b' : if (b_space) Putc(' '); break; /* 'b' w/ a + number */
case 'a' : case 'c' : case 'd' : case 'e' :
case 'f' : case 'g' : case 'h' : case 'i' :
case 'j' : case 'k' : case 'x' : Putc(' '); break;
default: break;
}
b_space = 1; /* reset flag to default for next time */
break;
default: b_flag = 0; break; /* junk stuff not in parens */
}
prev_ch=ch; /* remember this char in case !in_paren and next ch = '(' */
}
}
void psparse(source) /* Iqbal's original uncommented program, unmodified */
FILE *source; /* except for stripping i/o stuff off the top, etc: */
{
char *str;
char junk[80];
int ch, para=0, last=0;
while ((ch=fgetc(source)) != EOF)
{
switch (ch)
{
case '%' : if (para==0) fgets(junk, 80, source);
else putchar(ch);
case '\n' : if (last==1) { puts(""); last=0; } break;
case '(' : if (para++>0) putchar(ch); break;
case ')' : if (para-->1) putchar(ch);
else putchar(' ');
last=1; break;
case '\\' : if (para>0)
switch(ch=fgetc(source))
{
case '(' :
case ')' : putchar(ch); break;
case 't' : putchar('\t'); break;
case 'n' : putchar('\n'); break;
case '\\': putchar('\\'); break;
case '0' : case '1' : case '2' : case '3' :
case '4' : case '5' : case '6' : case '7' :
putchar('\\');
default: putchar(ch); break;
}
break;
default: if (para>0) putchar(ch);
}
}
}
|
C
|
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<math.h>
/************************************************************************************
* Jakub Zato *
*Wykonane: 06.12.2017 *
*Numer indeksu: 241504 *
*Program przetwarzajacy wybrany plik .pgm i zapisujacy go pod dowolna nazwa *
* *
************************************************************************************/
#define MAX 512 /* Maksymalny rozmiar wczytywanego obrazu */
#define DL_LINII 1024 /* Dlugosc buforow pomocniczych */
/************************************************************************************
* Funkcja wczytuje obraz PGM z pliku do tablicy *
* *
* \param[in] plik_we uchwyt do pliku z obrazem w formacie PGM *
* \param[out] obraz_pgm tablica, do ktorej zostanie zapisany obraz *
* \param[out] wymx szerokosc obrazka *
* \param[out] wymy wysokosc obrazka *
* \param[out] szarosci liczba odcieni szarosci *
* \return liczba wczytanych pikseli *
************************************************************************************/
int czytaj(FILE *plik_we,int obraz_pgm[][MAX],int *wymx,int *wymy, int *szarosci) {
char buf[DL_LINII]; /* bufor pomocniczy do czytania naglowka i komentarzy */
int znak; /* zmienna pomocnicza do czytania komentarzy */
int koniec=0; /* czy napotkano koniec danych w pliku */
int i,j;
/*Sprawdzenie czy podano prawidowy uchwyt pliku */
if (plik_we==NULL) {
fprintf(stderr,"Blad: Nie podano uchwytu do pliku\n");
return(0);
}
/* Sprawdzenie "numeru magicznego" - powinien by P2 */
if (fgets(buf,DL_LINII,plik_we)==NULL) /* Wczytanie pierwszej linii pliku do bufora */
koniec=1; /* Nie udalo sie? Koniec danych! */
if ( (buf[0]!='P') || (buf[1]!='2') || koniec) { /* Czy jest magiczne "P2"? */
fprintf(stderr,"Blad: To nie jest plik PGM\n");
return(0);
}
/* Pominiecie komentarzy */
do {
if ((znak=fgetc(plik_we))=='#') { /* Czy linia rozpoczyna sie od znaku '#'? */
if (fgets(buf,DL_LINII,plik_we)==NULL) /* Przeczytaj ja do bufora */
koniec=1; /* Zapamietaj ewentualny koniec danych */
} else {
ungetc(znak,plik_we); /* Gdy przeczytany znak z poczatku linii */
} /* nie jest '#' zwroc go */
} while (znak=='#' && !koniec); /* Powtarzaj dopoki sa linie komentarza */
/* i nie nastapil koniec danych */
/* Pobranie wymiarow obrazu i liczby odcieni szarosci */
if (fscanf(plik_we,"%d %d %d",wymx,wymy,szarosci)!=3) {
fprintf(stderr,"Blad: Brak wymiarow obrazu lub liczby stopni szarosci\n");
return(0);
}
/* Pobranie obrazu i zapisanie w tablicy obraz_pgm*/
for (i=0;i<*wymy;i++) {
for (j=0;j<*wymx;j++) {
if (fscanf(plik_we,"%d",&(obraz_pgm[i][j]))!=1) {
fprintf(stderr,"Blad: Niewlasciwe wymiary obrazu\n");
return(0);
}
}
}
return *wymx**wymy; /* Czytanie zakonczone sukcesem */
} /* Zwroc liczbe wczytanych pikseli */
/* Wyswietlenie obrazu o zadanej nazwie za pomoca programu "display" */
void wyswietl(char *n_pliku) {
char polecenie[DL_LINII]; /* bufor pomocniczy do zestawienia polecenia */
strcpy(polecenie,"display "); /* konstrukcja polecenia postaci */
strcat(polecenie,n_pliku); /* display "nazwa_pliku" & */
strcat(polecenie," &");
printf("%s\n",polecenie); /* wydruk kontrolny polecenia */
system(polecenie); /* wykonanie polecenia */
}
int zapisz(FILE *plik,int obraz_pgm[][MAX],int *wymx,int *wymy, int *szarosci) //Fukcja zapisujaca do wybranego pliku
{
int pixel=0; //zmienna pomocnicza
int cnt =0; //zmienna dzieki ktorej "ladniej sie zapisuje"
int x; //zmienne dzieki ktorym mozna latwo sie przemieszcac po tablicy
int y;
fprintf(plik,"P2\n%d %d\n%d\n",*wymx,*wymy,*szarosci); //zapisywanie "magicznej liczby"
for(y=0;y<*wymy;y++) //koljene zmienianie wartosci tablicy dwuwymiarowej
{
for(x=0;x<*wymx;x++)
{
pixel=obraz_pgm[y][x];
fprintf(plik,"%3d ",pixel);
if(pixel < 10) //warunki "uladniajace" zapis
fprintf(plik, " ");
if((pixel > 9) && (pixel < 100))
fprintf(plik, " ");
cnt += 4;
if(cnt > 67)
{
fprintf(plik,"\n");
cnt = 0;
}
}
}
return 0;
}
void progowaniec( int obraz_pgm[][MAX], int wymx, int wymy, int szarosci, int poziomp) //Funkcja progujaca czerni
{
int x, y;
for(y=0; y < wymy; y++)
for(x=0; x < wymx; x++)
if(obraz_pgm[y][x] <=poziomp) //warunek matematyczny dzialania funkcji
obraz_pgm[y][x] = 0;
}
void rozmyciepion( int obraz_pgm[][MAX], int wymx, int wymy, int radius) //funkcja rozmywajaca pionowo
{
int x, y,yp,ym;
int obrazL[MAX][MAX]; //tablica rozwiajujaca problem wczytywania argumentow spoza tablicy podstawowej
for(x=0; x < wymx; x++)
for(y=0; y < wymy; y++){
obrazL[y][x]=obraz_pgm[y][x]; //zapisywanie tablicy do tablicy pomocnicznej
ym=y-radius;
if(ym<0)ym=0; //sprawadznie czy nie wczytuje spoza tablicy
yp=y+radius;
if(yp>MAX)yp=MAX;
obraz_pgm[y][x] = (obrazL[ym][x] + obraz_pgm[y][x] + obraz_pgm[yp][x])/3 ; //warunek matemtyczny dzialnai funckji
}
}
void rozciaganieh( int obraz_pgm[][MAX], int wymx, int wymy, int *szarosci) //funckja rozciagajaca histogram
{
int x, y; //zmienne do "chodzenia" po tablicy
int min=255; //zmienna do sprawdzania minimum
int max=0; //zmienna do sprawdzania maksimum
*szarosci=255; //zmienienie zakresu obrazu
for(y=0; y< wymy; y++)
{
for(x=0; x< wymx; x++) //sprawdzanie minimum i maksimum w tablicy
{
if(obraz_pgm[y][x]<min)
min=obraz_pgm[x][y];
if(obraz_pgm[y][x]>max)
max=obraz_pgm[y][x];
}
}
for(y=0; y< wymy; y++)
{
for(x=0; x< wymx; x++)
{
obraz_pgm[y][x]=(obraz_pgm[y][x]-min)*(255/(max-min)); //warunek matematyczny dzialnia funckji
}
}
}
int main() {
int obraz[MAX][MAX] ; //tablica wczytujaca obraz
int wymx,wymy,odcieni; //podstawowe zmienne opisujace obraz
int odczytano = 0; //zmienna potrzebna do prototypu
FILE *plik; //deklaracja pliku
FILE *plik_wy; //jak wyzej
char nazwa[100]; //tablica na nazwe wejscia
char nazwa_wy[100]; //tablica na nazwe wyjscia
int poziomp=0; //zmienna do potrzebna do funkcji
int radius=0; //jak wyzej
char wybor[2]=" "; //zmienna pomocnicza w dzilaniu menu
/* /* Wczytanie zawartosci wskazanego pliku do pamieci PROTOTYP PROGRAMU
printf("Podaj nazwe pliku:\n");
scanf("%s",nazwa);
plik=fopen(nazwa,"r");
if (plik != NULL) { /* co spowoduje zakomentowanie tego warunku
odczytano = czytaj(plik,obraz,&wymx,&wymy,&odcieni);
}
/* Wyswietlenie poprawnie wczytanego obraza zewnetrznym programem
if (odczytano != 0)
wyswietl(nazwa);
/*Zapisywanie pliku
poziomp=122;
int radius=1;
rozciaganieh(plik,obraz,&wymx,&wymy,&odcieni);
fclose(plik);
wyswietl(nazwa);
printf("Podaj nazwe pliku do zapisu:\n");
scanf("%s",nazwa_wy);
plik=fopen(nazwa_wy,"w");
zapisz(plik,obraz,&wymx,&wymy,&odcieni);
fclose(plik);
wyswietl(nazwa_wy); */
printf("Witaj w programie do przetwarzanie obrazow!\n");
do //petla do wylaczanie programu
{
printf("1-odczyt\n2-przetwarzanie polprogowe czerni\n3-rozmycie pionowe\n4-rozciaganie histogramu\n5-wyswietl plik\n6-zapisz plik\n7-koniec");
scanf("%1s",wybor); //wczytywanie wyboru
switch(wybor[0]) //wybor dzialnia
{
case '1': //wczytywanie pliku
{
printf("Podaj nazwe pliku:\n");
scanf("%s",nazwa); //wczytywanie nazy pliku ktory chcemy wczytac
plik=fopen(nazwa,"r"); //otwieranie strumienia
if (plik != NULL)
{ /* co spowoduje zakomentowanie tego warunku */
odczytano = czytaj(plik,obraz,&wymx,&wymy,&odcieni);
fclose(plik); //zamykanie strumienia
}
break;
};
case '2': //progowanie czerni
{
printf("Podaj wartosc progowania(proponuje 122): ");
scanf("%d",&poziomp); //ustawenie poziomu progowania czerni
progowaniec(obraz,wymx,wymy,odcieni,poziomp);
break;
};
case '3': //rozmycie pionowe
{
printf("Podaj wartosc promienia: ");
scanf("%d",&radius); //ustawianie poziomu rozmycia
rozmyciepion(obraz,wymx,wymy,radius);
break;
};
case '4': //rozciaganie histogramu
{
rozciaganieh(obraz,wymx,wymy,&odcieni);
break;
};
case '5': //zapisywanie pliku
{
plik_wy=fopen("a","w"); //otwieranie strumienia i nazwa deafaultowa "a"
zapisz(plik_wy,obraz,&wymx,&wymy,&odcieni); //wczytywanie adresow poniewaz zmieniaja sie te zmienne
fclose(plik_wy);
wyswietl("a");
break;
};
case '6':
{
printf("Podaj nazwe pliku do zapisu:\n"); //wczytywanie nazwy do zapisania
scanf("%s",&nazwa_wy);
plik_wy=fopen(nazwa_wy,"w"); //otwieranie strumienia
zapisz(plik_wy,obraz,&wymx,&wymy,&odcieni);
fclose(plik_wy);
wyswietl(nazwa_wy); //wyswietla zapisany plik
break;
};
}
}while(wybor[0]!='7'); //argument dla ktorego program przestaje dzialac
}
/* Sprawozdanie
Przed uruchumieniem programu nalezy go skompilowac(najlepiej: gcc -o odczyt odczyt.c
Uruchamianie programu to komenda: ./odczyt
Testy:
1.Uruchamiam program i wczytuje obrazek, wyswietlam obrazek odpowenia komenda. Program dziala odpowiednio.
2.Uruchamiam program, wczytuje obraz, zmieniam obraz uzywajac funkcji np. rozymcie pionwe, wyswietlam obraz i obraz jest poprawnie przetworzony.
3.Uruchamiam program, wczytuje obraz, przetwarzam go a nastepni zaposuje przetworzony obraz. Program dziala odpowiednio.
4.Uruchamiam program i wczytuje obrazek a nastepni wybieram opcje z menu niedozwolym znakiem np. 'a', program dziala nieprawidlowo
Wnioski:
Nalezy pamietac zeby po kazdym otwarcia pliku fopen, nalezy go zamknac fclose.
W jednej z funkcji (rozmycie pionowe) nalezy pamietac zeby nie wczytywac argumenty spoza tablicy.
Wazne zeby program byl w tym samym katalogu co obrazki, bo inaczej program bedzie mial problem z wczytwaniem tych obrazow
Program nie posiada zabezpieczen na niepoprawne wpisywane danych/formatow
Warto pisac dokumentacje i komentarze
*/
|
C
|
#include <sys/socket.h>
#include <sys/un.h>
#include <systemd/sd-daemon.h>
#include <unistd.h>
#include <string.h>
#include <stdio.h>
#include <errno.h>
void
init_socket(struct sockaddr_un* a, const char* path)
{
memset(a,0,sizeof(struct sockaddr_un));
a->sun_family = AF_UNIX;
strncpy(a->sun_path, path, sizeof(a->sun_path));
}
int
get_socket_fd(const char* path)
{
int fd;
int n_files = sd_listen_fds(0);
if (n_files > 1)
{
fprintf(stderr, SD_ERR "[VM-HID] Too many file descriptors received.\n");
return 0;
}
else if (n_files == 1)
{
fd = SD_LISTEN_FDS_START + 0;
fprintf(stderr, SD_INFO "[VM-HID] Got file descriptor.\n");
return fd;
}
else
{
struct sockaddr addr;
struct sockaddr_un sock;
fprintf(stderr, SD_INFO "[VM-HID] Initializing socket...\n");
if ((fd = socket(AF_UNIX, SOCK_STREAM, 0)) < 0)
{
fprintf(stderr, SD_ERR "[VM-HID] Failed to initialize socket. Error %d: %s\n", errno, strerror(errno));
return 0;
}
memset(&addr,0,sizeof(struct sockaddr));
init_socket(&sock, path);
fprintf(stderr, SD_INFO "[VM-HID] Binding socket...\n");
if (bind(fd, &addr, sizeof(addr)) < 0)
{
fprintf(stderr, SD_ERR "[VM-HID] Failed to bind socket. Error %d: %s\n", errno, strerror(errno));
return 0;
}
if (listen(fd, SOMAXCONN) < 0)
{
fprintf(stderr, SD_ERR "[VM-HID] Failed to listen to socket. Error %d: %s\n", errno, strerror(errno));
return 0;
}
return fd;
}
}
int
get_connection(int fd)
{
int conn;
conn = accept(fd, 0, 0);
if (conn == -1)
fprintf(stderr, SD_ERR "[VM-HID] Failed to accept connection.\n");
return conn;
}
int read_connection(int conn, char buffer[128])
{
int rconn;
rconn = read(conn, buffer, 128);
if (rconn == -1)
fprintf(stderr, SD_ERR "[VM-HID] Failed to read connection.\n");
return rconn;
}
|
C
|
/* File: asm.h
*
* Header file containing hard-coded function-pointers to asm instructions
* and macros for x86 instructions.
*/
#ifndef ASM_H
#define ASM_H
#define PUSH_EAX 0x50
#define PUSH_ECX 0x51
#define PUSH_EDX 0x52
#define PUSH_EBX 0x53
#define PUSH_ESP 0x54
#define PUSH_EBP 0x55
#define PUSH_ESI 0x56
#define PUSH_EDI 0x57
#define POP_EAX 0x58
#define POP_ECX 0x59
#define POP_EDX 0x5a
#define POP_EBX 0x5b
#define POP_ESP 0x5c
#define POP_EBP 0x5d
#define POP_ESI 0x5e
#define POP_EDI 0x5f
#define PUSHAD_OPCODE 0x60 /* same as pusha */
#define POPAD_OPCODE 0x61 /* same as popa */
#define MOV_EBP_ESP 0x89e5
#define NOP_OPCODE 0x90
#define CALL_FAR_OPCODE 0x9a
#define RETN_OPCODE 0xc3
#define LEAVE_OPCODE 0xc9
#define RETF_OPCODE 0xcb
#define INT_OPCODE 0xcd
#define IRET_OPCODE 0xcf /* same as iretd */
#define HLT_OPCODE 0xf4
#define STI_OPCODE 0xfb
#define CLD_OPCODE 0xfc
#define CALL_OPCODE 0xff /* ff /2 = call r/m32; ff /3 = call m16:32 */
void (*nop)(void);
void (*ret)(void);
void (*hlt)(void);
void (*itr)(void);
void (*sti)(void);
#endif /* ASM_H */
|
C
|
#include "defines.h"
#include "entity.h"
#include "screens.h"
#include <stdbool.h>
#include <SDL.h>
#include <SDL_image.h>
#include <SDL_ttf.h>
#include <chipmunk.h>
#include <stdio.h>
// Usage: supply 0 args for normal play
// supply a directory name to use the level editor: if the directory
// already exists,
int main(int argc, char *argv[]) {
bool map_editor;
bool new_map;
if (argc > 1) return 1;
if (argc == 1) {
//TODO
}
SDL_Window *window = NULL;
SDL_Renderer *renderer = NULL;
cpSpace *space = NULL;
bool quit = false;
unsigned int lastTime = 0;
unsigned int lag = 0;
SDL_Event evt;
Game game = (Game) { NULL, NULL, NULL };
game.world = malloc(sizeof(World));
game.screen = malloc(sizeof(GameScreen));
if (SDL_Init(SDL_INIT_VIDEO) < 0) {
printf("Couldn't initialize SDL. Error: %s\n", SDL_GetError());
goto cleanup;
}
window = SDL_CreateWindow("Michael and the Hex World",
SDL_WINDOWPOS_UNDEFINED,
SDL_WINDOWPOS_UNDEFINED,
WINDOW_WIDTH,
WINDOW_HEIGHT,
SDL_WINDOW_SHOWN);
if (window == NULL) {
printf("Couldn't create window. Error: %s\n", SDL_GetError());
goto cleanup;
}
//Initialize renderer
renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED |
SDL_RENDERER_PRESENTVSYNC);
if (renderer == NULL) {
printf("Couldn't create renderer. Error: %s\n", SDL_GetError());
goto cleanup;
}
game.world->renderer = renderer;
//Initialize chipmunk space (For physics)
game.world->space = space;
if (TTF_Init() != 0) {
printf("Couldn't load font renderer. Error: %s\n", TTF_GetError());
goto cleanup;
}
if (!(IMG_Init(IMG_INIT_PNG) & IMG_INIT_PNG)) {
printf("Couldn't load image loader. Error: %s\n", IMG_GetError());
goto cleanup;
}
SDL_RWops *fontFile = SDL_RWFromFile("nsans.ttf", "rb");
if (fontFile == NULL) {
printf("%d Couldn't load font. Error: %s\n", __LINE__, SDL_GetError());
goto cleanup;
}
game.world->font = TTF_OpenFontRW(fontFile, 1, 42);
if (game.world->font == NULL) {
printf("%d Couldn't load font. Error: %s\n", __LINE__, TTF_GetError());
goto cleanup;
}
lastTime = SDL_GetTicks();
SDL_SetRenderDrawColor(renderer, 0, 0, 0, 255);
if (!Main_Init(&game)) {
goto cleanup;
}
while (!quit) {
unsigned int currentTime = SDL_GetTicks();
unsigned int delta = currentTime - lastTime;
lastTime = currentTime;
lag += delta;
while (SDL_PollEvent(&evt) != 0) {
if (evt.type == SDL_QUIT) {
quit = true;
goto cleanup;
}
else {
game.screen->handleEvent(&game, &evt);
}
}
while (lag >= TICKS_PER_UPDATE) {
game.screen->update(&game);
lag -= TICKS_PER_UPDATE;
}
SDL_RenderClear(renderer);
game.screen->render(&game);
SDL_RenderPresent(renderer);
if (delta < 33) {
SDL_Delay(33 - delta);
}
if (game.newScreen != NULL) {
game.screen->end(&game);
if (!game.newScreen(&game)) {
goto cleanup;
}
game.newScreen = NULL;
}
}
cleanup:
game.screen->end(&game);
free(game.screen);
World_Free(game.world);
SDL_DestroyWindow(window);
TTF_Quit();
SDL_Quit();
return 0;
}
|
C
|
#include <stdio.h>
void merge1(int A[],int l,int m,int mid)
{
int N1= mid-l+1;
int N2=m-mid;
int L[N1],R[N2];
for(int i=0;i<N1;i++) {
L[i] = A[l+i]; //Constructing left matrix
}
for(int i=0;i<N2;i++) {
R[i]=A[mid+1+i]; ////Constructing right matrix
}
int i1=0,i2=0,i3=l;
while(i1 < N1 && i2 < N2) { // merging of two halves if both left and right matrix are present.
if(L[i1] < R[i2] ) {
A[i3] = L[i1];
i1++; i3++;
} else {
A[i3] = R[i2];
i3++; i2++;
}
}
while(i1 < N1) { //Merging when only left matrix is present.
A[i3] = L[i1];
i3++; i1++;
}
while(i2 < N2) { //Merging when only right matrix is present.
A[i3] = R[i2];
i3++; i2++;
}
return ;
}
void merge(int ARR[],int l,int m,int n)
{
if(n<2) //Base critera
return;
else {
int mid = l+(m-l)/2;
merge(ARR,l,mid,(mid-l)+1); //Recursion using left half
merge(ARR,mid+1,m,(m-(mid+1))+1); //Recursion using right half
merge1(ARR,l,m,mid); //Merging both left and right halves
}
}
int main()
{
int i,A[6];
printf("Enter six values to be inserted into the aary : ");
for(i=0;i<6;i++) {
scanf("%d",&A[i]);
}
printf("Original array is : ");
for(i=0;i<6;i++) {
printf("%d ",A[i]);
}
printf("\n");
int l=0,m=5,num=6;
merge(A,l,m,num);
printf("Sorted array is as follows : ");
for(i=0;i<6;i++) {
printf("%d ",A[i]);
}
printf("\n");
return 0;
}
|
C
|
#include "oss.h"
#include "oss_gpio.h"
#if 0
///////////////////////////////////////////////////////////////
int oss_gpio_init(oss_gpio_t *gpio, int num)
{
int loop;
unsigned char cmd[128];
for(loop = 0; loop < num ; loop++)
{
// export gpio
memset(cmd, 0, 128);
sprintf(cmd, "echo %d > /sys/class/gpio/export", gpio[loop].number);
system(cmd);
//exist ?
// setup out/in
if(gpio->flags == OSS_GPIO_OUT)
{
memset(cmd, 0, 128);
sprintf(cmd, "echo %s > /sys/class/gpio%d/direction", "out", gpio[loop].number);
system(cmd);
memset(cmd, 0, 128);
sprintf(cmd, "echo %d > /sys/class/gpio%d/value", gpio[loop].value, gpio[loop].number);
system(cmd);
}
else if(gpio->flags == OSS_GPIO_IN)
{
memset(cmd, 0, 128);
sprintf(cmd, "echo %s > /sys/class/gpio%d/direction", "in", gpio[loop].number);
system(cmd);
}
}
return 1;
}
/////////////////////////////////////////////////////////////
int oss_gpio_set(oss_gpio_t *gpio, int value)
{
unsigned char cmd[128];
if(gpio->flags == OSS_GPIO_OUT)
{
memset(cmd, 0, 128);
sprintf(cmd, "echo %s > /sys/class/gpio%d/direction", "out", gpio->number);
system(cmd);
memset(cmd, 0, 128);
sprintf(cmd, "echo %d > /sys/class/gpio%d/value", gpio->value, gpio->number);
system(cmd);
}
return 1;
}
#endif
int oss_gpio_init(int io)
{
#ifdef WIN32
return (1);
#else
unsigned char cmd[128];
int error_value;
int status;
memset(cmd, 0, 128);
sprintf(cmd, "test -d /sys/class/gpio/gpio%d", io);
status = system(cmd);
if (WEXITSTATUS(status))
{
memset(cmd, 0, 128);
sprintf(cmd, "echo %d > /sys/class/gpio/export ", io);
status = system(cmd);
if (-1 == status)
{
printf("system error!");
exit(1);
}
else
{
if (WEXITSTATUS(status))
{
printf("The gpio is busy");
return (1);
}
}
#ifdef DEBUG
printf("gpio%d create\n", io);
#endif
}
#endif
}
int oss_gpio_output_mode(int io)
{
#ifdef WIN32
return (1);
#else
unsigned char cmd[128];
int error_value;
int status;
memset(cmd, 0, 128);
sprintf(cmd, "echo %s > /sys/class/gpio/gpio%d/direction", "out", io);
status = system(cmd);
if (-1 == status)
{
printf("system error!");
exit(1);
}
else
{
if (WEXITSTATUS(status))
{
printf("The gpio%d non-existence\n", io);
return (1);
}
}
#ifdef DEBUG
printf("gpio%d set output \n", io);
#endif
#endif
}
int oss_gpio_input_mode(int io)
{
#ifdef WIN32
return (1);
#else
unsigned char cmd[128];
int error_value;
int status;
memset(cmd, 0, 128);
sprintf(cmd, "echo %s > /sys/class/gpio/gpio%d/direction", "in", io);
status = system(cmd);
if (-1 == status)
{
printf("system error!");
exit(1);
}
else
{
if (WEXITSTATUS(status))
{
printf("The gpio%d non-existence\n", io);
return (1);
}
}
#ifdef DEBUG
printf("gpio%d set intput \n", io);
#endif
#endif
}
int oss_gpio_pin_set(int io)
{
#ifdef WIN32
return (1);
#else
unsigned char cmd[128];
int error_value;
int status;
memset(cmd, 0, 128);
sprintf(cmd, "echo 1 > /sys/class/gpio/gpio%d/value\n", io);
status = system(cmd);
if (-1 == status)
{
printf("system error!");
exit(1);
}
else
{
if (WEXITSTATUS(status))
{
printf("The gpio%d non-existence\n", io);
return (1);
}
}
#ifdef DEBUG
printf("pin gpio%d set\n", io);
#endif
#endif
}
int oss_gpio_pin_clear(int io)
{
#ifdef WIN32
return (1);
#else
unsigned char cmd[128];
int error_value;
int status;
memset(cmd, 0, 128);
sprintf(cmd, "echo 0 > /sys/class/gpio/gpio%d/value\n", io);
status = system(cmd);
if (-1 == status)
{
printf("system error!");
exit(1);
}
else
{
if (WEXITSTATUS(status))
{
printf("The gpio%d non-existence\n", io);
return (1);
}
}
#ifdef DEBUG
printf("pin gpio%d clear\n", io);
#endif
#endif
}
/*
int main(int argc, char *argv[])
{
int gpio[] = {0, 1, 2 , 3 , 4, 6, 11, 37};
int i;
for (i=0; i<8; i++) {
oss_gpio_init(gpio[i]);
oss_gpio_output_mode(gpio[i]);
}
for (i=0; i<8; i++) {
oss_gpio_init(gpio[i]);
oss_gpio_pin_set(gpio[i]);
printf("%d\n", gpio[i]);
sleep(1);
}
for (i=0; i<8; i++) {
oss_gpio_pin_clear(gpio[7-i]);
sleep(1);
}
}
*/
|
C
|
#include<stdio.h>
int main()
{
int low,high,i,flag;
printf("enter the two numbers intervals");
scanf("%d %d",&low,&high);
printf("prime numbers between %d and %d",low,high);
while(low<high)
{
flag=0;
for(i=2;i<=low/2;i++)
{
if(low %i==0)
{
flag = 1;
break;
}
}
if (flag == 0)
printf("%d ", low);
++low;
}
return 0;
}
|
C
|
#include<stdio.h>
#include<errno.h>
#include<unistd.h>
#include<sys/wait.h>
/*
int
main(void)
{
//system("ls -l");
//printf("%d",system(""));
//_exit(0);
}
*/
void
pr_exit(int status)
{
if(WIFEXITED(status))
printf("normal termination, exit status = %d\n",
WEXITSTATUS(status));
else if(WIFSIGNALED(status))
printf("abnormal termination, signal number = %d%s\n",
WTERMSIG(status),
#ifdef WCOREDUMP
WCOREDUMP(status) ? " (core file generated)" : "");
#else
"");
#endif
else if(WIFSTOPPED(status))
printf("child stopped, signal number = %d\n", WSTOPSIG(status));
}
int
system(const char *cmdstring)
{
pid_t pid;
int status;
if(cmdstring == NULL)
return(1);
if((pid = fork()) < 0) {
status = -1;
} else if(pid == 0) {
execl("/bin/sh", "sh", "-c", cmdstring, (char*)0);
_exit(127);
}else {
while(waitpid(pid, &status, 0) < 0) {
if(errno != EINTR) {
status = -1;
break;
}
}
}
return(status);
}
int
main(void)
{
int status;
if((status = system("date")) < 0)
err_sys("system() error");
pr_exit(status);
if((status = system("nosuchcommand")) < 0)
err_sys("system() error");
pr_exit(status);
if((status = system("who; exit 44")) < 0)
err_sys("system() error");
pr_exit(status);
exit(0);
}
|
C
|
//
// signal.c
// SDIS
//
// Created by Alexandre on 01/12/2017.
// Copyright © 2017 Alex & Luis. All rights reserved.
//
#include "signal.h"
void signal_new(signal_t* signal) {
mutex_new(&(signal->m));
int res = pthread_cond_init(&(signal->c), NULL);
xassert(res == 0, "Error creating condition variable");
}
void signal_free(signal_t* signal) {
mutex_free(&(signal->m));
int res = pthread_cond_destroy(&(signal->c));
xassert(res == 0, "Error destroying condition variable");
}
void signal_wait(signal_t* signal) {
mutex_lock(&(signal->m));
int res = pthread_cond_wait(&(signal->c), &(signal->m));
xassert(res == 0, "Error waiting for condition variable");
mutex_unlock(&(signal->m));
}
void signal_send(signal_t* signal) {
mutex_lock(&(signal->m));
int res = pthread_cond_signal(&(signal->c));
xassert(res == 0, "Error signaling condition variable");
mutex_unlock(&(signal->m));
}
|
C
|
#ifndef HASHTABLE_H
#define HASHTABLE_H
#include <stdlib.h>
#include <stdbool.h>
#include "string.h"
#define MULTIPLIER (37)
#define OXFORD_WORDS (200000)
typedef struct HASHNODE HASHNODE;
struct HASHNODE
{
char* storedString;
HASHNODE* next;
};
HASHNODE* hashTable[OXFORD_WORDS];
long HashListSize;
/**
* The function to create the array position for a given key string
*/
unsigned long hash(const char* s);
/**
* Adds a string as a key to the hash table
*/
void AddToHashTable(char* string);
/**
* Function to find the last node on a linked list (recursively)
*/
HASHNODE* GetLastNode(HASHNODE* currentNode);
/**
* Check if some value exists in the hash table
*/
bool CheckHashTable(const char* string);
/**
* Function to clear the memory of the hash nodes
*/
void ClearNode(HASHNODE* node);
#endif
|
C
|
#include "holberton.h"
/**
* append_text_to_file - function that create a text file and appends
*
* @filename: pointer to new txt file
* @text_content: pointer to text to write
*
* Return: text
*/
int append_text_to_file(const char *filename, char *text_content)
{
int doc, count;
if (filename != NULL)
{
doc = open(filename, O_CREAT | O_WRONLY | O_APPEND, 0600);
if (doc == -1)
{
return (-1);
}
if (text_content == NULL)
{
text_content = "";
}
for (count = 0; text_content[count] != '\0'; count++)
{
}
write(doc, text_content, count);
close(doc);
return (1);
}
return (-1);
}
|
C
|
#include "types.h"
#include "util.h"
#include "defs.h"
#include "network.h"
#include "e1000.h"
#define BROADCAST_MAC 0xFFFFFFFFFFFF
#define PROT_IP 0x0800
#define PROT_ARP 0x0806
#define PROT_UDP 17
#define PROT_ICMP 1
struct EthernetHeader
{
uint8_t tarmac[6];
uint8_t srcmac[6];
uint16_t protocal;
};
struct IPHeader
{
uint8_t header1[2];
uint16_t TOL;
uint8_t header2[5];
uint8_t protocal;
uint16_t cksum;
uint32_t srcip;
uint32_t tarip;
};
struct ICMPHeader
{
uint8_t type;
uint8_t code;
uint16_t cksum;
uint16_t flag;
uint16_t seq;
};
struct ARPHeader
{
uint16_t hwtype;
uint16_t protype;
uint8_t hwsize;
uint8_t prosize;
uint16_t opcode;
uint8_t data[20];
// uint8_t arp_smac[6];
// uint32_t sip;
// uint8_t arp_dmac[6];
// uint32_t dip;
};
static uint8_t fillbuf(uint8_t *buf, uint8_t k, uint64_t num, uint8_t len)
{
static uint8_t mask = -1;
for (short j = len - 1; j >= 0; --j)
{
buf[k++] = (num >> (j << 3)) & mask;
}
return k;
}
static uint8_t memcpy(uint8_t *dest, uint8_t *src, uint8_t len)
{
for (int i = 0; i < len; ++i)
{
dest[i] = src[i];
}
return len;
}
// This code is lifted from FreeBSD's ping.c, and is copyright by the Regents
// of the University of California.
static unsigned short
in_cksum(const unsigned char *addr, int len)
{
int nleft = len;
const unsigned short *w = (const unsigned short *)addr;
unsigned int sum = 0;
unsigned short answer = 0;
/*
* Our algorithm is simple, using a 32 bit accumulator (sum), we add
* sequential 16 bit words to it, and at the end, fold back all the
* carry bits from the top 16 bits into the lower 16 bits.
*/
while (nleft > 1)
{
sum += *w++;
nleft -= 2;
}
/* mop up an odd byte, if necessary */
if (nleft == 1)
{
*(unsigned char *)(&answer) = *(const unsigned char *)w;
sum += answer;
}
/* add back carry outs from top 16 bits to low 16 bits */
sum = (sum & 0xffff) + (sum >> 16);
sum += (sum >> 16);
/* guaranteed now that the lower 16 bits of sum are correct */
answer = ~sum; /* truncate to 16 bits */
return answer;
}
uint32_t IP2int(char *sIP)
{
int i = 0;
uint32_t v1 = 0, v2 = 0, v3 = 0, v4 = 0;
cprintf(sIP);
cprintf("\n");
cprintf("%d\n", sIP[9]);
for (i = 0; sIP[i] != '\0'; ++i)
;
for (i = 0; sIP[i] != '.'; ++i)
v1 = v1 * 10 + sIP[i] - '0';
for (++i; sIP[i] != '.'; ++i)
v2 = v2 * 10 + sIP[i] - '0';
for (++i; sIP[i] != '.'; ++i)
v3 = v3 * 10 + sIP[i] - '0';
for (++i; sIP[i] != '\0'; ++i)
v4 = v4 * 10 + sIP[i] - '0';
return (v1 << 24) + (v2 << 16) + (v3 << 8) + v4;
}
int hex_to_int(char ch)
{
uint i = 0;
if (ch >= '0' && ch <= '9')
{
i = ch - '0';
}
else if (ch >= 'A' && ch <= 'F')
{
i = 10 + (ch - 'A');
}
else if (ch >= 'a' && ch <= 'f')
{
i = 10 + (ch - 'a');
}
return i;
}
/**
* Pack the XX:Xx:XX:XX:XX:XX representation of MAC address
* into I:I:I:I:I:I
*/
uint64_t pack_mac(char *src)
{
uint64_t res;
uint8_t *dest = &res;
for (int i = 0, j = 0; i < 17; i += 3)
{
uint i1 = hex_to_int(src[i]);
uint i2 = hex_to_int(src[i + 1]);
dest[j++] = (i1 << 4) + i2;
}
return res;
}
uint32_t get_ip(char *ip, uint len)
{
uint ipv4 = 0;
char arr[4];
int n1 = 0;
uint ip_vals[4];
int n2 = 0;
for (int i = 0; i < len; i++)
{
char ch = ip[i];
if (ch == '.')
{
arr[n1++] = '\0';
n1 = 0;
ip_vals[n2++] = util_atoi(arr);
//cprintf("Check ipval:%d , arr:%s",ip_vals[n2],arr);
}
else
{
arr[n1++] = ch;
}
}
arr[n1++] = '\0';
n1 = 0;
ip_vals[n2++] = util_atoi(arr);
//cprintf("Final Check ipval:%d , arr:%s",ip_vals[n2],arr);
// ipv4 = (ip_vals[0]<<24) + (ip_vals[1]<<16) + (ip_vals[2]<<8) + ip_vals[3];
ipv4 = (ip_vals[3] << 24) + (ip_vals[2] << 16) + (ip_vals[1] << 8) + ip_vals[0];
return ipv4;
}
uint16_t htons(uint16_t v)
{
return (v >> 8) | (v << 8);
}
uint32_t htonl(uint32_t v)
{
return htons(v >> 16) | (htons((uint16_t)v) << 16);
}
char int_to_hex(uint n)
{
char ch = '0';
if (n >= 0 && n <= 9)
{
ch = '0' + n;
}
else if (n >= 10 && n <= 15)
{
ch = 'A' + (n - 10);
}
return ch;
}
// parse the mac address
void unpack_mac(uint8_t *mac, char *mac_str)
{
int c = 0;
for (int i = 0; i < 6; i++)
{
uint m = mac[i];
uint i2 = m & 0x0f;
uint i1 = (m & 0xf0) >> 4;
mac_str[c++] = int_to_hex(i1);
mac_str[c++] = int_to_hex(i2);
mac_str[c++] = ':';
}
mac_str[c - 1] = '\0';
}
// parse the ip value
void parse_ip(uint ip, char *ip_str)
{
uint v = 255;
uint8_t *ip_vals = &ip;
int c = 0;
for (int i = 3; i >= 0; i--)
{
uint8_t ip1 = ip_vals[i];
if (ip1 == 0)
{
ip_str[c++] = '0';
}
else
{
if (ip1 >= 100)
{
ip_str[c++] = ip1 / 100 + '0';
ip1 = ip1 % 100;
ip_str[c++] = ip1 / 10 + '0';
ip1 = ip1 % 10;
ip_str[c++] = ip1 + '0';
}
else if (ip1 >= 10)
{
ip_str[c++] = ip1 / 10 + '0';
ip1 = ip1 % 10;
ip_str[c++] = ip1 + '0';
}
else
{
ip_str[c++] = ip1 + '0';
}
}
ip_str[c++] = '.';
}
ip_str[c - 1] = '\0';
}
int send_Ethernet_frame(struct nic_device *nd, uint8_t *payload, int payload_len, uint8_t *tarmac, uint16_t protocal)
{
struct e1000 *the_e1000 = (struct e1000 *)nd->driver;
uint8_t *buffer = (uint8_t *)kalloc();
uint8_t posiphdrcks;
uint8_t posicmphdrcks;
uint8_t pos = 0;
//mac header
uint8_t *srcmac = the_e1000->mac_addr;
// pos = fillbuf(buffer, pos, tarmac, 6);
pos += memcpy(buffer, tarmac, 6);
pos += memcpy(buffer + pos, srcmac, 6);
// pos = fillbuf(buffer, pos, srcmac, 6);
pos = fillbuf(buffer, pos, protocal, 2);
pos += memcpy(buffer + pos, payload, payload_len);
nd->send_packet(nd->driver, buffer, pos);
kfree(buffer);
return 0;
}
int send_IP_datagram(struct nic_device *nd, uint8_t *payload, int payload_len, uint32_t tarip, uint16_t protocal)
{
struct e1000 *e1000 = (struct e1000 *)nd->driver;
static uint16_t id = 1;
uint8_t *buffer = (uint8_t *)kalloc();
uint8_t posiphdrcks;
uint8_t pos = 0;
//ip header
uint8_t vrs = 4;
uint8_t IHL = 5;
uint8_t TOS = 0;
uint16_t TOL = payload_len + sizeof(struct IPHeader);
uint16_t ID = id++;
uint16_t flag = 0;
uint16_t offset = 0;
uint16_t TTL = 32;
// uint8_t *piphdr = buffer;
pos = fillbuf(buffer, pos, (vrs << 4) + IHL, 1);
pos = fillbuf(buffer, pos, TOS, 1);
pos = fillbuf(buffer, pos, TOL, 2);
pos = fillbuf(buffer, pos, ID, 2);
pos = fillbuf(buffer, pos, (flag << 13) + offset, 2);
pos = fillbuf(buffer, pos, TTL, 1);
pos = fillbuf(buffer, pos, protocal, 1);
uint16_t cksum = 0;
uint32_t srcip = e1000->ip;
// uint32_t tarip = IP2int(str_tarip);
posiphdrcks = pos;
pos = fillbuf(buffer, pos, cksum, 2);
pos = fillbuf(buffer, pos, srcip, 4);
pos = fillbuf(buffer, pos, tarip, 4);
// fill payload
// pos = fillbuf(buffer, pos, payload, payload_len);
pos += memcpy(buffer + pos, payload, payload_len);
cksum = in_cksum(buffer, 20);
memmove(buffer + posiphdrcks, &cksum, 2);
// fillbuf(buffer, posiphdrcks, cksum, 2);
// uint16_t macprotocal = 0x0800;
// uint64_t dmac;
// memmove(&dmac, e1000->gateway_mac_addr, 6);
int res = send_Ethernet_frame(nd, buffer, pos, e1000->gateway_mac_addr, PROT_IP);
kfree(buffer);
return res;
}
int send_arpRequest(struct nic_device *nd, char *ipAddr)
{
struct e1000 *the_e1000 = (struct e1000 *)nd->driver;
// cprintf("Create ARP frame\n");
struct ARPHeader eth;
// char *sdmac = BROADCAST_MAC;
uint64_t dmac = BROADCAST_MAC;
/** ARP packet filling **/
eth.hwtype = htons(1);
eth.protype = htons(0x0800);
eth.hwsize = 0x06;
eth.prosize = 0x04;
//arp request
eth.opcode = htons(1);
memmove(eth.data, the_e1000->mac_addr, 6);
memmove(eth.data + 10, &dmac, 6);
*(uint32_t *)(eth.data + 6) = htonl(the_e1000->ip);
*(uint32_t *)(eth.data + 16) = htonl(IP2int(ipAddr));
return send_Ethernet_frame(nd, ð, sizeof(struct ARPHeader), &dmac, PROT_ARP);
}
int send_icmpRequest(struct nic_device *nd, char *tarips, uint8_t type, uint8_t code)
{
// static uint16_t id = 1;
// uint8_t *buffer = (uint8_t *)kalloc();
struct ICMPHeader hdr;
fillbuf(&hdr.type, 0, type, sizeof(hdr.type));
fillbuf(&hdr.code, 0, code, sizeof(hdr.code));
uint16_t flag = 1108;
fillbuf(&hdr.flag, 0, flag, sizeof(flag));
uint16_t cksum = 0;
fillbuf(&hdr.cksum, 0, cksum, sizeof(cksum));
uint16_t seq = 921;
fillbuf(&hdr.seq, 0, seq, sizeof(seq));
cksum = in_cksum(&hdr, sizeof(struct ICMPHeader));
fillbuf(&hdr.cksum, 0, cksum, sizeof(hdr.cksum));
uint32_t tarip = IP2int(tarips);
return send_IP_datagram(nd, &hdr, sizeof(struct ICMPHeader), tarip, PROT_ICMP);
}
void recv_ARP(struct nic_device *nd, struct ARPHeader *data)
{
if (htons(data->protype) != 0x0800)
{
cprintf("Not IPV4 protocol:%x\n", data->protype);
return;
}
struct e1000 *e1000 = (struct e1000 *)nd->driver;
switch (htons(data->opcode))
{
case 1:
cprintf("ARP Request\n");
{
uint32_t tar_ip = htonl(*(uint32_t *)(data->data + 16));
if (tar_ip != e1000->ip)
{
cprintf("not my ip:%x\n", tar_ip);
return;
}
uint8_t *dmac = data->data;
// memmove(&dmac, request->data + 10, 6);
if (tar_ip == e1000->gateway_ip)
memmove(e1000->gateway_mac_addr, &dmac, 6);
cprintf("Create ARP frame\n");
struct ARPHeader eth;
/** ARP packet filling **/
eth.hwtype = htons(1);
eth.protype = htons(0x0800);
eth.hwsize = 0x06;
eth.prosize = 0x04;
//arp request
eth.opcode = htons(2);
memmove(eth.data, e1000->mac_addr, 6);
*(uint32_t *)(eth.data + 6) = htonl(e1000->ip);
memmove(eth.data + 10, data->data, 10);
send_Ethernet_frame(nd, ð, sizeof(struct ARPHeader), dmac, PROT_ARP);
}
return;
case 2:
cprintf("ARP Reply\n");
{
uint32_t tar_ip = htonl(*(uint32_t *)(data->data + 16));
uint8_t *dmac = data->data;
if (tar_ip == e1000->gateway_ip)
memmove(e1000->gateway_mac_addr, &dmac, 6);
}
return;
default:
cprintf("Not an ARP reply: %x\n", data->opcode);
return;
}
}
void recv_IP_datagram(uint8_t *data, uint len)
{
struct IPHeader *header = data;
uint cksum = header->cksum;
header->cksum = 0;
if (in_cksum(data, sizeof(struct IPHeader)) != cksum)
{
cprintf("ERROR:recv_IP_datagram:checksum failed.\n");
return;
}
switch (header->protocal)
{
case PROT_UDP:
// cprintf("UDP Reply\n");
deliver_pkt(data + sizeof(struct IPHeader), header->TOL - sizeof(struct IPHeader), htonl(header->srcip));
break;
default:
cprintf("unsupported IP protocal:%d\n", header->protocal);
}
}
void recv_Ethernet_frame(struct nic_device *nd, uint8_t *frame, int frame_len)
{
struct EthernetHeader *header = frame;
struct e1000 *e1000 = nd->driver;
uint64_t broadcast = BROADCAST_MAC;
if (memcmp(header->tarmac, e1000->mac_addr, 6) && memcmp(header->tarmac, &broadcast, 6))
{
cprintf("invalid target mac address: %x", *(uint64_t *)(header->tarmac));
return;
}
switch (htons(header->protocal))
{
case PROT_IP:
recv_IP_datagram(frame + sizeof(struct EthernetHeader), frame_len - sizeof(struct EthernetHeader));
break;
case PROT_ARP:
recv_ARP(nd, frame + sizeof(struct EthernetHeader));
break;
default:
cprintf("unsupported protocal:%x\n", header->protocal);
break;
}
}
|
C
|
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <stdlib.h>
#include <string.h>
#include <sys/epoll.h>
#include <pthread.h>
#include "yidb.h"
#define BUFFER_SIZE (YIDB_MAX_KEYSIZE + YIDB_MAX_VALUESIZE + 100)
#define MAX_EVENTS 1000
/*
struct p_params{
int sockfd;
char buf[BUFFER_SIZE];
};
void *pthread_handleRequest(void *arg)
{
struct p_params *pprams;
pprams = (struct p_params *)arg;
char result[200];
memset(result,0,sizeof(result));
execNetStr(pprams->buf,result);
write(pprams->sockfd,result,sizeof(result));
free(pprams);
pthread_exit(0);
}
void handleRequest(int sockfd,char *buf){
struct p_params *pprams;
pprams = malloc(sizeof(struct p_params));
pprams->sockfd = sockfd;
strcpy(pprams->buf,buf);
pthread_t thread;
pthread_create(&thread,NULL,pthread_handleRequest,(void *)pprams);
}
*/
int net_serverStart(){
int server_sockfd,client_sockfd;
int len;
struct sockaddr_in server_address;
struct sockaddr_in client_address;
int sin_size,sockfd;
char buf[BUFFER_SIZE];
memset(buf,0,BUFFER_SIZE);
memset(&server_address,0,sizeof(server_address));
server_address.sin_family = AF_INET;
server_address.sin_addr.s_addr = INADDR_ANY;
server_address.sin_port = htons(yidbconfigObj->port);
//create socket server
if( (server_sockfd = socket(AF_INET,SOCK_STREAM,0)) == -1 ){
perror("socket");
exit(1);
}
//bind
if( bind(server_sockfd,(struct sockaddr*)&server_address,sizeof(server_address)) == -1 ){
perror("bind error");
exit(EXIT_FAILURE);
}
//listen
listen(server_sockfd,1000);
sin_size=sizeof(struct sockaddr_in);
//create epoll
int epoll_fd;
epoll_fd = epoll_create(MAX_EVENTS);
if(epoll_fd==-1)
{
perror("epoll_create failed");
exit(EXIT_FAILURE);
}
struct epoll_event ev;
struct epoll_event events[MAX_EVENTS];
ev.events=EPOLLIN|EPOLLET;
ev.data.fd=server_sockfd;
//register server event
if(epoll_ctl(epoll_fd,EPOLL_CTL_ADD,server_sockfd,&ev)==-1){
perror("epll_ctl:server_sockfd register failed");
exit(EXIT_FAILURE);
}
int nfds;//event nums
while(1){
//wait event
nfds = epoll_wait(epoll_fd,events,MAX_EVENTS,-1);
if(nfds==-1)
{ printf("failed\n");
perror("start epoll_wait failed");
exit(EXIT_FAILURE);
}
int i;
for(i=0;i<nfds;i++)
{
if(events[i].data.fd==server_sockfd){
//printf("new socket\n");
//client come
if((client_sockfd=accept(server_sockfd,(struct sockaddr *)&client_address,&sin_size))<0)
{
perror("accept client_sockfd failed");
exit(EXIT_FAILURE);
}
//register client event
ev.events=EPOLLIN|EPOLLET;
ev.data.fd=client_sockfd;
if(epoll_ctl(epoll_fd,EPOLL_CTL_ADD,client_sockfd,&ev)==-1)
{
perror("epoll_ctl:client_sockfd register failed\n");
exit(EXIT_FAILURE);
}
//printf("accept client %s\n",inet_ntoa(client_address.sin_addr));
}else if(events[i].events&EPOLLIN){
//event raise
sockfd = events[i].data.fd;
len = read(sockfd, buf, BUFFER_SIZE);
//printf("len:%d %s\n",len,buf);
if(len<=0)
{
epoll_ctl(epoll_fd,EPOLL_CTL_DEL,events[i].data.fd,&ev);
close(sockfd);
continue;
}
//exec
char result[200];
memset(result,0,sizeof(result));
execNetStr(buf,result);
//printf("result:%s\n",result);
write(sockfd,result,sizeof(result));
//handleRequest(sockfd,buf);
}
}
}
close(server_sockfd);
close(epoll_fd);
return 0;
}
|
C
|
#include<stdio.h>
#include<stdlib.h>
int main()
{
int n,i,count = 1;
char s[100000];
scanf("%s",s);
n = strlen(s);
for(i=0;i<n;i++)
{
if((int)s[i]<95)
count++;
}
printf("%d",count);
}
|
C
|
#include <stdio.h>
int main()
{
int side1,side2,side3;
printf("enter the side of tringal");
scanf("%d%d%d",&side1,&side2,&side3);
if(side1+side2>side3)
{
if(side2+side3>side1)
{
if(side1+side3>side2)
{
printf("tringal is valid");
}
else
{
printf("tringal is not valid");
}
}
else
{
printf("tringal is not valid");
}
}
else
{
printf("tringal is not valid");
}
return 0;
}
// the tringal is valid //
|
C
|
#include "command.h"
#include <unistd.h>
#include <stdio.h>
#include <dirent.h>
#include <string.h>
#include <stdlib.h>
void lfcat()
{
/* Uses dirent.h and a struct to store file info */
DIR *currentDirectory;
char cwd[PATH_MAX]; /* Stores the cwd path: /usr/blabla */
struct dirent *directory; /* Struct that holds file info */
FILE* fName;
char* line = NULL;
size_t length = 0;
FILE *input;
if (getcwd(cwd, sizeof(cwd)) != NULL) /* */
{
char* message = "<<In lfcat(): Step-01: Function called>>\n";
char* messageTwo = "<<In lfcat(): Step-02: Listing all files in current dir.\n";
// printf("Current working directory: %s\n", cwd);
// write(1, message, strlen(message));
currentDirectory = opendir(cwd);
// write(1, messageTwo, strlen(messageTwo));
FILE *fName = freopen("output.txt", "w+", stdout);
while ((directory = readdir(currentDirectory)) != NULL)
{
// write(1, "File: ", 6);
// write(1, directory->d_name, strlen(directory->d_name));
// write(1, "\n", 1);
if (strcmp(directory->d_name, "1_poem.txt") == 0 || strcmp(directory->d_name, "2_lyrics.txt") == 0 || strcmp(directory->d_name, "3_DE_Code.py") == 0)
{
write(1, "File: ", 6);
write(1, directory->d_name, strlen(directory->d_name));
write(1, "\n", 1);
input = fopen(directory->d_name, "r");
while (getline(&line, &length, input) != -1)
{
write(1, line, strlen(line));
write(1, "\n", 1);
// printf("%s", line);
}
// write(1, "\n", 1);
for(int i = 0; i < 80; i++)
write(1, "-",1);
write(1, "\n", 1);
}
}
}
else
{
printf("cwd error\n");
}
fclose(input);
closedir(currentDirectory);
exit(0);
}
|
C
|
#include "csv6.h"
uint8_t convert( char num1, char num2 )
{
uint8_t r1, r2, result;
switch(num1)
{
case '0': r1=(uint8_t)0x00; break;
case '1': r1=(uint8_t)0x01; break;
case '2': r1=(uint8_t)0x02; break;
case '3': r1=(uint8_t)0x03; break;
case '4': r1=(uint8_t)0x04; break;
case '5': r1=(uint8_t)0x05; break;
case '6': r1=(uint8_t)0x06; break;
case '7': r1=(uint8_t)0x07; break;
case '8': r1=(uint8_t)0x08; break;
case '9': r1=(uint8_t)0x09; break;
default: fprintf(stderr, "error convert: illegal parameter num1 = %c\n", num1); return (uint8_t)0xFF;
}
switch(num2)
{
case '0': r2=(uint8_t)0x00; break;
case '1': r2=(uint8_t)0x01; break;
case '2': r2=(uint8_t)0x02; break;
case '3': r2=(uint8_t)0x03; break;
case '4': r2=(uint8_t)0x04; break;
case '5': r2=(uint8_t)0x05; break;
case '6': r2=(uint8_t)0x06; break;
case '7': r2=(uint8_t)0x07; break;
case '8': r2=(uint8_t)0x08; break;
case '9': r2=(uint8_t)0x09; break;
default: fprintf(stderr, "error convert: illegal parameter num2 = %c\n", num1); return (uint8_t)0xFF;
}
result = (r1<<4) | r2;
return result;
}
|
C
|
int main()
{
int i,j=10,k=20,q,l,c,r,t;
printf("\n ENTER THE TOTAL NUMBER OF TICKETS:");
scanf("%d",&i);
for(i=0;i<=10;i++)
{
j%=j/75*100;
for(j=0;j>=20;j++)
{
l%=l/150*100;
}}
printf("\n dou you want refreshment:");
if(r==1)
{
printf("\n enter the option as yes");
r=j*i;
r=l*i;
}
else
{
printf("\n you have not selected the refreshment option");
}
printf("\n do you have coupon code:");
if(c==1)
{
printf("\n enter the code:");
scanf("%d",&c);
}
printf("\n enter the class");
if(l==1)
{
printf("\n enter the amount circle:");
scanf("%d",&k);
k=i*j/75*100;
if(t==1)
{
q=i*t/150*100;
}}
printf("\n the ticket code is:");
return 0;
}
|
C
|
/*
* Nick Waggoner
* Programming in C
* Due: 3-12-2020
*
* Description: This program inputs two values from the user and sends them
* to the correct function which is specified by the user after seeing the
* menu. Their selection calls the correct function using an array of function
* pointers and sends the values to it in pass by reference.
*
* Tags: functions, pointers, array, algebra
*/
#include <stdio.h>
//function prototypes:
double add(double *value0, double *value1);
double subtract(double *value0, double *value1);
double multiply(double *value0, double *value1);
double divide(double *value0, double *value1);
int main(int argv, char ** argc)
{
double value0 = 0;
double value1 = 0;
int pick = 0;
int choice = 1; //set to add by default
//initializes array of functions for calling
double (*functionPtr[])(double*, double*) = {add, subtract, multiply, divide};
//Header
printf("\nWelcome to Nick Waggoner's simple Calculator program");
printf("\nThis program takes in two user values and performs the");
printf("\ndesignated operation indicated by the user.");
while(choice != 0) {
//Scans for user input and stores it
printf("\n\nPlease input your first value >> ");
scanf("%lf", &value0);
printf("\n\nPlease input your second value >> ");
scanf("%lf", &value1);
//Menu screen
printf("\nWhat would you like to do with %.2f and %.2f?", value0, value1);
printf("\n\t\t0\texit");
printf("\n\t\t1\tadd\t(Value 1) + (Value 2))");
printf("\n\t\t2\tsubtract\t(Value 1) - (Value 2)");
printf("\n\t\t3\tmultiply\t(Value 1) x (Value 2)");
printf("\n\t\t4\tdivide\t(Value 1) / (Value 2)");
printf("\n\nChoice>> ");
scanf("%d", &pick);
if(pick > 0 & pick <= 4) {
choice = pick;
printf("%.2f", (*functionPtr[choice -1])(&value0, &value1));
}
//exit case: Changes value of choice to break the loop
else if(pick == 0){
printf("\nGoodbye! Have a nice day!\n\n\n\n\n\n");
choice = 0;
}
//This case if the value entered is outside the scope of the choices
else
{
printf("I'm sorry, that choice was not valid. Please choose again:");
}
}
return 0;
}
//Calculator Functions; perform the action, print the
//header, and return the answer in response
double add(double * value0, double * value1) {
double answer = 0;
answer = *value0 + *value1;
printf("\nResult>> %.2lf + %.2lf = ", *value0, *value1);
return answer;
}
double subtract(double * value0, double * value1) {
double answer = 0;
answer = *value0 - *value1;
printf("\nResult>> %.2lf - %.2lf = ", *value0, *value1);
return answer;
}
double multiply(double * value0, double * value1) {
double answer = 0;
answer = *value0 * *value1;
printf("\nResult>> %.2lf * %.2lf = ", *value0, *value1);
return answer;
}
double divide(double * value0, double * value1) {
double answer = 0;
answer = *value0 / *value1;
printf("\nResult>> %.2lf / %.2lf = ", *value0, *value1);
return answer;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char **argv, char **envp)
{
int i;
for (i=0; envp[i]!=NULL; i++)
printf("%2d%s\n",i, envp[i]);
}
|
C
|
/******************************************************************************
Online C Compiler.
Code, Compile, Run and Debug C program online.
Write your code in this editor and press "Run" button to compile and execute it.
*******************************************************************************/
#include <stdio.h>
#include <stdlib.h>
struct node
{
int data;
struct node *next;
};
struct node *head=NULL;
//function used to print the given linkList
void printLinkList()
{
struct node *temp;
temp=head;
while(temp!=NULL)
{
printf("%d ",temp->data);
temp=temp->next;
}
}
void insertAtBeginning(int data)
{
struct node *newNode;
newNode=(struct node*)malloc(sizeof(struct node));
newNode->data=data;
newNode->next=head;
head=newNode;
}
void insertAtEnd(int data)
{
struct node *newNode,*temp;
newNode=(struct node*)malloc(sizeof(struct node));
newNode->data=data;
newNode->next=NULL;
temp=head;
while(temp->next!=NULL)
{
temp=temp->next;
}
temp->next=newNode;
}
void insertAtPosition(int data, int pos)
{
struct node *newNode,*temp,*temp1;
newNode=NULL;
temp=head;
newNode=(struct node*)malloc(sizeof(struct node));
newNode->data=data;
while(pos>1)
{
temp1=temp;
temp=temp->next;
pos--;
}
newNode->next=temp1->next;
temp1->next=newNode;
}
void deleteFirstNode()
{
struct node *temp;
temp=head;
head=head->next;
free(temp);
}
void deleteLastNode()
{
struct node *temp,*temp2;
temp=head;
while(temp->next!=NULL)
{
temp2=temp;
temp=temp->next;
}
temp2->next=NULL;
free(temp);
}
void deleteAtPostion(int pos)
{
struct node *temp,*temp1;
temp=head;
while(pos>1)
{
temp1=temp;
temp=temp->next;
pos--;
}
temp1->next=temp->next;
free(temp);
}
int main()
{
head=(struct node*)malloc(sizeof(struct node));
head->data=1;
head->next=NULL;
struct node *second=NULL;
struct node *third=NULL;
second=(struct node*)malloc(sizeof(struct node));
third=(struct node*)malloc(sizeof(struct node));
head->next=second;
second->data=2;
second->next=third;
third->data=3;
third->next=NULL;
printLinkList();
printf("\n");
insertAtBeginning(0);
printLinkList();
printf("\n");
insertAtEnd(4);
printLinkList();
printf("\n");
insertAtPosition(5,3);
printLinkList();
printf("\n");
deleteFirstNode();
printLinkList();
printf("\n");
deleteLastNode();
printLinkList();
printf("\n");
insertAtPosition(555,5);
printLinkList();
printf("\n");
deleteAtPostion(2);
printLinkList();
return 0;
}
|
C
|
#import "Router.h"
#define self Router
Singleton(self);
SingletonDestructor(self);
rsdef(self, New) {
return (self) {
.resources = Resources_New(75)
};
}
def(void, Destroy) {
Resources_Free(this->resources);
}
def(void, DestroyMatch, MatchingRoute match) {
if (match.pathElems != NULL) {
RdStringArray_Free(match.pathElems);
}
if (match.routeElems != NULL) {
RdStringArray_Free(match.routeElems);
}
}
def(Resources *, GetResources) {
return this->resources;
}
def(void, AddResource, ResourceInterface *resource) {
Resources_Push(&this->resources, resource);
}
static sdef(bool, IsRoot, RdStringArray *elems) {
return elems->len == 2
&& elems->buf[0].len == 0
&& elems->buf[1].len == 0;
}
static def(bool, ParseSub, RdString route, RdString path, ref(OnPart) onPart) {
ssize_t j = -1;
size_t offset = 0;
bool bracket = false;
RdString name = $("");
RdString value = $("");
fwd(i, route.len) {
if (bracket) {
if (route.buf[i] == '{') {
throw(NestedBrackets);
} else if (route.buf[i] == '}') {
bracket = false;
name = String_Slice(route, offset, i - offset);
value = String_Slice(path, j + 1);
}
} else {
if (route.buf[i] == '{') {
bracket = true;
offset = i + 1;
} else {
RdString find = String_Slice(route, i);
fwd(u, find.len) {
if (find.buf[u] == '{') {
find.len = u;
}
}
ssize_t pos = String_Find(path, j + 1, find);
if (pos == String_NotFound) {
return false;
}
value = String_Slice(path, j + 1, pos - j - 1);
callback(onPart, name, value);
name.len = 0;
i += find.len - 1;
j = pos + find.len - 1;
}
}
}
if (name.len > 0) {
callback(onPart, name, value);
}
return true;
}
def(bool, IsRouteMatching, RdStringArray *route, RdStringArray *path) {
if (route->len > path->len) {
return false;
}
/* '/' should not act as a fall-back route. */
if (scall(IsRoot, route) && !scall(IsRoot, path)) {
return false;
}
fwd(i, route->len) {
if (String_BeginsWith(route->buf[i], $(":"))) {
continue;
}
if (!call(ParseSub, route->buf[i], path->buf[i], scall(OnPart_Empty))) {
return false;
}
}
return true;
}
def(void, ExtractParts, RdStringArray *route, RdStringArray *path, ref(OnPart) onPart) {
fwd(i, route->len) {
if (String_BeginsWith(route->buf[i], $(":"))) {
if (path->buf[i].len > 0) {
RdString name = String_Slice(route->buf[i], 1);
RdString value = path->buf[i];
callback(onPart, name, value);
}
} else {
call(ParseSub, route->buf[i], path->buf[i], onPart);
}
}
}
/* Finds a matching route. */
def(MatchingRoute, FindRoute, RdString path) {
RdStringArray *arrPath = String_Split(path, '/');
fwd(i, this->resources->len) {
ResourceInterface *resource = this->resources->buf[i];
fwd(j, ResourceInterface_MaxRoutes) {
ResourceRoute *route = &resource->routes[j];
if (route->path.len == 0) {
break;
}
RdStringArray *arrRoute = String_Split(route->path, '/');
if (call(IsRouteMatching, arrRoute, arrPath)) {
MatchingRoute match = {
.route = route,
.resource = resource,
.pathElems = arrPath,
.routeElems = arrRoute
};
return match;
}
RdStringArray_Free(arrRoute);
}
}
RdStringArray_Free(arrPath);
return (MatchingRoute) { .route = NULL };
}
def(MatchingRoute, GetDefaultRoute) {
fwd(i, this->resources->len) {
ResourceInterface *resource = this->resources->buf[i];
fwd(j, ResourceInterface_MaxRoutes) {
ResourceRoute *route = &resource->routes[j];
if (route->path.len == 0) {
break;
}
if (String_Equals(route->path, $("*"))) {
return (MatchingRoute) {
.route = route,
.resource = resource
};
}
}
}
return (MatchingRoute) { .route = NULL };
}
|
C
|
/*
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define BOOKNUM 5
typedef struct book{
char nazev[30];
char prijmeni[30];
char jmeno[30];
char zanr[30];
int rok;
int cena;
int id;
}TBook;
int main(void)
{
TBook book[BOOKNUM];
char c;
//nacteni knizek
for(int i=0; i<BOOKNUM; i++){
printf("Zadej nazev knihy, prijmeni autora, jmeno autora, zanr knihy, rok vydani, cenu a id:\n");
if(scanf("%s", book[i].nazev) != 1){
printf("Invaid input.\n");
return EXIT_FAILURE;
}
if((c =getc(stdin)) != ' '){
printf("Invaid input.\n");
return EXIT_FAILURE;
}
if(scanf("%s", book[i].prijmeni) != 1){
printf("Invaid input.\n");
return EXIT_FAILURE;
}
if((c =getc(stdin)) != ' '){
printf("Invaid input.\n");
return EXIT_FAILURE;
}
if(scanf("%s", book[i].jmeno) != 1){
printf("Invaid input.\n");
return EXIT_FAILURE;
}
if((c =getc(stdin)) != ' '){
printf("Invaid input.\n");
return EXIT_FAILURE;
}
if(scanf("%s", book[i].zanr) != 1){
printf("Invaid input.\n");
return EXIT_FAILURE;
}
if((c =getc(stdin)) != ' '){
printf("Invaid input.\n");
return EXIT_FAILURE;
}
if(scanf("%d", &book[i].rok) != 1){
printf("Invaid input.\n");
return EXIT_FAILURE;
}
if((c =getc(stdin)) != ' '){
printf("Invaid input.\n");
return EXIT_FAILURE;
}
if(scanf("%d", &book[i].cena) != 1){
printf("Invaid input.\n");
return EXIT_FAILURE;
}
if((c =getc(stdin)) != ' '){
printf("Invaid input.\n");
return EXIT_FAILURE;
}
if(scanf("%d", &book[i].id) != 1){
printf("Invaid input.\n");
return EXIT_FAILURE;
}
}
printf("Romany jsou:\n");
for(int i=0; i<BOOKNUM; i++){
if(strcmp(book[i].zanr, "roman") == 0)
printf("%s\n", book[i].nazev);
}
printf("\n");
printf("Knihy s cenou mensi nez 300,- Kc jsou:\n");
for(int i=0; i<BOOKNUM; i++){
if(book[i].cena < 300)
printf("%s\n", book[i].nazev);
}
printf("\n");
printf("Prijmeni vsech autoru jsou:\n");
for(int i=0; i<BOOKNUM; i++){
printf("%s\n", book[i].prijmeni);
}
printf("\n");
return EXIT_SUCCESS;
}
|
C
|
#include <stdio.h>
// Following XXXXXX will be a function that will print using printf("my_first_function\n");
void my_first_function(){
printf("my_first_function\n");
}
int main() {
my_first_function();
return 0;
}
|
C
|
#include<stdio.h>
int main()
{
int num=0,i;
printf("you have enter number \n");
do
{
i=getch();
if(i>=48&&i<=57)
{
printf("%c",i);
num=num*10+(i-48);
}
if(i==13)
break;
}while(1);
}
|
C
|
#include <stdio.h>
#include <unistd.h>
#include <errno.h>
#define OPEN_MAX ((int)sysconf(_SC_OPEN_MAX)) /* 一个进程最多能打开的文件数,也是文件描述符的最大值 */
int mydup2(int oldfd, int newfd)
{
int i, j, fd[OPEN_MAX];
/* 首先检验文件描述符的范围是否正确 */
if (oldfd < 0 || oldfd > (OPEN_MAX-1))
{
perror("oldfd error");
return -1;
}
if(newfd < 0 || newfd > (OPEN_MAX - 1))
{
perror("newfd error");
return -1;
}
/* 相等时返回newfd */
if(oldfd == newfd)
return newfd;
/* 先关闭newfd,好让dup时能有机会选择newfd作为返回值 */
close(newfd);
for(i=0; i<OPEN_MAX; i++)
{
if((fd[i] = dup(oldfd)) < 0)
{
perror("dup error");
return -1;
}
/* 关掉之前dup出来的文件描述符 */
if(fd[i] == newfd)
{
for(j=0; j<i; j++)
close(fd[j]);
return newfd;
}
}
return -1;
}
int main(int argc, char const *argv[])
{
int retfd;
if((retfd = mydup2(2, 5)) < 0)
{
perror("mydup2 error");
return -1;
}
printf("dup result:%d\n", retfd);
return 0;
}
/* result:
st@ubuntu:~/git_project/APUE/ch3_FileIO/answer$ ./a.out
dup result:5 -->返回值是newfd参数说明mydup2是正确执行了的
*/
|
C
|
#include <dirent.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <regex.h>
#include <fcntl.h>
#include <unistd.h>
// Splicing two strings and return a pointer
char* join(char *s1, char *s2)
{
char *result = malloc(strlen(s1)+strlen(s2)+1);
if (result == NULL) exit (1);
strcpy(result, s1);
strcat(result, s2);
return result;
}
// Preprocessor of regular expression
char *regular(char *path_0){
char *path = malloc(16);
char *path_1 = malloc(16);
strcpy(path,path_0);
for(int i = 0;i < sizeof(path);i++){
if(path[i]=='*'){
for(int j = sizeof(path);j >= i;j--){
path[j+1] = path[j];
}
path[i] = '.';
i++;
}
if(path[i]=='.'){
for(int j = sizeof(path);j >= i;j--){
path[j+1] = path[j];
}
path[i] = '\\';
i++;
}
}
strcpy(path_1,path);
return path_1;
}
// Compare path(the file name) to file_name(the input)
int judge_byname(char *path, char *file_name){
int status;
int cflags = REG_EXTENDED;
regmatch_t pmatch[1];
const size_t nmatch = 1;
regex_t reg;
const char * pattern = regular(file_name);
regcomp(®, pattern, cflags);
status = regexec(®, path, nmatch, pmatch, 0);
if(status == REG_NOMATCH){
return 1;
// not match
}else if(status == 0){
// match
return 0;
}
return 0;
}
// Compare path(the file content) to buffer(the processed inputed regular expression)
int judge_bycontent(char *path, char *buffer){
int status;
int cflags = REG_EXTENDED;
regmatch_t pmatch[1];
const size_t nmatch = 1;
regex_t reg;
const char * pattern = regular(buffer);
regcomp(®, pattern, cflags);
int file = open(path,O_RDONLY);
char buffer_0[2048];
ssize_t read_n;
read_n = read(file,buffer_0,2048);
char *buf = buffer_0;
if(read_n!=-1){
status = regexec(®, buf, nmatch, pmatch, 0);
if(status == REG_NOMATCH){
return 1;
// not match
}else if(status == 0){
// match
return 0;
}
}
regfree(®);
return 0;
}
// Search file by name and content judged by oper in path
int find_n(int oper,char *path,char *name_content,char *name_content_1){
DIR *dirp;
struct dirent *direntp;
dirp=opendir(path);
if(!dirp){
return 1;
}
while((direntp=readdir(dirp))!=NULL)
{
if(direntp->d_name[0] == '.' || strcmp(direntp->d_name,"..") == 0){
continue;
}
if(direntp->d_type == 4){
char *path_1;
if(strcmp(path,"/")==0){
path_1 = join("/",direntp->d_name);
}else{
path_1 = join(join(path,"/"),direntp->d_name);
}
find_n(oper,path_1,name_content,name_content_1);
}
if(direntp->d_type == 8){
if(oper == 1&&judge_byname(direntp->d_name,name_content)==0){
printf("file founded! location:%s\n",join(join(path,"/"),direntp->d_name));
}else if(oper == 2&&judge_bycontent(join(join(path,"/"),direntp->d_name),name_content)==0){
printf("file founded! location:%s\n",join(join(path,"/"),direntp->d_name));
}else if(oper == 3&&judge_byname(direntp->d_name,name_content)==0
&&judge_bycontent(join(join(path,"/"),direntp->d_name),name_content_1)==0){
printf("file founded! location:%s\n",join(join(path,"/"),direntp->d_name));
}
}
}
closedir(dirp);
return 0;
}
// First fuction to be used
void find(char *oper,char *path,char *name_content,char *name_content_1){
if(strcmp(oper,"-name")==0){
find_n(1,path,name_content,NULL);
}else if(strcmp(oper,"-content")==0){
find_n(2,path,name_content,NULL);
}else if(strcmp(oper,"-name-content")==0){
find_n(3,path,name_content,name_content_1);
}
}
int main (int argc, char *argv[]){
if(argc == 4){
find(argv[1],argv[3],argv[2],NULL);
return 0;
}else if(argc == 6){
if(strcmp(argv[1],"-name")==0 && strcmp(argv[3],"-content")==0){
find("-name-content",argv[5],argv[2],argv[4]);
}else if(strcmp(argv[3],"-name")==0 && strcmp(argv[1],"-content")==0){
find("-name-content",argv[5],argv[4],argv[2]);
}else {
printf("Wrong operation!\nUsage:rfind -name/-content str -content/-name str dir\n");
}
return 0;
}else{
printf("Wrong operation!\nUsage:rfind -name/-content str -content/-name str dir\n");
return 1;
}
}
|
C
|
/*
* Copyright 2014-2015 Dario Manesku. All rights reserved.
* License: http://www.opensource.org/licenses/BSD-2-Clause
*/
uint16_t alloc()
{
DM_CHECK(m_numHandles < max(), "handleAllocAlloc | %d, %d", m_numHandles, max());
if (m_numHandles < max())
{
const uint16_t index = m_numHandles++;
const uint16_t handle = m_handles[index];
uint16_t* sparse = &m_handles[max()];
sparse[handle] = index;
return handle;
}
return HandleAlloc::Invalid;
}
bool contains(uint16_t _handle)
{
DM_CHECK(_handle < max(), "handleAllocContains | %d, %d", _handle, max());
uint16_t* sparse = &m_handles[max()];
uint16_t index = sparse[_handle];
return (index < m_numHandles && m_handles[index] == _handle);
}
void free(uint16_t _handle)
{
DM_CHECK(m_numHandles > 0, "handleAllocFree | %d", m_numHandles);
uint16_t* sparse = &m_handles[max()];
uint16_t index = sparse[_handle];
if (index < m_numHandles && m_handles[index] == _handle)
{
--m_numHandles;
uint16_t temp = m_handles[m_numHandles];
m_handles[m_numHandles] = _handle;
sparse[temp] = index;
m_handles[index] = temp;
}
}
const uint16_t* getHandles() const
{
return m_handles;
}
uint16_t getHandleAt(uint16_t _idx) const
{
return m_handles[_idx];
}
void reset()
{
m_numHandles = 0;
for (uint16_t ii = 0, end = max(); ii < end; ++ii)
{
m_handles[ii] = ii;
}
}
/* vim: set sw=4 ts=4 expandtab: */
|
C
|
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<malloc.h>
typedef struct Qlist //定义顺序队列
{
int data[10];
int front;
int rear;
}Qlist;
void first(Qlist*a) //初始化
{
a->front = -1;
a->rear = -1;
}
void inQlist(Qlist* a, int n) //进
{
if (a->front == -1 && a->rear == -1) //第一次进队列
{
a->front = 0;
a->rear = 0;
a->data[0] = n;
}
else
{
a->rear++;
if (a->rear > 10)
{
printf("满\n");
a->rear--;
}
else
{
a->data[a->rear] = n;
}
}
}
int outQlist(Qlist* a) //出
{
int n;
if (a->front > a->rear ) //判断是不是满
{
printf("满\n");
return -1;
}
else
{
n = a->data[a->front];
a->front++;
return n;
}
}
int main()
{
int y;
Qlist* a;
a = (Qlist*)malloc(sizeof(Qlist));
first(a);
inQlist(a, 1);
inQlist(a, 2);
inQlist(a, 3);
y = outQlist(a);
printf("%d", y);
y = outQlist(a);
printf("%d", y);
y = outQlist(a);
printf("%d", y);
y = outQlist(a);
printf("%d", y);
return 0;
}
|
C
|
#ifndef __KMY_PRINTERDRV_H
#define __KMY_PRINTERDRV_H
#define Printer_OK 1
#define Printer_NoPaper 2
#define Printer_TooHot 3
#define Printer_InitError 4
#define Printer_InitOK 5
#define Printer_15sNoResponse 6 //ӡַʱ15sڴӡδȱֽӦ
extern const unsigned char WidthZoom1[3];
extern const unsigned char WidthZoom2[3];
extern const unsigned char WidthZoom3[3];
extern const unsigned char WidthZoom4[3];
extern const unsigned char WidthZoom5[3];
//const unsigned char WidthZoom0[3]={"\x1B\x55\x00"};
extern const unsigned char HighZoom1[3];
extern const unsigned char HighZoom2[3];
extern const unsigned char HighZoom3[3];
extern const unsigned char HighZoom4[3];
extern const unsigned char HighZoom5[3];
unsigned char kmy_PrinterInit(void);
//ܣӡʼ
//
//ֵ
// ʼPrinter_InitOK
// ʼ쳣Printer_InitError
//ע
char kmy_PrinterSetcommand(const unsigned char * command,unsigned char len);
//ܣӡ
//
// command: ַ
// len:
//ֵ
// óɹ(궨)Printer_OK
//ע
char kmy_PrinterString(const unsigned char * ch);
//ܣӡӡַ
//
// ch: ַ
//ֵ
// ӡɷ(궨)Printer_OK
// ȱֽ(궨)Printer_NoPaper
// ӡͷ̫ȷ(궨)Printer_TooHot
// 15s δյȱֽӦ(궨)Printer_15sNoResponse
//ע
// 1. chַȾС2048bytes
char kmy_PrinterBitmap(const unsigned char *p,unsigned int width, unsigned int height,unsigned int LeftMarginNum);
//ܣӡӡλͼ
//
// p: λͼݻַ
// width: λͼ
// height: λͼ߶
// LeftMarginNum: λͼĵ㿪ʼ
//ֵ
// ӡɷ(궨)Printer_OK
// ȱֽ(궨)Printer_NoPaper
// ӡͷ̫ȷ(궨)Printer_TooHot
//ע
// λͼʽΪ:ɫҺģȡģֽڵ
// LeftMarginNum+widthֵӦС384
// λͼĿΪ384
#endif
|
C
|
#include <stdio.h>
#include <string.h>
int main(){
int num = 0;
scanf("%d", &num);
int size = strlen(num);
int mod = 10;
int aux = 0;
int auxant = 0;
int vet[size];
for(int i = size;i >= 0;i--){
aux = num % mod;
if(i == size){
vet[i] = aux;
}
aux = (num - auxant) % mod;
mod = mod * 10;
if(i != num){
vet[i] = aux;
}
auxant = aux;
}
for(int i = 0;i < size;i++){
printf("%d", vet[i]);
}
}
|
C
|
#include "headers/servidor.h"
int iniciarServidor (int puerto)
{
int fd = 0, opc = 1, sfd = 0;
struct addrinfo Direccion,*res;
char auxport[5];
sprintf(auxport,"%d",puerto);
/********INICIALIZAR*****/
memset(&Direccion,0, sizeof (struct addrinfo));
/************************/
Direccion.ai_family = AF_UNSPEC;
Direccion.ai_socktype= SOCK_STREAM;
Direccion.ai_flags = AI_PASSIVE;
// TODO Harcodie el puerto MAL jaja
if((getaddrinfo(NULL,auxport,&Direccion,&res))!=0){
perror("getaddrinfo:");
exit(EXIT_FAILURE);
}
do
{
sfd = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
if (sfd < 0)
continue;
setsockopt(sfd,SOL_SOCKET,SO_REUSEADDR,&opc,sizeof (opc));
if (bind(sfd, res->ai_addr, res->ai_addrlen) != 0){
perror("bind");
exit(EXIT_FAILURE);
}
}while((res=res->ai_next)!=NULL);
freeaddrinfo(res);
listen(sfd,10);
return sfd;
}
|
C
|
#include<stdio.h>
int fibo(int n)
{
if(n==1) return 1;
if(n==2) return 1;
else return fibo(n-1)+fibo(n-2);
}
int main()
{
int n;
printf("enter the term u want to print");
scanf("%d",&n);
printf("%d",fibo(n));
fflush(stdin);
getchar();
}
|
C
|
#include "libxml/parser.h"
#include <libxml/tree.h>
#include <libxml/xmlmemory.h>
#include "user_xml_common.h"
#include "cgic.h"
//创建xml_file
int create_xml_file(const char *xml_file)
{
//assert(xml_file);
xmlDocPtr doc = NULL;
xmlNodePtr root_node = NULL;
//创建一个xml 文档
doc = xmlNewDoc(BAD_CAST"1.0");
if (doc == NULL) {
fprintf(stderr, "Failed to new doc.\n");
return -1;
}
//创建根节点
root_node = xmlNewNode(NULL, BAD_CAST"root");
if (root_node == NULL) {
fprintf(stderr, "Failed to new root node.\n");
goto FAILED;
}
//将根节点添加到文档中
xmlDocSetRootElement(doc, root_node);
//将文档保存到文件中,按照utf-8编码格式保存
xmlSaveFormatFileEnc(xml_file, doc, "UTF-8", 1);
xmlFreeDoc(doc);
return 0;
FAILED:
if (doc) {
xmlFreeDoc(doc);
}
return -1;
}
//向根节点添加一个节点
int add_node_info(const char* file_name, xmlNodePtr node)
{
//获取根节点
xmlDocPtr doc; //整个xml文档的树形结构
xmlNodePtr root_node; //xml节点
//获取树形结构
doc = xmlParseFile(file_name);
if(doc == NULL)
{
fprintf(stderr, "Failed to parse xml file:%s \n",file_name);
goto FAILED;
}
//获取根节点
root_node = xmlDocGetRootElement(doc);
if(root_node ==NULL)
{
fprintf(stderr, "Failed to get root node.\n");
goto FAILED;
}
//向根节点添加一个子节点
xmlAddChild(root_node,node);
xmlSaveFormatFileEnc(file_name,doc,"UTF-8",1);
xmlFreeDoc(doc);
return 0;
FAILED:
if (doc) {
xmlFreeDoc(doc);
}
return -1;
}
//删除一个节点文件
int del_xml_node(const char * file_name, int number,const char * node_nmae)
{
xmlNodePtr root_node = NULL;
xmlNodePtr cur_node = NULL;
xmlDocPtr doc; //整个xml文档的树形结构
int code =1;
int i;
//获取树形结构
doc = xmlParseFile(file_name);
if(doc == NULL)
{
fprintf(cgiOut, "Failed to parse xml file:%s \n",file_name);
goto FAILED;
}
//获取根节点
root_node = xmlDocGetRootElement(doc);
if(root_node ==NULL)
{
fprintf(cgiOut, "Failed to get root node.\n");
goto FAILED;
}
///判断根节点是否符合预先输入的内容
if (xmlStrcmp(root_node->name, (const xmlChar *)"root")) {
fprintf(cgiOut, "The root is not root.\n");
goto FAILED;
}
//遍历处理根节点的每一个子节点
cur_node = root_node->xmlChildrenNode;
while (cur_node != NULL)
{
if (!xmlStrcmp(cur_node->name, (const xmlChar *)node_nmae))
{
i++;
if(number==i)
{
xmlNodePtr tempNode;
tempNode = cur_node->next;
xmlUnlinkNode(cur_node);
xmlFreeNode(cur_node);
cur_node=tempNode;
continue;
}
}
cur_node = cur_node->next;
}
xmlSaveFormatFileEnc(file_name, doc, "UTF-8", 1);
//xmlSaveFile(IP_GROUP_FILE,doc);
xmlFreeDoc(doc);
return code;
FAILED:
if (doc) {
xmlFreeDoc(doc);
}
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define WATCHED 1
#define ON 2
#define OFF 0
int graph[1000][1000];
int count[1000];
int visited[1000];
int vertex, edge;
int cnt;
int gallery(int num, int isRoot){
visited[num] = 1;
int isWatched = 0;
int ret, check = 0;
for(int i=0; i<count[num]; i++){
if(visited[graph[num][i]] == 1)
continue;
ret = gallery(graph[num][i], 0);
if(ret == 2)
check = 1;
isWatched = isWatched || !ret;
}
if(isRoot && check != 1){
cnt++;
return -1;
}
else if(isWatched){
cnt++;
return ON;
}
else if(check)
return WATCHED;
return OFF;
}
void galleryAll(){
for(int i=0; i<vertex; i++)
if(visited[i] == -1)
gallery(i, 1);
}
int main() {
int caseNum;
scanf("%d", &caseNum);
int answer[caseNum];
for(int i=0; i<caseNum; i++){
memset(visited, -1, sizeof(visited));
memset(graph, -1, sizeof(graph));
memset(count, 0, sizeof(count));
cnt = 0;
scanf("%d%d", &vertex, &edge);
for(int j=0; j<edge; j++){
int num1, num2;
scanf("%d%d", &num1, &num2);
graph[num1][count[num1]++] = num2;
graph[num2][count[num2]++] = num1;
}
galleryAll();
answer[i] = cnt;
}
for(int i=0; i<caseNum; i++)
printf("%d\n", answer[i]);
return 0;
}
|
C
|
#ifndef _LINUX_JHASH_H
#define _LINUX_JHASH_H
/* jhash.h: Jenkins hash support.
*
* Copyright (C) 2006. Bob Jenkins (bob_jenkins@burtleburtle.net)
*
* http://burtleburtle.net/bob/hash/
*
* These are the credits from Bob's sources:
*
* lookup3.c, by Bob Jenkins, May 2006, Public Domain.
*
* These are functions for producing 32-bit hashes for hash table lookup.
* hashword(), hashlittle(), hashlittle2(), hashbig(), mix(), and final()
* are externally useful functions. Routines to test the hash are included
* if SELF_TEST is defined. You can use this free for any purpose. It's in
* the public domain. It has no warranty.
*
* Copyright (C) 2009-2010 Jozsef Kadlecsik (kadlec@blackhole.kfki.hu)
*
* I've modified Bob's hash to be useful in the Linux kernel, and
* any bugs present are my fault.
* Jozsef
*/
#include <linux/bitops.h>
#include <linux/unaligned/packed_struct.h>
/* Best hash sizes are of power of two */
#define jhash_size(n) ((u32)1<<(n))
/* Mask the hash value, i.e (value & jhash_mask(n)) instead of (value % n) */
#define jhash_mask(n) (jhash_size(n)-1)
/* __jhash_mix -- mix 3 32-bit values reversibly. */
#define __jhash_mix(a, b, c) \
{ \
a -= c; a ^= rol32(c, 4); c += b; \
b -= a; b ^= rol32(a, 6); a += c; \
c -= b; c ^= rol32(b, 8); b += a; \
a -= c; a ^= rol32(c, 16); c += b; \
b -= a; b ^= rol32(a, 19); a += c; \
c -= b; c ^= rol32(b, 4); b += a; \
}
/* __jhash_final - final mixing of 3 32-bit values (a,b,c) into c */
#define __jhash_final(a, b, c) \
{ \
c ^= b; c -= rol32(b, 14); \
a ^= c; a -= rol32(c, 11); \
b ^= a; b -= rol32(a, 25); \
c ^= b; c -= rol32(b, 16); \
a ^= c; a -= rol32(c, 4); \
b ^= a; b -= rol32(a, 14); \
c ^= b; c -= rol32(b, 24); \
}
/* An arbitrary initial parameter */
#define JHASH_INITVAL 0xdeadbeef
/* jhash - hash an arbitrary key
* @k: sequence of bytes as key
* @length: the length of the key
* @initval: the previous hash, or an arbitray value
*
* The generic version, hashes an arbitrary sequence of bytes.
* No alignment or length assumptions are made about the input key.
*
* Returns the hash value of the key. The result depends on endianness.
*/
static inline u32 jhash(const void *key, u32 length, u32 initval)
{
u32 a, b, c;
const u8 *k = key;
/* Set up the internal state */
a = b = c = JHASH_INITVAL + length + initval;
/* All but the last block: affect some 32 bits of (a,b,c) */
while (length > 12) {
a += __get_unaligned_cpu32(k);
b += __get_unaligned_cpu32(k + 4);
c += __get_unaligned_cpu32(k + 8);
__jhash_mix(a, b, c);
length -= 12;
k += 12;
}
/* Last block: affect all 32 bits of (c) */
/* All the case statements fall through */
switch (length) {
case 12: c += (u32)k[11]<<24;
case 11: c += (u32)k[10]<<16;
case 10: c += (u32)k[9]<<8;
case 9: c += k[8];
case 8: b += (u32)k[7]<<24;
case 7: b += (u32)k[6]<<16;
case 6: b += (u32)k[5]<<8;
case 5: b += k[4];
case 4: a += (u32)k[3]<<24;
case 3: a += (u32)k[2]<<16;
case 2: a += (u32)k[1]<<8;
case 1: a += k[0];
__jhash_final(a, b, c);
case 0: /* Nothing left to add */
break;
}
return c;
}
/* jhash2 - hash an array of u32's
* @k: the key which must be an array of u32's
* @length: the number of u32's in the key
* @initval: the previous hash, or an arbitray value
*
* Returns the hash value of the key.
*/
static inline u32 jhash2(const u32 *k, u32 length, u32 initval)
{
u32 a, b, c;
/* Set up the internal state */
a = b = c = JHASH_INITVAL + (length<<2) + initval;
/* Handle most of the key */
while (length > 3) {
a += k[0];
b += k[1];
c += k[2];
__jhash_mix(a, b, c);
length -= 3;
k += 3;
}
/* Handle the last 3 u32's: all the case statements fall through */
switch (length) {
case 3: c += k[2];
case 2: b += k[1];
case 1: a += k[0];
__jhash_final(a, b, c);
case 0: /* Nothing left to add */
break;
}
return c;
}
/* jhash_3words - hash exactly 3, 2 or 1 word(s) */
static inline u32 jhash_3words(u32 a, u32 b, u32 c, u32 initval)
{
a += JHASH_INITVAL;
b += JHASH_INITVAL;
c += initval;
__jhash_final(a, b, c);
return c;
}
static inline u32 jhash_2words(u32 a, u32 b, u32 initval)
{
return jhash_3words(a, b, 0, initval);
}
static inline u32 jhash_1word(u32 a, u32 initval)
{
return jhash_3words(a, 0, 0, initval);
}
#endif /* _LINUX_JHASH_H */
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <sys/time.h>
#include <smmintrin.h>
#define N 600000
double gettime(void)
{
struct timeval tv;
gettimeofday(&tv,NULL);
return tv.tv_sec + 1e-6*tv.tv_usec;
}
int main(int argc, char *argv[])
{
float r[N], a[N], b[N], maxvector[4];
float max = 0.0;
int i;
double dtime;
// Initialize input matrices
for (i = 0; i < N; i++)
{
a[i] = (float) i;
b[N-i-1] = (float) 2*i;
}
// Loop
dtime = gettime();
/* for (i = 0; i < N; i++)
{
r[i] = sqrtf(a[i]*a[i] + b[i]*b[i]) + 0.5;
if (r[i] > max) max = r[i];
}
*/
__m128 matmax;
for (i = 0; i < N; i+=4) {
__m128 av = _mm_load_ps(&a[i]);
__m128 bv = _mm_load_ps(&b[i]);
av = _mm_mul_ps(av,av);
bv = _mm_mul_ps(bv,bv);
__m128 vfinal = _mm_add_ps(av,bv);
vfinal = _mm_sqrt_ps(vfinal);
vfinal = _mm_add_ps(vfinal, _mm_set1_ps(0.5));
matmax = _mm_max_ps(vfinal, matmax);
_mm_store_ps(&r[i],vfinal);
}
_mm_store_ps(&maxvector[0],matmax);
for (i = 0; i<4; i++) {
if (maxvector[i] > max) {
max = maxvector[i];
}
}
dtime = gettime() - dtime;
// Print results
printf("r: %f %f %f %f %f %f\n",r[0],r[1],r[2],r[3],r[1000],r[1001]);
printf("max: %f\n",max);
printf("Exec time: %9.5f sec.\n",dtime);
}
|
C
|
#include "header.h"
char *getSum(char *a, char *b)
{
int i = 6;
int add = 0;
while (--i >= 0)
{
if (a[i] == '0' && b[i] == '0')
{
a[i] = '0' + add;
add = 0;
}
else if (a[i] != b[i])
a[i] = '1' - add;
else{
a[i] = '0' + add;
add = 1;
}
}
return (a);
}
int toInt(char *bits)
{
char* start = bits;
int total = 0;
while (*start)
{
total *= 2;
if (*start++ == '1')
total += 1;
}
return (total);
}
|
C
|
#include <stdio.h>
void print_array(int* a, int size) {
int i;
for (i=0; i<size; i++) {
printf("%4d", *(a+i));
}
putchar('\n');
}
int main() {
int a[] = {1,2,3,4,5,6,7,8,9};
print_array(a, sizeof(a)/sizeof(a[0]));
return 0;
}
|
C
|
/* TODO
[x] Implement -f -d -s
[x] Rewrite the whole delimiter thing
[ ] Fix the bug in -f delimiters
[ ] Add multibyte delimiter support
[ ] Field delimiter can't be newline
Notes after reading FreeBSD version:
1. I could have used getc, instead of managing local buffer
2. if *buf = 1 printf("%d - %d", *buf, *buf++) will print [soemthing]
- 1, because right expressions are evaluated first.
3. fgetln BSD version of getline
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <limits.h>
#include <ctype.h>
#include <locale.h>
#include <unistd.h>
#include <getopt.h>
#define BUF_SIZE 1024
struct option long_opt[] = {
{"bytes", required_argument, NULL, 'b'},
{"characters", required_argument, NULL, 'c'},
{"delimiter", required_argument, NULL, 'd'},
{"fields", required_argument, NULL, 'f'},
{"complement", no_argument, NULL, 'm'},
{"only-deilimited", no_argument, NULL, 's'},
{"output-delimiter", required_argument, NULL, 'o'},
{"zero-terminated", no_argument, NULL, 'z'},
{"help", no_argument, NULL, 'h'},
{"version", no_argument, NULL, 'v'},
{NULL, 0, NULL, 0}
};
struct range {
long high;
long low;
struct range *next;
struct range *prev;
};
enum operation_mode {bflag, fflag, none};
static struct range *ranges;
static char field_delimiter;
static int complement;
static int zero_terminate;
static char *output_delimiter;
/*TODO - write real error messages */
void usage(int status)
{
if (status != EXIT_SUCCESS) {
fputs("Usage: [program_name] [-flags blabla]\n", stderr);
} else {
puts("This is how you use the program, bye");
}
exit(status);
}
/* Implement the list parser as FSA */
#define INITIAL 0 // Init state
#define INIT_DASH 1 // [-]
#define INIT_NUM 2 // [num]
#define DASH_NUM 3 // -[num]
#define NUM_DASH 4 // num[-]
#define NUM_DASH_NUM 5 // num-[num]
#define END 6 // '\0'
/* FSA was not a good idea, function became unreadable. No wonder, neither
* coreutils nor BSD does FSA, both versions parse text using simple if else
* statements, ANYWAY I have to write this FSA till the end*/
void initialize_ranges(char *list)
{
int state;
struct range *curr;
struct range *prev;
int cont;
state = INITIAL;
cont = 1;
curr = prev = NULL;
while (cont) {
switch(state){
case INITIAL:
prev = curr;
curr = malloc(sizeof(struct range));
memset(curr, 0, sizeof(struct range));
if (!ranges) /*first elem in linked-list*/
ranges = curr;
if (prev != NULL) {
prev->next = curr;
curr->prev = prev;
}
if (*list == '-') {
list++;
state = INIT_DASH;
} else if (isdigit(*list)) {
state = INIT_NUM;
} else {
usage(EXIT_FAILURE);
}
break;
case INIT_DASH:
curr->low = 1;
if (isdigit(*list)) {
state = DASH_NUM;
} else {
usage(EXIT_FAILURE);
}
break;
case INIT_NUM:
curr->low = strtol(list, &list, 10);
curr->high = curr->low;
if (*list == '-') {
list++;
state = NUM_DASH;
} else if (*list == ',') {
list++;
state = INITIAL;
} else if (*list == '\0') {
state = END;
} else {
usage(EXIT_FAILURE);
}
break;
case DASH_NUM:
curr->high = strtol(list, &list, 10);
if (*list == ',') {
state = INITIAL;
list++;
} else if (*list == '\0') {
state = END;
} else {
usage(EXIT_FAILURE);
}
break;
case NUM_DASH:
curr->high = LONG_MAX;
if (*list == ',') {
list++;
state = INITIAL;
} else if (isdigit(*list)) {
state = NUM_DASH_NUM;
} else if (*list == '\0') {
state = END;
} else {
usage(EXIT_FAILURE);
}
break;
case NUM_DASH_NUM:
curr->high = strtol(list, &list, 10);
if (curr->high < curr->low) {
fputs("Range should be increasing\n", stderr);
usage(EXIT_FAILURE);
}
if (*list == ',') {
list++;
state = INITIAL;
} else if (*list == '\0') {
state = END;
} else {
usage(EXIT_FAILURE);
}
break;
case END:
cont = 0;
break;
default:
usage(EXIT_FAILURE);
}
}
}
/* TODO -This is very inefficient as it iterates over the linked list for every
* byte in the files */
int in_range(int indx)
{
struct range *tmp;
tmp = ranges;
indx++; // Indexes start from 0, while ranges start from 1
while (tmp != NULL) {
if (tmp->low <= indx && tmp->high >= indx) {
return 1 ^ complement;
}
tmp = tmp->next;
}
return complement; // 0 ^ complement is same as complement
}
void bcut(FILE *f)
{
int j;
int indx;
int btread; /* number of bytes read from the file */
char *buf;
int prev_out; /* 1 - previous token was outputed, 0 - was not*/
int first; /* It's the first token of the line */
buf = malloc(sizeof(char) * 1024);
indx = 0;
prev_out = 0;
first = 1;
while ((btread = fread(buf, 1, BUF_SIZE, f)) != 0) {
for (j = 0; j < btread; j++) {
if (indx == 0) {
first = 1;
prev_out = 0;
}
if (buf[j] == '\n') {
fputc(zero_terminate ? '\0' : '\n',
stdout);
indx = 0;
} else if (in_range(indx)) {
if (prev_out == 0 && !first) {
printf("%s", output_delimiter);
}
prev_out = 1;
first = 0;
fputc(buf[j], stdout);
indx++;
} else {
indx++;
prev_out = 0;
}
}
}
free(buf);
}
void fcut(FILE *f)
{
int i;
int indx;
int output; /*bool value, 1 output char, 0 do not */
int btread;
char *buf;
int prev_out; /* 1 - previous token was outputed, 0 - was not*/
int first; /* It's the first token of the line */
buf = malloc(sizeof(char) * BUF_SIZE);
indx = 0;
prev_out = 0;
first = 1;
output = in_range(indx);
while ((btread = fread(buf, 1, BUF_SIZE, f)) != 0) {
for (i = 0; i < btread; i++) {
if (indx == 0) {
first = 1;
prev_out = 0;
}
if (buf[i] == '\n') {
fputc(zero_terminate ? '\0' : '\n',
stdout);
indx = 0;
output = in_range(indx);
} else if (buf[i] == field_delimiter) {
indx++;
output = in_range(indx);
fprintf(stderr, "DEL - >po %d, out %d\n",
prev_out, output);
if (prev_out && output)
fputc(buf[i], stdout);
} else if (output) {
fputc(buf[i], stdout);
if (prev_out == 0 && !first) {
printf("%s", output_delimiter);
}
prev_out = 1;
} else {
prev_out = 0;
}
}
}
}
void do_cut(enum operation_mode mode, char *argv[], int size)
{
int i;
FILE *f;
for (i = 0; i < size; i++) {
if ((f = fopen(argv[i], "r")) == NULL) {
fprintf(stderr, "couldn't open the file %s\n", argv[i]);
} else if (mode == bflag) {
bcut(f);
} else if (mode == fflag) {
fcut(f);
}
}
}
int main(int argc, char *argv[])
{
int ch;
char *list_range;
enum operation_mode mode = none;
output_delimiter = NULL;
setlocale(LC_ALL, "");
while ((ch = getopt_long(argc, argv, "b:c:f:d:nsz", long_opt, NULL)) != -1) {
switch(ch) {
case 'b':
case 'c': // -b and -c options are the same
if(mode != none)
usage(EXIT_FAILURE);
mode = bflag;
list_range = optarg;
break;
case 'f':
if(mode != none)
usage(EXIT_FAILURE);
mode = fflag;
list_range = optarg;
break;
case 'd':
/*TODO - add multibyte delimiter later */
if (strlen(optarg) != 1)
usage(EXIT_FAILURE);
field_delimiter = *optarg;
break;
case 'n':
/* Ignore this option */
break;
case 'm':
complement = 1;
break;
case 's':
break;
case 'o':
output_delimiter = optarg;
break;
case 'z':
zero_terminate = 1;
break;
case 'h':
usage(EXIT_SUCCESS);
break;
case 'v':
puts("VERSION HERE");
exit(EXIT_SUCCESS);
default:
usage(EXIT_FAILURE);
}
}
if (mode != bflag && mode != fflag)
usage(EXIT_FAILURE);
if (optind == argc)
usage(EXIT_FAILURE);
if (mode == fflag && !output_delimiter) {
char del[2] = { field_delimiter, '\0'};
output_delimiter = del;
}
initialize_ranges(list_range);
do_cut(mode, argv + optind, argc - optind);
exit(EXIT_SUCCESS);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
struct node {
int data;
struct node *next;
};
struct queue {
struct node *front;
struct node *rear;
};
void dequeue (struct queue **q) {
int dequeue_data;
if (NULL == (*q)->front) {
printf("Empty Queue\n");
return;
}
dequeue_data = (*q)->front->data;
struct node *temp = (*q)->front;
(*q)->front = (*q)->front->next;
printf("Removed node from Queue\nData[%d]\n", dequeue_data);
free(temp);
return;
}
void enqueue (struct queue **q, int data) {
struct node *new = (struct node *) malloc(sizeof(struct node));
new->data = data;
new->next = NULL;
if (NULL == (*q)->rear) {
(*q)->rear = (*q)->front = new;
printf("Adding node to Empty Queue\nData[%d]\n", (*q)->rear->data);
return;
}
(*q)->rear->next = new;
(*q)->rear = new;
printf("Adding node to Queue\nData[%d]\n", (*q)->rear->data);
return;
}
int main (void) {
struct queue *q = (struct queue *) malloc(sizeof(struct queue));
q->front = q->rear = NULL;
enqueue(&q, 1);
enqueue(&q, 2);
enqueue(&q, 3);
dequeue(&q);
dequeue(&q);
dequeue(&q);
dequeue(&q);
return 0;
}
|
C
|
#ifndef JSON_H
#define JSON_H
/**
* JSON type enumerator.
* @json_null_v: Null.
* @json_true_v: True boolean.
* @json_false_v: False boolean.
* @json_num_v: Number.
* @json_str_v: String.
* @json_arr_v: Array.
* @json_obj_v: Object.
*/
enum json_e {
json_null_v,
json_true_v,
json_false_v,
json_num_v,
json_str_v,
json_obj_v,
json_arr_v
};
/**
* JSON data union.
* @num: The number.
* @str: The string.
* @arr: The array.
* @obj: The object.
*/
union json_u {
double num;
char *str;
struct json_arr_t *arr;
struct json_obj_t *obj;
};
/**
* JSON value structure.
* @type: The type.
* @data: The data.
*/
struct json_t {
enum json_e type;
union json_u data;
};
/**
* JSON array structure.
* @vec: The vector.
* @len: The length.
*/
struct json_arr_t {
struct json_t **vec;
unsigned int len;
};
/**
* JSON object structure.
* @root: Property tree root.
*/
struct json_obj_t {
struct avltree_root_t root;
};
/**
* JSON property structure.
* @key: The key.
* @value: The value.
* @node: The tree node.
*/
struct json_prop_t {
char *key;
struct json_t *value;
struct avltree_node_t node;
};
/*
* json declarations
*/
struct json_t *json_new(enum json_e type, union json_u data);
void json_delete(struct json_t *json);
struct json_t *json_null(void);
struct json_t *json_bool(bool flag);
struct json_t *json_num(double num);
struct json_t *json_str(char *str);
struct json_t *json_arr(struct json_arr_t *arr);
struct io_chunk_t json_chunk(const struct json_t *json);
void json_print(struct json_t *json, struct io_file_t file);
/*
* array declarations
*/
struct json_arr_t *json_arr_new(void);
void json_arr_delete(struct json_arr_t *arr);
void json_arr_append(struct json_arr_t *arr, struct json_t *el);
struct io_chunk_t json_arr_chunk(const struct json_t *json);
void json_arr_print(struct json_arr_t *arr, struct io_file_t file);
/*
* object declarations
*/
struct json_obj_t *json_obj_new(void);
void json_obj_delete(struct json_obj_t *obj);
struct json_prop_t *json_obj_add(struct json_obj_t *obj, char *key, struct json_t *value);
struct json_prop_t *json_obj_get(struct json_obj_t *obj, const char *key);
struct json_t *json_obj_getval(struct json_obj_t *obj, const char *key);
struct json_prop_t *json_obj_first(struct json_obj_t *obj);
struct json_prop_t *json_obj_last(struct json_obj_t *obj);
struct json_prop_t *json_obj_prev(struct json_prop_t *prop);
struct json_prop_t *json_obj_next(struct json_prop_t *prop);
struct io_chunk_t json_obj_chunk(const struct json_obj_t *json);
void json_obj_print(struct json_obj_t *obj, struct io_file_t file);
char *json_parse_file(struct json_t **json, struct io_file_t file);
char *json_parse_str(struct json_t **json, const char *str);
char *json_parse_path(struct json_t **json, const char *path);
/**
* Retrieve the number of children in an object.
* @obj: The object.
* &returns: The number of children.
*/
static inline unsigned int json_obj_cnt(struct json_obj_t *obj)
{
return obj->root.count;
}
/*
* verification declarations
*/
double json_num_range(struct json_t *json, double low, double high);
bool json_str_get(struct json_t *json, const char **out);
bool json_str_objget(struct json_obj_t *obj, const char *id, const char **out);
bool json_get_double(struct json_t *json, double *out);
bool json_get_int(struct json_t *json, int *out);
bool json_get_uint16(struct json_t *json, uint16_t *out);
double json_chk_range(struct json_t *json, double low, double high);
struct json_arr_t *json_chk_arr(struct json_t *json, int len);
struct json_obj_t *json_chk_obj(struct json_t *json, ...);
char *json_getf(struct json_t *json, const char *restrict fmt, ...);
char *json_vgetf(struct json_t *json, const char *restrict fmt, va_list args);
char *json_vgetfptr(struct json_t *json, const char *restrict *restrict fmt, struct arglist_t *args);
/**
* Delete a JSON object if non-null.
* @json: The JSON object.
*/
static inline void json_erase(struct json_t *json)
{
if(json != NULL)
json_delete(json);
}
#endif
|
C
|
//task1 C program to add two complex numbers using structure
#include<stdio.h>
#include<conio.h>
struct complex
{
int real;
int imaginary;
};
int main()
{
complex c1, c2, c3;
printf("Enter the real and imaginary part of first comp;lex number: ");
scanf_s("%d %d", &c1.real, &c1.imaginary);
printf("\n Enter the real and imaginary part of second complex number: ");
scanf_s("%d %d", &c2.real, &c2.imaginary);
c3.real = c1.real + c2.real;
c3.imaginary = c1.imaginary + c2.imaginary;
printf("the sum is : %d+i%d", c3.real, c3.imaginary);
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include "BST.h"
#include "Stack.h"
#include "Queue.h" //so we can do a level order traversal
struct treeNode {
TreeItem item; //int
Treelink left; //struct treeNode *
Treelink right;
};
//Local helper functions
static Treelink createNode(TreeItem item){
Treelink ret = calloc(sizeof(struct treeNode), 1);
ret -> item = item;
return ret;
}
void destroyTree(Treelink tree) {
if (tree != NULL) {
destroyTree(tree -> left);
destroyTree(tree -> right);
}
free(tree);
}
static int max(TreeItem i1, TreeItem i2) {
int max = i1;
if(max < i2) max = i2;
return max;
}
int height(Treelink t) {
int h = 0;
if (t != NULL) {
h++;
int lH = height(t -> left);
int rH = height(t -> right);
if (lH < rH) h = rH;
else h = lH;
}
return h;
}
//what size?
int size(Treelink t) {
if (t == NULL) {
return 0;
} else {
return 1 + size(t->left) + size(t -> right);
}
}
//Interface functions
TreeItem getItem(Treelink node){
return node -> item;
}
Treelink createTree(void){
return NULL;
}
//returns the node of the element with item i
Treelink search(Treelink t, TreeItem i){
Treelink ret = NULL;
if (t -> item == i) {
ret = t;
} else {
ret = search(t -> left, i);
if (ret == NULL) {
ret = search(t -> right, i);
}
}
return ret;
}
//returns the node of the element with item i
Treelink searchIterative(Treelink t, TreeItem i){
Treelink ret = NULL;
Treelink cur = t;
while (cur != NULL) {
if (i < cur -> item) {
cur = cur -> left;
} else if (i > cur -> item) {
cur = cur -> right;
} else {
ret = cur;
cur = NULL;
}
}
return ret;
}
void inorderTraversal (Treelink tree) {
if (tree != NULL && tree -> left == NULL && tree -> right == NULL)
printf("%d ", tree -> item);
else if (tree != NULL) {
if (tree -> left != NULL)
inorderTraversal(tree -> left);
printf("%d ", tree -> item);
if (tree -> right != NULL)
inorderTraversal(tree -> right);
}
}
void postorderTraversal(Treelink tree) {
if (tree != NULL && tree -> left == NULL && tree -> right == NULL)
printf("%d ", tree -> item);
else if (tree != NULL) {
if (tree -> left != NULL)
inorderTraversal(tree -> left);
if (tree -> right != NULL)
inorderTraversal(tree -> right);
printf("%d ", tree -> item);
}
}
void preorderTraversal(Treelink tree) {
if (tree != NULL && tree -> left == NULL && tree -> right == NULL)
printf("%d ", tree -> item);
else if (tree != NULL) {
printf("%d ", tree -> item);
if (tree -> left != NULL)
inorderTraversal(tree -> left);
if (tree -> right != NULL)
inorderTraversal(tree -> right);
}
}
//Returns the root of the tree
//inserts duplicates on theleft hand side of tree
Treelink insertRec(Treelink tree, TreeItem item) {
Treelink ret = createNode(item);
if(tree == NULL) {
tree = ret;
} else if (item > tree -> item) {
tree -> right = insertRec(tree -> right, item);
} else {
tree -> left = insertRec(tree -> left, item);
}
return tree;
}
//Returns the root of the tree
//inserts duplicates on theleft hand side of tree
Treelink insertIterative(Treelink tree, TreeItem key) {
Treelink ret = createNode(item);
Treelink cur = tree;
while (cur != NULL) {
if (item > cur -> item) {
cur = cur -> right;
} else {
cur = cur -> left;
}
}
cur = ret;
return tree;
}
void levelOrderTraversal(Treelink tree) {
if (tree != NULL)
printf("%d ", tree -> item);
if (tree -> left != NULL)
levelOrderTraversal(tree -> left);
if (tree -> right != NULL)
levelOrderTraversal(tree -> right);
}
//Same as recursive Preorder
void mysteryIterativeTraversal(Treelink tree) {
}
//Assume t1 is the left subtree and t2 the right subtree
static Treelink join(Treelink t1, Treelink t2) {
if (t1 == NULL) return t2;
if (t2 == NULL) return t1;
else {
Treelink lm = t2;
Treelink pre = NULL;
while (lm -> left != NULL) {
pre = lm;
lm = lm -> left;
}
if (pre != NULL) {
pre -> left = lm -> right;
lm -> right = t2;
}
lm -> left = t1;
}
}
Treelink delete(Treelink tree, TreeItem item) {
if (tree == NULL) {
return tree;
} else if (item < tree -> item) {
tree -> left = delete(tree -> left, item);
} else if (item > tree -> item) {
tree -> right = delete(tree -> right, item);
} else {
Treelink del = tree;
tree = join(tree -> left, tree -> right);
free(del);
return tree;
}
}
static void doShowBSTree(Treelink t, int level) {
}
void showBSTree(Treelink t) {
}
//PRACTICE QUESTIONS
//Some of these questions would only
//be doable assuming the tree has int items.
int sumEven(Treelink tree){
int res = 0;
if (tree != NULL) {
}
}
TreeItem getSmallest(Treelink tree) {
}
//An internal node has at least one non-null child
int numInternalNodes(Treelink tree){
}
//Does a path from the root to an external node(in this case an external node can be considered to have at least one null child)
//have the given sum?
//0 false
//1 true
int hasPathSum(Treelink tree, int sum) {
}
/*
//Double tree
//
// 2
// / \
// 1 3
//
// would become
// 2
// / \
// 2 3
// / /
// 1 3
// /
// 1
*/
void doubleTree(Treelink tree) {
}
//Delete nodes with items < min or > max
Treelink trimTree(Treelink tree, int min, int max);
|
C
|
#include "holberton.h"
/**
* _strpbrk - function locates the first occurrence
* in thestring s of any of the bytes in the string accept.
* @s: Source string.
* @accept: Characters to look for.
* Return: Remaining string from point character occurs.
*/
char *_strpbrk(char *s, char *accept)
{
unsigned int i, ii;
for (i = 0; s[i] != '\0'; i++)
{
for (ii = 0; accept[ii] != '\0'; ii++)
{
if (accept[ii] == s[i])
{
return (s + i);
}
}
}
return (0);
}
|
C
|
#include "mex.h"
#include <stdio.h>
#define STRING "hello world"
void ABcopy _PARAMS((double *a,double *b,int mn));
void mexfunction1(nlhs, plhs, nrhs, prhs)
int nlhs, nrhs;
Matrix *plhs[]; Matrix *prhs[];
{
Matrix *ptrA,*ptrB;
double *A,*B;
int m,n,it,strl;
char *str;
double *header;
mexWarnMsgTxt("This function requires 2 inputs");
if (nrhs!=2) mexErrMsgTxt("This function requires 2 inputs!");
if (nlhs>3) mexErrMsgTxt("This function requires at most 3 outputs!");
ptrA = prhs[0];
if (! mxIsNumeric(prhs[0])) mexErrMsgTxt("First argument must be numeric matrix.");
if (! mxIsString(prhs[1])) mexErrMsgTxt("Second argument must be a string.");
m = mxGetM(ptrA);n = mxGetN(ptrA);
A = mxGetPr(ptrA);
it=0;
ptrB = mxCreateFull(n,m,it);
m = mxGetM(ptrB);n = mxGetN(ptrB);
B = mxGetPr(ptrB);
ABcopy(A,B,m*n);
plhs[0]=prhs[0];
plhs[1]= ptrB;
m=mxGetM(prhs[1]);
strl=mxGetN(prhs[1]);
str=mxCalloc(m*strl+1,sizeof(char));
mxGetString(prhs[1],str,m*strl);
plhs[2]=mxCreateString(str);
}
void ABcopy(a,b,mn)
double *a; double *b;
int mn;
{
int i;
for ( i=0 ; i < mn ; i++)
{
b[i] = a[i] + 33.0 +i;
}
}
|
C
|
#include "list.h"
#include "malloc.h"
#include "utils.h"
list_t *empty_list()
{
list_t *l = mem_alloc(sizeof(list_t));
*l = NULL;
return l;
}
bool is_empty_list(list_t *l)
{
return *l == NULL;
}
void push(list_t *l, u_int32 x)
{
list_t u = mem_alloc(sizeof(struct list));
u->head = x;
u->tail = *l;
*l = u;
}
u_int32 pop(list_t *l)
{
u_int32 x = (*l)->head;
list_t tail = (*l)->tail;
mem_free(*l);
*l = tail;
return x;
}
void remove_elt(list_t *l, u_int32 x)
{
if (*l) {
if ((*l)->head == x) {
list_t tail = (*l)->tail;
mem_free(*l);
*l = tail;
} else {
list_t curr = *l;
while (curr->tail && curr->tail->head != x) {
curr = curr->tail;
}
if (curr->tail) {
list_t tail = curr->tail->tail;
mem_free(curr->tail);
curr->tail = tail;
}
}
}
}
u_int32 max_list(list_t *l)
{
u_int32 max_elt = (*l)->head;
list_t curr = (*l)->tail;
while (curr)
{
max_elt = max(max_elt, curr->head);
curr = curr->tail;
}
return max_elt;
}
u_int32 extract_max(list_t *l)
{
u_int32 max_elt = max_list(l);
remove_elt(l, max_elt);
return max_elt;
}
void reverse(list_t *l)
{
list_t rev = NULL;
list_t curr = *l;
while (curr) {
push(&rev, curr->head);
curr = curr->tail;
}
*l = rev;
}
u_int32 find(list_t *l, bool (*p)(u_int32), bool remove)
{
list_t curr = *l;
while (curr) {
if (p(curr->head)) {
if (remove) {
remove_elt(l, curr->head);
}
return curr->head;
}
curr = curr->tail;
}
return 0;
}
void delete_list(list_t *l, bool free_elts)
{
while (!is_empty_list(l)) {
u_int32 x = pop(l);
if (free_elts) {
mem_free((void *)x);
}
}
mem_free(l);
}
|
C
|
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <signal.h>
#include <utility/fdthread.linux.h>
volatile sig_atomic_t running = 1;
void sigint(int sig){
printf("- SIGINT received. Halting...\n");
running = 0;
}
int main(int argc, const char *argv[]) {
printf("(exec) %s ", argv[0]);
for (int i=1;i<argc;i++) {
printf("%s ", argv[i]);
}
printf("\n");
signal(SIGINT, sigint);
initFdThread();
while(running) {
sleep(1);
}
closeFdThread();
exit(0);
}
|
C
|
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
void myPow(int *mas, int n, int pow, int quantity)
{
int i, j;
for (i = 0; i < pow; i++)
{
for (j = 0; j < quantity; j++) mas[j] *= n;
for (j = 0; j < quantity; j++)
if (mas[j] >= 16)
{
mas[j + 1] += mas[j] / 16;
mas[j] %= 16;
}
}
}
int main()
{
int n, i;
n = (5000 * (log(3) / log(16)) + 1);
int *mas = (int*)malloc(n * sizeof(int));
mas[0] = 1;
for (i = 1; i < n; i++) mas[i] = 0;
myPow(mas, 3, 5000, n);
for (i = n - 1; i >= 0; i--) printf("%x", mas[i]);
printf("\n");
free(mas);
system("pause");
return 0;
}
|
C
|
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include "common.h"
CarInfo *GetCarNode(void)
{
CarInfo *p;
p = malloc(sizeof(CarInfo));
if(p == NULL)
{
return NULL;
}
else
{
p->next = NULL;
return p;
}
}
CarInfo *InsertCars(CarInfo *cars, CarInfo *p)
{
CarInfo *Total, *Temp;
//if the node list is empty
if (cars == NULL)
{
cars = p;
return cars;
}
//if the node list is not empty
Total = cars;
while (Total != NULL)
{
Temp = Total;
Total = Total->next;
}
Temp->next = p;
return cars;
}
CarInfo *DeleteCars(CarInfo *cars, char *Brand, int Model)
{
CarInfo *Current = NULL, *Prev = NULL;
Current = cars;
while(Current!=NULL)
{
if(0 == strcmp(Current->Brand,Brand) && Current->Model == Model)
{ // the node is at the first
if(Current == cars)
{
cars=Current->next;
free(Current);
return cars;
}
else
{ // the node is at the middle
Prev->next=Current->next;
free(Current);
return cars;
}
}
else
{ // it didn't find specified node.
Prev=Current;
Current=Current->next;
}
}
return cars;
}
const char *get_proto_string(CarProto pt)
{
switch (pt) {
case PROTO_USA:
return "USA";
case PROTO_CHINA:
return "CHINA";
case PROTO_JAPAN:
return "JAPAN";
default:
return "UNKNOWN";
}
}
void PrintCars(CarInfo *cars)
{
CarInfo *Head;
for(Head = cars; Head != NULL; Head = Head->next)
{
printf("===Brand:[%s] Model:[%d] Contry:[%s]\n",Head->Brand,Head->Model,get_proto_string(Head->Contry));
}
}
void FreeCarsList(CarInfo *cars)
{
CarInfo *Head,*Temp;
Head = cars;
while(Head != NULL)
{
Temp = Head->next;
free(Head);
Head = Temp;
}
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
#define N 100
int length(char *s)
{
int i=0;
while(*s!='\0')
{
i++;
s++;
}
return i;
}
int main()
{
int len;
char s[N];
printf("ַ:");
scanf("%s",s);
len=length(s);
printf("ַ:%d\n",len);
return 0;
}
|
C
|
/*3. Dado trs valores, verificar se eles podem constituir os lados de um
tringulo (tringulo umafigura geomtrica onde cada
lado menor do que a soma dos outros dois lados).*/
#include<stdio.h>
int main(){
double A, B, C;
printf("Digite o valor de A:\n");
scanf("%lf", &A);
printf("Digite o valor de B:\n");
scanf("%lf", &B);
printf("Digite valor de C:\n");
scanf("%lf", &C);
if(A + B <= C || A + C <= B || B + C <= A)
printf("Impossivel constituir os lados de um triangulo!\n");
else{
printf("E possivel constituir os lados de um triangulo!");
}
return 0;
}
|
C
|
uint32_t reverseBits(uint32_t n) {
uint32_t rev = 0;
for (int i = 0; i < 32; i++, n >>= 1) {
rev <<= 1;
rev |= n & 1;
}
return rev;
}
|
C
|
//
// Created by wdenejko on 28.06.16.
//
#include <stdio.h>
#include <stdlib.h>
int main() {
FILE *fp;
fp = fopen("/home/wdenejko/Dokumenty/a.bin", "rb");
if (fp == NULL) {
printf("Failed to open file\n");
return 1;
}
long size;
size = ftell(fp);
printf("Size = %ld\n", size);
fseek(fp, 0L, 2);
size = ftell(fp);
printf("Size = %ld\n", size);
int n = size / sizeof(double);
printf("No of records: %d\n", n);
double *data;
data = (double *)malloc(sizeof(double) * n);
fseek(fp, 0L, 0);
fread((void *)data, sizeof(double), n, fp);
int i;
for (i = 0; i < n; i++) {
printf("%10.2lf\n", data[i]);
}
fclose(fp);
return 0;
}
|
C
|
/*
* error.c
*
* Created on: Jun 21, 2015
* Author: Kyle Harper
*/
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <stdarg.h>
/* show_error
* Displays an error to stderr and aborts if exit_code is non-zero. This function should basically only be used when we want to
* exit after error message.
*/
void show_error(int exit_code, char *format, ...) {
va_list list;
fprintf(stderr, "ERROR: ");
va_start(list, format);
vfprintf(stderr, format, list);
va_end(list);
fprintf(stderr, "\nABORTING\n");
if (exit_code != 0)
exit(exit_code);
printf("The show_error function was given exit code 0, this shouldn't ever happen. Bailing.\n");
exit(1);
}
/* show_file_error
* Looks up the error_code sent to send a useful message.
*/
void show_file_error(char *filespec, int error_code) {
switch (error_code) {
case 0:
fprintf(stderr, "show_file_error() was called with an error_code of 0, this shouldn't have happened.\n");
break;
case ENOENT:
fprintf(stderr, "File/directory not found: %s\n", filespec);
break;
case EACCES:
fprintf(stderr, "Access denied to directory: %s\n", filespec);
break;
case ELOOP:
fprintf(stderr, "Path specified appears to be a symbolic link that loops: %s\n", filespec);
break;
case ENAMETOOLONG:
fprintf(stderr, "File/directory name is too long for this platform: %s\n", filespec);
break;
case ENFILE:
fprintf(stderr, "Too many file concurrently open by the system, cannot open filespec: %s\n", filespec);
break;
case EMFILE:
fprintf(stderr, "Too many open files by this process, cannot open filespec: %s\n", filespec);
break;
case ENOMEM:
fprintf(stderr, "No available memory to open this file/directory: %s\n", filespec);
break;
default:
fprintf(stderr, "Untrapped error code trying to access %s, code is: %d\n", filespec, errno);
break;
}
}
|
C
|
#include <stdio.h>
#include <time.h>
#include <stddef.h>
#include <gsl/gsl_matrix.h>
#include <math.h>
#include <limits.h>
#include <string.h>
#include <stdint.h>
#include <unistd.h>
#include "comms.h"
typedef uint8_t encoded_word;
char *comms_PackMessage(struct comms_Packet pck) {
union {
struct comms_Packet packet;
char values[sizeof(struct comms_Packet)];
} conv;
conv.packet = pck;
char *ret = malloc(sizeof(struct comms_Packet));
memcpy(ret, conv.values, sizeof(struct comms_Packet));
return ret;
}
struct comms_Packet comms_UnpackMessage(char *values) {
union {
struct comms_Packet packet;
char values[sizeof(struct comms_Packet)];
} conv;
memcpy(conv.values, values, sizeof(struct comms_Packet));
return conv.packet;
}
/*char *comms_PackControl(struct comms_Control ctrl) {
union {
struct comms_Control control;
char values[sizeof(struct comms_Control)];
} conv;
conv.control = ctrl;
char *ret = malloc(sizeof(struct comms_Control));
memcpy(ret, conv.values, sizeof(struct comms_Control));
return ret;
}
struct comms_Control comms_UnpackControl(char *values) {
union {
struct comms_Control control;
char values[sizeof(struct comms_Control)];
} conv;
memcpy(conv.values, values, sizeof(struct comms_Control));
return conv.control;
}*/
char *comms_EncodeMessage(struct comms_Packet pck) {
int pckcodes = (sizeof(struct comms_Packet)*CHAR_BIT)/comms_codelen;
union {
struct comms_Packet packet;
char values[sizeof(struct comms_Packet)];
} conv;
conv.packet = pck;
int bits[sizeof(struct comms_Packet)*CHAR_BIT];
for (int i = 0; i < sizeof(struct comms_Packet); i++) {
for (int j = CHAR_BIT-1; j >= 0; j--) {
bits[i*CHAR_BIT+(CHAR_BIT-(j+1))] = (conv.values[i] >> j)&1;
}
}
int unencoded[pckcodes][comms_codelen];
for (int i = 0; i < pckcodes; i++) {
for (int j = 0; j < comms_codelen; j++) {
unencoded[i][j] = (bits[j+i*comms_codelen])&1;
}
}
union {
encoded_word codes[pckcodes];// : int(pow(2,comms_codelen-1));
char values[(int)(pow(2,comms_codelen-1)*pckcodes/CHAR_BIT)];
} encoded;
int **hadamard;
hadamard = comms_hadamard(comms_codelen); //comms_codelen is max length of input
for (int i = 0; i < pckcodes; i++) {
int index = 0; // max is 2^comms_codelen
for (int j = 0; j < comms_codelen; j++) { // get index of code
index += (unencoded[i][comms_codelen-1-j]<<j);
}
encoded.codes[i] = 0;
for (int j = 0; j < pow(2, comms_codelen-1); j++) { // get code from index
encoded.codes[i] += (hadamard[index][(int)pow(2,comms_codelen-1)-j-1]<<j);
}
}
char *ret = malloc(pow(2,comms_codelen-1)*pckcodes/CHAR_BIT);
memcpy(ret, encoded.values, pow(2,comms_codelen-1)*pckcodes/CHAR_BIT);
return ret;
}
struct comms_Packet comms_DecodeMessage(char *buffer) {
int pckcodes = (sizeof(struct comms_Packet)*CHAR_BIT)/comms_codelen;
union {
encoded_word codes[pckcodes];// : int(pow(2,comms_codelen-1));
char values[(int)(pow(2,comms_codelen-1)*pckcodes)];
} encoded;
memcpy(encoded.values, buffer, pow(2,comms_codelen-1)*pckcodes);
int **hadamard;
hadamard = comms_hadamard(comms_codelen); //comms_codelen is max length of input
int unencoded[pckcodes]; // max is comms_codelen
for (int i = 0; i < pckcodes; i++) {
int min = pow(2,comms_codelen-1); // max error is this, but any big number is fine
int imin = 0;
for (int j = 0; j < pow(2,comms_codelen); j++) {
encoded_word had = 0;
for (int k = 0; k < pow(2,comms_codelen-1); k++) { // get j'th code
had += (hadamard[j][(int)pow(2,comms_codelen-1)-k-1]<<k);
}
int hd = comms_hammingdistance(encoded.codes[i], had); // then match to find closest
//printf("\nhd = %d",hd);
if (hd < min) {
min = hd;
imin = j;
}
}
comms_hamdist = min;
unencoded[i] = 0;
unencoded[i] = imin;
}
int bits[sizeof(struct comms_Packet)*CHAR_BIT];
for (int i = 0; i < pckcodes; i++) {
for (int j = comms_codelen-1; j >= 0 ; j--) {
bits[comms_codelen*i+(comms_codelen-(j+1))] = (unencoded[i]>>j)&1;
}
}
union {
struct comms_Packet packet;
char values[sizeof(struct comms_Packet)];
} conv;
for (int i = 0; i < sizeof(struct comms_Packet); i++) {
conv.values[i] = 0;
for (int j = 0; j < CHAR_BIT; j++) {
conv.values[i] += bits[i*CHAR_BIT+j] << (CHAR_BIT-1-j);
}
}
return conv.packet;
}
int comms_hammingdistance(encoded_word a, encoded_word b) {
encoded_word z = a^b;
int n = 0;
while (z) {
if (z&1){
n++;
}
z >>= 1;
}
return n;
}
int **comms_hadamard(int comms_codelen) {
gsl_matrix *initTop = gsl_matrix_alloc(2,2);
initTop->tda = 2;
gsl_matrix_set(initTop,0,0,1); //start of top half with matrix:
gsl_matrix_set(initTop,0,1,1); // 1 1
gsl_matrix_set(initTop,1,0,1); // 1 -1
gsl_matrix_set(initTop,1,1,-1);
gsl_matrix *matrixTop = gsl_matrix_alloc(1,1);
matrixTop->tda = 1;
gsl_matrix_set(matrixTop,0,0,1);
for (int i = 0; i < comms_codelen-1; i++) { //comms_codelen is -1 as t&b allow *2 the codes
matrixTop = comms_KPro(matrixTop,initTop);
}
gsl_matrix *initBottom = gsl_matrix_alloc(2,2);
initBottom->tda = 2;
gsl_matrix_set(initBottom,0,0,-1); //start of bottom half with matrix:
gsl_matrix_set(initBottom,0,1,-1); // -1 -1
gsl_matrix_set(initBottom,1,0,-1); // -1 1
gsl_matrix_set(initBottom,1,1,1);
gsl_matrix *matrixBottom = gsl_matrix_alloc(1,1);
matrixBottom->tda = 1;
gsl_matrix_set(matrixBottom,0,0,1);
for (int i = 0; i < comms_codelen-1; i++) {
matrixBottom = comms_KPro(matrixBottom,initBottom);
}
int **hadamard = calloc(pow(2, comms_codelen), sizeof(int*));
for (int i = 0; i < pow(2, comms_codelen); i++) {
hadamard[i] = calloc(pow(2,comms_codelen-1), sizeof(int));
}
double value;
for (int i = 0; i < pow(2, comms_codelen); i++) {
for (int j = 0; j < pow(2, comms_codelen-1); j++) {
if (i < pow(2,comms_codelen-1)) {
value = gsl_matrix_get(matrixTop,i,j); //take from the top half
} else {
value = gsl_matrix_get(matrixBottom,i-pow(2,comms_codelen-1),j); //then the bottom half
}
if (value == 1) {
hadamard[i][j] = 1;
// printf("1");
} else {
hadamard[i][j] = 0;
// printf("0");
}
}
//printf("\n");
}
// printf("\n");
// printf("\n");
return hadamard;
}
/*sourced from https://stackoverflow.com/questions/13722543/efficient-way-to-compute-kronecker-product-of-matrices-with-gsl*/
gsl_matrix *comms_KPro(gsl_matrix *a, gsl_matrix *b) {
int i, j, k, l;
int m, p, n, q;
m = a->size1;
p = a->size2;
n = b->size1;
q = b->size2;
gsl_matrix *c = gsl_matrix_alloc(m*n, p*q);
double da, db;
for (i = 0; i < m; i++) {
for (j = 0; j < p; j++) {
da = gsl_matrix_get (a, i, j);
for (k = 0; k < n; k++) {
for (l = 0; l < q; l++) {
db = gsl_matrix_get (b, k, l);
gsl_matrix_set (c, n*i+k, q*j+l, da * db);
}
}
}
}
return c;
}
int comms_printbin (encoded_word dec) {
for (int i = (CHAR_BIT*sizeof(encoded_word))-1; i >= 0; i--) {
if (((dec>>i)&1)==1) {
printf("1");
} else {
printf("0");
}
}
return EXIT_SUCCESS;
}
|
C
|
/*
* Print error messages based on value in `errno'.
*/
#include <stdio.h>
extern int errno;
extern char *sys_errlist[];
extern int sys_nerr;
perror(s)
register char *s;
{
register char *es;
if (errno < sys_nerr)
es = sys_errlist[errno]; else
es = "Bad error number";
if (s != NULL) {
fputs(s, stderr);
fputs(": ", stderr);
}
fputs(es, stderr);
fputs("\n", stderr);
}
|
C
|
#include <convert.h>
Provider * Convert_GetNHigherAnnualProfit(Provider *self, int N_number) {
char string[STR_SIZE * STR_SIZE] = "";
for (int i = 0; i < Provider_countList(self); ++i) {
char buffer[STR_SIZE] = "";
strcat(string, Convert_structureToString(buffer, Provider_getStructure(self, i)));
strcat(string, " ");
}
string[strlen(string) - 1] = '\0';
Provider * list = Convert_stringToList(string);
int size = Provider_countList(list);
for (int i = 0; i < size - N_number; ++i) {
int indexMin = 0;
for (int j = 0; j < Provider_countList(list); ++j) {
if (*Provider_getAnnualProfit(Provider_getStructure(list, indexMin)) > *Provider_getAnnualProfit(Provider_getStructure(list, j))) {
indexMin = j;
}
}
Provider_deleteStructure(&list, indexMin);
}
return list;
}
void Convert_changeFieldInList(Provider *self, int indexProvider, int indexField, char *data) {
Provider * current = Provider_getStructure(self, indexProvider);
if (indexField == 0) strcpy(Provider_getProvName(current), data);
if (indexField == 1) *Provider_getYear(current) = atoi(data);
if (indexField == 2) *Provider_getAnnualProfit(current) = atof(data);
if (indexField == 3) strcpy(Provider_getOwnerName(current), data);
if (indexField == 4) strcpy(Provider_getOwnerSurname(current),data);
if (indexField == 5) *Provider_getAge(current) = atoi(data);
}
Provider * Convert_stringToList(char *string) {
char provName[STR_SIZE];
int year;
long double annualProfit;
char ownerName[STR_SIZE];
char ownerSurname[STR_SIZE];
int age;
Provider * list = NULL;
for (int i = 0; string != NULL; ++i) {
sscanf(string, "%s %i %Lf %s %s %i", provName, &year, &annualProfit, ownerName, ownerSurname, &age);
Provider_addLast(&list, Provider_newStructure(provName, year, annualProfit, ownerName, ownerSurname, age));
for (int j = 0; j < 6; ++j) {
if (strchr(string, ' ') == NULL) {
string = NULL;
break;
}
string = strchr(string, ' ') + 1;
}
}
return list;
}
char * Convert_structureToString(char *result, Provider *self) {
if (self == NULL) {
strcpy(result, "");
return result;
}
char provName[STR_SIZE] = "";
strcpy(provName, Provider_getProvName(self));
int year = *Provider_getYear(self);
long double annualProfit = *Provider_getAnnualProfit(self);
char ownerName[STR_SIZE] = "";
strcpy(ownerName, Provider_getOwnerName(self));
char ownerSurname[STR_SIZE] = "";
strcpy(ownerSurname, Provider_getOwnerSurname(self));
int age = *Provider_getAge(self);
sprintf(result,"%s %i %Lg %s %s %i", provName, year, annualProfit, ownerName, ownerSurname, age);
return result;
}
bool correctName(char * string) {
if (!strcmp(string, "")) return false;
if (!isupper(string[0])) return false;
for (int i = 1; i < strlen(string); i++) {
if (!isalpha(string[i])) return false;
}
return true;
}
bool correctYear(char * string) {
if (!strcmp(string, "")) return false;
for (int i = 0; i < strlen(string); i++) {
if (!isdigit(string[i])) return false;
}
int year = atoi(string);
if (year > 2017 || year <= 1800) return false;
return true;
}
bool correctAnnualProfit(char *string) {
if (!strcmp(string, "")) return false;
for (int i = 0; i < strlen(string); i++) {
if (!isdigit(string[i]) && !(string[i] == '.' && i != 0 && i != strlen(string) - 1 && strlen(string) - i <= 3)) return false;
}
return true;
}
bool correctAge(char * string) {
if (!strcmp(string, "")) return false;
for (int i = 0; i < strlen(string); i++) {
if (!isdigit(string[i])) return false;
}
int age = atoi(string);
if (age > 147 || age < 1) return false;
return true;
}
bool correctIndex(char * string, int maxIndex) {
if (!strcmp(string, "")) return true;
for (int i = 0; i < strlen(string); ++i) {
if (!isdigit(string[i]))return false;
}
if (atoi(string) >= maxIndex) return false;
return true;
}
bool correctFileName(char * string) {
if (!strcmp(string, "")) return false;
if (strstr(string, ".txt") == NULL && strstr(string, ".txt") + 4 != '\0') return false;
for (int i = 0; i < strlen(string) - 4 ; i++) {
if (!isalpha(string[i]) && !isdigit(string[i])) return false;
}
return true;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
struct node
{
int data;
struct node* next;
};
struct node* head;
int main()
{
int a[]={1,2,3,4,5};
struct node* create(int a[],int);
void display(struct node*);
void sortinsert(struct node*,int);
head=create(a,5);
display(head);
sortinsert(head,10);
sortinsert(head,0);
display(head);
}
struct node* create(int a[],int n)
{struct node *p,*t,*last;
p=(struct node*)malloc(sizeof(struct node));
p->data=a[0];
p->next=NULL;
last=p;
int i;
for(i=1;i<n;i++)
{
t=(struct node*)malloc(sizeof(struct node));
t->data=a[i];
t->next=NULL;
last->next=t;
last=t;
}
return p;
}
void display(struct node* p)
{
printf("the elements of the linked list are: \n");
while(p!=NULL)
{
printf("%d \n",p->data);
p=p->next;
}
}
void sortinsert(struct node* p,int x)
{
struct node *t,*q; /*q is follower pointer*/
t=(struct node*)malloc(sizeof(struct node));
t->data=x;
if(p==NULL) /*case when linked list has no elements*/
{
t->next=NULL;
head=t; /*head is globally accessible*/
}
/*else condition*/
while(p!=NULL && p->data<x) /*2 conditions where loop will continue,one of them fails and the loop stops*/
{
q=p; /*follower pointer*/
p=p->next;
}
if(p==head) /*case of left most insertion which is a special case,the first element of the linked list is greater than the element to be inserted*/
{
t->next=p;
head=t; /*linked list points on the newly created node*/
}
else /*normal insertion technique*/
{
t->next=p;
q->next=t;
}
}
|
C
|
#include <stdio.h>
void main()
{
printf("New line \n");
printf("\ttabulation\n");
printf("this is a\bbackspace\n");
printf("\"quotes\"\n");
printf("\\slash\n");
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
int main(){
int *p;
p = (int*) calloc(10, sizeof(int));
if (p == NULL) {
printf("Erro: Memoria insuficiente!\n");
}
else {
int i;
for (i=0; i<10; i++) {
printf("Informe um valor: \n");
scanf("%d", &p[i]);
}
}
}
|
C
|
#include <stddef.h>
#include <inttypes.h>
#include <string.h> // memset
#include <sys/mman.h>
#define MEASURE_TIME
#ifdef MEASURE_TIME
# include <stdio.h>
# include <time.h>
#endif
#define OS_BLOCK_BITS (12)
#define OS_BLOCK_SIZE (((uintptr_t)1) << OS_BLOCK_BITS)
#define OS_PAGE_SIZE (4096)
#define NUM_BUCKETS (OS_BLOCK_BITS - 1)
struct Block;
struct Smallblock
{
uintptr_t size;
void *start;
};
_Static_assert(sizeof(struct Smallblock) == (2 * sizeof(void*)), "");
struct Block
{
uintptr_t free_count;
uintptr_t avail_count;
struct Smallblock small_block;
};
_Static_assert(sizeof(struct Block) == (4 * sizeof(void*)), "");
struct Bin
{
struct Block *blocks[NUM_BUCKETS];
};
static __thread struct Bin bin;
#ifdef MEASURE_TIME
static uint64_t get_cycles_start()
{
uint64_t cycles;
asm volatile(
"cpuid\n\t"
"rdtsc\n\t"
"shl $32, %%rdx\n\t"
"or %%rdx, %%rax"
: "=a"(cycles)
:
: "%rbx", "%rcx", "%rdx", "memory"
);
return cycles;
}
static uint64_t get_cycles_stop()
{
uint32_t cycles_high;
uint32_t cycles_low;
asm volatile(
"rdtscp\n\t"
"mov %%edx, %0\n\t"
"mov %%eax, %1\n\t"
"cpuid\n\t"
: "=r"(cycles_high), "=r"(cycles_low)
:
: "%rax", "%rbx", "%rcx", "%rdx", "memory"
);
const uint64_t rdtscVal = (((uint64_t)cycles_high) << 32)
| ((uint64_t)cycles_low);
return rdtscVal;
}
#endif
static uintptr_t align_up(uintptr_t numToRound, uintptr_t multiple)
{
uintptr_t mask = multiple - 1;
return (numToRound + mask) & ~mask;
}
static uintptr_t bin_bits(uintptr_t x)
{
//if(x < 2) {
// return 0;
//}
return (8 * sizeof(uintptr_t)) - __builtin_clzl(x - 1);
}
static uintptr_t bin_internal_size(uintptr_t binIdx)
{
return sizeof(struct Smallblock) + (((uintptr_t)1) << (binIdx));
}
static void* os_mmap(uintptr_t size)
{
void *mem = mmap(NULL, size, PROT_READ | PROT_WRITE | PROT_EXEC, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
if(mem == MAP_FAILED) {
return NULL;
}
return mem;
}
static void os_unmap(void *ptr, uintptr_t size)
{
munmap(ptr, size);
}
static void* waste_alloc(uintptr_t size)
{
if(size == 0) {
return NULL;
}
if(size < (2 * sizeof(void*))) {
size = 2 * sizeof(void*);
}
uintptr_t binIdx = bin_bits(size);
if(binIdx < NUM_BUCKETS) {
// small allocation, fast path
const uintptr_t small_intern_size = bin_internal_size(binIdx);
struct Block *block = bin.blocks[binIdx];
if(block == NULL) {
block = (struct Block*)os_mmap(OS_BLOCK_SIZE);
if(block == NULL) {
return NULL;
}
bin.blocks[binIdx] = block;
uintptr_t available_small_blocks = (OS_BLOCK_SIZE - sizeof(struct Block)) / small_intern_size;
block->free_count = available_small_blocks;
block->avail_count = available_small_blocks;
block->small_block.size = OS_BLOCK_SIZE;
block->small_block.start = block + 1;
}
struct Smallblock *small_block = (struct Smallblock*)block->small_block.start;
block->small_block.start = (void*)(((uintptr_t)small_block) + small_intern_size);
small_block->size = small_intern_size;
small_block->start = block;
uintptr_t avail = block->avail_count;
avail -= 1;
block->avail_count = avail;
if(avail == 0) {
bin.blocks[binIdx] = NULL;
}
return small_block + 1;
}
// else large allocation
uintptr_t mmapSize = align_up(size + sizeof(struct Block), OS_PAGE_SIZE);
struct Block *block = (struct Block*)os_mmap(mmapSize);
if(block == NULL) {
return NULL;
}
block->free_count = 1;
block->avail_count = 0;
block->small_block.size = mmapSize;
block->small_block.start = block;
return block + 1;
return NULL;
}
static void* waste_memalign(uintptr_t alignment, uintptr_t size)
{
// if not power of two
if(!((alignment != 0) && !(alignment & (alignment - 1)))) {
return NULL;
}
if(size == 0) {
return NULL;
}
if(alignment < (2 * sizeof(void*))) {
return waste_alloc(size);
}
void *mem = waste_alloc(size + (alignment - 1) + sizeof(struct Smallblock));
if(mem == NULL) {
return NULL;
}
struct Smallblock *small_block = ((struct Smallblock*)mem) - 1;
uintptr_t mem_val = (uintptr_t)mem;
uintptr_t out_mem_val = align_up(mem_val + sizeof(struct Smallblock), alignment);
struct Smallblock *my_sb = (struct Smallblock*)(out_mem_val - sizeof(struct Smallblock));
my_sb->size = small_block->size;
my_sb->start = small_block->start;
return my_sb + 1;
}
static void waste_free(void *ptr)
{
if(ptr == NULL) {
return;
}
struct Smallblock *small_block = ((struct Smallblock*)ptr) - 1;
struct Block *block = (struct Block*)(small_block->start);
uintptr_t new_count = __atomic_sub_fetch(&block->free_count, 1, __ATOMIC_SEQ_CST);
if(new_count == 0) {
os_unmap(block, block->small_block.size);
}
}
static void* waste_realloc(void *ptr, uintptr_t size)
{
if(ptr == NULL) {
return waste_alloc(size);
}
if(size == 0) {
waste_free(ptr);
return NULL;
}
struct Smallblock *small_block = ((struct Smallblock*)ptr) - 1;
uintptr_t old_intern_size = small_block->size;
uintptr_t old_user_size = old_intern_size;
if(old_intern_size > bin_internal_size(NUM_BUCKETS - 1)) {
// large block
old_user_size -= sizeof(struct Block);
}
else {
// small block
old_user_size -= sizeof(struct Smallblock);
}
if(old_user_size >= size) {
return ptr;
}
void *out = waste_alloc(size);
if(out == NULL) {
return NULL;
}
memcpy(out, ptr, old_user_size);
waste_free(ptr);
return out;
}
//////
//////
//////
#ifdef __cplusplus
extern "C" {
#endif
void* malloc(size_t size)
{
#ifdef MEASURE_TIME
uint64_t time = get_cycles_start();
#endif
void *out = waste_alloc(size);
#ifdef MEASURE_TIME
time = get_cycles_stop() - time;
fprintf(stderr, "malloc %" PRIu64 "\n", time);
#endif
return out;
}
void* memalign(size_t alignment, size_t size)
{
#ifdef MEASURE_TIME
uint64_t time = get_cycles_start();
#endif
void *out = waste_memalign(alignment, size);
#ifdef MEASURE_TIME
time = get_cycles_stop() - time;
fprintf(stderr, "memalign %" PRIu64 "\n", time);
#endif
return out;
}
void free(void *ptr)
{
#ifdef MEASURE_TIME
uint64_t time = get_cycles_start();
#endif
waste_free(ptr);
#ifdef MEASURE_TIME
time = get_cycles_stop() - time;
fprintf(stderr, "free %" PRIu64 "\n", time);
#endif
}
void* realloc(void *ptr, size_t size)
{
#ifdef MEASURE_TIME
uint64_t time = get_cycles_start();
#endif
void *out = waste_realloc(ptr, size);
#ifdef MEASURE_TIME
time = get_cycles_stop() - time;
fprintf(stderr, "realloc %" PRIu64 "\n", time);
#endif
return out;
}
int posix_memalign(void **memptr, size_t alignment, size_t size)
{
void *out;
if((alignment % sizeof(void*)) != 0) {
return 22;
}
/* if not power of two */
if(!((alignment != 0) && !(alignment & (alignment - 1)))) {
return 22;
}
if(size == 0) {
*memptr = NULL;
return 0;
}
out = memalign(alignment, size);
if(out == NULL) {
return 12;
}
*memptr = out;
return 0;
}
void* calloc(size_t nmemb, size_t size)
{
void *out;
size_t fullsize = nmemb * size;
if((size != 0) && ((fullsize / size) != nmemb)) {
return NULL;
}
out = malloc(fullsize);
if(out == NULL) {
return NULL;
}
memset(out, 0, fullsize);
return out;
}
void* valloc(size_t size)
{
return memalign(OS_PAGE_SIZE, size);
}
void* pvalloc(size_t size)
{
size_t rem, allocsize;
rem = size % OS_PAGE_SIZE;
allocsize = size;
if(rem != 0) {
allocsize = OS_PAGE_SIZE + (size - rem);
}
return memalign(OS_PAGE_SIZE, allocsize);
}
void* aligned_alloc(size_t alignment, size_t size)
{
if(alignment > size) {
return NULL;
}
if((size % alignment) != 0) {
return NULL;
}
return memalign(alignment, size);
}
#ifdef __cplusplus
}
#endif
|
C
|
/*
* FIND_NODE_IN_MLB.h
*
* Created on: 11 lug 2016
* Author: antonio
*/
#ifndef DIJKSTRA_PROCEDURE_MANAGEMENT_INSERT_NODE_IN_MLB_H_
#define DIJKSTRA_PROCEDURE_MANAGEMENT_INSERT_NODE_IN_MLB_H_
/**
This function insert a node in the correct position in the Multi Level Bucekt.
The function, at first find the level and then the correct bucket in the level.
If the level pointer is null, there isn't no one bucket in it. Then the
function builds the bucket array and assigns each bucket the relative range.
*/
void insert_node_in_MLB(Multi_Level_Bucket *MLB, V_set *set_of_vertex, int id_in_node, int p)
{
xy_in_MLB *pos=(xy_in_MLB *)malloc(sizeof(xy_in_MLB));
pos=find_position(MLB, set_of_vertex->V[id_in_node].dist, p);
// Find the position that the node will occupy in the Multi level bucket.
if (pos->l < MLB->actual_level) MLB->actual_level=pos->l;
// Update the lower not empty level in the structure
/************************************************************************************/
/********************************* ADD A NODE IN A BUCKET ***************************/
/************************************************************************************/
/**/// Insert the node in the correct bucket. /**/
/**/add_in_bucket(MLB, set_of_vertex, pos, id_in_node, p); /**/
/************************************************************************************/
/************************************************************************************/
if (MLB->LEVEL[pos->l].active_bucket > pos->b)
MLB->LEVEL[pos->l].active_bucket=pos->b;
pos=NULL;free(pos);
return;
}
#endif /* DIJKSTRA_PROCEDURE_MANAGEMENT_INSERT_NODE_IN_MLB_H_ */
|
C
|
#include "forth.h"
#include "words.h"
#include <inttypes.h>
#include <stdio.h>
#include <string.h>
#define STACK 16384
#define RETURN_STACK 4096
#define MEMORY 16384
#define MAX(a, b) (a < b ? b : a)
int main(void)
{
enum forth_result status;
struct forth forth = {0};
forth_init(&forth, STACK, RETURN_STACK, MEMORY);
words_init(&forth);
forth.input = stdin;
status = forth_run(&forth);
printf("Complete with status: %d\n", status);
forth_free(&forth);
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
int main()
{
/*
strlen(nombre) --> Me devuelve el largo de la cadena.
strcpy(nombre, nombre2) --> Copia la cadena de la derecha a la de la izquierda, sera como hacer nombre = nombre2
strncpy(nombre, nombre2, 5) --> Hace lo mismo que strcpy pero hasta el caracter que pasemos por la funcion.
*/
char n1[10] = "Juan";
char n2[10] = "Juana";
//int x;
//int y;
//x = strcmp(n1, n2);//Cuando el de la derecha est antes en el diccionario que el de la izquierda me devuelve 1, si son iguales me devuelve 0 y si el de la izquierda est antes, me devuelve -1.
//y = stricmp(n1, n2);//Hace lo mismo que strcmp pero sin ser sensible a minsculas y maysculas.
//strupr(n1);//Pasa cadena a maysculas.
//strlwr(n2);//Pasa cadena a minsculas
n2[0] = toupper(n2[0]);//Pasa a mayuscula la primer letra.
printf("%s\n",n1);
printf("%s\n",n2);
return 0;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.