language
large_stringclasses 1
value | text
stringlengths 9
2.95M
|
---|---|
C
|
/*
车轮子练习
*/
#include <stdio.h>
int main(){
int num = 0, num1 = 0;
for(num = 0;num <= 7;num++){
for(num1 = 0;num1 <= (28 - 4 * num)/3;num1++){
if(28 == (4 * num + 3 * num1 + 2 * (10 - num - num1))){
printf("汽车有%d辆,三轮车有%d辆,自行车有%d辆\n", num, num1, 10 - num - num1);
}
}
}
return 0;
}
|
C
|
bool recur(char **board, int row, int col, int x, int y, char* word)
{
bool res;
if(*word == '\0')
{
return true;
}
if(x < 0 || x >= row || y < 0 || y >= col || *word != board[x][y])
{
return false;
}
board[x][y] = '\0';
res = recur(board,row,col,x -1,y,word + 1) || recur(board,row,col,x+1,y,word + 1) || \
recur(board,row,col,x,y+1,word + 1) || recur(board,row,col,x,y-1,word + 1);
board[x][y] = *word;
return res;
}
bool exist(char** board, int boardSize, int* boardColSize, char * word){
int i = 0, j = 0;
for(i = 0; i < boardSize; i++)
{
for(j = 0; j < boardColSize[0]; j++)
{
if(board[i][j] ==word[0] && recur(board,boardSize,boardColSize[0],i,j,word))
{
return true;
}
}
}
return false;
}
|
C
|
//cleint_main.c
#define _CLIENT_H_
#include "suckittalk.h"
void theEndOfTheCli(int sig)
{
if(sig == SIGINT)
{
my_str("\nEnd of ze Client\n");
exit(1);
}
}
int main(int argc, char** argv)
{
int sockfd;
int n;
int port_num;
char buffer[BUFFSIZE];
char* nname;
struct sockaddr_in server_adderess;
struct hostent* server;
if(argc < 3)
{
my_str("Use: [Machine_Name] [port_num]\n");
exit(1);
}
port_num = my_atoi(argv[2]);
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd < 0)
my_str("ERROR opening socket");
server = gethostbyname(argv[1]);
if (server == NULL)
{
my_str("ERROR, no such host\n");
exit(0);
}
bzero((char*)&server_adderess, sizeof(server_adderess));
server_adderess.sin_family = AF_INET;
bcopy((char *)server->h_addr, (char *)&server_adderess.sin_addr.s_addr, server->h_length);
server_adderess.sin_port = htons(port_num);
//my_str("Try connection now\n");
if(connect(sockfd, (struct sockaddr *)&server_adderess, sizeof(server_adderess))<0)
{
my_str("Could not connect to ");
my_str(argv[1]);
my_char('\n');
exit(0);
}
signal(SIGINT, theEndOfTheCli);
//Initilizing Done
//Starting Program
bzero(buffer, BUFFSIZE);
nname = (char*)my_xmalloc(50*sizeof(char));
my_str("Nickname: ");
n = read(0, nname, 49);
nname[n] = '\0';
int i=0;
while(nname[i] != '\0')
{
if(nname[i++] == '\n')
nname[--i] = '\0';
}
if(n <= 0)
my_str("Invalid nick name\n");
n = write(sockfd, nname, my_strlen(nname));
if(n < 0)
my_str("ERROR writing to socket\n");
//my_str(buffer);
while(1)
{
bzero(buffer, BUFFSIZE);
my_str(nname);
my_str(": ");
n = read(0, buffer, BUFFSIZE-1);
i=0;
while(buffer[i] != '\0')
{
if(buffer[i++] == '\n')
buffer[--i] = '\0';
}
if(n <= 0)
my_str("Unable to read\n");
n = write(sockfd, buffer, my_strlen(buffer));
if(my_strncmp(buffer, "/exit", 5) == 0)
exit(0);
if(my_strncmp(buffer, "/nick", 5) == 0)
{
free(nname);
nname = my_strdup(&buffer[6]);
}
if(n <= 0)
my_str("Unable to Write\n");
}
}
|
C
|
/*
Simple GFX (graphics) library based on SDL library
Author: Fabrício Sérgio de Paula (fabricio.paula@gmail.com)
Year: 2013
Use: Before using this library you must install the SDL_gfx and SDL_ttf libraries.
After that, make sure all gfx library files are at the YOUR-PROGRAM-DIR/gfx directory.
Then, your program must include gfx.h and be linked with the -lgfx -lSDL_gfx -lSDL_ttf
options.
*/
#ifndef _GFX_H_
#define _GFX_H_
#include <SDL/SDL.h>
#include <SDL/SDL_gfxPrimitives.h>
#include <SDL/SDL_ttf.h>
#include <assert.h>
#define FONT_NAME "gfx/FreeSans.ttf"
void gfx_init(unsigned width, unsigned height, const char* caption); /* graphic window initialization */
void gfx_quit(); /* graphic window termination */
unsigned gfx_get_width(); /* get window width */
unsigned gfx_get_height(); /* get window height */
void gfx_get_color(unsigned short* r, unsigned short* g, unsigned short* b); /* get current text/object color */
void gfx_set_color(unsigned short r, unsigned short g, unsigned short b); /* set text/object color */
unsigned short gfx_get_font_size(); /* get current text font size */
void gfx_set_font_size(unsigned short size); /* set the text font size */
void gfx_get_text_size(const char* text, int* width, int* height); /* get the width and height of text to be printed on screen */
void gfx_clear(); /* clear screen */
void gfx_text(int x, int y, const char* msg); /* print message at (x,y) point */
void gfx_line(int x1, int y1, int x2, int y2); /* draw a line from (x1,y1) to (x2,y2) */
void gfx_rectangle(int x1, int y1, int x2, int y2); /* draw a rectangle of top-left corner (x1,y1) and bottom-right corner (x2,y2) */
void gfx_filled_rectangle(int x1, int y1, int x2, int y2); /* draw and fill */
void gfx_ellipse(int x, int y, int rx, int ry); /* draw ellipse at center (x,y) and x radius rx and y radius ry */
void gfx_filled_ellipse(int x, int y, int rx, int ry); /* draw and fill */
#endif
|
C
|
#include "SearchCase.h"
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include "Search/Search.h"
#include "SortAlgorithm/SortAlgorithm.h"
#define SIZE 50
void SearchCase()
{
int a[SIZE] = {0};
int index = -1;
int i;
int key;
srand((unsigned int)time(NULL));
for (i=0; i<SIZE; i++) {
a[i] = rand() % 100;
}
key = rand() % 100;
MergeSort(a, SIZE);
// index = Feibo_Search(a, 0, SIZE-1, key);
index = Interpolation_Search(a, 0, SIZE-1, key);
// index = Binary_Search_Ex(a, 0, SIZE-1, key);
// index = Binary_Search(a, 0, SIZE-1, key);
// index = Static_Search(a, SIZE, key);
if (index >= 0) {
printf("array:\n");
Print_Arr(a, SIZE);
printf("Succes!\n");
printf("key = %d, index = %d\n", key, index);
} else {
Print_Arr(a, SIZE);
printf("Fail!\n");
printf("key = %d, index = %d\n", key, index);
}
// SeqList* list = SeqList_Create(SIZE);
//
// for (i=0; i<SIZE; i++) {
// SeqList_Insert(list, (SeqListNode*)(a + i), i);
// }
//
// Print_SeqList(list);
//
// index = Dynamic_Search(list, key);
//
// if (index != -1) {
// Print_SeqList(list);
// printf("Succes!\n");
// printf("key = %d, index = %d\n", key, index);
// } else {
// Print_SeqList(list);
// printf("Fail!\n");
// printf("key = %d, index = %d\n", key, index);
// }
//
// SeqList_Destroy(list);
// int a[SIZE+1] = {0};
// int index = -1;
// int i;
// int key;
//
// srand((unsigned int)time(NULL));
//
// for (i=1; i<=SIZE; i++) {
// a[i] = rand() % 100;
// }
//
// key = rand() % 100;
//
// index = Another_Search(a, SIZE, key);
//
// if (index > 0) {
// Print_Arr(a, SIZE);
// printf("succes!\n");
// printf("key = %d, index = %d\n", key, index);
// } else {
// Print_Arr(a, SIZE);
// printf("Fail!\n");
// printf("key = %d, index = %d\n", key, index);
//
// }
}
void OthreCase()
{
int a[] = {1, 1, 2, 3, 2, 3, 4, 4, 6, 5, 7, 5, 6, 7, 10};
int b[] = {1, 2, 3, 4, 5, 6, 7, 7, 8, 9, 10};
printf("single number = %d\n", FindTheSingleNumber(a, sizeof(a) / sizeof(*a)));
printf("duplicate number = %d\n", FindTheDuplicateNumber(b, sizeof(b) / sizeof(*b)));
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_treatment.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: symatevo <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/04/03 14:54:27 by symatevo #+# #+# */
/* Updated: 2021/04/03 15:29:03 by symatevo ### ########.fr */
/* */
/* ************************************************************************** */
#include "../includes/ft_printf.h"
int ft_is_in_type_list(int c)
{
return ((c == 'c') || (c == 's') || (c == 'p') || (c == 'd') || (c == 'i')
|| (c == 'u') || (c == 'x') || (c == 'X') || (c == '%'));
}
int ft_is_in_flags_list(int c)
{
return ((c == '-') || (c == ' ') || (c == '0') || (c == '.') || (c == '*'));
}
int ft_treatment(int c, t_flags flags, va_list args)
{
int char_count;
char_count = 0;
if (c == 'c')
char_count = ft_treat_char(va_arg(args, int), flags);
else if (c == 's')
char_count = ft_treat_string(va_arg(args, char *), flags);
else if (c == 'p')
char_count = ft_treat_pointer(va_arg(args, unsigned long long), flags);
else if (c == 'd' || c == 'i')
char_count = ft_treat_int(va_arg(args, int), flags);
else if (c == 'u')
char_count += ft_treat_uint((unsigned int)va_arg(args, unsigned int),
flags);
else if (c == 'x')
char_count += ft_treat_hexa(va_arg(args, unsigned int), 1, flags);
else if (c == 'X')
char_count += ft_treat_hexa(va_arg(args, unsigned int), 0, flags);
else if (c == '%')
char_count += ft_treat_percent(flags);
return (char_count);
}
|
C
|
/*
* File: console.c
*
*
* Writing on the console device.
*/
// Esse console é full screen e não precisa de muitos recursos gráficos.
// Somete o super user poderá usá-lo.
// Só existem quatro consoles virtuais. Um deles será usado para
// registrar o servidor gráfico.
// Para pseudo terminais veja: vt.c
// #todo:
// Control Sequence Introducer (CSI)
// See:
// https://docs.microsoft.com/en-us/windows/console/console-virtual-terminal-sequences
//
#include <kernel.h>
// Usado para manipular csi
static unsigned long __state = 0;
#define NPAR 16
static unsigned long npar, par[NPAR];
static unsigned long ques=0;
static unsigned char attr=0x07;
void __local_ri (void)
{
//#todo
}
void __local_gotoxy ( int new_x, int new_y, int console_number )
{
//deletar.
//if (new_x>=columns || new_y>=lines)
//return;
//x=new_x;
//y=new_y;
//pos=origin+((y*columns+x)<<1);
if ( new_x >= (TTY[console_number].cursor_right-1) )
return;
if ( new_y >= (TTY[console_number].cursor_bottom-1) )
return;
TTY[console_number].cursor_x = new_x;
TTY[console_number].cursor_y = new_y;
}
// #bugbug
// Isso tá errado.
#define __RESPONSE "\033[?1;2c"
void __respond (int console_number)
{
char * p = __RESPONSE;
while (*p) {
//PUTCH(*p,tty->read_q);
console_putchar ( (int) *p, console_number );
p++;
}
//copy_to_cooked(tty);
}
static int saved_x=0;
static int saved_y=0;
void __local_save_cur (int console_number)
{
saved_x = TTY[console_number].cursor_x;
saved_y = TTY[console_number].cursor_y;
}
void __local_restore_cur (int console_number)
{
TTY[console_number].cursor_x = saved_x;
TTY[console_number].cursor_y = saved_y;
}
// See:
// https://en.wikipedia.org/wiki/Control_character
// https://en.wikipedia.org/wiki/C0_and_C1_control_codes#Device_control
void __local_insert_char ( int console_number )
{
//int i=x;
//unsigned short tmp,old=0x0720;
//unsigned short * p = (unsigned short *) pos;
/*
while (i++ < columns) {
// Salvo o char da posição atual.
tmp = *p;
// coloco o char de controle na posição atual
// ou o caractere salvo anteriomente.
*p=old;
// coloco o caractere salvo para uso futuro.
old=tmp;
//avança até o fim da linha.
p++;
}
*/
//int i = TTY[console_number].cursor_x;
//int tmp;
//int old = 0x20;
// #bugbug
// Não é possível fazer essa rotina pois não temos um buffer e chars.
//while (i++ < TTY[console_number].cursor_height ) {};
console_putchar (0x20, console_number);
}
void __local_insert_line(int console_number)
{
int oldtop,oldbottom;
oldtop = TTY[console_number].cursor_top;
oldbottom = TTY[console_number].cursor_bottom;
TTY[console_number].cursor_top = TTY[console_number].cursor_y;
TTY[console_number].cursor_bottom = TTY[console_number].cursor_bottom;
console_scroll (console_number);
TTY[console_number].cursor_top = oldtop;
TTY[console_number].cursor_bottom = oldbottom;
}
void __local_delete_char(int console_number)
{
console_putchar ( ' ', console_number);
/*
int i;
unsigned short * p = (unsigned short *) pos;
if (x >= columns)
return;
i = x;
while (++i < columns)
{
*p = *(p+1);
p++;
}
*p=0x0720;
*/
}
void __local_delete_line(int console_number)
{
int oldtop,oldbottom;
oldtop = TTY[console_number].cursor_top;
oldbottom = TTY[console_number].cursor_bottom;
TTY[console_number].cursor_top = TTY[console_number].cursor_y;
TTY[console_number].cursor_bottom = TTY[console_number].cursor_bottom;
//#todo
//scrup();
TTY[console_number].cursor_top = oldtop;
TTY[console_number].cursor_bottom = oldbottom;
}
void csi_J (int par)
{
/*
long count __asm__("cx");
long start __asm__("di");
switch (par) {
case 0: //erase from cursor to end of display
count = (scr_end-pos)>>1;
start = pos;
break;
case 1: //erase from start to cursor
count = (pos-origin)>>1;
start = origin;
break;
case 2: // erase whole display
count = columns*lines;
start = origin;
break;
default:
return;
}
__asm__("cld\n\t"
"rep\n\t"
"stosw\n\t"
::"c" (count),
"D" (start),"a" (0x0720)
:"cx","di");
*/
}
void csi_K(int par)
{
/*
long count __asm__("cx");
long start __asm__("di");
switch (par) {
case 0: //erase from cursor to end of line
if (x>=columns)
return;
count = columns-x;
start = pos;
break;
case 1: //erase from start of line to cursor
start = pos - (x<<1);
count = (x<columns)?x:columns;
break;
case 2: //erase whole line
start = pos - (x<<1);
count = columns;
break;
default:
return;
}
__asm__("cld\n\t"
"rep\n\t"
"stosw\n\t"
::"c" (count),
"D" (start),"a" (0x0720)
:"cx","di");
*/
}
void csi_m(void)
{
int i;
for (i=0;i<=npar;i++)
switch (par[i]) {
case 0:
attr=0x07;
break;
case 1:
attr=0x0f;
break;
case 4:
attr=0x0f;
break;
case 7:
attr=0x70;
break;
case 27:
attr=0x07;
break;
}
}
void csi_M ( int nr, int console_number )
{
if ( nr > TTY[console_number].cursor_height )
nr = TTY[console_number].cursor_height;
else if (!nr)
nr=1;
while (nr--)
__local_delete_line(console_number);
}
void csi_L (int nr, int console_number)
{
if (nr > TTY[console_number].cursor_height)
nr = TTY[console_number].cursor_height;
else if (!nr)
nr=1;
while (nr--)
__local_insert_line(console_number);
}
void csi_P (int nr, int console_number)
{
if (nr > TTY[console_number].cursor_right -1 )
nr = TTY[console_number].cursor_right -1 ;
else if (!nr)
nr=1;
while (nr--)
__local_delete_char(console_number);
}
void csi_at (int nr, int console_number)
{
if (nr > TTY[console_number].cursor_right -1 )
nr = TTY[console_number].cursor_right -1 ;
else if (!nr)
nr=1;
while (nr--)
__local_insert_char(console_number);
}
/*
***************************************
* _console_outbyte:
*
*
* Outputs a char on the console device;
*
*/
// see stdio.h
void _console_outbyte (int c, int console_number){
unsigned long i;
unsigned long x;
unsigned long y;
//O caractere.
char ch = (char) c;
// #test
// Tentando pegar as dimensões do char.
// #importante:
// Não pode ser 0, pois poderíamos ter divisão por zero.
int cWidth = get_char_width ();
int cHeight = get_char_height ();
if ( cWidth == 0 || cHeight == 0 )
{
//#debug
debug_print ("_outbyte: char w h");
printf ("_outbyte: fail w h ");
die ();
}
// #bugbug
// Caso estejamos em modo texto.
// Isso ainda não é suportado.
if ( VideoBlock.useGui == 0 )
{
debug_print ("_outbyte: kernel in text mode");
kprintf ("_outbyte: kernel in text mode");
die ();
}
// #Importante:
// Essa rotina não sabe nada sobre janela, ela escreve na tela como
// um todo. Só está considerando as dimensões do 'char'.
// Caso estivermos em modo gráfico.
if ( VideoBlock.useGui == 1 )
{
//#importante: Essa rotina de pintura deveria ser exclusiva para
//dentro do terminal.
//então essa flag não faz sentido.
if ( stdio_terminalmode_flag == 1 )
{
// ## NÃO TRANPARENTE ##
// se estamos no modo terminal então usaremos as cores
// configuradas na estrutura do terminal atual.
// Branco no preto é um padrão para terminal.
draw_char ( cWidth * TTY[console_number].cursor_x,
cHeight * TTY[console_number].cursor_y,
c,
COLOR_TERMINALTEXT, COLOR_TERMINAL2 );
}else{
// ## TRANSPARENTE ##
// se não estamos no modo terminal então usaremos
// char transparente.
// Não sabemos o fundo. Vamos selecionar o foreground.
drawchar_transparent (
cWidth* TTY[console_number].cursor_x,
cHeight * TTY[console_number].cursor_y,
TTY[console_number].cursor_color,
c );
};
//#testando ...
//g_cursor_x++;
//goto done;
//return;
};
}
/*
*******************************************************************
* outbyte:
* Trata o caractere a ser imprimido e chama a rotina /_outbyte/
* para efetivamente colocar o caractere na tela.
*
* Essa rotina é chamada pelas funções: /putchar/scroll/.
* @todo: Colocar no buffer de arquivo.
*/
void console_outbyte (int c, int console_number){
static char prev = 0;
unsigned long __cWidth = gwsGetCurrentFontCharWidth();
unsigned long __cHeight = gwsGetCurrentFontCharHeight();
if ( __cWidth == 0 || __cHeight == 0 ){
panic ("console_outbyte: char size\n");
}
// Obs:
// Podemos setar a posição do curso usando método,
// simulando uma variável protegida.
//checkChar:
//Opção
//switch ??
//form feed - Nova tela.
if ( c == '\f' )
{
TTY[console_number].cursor_y = TTY[console_number].cursor_top;
TTY[console_number].cursor_x = TTY[console_number].cursor_left;
return;
}
// #m$.
// É normal \n retornar sem imprimir nada.
//Início da próxima linha.
if ( c == '\n' && prev == '\r' )
{
// #todo:
// Melhorar esse limite.
if ( TTY[console_number].cursor_y >= (TTY[console_number].cursor_bottom-1) )
{
console_scroll (console_number);
TTY[console_number].cursor_y = (TTY[console_number].cursor_bottom-1);
prev = c;
}else{
TTY[console_number].cursor_y++;
TTY[console_number].cursor_x = TTY[console_number].cursor_left;
prev = c;
};
return;
};
//Próxima linha no modo terminal.
if ( c == '\n' && prev != '\r' )
{
if ( TTY[console_number].cursor_y >= (TTY[console_number].cursor_bottom-1) ){
console_scroll (console_number);
TTY[console_number].cursor_y = (TTY[console_number].cursor_bottom-1);
prev = c;
}else{
TTY[console_number].cursor_y++;
//Retornaremos mesmo assim ao início da linha
//se estivermos imprimindo no terminal.
if ( stdio_terminalmode_flag == 1 )
{
TTY[console_number].cursor_x = TTY[console_number].cursor_left;
}
//verbose mode do kernel.
//permite que a tela do kernel funcione igual a um
//terminal, imprimindo os printfs um abaixo do outro.
//sempre reiniciando x.
if ( stdio_verbosemode_flag == 1 )
{
TTY[console_number].cursor_x = TTY[console_number].cursor_left;
}
//Obs: No caso estarmos imprimindo em um editor
//então não devemos voltar ao início da linha.
prev = c;
};
return;
};
//tab
//@todo: Criar a variável 'g_tab_size'.
if( c == '\t' )
{
TTY[console_number].cursor_x += (8);
//g_cursor_x += (4);
prev = c;
return;
//Não adianta só avançar, tem que apagar o caminho até lá.
//int tOffset;
//tOffset = 8 - ( g_cursor_left % 8 );
//while(tOffset--){
// _outbyte(' ');
//}
//Olha que coisa idiota, e se tOffset for 0.
//set_up_cursor( g_cursor_x +tOffset, g_cursor_y );
//return;
};
//liberando esse limite.
//permitindo os caracteres menores que 32.
//if( c < ' ' && c != '\r' && c != '\n' && c != '\t' && c != '\b' )
//{
// return;
//};
//Apenas voltar ao início da linha.
if( c == '\r' )
{
TTY[console_number].cursor_x = TTY[console_number].cursor_left;
prev = c;
return;
};
//#@todo#bugbug
//retirei esse retorno para o espaço, com isso
// o ascii 32 foi pintado, mas como todos os
//bits estão desligados, não pintou nada.
//space
//if( c == ' ' )
//{
// g_cursor_x++;
// prev = c;
// return;
//};
// backspace ??
if ( c == 8 )
{
TTY[console_number].cursor_x--;
prev = c;
return;
};
//
// limits
//
// Filtra as dimensões da janela onde está pintando.
// @todo: Esses limites precisam de variável global.
// mas estamos usando printf pra tudo.
// cada elemento terá que impor seu próprio limite.
// O processo shell impõe seu limite.
// a janela impõe seu limite etc...
// Esse aqui é o limite máximo de uma linha.
// Poderia ser o limite imposto pela disciplina de linha
// do kernel para o máximo de input. Pois o input é
// armazenado em uma linha.
//checkLimits:
//Limites para o número de caracteres numa linha.
if ( TTY[console_number].cursor_x >= (TTY[console_number].cursor_right-1) )
{
TTY[console_number].cursor_x = TTY[console_number].cursor_left;
TTY[console_number].cursor_y++;
}else{
// Incrementando.
// Apenas incrementa a coluna.
TTY[console_number].cursor_x++;
};
// #bugbug
// Tem um scroll logo acima que considera um valor
// de limite diferente desse.
// Número máximo de linhas. (n pixels por linha.)
if ( TTY[console_number].cursor_y >= TTY[console_number].cursor_bottom )
{
console_scroll (console_number);
TTY[console_number].cursor_y = TTY[console_number].cursor_bottom;
};
//
// Imprime os caracteres normais.
//
// Nesse momento imprimiremos os caracteres.
// Imprime os caracteres normais.
// Atualisa o prev.
_console_outbyte (c, console_number);
prev = c;
}
// #importante
// Colocamos um caractere na tela de um terminal virtual.
// #bugbug: Como essa rotina escreve na memória de vídeo,
// então precisamos, antes de uma string efetuar a
// sincronização do retraço vertical e não a cada char.
void console_putchar ( int c, int console_number ){
// Pegamos as dimensões do caractere.
int cWidth = get_char_width ();
int cHeight = get_char_height ();
if ( cWidth == 0 || cHeight == 0 ){
panic ("console_putchar: char");
}
// flag on.
stdio_terminalmode_flag = 1;
//
// Console limits
//
if ( console_number < 0 || console_number >= 4 ){
panic ("console_putchar: console_number");
}
// Desenhar o char no backbuffer
// #todo: Escolher um nome de função que reflita
// essa condição de desenharmos o char no backbuffer.
console_outbyte ( (int) c, console_number );
// Copiar o retângulo na memória de vídeo.
refresh_rectangle (
TTY[console_number].cursor_x * cWidth,
TTY[console_number].cursor_y * cHeight,
cWidth,
cHeight );
// flag off.
stdio_terminalmode_flag = 0;
}
// Não tem escape sequence
// Funciona na máquina real
ssize_t __console_write (int console_number, const void *buf, size_t count)
{
if ( console_number < 0 || console_number > 3 )
return -1;
if (!count)
return -1;
char *data = (char *) buf;
char ch;
//
// Write string
//
// original - backup
size_t __i;
for (__i=0; __i<count; __i++)
console_putchar ( (int) data[__i], console_number);
return count;
}
ssize_t console_read (int console_number, const void *buf, size_t count)
{
return -1; //todo
}
// Tem escape sequence
ssize_t console_write (int console_number, const void *buf, size_t count)
{
if ( console_number < 0 || console_number > 3 )
{
printf ("console_write: console_number\n");
refresh_screen();
return -1;
}
if (!count)
{
printf ("console_write: count\n");
refresh_screen();
return -1;
}
if ( (void *) buf == NULL )
{
printf ("console_write: buf\n");
refresh_screen();
return -1;
}
//#DEBUG
//printf ("console_write: >>> \n");
char *data = (char *) buf;
char ch;
// #debug
//console_putchar ( '@',console_number);
//console_putchar ( ' ',console_number);
//console_putchar ( '\n',console_number);
//...
//
// Write string
//
// #debug
// Ok, libc do atacama usa essa rotina.
// console_putchar ( '@', console_number);
// Inicializando.
// Dão dá mais pra confiar !
__state = 0;
int i;
for (i=0; i<count; i++){
ch = data[i];
switch (__state){
// State 0
case 0:
// #debug
//console_putchar ( '@',console_number);
//console_putchar ( '0',console_number);
//console_putchar ( '\n',console_number);
// Printable ?
if (ch >31 && ch <127) {
console_putchar ( ch, console_number );
// Escape.
} else if (ch==27)
__state=1;
else if (ch==10 || ch==11 || ch==12)
console_putchar ( ch, console_number ); // \n ???
else if (ch==13)
console_putchar ( ch, console_number ); //cr \n
else if (ch==8) {
console_putchar ( ch, console_number ); // backspace.
} else if (ch==9) {
console_putchar ( ch, console_number ); // horizontal tab
}
break;
// State 1
case 1:
// #debug
//console_putchar ( '@',console_number);
//console_putchar ( '1',console_number);
//console_putchar ( '\n',console_number);
__state=0;
if (ch=='[')
__state=2;
else if (ch=='E')
__local_gotoxy ( 0, (TTY[console_number].cursor_y + 1), console_number );
else if (ch=='M')
__local_ri (); //scroll. deixa pra depois. kkk
else if (ch=='D')
console_putchar ( ch, console_number ); //lf();
else if (ch=='Z')
__respond (console_number); //test
else if ( TTY[console_number].cursor_x == '7') //?? What L.T.
__local_save_cur (console_number);
else if ( TTY[console_number].cursor_x == '8' ) //?? What L.T.
__local_restore_cur (console_number);
break;
//State 2
case 2:
// #debug
//console_putchar ( '@',console_number);
//console_putchar ( '2',console_number);
//console_putchar ( '\n',console_number);
// Clean
for ( npar=0; npar<NPAR; npar++ )
par[npar]=0;
npar=0;
__state=3; // Next state.
if ( ques = ( ch == '?' ) )
break;
case 3:
// #debug
//console_putchar ( '@',console_number);
//console_putchar ( '3',console_number);
//console_putchar ( '\n',console_number);
if ( ch==';' && npar<NPAR-1) {
npar++;
break;
} else if ( ch >= '0' && ch <='9') {
par[npar] = 10 * par[npar] + ch -'0';
break;
} else __state=4;
case 4:
// #debug
//console_putchar ( '@',console_number);
//console_putchar ( '4',console_number);
//console_putchar ( '\n',console_number);
__state=0;
switch (ch) {
case 'G': case '`':
if (par[0]) par[0]--;
__local_gotoxy (par[0], TTY[console_number].cursor_y, console_number);
break;
case 'A':
if (!par[0]) par[0]++;
__local_gotoxy ( TTY[console_number].cursor_x, TTY[console_number].cursor_y - par[0], console_number);
break;
case 'B': case 'e':
if (!par[0]) par[0]++;
__local_gotoxy ( TTY[console_number].cursor_x, TTY[console_number].cursor_y + par[0], console_number);
break;
case 'C': case 'a':
if (!par[0]) par[0]++;
__local_gotoxy ( TTY[console_number].cursor_x + par[0], TTY[console_number].cursor_y, console_number);
break;
case 'D':
if (!par[0]) par[0]++;
__local_gotoxy ( TTY[console_number].cursor_x - par[0], TTY[console_number].cursor_y, console_number);
break;
case 'E':
if (!par[0]) par[0]++;
__local_gotoxy (0, TTY[console_number].cursor_y + par[0], console_number);
break;
case 'F':
if (!par[0]) par[0]++;
__local_gotoxy (0, TTY[console_number].cursor_y - par[0], console_number);
break;
case 'd':
if (par[0]) par[0]--;
__local_gotoxy ( TTY[console_number].cursor_x, par[0], console_number);
break;
case 'H': case 'f':
if (par[0]) par[0]--;
if (par[1]) par[1]--;
__local_gotoxy (par[1],par[0], console_number);
break;
case 'J':
csi_J (par[0]);
break;
case 'K':
csi_K (par[0]);
break;
case 'L':
csi_L (par[0], console_number);
break;
case 'M':
csi_M (par[0], console_number );
break;
case 'P':
csi_P (par[0], console_number);
break;
case '@':
csi_at (par[0], console_number);
break;
case 'm':
csi_m ();
break;
case 'r':
if (par[0]) par[0]--;
if (!par[1]) par[1] = TTY[console_number].cursor_height; //?? da fuck
if (par[0] < par[1] &&
par[1] <= TTY[console_number].cursor_height ) {
TTY[console_number].cursor_top =par[0];
TTY[console_number].cursor_bottom = par[1];
}
break;
case 's':
__local_save_cur( console_number );
break;
case 'u':
__local_restore_cur (console_number);
break;
};
break;
default:
printf ("console_write: default\n");
refresh_screen();
return -1;
break;
};
};
//printf ("console_write: done\n");
//refresh_screen();
return count;
}
/*
********************************************
* scroll:
* Isso pode ser útil em full screen e na inicialização do kernel.
*
* *Importante: Um (retângulo) num terminal deve ser o lugar onde o buffer
* de linhas deve ser pintado. Obs: Esse retãngulo pode ser configurado através
* de uma função.
* Scroll the screen in text mode.
* Scroll the screen in graphical mode.
* @todo Poderiam ser duas funções: ex: gui_scroll().
*
* * IMPORTANTE
* O que devemos fazer é reordenar as linhas nos buffers de linhas
* para mensagens de texto em algum terminal.
*
* @todo: Ele não será feito dessa forma, termos uma disciplica de linhas
* num array de linhas que pertence à uma janela.
*
* @todo: Fazer o scroll somente no stream stdin e depois mostrar ele pronto.
*
*/
void console_scroll (int console_number){
// #debug
// opção de suspender.
//return;
// Salvar cursor.
unsigned long OldX, OldY;
int i=0;
// Se estamos em Modo gráfico (GUI).
if ( VideoBlock.useGui == 1 )
{
// copia o retângulo.
// #todo: olhar as rotinas de copiar retângulo.
//See: comp/rect.c
scroll_screen_rect ();
//Limpa a última linha.
//salva cursor
OldX = TTY[console_number].cursor_x;
OldY = TTY[console_number].cursor_y;
// Cursor na ultima linha.
TTY[console_number].cursor_x = TTY[console_number].cursor_left;
TTY[console_number].cursor_y = ( TTY[console_number].cursor_bottom -1);
// Limpa a últime linha.
for ( i = TTY[console_number].cursor_x; i < TTY[console_number].cursor_right; i++ )
{
_console_outbyte (' ',console_number);
};
// Reposiciona o cursor na última linha.
TTY[console_number].cursor_x = TTY[console_number].cursor_left;
TTY[console_number].cursor_y = OldY; //( TTY[console_number].cursor_bottom -1);
refresh_screen ();
}
}
/*
********************************
* kclear:
* Limpa a tela em text mode.
* # isso não faz parte da lib c. Deletar.
*/
int kclear (int color, int console_number)
{
int Status = -1;
if ( VideoBlock.useGui == 1 )
{
backgroundDraw ( COLOR_BLUE );
TTY[console_number].cursor_x = 0;
TTY[console_number].cursor_y = 0;
Status = 0;
}else{
Status = -1;
};
return (int) Status;
}
/*
* kclearClientArea:
*/
// Limpa a tela em text mode.
// Isso não faz parte da lib c. Deletar.
int kclearClientArea (int color)
{
return (int) kclear (color, current_vc);
}
/*
*************************************
* insert_line:
*
*/
// Incluir uma linha no buffer de linhas da estrutura do tty atual.
// vamos copiar esse esquema do edito de textos em ring3.
int insert_line ( char *string, int line ){
/*
int l;
struct tty_line_d *Line;
//if ( (void *) string == NULL )
// return -1;
if ( (void *) CurrentTTY != NULL )
{
if ( CurrentTTY->used == 1 && CurrentTTY->magic == 1234 )
{
//Linha atual para se escrever no stdout do current tty
l = CurrentTTY->current_line;
//Pega o ponteiro para estrutura de linha da linha atual.
Line = (struct tty_line_d *) CurrentTTY->lines[l];
if ( (void *) Line == NULL )
return -1;
//Buffer pra colocar chars.
//Line->CHARS[0]
//Line->ATTRIBUTES[0]
//inicio do texto dentro da linha atual
//CurrentTTY->left
//fim do texto dentro da linha atual
//CurrentTTY->right
//posição do ponteiro dentro da linha atual.
//CurrentTTY->pos
}
};
*/
return (int) -1;
}
/*
*******************************************
* REFRESH_STREAM:
* #IMPORTANTE
* REFRESH SOME GIVEN STREAM INTO TERMINAL CLIENT WINDOW !!
*/
void REFRESH_STREAM ( FILE *stream ){
char *c;
//#debug
//sprintf ( stream->_base, "TESTING STDOUT ..." );
int i;
int j;
j = 80*25;
c = stream->_base;
int cWidth = get_char_width ();
int cHeight = get_char_height ();
if ( cWidth == 0 || cHeight == 0 )
{
panic ("REFRESH_STREAM: char w h ");
}
// Seleciona o modo terminal.
//++
stdio_terminalmode_flag = 1;
for ( i=0; i<j; i++ )
{
printf ("%c", *c );
refresh_rectangle (
TTY[current_vc].cursor_x * cWidth,
TTY[current_vc].cursor_y * cHeight,
cWidth, cHeight );
c++;
};
stdio_terminalmode_flag = 0;
//--
}
void console_set_current_virtual_console ( int n )
{
if ( n < 0 )
{
return;
}
if ( n >= 4 )
{
return;
}
current_vc = n;
}
int console_get_current_virtual_console (void)
{
return (int) current_vc;
}
void console_init_virtual_console (int n)
{
if ( n < 0 )
{
return;
}
if ( n >= 4 )
{
return;
}
TTY[n].cursor_x = 0;
TTY[n].cursor_y = 0;
TTY[n].cursor_width = 80;
TTY[n].cursor_height = 80;
TTY[n].cursor_left = 0;
TTY[n].cursor_top = 0;
TTY[n].cursor_right = 80;
TTY[n].cursor_bottom = 80;
TTY[n].cursor_color = COLOR_GREEN; //COLOR_TERMINALTEXT;
}
//
//=========
//
/*
int console_can_read( void);
int console_can_read( void)
{
return 0; //false
}
*/
/*
int console_can_write( void);
int console_can_write( void)
{
return 1; //true
}
*/
|
C
|
/*
File: array.c
Developer: Delenn Sapp
Date: October 22, 2016
Dynamically allocated array
*/
#include <stdlib.h>
#include <stdio.h>
#include "array.h"
#include "../scanner/scanner.h"
#define DEFAULT_SIZE 8
struct array
{
void **array;
int size;
int currentIndex;
};
Array *newArray()
{
Array *a = allocate(sizeof(Array));
a->array = allocate(sizeof(void *) * DEFAULT_SIZE);
a->size = DEFAULT_SIZE;
a->currentIndex = 0;
return a;
}
void freeArray(Array *a)
{
free(a->array);
free(a);
}
void append(Array *a, void *item)
{
int index = a->currentIndex;
if(index == a->size)
{
a->size = a->size * 2;
a->array = reallocate(a->array, sizeof(void *) * a->size);
}
a->array[index] = item;
a->currentIndex += 1;
}
void *getIndex(Array *a, int index)
{
return a->array[index];
}
int getArraySize(Array *a)
{
return a->currentIndex;
}
void setArray(Array *a, int index, void *v)
{
a->array[index] = v;
}
|
C
|
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
//Pending global variables
#define _GNU_SOURCE
//Memory is in Integer format and Opcode is in String format
//Total CPU registers=8
#define REG_NUM 8
int Register_array[REG_NUM];
//DEfining memory size
#define MEM_SIZE 1024
int memory_array[MEM_SIZE];
//program counter
int pc;
//stack pointer
int sp;
//Instruction counter
int noOfInstructions = 0;
//defining physical memory
#define OS_BOOT_Base 0
#define INS_START_ADDR 128
#define DAT_START_ADDR 384
#define Stack_Base 896
#define Stack_top 1024
//defining opcode
#define LD 0x40
#define ST 0x41
int CF,OF = 0; //carry flag and overflag init
int SF,ZF =0;
//To clear the structure
static const struct instructionStructure Empty;
//Read Write structure
struct instructionStructure {
int source1;
int source2;
int destination;
int immediate;
int value;
const char * opcode; // LW = Read & SW = Write
};
//Function to check existence of a char
int checkExistence(char * str, char* a);
//Function to get value between 2 chars
char * getValueBetween(const char *const string, const char *const start, const char *const end);
//Function to convert string into an Instruction Struct
struct instructionStructure parseInstruction(char* strInst);
//Function to replace special chars in a string
char * replaceChar(char * str, char specialChar, char newChar);
//Function to split Instruction string and return string array
char ** splitInstruction(char * instruction);
//READ opration from Source1 address
int readValue(int source);
//WRITE opration at Destination address
void writeValue(int destination, int source);
//OPERATION function
void operate(struct instructionStructure inst);
//Print all values after every instruction execution
int print_values();
//Function to take input from a file with instruction to execute
char **takeInput(char *inputfilePath);
//Function to check is String contains all numbers
int checkAllDigits(const char *str);
//Function to remove starting chars from a string
char * removeStartingChars(char * str,int i);
//Function to store instructions to Instruction memory
int storeInstruction(char* strInst, int location);
//FUnction to get no of instructions
int getNoOfInstruction(char *inputfilePath);
/* ALU functions */
//modulus operation
int mod(int p, int q);
//division
int division(int p, int q);
//multiplication
int mul(int p,int q);
//subtraction
int sub(int p, int q);
//addition
int add(int p, int q);
//ALU function
int aluOperations(int input1,int input2,const char* operation);
int main(){
//4294967295 4294967266
Register_array[0] = -55;
Register_array[1] = -20;
Register_array[2] = 75;
Register_array[3] = 2147483647;
//initialisation
pc = INS_START_ADDR;
sp = Stack_top;
struct instructionStructure inst;
printf("Please provide the filepath for instructions \n");
char filePath[100];
scanf("%s",filePath);
char **InstructionBucket = malloc(100 * sizeof(char *));
char **localInstructions = malloc(100 * sizeof(char *));
//temp path ----------------"/home/paragas12/test/ins.txt"
InstructionBucket = takeInput(filePath);
localInstructions = takeInput(filePath);
noOfInstructions = getNoOfInstruction(filePath);
//Store instructions into memory before execution
for(int j = 0 ; j< noOfInstructions ; j++){
if(storeInstruction(InstructionBucket[j],j+INS_START_ADDR) != 0){
printf("Problem with instruction: %s",InstructionBucket[j]);
exit(-1);
}
}
print_values();
//Find no. of instructions int *ptr = begin; *ptr; ptr++
for(int i=0;i< noOfInstructions;i++){
printf("%s\n",localInstructions[i]);
inst = parseInstruction(localInstructions[i]);
//Operate on given input
operate(inst);
pc = pc+1;
print_values();
}
return 0;
}
//Function to check existence of a char
int checkExistence(char * str, char* a){
char *checkingString = str;
while (*checkingString){
if (strchr(a, *checkingString))
{
return 1;
}
checkingString++;
}
return 0;
}
//Function to get value between 2 chars
char *getValueBetween(const char *const string, const char *const start, const char *const end)
{
char *a;
char *b;
size_t length;
char *result;
if ((string == NULL) || (start == NULL) || (end == NULL))
return NULL;
length = strlen(start);
a = strstr(string, start);
if (a == NULL)
return NULL;
a += length;
b = strstr(a, end);
if (b == NULL)
return b;
length = b - a;
result = malloc(1 + length);
if (result == NULL)
return NULL;
result[length] = '\0';
memcpy(result, a, length);
return result;
}
//Function to convert string into an Instruction Struct
struct instructionStructure parseInstruction(char* strInst){
struct instructionStructure inst;
inst.immediate =0;
char* position;
strInst = replaceChar(strInst,',',' ');
char **strArray = splitInstruction(strInst);
if(sizeof(strArray) < 3)
return inst;
inst.opcode = strArray[0];
if(strstr(strArray[0], "SW") == NULL && strstr(strArray[0], "LW") == NULL){
char* parameter1 = removeStartingChars(strArray[1],1); //R1
char* parameter2 = removeStartingChars(strArray[2],1);//R2
char* parameter3 = removeStartingChars(strArray[3],1);//R3
if(strstr(inst.opcode, "ADD") != NULL || strstr(inst.opcode, "SUB") != NULL || strstr(inst.opcode, "MOD") != NULL || strstr(inst.opcode, "MUL") != NULL || strstr(inst.opcode, "DIV") != NULL){
// Add R1,R2,R3 SUB R1,R2,R3 DIV R1,R2,R3 MUL R1,R2,R3
// R1 do operation R2--> store result in R3(destination)
inst.source1 = (int)strtol(parameter2,&position,sizeof(parameter2));
inst.source2 = (int)strtol(parameter3,&position,sizeof(parameter3));
inst.destination = (int)strtol(parameter1,&position,sizeof(parameter1));
}
}else{
if(strchr(strArray[2],'(')==NULL){
char* parameter1 = removeStartingChars(strArray[1],1);
char* parameter2 = removeStartingChars(strArray[2],1);
//SW R1,R2
//LW R2,R3
if(strstr(inst.opcode, "SW") != NULL){
inst.source1 = (int)strtol(parameter1,&position,sizeof(parameter1));
inst.destination = (int)strtol(parameter2,&position,sizeof(parameter2));
} else if (strstr(inst.opcode, "LW") != NULL){
inst.source1 = (int)strtol(parameter2,&position,sizeof(parameter2));
inst.destination = (int)strtol(parameter1,&position,sizeof(parameter1));
}
}else{
char* parameter1 = removeStartingChars(strArray[1],1);
char* parameter2 = removeStartingChars(getValueBetween(strArray[2],"(",")"),1);
char* immidiateValue = getValueBetween(strArray[2],"","(");
//SW R1,5(R2)
//LW R2,5(R1)
if(strstr(inst.opcode, "SW") != NULL){
inst.source1 = (int)strtol(parameter1,&position,sizeof(parameter1));
inst.destination = (int)strtol(parameter2,&position,sizeof(parameter2));
inst.immediate = (int)strtol(immidiateValue,&position,sizeof(immidiateValue));
} else if (strstr(inst.opcode, "LW") != NULL){
inst.source1 = (int)strtol(parameter2,&position,sizeof(parameter2));
inst.destination = (int)strtol(parameter1,&position,sizeof(parameter1));
inst.immediate = (int)strtol(immidiateValue,&position,sizeof(immidiateValue));
}
}
}
return inst;
}
//Function to store instructions to Instruction memory
int storeInstruction(char* strInst, int location){
char* position;
char instruction[100];
strInst = replaceChar(strInst,',',' ');
char **strArray = splitInstruction(strInst);
if(sizeof(strArray) < 3)
return -1;
/******************* Opcodes ****************/
/*
LW 40
SW 41
ADD 42
SUB 43
MUL 44
DIV 45
MOD 46 */
char* op;
if(strstr(strArray[0], "LW") != NULL){
op = "40";
}else if(strcmp(strArray[0], "SW") != 0){
op = "41";
}else if(strcmp(strArray[0], "ADD") != 0){
op = "42";
}else if(strcmp(strArray[0], "SUB") != 0){
op = "43";
}else if(strcmp(strArray[0], "MUL") != 0){
op = "44";
}else if(strcmp(strArray[0], "DIV") != 0){
op = "45";
}else if(strcmp(strArray[0], "MOD") != 0){
op = "46";
}else{
op = "-1";
return -1;
}
//Instructin format
//Add Op 2, Rt 1, Rs 1 and Rt/Immidiate 2
//Lw Op 2, Rt 1, Rs 1 and Immidiate 2
if(strstr(strArray[0], "SW") == NULL && strstr(strArray[0], "LW") == NULL){
char* parameter1 = removeStartingChars(strArray[1],1); //R1
char* parameter2 = removeStartingChars(strArray[2],1);//R2
char* parameter3 = removeStartingChars(strArray[3],1);//R3
if(strstr(strArray[0], "ADD") != NULL || strstr(strArray[0], "SUB") != NULL || strstr(strArray[0], "MOD") != NULL || strstr(strArray[0], "MUL") != NULL || strstr(strArray[0], "DIV") != NULL){
// Add R1,R2,R3 SUB R1,R2,R3 DIV R1,R2,R3 MUL R1,R2,R3
// R1 do operation R2--> store result in R3(destination)
int p1 = (int)strtol(parameter1,&position,sizeof(parameter1));
int p2 = (int)strtol(parameter2,&position,sizeof(parameter2));
int p3 = (int)strtol(parameter3,&position,sizeof(parameter3));
sprintf(instruction,"%s%01d%01d%02d",op,p3,p1,p2);
memory_array[location] = atoi(instruction);
}
}else{
if(strchr(strArray[2],'(')==NULL){
char* parameter1 = removeStartingChars(strArray[1],1);
char* parameter2 = removeStartingChars(strArray[2],1);
//SW R1,R2
//LW R2,R3
if(strstr(strArray[0], "SW") != NULL){
int s = (int)strtol(parameter1,&position,sizeof(parameter1));
int d = (int)strtol(parameter2,&position,sizeof(parameter2));
sprintf(instruction,"%s%01d%01d00",op,d,s);
memory_array[location] = atoi(instruction);
} else if (strstr(strArray[0], "LW") != NULL){
int s = (int)strtol(parameter2,&position,sizeof(parameter2));
int d = (int)strtol(parameter1,&position,sizeof(parameter1));
sprintf(instruction,"%s%01d%01d00",op,d,s);
memory_array[location] = atoi(instruction);
}
}else{
char* parameter1 = removeStartingChars(strArray[1],1);
char* parameter2 = removeStartingChars(getValueBetween(strArray[2],"(",")"),1);
char* immidiateValue = getValueBetween(strArray[2],"","(");
//SW R1,5(R2)
//LW R2,5(R1)
if(strstr(strArray[0], "SW") != NULL){
int s = (int)strtol(parameter1,&position,sizeof(parameter1));
int d = (int)strtol(parameter2,&position,sizeof(parameter2));
int i = (int)strtol(immidiateValue,&position,sizeof(immidiateValue));
sprintf(instruction,"%s%01d%01d%02d",op,d,s,i);
memory_array[location] = atoi(instruction);
} else if (strstr(strArray[0], "LW") != NULL){
int s = (int)strtol(parameter2,&position,sizeof(parameter2));
int d = (int)strtol(parameter1,&position,sizeof(parameter1));
int i = (int)strtol(immidiateValue,&position,sizeof(immidiateValue));
sprintf(instruction,"%s%01d%01d%02d",op,d,s,i);
memory_array[location] = atoi(instruction);
}
}
}
return 0;
}
//Function to remove starting chars from a string
char * removeStartingChars(char* str,int i){
char *newStr = malloc(sizeof(str) * sizeof(char));
for(int j = 0;j<sizeof(str)-1;j++)
newStr[j] = str[j+1];
newStr[sizeof(str)-1] = '\0';
return newStr;
}
//Function to check is String contains all numbers
int checkAllDigits(const char *str){
while (*str) {
if (isdigit(*str++) == 0)
return 0;
}
return 1;
}
//Function to split Instruction string and return string array
char ** splitInstruction(char * instruction){
char *position = strtok (instruction, " ");
char **array = malloc(10 * sizeof(char *));
int i = 0;
while (position != NULL)
{
array[i++] = position;
position = strtok (NULL, " ");
}
return array;
}
//Function to replace special chars in a string
char * replaceChar(char * str, char specialChar, char newChar){
for (char* p = str; p = strchr(p,specialChar); ++p) {
*p = newChar;
}
return str;
}
//Function to take input from a file with instruction to execute
char **takeInput(char *inputfilePath){
FILE * fp;
char line[50];
char **instructionContainer = malloc(100 * sizeof(char *));
int i=0;
fp = fopen(inputfilePath, "r");
if (fp) {
while(fgets(line,sizeof(line),fp)!= NULL && line !=""){
instructionContainer[i] = malloc (sizeof(line));
strcpy(instructionContainer[i], line);
i++;
}
} else {
printf("File not found !! \n");
exit(-1);
}
fclose(fp);
return instructionContainer;
}
//FUnction to get no of instructions
int getNoOfInstruction(char *inputfilePath){
FILE * fp = fopen(inputfilePath, "r");
int total =0;
//Get no of nstructions
int ch =0;
if(fp == NULL) return 0;
while(!feof(fp)){
ch = fgetc(fp);
if(ch == '\n'){
total++;
}
}
fclose(fp);
return total;
}
//OPERATION function
void operate(struct instructionStructure inst) {
if (strstr(inst.opcode, "LW") != NULL) {
printf("Reading from %d\n",DAT_START_ADDR +inst.immediate+ Register_array[inst.source1]);
Register_array[inst.destination] = readValue(DAT_START_ADDR +inst.immediate+ Register_array[inst.source1]);
}
else if (strstr(inst.opcode, "SW") != NULL) {
printf("Writing to %d\n",Register_array[inst.destination] + inst.immediate + DAT_START_ADDR );
writeValue(Register_array[inst.destination] + inst.immediate + DAT_START_ADDR,Register_array[inst.source1]);
}else if (strstr(inst.opcode, "ADD") != NULL || strstr(inst.opcode, "SUB") != NULL || strstr(inst.opcode, "MUL") != NULL || strstr(inst.opcode, "MOD") != NULL || strstr(inst.opcode, "DIV") != NULL) {
Register_array[inst.destination] = aluOperations(Register_array[inst.source1],Register_array[inst.source2],inst.opcode);
printf("\tResult: %d",Register_array[inst.destination]);
if(Register_array[inst.destination] == 0){
ZF = 1;
}
if (Register_array[inst.destination] == 2147483647 || Register_array[inst.destination] == -2147483574){
CF = 1;
}
if(Register_array[inst.destination] < 0){
SF = 1;
}
if(Register_array[inst.source1] > 0 && Register_array[inst.source2] > 0){
if(Register_array[inst.destination] < 00){
OF = 1;
}
}else if(Register_array[inst.source1] < 0 && Register_array[inst.source2] < 0){
if(Register_array[inst.destination] > 0){
OF = 1;
}
}else{
OF = 0;
}
}else{
printf("Invalid opcode\n" );
exit(-1);
}
}
//READ opration from Source1 address
int readValue(int source) {
return memory_array[source];
}
//WRITE opration at Destination address
void writeValue(int destination, int source) {
memory_array[destination] = source;
}
//ALU function
int aluOperations(int input1,int input2,const char* operation){
int result = 0;
if (strstr(operation, "ADD") != NULL) {
printf("reached add ");
printf("\ninuput 1: %d \tinput 2: %d",input1,input2);
result = add(input1,input2);
}else if (strstr(operation, "SUB") != NULL) {
result = sub(input1,input2);
}else if (strstr(operation, "DIV") != NULL) {
result = division(input1,input2);
}else if (strstr(operation, "MUL") != NULL) {
result = mul(input1,input2);
}else if (strstr(operation, "MOD") != NULL) {
result = mod(input1,input2);
}
//printf("Result: %d",result);
//Carry overflow flag
if (result > 2147483647 || result < -2147483647)
{
printf("Reached carry flag if");
CF = 1;
printf("Carry occurs during operation: %s",operation);
}
return result;
}
//-----------------------------------Bitwise arthimetic Functions-----------------------------------------------------------------------
//addition
int add(int p, int q)
{
if (q == 0)
return p;
else
return add( p ^ q, (p & q) << 1);
}
//subtraction
int sub(int p, int q)
{
if (q == 0)
return p;
return sub(p ^ q, (~p & q) << 1);
}
//multiplication
int mul(int p,int q)
{
int mulvalue=0;
while (q!= 0)
{
if (q & 1)
{
mulvalue = add(mulvalue,p);
}
p <<= 1;
q>>= 1;
}
return mulvalue;
}
//division
int division(int p, int q)
{
int r = 1, temp1;
temp1 = q;
if (p== 0 || q == 0)
{
printf("Division by zero exception in division function\n");
}
if ((p != 0 && q != 0) && (q < p))
{
while (((temp1 << 1) - p) < 0)
{
temp1 = temp1 << 1;
r = r<< 1;
}
while ((temp1 + q) <= p)
{
temp1 = add(temp1, q);
r =add(r,1);
}
}
if (q>0)q=r;
return q;
}
//modulus operation
int mod(int p, int q)
{
int remainder,n = 0;
if (p== 0 || q == 0)
{
printf("Division by zero exception in mod function\n");
}
if (n>0 && q == 2^n)
{
remainder = (p& (q - 1));
}
else
{
remainder = (p - (mul(q,(p/q))));
}
return remainder;
}
//Print all values after every execution
int print_values()
{
printf("\n########################################################\n");
printf("\t\tRegisters values\n");
printf("########################################################\n");
printf("R0 = %d\t\tR1 = %d\t\tR2 = %d\t\tR3 = %d\n",Register_array[0],Register_array[1],Register_array[2],Register_array[3]);
printf("R4 = %d\t\tR5 = %d\t\tR6 = %d\t\tR7 = %d\n",Register_array[4],Register_array[5],Register_array[6],Register_array[7]);
printf("Flags::\t\tCF=%d\t\tOF =%d\t\tZF =%d\t\tSF =%d\n",CF,OF,ZF,SF);
printf("########################################################\n");
printf("\tProgram Counter\n");
printf("########################################################\n");
printf("\tPC = %u\n", pc);
printf("########################################################\n");
printf("\tOperating System allocated Memory\n");
printf("########################################################\n");
printf("Address \t\tMemory\n");
for (int i = 0; i <INS_START_ADDR; i = i + 16)
{
printf("%06d %02X %02X %02X %02X ", i, memory_array[i], memory_array[i+1], memory_array[i+2], memory_array[i+3]);
printf("%02X %02X %02X %02X ", memory_array[i+4], memory_array[i+5], memory_array[i+6], memory_array[i+7]);
printf("%02X %02X %02X %02X ", memory_array[i+8], memory_array[i+9], memory_array[i+10], memory_array[i+11]);
printf("%02X %02X %02X %02X \n", memory_array[i+12], memory_array[i+13], memory_array[i+14],memory_array[i+15]);
}
printf("########################################################\n");
printf("\tInstruction Memory\n");
printf("########################################################\n");
printf("Address \t\tMemory\n");
for (int i=INS_START_ADDR; i <DAT_START_ADDR; i = i+16)
{
printf("%06d %02X %02X %02X %02X ", i, memory_array[i], memory_array[i+1], memory_array[i+2], memory_array[i+3]);
printf("%02X %02X %02X %02X ", memory_array[i+4], memory_array[i+5], memory_array[i+6], memory_array[i+7]);
printf("%02X %02X %02X %02X ", memory_array[i+8], memory_array[i+9], memory_array[i+10], memory_array[i+11]);
printf("%02X %02X %02X %02X \n", memory_array[i+12], memory_array[i+13], memory_array[i+14], memory_array[i+15]);
}
printf("########################################################\n");
printf("\tData Memory\n");
printf("########################################################\n");
printf("Address \t\tMemory\n");
for (int i =DAT_START_ADDR; i < Stack_Base; i = i+16)
{
printf("%06d %02X %02X %02X %02X ", i, memory_array[i], memory_array[i+1], memory_array[i+2], memory_array[i+3]);
printf("%02X %02X %02X %02X ", memory_array[i+4], memory_array[i+5], memory_array[i+6], memory_array[i+7]);
printf("%02X %02X %02X %02X ", memory_array[i+8], memory_array[i+9], memory_array[i+10], memory_array[i+11]);
printf("%02X %02X %02X %02X \n", memory_array[i+12], memory_array[i+13], memory_array[i+14], memory_array[i+15]);
}
printf("########################################################\n");
printf("\tStack Memory\n");
printf("########################################################\n");
printf("Address \t\tMemory\n");
for (int i = Stack_Base; i < 1024; i = i+16)
{
printf("%06d %02X %02X %02X %02X ", i, memory_array[i], memory_array[i+1], memory_array[i+2], memory_array[i+3]);
printf("%02X %02X %02X %02X ", memory_array[i+4], memory_array[i+5], memory_array[i+6], memory_array[i+7]);
printf("%02X %02X %02X %02X ", memory_array[i+8], memory_array[i+9], memory_array[i+10], memory_array[i+11]);
printf("%02X %02X %02X %02X \n", memory_array[i+12], memory_array[i+13], memory_array[i+14], memory_array[i+15]);
}
printf("\n");
}
|
C
|
#include "elecanisms.h"
int16_t main(void) {
init_elecanisms();
uint16_t OCRvalue;
uint8_t *RPOR, *RPINR;
T1CON = 0x0030; // set Timer1 period to 0.5s
PR1 = 0x1869;
TMR1 = 0; // set Timer1 count to 0
IFS0bits.T1IF = 0; // lower Timer1 interrupt flag
T1CONbits.TON = 1; // turn on Timer1
// initialize the motor
D1_DIR = OUT; // configure D1 to be a digital output
D1 = 0; // set D1 low
RPOR = (uint8_t *)&RPOR0;
RPINR = (uint8_t *)&RPINR0;
__builtin_write_OSCCONL(OSCCON & 0xBF);
RPOR[D1_RP] = OC1_RP;
__builtin_write_OSCCONL(OSCCON | 0x40);
OC1CON1 = 0x1C06; // configure OC1 module to use the peripheral clock (i.e., FCY, OCTSEL<2:0> = 0b111) and to operate in edge-aligned PWM mode (OCM<2:0> = 0b110)
OC1CON2 = 0x001F; // configure OC1 module to syncrhonize to itself (i.e., OCTRIG = 0 and SYNCSEL<4:0> = 0b11111)
OC1RS = (uint16_t)(FCY / 1e4 - 1.); // configure period register to get a frequency of 1kHz
OCRvalue = 10*OC1RS/100; // configure duty cycle to 1% (i.e., period / 10)r
OC1R = 0; //both are stopped
OC1TMR = 0; // set OC1 timer count to
while(1) {
if (D0 == 1){
LED1 = 1;
OC1R = 5*OCRvalue;
}
else {
LED1 = 0;
OC1R = 0;
}
}
}
|
C
|
#include<stdio.h>
int main()
{
int a[5]={1,2,3,4,5};
int i,j,max,temp;
for(i=4;i>=0;i--)
{
max=i;
for(j=i-1;j>=0;j--)
{
if(a[j]<a[max]) max=j;
}
temp=a[i];
a[i]=a[max];
a[max]=temp;
}
for(i=0;i<5;i++) printf("%d\n",a[i]);
return 0;
}
|
C
|
#include <stdlib.h>
#include <time.h>
#include <stdio.h>
#include <ctype.h>
/**
* main - Determine if the last digit of a random number is
* greater than or less than 5, or is zero..
(*
* Return: 0 on success
*/
int main(void)
{
char i = 'a';
char j = 'z';
while (i <= j)
{
putchar(i);
i++;
}
i = 'a';
j = 'z';
while (i <= j)
{
putchar(toupper(i));
i++;
}
putchar('\n');
return (0);
}
|
C
|
/*
* Node.h
*
* Created on: 22-Jun-2020
* Author: naren
*/
#ifndef SRC_NODE_H_
#define SRC_NODE_H_
#include<string>
struct Node{
int data;
Node *next;
/**
* @param data of current node
* @param link of next node
*/
Node(int data, Node *next){
this->data = data;
this->next = next;
}
/**
* @param data of current node
* set next to NULL
*/
Node(int data){
this->data = data;
this->next = NULL;
}
};
#endif /* SRC_NODE_H_ */
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include "doublylinked_list.h"
int main(void) {
Cell *head = CreateCell(0, true);
Cell *elem;
InsertNext(head, CreateCell(2, false));
InsertNext(head, CreateCell(1, false));
InsertPrev(head, CreateCell(5, false));
Display(head);
elem = SearchCell(head, 2);
InsertNext(elem, CreateCell(3, false));
Display(head);
elem = SearchCell(head, 5);
DeleteCell(elem);
Display(head);
return EXIT_SUCCESS;
}
|
C
|
#include <stdio.h>
#define MAXN 1000005
int a[MAXN];
int k, n, d;
main() {
scanf("%d", &k);
while (scanf("%d", &d), d >= 0) {
a[n++] = d;
}
k > n ? printf("NULL\n") : printf("%d\n", a[n - k]);
return 0;
}
|
C
|
#include <stdio.h>
#include <sgtty.h>
#include <ctype.h>
#include "boolean.h"
#include "termcap.h"
#define NIL 0 /* Null pointer */
#define DIRSIZE 16 /* Terminal Directory Size */
#define NUMCAP 30 /* Number of capabilities */
#define DATABYTES 4 /* Number of bytes before pointers */
#define STDOUT 1 /* Standard output descriptor */
#define STDIN 0 /* Standard input descriptor */
#define DATA_READY 0x80 /* ttyget "data ready" bit */
#define QUEUE_SIZE 10 /* Input queue size */
struct ttycap cap; /* Terminal capabilities */
int nrows; /* Number of rows on screen */
int ncols; /* Number of columns on screen */
int p_l_row; /* Physical last row */
int p_l_column; /* Physical last column */
int last_row; /* Last row number (0 origin) */
int last_column; /* Last column number (0 origin) */
int delay; /* Screen settle time in seconds */
int cu_size; /* Size of cursor up string */
int cd_size; /* Size of cursor down string */
int cl_size; /* Size of cursor left string */
int cr_size; /* Size of cursor right string */
int hm_size; /* Size of home up string */
int row; /* Current row number (0 origin) */
int column; /* Current column number (0 origin) */
static char ique[QUEUE_SIZE]; /* Input character queue */
static int q_in; /* queue "in" pointer */
static int q_out; /* queue "out" pointer */
BOOLEAN margin; /* True if right margin hit */
blank_line() /* Blank from current position */
{
int i;
if (cap.c_blank != NULL) fputs(cap.c_blank,stdout);
else {
i = column;
while (column <= last_column && !margin) c_output(' ');
if (row == p_l_row) command_line(i);
else move_to(i,row);
}
}
static int check_cursor(s,v) /* Check for cursor string */
char *s; /* Cursor string */
int v; /* Value (< 0) to be returned if match
0 returned if no match
1 returned if lead-in match */
{
int value;
if (s==NULL) return 0;
if ( (value=comp_str(s))==0 ) return 0;
if ( value < 0 ) return 1;
q_out = (q_out+value >= QUEUE_SIZE) ?
q_out+value-QUEUE_SIZE: q_out+value;
return v;
}
clear_screen() /* Clear screen */
{
fputs(cap.c_clear,stdout);
if (delay != 0) sleep(delay);
row = column = 0;
margin = FALSE;
}
command_line(n) /* Move to column n in command line */
int n;
{
int save_row;
save_row = last_row;
last_row = p_l_row;
move_to(n,p_l_row);
last_row = save_row;
}
static int comp_str(s) /* Compare queue to string */
char *s; /* Object string */
/* Returns:
0 if no match
-1 if partial match (lead-in characters)
>0 if exact match and value is string length
*/
{
int i, j; /* string pointers */
if ( s==NULL || (j=q_out)==q_in ) return 0;
i = 0;
while (*(s+i)==ique[j]) {
i++;
if (*(s+i) == NULL) return i;
j = (j<(QUEUE_SIZE-1))? j+1 : 0;
if (j==q_in) return -1;
}
return 0;
}
cursor(v) /* move cursor according to special value */
int v;
{
switch (v) {
case HOME_KEY:
home_up();
break;
case UP_KEY:
move_up(1);
break;
case DOWN_KEY:
move_down(1);
break;
case LEFT_KEY:
move_left(1);
break;
case RIGHT_KEY:
move_right(1);
break;
}
}
c_output(c) /* Output character at current position */
char c;
{
if (!margin) {
putchar(c);
if (column != last_column) column++;
else margin = TRUE;
}
}
home_up() /* Home cursor */
{
fputs(cap.c_home,stdout);
row = column = 0;
margin = FALSE;
}
int input(wait,echo) /* Input character */
BOOLEAN wait; /* True if should wait for character */
BOOLEAN echo; /* True if should echo character */
/* Value is the integer cast of the character.
A value less than zero indicates that a cursor positioning
key or function key was typed. The corresponding values
are given in "termcap.h".
If the character typed is a printing character, the
cursor position is moved right one position unless
it is already in the rightmost column.
The DEL character is not considered a printing character.
If "wait" is FALSE and no data is available, NO_DATA
is returned.
*/
{
struct sgttyb ttbuf;
char ch;
int possible(); /* Check for cursor sequence */
int special;
while (TRUE) {
special = (q_in!=q_out)? possible(): 0;
if (special < 0) {
if (echo) cursor(special);
return special;
}
if ( special==0 && q_in!=q_out ) {
ch = ique[q_out++];
if (q_out == QUEUE_SIZE) q_out=0;
if (echo && isprint(ch)) {
putchar(ch);
if (column<last_column) column++;
}
return (int)ch;
} else if (!wait) {
gtty(STDIN,&ttbuf);
if ((ttbuf.sg_speed & DATA_READY) == 0)
return NO_DATA;
else {
ique[q_in++] = getchar() & 0x7f;
if (q_in == QUEUE_SIZE) q_in = 0;
}
} else {
ique[q_in++] = getchar() & 0x7f;
if (q_in == QUEUE_SIZE) q_in = 0;
}
}
}
static int possible() /* Return possible cursor sequence */
/* Response:
0 if not sequence or lead-in to sequence
> 0 if a lead-in to a sequence
< 0 if a sequence, value should be returned to user
*/
{
int value;
if((value=check_cursor(cap.c_hmkey,HOME_KEY))!=0 ||
(value=check_cursor(cap.c_uarrow,UP_KEY))!=0 ||
(value=check_cursor(cap.c_darrow,DOWN_KEY))!=0 ||
(value=check_cursor(cap.c_larrow,LEFT_KEY))!=0 ||
(value=check_cursor(cap.c_rarrow,RIGHT_KEY))!=0 ||
(value=check_cursor(cap.c_fn0,KEY(0)))!=0 ||
(value=check_cursor(cap.c_fn1,KEY(1)))!=0) return value;
if((value=check_cursor(cap.c_fn2,KEY(2)))!=0 ||
(value=check_cursor(cap.c_fn3,KEY(3)))!=0 ||
(value=check_cursor(cap.c_fn4,KEY(4)))!=0 ||
(value=check_cursor(cap.c_fn5,KEY(5)))!=0 ||
(value=check_cursor(cap.c_fn6,KEY(6)))!=0 ||
(value=check_cursor(cap.c_fn7,KEY(7)))!=0 ||
(value=check_cursor(cap.c_fn8,KEY(8)))!=0 ||
(value=check_cursor(cap.c_fn9,KEY(9)))!=0) return value;
return 0;
}
s_output(s) /* Output string at current position */
char *s;
{
for (; *s != NULL; s++) c_output(*s);
}
BOOLEAN termcap(cp) /* Get terminal capabilities */
struct ttycap *cp;
{
char **cap_ptr;
int i;
long j;
int fd;
int direct[DIRSIZE];
long lseek();
int open(), read();
if ( (fd=open("/etc/termcap",0)) == -1) return FALSE;
if (
(i=read(fd,(char *)direct,sizeof(int)*DIRSIZE)) == -1 ||
i != sizeof(int)*DIRSIZE ||
(i=direct[termnumb(0)]) == 0 ||
(j=lseek(fd, (long)i, 0)) == -1L ||
(i=read(fd,(char *)cp,sizeof(struct ttycap))) == -1 ||
i != sizeof(struct ttycap)
) {
close(fd);
return FALSE;
}
close(fd);
cap_ptr = (char **)( (char *)cp+DATABYTES );
for (i=NUMCAP; i--; cap_ptr++)
if (*cap_ptr != NIL) *cap_ptr += (unsigned)cp;
return TRUE;
}
BOOLEAN terminit() /* Initialize terminal */
{
if ( ! termcap(&cap) ) return FALSE;
nrows = (int)cap.c_rows;
ncols = (int)cap.c_cols;
p_l_row = nrows-1;
last_row = nrows-2;
p_l_column = last_column = ncols-1;
delay = (int)cap.c_wait;
cu_size = strlen(cap.c_up);
cd_size = strlen(cap.c_down);
cl_size = strlen(cap.c_left);
cr_size = strlen(cap.c_right);
hm_size = strlen(cap.c_home);
setbuf(stdout,0);
set_raw(stdout->_fd);
if (cap.c_init != NIL) fputs(cap.c_init,stdout);
clear_screen();
return TRUE;
}
|
C
|
#pragma once
/** *************************************************************************************
* Dossier 1 : Analyse de donnees clients
* ======================================
*
* Group table functions prototypes
*
* PP 2020-2021 - Laura Binacchi - Fedora 32
****************************************************************************************/
#include "db_file/database.h"
/**
* Imports a group from a csv file line to the dat file
*
* @param db: database information stored in RAM
* @param csv_line: csv line buffer to import
*
* @return the number of new records imported (1 if all is ok)
*/
int import_group(struct db *db, char *csv_line);
/**
* Exports a group from the dat file to a new csv file
*
* @param db: database information stored in RAM
*
* @return the number of tuples successfully exported (1 or 0)
*/
int export_group(struct db *db);
/**
* Loads the group table from the database file to the RAM stored buffer
*
* @param db: database information stored in RAM
* @param count: number of records to load
*
* @return the number of records successfully loaded
*/
int load_groups(struct db *db, int count);
/**
* Reads a group by direct access in the database file
* /!\ free after use
*
* @param db: database information stored in RAM
* @param db: group offset in the database file
*
* @return either
* a pointer to the group found
* NULL if an error occured
*/
void *read_group(struct db *db, unsigned offset);
/**
* Prints a detailed vue of a group
*
* @param group: group to print
*/
void print_group_details(struct group *group);
/**
* Prints a group
*
* @param group: group to print
*/
void print_group(struct group *group);
/**
* Prints the group table header containing its fields names
*/
void print_group_header(void);
/**
* Compares a searched id with the group id
*
* @param db: database information stored in RAM
* @param offset: offset of the group to compare
* @param searched: id searched
*
* @return either
* < 0 if the searched id is lower than the group id
* 0 if the searched id is equal to the group id
* > 0 if the searched id is greater than the group id
* INT_MAX if an error occured
*/
int compare_group_id(struct db *db, unsigned offset, unsigned searched);
/**
* Compares a group referenced by its index with a searched substring
*
* @param db: database information stored in RAM
* @param i: index of the group to compare
* @param searched: substring searched
*
* @return either:
* - the pointer of the group if one of its field contains the substring
* - NULL if no field contains the substring
*/
void *compare_group(struct db *db, unsigned i, char *searched);
|
C
|
#include "function_list.h"
libab_result libab_function_list_init(libab_function_list* list) {
return libab_ref_vec_init(&list->functions);
}
libab_result libab_function_list_insert(libab_function_list* list,
libab_ref* function) {
return libab_ref_vec_insert(&list->functions, function);
}
size_t libab_function_list_size(libab_function_list* list) {
return list->functions.size;
}
void libab_function_list_index(libab_function_list* list, size_t index,
libab_ref* into) {
libab_ref_vec_index(&list->functions, index, into);
}
void libab_function_list_free(libab_function_list* list) {
libab_ref_vec_free(&list->functions);
}
|
C
|
#include <stdio.h>
int x;
#define CZYT(a, d) printf("Podaj wartosc "#a":"); scanf("%"#d"", &a);
int main()
{
x=0;
CZYT(x, d)
printf("%d\n", x);
return 0;
}
|
C
|
// first OpenVG program
// Anthony Starks (ajstarks@gmail.com)
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include "VG/openvg.h"
#include "VG/vgu.h"
#include "fontinfo.h"
#include "shapes.h"
int main() {
int width, height;
char s[3];
init(&width, &height); // Graphics initialization
Start(width, height); // Start the picture
Background(0, 0, 0); // Black background
Fill(44, 77, 232, 1); // Big blue marble
//Circle(width / 2, 0, width); // The "world"
int size = 40;
float w = 0.5 * width;
float h = 0.5 * height;
float x = 0.25 * width;
float y = height - 0.25 * height;
Rect(x, (1 - 0.25) * height - 0.5 * height,w,h);
//TextMid(width / 2, height / 2, "hello, world", SerifTypeface, width / 10); // Greetings
char* text = "Three years ago, Despicable Me launched Illumination Entertainment and announced Universal Studios as a viable player in the animation game (only Disney/Pixar and DreamWorks used to show up to these box-office battles). The film wasn't even the only supervillain animation to hit the theaters that year, but it did one-up its rival Megamind both in critical acclaim and commercial success.\n\nNow, the original film's creative team returns with Despicable Me 2, continuing the adventures of former supervillain father Gru, his precocious daughters Margo, Edith, and Agnes, and his little...";
printf("Writing text\n");
Fill(255, 255, 255, 1); // White text
TextWrap(x, y, text,
w, h, 0.2, SerifTypeface, size);
printf("End\n");
End(); // End the picture
fgets(s, 2, stdin); // look at the pic, end with [RETURN]
finish(); // Graphics cleanup
exit(0);
}
|
C
|
#include <stdio.h>
int main()
{
// int ch = 'A';
// int count = 3;
//
// while (count)
// {
// ch += count;
// count -= 1;
// putchar(ch);
// }
//
// putchar('\n');
char* std1;
char i;
printf("Input a line of english sentence:");
while (( i = getchar())!= '\n') // getchar治Ҫiwhile (getchar() != '\n')
{
if ((int) i >= 65 && (int)i <= 90)
{
putchar(int i + 32 ); continue;
// return;
// return;
}
if ((int) i >= 97 && (int)i <= 122)
{
putchar( int i - 32);continue;
}
else
{
putchar(i);continue;
}
}
return 0;
}
|
C
|
#include <stdio.h>
int main()
{
int i=0,n=6,Pos=0,Zero=0,Negg=0;
short Start[]={0x7602, 0x8D48, 0x2120, 0, 0xE605, 4};
for(i;i<n;i++)
{
if(Start[i]==0)
{ Zero++;}
else if(Start[i]<0)
{Negg++;}
else if(Start[i]>0)
{Pos++;}
}
printf("Pos=%d Zero=%d Negg=%d\n",Pos,Zero,Negg);
return 0;
}
/*
7. 零、正數、與負數的個數
目的 : 決定一串數目中,零、正數(最高效位元為 0,其餘不全
為 0)、與負數(最高效位元為 1)的個數。此串數目的個數存 於 n 中,且數目本身由 Start 開始。把零、正數、與負數的 個數分別存於 Zero、Pos 與 Negg 中。
範例:
int n = 6;
int Pos; int Zero; int Negg;
short Start[]={0x7602, 0x8D48, 0x2120, 0, 0xE605, 4}; 結果:
Pos = 3(4,如果0算正數) Zero =1 Negg=2
*/
|
C
|
/*
예제 HelloWorld.c를 참고하여, 각자의 이름, 주소, 전화번호를 출력하는 간단한 프로그램을 작성해보자.
작성하면서 코드에 주석도 사용하도록 하자. 출력 결과의 예는 다음과 같다.
출력 예)
이창현
경기도 수원시 영통구 매탄동
010-4477-XXXX
*/
#include <stdio.h>
int main(void)
{
printf("최현준\n");
printf("경기도 성남시 분당구 판교동\n");
printf("010-9298-XXXX");
return 0;
}
|
C
|
/*
* @file Date.h
* @details Contains all alarm function prototypes
* and the Date structure definition
* Uses header guards so extern definitions
* aren't used in Date.c module
* @author Liam JA MacDonald
* @date 2-Oct-2019 (Created)
* @date 9-Oct-2019 (Last Modified)
*/
#pragma once
/*
* @brief date structure
* @details Holds all variables needed for date
* state.
* int day: holds current day
* int month: holds current month
* int year: holds current year
* Set by setDate function in Date.c module.
* Each member variable has an update function
*/
typedef struct date_
{
int day;
int month;
int year;
}date;
#ifndef GLOBAL_DATE
#define GLOBAL_DATE
extern int setDate(char*);
extern void updateDay(void);
#else
int monthNumber(char*);
int checkDate(int,int,int);
void updateMonth(void);
void updateYear(void);
#endif /* DATE_H_ */
|
C
|
/*!
* \file genericLLTest.c
* \brief Source file to test generic LinkList
*
* Revision History:
* Date User Comments
* 4-Apr-19 Mukund A Create Original
*/
#include <stdio.h>
#include <stdbool.h>
#include "genericLL.h"
void iterateInt(void *);
int findKey(void *, void *);
int comparatorFn(void *left, void *right);
void main()
{
// create new linklist
printf("\n\n\n Sorting List\n\n");
void *ptrInt3 = sListNew(sizeof(int));
// insert values
int arr[] = {13,15,1,5,2,99,45,21,8,12,9};
int arrSize = sizeof(arr)/sizeof(int);
printf("array size to be inserted : %d\n", arrSize);
for(int i = 0; i < arrSize; i++) {
printf("Value inserting : %d\n", *(arr+i));
sListItemAdd(ptrInt3, (arr+i));
}
// List size
printf("Node Count in ptrInt3 : %d\n", sListGetCount(ptrInt3));
// print unsorted list
printf("\n\n Unsorted List : \n");
sListIterator(ptrInt3, iterateInt);
// sort the list
sListSort(ptrInt3, comparatorFn);
//print the sorted list
printf("\n\n Sorted List : \n");
sListIterator(ptrInt3, iterateInt);
// get Count
printf("HighMarkCount : %d\n", sListGetHighMark(ptrInt3));
printf("Count : %d\n", sListGetCount(ptrInt3));
// Pop a node
printf("Delete a node\n");
int a = 21;
int b = 45;
sListItemDel(ptrInt3, &a, findKey);
sListItemDel(ptrInt3, &b, findKey);
// get Count
printf("HighMarkCount : %d\n", sListGetHighMark(ptrInt3));
printf("Count : %d\n", sListGetCount(ptrInt3));
sListItemAdd(ptrInt3, &a);
// get Count
printf("HighMarkCount : %d\n", sListGetHighMark(ptrInt3));
printf("Count : %d\n", sListGetCount(ptrInt3));
sListItemAdd(ptrInt3, &a);
// get Count
printf("HighMarkCount : %d\n", sListGetHighMark(ptrInt3));
printf("Count : %d\n", sListGetCount(ptrInt3));
sListItemAdd(ptrInt3, &a);
// get Count
printf("HighMarkCount : %d\n", sListGetHighMark(ptrInt3));
printf("Count : %d\n", sListGetCount(ptrInt3));
}
void iterateInt(void *data)
{
printf("Value : %d\n", *(int *)data);
// (*(int *)data)++; // User can modify the value
}
int findKey(void *data, void *key)
{
if(*(int *)data == *(int *)key) {
return 1;
} else {
return 0;
}
}
int comparatorFn(void *left, void *right)
{
if(*(int *)left == *(int *)right) {
return 0;
} else if (*(int *)left <= *(int *)right) {
return -1;
} else {
return 1;
}
}
|
C
|
/*
### AVENTURA 2 ###
Squad: LRAOS
Miembros:
Camino, Lluís
López, Rubén
Reyes, Andrea
*/
#define _POSIX_C_SOURCE 200112L
#define COMMAND_LINE_SIZE 1024
#define ARGS_SIZE 64
#define PROMPT '$'
#define TRUE 1
#define FALSE 0
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h> //errno
#include <string.h> //strerror()
#pragma region //COLORES (Eliminar los que no se usen)
#define RESET_COLOR "\x1b[0m"
#define NEGRO_T "\x1b[30m"
#define NEGRO_F "\x1b[40m"
#define ROJO_T "\x1b[31m"
#define ROJO_F "\x1b[41m"
#define VERDE_T "\x1b[32m"
#define VERDE_F "\x1b[42m"
#define AMARILLO_T "\x1b[33m"
#define AMARILLO_F "\x1b[43m"
#define AZUL_T "\x1b[34m"
#define AZUL_F "\x1b[44m"
#define MAGENTA_T "\x1b[35m"
#define MAGENTA_F "\x1b[45m"
#define CYAN_T "\x1b[36m"
#define CYAN_F "\x1b[46m"
#define BLANCO_T "\x1b[37m"
#define BLANCO_F "\x1b[47m"
#pragma endregion
void imprimir_prompt();
char *read_line(char *line);
int execute_line(char *line);
int parse_args(char **args, char *line);
int check_internal(char **args);
int internal_cd(char **args);
int internal_export(char **args);
int internal_source(char **args);
int internal_jobs(char **args);
int internal_cd(char **args);
void imprimir_prompt() {
char dir [ARGS_SIZE];
getcwd(dir, ARGS_SIZE);
char ESC = 27;
printf("%c[1m"VERDE_T"%s:~"AZUL_T"%s"ROJO_T"%c "RESET_COLOR , ESC ,getenv("USER"),dir,PROMPT);
printf("%c[0m",ESC); /* turn off bold */
fflush(stdout);
}
int main() {
char line[ARGS_SIZE];
while (read_line(line)) {
execute_line(line);
}
return 0;
}
char *read_line(char *line) {
imprimir_prompt();
fgets(line, ARGS_SIZE, stdin);
return line;
}
int execute_line(char *line) {
char *args[ARGS_SIZE];
parse_args(args, line);
int check = check_internal(args);
if (check == FALSE) { // Ejecutar comando externo
pid_t pid = fork();
if (pid == 0) { // Proceso hijo
printf("[execute_line() → PID Hijo: %d]\n", getpid());
if (execvp(args[0], args) == -1) {
fprintf(stderr, "%s\n", strerror(errno));
exit(FALSE);
}
} else if (pid > 0) { // Proceso padre
printf("[execute_line() → PID Padre: %d]\n", getpid());
wait(NULL);
} else {
// Error
}
return TRUE;
} else {
return check;
}
}
/**
* Divide una instrucción en tokens, que guarda en el
* parámetro **args.
* @param args, line
* @return Número de tokens
*/
int parse_args(char **args, char *line) {
const char s[4]="\t\n ";
char * token;
token = strtok(line, s);
int i = 0;
while (token != NULL) {
if (token[0] != '#') {
args[i] = token;
i++;
}
token = strtok(NULL, s);
}
args[i] = token;
return i;
}
/*
* Función booleana que averigua si args[0] se trata de un
* comando interno y llama a la función correspondiente para
* tratarlo.
* @param args
* @return:
* FALSE: si no se trata de un comando interno
* TRUE: se ha ejecutado un comando interno
*/
int check_internal(char **args) {
int comp = strcmp(args[0], "cd");
if (comp == 0) {
return internal_cd(&args[0]);
}
comp = strcmp(args[0], "export");
if (comp == 0) {
return internal_export(&args[0]);
}
comp = strcmp(args[0], "source");
if (comp == 0) {
return internal_source(&args[0]);
}
comp = strcmp(args[0], "jobs");
if (comp == 0) {
return internal_jobs(&args[0]);
}
comp = strcmp(args[0], "exit");
if (comp == 0) {
exit(0);
}
return FALSE;
}
/*
* Función que notifica la sintaxis correcta de la instrucción
* utilizando la salida estandar de errores stderr.
* @param args
* @return:
* TRUE: no ocurrieron errores en la ejecución
* -1: ocurrió un error durante la ejecucuón
*/
int internal_cd(char **args) {
int r;
char s[180];
/* ### Línea de test - Eliminar después ### */
printf("Ruta anterior: [internal_cd() → %s] \n", getcwd(s,sizeof(s)));
/* ################################ */
if (args[1]==NULL){
r = chdir(getenv("HOME"));
/* ### Línea de test - Eliminar después ### */
printf("Ruta actual: [internal_cd() → %s] \n", getcwd(s,sizeof(s)));
/* ################################ */
if (r==-1){
fprintf(stderr, "chdir: %s\n", strerror(errno));
}
return r == 0 ? TRUE : -1;
}else{
r = chdir(args[1]);
/* ### Línea de test - Eliminar después ### */
printf("Ruta actual: [internal_cd() → %s] \n", getcwd(s,sizeof(s)));
/* ################################ */
if (r==-1){
fprintf(stderr, "chdir: %s\n", strerror(errno));
}
return r == 0 ? TRUE : -1;
}
}
/**
* Comando interno export, define una variable de entorno.
* Sintaxis: export Nombre=Valor
* @param args
* @return:
* TRUE: ejecución correcta
* -1: error en la ejecución
*/
int internal_export(char **args){
//Control de errores: sin argumentos despues de export
if(args[1] == NULL){
fprintf(stderr, "Error de sintaxis. Uso: export Nombre=Valor\n");
return -1;//error
}
//Separación en tokens de la instruccion
char *nom = strtok(args[1], "=");
char *val = strtok(NULL, " ");
//Control de errores: uso incorrecto de los argumentos contiguos a export
if(val == NULL){
fprintf(stderr, "Error de sintaxis. Uso: export Nombre=Valor\n");
return -1;//error
}
printf("[internal_export()→ Esta función asignará valores a variables de entorno]\n");
printf("[internal_export()→ Nombre: %s]\n", nom);
printf("[internal_export()→ Valor: %s]\n",val);
printf("[internal_export()→ antiguo valor para %s: %s]\n", nom, getenv(nom));
setenv(nom, val, 1);
printf("[internal_export()→ nuevo valor para %s: %s]\n",nom,getenv(nom) );
return TRUE;
}
/**
* Comando interno source, lee un fichero línea a línea
* Sintaxis: source <nombre_fichero>
* @param args
* @return:
* 0: ejecución correcta
* -1: error en la ejecución
*/
int internal_source(char **args) {
FILE *fp;
char str[100];
int e;
printf("Función source\n");
if (args[1]==NULL){
fprintf(stderr, "Error de sintaxis. Uso: source <nombre_fichero>\n");
return -1;
}else{
fp = fopen(args[1], "r"); // se abre el fichero
if(fp==NULL){ // se comprueba que existe el fichero
fprintf(stderr, "fopen: %s\n", strerror(errno));
return -1;
}
while(fgets(str, 100, fp)){ // se lee el fichero línea a línea
e = execute_line(str);
fflush(stdin); // se limpia el stream del fichero
}
e = fclose(fp); // se cierra el fichero
if(e==-1){
fprintf(stderr, "fclose: %s\n", strerror(errno));
return e;
}
}
return TRUE;
}
int internal_jobs(char **args) {
printf("Función Jobs\n");
return TRUE;
}
|
C
|
/* ڵ
000000111000
000100111100
001001010001
001100101101
010001111101
010100000000
110000000011
-100000000000
*/
#include <stdio.h>
#include <string.h>
#include "stdlib.h"
typedef struct { //ɾ
unsigned short opcode:4;
unsigned short operand:8;
}inc;
inc memory[256]; //
short r1,r2,r3,r4; //
inc mbr;
char pc1[4];
int pc,mar;
//---Լ
void inc_print(inc);
void decode(inc);
void two (int);
//-------------------------------------------
void main(){
int add, opco, oper, i;
char ad[4], opc[4], ope[4];
char menu, inter;
printf(" \n");
printf(" Assembly Team Project \n");
printf(" : ӿ, , \n");
printf(" \n");
while(1){
printf("\n \n");
printf(" M E N U \n");
printf(" a : \n");
printf(" p : PC Է \n");
printf(" c : \n");
printf(" i : ͷƮ \n");
printf(" e : \n");
printf(" \n\n");
printf(" * ϼ : "); // ߿....
scanf("%c", &menu);
switch(menu){
case 'a': // Է
while(1){
printf(" - [address][opcode][operand] : ");
// 2 Է¹ޱ
fflush(stdin);
for(i=0; i<4; i++)
scanf("%c", &ad[i]);
for(i=0; i<4; i++)
scanf("%c", &opc[i]);
for(i=0; i<4; i++)
scanf("%c", &ope[i]);
// 2 · Է¹ 10 ٲٱ
add = 8*(ad[0]-48) + 4*(ad[1]-48) + 2*(ad[2]-48) + 1*(ad[3]-48);
opco = 8*(opc[0]-48) + 4*(opc[1]-48) + 2*(opc[2]-48) + 1*(opc[3]-48);
oper = 8*(ope[0]-48) + 4*(ope[1]-48) + 2*(ope[2]-48) + 1*(ope[3]-48);
// Է° ƴ϶ ش opcode,operand
if(add>=0 && opco>=0 && oper>=0){
memory[add].opcode=opco;
memory[add].operand=oper;
continue;
}
break; // Է° (Ѱ..)
}
break;
case 'p': // pc Է
printf(" - Input PC : ");
// 2 Է¹ޱ
fflush(stdin);
for(i=0; i<4; i++)
scanf("%c", &pc1[i]);
// 2 · Է¹ 10 ٲٱ
pc = 8*(pc1[0]-48) + 4*(pc1[1]-48) + 2*(pc1[2]-48) + 1*(pc1[3]-48);
break;
case 'c': //
printf("\n - PC = "); two(pc); printf("\n");
mar=pc; // mar pc ־
printf(" - MAR <- "); two(pc); printf("\n");
// ش opcode,operand mbr
mbr.opcode=memory[pc].opcode;
mbr.operand=memory[pc].operand;
printf(" - MBR <- "); inc_print(mbr);
decode(mbr); // ɾ ص
break;
case 'i': // ͷƮ
printf( " \n");
printf(" !!!ͷƮ !!! \n") ;
printf(" ͷƮ Ϸ rԷ\n");
while(1){
scanf("%c", &inter);
if(inter=='r')
break;
printf(" --interrupt mode--");
fflush(stdin);
}
printf(" !!!ͷƮ !!! \n");
printf(" \n");
break;
case 'e': // α
printf(" - α մϴ. ByeBye~\n");
exit(1);
break;
default:
printf("ȹٷ Էϼ!");
}//switch
fflush(stdin);
}//while
}//main
//------10 2 ------------
void two (int dec){
// Է¹ 10 2 迭
int i;
int a[4] ;
a[3] = dec % 2 ;
dec = dec / 2 ;
a[2] = dec % 2 ;
dec = dec / 2 ;
a[1] = dec % 2 ;
a[0] = dec / 2 ;
//
for ( i = 0 ; i < 4 ; i ++ )
printf ("%d", a[i] ) ;
}
//----mbr -------------------
void inc_print(inc i){
// Է¹ structureȿִ 10 2 迭
int j;
int a[4], b[4] ;
a[3] = i.opcode % 2 ;
i.opcode = i.opcode / 2 ;
a[2] = i.opcode % 2 ;
i.opcode = i.opcode / 2 ;
a[1] = i.opcode % 2 ;
a[0] = i.opcode / 2 ;
b[3] = i.operand % 2 ;
i.operand = i.operand / 2 ;
b[2] = i.operand % 2 ;
i.operand = i.operand / 2 ;
b[1] = i.operand % 2 ;
b[0] = i.operand / 2 ;
for ( j = 0 ; j < 4 ; j ++ )
printf ("%d", a[j] ) ;
printf (" ") ;
for ( j = 0 ; j < 4 ; j ++ )
printf ("%d", b[j] ) ;
printf ("\n") ;
}
//---ڵ-------------------------------------
void decode(inc mbr) {
printf("\n \n");
printf(" Decoder Execution \n");
printf(" \n");
r2=mbr.opcode; // mbr opcode r2
r3=mbr.operand; // mbr operand r3
switch(r2){
case 0: // ɾ HALT
if(r3==0){ //r3 0̸
printf(" END \n");
pc=14;
exit(1);
}
break;
case 1: // ɾ LOAD
printf(" LOAD \n");
r1=memory[r3].operand; // r3 operand r1
printf(" - R1 <==memory["); two(r3); printf("]\n");
pc++; // pc
printf(" - PC +1 \n");
printf("\n") ;
break;
case 2: // ɾ STOR
printf(" STORD \n");
memory[r3].operand=r1; // r1 r3 operand
printf(" - memory["); two(r3); printf("] <-- R1\n");
pc++; // pc
printf(" - PC +1 \n");
printf("\n") ;
break;
case 3: // ɾ ADD
printf(" ADD \n");
printf(" - ALU ؼ \n");
r1+=memory[r3].operand; // r1 r3 operand r1
printf(" - R1 = R1 + memory["); two(r3); printf("] \n");
pc++;// pc
printf(" - PC +1 \n");
printf("\n") ;
break;
case 4: // ɾ SUBT
printf(" SUB \n");
printf(" - ALU ؼ \n");
r1 -= memory[r3].operand; // r1 r3 operand r1
printf(" - R1 = R1 - memory["); two(r3); printf("] \n");
pc++;// pc
printf(" - PC +1 \n");
printf("\n") ;
break;
case 5: // ɾ JL
printf(" JL \n");
if(r1<10){ //r1 10 ۴ٸ
pc=r3; // pc r3
printf(" - PC = "); two(r3); printf("\n");
}
else{
pc++;// pc
printf(" - PC +1 \n");
}
printf("\n") ;
break;
case 6: // ɾ JMP
printf(" JMP \n");
pc=r3; // pc r3. б
printf(" - PC = "); two(r3); printf("\n");
printf("\n") ;
break;
case 7: // ɾ PRINT
printf(" PRINT \n");
printf (" - ") ;
two(r3); printf(" = "); two(memory[r3].operand);
pc++;// pc
printf("\n - PC +1 \n");
printf("\n") ;
break;
default:
printf(" ߸ opcode Դϴ. \n");
printf("\n") ;
}//switch
}
|
C
|
// Nathaniel Lyra
// COP 3502C, Spring 2019
// na107394
// Create a "lonely party array", where arrays are broken into fragments
// that get allocated and deallocateded on an as needed basis.
#include "header.h"
#include <stdio.h>
#include <stdlib.h>
LonelyPartyArray *createLonelyPartyArray(int num_fragments, int fragment_length)
{
int i, j;
// If one or both parameters passed are <= 0, immediately return NULL.
if ((num_fragments || fragment_length) <= 0)
{
return NULL;
}
// Dynamically allocates a new struct LPA type called party of size LPA*.
LPA *party = malloc(sizeof(LPA*) * (num_fragments * fragment_length));
// If malloc function fails for some reason, return NULL.
if (party == NULL)
return NULL;
// Set each new struct member to corresponding and appropriate value.
party->num_fragments = num_fragments;
party->fragment_length = fragment_length;
party->num_active_fragments = 0;
party->size = 0;
// Dynamically allocate struct member "fragments" to size of the parameter being passed.
party->fragments = malloc(sizeof(int*) * (num_fragments));
// If malloc function fails, free all memory previously allocated and return NULL.
if (party->fragments == NULL)
{
free(party);
return NULL;
}
// Dynamically allocate struct member fragment_sizes
party->fragment_sizes = malloc(sizeof(int) * (num_fragments));
// Set each fragments to NULL and fragment_sizes to 0 since no cells are currently in use.
for (i = 0; i < num_fragments; i++)
{
party->fragments[i] = NULL;
party->fragment_sizes[i] = 0;
}
// Since function has not yet returned NULL, means malloc succeeded. Print success message.
printf("-> A new LonelyPartyArray has emerged from the void. (capacity: %d, fragments: %d)\n",
party->num_fragments * party->fragment_length, party->num_fragments);
// Return pointer to new LonelyPartyArray.
return party;
}
LonelyPartyArray *destroyLonelyPartyArray(LonelyPartyArray *party)
{
int i, j;
// If party is NULL, just return NULL.
if (party == NULL)
return NULL;
// Free each of fragments subsets if it's not NULL.
for (i = 0; i < party->num_fragments; i++)
{
if ((party->fragments[i]) != NULL)
free(party->fragments[i]);
else
free(party->fragments[i]);
}
// Then free each of the struct members themselves after having freed their subsets.
free(party->fragments);
free(party->fragment_sizes);
free(party);
printf("-> The LonelyPartyArray has returned to the void.\n");
return NULL;
}
int set(LonelyPartyArray *party, int index, int key)
{
// Variable declarations/initializations.
int num_fragments, fragment_length, printfrag, printoffset;
int i, lowindex, highindex, invalid = 0;
// Check if struct pointer is NULL, return failure.
if (party == NULL)
{
printf("-> Bloop! NULL pointer detected in set().\n");
return LPA_FAILURE;
}
// Assigning values to easier variable names.
fragment_length = party->fragment_length;
num_fragments = party->num_fragments;
printfrag = index/fragment_length;
printoffset = index%fragment_length;
// If index is considered "invalid", return failure.
if ((index < 0) || (index > (num_fragments * fragment_length - 1)))
{
invalid = 1;
// If party is not NULL and it's invalid..
if ((party != NULL) && (invalid == 1))
{
printf("-> Bloop! Invalid access in set(). ");
printf("(index: %d, fragment: %d, offset: %d)\n", index, printfrag, printoffset);
return LPA_FAILURE;
}
return LPA_FAILURE;
}
// If the specific fragment is not NULL..
if ((party->fragments[index/fragment_length]) != NULL)
{
// If the fragment has been allocated but the cell has been marked UNUSED...
if (party->fragments[index / fragment_length][index % fragment_length] == UNUSED)
{
// Insert key.
party->fragments[index / fragment_length][index % fragment_length] = key;
// Increment size and fragment_sizes members accordingly.
party->size++;
party->fragment_sizes[index / fragment_length]++;
return LPA_SUCCESS;
}
// If the cell is already in use, just increcement the count for that index.
else if (party->fragments[index / fragment_length][index % fragment_length] != UNUSED)
{
party->fragments[index / fragment_length][index % fragment_length] = key;
return LPA_SUCCESS;
}
}
// If fragment where we need to insert key is NULL, malloc that
// fragment (an array of fragment_length integers)...
// Update our number of active fragments struct member.
else
{
party->fragments[index/fragment_length] = malloc(sizeof(int) * (fragment_length));
lowindex = index - (index%fragment_length);
highindex = lowindex + (fragment_length - 1);
printf("-> Spawned fragment %d. ", index/fragment_length);
printf("(capacity: %d, indices: %d..%d)\n", fragment_length, lowindex, highindex);
party->num_active_fragments++;
// And set each cell in the fragment to UNUSED.
for (i = 0; i < fragment_length; i++)
party->fragments[index/fragment_length][i] = UNUSED;
// Set the key to the appropriate corresponding index.
party->fragments[index/fragment_length][index % fragment_length] = key;
// Increment Size member.
party->size++;
// Increment fragment_sizes member.
party->fragment_sizes[index/fragment_length]++;
return LPA_SUCCESS;
}
return LPA_FAILURE;
}
int get(LonelyPartyArray *party, int index)
{
int fraglen, numfrags;
// If party pointer is NULL, printf and return failure.
if (party == NULL)
{
printf("-> Bloop! NULL pointer detected in get().\n");
return LPA_FAILURE;
}
fraglen = party->fragment_length;
numfrags = party->num_fragments;
// If index is invalid and party pointer is not NULL, printf and return failure.
if (((index < 0) || (index > (numfrags * fraglen - 1))))
{
printf("-> Bloop! Invalid access in get(). ");
printf("(index: %d, fragment: %d, offset: %d)\n", index, index/fraglen, index%fraglen);
return LPA_FAILURE;
}
// If index refers to a cell in an unallocated fragment, return UNUSED.
if (party->fragments[index/fraglen] == NULL)
{
return UNUSED;
}
// Return value in cell where index maps to.
return party->fragments[index/fraglen][index%fraglen];
}
int delete(LonelyPartyArray *party, int index)
{
int fraglen, numfrags;
int lowindex, highindex;
// If party pointer is NULL, printf and return failure.
if (party == NULL)
{
printf("-> Bloop! NULL pointer detected in delete().\n");
return LPA_FAILURE;
}
fraglen = party->fragment_length;
numfrags = party->num_fragments;
// If index is invalid, printf and return failure.
if (((index < 0) || (index > (numfrags * fraglen - 1))))
{
printf("-> Bloop! Invalid access in delete(). ");
printf("(index: %d, fragment: %d, offset: %d)\n", index, index/fraglen, index%fraglen);
return LPA_FAILURE;
}
// If fragment being mapped to is NULL, return failure.
if (party->fragments[index/fraglen] == NULL)
return LPA_FAILURE;
// If cell being sought is not alreadys set to UNUSED..
if (party->fragments[index/fraglen][index%fraglen] != UNUSED)
{
// Set the cell to UNUSED, decrease size member, and decrease
// fragment_sizes to correct number of used cells in that fragment.
party->fragments[index/fraglen][index%fraglen] = UNUSED;
party->size--;
party->fragment_sizes[index/fraglen]--;
// If deleting the value in that cell causes that fragment to be
// empty..
if(party->fragment_sizes[index/fraglen] == 0)
{
// Deallocate that fragment, and set it to NULL.
free(party->fragments[index/fraglen]);
party->fragments[index/fraglen] = NULL;
// Update number of active fragments struct member.
party->num_active_fragments--;
// Printf appropriate variables.
lowindex = index - (index % fraglen);
highindex = lowindex + (fraglen - 1);
printf("-> Deallocated fragment %d. ", index/fraglen);
printf("(capacity: %d, indices: %d..%d)\n", fraglen, lowindex, highindex);
}
return LPA_SUCCESS;
}
// If cell is already marked as UNUSED, return failure.
if (party->fragments[index/fraglen][index%fraglen] == UNUSED)
return LPA_FAILURE;
return LPA_FAILURE;
}
int containsKey(LonelyPartyArray *party, int key)
{
int i, j;
int numfrags, fraglen;
// If party pointer is NULL, return 0.
if (party == NULL)
return 0;
numfrags = party->num_fragments;
fraglen = party->fragment_length;
// Run a for-loop through each cell of each fragment to check for key.
for (i = 0; i < numfrags; i++)
{
for (j = 0; j < fraglen; j++)
{
if (party->fragments[i][j] == key)
return 1;
}
}
// If key was not found in the above for-loop, return 0.
return 0;
}
int isSet(LonelyPartyArray *party, int index)
{
int numfrags, fraglen;
// If party pointer is NULL, return 0.
if (party == NULL)
return 0;
numfrags = party->num_fragments;
fraglen = party->fragment_length;
// If index is invalid, return 0.
if (((index < 0) || (index > (numfrags * fraglen - 1))))
return 0;
// If fragment has not been allocated yet, return 0.
if (party->fragments[index/fraglen] == NULL)
return 0;
// If cell is marked as UNUSED, return 0.
if (party->fragments[index/fraglen][index%fraglen] == UNUSED)
return 0;
// Otherwise, return 1.
return 1;
}
int printIfValid(LonelyPartyArray *party, int index)
{
int fraglen, numfrags;
// If 1) party pointer is NULL, 2) index is invalid, 3) fragment is NULL
// or 4) the cell is UNUSED, return failure.
if (party == NULL)
return LPA_FAILURE;
fraglen = party->fragment_length;
numfrags = party->num_fragments;
// If index is invalid, return failure.
if (((index < 0) || (index > (numfrags * fraglen - 1))))
return LPA_FAILURE;
// If fragment where index is mapping to is NULL, return failure.
if (party->fragments[index/fraglen] == NULL)
return LPA_FAILURE;
// If cell where index is being mapped to is UNUSED, return failure.
if (party->fragments[index/fraglen][index%fraglen] == UNUSED)
return LPA_FAILURE;
// Otherwise printf and return success.
printf("%d\n", party->fragments[index/fraglen][index%fraglen]);
return LPA_SUCCESS;
}
LonelyPartyArray *resetLonelyPartyArray(LonelyPartyArray *party)
{
int i, j;
int fraglen, numfrags;
// If struct pointer is NULL, return failure.
if (party == NULL)
{
printf("-> Bloop! NULL pointer detected in resetLonelyPartyArray().\n");
return party;
}
fraglen = party->fragment_length;
numfrags = party->num_fragments;
// Run a for-loop through each fragment and the fragment_sizes array.
for (i = 0; i < numfrags; i++)
{
// Set each one back to 0.
party->fragment_sizes[i] = 0;
// And if fragment is not NULL, and cell is not UNUSED, set it to UNUSED.
if (party->fragments[i] != NULL)
{
for (j = 0; j < fraglen; j++)
{
if (party->fragments[i][j] != UNUSED)
{
party->fragments[i][j] = UNUSED;
}
}
// Free fragment and set it to NULL.
free(party->fragments[i]);
party->fragments[i] = NULL;
}
}
// Reset rest of struct members to 0.
party->size = 0;
party->num_active_fragments = 0;
printf("-> The LonelyPartyArray has returned to its nascent state. ");
printf("(capacity: %d, fragments: %d)\n", fraglen*numfrags, numfrags);
return party;
}
int getSize(LonelyPartyArray *party)
{
// If struct pointer is NULL, return -1, otherwise return its size.
if (party == NULL)
return -1;
else
return party->size;
}
int getCapacity(LonelyPartyArray *party)
{
int numfrags, fraglen;
// If struct pointer is NULL, return -1, otherwise return its capacity.
if (party == NULL)
{
return -1;
}
else
{
numfrags = party->num_fragments;
fraglen = party->fragment_length;
return numfrags * fraglen;
}
}
int getAllocatedCellCount(LonelyPartyArray *party)
{
int fraglen, numactivefrags;
// If struct pointer is NULL, return -1, otherwise return the number of allocated cells.
if (party == NULL)
{
return -1;
}
else
{
fraglen = party->fragment_length;
numactivefrags = party->num_active_fragments;
return fraglen * numactivefrags;
}
}
long long unsigned int getArraySizeInBytes(LonelyPartyArray *party)
{
// If struct pointer is NULL, return 0, otherwise return size of a regular,
// non-dynamic array in bytes.
if (party == NULL)
return 0;
int numCells = party->num_fragments * party->fragment_length;
long long unsigned int bytes = numCells * sizeof(int);
return bytes;
}
long long unsigned int getCurrentSizeInBytes(LonelyPartyArray *party)
{
int i, j;
long long unsigned int fragsArrayPointers, fragsArrayCells, fragSizesArray, total;
// If struct pointer is NULL, return 0.
if (party == NULL)
return 0;
// Store size of an LPA pointer and an LPA struct inside variables.
long long unsigned int LPApointer = sizeof(LPA*);
long long unsigned int LPAstruct = sizeof(LPA);
// Store sizes of pointers in fragments array, size of each int cell, and size of
// each int fragment in fragment_sizes array.
fragsArrayPointers = sizeof(int*) * party->num_fragments;
fragsArrayCells = (sizeof(int) * party->fragment_length) * party->num_active_fragments;
fragSizesArray = sizeof(int) * party->num_fragments;
// Add them all up, return that value.
total = LPApointer + LPAstruct + fragsArrayPointers + fragsArrayCells + fragSizesArray;
return total;
}
double difficultyRating(void)
{
return 2.9;
}
double hoursSpent(void)
{
return 15.5;
}
//Bonus function:
LonelyPartyArray *cloneLonelyPartyArray(LonelyPartyArray *party)
{
int i, j;
// If party pointer is NULL, return NULL.
if (party == NULL)
return NULL;
// Dynamically allocate memory for a struct pointer of size num_fragments * fragment_length.
LPA *clone = malloc(sizeof(LPA*) * (party->num_fragments * party->fragment_length));
// If malloc failed, free memory and return NULL.
if (party == NULL)
{
free(clone);
return NULL;
}
// Clone the integer data type struct members.
clone->size = party->size;
clone->num_fragments = party->num_fragments;
clone->fragment_length = party->fragment_length;
clone->num_active_fragments = party->num_active_fragments;
// Dynamically allocate the fragments array of integer arrays.
clone->fragments = malloc(sizeof(int*) * (party->num_fragments));
// If call to malloc failed, free and return NULL.
if (clone->fragments == NULL)
{
free(clone->fragments);
return NULL;
}
// Go through each fragment in clone and...
for (i = 0; i < clone->num_fragments; i++)
{
// ...malloc each array of integers.
clone->fragments[i] = malloc(sizeof(int) * clone->fragment_length);
// If that fragment in the original is NULL, set the clone to NULL also, and continue.
if (party->fragments[i] == NULL)
{
clone->fragments[i] = NULL;
continue;
}
// Otherwise copy the original cell's value into the clone's cell.
else
for (j = 0; j < clone->fragment_length; j++)
{
clone->fragments[i][j] = party->fragments[i][j];
}
}
// Dynamically allocate space for the fragment_sizes array of integers.
clone->fragment_sizes = malloc(sizeof(int) * (party->num_fragments));
// If call to malloc failed, free previously allocated blocks of memory.
if (clone->fragment_sizes == NULL)
{
for (i = 0; i < clone->num_fragments; i++)
{
free(clone->fragments[i]);
}
free(clone);
free(clone->fragment_sizes);
return NULL;
}
// If malloc succeeded, copy each of the original value into clone's.
for (i = 0; i < clone->num_fragments; i++)
{
clone->fragment_sizes[i] = party->fragment_sizes[i];
}
printf("-> Successfully cloned the LonelyPartyArray. (capacity: %d, fragments: %d)\n",
clone->num_fragments * clone->fragment_length, clone->num_fragments);
return clone;
}
|
C
|
#include "holberton.h"
#include <stdio.h>
/**
* puts_half - print second half
* @str : char
* Return : nothing(mean true).
*/
void puts_half(char *str)
{
int i, z;
z = 0;
while (str[z] != '\0')
{
z++;
}
if (z % 2 == 0)
{
for (i = z / 2; str[i] != '\0' ; i++)
{
if (i < z)
_putchar(str[i]);
}
}
else
{
for (i = (z - 1 / 2); str[i] != '\0' ; i++)
{
if (i < z)
_putchar(str[i]);
}
}
_putchar('\n');
}
|
C
|
/*!
* \file
* \brief AdSwio Click example
*
* # Description
* This click provides a fully integrated single chip solution for input and output operation.
* The AD-SWIO Click contains four 13-bit DACs, one per chanal, and 16-bit Σ-∆ ADC.
* These options give a lot of flexibility in choosing functionality for analog output,
* analog input, digital input, resistance temperature detector (RTD), and thermocouple
* measurements integrated into a single chip solution with a serial peripheral interface (SPI).
*
* The demo application is composed of two sections :
*
* ## Application Init
* Performs a hardware reset of the click board and
* executes a default configuration that enables channel A and sets it to measure voltage
* input in the range from 0V to 10V, with 4800 SPS.
*
* ## Application Task
* Waits for the data ready and then reads the results of ADC conversion from channel A
* and if response is ok, then prints the results on the uart console.
*
* ## Additional Functions
*
* - void application_default_handler ( uint8_t *err_msg ) - Sends an error report messages from click
* driver to initialized console module. It must be set using adswio2_set_handler function.
*
*
* \author MikroE Team
*
*/
// ------------------------------------------------------------------- INCLUDES
#include "board.h"
#include "log.h"
#include "adswio.h"
// ------------------------------------------------------------------ VARIABLES
static adswio_t adswio;
static log_t logger;
static uint8_t adswio_rdy;
static adswio_err_t adswio_err;
static uint16_t adswio_ch_a;
static float adswio_res;
const uint16_t ADSWIO_RANGE_VOLT_MV = 10000;
const uint32_t ADSWIO_RANGE_RESOLUTION = 65536;
// ------------------------------------------------------ ADDITIONAL FUNCTIONS
void application_default_handler ( uint8_t *err_msg )
{
char *err_ptr = err_msg;
log_printf( &logger, "\r\n" );
log_printf( &logger, "[ERROR] : %s", err_ptr );
log_printf( &logger, "\r\n" );
}
// ------------------------------------------------------ APPLICATION FUNCTIONS
void application_init ( void )
{
log_cfg_t log_cfg;
adswio_cfg_t cfg;
/**
* Logger initialization.
* Default baud rate: 115200
* Default log level: LOG_LEVEL_DEBUG
* @note If USB_UART_RX and USB_UART_TX
* are defined as HAL_PIN_NC, you will
* need to define them manually for log to work.
* See @b LOG_MAP_USB_UART macro definition for detailed explanation.
*/
LOG_MAP_USB_UART( log_cfg );
log_init( &logger, &log_cfg );
log_info( &logger, "---- Application Init ----" );
// Click initialization.
adswio_cfg_setup( &cfg );
ADSWIO_MAP_MIKROBUS( cfg, MIKROBUS_1 );
adswio_init( &adswio, &cfg );
Delay_ms( 100 );
adswio_default_cfg( &adswio );
Delay_ms( 1000 );
adswio_rdy = DUMMY;
adswio_ch_a = DUMMY;
adswio_res = DUMMY;
adswio_err = ADSWIO_ERR_STATUS_OK;
log_printf( &logger, " AD-SWIO click initialization done \r\n");
log_printf( &logger, "************************************\r\n");
}
void application_task ( void )
{
uint16_t timeout = 0;
do
{
Delay_1ms( );
timeout++;
adswio_rdy = adswio_status_pin_ready( &adswio );
if ( timeout > 3000 )
{
timeout = 0;
log_printf( &logger, " Reinitializing...");
adswio_default_cfg( &adswio );
log_printf( &logger, "Done\r\n");
}
}
while ( adswio_rdy != 0 );
adswio_err = adswio_get_conv_results( &adswio, ADSWIO_SETUP_CONV_EN_CHA, &adswio_ch_a );
if ( adswio_err == ADSWIO_ERR_STATUS_OK )
{
adswio_res = adswio_ch_a;
adswio_res /= ADSWIO_RANGE_RESOLUTION;
adswio_res *= ADSWIO_RANGE_VOLT_MV;
adswio_ch_a = adswio_res;
log_printf( &logger, " Voltage from channel A: %d mV\r\n", adswio_ch_a );
log_printf( &logger, "-----------------------------------\r\n\r\n" );
Delay_ms( 200 );
}
}
void main ( void )
{
application_init( );
for ( ; ; )
{
application_task( );
}
}
// ------------------------------------------------------------------------ END
|
C
|
#include "bh.h"
struct HeapStruct
{
int Capacity; // maximum heap size
int Size; // current heap size
int *Elements; // an array of element
};
BinHeap
initializeBH(
int MaxElements)
{
BinHeap H;
H = malloc(sizeof(struct HeapStruct));
assert(H);
// Allocate the array plus one extra for sentinel
H->Elements = malloc(sizeof(int) * (MaxElements + 1));
assert(H->Elements);
H->Capacity = MaxElements;
H->Size = 0;
H->Elements[0] = INT_MIN; //Use this to break the while loop in insertion routine. Detailed see MAW p.183
return H;
}
void
destroyBinHeap(
BinHeap H)
{
free(H->Elements); // array implementation. can be directly freed
free(H);
}
// We assume the array implementation. We don't touch sentinel.
void
makeEmptyBH(
BinHeap H)
{
int i;
for(i = 1; i < H->Capacity; i++)
H->Elements[i] = 0;
H->Size = 0;
}
// H->Element[0] is a sentinel. The usage of sentinel explanation
// see MAW p.183
// percolate up strategy is contained inside the routine
void
insertBH(int X,
BinHeap H)
{
int i;
if(isFull(H))
fatal("Heap is full!");
for(i = ++H->Size; H->Elements[i/2] > X; i/=2)
H->Elements[i] = H->Elements[i/2];
H->Elements[i] = X;
}
// percolate down strategy is contained inside the routine
int
deleteMinBH(BinHeap H)
{
int i, child;
int minElement, lastElement;
if(isEmpty(H))
{
fatal("Heap is empty!");
return H->Elements[0];
}
minElement = H->Elements[1];
lastElement = H->Elements[H->Size--];
for(i = 1; i*2 <= H->Size; i = child)
{
// Find smaller child
child = i * 2;
if( child != H->Size &&
H->Elements[child + 1] < H->Elements[child])
child++;
// percolate one level
// if lastElement is smaller than the smaller child,
// then "X can be placed in the hole, then we are done." -- MAW p.183
if (lastElement > H->Elements[child])
H->Elements[i] = H->Elements[child];
else
break;
}
H->Elements[i] = lastElement;
return minElement;
}
int
findMinBH(BinHeap H)
{
return H->Elements[1];
}
int
isEmpty(BinHeap H)
{
return (H->Size == 0);
}
int
isFull(BinHeap H)
{
return (H->Size == H->Capacity);
}
// Here, we use insert to build Binary Heap
BinHeap
initializeBinHeapFromArray(
int* array,
int arrayLength)
{
int i;
BinHeap H = initializeBH(100);
for(i = 0; i < arrayLength; i++)
insertBH(array[i], H);
return H;
}
static void
bh_print_dot_aux(BinHeap H,
FILE* stream)
{
int i;
for(i=1; i*2 <= H->Size; i++)
{
fprintf(stream, "node%d [label=%d];\n", i, H->Elements[i]);
fprintf(stream, "node%d [label=%d];\n", 2*i, H->Elements[2*i]);
fprintf(stream, "node%d->node%d;\n", i, 2*i);
if (i*2 != H->Size)
{
fprintf(stream, "node%d [label=%d];\n", 2*i+1, H->Elements[2*i+1]);
fprintf(stream, "node%d->node%d;\n", i, 2*i+1);
}
}
}
void
bh_print_dot(BinHeap H,
FILE* stream)
{
fprintf(stream, "digraph BinaryHeap {\n");
bh_print_dot_aux(H, stream);
fprintf(stream, "}\n");
}
static void
percolateUp(Position pos,
BinHeap H)
{
int i;
int target = H->Elements[pos];
for(i = pos; H->Elements[i/2] > target; i/=2)
{
H->Elements[i] = H->Elements[i/2];
}
H->Elements[i] = target;
}
static void
percolateDown(Position pos,
BinHeap H)
{
int target = H->Elements[pos];
int i, child;
for(i = pos; 2*i <= H->Size; i = child)
{
child = 2*i;
if (child < H->Size && H->Elements[child] > H->Elements[child+1])
child++;
if (target > H->Elements[child])
H->Elements[i] = H->Elements[child];
else
break;
}
H->Elements[i] = target;
}
BinHeap
buildHeap(int* array,
int arrayLength)
{
BinHeap H = initializeBH(2*arrayLength);
// We first construct a complete binary tree
int i;
for(i = 1; i < arrayLength + 1; i++)
H->Elements[i] = array[i-1];
H->Size = arrayLength;
#ifdef DEBUG
printf("H->Size: %d\n", H->Size);
printArray(H->Elements, H->Size+1);
#endif
// Then we carry out figure 6.14 (p.187) to restore the
// binary heap property
for( i = H->Size / 2; i > 0; i--)
{
percolateDown(i, H);
#ifdef DEBUG
printf("After percolateDown(%d):", i);
printArray(H->Elements, H->Size+1);
#endif
}
return H;
}
void
decreaseKey(Position P,
int delta,
BinHeap H)
{
if(delta < 0)
fatal("delta cannot be negative!");
#ifdef DEBUG
printf("Value at %d: %d\n", P, retrieve(P,T));
#endif
H->Elements[P] -= delta;
percolateUp(P, H);
}
void
increaseKey(Position P,
int delta,
BinHeap H)
{
if (delta < 0)
fatal("delta cannot be negative!");
H->Elements[P] += delta;
percolateDown(P, H);
}
void
delete(Position P,
BinHeap H)
{
decreaseKey(P, INT_MAX-10, H);
deleteMinBH(H);
}
|
C
|
#include "tm1650.h"
#include "delay.h"
#include "stdbool.h"
void dtmelay(unsigned char x)
{
unsigned char i;
for(;x>0;x--) for(i=110;i>0;i--);
}
void TM16_SDA_IN(void ) //设置SDA为输入模式
{
GPIO_InitTypeDef GPIO_INIT; //设置SDA为输入模式
GPIO_INIT.GPIO_Mode = GPIO_Mode_IN; //设置成上拉输入
GPIO_INIT.GPIO_PuPd = GPIO_PuPd_UP;
GPIO_INIT.GPIO_Pin=TM16_SDA;
GPIO_INIT.GPIO_Speed=GPIO_Speed_40MHz;
GPIO_Init(TM16_PORT,&GPIO_INIT);
}
void TM16_SDA_OUT(void ) //设置SDA为输出模式
{
GPIO_InitTypeDef GPIO_INIT;
GPIO_INIT.GPIO_Mode = GPIO_Mode_OUT; //推挽输出
GPIO_INIT.GPIO_OType = GPIO_OType_PP;
GPIO_INIT.GPIO_Pin=TM16_SDA;
GPIO_INIT.GPIO_Speed=GPIO_Speed_40MHz;
GPIO_Init(TM16_PORT,&GPIO_INIT);
}
void TM16_IIC_Start(void ) //开始信号
{
TM16_SDA_H;
TM16_SCL_H;
TM16_delay(5);
TM16_SDA_L;
TM16_delay(5);
TM16_SCL_L;
}
void TM16_IIC_Stop(void ) //停止信号
{
TM16_SDA_L;
TM16_SCL_H;
TM16_delay(5);
TM16_SDA_H;
TM16_delay(5);
TM16_SCL_L;
}
bool TM16_Read_ACK(void ) //读取应答信号
{
bool ack;
TM16_SDA_IN();
TM16_SCL_H;
if(TM16_ReadSDA() == SET) ack=true;
else ack=false;
TM16_SCL_L;
TM16_delay(5);
TM16_SDA_OUT();
return ack;
}
void TM16_Send_ACK(bool ack)
{
TM16_SDA_OUT();
if(ack == true) TM16_SDA_H;
else TM16_SDA_L;
TM16_SCL_H;
TM16_delay(5);
TM16_SCL_L;
}
void TM16_Send_Byte(unsigned char byte) //发送一位数据
{
unsigned char count;
TM16_SCL_L;
for(count=0;count<8;count++)
{
if(byte & 0x80) TM16_SDA_H;
else TM16_SDA_L;
byte<<=1;
TM16_delay(2);
TM16_SCL_H;
TM16_delay(5);
TM16_SCL_L;
TM16_delay(5);
}
TM16_Read_ACK();
}
unsigned char TM16_Read_Byte(void ) //读取一位数据
{
unsigned char byte,count;
TM16_SDA_IN();
TM16_SDA_H;
for(count=0;count<8;count ++)
{
TM16_SCL_H;
byte<<=1;
if(TM16_ReadSDA() == SET) byte|=0x01;
else byte&=0xfe;
TM16_SDA_L;
TM16_delay(5);
}
TM16_SDA_IN();
return byte;
}
void TM16_Write_REG(unsigned char reg, unsigned char data) //写命令,设置
{
TM16_IIC_Start();
TM16_Send_Byte(reg);
TM16_Send_Byte(data);
TM16_IIC_Stop();
}
void TM16_Set_Brig(unsigned char BRIG) //设置数码管显示的亮度
{
unsigned char brig[]={0x11,0x21,0x31,0x41,0x51,0x61,0x71,0x01};
if((BRIG >= 0) && (BRIG <= 7)){
TM16_Write_REG(0x48,brig[BRIG]);
}
else{
TM16_Write_REG(0x48,brig[0]);
}
}
void TM16_INIT(unsigned char brig) //TM165 的初始化 brig为初始化亮度0-7
{
GPIO_InitTypeDef GPIO_INIT;
RCC_AHBPeriphClockCmd(RCC_AHBPeriph_GPIOB ,ENABLE);
GPIO_INIT.GPIO_Mode = GPIO_Mode_OUT; //推挽输出
GPIO_INIT.GPIO_OType = GPIO_OType_PP;
GPIO_INIT.GPIO_Pin=TM16_SDA | TM16_SCL;
GPIO_INIT.GPIO_Speed=GPIO_Speed_40MHz;
GPIO_Init(TM16_PORT,&GPIO_INIT);
delay_ms(200);
TM16_Set_Brig(brig);
}
//显示函数,data为显示的数据,0-99,di设置是否显示小数点,0为都不显示小数点,1为第一位显示小数点,2为第二位显示小数点,3为第一位和第二位都显示小数点
void TM16_Display(unsigned int data,unsigned char di)
{
static unsigned char TM16_Display_buf[10]={0x3F,0x6,0x5B,0x4F,0x66,0x6D,0x7D,0x7,0x7F,0x6F};
unsigned int bit1,bit2,bit3,bit4;
bit1 = data / 1000;
bit2 = (data - bit1 * 1000) / 100;
bit3 = (data - bit1 * 1000 - bit2 * 100) / 10;
bit4 = (data - bit1 * 1000 - bit2 * 100 - bit3 * 10) % 10;
TM16_Write_REG(0x68,TM16_Display_buf[bit1]);
TM16_Write_REG(0x6a,TM16_Display_buf[bit2]);
TM16_Write_REG(0x6c,TM16_Display_buf[bit3]);
TM16_Write_REG(0x6e,TM16_Display_buf[bit4]);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#define LENGTH 32
int count_num(int value)
{
int count = 0;
while(value>0)
{
value /= 10;
count ++;
}
return count;
}
int main(int argc, char *argv[])
{
char *str = argv[0];
int a,b,c,x,z;
int max;
int i,j,k;
int res;
int num=5;
if (argv[1])
num = atoi(argv[1]);
for(i=1; i<=num; i++)
{
for(j=1; j<=num; j++)
{
max = num*num;
z = count_num(max);
x = count_num(num);
a = count_num(i);
for(a; (x-a)+1>0; a++)
{
printf(" ");
}
printf("%d X", i);
b=count_num(j);
for(b; (x-b)+1>0; b++)
{
printf(" ");
}
printf("%d =", j);
res = i*j;
c=count_num(res);
for(c; (z-c)+1>0; c++)
{
printf(" ");
}
printf("%d\n", res);
}
}
}
|
C
|
#ifndef BITMAPFONT_H
#define BITMAPFONT_H
#include <stdbool.h>
#include <SDL.h>
/*
* The bitmapfont contains information for rendering a char* on an SDL_Renderer.
* A bitmapfont is initialized using an image, where each glyph is separated by
* a 'separation color'. The separation color is the first pixel read in the
* image, in the top-left corner.
*/
struct bitmapfont {
SDL_Renderer* renderer; // Used to create a texture from a surface.
SDL_Surface* surface; // Image file to surface. Used to read pixels.
char* glyphs; // The characters.
size_t glyphs_len; // Amount of glyphs.
SDL_Rect** rects; // The individual rectangles per glyph.
SDL_Texture* texture; // The texture containing the glyphs image.
};
/*
* Initialize the bitmapfont pointed at by `bmf'. The renderer is used to
* create a texture from the surface. The `path' is the file to the font
* texture, and the `glyphs'
*
* TODO: document the way the glyphs and the font image works together.
*/
struct bitmapfont* bitmapfont_create(SDL_Renderer* r, const char* path, const char* glyphs);
/*
* Frees resources.
*/
void bitmapfont_free(struct bitmapfont* bmf);
/*
* Renders the given `txt' at the position x, y on the `renderer' of the bitmapfont.
*/
void bitmapfont_render(struct bitmapfont* bmf, int x, int y, const char* txt);
/*
* This function will render the formatted string to the renderer at starting
* position (x, y). It will be slightly slower than bitmapfont_render since it
* will use `vsnprintf' twice (once for knowing the size of the string, once
* for actually formatting it to the target char*).
*/
void bitmapfont_renderf(struct bitmapfont* bmf, int x, int y, const char* fmt, ...);
#endif // BITMAPFONT_H
|
C
|
/*
* File: proj1.c
* Author: Diogo Dinis (99066)
* Description: IAED 1st Project - 2021
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/* --General defines-- */
/* Defines the max. size of a task description */
#define TASK_DESCR_SIZE 50
/* Defines the max. number of tasks */
#define MAX_TASKS 10000
/* Defines the max. size of an activity name */
#define ACTIVITY_SIZE 20
/* Defines the max. number of activities */
#define MAX_ACTIVITIES 10
/* Defines the starting activity */
#define DEFAULT_ACTIVITY "TO DO"
/* Defines the ending activity */
#define FINAL_ACTIVITY "DONE"
/* Defines the initial time */
#define INIT_TIME 0
/* Defines the max. number of users */
#define MAX_USERS 50
/* Defines the max. size of an user name */
#define USER_SIZE 20
/* Value to choose sorting by time */
#define SORT_TYPE_TIME 0
/* Value to choose sorting by description */
#define SORT_TYPE_DESC 1
/* --String defines (Valid)-- */
#define VALID_TASK "task %d\n"
#define LIST_TASK "%d %s #%d %s\n"
#define PRINT_TIME "%d\n"
#define LIST_STRING "%s\n"
#define VALID_TODO "duration=%d slack=%d\n"
#define VALID_LIST_ACT "%d %d %s\n"
/* --String defines (Errors - General)-- */
#define ERROR_INV_TIME "invalid time\n"
#define ERROR_INV_DUR "invalid duration\n"
#define ERROR_INV_DESC "invalid description\n"
#define ERROR_TASK_AS "task already started\n"
/* --String defines (Errors - Item not found)-- */
#define ERROR_NO_TASK "%d: no such task\n"
#define ERROR_NO_TASK_S "no such task\n"
#define ERROR_NO_USER "no such user\n"
#define ERROR_NO_ACTIVITY "no such activity\n"
/* --String defines (Errors - Duplicated Item)-- */
#define ERROR_DUP_DESC "duplicate description\n"
#define ERROR_DUP_ACT "duplicate activity\n"
#define ERROR_USER_AE "user already exists\n"
/* --String defines (Errors - Size Limit)-- */
#define ERROR_TM_TASK "too many tasks\n"
#define ERROR_TM_USERS "too many users\n"
#define ERROR_TM_ACT "too many activities\n"
/* --Sorting Macros-- */
#define key(A) (A)
#define less(A, B) (key(A) < key(B))
/* Initializes global time */
int time = INIT_TIME;
/* Initializes counting of tasks, users and activities */
int nr_tasks = 0, nr_users = 0, nr_activities = 3;
/* Initializes list of activities and users */
char activities[MAX_ACTIVITIES + 1]
[ACTIVITY_SIZE + 1] = {"TO DO", "IN PROGRESS", "DONE"},
users[MAX_USERS + 1][USER_SIZE + 1];
/* Defines the Task struct */
typedef struct Task {
int identifier;
char description[TASK_DESCR_SIZE + 1];
char user[USER_SIZE + 1];
char activity[ACTIVITY_SIZE];
int e_duration;
int t_beginning;
} Task;
/* Initializes list of tasks*/
Task tasks[MAX_TASKS + 1];
/* Initializes auxiliary task and list of tasks */
Task current;
Task aux[MAX_TASKS + 1];
/* Auxiliary function of merge-sort (sort according task time) */
void merge_time(Task a[], int l, int m, int r) {
int i, j, k;
/* Fills auxiliary list */
for (i = m + 1; i > l; i--)
aux[i - 1] = a[i - 1];
for (j = m; j < r; j++)
aux[r + m - j] = a[j + 1];
/* Add sorted elements to destination list */
for (k = l; k <= r; k++)
/* Adds stability to the sorting when t_beggining is the same */
if (i > m)
a[k] = aux[j--];
else if (aux[j].t_beginning < aux[i].t_beginning)
a[k] = aux[j--];
else
a[k] = aux[i++];
}
/* Auxiliary function of merge-sort (sort according task description) */
void merge_desc(Task a[], int l, int m, int r) {
int i, j, k;
/* Fills auxiliary list */
for (i = m + 1; i > l; i--)
aux[i - 1] = a[i - 1];
for (j = m; j < r; j++)
aux[r + m - j] = a[j + 1];
/* Add sorted elements to destination list */
for (k = l; k <= r; k++)
if (strcmp(aux[j].description, aux[i].description) < 0)
a[k] = aux[j--];
else
a[k] = aux[i++];
}
/* Main function of merge-sort */
void sort(Task a[], int l, int r, int type) {
/* Chooses the point where to split */
int m = (r + l) / 2;
if (l >= r)
return;
/* Splits list */
sort(a, l, m, type);
sort(a, m + 1, r, type);
/* Chooses whether to sort by description or beggining time */
if (type == SORT_TYPE_TIME)
merge_time(a, l, m, r);
else
merge_desc(a, l, m, r);
}
/* Function to add task from stdin input */
void add_task() {
int i;
scanf(" %d ", ¤t.e_duration);
fgets(current.description, TASK_DESCR_SIZE + 1, stdin);
current.description[strcspn(current.description, "\n")] = 0;
/* Checks if limit not exceeded */
if (nr_tasks == MAX_TASKS) {
printf(ERROR_TM_TASK);
return;
}
/* Checks if task already exists */
for (i = 0; i < nr_tasks; i++) {
if (strcmp(tasks[i].description, current.description) == 0) {
printf(ERROR_DUP_DESC);
return;
}
}
if (current.e_duration <= 0) {
printf(ERROR_INV_DUR);
return;
}
strcpy(current.activity, DEFAULT_ACTIVITY);
current.identifier = nr_tasks + 1;
tasks[nr_tasks] = current;
nr_tasks++;
printf(VALID_TASK, current.identifier);
}
/* List specific task or all of them depending on input*/
void list_tasks() {
int i, id = 0, found;
char ch;
if ((ch = getchar()) == ' ') {
while (scanf(" %d", &id)) {
/* List task(s) given by the input or error if it doesnt exist */
for (i = 0; i < nr_tasks; i++) {
found = 0;
if (tasks[i].identifier == id) {
printf(LIST_TASK, tasks[i].identifier, tasks[i].activity,
tasks[i].e_duration, tasks[i].description);
found++;
break;
}
}
if (!found)
printf(ERROR_NO_TASK, id);
}
} else {
/* List all tasks sorted by description */
sort(tasks, 0, nr_tasks - 1, SORT_TYPE_DESC);
for (i = 0; i < nr_tasks; i++) {
current = tasks[i];
printf(LIST_TASK, current.identifier, current.activity,
current.e_duration, current.description);
}
}
}
/* Shows or advances time depending on the input */
void step_forward() {
int dur = 0;
char end;
/* Verifies if input is valid and adds time */
if (scanf("%d%c", &dur, &end) == 2 && end == '\n' && dur >= 0) {
time += dur;
printf(PRINT_TIME, time);
} else {
printf(ERROR_INV_TIME);
}
}
/* List all users */
void list_users() {
int i = 0;
for (i = 0; i < nr_users; i++) {
printf(LIST_STRING, users[i]);
}
}
/* Adds an user given from the input */
void add_user() {
char user[USER_SIZE + 1];
int i;
if (getchar() == ' ') {
fscanf(stdin, "%s", user);
/* If user doesn't exists and max users not exceeded, add it */
for (i = 0; i < nr_users; i++) {
if (!strcmp(user, users[i])) {
printf(ERROR_USER_AE);
return;
}
}
if (nr_users == MAX_USERS) {
printf(ERROR_TM_USERS);
return;
}
strcpy(users[nr_users], user);
nr_users++;
} else {
list_users();
}
}
/* Verifies for impediments to moving tasks */
int mv_task_ver(char activity[], char user[], int *id, int *act) {
int i;
/* Verifies task existence */
for (i = 0; i <= nr_tasks; i++) {
if (i == nr_tasks) {
printf(ERROR_NO_TASK_S);
return 1;
}
if (*id == tasks[i].identifier) {
*act = i;
break;
}
}
/* Verifies if task already started*/
if (!strcmp(activity, DEFAULT_ACTIVITY)) {
if (strcmp(tasks[*act].activity, DEFAULT_ACTIVITY))
printf(ERROR_TASK_AS);
return 1;
}
/* Verifies user existence */
for (i = 0; i <= nr_users; i++) {
if (i == nr_users) {
printf(ERROR_NO_USER);
return 1;
}
if (!strcmp(user, users[i]))
break;
}
/* Verifies if activity exists */
for (i = 0; i <= nr_activities; i++) {
if (i == nr_activities) {
printf(ERROR_NO_ACTIVITY);
return 1;
}
if (!strcmp(activity, activities[i]))
break;
}
return 0;
}
/* Moves task from current activity to one given by the input */
void move_task() {
int id, act = 0, duration, slack;
char user[USER_SIZE + 1], activity[ACTIVITY_SIZE + 1];
/* Get input */
scanf("%d %s ", &id, user);
fgets(activity, ACTIVITY_SIZE + 1, stdin);
if (activity[strlen(activity) - 1] == '\n') {
activity[strlen(activity) - 1] = '\0';
}
/* Check for errors*/
if (mv_task_ver(activity, user, &id, &act)) {
return;
}
/* Update task beggining time*/
if (!strcmp(tasks[act].activity, DEFAULT_ACTIVITY)) {
tasks[act].t_beginning = time;
}
/* Update task user*/
strcpy(tasks[act].user, user);
/* If task is moved to the Final activity, print duration info*/
if (!strcmp(activity, FINAL_ACTIVITY) &&
strcmp(tasks[act].activity, FINAL_ACTIVITY)) {
duration = time - tasks[act].t_beginning;
slack = duration - tasks[act].e_duration;
printf(VALID_TODO, duration, slack);
}
strcpy(tasks[act].activity, activity);
}
/* Verifies for impediments to list tasks of a given activity */
int ls_act_ver(char activity[]) {
int i;
/* Verifies if the given activity exists */
for (i = 0; i < nr_activities; i++) {
if (!strcmp(activity, activities[i])) {
return 0;
}
}
printf(ERROR_NO_ACTIVITY);
return 1;
}
/* List all the tasks that are on a certain activity given by the input */
void list_act() {
int i = 0, count = 0;
char activity[ACTIVITY_SIZE + 1];
Task list[MAX_TASKS + 1];
/* Get input */
getchar();
fgets(activity, ACTIVITY_SIZE + 1, stdin);
activity[strlen(activity) - 1] = '\0';
/* Check errors */
if (ls_act_ver(activity))
return;
/* Filters tasks to a given activity */
for (i = 0; i < nr_tasks; i++) {
if (!strcmp(tasks[i].activity, activity)) {
list[count] = tasks[i];
count++;
}
}
/* Sorts the output by beggining time and then by description */
sort(list, 0, count - 1, SORT_TYPE_DESC);
sort(list, 0, count - 1, SORT_TYPE_TIME);
for (i = 0; i < count; i++) {
printf(VALID_LIST_ACT, list[i].identifier, list[i].t_beginning,
list[i].description);
}
}
/* Verifies for impediments to add an activity */
int add_act_ver(char activity[]) {
int i, size = strlen(activity);
/* Searches for invalid characters */
for (i = 0; i < size; i++) {
if (activity[i] >= 'a' && activity[i] <= 'z') {
printf(ERROR_INV_DESC);
return 1;
}
}
/* Corrects the last character */
if (activity[size - 1] == '\n') {
activity[size - 1] = '\0';
}
/* Verifies if the activity already exists */
for (i = 0; i < nr_activities; i++) {
if (!strcmp(activity, activities[i])) {
printf(ERROR_DUP_ACT);
return 1;
}
}
return 0;
}
/* Adds an activity from the input */
void add_activ() {
int i;
char activity[ACTIVITY_SIZE + 1];
if (getchar() == ' ') {
fgets(activity, ACTIVITY_SIZE + 1, stdin);
if (nr_activities == MAX_ACTIVITIES) {
printf(ERROR_TM_ACT);
return;
}
if (add_act_ver(activity)) {
return;
}
strcpy(activities[nr_activities], activity);
nr_activities++;
return;
}
for (i = 0; i < nr_activities; i++) {
printf(LIST_STRING, activities[i]);
}
}
/* Reads the option character from stdin and launches the function associated */
int main() {
char option;
while (1) {
option = getchar();
switch (option) {
case 'q':
return 0;
case 't':
add_task();
break;
case 'l':
list_tasks();
break;
case 'n':
step_forward();
break;
case 'u':
add_user();
break;
case 'm':
move_task();
break;
case 'd':
list_act();
break;
case 'a':
add_activ();
break;
}
}
return 0;
}
|
C
|
#include "structs.h"
#include "c.h"
int dirID = 0;
int fileID = 0;
void list(Node* Ierarchy) { //recursive function that creates the hierachy
DIR *directory, *tempDirectory;
char newname[49];
struct dirent *dir;
if ((directory = opendir(Ierarchy->name)) == NULL) { //tries to open the node's name
return;
}
while ((dir = readdir(directory)) != NULL) { //if the name is a directory, open the directory
if (dir->d_ino == 0) continue;
if (strcmp(dir->d_name, ".") == 0) continue; //ignore current directory
if (strcmp(dir->d_name, "..") == 0) continue; //ignore parent directory
strcpy(newname, Ierarchy->name); //create the full path of the new element found in the directory
strcat(newname, "/");
strcat(newname, dir->d_name);
if ((tempDirectory = opendir(newname)) == NULL) { //if by trying to open the new element you get NULL
fileID++;
Files* newFile = malloc(sizeof(Files)); //it is a file, create a file node
strcpy(newFile->filename, newname);
newFile->level = Ierarchy->level + 1; //append it to the visited directory's list of files
newFile->parent = Ierarchy->dirID;
newFile->TreeID = Ierarchy->TreeID;
newFile->next = NULL;
if (Ierarchy->files == NULL) {
Ierarchy->files = newFile;
}
else {
Files* tempFile = Ierarchy->files;
while (tempFile->next != NULL) {
tempFile = tempFile->next;
}
tempFile->next = newFile;
}
}
else { //else if by trying to open the new element you find a directory
Node* newNode = malloc(sizeof(Node)); //append it to the general list of directories
dirID++;
strcpy(newNode->name, newname);
newNode->level = Ierarchy->level + 1;
newNode->TreeID = Ierarchy->TreeID;
newNode->dirID = dirID;
newNode->isDir = 1;
newNode->parent = Ierarchy->dirID;
Node* temp = Ierarchy;
while (temp->next != NULL) {
temp = temp->next;
}
newNode->prev = temp;
newNode->next = NULL;
newNode->dirs = NULL;
newNode->files = NULL;
temp->next = newNode;
Dirs* newDir = malloc(sizeof(Dirs)); //and append it to the list of directories of the current
strcpy(newDir->dirname, newname); //directory we are working on
newDir->level = newNode->level;
newDir->parent = Ierarchy->dirID;
newDir->TreeID = Ierarchy->TreeID;
newDir->next = NULL;
if (Ierarchy->dirs == NULL) {
Ierarchy->dirs = newDir;
}
else {
Dirs* tempDir = Ierarchy->dirs;
while (tempDir->next != NULL) {
tempDir = tempDir->next;
}
tempDir->next = newDir;
}
list(newNode); //and since you found a directory, visit the new directory
} //and do the same things, open, get its files and directories, append them etc.
}
closedir(directory);
}
Dirs* listDirectories(int* DirsCount, int numOfFiles, Node* Ierarchy) {
//gets every directory from the hierarchy and creates a simply linked list
Dirs* Directories = NULL;
int i, j;
for (i = 0; i < numOfFiles; ++i) {
int currDirs = DirsCount[i];
Node* temp = &Ierarchy[i];
for (j = 0; j < currDirs; ++j) {
Dirs* tempDir = malloc(sizeof(Dirs));
strcpy(tempDir->dirname, temp->name);
tempDir->level = temp->level;
tempDir->parent = temp->parent;
tempDir->TreeID = temp->TreeID;
tempDir->next = NULL;
if (Directories == NULL) {
Directories = tempDir;
}
else {
Dirs* tempDir2 = Directories;
while (tempDir2->next != NULL) {
tempDir2 = tempDir2->next;
}
tempDir2->next = tempDir;
}
temp = temp->next;
}
}
return Directories;
}
Files* listFiles(int* FilesCount, int* DirsCount, int numOfFiles, Node* Ierarchy) {
//gets every file from the hierarchy and creates a simply linked list
Files* FilesList = NULL;
int i, j;
for (i = 0; i < numOfFiles; ++i) {
int currFiles = FilesCount[i];
int currDirs = DirsCount[i];
Node* temp = &Ierarchy[i];
for (j = 0; j < currDirs; ++j) {
if (temp->files != NULL) {
Files* tempFile = temp->files;
while (tempFile != NULL) {
Files* toADD = malloc(sizeof(Files));
strcpy(toADD->filename, tempFile->filename);
toADD->level = tempFile->level;
toADD->parent = tempFile->parent;
toADD->TreeID = tempFile->TreeID;
toADD->next = NULL;
if (FilesList == NULL) {
FilesList = toADD;
}
else {
Files* tempFile2 = FilesList;
while (tempFile2->next != NULL) {
tempFile2 = tempFile2->next;
}
tempFile2->next = toADD;
}
tempFile = tempFile->next;
}
}
temp = temp->next;
}
}
return FilesList;
}
void createDirsMetadata(Dirs* Directories) {
//strcpy to a buffer the access rights of each directory and pass it to the list
struct stat statbuf;
struct group *grp;
struct passwd *pwd;
Dirs* tempDirs = Directories;
while (tempDirs != NULL) {
if (stat(tempDirs->dirname, &statbuf) != -1) {
char accessRights[10];
if (S_ISDIR(statbuf.st_mode)) accessRights[0] = 'd'; else accessRights[0] = '-';
if (statbuf.st_mode & S_IRUSR) accessRights[1] = 'r'; else accessRights[1] = '-';
if (statbuf.st_mode & S_IWUSR) accessRights[2] = 'w'; else accessRights[2] = '-';
if (statbuf.st_mode & S_IXUSR) accessRights[3] = 'x'; else accessRights[3] = '-';
if (statbuf.st_mode & S_IRGRP) accessRights[4] = 'r'; else accessRights[4] = '-';
if (statbuf.st_mode & S_IWGRP) accessRights[5] = 'w'; else accessRights[5] = '-';
if (statbuf.st_mode & S_IXGRP) accessRights[6] = 'x'; else accessRights[6] = '-';
if (statbuf.st_mode & S_IROTH) accessRights[7] = 'r'; else accessRights[7] = '-';
if (statbuf.st_mode & S_IWOTH) accessRights[8] = 'w'; else accessRights[8] = '-';
if (statbuf.st_mode & S_IXOTH) accessRights[9] = 'x'; else accessRights[9] = '-';
strcpy(tempDirs->accessRights, accessRights);
tempDirs->size = statbuf.st_size;
}
tempDirs = tempDirs->next;
}
return;
}
void createFileMetadata(Files* FilesList) {
//strcpy to a buffer the access rights of each file and pass it to the list
struct stat statbuf;
struct group *grp;
struct passwd *pwd;
Files* tempFiles = FilesList;
while (tempFiles != NULL) {
if (stat(tempFiles->filename, &statbuf) != -1) {
char accessRights[10];
if (S_ISDIR(statbuf.st_mode)) accessRights[0] = 'd'; else accessRights[0] = '-';
if (statbuf.st_mode & S_IRUSR) accessRights[1] = 'r'; else accessRights[1] = '-';
if (statbuf.st_mode & S_IWUSR) accessRights[2] = 'w'; else accessRights[2] = '-';
if (statbuf.st_mode & S_IXUSR) accessRights[3] = 'x'; else accessRights[3] = '-';
if (statbuf.st_mode & S_IRGRP) accessRights[4] = 'r'; else accessRights[4] = '-';
if (statbuf.st_mode & S_IWGRP) accessRights[5] = 'w'; else accessRights[5] = '-';
if (statbuf.st_mode & S_IXGRP) accessRights[6] = 'x'; else accessRights[6] = '-';
if (statbuf.st_mode & S_IROTH) accessRights[7] = 'r'; else accessRights[7] = '-';
if (statbuf.st_mode & S_IWOTH) accessRights[8] = 'w'; else accessRights[8] = '-';
if (statbuf.st_mode & S_IXOTH) accessRights[9] = 'x'; else accessRights[9] = '-';
strcpy(tempFiles->accessRights, accessRights);
tempFiles->size = statbuf.st_size;
}
tempFiles = tempFiles->next;
}
return;
}
void writeMetadata(FILE* fileOutDesc, Dirs* Directories, Files* FilesList, BlockStats* BS, int zip) {
int sizeOfFiles = sizeof(Files);
int sizeOfDirs = sizeof(Dirs);
int sizeofBS = sizeof(BlockStats);
int totalSize = sizeofBS + sizeOfFiles*(BS->numOfFiles) + sizeOfDirs*(BS->numOfDirs);
int blocksToAlloc = totalSize/BLOCK_SIZE;
if (totalSize%BLOCK_SIZE) {
blocksToAlloc++;
}
BS->numOfBlocks = blocksToAlloc;
Dirs* tempDirsB = Directories;
Files* tempFilesB = FilesList;
int counter = sizeofBS;
int i, endFlag = 0, endFlag2 = 0;
void *blockPtr = calloc(BLOCK_SIZE, sizeof(char));
memcpy(blockPtr, BS, sizeof(BlockStats));
fwrite(blockPtr, sizeof(BlockStats), 1, fileOutDesc);
blockPtr += sizeof(BlockStats);
for (i = 0; i < blocksToAlloc; ++i) {
while ((counter + sizeOfDirs) <= BLOCK_SIZE) {
if (endFlag && endFlag2) break;
if (endFlag != 1) {
tempDirsB->numOfBlocks = 1;
memcpy(blockPtr, tempDirsB, sizeof(Dirs));
fwrite(blockPtr, 1, sizeof(Dirs), fileOutDesc);
blockPtr += sizeof(Dirs);
tempDirsB = tempDirsB->next;
if (tempDirsB == NULL) {
endFlag = 1;
}
counter += sizeOfDirs;
}
else {
int blocksNum = (tempFilesB->size)/BLOCK_SIZE;
if ((tempFilesB->size)%BLOCK_SIZE) blocksNum++;
tempFilesB->numOfBlocks = blocksNum;
//if (zip) {
// if (strstr(tempFilesB->filename, ".tar") != NULL) {
// memcpy(blockPtr, tempFilesB, sizeof(Files));
// fwrite(blockPtr, 1, sizeof(Files), fileOutDesc);
// blockPtr += sizeof(Files);
// }
//}
//else {
memcpy(blockPtr, tempFilesB, sizeof(Files));
fwrite(blockPtr, 1, sizeof(Files), fileOutDesc);
blockPtr += sizeof(Files);
//}
tempFilesB = tempFilesB->next;
if (tempFilesB == NULL) {
endFlag2 = 1;
}
counter += sizeOfFiles;
}
}
blockPtr -= counter;
counter = 0;
}
printf("Done with the metadata.\n");
tempFilesB = FilesList;
char fname[49];
FILE* fileInDesc;
while (tempFilesB != NULL) {
strcpy(fname, tempFilesB->filename);
if ((fileInDesc = fopen(fname, "r")) == NULL) {
perror("Open original file");
}
fseek(fileInDesc, 0, SEEK_END);
int numBytes = ftell(fileInDesc);
rewind(fileInDesc);
int blocksNum = numBytes / BLOCK_SIZE;
if (numBytes%BLOCK_SIZE) {
blocksNum++;
}
void *blockPtr = malloc(BLOCK_SIZE);
for (i = 0; i < (blocksNum - 1); ++i) {
int size = fread(blockPtr, 1, BLOCK_SIZE, fileInDesc);
fwrite(blockPtr, 1, size, fileOutDesc);
}
char ch = '0';
if (numBytes%BLOCK_SIZE) {
int size = fread(blockPtr, 1, (numBytes%BLOCK_SIZE) + 1, fileInDesc);
int zero_bytes = BLOCK_SIZE - size;
fwrite(blockPtr, 1, size, fileOutDesc);
for (i = 0; i < zero_bytes; ++i) {
size = fwrite(&ch, sizeof(char), 1, fileOutDesc);
if (size == -1) perror("write");
}
}
fclose(fileInDesc);
tempFilesB = tempFilesB->next;
}
printf("Done with the files.\n");
}
|
C
|
#include "eServicios.h"
#include "input.h"
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
int servicio_searchIndexById(eServicio* unServicio, int size, int id)
{
int rtn = -1;
int i;
for (i=0; i<size; i++)
{
if (unServicio[i].id == id)
{
rtn = i;
}
}
return rtn;
}
void servicio_listarServicios(eServicio* listaServicios, int size)
{
int i;
printf ("idServicio Descripcion Precio \n");
for (i=0; i<size; i++)
{
servicio_mostrarUnServicio(listaServicios, i);
}
}
void servicio_mostrarUnServicio (eServicio* unServicio, int index)
{
printf ("%d %s %f\n", unServicio[index].id, unServicio[index].descripcion, unServicio[index].precio);
}
int servicio_getIdServicio(eServicio* listaServicios, int size3)
{
int rtn = -1;
int idServicio;
int flagError = 0;
int i;
while (flagError <= 3)
{
Get_Int("ingrese un id de servicio de la lista:\n", "ERROR. el id debe ser numerico. ingrese un id de servicio de la lista:\n", &idServicio);
for(i=0; i<size3; i++)
{
if (idServicio == listaServicios[i].id)
{
flagError = 3;
rtn = idServicio;
break;
}
}
flagError++;
}
return rtn;
}
int servicio_validarId(eServicio* unServicio, int size, int auxId)
{
int rtn = 0;
int i;
for (i=0; i<size; i++)
{
if (unServicio[i].id == auxId)
{
rtn = auxId;
break;
}
}
return rtn;
}
void auxServicio_inicializarEstructuraAuxiliar(eServicio* unServicio, int size, eAuxServicio* auxServicio, int size2)
{
int i;
for (i=0; i<size; i++)
{
auxServicio[i].id = unServicio[i].id;
strcpy (auxServicio[i].descripcion, unServicio[i].descripcion);
auxServicio[i].precio = unServicio[i].precio;
auxServicio[i].contadorTrabajos = 0;
}
}
void auxServicio_mostrarMayorContadorServicios(eAuxServicio* auxListaServicios, int size3)
{
int i;
int mayorContador = 0;
for (i=0; i<size3; i++)
{
if (i==0 || auxListaServicios[i].contadorTrabajos > mayorContador)
{
mayorContador = auxListaServicios[i].contadorTrabajos;
}
}
printf("El/Los servicios mas realizados es/son:\n");
for (i=0; i<size3; i++)
{
if (auxListaServicios[i].contadorTrabajos == mayorContador)
{
printf("-%s: %d\n", auxListaServicios[i].descripcion, auxListaServicios[i].contadorTrabajos);
}
}
}
|
C
|
/*
ȭ Է¹ Ͽ ϴ ۾
*/
#include <stdio.h>
#pragma warning(disable:4996)
int main() {
char name[7];
int grade;
char major[7];
//step1. ü
FILE* fp;
fp = fopen("c:\\Sample\\studnet.txt","wt");
for (int i = 0; i < 3; i++) {
printf("̸ г а Է : ");
scanf("%s %d %s", name, &grade, major);
getchar();
fprintf(fp, "%s %d %s\n", name, grade, major);
}
fclose(fp);
return 0;
}
|
C
|
// Contains auxiliary functions like template-matching, and other calculation functions
#include <stdlib.h>
#include <gtk/gtk.h>
#include <math.h>
// Defining keyboard grouping
// The number definitions vary depending how difficult the keys are to reach from one another
// NEEDS CHANGE --- TOP PRIORITY
#define TOP1 1000
#define TOP2 1008
#define TOP3 1002
#define MIDA1 1001
#define MIDA2 1010
#define MIDA3 1007
#define MIDB1 1003
#define MIDB2 1012
#define MIDB3 1004
#define BOT1 1005
#define BOT2 1006
#define NONE 9999
int distance_map(char key1, char key2);
struct __input { // Clone of the structure 'input' in functions.h
char type[10];
char key;
guint time;
int shift;
int caps;
} *LRIT_in;
double calculate_GF(FILE *file) // Calculates Grouping Factor time for a particular entry,
{ // whether username, password or large text entry. NOTE: Will work on a raw input file, i.e. file containing raw keystroke data
// NOTE:
// Grouping Factor(G.F.) is defined as:
// G.F. = (CrossGroup Distance) * (Interkey Time) / Count
//
// where CrossGroup Distance =
// InterKey Time =
// Count =
int i, j, k = line_count(file);
char dummy[110];
double sum = 0;
int count = 0;
LRIT_in = calloc(k, sizeof(struct __input));
fscanf(file, "%s %s", dummy, dummy);
for(i=0;i<k;i++)
fscanf(file, "%s %c %d %d %d", LRIT_in[i].type, &LRIT_in[i].key, &LRIT_in[i].time, &LRIT_in[i].shift, &LRIT_in[i].caps);
for(i=0;i<k;i++)
if(strcmp(LRIT_in[i].type, "press")==0)
{
for(j=i+1;j<k;j++)
if(strcmp(LRIT_in[j].type, "press")==0)
break;
int d = distance_map(LRIT_in[i].key, LRIT_in[j].key);
if(d != -1) {
sum = sum + (double)d*(LRIT_in[j].time - LRIT_in[i].time);
count++;
}
}
free(LRIT_in);
return (sum/(double)count);
}
int group(char key)
{
if(key >= '1' && key <= '4') return TOP1;
else if(key >= '5' && key <= '7') return TOP2;
else if(key == '0' || key=='8' || key=='9' || key=='_') return TOP3;
else if(
key == 'q' || key == 'Q' ||
key == 'w' || key == 'W' ||
key == 'e' || key == 'E'
) return MIDA1;
else if(
key == 'r' || key == 'R' ||
key == 't' || key == 'T' ||
key == 'y' || key == 'Y'
) return MIDA2;
else if(
key == 'u' || key == 'U' ||
key == 'i' || key == 'I' ||
key == 'o' || key == 'O' ||
key == 'p' || key == 'P'
) return MIDA3;
else if(
key == 'a' || key == 'A' ||
key == 's' || key == 'S' ||
key == 'd' || key == 'D'
) return MIDB1;
else if(
key == 'f' || key == 'F' ||
key == 'g' || key == 'G' ||
key == 'h' || key == 'H'
) return MIDB2;
else if(
key == 'j' || key == 'J' ||
key == 'k' || key == 'K' ||
key == 'l' || key == 'L'
) return MIDB3;
else if(
key == 'z' || key == 'Z' ||
key == 'x' || key == 'X' ||
key == 'c' || key == 'C' ||
key == 'v' || key == 'V'
) return BOT1;
else if(
key == 'b' || key == 'B' ||
key == 'n' || key == 'N' ||
key == 'm' || key == 'M'
) return BOT2;
else return NONE;
}
int distance_map(char key1, char key2)
{
int g1, g2;
g1 = group(key1);
g2 = group(key2);
if(g1!=NONE && g2!=NONE)
return((int)fabs(g1-g2));
else return (-1);
}
int line_count(FILE *f)
{//printf("in count\n");
rewind(f);
char buf[100];
int count = 0;
while(fgets(buf, 100, f) != NULL)
count++;
rewind(f);
// printf("count = %d\n", count);
return count;
}
double SD(FILE *file)
{
int i, j, k = line_count(file);
char dummy[110];
LRIT_in = calloc(k, sizeof(struct __input));
fscanf(file, "%s %s", dummy, dummy);
for(i=0;i<k;i++)
fscanf(file, "%s %c %d %d %d", LRIT_in[i].type, &LRIT_in[i].key, &LRIT_in[i].time, &LRIT_in[i].shift, &LRIT_in[i].caps);
// Write Code
}
|
C
|
#include <stdio.h>
#include <string.h>
char s[1000][200];
int main(){
while(1){
int n; scanf("%d", &n);
if ( !n ) break;
getchar();
memset(s, 0, sizeof(s));
for (int i=0; i<n; i++) {
scanf("%s[^\n]", s[i]);
}
int cur=0;
for (int i=0; i<n; i++){
for (int j=cur; j<102; j++){
if ( s[i][j] == ' ' ) {
cur=j;
break;
}
}
}
printf("%d\n",cur+1);
}
}
|
C
|
/* File Name : bpt.c
* Author : Kim, Myeong Jae
* Due Date : 2017-11-5
*
* This is a implementation of disk-based b+tree */
#include "bpt.h"
#include <string.h>
#include <sys/stat.h>
#include <sys/types.h>
#include "bpt_header_object.h"
#include "bpt_page_object.h"
#include "bpt_free_page_manager.h"
#include "bpt_fd_table_map.h"
#include "bpt_buffer_manager.h"
// Current page offset
// Page moving must be occurred via go_to_page function.
static off64_t current_page_start_offset = 0;
// header page array always exists.
extern header_object_t header_page[MAX_TABLE_NUM + 1];
// Clearing page.
const int8_t empty_page_dummy[PAGE_SIZE] = {0};
static bool clear_resource_is_registered = false;
/** int64_t get_current_page_number(void) {
* off64_t current_offset = lseek64(db, 0, SEEK_CUR);
* if (current_offset < 0) {
* perror("(get_current_page_offset)");
* exit(1);
* }
* return current_offset / PAGE_SIZE;
* } */
// This function change current_page_head of required page.
void go_to_page_number(const int32_t table_id, const int64_t page_number) {
int32_t fd = get_fd_of_table(table_id);
current_page_start_offset = lseek64(fd, page_number * PAGE_SIZE, SEEK_SET);
if (current_page_start_offset < 0) {
perror("(go_to_page) moving file offset failed.");
assert(false);
exit(1);
}
}
void print_all(int32_t table_id) {
page_object_t page_buffer;
page_object_constructor(&page_buffer, table_id,
header_page[table_id].get_root_page_offset(&header_page[table_id]) / PAGE_SIZE);
/** page_buffer.set_current_page_number(&page_buffer,
* header_page[table_id].get_root_page_offset(&header_page[table_id]) / PAGE_SIZE);
* page_buffer.read(&page_buffer); */
while (page_buffer.get_type(&page_buffer) != LEAF_PAGE) {
assert(page_buffer.get_type(&page_buffer) != INVALID_PAGE);
page_buffer.set_current_page_number(&page_buffer,
page_buffer.page->header.one_more_page_offset / PAGE_SIZE);
page_buffer.read(&page_buffer);
}
// Leaf is found.
int64_t i;
int64_t correct = 1;
while(1){
assert(page_buffer.get_type(&page_buffer) == LEAF_PAGE);
for (i = 0; i < page_buffer.page->header.number_of_keys; ++i) {
printf("[table_id: %d, page #%ld] key:%ld, value:%s\n",
page_buffer.table_id,
page_buffer.get_current_page_number(&page_buffer),
page_buffer.page->content.records[i].key,
page_buffer.page->content.records[i].value);
if (page_buffer.page->content.records[i].key
!= correct++) {
assert(false);
}
}
if (page_buffer.page->header.one_more_page_offset != 0) {
page_buffer.set_current_page_number(&page_buffer,
page_buffer.page->header.one_more_page_offset / PAGE_SIZE);
page_buffer.read(&page_buffer);
} else {
break;
}
}
page_object_destructor(&page_buffer);
}
void print_header_page(int32_t table_id) {
header_page[table_id].print(&header_page[table_id]);
}
/** void print_page(const int32_t table_id, const int64_t page_number) {
* page_header_t header;
*
* go_to_page_number(table_id, page_number);
*
* memset(&header, 0 , sizeof(header));
* if (read(db, &header, sizeof(header)) < 0) {
* perror("(print_page)");
* exit(1);
* }
*
* printf(" ** Printing Page Header ** \n");
* printf(" linked_page_offset: %ld\n",
* header.linked_page_offset);
* printf(" is_leaf: %d\n", header.is_leaf);
* printf(" number_of_keys: %d\n",
* header.number_of_keys);
* printf(" one_more_page_offset: %ld\n",
* header.one_more_page_offset);
* printf(" ** End ** \n");
*
*
* //TODO: print other informations
* } */
// This function is called when a DB file is first generated.
// Initialize header page and root.
void init_table(const int32_t table_id) {
// DB exists
#ifdef DBG
printf("(initialize_db) DB Initializing start!\n");
#endif
// Page 0 is header page.
// Page 1 is free page dummy.
// Page 2 is Root page.
// The number of pages includes all kinds of pages.
// '3' means header page, free page dummy, root page
// Free page offset, Root page offset, number of pages.
header_page[table_id].set(&header_page[table_id], 1 * PAGE_SIZE, 2 * PAGE_SIZE, 3);
header_page[table_id].write(&header_page[table_id]);
// Go to root page
page_object_t page;
memset(&page, 0, sizeof(page));
page_object_constructor(&page, table_id, 2);
/** page.current_page_number = 2; */
/** page.read(&page); */
// Write header of root
// Parent of root is root.
// DB has at least three pages.
// 1. Header page
// 2. Free page dummy
// 3. Root page
// Root's parent offset should be zero.
page.page->header.is_leaf = true;
page.write(&page);
page_object_destructor(&page);
}
// This function finds the leaf page that a key will be stored.
int64_t find_leaf_page(int32_t table_id, const int key) {
int32_t i = 0;
// page object is needed.
page_object_t page;
page_object_constructor(&page, table_id,
header_page[table_id].get_root_page_offset(&header_page[table_id]) / PAGE_SIZE);
// When root has no keys
if (page.page->header.number_of_keys == 0) {
goto end;
}
// Leaf is not found. Go to found leaf
/** int64_t parent_offset; */
while(page.get_type(&page) != LEAF_PAGE) {
assert(page.get_type(&page) != INVALID_PAGE);
/** parent_offset = page.current_page_number * PAGE_SIZE; */
// Internal page is found
// Check one_more_page_offset
i = 0;
while(i < page.get_number_of_keys(&page)) {
if (key >= page.get_key_and_offset(&page, i)->key) {
i++;
} else {
break;
}
}
// Next page is found. Go to next page
if (i == 0) {
page.set_current_page_number(&page,
page.page->header.one_more_page_offset / PAGE_SIZE);
} else {
// i-1 because of the internal page structure
page.set_current_page_number(&page,
page.get_key_and_offset(&page, i-1)->page_offset / PAGE_SIZE);
}
page.read(&page);
///////////////////////////////////////////////
/** page.page->header.linked_page_offset = parent_offset; */
/** page.write(&page); */
///////////////////////////////////////////////
}
int64_t rt_value;
end:
rt_value = page.get_current_page_number(&page);
page_object_destructor(&page);
return rt_value;
}
/* Functions related with Insert() End */
int open_table (char *pathname){
// setting header page
int32_t fd = open(pathname, O_RDWR | O_LARGEFILE);
int32_t table_id;
if (fd < 0) {
// Opening is failed.
#ifdef DBG
printf("(open_table) DB not exists. Create new one.\n");
#endif
// Create file and change its permission
fd = open(pathname, O_RDWR | O_CREAT | O_EXCL | O_LARGEFILE);
if (fd < 0) {
// Creating is failed.
perror("(open_table) DB opening is failed.");
fprintf(stderr, "(open_table) Terminate the program\n");
return -1;
}
// Change its permission.
chmod(pathname, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);
// DB is created. Initialize header page and root.
table_id = set_new_table_of_fd(fd);
init_table(table_id);
} else{
table_id = set_new_table_of_fd(fd);
// Table is already initialized.
}
// Read header
header_page[table_id].read(&header_page[table_id]);
// Initialize free_page_manger.
free_page_manager_init(table_id);
return table_id;
}
int insert(int32_t table_id, int64_t key, char *value){
#ifdef DBG
printf("(insert) Start insert. key: %ld, value: %s\n", key, value);
#endif
/** If same value is exist, do nothing */
// TODO: Implement find
/** Create a new record */
record_t record;
record.key = key;
strncpy(record.value, value, sizeof(record.value));
/** Find a leaf page to insert the value */
int64_t leaf_page = find_leaf_page(table_id, key);
/** If leaf has room for record, insert */
page_object_t page;
page_object_constructor(&page,table_id, leaf_page);
/** page.set_current_page_number(&page, leaf_page);
* page.read(&page); */
page.type = LEAF_PAGE;
if (page.insert_record(&page, &record)) {
// insertion is successful.
page_object_destructor(&page);
return 0;
}
/** If leaf has no room for record, split and insert */
int rt_value = page.insert_record_after_splitting(&page, &record);
page_object_destructor(&page);
return rt_value;
}
char find_result_buffer[VALUE_SIZE];
char * find(int32_t table_id, int64_t key){
int64_t i = 0;
page_object_t page_buffer;
int64_t leaf_page = find_leaf_page(table_id, key);
if (leaf_page == 0) {
return NULL;
}
page_object_constructor(&page_buffer, table_id, leaf_page);
/** page_buffer.set_current_page_number(&page_buffer, leaf_page); */
/** page_buffer.read(&page_buffer); */
char* rt_value;
for (i = 0; i < page_buffer.get_number_of_keys(&page_buffer); ++i) {
if (page_buffer.page->content.records[i].key == (int64_t)key) {
break;
}
}
if (i == page_buffer.get_number_of_keys(&page_buffer)) {
rt_value = NULL;
} else {
memset(find_result_buffer, 0, sizeof(find_result_buffer));
memcpy(find_result_buffer, page_buffer.page->content.records[i].value,
sizeof(find_result_buffer));
rt_value = find_result_buffer;
}
page_object_destructor(&page_buffer);
return rt_value;
}
int delete(int32_t table_id, int64_t key){
page_object_t page_buffer;
int64_t leaf_page = find_leaf_page(table_id, key);
if (leaf_page == 0) {
// Key is not found
return 1;
}
page_object_constructor(&page_buffer, table_id, leaf_page);
/** page_buffer.set_current_page_number(&page_buffer, leaf_page);
* page_buffer.read(&page_buffer); */
assert(page_buffer.get_type(&page_buffer) == LEAF_PAGE);
int rt_value;
if (page_buffer.delete_record_of_key(&page_buffer, key) == false) {
// Deletion is failed.
rt_value = 1;
} else {
rt_value = 0;
}
page_object_destructor(&page_buffer);
return rt_value;
}
extern buf_mgr_t buf_mgr;
int close_table(int table_id){
// clear free pages.
/** free_page_clean(table_id); */
// flush buffer frames
buf_mgr.flush_table(&buf_mgr, table_id);
int fd = get_fd_of_table(table_id);
if(close(fd) < 0) {
perror("(close_table)");
exit(1);
}
if(remove_table_id_mapping(table_id) == true) {
return 0;
} else {
return -1;
}
}
int init_db (int buf_num){
buf_mgr_constructor(&buf_mgr, buf_num);
}
int shutdown_db(void) {
// free page clean
int i;
buf_mgr.flush_all(&buf_mgr);
for (i = 0; i < MAX_TABLE_NUM + 1; ++i) {
if (get_fd_of_table(i) != 0) {
/** free_page_clean(i); */
}
}
buf_mgr_destructor(&buf_mgr);
}
|
C
|
#include <sys/types.h>
#include <sys/stat.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <stdio.h>
#include <pwd.h>
#define MAX 512
#define AUTH_FILE "/etc/triface.own"
#define COMM_FILE "/etc/triface.com"
extern char **environ;
char *GetFileName(char *obj)
{
char *path;
char *file;
if ( (file=(char *)calloc(MAX, sizeof(char))) == NULL )
exit(-2);
path = getenv("WORK_HOME");
if ( !path || (strlen(path)+strlen(obj)) > MAX )
return NULL;
memcpy(file, path, strlen(path));
memcpy(file+strlen(file), obj, strlen(obj));
return file;
}
/* bool */
int CheckValidCommand(char *arg)
{
FILE *fd;
char *comm_file;
char tmp[MAX];
struct stat st_file;
comm_file = GetFileName(COMM_FILE);
if ( stat(comm_file, &st_file) == -1 )
return 0;
if ( (fd = fopen(comm_file, "r")) == NULL )
return -0;
while (fgets(tmp, MAX-1, fd))
{
tmp[strlen(tmp)-1] = '\0';
if ( strncmp(tmp, arg, strlen(arg)) == 0 )
{
fclose(fd);
return 1;
}
}
fclose(fd);
return 0;
}
uid_t GetUserAuthorized(void)
{
FILE *fd;
char *auth_file;
char tmp[MAX];
struct passwd *owner;
struct stat st_file;
auth_file = GetFileName(AUTH_FILE);
if ( stat(auth_file, &st_file) == -1 )
return -1;
if ( (fd = fopen(auth_file, "r")) == NULL )
return -1;
if ( fgets(tmp, MAX-1, fd) == NULL )
return fclose(fd);
fclose(fd);
tmp[strlen(tmp)-1] = '\0';
if ( (owner = getpwnam(tmp)) == NULL )
return -1;
else
return owner->pw_uid;
}
int main(int argc, char **argv)
{
int i;
uid_t euid, uid;
char *ptr[argc];
euid = geteuid();
if ( euid != 0 )
return printf("File must be setuid for root\n");
uid = getuid();
if ( GetUserAuthorized() != uid )
return printf("UID %ld is not authorized to execute this file\n", uid);
if ( argc < 2 || !CheckValidCommand(argv[1]))
return printf("Invalid command\n");
for (i=1; i < argc; i++)
ptr[i-1] = argv[i];
ptr[i-1] = NULL;
setuid(0);
execve(ptr[0], ptr, environ);
exit(0);
}
|
C
|
#include<stdio.h>
void swap(intx,inty)
{
int t;
t=a;
a=b;
b=t;
}
int main()
{
int a=100,b=200;
printf("\n before swapping a = %d b = %d",a,b);
swap(a,b)
printf("\n after swapping a = %d b = %d",a,b);
return 0;
}
|
C
|
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <string.h>
#include <stdio.h>
#include <errno.h>
#include <time.h>
#include <stdbool.h>
#define DAYTIME_SERVER_PORT 13
#define MAX_CLIENT 1000
#define MAX_LEN 80
int main(int argc, char **argv)
{
int servFd, ret;
int clientFd;
struct sockaddr_in addr;
servFd = socket(AF_INET, SOCK_STREAM, 0);
if(servFd == -1) {
printf("%s: %s\n", "socket", strerror(errno));
return -1;
}
memset(&addr, 0, sizeof(addr));
addr.sin_family = AF_INET;
addr.sin_addr.s_addr = htonl(INADDR_ANY);
addr.sin_port = htons(DAYTIME_SERVER_PORT);
ret = bind(servFd, (struct sockaddr*)&addr, sizeof(addr));
if (ret != 0) {
printf("%s: %s\n", "bind", strerror(errno));
return -1;
}
ret = listen(servFd, MAX_CLIENT);
if (ret != 0) {
printf("%s: %s\n", "listen", strerror(errno));
return -1;
}
time_t currentTime;
char sendBuf[MAX_LEN];
while (true) {
clientFd = accept(servFd, (struct sockaddr*)NULL, NULL);
if (clientFd > 0) {
currentTime = time(NULL);
snprintf(sendBuf, MAX_LEN, "%s\n", ctime(¤tTime));
write(clientFd, sendBuf, strlen(sendBuf));
close(clientFd);
}
else {
printf("error occuced when client attemp to connect\n");
}
}
return 0;
}
|
C
|
/*
* Init.c
*
* Created: 04-11-2020 12:24:15
* Author: Kenneth
*/
#include <stdio.h>
#include <avr/io.h>
void Init(void)
{
/* Matrix Keyboard */
// Column sat til hj
DDRK |= (1<<PK0);
DDRK |= (1<<PK1);
DDRK |= (1<<PK2);
DDRK |= (1<<PK3);
// Row sat til input
PORTK |= (1<<PK4);
PORTK |= (1<<PK5);
PORTK |= (1<<PK6);
PORTK |= (1<<PK7);
}
|
C
|
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
void traverse(struct TreeNode *root, int *min) {
if (root) {
if (min[0] == -1) {
min[0] = root->val;
} else {
if (root->val < min[0]) {
min[1] = min[0];
min[0] = root->val;
} else if ((min[0] != root->val) && (min[1] == -1 || root->val < min[1])) {
min[1] = root->val;
}
}
if (root->left) {
traverse(root->left, min);
}
if (root->right) {
traverse(root->right, min);
}
}
}
int findSecondMinimumValue(struct TreeNode* root){
int min[2] = { -1, -1 }; // [smallest, second-smallest]
traverse(root, min);
if (min[0] != min[1]) {
return min[1];
}
return -1;
}
|
C
|
#include<stdio.h>
#include<stdlib.h>
#include "2.h"
node* f9(node* p, int value)
{
node* initp = p;
node* newp = (node*)malloc(sizeof(node));
newp->data = value;
while (p->next != NULL&&value > p->next->data)
{
p = p->next;
}
if(p->next==NULL)
{
newp->next = p->next;
p->next = newp;
}
else
{
newp->next = p->next;
p->next = newp;
}
show(initp);
}
|
C
|
/*
* time.h
* Times the difference and sends the data out via UDP
*
* Created on: July 2, 2016
* Author: elvin.chua
*/
#ifndef STATS_H_
#define STATS_H_
#include <sys/time.h>
#include <stdint.h>
#include <stdio.h>
#include <string.h>
#include <sys/socket.h>
#include <arpa/inet.h>
typedef struct{
uint32_t id;
uint32_t timeTaken;
} TimePacket;
static struct timeval startTime[32];
static int histoUdpSock;
static struct sockaddr_in histoAddr;
static void HistoInit(){
histoUdpSock = 0;
histoUdpSock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
memset((char *) &histoAddr, 0, sizeof(histoAddr));
histoAddr.sin_family = AF_INET;
histoAddr.sin_port = htons(19000);
inet_aton("127.0.0.1", &histoAddr.sin_addr);
}
static void HistoStart(int i){
gettimeofday(&(startTime[i]), 0);
}
static void HistoStop(int i){
struct timeval end;
gettimeofday(&end, 0);
TimePacket p;
p.id = i;
p.timeTaken = (end.tv_sec - startTime[i].tv_sec) * 1000000 + (end.tv_usec - startTime[i].tv_usec);
if(histoUdpSock > 0){
sendto(histoUdpSock, (void *) &p, sizeof(p), 0, (struct sockaddr *) &histoAddr, sizeof(histoAddr));
}
}
#endif /* STATS_H_ */
|
C
|
#include <stdio.h>
void printSquare(int size) {
for ( int rows = 0, counter = 1; rows < size; rows++ ) {
for ( int cols = 0; cols < size -1; cols++ ) {
printf("%d ", counter);
counter +=1;
}
printf("%d\n", counter);
counter += 1;
}
}
void printPiramid(int size) {
for ( int i = 0, counter = 1; 1 < size; i++ ) {
printf("%d ", counter);
counter += 1;
}
printf("%d\n", counter);
counter +=1;
}
|
C
|
#pragma once
typedef struct cs_sl_node cs_sl_node_t;
typedef struct cs_slist cs_slist_t;
struct cs_sl_node {
void* data;
cs_sl_node_t* next;
};
struct cs_slist {
cs_sl_node_t* head;
};
cs_sl_node_t* cs_sl_node_new(void* data);
void cs_sl_node_free(cs_sl_node_t* node);
cs_slist_t* cs_slist_new();
void cs_slist_free(cs_slist_t*);
cs_sl_node_t* cs_slist_search(cs_slist_t*, void* data);
void cs_slist_insert(cs_slist_t*, cs_sl_node_t* x);
void cs_slist_remove(cs_slist_t*, cs_sl_node_t* x);
void cs_slist_reverse(cs_slist_t*);
void cs_slist_print(const cs_slist_t*);
|
C
|
#include <signal.h>
static
__sighandler_t set_mask(int sig, int how, __sighandler_t ret)
{
sigset_t set;
// Create an empty signal set.
if (sigemptyset(&set) < 0)
return SIG_ERR;
// Add the specified signal.
if (sigaddset(&set, sig) < 0)
return SIG_ERR;
// Add the signal set to the current signal mask.
if (sigprocmask(how, &set, NULL) < 0)
return SIG_ERR;
return ret;
}
__sighandler_t sigset(int sig, __sighandler_t disp)
{
struct sigaction nact, oact;
// Block the signal if needed
if (disp == SIG_HOLD)
return set_mask(sig, SIG_BLOCK, SIG_HOLD);
nact.sa_handler = disp;
if (sigemptyset(&nact.sa_mask) < 0)
return SIG_ERR;
nact.sa_flags = 0;
if (sigaction(sig, &nact, &oact) < 0)
return SIG_ERR;
return set_mask(sig, SIG_UNBLOCK, oact.sa_handler);
}
|
C
|
/*
Author: Niek van Leeuwen
Date: 07-11-2019
*/
#include "client.h"
#include <sensordata.h>
int send_packet(int, struct sockaddr * ,socklen_t, int interval);
int main(int argc, char *argv[])
{
int sockfd, ret, portno, interval;
char* server_ip;
struct sockaddr_in serveraddress;
//default values defined in client.h
server_ip = DEFAULT_SERVER_IP;
interval = DEFAULT_INTERVAL;
portno = DEFAULT_PORT;
// handle the arguments
for (int i = 0; i < argc; i++) {
// the user wants to use another port than the default one
if (!strcmp(argv[i], "-p") || !strcmp(argv[i], "--port")){
// check if the argument is a digit
if(isNumber(argv[i+1])){
portno = atoi(argv[i+1]);
}else{
printf("The Port number provided is not correct!\n");
exit(1);
}
}
// the user wants another server ip adress
if (!strcmp(argv[i], "-si") || !strcmp(argv[i], "--serverip")){
// check if the argument is a valid IP Adress
if(isValidIpAddress(argv[i+1])){
server_ip = argv[i+1];
}else{
printf("The IP Address provided is not correct!\n");
exit(1);
}
}
// the user wants another buffersize
if (!strcmp(argv[i], "-i") || !strcmp(argv[i], "--interval")){
// check if the argument is a digit
if (isNumber(argv[i+1])){
interval = atoi(argv[i+1]);
}else{
printf("The interval provided is not correct!\n");
exit(1);
}
}
// the user needs help
if (!strcmp(argv[i], "-h") || !strcmp(argv[i], "--help")){
help();
}
}
// print the startup message
startup_message(server_ip, portno, interval);
//convert from milliseconds to seconds
interval = interval / 1000;
// create a socket
sockfd = socket(AF_INET, SOCK_DGRAM, 0);
if(0 > sockfd)
{
perror("Error while creating socket");
exit(1);
}
memset(&serveraddress, 0, sizeof(serveraddress));
serveraddress.sin_family = AF_INET;
serveraddress.sin_port = htons(portno);
serveraddress.sin_addr.s_addr = inet_addr(server_ip);
printf("Client Starting service...\n");
ret = send_packet(sockfd ,(struct sockaddr *)&serveraddress, sizeof(serveraddress), interval);
if (ret < 0)
{
printf("Client Exiting - Some error occured\n");
close(sockfd);
exit(1);
}
close(sockfd);
exit(0);
}
int send_packet(int sockfd , struct sockaddr *to ,socklen_t servaddrlength, int interval)
{
int ret;
SENSOR_DATA sensordata;
int i = 0;
while(true)
{
//updating the struct
sensordata.potix_return = i;
sensordata.potiy_return = i * -1;
sensordata.packets_sent = i;
// sending the read data over socket
ret = sendto(sockfd, (void *)&sensordata, sizeof(sensordata), 0, to, servaddrlength);
if (0 > ret)
{
perror("Error in sending data:\n");
return -1;
}
printf("Data Sent To Server, packet number: %i\n\n", i);
sleep(interval);
i++;
}
return 0;
}
|
C
|
int main()
{
int a;
printf("enter a number: ");
scanf("%i, &a");
if( a <= 50, a++ )
printf("odd");
else
printf("even");
return 0;
}
|
C
|
/**
* @mainpage
* # Загальне завдання
* 1. **Зробити** tree
*
* @author Gladkov K.
* @date 14-feb-2020
* @version 1.0
*/
/**
* @file main.c
* @brief Файл з main, який також викликае функцii
*
* @author Gladkov K.
* @date 14-feb-2020
* @version 1.0
*/
#include "lib.h"
int main()
{
printf("Program was made by Gladkov Kostyantyn for 14th lab work which is about working with files.\n");
// Directory path to list files
char path[100];
printf("Enter path to list files: ");
scanf("%s", path);
tree(path, 0);
dir_size(path);
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <fcntl.h>
#include <sys/mman.h>
#include <linux/videodev2.h>
#define VIDEO_WIDTH 640
#define VIDEO_HEIGHT 480
#define VIDEO_FORMAT V4L2_PIX_FMT_H264
#define BUFFER_COUNT 4
struct buffer
{
void* start;
unsigned int length;
};
int hexDump(char* buf, int buf_len)
{
int i = 0;
for(i = 0; i < buf_len; i++)
{
printf("%02x ", buf[i]);
if((i + 15)%16 == 0)
{
printf("\n");
}
}
printf("\n");
return 0;
}
int process_frame(void* frame, int frame_len)
{
printf("frame_len:%d\n", frame_len);
return 0;
}
int openCam(char* camName)
{
int fd = open(camName, O_RDWR);
if(fd < 0)
{
return -1;
}
return fd;
}
int closeCam(int fd)
{
if(fd != -1)
{
return close(fd);
}
return -1;
}
int getCamInfo(int fd)
{
int ret = -1;
struct v4l2_capability cap;
memset(&cap, 0, sizeof(cap));
ret = ioctl(fd, VIDIOC_QUERYCAP, &cap);
if(ret < 0)
{
printf("VIDIOC_QUERYCAP failed (%d)\n", ret);
perror("VIDIOC_QUERYCAP");
return ret;
}
printf("Camera Capability Informations:\n");
printf("\tDriver Name:%s\n", cap.driver);
printf("\tCard Name:%s\n", cap.card);
printf("\tBuf info:%s\n", cap.bus_info);
printf("\tDriver Version:%u.%u.%u\n", (cap.version>>16)&0xff, (cap.version>>8)&0xff, cap.version&0xff);
printf("\tCapabilities:0x%08x\n", cap.capabilities);
return ret;
}
int dumpCamFmt(struct v4l2_format* pFmt)
{
if(NULL == pFmt)
{
return -1;
}
char fmtStr[8] = {0};
memcpy(fmtStr, &pFmt->fmt.pix.pixelformat, 4);
printf("Stream Format Informations:\n");
printf("\ttype:%d\n", pFmt->type);
printf("\twidth:%d\n", pFmt->fmt.pix.width);
printf("\theight:%d\n", pFmt->fmt.pix.height);
printf("\tpixelformat:%s\n", fmtStr);
printf("\tfield:%d\n", pFmt->fmt.pix.field);
printf("\tbytesPerLine:%d\n", pFmt->fmt.pix.bytesperline);
printf("\tsizeimage:%d\n", pFmt->fmt.pix.sizeimage);
printf("\tcolorspace:%d\n", pFmt->fmt.pix.colorspace);
printf("\tpriv:%d\n", pFmt->fmt.pix.priv);
printf("\traw_data:%s\n", pFmt->fmt.raw_data);
return 0;
}
int loadCamFmt(struct v4l2_format *pFmt)
{
if(NULL == pFmt)
{
return -1;
}
memset(pFmt, 0, sizeof(struct v4l2_format));
pFmt->type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
pFmt->fmt.pix.width = VIDEO_WIDTH;
pFmt->fmt.pix.height = VIDEO_HEIGHT;
pFmt->fmt.pix.pixelformat = V4L2_PIX_FMT_H264;
pFmt->fmt.pix.field = V4L2_FIELD_INTERLACED;
return 0;
}
int getCamFmt(int fd)
{
printf("%s\n", __func__);
int ret = -1;
struct v4l2_format fmt;
memset(&fmt, 0, sizeof(fmt));
fmt.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
ret = ioctl(fd, VIDIOC_G_FMT, &fmt);
if(ret < 0)
{
printf("VIDIOC_G_FMT failed (%d)\n", ret);
perror("VIDIOC_G_FMT");
return ret;
}
dumpCamFmt(&fmt);
return ret;
}
int setCamFmt(int fd, struct v4l2_format *pFmt)
{
int ret = -1;
if(NULL == pFmt)
{
return -1;
}
ret = ioctl(fd, VIDIOC_S_FMT, pFmt);
if(ret < 0)
{
printf("VIDIOC_S_FMT failed (%d)\n", ret);
perror("VIDIOC_S_FMT");
return ret;
}
return ret;
}
int showCamSupportedFmt(int fd)
{
//Check Supported Format
struct v4l2_fmtdesc fmtdesc;
memset(&fmtdesc, 0, sizeof(struct v4l2_fmtdesc));
fmtdesc.index = 0;
fmtdesc.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
printf("Supported format:\n");
while(ioctl(fd, VIDIOC_ENUM_FMT, &fmtdesc) != -1)
{
printf("\t%d.%s\n", fmtdesc.index+1, fmtdesc.description);
fmtdesc.index++;
}
return 0;
}
int showCamFrameSetting(int fd)
{
//Show Current Frame Setting
printf("%s\n", __func__);
struct v4l2_format fmt;
memset(&fmt, 0, sizeof(fmt));
fmt.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
int ret = ioctl(fd, VIDIOC_G_FMT, &fmt);
if(ret < 0)
{
perror("VIDIOC_G_FMT");
return -1;
}
printf("Current data format information:\n");
//dumpCamFmt(&fmt);
struct v4l2_fmtdesc fmtdesc;
memset(&fmtdesc, 0, sizeof(struct v4l2_fmtdesc));
fmtdesc.index = 0;
fmtdesc.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
while(ioctl(fd, VIDIOC_ENUM_FMT, &fmtdesc) != -1)
{
if(fmtdesc.pixelformat & fmt.fmt.pix.pixelformat)
{
printf("\tformat:%s\n", fmtdesc.description);
break;
}
fmtdesc.index++;
}
return 0;
}
int isSupportRGB32(int fd)
{
//Check if support a format
struct v4l2_format fmt;
memset(&fmt, 0, sizeof(struct v4l2_format));
fmt.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
fmt.fmt.pix.pixelformat = V4L2_PIX_FMT_RGB32;
if(ioctl(fd, VIDIOC_TRY_FMT, &fmt) == -1)
{
if(errno == EINVAL)
{
printf("Do not support format RGB32!\n");
return -1;
}
}
return 0;
}
int dumpV4l2Buf(struct v4l2_buffer* pBuf)
{
printf("BufInfo:\n");
printf("\tindex:%u\n", pBuf->index);
printf("\ttype:%u\n", pBuf->type);
printf("\tbytesused:%u\n", pBuf->bytesused);
printf("\tflags:%u\n", pBuf->flags);
//flags
if(pBuf->flags & V4L2_BUF_FLAG_MAPPED)
{
printf("\t\tV4L2_BUF_FLAG_MAPPED\n");
}
if(pBuf->flags & V4L2_BUF_FLAG_QUEUED)
{
printf("\t\tV4L2_BUF_FLAG_QUEUED\n");
}
if(pBuf->flags & V4L2_BUF_FLAG_DONE)
{
printf("\t\tV4L2_BUF_FLAG_DONE\n");
}
if(pBuf->flags & V4L2_BUF_FLAG_KEYFRAME)
{
printf("\t\tV4L2_BUF_FLAG_KEYFRAME\n");
}
if(pBuf->flags & V4L2_BUF_FLAG_PFRAME)
{
printf("\t\tV4L2_BUF_FLAG_PFRAME\n");
}
if(pBuf->flags & V4L2_BUF_FLAG_BFRAME)
{
printf("\t\tV4L2_BUF_FLAG_BFRAME\n");
}
if(pBuf->flags & V4L2_BUF_FLAG_ERROR)
{
printf("\t\tV4L2_BUF_FLAG_ERROR\n");
}
printf("\ttimestamp:%u.%u\n", pBuf->timestamp.tv_sec, pBuf->timestamp.tv_usec);
printf("\ttimecode:\n");
printf("\t\ttype:%u\n", pBuf->timecode.type);
printf("\t\tflags:%u\n", pBuf->timecode.flags);
printf("\t\tframes:%u\n", pBuf->timecode.frames);
printf("\t\t[%u:%u:%u]\n",
pBuf->timecode.hours,
pBuf->timecode.minutes,
pBuf->timecode.seconds);
printf("\tsequence:%u\n", pBuf->sequence);
}
//Show the current input video supported format.
int showInputSupport(int fd)
{
struct v4l2_input input;
memset(&input, 0, sizeof(struct v4l2_input));
//Get the Current input index.
if(-1 == ioctl(fd, VIDIOC_G_INPUT, &input.index))
{
perror("VIOIOC_G_INPUT");
return -1;
}
//Get the Information matched to the index
if(-1 == ioctl(fd, VIDIOC_ENUMINPUT, &input))
{
perror("VIDIOC_ENUMINPUT");
return -1;
}
printf("Current input %s supports:\n", input.name);
printf("\tindex:%d\n", input.index);
printf("\tname:%s\n", input.name);
printf("\ttype:%d\n", input.type);
printf("\taudioset:%d\n", input.audioset);
printf("\ttuner:%d\n", input.tuner);
printf("\tstatus:%d\n", input.status);
return 0;
}
//This function is not working.
int showCamStandard(int fd)
{
struct v4l2_input input;
memset(&input, 0, sizeof(struct v4l2_input));
//Get the Current input index.
if(-1 == ioctl(fd, VIDIOC_G_INPUT, &input.index))
{
perror("VIOIOC_G_INPUT");
return -1;
}
//Get the Information matched to the index
if(-1 == ioctl(fd, VIDIOC_ENUMINPUT, &input))
{
perror("VIDIOC_ENUMINPUT");
return -1;
}
struct v4l2_standard standard;
memset(&standard, 0, sizeof(struct v4l2_standard));
standard.index = 0;
//Get all the standards that the camera support.
while(0 == ioctl(fd, VIDIOC_ENUMSTD, &standard))
{
printf("standard.index:%d\n", standard.index);
if(standard.id & input.std)
{
printf("%s\n", standard.name);
}
standard.index++;
}
//EINVAL indicates the end of the enumeration.
if(errno != EINVAL || standard.index == 0)
{
perror("VIDIOC_ENUMSTD");
return -1;
}
//
v4l2_std_id std_id;
memset(&standard, 0, sizeof(standard));
if(-1 == ioctl(fd, VIDIOC_G_STD, &std_id))
{
perror("VIDIOC_G_STD");
return -1;
}
memset(&standard, 0, sizeof(standard));
standard.index = 0;
while(0 == ioctl(fd, VIDIOC_ENUMSTD, &standard))
{
if(standard.id & std_id)
{
printf("Current video standard:%s\n", standard.name);
break;
}
standard.index++;
}
if(errno == EINVAL || standard.index == 0)
{
perror("VIDIOC_ENUMSTD");
return -1;
}
return 0;
}
int mapAndEnqueueBuf(int fd, struct v4l2_requestbuffers *pReq, struct buffer* pFrameBuf)
{
//Map the Frame Cache Buffer to User Application Buffer.
int i;
for(i = 0; i < pReq->count; i++)
{
struct v4l2_buffer buf;
memset(&buf, 0, sizeof(buf));
buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
buf.memory = V4L2_MEMORY_MMAP;
buf.index = i;
//Get phy addr and size.
if(-1 == ioctl(fd, VIDIOC_QUERYBUF, &buf))
{
perror("VIDIOC_QUERYBUF");
return -1;
}
//Map buffer
pFrameBuf[i].length = buf.length;
pFrameBuf[i].start = mmap(NULL, buf.length, PROT_READ|PROT_WRITE, MAP_SHARED, fd, buf.m.offset);
if(MAP_FAILED == pFrameBuf[i].start)
{
perror("MMAP error");
return -1;
}
//Queue buffer
ioctl(fd, VIDIOC_QBUF, &buf);
}
return 0;
}
int main()
{
char devStr[64] = {0};
sprintf(devStr, "/dev/video%d", 1);
int camFd = openCam(devStr);
if(camFd < 0)
{
printf("Open camera device %s error\n", devStr);
return -1;
}
getCamInfo(camFd);
showCamSupportedFmt(camFd);
struct v4l2_format fmt;
memset(&fmt, 0, sizeof(fmt));
loadCamFmt(&fmt);
setCamFmt(camFd, &fmt);
getCamFmt(camFd);
showCamFrameSetting(camFd);
showInputSupport(camFd);
//Request Frame Buffers
struct v4l2_requestbuffers req;
memset(&req, 0, sizeof(req));
req.count = BUFFER_COUNT;
req.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
req.memory = V4L2_MEMORY_MMAP;
if(0 > ioctl(camFd, VIDIOC_REQBUFS, &req))
{
perror("VIDIOC_REQBUFS");
return -1;
}
//Allocate Memory for buffers.
struct buffer* buffers = NULL;
buffers = (struct buffer*)calloc(BUFFER_COUNT, sizeof(*buffers));
if(!buffers)
{
fprintf(stderr, "Out of memory\n");
return -1;
}
mapAndEnqueueBuf(camFd, &req, buffers);
//Start the Video Capture.
enum v4l2_buf_type type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
ioctl(camFd, VIDIOC_STREAMON, &type);
//
while(1)
{
struct v4l2_buffer buf;
memset(&buf, 0, sizeof(buf));
buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
buf.memory = V4L2_MEMORY_MMAP;
ioctl(camFd, VIDIOC_DQBUF, &buf);
//dumpV4l2Buf(&buf);
process_frame(buffers[buf.index].start, buf.bytesused);
ioctl(camFd, VIDIOC_QBUF, &buf);
}
if(camFd)
{
close(camFd);
}
return 0;
}
|
C
|
#include<stdio.h>
int main()
{
int a,b,n,m,i,j,mini,sum,sets=1,avg;
while(scanf("%d",&n))
{
if(n==0)
break;
m=0;
sum=0;
int num[n];
for(i=0;i<n;i++)
{
scanf("%d",&num[i]);
sum=sum+num[i];
}
avg=sum/n;
for(j=0;j<n;j++)
{
if(num[j]>avg)
{
a=num[j]-avg;
m=m+a;
}
}
printf("Set #%d\nThe minimum number of moves is %d.\n\n",sets,m);
sets++;
}
return 0;
}
|
C
|
#include "Include.h"
#define SET_595CS {GPIO_SetBits(GPIOB, GPIO_Pin_5);}
#define CLR_595CS {GPIO_ResetBits(GPIOB, GPIO_Pin_5);}
const unsigned char DisplayData[] =
{
0xFA,0xC0,0x76,0xF4,0xCC,0xBC,0xBE,0xD0,0xFE,0xFC,0
};
void Led8IOInit(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB, ENABLE);
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_5;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_10MHz;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP;
GPIO_Init(GPIOB, &GPIO_InitStructure);
SET_595CS
}
void SPIInit(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
SPI_InitTypeDef SPI_InitStructure;
RCC_APB2PeriphClockCmd(RCC_APB2Periph_SPI1, ENABLE);//ʹSPI1ʱ
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA, ENABLE);
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_5 | GPIO_Pin_6 | GPIO_Pin_7;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_10MHz;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;
GPIO_Init(GPIOA, &GPIO_InitStructure);
SPI_InitStructure.SPI_Direction = SPI_Direction_2Lines_FullDuplex;
SPI_InitStructure.SPI_Mode = SPI_Mode_Master;
SPI_InitStructure.SPI_DataSize = SPI_DataSize_8b;
SPI_InitStructure.SPI_CPOL = SPI_CPOL_Low;
SPI_InitStructure.SPI_CPHA = SPI_CPHA_1Edge;
SPI_InitStructure.SPI_NSS = SPI_NSS_Soft;
SPI_InitStructure.SPI_BaudRatePrescaler = SPI_BaudRatePrescaler_2;
SPI_InitStructure.SPI_FirstBit = SPI_FirstBit_MSB;
SPI_InitStructure.SPI_CRCPolynomial = 7;
SPI_Init(SPI1, &SPI_InitStructure);
SPI_Cmd(SPI1, ENABLE);//ʹSPI1
Led8IOInit();
DisplayNumber(0xFF);
}
unsigned char SPI1Action(unsigned char SendData)
{
while(SPI_I2S_GetFlagStatus(SPI1, SPI_I2S_FLAG_TXE)==RESET);
SPI_I2S_SendData(SPI1,SendData);
while(SPI_I2S_GetFlagStatus(SPI1, SPI_I2S_FLAG_RXNE)==RESET);
return(SPI_I2S_ReceiveData(SPI1));
}
void DisplayNumber(unsigned char Number)
{
if(Number>10)
{
Number = 10;
}
CLR_595CS
SPI1Action(DisplayData[Number]);
SET_595CS
}
void SPITest(void)
{
unsigned char i = 0;
Led8IOInit();
while(1)
{
DisplayNumber(i);
i++;
if(i>10)
{
i = 0;
}
DelayNmS(200);
}
while(1)
{
CLR_595CS
SPI1Action(0x55);
SET_595CS
DelayNmS(200);
}
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* get_file_rights.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: abarnett <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2019/04/04 14:54:42 by abarnett #+# #+# */
/* Updated: 2019/04/04 15:25:55 by abarnett ### ########.fr */
/* */
/* ************************************************************************** */
#include "ft_string.h"
#include <sys/stat.h>
/*
** The file mode printed under the -l option consists of the entry type, owner
** permissions, and group permissions. The entry type character describes the
** type of file, as follows:
**
** b Block special file
** c Character special file
** d Directory
** l Symbolic link
** s Socket link
** p FIFO
** - Regular file
**
** The next three fields are three characters each: owner permissions, group
** permissions, and other permissions. Each field has three character
** positions:
**
** 1. If r, the file is readable; if -, it is not readable.
**
** 2. If w, the file is writable; if -, it is not writable.
**
** 3. The first of the following that applies:
**
** S If in the owner permissions, the file is not executable
** and set-user-ID mode is set. If in the group permissions, the
** file is not executable and set-group-ID mode is set.
**
** s If in the owner permissions, the file is executable and
** set-user-ID mode is set. If in the group permissions, the file
** is executable and setgroup-ID mode is set.
**
** x The file is executable or the directory is searchable.
**
** - The file is neither readable, writable, executable, nor
** set-user-ID nor set-group-ID mode, nor sticky. (See below.)
**
** These next two apply only to the third character in the last group
** (other permissions).
**
** T The sticky bit is set (mode 1000), but not execute or
** search permission. (See chmod(1) or sticky(8).)
**
** t The sticky bit is set (mode 1000), and is searchable or
** executable. (See chmod(1) or sticky(8).)
*/
static char type_letter(int mode)
{
char mode_char;
if (S_ISREG(mode))
mode_char = '-';
else if (S_ISBLK(mode))
mode_char = 'b';
else if (S_ISCHR(mode))
mode_char = 'c';
else if (S_ISDIR(mode))
mode_char = 'd';
else if (S_ISLNK(mode))
mode_char = 'l';
else if (S_ISFIFO(mode))
mode_char = 'p';
else if (S_ISSOCK(mode))
mode_char = 's';
else
mode_char = '?';
return (mode_char);
}
char *get_rights(struct stat *stats)
{
char *rights;
unsigned int bits;
int i;
rights = ft_strdup("-rwxrwxrwx");
bits = (stats->st_mode) & (S_IRWXU | S_IRWXG | S_IRWXO);
i = 0;
while (i < 9)
{
if (!(bits & (1 << i)))
rights[9 - i] = '-';
++i;
}
rights[0] = type_letter(stats->st_mode);
if (S_ISUID & stats->st_mode)
rights[3] = (rights[3] == '-') ? 'S' : 's';
if (S_ISGID & stats->st_mode)
rights[6] = (rights[6] == '-') ? 'S' : 's';
if (S_ISVTX & stats->st_mode)
rights[9] = (rights[9] == '-') ? 'T' : 't';
return (rights);
}
|
C
|
/*------------------------------------------------*/
/* kod.c */
/* Toto je libovolny komentar
* v souboru kod.c */
#include <stdio.h> //standardni knihovna
int main(void)
{
printf("Hello World\n");
return 0;
}
/*------------------------------------------------*/
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "list.h"
#include "hash.h"
#include "bitmap.h"
#define MAXCMD_LEN 100
#define MAXARGV_LEN 20
//comparison function of list
bool compare_list(const struct list_elem *a, const struct list_elem *b, void *aux) {
struct list_item *A;
A = list_entry(a, struct list_item, elem);
struct list_item *B;
B = list_entry(b, struct list_item, elem);
if(A->data < B->data)
return true;
else
return false;
}
//comparison function of hash
bool compare_hash(const struct hash_elem *a, const struct hash_elem *b, void *aux) {
struct hash_item *A;
A = hash_entry(a, struct hash_item, elem);
struct hash_item *B;
B = hash_entry(b, struct hash_item, elem);
if(A->data < B->data)
return true;
else
return false;
}
//computes and returns the hash value for hash element E
unsigned hash_func(const struct hash_elem *e, void *aux) {
struct hash_item *E;
E = hash_entry(e, struct hash_item, elem);
return hash_int(E->data);
}
//hash action function : squares data of hash element E
void square_func(struct hash_elem *e, void *aux) {
struct hash_item *item;
item = hash_entry(e, struct hash_item, elem);
item->data *= item->data;
}
//hash action function : triples data of hash element E
void triple_func(struct hash_elem *e, void *aux) {
struct hash_item *item;
item = hash_entry(e, struct hash_item, elem);
item->data *= (item->data)*(item->data);
}
//hash action function : deallocate heap area of hash element E
void destructor_func(struct hash_elem *e, void *aux) {
free(e);
}
/*
main function below continuously gets input from console.
After getting input command, follows procedures below.
(1) get arguments from cmd string through parsing.
(2) call related function with arguments
loop continues until command "quit" is given.
*/
int main(void) {
char cmd[MAXCMD_LEN];
//Required data structures in the program : List, Hash, Bitmap
struct list list[10];
struct hash hash[10];
void* bm[10];
while(1) {
fgets(cmd, MAXCMD_LEN, stdin);
cmd[strlen(cmd)-1]='\0';
int length = strlen(cmd);
if(!strcmp(cmd, "quit"))
break;
else if(!strncmp(cmd, "create list ", 12)) {
char argv[MAXARGV_LEN];
for(int i=12; i<=length; i++)
argv[i-12] = cmd[i];
int list_idx = argv[strlen(argv)-1]-'0';
list_init(&list[list_idx]);
}
else if(!strncmp(cmd, "dumpdata ", 9)) {
char argv[MAXARGV_LEN];
for(int i=9; i<=length; i++)
argv[i-9] = cmd[i];
if(!strncmp(argv, "list", 4)) {
int list_idx = argv[strlen(argv)-1]-'0';
struct list_elem* temp;
for(temp = list_begin(&list[list_idx]); temp != list_end(&list[list_idx]); temp = list_next(temp)) {
struct list_item * item = list_entry(temp, struct list_item, elem);
printf("%d ", item->data);
}
if(temp!=list_begin(&list[list_idx]))
puts("");
}
else if(!strncmp(argv, "hash", 4)) {
int hash_idx = argv[strlen(argv)-1]-'0';
struct hash_iterator iter;
hash_first(&iter, &hash[hash_idx]);
while(hash_next(&iter)) {
struct hash_item *item = hash_entry(hash_cur(&iter), struct hash_item, elem);
printf("%d ", item->data);
}
if(!hash_empty(&hash[hash_idx]))
puts("");
}
else if(!strncmp(argv, "bm", 2)) {
int bitmap_idx = argv[strlen(argv)-1]-'0';
size_t bit_cnt = bitmap_size(bm[bitmap_idx]);
for(size_t i=0; i<bit_cnt; i++) {
bool result = bitmap_test(bm[bitmap_idx], i);
if(result==false)
printf("0");
else
printf("1");
}
if(bit_cnt!=0)
puts("");
}
}
else if(!strncmp(cmd, "list_push_front ", 16)) {
char argv1[MAXARGV_LEN];
char argv2[MAXARGV_LEN];
int i;
for(i=16; cmd[i]!=' '; i++)
argv1[i-16] = cmd[i];
argv1[i-16]='\0';
int list_idx = argv1[strlen(argv1)-1]-'0';
i++;
for(int j=i; j<=length; j++)
argv2[j-i] = cmd[j];
struct list_elem* target = (struct list_elem*)malloc(sizeof(struct list_elem));
list_push_front(&list[list_idx], target);
struct list_item * item = list_entry(target, struct list_item, elem);
item->data = atoi(argv2);
}
else if(!strncmp(cmd, "list_push_back ", 15)) {
char argv1[MAXARGV_LEN];
char argv2[MAXARGV_LEN];
int i;
for(i=15; cmd[i]!=' '; i++)
argv1[i-15] = cmd[i];
argv1[i-15]='\0';
int list_idx = argv1[strlen(argv1)-1]-'0';
i++;
for(int j=i; j<=length; j++)
argv2[j-i] = cmd[j];
struct list_elem* target = (struct list_elem*)malloc(sizeof(struct list_elem));
list_push_back(&list[list_idx], target);
struct list_item * item = list_entry(target, struct list_item, elem);
item->data = atoi(argv2);
}
else if(!strncmp(cmd, "list_front ", 11)) {
char argv[MAXARGV_LEN];
for(int i=11; i<=length; i++)
argv[i-11] = cmd[i];
int list_idx = argv[strlen(argv)-1]-'0';
struct list_elem* temp;
temp = list_front(&list[list_idx]);
struct list_item * item = list_entry(temp, struct list_item, elem);
printf("%d\n", item->data);
}
else if(!strncmp(cmd, "list_back ", 10)) {
char argv[MAXARGV_LEN];
for(int i=10; i<=length; i++)
argv[i-10] = cmd[i];
int list_idx = argv[strlen(argv)-1]-'0';
struct list_elem* temp;
temp = list_back(&list[list_idx]);
struct list_item * item = list_entry(temp, struct list_item, elem);
printf("%d\n", item->data);
}
else if(!strncmp(cmd, "list_pop_front ", 15)) {
char argv[MAXARGV_LEN];
for(int i=15; i<=length; i++)
argv[i-15] = cmd[i];
int list_idx = argv[strlen(argv)-1]-'0';
struct list_elem* temp;
temp = list_pop_front(&list[list_idx]);
free(temp);
}
else if(!strncmp(cmd, "list_pop_back ", 14)) {
char argv[MAXARGV_LEN];
for(int i=14; i<=length; i++)
argv[i-14] = cmd[i];
int list_idx = argv[strlen(argv)-1]-'0';
struct list_elem* temp;
temp = list_pop_back(&list[list_idx]);
free(temp);
}
else if(!strncmp(cmd, "delete ", 7)) {
char argv[MAXARGV_LEN];
for(int i=7; i<=length; i++)
argv[i-7] = cmd[i];
if(!strncmp(argv, "list", 4)) {
int list_idx = argv[strlen(argv)-1]-'0';
while(!list_empty(&list[list_idx])) {
struct list_elem * e;
e = list_pop_front(&list[list_idx]);
free(e);
}
}
else if(!strncmp(argv, "hash", 4)) {
int hash_idx = argv[strlen(argv)-1]-'0';
hash_destroy(&hash[hash_idx], destructor_func);
}
else if(!strncmp(argv, "bm", 2)) {
int bitmap_idx = argv[strlen(argv)-1]-'0';
bitmap_destroy(bm[bitmap_idx]);
}
}
else if(!strncmp(cmd, "list_insert ", 12)) {
char argv1[MAXARGV_LEN];
char argv2[MAXARGV_LEN];
char argv3[MAXARGV_LEN];
int i;
for(i=12; cmd[i]!=' '; i++)
argv1[i-12] = cmd[i];
argv1[i-12]='\0';
int list_idx = argv1[strlen(argv1)-1]-'0';
i++;
int j;
for(j=i; cmd[j]!=' '; j++)
argv2[j-i] = cmd[j];
argv2[j-i]='\0';
j++;
int k;
for(k=j; k<=length; k++)
argv3[k-j] = cmd[k];
struct list_elem* target = (struct list_elem*)malloc(sizeof(struct list_elem));
struct list_item * item = list_entry(target, struct list_item, elem);
item->data = atoi(argv3);
int idx=atoi(argv2);
struct list_elem* temp;
temp = list_begin(&list[list_idx]);
for(int i=0; i<idx; i++)
temp = list_next(temp);
list_insert(temp, target);
}
else if(!strncmp(cmd, "list_empty ", 11)) {
char argv[MAXARGV_LEN];
for(int i=11; i<=length; i++)
argv[i-11] = cmd[i];
int list_idx = argv[strlen(argv)-1]-'0';
if(list_empty(&list[list_idx]))
puts("true");
else
puts("false");
}
else if(!strncmp(cmd, "list_size ", 10)) {
char argv[MAXARGV_LEN];
for(int i=10; i<=length; i++)
argv[i-10] = cmd[i];
int list_idx = argv[strlen(argv)-1]-'0';
printf("%zu\n", list_size(&list[list_idx]));
}
else if(!strncmp(cmd, "list_max ", 9)) {
char argv[MAXARGV_LEN];
for(int i=9; i<=length; i++)
argv[i-9] = cmd[i];
int list_idx = argv[strlen(argv)-1]-'0';
struct list_elem * max_elem;
max_elem = list_max(&list[list_idx], compare_list, NULL);
struct list_item * max_item;
max_item = list_entry(max_elem, struct list_item, elem);
printf("%d\n", max_item->data);
}
else if(!strncmp(cmd, "list_min ", 9)) {
char argv[MAXARGV_LEN];
for(int i=9; i<=length; i++)
argv[i-9] = cmd[i];
int list_idx = argv[strlen(argv)-1]-'0';
struct list_elem * min_elem;
min_elem = list_min(&list[list_idx], compare_list, NULL);
struct list_item * min_item;
min_item = list_entry(min_elem, struct list_item, elem);
printf("%d\n", min_item->data);
}
else if(!strncmp(cmd, "list_remove ", 12)) {
char argv1[MAXARGV_LEN];
char argv2[MAXARGV_LEN];
int i;
for(i=12; cmd[i]!=' '; i++)
argv1[i-12] = cmd[i];
argv1[i-12]='\0';
int list_idx = argv1[strlen(argv1)-1]-'0';
i++;
for(int j=i; j<=length; j++)
argv2[j-i] = cmd[j];
int idx=atoi(argv2);
struct list_elem* temp;
temp = list_begin(&list[list_idx]);
for(int i=0; i<idx; i++)
temp = list_next(temp);
list_remove(temp);
free(temp);
}
else if(!strncmp(cmd, "list_reverse ", 13)) {
char argv[MAXARGV_LEN];
for(int i=13; i<=length; i++)
argv[i-13] = cmd[i];
int list_idx = argv[strlen(argv)-1]-'0';
list_reverse(&list[list_idx]);
}
else if(!strncmp(cmd, "list_insert_ordered ", 20)) {
char argv1[MAXARGV_LEN];
char argv2[MAXARGV_LEN];
int i;
for(i=20; cmd[i]!=' '; i++)
argv1[i-20] = cmd[i];
argv1[i-20]='\0';
int list_idx = argv1[strlen(argv1)-1]-'0';
i++;
for(int j=i; j<=length; j++)
argv2[j-i] = cmd[j];
int value=atoi(argv2);
struct list_elem* temp = (struct list_elem*)malloc(sizeof(struct list_elem));
struct list_item* item = list_entry(temp, struct list_item, elem);
item->data = value;
list_insert_ordered(&list[list_idx], temp, compare_list, NULL);
}
else if(!strncmp(cmd, "list_swap ", 10)) {
char argv1[MAXARGV_LEN];
char argv2[MAXARGV_LEN];
char argv3[MAXARGV_LEN];
int i;
for(i=10; cmd[i]!=' '; i++)
argv1[i-10] = cmd[i];
argv1[i-10] = '\0';
int list_idx = argv1[strlen(argv1)-1]-'0';
i++;
int j;
for(j=i; cmd[j]!=' '; j++)
argv2[j-i] = cmd[j];
argv2[j-i]='\0';
j++;
int k;
for(k=j; k<=length; k++)
argv3[k-j] = cmd[k];
int idx1 = atoi(argv2);
int idx2 = atoi(argv3);
struct list_elem* target1;
struct list_elem* target2;
target1 = list_begin(&list[list_idx]);
target2 = list_begin(&list[list_idx]);
for(int i=0; i<idx1; i++)
target1 = list_next(target1);
for(int j=0; j<idx2; j++)
target2 = list_next(target2);
list_swap(target1, target2);
}
else if(!strncmp(cmd, "list_sort ", 10)) {
char argv[MAXARGV_LEN];
for(int i=10; i<=length; i++)
argv[i-10] = cmd[i];
int list_idx = argv[strlen(argv)-1]-'0';
list_sort(&list[list_idx], compare_list, NULL);
}
else if(!strncmp(cmd, "list_splice ", 12)) {
char argv1[MAXARGV_LEN];
char argv2[MAXARGV_LEN];
char argv3[MAXARGV_LEN];
char argv4[MAXARGV_LEN];
char argv5[MAXARGV_LEN];
int i, j, k, l, m;
for(i=12; cmd[i]!=' '; i++)
argv1[i-12] = cmd[i];
argv1[i-12] = '\0';
i++;
int list_idx1 = argv1[strlen(argv1)-1]-'0';
for(j=i; cmd[j]!=' '; j++)
argv2[j-i] = cmd[j];
argv2[j-i] = '\0';
j++;
int before = atoi(argv2);
for(k=j; cmd[k]!=' '; k++)
argv3[k-j] = cmd[k];
argv3[k-j] = '\0';
k++;
int list_idx2 = argv3[strlen(argv3)-1]-'0';
for(l=k; cmd[l]!=' '; l++)
argv4[l-k] = cmd[l];
argv4[l-k] = '\0';
l++;
int first = atoi(argv4);
for(m=l; m<=length; m++)
argv5[m-l] = cmd[m];
int last = atoi(argv5);
struct list_elem * before_e = list_begin(&list[list_idx1]);
for(int i=0; i<before; i++)
before_e = list_next(before_e);
struct list_elem * first_e = list_begin(&list[list_idx2]);
for(int i=0; i<first; i++)
first_e = list_next(first_e);
struct list_elem * last_e = list_begin(&list[list_idx2]);
for(int i=0; i<last; i++)
last_e = list_next(last_e);
list_splice(before_e, first_e, last_e);
}
else if(!strncmp(cmd, "list_unique ", 12)) {
char argv1[MAXARGV_LEN];
char argv2[MAXARGV_LEN];
int i, j;
for(i=12; cmd[i]!=' ' && cmd[i]!='\0'; i++)
argv1[i-12] = cmd[i];
argv1[i-12] = '\0';
int list_idx1 = argv1[strlen(argv1)-1]-'0';
int list_idx2;
if(cmd[i]=='\0') {
list_idx2=-1;
argv2[0]='\0';
}
else {
i++;
for(j=i; j<=length; j++)
argv2[j-i] = cmd[j];
list_idx2 = argv2[strlen(argv2)-1]-'0';
}
if(list_idx2!=-1)
list_unique(&list[list_idx1], &list[list_idx2], compare_list, NULL);
else
list_unique(&list[list_idx1], NULL, compare_list, NULL);
}
else if(!strncmp(cmd, "list_shuffle ", 13)) {
char argv[MAXARGV_LEN];
for(int i=13; i<=length; i++)
argv[i-13] = cmd[i];
int list_idx = argv[strlen(argv)-1]-'0';
list_shuffle(&list[list_idx]);
}
else if(!strncmp(cmd, "create hashtable ", 17)) {
char argv[MAXARGV_LEN];
for(int i=17; i<=length; i++)
argv[i-17] = cmd[i];
int hash_idx = argv[strlen(argv)-1]-'0';
hash_init(&hash[hash_idx], hash_func, compare_hash, NULL);
}
else if(!strncmp(cmd, "hash_insert ", 12)) {
char argv1[MAXARGV_LEN];
char argv2[MAXARGV_LEN];
int i, j;
for(i=12; cmd[i]!= ' '; i++)
argv1[i-12] = cmd[i];
argv1[i-12] = '\0';
i++;
int hash_idx = argv1[strlen(argv1)-1]-'0';
for(j=i; j<=length; j++)
argv2[j-i] = cmd[j];
int value = atoi(argv2);
struct hash_elem *target = (struct hash_elem*)malloc(sizeof(struct hash_elem));
struct hash_item *item = hash_entry(target, struct hash_item, elem);
item->data = value;
hash_insert(&hash[hash_idx], target);
}
else if(!strncmp(cmd, "hash_apply ", 11)) {
char argv1[MAXARGV_LEN];
char argv2[MAXARGV_LEN];
int i, j;
for(i=11; cmd[i]!=' '; i++)
argv1[i-11] = cmd[i];
argv1[i-11] = '\0';
i++;
int hash_idx = argv1[strlen(argv1)-1]-'0';
for(j=i; j<=length; j++)
argv2[j-i] = cmd[j];
if(!strcmp(argv2, "square"))
hash_apply(&hash[hash_idx], square_func);
else if(!strcmp(argv2, "triple"))
hash_apply(&hash[hash_idx], triple_func);
}
else if(!strncmp(cmd, "hash_delete ", 12)) {
char argv1[MAXARGV_LEN];
char argv2[MAXARGV_LEN];
int i, j;
for(i=12; cmd[i]!=' '; i++)
argv1[i-12] = cmd[i];
argv1[i-12] = '\0';
i++;
int hash_idx = argv1[strlen(argv1)-1]-'0';
for(j=i; j<=length; j++)
argv2[j-i] = cmd[j];
int value = atoi(argv2);
struct hash_elem * target = (struct hash_elem*)malloc(sizeof(struct hash_elem));
struct hash_item * item = hash_entry(target, struct hash_item, elem);
item->data = value;
struct hash_elem * result = hash_delete(&hash[hash_idx], target);
free(target);
if(result!=NULL)
free(result);
}
else if(!strncmp(cmd, "hash_find ", 10)) {
char argv1[MAXARGV_LEN];
char argv2[MAXARGV_LEN];
int i, j;
for(i=10; cmd[i]!=' '; i++)
argv1[i-10] = cmd[i];
argv1[i-10] = '\0';
i++;
int hash_idx = argv1[strlen(argv1)-1]-'0';
for(j=i; j<=length; j++)
argv2[j-i] = cmd[j];
int value = atoi(argv2);
struct hash_elem * target = (struct hash_elem*)malloc(sizeof(struct hash_elem));
struct hash_item * item = hash_entry(target, struct hash_item, elem);
item->data = value;
struct hash_elem *result = hash_find(&hash[hash_idx], target);
if(result!=NULL)
printf("%d\n", item->data);
free(target);
}
else if(!strncmp(cmd, "hash_replace ", 13)) {
char argv1[MAXARGV_LEN];
char argv2[MAXARGV_LEN];
int i, j;
for(i=13; cmd[i]!=' '; i++)
argv1[i-13] = cmd[i];
argv1[i-13] = '\0';
i++;
int hash_idx = argv1[strlen(argv1)-1]-'0';
for(j=i; j<=length; j++)
argv2[j-i] = cmd[j];
int value = atoi(argv2);
struct hash_elem * target = (struct hash_elem*)malloc(sizeof(struct hash_elem));
struct hash_item * item = hash_entry(target, struct hash_item, elem);
item->data = value;
struct hash_elem *result = hash_replace(&hash[hash_idx], target);
if(result!=NULL)
free(result);
}
else if(!strncmp(cmd, "hash_empty ", 11)) {
char argv[MAXARGV_LEN];
for(int i=11; i<=length; i++)
argv[i-11] = cmd[i];
int hash_idx = argv[strlen(argv)-1]-'0';
bool result = hash_empty(&hash[hash_idx]);
if(result)
puts("true");
else
puts("false");
}
else if(!strncmp(cmd, "hash_size ", 10)) {
char argv[MAXARGV_LEN];
for(int i=10; i<=length; i++)
argv[i-10] = cmd[i];
int hash_idx = argv[strlen(argv)-1]-'0';
printf("%zu\n", hash_size(&hash[hash_idx]));
}
else if(!strncmp(cmd, "hash_clear ", 11)) {
char argv[MAXARGV_LEN];
for(int i=11; i<=length; i++)
argv[i-11] = cmd[i];
int hash_idx = argv[strlen(argv)-1]-'0';
hash_clear(&hash[hash_idx], destructor_func);
}
else if(!strncmp(cmd, "create bitmap ", 14)) {
char argv1[MAXARGV_LEN];
char argv2[MAXARGV_LEN];
int i, j;
for(i=14; cmd[i]!=' '; i++)
argv1[i-14] = cmd[i];
argv1[i-14] = '\0';
i++;
int bitmap_idx = argv1[strlen(argv1)-1]-'0';
for(j=i; j<=length; j++)
argv2[j-i] = cmd[j];
size_t bit_cnt = atoi(argv2);
bm[bitmap_idx] = bitmap_create(bit_cnt);
}
else if(!strncmp(cmd, "bitmap_mark ", 12)) {
char argv1[MAXARGV_LEN];
char argv2[MAXARGV_LEN];
int i, j;
for(i=12; cmd[i]!=' '; i++)
argv1[i-12] = cmd[i];
argv1[i-12] = '\0';
i++;
int bitmap_idx = argv1[strlen(argv1)-1]-'0';
for(j=i; j<=length; j++)
argv2[j-i] = cmd[j];
size_t bit_idx = atoi(argv2);
bitmap_mark(bm[bitmap_idx], bit_idx);
}
else if(!strncmp(cmd, "bitmap_all ", 11)) {
char argv1[MAXARGV_LEN];
char argv2[MAXARGV_LEN];
char argv3[MAXARGV_LEN];
int i, j, k;
for(i=11; cmd[i]!=' '; i++)
argv1[i-11] = cmd[i];
argv1[i-11] = '\0';
i++;
int bitmap_idx = argv1[strlen(argv1)-1]-'0';
for(j=i; cmd[j]!=' '; j++)
argv2[j-i] = cmd[j];
argv2[j-i] = '\0';
j++;
size_t start = atoi(argv2);
for(k=j; k<=length; k++)
argv3[k-j] = cmd[k];
size_t cnt = atoi(argv3);
bool result = bitmap_all(bm[bitmap_idx], start, cnt);
if(result)
puts("true");
else
puts("false");
}
else if(!strncmp(cmd, "bitmap_any ", 11)) {
char argv1[MAXARGV_LEN];
char argv2[MAXARGV_LEN];
char argv3[MAXARGV_LEN];
int i, j, k;
for(i=11; cmd[i]!=' '; i++)
argv1[i-11] = cmd[i];
argv1[i-11] = '\0';
i++;
int bitmap_idx = argv1[strlen(argv1)-1]-'0';
for(j=i; cmd[j]!=' '; j++)
argv2[j-i] = cmd[j];
argv2[j-i] = '\0';
j++;
size_t start = atoi(argv2);
for(k=j; k<=length; k++)
argv3[k-j] = cmd[k];
size_t cnt = atoi(argv3);
bool result = bitmap_any(bm[bitmap_idx], start, cnt);
if(result)
puts("true");
else
puts("false");
}
else if(!strncmp(cmd, "bitmap_contains ", 16)) {
char argv1[MAXARGV_LEN];
char argv2[MAXARGV_LEN];
char argv3[MAXARGV_LEN];
char argv4[MAXARGV_LEN];
int i, j, k, l;
for(i=16; cmd[i]!=' '; i++)
argv1[i-16] = cmd[i];
argv1[i-16] = '\0';
i++;
int bitmap_idx = argv1[strlen(argv1)-1]-'0';
for(j=i; cmd[j]!=' '; j++)
argv2[j-i] = cmd[j];
argv2[j-i] = '\0';
j++;
size_t start = atoi(argv2);
for(k=j; cmd[k]!=' '; k++)
argv3[k-j] = cmd[k];
argv3[k-j] = '\0';
k++;
size_t cnt = atoi(argv3);
for(l=k; l<=length; l++)
argv4[l-k] = cmd[l];
bool value;
if(!strcmp(argv4, "true"))
value = true;
else if(!strcmp(argv4, "false"))
value = false;
bool result = bitmap_contains(bm[bitmap_idx], start, cnt, value);
if(result)
puts("true");
else
puts("false");
}
else if(!strncmp(cmd, "bitmap_count ", 13)) {
char argv1[MAXARGV_LEN];
char argv2[MAXARGV_LEN];
char argv3[MAXARGV_LEN];
char argv4[MAXARGV_LEN];
int i, j, k, l;
for(i=13; cmd[i]!=' '; i++)
argv1[i-13] = cmd[i];
argv1[i-13] = '\0';
i++;
int bitmap_idx = argv1[strlen(argv1)-1]-'0';
for(j=i; cmd[j]!=' '; j++)
argv2[j-i] = cmd[j];
argv2[j-i] = '\0';
j++;
size_t start = atoi(argv2);
for(k=j; cmd[k]!=' '; k++)
argv3[k-j] = cmd[k];
argv3[k-j] = '\0';
k++;
size_t cnt = atoi(argv3);
for(l=k; l<=length; l++)
argv4[l-k] = cmd[l];
bool value;
if(!strcmp(argv4, "true"))
value = true;
else if(!strcmp(argv4, "false"))
value = false;
size_t result = bitmap_count(bm[bitmap_idx], start, cnt, value);
printf("%zu\n", result);
}
else if(!strncmp(cmd, "bitmap_dump ", 12)) {
char argv[MAXARGV_LEN];
int i;
for(i=12; i<=length; i++)
argv[i-12] = cmd[i];
int bitmap_idx = argv[strlen(argv)-1]-'0';
bitmap_dump(bm[bitmap_idx]);
}
else if(!strncmp(cmd, "bitmap_flip ", 12)) {
char argv1[MAXARGV_LEN];
char argv2[MAXARGV_LEN];
int i, j;
for(i=12; cmd[i]!=' '; i++)
argv1[i-12] = cmd[i];
argv1[i-12] = '\0';
i++;
int bitmap_idx = argv1[strlen(argv1)-1]-'0';
for(j=i; j<=length; j++)
argv2[j-i] = cmd[j];
size_t bit_idx = atoi(argv2);
bitmap_flip(bm[bitmap_idx], bit_idx);
}
else if(!strncmp(cmd, "bitmap_none ", 12)) {
char argv1[MAXARGV_LEN];
char argv2[MAXARGV_LEN];
char argv3[MAXARGV_LEN];
int i, j, k;
for(i=12; cmd[i]!=' '; i++)
argv1[i-12] = cmd[i];
argv1[i-12] = '\0';
i++;
int bitmap_idx = argv1[strlen(argv1)-1]-'0';
for(j=i; cmd[j]!=' '; j++)
argv2[j-i] = cmd[j];
argv2[j-i] = '\0';
j++;
size_t start = atoi(argv2);
for(k=j; k<=length; k++)
argv3[k-j] = cmd[k];
size_t cnt = atoi(argv3);
bool result = bitmap_none(bm[bitmap_idx], start, cnt);
if(result)
puts("true");
else
puts("false");
}
else if(!strncmp(cmd, "bitmap_reset ", 13)) {
char argv1[MAXARGV_LEN];
char argv2[MAXARGV_LEN];
int i, j;
for(i=13; cmd[i]!=' '; i++)
argv1[i-13] = cmd[i];
argv1[i-13] = '\0';
i++;
int bitmap_idx = argv1[strlen(argv1)-1]-'0';
for(j=i; j<=length; j++)
argv2[j-i] = cmd[j];
size_t bit_idx = atoi(argv2);
bitmap_reset(bm[bitmap_idx], bit_idx);
}
else if(!strncmp(cmd, "bitmap_scan_and_flip ", 21)) {
char argv1[MAXARGV_LEN];
char argv2[MAXARGV_LEN];
char argv3[MAXARGV_LEN];
char argv4[MAXARGV_LEN];
int i, j, k, l;
for(i=21; cmd[i]!=' '; i++)
argv1[i-21] = cmd[i];
argv1[i-21] = '\0';
i++;
int bitmap_idx = argv1[strlen(argv1)-1]-'0';
for(j=i; cmd[j]!=' '; j++)
argv2[j-i] = cmd[j];
argv2[j-i] = '\0';
j++;
size_t start = atoi(argv2);
for(k=j; cmd[k]!=' '; k++)
argv3[k-j] = cmd[k];
argv3[k-j] = '\0';
k++;
size_t cnt = atoi(argv3);
for(l=k; l<=length; l++)
argv4[l-k] = cmd[l];
bool value;
if(!strcmp(argv4, "true"))
value = true;
else if(!strcmp(argv4, "false"))
value = false;
printf("%zu\n", bitmap_scan_and_flip(bm[bitmap_idx], start, cnt, value));
}
else if(!strncmp(cmd, "bitmap_scan ", 12)) {
char argv1[MAXARGV_LEN];
char argv2[MAXARGV_LEN];
char argv3[MAXARGV_LEN];
char argv4[MAXARGV_LEN];
int i, j, k, l;
for(i=12; cmd[i]!=' '; i++)
argv1[i-12] = cmd[i];
argv1[i-12] = '\0';
i++;
int bitmap_idx = argv1[strlen(argv1)-1]-'0';
for(j=i; cmd[j]!=' '; j++)
argv2[j-i] = cmd[j];
argv2[j-i] = '\0';
j++;
size_t start = atoi(argv2);
for(k=j; cmd[k]!=' '; k++)
argv3[k-j] = cmd[k];
argv3[k-j] = '\0';
k++;
size_t cnt = atoi(argv3);
for(l=k; l<=length; l++)
argv4[l-k] = cmd[l];
bool value;
if(!strcmp(argv4, "true"))
value = true;
else if(!strcmp(argv4, "false"))
value = false;
printf("%zu\n", bitmap_scan(bm[bitmap_idx], start, cnt, value));
}
else if(!strncmp(cmd, "bitmap_set_all ", 15)) {
char argv1[MAXARGV_LEN];
char argv2[MAXARGV_LEN];
int i, j;
for(i=15; cmd[i]!=' '; i++)
argv1[i-15] = cmd[i];
argv1[i-15] = '\0';
i++;
int bitmap_idx = argv1[strlen(argv1)-1]-'0';
for(j=i; j<=length; j++)
argv2[j-i] = cmd[j];
bool value;
if(!strcmp(argv2, "true"))
value = true;
else if(!strcmp(argv2, "false"))
value = false;
bitmap_set_all(bm[bitmap_idx], value);
}
else if(!strncmp(cmd, "bitmap_set ", 11)) {
char argv1[MAXARGV_LEN];
char argv2[MAXARGV_LEN];
char argv3[MAXARGV_LEN];
int i, j, k;
for(i=11; cmd[i]!=' '; i++)
argv1[i-11] = cmd[i];
argv1[i-11] = '\0';
i++;
int bitmap_idx = argv1[strlen(argv1)-1]-'0';
for(j=i; cmd[j]!=' '; j++)
argv2[j-i] = cmd[j];
argv2[j-i] = '\0';
j++;
size_t idx = atoi(argv2);
for(k=j; k<=length; k++)
argv3[k-j] = cmd[k];
bool value;
if(!strcmp(argv3, "true"))
value = true;
else if(!strcmp(argv3, "false"))
value = false;
bitmap_set(bm[bitmap_idx], idx, value);
}
else if(!strncmp(cmd, "bitmap_set_multiple ", 20)) {
char argv1[MAXARGV_LEN];
char argv2[MAXARGV_LEN];
char argv3[MAXARGV_LEN];
char argv4[MAXARGV_LEN];
int i, j, k, l;
for(i=20; cmd[i]!=' '; i++)
argv1[i-20] = cmd[i];
argv1[i-20] = '\0';
i++;
int bitmap_idx = argv1[strlen(argv1)-1]-'0';
for(j=i; cmd[j]!=' '; j++)
argv2[j-i] = cmd[j];
argv2[j-i] = '\0';
j++;
size_t start = atoi(argv2);
for(k=j; cmd[k]!=' '; k++)
argv3[k-j] = cmd[k];
argv3[k-j] = '\0';
k++;
size_t cnt = atoi(argv3);
for(l=k; l<=length; l++)
argv4[l-k] = cmd[l];
bool value;
if(!strcmp(argv4, "true"))
value = true;
else if(!strcmp(argv4, "false"))
value = false;
bitmap_set_multiple(bm[bitmap_idx], start, cnt, value);
}
else if(!strncmp(cmd, "bitmap_size ", 12)) {
char argv[MAXARGV_LEN];
int i;
for(i=12; i<=length; i++)
argv[i-12] = cmd[i];
int bitmap_idx = argv[strlen(argv)-1]-'0';
printf("%zu\n", bitmap_size(bm[bitmap_idx]));
}
else if(!strncmp(cmd, "bitmap_test ", 12)) {
char argv1[MAXARGV_LEN];
char argv2[MAXARGV_LEN];
int i, j;
for(i=12; cmd[i]!=' '; i++)
argv1[i-12] = cmd[i];
argv1[i-12] = '\0';
i++;
int bitmap_idx = argv1[strlen(argv1)-1]-'0';
for(j=i; j<=length; j++)
argv2[j-i] = cmd[j];
size_t idx = atoi(argv2);
bool result = bitmap_test(bm[bitmap_idx], idx);
if(result)
puts("true");
else
puts("false");
}
else if(!strncmp(cmd, "bitmap_expand ", 14)) {
char argv1[MAXARGV_LEN];
char argv2[MAXARGV_LEN];
int i, j;
for(i=14; cmd[i]!=' '; i++)
argv1[i-14] = cmd[i];
argv1[i-14] = '\0';
int bitmap_idx = argv1[strlen(argv2)-1]-'0';
for(j=i; j<=length; j++)
argv2[j-i] = cmd[j];
int size = atoi(argv2);
bm[bitmap_idx] = bitmap_expand(bm[bitmap_idx], size);
}
}
return 0;
}
|
C
|
#include <stdio.h>
#include <string.h>
int main(void){
char answer[50];
//string 같은 경우에 &를 쓰지는 않는다. 왜냐하면 처음요소의 주소 자체이기 때문이다.
scanf("%s" , answer);
printf("hello, %s", answer);
return 0;
}
|
C
|
#include "my_tpl_lhash.H"
#include <iostream>
struct Data : public LhashBucket<int>
{
int data_member;
Data(int _key, int _data) :
LhashBucket<int>(_key),
data_member(_data)
{
// empty
}
};
unsigned long hash_fct(const int & key)
{
return key;
}
int main()
{
LhashTable<int> table(hash_fct);
int i;
for (i=0; i<1000; i++)
{
Data * data = AllocNew(*objectAlloc, Data) ((i%2)+1, i);
table.insert(data);
data = AllocNew(*objectAlloc, Data) (12, i);
table.insert(data);
}
int counter = 0;
for (i=1; i<=2; i++)
{
Data * searched_data = static_cast<Data*>(table.search(12)),
* cursor;
cursor = searched_data;
do
{
counter++;
cout << "Key: <" << cursor->getKey() << "> Data: " <<
cursor->data_member << endl;
cursor = static_cast<Data*>(table.searchPrev(cursor));
} while (cursor != searched_data);
}
cout << "Total number of records: " << counter << endl;
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
int main()
{
long unsigned int n,s=1,j=0,t,i;
printf("enter no ");
scanf(" %d", &n);
for(i=1; ; i++){
t=s;
s +=j;
j=t;
if(n==s){printf("yes");break;}else
if(s>n){printf("no");break;}else{continue;}}
return 0;
}
|
C
|
/**********************************************************************************************************
*ļCmd_process.c
*ʱ: 2012-10-18
*: ںTCPúͲѯָ
*
* ˾
**********************************************************************************************************/
#include "cmd_process.h"
/********************************************************************************************************
** : cmd_check
** : УַǷȷ
********************************************************************************************************/
static uint16 cmd_check(const char* sprintf_buf)
{
uint16 i;
uint16 cnt=0;
uint16 sum=0;
unsigned char checknum;
for(i = 2 ;i < UART_RCV_BUF_LEN;i++)
{
if((sprintf_buf[i] == 0x0D)&&(sprintf_buf[i+1] == 0x0a))
{
checknum = sprintf_buf[i-1]&0xff; //ȡУ
cnt = i-1; //ָֽ
break;
}
}
if(cnt)
{
for(i = 0 ;i < cnt ;i++)
{
sum+=sprintf_buf[i]; //ֽ
}
if(checknum==(sum&0xff)) //УȽ
{
cnt+=3; //Уȷ
}else
{
cnt = 0; //Уʧ
}
}
return cnt;
}
/********************************************************************************************************
** : creat_ch
** : ַתΪУַ +У루1ֽڣ+0x0D+0x0A
********************************************************************************************************/
uint16 creat_ch(char *dest,char *src)
{
char *cp;
uint16 cnt = 0;
uint16 sum = 0;
cp = src;
while(*cp != '\0')
{
sum+=*cp;
cnt++;
cp++;
}
memcpy(dest,src,cnt);
dest[cnt] &= 0x00;
dest[cnt] |= (sum&0xff);
dest[cnt+1] = 0x0D;
dest[cnt+2] = 0x0A;
cnt+=3;
return cnt;
}
/********************************************************************************************************
** : cmd_process
** : ָ
********************************************************************************************************/
int cmd_process( char* sprintf_buf ,int *str_len)
{
int send_To_uart = 0; //ѡUART-2===ָУ-1=====ûиָ0===01x===1x·
CMD_ID cmdid=ERR; //ָö
uint16 len; //ַ
uint8 i=0;
uint8 num=0; //ͨţ洢ַת
uint8 channel1=0,channel2=0; //洢
char string_Cache[12]={'\0'}; //ַ
char string_Buf[UART_RCV_BUF_LEN]={0}; //洢δУַ
len = cmd_check(sprintf_buf); //ָУ
if(!len)
{
//*str_len = creat_ch(sprintf_buf,"CHECK_ERROR");
err(0);
return -1; //Уʧܷ0
}
if(strstr(&sprintf_buf[0], "GETVERSION") != NULL)
{
cmdid = GETVERSION; //ȡ汾
}
else if(strstr(&sprintf_buf[0], "OK") != NULL)
{
if(sprintf_buf[2]=='C')
{
cmdid = OKCH; //ҵ̷صͨóɹ
}
else if(sprintf_buf[2]=='S')
{
cmdid = OKSETSW; //ҵ̷ضͨóɹ
}
else if(sprintf_buf[2]=='R')
{
cmdid = OKRST;
}
}
else if(strstr(&sprintf_buf[0], "SETSW") != NULL)
{
cmdid = SETSW; //·л
}
else if(strstr(&sprintf_buf[0], "CH") != NULL)
{
cmdid = CH; //·л
}
else if(strstr(&sprintf_buf[0], "GETSW") != NULL)
{
if(sprintf_buf[5]=='A') //ѯй·
{
cmdid = GETSWA;
}else
{
cmdid = GETSW; //ѯӦ·
}
}
else if(strstr(&sprintf_buf[0], "RST") != NULL)
{
cmdid = RST; //·λ
}
#ifdef MASTER_CPU
switch(cmdid)
{
case ERR:{
err(1);
send_To_uart = -2; //Ӵ0
}
break;
/****ذ汾****/
// GETVERSION
case GETVERSION:{
//0ذ汾ţ
*str_len = creat_ch(sprintf_buf,(char *)SVersion);
send_To_uart = 0;
//Ӵ0
}
break;
/****ùͨתҵ****/
// SETSW xx~xx,xx~xx
case SETSW:{
*str_len =len;
send_To_uart = 0;
}
break;
/****õ·ͨתҵ****/
//CHxx~CHyy
case CH:{
*str_len =len;
send_To_uart = 0;
}
break;
/****ѯͨ*****/
//GETSWxx---ѯ·GETSWA-----ѯͨ
case GETSW:
case GETSWA:{
if(cmdid==GETSW) //·ѯָ
{
num = (uint8)(sprintf_buf[5]-'0')*10;
num += (uint8)(sprintf_buf[6]-'0');
if(num == 0)
{
;
}
else
{
if(EPROM.Channel[num-1] != 0) //numΪͨEPROM.Channel[num-1]Ϊͨ
{
//תΪַʽCHxx~CHyy;
sprintf(string_Buf,"%s%02d%s%s%02d","CH",(int )num,"~","CH",(int)EPROM.Channel[num-1]);
}else
{
sprintf(string_Buf,"%s%02d%s%s%02d","CH",(int )num,"~","CH",num);
}
}
}
else if(cmdid==GETSWA) //ͨѯָ
{
for(i =0;i< MAX_CHANNEL;i++) //MAX_CHANNELͨ
{
if(EPROM.Channel[i]!=0) //EPROM.Channel[i]==0ʾͨiӶϿ
{
sprintf(string_Cache,"%s%02d%s%s%02d","CH",(int)(i+1),"~","CH",(int)EPROM.Channel[i]);
}else
{
sprintf(string_Cache,"%s%02d%s%s%02d","CH",(int)(i+1),"~","CH",0);
}
strcat(string_Buf,string_Cache);
}
}
/****ַУ0D 0A****/
*str_len =(int)creat_ch(sprintf_buf,string_Buf);
send_To_uart = 0;
}
break;
/****λָ****/
case RST:{
reset(); //Ӵ1͵ҵCPU
}
break;
/****ָΪҵ̷أһɹظָʽ£****/
/**** OKCHxx~CHyy+У+0x0D+0x0A ****/
case OKCH:{ //ͨóɹ
channel1 = ((uint8)(sprintf_buf[4]-'0'))*10+((uint8)(sprintf_buf[5]-'0'));
channel2 = ((uint8)(sprintf_buf[9]-'0'))*10+((uint8)(sprintf_buf[10]-'0'));
EPROM.Channel[channel1-1]=channel2;
Save_To_EPROM((uint8 *)&EPROM.Channel[channel1-1],1);//洢ͨ״̬channelͨӵchannel2ͨ
*str_len = len;
send_To_uart = 0;
}
break;
/**** ͨ****/
/**** OKSETSW xx~yy,nn~mm,ii~jj+У+0x0D+0x0A ****/
case OKSETSW:{
for(i=8;i<len-6;i+=6)
{
channel1 = ((uint8)(sprintf_buf[i]-'0'))*10+((uint8)(sprintf_buf[i+1]-'0'));
channel2 = ((uint8)(sprintf_buf[i+3]-'0'))*10+((uint8)(sprintf_buf[i+4]-'0'));
EPROM.Channel[channel1-1]=channel2;
Save_To_EPROM((uint8 *)&EPROM.Channel[channel1-1],1);
}
*str_len = len;
//*str_len = creat_ch(sprintf_buf,"OK");
send_To_uart = 0;
}
break;
case OKRST:{
}
break;
default:break;
}
#endif
return send_To_uart;
}
|
C
|
#include<stdio.h>
#include<stdlib.h>
int add(int a, int b, int c){
printf("Value a: %d \n", a);
printf("Value b: %d \n", b);
printf("Value c: %d \n", c);
return a + b + c;
}
int main(){
int a = 1;
int b = 2;
int c = 3;
int sum = add(a, b, c);
printf("Sum = %d\n", sum);
return 0;
}
|
C
|
#include<stdio.h>
int conditional(int x,int y,int z)
{
return ((x&y)|((~x)&z));
}
int main()
{
int x,y,z;
scanf("%d%d%d",&x,&y,&z);
int a=conditional(x,y,z);
printf("%d",a);
}
|
C
|
/*
Author: Levana Scirai
Task1 for C
File h of myMath
*/
float add(float x , float y); //returns x + y
float sub(float x , float y);// returns x - y
double mul(double x , int y); //returns y*x
double div(double x, int y);//returns x/y
double Exp(int x); // Expondential _ Fuction
double Pow(double x , int y); // power
|
C
|
#include<stdio.h>
#include<math.h>
long flag[]={0,2,4,9,16,25,64,289,729,1681,2401,3481,4096,5041,7921,10201,15625,17161,27889,28561,29929,65536,83521,85849,146689,262144,279841,458329,491401,531441,552049,579121,597529,683929,703921,707281,734449,829921,1190281};
long binary(long a[],long m,long l,long u){
long mid;
if(l<=u)
{
mid=(l+u)/2;
if(a[mid]<=m && a[mid+1]>m)
return mid;
else if(a[mid]>m && a[mid-1]<=m)
return (mid-1);
else if(a[mid]>m)
return binary(a,m,l,mid-1);
else
return binary(a,m,mid+1,u);
}
return 0;
}
long bin(long a[],long m,long l,long u){
long mid;
if(l<=u)
{
mid=(l+u)/2;
if(a[mid]==m)
return (mid-1);
else if(a[mid]<m && a[mid+1]>m)
return mid;
else if(a[mid]>m && a[mid-1]<m)
return (mid-1);
else if(a[mid]>m)
return bin(a,m,l,mid-1);
else
return bin(a,m,mid+1,u);
}
return 0;
}
int main()
{
int t;
long a,b,d;
scanf("%d",&t);
while(t--)
{
scanf("%ld %ld",&a,&b);
d=binary(flag,b,0,38)-bin(flag,a,0,38);
printf("%ld\n",d);
}
return(0);
}
|
C
|
#define _CRT_SECURE_NO_WARNINGS 1
#define _CRT_NONSTDC_NO_DEPRECATE 1
#include "stdio.h"
#include "stdlib.h"
#include "string.h"
#include "ctype.h"
#include "limits.h"
#include "math.h"
#include "stdbool.h"
void caclulate(int *nums, int numsSize, int index, int S, int sum, int *cnt)
{
if (index == numsSize)
*cnt += (sum == S);
else
{
caclulate(nums, numsSize, index + 1, S, sum + nums[index], cnt);
caclulate(nums, numsSize, index + 1, S, sum - nums[index], cnt);
}
}
int findTargetSumWays(int* nums, int numsSize, int S){
int cnt = 0;
caclulate(nums, numsSize, 0, S, 0, &cnt);
return cnt;
}
|
C
|
#include "/players/jaraxle/define.h"
inherit "/players/jaraxle/room.c";
reset(arg) {
if(arg) return;
set_light(1);
short_desc = "Third Earth";
long_desc =
" This mideastern edge of the forest is quite tame and calm. The\n"+
"trees make a tall, close line along the edge of the forest barring\n"+
"venture further to the east. The grass is uneven, yet clear of forest\n"+
"debris. Groups of gathering flowers grow in sunlit patches to the north\n"+
"and south. A clear trail leads off to the western edge.\n";
items = ({
"flowers","Small groups of dasies and dandelions grow in the sunlight that creeps through the treetops",
"edge","The eastern edge of the forest is protected by an unpassable assemblage of trees",
"forest","High reaching trees with thick branches waving slowly in the wind",
"trees","Tall trees with thick branches surround the forest. The trees are thickest to the east, where most of the passage is blocked.\nYou notice a thin break in a trees",
"break","A gap between trees that looks like a path",
"path","A thin path you can "+HIW+"walk"+NORM+"",
"branches","Large branches which grow low to the ground.\nPerhaps you can use them to "+HIW+"climb"+NORM+" up the "+HIW+"trees"+NORM+" with",
"grass","The grass grows in uneven heights up to six inches tall",
"trail","A trail made of trampled grass from consistent travel",
"trampled grass","Many footsteps have traveled this path",
"dasies","Petit white and yellow dasies growing freely",
"dandelions","Large puffs of dandelion seeds grow abundantly"
});
dest_dir = ({
"/players/jaraxle/3rd/warrior/rooms/room2.c","west",
"/players/jaraxle/3rd/warrior/rooms/roome3.c","north",
"/players/jaraxle/3rd/warrior/rooms/roome.c","south",
"/players/jaraxle/3rd/warrior/rooms/entrance.c","southwest",
"/players/jaraxle/3rd/warrior/rooms/room3.c","northwest",
});
}
init() {
::init();
add_action("climb","climb");
add_action("walk","walk");
add_action("walk","squeeze");
}
climb(arg) {
if(arg == "trees" || arg == "tree") {
write("You climb up the branches into the tree.\n");
this_player()->move_player("climbs up a tree#/players/jaraxle/3rd/warrior/rooms/treee2");
return 1; }
write("Climb what?\n"); return 1; }
walk(arg){
if(arg == "path" || arg == "east") {
write("You squeeze between the trees onto a path to the east.\n");
this_player()->move_player("walks the eastern path#/players/jaraxle/3rd/volcano/rooms/path");
return 1; }
notify_fail("Walk where?\n"); return 0; }
|
C
|
// Array exercise Q3
#include <stdio.h>
int main() {
int mata[5];
printf("\nPlease enter 5 integers separated by space:\n");
for(int i=0; i<5 ; i++) scanf("%d",&mata[i]);
printf("Content of array are:\n");
for(int i=0; i<5 ; i++)
printf("%d\n",mata[i]);
return 0;
}
|
C
|
#include<stdio.h>
int main()
{
int i, n, score[1000];
printf("enter the value of n : ");
scanf("%d", &n);
for(i=0; i<n; i++)
scanf("%d", &score[i]);
int max = score[0]; int min = score[0];
int max_count =0, min_count=0;
for(i=0; i<n; i++){
if(score[i]>max){
max = score[i];
max_count++;
}
if(score[i]<min){
min = score[i];
min_count++;
}
}
printf("%d %d", max_count, min_count);
}
|
C
|
#include <stdlib.h>
/*
Returns a pointer to the first occurrence of character in the C string str.
The terminating null-character is considered part of the C string. Therefore,
it can also be located to retrieve a pointer to the end of a string.
@param str the string to be searched
@param len the number of characters to search
@param character the character to search for
@returns A pointer to the first occurrence of character in str.
If the value is not found, the function returns a null pointer.
*/
const char *strnchr(const char *str, size_t len, int character) {
const char *end = str + len;
char c = (char)character;
do {
if (*str == c) {
return str;
}
} while (++str <= end);
return NULL;
}
|
C
|
/**************************************************************************
*
* auxi.h
*
* Header file for auxi.c
*
* (C) 1999 Dan Foygel (dfoygel@cs.cmu.edu)
* Carnegie Mellon University
*
* Based heavily on code written by Dimitris Margaritis (dmarg@cs.cmu.edu)
*
**************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <sys/time.h>
#include <unistd.h>
#include <math.h>
#ifndef AUX_H
#define AUX_H 1
/* Global variables. */
extern char *progname; /* Should be defined by all programs who call this
library, and should contain the program name. */
#define SYS_ERROR1(format, arg) \
{ \
char tmp_buf[256]; \
sprintf(tmp_buf, "%s: %s:%d %s(): " format, \
progname, __FILE__, __LINE__, __FUNCTION__, arg); \
perror(tmp_buf); \
exit(1); \
}
#define SYS_ERROR2(format, arg1, arg2) \
{ \
char tmp_buf[256]; \
sprintf(tmp_buf, "%s: %s:%d %s(): " format, \
progname, __FILE__, __LINE__, __FUNCTION__, arg1, arg2); \
perror(tmp_buf); \
exit(1); \
}
#define SYS_ERROR3(format, arg1, arg2, arg3) \
{ \
char tmp_buf[256]; \
sprintf(tmp_buf, "%s: %s:%d %s(): " format, \
progname, __FILE__, __LINE__, __FUNCTION__, arg1, arg2, arg3); \
perror(tmp_buf); \
exit(1); \
}
#define USER_ERROR1(format, arg) \
{ \
fprintf(stderr, "%s: %s:%d %s(): " format "\n", \
progname, __FILE__, __LINE__, __FUNCTION__, arg); \
exit(1); \
}
#define USER_ERROR2(format, arg1, arg2) \
{ \
fprintf(stderr, "%s: %s:%d %s(): " format "\n", \
progname, __FILE__, __LINE__, __FUNCTION__, arg1, arg2); \
exit(1); \
}
#define USER_ERROR3(format, arg1, arg2, arg3) \
{ \
fprintf(stderr, "%s: %s:%d %s(): " format "\n", \
progname, __FILE__, __LINE__, __FUNCTION__, arg1, arg2, arg3); \
exit(1); \
}
#ifndef SQUARE
#define SQUARE(x) ((x) * (x))
#endif // SQUARE
#ifndef ABS
#define ABS(x) (((x) > 0) ? (x) : -(x))
#endif // ABS
#ifndef MIN
#define MIN(x, y) (((x) < (y)) ? (x) : (y))
#endif // MIN
#ifndef MAX
#define MAX(x, y) (((x) > (y)) ? (x) : (y))
#endif // MAX
#define PI M_PI
#define DEG * 180.0 / PI /* Convert to degrees. */
#define RAD * PI / 180.0 /* Convert to radians. */
#ifdef sun
#define RAND_MAX (pow(2.0, 31.0) - 1.0)
#endif // sun
#ifndef EPSILON
#define EPSILON 0.005
#endif
/* Global variables. */
extern int random_seed;
/* Declarations. */
void *getmem(size_t bytes);
double uniform(double a, double b);
#endif // AUX_H
/**************************************************************************/
|
C
|
#include "inputs.h"
float getFloat(char* message)
{
float aux;
printf("%s",message);
scanf("%f",&aux);
return aux;
}
int getInt(char* message)
{
int aux;
printf("%s",message);
scanf("%d",&aux);
return aux;
}
char getChar(char* message)
{
char aux;
printf("%s",message);
fflush(stdin);
scanf("%c",&aux);
return aux;
}
//char getNumberRandom(int since , int until, int start)
//{
// if(start)
//srand (time(NULL));
// return since + (rand() % (until + 1 - since)) ;
//}
int isNumericFloat(char str[])
{
int i=0;
int cantidadPuntos=0;
while(str[i] != '\0')
{
if (str[i] == '.' && cantidadPuntos == 0)
{
cantidadPuntos++;
i++;
continue;
}
if(str[i] < '0' || str[i] > '9')
return 0;
i++;
}
return 1;
}
int isNumeric(char str[])
{
int i=0;
while(str[i] != '\0')
{
if(str[i] < '0' || str[i] > '9')
return 0;
i++;
}
return 1;
}
int isJustLetters(char str[])
{
int i=0;
while(str[i] != '\0')
{
if((str[i] != ' ') && (str[i] < 'a' || str[i] > 'z') && (str[i] < 'A' || str[i] > 'Z'))
return 0;
i++;
}
return 1;
}
int isAlfaNumeric(char str[])
{
int i=0;
while(str[i] != '\0')
{
if((str[i] != ' ') && (str[i] < 'a' || str[i] > 'z') && (str[i] < 'A' || str[i] > 'Z') && (str[i] < '0' || str[i] > '9'))
return 0;
i++;
}
return 1;
}
int isTelephone(char str[])
{
int i=0;
int contadorGuiones=0;
while(str[i] != '\0')
{
if((str[i] != ' ') && (str[i] != '-') && (str[i] < '0' || str[i] > '9'))
return 0;
if(str[i] == '-')
contadorGuiones++;
i++;
}
if(contadorGuiones==1) // debe tener un guion
return 1;
return 0;
}
void getString(char message[],char input[])
{
printf("%s",message);
scanf ("%s", input);
}
int getStringLetters(char message[],char input[])
{
char aux[256];
getString(message,aux);
if(isJustLetters(aux))
{
strcpy(input,aux);
return 1;
}
return 0;
}
int getStringNumbers(char message[],char input[])
{
char aux[256];
getString(message,aux);
if(isNumeric(aux))
{
strcpy(input,aux);
return 1;
}
return 0;
}
int getStringNumbersFloat(char mensaje[],char input[])
{
char aux[256];
getString(mensaje,aux);
if(isNumericFloat(aux))
{
strcpy(input,aux);
return 1;
}
return 0;
}
void getValidInt(char requestMessage[],char errorMessage[], int lowLimit, int hiLimit,int* input)
{
char auxStr[256];
while(1)
{
while(!getStringNumbers(requestMessage,auxStr))
{
printf ("%s\n",errorMessage);
continue;
}
*input = atoi(auxStr);
if(*input < lowLimit || *input > hiLimit)
{
printf ("El numero del debe ser mayor a %d y menor a %d\n",lowLimit,hiLimit);
continue;
}
break;
}
}
/**
* \brief Limpia el stdin, similar a fflush
* \param -
* \return -
*
*/
void cleanStdin(void)
{
int c;
do
{
c = getchar();
}
while (c != '\n' && c != EOF);
}
void getValidString(char requestMessage[],char errorMessage[],int lowLimit, int hiLimit, char* input)
{
int lenString;//verifica que sea el largo correspondiente
char auxString[256];//sino hago un aux me dice que hay un desbordamiento en la pila
//*** stack smashing detected ***: <unknown> terminated Aborted (core dumped)
while(1)
{
if (!getStringLetters(requestMessage,auxString))
{
printf ("%s\n",errorMessage);
continue;
}
lenString=strlen(auxString);
if(lenString < lowLimit || lenString > hiLimit)
{
printf ("El caracter del debe ser mayor a %d y menor a %d\n",lowLimit,hiLimit);
continue;
}
stringToLower(auxString);
firstToUpper(auxString);
strcpy(input,auxString);//si cumple con todas las normativas recien lo asigno a input
break;
}
}
void firstToUpper(char name[])
{
stringToLower(name);
name[0] = toupper(name[0]);
int j=0;
while(name[j]!='\0')
{
if(name[j]==' ')
{
name[j+1]= toupper (name[j+1]);
}
j++;
}
}
void stringToUpper (char letters[])
{
int i; //variable de control que permite revisar el string
for (i=0; letters[i] != '\0'; i++)
{
letters[i] = toupper(letters[i]);
}
}
void stringToLower (char letters[])
{
int i; // variable de control que permite revisar el string
for (i=0; letters[i] != '\0'; i++)
{
letters[i] = tolower(letters[i]);
}
}
|
C
|
/*
============================================================================
Name : factorial.c
Author : Myrella Alejandra
Version :
Copyright : Your copyright notice
Description : Hello OpenMP World in C
============================================================================
*/
#include <omp.h>
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
/**
* Hello OpenMP World prints the number of threads and the current thread id
*/
int thread_count;
int n;
long fact;
void* Thread_factorial(void* rank);
//void Get_args(int argc, char* argv[]);
int main(int argc, char *argv[]) {
long thread;
pthread_t* thread_handles;
n = 10;
//Get_args(argc, argv);
thread_count = strtol(argv[1], NULL, 10);
thread_handles = malloc(thread_count * sizeof(pthread_t));
//printf("Escriba el numero del factorial: ");
fact = 1;
for (thread = 0; thread < thread_count; thread++)
pthread_create(&thread_handles[thread], NULL, Thread_factorial,
(void*) thread);
for (thread = 0; thread < thread_count; thread++)
pthread_join(thread_handles[thread], NULL);
printf("El factorial de %d es %d\n", n, fact);
/* This creates a team of threads; each thread has own copy of variables */
free(thread_handles);
return 0;
}
void* Thread_factorial(void* rank) {
long my_rank = (long) rank;
long my_fact=1;
long long i;
long long my_n = n / thread_count;
long long my_first_i = my_n * my_rank + 1;
long long my_last_i = my_first_i + (my_n - 1);
for (i = my_first_i; i <= my_last_i; i++) {
my_fact = my_fact * i;
}
fact = fact* my_fact;
return NULL;
} /* Thread_sum */
|
C
|
#include <stdio.h>
int main (void)
{
extern char **environ;
char **p;
for (p = environ; *p; p++)
printf("%s\n", *p);
return (0);
}
|
C
|
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/mman.h>
#include <unistd.h>
#include <pthread.h>
#include <string.h>
#include "warehousesim.h"
// stations
struct station stations[4];
package *pileHead = NULL; // pile of pending packages
// tracking packages completed
int packagesCompleted = 0;
int bluePackages = 0;
int redPackages = 0;
int greenPackages = 0;
int yellowPackages = 0;
// locks/mutexes
pthread_mutex_t grabMtx = PTHREAD_MUTEX_INITIALIZER; // mutex for grabbing packages
pthread_mutex_t stationMtx = PTHREAD_MUTEX_INITIALIZER; // mutex for getting on a station
pthread_mutex_t doneMtx = PTHREAD_MUTEX_INITIALIZER;
// condition variables for conveyor and robot queue
pthread_cond_t readyCond = PTHREAD_COND_INITIALIZER;
pthread_cond_t teamConds[4] = {PTHREAD_COND_INITIALIZER, PTHREAD_COND_INITIALIZER, PTHREAD_COND_INITIALIZER, PTHREAD_COND_INITIALIZER};
void incrementPackages(int teamNum)
{
// keeps track of the number of packages each team has completed globally
packagesCompleted++;
switch (teamNum)
{
case 0:
bluePackages++;
break;
case 1:
redPackages++;
break;
case 2:
greenPackages++;
break;
case 3:
yellowPackages++;
break;
}
return;
}
// main thread function, handles robot robots grabbing packages, doing work, moving packages, and joining the queue
void *slaveAway(void *arg)
{
robotNode *robot = ((robotNode *)arg); // casting input to type robot
package *robotPackage = NULL; // just to prevent ptr->package->whatever
station *currStation = NULL; // pointer to station robot is working at or wants to move to
int robotId = robot->robotId; // makes accessing the robot's id easier
int robotTeam = robot->team; // makes accessing the robot's team number easier
char *teamName = robot->teamName; // makes accessing the robot's team name easier
pthread_cond_t *busyCond = &teamConds[robotTeam]; // setting the robot queue condition variable based on the robot's team
while (1)
{
while (1)
{
if (pileHead == NULL)
{
return NULL; // terminate thread when there are no more packages
}
pthread_mutex_lock(&grabMtx);
// grabbing a package should be protected
if (robot->isFree)
{
break; // enter package grabbing logic if robot is free and package is available, grabMtx remains locked to make grabbing package atomic
}
else
{
printf("BUSY: Currently not robot %s #%d's turn\n",
teamName, robotId);
pthread_cond_wait(busyCond, &grabMtx); // if it is not robot's turn to grab a package, relinquish the CPU until a robot on the same team completes a package
pthread_mutex_unlock(&grabMtx);
}
}
robot->isFree = 0; // once a robot grabs a package they cannot grab another
robot->package = pileHead; // store package into robot to work on
robotPackage = robot->package; // store reference to package in robotPackage
printf("GRAB: Robot %s #%d grabbed package %d\n",
teamName, robotId, robotPackage->packageNum); // prints info about robot id and package id when a robot grabs a package
printf("INST: Package #%d has a total of %d instructions\n",
robotPackage->packageNum, robotPackage->instructionCount); // prints the number of instructions the given package has
printf("INFO: Package #%d has the following instructions: ", robotPackage->packageNum);
printf("[");
for (int i = 0; i < robotPackage->instructionCount; i++)
// prints each of the instructions of the package in order
{
if (i)
printf(", ");
int temp;
temp = robotPackage->custInstructions[i] - 1;
printf("%s", temp == WEIGHT ? "Weight" : temp == BARCODE ? "Barcode"
: temp == XRAY ? "X-ray"
: "Jostle");
}
printf("]\n");
pileHead = pileHead->nextPackage; // pile goes to next package for another robot to grab
pthread_mutex_unlock(&grabMtx);
printf("STRT: Robot %s #%d is starting to work on package %d\n",
teamName, robotId, robotPackage->packageNum); // prints that the robot is about to begin moving and working on packages
for (int i = 0; i < robotPackage->instructionCount; i++) // cycles through each instruction for the given robotPackage
{
currStation = stations + (robotPackage->custInstructions[i] - 1);
printf("MOVE: Robot %s #%d is moving Package #%d to Station %s\n",
teamName, robotId, robotPackage->packageNum, currStation->stationName); // prints that the robot is about to attempt to move a package, either from the PPP to a station or along the conveyor system
/* below is the conveyor system */
int stationFreeFlag = 1;
while (1)
{
pthread_mutex_lock(&stationMtx); // checking whether or not a station is free must be atomic so no two robots and working at the same place at the same time
stationFreeFlag = currStation->isFree;
if (stationFreeFlag) // checks if the incoming station is free
{
usleep(rand() % (10000 - 1000 + 1) + 1000); // Conveyor belt - takes random time
currStation->isFree = 0; // if a robot can move to a station, that station is no longer free
pthread_mutex_unlock(&stationMtx);
break; // enter working-on-package logic
}
else
{
printf("WAIT: Station %s is currently busy. Robot %s #%d waiting with Package #%d\n",
currStation->stationName, teamName, robotId, robotPackage->packageNum); // prints that the robot cannot move to its desired station because the station is busy
pthread_cond_wait(&readyCond, &stationMtx); // waits for a robot to finish working on a station before checking station availability again
pthread_mutex_unlock(&stationMtx);
}
}
printf("WORK: Robot %s #%d working on Package #%d at Station %s\n",
teamName, robotId, robotPackage->packageNum, currStation->stationName); // prints out that a working is doing work at a station
if (robotPackage->fragile == 1, strcmp(currStation->stationName, "Jostle") == 0)
{
printf("VLNT: Package #%d is fragile! Robot %s #%d is shaking the sh*t out of it\n",
robotPackage->packageNum, teamName, robotId); // shakes the package if necessary
}
usleep(rand() % (10000 - 1000 + 1) + 1000); // Work on package - random time
printf("DONE: Robot %s #%d is finished working on Package #%d at Station %s\n",
teamName, robotId, robotPackage->packageNum, currStation->stationName); // prints that a Robot finished working on a package at their station
printf("FREE: Station %s is now free\n", currStation->stationName); // prints that the station they were previously working on is now free
currStation->isFree = 1; // sets the current station to free, simulating the working picking up their package from the station
pthread_cond_broadcast(&readyCond); // broadcasts the condition variable to every Robot currently waiting on a station, allowing them to recheck if they can move where they want to go
}
robot->nextRobot->isFree = 1; // lets the next Robot in the queue know that it can now grab a package
pthread_mutex_lock(&doneMtx); // incrementing packages must be atomic
incrementPackages(robotTeam); // calls package incrementing helper function
pthread_mutex_unlock(&doneMtx); // grabbing a package should be protected
printf("CMLT: Robot %s #%d is finished working on Package #%d \n",
teamName, robotId, robotPackage->packageNum); // prints that a Robot is finished working on their package
pthread_cond_broadcast(busyCond); // lets the Robots in the Robot's team's queue know that they might be next in line
}
}
int main()
{
robotNode *robotsHead[4] = {NULL, NULL, NULL, NULL}; // initializes the robot queue heads
int randSeed = getSeed(); // calls helper function to extract seed from seed.txt
printf("Random seed is: %d\n", randSeed);
sleep(1);
printf("Seeding the randomizer...\n");
sleep(1);
srand(randSeed); // seed the randomizer
// number of packageCount, randomly generated (current upper and lower bounds are 80 to adhere to project specs)
int packageCount = rand() % (UPPER - LOWER + 1) + LOWER;
printf("Total number of packages to be processed is: %d\n", packageCount);
// sleep(1);
// initialize everything
createPackages(packageCount, &pileHead); // calls helper function to create PPP
createStations(stations); // calls helper function to create each station
for (int i = 0; i < NUM_TEAMS; i++)
{
createRobots(&robotsHead[i], i); // creates each robot queue and stores 10 robots in each
}
pthread_t *robotThreads = (pthread_t *)malloc(NUM_ROBOTS * NUM_TEAMS * sizeof(pthread_t)); // allocating enough memory for each pthread (number of robots per team * number of teams * size of pthread)
// spawn threads (40 threads, 4 teams 10 robots each team)
printf("-----------Beginning warehouse simulation-----------\n");
sleep(1);
int spawnIndex = 0; // keeps track of which thread is being spawned
for (int i = 0; i < NUM_TEAMS; i++) // loops through each team
{
for (int j = 0; j < NUM_ROBOTS; j++) // loops through each robot in each team
{
pthread_create(&robotThreads[spawnIndex], NULL, slaveAway, robotsHead[i]);
robotsHead[i] = robotsHead[i]->nextRobot;
spawnIndex++;
}
}
// join threads
int joinIndex = 0;
for (int i = 0; i < NUM_TEAMS; i++)
{
for (int j = 0; j < NUM_ROBOTS; j++)
{
pthread_join(robotThreads[joinIndex], NULL);
joinIndex++;
}
}
printf("----------------------------------------------------------------\n");
printf("Packages requested: %d\tPackages completed: %d \n", packageCount, packagesCompleted);
printf("Blue Processed: %d\tRed Processed: %d\tGreen Processed: %d\tYellow Processed: %d\n",
bluePackages, redPackages, greenPackages, yellowPackages);
printf("--------------------------Simulation Over-----------------------\n");
free(robotThreads);
return 0;
}
|
C
|
/**
有21根火柴,两人依次取,每次每人只可取走1〜4根,不能多取,也不能不取,谁取到最后一根火柴谁输。
请编写一个人机对弈程序,要求人先取,计算机后取;计算机为“常胜将军”。
*/
#include <stdio.h>
int main()
{
int computer, people, spare = 21;
printf(" -----------------------------------------\n");
printf(" -------- 你不能战胜我,不信试试 --------\n");
printf(" -----------------------------------------\n\n");
printf("Game begin:\n\n");
while(1)
{
printf(" ---------- 目前还有火柴 %d 根 ----------\n", spare);
printf("People:");
scanf("%d", &people);
if(people<1 || people>4 || people>spare)
{
printf("你违规了,你取的火柴数有问题!\n\n");
continue;
}
spare = spare - people;
if( spare==0 )
{
printf("\nComputer win! Game Over!\n");
break;
}
computer = 5 - people;
spare = spare - computer;
printf("Computer:%d \n", computer);
if( spare==0 )
{
printf("\nPeople win! Game Over!\n");
break;
}
}
return 0;
}
//运行结果:
/**
-----------------------------------------
-------- 你不能战胜我,不信试试 --------
-----------------------------------------
Game begin:
---------- 目前还有火柴 21 根 ----------
People:1
Computer:4
---------- 目前还有火柴 16 根 ----------
People:3
Computer:2
---------- 目前还有火柴 11 根 ----------
People:2
Computer:3
---------- 目前还有火柴 6 根 ----------
People:4
Computer:1
---------- 目前还有火柴 1 根 ----------
People:1
Computer win! Game Over!
*/
|
C
|
//计算均差
#define _CRT_SECURE_NO_WARNINGS 1
#include <stdio.h>
#include <math.h>
double calculateSD(double data[]);
int main()
{
int i;
double data[10];
printf("输入10个元素: ");
for (i = 0; i < 10; ++i)
scanf("%lf", &data[i]);
printf("\n标准偏差 = %.6lf\n", calculateSD(data));
return 0;
}
double calculateSD(double data[])
{
double sum = 0.0, mean, standardDeviation = 0.0;
int i;
for (i = 0; i < 10; ++i)
{
sum += data[i];
}
mean = sum / 10;
for (i = 0; i < 10; ++i)
standardDeviation += pow(data[i] - mean, 2);
return sqrt(standardDeviation / 10);
}
|
C
|
/************************
* 模块参数的测试例子
* Author: zht
* Date: 2015-04-16
************************/
#include <linux/module.h>
static int abc = 5;
module_param(abc, int, 0644);
static char *name = "shrek";
module_param(name, charp, 0444);
static int test = 0;
module_param(test, bool, 0644);
static int sizes[] = {10, 20, 30, 40};
module_param_array(sizes, int, NULL, 0644);
static int __init my_init(void)
{
int i = 0;
printk("===In init()===\n");
printk("abc = %d; name is %s; test = %d\n", \
abc, name, test);
for (i=0; i<ARRAY_SIZE(sizes); i++)
printk("sizes[%d] = %d\n", i, sizes[i]);
return 0;
}
static void __exit my_exit(void)
{
int i;
printk("===In exit()===\n");
printk("abc = %d; name is %s; test = %d\n", \
abc, name, test);
for (i=0; i<ARRAY_SIZE(sizes); i++)
printk("sizes[%d] = %d\n", i, sizes[i]);
}
module_init(my_init);
module_exit(my_exit);
MODULE_AUTHOR("ZHT");
MODULE_LICENSE("GPL");
|
C
|
#include <stdio.h>
int main(void)
{
int x1, x2, x3, x4, x5, x6, x7, x8, x9, x10, x11, x12, x13, x14, x15, x16;
int row1_sum, row2_sum, row3_sum, row4_sum;
int column1_sum, column2_sum, column3_sum, column4_sum;
int diagonal_leftright_sum, diagonal_rightleft_sum;
printf("Enter the numbers from 1 to 16 in any order: ");
scanf("%d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d", &x1, &x2, &x3,
&x4, &x5, &x6, &x7, &x8, &x9, &x10, &x11,
&x12, &x13, &x14, &x15, &x16);
row1_sum = x1 + x2 + x3 + x4;
row2_sum = x5 + x6 + x7 + x8;
row3_sum = x9 + x10 + x11 + x12;
row4_sum = x13 + x14 + x15 + x16;
column1_sum = x1 + x5 + x9 + x13;
column2_sum = x2 + x6 + x10 + x14;
column3_sum = x3 + x7 + x11 + x15;
column4_sum = x4 + x8 + x12 + x16;
diagonal_leftright_sum = x1 + x6 + x11 + x16;
diagonal_rightleft_sum = x4 + x7 + x10 + x13;
printf("%d %d %d %d\n", x1, x2, x3, x4);
printf("%d %d %d %d\n", x5, x6, x7, x8);
printf("%d %d %d %d\n", x9, x10, x11, x12);
printf("%d %d %d %d\n", x13, x14, x15, x16);
printf("Row sums: %d %d %d %d\n", row1_sum, row2_sum, row3_sum, row4_sum);
printf("Column sums: %d %d %d %d\n", column1_sum, column2_sum, column3_sum
, column4_sum);
printf("Diagonal sums: %d %d\n", diagonal_leftright_sum,
diagonal_rightleft_sum);
return 0;
}
|
C
|
/*
** get_table.c for get_table.c in /home/rousse_i/rendu/CPE/Sudoki-Bi/src
**
** Made by mathis rousselot
** Login <rousse_i@epitech.net>
**
** Started on Sat Feb 27 10:42:06 2016 mathis rousselot
** Last update Sat Feb 27 14:34:14 2016 mathis rousselot
*/
typedef struct s_curs
{
int curs;
int curs_2;
int curs_3;
} t_curs;
int check_nbr(int ***tab, char carac, t_curs *curs, int nbr_su)
{
if (carac <= '9' && carac >= '0')
{
tab[curs->curs][curs->curs_2][curs->curs_3] = carac - '0';
curs->curs_3++;
}
else
{
tab[curs->curs][curs->curs_2][curs->curs_3] = 0;
curs->curs_3++;
}
if (curs->curs_3 == 9)
{
curs->curs_3 = 0;
curs->curs_2++;
}
if (curs->curs_2 == 9)
{
curs->curs_2 = 0;
curs->curs++;
}
if (curs->curs == nbr_su)
return (1);
return (0);
}
int get_table(int ***tab, char *str, int nbr_su)
{
t_curs curs;
int cont;
int nbr;
cont = 0;
curs.curs = 0;
curs.curs_2 = 0;
curs.curs_3 = 0;
nbr = 0;
while (str[cont] != '\0')
{
if ((cont >= 230 * nbr + 19 + nbr && cont <= 230 * (nbr + 1) - 19 + nbr)
&& cont % 21 <= 18 && cont % 21 % 2 != 1 && cont % 21 != 0)
if (check_nbr(tab, str[cont], &curs, nbr_su) == 1)
return (1);
if (cont == 230 + 230 * nbr + nbr)
nbr++;
cont++;
}
return (0);
}
|
C
|
#include <stdio.h>
int main()
{
int j,i,A[5],temp;
for(i=0;i<5;i++) {
scanf("%d",&A[i]);
}
//int steps=0;
for(i=0;i<4;i++) {
//steps++;
int swap=0;
for(j=0;j<4-i;j++) {
//steps++;
if(A[j]>A[j+1]){
swap++;
temp=A[j];
A[j]=A[j+1];
A[j+1]=temp;
}
}
if(swap ==0)
break;
}
for(i=0;i<5;i++)
printf("%d ",A[i]);
printf("\n");
//printf("Steps taken =%d\n",steps);
return 0;
}
|
C
|
// Lab08
// one_per_line
// Zixuan Guo (z5173593)
#include <stdio.h>
int main (void) {
printf("Enter a string: ");
char line[4096];
int i = 0;
fgets(line, 4096, stdin);
while (line[i] != '\n') {
printf("%c\n", line[i]);
i++;
}
return 0;
}
|
C
|
/*дһfun,Ĺ:ʵַ(ʹÿ⺯strcat),p2ַָӵp1ַָ
,ֱַ:
FirstString
SecondString
:FirstStringSecondString
ע:Դ¡
Ķmainеκ,ںfunĻд䡣
:*/
#include<stdio.h>
#include<stdlib.h>
void fun(char p1[],char p2[])
{
/***************Begin************/
int i=0,j=0;
for(;p1[i];i++);
for(;p2[j];j++) p1[i++]=p2[j];
p1[i]=0;
/*************** End ************/
}
int main()
{
FILE *wf,*in;
char s1[80],s2[40];
char p1[80]="FirstString",p2[40]="SecondString";
printf("Enter s1 and s2:\n") ;
scanf("%s%s",s1,s2);
printf("s1=%s\n",s1);
printf("s2=%s\n",s2);
printf("Invoke fun(s1,s2):\n");
fun(s1,s2);
printf("After invoking:\n");
printf("%s\n",s1);
/******************************/
in=fopen("in16.dat","r");
wf=fopen("out16.dat","w");
fscanf(in,"%s %s",p1,p2);
fun(p1,p2);
fprintf(wf,"%s",p1);
fclose(in);
fclose(wf);
/*****************************/
return 0;
}
|
C
|
//motors
int r_motor = 1 ;
int l_motor = 2 ;
//set default motor speed
int r_vel = 900;
int l_vel = 700;
int constrain_velocity ( int vel )
{
vel = vel > 1000 ? 1000 : ( vel < -1000 ? -1000 : vel) ; //if > 1000 constrain to to 1000, less then -1000 constrain to -1000
return vel;
}
int main()
{
int sensor_dif = 0 ;
int c_msg = 0 ;
int f_msg = 0 ;
int s_msg = 0 ;
set_each_analog_state(0,0,1,1,0,0,0,0); //disable internal pulldown resistor
sleep(0.02);
//start robot moving forward
mav( r_motor, r_vel );
mav( l_motor, l_vel );
while(1) //two states too close, too far
{
//too far from wall, turn toward wall
if (analog10(2) <= 600)
{
if( !f_msg ){ printf("too far from wall\n"); f_msg = 1; c_msg = 0; s_msg = 0; }
mav( r_motor, constrain_velocity( r_vel ));
mav( l_motor, constrain_velocity( l_vel + 80 )); //not same as too close to wall since l motor seems faster
}
//too close to wall, turn away from wall
else
{
if( !c_msg ){ printf("too close from wall\n"); c_msg = 1; f_msg = 0; s_msg = 0; }
mav( r_motor, constrain_velocity( r_vel + 100 ));
mav( l_motor, constrain_velocity( l_vel ));
}
}
return 0;
}
|
C
|
/**/
#include <stdio.h>
int
main(void)
{
int int1, int2, int3;
printf("Please enter 3 numbers separated by spaces > ");
scanf("%d%d%d", &int1, &int2, &int3);
if ((int1 < int2 && int1 > int3) || (int1 > int2 && int1 < int3))
printf("%d is the median\n", int1);
else if ((int2 < int3 && int2 > int1) || (int2 > int3 && int2 < int1))
printf("%d is the median\n", int2);
else
printf("%d is the median\n", int3);
return(0);
}
|
C
|
#include <stdio.h>
static int daytab[2][13] = {
{0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31},
{0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31},
};
/* judge if year is leap year */
int is_leap_year(int year) {
return ((year % 4 == 0 && year % 100 != 0) || year % 400 ==0);
}
/* day_of_year : set day of year by month & day */
int day_of_year(int year, int month, int day) {
if(year < 0) {
return -1;
}
if(month < 1 || month > 12) {
return -1;
}
if(day < 1) {
return -1;
}
int i, j;
i = is_leap_year(year) ? 0 : 1;
j = 1;
if(day > daytab[i][month]) {
return -1;
}
while(j < month) {
day += daytab[i][j];
j++;
}
return day;
}
/* set month, day from day of year */
void month_day(int year, int year_day, int *p_month, int *p_day) {
if(year > 0 && year_day < 366) {
int i, j;
i = is_leap_year(year) ? 0 : 1;
j = 1;
while(j <= 12) {
if(year_day > daytab[i][j]) {
year_day -= daytab[i][j];
}
else {
*p_month = j;
*p_day = year_day;
break;
}
j++;
}
}
}
int main() {
int month;
int day;
month_day(2014, 32, &month, &day);
printf("month: %d, day: %d\n", month, day);
return 0;
}
|
C
|
/* File: utilities.c
* Author: Amr Gaber
* Created: 11/4/2010
* Last Modified: 21/10/2010
* Purpose: Executes utility operations
*/
#include "utilities.h"
extern int errno;
/* void ERROR(char *message, unsigned int lineNum, char systemError) -- prints
* error message then exits program with status -1
*/
void ERROR(char *message, unsigned int lineNum, char systemError) {
#ifdef DEBUG
fprintf(stderr, "%u:", lineNum);
#endif
if (systemError)
perror(message);
else
fprintf(stderr, "ERROR: %s\n", message);
exit(-1);
}
|
C
|
#include<stdio.h>
int main(void)
{
unsigned int x;
int count=0;
scanf("%u",&x);
while(x!=0)
{
if(x&1)
count++;
x=x>>1;
}
printf("%d\n",count);
return 0;
}
|
C
|
#pragma once
#include "SDL/SDL.h" // for the SDL_Rect extension...
#include "spoint.h"
/**
* a rectangle class that can be interfaced as a x,y,w,h rectangle as well as a
* 2-corners rectangle (min, max):
*
* minx,miny
* ^--W--+
* | |
* H |
* | maxx,maxy
* +-----^
*
* @note: using getWidth() and getHeight() methods treats the height and width
* as signed, which is a change from the SDL_Rect spec
*/
struct SRect : public SDL_Rect
{
/**
* given min and max points, makes this a valid inscribed rectangle
* @param a_min minimum x/y coordinate of the rectangle
* @param a_max maximum x/y coordinate of the rectangle
*/
inline void set(const SPoint & a_min, const SPoint & a_max)
{
x=a_min.x;
y=a_min.y;
w=a_max.x-x;
h=a_max.y-y;
}
/** given points in arbitrary order, makes this an inscribed rectangle */
void setFromPoints(const SPoint & a, const SPoint & b)
{
SPoint min(((a.x<b.x)?a.x:b.x),((a.y<b.y)?a.y:b.y));
SPoint max(((a.x>b.x)?a.x:b.x),((a.y>b.y)?a.y:b.y));
set(min, max);
}
/** creates a valid rectangle inscribed into two points in arbitrary order */
SRect(const SPoint & a, const SPoint & b)
{
setFromPoints(a,b);
}
/** copy constructor */
SRect(const SDL_Rect & r)
{
*((SDL_Rect*)this) = r;
}
/** initialization method */
inline void set(const int & a_x, const int & a_y, const int & a_w, const int & a_h)
{x=a_x;y=a_y;w=a_w;h=a_h;}
/** sets the rectangle to be all zeros (zero size at the origin) */
inline void clear(){set(0,0,0,0);}
/** default constructor creates an invalid rectangle (zero size) at the origin */
SRect(){clear();}
/** complete constructor */
SRect(const int & x, const int & y, const int & w, const int & h){set(x,y,w,h);}
/** copy method */
inline void set(const SDL_Rect & r){x=r.x;y=r.y;w=r.w;h=r.h;}
/** set the position of the rectangle (upper-left hand corner x/y, moves the rectangle) */
inline void setPosition(const SPoint & p){x=p.x;y=p.y;}
/** sets the size of the rectangle (width/height) */
inline void setDimension(const SPoint & p){w=p.x;h=p.y;}
/** gets the position of the rectangle (upper-left hand corner x/y) */
inline SPoint getPosition() const {return SPoint(x,y);}
/** gets the dimensions of the rectangle (width/height) */
inline SPoint getDimension() const {return SPoint(w,h);}
/** @return x position of rectangle (left edge location) */
inline short getX() const { return x; }
/** @return y position of rectangle (top edge location) */
inline short getY() const { return y; }
/** @return left edge location */
inline short getMinX() const { return x; }
/** @return right edge location */
inline short getMaxX() const { return x+(signed)w; }
/** @return top edge location */
inline short getMinY() const { return y; }
/** @return bottom edge location */
inline short getMaxY() const { return y+(signed)h; }
/** @return upper-left corner */
inline SPoint getMin() const { return SPoint(getMinX(),getMinY()); }
/** @return lower-right corner */
inline SPoint getMax() const { return SPoint(getMaxX(),getMaxY()); }
/** @return width */
inline short getWidth() const { return (signed)w; }
/** @return height */
inline short getHeight() const{ return (signed)h; }
/** set the x position value (moves the rectangle) */
inline void setX(const int & a_value){ x = a_value; }
/** set the y position value (moves the rectangle) */
inline void setY(const int & a_value){ y = a_value; }
/** set the width value (moves the max value) */
inline void setWidth(const int & a_value){ w=a_value; }
/** set the height value (moves the max value) */
inline void setHeight(const int & a_value){ h=a_value; }
/** set the left-edge location (resizes the rectangle) */
inline void setMinX(const int & a_value){ w+=x-a_value;x=a_value; }
/** set the right-edge location (resizes the rectangle) */
inline void setMaxX(const int & a_value){ w=a_value-x; }
/** set the top-edge location (resizes the rectangle) */
inline void setMinY(const int & a_value){ h+=y-a_value;y=a_value; }
/** set the bottom-edge location (resizes the rectangle) */
inline void setMaxY(const int & a_value){ h=a_value-y; }
/** set the upper-left corner location (resizes the rectangle) */
inline void setMin(const SPoint & p){setMinX(p.x);setMinY(p.y);}
/** set the lower-right corner location (resizes the rectangle) */
inline void setMax(const SPoint & p){setMaxX(p.x);setMaxY(p.y);}
/** @return true if the width and height are both zero */
inline bool isZero(){return !w && !h;}
/** @return true if the width and height are both greater than one */
inline bool isValid()const{return getWidth()>0&&getHeight()>0;}
/** @return if this intersects (overlaps at all) the given rectangle */
inline bool intersects(const SRect & r)
{
return !( r.getMaxX() < getMinX() || r.getMinX() > getMaxX()
|| r.getMaxY() < getMinY() || r.getMinY() > getMaxY() );
}
/** @return true if this rectangle contains the given location */
inline bool contains(const SPoint & p)
{
return getMinX() <= p.x && getMinY() <= p.y
&& getMaxX() > p.x && getMaxY() > p.y;
}
/** @return true if this and the given rectangle have identical values */
inline bool equals(const SRect & r){return x==r.x&&y==r.y&&w==r.w&&h==r.h;}
/** adds a given rectangle's area to this rectangle (may resize the rectangle) */
void add(const SRect & r)
{
if(r.getMinX() < getMinX()) setMinX(r.getMinX());
if(r.getMaxX() > getMaxX()) setMaxX(r.getMaxX());
if(r.getMinY() < getMinY()) setMinY(r.getMinY());
if(r.getMaxY() > getMaxY()) setMaxY(r.getMaxY());
}
/** makes this rectangle only the intersection with the given rectangle */
void clip(const SRect & r)
{
if(r.getMinX() > getMinX()) setMinX(r.getMinX());
if(r.getMaxX() < getMaxX()) setMaxX(r.getMaxX());
if(r.getMinY() > getMinY()) setMinY(r.getMinY());
if(r.getMaxY() < getMaxY()) setMaxY(r.getMaxY());
}
/** @return what this rectangle would be if it were clipped */
SRect clipped(const SRect & a_clippingRect)
{
SRect r(*this);
r.clip(a_clippingRect);
return r;
}
/** reduces the rectangles size in all directions by the given value */
void inset(const int & a_border)
{set(x+a_border, y+a_border, w-a_border*2, h-a_border*2);}
/** @return what this rectangle would be if it were inset the given value */
SRect insetted(const int & a_border)
{SRect insetRect(*this);insetRect.inset(a_border);return insetRect;}
/** @return a rectangle moved over a_direction units (this rectangle is a unit-size) */
SRect unitsOver(const SPoint & a_direction)
{
return SRect(x+getWidth()*a_direction.getX(),
y+getHeight()*a_direction.getY(),getWidth(),getHeight());
}
/** add a_direction to the rectangle's position */
void move(const SPoint & a_direction)
{
x+=a_direction.getX();
y+=a_direction.getY();
}
/** @return this rectangle if it were moved a_direction */
SRect moved(const SPoint & a_direction)
{
SRect r(*this);
r.move(a_direction);
return r;
}
/** used by getField() and setField() */
static const int X = 0, Y = 1;
static const int MIN = 2; //SPoint::NUM_DIMENSIONS*1
/** used by getField() and setField() */
static const int MIN_X = MIN+X, MIN_Y = MIN+Y;
static const int MAX = 4; //SPoint::NUM_DIMENSIONS*2
/** used by getField() and setField() */
static const int MAX_X = MAX+X, MAX_Y = MAX+Y;
static const int DIMENSION = 6; //SPoint::NUM_DIMENSIONS*3
/** used by getField() and setField() */
static const int WIDTH = DIMENSION+X, HEIGHT = DIMENSION+Y;
/** @param a_field (X, Y, MIN_X, MIN_Y, MAX_X, MAX_Y, WIDTH, HEIGHT) */
short getField(const int & a_field) const
{
switch(a_field)
{
case MIN_X: return getMinX();
case MIN_Y: return getMinY();
case MAX_X: return getMaxX();
case MAX_Y: return getMaxY();
case X: return getX();
case Y: return getY();
case WIDTH: return getWidth();
case HEIGHT: return getHeight();
}
return 0;
}
/** @param a_field (X, Y, MIN_X, MIN_Y, MAX_X, MAX_Y, WIDTH, HEIGHT) */
void setField(const int & a_field, const short & a_value)
{
switch(a_field)
{
case MIN_X: return setMinX(a_value);
case MIN_Y: return setMinY(a_value);
case MAX_X: return setMaxX(a_value);
case MAX_Y: return setMaxY(a_value);
case X: return setX(a_value);
case Y: return setY(a_value);
case WIDTH: return setWidth(a_value);
case HEIGHT: return setHeight(a_value);
}
}
/** force this rectangle to overlap as much area as possible with the given rectangle */
void keepBound(const SRect & area)
{
bool isSmallerThanArea;
// go through X and Y dimensions
for(int d = 0; d < 2; ++d)
{
isSmallerThanArea = getField(DIMENSION+d) < area.getField(DIMENSION+d);
if(isSmallerThanArea
?(getField(MIN+d) <= area.getField(MIN+d))
:(getField(MIN+d) >= area.getField(MIN+d)))
setField(d, area.getField(d));
else if(isSmallerThanArea
?(getField(MAX+d) >= area.getField(MAX+d))
:(getField(MAX+d) <= area.getField(MAX+d)))
setField(d, area.getField(MAX+d)-getField(DIMENSION+d));
}
}
/** multiply the dimensions and position of this rectangle */
void multiply(const int & a_value){
setX(getX()*a_value);
setY(getY()*a_value);
setWidth(getWidth()*a_value);
setHeight(getHeight()*a_value);
}
};
|
C
|
#ifndef _heap_sort_h
#define _heap_sort_h
#include <stdlib.h>
#define ValType double
#define IS_LESS(v1, v2) (v1 < v2)
void siftDown(ValType *a, int start, int end);
void heapsort(ValType *a, int count);
// do a swap between two values
#define SWAP(r, s) do{ValType t=r; r=s; s=t;} while(0)
#endif
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* handle_char.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: ozabara <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2017/03/13 16:09:50 by ozabara #+# #+# */
/* Updated: 2017/03/13 16:45:13 by ozabara ### ########.fr */
/* */
/* ************************************************************************** */
#include "ft_printf.h"
static void pf_print_char_1(char **fmt, t_format *tf, void *arg)
{
int i;
*fmt = ft_strnew(1);
*fmt[0] = (char)arg;
if (tf->min_width > 0)
{
ft_strdel(fmt);
*fmt = ft_strnew(tf->min_width);
i = -1;
if (!(tf->flags->justify_left))
{
while (++i < tf->min_width - 1)
(*fmt)[i] = (tf->flags->add_zeros) ? '0' : ' ';
(*fmt)[i] = (char)arg;
}
else
{
(*fmt)[++i] = (char)arg;
while (++i < tf->min_width)
(*fmt)[i] = (tf->flags->add_zeros) ? '0' : ' ';
}
}
}
static void pf_subprint_char_2(char **fmt, void *arg, int *d)
{
if ((int)arg < 256)
{
*fmt = ft_strnew(1);
(*fmt)[0] = (int)arg - 256;
}
else
*fmt = pf_wchar_to_char((wchar_t)arg);
*d = ft_strlen(*fmt);
}
static void pf_print_char_2(char **fmt, t_format *tf, void *arg)
{
int i;
int d;
int h;
char *t;
pf_subprint_char_2(fmt, arg, &d);
if ((h = -1) && tf->min_width > 0)
{
ft_strdel(fmt);
t = pf_wchar_to_char((wchar_t)arg);
*fmt = ft_strnew(tf->min_width + d - 1);
if ((i = -1) && !(tf->flags->justify_left))
{
while (++i < tf->min_width - 1)
(*fmt)[i] = (tf->flags->add_zeros) ? '0' : ' ';
while (++h < d)
(*fmt)[i + h] = t[h];
}
else
{
(*fmt)[++i] = (char)arg;
while (++i < tf->min_width)
(*fmt)[i] = (tf->flags->add_zeros) ? '0' : ' ';
}
}
}
void pf_handle_char(char **fmt, t_format *tf, void *arg)
{
if (tf->length == 3 || tf->length == 4 || tf->type == 14)
pf_print_char_2(fmt, tf, arg);
else
pf_print_char_1(fmt, tf, arg);
}
|
C
|
#define NULL ((void*)0)
typedef unsigned long size_t; // Customize by platform.
typedef long intptr_t; typedef unsigned long uintptr_t;
typedef long scalar_t__; // Either arithmetic or pointer type.
/* By default, we understand bool (as a convenience). */
typedef int bool;
#define false 0
#define true 1
/* Forward declarations */
typedef struct TYPE_7__ TYPE_3__ ;
typedef struct TYPE_6__ TYPE_2__ ;
typedef struct TYPE_5__ TYPE_1__ ;
/* Type definitions */
typedef int /*<<< orphan*/ pairingheap_node ;
struct TYPE_7__ {TYPE_1__* distances; } ;
struct TYPE_6__ {int numberOfOrderBys; } ;
struct TYPE_5__ {int /*<<< orphan*/ value; scalar_t__ isnull; } ;
typedef TYPE_2__* IndexScanDesc ;
typedef TYPE_3__ GISTSearchItem ;
/* Variables and functions */
scalar_t__ GISTSearchItemIsHeap (TYPE_3__ const) ;
int float8_cmp_internal (int /*<<< orphan*/ ,int /*<<< orphan*/ ) ;
__attribute__((used)) static int
pairingheap_GISTSearchItem_cmp(const pairingheap_node *a, const pairingheap_node *b, void *arg)
{
const GISTSearchItem *sa = (const GISTSearchItem *) a;
const GISTSearchItem *sb = (const GISTSearchItem *) b;
IndexScanDesc scan = (IndexScanDesc) arg;
int i;
/* Order according to distance comparison */
for (i = 0; i < scan->numberOfOrderBys; i++)
{
if (sa->distances[i].isnull)
{
if (!sb->distances[i].isnull)
return -1;
}
else if (sb->distances[i].isnull)
{
return 1;
}
else
{
int cmp = -float8_cmp_internal(sa->distances[i].value,
sb->distances[i].value);
if (cmp != 0)
return cmp;
}
}
/* Heap items go before inner pages, to ensure a depth-first search */
if (GISTSearchItemIsHeap(*sa) && !GISTSearchItemIsHeap(*sb))
return 1;
if (!GISTSearchItemIsHeap(*sa) && GISTSearchItemIsHeap(*sb))
return -1;
return 0;
}
|
C
|
#include "stm32f103c8_rcc_driver.h"
uint16_t ahb_prescaler[8] = { 2, 4, 8, 16, 32, 64, 128, 256 };
uint16_t apb1_prescaler[4] = { 2, 4, 8, 16 };
uint32_t rcc_get_pclk1_value() {
uint8_t hpre, ppre, ahb, apb1;
uint32_t sysclk;
uint8_t clksrc = ((RCC->CFGR >> 2) & 0x3);
// HSI
if (clksrc == 0) {
sysclk = 16; //16 MHz
}
// HSE
else if (clksrc == 1) {
sysclk = 8; //8 MHz
}
// AHB
hpre = ((RCC->CFGR >> RCC_CFGR_HPRE) & 0xF);
if (hpre < 8) {
ahb = 1;
} else {
ahb = ahb_prescaler[hpre - 8];
}
// APB1
ppre = ((RCC->CFGR >> RCC_CFGR_PPRE1) & 0xF);
if (ppre < 4) {
apb1 = 1;
} else {
apb1 = apb1_prescaler[ppre - 4];
}
return (sysclk / ahb) / apb1;
}
|
C
|
/*
* sauvegardeFichier.c
*
* Created on: 10 mai 2013
* Author: Pauldb
*/
#include <stdio.h>
#include <stdlib.h>
#include <errno.h> //traitement des erreurs pour fopen
#include <string.h>
extern int errno ;
#include "structures.h"
#include "defines.h"
/*Permet d'enregistrer TOUT le fichier de parametrage*/
void sauverFichierParametrage(T_Section section)
{
FILE *f = NULL;
char *fichier = section.nom;
int nbr = section.nbrAnnees;
T_Annee * tab = section.tabAnnees;
char urlComplet[MAX_CHAR];
int i = 0, j = 0, k = 0;
sprintf(urlComplet,"%s%s.txt",URL_SECTIONS,fichier); //Concatnation URLDOSSIER+URLFICHIER
if(DEBUG)
printf("\nurlComplet = %s\n", urlComplet);
f = fopen(urlComplet, "w+");
if(f == NULL)
{
printf("Erreur lors de l'ouverture de %s\n", urlComplet);
perror ("The following error occurred");
printf( "Value of errno: %d\n", errno );
exit(0);
}
if(DEBUG)
printf("Fichier correctement ouvert en ecriture\n");
fprintf(f, "%d;\n", nbr); // Ecriture du nombre total d'annes/sections.
if(DEBUG)
printf("nbAnnee = %d\n", nbr);
for(i = 0 ; i < nbr ; i++)
{
fprintf(f, "%s;", tab[i].nomAnneeSection);//Nom annee
fprintf(f, "%s;", tab[i].abbreviation);//Abbreviation
fprintf(f, "%d;", tab[i].compteurMatricule);//Nom annee
fprintf(f, "%d;", tab[i].nbClasses);//Nombre de classe dans l'anne
if(DEBUG)
{
printf("nom Section %s, nombre de classe : %d\n", tab[i].nomAnneeSection, tab[i].nbClasses);
printf("Classes:\n");
}
for(j = 0 ; j < tab[i].nbClasses ; j++)
{
fprintf(f, "%s;", tab[i].nomClasse[j]);
if(DEBUG)
printf("\t%s\n", tab[i].nomClasse[j]);
}
fprintf(f, "%d;", tab[i].nbCoursParEtudiant);
if(DEBUG)
printf("nbCoursParEtudiant = %d\nCours:\n", tab[i].nbCoursParEtudiant);
for(k = 0 ; k < tab[i].nbCoursParEtudiant ; k++)
{
fprintf(f, "%s;", tab[i].tabCours[k].nomCours);
fprintf(f, "%d;", tab[i].tabCours[k].ponderation);
if(DEBUG)
printf("\t%s (%d)", tab[i].tabCours[k].nomCours, tab[i].tabCours[k].ponderation);
}
fprintf(f, "\n");
}
fclose(f);
}
/*
* @chargerFichierParametrage(char*): Cette fonction lit un fichier de section
* et retourne une structure T_Section charge selon les informations
* du fichier. Le nom du fichier lire est reu en paramtre, et est considr comme
* tant VALIDE.
* @param: L'adressse du fichier charger.
* @return: Elle retourne la structure cre partir du fichier.
*/
T_Section chargerFichierParametrage(char* fichier)
{
int j = 0, k, l, m;
T_Section sectionChargee;
T_Annee *tab;
FILE *f = NULL;
char s[TAILLE_MAX];
char *url1 = URI_FICHIERS;
char urlComplet[MAX_CHAR];
sprintf(urlComplet,"%s%s",url1,fichier); //Concatnation URLDOSSIER+URLFICHIER
if(DEBUG)
printf("\nurlComplet = %s\n", urlComplet);
f = fopen(urlComplet, "rt");
if(f == NULL)
{
printf("Erreur lors de l'ouverture de %s", urlComplet);
exit(0);
}
/*On rcupre le nombre d'annee/Section*/
fgets(s, TAILLE_MAX, f);
int nbrAnneeSection = atoi(s);
sectionChargee.nbrAnnees = nbrAnneeSection;
sectionChargee.tabAnnees = (T_Annee*) malloc(sizeof(T_Annee) * nbrAnneeSection);
tab = (T_Annee*) malloc(sizeof(T_Annee) * nbrAnneeSection);
while(fgets(s, TAILLE_MAX, f) != NULL) // Tant que l'on parvient lire dans le fichier
{
strcpy(tab[j].nomAnneeSection, strtok(s,";")); if(DEBUG) printf("Nom Annee/section : %s\n", tab[j].nomAnneeSection);
strcpy(tab[j].abbreviation, strtok(NULL,";")); if(DEBUG) printf("Abbreviation : %s\n", tab[j].abbreviation);
tab[j].compteurMatricule = atoi(strtok(NULL,";")); if(DEBUG) printf("Compteur matricule : %d\n", tab[j].compteurMatricule);
tab[j].nbClasses = atoi(strtok(NULL, ";")); if(DEBUG) printf("Nombre de classes : %d\n", tab[j].nbClasses);
tab[j].nomClasse = (char **) malloc(tab[j].nbClasses * sizeof(char*));
if(tab[j].nomClasse == NULL)
exit(0);
for(l = 0 ; l < tab[j].nbClasses ; l++)
{
tab[j].nomClasse[l] = (char *) malloc(TAILLE_MAX * sizeof(char));
if(tab[j].nomClasse[l] == 0)
exit(0);
}
for(k = 0 ; k < tab[j].nbClasses ; k++)
{
strcpy(tab[j].nomClasse[k], strtok(NULL,";")); if (DEBUG) printf("Classe %d : %s\n", k, tab[j].nomClasse[k]);
}
tab[j].nbCoursParEtudiant = atoi(strtok(NULL, ";")); if(DEBUG) printf("Nombre de Cours : %d\n", tab[j].nbCoursParEtudiant);
tab[j].tabCours = malloc(tab[j].nbCoursParEtudiant * sizeof(T_Cours));
if(tab[j].tabCours == 0)
exit(0);
for(m = 0 ; m < tab[j].nbCoursParEtudiant ; m++)
{
strcpy(tab[j].tabCours[m].nomCours, strtok(NULL, ";"));
tab[j].tabCours[m].ponderation = atoi(strtok(NULL, ";"));
if(DEBUG)
{
printf("Cours %d : %s\n", m, tab[j].tabCours[m].nomCours);
printf("Ponderation %d : %d\n", m, tab[j].tabCours[m].ponderation);
}
}
tab[j].tabClasse = malloc(tab[j].nbClasses * sizeof(T_Classe));
for(l = 0; l < tab[j].nbClasses; l++){
strcpy(tab[j].tabClasse[l].nomClasse, tab[j].nomClasse[l]);
}
if(DEBUG) printf("\n");
j++;
}
sectionChargee.tabAnnees = tab;
return sectionChargee;
}
|
C
|
/*
* AUTORES: Ane Zubillaga, Ian Recke, Ivan Sorbet, Alejandro Meza
*version del 30/11/2019
*/
#include <stdio.h>
#include <stdlib.h>
#include "fragmentar.h"
#include <sys/errno.h>
#include <wchar.h>
#include <math.h>
#include <unistd.h>
#include "arbolBin.h"
#define clear() printf("\n")
tipoArbolBin arbol1;
typedef struct datos{
float ir;
float na;
float mg;
float al;
float si;
float k;
float ca;
float va;
float fe;
int tipo;
}Datos;
/*typedef struct tablaentropia{
double entr;
int pos;
}Tablaentropia;*/
int clase(tipoArbolBin a, float ir, float na, float mg, float al, float si, float k, float ca, float va, float fe);
void quicksort(Datos cadena[], int izq, int der, float determinante[]);
tipoArbolBin creaArbol(Datos datos[],int comienzo,int final);
void start_arbol_decision(){
clear();
printf("\033[1;31m");
printf("\n\n\n\n******************""************************");
printf("\n\n\n\t****ARBOL DE DECISION****");
printf("\n\n\n\n******************""************************");
char *name = getenv("USER");
printf("\n\n\n\tUSUARIO ES: @%s", name);
printf("\033[0m");
printf("\n");
sleep(1);
clear();
}
double entropialateral(int tipo[],int inicio, int final){
double tipos1 = 0,tipos2 = 0,tipos3 = 0,tipos4 = 0,tipos5 = 0,tipos6 = 0,tipos7 = 0;
double entropia = 0;
double total=(final-inicio+1);
int i=inicio;
while(i<=final){
if(tipo[i]==1){
tipos1++;
}
else if(tipo[i]==2){
tipos2++;
}
else if(tipo[i]==3){
tipos3++;
}
else if(tipo[i]==4){
tipos4++;
}
else if(tipo[i]==5){
tipos5++;
}
else if(tipo[i]==6){
tipos6++;
}
else if(tipo[i]==7){
tipos7++;
}
i++;
}
double tabla[7] = {tipos1, tipos2, tipos3, tipos4, tipos5, tipos6, tipos7};
for (int h=0; h<7; h++)
{
if (tabla[h] != 0)
entropia = entropia - ((tabla[h]/total)*log2(tabla[h]/total));
// printf("Dentro del for %f\n", entropia);
}
return entropia;
}
void entropia(int tipo[],int comienzo, int longitud,int *posicion,double *entro)
{ int numelem=longitud+1-comienzo;
double menor=1000;
int posmenor=comienzo;
double entropia = 0;
int i = comienzo;
while (i < longitud)
{
if (tipo[i]!= tipo[i+1])
{
double entrizq = entropialateral(tipo, comienzo, i);
double entrdech = entropialateral(tipo, i+1, longitud);
entropia =(((double)((double)(i-comienzo)/(double)numelem)*entrizq) + (((double)((double)(longitud)-(double)i)/(double)numelem)*entrdech));//voy por aqui
if(entropia<menor){
posmenor=i;
menor=entropia;
}
}
i++;
}
*posicion=posmenor;
*entro=menor;
}
int main(void)
{
start_arbol_decision();
FILE *f;
char dats[400];
float ir=0 ,na=0, mg=0, al=0, si=0, k=0, ca=0, va=0, fe=0;
char aux[100];
f = fopen("problem_glass.csv", "r+");
fgets(aux, 100, f); //lee los valores que no van a servir de la primera fila
int j = 0;
Datos datos[300]; //vector de tipo datos-->cada elemento, contiene un valor de todos los campos
while (!feof(f)) //mientras no se acabe el fichero
{
fgets(dats, 400, f);
if(feof(f))//si cuando lee el fgets es nulo, es decir es fin de fichero, da error y entra aqui, porque es feof y sale del buccle.
break;
char **frasefragmentada = fragmenta(dats); //dats contiene la linea
datos[j].ir = atof(frasefragmentada[0]);
datos[j].na = atof(frasefragmentada[1]);
datos[j].mg = atof(frasefragmentada[2]);
datos[j].al = atof(frasefragmentada[3]);
datos[j].si = atof(frasefragmentada[4]);
datos[j].k = atof(frasefragmentada[5]);
datos[j].ca = atof(frasefragmentada[6]);
datos[j].va = atof(frasefragmentada[7]);
datos[j].fe = atof(frasefragmentada[8]);
datos[j].tipo = atoi(frasefragmentada[9]);
j++;
}
fclose(f);
nuevoArbolBin(&arbol1);
arbol1=creaArbol(datos,0,j-1);
//preorden(arbol1);
// printf("Introduzca los valores de los elementos para identificar la clase\n");
printf("Introduzca en el siguiente orden: índice de refracción, sodio, magnesio, aluminio ");
printf("silicio, potasio, calcio, va, hierro y tipo\n");
scanf("%f %f %f %f %f %f %f %f %f", &ir, &na, &mg, &al, &si, &k, &ca, &va, &fe);
int solucion = clase(arbol1, ir, na, mg, al, si, k, ca, va, fe);
printf("El resultado es %d\n", solucion);
//llamo al arbol
return 0;
}
int casoBase(Datos datos[], int comienzo, int final){
// sleep(1);
double probabilidad = 0.8;
double total = final -comienzo +1;
double tipos1 = 0,tipos2 = 0,tipos3 = 0,tipos4 = 0,tipos5 = 0,tipos6 = 0,tipos7 = 0;
for(int i = comienzo; i<final+1; i++){
if(datos[i].tipo==1){
tipos1++;
}
else if(datos[i].tipo==2){
tipos2++;
}
else if(datos[i].tipo==3){
tipos3++;
}
else if(datos[i].tipo==4){
tipos4++;
}
else if(datos[i].tipo==5){
tipos5++;
}
else if(datos[i].tipo==6){
tipos6++;
}
else if(datos[i].tipo==7){
tipos7++;
}
}
///////////////////
if((tipos1/total)>=probabilidad){
return 1;
}
else if((tipos2/total)>=probabilidad){
return 2;
}
else if((tipos3/total)>=probabilidad){
return 3;
}
else if((tipos4/total)>=probabilidad){
return 4;
}
else if((tipos5/total)>=probabilidad){
return 5;
}
else if((tipos6/total)>=probabilidad){
return 6;
}
else if((tipos7/total)>=probabilidad){
return 7;
}
else{
return -1;
}
}
tipoArbolBin creaArbol(Datos datos[],int comienzo,int final){
//int posicion2 = entropia(tipo,j-1);
// printf("posicion %d",posicion2);
// if (comienzo != final){
int elemento = 0;
float umbral = 0;
float ir[final+1];
for (int i=comienzo; i<final+1; i++)
{
ir[i] = datos[i].ir;
}
quicksort(datos, comienzo, final, ir);
int tipo[final+1];
for (int i=comienzo; i<final+1; i++)
{
tipo[i] = datos[i].tipo;
}
int posir=0;
double entroir=0;
entropia(tipo,comienzo,final,&posir,&entroir);
//printf("posicion %d\n",posicion);
//ENTROPIA
/////////
float na[final+1];
for (int i=comienzo; i<final+1; i++)
{
na[i] = datos[i].na;
}
quicksort(datos, comienzo, final, na);
for (int i=comienzo; i<final+1; i++)
{
tipo[i] = datos[i].tipo;
}
int posna=0;
double entrona=0;
entropia(tipo,comienzo,final,&posna,&entrona);
// int posicion2 = entropia(&(datos)->tipo,j-1);
// printf("posicion %d",posicion2);
//ENTROPIA
/////
/*for (int i=0; i<j; i++)
{
printf("%f\n", datos[i].na);
}*/
float mg[final+1];
for(int i =comienzo; i<final+1; i++){
mg[i]=datos[i].mg;
}
quicksort(datos,comienzo, final, mg);
for (int i=comienzo; i<final+1; i++)
{
tipo[i] = datos[i].tipo;
}
int posmg=0;
double entromg=0;
entropia(tipo,comienzo,final,&posmg,&entromg);
//ENTROPIA
///////////////////
float al[final+1];
for(int i =comienzo; i<final+1; i++){
al[i] = datos[i].al;
}
quicksort(datos,comienzo, final, al);
for (int i=comienzo; i<final+1; i++)
{
tipo[i] = datos[i].tipo;
}
int posal=0;
double entroal=0;
entropia(tipo,comienzo,final,&posal,&entroal);
//ENTROPIA
/////////////////////
float si[final+1];
for(int i=comienzo; i<final+1; i++){
si[i]=datos[i].si;
}
quicksort(datos,comienzo, final, si);
for (int i=comienzo; i<final+1; i++)
{
tipo[i] = datos[i].tipo;
}
int possi=0;
double entrosi=0;
entropia(tipo,comienzo,final,&possi,&entrosi);
//ENTROPIA
/////////////////////
float k[final+1];
for(int i=comienzo; i<final+1; i++){
k[i] = datos[i].k;
}
quicksort(datos,comienzo, final, k);
for (int i=comienzo; i<final+1; i++)
{
tipo[i] = datos[i].tipo;
}
int posk=0;
double entrok=0;
entropia(tipo,comienzo,final,&posk,&entrok);
//ENTROPIA
float ca[final+1];
for(int i =comienzo; i<final+1; i++){
ca[i] = datos[i].ca;
}
quicksort(datos,comienzo, final, ca);
for (int i=comienzo; i<final+1; i++)
{
tipo[i] = datos[i].tipo;
}
int posca=0;
double entroca=0;
entropia(tipo,comienzo,final,&posca,&entroca);
//ENTROPIA
float va[final+1];
for(int i=comienzo; i<final+1; i++){
va[i]= datos[i].va;
}
quicksort(datos,comienzo, final, va);
for (int i=comienzo; i<final+1; i++)
{
tipo[i] = datos[i].tipo;
}
int posva=0;
double entrova=0;
entropia(tipo,comienzo,final,&posva,&entrova);
//ENTROPIA
float fe[final+1];
for(int i=comienzo; i<final+1; i++){
fe[i] = datos[i].fe;
}
quicksort(datos,comienzo, final, fe);
for (int i=comienzo; i<final+1; i++)
{
tipo[i] = datos[i].tipo;
}
int posfe=0;
double entrofe=0;
entropia(tipo,comienzo,final,&posfe,&entrofe);
//ENTROPIA
//Tablaentropia t = entropia(tipo, j-1);
double menor = 1000;
if (entroir < menor){
elemento=11;
menor = entroir;
}
if (entrona < menor){
elemento=12;
menor = entrona;
}
if (entromg < menor){
elemento=13;
menor = entromg;
}
if (entroal < menor){
elemento=14;
menor = entroal;
}
if (entrosi < menor){
elemento=15;
menor = entrosi;
}
if (entrok < menor){
elemento=16;
menor = entrok;
}
if (entroca < menor){
elemento=17;
menor = entroca;
}
if (entrova < menor){
elemento=18;
menor = entrova;
}
if (entrofe < menor){
elemento=19;
menor = entrofe;
}
if (entroir < menor){
elemento = 11;
menor = entroir;
}
//printf("Antes de posicion\n");
int posicion = 0;
if(elemento==11){
// printf("11\n");
quicksort(datos, comienzo, final, ir);
umbral = (datos[posir].ir+datos[posir+1].ir)/2;
posicion = posir;
}
else if(elemento==12){
// printf("12\n");
quicksort(datos, comienzo, final, na);
umbral = (datos[posna].na+datos[posna+1].na)/2;
posicion = posna;
}
else if(elemento==13){
// printf("13\n");
quicksort(datos, comienzo, final, mg);
umbral = (datos[posmg].mg+datos[posmg+1].mg)/2;
posicion = posmg;
}
else if(elemento==14)
{
// printf("14\n");
quicksort(datos, comienzo, final, al);
umbral = (datos[posal].al+datos[posal+1].al)/2 ;
posicion = posal;
}
else if(elemento==15){
// printf("15\n");
quicksort(datos, comienzo, final, si);
umbral = (datos[possi].si+datos[possi+1].si)/2;
posicion = possi;
}
else if(elemento==16){
// printf("16\n");
quicksort(datos, comienzo, final, k);
umbral = (datos[posk].k+datos[posk].k)/2;
posicion =posk;
}
else if(elemento==17){
// printf("17\n");
quicksort(datos, comienzo, final, ca);
// printf("paso\n");
// printf("posmenor ca: %d\n", posca);
umbral = (datos[posca].ca+datos[posca+1].ca)/2;
// printf("umbral: %f\n", umbral);
posicion = posca;
}
else if(elemento==18){
// printf("18\n");
quicksort(datos, comienzo, final, va);
umbral = (datos[posva].va+datos[posva+1].va)/2;
posicion = posva;
}
else if(elemento==19){
// printf("19\n");
quicksort(datos, comienzo, final, fe);
umbral = (datos[posfe].fe+datos[posfe+1].fe)/2;
posicion = posfe;
}
// printf("Antes\n");
int solucion = casoBase(datos, comienzo, final);
// printf("Solucion\n");
if(solucion !=-1){
// printf("Entro caso base\n");
tipoElementoArbolBin tip;
tip.elemento=elemento;
tip.umbral=0;
tip.entropia=solucion;
arbol1 = construir(tip, NULL, NULL);
}
else{
// printf("Entro otro caso\n");
tipoElementoArbolBin ti;
ti.elemento=elemento;
ti.umbral=umbral;
ti.entropia=menor;
// printf("POSICION %d\n",posicion);
arbol1 = construir(ti, creaArbol(datos,comienzo,posicion),creaArbol(datos,posicion+1,final));
}
// }
//
// else{
// tipoElementoArbolBin ti1;
// ti1.elemento=0;
// ti1.umbral=0;
// ti1.entropia=datos[comienzo].tipo;
// arbol1 = construir(ti1, NULL, NULL);
// }
return arbol1;
}
void quicksort(Datos cadena[], int izq, int der, float determinante[])
{
int i=izq;
int d=der;
float centro=determinante[(i+d)/2];
do {
while (determinante[i]<centro && i<der)
{
i++;
}
while (centro<determinante[d] && d>izq)
{
d--;
}
if (i<=d)
{
Datos aux=cadena[i];
cadena[i]=cadena[d];
cadena[d]=aux;
float auxi=determinante[i];
determinante[i] = determinante[d];
determinante[d] = auxi;
i++;
d--;
}
} while(i<=d);
if (izq < d)
{
quicksort(cadena, izq, d, determinante);
}
if(der > i)
{
quicksort(cadena, i, der, determinante);
}
}
// int clase(tipoArbolBin a, float ir, float na, float mg, float al, float si, float k, float ca, float va, float fe)
// {
// int tipo = 0;
// if (a->elem.elemento == 0)
// {
// return (int)a->elem.entropia;
// }
// else if (a->elem.elemento != 0)
// {
// if (a->elem.elemento == 11)
// {
// if (a->elem.umbral > ir)
// tipo = clase(a->izda, ir, na, mg, al, si, k, ca, va, fe);
// else
// tipo = clase(a->dcha, ir, na, mg, al, si, k, ca, va, fe);
// }
// if (a->elem.elemento == 12)
// {
// if (a->elem.umbral > na)
// tipo = clase(a->izda, ir, na, mg, al, si, k, ca, va, fe);
// else
// tipo = clase(a->dcha, ir, na, mg, al, si, k, ca, va, fe);
// }
// if (a->elem.elemento == 13)
// {
// if (a->elem.umbral > mg)
// tipo = clase(a->izda, ir, na, mg, al, si, k, ca, va, fe);
// else
// tipo = clase(a->dcha, ir, na, mg, al, si, k, ca, va, fe);
// }
// if (a->elem.elemento == 14)
// {
// if (a->elem.umbral > al)
// tipo = clase(a->izda, ir, na, mg, al, si, k, ca, va, fe);
// else
// tipo = clase(a->dcha, ir, na, mg, al, si, k, ca, va, fe);
// }
//
// if (a->elem.elemento == 15)
// {
// if (a->elem.umbral > si)
// a = a->izda;
// else
// tipo = clase(a->dcha, ir, na, mg, al, si, k, ca, va, fe);
// }
//
// if (a->elem.elemento == 16)
// {
// if (a->elem.umbral > k)
// tipo = clase(a->izda, ir, na, mg, al, si, k, ca, va, fe);
// else
// tipo = clase(a->dcha, ir, na, mg, al, si, k, ca, va, fe);
// }
//
// if (a->elem.elemento == 17)
// {
// if (a->elem.umbral > ca)
// tipo = clase(a->izda, ir, na, mg, al, si, k, ca, va, fe);
// else
// tipo = clase(a->dcha, ir, na, mg, al, si, k, ca, va, fe);
// }
//
// if (a->elem.elemento == 18)
// {
// if (a->elem.umbral > va)
// tipo = clase(a->izda, ir, na, mg, al, si, k, ca, va, fe);
// else
// tipo = clase(a->dcha, ir, na, mg, al, si, k, ca, va, fe);
// }
//
// if (a->elem.elemento == 19)
// {
// if (a->elem.umbral > fe)
// tipo = clase(a->izda, ir, na, mg, al, si, k, ca, va, fe);
// else
// tipo = clase(a->dcha, ir, na, mg, al, si, k, ca, va, fe);
// }
// }
// return tipo;
// }
int clase(tipoArbolBin a, float ir, float na, float mg, float al, float si, float k, float ca, float va, float fe)
{
while(a->dcha !=NULL && a->izda != NULL){
if (a->elem.elemento == 0)
{
return (int)a->elem.entropia;
}
else if (a->elem.elemento != 0)
{
if (a->elem.elemento == 11)
{
if (a->elem.umbral > ir)
a = a->izda;
else
a = a->dcha;
}
if (a->elem.elemento == 12)
{
if (a->elem.umbral > na)
a = a->izda;
else
a = a->dcha;
}
if (a->elem.elemento == 13)
{
if (a->elem.umbral > mg)
a = a->izda;
else
a = a->dcha;
}
if (a->elem.elemento == 14)
{
if (a->elem.umbral > al)
a = a->izda;
else
a = a->dcha;
}
if (a->elem.elemento == 15)
{
if (a->elem.umbral > si)
a = a->izda;
else
a = a->dcha;
}
if (a->elem.elemento == 16)
{
if (a->elem.umbral > k)
a = a->izda;
else
a = a->dcha;
}
if (a->elem.elemento == 17)
{
if (a->elem.umbral > ca)
a = a->izda;
else
a = a->dcha;
}
if (a->elem.elemento == 18)
{
if (a->elem.umbral > va)
a = a->izda;
else
a = a->dcha;
}
if (a->elem.elemento == 19)
{
if (a->elem.umbral > fe)
a = a->izda;
else
a = a->dcha;
}
}
}
return (int)a->elem.entropia;
}
|
C
|
/*#####################################
#c_grep
#Trabajo Práctico Nº2
#Ejercicio Número 4
#Arias, Rodrigo DNI: 34.712.865
#Culen, Fernando DNI: 35.229.859
#García Alves, Pablo DNI: 34.394.775
#Juffar, Sebastian DNI: 34.497.148
#Nogueiras, Jorge DNI: 34.670.613
#1 REENTREGA
#####################################*/
#include "c_grep.h"
int main(int argc, char *argv[])
{
//declaracion de variables
// VALIDACION DE PARAMETROS NECESARIOS
if(argc<3 || argc<2) {
if(argc==2 && (!strcmp(argv[1],"-?" ) || !strcmp(argv[1],"-help" ) ) )
{
errorMessage();
exit(1);
}
else
printf("ERROR EN LA CANTIDAD DE PARAMETROS \n ");
errorMessage();
exit(1);
}
// VALIDAR SI ES O NO RECURSIVO
if(!strcmp(argv[argc-1],"-r"))
{
procesarrecursivo(argc,argv);
return 0;
}
else
{
int x;
//funcion simpre sin el -r
for( x=2; x<argc; x++)
{
//Creo un hijo por cada archivo que tengo
if(!fork())
{
norecur(argc,argv,x);
return 0;
}//fin if fork
}//fin for archivos
for (x=0; x<argc; x++)
wait(NULL);
return 0;
}
return 0;
}
//procesa archivos no recursivos
int norecur(int argc, char *argv[],int x)
{
//variables archivo
FILE *fp;//entrada
FILE *fps;//salida
char linea[500];
char nombrearchivo[500];
int nl=1;
int numeroaciertos=0;
//variables busqueda
int rv;
regex_t exp; //Our compiled expression
//Validar texto
char extencion[2000]; // va contener la extencion
char path[2000]; // tiene el directorio
unsigned num;
size_t end = strlen(argv[2])-1;
size_t end_path;
int bandera=0;
if(strchr(argv[2],'/'))
{
end_path =strlen(argv[2])- (strlen(strrchr(argv[2],'/')+1));
strncpy(path,argv[2],end_path);
path[end_path]='\0';
}
else {
sprintf(path,"./%s",argv[x]);
bandera=1;
}
strncpy(extencion , strrchr(argv[2],'.')+1, end);
//verifico apertura
if((fp=fopen(argv[x], "r")) == NULL)
{
printf("El directorio no es valido o no existe : %s \n",argv[x]);
errorMessage();
exit(1);
}
//1. CARGAR LA EXPRE
rv = regcomp(&exp,argv[1], REG_EXTENDED);
if (rv != 0) {
printf("regcomp fallo con %d\n", rv);
}
//2. CORRER LA BUSQUEDA
while(fgets(linea,sizeof(linea),fp))
{
if(match(&exp,linea))
{ if(!numeroaciertos)
{
sprintf(nombrearchivo,"./%d.txt",getpid());
if((fps=fopen(nombrearchivo, "w")) == NULL)
{
printf("El directorio no es valido o no existe : %s \n",nombrearchivo);
errorMessage();
exit(1);
}
fprintf(fps,"%s \n",argv[x]);
fprintf(fps,"Linea %d : %s \n",nl,linea);
printf("%s \n",argv[x]);
printf("Linea %d : %s \n",nl,linea);
numeroaciertos++;
}
else {
fprintf(fps,"Linea %d : %s\n",nl,linea);
printf("Linea %d : %s\n",nl,linea);
numeroaciertos++;
}
}//fin del if de acierto
nl++;
}//fin de recorrer lineas
//si hay aciertos cierro el archivo q se abrio para escribir
if(numeroaciertos)
fclose(fps);
//3. LIBERAR
regfree(&exp);
//cierro el arhivo de lectura
fclose(fp);
return 1;
}
//separa la extencion y el path de los arhivos recursivos
int procesarrecursivo(int argc, char *argv[])
{
FILE *archivos;
char extencion[20000]; // va contener la extencion
char path[20000]; // tiene el directorio
char *nombreArchivo;
unsigned num;
size_t end = strlen(argv[2])-1;
size_t end_path =strlen(argv[2])- (strlen(strrchr(argv[2],'/')+1));
int x=0;
if(strchr(argv[2],'/'))
{
strncpy(path,argv[2],end_path);
path[end_path]='\0';
}
strncpy(extencion , strrchr(argv[2],'.')+1, end);
nombreArchivo = basename(argv[2]);
num=cuentaArchivos(path, 1,extencion,argv[1],nombreArchivo,argc);
char linea[50000];
char nombrecompleto[50000];
//verifico apertura
if((archivos=fopen("/tmp/temporaldenombres", "r")) == NULL)
{
printf("El directorio no es valido o no existe \n");
errorMessage();
exit(1);
}
while(fgets(linea,sizeof(linea),archivos))
{
linea[strlen(linea)-1] ='\0';
if(!fork()) {
recur(linea,argv[1]);
return 0;
}
}
for(x=0; x<num; x++)
wait(NULL);
fclose(archivos);
remove("/tmp/temporaldenombres");
}
unsigned cuentaArchivos(char *ruta, int niv,char *extencion,char*patron,char *nombreArchivo, int cantidadArgumentos)
{
/* Con un puntero a DIR abriremos el directorio */
DIR *dir;
/* en *ent habrá información sobre el archivo que se está "sacando" a cada momento */
struct dirent *ent;
unsigned numfiles=0; /* Ficheros en el directorio actual */
unsigned char tipo; /* Tipo: fichero /directorio/enlace/etc */
char *nombrecompleto; /* Nombre completo del fichero */
char *posstr; /* Cadena usada para posicionarnos horizontalmente */
int validarTodos = 0;
dir = opendir (ruta);
/* Miramos que no haya error */
if (dir == NULL) {
error("No puedo abrir el directorio");
int errorMessage() ;
}
while ((ent = readdir (dir)) != NULL)
{
if ( (strcmp(ent->d_name, ".")!=0) && (strcmp(ent->d_name, "..")!=0) )
{
nombrecompleto=getFullName(ruta, ent);
tipo=getFileType(nombrecompleto, ent);
if (tipo!=DT_DIR)
{ if(strchr(ent->d_name,'.'))
{
//size_t begin = strlen(ent->d_name)-3;
size_t end = strlen(ent->d_name)-1;
char substr[2000];
strncpy(substr , strchr(ent->d_name,'.')+1, end);
if(nombreArchivo[0] == '*' && nombreArchivo[1] == '.'){
validarTodos = 1;
}
if(cantidadArgumentos >= 5){
validarTodos = 1;
}
if(strcmp(substr,extencion)==0)
{
if(validarTodos == 1){
grabar_nombre(nombrecompleto);
++numfiles;
}else if(!strcmp(nombreArchivo,ent->d_name)){
grabar_nombre(nombrecompleto);
++numfiles;
}
}
}
}
else
{ posstr=generaPosStr(niv);
// printf("Entrando en: %s\n",nombrecompleto);
numfiles+=cuentaArchivos(nombrecompleto, niv+1,extencion,patron,nombreArchivo,cantidadArgumentos);
/* Podemos poner las líneas que queramos */
free(posstr);
}
free(nombrecompleto);
}//FIN IF PRINCIPAL
}//FIN WHILE
closedir (dir);
return numfiles;
}
//procesa archivos recursivos
int recur(char *argv,char *patron)
{
//variables archivo
FILE *fp;//entrada
FILE *fps;//salida
char linea[5000];
int nl=1;
int numeroaciertos=0;
char nombrearchivo[5000];
//variables busqueda
int rv;
regex_t exp; //Our compiled expression
//verifico apertura
if((fp=fopen(argv, "r")) == NULL)
{
printf("El directorio no es valido o no existe %s \n",argv);
int errorMessage();
exit(1);
}
//1. CARGAR LA EXPRE
rv = regcomp(&exp,patron, REG_EXTENDED);//esta mal cambiar busqueda
if (rv != 0) {
printf("regcomp fallo con %d\n", rv);
int errorMessage() ;
}
//2. CORRER LA BUSQUEDA
while(fgets(linea,sizeof(linea),fp))
{
if(match(&exp,linea))
{
if(!numeroaciertos)
{
sprintf(nombrearchivo,"./%d.txt",getpid());
if((fps=fopen(nombrearchivo,"w")) == NULL)
{
printf("El directorio no es valido o no existe %s \n",nombrearchivo);
errorMessage();
exit(1);
}
fprintf(fps,"%s \n",argv);
fprintf(fps,"Linea %d : %s \n",nl,linea);
printf("%s \n",argv);
printf("Linea %d : %s \n",nl,linea);
numeroaciertos++;
}
else {
fprintf(fps,"Linea %d : %s\n",nl,linea);
printf("Linea %d : %s\n",nl,linea);
numeroaciertos++;
}
}//fin del if de acierto
nl++;
}//fin de recorrer lineas
if(numeroaciertos) {
//si hay aciertos cierro el archivo q se abrio para escrib
fclose(fps);
}
//cierro el arhivo de lectura
fclose(fp);
return 1;
}
//
void grabar_nombre(char * nombre)
{
FILE *fp1;//salida
if((fp1=fopen("/tmp/temporaldenombres","a+")) == NULL)
{
printf("El directorio no es valido o no existe \n");
int errorMessage();
exit(1);
}
fprintf(fp1,"%s\n",nombre);
fclose(fp1);
}
//tipo de archivo
unsigned char getFileType(char *nombre, struct dirent *ent)
{
unsigned char tipo;
tipo=ent->d_type;
if (tipo==DT_UNKNOWN)
{
tipo=statFileType(nombre);
}
return tipo;
}
//////////////////// funciones para validar archivos //////////////////////////
/* stat() vale para mucho más, pero sólo queremos el tipo ahora */
unsigned char statFileType(char *fname)
{
struct stat sdata;
/* Intentamos el stat() si no funciona, devolvemos tipo desconocido */
if (stat(fname, &sdata)==-1)
{
return DT_UNKNOWN;
}
switch (sdata.st_mode & S_IFMT)
{
case S_IFBLK:
return DT_BLK;
case S_IFCHR:
return DT_CHR;
case S_IFDIR:
return DT_DIR;
case S_IFIFO:
return DT_FIFO;
case S_IFLNK:
return DT_LNK;
case S_IFREG:
return DT_REG;
case S_IFSOCK:
return DT_SOCK;
default:
return DT_UNKNOWN;
}
}
//funcion para manejo de errores
void error(const char *s)
{
/* perror() devuelve la cadena S y el error (en cadena de caracteres) que tenga errno */
perror (s);
exit(EXIT_FAILURE);
}
//nombre completo
char *getFullName(char *ruta, struct dirent *ent)
{
char *nombrecompleto;
int tmp;
tmp=strlen(ruta);
nombrecompleto=malloc(tmp+strlen(ent->d_name)+2); /* Sumamos 2, por el \0 y la barra de directorios (/) no sabemos si falta */
if (ruta[tmp-1]=='/')
sprintf(nombrecompleto,"%s%s", ruta, ent->d_name);
else
sprintf(nombrecompleto,"%s/%s", ruta, ent->d_name);
return nombrecompleto;
}
char *generaPosStr(int niv)
{
int i;
char *tmp=malloc(niv*2+1); /* Dos espacios por nivel más terminador */
for (i=0; i<niv*2; ++i)
tmp[i]=' ';
tmp[niv*2]='\0';
return tmp;
}
/* Se encarga de hacer la busqueda */
int match(regex_t *pexp, char *sz) {
regmatch_t matches[1];
if (regexec(pexp, sz, 1, matches, 0) == 0) {
return 1;
} else {
return 0;
}
}
int errorMessage() {
printf("AYUDA \n");
printf("El programa simula el funcionamiento del comando grep,");
printf("se recibe como parámetros el patrón a buscar,");
printf("un filtro para los archivos que tiene que evaluar\n");
printf("OPCIONAL indique si la búsqueda debe incluir subdirectorios\n");
printf("MODO DE USO \n");
printf("1-$ ./c_grep /patron/ *.txt \n");
printf("2-$ ./c_grep /patron/ ./*.dat [-r] <Busca en subdirectorios \n");
printf("PARAMETROS \n");
printf("-? Para pedir la ayuda\n");
printf("/patron/ Se pude utilizar patrones de busqueda para la busqueda en los archivos\n");
printf("path/*.dat Direccion de archivo/s a buscar con su extencion \n");
printf("[-r] <Busca en subdirectorios \n");
printf("ACLARACIONES: \n");
printf("1-El programa solo busca en archivos de texto\n");
printf("2-Si se encuentran aciertos se crea un archivo que contiene : el archivo leído,");
printf("el número de línea en que se encontró coincidencia y el contenido de la misma");
printf("\n3-Estos archivos con los aciertos se alojaran en el direcotorio donde se ejecuto el comando.\n");
return 1;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include "lib.h"
void inicializarArray(sProducto* campo, int size)
{
int i;
for(i=0; i<CANT; i++)
{
campo[i].estaCargado=0; //inicializo en 0, no esta cargado
}
}
int carga(int size, char msj, sProducto* campo)
{
char auxPosicion[10];
char bufferNombre[200];
char bufferDescripcion[300];
char bufferPrecio[200];
int auxPosicionEntero;
printf(msj); //ingrese posicion
if(validarNumero(fgets(auxPosicion, 10, stdin)==0))
{
auxPosicionEntero=atoi(auxPosicion);
if(auxPosicionEntero <= size && auxPosicionEntero > 0)
{
auxPosicionEntero=auxPosicionEntero-1;
if(campo[auxPosicionEntero].estaCargado==0)
{
//while(flag==0) //0 esta bien
fgets(bufferNombre, 200, stdin);
fgets(bufferDescripcion, 200, stdin);
fgets(bufferPrecio, 200, stdin);
}
}
}
if(validarLetras(bufferNombre)==0 && validarLetras(bufferDescripcion)==0 && validarFlotante(bufferPrecio)==0)
{
campo[auxPosicionEntero].nombre
}
}
int validarNumero(char`* valor)
{
int retorno =0; //0 esta bien
return retorno;
}
int validarLetras(char`* valor)
{
int retorno =0; //0 esta bien
return retorno;
}
int validarFlotante(char`* valor)
{
int retorno =0; //0 esta bien
return retorno;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.