language
large_stringclasses 1
value | text
stringlengths 9
2.95M
|
---|---|
C
|
/*
Lee una secuencia y extrae la frecuencia relativa de ACGT
Reads a sequence and calcs ACGT frequencies
*/
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <sys/types.h>
#include <dirent.h>
#include <math.h>
#include <time.h>
int main(int ac,char** av){
char c;
int i,j,n;
if(ac<2){
printf("\n Uso:\n\tprobACGT entrada salida \n");exit(-1);
}
j=0;
// Open files.
FILE *fe,*fs;
if((fe=fopen(av[1],"r"))==NULL){
printf("Error\n");
}
if((fs=fopen(av[2],"w"))==NULL){
printf("Error\n");
}
// Hay que saltar la primera línea e insertarla en el archivo salida
// first line
c=getc(fe);
while(c!='\n') {
c=getc(fe);
}
i=0;
int A,C,G,T;
float pA,pC,pG,pT;
A=C=G=T=0;
while(!feof(fe)){
c=getc(fe);
//printf("%c.%d\n",c,i);
switch(c){
case 'A':
A++; i++;
break;
case 'C':
C++; i++;
break;
case 'G':
G++; i++;
break;
case 'T':
T++; i++;
break;
default:
break;
}
}
n=i;
pA=(float)A/i;
pC=(float)C/i;
pG=(float)G/i;
pT=(float)T/i;
fclose(fe);
fprintf(fs,"A\t%f\nC\t%f\nG\t%f\nT\t%f\n",pA,pC,pG,pT);
fclose(fs);
return 0;
}
|
C
|
/*2.2. Realizar un algoritmo (en seudo o en C), que lea el archivo de texto generado en el ejercicio anterior y visualice por pantalla cada registro del archivo. */
#include<stdio.h>
void imprimirArchivo(FILE *file,int *registrosLeidos);
int main(){
FILE *file = fopen("Alumnos_eje1_5.txt","r");/*Abre el archivo en modo lectura */
int registrosLeidos = 0;
imprimirArchivo(file,®istrosLeidos);
printf("\nLa cantidad de registros leidos es: %d",registrosLeidos);
return 0;
}
void imprimirArchivo(FILE *file,int *registrosLeidos){
if(file == NULL){/*null resulta ser un valor especial aplicado a un puntero (o referencia) usado para indicar que no se apunta a un objeto o dato vlidos*/
printf("Error abriendo el archivo");
}else{
printf("Contenido del archivo:\n-----------------------\n" );
char _char; /*variable para almacenar el carcter leido del archivo*/
/*La funcin feof() se utiliza para detectar cuando no quedan ms elementos en un archivo, devolviendo un valor distinto de cero en este caso. */
while (!feof(file)) { /* mientras no sea fin de archivo*/
_char = fgetc(file);/*leer 1 carcter del archivo y mueve el puntero interno al siguiente carcter del archivo*/
printf( "%c",_char); /*imprmir carcter leido*/
if(_char == ';'){/*el fin de cada lnea era ";"*/
*registrosLeidos+=1;
}
}
fclose(file); /*Cierra el archivo*/
}
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include "thread.h"
void switch_to(struct task_struct *next); // 定义在 switch.s 中
static struct task_struct init_task = {0, NULL, 0, {0}};
struct task_struct *current = &init_task;
struct task_struct *pick()
{
int current_id = current->id;
int i = current_id;
struct task_struct *next = NULL;
// 寻找下一个不空的线程
while (1)
{
i = (i + 1) % NR_TASKS;
if (task[i])
{
next = task[i];
break;
}
}
return next;
}
void schedule()
{
struct task_struct *next = pick();
if (next)
{
switch_to(next);
}
}
|
C
|
/*
* Daniel Goncalves > 1151452@isep.ipp.pt
* ARQCP - Turma 2DK
*
* main.c
*
*/
#include <stdio.h>
#include "test_equal.h"
/*
* Module 4 - Exercise 6
*/
int main(void) {
// 1
char str1[] = "Hello";
char *ptr1 = str1;
char str2[] = "Hello";
char *ptr2 = str2;
int boolean = test_equal(ptr1, ptr2);
printf("String 1: \"%s\"\nString 2: \"%s\"\nString 1 & 2 are %sequal\n\n",
str1, str2, (boolean == 1) ? "" : "not ");
// 2
char str3[] = "Hi";
ptr1 = str3;
char str4[] = "Hello";
ptr2 = str4;
boolean = test_equal(ptr1, ptr2);
printf("String 1: \"%s\"\nString 2: \"%s\"\nString 1 & 2 are %sequal\n\n",
str3, str4, (boolean == 1) ? "" : "not ");
// 3
char str5[] = "";
ptr1 = str5;
char str6[] = "";
ptr2 = str6;
boolean = test_equal(ptr1, ptr2);
printf("String 1: \"%s\"\nString 2: \"%s\"\nString 1 & 2 are %sequal\n\n",
str5, str6, (boolean == 1) ? "" : "not ");
// 4
char str7[] = "Trump is the new USA President!";
ptr1 = str7;
char str8[] = "That is so wrong in many ways!";
ptr2 = str8;
boolean = test_equal(ptr1, ptr2);
printf("String 1: \"%s\"\nString 2: \"%s\"\nString 1 & 2 are %sequal\n\n",
str7, str8, (boolean == 1) ? "" : "not ");
return 0;
}
|
C
|
/**
* Take a DFA and remove indistinguishable states
* The DFA is represented as a transition table.
*/
#include "minimize_dfa.h"
#include "string.h"
#include "common.h"
#include "queue.h"
#include "is_reg_lang_empty.h"
#ifndef HOPCROFT_ALGO
/**
* An implementation of :
*
* MR403320 (53 #7132) 68A25 (94A30)
* Hopcroft, John An $n$ log $n$ algorithm for minimizing states in a finite automaton.
* Theory of machines and computations (Proc. Internat. Sympos., Technion, Haifa, 1971), pp. 189–196. Academic Press, New York, 1971.
*/
// This transformation is inverse of itself.
#define REVERSE_INDEX(__NUM__, __INDEX__) (__NUM__) - (__INDEX__) - 1
#define COND_SWAP(FIRST, SECOND) \
int temp;\
if (FIRST > SECOND) {\
temp = FIRST;\
FIRST = SECOND;\
SECOND = temp;\
}
#endif
int* find_reachable(DFA *in_dfa, DFA *out_dfa)
{
int* reachable = (int*) malloc(sizeof(int) * in_dfa->num_states);
memset(reachable + 1, 0, sizeof(int) * in_dfa->num_states - 1);
Queue* queue = create_queue();
// push the start state.
queue_push(queue, 0);
reachable[0] = 1;
out_dfa->num_states++;
// do BFS on the in_dfa transition Directed Graph.
while(!queue_empty(queue)) {
int elem, c_elem;
elem = queue_pop(queue);
for (int i = 0; i < in_dfa->num_char; i++) {
c_elem = in_dfa->transition_func[elem][i];
if (!reachable[c_elem]) {
queue_push(queue, c_elem);
reachable[c_elem] = 1;
out_dfa->num_states++;
}
}
}
return reachable;
}
void create_transition_function(DFA *in_dfa, DFA *out_dfa, int *state_map)
{
int* reachable = find_reachable(in_dfa, out_dfa);
// transition function
out_dfa->transition_func = (int**) malloc(sizeof(int*)
* out_dfa->num_states);
memset(state_map, -1, sizeof(int)*in_dfa->num_states);
int count = 0;
for (int i = 0; i < in_dfa->num_states; i++) {
if (reachable[i])
state_map[i] = count++;
}
assert_cond(count == out_dfa->num_states, "element count mismatch");
for (int i = 0; i < in_dfa->num_states; i++) {
if (reachable[i]) {
out_dfa->transition_func[state_map[i]] = (int*) malloc(sizeof(int)
* in_dfa->num_char);
for (int j = 0; j < in_dfa->num_char; j++) {
assert_cond(state_map[in_dfa->transition_func[i][j]] != -1,
"Some reachable state did not get marked");
out_dfa->transition_func[state_map[i]][j] =
state_map[in_dfa->transition_func[i][j]];
}
}
}
free(reachable);
}
void find_final_states(DFA *in_dfa, DFA *out_dfa, int *state_map)
{
int* final = (int*) malloc(sizeof(int) * out_dfa->num_states);
out_dfa->num_final_states = 0;
memset(final, 0, sizeof(int) * out_dfa->num_states);
for (int i = 0; i < in_dfa->num_final_states; i++) {
int state;
state = state_map[in_dfa->final_states[i]];
if (state != -1) {
final[state] = 1;
out_dfa->num_final_states++;
}
}
assert_cond(out_dfa->num_final_states <= in_dfa->num_final_states,
"final states in new dfa should be less or equal");
out_dfa->final_states = (int*) malloc(sizeof(int) * out_dfa->num_final_states);
int count = 0;
for (int i = 0; i < out_dfa->num_states; i++) {
if (final[i]) out_dfa->final_states[count++] = i;
}
free(final);
}
DFA *remove_unreachable(DFA *in_dfa)
{
DFA *out_dfa = (DFA*) malloc(sizeof(DFA));
out_dfa->num_states = 0;
int* state_map = (int*) malloc(sizeof(int) * in_dfa->num_states);
create_transition_function(in_dfa, out_dfa, state_map);
find_final_states(in_dfa, out_dfa, state_map);
free(state_map);
out_dfa->num_char = in_dfa->num_char;
return out_dfa;
}
#ifdef HOPCROFT_ALGO
#define DOUBLE_LIST_INSERT(STATE, BLOCK_NUM, HEAD)\
blocks[BLOCK_NUM]->HEAD = double_list_insert(blocks[BLOCK_NUM]->HEAD,\
&dbl_lst_nodes[STATE]);\
dbl_lst_nodes[STATE].block_num = BLOCK_NUM;\
blocks[BLOCK_NUM]->num_elem++;\
for (j = 0; j < in_dfa->num_char; j++) {\
if (inv_trans_func[STATE][j]->count != 0)\
blocks[BLOCK_NUM]->elem_count[j]++;\
}
#define DOUBLE_LIST_REMOVE(STATE, BLOCK_NUM, HEAD)\
blocks[BLOCK_NUM]->HEAD = double_list_remove(blocks[BLOCK_NUM]->HEAD,\
&dbl_lst_nodes[STATE]);\
blocks[BLOCK_NUM]->num_elem--;\
for (j = 0; j < in_dfa->num_char; j++) {\
if (inv_trans_func[STATE][j]->count != 0)\
blocks[BLOCK_NUM]->elem_count[j]--;\
}
DoubleList* create_dbl_lst_nodes(int num_states)
{
// vector of nodes
DoubleList *dbl_lst_nodes = (DoubleList*) malloc(sizeof(DoubleList) * num_states);
for (int i = 0; i < num_states; i++) {
dbl_lst_nodes[i].state_num = i;
dbl_lst_nodes[i].block_num = -1;
dbl_lst_nodes[i].to_move = 0;
dbl_lst_nodes[i].previous = dbl_lst_nodes[i].next = NULL;
}
return dbl_lst_nodes;
}
void destroy_dbl_lst_nodes(DoubleList* dbl_lst_nodes)
{
free(dbl_lst_nodes);
}
InverseTrans*** crt_inv_transtn_tbl(DFA *in_dfa, DoubleList *nodes)
{
int i, j;
// Create inverse transition table.
InverseTrans ***inv_trans_func = (InverseTrans***)
malloc(sizeof(InverseTrans**) * in_dfa->num_states);
for (i = 0; i < in_dfa->num_states; i++) {
inv_trans_func[i] = (InverseTrans**)
malloc(sizeof(InverseTrans*) * in_dfa->num_char);
for (j = 0; j < in_dfa->num_char; j++) {
inv_trans_func[i][j] = (InverseTrans*) malloc(sizeof(InverseTrans));
inv_trans_func[i][j]->list = NULL;
inv_trans_func[i][j]->count = 0;
}
}
List *list_node;
int target;
for (i = 0; i < in_dfa->num_states; i++) {
for (j = 0; j < in_dfa->num_char; j++) {
list_node = (List*) malloc(sizeof(List));
list_node->dbl_node = &nodes[i];
list_node->state_num = i;
target = in_dfa->transition_func[i][j];
inv_trans_func[target][j]->count++;
inv_trans_func[target][j]->list = list_insert(inv_trans_func[target][j]->list,
list_node);
}
}
return inv_trans_func;
}
void destroy_inv_transtn_tbl(InverseTrans*** inv_trans_func, DFA* in_dfa)
{
for (int i = 0; i < in_dfa->num_states; i++) {
for (int j = 0; j < in_dfa->num_char; j++) {
free(inv_trans_func[i][j]);
}
free(inv_trans_func[i]);
}
free(inv_trans_func);
}
Block** initialize_blocks(DFA *in_dfa, DoubleList *dbl_lst_nodes, InverseTrans ***inv_trans_func)
{
int i,j;
// vector of blocks
Block **blocks = (Block**) malloc(sizeof(Block*) * in_dfa->num_states);
for (i = 0; i < in_dfa->num_states; i++) {
blocks[i] = (Block*) malloc(sizeof(Block));
blocks[i]->head = NULL;
blocks[i]->move_head = NULL;
blocks[i]->elem_count = (int*) malloc(sizeof(int)*in_dfa->num_char);
memset(blocks[i]->elem_count, 0, in_dfa->num_char*sizeof(int));
blocks[i]->num_elem = 0;
blocks[i]->move_count = 0;
}
int state;
for (i = 0; i < in_dfa->num_final_states; i++) {
state = in_dfa->final_states[i];
DOUBLE_LIST_INSERT(state, 0, head);
}
for (i = 0; i < in_dfa->num_states; i++) {
if (dbl_lst_nodes[i].block_num == -1) {
DOUBLE_LIST_INSERT(i, 1, head);
}
}
return blocks;
}
void destroy_blocks(Block** blocks, int num_states)
{
for (int i = 0; i < num_states; i++) {
free(blocks[i]);
}
free(blocks);
}
#if DEBUG
void print_blocks(Block** blocks, int num_states, int num_char)
{
DoubleList* dbl_node;
for (int i = 0; i < num_states; i++) {
printf("Block %d\n", i);
for (int j = 0; j < num_char; j++)
printf("%d ", blocks[i]->elem_count[j]);
printf("\n");
dbl_node = blocks[i]->head;
if (dbl_node) {
printf("%d", dbl_node->state_num);
dbl_node = dbl_node->next;
while (dbl_node) {
printf(" -> ");
printf("%d", dbl_node->state_num);
dbl_node = dbl_node->next;
}
printf("\n");
}
else printf("empty!\n");
}
printf("\n\n");
}
#endif
List** initialize_l_sets(DFA* in_dfa, Block** blocks)
{
int i;
List **l_sets = (List**) malloc(sizeof(List*)*in_dfa->num_char);
for (i = 0; i < in_dfa->num_char; i++)
l_sets[i] = NULL;
// init L sets for each char
List *node;
for (i = 0; i < in_dfa->num_char; i++) {
node = (List*) malloc(sizeof(List));
if (blocks[0]->elem_count[i] <= blocks[1]->elem_count[i]
&& blocks[0]->elem_count[i] != 0) {
node->state_num = 0;
l_sets[i] = list_insert(l_sets[i], node);
}
else if(blocks[1]->elem_count[i] != 0) {
node->state_num = 1;
l_sets[i] = list_insert(l_sets[i], node);
}
else if (blocks[0]->elem_count[i] != 0) {
node->state_num = 0;
l_sets[i] = list_insert(l_sets[i], node);
}
}
return l_sets;
}
void destroy_l_sets(List** l_sets)
{
free(l_sets);
}
#if DEBUG
void print_l_sets(List** l_sets, int num_char)
{
List *node;
for (int i = 0; i < num_char; i++) {
printf("Lset num %d\n", i);
node = l_sets[i];
if (node) {
printf("%d", node->state_num);
node = node->next;
while(node) printf(" -> %d", node->state_num);
}
printf("\n");
}
}
#endif
int refine_blocks(DFA *in_dfa, InverseTrans ***inv_trans_func, List **l_sets,
Block **blocks, DoubleList* dbl_lst_nodes)
{
int i, j, num_states = 2, ref_block, from_block;
List *frm_state, *node;
DoubleList *dbl_node, *to_state;
List *move_head = NULL;
List *move_nde_lst = (List*) malloc(sizeof(List)
* in_dfa->num_states);
for (i = 0; i < in_dfa->num_states; i++) {
move_nde_lst[i].block_num = i;
move_nde_lst[i].to_move = 0;
move_nde_lst[i].next = NULL;
}
while (1) {
#if DEBUG
print_l_sets(l_sets, in_dfa->num_char);
print_blocks(blocks, num_states, in_dfa->num_char);
#endif
// pick one set from L and one char
for (i = 0; i < in_dfa->num_char; i++) {
if (l_sets[i] != NULL)
break;
}
if (i != in_dfa->num_char) {
node = l_sets[i];
l_sets[i] = node->next;
ref_block = node->state_num;
free(node);
// refine using that set and char
// put blocks on copy list
to_state = blocks[ref_block]->head;
while (to_state != NULL) {
frm_state = inv_trans_func[to_state->state_num][i]->list;
while (frm_state != NULL) {
dbl_node = frm_state->dbl_node;
from_block = dbl_node->block_num;
if (from_block != ref_block
&& dbl_node->to_move == 0) {
blocks[from_block]->head = double_list_remove(blocks[from_block]->head,
dbl_node);
blocks[from_block]->move_head = double_list_insert(
blocks[from_block]->move_head,
dbl_node);
dbl_node->to_move = 1;
if (move_nde_lst[from_block].to_move == 0) {
move_head = list_insert(move_head, &move_nde_lst[from_block]);
move_nde_lst[from_block].to_move = 1;
}
blocks[from_block]->move_count++;
}
frm_state = frm_state->next;
}
to_state = to_state->next;
} // put on copy list
while (move_head) {
from_block = move_head->block_num;
if (blocks[from_block]->move_count != blocks[from_block]->num_elem) {
// copy to new block
dbl_node = blocks[from_block]->move_head;
do {
DOUBLE_LIST_REMOVE(dbl_node->state_num, from_block, move_head);
DOUBLE_LIST_INSERT(dbl_node->state_num, num_states, head);
dbl_node->to_move = 0;
dbl_node = blocks[from_block]->move_head;
} while (dbl_node);
// update l_sets
for (j = 0; j < in_dfa->num_char; j++) {
node = (List*) malloc(sizeof(List));
if (blocks[num_states]->elem_count[j] <= blocks[from_block]->elem_count[j]
&& blocks[num_states]->elem_count[j] != 0) {
node->state_num = num_states;
l_sets[j] = list_insert(l_sets[j], node);
}
else if (blocks[from_block]->elem_count[j] != 0) {
node->state_num = from_block;
if (list_search(l_sets[j], node) == NULL)
l_sets[j] = list_insert(l_sets[j], node);
}
else if (blocks[num_states]->elem_count[j] != 0) {
node->state_num = num_states;
l_sets[j] = list_insert(l_sets[j], node);
}
}
num_states++;
}
else {
// copy back from move head to head
dbl_node = blocks[from_block]->move_head;
do {
blocks[from_block]->move_head = double_list_remove(
blocks[from_block]->move_head,
dbl_node);
blocks[from_block]->head = double_list_insert(blocks[from_block]->head,
dbl_node);
dbl_node->to_move = 0;
dbl_node = blocks[from_block]->move_head;
} while (dbl_node);
}
blocks[from_block]->move_count = 0;
move_head->to_move = 0;
move_head = list_remove(move_head, move_head);
}
} // if i found
else {
break;
}
}
free(move_nde_lst);
return num_states;
}
DFA* create_out_dfa(DFA *in_dfa, DoubleList *dbl_lst_nodes,
Block **blocks, int num_states )
{
// Create out DFA
int state;
DFA *out_dfa = (DFA*) malloc(sizeof(DFA));
out_dfa->num_states = num_states;
out_dfa->num_char = in_dfa->num_char;
out_dfa->transition_func = (int**) malloc(sizeof(int*) * num_states);
out_dfa->num_final_states = 0;
// Calculate old final states.
int* old_final_states = (int*) malloc(sizeof(int) * in_dfa->num_states);
int* final_states = (int*) malloc(sizeof(int) * num_states);
memset(old_final_states, 0, sizeof(int) * in_dfa->num_states);
memset(final_states, 0, sizeof(int) * num_states);
for (int i = 0; i < in_dfa->num_final_states; i++) {
old_final_states[in_dfa->final_states[i]] = 1;
}
// Create new transition function and mark new final states.
for (int i = 0; i < num_states; i++) {
out_dfa->transition_func[i] = (int*) malloc(sizeof(int) * in_dfa->num_char);
for (int j = 0; j < in_dfa->num_char; j++) {
state = in_dfa->transition_func[blocks[i]->head->state_num][j];
out_dfa->transition_func[i][j] = dbl_lst_nodes[state].block_num;
}
state = blocks[i]->head->state_num;
if (old_final_states[state]) {
final_states[i] = 1;
out_dfa->num_final_states++;
}
}
// create new final states list.
out_dfa->final_states = (int*) malloc(sizeof(int) * out_dfa->num_final_states);
int j = 0;
for (int i = 0; i < num_states; i++) {
if (final_states[i]) {
out_dfa->final_states[j] = i;
j++;
}
}
// free up the memory
free(final_states);
free(old_final_states);
return out_dfa;
}
// Hopcroft's partitioning into equivalence set
// algorithm.
DFA *remove_indistinguishable(DFA *in_dfa)
{
DoubleList* dbl_lst_nodes = create_dbl_lst_nodes(in_dfa->num_states);
InverseTrans ***inv_trans_func = crt_inv_transtn_tbl(in_dfa, dbl_lst_nodes);
Block **blocks = initialize_blocks(in_dfa, dbl_lst_nodes, inv_trans_func);
List **l_sets = initialize_l_sets(in_dfa, blocks);
int num_states = refine_blocks(in_dfa, inv_trans_func, l_sets, blocks,
dbl_lst_nodes);
destroy_l_sets(l_sets);
destroy_inv_transtn_tbl(inv_trans_func, in_dfa);
DFA *out_dfa = create_out_dfa(in_dfa, dbl_lst_nodes, blocks, num_states);
// Free up memory
destroy_blocks(blocks, in_dfa->num_states);
destroy_dbl_lst_nodes(dbl_lst_nodes);
// Free up the in_dfa and associated data.
for (int i = 0; i < in_dfa->num_states; i++)
free(in_dfa->transition_func[i]);
free(in_dfa->transition_func);
free(in_dfa->final_states);
free(in_dfa);
return out_dfa;
}
#else
// The inductive discovery algorithm for
// finding distinguishable pairs
DFA *remove_indistinguishable(DFA *in_dfa)
{
int i, j;
int states = in_dfa->num_states;
int chars = in_dfa->num_char;
int *final_states = (int*) malloc(sizeof(int)*states);
memset(final_states, 0, states*sizeof(int));
// copy over final states info
for (i = 0; i < in_dfa->num_final_states; i++)
{
final_states[in_dfa->final_states[i]] = 1;
}
// dist_pairs stores columns in reverse and does not
// have column for index 0 (state 0)
// rows are stored from 0 but last state does not have
// a row.
// Only the upper triangle is of interest.
int **dist_pairs = (int**) malloc(sizeof(int*) * (states - 1));
// Base case:
// distinguish final and non-final
for (i = 0; i < states - 1; i++)
{
dist_pairs[i] = (int*) malloc(sizeof(int) * (states - 1));
for (j = 0; j < REVERSE_INDEX(states, i); j++)
{
if (final_states[i] != final_states[REVERSE_INDEX(states, j)])
dist_pairs[i][j] = 1;
else
dist_pairs[i][j] = 0;
}
}
// Induction:
// All pair which transition to distinguished pair
// on some input alphabet are distinguishable
int added, k, row, col;
do {
added = 0;
for (i = 0; i < states - 1; i++)
{
for (j = 0; j < REVERSE_INDEX(states, i); j++)
{
if (dist_pairs[i][j] == 1) continue;
for ( k = 0; k < chars; k++)
{
row = in_dfa->transition_func[i][k];
col = in_dfa->transition_func[REVERSE_INDEX(states, j)][k];
if (col != row)
{
COND_SWAP(row, col);
if (dist_pairs[row][REVERSE_INDEX(states, col)] == 1) {
dist_pairs[i][j] = 1;
added = 1;
break;
}
}
}
}
}
} while (added); // keep doing till last iteration produced a new pair
int new_index = 0, num_final = 0;
int *indist_states = (int*) malloc(sizeof(int)*states);
int *new_final_states = (int*) malloc(sizeof(int)*states);
for (i = 0; i < states; i++)
indist_states[i] = -1;
// re-calculate state indexes
for (i = 0; i < states - 1; i++)
{
if (indist_states[i] == -1) {
indist_states[i] = new_index;
if (final_states[i])
new_final_states[num_final++] = new_index;
new_index++;
}
for (j = 0; j < REVERSE_INDEX(states, i); j++)
{
if (indist_states[REVERSE_INDEX(states, j)] == -1 && dist_pairs[i][j] == 0)
{
indist_states[REVERSE_INDEX(states, j)] = indist_states[i];
}
}
}
// check if last state was considered
if (indist_states[states - 1] == -1) {
indist_states[states - 1] = new_index;
if (final_states[i])
new_final_states[num_final++] = new_index;
new_index++;
}
DFA *out_dfa = (DFA*) malloc(sizeof(DFA));
int **transition_function = (int**) malloc(sizeof(int*)*new_index);
int last_group = -1;
for (i = 0; i < states; i++)
{
if (indist_states[i] <= last_group) continue;
transition_function[++last_group] = (int*) malloc(sizeof(int)*chars);
assert_cond(last_group == indist_states[i], "Group being considered does not\
match states new index");
for (j = 0; j < chars; j++)
{
transition_function[last_group][j] =
indist_states[in_dfa->transition_func[i][j]];
}
}
assert_cond(last_group + 1 == new_index, "Number of rows added to transition \
function does not match new state count. LG: %d, NI: %d", last_group, new_index);
out_dfa->transition_func = transition_function;
out_dfa->num_char = chars;
out_dfa->num_states = new_index;
out_dfa->final_states = (int*) malloc(num_final*sizeof(int));
memcpy(out_dfa->final_states, new_final_states, sizeof(int)*num_final);
out_dfa->num_final_states = num_final;
// mem cleanup
free(final_states);
for (i = 0; i < states - 1; i++)
free(dist_pairs[i]);
free(dist_pairs);
free(indist_states);
free(new_final_states);
return out_dfa;
}
#endif
DFA *minimize_dfa(DFA *in_dfa)
{
if (is_reg_lang_empty(in_dfa)) {
printf("Input regular language is empty, can't be minimized!\n");
exit(EXIT_FAILURE);
}
DFA* out_dfa = remove_unreachable(in_dfa);
printf("Reachable states %d\n\n", out_dfa->num_states);
out_dfa = remove_indistinguishable(out_dfa);
return out_dfa;
}
int main(int argc, char **argv)
{
int i, j;
check_arg_count(argc, 2, "Usage: mindfa <DFA_FILE>\n");
DFA *out_dfa = minimize_dfa(parse_dfa(argv[1]));
printf("Out DFA\n\n");
printf("Num states %d \n", out_dfa->num_states);
printf("Num char %d \n", out_dfa->num_char);
printf("Transition Function:\n");
for (i = 0; i < out_dfa->num_states; i++)
{
printf("%d:", i);
for (j = 0; j < out_dfa->num_char; j++)
{
printf("\t%d", out_dfa->transition_func[i][j]);
}
printf("\n");
}
printf("Final states: %d\n", out_dfa->num_final_states);
printf("Final state:\t");
for (i = 0; i < out_dfa->num_final_states; i++)
{
printf("%d\t", out_dfa->final_states[i]);
}
printf("\n\n");
return 0;
}
|
C
|
#include<stdio.h>
int main(){
float j,r,t;
scanf("%f",&j);
scanf("%f",&r);
scanf("%f",&t);
if(j<r){
if(r<t)printf("%.1f\n",t);
else printf("%.1f\n",r);
}
else {
if(j<t)printf("%.1f\n",t);
else printf("%.1f\n",j);
}
return 0;
}
|
C
|
#ifndef CIRCULARLY_LIST_H
#define CIRCULARLY_LIST_H
#define CLIST_INIT(list) \
{ \
(list)->head = NULL; \
}
#define CLIST_ENTRY_INIT(entry) \
{ \
(entry)->prev = entry; \
(entry)->next = entry; \
}
#define CLIST_HEAD(list) \
(list)->head
#define CLIST_TAIL(list) \
(((list)->head != NULL) ? (list)->head->prev : NULL)
#define CLIST_IS_EMPTY(list) \
((list)->head == NULL)
#define CLIST_IS_TAIL(list, entry) \
(((list)->head != NULL) ? ((list)->head->prev == (entry)) : 0)
#define CLIST_ADD(list, entry) \
{ \
if (CLIST_IS_EMPTY(list)) { \
(entry)->next = entry; \
(entry)->prev = entry; \
(list)->head = entry; \
} else { \
(entry)->next = (list)->head; \
(entry)->prev = CLIST_TAIL(list); \
(entry)->prev->next = (entry); \
(entry)->next->prev = (entry); \
} \
}
#define CLIST_REMOVE(list, entry) \
{ \
if ((list)->head == (entry)) { \
(list)->head = ((entry)->next != (entry)) ? (entry)->next : NULL; \
} \
(entry)->prev->next = (entry)->next; \
(entry)->next->prev = (entry)->prev; \
}
#define CLIST_ENTRY_NEXT(entry) \
(entry)->next
#define CLIST_ENTRY_PREV(entry) \
(entry)->prev
#define CLIST_HAS_NEXT(list, entry) \
((list)->head != (entry)->next)
#endif /* CIRCULARLY_LIST_H */
|
C
|
#include<stdio.h>
#include<stdlib.h>
int *fun();
int main()
{
int *ptr;
ptr=fun();
printf("%d\n",*ptr);
return 0;
}
int *fun()
{
//int *point;
int *point = malloc(1*(sizeof *point));
if (point == NULL)
printf("Memory allocation failed\n");
*point=12;
return point;
}
|
C
|
/**Перевод температуры из градусов по Фаренгейту в градусы по Цельсию*/
#include <stdio.h>
#define LOWER 0 // нижний предел температуры
#define UPPER 300 // верхний предел температуры
#define STEP 20 // шаг изменения температуры
void convert();
int main()
{
printf("Temperature convert\n");
printf("-------------------\n");
printf("%2c %5c\n", 'F', 'C');
printf("-------------------\n");
convert();
}
void convert() { // расчет температуры и вывод на экран
for(int fahr = LOWER; fahr <= UPPER; fahr = fahr + STEP) {
printf("%3d %6.2f\n", fahr, (5.0 / 9.0) * (fahr - 32.0));
}
}
|
C
|
#include <stdio.h>
#include <math.h>
#define MAX 100000000
#define LIMIT 10000
#define PRIMELEN 5761456
unsigned flag[(MAX>>6) + 1];
int primes[PRIMELEN+10], total;
#define isComposite(x) (flag[x>>6]&(1<<((x>>1)&31)))
#define setComposite(x) (flag[x>>6]|=(1<<((x>>1)&31)))
void primeSieve()
{
int i, j, k;
for(i=3; i<LIMIT; i+=2)
if(!isComposite(i))
for(j=i*i,k=i<<1; j<MAX; j+=k)
setComposite(j);
primes[0] = -1;
primes[1] = 2;
for(i=3,j=2; i<MAX; i+=2)
if(!isComposite(i))
primes[j++] = i;
total = j;
}
int binarySearch(int start, int end, int value)
{
int mid;
while(start <= end)
{
if(value < primes[start])
return start-1;
if(value > primes[end])
return end;
mid = (start+end) / 2;
if(value == primes[mid])
return mid;
else if(value < primes[mid])
end = mid-1;
else
start = mid+1;
}
return total-1;
}
int main()
{
primeSieve();
unsigned int n;
double x, p, error;
while(scanf("%d", &n)==1 && n)
{
p = binarySearch(0, total-1, n);
x = n;
error = ( fabs(p - x/log(x)) / p ) * 100.0;
printf("%.1lf\n", error);
}
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
///lipseste un subpunct.repetitia
void citire(char **s,char **titlu,char *numeFisier)
{
FILE *f;
f=fopen(numeFisier,"r");
if(f==NULL)
{
printf("Eroare deschidere fisier");
return ;
}
char c = fgetc(f);
int lung = 0;
(*titlu) = NULL;
while(c!='\n')
{
lung ++;
char *aux1;
aux1 = realloc ( *titlu, (lung+1)*sizeof(char));
if(aux1 == NULL)
return ;
(*titlu) = aux1;
(*titlu)[lung-1]=c;
(*titlu)[lung] = '\0';
c = fgetc(f);
}
lung=0;
c=fgetc(f);//citim \n de dupa titlu
(*s) = NULL;
while( (c = fgetc(f)) != EOF )
{
lung++;
char *aux1;
aux1 = realloc ( *s, (lung+1)*sizeof(char));
if(aux1 == NULL)
return ;
(*s) = aux1;
(*s)[lung-1]=c;
(*s)[lung] = '\0';
}
printf("%s %s",*titlu,*s);
fclose(f);
}
void initializareZero(int v[],int n)
{
int i;
for(i=0;i<n;i++)
v[i]=0;
}
void transformMic(char *c)
{
if((*c)>='A' && (*c)<='Z')
(*c)=(*c)-'A'+'a';
}
void asonanta(char *s)
{
int v['z'-'a'+1];
initializareZero(v,'z'-'a'+1);
int rand=1;
int maxi=0;
int i;
for(i=0;s[i];i++)
{
char c=s[i];
if(c=='\n')
{
if(maxi!=0)
{
printf("rand=%d ",rand);
int j;
for(j=0;j<'z'-'a'+1;j++)
if(v[j]==maxi)
printf("%c ",j+'a');
printf("\n");
rand++;
initializareZero(v,'z'-'a'+1);
maxi=0;
}
}
else
{
if(strchr("aeiouAEIOU",c))
{
transformMic(&c);
v[c-'a']++;
if(v[c-'a']>maxi)maxi=v[c-'a'];
}
}
}
}
void ingambament(char *s,char *numeFisier)
{
FILE *f;
f=fopen(numeFisier,"w");
if(f==NULL)
{
printf("Eroare deschidere fisier");
return ;
}
char *t,*p;
int lung=strlen(s);
t=(char *)malloc(lung*sizeof(char));
strcpy(t,s);
//ca sa nu pierdem sirul initial
p=strtok(t,"\n");
while(p)
{
if(p[0]>='a' && p[0]<='z') //e litera mica
fprintf(f,"%s \n",p);
p=strtok(NULL,"\n");
}
fclose(f);
}
int main()
{
char *titlu,*s;
citire(&s,&titlu,"poezie.txt");
asonanta(s);
printf("\n");
ingambament(s,"ingambament.out");
free(titlu);
free(s);
return 0;
}
|
C
|
#include<stdio.h>
#include<stdlib.h>
#include<malloc.h>
#include<string.h>
typedef struct
{
char num[10];
char name[20];
char date[15];
double pay;
} employee;
typedef struct node
{
employee p;
struct node *pre;
struct node *next;
}node, *linklist;
linklist head, last;
void setData(linklist p)
{
printf(": ");
scanf("%s", &p->p.num);
printf(": ");
scanf("%s", &p->p.name);
printf("ְʱ: ");
scanf("%s", &p->p.date);
printf(": ");
scanf("%lf", &p->p.pay);
}
void Insert(linklist p)
{
setData(p);
p->next = last;
last->pre->next = p;
p->pre = last->pre;
last->pre = p;
}
void Add()
{
char ch;
do
{
linklist p = (linklist)malloc(sizeof(node));
system("cls");
Insert(p);
printf("Ƿ?");
scanf(" %c", &ch);
}while(ch == 'y' || ch == 'Y');
}
linklist Qur(int method)
{
char ch[20];
linklist p = head->next;
if(method == 0)
{
printf("ѡѯʽ:(1 2)");
scanf("%d", &method);
}
if(method == 1)
{
printf(":");
scanf("%s", ch);
while(p != last)
{
if(strcmp(ch, p->p.name) == 0)
break;
p = p->next;
}
}
else if(method == 2)
{
printf(":");
scanf("%s", ch);
while(p != last)
{
if(strcmp(ch, p->p.date) == 0)
break;
p = p->next;
}
}
if(p == last)
{
printf("δҵ\n");
system("pause");
}
return p;
}
void Del()
{
linklist p = Qur(1);
if(p == last)
return;
p->pre->next = p->next;
p->next->pre = p->pre;
free(p);
printf("ɾɹ\n");
system("pause");
}
void Modify()
{
linklist p = Qur(1);
if(p == last)
return;
setData(p);
}
void printTitle()
{
printf("\t \t ְ\t \n");
}
void show(linklist p)
{
printf("%s\t%s\t%s\t%.2lf\n", p->p.num, p->p.name, p->p.date, p->p.pay);
}
void Sort()
{
linklist p, q;
for(p = head->next; p != last; p = p->next)
{
for(q = q->next; q != last; q = q->next)
{
if(p->p.pay < q->p.pay)
{
employee temp = p->p;
p->p = q->p;
q->p = temp;
}
}
}
printf(".\n");
system("pause");
}
void Tongji()
{
linklist p = head->next;
Sort();
printTitle();
while(p != last)
{
show(p);
p = p->next;
}
system("pause");
}
void Wrong()
{
printf("!\n");
system("pause");
}
void menu(void)
{
system("cls");
printf("**********ʹϵͳ**********\n");
printf("* *\n");
printf("* 1: *\n");
printf("* 2:ɾ *\n");
printf("* 3.ѯ *\n");
printf("* 4. *\n");
printf("* 5.ͳ *\n");
printf("* 6. *\n");
printf("* 0.˳ *\n");
printf("*******************************\n");
}
int select()
{
int choose;
scanf("%d", &choose);
switch(choose)
{
case 1:
Add();
break;
case 2:
Del();
break;
case 3:
{
linklist p = Qur(0);
if(p != last)
{
show(p);
system("pause");
}
break;
}
case 4:
Modify();
break;
case 5:
Tongji();
break;
case 6:
Sort();
break;
case 0:
break;
default:
Wrong();
break;
}
return choose;
}
void destroy()
{
linklist p = head->next;
while(p != last)
{
head->next = p->next;
free(p);
p = head->next;
}
free(head);
free(last);
}
int main()
{
head = (linklist)malloc(sizeof(node));
last = (linklist)malloc(sizeof(node));
head->next = last;
last->next = NULL;
last->pre = head;
head->pre = NULL;
do
{
menu();
}while(select() != 0);
destroy();
return 0;
}
|
C
|
#include <stdio.h>
int main(void){
int N,A,min=1000000010,max=0;
scanf("%d",&N);
for(int i=0;i<N;i++){
scanf("%d",&A);
if(A<min) min=A;
if(A>max) max=A;
}
printf("%d\n",max-min);
return 0;
} ./Main.c: In function main:
./Main.c:5:3: warning: ignoring return value of scanf, declared with attribute warn_unused_result [-Wunused-result]
scanf("%d",&N);
^
./Main.c:7:5: warning: ignoring return value of scanf, declared with attribute warn_unused_result [-Wunused-result]
scanf("%d",&A);
^
|
C
|
int removeElement(int* nums, int numsSize, int val){
int slow=0;
for (int i=0 ;i<numsSize ; i++){
if(nums[i] != val){
nums[slow] = nums[i];
slow++;
}
}
return slow;
}
|
C
|
#include <stdio.h>
int main(int argc, char const *argv[])
{
int len = 3;
char string[len];
int i;
for (i = 0; i < len-1; ++i)
{
string[i] = '-';
}
printf("%s\n", string);
string[2] = '\0';
string[0] = '0';
string[1] = '0';
printf("%s\n", string);
int j = 0;
string[j] = '1';
string[++j] = '2';
printf("%s\n", string);
j = 0;
if (--j == 0)
{
printf("IN\n");
}
else
{
printf("OUT\n");
}
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <ctype.h>
#include <dirent.h>
#define LEN 4096
char* get_filetype(const char* file);
void send_error(int status,char* title);
void send_header(int status,char* title, char* filetype);
void decode(char* to, char* from);
void encode(char* to, char* from);
int main(int argc,const char* argv[])
{
if(argc < 2)
send_error(500,"server error : argc < 2");
//if(access(argv[1],R_OK | F_OK) != 0)
if(chdir(argv[1]) < 0)
send_error(500,"server error : chdir error");
char line[LEN],type[LEN],path[LEN],protocol[LEN];
if(fgets(line,sizeof(line),stdin) == NULL)
send_error(500,"server error : type path protocol");
if(sscanf(line,"%[^ ] %[^ ] %[^ ]",type,path,protocol) != 3)
send_error(400,"bad request");
if(strcasecmp(type,"GET") != 0)
send_error(400,"method not allow");
if(path[0] != '/')
send_error(404,"file not found");
while(fgets(line,sizeof(line),stdin) != NULL)
{
if(strcmp(line,"\n") == 0 || strcmp(line,"\r\n") == 0)
break;
}
char file[LEN];
struct stat st;
file[0] = '.';
decode(file+1,path);
//printf("%s\n",&path[1]);
//printf("%s\n",file);
if(stat(file,&st) < 0)
{
printf("file : %s\r\n",file);
send_error(500,"server error : stat");
}
if(S_ISDIR(st.st_mode))
{
send_header(200,"OK","text/html;charset=utf-8");
printf("<html>"
"<head><title>Index of %s</title></head>"
"<body bgcolor=\"#cc99cc\">"
"<h4>Index of %s</h4>"
"<pre>"
,file,file);
struct dirent** dl;
int nf = scandir(file,&dl,NULL,alphasort);
if(nf < 0)
perror("scandir");
else
{
struct stat fst;
char stfile[LEN];
for(int i=0;i<nf; ++i)
{
strcpy(stfile,file);
strcat(stfile,"/");
strcat(stfile,dl[i]->d_name);
if(lstat(stfile,&fst) < 0)
printf("<a href=\"%s%s/\">%-32.32s/</a>",file+1,dl[i]->d_name,dl[i]->d_name);
else if(S_ISDIR(fst.st_mode))
printf("<a href=\"%s%s/\">%-32.32s/</a> \t\t%14lld",file+1,dl[i]->d_name,dl[i]->d_name,(long long)fst.st_size);
else
printf("<a href=\"%s%s\">%-32.32s</a> \t\t%14lld",file+1,dl[i]->d_name,dl[i]->d_name,(long long)fst.st_size);
printf("<br/>");
}
}
printf("</pre>"
"</body>"
"</html>");
}
else
{
//普通文件
FILE* fp = fopen(file,"r");
if(fp == NULL)
send_error(500,"server error : open file");
send_header(200,"send header",get_filetype(file));
int ch;//这里必须用int判断EOF,我真是菜鸡。
while((ch = getc(fp)) != EOF)
{
putchar(ch);
}
fflush(stdout);
fclose(fp);
fp = NULL;
}
// printf("test success !\n");
return 0;
}
int hex2d(char hex)
{
if(hex >= '0' && hex <= '9')
return hex-'0';
else if(hex >= 'a' && hex <= 'f')
return hex-'a'+10;
else if(hex >= 'A' && hex <= 'F')
return hex-'A'+10;
else
return hex;
}
void decode(char* to, char* from)
{
if(to == NULL || from == NULL)
return;
while(*from != '\0')
{
if(from[0] == '%' && isxdigit(from[1]) && isxdigit(from[2]))
{
*to = hex2d(from[1])*16 + hex2d(from[2]);
from += 3;
}
else
{
*to = *from;
++from;
}
++to;
}
*to = '\0';
}
void encode(char* to, char* from)
{
if(to == NULL && from == NULL)
return;
while(*from != '\0')
{
if(isalnum(*from) || strchr("/._-~",*from) != NULL)
{
*to = *from;
++to;
++from;
}
else
{
sprintf(to,"%%%02x",*from);
to += 3;
from += 3;
}
}
*to = '\0';
}
char* get_filetype(const char* file)
{
if(file == NULL)
return NULL;
char* dot = strrchr(file,'.');
if(*dot == '\0')
return "text/plain; charset=utf-8";
else if(strcmp(dot,".html") == 0)
return "text/html; charset=utf-8";
else if(strcmp(dot, ".jpg") == 0)
return "image/jpeg";
else if(strcmp(dot, ".gif") == 0)
return "image/gif";
else if(strcmp(dot, ".png") == 0)
return "image/png";
else if(strcmp(dot, ".wav") == 0)
return "audio/wav";
else if(strcmp(dot, ".avi") == 0)
return "video/x-msvideo";
else if(strcmp(dot, ".mov") == 0)
return "video/quicktime";
else if(strcmp(dot, ".mp3") == 0)
return "audio/mpeg";
else
return "text/plain; charset=utf-8";
}
void send_header(int status, char* title, char* filetype)
{
if(title == NULL || filetype == NULL)
{
title = "ERROR";
filetype = "text/plain; charset=utf-8";
}
printf("HTTP/1.1 %d %s\r\n",status,title);
printf("Content-Type:%s\r\n",filetype);
printf("\r\n");
}
void send_error(int status,char* title)
{
if(title == NULL)
title = "ERROR";
send_header(status,title,"text/html; charset=utf-8");
printf("<html>\n"
"<head><title>%d %s</title></head>\n"
"<body bgcolor=\"#cc99cc\">\n"
"<h4>error!</h4>\n"
"<hr>\n"
"<address>\n"
"<a href=\"https://liuziqiao.github.io/\">liuxiaokun</a>\n"
"</address>\n"
"</body>\n"
"</html>",
status,title);
fflush(stdout);
exit(1);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
void freeMatrix(int row, int col, double **matrix)
{
for (int i = 0; i < (row * col); i++)
{
free(matrix[i]);
}
free(matrix);
}
void printMatrix(int row, int col, double **matrix)
{
printf("Rows: %d\n", row);
printf("Columns: %d\n", col);
for (int i = 0; i < row; i++)
{
for (int j = 0; j < col; j++)
printf("%lf ", matrix[i][j]);
printf("\n");
}
}
/*void multiply(int a)
{
double **resultMatrix = (double**) malloc((aRow * bCol) * sizeof(double*));
for (int i = 0; i < (aRow * bCol); i++)
{
resultMatrix[i] = (int*) malloc((aRow * bCol) * sizeof(int));
}
for(int i = 0; i < aRow; i++)
{
for(int j = 0; j < bCol; j++)
{
resultMatrix[i][j] = 0;
for(int k = 0; k < aCol; k++)
{
resultMatrix[i][j] += aMatrix[i][k] * bMatrix[k][j];
}
}
}
}*/
#define MAX_PATH_SIZE 100
int main(int argc, char* argv[])
{
char filePath[MAX_PATH_SIZE];
int N = 0;
printf("Enter amount of files: ");
scanf("%d", &N);
int row = 0;
int col = 0;
for (int i = 0; i < N; i++)
{
printf("Enter the path of the %d file: ", i+1);
scanf("%s", &filePath);
FILE *file = fopen(filePath, "r");
if (!file)
{
printf("\nCan't open file! Errno: %d\n", ENOENT);
exit(1);
}
int row = 0; //количество строк в матрице
int col = 0; //количество столбцов в матрице
double buff = 0; //буфер чисел в файле
fscanf(file, "%d", &row);
buff = 0;
fscanf(file, "%d", &col);
buff = 0;
double **matrix = (double**) malloc((row * col) * sizeof(double*));
for (int i = 0; i < (row * col); i++)
{
matrix[i] = (double*) malloc((row * col) * sizeof(double));
}
while (!feof(file))
{
for(int i = 0; i < row; i++)
{
for(int j = 0; j < col; j++)
{
fscanf(file, "%lf" , &buff);
if(buff > (sizeof(double)-1))
{
printf("\nElement is too big!\n");
exit(1);
}
matrix[i][j] = buff;
}
}
}
/*switch (i) {
case 0:
memcpy(amatrix, matrix, sizeof(matrix));
break;
default:
memcpy(bmatrix, matrix, sizeof(matrix));
multiply(amatrix, bmatrix);
memcpy(amatrix, cmatrix, sizeof(cmatrix));
break;
}*/
printMatrix(row, col, matrix);
fclose(file);
}
}
|
C
|
#include "monty.h"
/**
* m_pop - delete element top of stack
* @head: doble pointer to head of d linked list
* @line_count: current line of monty file
* Return: returns void
*/
void m_pop(stack_t **head, unsigned int line_count)
{
stack_t *temp;
if (!(*head) || !head)
{
dprintf(2, "L%u: can't pop an empty stack\n", line_count);
free_all();
exit(EXIT_FAILURE);
}
temp = *head;
if (temp->next)
{
temp->next->prev = NULL;
*head = temp->next;
}
else
*head = NULL;
free(temp);
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_getval_fromabspos.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: spajeo <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2017/10/28 03:47:09 by spajeo #+# #+# */
/* Updated: 2018/04/09 14:54:45 by spajeo ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
#include "liblst.h"
#include "push_swap.h"
/*
**
**
** int *ft_getval_fromabspos(t_lst *head, int*(*get_int)(t_lst *), size_t pos)
** OBTAINS THE NTH VALUE REGARDING THE VALUE NOT THE POS
**
** returns the **ADDRESS** of the value
*/
int ft_getval_fromabspos(t_lst *head, int *(* get_int)(t_lst *), size_t pos)
{
t_lst *tmp;
t_lst *test;
size_t inferior;
inferior = 0;
tmp = head->next;
while (tmp != head) // head->prev
{
while (test != head)
{
if (*get_int(tmp) < *get_int(test))
{
++inferior;
}
test = test->next;
}
if (inferior == pos)
return (*get_int(tmp));
inferior = 0;
test = head->next;
tmp = tmp->next;
}
return (0);
}
|
C
|
/* SPDX-License-Identifier: Apache-2.0
* Copyright © 2021 VMware, Inc.
*/
#include "alloc-util.h"
#include "cli.h"
#include "macros.h"
#include "log.h"
int cli_manager_new(const Cli *cli_commands, CliManager **ret) {
_auto_cleanup_ CliManager *m = NULL;
size_t i;
assert(cli_commands);
assert(ret);
m = new0(CliManager, 1);
if (!m)
return log_oom();
*m = (CliManager) {
.hash = g_hash_table_new(g_str_hash, g_str_equal),
.commands = (Cli *) cli_commands,
};
if (!m->hash)
return log_oom();
for (i = 0; cli_commands[i].name; i++)
g_hash_table_insert(m->hash, (gpointer *) cli_commands[i].name, (gpointer *) &cli_commands[i]);
*ret = steal_pointer(m);
return 0;
}
void cli_unref(CliManager *m) {
if (!m)
return;
g_hash_table_unref(m->hash);
free(m);
}
static Cli *cli_get_command(const CliManager *m, const char *name) {
assert(m);
assert(name);
return g_hash_table_lookup(m->hash, name);
}
int cli_run_command(const CliManager *m, int argc, char *argv[]) {
Cli *command = NULL;
int remaining_argc;
char *name;
assert(m);
remaining_argc = argc - optind;
argv += optind;
optind = 0;
name = argv[0];
/* run default if no command specified */
if (!name) {
int i;
for (i = 0;; i++) {
if (m->commands[i].default_command)
command = m->commands;
remaining_argc = 1;
return command->run(remaining_argc, argv);
}
}
command = cli_get_command(m, name);
if (!command) {
log_warning("Unknown cli command '%s'.", name);
return -EINVAL;
}
if (command->min_args != WORD_ANY && (unsigned) remaining_argc <= command->min_args) {
log_warning("Too few arguments.");
return -EINVAL;
}
if (command->max_args != WORD_ANY && (unsigned) remaining_argc > command->max_args) {
log_warning("Too many arguments.");
return -EINVAL;
}
return command->run(remaining_argc, argv);
}
|
C
|
#include "sort.h"
/**
* bubble_sort - sorts by comparing adjacent
* numbers and swapping if prev is larger
* than next.
*
* @array: data to be sorted
* @size: size of array
*
* Return: void
*/
void bubble_sort(int *array, size_t size)
{
unsigned int flag = 1, tmp;
size_t idx = 0;
if (size < 2 || array == NULL)
return;
while (flag != 0)
{
flag = 0;
for (idx = 0; idx < size - 1; idx++)
{
if (array[idx] <= array[idx + 1])
continue;
else
{
tmp = array[idx];
array[idx] = array[idx + 1];
array[idx + 1] = tmp;
flag = 1;
}
print_array(array, size);
}
}
}
|
C
|
int sumarNumeros(int, int);
int sumarNumeros(int numero1, int numero2){
int resultado;
resultado = numero1 + numero2;
return resultado;
}
|
C
|
// Example of message queue in C.
// For educational purposes only.
// Author: Vaclav Bohac
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <signal.h>
#include <stdarg.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#define DATA_SIZE 4096
typedef struct MsgType{
long mtype; /* message type, must be > 0 */
int queue_type; /* 0 : Admin SQ */
/* 1 : Admin CQ */
/* 2 : SQ */
/* 3 : CQ */
int command; /* 0 : Read */
/* 1 : Write */
/* 2 : Trim */
int index; // queue index
unsigned long addr; // target address
char data[DATA_SIZE]; // data
}MsgType;
void init_msg(struct MsgType* msg)
{
msg->mtype = 0;
msg->queue_type = -1;
msg->command = -1;
msg->index = 0;
msg->addr = 0x00000000;
strcpy(msg->data,"data");
}
void set_msg(struct MsgType* msg, long mtype, int qtype, int command, int index, unsigned long addr, char* data)
{
msg->mtype = mtype;
msg->queue_type= qtype;
msg->command = command;
msg->index = index;
msg->addr = addr;
strcpy(msg->data,data);
}
int main ( void )
{
key_t key = 4071;
int que_id = msgget(key,0666);
if(que_id==-1)
{
que_id = msgget(key, IPC_CREAT|0666);
if(que_id==-1)
{
printf("msgget error\n");
return -1;
}
}
MsgType msg;
int msg_size = 0;
init_msg(&msg);
set_msg(&msg,2696,3,1,0,0x80000000,"hello world");
msg_size = sizeof(msg) - sizeof(msg.mtype);
int rtn = msgsnd(que_id, &msg, msg_size, IPC_NOWAIT);
if (rtn == -1) {
printf("msgsnd() fail\n");
return -1;
}
}
|
C
|
#include<stdio.h>
int main()
{
int num1,num2,num3;
printf("\nEnter three numbers:\n");
scanf("%d%d%d",&num1,&num2,&num3);
if(num1>num2&&num1>num3)
{
printf("%d is greater",num1);
}
if(num2>num1&&num2>num3)
{
printf("%d is greater",num2);
}
if(num3>num1&&num3>num2)
{
printf("%d is greater",num3);
}
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#define STACK_INIT 100
#define STACK_ADD 10
typedef char type;
typedef struct
{
type *base,*top;
int stacksize;
}SqStack;
SqStack StackInit()
{
SqStack s;
s.base=(type*)malloc(STACK_INIT*sizeof(type));
if(!s.base) exit(0);
s.top=s.base;
s.stacksize=STACK_INIT;
return s;
}
SqStack Push(SqStack s,type e)
{
if(s.top-s.base>=s.stacksize)
{
s.base=(type*)realloc(s.base,(s.stacksize+STACK_ADD)*sizeof(type));
if(!s.base) exit(0);
s.top=s.base+s.stacksize;
s.stacksize+=STACK_ADD;
}
*s.top++=e;
return s;
}
SqStack Pop(SqStack s,type *e)
{
if(s.top==s.base) exit(0);
*e=*--s.top;
return s;
}
void Traverse(SqStack s)
{
while(s.top!=s.base)
printf("%c ",*--s.top);
printf("\n");
}
int Judge(char a[])
{
SqStack s;
type e;
s=StackInit();
int i=0;
while(a[i]!='&' && a[i])
{
s=Push(s,a[i]);
i++;
}
if(!a[i]) return 0;
else i++;
while(a[i])
{
s=Pop(s,&e);
if(e!=a[i]) return 0;
i++;
}
return 1;
}
int main()
{
char buffer[100];
int result;
scanf("%s",&buffer);
result=Judge(buffer);
printf("result=%d\n",result);
return 0;
}
|
C
|
#include <stdio.h>
int main()
{
char netid [7];
FILE *fptr;
if ((fptr = fopen("netid.md","r")) == NULL){
printf("Error! opening file");
// Program exits if the file pointer returns NULL.
exit(1);
}
fscanf(fptr,"%s", &netid);
printf(netid);
fclose(fptr);
return 0;
}
|
C
|
#include<stdio.h>
int main(int argc, char const *argv[])
{
/* code */
int i,n,sum=0;
printf("Enter you number :- ");
scanf("%d",&n);
for (i = 0; i < n+1; i++)
{
/* code */
sum +=i;
}
printf("\nSum of all Natureal number is :- %d",sum);
printf("\n");
return 0;
}
|
C
|
3.
#include <stdio.h>
#define NUM_BLOCKS 4
#define BLOCK_WIDTH 1
__global__ void hello()
{
printf("Hello world! I'm a thread in block %d\n", blockIdx.x);
}
int main(int argc,char **argv)
{
// launch the kernel
hello<<<NUM_BLOCKS, BLOCK_WIDTH>>>();
// force the printf()s to flush
cudaDeviceSynchronize();
printf("That's all!\n");
return 0;
4.#include <stdio.h>
#define NUM_BLOCKS 1
#define BLOCK_WIDTH 8
__global__ void hello()
{
printf("Hello world! I'm thread %d\n", threadIdx.x);
}
int main(int argc,char **argv)
{
// launch the kernel
hello<<<NUM_BLOCKS, BLOCK_WIDTH>>>();
// force the printf()s to flush
cudaDeviceSynchronize();
printf("That's all!\n");
return 0;
|
C
|
/************************************************************
*
* FONCTIONS DE LECTURE/ECRITURE DANS UN FICHIER
*
************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include "sgf-header.h"
#include "sgf-impl.h"
void sgf_read_block(OFILE* file, int block_number);
/************************************************************
* Initialisation du SGF
************************************************************/
void init_sgf(void) {
init_sgf_fat();
init_sgf_dir();
}
/************************************************************
Lire un caractère dans un fichier ouvert. Cette fonction
renvoie -1 si elle trouve la fin du fichier.
Description :
- si la fin du fichier est atteinte (comparaison entre ptr
et la taille), renvoyer -1
- si le buffer est vide (test à faire sur ptr % BLOCK_SIZE)
appeler la fonction sgf_read_block pour le remplir
- renvoyer le caractère dans la bonne position du buffer
(position à calculer en fonction de ptr).
************************************************************/
int sgf_getc(OFILE* file) {
if(file->ptr >= file->inode.size) {
return -1;
}
if(file->ptr % BLOCK_SIZE == 0) {
sgf_read_block(file,(file->ptr / BLOCK_SIZE));
}
return file->buffer[file->ptr++ % BLOCK_SIZE];
}
/************************************************************
Lire dans le "buffer" le bloc logique "block_number"
dans le fichier ouvert "file".
Description :
- il faut calculer l'adresse du bloc physique qui contient
le bloc logique de numéro "block_number"
- pour ce faire, il faut partir de first (adresse physique
du premier bloc disponible dans l'INODE) et parcourir
le chainage de la FAT block_number fois.
- une fois l'adresse trouvée, il faut lire le bloc
dans le buffer
************************************************************/
void sgf_read_block(OFILE* file, int block_number) {
/*sgf_read_block_impl(file, block_number);*/
int tmp = file->inode.first;
int i;
for (i = 0; i < block_number; i++) {
tmp = get_fat(tmp);
}
read_block(tmp, &file->buffer);
}
/************************************************************
Ajouter le bloc contenu dans le tampon au fichier
ouvert décrit par "file".
Description :
- allouer un bloc libre (fonction alloc_block)
- écrire le buffer dans ce bloc
- écrire la valeur EOF dans la FAT pour ce bloc
- si ce bloc est le premier (test sur first/last),
- mettre à jour first et last de l'INODE
- écrire l'INODE sur disque
- sinon
- il y a donc déjà un dernier bloc (devenu l'avant dernier)
- mettre à jour la FAT pour que l'avant dernier bloc
pointe sur le dernier
- mettre à jour last de l'INODE
- écrire l'INODE sur disque
************************************************************/
void sgf_append_block(OFILE* file) {
/* sgf_append_block_impl(file); */
int block = alloc_block();
write_block(block, &file->buffer);
set_fat(block, FAT_EOF);
if (file->inode.first == FAT_EOF) {
file->inode.first = block;
file->inode.last = block;
write_inode(block, file->inode);
} else {
int tmp = file->inode.last;
set_fat(tmp, block);
file->inode.last = block;
write_inode(block, file->inode);
}
}
/************************************************************
Ecrire le caractère "c" dans le fichier ouvert
décrit par "file".
Description :
- il y a toujours de la place dans le buffer (postulat)
- placer le caractère dans le buffer (en fonction de ptr)
- si le buffer est plein (test sur ptr % BLOCK_SIZE),
ajouter le bloc au fichier (sgf_append_block)
************************************************************/
void sgf_putc(OFILE* file, char c) {
/* sgf_putc_impl(file, c); */
file->buffer[file->ptr++ % BLOCK_SIZE] = c;
if (file->ptr % BLOCK_SIZE == 0) {
sgf_append_block(file);
}
}
/************************************************************
Écrire la chaîne de caractère "s" dans un fichier ouvert
en écriture décrit par "file".
************************************************************/
void sgf_puts(OFILE* file, char* s) {
assert (file->mode == WRITE_MODE);
for (; (*s != '\0'); s++) {
sgf_putc(file, *s);
}
}
/************************************************************
Détruire un fichier.
Description :
- lire l'INODE et le libérer (FAT_FREE dans la FAT)
- parcours le chaînage et libérer tous les blocs
************************************************************/
void sgf_remove(int adr_inode) {
sgf_remove_impl(adr_inode);
}
/************************************************************
Créer un inode vide, initialiser l'INODE passé en paramètre
et renvoyer l'adresse. (renvoie -1 en cas d'erreur)
Description :
- allouer un bloc libre (fonction alloc_block)
- initialiser les champs de l'INODE (0 et FAT_EOF)
- sauver l'INODE et mettre à jour la FAT
************************************************************/
static int create_inode(INODE *inode) {
return create_inode_impl(inode);
}
/************************************************************
Ouvrir un fichier en écriture seulement (NULL si échec).
************************************************************/
OFILE* sgf_open_write(const char* nom) {
int adr_inode, oldinode;
INODE inode;
OFILE* file;
/* Rechercher un bloc libre sur disque */
adr_inode = create_inode(&inode);
if (adr_inode < 0) return NULL;
/* Allouer une structure OFILE */
file = malloc(sizeof(OFILE));
if (file == NULL) return (NULL);
/* mettre à jour le répertoire */
oldinode = add_inode(nom, adr_inode);
if (oldinode > 0) sgf_remove(oldinode);
file->inode = inode;
file->adr_inode = adr_inode;
file->mode = WRITE_MODE;
file->ptr = 0;
return (file);
}
/************************************************************
Ouvrir un fichier en lecture seulement (NULL si échec).
************************************************************/
OFILE* sgf_open_read(const char* nom) {
int adr_inode;
INODE inode;
OFILE* file;
/* Chercher le fichier dans le répertoire */
adr_inode = find_inode(nom);
if (adr_inode < 0) return (NULL);
/* lire l'INODE */
inode = read_inode(adr_inode);
/* Allouer une structure OFILE */
file = malloc(sizeof(OFILE));
if (file == NULL) return (NULL);
file->inode = inode;
file->adr_inode = adr_inode;
file->mode = READ_MODE;
file->ptr = 0;
return (file);
}
/************************************************************
Fermer un fichier ouvert.
Description :
- si le fichier est ouvert en écriture et que le buffer
n'est pas vide (ptr % BLOCK_SIZE), ajouter le dernier bloc
au fichier (fonction sgf_append_block)
************************************************************/
void sgf_close(OFILE* file) {
/*sgf_close_impl(file);*/
if (file->mode == WRITE_MODE && (file->ptr % BLOCK_SIZE != 0)) {
sgf_append_block(file);
}
}
int sgf_seek(OFILE* f, int pos) {
if (pos > f->inode.size)
return -1;
if (pos % BLOCK_SIZE != 0) {
sgf_read_block(f, (pos / BLOCK_SIZE));
}
f->ptr += pos;
return 0;
}
|
C
|
#include "dog.h"
/**
* init_dog - initialize the dog structure with input information
* @d: pointer to structure - dog
* @name: string literal containing dog name
* @age: float value age of dog
* @owner: string literal containing owner name
*
* Return: void
*/
void init_dog(struct dog *d, char *name, float age, char *owner)
{
if (d)
{
(*d).name = name;
(*d).age = age;
(*d).owner = owner;
}
}
|
C
|
/*
Autor: Tomás de Carvalho Coelho, Eng comp, 418391
*/
#include <stdio.h>
int main() {
int i,j;
for (i = 0; i <= 20; i+=2) {
for (j = 10; j <= 30; j+=10) {
if (i == 0 || i == 10 || i == 20)
printf("I=%.0lf J=%.0lf\n", i / 10.0, (j + i) / 10.0);
else
printf("I=%.1lf J=%.1lf\n", i / 10.0, (j + i) / 10.0);
}
}
return 0;
}
|
C
|
/*
Suppose you have N eggs and you want to determine from which floor in a K-floor building you can drop an egg such that it doesn't break. You have to determine the minimum number of attempts you need in order find the critical floor in the worst case while using the best strategy.There are few rules given below.
An egg that survives a fall can be used again.
A broken egg must be discarded.
The effect of a fall is the same for all eggs.
If the egg doesn't break at a certain floor, it will not break at any floor below.
If the eggs breaks at a certain floor, it will break at any floor above.
For more description on this problem see wiki page
Input:
The first line of input is T denoting the number of testcases.Then each of the T lines contains two positive integer N and K where 'N' is the number of eggs and 'K' is number of floor in building.
Output:
For each test case, print a single line containing one integer the minimum number of attempt you need in order find the critical floor.
Constraints:
1<=T<=30
1<=N<=10
1<=K<=50
Example:
Input:
2
2 10
3 5
Output:
4
3
** For More Input/Output Examples Use 'Expected Output' option **
*/
|
C
|
#ifndef SIGNALS_H
#define SIGNALS_H
#include <setjmp.h>
/* variables */
extern sigjmp_buf env;
/* ============================= sig_atomic_t =============================
"sig_atomic_t" is only async-signal safe (not thread-safe)
sig_atomic_t is not an atomic data type. It is just the data type
that you are allowed to use in the context of a signal handler.
Better read the name as "atomic relative to signal handling".
To guarantee communication with and from a signal handler, only
one of the properties of atomic data types is needed, namely the
fact that read and update will always see a consistent value,
e.g. sig_atomic_t is guaranteed to be read and written in one go.
So a platform may choose any integer base type as sig_atomic_t for
which it can make the guarantee that volatile sig_atomic_t can be
safely used in signal handlers. Many platforms chose int for this,
because they know that for them int is written with a single instruction.
=============================== volatile ==================================
"volatile" here is essential, since the flag "jump_active" will be accessed
asynchronously by multiple threads of the process, i.e. the main thread
and the signal handler thread. The type guarantees atomic access to the
variable across multiple threads.
*/
extern volatile sig_atomic_t jump_active;
/* function declarations */
/* trap SIGINT and perform long jump */
void sigint_handler();
/* trap SIGCHLD and perform job management */
void sigchld_handler();
#endif /* SIGNALS */
|
C
|
#include <stdio.h>
void helper(int b)
{
printf("Twice of given number is = %d", 2*b);
}
int main()
{
// a is pointer to void function helper
// helper functions need int input
void (*a) (int) = helper;
a(10.5); //Call fun by using pointer and input value
return 0;
}
|
C
|
/*
** EPITECH PROJECT, 2018
** my_revstr.c
** File description:
** reverse a string
*/
#include "mysh.h"
#include <stdio.h>
#include <stdlib.h>
char *my_revstr(char *str)
{
char *new = calloc(1, sizeof(char) * my_strlen(str) + 1);
int j = 0;
for (int i = my_strlen(str) - 1; i >= 0; i--, j++)
new[j] = str[i];
return (new);
}
|
C
|
#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
#include<string.h>
//дһÿεnumֵͻ1
//void ADD(int *p)
//{
// (*p)++;
//}
//int main()
//{
// int num = 0;
// ADD(&num);
// printf("%d\n", num);
// ADD(&num);
// printf("%d\n", num);
//
// return 0;
//}
//int main()
//{
// printf("%d\n", strlen("abc")); //һķֵΪһIJ ----ʽ
//
// return 0;
//}
//int main()
//{
// //printfصַĿ
// printf("%d", printf("%d", printf("%d",43))); //һδӡ432ڶδӡ21һδӡ1
// //ԽΪ43 2 1
//
//
//
//
// return 0;
//}
//#include "ADD.h" //Լͷļ
//int main()
//{
// int a = 0;
// int b = 20;
// int sum = 0;
// //ĵ
// sum=ADD(a, b);
// printf("%d", sum);
// return 0;
//}
////ĵݹ
//int main()
//{
//
// printf("hh\n");
// main(); //ݹ ջ
//
//
// return 0;
//}
//void print(int n)
//{
// if (n > 9)
// {
// print(n / 10);
// }
// printf("%d", n % 10);
//}
//int main()
//{
// unsigned int num = 0;
// scanf("%d", &num); //1234
// //ݹ
// print(num);
//
//
// return 0;
//}
//int my_strlen(char* str)
//{
// int count = 0;
// while (*str != '\0')
// {
// count++;
// str++;
// }
// return count;
//}
//ݹ
int my_strlen(char* str)
{
if (*str != '\0')
{
return 1 + my_strlen(str + 1);
}
else
{
return 0;
}
}
//Ѵ»С
int main()
{
char arr[] = "bit";
int len = my_strlen(arr); //arr飬鴫ΣȥIJ飬ǵһԪصĵַ
printf("len = %d\n", len);
return 0;
}
|
C
|
#include "cpu/reg.h"
#include "common.h"
#include "page.h"
#include "stdlib.h"
extern uint32_t hwaddr_read(hwaddr_t addr,size_t len);
void maptlb()
{
int i=0;
for (i=0;i<TLB_SIZE;i++) TLB[i].valid=false;
}
bool page_enable()
{
if ((cpu.CR0&0x1)&&(cpu.CR0>>31)) return true;
return false;
}
bool page_cross(uint32_t addr,int len)
{
if (page_enable()&&addr>>12!=(addr+len-1)>>12) return true;
return false;
}
uint32_t TLB_fill(uint32_t addr)
{
int i=0;
for (;i<TLB_SIZE;i++) if (TLB[i].valid==false) break;
if (i==TLB_SIZE){ srand(addr);i=rand()%TLB_SIZE;}
TLB[i].valid=true;
uint32_t base=cpu.CR3>>12<<12;
hwaddr_t table_now=hwaddr_read((addr>>22)*4+base,4);//read页表的物理地址
assert(table_now&0x1);// error in hello.c
hwaddr_t page_now=hwaddr_read(((addr>>12)&0x3ff)*4+(table_now>>12<<12),4);//read页的物理地址
assert(page_now&0x1);
TLB[i].mark=addr>>12<<12;
TLB[i].addr=page_now>>12<<12;
return (page_now>>12<<12)+(addr&0xfff);
}
//80480aa
//0000 1000 00|00 0100 1000 |0000 1010 1010
//128*1024*1024=4*1024*(32*1024) number of page and page_entry
hwaddr_t page_translate(lnaddr_t addr)
{
if(page_enable()) {
int i=0;
for (;i<TLB_SIZE;i++) if (TLB[i].valid&&TLB[i].mark==addr>>12<<12) { return TLB[i].addr+(addr&0xfff);break;}
return TLB_fill(addr);
}
else return addr;
}
void printpage(uint32_t addr)
{
uint32_t base=0x00140000>>12<<12;
hwaddr_t table_now=hwaddr_read((addr>>22)*4+base,4);
hwaddr_t page_now=hwaddr_read(((addr>>12)&0x3ff)*4+(table_now>>12<<12),4);
uint32_t value=hwaddr_read((page_now>>12<<12)+(addr&0xfff),4);
printf("table=0x%x\npage=0x%x\nvalue=0x%x\n",table_now,page_now,value);
}
|
C
|
#include <stdlib.h>
#include "tools.h"
#include "video_draw.h"
void video_draw_pixel(unsigned char *rgb, unsigned int rowstride, unsigned int h, unsigned int x, unsigned int y, unsigned char r, unsigned char g, unsigned char b) {
if(x>=0 && x*3+2<rowstride && y>=0 && y<h) {
rgb[y*rowstride + x*3 + 0] = r;
rgb[y*rowstride + x*3 + 1] = g;
rgb[y*rowstride + x*3 + 2] = b;
}
}
void video_draw_line(unsigned char *rgb, unsigned int w, unsigned int h, unsigned int rowstride, unsigned int x0, unsigned int y0, unsigned int x1, unsigned int y1, unsigned char r, unsigned char g, unsigned char b) {
// Bresenham algorithm
x0 = CLAMP(0, x0, w-1);
y0 = CLAMP(0, y0, h-1);
x1 = CLAMP(0, x1, w-1);
y1 = CLAMP(0, y1, h-1);
int dx = abs((int)x1-(int)x0), sx = x0<x1 ? 1 : -1;
int dy = abs((int)y1-(int)y0), sy = y0<y1 ? 1 : -1;
int err = (dx>dy ? dx : -dy)/2, e2;
for(;;) {
video_draw_pixel(rgb, rowstride, h, x0, y0, r, g, b);
if(x0==x1 && y0==y1) break;
e2 = err;
if(e2 >-dx) { err -= dy; x0 += sx; }
if(e2 < dy) { err += dx; y0 += sy; }
}
}
void video_draw_cross(unsigned char *rgb, unsigned int w, unsigned int h, unsigned int rowstride, unsigned int x, unsigned int y, unsigned int size, unsigned char r, unsigned char g, unsigned char b) {
video_draw_line(rgb, w, h, rowstride, x-size, y, x+size, y, r, g, b);
video_draw_line(rgb, w, h, rowstride, x, y-size, x, y+size, r, g, b);
}
void video_draw_circle(unsigned char *rgb, unsigned int w, unsigned int h, unsigned int rowstride, unsigned int xc, unsigned int yc, unsigned int ray, unsigned char r, unsigned char g, unsigned char b) {
unsigned int x= ray, y= 0;//local coords
int cd2= 0; //current distance squared - radius squared
video_draw_pixel(rgb, rowstride, h, xc-ray, yc, r, g, b);
video_draw_pixel(rgb, rowstride, h, xc+ray, yc, r, g, b);
video_draw_pixel(rgb, rowstride, h, xc, yc-ray, r, g, b);
video_draw_pixel(rgb, rowstride, h, xc, yc+ray, r, g, b);
while (x > y) //only formulate 1/8 of circle
{
cd2-= (--x) - (++y);
if (cd2 < 0) cd2+=x++;
video_draw_pixel(rgb, rowstride, h, xc-x, yc-y, r, g, b);//upper left left
video_draw_pixel(rgb, rowstride, h, xc-y, yc-x, r, g, b);//upper upper left
video_draw_pixel(rgb, rowstride, h, xc+y, yc-x, r, g, b);//upper upper right
video_draw_pixel(rgb, rowstride, h, xc+x, yc-y, r, g, b);//upper right right
video_draw_pixel(rgb, rowstride, h, xc-x, yc+y, r, g, b);//lower left left
video_draw_pixel(rgb, rowstride, h, xc-y, yc+x, r, g, b);//lower lower left
video_draw_pixel(rgb, rowstride, h, xc+y, yc+x, r, g, b);//lower lower right
video_draw_pixel(rgb, rowstride, h, xc+x, yc+y, r, g, b);//lower right right
}
}
void video_draw_box_ovr(unsigned char *rgb, unsigned int w, unsigned int h, unsigned int rowstride, int bx, int by, int bw, int bh, unsigned char r, unsigned char g, unsigned char b) {
if((bx < w && bx + bw > w) || (bx < 0 && bx + bw > 0)) {
// right
video_draw_line(rgb, w, h, rowstride, MOD(bx, (int)w), by, MOD(bx, (int)w), by+bh-1, r, g, b);
video_draw_line(rgb, w, h, rowstride, MOD(bx, (int)w), by, w-1, by, r, g, b);
video_draw_line(rgb, w, h, rowstride, MOD(bx, (int)w), by+bh-1, w-1, by+bh-1, r, g, b);
// left
video_draw_line(rgb, w, h, rowstride, MOD(bx+bw-1, (int)w), by, MOD(bx+bw-1, (int)w), by+bh-1, r, g, b);
video_draw_line(rgb, w, h, rowstride, 0, by, MOD(bx+bw-1, (int)w), by, r, g, b);
video_draw_line(rgb, w, h, rowstride, 0, by+bh-1, MOD(bx+bw-1, (int)w), by+bh-1, r, g, b);
}
else {
video_draw_line(rgb, w, h, rowstride, MOD(bx, (int)w), by, MOD(bx, (int)w), by+bh-1, r, g, b);
video_draw_line(rgb, w, h, rowstride, MOD(bx, (int)w), by, MOD(bx+bw-1, (int)w), by, r, g, b);
video_draw_line(rgb, w, h, rowstride, MOD(bx, (int)w), by+bh-1, MOD(bx+bw-1, (int)w), by+bh-1, r, g, b);
video_draw_line(rgb, w, h, rowstride, MOD(bx+bw-1, (int)w), by, MOD(bx+bw-1, (int)w), by+bh-1, r, g, b);
}
}
|
C
|
/*
* Copyright (C) 2002, Simon Nieuviarts
*/
#include <stdio.h>
#include <stddef.h>
#include <stdlib.h>
#include <errno.h>
#include <limits.h>
#include <string.h>
#include "readcmd.h"
#include "jobs.h"
#include "csapp.h"
#include <signal.h>
#define Stopped 0 //Processes Stopped in the background
#define Running 1 //Processes Runing in the background
#define Terminated 2 //Processes is terminated
static int count = 0; //Compter le nombre des fils en arriere plan
static int count1 = 0; // Compter le nombre des fils stoppés
static int s = 0; //sert pour tester si on a un signal "SIGTSTP" ou non
static int countJobs = 1; // Compter le nombre des jobs
Jobs *listJobs = NULL; // Liste des Jobs
void executeSimpleCommande(char** cmd){ //Cette fonction permet d'executer une commande Simple (sans pip "|" ou redirection "<" ">" ">>")
if(strcmp(cmd[0],"jobs") == 0){ //Si la commande est "jobs"
printf("\n*****************************************\n");
printf("\n* Jobs *\n");
printf("\n*****************************************\n");
printf("[Num]\t\t[Status]\t\t[PID]\t\t[Name] \n");
DisplayJobs(listJobs); //afficher la liste des jobs
}else if (strcmp(cmd[0],"quit")==0 || strcmp(cmd[0], "exit") == 0){ //Si la commande est "quit" ou "exit", on vide la liste des jobs
FreeJobs(listJobs);
}else if (strcmp(cmd[0],"kill")== 0 && strcmp(cmd[1],"-9")== 0){ //Si la commande est kill
int Pid = atoi(cmd[2]); //Canvertir l’argument du numéro 2 en un entier
kill(Pid,SIGKILL); //On Tue le prossecus fils du pid "Pid"
//changeStatus(Pid);
printf("The Processes %d is terminated\n",Pid);
}else if(strcmp(cmd[0],"kill")== 0 && strcmp(cmd[1],"-2")== 0){
int Pid = atoi(cmd[2]); //Canvertir l’argument du numéro 2 en un entier
kill(Pid,SIGTSTP); //On stope le prossecus fils du pid "Pid"
changeStatus(Pid); //fonction permet de changer le status d'un processus terminé en status : 2 (Terminated)
}
else{
int status = execvp(cmd[0],cmd); //executer une commande simple avec execvp()
if(status == -1){ //statut de la commande soit "=0" => sucess , "=-1" => echec
printf("%s: Command not found\n", cmd[0]); //Si la commande ne s'exécute pas donc soi la commande n'existe ou non implémentée
}
}
}
void redirectionEntreeSortie(char * in, char * out){ //commande de type redirection ">" "<"
int descriptor;
if (in != NULL){ //tester si on a une redirection "<"
descriptor = open(in,O_RDONLY); //Ouvrire le fichier "in" en mode lecture seule
if(descriptor < 0){ // Tester si on a bien retourner notre descripteur fichier
printf("%s : Permission denied\n",in); ////Erreur sur le droit de lecture du fichier "in"
}else{
dup2(descriptor,0); //Changer la sortie standard "stdin" avec le descripteur du fichier "in"
close(descriptor); // Fermer le descripteur de notre fichier "in"
}
}
if(out != NULL){ //tester si on a une redirection vers la sortie standard ">"
descriptor = open(out,O_WRONLY | O_CREAT | O_TRUNC, S_IRWXU | S_IRGRP | S_IROTH); //Ouvrire le fichier "out" en mode ecriture s'il n'existe pas il va le cree
if(dup2(descriptor,1) < 0){ // Tester si on a bien retourner notre descripteur fichier
printf("%s.txt: Permission denied\n",out);//Erreur sur les droits de manipulation du fichier lu ou crée "out"
}else{
dup2(descriptor, 1); //Changer la sortie standard "stdout" avec le descripteur du fichier "out"
close(descriptor); // Fermer le descripteur de notre fichier "out"
}
}
}
void executeCommandePipe(struct cmdline *l){ //Exécuter une commande avec multiple pipes
int nbrPipe=0;
int** p;
pid_t* pid = NULL;
for (int i=0; l->seq[i]!=0; i++) { //calculer le nombre des pipes
nbrPipe++;
}// nombre de pipes: nbrPipe-1
p = (int **) malloc (sizeof(int) * (nbrPipe)); //Allouer les lignes d'un matrice pour n-pipes(= nbrPipe -1 )
pid = (pid_t *) malloc (sizeof(pid_t) * nbrPipe -1 ); // Allouer un tableau dynamique pour enregistré les processus exécutés dans les n-pipes pour les tués après
for(int i=0;i<nbrPipe-1;i++){
p[i]= (int *) malloc(2*sizeof(int)); //Allouer les colonnes du matrice pour deux case: l'entreé et la sortie de la pipe
if (pipe(p[i])<0){ //Tester si une pipe est bien creé
printf("Creation pipe Failed\n");
}
}
for (int i = 0; i < nbrPipe; ++i){
pid[i] = fork(); //Dans chaque itération on crée un fils pour chaque commande dans la table "cmd"
if(pid[i]<0){ // Tester le statut du création d'un fils
printf("Error creation a Child\n");
}else if (pid[i] == 0){ //On est dans le fils.On commence à configurer les pipes, on traite 3 cas principaux
if (i==0){ //Cas 1 : La première commande, sa sortie doit être l'entrée de la prochaine pipe
redirectionEntreeSortie(l->in,l->out); //Faire une redirection s'elle existe
dup2(p[i][1],STDOUT_FILENO); //Configurer la premiere pipe, sa sortie est enregiistrer dans le fichier temporaire STDOUT_FILENO
for(int j=0;j<nbrPipe-1;j++){
if(j==0){
close(p[j][0]); //Fermer l'entrée de la pipe "j"
}else{
close(p[j][0]); //Fermer l'entrée de la pipe "j"
close(p[j][1]); //Fermer la sortie de la pipe "j"
}
}
}else if (i == nbrPipe-1){ //Cas 2: La dernière commande: l'entrée de cette dernière doit être la sortie de la dernière pipe "Indice=nbrPipes-1"
redirectionEntreeSortie(l->in,l->out); //Faire une redirection s'elle existe
dup2(p[i-1][0],STDIN_FILENO); ////Configurer la dernière pipe, l'entrée de cette dernière est la sortie de la dernière pipe
for(int j=0;j<nbrPipe-1;j++){
if(j== i-1){
close(p[j][1]); //Fermer la sortie de la pipe "j"
}else{
close(p[j][0]); //Fermer l'entrée de la pipe "j"
close(p[j][1]); //Fermer la sortie de la pipe "j"
}
}
}else{ //Cas 3: Les commandes au milieu
dup2(p[i][1],STDOUT_FILENO); //Configurer la pipe "i-1" pour qu'elle soit l'entree
dup2(p[i-1][0],STDIN_FILENO); //de la pipe suivante
for(int j=0;j<nbrPipe-1;j++){
if(j==i){
close(p[j][0]); // Fermer l'entrée de la pipe "j"
}else if(j==i-1){
close(p[j][1]); // Fermer la sortie de la pipe "j"
}else{
close(p[j][0]); // Fermer l'entrée de la pipe "j"
close(p[j][1]); // Fermer la sortie de la pipe "j"
}
}
}
executeSimpleCommande(l->seq[i]); //Executer une commande simple
exit(0); //Fils mort
}
}
for(int i =0;i<nbrPipe-1;i++){ //Fermer les entree et sorties de toutes les pipes
close(p[i][0]);
close(p[i][1]);
}
for(int i=0;i<nbrPipe;i++){ //Attendre tous les fils crées
waitpid(pid[i],NULL,0);
}
for(int i=0;i<nbrPipe-1;i++){
free(p[i]);
}
free(p); //Libérer le matrice des pipe
free(pid); //Libérer le pid
}
void executeCommandeRediretionOut(char** cmd, char* out){ //Exécuter une commande de redirection de type ">"
if (strcmp(out,">")!=0)
{ redirectionEntreeSortie(NULL,out);
executeSimpleCommande(cmd);
}else{
perror("Command no implemented\n"); //Au cas ou on a une commande de type ">>" on affiche ce message
}
}
void executeCommandeRediretionIn(char** cmd, char* in,char* out){ //Exécuter une commande de redirection de type "<"
redirectionEntreeSortie(in,out);
executeSimpleCommande(cmd);
}
void handler_CHILD(int sig){ //Cette fonction ramasse les processus terminés pour éviter la prolifération de zombis
pid_t fils;
while((fils = waitpid(-1, NULL, WNOHANG)) > 0) {
printf("[%d] : terminated in Background\n", fils);
}
}
void handler_SIGINT(int sig){ // "Ctr+C" Cette fonction s'exécute lorsque le fils reçoit un signal de type SIGINT
printf("\nSIGINT recus ^^ \n");
fflush(stdout); //Vider le buffer
return; //pour continue dans notre shell
}
void handler_SIGTSTP(int sig){ // "Ctr+Z" :Cette fonction s'exécute lorsque le fils reçoit un signal de type SIGTSTP
s = 1;
count1++; //Incrémenter le nombre des processus stoppés dans l'arrière-plan
printf("\nSIGTSTP recus ^^\n");
fflush(stdout); //Vider le buffer
return; //pour continue dans notre shell
}
Jobs* ADDjob(pid_t pid, char* name, int status, Jobs* listJobs){ //Ajouter un job dans la liste static des jobs "listJobs"
Jobs* job =(Jobs*) malloc(sizeof(Jobs)); // Crée un job dynamiquement de type "Jobs"
if (job == NULL) //Tester la creation d'un job
exit(EXIT_FAILURE);
job->pid = pid;
job->jbname = malloc(sizeof(char)*(strlen(name)+1));
strcpy(job->jbname, name); // pour copie le nom proprement
job->status = status;
job->num = countJobs;
job->next = listJobs; // chainer le job avec la liste "listJobs"
countJobs++; //Incrimenter le numero pour le job suivant
return job; //Retourner le job
}
void DisplayJobs(Jobs* listJobs){ //Affichage récursive de la liste des jobs "listJobs"
if (listJobs==NULL){ //tester si on pas encore atteint la fin de la liste
return;
}
int ProssStatus = listJobs->status;
if(ProssStatus==1){ //tester le statut d'un processus
printf("[%d]+\t\tRunning\t\t%d\t\t%s\t\n", listJobs->num,listJobs->pid,listJobs->jbname);
}else if(ProssStatus==0){
printf("[%d]+\t\tStopped\t\t%d\t\t%s \n", listJobs->num,listJobs->pid, listJobs->jbname);
}else{
printf("[%d]+\t\tTerminited\t\t%d\t\t%s \n", listJobs->num,listJobs->pid, listJobs->jbname);
}
DisplayJobs(listJobs->next); //pour afficher le job suivant
}
void FreeJobs(Jobs* listJobs){ //
while (listJobs != NULL) { /* tant que la liste n'est pas vide je libère job par job */
Jobs *cell = listJobs;
listJobs = listJobs->next;
free(cell);
}
}
void changeStatus(pid_t pid){ //fonction permet de changer le status d'un processus terminé en status : 2 (Terminated)
Jobs *cell = listJobs;
if(listJobs!=NULL){
while (listJobs != NULL) {
if (listJobs->pid == pid)
{
listJobs->status = Terminated;
return;
}
listJobs = listJobs->next;
}
}
return;
}
void executeCommande(struct cmdline *l){
int background = 0; // Variable pour savoir le statut d'un processus
signal(SIGCHLD, handler_CHILD);
signal(SIGINT,SIG_IGN); //Ignorer le signal SIGINT
signal(SIGTSTP,SIG_IGN); //Ignorer le signal SIGTSTP
if (l->tachFond == '&'){ //Tester si l'utilisateur a tapé le caractère "&" aprés un programme
background = 1; //Pour dire que le processus est on arrière-plan
}
pid_t pid = fork(); //Cree un fils
signal(SIGINT,handler_SIGINT); // Attendre un signal SIGINT
signal(SIGTSTP, handler_SIGTSTP); // Attendre un signal SIGTSTP
if (pid<0){ //Tester la creation d'un processus fils
perror("Error Creation Child ");
}
if(pid==0){ //C'est le fils
if (l->seq[1] == NULL){ //Commande sans pipes
if (l->out==NULL && l->in==NULL){ // Commande Simple
executeSimpleCommande(l->seq[0]);
}else if(l->in==NULL){ //Commande avec redirection ">"
executeCommandeRediretionOut(l->seq[0],l->out);
}else{ //Commande avec redirection "<""
executeCommandeRediretionIn(l->seq[0],l->in,l->out);
}
}else{ //Commande avec pipes "|"
executeCommandePipe(l);
}
exit(0); //fils mort
}else{ //C'est le Pere
if (background){ //Si on est on est en arriere plan
count++; // Compter le nombre des fils qui s'exécutent dans l'arrière-plan dans la session courante
printf("[%d]+ %d\n",count,pid);
listJobs=ADDjob(pid,l->seq[0][0],Running,listJobs); //Ajouter un job
}else{
printf("[%d]\n",pid); //Afficher le Pid du processus qui s'execute en premmier plan
}
if(background) {
return;
}
while(waitpid(pid, NULL, 0|WUNTRACED) == -1){} //Attendre le fils de Pid "pid"
if (s!=1){ //Si le processus n'a pas recus un signal de type SIGTSTP
printf("[%d]: termine\n", pid);
}else{ //Si oui alors le s=1
printf("[%d]+\t\tStopped\n",count1);
s=0; //Réinitialiser le la variable "s"
listJobs=ADDjob(pid,l->seq[0][0],Stopped,listJobs); //Ajouter un job dans la liste "listJobs"
}
}
}
static void memory_error(void)
{
errno = ENOMEM;
perror(0);
exit(1);
}
static void *xmalloc(size_t size)
{
void *p = malloc(size);
if (!p) memory_error();
return p;
}
static void *xrealloc(void *ptr, size_t size)
{
void *p = realloc(ptr, size);
if (!p) memory_error();
return p;
}
/* Read a line from standard input and put it in a char[] */
static char *readline(void)
{
size_t buf_len = 16;
char *buf = xmalloc(buf_len * sizeof(char));
if (fgets(buf, buf_len, stdin) == NULL) {
free(buf);
return NULL;
}
if (feof(stdin)) { /* End of file (ctrl-d) */
fflush(stdout);
exit(0);
}
do {
size_t l = strlen(buf);
if ((l > 0) && (buf[l-1] == '\n')) {
l--;
buf[l] = 0;
return buf;
}
if (buf_len >= (INT_MAX / 2)) memory_error();
buf_len *= 2;
buf = xrealloc(buf, buf_len * sizeof(char));
if (fgets(buf + l, buf_len - l, stdin) == NULL) return buf;
} while (1);
}
/* Split the string in words, according to the simple shell grammar. */
static char **split_in_words(char *line)
{
char *cur = line;
char **tab = 0;
size_t l = 0;
char c;
while ((c = *cur) != 0) {
char *w = 0;
char *start;
switch (c) {
case ' ':
case '\t':
/* Ignore any whitespace */
cur++;
break;
case '<':
w = "<";
cur++;
break;
case '>':
w = ">";
cur++;
break;
case '|':
w = "|";
cur++;
break;
case '&':
w = "&";
cur++;
break;
default:
/* Another word */
start = cur;
while (c) {
c = *++cur;
switch (c) {
case 0:
case ' ':
case '\t':
case '<':
case '>':
case '|':
case '&':
c = 0;
break;
default: ;
}
}
w = xmalloc((cur - start + 1) * sizeof(char));
strncpy(w, start, cur - start);
w[cur - start] = 0;
}
if (w) {
tab = xrealloc(tab, (l + 1) * sizeof(char *));
tab[l++] = w;
}
}
tab = xrealloc(tab, (l + 1) * sizeof(char *));
tab[l++] = 0;
return tab;
}
static void freeseq(char ***seq)
{
int i, j;
for (i=0; seq[i]!=0; i++) {
char **cmd = seq[i];
for (j=0; cmd[j]!=0; j++) free(cmd[j]);
free(cmd);
}
free(seq);
}
/* Free the fields of the structure but not the structure itself */
static void freecmd(struct cmdline *s)
{
if (s->in) free(s->in);
if (s->out) free(s->out);
if (s->seq) freeseq(s->seq);
}
struct cmdline *readcmd(void)
{
static struct cmdline *static_cmdline = 0;
struct cmdline *s = static_cmdline;
char *line;
char **words;
int i;
char *w;
char **cmd;
char ***seq;
size_t cmd_len, seq_len;
line = readline();
if (line == NULL) {
if (s) {
freecmd(s);
free(s);
}
return static_cmdline = 0;
}
cmd = xmalloc(sizeof(char *));
cmd[0] = 0;
cmd_len = 0;
seq = xmalloc(sizeof(char **));
seq[0] = 0;
seq_len = 0;
words = split_in_words(line);
free(line);
if (!s)
static_cmdline = s = xmalloc(sizeof(struct cmdline));
else
freecmd(s);
s->err = 0;
s->in = 0;
s->out = 0;
s->seq = 0;
s->tachFond = 0;
i = 0;
while ((w = words[i++]) != 0) {
switch (w[0]) {
case '<':
/* Tricky : the word can only be "<" */
if (s->in) {
s->err = "only one input file supported";
goto error;
}
if (words[i] == 0) {
s->err = "filename missing for input redirection";
goto error;
}
s->in = words[i++];
break;
case '>':
/* Tricky : the word can only be ">" */
if (s->out) {
s->err = "only one output file supported";
goto error;
}
if (words[i] == 0) {
s->err = "filename missing for output redirection";
goto error;
}
s->out = words[i++];
break;
case '|':
/* Tricky : the word can only be "|" */
if (cmd_len == 0) {
s->err = "misplaced pipe";
goto error;
}
seq = xrealloc(seq, (seq_len + 2) * sizeof(char **));
seq[seq_len++] = cmd;
seq[seq_len] = 0;
cmd = xmalloc(sizeof(char *));
cmd[0] = 0;
cmd_len = 0;
break;
case '&':
/* Tricky : the word can only be "&" */
if (cmd_len == 0) {
s->err = "misplaced &";
goto error;
}
s->tachFond = '&';
break;
default:
cmd = xrealloc(cmd, (cmd_len + 2) * sizeof(char *));
cmd[cmd_len++] = w;
cmd[cmd_len] = 0;
}
}
if (cmd_len != 0) {
seq = xrealloc(seq, (seq_len + 2) * sizeof(char **));
seq[seq_len++] = cmd;
seq[seq_len] = 0;
} else if (seq_len != 0) {
s->err = "misplaced pipe";
i--;
goto error;
} else
free(cmd);
free(words);
s->seq = seq;
return s;
error:
while ((w = words[i++]) != 0) {
switch (w[0]) {
case '<':
case '>':
case '|':
case '&':
break;
default:
free(w);
}
}
free(words);
freeseq(seq);
for (i=0; cmd[i]!=0; i++) free(cmd[i]);
free(cmd);
if (s->in) {
free(s->in);
s->in = 0;
}
if (s->out) {
free(s->out);
s->out = 0;
}
return s;
}
|
C
|
#include <stdio.h>
void sum_of_digit(int);
void main()
{
int n;
printf("Enter an integer\n");
scanf("%d", &n);
sum_of_digit(n);
}
void sum_of_digit(int n)
{
int t, sum = 0, remainder;
t = n;
while (t != 0)
{
remainder = t % 10;
printf("%d\n",remainder);
sum = sum + remainder;
printf("%d\n",sum);
t = t / 10;
printf("%d\n",t);
printf("\n\n\n");
}
printf("Sum of digits of %d = %d\n", n, sum);
}
|
C
|
#include <inttypes.h>
#include <stdio.h>
#include <stdlib.h>
#include <regex.h>
#include <string.h>
#include <ctype.h>
#include "parse.h"
#include "smallfunc.h"
/*
A place for short simple functions, counting items in strings,
converting strings to numbers.. etc.
*/
/*
Example, If you want to check if a string is only
made up of "0" and "1" like this "0101010101"
you call string_contains("0101010101","10",strlen("0101010101"));
*/
/*return 1 if all match, else zero if fail*/
int string_contains(const char * str, const char * chars, const unsigned int size)
{
unsigned int i,a;
unsigned ret;
ret=0;
for(i=0;(i<size) && (str[i]!='\0');i++)
{
for(a=0;chars[a]!='\0';a++)
{
ret |= (str[i]==chars[a]);
}
if(!ret)
{
return 0;
}
}
return 1;
}
/*Convert a string of 1's and 0's to a number, max length is 64 bits*/
uint64_t binstr_to_uint64(const char * str, const unsigned int size)
{
uint64_t temp;
unsigned int i;
temp=0;
/*
string is encodeded, MSB first, LSB last.
*/
for(i=0;(i<size) && (i<64);i++)
{
if(str[i]=='1')
{
temp |= 1<<(size-i-1);
}
}
return temp;
}
/*count n of arguments int a string "a,b,c,d"=4*/
unsigned int count_args(const char * op_args, const unsigned int strlen_op_args)
{
unsigned int i;
unsigned int arg_c;
/*Parse op_args, and count number of args*/
for(i=0,arg_c=0;i<strlen_op_args;i++)
{
if(op_args[i]!=',')
{
if(op_args[i]!=' ')
{
/*this was used in encode_opcode to make the string "abcd" out of "a,b,c,d"*/
/*op_list[arg_c].arg_t = op_args[i];*/
arg_c++;
}
}
else
{
}
}
return arg_c;
}
ARG_TYPE isHex(const char * str, const unsigned int len)
{
ARG_TYPE is;
unsigned int sc;
if(!strncmp(str, "0x", 2))
{
/*This has potential to be a hex number*/
is=ISHEX;
for(sc=2;(sc<len) && (is==ISHEX);sc++)
{
if(isxdigit(str[sc]))
{
/*It is still hex*/
is=ISHEX;
}else
{
/*It is not hex*/
is=ISUNDEFINED;
}
}
} else
{
is=ISUNDEFINED;
}
return is;
}
ARG_TYPE isDigit(const char * str, const unsigned int len)
{
ARG_TYPE is;
unsigned int sc;
is=ISNUMBER;
for(sc=0;(sc<len) && (is==ISNUMBER);sc++)
{
if(isdigit(str[sc]))
{
/*It is still a number*/
is=ISNUMBER;
}else
{
/*It is not a number*/
is=ISUNDEFINED;
}
}
return is;
}
ARG_TYPE isNumberType(const char * str, const unsigned int len)
{
ARG_TYPE is;
is=isHex(str, len);
if(is==ISUNDEFINED)
{
is=isDigit(str, len);
}
return is;
}
/*returns number of 'word_size' the number 'a' fits in*/
uint64_t bitSize(uint64_t a)
{
const uint64_t size = sizeof(uint64_t)*8;
uint64_t i;
for(i=0;(i<size) && ((a & (((uint64_t)1)<<((size-1)-i)))==0) ;i++);
i=size-i;
return i;
}
uint64_t nWords(const uint64_t bitsize, const uint64_t wordsize)
{
if((bitsize % wordsize) == 0)
{
return (bitsize/wordsize)*16;
}
return (bitsize / wordsize) * wordsize + wordsize;
}
char * remWhite(char * s, const unsigned int len)
{
unsigned int i,a;
signed foundother=0;
for(i=0;i<len;i++)
{
if( (isspace(s[i]) || s[i]==' ') && foundother==0)
{
for(a=i;a<len;a++)
{
s[a]=s[a+1];
}
} else foundother=1;
if(isspace(s[i]) && foundother==1)
{
s[i]=' ';
}
}
foundother=0;
for(i=len-1;i>0;i--)
{
if( (isspace(s[i]) || s[i]==' ') && foundother==0)
{
s[i]=0;
} else foundother=1;
}
return s;
}
/*copies the string from str to store until it finds the character split*/
/*if the character split is within a [], () or {} it ignores that one*/
/*if there is a string like this "abc,def,xyz" and we want the string "def"*/
/*specify split=',' and nth=1 for the second string split by the character ','*/
void splitString(char * store, const char * str, const unsigned int len, const char split, const unsigned int nth)
{
unsigned int i,a,b;
i=0;
for(b=0;b<(nth+1);b++)
{
a=0;
for(i=i;(i<len) && (str[i]!=split);i++)
{
if(str[i]=='[')
{
for(i=i;(i<len) && (str[i]!=']');i++)
{
store[a++]=str[i];
}
}
if(str[i]=='(')
{
for(i=i;(i<len) && (str[i]!=')');i++)
{
store[a++]=str[i];
}
}
if(str[i]=='{')
{
for(i=i;(i<len) && (str[i]!='}');i++)
{
store[a++]=str[i];
}
}
store[a++]=str[i];
}
i++;
store[a++]='\0';
}
}
unsigned int breakString(char * store, const char * str, const size_t strl)
{
unsigned int i,a;
char temp[MAX_CNT_OF_LINE];
signed found_other;
a=0;
found_other=0;
if(strl>10000)
{
return 0;
}
for(i=0;i<strl;i++)
{
if((!isblank(str[i])))
{
found_other=1;
temp[a] = str[i];
a++;
}
else if((found_other==1) && isblank(str[i]))
{
i=strl;
}
}
temp[a]='\0';
strncpy(store,temp,a);
return a;
}
|
C
|
#include <stdlib.h>
#include <stdio.h>
#include "arvore_rubro_negra.h"
/* no especial que ira representar todos os nos externos (folhas) */
PNO externo = NULL;
PNO suporte_raiz = NULL;
/* inicializa uma arvore vazia */
void inicializar_arvoreRB(PNO* raiz){
externo = (PNO) malloc(sizeof(NO));
externo->cor = negro;
*raiz = externo;
suporte_raiz = *raiz;
}
/* imprime em pre-ordem*/
void imprime_arvoreRB(PNO raiz){
if (raiz == externo){
printf("(N)");
return;
}
printf("(");
//imprime a cor
if (raiz->cor == rubro) printf("R ");
else printf("N ");
printf("%d",raiz->chave);
imprime_arvoreRB(raiz->esq);
imprime_arvoreRB(raiz->dir);
printf(")");
}
/* cria um novo (aloca memoria) com chave=ch, inicializa propriamente os filhos esquerdo e direito e retorna
seu endereco */
PNO criar_novo_no(TIPOCHAVE ch){
PNO novo = (PNO) malloc(sizeof(NO));
novo->chave = ch;
novo->pai = NULL;
novo->dir = externo;
novo->esq = externo;
novo->cor = rubro;
return novo;
}
/* verifica e acerta o equilibrio de um no após uma inserção. */
void rotacionar(PNO* raiz, PNO filho, PNO atual, PNO pai, PNO avo, char* controle) {
PNO auxraiz;
if (*controle != 2 && atual != NULL && pai != NULL) {
//pai é negro
if ((pai->dir == atual && pai->esq->cor == rubro) || (pai->esq == atual && pai->dir->cor == rubro)) {
*controle = 0;
//irmão do atual é rubro
if (pai->dir == atual) {
pai->esq->cor = negro;
} else {
pai->dir->cor = negro;
}
atual->cor = negro;
if (*raiz != pai) {
pai->cor = rubro;
}
if (avo != NULL && avo->cor == rubro){ // Controle acho que era para o avo
//desequilibro chamada recursiva
rotacionar(raiz, pai, avo, avo->pai, avo->pai->pai, controle);
}
*controle = 1;
} else {
//irmão do atual é negro
if (atual->esq == filho && pai->esq == atual) {
auxraiz = pai;
atual->cor = negro;
pai->cor = rubro;
rotacionar_a_direita(&pai, atual);
if (auxraiz == *raiz) {
*raiz = pai;
suporte_raiz = *raiz;
}
} else if(atual->esq == filho && pai->dir == atual) {
auxraiz = pai;
filho->cor = negro;
pai->cor = rubro;
rotacionar_a_direita(&atual, filho);
rotacionar_a_esquerda(&pai, atual); //Aqui talvez seja atual ou filho
if (auxraiz == *raiz) {
*raiz = pai;
suporte_raiz = *raiz;
}
} else if (atual->dir == filho && pai->dir == atual) {
auxraiz = pai;
atual->cor = negro;
pai->cor = rubro;
rotacionar_a_esquerda(&pai, atual);
if (auxraiz == *raiz) {
*raiz = pai;
suporte_raiz = *raiz;
}
} else {
auxraiz = pai;
filho->cor = negro;
pai->cor = rubro;
rotacionar_a_esquerda(&atual, filho);
rotacionar_a_direita(&pai, atual);
if (auxraiz == *raiz) {
*raiz = pai;
suporte_raiz = *raiz;
}
}
*controle = 1;
}
*controle = 2;
}
}
/* insere sem repeticao um novo no com chave = x, atual, pai e avo apontam, respectivamente, para o no corrente da busca, seu pai e seu avo, e controle controla a chamada da funcao rotacionar. Retorna true se inserir com sucesso e false caso contrario (se ja existir um no com a chave x). */
bool inserir_RN(PNO* raiz, TIPOCHAVE x, PNO* atual, PNO pai, PNO avo, char* controle){
if (arvoreRN_vazia(*raiz)) {
*raiz = criar_novo_no(x);
(*raiz)->cor = negro;
suporte_raiz = *raiz;
return true;
}
PNO auxnovo;
if (x == (*atual)->chave) {
return false;
} else if (x > (*atual)->chave) {
if ((*atual)->dir != externo) {
inserir_RN(raiz, x, &(*atual)->dir, *atual, (*atual)->pai, controle);
} else {
auxnovo = criar_novo_no(x);
auxnovo->pai = *atual;
(*atual)->dir = auxnovo;
}
} else {
if ((*atual)->esq != externo) {
inserir_RN(raiz, x, &(*atual)->esq, *atual, (*atual)->pai, controle);
} else {
auxnovo = criar_novo_no(x);
auxnovo->pai = *atual;
(*atual)->esq = auxnovo;
}
}
if (*controle != 2 && (*atual)->cor == rubro) { //Caso 2
rotacionar(raiz, auxnovo, *atual, (*atual)->pai, (*atual)->pai->pai, controle);
}
return true;
}
/* retorna true se a arvore rubro negra estiver vazia e false caso contrario */
bool arvoreRN_vazia(PNO raiz){
if (raiz == externo) return true;
return false;
}
/* Busca o nó com chave = x.
Retorna o ponteiro para o nó.
Você pode utilizar o no "externo" como sentinela. */
PNO buscar_no(PNO raiz, TIPOCHAVE x){
if (arvoreRN_vazia(raiz)) return NULL;
PNO no = raiz;
while (no != externo && no->chave != x) {
if (x > no->chave) { // vai para a direita
no = no->dir;
} else { //vai para a esquerda
no = no->esq;
}
}
if (no != externo){
return no;
} else {
return NULL;
}
}
/* retorna um ponteiro para o nó que é o menor descendente direito de "no" (que não seja o externo). */
PNO menor_descendente_direito(PNO no){
if (no != NULL) {
PNO aux_dir = no->dir;
if (aux_dir != externo) {
while (aux_dir->esq != externo) {
aux_dir = aux_dir->esq;
}
return aux_dir;
}
}
return NULL;
}
/* remove a chave x da arvore com raiz apontada por raiz.
Retorna true se removeu com sucesso e false caso contrario (se nao havia um no com a chave x). */
bool remover_RN(PNO* raiz, TIPOCHAVE x){
PNO auxno, auxpai, auxmenor, auxraiz, duplamente_negro; //duplamente_negro e o filho do no a ser removido
auxno = buscar_no(*raiz, x);
if (auxno != NULL) {
COR cor_no = auxno->cor;
if(auxno->esq != externo && auxno->dir != externo) {
auxmenor = menor_descendente_direito(auxno);
cor_no = auxmenor->cor;
auxno->chave = auxmenor->chave;
auxpai = auxmenor->pai;
auxraiz = auxpai;
if (auxmenor->dir != externo) {
if (auxpai->chave != x) { // É o proprio nó com o valor a ser removido
auxpai->esq = auxmenor->dir;
auxmenor->dir->pai = auxpai;
} else {
auxno->dir = auxmenor->dir;
auxmenor->dir->pai = auxno;
}
duplamente_negro = auxmenor->dir;
} else {
if (auxpai->esq == auxmenor) {
auxpai->esq = externo;
} else {
auxpai->dir = externo;
}
duplamente_negro = externo;
}
free(auxmenor);
} else if (auxno->esq != externo) {
auxpai = auxno->pai;
auxraiz = auxpai;
if (auxpai != NULL) {
if (auxpai->dir == auxno) {
auxpai->dir = auxno->esq;
auxpai->esq->pai = auxpai;
} else {
auxpai->esq = auxno->esq;
auxpai->esq->pai = auxpai;
}
duplamente_negro = auxpai->esq;
} else {
*raiz = auxno->esq;
(*raiz)->pai = NULL;
suporte_raiz = *raiz;
duplamente_negro = *raiz;
}
free(auxno);
} else if (auxno->dir != externo) {
auxpai = auxno->pai;
auxraiz = auxpai;
if (auxpai != NULL) {
if (auxpai->dir == auxno) {
auxpai->dir = auxno->dir;
auxpai->dir->pai = auxpai;
} else {
auxpai->esq = auxno->dir;
auxpai->dir->pai = auxpai;
}
duplamente_negro = auxpai->dir;
} else {
*raiz = auxno->dir;
(*raiz)->pai = NULL;
suporte_raiz = *raiz;
duplamente_negro = *raiz;
}
free(auxno);
} else {
duplamente_negro = externo;
auxpai = auxno->pai;
auxraiz = auxpai;
if (auxpai != NULL) {
if (auxpai->dir == auxno) {
auxpai->dir = externo;
} else {
auxpai->esq = externo;
}
} else {
//Arvore totalmente vazia apos a delecao
*raiz = externo;
suporte_raiz = *raiz;
}
free(auxno);
}
if (cor_no != rubro) { // o duplamente_negro é usado aqui
//Balancear
equilibrar_RN_apos_remocao(&auxpai, duplamente_negro);
if (suporte_raiz != *raiz) {
(*raiz) = suporte_raiz;
}
}
} else {
return false;
}
return true;
}
/* faz uma rotação a esquerda no nó no, na árvore apontada por raiz */
void rotacionar_a_esquerda(PNO* raiz, PNO no){
PNO pai, avo, filho_no_esq;
bool filho_avo_dir;
pai = *raiz;
avo = pai->pai;
if (avo != NULL) {
if (avo->dir == pai) {
filho_avo_dir = true;
} else {
filho_avo_dir = false; //é filho dir em rot duplas
}
}
filho_no_esq = no->esq;
no->pai = avo;
pai->dir = filho_no_esq;
pai->pai = no;
no->esq = pai;
if (filho_no_esq != externo) {
filho_no_esq->pai = pai;
}
if (avo != NULL) {
if (filho_avo_dir) {
avo->dir = no;
} else {
avo->esq = no;
}
}
*raiz = no;
}
/* faz uma rotação a direita no nó no, na árvore apontada por raiz */
void rotacionar_a_direita(PNO* raiz, PNO no){
PNO pai, avo, filho_no_dir;
bool filho_avo_esq;
pai = *raiz;
avo = pai->pai;
if (avo != NULL) {
if (avo->esq == pai) {
filho_avo_esq = true;
} else {
filho_avo_esq = false; //é filho dir em rot duplas
}
}
filho_no_dir = no->dir;
no->pai = avo;
pai->esq = filho_no_dir;
pai->pai = no;
no->dir = pai;
if (filho_no_dir != externo) {
filho_no_dir->pai = pai;
}
if (avo != NULL) {
if (filho_avo_esq) {
avo->esq = no;
} else {
avo->dir = no;
}
}
*raiz = no;
}
/* equilibra a érvore apontada por raiz, assumindo que o nó problemático é q. */
void equilibrar_RN_apos_remocao(PNO* raiz, PNO q){
PNO pai, irmao;
pai = *raiz;
if (pai != q && pai != NULL && q != NULL && q->cor == negro) {
if (pai->esq == q) {
irmao = pai->dir;
//Caso de 1-4 duplamente negro como filho ESQUERDO
if (irmao->cor == rubro) {
//Caso 1 - irmao é rubro, logo pai é negro.
pai->cor = rubro;
irmao->cor = negro;
rotacionar_a_esquerda(&pai, irmao);
if (pai->pai == NULL) {
*raiz = pai;
suporte_raiz = *raiz;
}
equilibrar_RN_apos_remocao(&pai->esq, q); // o filho do pai virou raiz, entao temos que continuar na mesma raiz
} else if (irmao->cor == negro && irmao->esq->cor == negro && irmao->dir->cor == negro) {
//Caso 2 - irmao é negro e seus filhos tbm
irmao->cor = rubro;
if (pai->cor == negro) { // pai vira duplamente negro, logo tenho que equilibrar ele
equilibrar_RN_apos_remocao(&pai->pai, pai);
} else {
pai->cor = negro; // arvore balanceada
}
} else if (irmao->cor == negro && irmao->esq->cor == rubro && irmao->dir->cor == negro) {
// Caso 3 - irmao é negro, o filho direito tbm e o esquerdo é rubro.
irmao->cor = rubro;
irmao->esq->cor = negro;
rotacionar_a_direita(&irmao, irmao->esq); //transformado em Caso 4
equilibrar_RN_apos_remocao(&pai, q);
} else {
// Caso 4 - irmao é negro e filho direito é rubro, nao se sabe a cor do outro filho
irmao->cor = pai->cor; //nao sabemos a cor do pai
pai->cor = negro;
irmao->dir->cor = negro;
rotacionar_a_esquerda(&pai, irmao);
if (pai->pai == NULL) {
*raiz = pai;
suporte_raiz = *raiz;
}
}
} else { // q e filho dir de pai
irmao = pai->esq;
//Caso de 1-4 duplamente negro como filho DIREITO
if (irmao->cor == rubro) {
//Caso 1 - irmao é rubro, logo pai é negro.
pai->cor = rubro;
irmao->cor = negro;
rotacionar_a_direita(&pai, irmao);
if (pai->pai == NULL) {
*raiz = pai;
suporte_raiz = *raiz;
}
equilibrar_RN_apos_remocao(&pai->dir, q);
} else if (irmao->cor == negro && irmao->dir->cor == negro && irmao->esq->cor == negro) {
//Caso 2 - irmao é negro e seus filhos tbm
irmao->cor = rubro;
if (pai->cor == negro) { // pai vira duplamente negro, logo tenho que equilibrar ele
equilibrar_RN_apos_remocao(&pai->pai, pai);
} else {
pai->cor = negro; // arvore balanceada
}
} else if (irmao->cor == negro && irmao->dir->cor == rubro && irmao->esq->cor == negro) {
// Caso 3 - irmao é negro, o filho esquerdo tbm e o direito é rubro.
irmao->cor = rubro;
irmao->dir->cor = negro;
rotacionar_a_esquerda(&irmao, irmao->dir); //transformado em Caso 4
equilibrar_RN_apos_remocao(&pai, q);
} else {
// Caso 4 - irmao é negro e filho esquerdo é rubro, nao se sabe a cor do outro filho
irmao->cor = pai->cor; //nao sabemos a cor do pai
pai->cor = negro;
irmao->esq->cor = negro;
rotacionar_a_direita(&pai, irmao);
if (pai->pai == NULL) {
*raiz = pai;
suporte_raiz = *raiz;
}
}
}
} else {
if (q != NULL && q->cor == rubro) {
q->cor = negro;
}
}
return;
}
|
C
|
#ifndef _TASKS_H
#define _TASKS_H
#define MAX_TASKS 2
typedef struct
{
void(*fun)(void); // pointer to the task function
unsigned int trigger_time; // period [in ms] when task is executed
unsigned int current_time; // internal counter, set to 0 on init
} TASK;
extern TASK tasks[MAX_TASKS];
void tasks_init();
void tasks_set(unsigned int taskId, void(*fun)(void), unsigned int trigger_time);
#endif
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main( int ac, char **av )
{
struct tm tm ;
/* best set it, since it's not static data */
memset((void*)&tm, 0, sizeof(struct tm)) ;
strptime( "1980/06/01 01:00", "%Y/%m/%d %H:%M", &tm ) ;
tm.tm_hour -= 1 ;
time_t t = mktime(&tm) ;
char buf[BUFSIZ] ;
strftime( buf, BUFSIZ, "%Y/%m/%d %H:%M:%S", localtime(&t) ) ;
printf( "%s\n", buf ) ;
return 0 ;
}
|
C
|
/* passed: 0ms */
/**
* Return an array of arrays of size *returnSize.
* The sizes of the arrays are returned as *returnColumnSizes array.
* Note: Both returned array and *columnSizes array must be malloced, assume caller calls free().
*/
int** generate(int numRows, int* returnSize, int** returnColumnSizes){
int i=0, j=0;
int ** result = NULL;
if (numRows == 0)
{
*returnSize = 0;
return NULL;
}
result = (int**)malloc(sizeof(int*)*numRows);
if (NULL == result)
{
*returnSize = 0;
return NULL;
}
*returnColumnSizes = (int*)malloc(sizeof(int)*numRows);
if (NULL == result)
{
free(result);
*returnSize = 0;
return NULL;
}
*returnSize = numRows;
for(i=0; i<numRows; i++)
{
(*returnColumnSizes)[i] = i+1;
result[i] = (int*)malloc(sizeof(int)*(i+1));
if (NULL == result[i])
{
for(j=0; j<i; j++)
free(result[j]);
free(result);
free(*returnColumnSizes);
*returnSize = 0;
return NULL;
}
// calc the i line
for (j = 0; j<=(i+1)/2; j++)
{
if (j==0 || j==i) // notice: without j==i, when i=1, will crash
{
result[i][j] = 1;
result[i][i-j] = 1;
}
else
{
result[i][j] = result[i-1][j-1] + result[i-1][j];
result[i][i-j] = result[i][j];
}
}
}
return result;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "ot_user_information.h"
ot_user_information_t *ot_user_information_create()
{
ot_user_information_t *this = malloc(sizeof(ot_user_information_t));
if (this == NULL)
{
printf("Allocation Error!\n");
}
return this;
}
void ot_user_information_init(ot_user_information_t *this)
{
this->sample_buffer = malloc(GENERAL_BUFFER_SIZE);
memset(this->name, '\0', GENERAL_BUFFER_SIZE);
memset(this->surname, '\0', GENERAL_BUFFER_SIZE);
memset(this->sample_buffer, '\0', GENERAL_BUFFER_SIZE);
}
void ot_user_information_set_name(ot_user_information_t *this, char *name)
{
// Important Rule - Memory Leak or Memory Corruption
// For example name size=5
// For example name size=15
if (strlen(name) < GENERAL_BUFFER_SIZE)
{
strncpy(this->name, name, strlen(name));
}
}
char *ot_user_information_get_name(ot_user_information_t *this)
{
return this->name;
}
void ot_user_information_set_surname(ot_user_information_t *this, char *surname)
{
// Important Rule - Memory Leak or Memory Corruption
// For example name size=5
// For example name size=15
if (strlen(surname) < GENERAL_BUFFER_SIZE)
{
strncpy(this->surname, surname, strlen(surname));
}
}
char *ot_user_information_get_surname(ot_user_information_t *this)
{
return this->surname;
}
void ot_user_information_set_sample_buffer(ot_user_information_t *this, char *sample_buffer)
{
if (strlen(sample_buffer) < GENERAL_BUFFER_SIZE)
{
strncpy(this->sample_buffer, sample_buffer, strlen(sample_buffer));
}
}
char *ot_user_information_get_sample_buffer(ot_user_information_t *this)
{
return this->sample_buffer;
}
void ot_user_information_display_users(void *user)
{
ot_user_information_t *this = user;
if (this != NULL)
{
printf("this->name = %s\n", this->name);
printf("this->surname = %s\n", this->surname);
printf("this->sample_buffer = %s\n", this->sample_buffer);
}
}
int ot_user_information_compare_users(void *user_1, void *user_surname)
{
if (!strcmp(ot_user_information_get_surname(user_1), user_surname))
{
printf("Users Equal\n");
return 0;
}
return -1;
}
int ot_user_information_hash_key_calculater(ot_user_information_t *this)
{
int key = 0;
char *surname = ot_user_information_get_surname(this);
for (size_t i = 0; i < strlen(ot_user_information_get_surname(this)); i++)
{
key += surname[i];
}
return key;
}
void ot_user_information_deinit(ot_user_information_t *this)
{
memset(this->name, '\0', GENERAL_BUFFER_SIZE);
memset(this->surname, '\0', GENERAL_BUFFER_SIZE);
free(this->sample_buffer);
}
void ot_user_information_destroy(void *this)
{
ot_user_information_deinit(this);
free(this);
}
void ot_user_information_test()
{
char *temp;
ot_user_information_t *this = ot_user_information_create();
ot_user_information_init(this);
ot_user_information_set_sample_buffer(this, "sample_buffer");
temp = ot_user_information_get_sample_buffer(this);
printf("temp sample_buffer=%s\n", temp);
ot_user_information_set_name(this, "Onur");
temp = ot_user_information_get_name(this);
printf("temp name=%s\n", temp);
ot_user_information_set_surname(this, "Taslioglu");
temp = ot_user_information_get_surname(this);
printf("temp surname=%s\n", temp);
ot_user_information_display_users(this);
ot_user_information_deinit(this);
ot_user_information_init(this);
ot_user_information_set_name(this, "Joe");
ot_user_information_set_surname(this, "Done");
ot_user_information_set_sample_buffer(this, "sample_buffer");
ot_user_information_display_users(this);
ot_user_information_destroy(this);
}
|
C
|
/*************************************************************************
> File Name: stack.h
> Author:
> Mail:
> Created Time: Thu 09 Mar 2017 11:24:43 AM CST
************************************************************************/
#ifndef _STACK_H
#define _STACK_H
typedef struct _intStack{
int *elems;
int logicalLen;
int allocLength;
}intStack;
void intStackNew(intStack *pIntS);
void intStackDispose(intStack *pIntS);
void intStackPush(intStack *pIntS, int iValue);
int intStackPop(intStack *pIntS);
#endif
|
C
|
#include <string.h>
#include "libft.h"
char *ft_strncat(char *dest, const char *src, size_t n)
{
size_t index = 0;
size_t indexx = 0;
while (dest[index] != '\0')
{
index++;
}
while (indexx < n)
{
dest[index] = src[indexx];
index++;
indexx++;
}
return dest;
}
|
C
|
/*#include<stdio.h>
#include<string.h>
int main()
{
int n,a,j,k,i,n1;
char s1[10],s2[10],s3[10];
printf("Enter name: ");
gets(s1);
n1=strlen(s1);
//printf("%d",n1);
for(i=0;i<=n1-1;i++)
{
printf("s1[%d]=%c\n",i,s1[i]);
s3[j]=s1[i];
j++;
}
for(i=n1-1;i>=0;i--)
{
//printf("s2[%d]=%c\n",i,s2[i]);
s2[i]=s1[i];
}
for(i=0;i<=n1-1;i++)
{
if(s2[i]==s3[i])
{
printf("\nPalindrome");
}
else
{
printf("Not Palindrome");
}
}
return 0;
}*/
#include<stdio.h>
#include<string.h>
int main()
{
char s1[10],s2[10],s3[10];
int i,j=0,n,k,l;
printf("Enter a word: ");
gets(s1);
l=strlen(s1);
//printf("%d",l);
for(i=0;i<l;i++)
{
s2[i]=s1[i];
}
for(i=l-1,j=0;i>=0,j<l;i--,j++)
{
s3[j]=s2[i];
}
for(j=0;j<l;j++)
{
if(s2[j]==s3[j])
{
printf("Palindrome\n");
}
else
{
printf("Not Palindrome\n");
}
}
/*for(i=l,j=0;i>0,j<l;i--,j++)
{
s3[j]=s2[l];
}*/
return 0;
}
|
C
|
#include <assert.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include "symbol.h"
/*
Create a new SYMBOL provided the symbolName. The symbolValue will
be initialized to NULL. Use SETQ to set the symbolValue.
*/
VALUE_PTR MAKE_SYMBOL(STRING symbolName) {
assert(symbolName != NULL);
SYMBOL_PTR symbol = (SYMBOL_PTR)malloc(sizeof(SYMBOL));
// don't alias the symbolName argument, make a copy
symbol->symbolName = (STRING)malloc(strlen(symbolName)+sizeof(CHAR));
strcpy(symbol->symbolName, symbolName);
symbol->symbolValue = NULL;
return MAKE_SYMBOL_VALUE(symbol);
}
/*
Return the name of the SYMBOL
*/
STRING SYMBOL_NAME(VALUE_PTR symbol) {
if (symbol != NULL && IS_VALUE_SYMBOL(symbol)) {
return ((SYMBOL_PTR)GET_SYMBOL_VALUE(symbol))->symbolName;
} else {
return NULL;
}
}
/*
Return the value of the SYMBOL
*/
VALUE_PTR SYMBOL_VALUE(VALUE_PTR symbol) {
if (symbol != NULL && IS_VALUE_SYMBOL(symbol)) {
return ((SYMBOL_PTR)GET_SYMBOL_VALUE(symbol))->symbolValue;
} else {
return NULL;
}
}
/*
Release SYMBOL_NAME to memory
*/
void FREE_SYMBOL_NAME(SYMBOL_PTR symbol) {
assert(symbol != NULL);
if (symbol->symbolName != NULL) {
free(symbol->symbolName);
symbol->symbolName = NULL;
}
}
/*
Release SYMBOL_VALUE to memory
*/
void FREE_SYMBOL_VALUE(SYMBOL_PTR symbol) {
assert(symbol != NULL);
if (symbol->symbolValue != NULL) {
FREE_VALUE(symbol->symbolValue);
symbol->symbolValue = NULL;
}
}
/*
Release SYMBOL_PTR to memory, releasing all consituent members
*/
void FREE_SYMBOL(SYMBOL_PTR symbol) {
assert(symbol != NULL);
FREE_SYMBOL_NAME(symbol);
FREE_SYMBOL_VALUE(symbol);
free(symbol);
return;
}
/*
Change the value of an existing, i.e. already initialized, symbol.
*/
VALUE_PTR SETQ(VALUE_PTR symbol, VALUE_PTR symbolValue) {
if (symbol != NULL && IS_VALUE_SYMBOL(symbol)) {
FREE_VALUE(((SYMBOL_PTR)(symbol->value.symbol))->symbolValue);
((SYMBOL_PTR)(symbol->value.symbol))->symbolValue = symbolValue;
return symbol;
} else {
return MAKE_NIL_VALUE();
}
}
/*
Print symbol name
*/
void PRINT_SYMBOL_NAME(VALUE_PTR symbol) {
if (symbol != NULL && IS_VALUE_SYMBOL(symbol)) {
printf("%s ", ((SYMBOL_PTR)GET_SYMBOL_VALUE(symbol))->symbolName);
} else {
printf("NIL ");
}
}
/*
Print symbol value
*/
void PRINT_SYMBOL_VALUE(VALUE_PTR symbol) {
if (symbol != NULL && IS_VALUE_SYMBOL(symbol)) {
PRINT_VALUE(symbol);
} else {
printf("NIL ");
}
}
/*
Print symbol, this prints the name
*/
void PRINT_SYMBOL(VALUE_PTR symbol) {
PRINT_SYMBOL_NAME(symbol);
}
|
C
|
#include "hash_tables.h"
/**
* hash_table_set - adds and element to the hash table
*@ht: hash table
*@key: key of the table
*@value: value associated with the key
*
* Return: 1 on success, 0 on failue
*/
int hash_table_set(hash_table_t *ht, const char *key, const char *value)
{
unsigned long int size;
unsigned long int index;
hash_node_t *hashIndex, *node, *prev, *new;
if (key == NULL || value == NULL || ht == NULL)
return (0);
size = ht->size;
index = key_index((const unsigned char *)key, size);
hashIndex = ht->array[index];
node = hashIndex;
new = malloc(sizeof(hash_node_t));
if (node == NULL)
{
node = new;
ht->array[index] = node;
}
else
{
while (node != NULL)
{
prev = node;
if (strcmp(node->key, key) == 0)
break;
node = node->next;
}
node = new;
prev->next = node;
}
node->key = (char *)key;
node->value = (char *)value;
node->next = NULL;
return (1);
}
|
C
|
/** @brief Funciones Exclusivas para el juego.
*
* Aqui encontraras las funciones que son de utilidad para este juego y que dificilmente podran ser utilizadas
* en otros proyectos a menos que sean muy similares.
*
* @file zanahoria.h
* @version 0.1
* @date 22/04/2012
* @author JesusGoku
*
*/
#ifndef __ZANAHORIA_H__
#define __ZANAHORIA_H__
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <time.h>
#include <ctype.h>
#include <my_function.h>
#include <memoria.h>
#include <colores.h>
#include <lista.h>
/** @defgroup TableroConf Configuracion Tablero
*
* Configuracion del tamano maximo y minimo de tablero
* el tamano minimo es debido a la cantidad minima para que se desarrolle
* un juego, con al menos dos conejos
* El tamano maximo esta dado por el espacio que ocuparia el tablero en una
* consola a pantalla completa (resolucion 1280x800) para que el tablero
* pudiera caer entero y ser jugable sin hacer scroll
*
* @{
*/
#define TABLERO_MIN_SIZE 5
#define TABLERO_MAX_SIZE 25
/** @} */ // end of TableroConf
/** @defgroup ConejosInicialesConf Configuracion Conejos Iniciales
*
* Configuracion de la cantidad minima de conejos y la
* Tasa maxima de conejos en relacion al tamano del tablero
*
* @{
*/
#define CONEJOS_INICIALES_MIN 2
#define CONEJOS_INICIALES_MAX_TASA 0.1
/** @} */ // end of ConejosInicialesConf
/** @defgroup ElementosTablero Elementos de tablero.
*
* Constantes que representan a los elementos del tablero de juegos
*
* @{
*/
#define ZANAHORIA 'z'
#define CONEJO '&'
#define CADAVER '#'
#define TRAMPOLIN '<'
#define CONEJO_TRAMPOLIN '?'
#define CELDA_VACIA ' '
#define ZANAHORIA_MUERTA 'x'
/** @} */ // end of ElementosTablero
/** @defgroup MovimientosPermitidos Movimientos de juego.
*
* Comstamtes que representan a las teclas validas como
* comandos de juego.
*
* @{
*/
#define MOV_TOP_N '8'
#define MOV_TOP_C 'u'
#define MOV_TOPLEFT_N '7'
#define MOV_TOPLEFT_C 'y'
#define MOV_LEFT_N '4'
#define MOV_LEFT_C 'h'
#define MOV_BOTTOMLEFT_N '1'
#define MOV_BOTTOMLEFT_C 'n'
#define MOV_BOTTOM_N '2'
#define MOV_BOTTOM_C 'm'
#define MOV_BOTTOMRIGHT_N '3'
#define MOV_BOTTOMRIGHT_C ','
#define MOV_RIGHT_N '6'
#define MOV_RIGHT_C 'k'
#define MOV_TOPRIGHT_N '9'
#define MOV_TOPRIGHT_C 'i'
#define MOV_CENTER_N '5'
#define MOV_CENTER_C 'j'
#define MOV_TRANSPORT_C 't'
#define ACTION_QUIT_C 'q'
#define ACTION_SAVE_C 's'
/** @} */ // end of MovimientosPermitidos
/** @defgroup MovimientosCodigos Codigo de Movimiento
*
* Codigos internos de las diferentes acciones dentro del juego
*
* @{
*/
#define MOVE_TOP 8
#define MOVE_TOPLEFT 7
#define MOVE_LEFT 4
#define MOVE_BOTTOMLEFT 1
#define MOVE_BOTTOM 2
#define MOVE_BOTTOMRIGHT 3
#define MOVE_RIGHT 6
#define MOVE_TOPRIGHT 9
#define MOVE_CENTER 5
#define MOVE_TRANSPORT 10
#define ACTION_QUIT 11
#define ACTION_SAVE 12
/** @} */ // end of MovimientosCodigos
/** @defgroup MontoPuntajes Constantes con el aumento de puntaje
*
* Constantes con la cantidad de puntaje que se otorga por cada accion
*
* @{
*/
#define PUNTAJE_MOV 5
#define PUNTAJE_CHOQUE 50
#define PUNTAJE_NIVEL 100
/** @} */ // end of MontoPuntajes
/** @defgroup TasasIncremento Tasas de aumentos para las etaoas
*
* Tasas de incremento para los conejos y los trampolines a medida
* que avanza el juego
*
* @{
*/
#define TASA_AUMENTO_CONEJOS 0.25
#define TASA_AUMENTO_TRAMPOLINES 0.2
/** @} */ // end of TasasIncremento
/** @defgroup TrampolinesConfig Configuracion para los tampolines
*
* Configuracion de nivel en donde inician los trampolines y
* la cantidad de trampolines iniciales
*
* @{
*/
#define NIVEL_TRAMPOLINES_START 2
#define TRAMPOLINES_INICIALES 2
/** @} */ // end of TrampolinesConfig
/** @brief Archivo para guardar y recuperar la partida */
#define FILE_PARTIDA "partida.dat"
/** @defgroup RankingConf Configuracion del Ranking
*
* Configuracion del tamano maximo del nombre
* Cantidad de entradas en el ranking
* y archivo en donde se guardara el ranking
*
* @{
*/
#define MAX_SIZE_NAME 20
#define RANKING_NUM 10
#define FILE_RANKING "ranking.dat"
/** @} */ // end of RankingConf
/* @defgoup ConfigListaPartidas Configuracion lista de partidas
*
* @{
*/
#define FOLDER_PARTIDAS "partidas/" /*!< Carpeta donde se guardas las partidas */
#define FILE_PARTIDA_PREFIX "partida-" /*!< Prefijo para las partidas guardas */
#define FILE_PARTIDA_EXT ".dat" /*!< Extension de los archivos de partida */
/** @} */ // end of ConfigListaPartidas
/** @brief Estructura de Datos para los datos del Ranking
*/
typedef struct itemRanking {
char nombre[MAX_SIZE_NAME + 1];
int puntaje;
} ItemRanking;
/** @brief Solicita la cantidad de conejos iniciales al usuario.
*
* Se deben enviar las dimensiones del tablero para calcular una numero max
* para la cantidad de conejos ingresadas por el usuario, cosa de que el juego tenga sentido.
* Se ha establecido arbitrariamente al 10% del tamaño total de casillas disponibles en el tablero
* esto pensando en que a medida de que avanze el juego la cantidad de conejos ira aumentando.
*
* Tambien se fija la cantidad minina de conejos en 2 ya que de lo contrario
* seria imposible que hibiera un choque entre ellos.
*
* @param f puntero a entero con el numero de filas del tablero de juego
* @param c puntero a entero con el numero de columnas del tablero de juego
* @param ci puntero a entero donde se almacenara el numero de conejos iniciales ingresado.
*
*/
void pedirConejosIniciales(int *f, int *c, int *ci);
/** @brief Solicita al usuario las dimensiones del tablero.
*
* Se ha establecido arbitrariamente que las dimensiones del tablero deben de ser impar
* con el objeto de que haya un solo centro en lugar de cuatro cuando las dimensiones del
* tablero es par.
*
* Tambien se ha establecido como tamaño minimo de tablero el numero 5 ya que es el minimo aceptable
* para que caiga la zanahoria en el centro y un 10% de conejos y se pueda desarrollar un juego.
*
* Como comentario adicional se establecen la cantidad de filas y columnas por separado, aun cuando
* para este juego la dimension del tablero es cuadrada, pero he decidido dejarla asi para que pueda ser modificado
* facilmente en caso de que se desee que no sea asi.
*
* @param f puntero a entero donde se almacenara el numero de filas
* @param c puntero a entero donde se almacenara el numero de columnas
*/
void pedirDimensionTablero(int *f, int *c);
/** @brief Inicializa el tablero al equivalente a CELDA_VACIA.
*
* llena todo las casillas del tablero con el caracter representado por la constante
* CELDA_VACIA
*
* @param tablero puntero a la matriz que representa al tablero
* @param f entero con la cantidad de filas del tablero
* @param c entero con la cantidad de columnas del tablero
*
*/
void tablero_ini(char **tablero, int f, int c);
/** @brief Muestra el tablero en pantalla.
*
* @param tablero puntero a la matriz que representa al tablero
* @param f entero con la cantidad de filas del tablero
* @param c entero con la cantidad de columnas del tablero
*
*/
void tablero_view(char **tablero, int f, int c);
/** @brief Muestra el tablero en pantalla de forma espectacular.
*
* Esta es una version mejorar la version anterior que muestra el tablero de una forma
* mas organizada a la vista al simular verdaderamente un tablero y sus casillas
* por donde se desplazan la zanahoria y los conejos que quieren devorarla.
* Tiene la desventaja de ocupar mas espacio para su representacion, lo que limita el
* tamano de los tableros posibles.
*
* @param tablero puntero a la matriz que representa al tablero
* @param filas entero con la cantidad de filas del tablero
* @param columnas entero con la cantidad de columnas del tablero
*
*/
void tablero_pretty_view(char **tablero, const int filas, const int columnas);
/** @brief Ubica a la zanahoria en el centro del escenario.
*
* @param tablero puntero a la matriz que representa al tablero
* @param f entero con la cantidad de filas del tablero
* @param c entero con la cantidad de columnas del tablero
*/
void ubicarZanahoriaInicial(char **tablero, const int f, const int c);
/** @brief Ubica una cierta cantidad de conejos aleatoriamente por el tablero.
*
*
* @param tablero puntero a la matriz que representa al tablero
* @param m entero con la cantidad de filas del tablero
* @param n entero con la cantidad de columnas del tablero
* @param conejos entero con la cantidad de conejos a ubicar aleatoriamente
*
*/
void ubicarConejosIniciales(char **tablero, const int m, const int n, const int conejos);
/** @brief Ubicar los tamprolines aleatoriamente por el tablero.
*
* @param tablero puntero a la matriz que representa al tablero
* @param m entero con la cantidad de filas del tablero
* @param n entero con la cantidad de columnas del tablero
* @param trampolines entero con la cantidad de tableros a ubicar aleatoriamente
*/
void ubicarTrampolines(char **tablero, const int m, const int n, const int trampolines);
/** @brief Devuelve las coordenas de la zanahoria en el tablero.
*
* @param tablero puntero a la matriz que representa al tablero
* @param filas entero con la cantidad de filas del tablero
* @param columnas entero con la cantidad de columnas del tablero
* @param coordZF puntero a entero donde se almacenara la coordena fila de la zanahoria
* @param coordZC puntero a entero donde se almacenara la coordena columna de la zanahoria
*/
void posicionZanahoria(char **tablero, const int filas, const int columnas, int *coordZF, int *coordZC);
/** @brief Pide el siguiemte movimiento a ejecutar al usuario.
*
* Se encarga de validar que al menos sea un comando de juego valido o lo vuelve a pedir
*
* @return devuelve un entero que representa el movimiento ingresado por el usuario
*/
int pedirSiguienteMovimiento();
/** @brief Ejecuta el movimiento de la zanahoria hasta mov.
*
* El movimiento se ejecuta siempre de que sea un movimiento valido
* es decir que no se salga del tablero o que no haya otro objeto
* en la casilla a la que se desea mover.
*
* Ademas se debe validar que para que el movimiento sea valido, no exista el riesgo
* de que en la casilla a donde se va a mover vaya a ser comido. Por eso se utilizan dos
* funciones auxiliares para verificar las dos vecindades de si hay algun potencial conejo
* que pueda hacer invalida la jugada. Por ese motivo se pasa el nivel que a primeras podria
* parecer inecesario pero a como los trampolines solo comienzan a aparecer desde el 2do
* nivel y estos son lo que permiten a los conejos saltar de a dos espacios, no tiene sentido
* gastar tiempo llamando a la funcion que se encarga de revisar la segunda vecindad si no
* hay riesgo aun.
*
* Para realizar el ahorro comentado en el parrafo anterior se aprovecha la evaluacion de
* expresiones logicas de C por cortocircuito evaluando si el nivel es menos que el nivel
* en que comienzan a aparecer los trampolines O verificar la vecindad, y ya que hasta que
* se alcanze el nivel la primera expresion siempre dara verdadero, se ya sabe que la expresion
* es verdadera y no ejecutara la funcion para revisar la vecindad. No asi cuando se alcanza el
* nivel para los trampolines donde la primera expresion dara falso y C se vera obligado a
* evaluar la seguna expresion, osea la funcion que verifica el segundo cuandrante para
* conocer el valor de verdad de la expresion, dependiendo ahora exclusivamente de ella el
* valor de la expresion.
*
* @param mov entero que representa al movimiento que solicito el usuario
* @param tablero puntero a la matriz que representa al tablero
* @param filas entero con la cantidad de filas del tablero
* @param columnas entero con la cantidad de columnas del tablero
* @param nivel entero con el nivel en el que se encuentra el juego
*
* @return Devuelve 0 si el movimiento no es valido, y 1 si lo es y la mueve hasta la posicion
*/
int ejecutarMovimientoZanahoria(const int mov, char **tablero, const int filas, const int columnas, const int nivel);
/** @brief Ejecuta el movimiento de todos los conejos persiguiendo al conejo.
*
* @param tablero puntero a la matriz que representa al tablero
* @param tableroCopy puntero a la matriz que representa a una copia del tablero para poder realizar los movimientos
* @param filas entero con la cantidad de filas del tablero
* @param columnas entero con la cantidad de columnas del tablero
* @param conejosVivos puntero a entero donde se almacena la cantidad de conejos vivos que se disminuira en caso de colision de conejos
* @param puntaje puntero a entero donde se lleva el puntaje que ira aumentando en caso de colision de acuerdo a los establecido en la constante PUNTAJE_CHOQUE
*
* @return Devuelve 0 en caso de que un conejo haya caido sobre la zanahoria, en caso contrario retorna 1
*/
int ejecutarMovimientoConejos(char **tablero, char **tableroCopy, const int filas, const int columnas, int *conejosVivos, int *puntaje);
/**
* @brief Posicion al conejo en una posicion alatoria del trablero.
*
* @param tablero puntero a la matriz que representa al tablero
* @param filas entero con la cantidad de filas del tablero
* @param columnas entero con la cantidad de columnas del tablero
*
*/
void ejecutarTeletransportacion(char **tablero, const int filas, const int columnas);
/**
* @brief Verifica la vencindad de la zanahoria para verificar si hay peligro al ubicarse hay.
*
* @param tablero puntero a la matriz que representa al tablero
* @param m entero con la cantidad de filas del tablero
* @param n entero con la cantidad de columnas del tablero
* @param f entero que indica la fila a donde estara ubicada la zanahoria
* @param c entero que indica la columna a donde estara ubicada la zanahoria
* @param salto entero, si valor es 1 verifica la primera vecindad, si valor es 2 verifica la segunda vecindad
*
*/
int verificarVecindadZanahoria(char **tablero, const int m, const int n, const int f, const int c, const int salto);
/**
* @brief Verifica la primera vecindad en busca de peligros.
*
* @param tablero puntero a la matriz que representa al tablero
* @param m entero con la cantidad de filas del tablero
* @param n entero con la cantidad de columnas del tablero
* @param f entero que indica la fila a donde estara ubicada la zanahoria
* @param c entero que indica la columna a donde estara ubicada la zanahoria
*
*/
int verificarPrimeraVecindadZanahoria(char **tablero, const int m, const int n, const int f, const int c);
/**
* @brief Verifica la segunda vencindad en caso de peligros.
*
* @param tablero puntero a la matriz que representa al tablero
* @param m entero con la cantidad de filas del tablero
* @param n entero con la cantidad de columnas del tablero
* @param f entero que indica la fila a donde estara ubicada la zanahoria
* @param c entero que indica la columna a donde estara ubicada la zanahoria
* @param salto entero, si valor es 1 verifica la primera vecindad, si valor es 2 verifica la segunda vecindad
*
*/
int verificarSegundaVecindadZanahoria(char **tablero, const int m, const int n, const int f, const int c);
/**
* @brief Carga una partida desde un fichero.
*
* @param ficheroName puntero a cadena con el nombre del archivo que contiene la partida
* @param filas puntero a entero donde se almacena la cantidad de filas del tablero guardado
* @param columnas puntero a entero donde se almacena la cantidad de columnas del tablero guardado
* @param conejosIniciales puntero a entero donde se almacenara la cantidad de conejos iniciales
* @param conejosVivos puntero a entero donde se alamacenara la cantidad de conejos vivos en la partida guardada
* @param nivel puntero a entero donde se almacenara el nivel de la partida guardada
* @param puntaje puntero a entero donde se almacenara el puntaje en la partida guardada
* @param trampolnes puntero a flotante donde se almacenara la cantidad de trampolines guardadas
*
* @return devulve un puntero al tablero con los datos de la partida guardada
*
*/
char **cargarPartida(char *ficheroName, int *filas, int *columnas, int *conejosIniciales, int *conejosVivos, int *nivel, int *puntaje, float *trampolines);
/**
* @brief Guarda una partida en un fichero.
*
* @param ficheroName puntero a cadena con el nombre del fichero donde se guardara la partida
* @param tablero puntero a el tablero que se desea guardar
* @param filas entero con la cantidad de filas del tablero
* @param columnas entero con la cantidad de columnas del tablero
* @param partina_nombre puntero a cadena con el nombre asignado a la partida
* @param conejosIniciales entero con la cantidad inicial de conejos ingresada por el usuario
* @param conejosVivos entero con la cantidad de conejos vivos al momento de llamar la funcion
* @param nivel entero con el nivel al momento de llamar a la funcion
* @param puntaje entero con el puntaje al momento de llamar a la funcion
* @param trampolines flotante con la cantidad de trampolines en el nivel
*/
int guardarPartida(char *ficheroName, char **tablero, const int filas, const int columnas, char *partida_nombre, const int conejosIniciales, const int conejosVivos, const int nivel, const int puntaje, const float trampolines);
/** @brief Genera una lista con las partidas disponibles en el directorio de partidas.
*
* Va intentando abrir archivos consecutivos que sean posibles partidas guardadas,
* cuando el primero de ellos no se puede abrir significa que no hay mas.
*
* @return devulve un puntero a la lista de partidas
*/
TipoNodoNombre * generar_lista_partidas();
/**
* @brief Muesta el ranking.
*
* @param ranking puntero al arreglo de estructuras que contiene el ranking
* @param n cantidad de entradas que tiene el ranking
*
*/
void mostrarRanking(ItemRanking *ranking, const int n);
/**
* @brief Muestra el ranking destacando una poscion.
*
* @param ranking puntero a estructura que contiene el ranking
* @param n entero correspondiente al tamano del ranking
* @param pos entero con la posicion que se desea destacar
*
*/
void mostrarRankingDestacado(ItemRanking *ranking, const int n, const int pos);
/**
* @brief Ingresa un elemento al ranking.
*
* @param ranking puntero a un arreglo de estructura itemRanking que contiene el ranking
* @param n entero correspondiente al tamano del ranking
* @param elemento puntero a estructura con los datos que quieres ingresar al ranking
*
* @return devuelve 0 si no puede ingresar al ranking o el numero de la posicion en que quedo en el ranking
*/
int ingresarRanking(ItemRanking *ranking, const int n, ItemRanking *elemento);
/**
* @brief Guarda el ranking a un archivo.
*
* El ranking se guarda un archivo binario ya que hace mucho mas sencillo el recuperar la informacion posteriormente.
*
* @param ranking puntero a un arreglo de estructura itemRanking que contiene el ranking
* @param n entero correspondiente al tamano del ranking
*
* @return 1 si se logro abrir y guardar el ranking, 0 de lo contrario
*/
int guardarRanking(ItemRanking *ranking, const int n);
/**
* @brief Carga el ranking desde un archivo
*
* @param ranking puntero a un arreglo de estructura itemRanking que contendra el ranking
* @param n entero correspondiente al tamano del ranking que se espera en el archivo
*
* @return devuelve 1 si logro abrir el archivo y recuperar el rankin, 0 de lo contrario
*/
int cargarRanking(ItemRanking *ranking, const int n);
/**
* @brief Inicializa las variables del ranking con valores iniciales
*
* @param ranking puntero a un arreglo de estructura itemRanking que apunta a el ranking
* @param n entero correspondiente al tamano del ranking
*/
void inicializarRanking(ItemRanking *ranking, const int n);
/**
* @brief Muestra las instrucciones del juego.
*/
void mostrarAyuda();
#endif // __ZANAHORIA_H__
|
C
|
/**
* @By Jesper And Thorbjrn
*
*/
#include <stdio.h>
#include "GPIO.h"
#include <errno.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <signal.h>
#ifndef WIN32
#include <unistd.h>
#endif
#include <jack/jack.h>
jack_port_t **input_ports;
jack_port_t **output_ports;
jack_client_t *client;
static int gpioPinNumbers[8] = {17, 27, 22, 24, 5, 12, 13, 26};
float calculateRMS(jack_nframes_t nframes, jack_default_audio_sample_t *in);
static void signal_handler ( int sig )
{
jack_client_close ( client );
fprintf ( stderr, "signal received, exiting ...\n" );
exit ( 0 );
}
/**
* The process callback for this JACK application is called in a
* special realtime thread once for each audio cycle.
*
* This is the workhose, calculating the compression and saving the value
* on the output. It takes frames which contains the left and right sounds
* of the song, and gets read once for each to get stereo output.
*/
int
process ( jack_nframes_t nframes, void *arg ) //could possibly take a left/right parameter in to apply the process to independent stereo?
{
int defaultSize = sizeof ( jack_default_audio_sample_t );
int i;
/* Set the desired values for the parameters */
int x, offset = 16; //dB
float kneeWidth = 2.4, ratio = 5, attackTime = 0.05, releaseTime = 0.2;
float threshold = 0;
/* Save the value of the Dipswitch to the integer v and use that to set the threshold*/
int v = -(getDipValue(gpioPinNumbers));
threshold = v;//
/* Set the in and out buffers with values */
jack_default_audio_sample_t *in, *out;
jack_default_audio_sample_t buffer;
uint32_t sampleRate = jack_get_sample_rate(client);
/* Start the forloop for stereo */
for ( i = 0; i < 2; i++ )
{
in = jack_port_get_buffer ( input_ports[i], nframes );
out = jack_port_get_buffer ( output_ports[i], nframes );
/* Calculate the coefficients */
float attackTimeCoefficient = exp ((-log(9)/(sampleRate*attackTime)));
float releaseTimeCoefficient = exp ((-log(9)/(sampleRate*releaseTime)));
float computedGain = 0;
static float smoothedGain = 0.0;
float rms = calculateRMS(nframes, in)*sqrt(2);
float xdb = 0, xsc = 0,madeUpGain, makeUpGain = 0;
/* Decibel Domain */
xdb = 20*log10(rms);
/* Calculate the knee with set thresholds and width */
if ((threshold-(kneeWidth/2)) <=xdb && xdb<= (threshold+(kneeWidth/2))){
xsc = xdb + (((1/ratio) -1)*(pow(xdb - threshold+(kneeWidth/2), 2)))/(2*kneeWidth);
}
else if ( xdb> (threshold+(kneeWidth/2))) {
xsc = threshold + ((xdb - threshold)/ratio);
}
else {
xsc = xdb;
}
computedGain = xsc - xdb;
for(x = 0; x <= nframes-1; x++){
if (computedGain > smoothedGain /*previousValue of S.G.*/){
smoothedGain = smoothedGain*attackTimeCoefficient + (1-attackTimeCoefficient)*computedGain;
}
else if(computedGain<= smoothedGain){
smoothedGain = smoothedGain*releaseTimeCoefficient + (1-releaseTimeCoefficient)*computedGain;
}
makeUpGain = (threshold + offset +((threshold + offset)/ratio))/3; // divide by six (cuz reasons)
madeUpGain = -makeUpGain + smoothedGain;
buffer = pow(10, madeUpGain/20);
/* Set output */
out[x] = in[x] * buffer;
}
/* Debug values that gets printed in the end, can be removed */
float output = out[0];
float outputDB = 20*log10(sqrt(output*output));
static float input = 0;
if(in[0] > input){
input = in[0];
}
float inputDB = 20*log10(sqrt(input*input));
printf("Input: %+f, output: %f, SG: %+f, Thresh: %f, MakeUpGain: %f\n", inputDB, outputDB, smoothedGain, threshold, makeUpGain);
/* End of debug Values */
}
return 0;
}
float calculateRMS(jack_nframes_t nframes, jack_default_audio_sample_t *in){ //
int i;
float raw = 0;
for( i = 0 ; i < nframes ; i++ ){
raw += in[i] * in[i] ;
}
float rms = raw / ((float) nframes);
rms = sqrt(rms) ;
return rms;
}
int // a callback method that prints new sample rate at sample rate change
srate (jack_nframes_t nframes, void *arg)
{
printf ("the sample rate is now %lu/sec\n", nframes);
return 0;
}
/**
* JACK calls this shutdown_callback if the server ever shuts down or
* decides to disconnect the client.
*/
void
jack_shutdown ( void *arg )
{
jack_free ( input_ports );
jack_free ( output_ports );
exit ( 1 );
}
int
main ( int argc, char *argv[] )
{
/*Setup the IO pins for Dipswitch (for threshold controll) */
setup_io();
int i;
const char **ports;
const char *client_name;
const char *server_name = NULL;
jack_options_t options = JackNullOption;
jack_status_t status;
if ( argc >= 2 )
{
client_name = argv[1];
if ( argc >= 3 )
{
server_name = argv[2];
options |= JackServerName;
}
}
else
{
client_name = strrchr ( argv[0], '/' );
if ( client_name == 0 )
{
client_name = argv[0];
}
else
{
client_name++;
}
}
/* open a client connection to the JACK server */
client = jack_client_open ( client_name, options, &status, server_name );
if ( client == NULL )
{
fprintf ( stderr, "jack_client_open() failed, "
"status = 0x%2.0x\n", status );
if ( status & JackServerFailed )
{
fprintf ( stderr, "Unable to connect to JACK server\n" );
}
exit ( 1 );
}
if ( status & JackServerStarted )
{
fprintf ( stderr, "JACK server started\n" );
}
if ( status & JackNameNotUnique )
{
client_name = jack_get_client_name ( client );
fprintf ( stderr, "unique name `%s' assigned\n", client_name );
}
/* tell the JACK server to call `process()' whenever
there is work to be done.
*/
processing_data_t processData = {};
jack_set_process_callback ( client, process, &processData );
jack_set_sample_rate_callback (client, srate, 0);
/* tell the JACK server to call `jack_shutdown()' if
it ever shuts down, either entirely, or if it
just decides to stop calling us.
*/
jack_on_shutdown ( client, jack_shutdown, 0 );
/* create two ports pairs*/
input_ports = ( jack_port_t** ) calloc ( 2, sizeof ( jack_port_t* ) );
output_ports = ( jack_port_t** ) calloc ( 2, sizeof ( jack_port_t* ) );
char port_name[16];
for ( i = 0; i < 2; i++ )
{
sprintf ( port_name, "input_%d", i + 1 );
input_ports[i] = jack_port_register ( client, port_name, JACK_DEFAULT_AUDIO_TYPE, JackPortIsInput, 0 );
sprintf ( port_name, "output_%d", i + 1 );
output_ports[i] = jack_port_register ( client, port_name, JACK_DEFAULT_AUDIO_TYPE, JackPortIsOutput, 0 );
if ( ( input_ports[i] == NULL ) || ( output_ports[i] == NULL ) )
{
fprintf ( stderr, "no more JACK ports available\n" );
exit ( 1 );
}
}
/* Tell the JACK server that we are ready to roll. Our
* process() callback will start running now. */
if ( jack_activate ( client ) )
{
fprintf ( stderr, "cannot activate client" );
exit ( 1 );
}
/* Connect the ports. You can't do this before the client is
* activated, because we can't make connections to
* that aren't running. Note the confusing (but necessary)
* orientation of the driver backend ports: playback ports are
* "input" to the backend, and capture ports are "output" from
* it.
*/
ports = jack_get_ports ( client, NULL, NULL, JackPortIsPhysical|JackPortIsInput );
if ( ports == NULL )
{
fprintf ( stderr, "no physical playback ports\n" );
exit ( 1 );
}
for ( i = 0; i < 2; i++ )
if ( jack_connect ( client, jack_port_name ( output_ports[i] ), ports[i] ) )
fprintf ( stderr, "cannot connect input ports\n" );
jack_free ( ports );
ports = jack_get_ports ( client, NULL, NULL, JackPortIsPhysical | JackPortIsOutput );
if ( ports == NULL )
{
fprintf ( stderr, "no physical capture ports\n" );
exit ( 1 );
}
for ( i = 0; i < 2; i++ )
if ( jack_connect ( client, ports[i], jack_port_name ( input_ports[i] ) ) )
fprintf ( stderr, "cannot connect input ports\n" );
jack_free ( ports );
/* install a signal handler to properly quits jack client */
#ifdef WIN32
signal ( SIGINT, signal_handler );
signal ( SIGABRT, signal_handler );
signal ( SIGTERM, signal_handler );
#else
signal ( SIGQUIT, signal_handler );
signal ( SIGTERM, signal_handler );
signal ( SIGHUP, signal_handler );
signal ( SIGINT, signal_handler );
#endif
/* keep running until the transport stops */
while (1)
{
#ifdef WIN32
Sleep ( 1000 );
#else
sleep ( 1 );
#endif
}
jack_client_close ( client );
exit ( 0 );
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
int i,n,c;
char word[101] = {'\0'};
scanf("%d\n", &n);
for(c=i=0; i<n; ++i){
scanf("%s", word);
if(i==n-1){
int l=strlen(word);
word[l-1] = '\0';
}
if(strcmp(word, "TAKAHASHIKUN") == 0 ||
strcmp(word, "Takahashikun") == 0 ||
strcmp(word, "takahashikun") == 0){
++c;
}
}
printf("%d\n", c);
return 0;
}
|
C
|
#include <stdio.h>
char nombres[3][20] = {"fulano","mengano","perano"};
int main(void){
char *a;
char (*b)[20];
char *c;
char (*d)[3][20];
a = &nombres[0][0];
printf("El nombre es %s",a);
b = nombres;
c = &nombres[0][0];
d = &nombres;
for(int i=0; i < 3;i++){
printf("char (*)[] el nombre [%d] es %s \n",i,(char *)(b+i));
printf("char*: el nombre [%d] es %s \n",i,(char *)(c + (i*2)));
printf("char (*)[][]: el nombre [%d] es %s\n",i,(char *)(d+i));
}
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main(void)
{
int i;
char *cmd[] = {"/bin/echo", "Hello", 0};
for (i = 0; i < 10; i++) {
printf("%d\n", getpid() );
execve("echo", cmd, NULL);
sleep(1); // 1sec
}
return 0;
}
|
C
|
#include "socket.h"
#include <errno.h>
#include <netdb.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <signal.h>
// Siempre que halla if (0> algo) significa "Si hay error"
// Siempre que halla if (0< algo) significa "Si NO hay error"
//**********************************************************************************//
// SOCKETS //
//**********************************************************************************//
void socket_set_port_string(t_port port, char *portStr) {
sprintf(portStr, "%d", port);
}
int socket_listen(t_port port) {
signal(SIGPIPE, SIG_IGN);
struct addrinfo hints;
struct addrinfo *serverInfo;
memset(&hints, 0, sizeof(hints));
hints.ai_family = AF_UNSPEC; // No importa si uso IPv4 o IPv6
hints.ai_flags = AI_PASSIVE; // Asigna el address del localhost: 127.0.0.1
hints.ai_socktype = SOCK_STREAM; // Indica que usaremos el protocolo TCP
char portStr[10];
socket_set_port_string(port, portStr);
getaddrinfo(NULL, portStr, &hints, &serverInfo);
int fd = socket(serverInfo->ai_family, serverInfo->ai_socktype, serverInfo->ai_protocol);
if (0 > fd) {
freeaddrinfo(serverInfo);
return SOCKET_ERROR_SOCKET;
}
if (0 > bind(fd, serverInfo->ai_addr, serverInfo->ai_addrlen)) {
freeaddrinfo(serverInfo);
return SOCKET_ERROR_BIND;
}
int yes = 1;
if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(int)) == -1) {
return SOCKET_ERROR_SETSOCKETOPT;
}
freeaddrinfo(serverInfo);
if (0 > listen(fd, 5)) {
return SOCKET_ERROR_LISTEN;
}
return fd;
}
// Accept without getting the client's IP
int socket_accept(int fdListener) {
char *IP = NULL;
int fd = socket_accept_and_get_ip(fdListener, &IP);
if (IP) {
free(IP);
}
return fd;
}
// Accept getting the client's IP
int socket_accept_and_get_ip(int fdListener, char **ipAddress) {
struct sockaddr_in addr;
socklen_t addrlen = sizeof(addr);
int fd = accept(fdListener, (struct sockaddr *) &addr, &addrlen);
if (0 > fd) {
return SOCKET_ERROR_ACCEPT;
}
// set the ip.
*ipAddress = malloc(INET_ADDRSTRLEN);
inet_ntop(AF_INET, &addr.sin_addr.s_addr, *ipAddress, INET_ADDRSTRLEN);
return fd;
}
int socket_connect(const char* ip, t_port port) {
signal(SIGPIPE, SIG_IGN);
struct addrinfo hints;
struct addrinfo *serverInfo;
memset(&hints, 0, sizeof(hints));
hints.ai_family = AF_UNSPEC; // Permite que la maquina se encargue de verificar si usamos IPv4 o IPv6
hints.ai_socktype = SOCK_STREAM; // Indica que usaremos el protocolo TCP
char portStr[10];
socket_set_port_string(port, portStr);
getaddrinfo(ip, portStr, &hints, &serverInfo);
if (!serverInfo) {
return SOCKET_ERROR_ADDRESS;
}
int fd = socket(serverInfo->ai_family, serverInfo->ai_socktype, serverInfo->ai_protocol);
if (0 > fd) {
freeaddrinfo(serverInfo);
return SOCKET_ERROR_SOCKET;
}
if (0 > connect(fd, serverInfo->ai_addr, serverInfo->ai_addrlen)) {
close(fd);
freeaddrinfo(serverInfo);
return SOCKET_ERROR_CONNECT;
}
freeaddrinfo(serverInfo);
return fd;
}
e_socket_status socket_close(int socket) {
//if (0 > close(socket)) {
if (0 > shutdown(socket, SHUT_RDWR)) {
return SOCKET_ERROR_CLOSE;
}
return SOCKET_ERROR_NONE;
}
//**********************************************************************************//
// INTEGER //
//**********************************************************************************//
//chequea el endianess
int isBigEndian() {
return !isLittleEndian();
}
int isLittleEndian() {
static const int THE_ANSWER = 42;
return (*((const char*) &THE_ANSWER) == THE_ANSWER);
}
//hton un poco mas generico, tenes que mandarle el sizeoff del tipo de dato que mandes
void* hton(void* value, size_t size) {
if (isLittleEndian()) {
void* l = value;
void* a = malloc(1);
void* r = value + size - 1;
for (; l < r; l++, r--) {
memcpy(a, l, 1);
memcpy(l, r, 1);
memcpy(r, a, 1);
}
free(a);
}
return value;
}
//send y recv especificos para integer (con el hton generico pasando el tamaño por param)
e_socket_status socket_send_integer(int socket, void* integer, size_t size) {
e_socket_status status = socket_send(socket, hton(integer, size), size);
hton(integer, size);
return status;
}
e_socket_status socket_recv_integer(int socket, void* integer, size_t size) {
e_socket_status status = socket_recv(socket, integer, size);
hton(integer, size);
return status;
}
//**********************************************************************************//
// STREAM //
//**********************************************************************************//
e_socket_status socket_send(int socket, void* stream, size_t size) {
if (!stream) {
return SOCKET_ERROR_SEND;
}
void* data = stream; //data es el puntero que voy a usar para ir avanzando en el stream y saber desde donde empezar
size_t tosend = size; //tosend es el tamaño total a mandar y count es lo que mando en ese send especifico
int count = 0;
while (tosend) {
int retry = 3;
while (0 >= (count = send(socket, data, tosend, 0)) && retry--) {
switch (errno) {
case ECONNREFUSED:
case EAGAIN:
case ETIMEDOUT:
usleep(1000000);
break;
case EPIPE:
default:
return SOCKET_ERROR_SEND;
}
}
if (!count || 0 > count) {
return SOCKET_ERROR_SEND;
}
tosend -= count;
data += count;
}
return SOCKET_ERROR_NONE;
}
//Similar a la anterior pero con recv (no sirve para multiplexado
e_socket_status socket_recv(int socket, void* stream, size_t size) {
if (!stream) {
return SOCKET_ERROR_RECV;
}
void *data = stream; // Saves a pointer to keep moving until all size is read.
size_t left = size; // Saves the left size to read.s
int count;
while (left) {
int retry = 3;
while (0 >= (count = recv(socket, data, left, 0)) && retry--) {
switch (errno) {
case ECONNREFUSED:
case EAGAIN:
case ETIMEDOUT:
usleep(1000000);
break;
case EPIPE:
default:
return SOCKET_ERROR_RECV;
}
}
if (!count || 0 > count) {
return SOCKET_ERROR_RECV;
}
left -= count;
data += count; // Moves pointer forward
}
return SOCKET_ERROR_NONE;
}
//**********************************************************************************//
// PACKET //
//**********************************************************************************//
//Los paquetes son cuando no se el tamaño total que voy a mandar (no es un tamaño fijo)
e_socket_status socket_send_packet(int socket, void* packet, size_t size) {
if (!packet)
return SOCKET_ERROR_SEND;
size_t ssize = sizeof(size_t); //El tamaño del tamaño de lo que va a mandar
size_t spacket = size; //El tamaño de lo que realmente va a mandar
hton(&size, ssize);
e_socket_status status = socket_send(socket, &size, ssize); // manda el header
if (0 > status)
return status;
status = socket_send(socket, packet, spacket); // manda el buffer
return status;
}
e_socket_status socket_recv_packet(int socket, void** packet, size_t* size) {
e_socket_status status = socket_recv_integer(socket, size, sizeof(size_t));
if (0 > status)
return status;
*packet = malloc(*size); //hace un malloc del tamaño que tiene que recibir (parametro)
status = socket_recv(socket, *packet, *size); //recibe ese tamaño en el buffer (packet) para desserializarlo en implementacion particular
if (0 > status)
free(*packet);
return status;
}
// Es igual a recv packet pero NO hace un malloc, esto sirve para tirar el resultado a una memoria que ya fue malloc'ed en otro lado (mmap por ej)
e_socket_status socket_recv_packet_to_memory(int socket, void** packet, size_t* size) {
e_socket_status status = socket_recv_integer(socket, size, sizeof(size_t));
if (0 > status)
return status;
status = socket_recv(socket, *packet, *size); //recibe ese tamaño en el buffer (packet) para desserializarlo en implementacion particular
return status;
}
//**********************************************************************************//
// STRING //
//**********************************************************************************//
//estas son implementaciones particulares de como mandar un paquete, si por ejemplo es un char* (string)
e_socket_status socket_send_string(int socket, char* string) {
if (!string)
return SOCKET_ERROR_SEND;
return socket_send_packet(socket, string, sizeof(char) * (strlen(string) + 1));
}
e_socket_status socket_recv_string(int socket, char** string) {
size_t size;
e_socket_status status = socket_recv_packet(socket, (void**) string, &size);
if (0 > status)
return status;
if (size != sizeof(char) * (1 + strlen(*string))) {
free(*string);
return SOCKET_ERROR_SEND;
}
return status;
}
//**********************************************************************************//
// HANDSHAKE //
//**********************************************************************************//
//Es un paso inicial antes de empezar la comunicacion para saber con quien estamos hablando
//Uso define para que se lea bien, y se entienda relativamente facil
#define HANDSHAKE_WELCOME 0x01
#define _HANDSHAKE_WELCOME "WELCOME"
#define _HANDSHAKE_MARTA "IMMARTA"
#define _HANDSHAKE_FILESYSTEM "IMFILESYSTEM"
#define _HANDSHAKE_NODO "IMNODO"
#define _HANDSHAKE_JOB "IMJOB"
//recibe un string y devuelve el hexa
static int _get_handshake_code(char* handshake) {
if (!strcmp(handshake, _HANDSHAKE_WELCOME))
return HANDSHAKE_WELCOME;
if (!strcmp(handshake, _HANDSHAKE_MARTA))
return HANDSHAKE_MARTA;
if (!strcmp(handshake, _HANDSHAKE_FILESYSTEM))
return HANDSHAKE_FILESYSTEM;
if (!strcmp(handshake, _HANDSHAKE_NODO))
return HANDSHAKE_NODO;
if (!strcmp(handshake, _HANDSHAKE_JOB))
return HANDSHAKE_JOB;
return 0x00;
}
//recibe el hexa y devuelve un string
static char* _get_handshake_msg(int handshake) {
switch (handshake) {
case HANDSHAKE_MARTA:
return _HANDSHAKE_MARTA;
case HANDSHAKE_FILESYSTEM:
return _HANDSHAKE_FILESYSTEM;
case HANDSHAKE_NODO:
return _HANDSHAKE_NODO;
case HANDSHAKE_JOB:
return _HANDSHAKE_JOB;
}
return NULL;
}
//Recibe un handshake y devuelve el hexa
static int _check_handshake(int socket, int handshake) { //int handshake son los permitidos (ver to client)
char* hi;
int recive = socket_recv_string(socket, &hi); //HACE EL RECV
if (0 > recive)
return recive;
int hscode = _get_handshake_code(hi); //consigue el hexa
free(hi);
return hscode & handshake ? hscode : SOCKET_ERROR_HANDSHAKE; //Devuelve el hexa si es de los permitidos a travez de una multiplicacion binaria (&)
}
//El cliente le envia el handshake al servidor, se usa despues del connect
int socket_handshake_to_server(int socket, int hiserver, int hiclient) {
int server = _check_handshake(socket, hiserver); //Primero recibe el handshake del servidor
if (0 > server)
return server;
if (0 > socket_send_string(socket, _get_handshake_msg(hiclient))) //Envia su handshake al servidor
return SOCKET_ERROR_SEND;
int wellcome = _check_handshake(socket, HANDSHAKE_WELCOME); //Espera a que el servidor le de el ok (WELLCOME)
if (wellcome == SOCKET_ERROR_HANDSHAKE)
wellcome = SOCKET_ERROR_WELCOME;
return 0 > wellcome ? wellcome : server; //devuelve wellcome (error, o 1 si esta ok)
}
//El servidor le envia el handshake al cliente, se usa despues del accept
//hiclient se debe expresar como una suma binaria (or | ) si es mas de uno asi se permite pasar a todos esos, una posible llamada seria
//switch(socket_handshake_to_client(fd, HANDSHAKE_MARTA, HNADSHAKE_JOB | HANDSHAKE_FILESYSTEM)) dependiendo del resultado
//se que accion tomar, porque me devuelve cual handshake recibi.
int socket_handshake_to_client(int socket, int hiserver, int hiclient) {
if (0 > socket_send_string(socket, _get_handshake_msg(hiserver))) //Primero envia el handshake al cliente
return SOCKET_ERROR_SEND;
int client = _check_handshake(socket, hiclient); //Se fija si el recibido esta en los permitidos (hiclient)
if (0 > client)
return client;
if (0 > socket_send_string(socket, _HANDSHAKE_WELCOME)) //Si esta permitido envia el wellcome
return SOCKET_ERROR_WELCOME;
return client;
}
|
C
|
#include "cfunc.h"
/*---------------------------------------------------------
// , .
---------------------------------------------------------*/
/*-----------------------------------------
-----------------------------------------*/
//
szMs cMasSizeF(char *szNameFl)
{
szMs szMass;
FILE *sf;
if( (sf = fopen(szNameFl, "r")) == NULL)
{
printf("ERROR!!! !\n");
system("pause");
exit(-1);
}
else
{
fscanf(sf,"%d%d", &szMass.height, &szMass.width);
fclose(sf);
return szMass;
}
}
//
void CFillingMassRand(void)
{
char NameFlSize[255];
cout << " : ";
cin >> NameFlSize;
szMs MassSize = cmasSizeF(NameFlSize);
char NameFl[255];
cout << " : ";
cin >> NameFl;
cout << " , : ";
int rMax = 0, rMin = 0;
cin >> rMax >> rMin;
ofstream FMass(NameFl);
if(!FMass.is_open())
{
cout << " !" << endl;
system("pause");
exit(-1);
}
for(int counter = 0; counter < MassSize.height; counter ++)
{
for(int cntr = 0; cntr < MassSize.width; cntr++)
{
FMass << (rMin) + rand() % ((rMax + 1) - rMin) << "\t";
}
FMass << endl;
}
cout << " ." << endl;
FMass.close();
}
|
C
|
uint32_t reverseBits(uint32_t n) {
uint32_t r = 0, x = 32;
while(x--){
r = (r << 1) | (n & 1);
n >>= 1;
}
return r;
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_split.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: mifernan <mifernan@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2019/10/26 18:11:40 by mifernan #+# #+# */
/* Updated: 2019/12/06 12:08:34 by mifernan ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
static int len_w(char const *s, char sep, int i)
{
int cpt;
cpt = 0;
while (s && s[i] != sep && s[i])
{
cpt++;
i++;
}
return (cpt);
}
static int ft_nb_words(char const *s, char sep)
{
int i;
int cpt;
i = 0;
cpt = 0;
while (s && s[i])
{
if ((i == 0 && s[i] != sep) ||
(i > 0 && s[i - 1] == sep && s[i] != sep))
{
while (s[i] != sep && s[i])
i++;
cpt++;
}
else
i++;
}
return (cpt);
}
char **ft_split(char const *s, char c)
{
size_t i;
int word;
int letter;
char **new;
i = 0;
word = 0;
if (!(new = (char**)malloc(sizeof(char*) * (ft_nb_words(s, c) + 1))))
return (NULL);
while (s && s[i] && ft_nb_words(s, c) > 0)
{
letter = 0;
while (s[i] == c && s[i])
i++;
if (!(new[word] = (char*)malloc(sizeof(char) * (len_w(s, c, i) + 1))))
return (NULL);
while (s[i] != c && s[i])
new[word][letter++] = s[i++];
new[word][letter] = '\0';
while (i < (size_t)ft_strlen(s) && s[i] == c)
i++;
word++;
}
new[word] = NULL;
return (new);
}
|
C
|
#include <stdio.h>
int main() {
int side1, side2, side3;
printf("A: ");
scanf("%d", &side1);
printf("B: ");
scanf("%d", &side2);
printf("C: ");
scanf("%d", &side3);
if((side1 + side2 > side3) && (side1 + side3 > side2) && (side2 + side3 > side1)) {
if(side1==side2 && side2==side3) {
printf("Equilateral triangle.");
}else if(side1==side2 || side1==side3 || side2==side3) {
printf("Isosceles triangle.");
}else {
printf("Scalene triangle.");
}
}else {
printf("Triangle type invalid.");
}
return 0;
}
|
C
|
#include <stdio.h>
// This function takes a string (recall a string is a character array)
void write_message(char name[]) {
printf("Hello, %s\n", name);
}
int main() {
write_message((char *) "Dave");
write_message((char *) "Victoria");
return 0;
}
|
C
|
// Filename: cpfile.c
// Compile command: gcc cpfile.c -o cpfile.exe
#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
#define SIZ 128
// Copy from source file to target file. Adapted from The C Programming
//Language
// by Kernighan and Ritchie.
int main(int argc, const char *argv[]) {
int f1, f2;
// Do we have right number of arguments?
if (argc != 3){
printf("Wrong number of command line arguments\n");
// exit(1);
return 1;
}
// Can we access thge source file?
if ((f1 = open(argv[1], O_RDONLY, 0)) == -1){
printf("Can't open %s \n", argv[1]);
return 2;
}
// Can we create the target file?
if ((f2 = creat(argv[2], 0644)) == -1){
printf("Can't create %s \n", argv[2]);
return 3;
}
// Copy source file contents to target file.
char buf[SIZ];
int n;
while ((n = read( f1, buf, SIZ)) > 0)
if (write(f2, buf, n) != n){
printf("Can't write file" );
close(f1);
close(f2);
return 4;
}
close(f1);
close(f2);
printf("Success!" );
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <termios.h>
#include <unistd.h>
#include <string.h>
#include "functions.c"
#include "keys.c"
#include "printing.c"
int main()
{
static struct termios oldt, newt;
tcgetattr(STDIN_FILENO,&oldt);
newt = oldt;
newt.c_lflag &= ~(ICANON|ECHO);
tcsetattr(STDIN_FILENO,TCSANOW,&newt);
pEnteredKeys = InitGlobalStruct(&pEnteredKeys);
if(NULL != pEnteredKeys)
{
PrintMessage();
if(EXIT_SUCCESSFULL == Begin(pEnteredKeys))
{
CLEAR();
printf("Exit successfull!");
tcsetattr(STDIN_FILENO,TCSANOW,&oldt);
}
}
else
{
printf("Something went wrong! Memory allocation error!");
}
tcsetattr(STDIN_FILENO,TCSANOW,&oldt);
return 0;
}
|
C
|
#pragma once
#include "stdlib.h"
#include "stdio.h"
#include "string.h"
struct list
{
void * data;
struct list * next;
};
void addEnd(struct list ** head, void * element, int size);
struct list *del(struct list ** head, int i);
void delList(struct list ** head);
struct list * showElem(struct list * head, int i);
void addAsc(struct list **head, void * element, int size, int Larger(void*,void*));
int compInt(void* a, void* b);
int search(struct list *head, void * element, int Comp(void*, void*));
struct list * get(struct list *head, int i);
|
C
|
#if !defined(MP6_H)
#define MP6_H
#include <stdint.h>
// Flood from (startX, startY) until meeting black (RGB=000000), filling
// with the specified RGB color.
extern void basicFlood
(int32_t width, int32_t height, const uint8_t* inRed,
const uint8_t* inGreen, const uint8_t* inBlue, int32_t startX,
int32_t startY, uint8_t floodR, uint8_t floodG, uint8_t floodB,
uint8_t* outRed, uint8_t* outGreen, uint8_t* outBlue);
// Returns 1 iff two colors are within Euclidean distance squared of
// one another in RGB space.
extern int32_t colorsWithinDistSq
(uint8_t r1, uint8_t g1, uint8_t b1,
uint8_t r2, uint8_t g2, uint8_t b2, uint32_t distSq);
// Flood from (startX, startY) until meeting a color within distSq
// (Euclidian distance squared in RGB space) of black (RGB=000000), filling
// with the specified RGB color.
extern void greyFlood
(int32_t width, int32_t height, const uint8_t* inRed,
const uint8_t* inGreen, const uint8_t* inBlue, int32_t startX,
int32_t startY, uint8_t floodR, uint8_t floodG, uint8_t floodB,
uint32_t distSq, uint8_t* outRed, uint8_t* outGreen, uint8_t* outBlue);
// Flood from (startX, startY) until meeting a color more than distSq
// (Euclidian distance squared in RGB space) away from the color at
// the starting point, also stopping at 40 pixels from the starting point.
// Fill with the specified RGB color.
extern void limitedFlood
(int32_t width, int32_t height, const uint8_t* inRed,
const uint8_t* inGreen, const uint8_t* inBlue, int32_t startX,
int32_t startY, uint8_t floodR, uint8_t floodG, uint8_t floodB,
uint32_t distSq, uint8_t* outRed, uint8_t* outGreen, uint8_t* outBlue);
// ------------------------------------------------------------------------
// The following routines are in mp6recurse.c, and are only called
// from the wrapper functions in mp6.c.
// called by basicFlood to perform marking of the flooded region
extern void basicRecurse
(int32_t width, int32_t height, const uint8_t* inRed,
const uint8_t* inGreen, const uint8_t* inBlue, int32_t x, int32_t y,
uint8_t* marking);
// called by greyFlood to perform marking of the flooded region
extern void greyRecurse
(int32_t width, int32_t height, const uint8_t* inRed,
const uint8_t* inGreen, const uint8_t* inBlue, int32_t x, int32_t y,
uint32_t distSq, uint8_t* marking);
// called by limitedFlood to perform marking of the flooded region
extern void limitedRecurse
(int32_t width, int32_t height, const uint8_t* inRed,
const uint8_t* inGreen, const uint8_t* inBlue, int32_t origX,
int32_t origY, int32_t x, int32_t y, uint32_t distSq, uint8_t* marking);
// ------------------------------------------------------------------------
#endif // MP6_H
|
C
|
#define MaxSize 100
#define ElementType int
#include<stdio.h>
ElementType S[MaxSize];
int top;
void main(){
top=0;
Push(S,top,9);
printf("%d",top);//˵Ӧtop ++ Dzû ˵ ڲΪرʵ
}
void Push(ElementType S[], int top, ElementType item)
{if (top==MaxSize-1) {
printf("manle"); return;
}else {
S[++top] = item;
return;
}
}
|
C
|
#include "length.h"
#include <stdlib.h>
#define INCH_PER_FOOT 12
#define FOOT_PER_YARD 3
#define INCH_PER_YARD (INCH_PER_FOOT * FOOT_PER_YARD)
typedef LengthPtr (*SingleAsFunc)(LengthPtr obj, UintType uint);
LengthPtr NewLength(double val, UintType uint) {
LengthPtr length = (LengthPtr) malloc(sizeof(Length));
length->val = val;
length->uint = uint;
return length;
}
LengthPtr InchAs(LengthPtr obj, UintType uint) {
double val = (uint == FOOT) ? (obj->val / INCH_PER_FOOT) : (obj->val / INCH_PER_YARD);
return NewLength(val, uint);
}
LengthPtr FootAs(LengthPtr obj, UintType uint) {
double val = (uint == INCH) ? (obj->val * INCH_PER_FOOT) : (obj->val / FOOT_PER_YARD);
return NewLength(val, uint);
}
LengthPtr YardAs(LengthPtr obj, UintType uint) {
double val = (uint == INCH) ? (obj->val * INCH_PER_YARD) : (obj->val * FOOT_PER_YARD);
return NewLength(val, uint);
}
SingleAsFunc g_procFuncList[] = {InchAs, FootAs, YardAs};
LengthPtr As(LengthPtr obj, UintType uint) {
if (obj->uint == uint) {
return obj;
}
return g_procFuncList[obj->uint](obj, uint);
}
|
C
|
/*------------------Project Includes-----------------*/
#include "led.h"
/*-------------------Driver Includes-----------------*/
#include "driverlib/sysctl.h"
#include "driverlib/gpio.h"
#include "driverlib/pin_map.h"
#include "driverlib/pwm.h"
/*-------------------HW define Includes--------------*/
#include "inc/hw_memmap.h"
/*-------------------Macro Definitions----------------*/
#define GPIO_PORTF_LOCK_R (*((volatile unsigned long *)0x40025520))
#define GPIO_PORTF_CR_R (*((volatile unsigned long *)0x40025524))
// Color LED(s) PortF
// dark --- 0
// red R-- 0x02 - 1
// blue --B 0x04 - 2
// green -G- 0x08
// yellow RG- 0x0A
// sky blue -GB 0x0C
// white RGB 0x0E
// pink R-B 0x06
#define PWM_disable (false) //Switch to disable PWM output
#define PWM_enable (true) //Switch to enable PWM output
/*-------------------Function Definitions-------------*/
void RGB_Led_Init(void)
{
SysCtlPeripheralEnable(SYSCTL_PERIPH_GPIOF); //Enable clock on port F
GPIO_PORTF_CR_R |= 0x1F; //Allow changes to PF4-0
GPIOPinTypeGPIOOutput(GPIO_PORTF_BASE, GPIO_PIN_1|GPIO_PIN_2|GPIO_PIN_3); //Set PF1,2,3 GPIO Output
GPIODirModeSet(GPIO_PORTF_BASE, GPIO_PIN_1|GPIO_PIN_2|GPIO_PIN_3, GPIO_DIR_MODE_OUT); //Set direction Output for PF1,2,3
GPIOPadConfigSet(GPIO_PORTF_BASE, GPIO_PIN_1|GPIO_PIN_2|GPIO_PIN_3, GPIO_STRENGTH_2MA,GPIO_PIN_TYPE_STD); //Configure PF1,2,3
GPIOPinWrite(GPIO_PORTF_BASE, GPIO_PIN_1|GPIO_PIN_2|GPIO_PIN_3, 0); //Set initially to 0
}
void Led_toggle(unsigned char color)
{
static unsigned char status = 1;
if(status) {
GPIOPinWrite(GPIO_PORTF_BASE, color, color); //switch on desired color
}
else {
GPIOPinWrite(GPIO_PORTF_BASE, color, 0); //switch off
}
status ^= 1; //toggle status
}
void RGB_PWM_Init(unsigned long PWM_Period)
{
//PF1 is Red
//PF2 is Blue
//PF3 is Green
SysCtlPWMClockSet(SYSCTL_PWMDIV_1); //Enable clock for PWM
SysCtlPeripheralEnable(SYSCTL_PERIPH_PWM1); //PWM enable
SysCtlPeripheralEnable(SYSCTL_PERIPH_GPIOF); //Port F enable
GPIOPinConfigure(GPIO_PF1_M1PWM5); //Configure PF1, Function LED toggle
GPIOPinConfigure(GPIO_PF2_M1PWM6); //Configure PF2, Function LED toggle
GPIOPinConfigure(GPIO_PF3_M1PWM7); //Configure PF3, Function LED toggle
GPIOPinTypePWM(GPIO_PORTF_BASE, GPIO_PIN_1); //Set PWM for PF1, Function LED toggle
GPIOPinTypePWM(GPIO_PORTF_BASE, GPIO_PIN_2); //Set PWM for PF2, Function LED toggle
GPIOPinTypePWM(GPIO_PORTF_BASE, GPIO_PIN_3); //Set PWM for PF3, Function LED toggle
PWMGenConfigure(PWM1_BASE, PWM_GEN_2, PWM_GEN_MODE_DOWN | PWM_GEN_MODE_NO_SYNC); //Configure Generator 2
PWMGenPeriodSet(PWM1_BASE, PWM_GEN_2, PWM_Period); //Configure Generator 2 period (frequency)
PWMGenConfigure(PWM1_BASE, PWM_GEN_3, PWM_GEN_MODE_DOWN | PWM_GEN_MODE_NO_SYNC); //Configure Generator 3
PWMGenPeriodSet(PWM1_BASE, PWM_GEN_3, PWM_Period); //Configure Generator 3 period (frequency)
PWMPulseWidthSet(PWM1_BASE, PWM_OUT_5, (50*(PWMGenPeriodGet(PWM1_BASE,PWM_GEN_2))/100));//Set initial duty cycle 10%
PWMGenEnable(PWM1_BASE, PWM_GEN_2); //Enable Generator 2
PWMPulseWidthSet(PWM1_BASE, PWM_OUT_6, (50*(PWMGenPeriodGet(PWM1_BASE,PWM_GEN_3))/100));//Set initial duty cycle 10%
PWMGenEnable(PWM1_BASE, PWM_GEN_3); //Enable Generator 3
PWMPulseWidthSet(PWM1_BASE, PWM_OUT_7, (99*(PWMGenPeriodGet(PWM1_BASE,PWM_GEN_3))/100));//Set initial duty cycle 10%
PWMGenEnable(PWM1_BASE, PWM_GEN_3); //Enable Generator 3
PWMOutputState(PWM1_BASE, PWM_OUT_5_BIT , PWM_enable);
PWMOutputState(PWM1_BASE, PWM_OUT_6_BIT , PWM_enable);
}
void RED_PWM_DutyCycle(unsigned long duty_cycle)
{
if(duty_cycle <= 0)
{
PWMOutputState(PWM1_BASE, PWM_OUT_5_BIT , PWM_disable); //If requested duty cycle is 0% stop PWM output
PWMGenDisable(PWM1_BASE, PWM_GEN_2); //Disable generator 2 temporarly
}
else
{
if(duty_cycle >= 99)
{
duty_cycle = 99; //Set duty cycle to 99% if request is greater than 99%
}
PWMPulseWidthSet(PWM1_BASE, PWM_OUT_5, (duty_cycle*(PWMGenPeriodGet(PWM1_BASE,PWM_GEN_2))/100)); //Set duty cycle
PWMGenEnable(PWM1_BASE, PWM_GEN_2); //Enable generator 2
PWMOutputState(PWM1_BASE, PWM_OUT_5_BIT , PWM_enable); //Enable PWM output on PF1 - Red LED
}
}
void GREEN_PWM_DutyCycle(unsigned long duty_cycle) //Not used in this project
{
if(duty_cycle == 0)
{
PWMOutputState(PWM1_BASE, PWM_OUT_7_BIT , PWM_disable); //If requested duty cycle is 0% stop PWM output
PWMGenDisable(PWM1_BASE, PWM_GEN_3); //Disable generator 3 temporarly
}
else
{
if(duty_cycle >99)
{
duty_cycle = 99; //Set duty cycle to 99% if request is greater than 99%
}
PWMPulseWidthSet(PWM1_BASE, PWM_OUT_7, (duty_cycle*(PWMGenPeriodGet(PWM1_BASE,PWM_GEN_3))/100)); //Set duty cycle
PWMGenEnable(PWM1_BASE, PWM_GEN_3); //Enable generator 3
PWMOutputState(PWM1_BASE, PWM_OUT_7_BIT , PWM_enable); //Enable PWM output on PF3 - Green LED
}
}
void BLUE_PWM_DutyCycle(unsigned long duty_cycle)
{
if(duty_cycle == 0)
{
PWMOutputState(PWM1_BASE, PWM_OUT_6_BIT , PWM_disable); //If requested duty cycle is 0% stop PWM output
PWMGenDisable(PWM1_BASE, PWM_GEN_3); //Disable generator 3 temporarly
}
else
{
if(duty_cycle >99)
{
duty_cycle = 99; //Set duty cycle to 99% if request is greater than 99%
}
PWMPulseWidthSet(PWM1_BASE, PWM_OUT_6, (duty_cycle*(PWMGenPeriodGet(PWM1_BASE,PWM_GEN_3))/100)); //Set duty cycle
PWMGenEnable(PWM1_BASE, PWM_GEN_3); //Enable generator 3
PWMOutputState(PWM1_BASE, PWM_OUT_6_BIT , PWM_enable); //Enable PWM output on PF2 - Blue LED
}
}
//EOF
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main() {
int i, j;
char carac;
srand(time(NULL));
do {
fflush(stdin);
printf("\n Nombre de caractere(s) : ");
}
while ((scanf("%d", &i) == 0) && i < 1);
printf("\n\n Votre code est : ");
for (j = 0; j < i; j++) {
switch (rand() % 4) {
case 0:
carac = ((rand() % 26) + 'A');
break;
case 1:
carac = ((rand() % 26) + 'a');
break;
case 2:
carac = ((rand() % 9) + '1');
break;
case 3:
carac = (rand() % 2) ? '!' : '?';
}
printf("%c", carac);
}
getch();
return 0;
}
|
C
|
/*
Cameron Elwood
Unversity of Victoria
CSC 360
V00152812
Assignment 2
*/
#define _POSIX_SOURCE
#define _BSD_SOURCE
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/time.h>
#include <signal.h>
#include <pthread.h>
#include <unistd.h>
#include <string.h>
#include <readline/readline.h>
#include <readline/history.h>
/*
stuct containing all info for customers
user_id: the id of the user
service_time: the time the user process will be sleeping for while being processed
arrival_time: the time the process attempts to enter the queue
which_queue: which queue the process is in
whereIn_queue: where the user is in the queue
server: which clerk handles this customer
*/
struct customer_info{
int user_id;
int service_time;
int arrival_time;
int which_queue;
int whereIn_queue;
int server;
};
/*
stuct containing the id of the clerk
*/
struct clerk_info{
int clerk_id;
};
//mutex for queue volumes
pthread_mutex_t queues_mutex = PTHREAD_MUTEX_INITIALIZER;
//mutex and convar for clerk1
pthread_mutex_t clerk1_mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t clerk1_convar = PTHREAD_COND_INITIALIZER;
//mutex and convar for clerk2
pthread_mutex_t clerk2_mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t clerk2_convar = PTHREAD_COND_INITIALIZER;
//mutexs and convars for each queue
pthread_mutex_t q1_mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t q2_mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t q3_mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t q4_mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t q1_convar = PTHREAD_COND_INITIALIZER;
pthread_cond_t q2_convar = PTHREAD_COND_INITIALIZER;
pthread_cond_t q3_convar = PTHREAD_COND_INITIALIZER;
pthread_cond_t q4_convar = PTHREAD_COND_INITIALIZER;
//mutexs and convars for handling race conditions with clerk broadcastings.
pthread_mutex_t q1_custConflict_mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t q2_custConflict_mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t q3_custConflict_mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t q4_custConflict_mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t q1_custConflict_convar = PTHREAD_COND_INITIALIZER;
pthread_cond_t q2_custConflict_convar = PTHREAD_COND_INITIALIZER;
pthread_cond_t q3_custConflict_convar = PTHREAD_COND_INITIALIZER;
pthread_cond_t q4_custConflict_convar = PTHREAD_COND_INITIALIZER;
//globals
static struct timeval init_time; //start time
int numCustomersGlob; //total number of customers
double overall_waiting_time; //overall waiting time
int queue_length[4]; //how many customers are in each queue
int queue_countDown[4]; //used while moving all customers in the queue (during broadcast)
//add 2 more variables, c1 and c2, which will be integers. these will store values from 0-3 representing which queue they are working in.
int c1 = -1; //clerk1
int c2 = -1; //clerk2
//clerk status
int c1_busy = 0;// 0 not busy, 1 busy, 2 requesting customer
int c2_busy = 0;
/*
conVarCommands
does a convar command on a specified queue
takes in 2 ints, whichCommand and currentQueue
whichCommand is which command to be used. 1 is wait, 2 is broadcast clerk->customer 3 is broadcast cust->clerk
currentQueue is the queue that the caller is in. 0-3
returns 0.
*/
int conVarCommands(int whichCommand, int currentQueue){
int test = 1;
if(whichCommand == 1){ //wait for a queue is 1
if(currentQueue == 0){
test = pthread_cond_wait(&q1_convar, &q1_mutex);
}else if(currentQueue == 1){
test = pthread_cond_wait(&q2_convar, &q2_mutex);
}else if(currentQueue == 2){
test = pthread_cond_wait(&q3_convar, &q3_mutex);
}else if(currentQueue == 3){
test = pthread_cond_wait(&q4_convar, &q4_mutex);
}
if(test != 0){
printf("error cond wait");
exit(0);
}
}else if(whichCommand == 2){ //convar broadcast to queues is 2 (for a specfic queued customers, from clerks)
if(currentQueue == 0){
test = pthread_cond_broadcast(&q1_convar);
}else if(currentQueue == 1){
test = pthread_cond_broadcast(&q2_convar);
}else if(currentQueue == 2){
test = pthread_cond_broadcast(&q3_convar);
}else if(currentQueue == 3){
test = pthread_cond_broadcast(&q4_convar);
}
if(test != 0){
printf("error broadcase");
exit(0);
}
}else if(whichCommand == 3){ //customer sends a signal to a potentially waiting clerk.
if(currentQueue == 0){
test = pthread_cond_broadcast(&q1_custConflict_convar);
}else if(currentQueue == 1){
test = pthread_cond_broadcast(&q2_custConflict_convar);
}else if(currentQueue == 2){
test = pthread_cond_broadcast(&q3_custConflict_convar);
}else if(currentQueue == 3){
test = pthread_cond_broadcast(&q4_custConflict_convar);
}
if(test != 0){
printf("error broadcast");
exit(0);
}
}
}
/*
lockUnlockMutex
locks or unlocks the mutex for a given queue
takes in 2 integers lockOrUnlock and currentQueue
lockOrUnlock tells us if its going to lock the mutex or unlock it. 1 is unlock 0 is lock
currentQueue is the queue the caller is interested in.
returns 0
*/
int lockUnlockMutex(int lockOrUnlock, int currentQueue){
int test = 1;
if(lockOrUnlock == 0){
if(currentQueue == 0){
test = pthread_mutex_lock(&q1_mutex);
}else if(currentQueue == 1){
test = pthread_mutex_lock(&q2_mutex);
}else if(currentQueue == 2){
test = pthread_mutex_lock(&q3_mutex);
}else if(currentQueue == 3){
test = pthread_mutex_lock(&q4_mutex);
}
if(test != 0){
printf("error locking mutex");
exit(0);
}
}else{
if(currentQueue == 0){
test = pthread_mutex_unlock(&q1_mutex);
}else if(currentQueue == 1){
test = pthread_mutex_unlock(&q2_mutex);
}else if(currentQueue == 2){
test = pthread_mutex_unlock(&q3_mutex);
}else if(currentQueue == 3){
test = pthread_mutex_unlock(&q4_mutex);
}
if(test != 0){
printf("error unlocking mutex");
exit(0);
}
}
return 0;
}
/*
lockUnlockMutexClerks
locks or unlocks the mutex for a given clerk (done during clerk conflicts)
takes in 2 integers lockOrUnlock and currentQueue
lockOrUnlock tells us if its going to lock the mutex or unlock it. 1 is unlock 0 is lock
currentQueue is the queue the caller is interested in.
returns 0
*/
int lockUnlockMutexClerks(int lockOrUnlock, int currentQueue){
int test = 1;
if(lockOrUnlock == 0){
if(currentQueue == 0){
test = pthread_mutex_lock(&q1_custConflict_mutex);
}else if(currentQueue == 1){
test = pthread_mutex_lock(&q2_custConflict_mutex);
}else if(currentQueue == 2){
test = pthread_mutex_lock(&q3_custConflict_mutex);
}else if(currentQueue == 3){
test = pthread_mutex_lock(&q4_custConflict_mutex);
}
if(test != 0){
printf("error locking mutex");
exit(0);
}
}else{
if(currentQueue == 0){
test = pthread_mutex_unlock(&q1_custConflict_mutex);
}else if(currentQueue == 1){
test = pthread_mutex_unlock(&q2_custConflict_mutex);
}else if(currentQueue == 2){
test = pthread_mutex_unlock(&q3_custConflict_mutex);
}else if(currentQueue == 3){
test = pthread_mutex_unlock(&q4_custConflict_mutex);
}
if(test != 0){
printf("error unlocking mutex");
exit(0);
}
}
return 0;
}
//0 is clerk, 1 is customer
/*
checkQueue
this decides which queue the caller will enter.
takes in an integer cuOrCl which says wether it is the clerk or the customer calling
if it is the clerk, it gets the largest queue
if it is the customer it is the smallest queue
if a clerk requests, and all queues are empty it returns negative 1, so that the clerk can sleep to save cpu
if a customer or a clerk request and all queues are the same length, a queue is randomly picked.
returns the queue to be entered.
*/
int checkQueue(int cuOrCl){
if(queue_length[0] == 0 && queue_length[1]==0 && queue_length[2]==0 && queue_length[3]==0 && cuOrCl == 0){ //when the queues are all empty and the clerk is requesting return -1
return -1;
}
if((queue_length[0] == queue_length[1] && queue_length[1]==queue_length[2] && queue_length[2] == queue_length[3])){
int r = rand();
r = r % 4;
return r;
}
int largest = 0;
int largestSpot = 0;
int smallest = 15;
int smallestSpot = 0;
for(int i = 0; i< 4; i++){
if(queue_length[i] > largest){
largest = queue_length[i];
largestSpot = i;
}
if(queue_length[i] < smallest){
smallest = queue_length[i];
smallestSpot = i;
}
}
if(cuOrCl == 1){
return smallestSpot;
}else{
return largestSpot;
}
}
/*
clerk_entry
takes in a clerkInfo object
runs a clerk process, which exists when the number of customers hits 0 (global customers);
specific information about it can be find in the code.
*/
void *clerk_entry(void * clerkInfo){
int test = 1;
//if the queues are empty, sleep and try again
struct clerk_info * p_clerkInfo = clerkInfo;
while(numCustomersGlob != 0){
test = pthread_mutex_lock(&queues_mutex);
if(test != 0){
printf("error locking mutex");
exit(0);
}
int queueTake = checkQueue(0);
if(queueTake == -1){
test = pthread_mutex_unlock(&queues_mutex);
if(test != 0){
printf("error locking mutex");
exit(0);
}
if(queueTake == -1 && numCustomersGlob < 1){
break;
}
usleep(100);
continue;
}
lockUnlockMutex(0, queueTake); //lock that queue
queue_length[queueTake]--;
numCustomersGlob--;
//this segment is to handle the event of customers moving through the queue (which is implemented as a convar) and having the other clerk request from that
//queue at the same time. This makes it so the clerk has to wait till they are done moving through the queue.
if(p_clerkInfo->clerk_id == 1){
if(c2 == queueTake){
//release the mutex and wait
lockUnlockMutex(1, queueTake);
lockUnlockMutexClerks(0, queueTake);
conVarCommands(3, queueTake);
lockUnlockMutexClerks(1, queueTake);
lockUnlockMutex(0, queueTake);
}
c1 = queueTake;
c1_busy = 2;
}else if(p_clerkInfo->clerk_id == 2){
if(c1 == queueTake){
//release the mutex and wait
lockUnlockMutex(1, queueTake);
lockUnlockMutexClerks(0, queueTake);
conVarCommands(3, queueTake);
lockUnlockMutexClerks(1, queueTake);
lockUnlockMutex(0, queueTake);
}
c2 = queueTake;
c2_busy = 2;
}
test = pthread_mutex_unlock(&queues_mutex); //unlock the amount of values in a queue
if(test != 0){
printf("error unlocking mutex");
exit(0);
}
queue_countDown[queueTake] = queue_length[queueTake]+1;
conVarCommands(2, queueTake); //broadcast to processes BROADCAST--BROADCAST
lockUnlockMutex(1, queueTake); //unlock the current queue
//based on which clerk it is. lock its mutex
if(p_clerkInfo->clerk_id == 1){
test = pthread_mutex_lock(&clerk1_mutex);
if(test != 0){
printf("error locking mutex");
exit(0);
}
test = pthread_cond_wait(&clerk1_convar, &clerk1_mutex);
if(test != 0){
printf("error waiting convar");
exit(0);
}
test = pthread_mutex_unlock(&clerk1_mutex);
if(test != 0){
printf("error unlocking mutex");
exit(0);
}
}else if(p_clerkInfo->clerk_id == 2){
test = pthread_mutex_lock(&clerk2_mutex);
if(test != 0){
printf("error locking mutex");
exit(0);
}
test = pthread_cond_wait(&clerk2_convar, &clerk2_mutex);
if(test != 0){
printf("error waiting convcar");
exit(0);
}
test = pthread_mutex_unlock(&clerk2_mutex);
if(test != 0){
printf("error unlocking mutex");
exit(0);
}
}
}
pthread_exit(NULL);
return NULL;
}
/*
customer thread
takes in a customer information object
most of the action / waiting is done in this process
*/
void * customer_entry(void * cus_info){
struct customer_info * p_myInfo = cus_info;
struct timeval cur_time; //time structs, one for when the customer enters the queue, one for when the clerk takes the customer
double enterQueue_time;
usleep((p_myInfo->arrival_time)*100000);
fprintf(stdout, "A customer arrives: customer ID %2d. \n", p_myInfo->user_id);
int test = 1;
test = pthread_mutex_lock(&queues_mutex);
if(test != 0){
printf("error locking mutex");
exit(0);
}
int queueEnter = checkQueue(1);
lockUnlockMutex(0, queueEnter);
p_myInfo->which_queue = queueEnter;
p_myInfo->whereIn_queue = queue_length[queueEnter]+1;//this will return the number in the queue, so 1 will be the "first" in the queue
queue_length[queueEnter]++;
fprintf(stdout, "Customer %d enters a queue: the queue ID %1d, and queue location %2d. \n",p_myInfo->user_id, queueEnter+1, p_myInfo->whereIn_queue);
gettimeofday(&cur_time,NULL); //taking the time of when the customer enters the queue
enterQueue_time = (cur_time.tv_sec + (double) cur_time.tv_usec / 1000000);
test = pthread_mutex_unlock(&queues_mutex);
if(test != 0){
printf("error locking mutex");
exit(0);
}
do{
//this is where movement in the queue is simulated
conVarCommands(1, queueEnter); //1 is wait -> wait for signal from the clerk
p_myInfo->whereIn_queue--; //decrease their number in the queue
if(p_myInfo->whereIn_queue == 0){
if(c1 == p_myInfo->which_queue && c1_busy == 2){ //need to add boolean to check if c1 is busy
p_myInfo->server = 1;
c1_busy = 1;
}else if(c2 == p_myInfo->which_queue && c2_busy == 2){
p_myInfo->server = 2;
c2_busy = 1;
}else{
printf("error in customer entry with server establishment.\n"); //for testing. should never get called
}
}
queue_countDown[p_myInfo->which_queue]--;
if(queue_countDown[p_myInfo->which_queue] == 0){
conVarCommands(3, p_myInfo->which_queue);
}
//lockUnlockMutex(1, queueEnter);//unlock the mutex again to allow the rest of the values to decrement. Only 1 should be 0
}while(p_myInfo->whereIn_queue != 0);
lockUnlockMutex(1, queueEnter);
//time stuff
double cur_secs, init_secs, final_secs, waitInQueue_time;
init_secs = (init_time.tv_sec + (double) init_time.tv_usec / 1000000);
gettimeofday(&cur_time, NULL);
cur_secs = (cur_time.tv_sec + (double) cur_time.tv_usec / 1000000);
double currTime = cur_secs - init_secs;
waitInQueue_time = cur_secs - enterQueue_time;
fprintf(stdout, "A clerk starts serving a customer: time in queue %.2f, service start time %.2f, the customer ID %2d, the clerk ID %1d. \n", waitInQueue_time, currTime, p_myInfo->user_id, p_myInfo->server); //currTime is a double
usleep((p_myInfo->service_time)*100000);
gettimeofday(&cur_time, NULL);
final_secs = (cur_time.tv_sec + (double) cur_time.tv_usec / 1000000);
double endTime = final_secs - init_secs; //might be final_secs - cur_secs
fprintf(stdout, "A clerk finishes serving a customer: end time %.2f, the customer ID %2d, the clerk ID %1d. \n", endTime, p_myInfo->user_id, p_myInfo->server);
overall_waiting_time = overall_waiting_time + waitInQueue_time;
//tells the clerk process that it can take the next customer
if(c1 == p_myInfo->which_queue && c1_busy == 1){
c1_busy = 0;
test = pthread_cond_signal(&clerk1_convar);
if(test != 0){
printf("error signalling mutex");
exit(0);
}
}else if(c2 == p_myInfo->which_queue && c2_busy == 1){
c2_busy = 0;
test = pthread_cond_signal(&clerk2_convar);
if(test != 0){
printf("error signalling mutex");
exit(0);
}
}else{
printf("\nerror in customer signalling the clerk\n\n");
exit(0);
}
pthread_exit(NULL);
return NULL;
}
int main(int argc, char* argv[]){
srand(time(NULL)); //get random time to use incase queues are all equal length
char * input;
while(1) {
char *prompt = "ACS: > ";
input = readline(prompt);
if(input == NULL || strcmp(input, "") == 0) {
continue;
}
if(strcmp(input, "end") ==0){ //if end is entered into the prompt we end the run. This was implemented to allow for bash script automated testing
break;
}
gettimeofday(&init_time, NULL); //for when the program starts.
overall_waiting_time = 0;
FILE* file = fopen(input, "r");
if(file == NULL){
printf("file %s had an error\n", input);
continue;
}
char line[256];
fgets(line, sizeof(line), file);
int token = atoi(strtok(line,""));
int numCustomers = token;
numCustomersGlob = numCustomers;
struct customer_info custID[token];
int count = 0;
while (fgets(line, sizeof(line), file)) {
token = atoi(strtok(line,":"));
if(token < 0){
numCustomers--;
continue;
}
custID[count].user_id = token;
token = atoi(strtok(NULL, ","));
if(token < 0){
numCustomers--;
continue;
}
custID[count].arrival_time = token;
token = atoi(strtok(NULL, ""));
if(token < 0){
numCustomers--;
continue;
}
custID[count].service_time = token;
count++;
}
numCustomersGlob = numCustomers;
fclose(file);
pthread_t threadClerkId[2];
struct clerk_info clerkID[2];
pthread_t threadCustId[numCustomers];
int i =0;
int test = 1;
for(i = 0; i<2; i++){
clerkID[i].clerk_id = i+1; //defining the ids of the clerks, if there are more details to add can remove and do outside of this loop
test = pthread_create(&threadClerkId[i], NULL, clerk_entry, (void *) &clerkID[i]);
if(test != 0){
printf("error creating thread %d\n", i);
exit(0);
}
}
for(i = 0; i < numCustomers; i++){ // number of customers
//printf("IDS:: %2d\n", custID[i].user_id);
test = pthread_create(&threadCustId[i], NULL, customer_entry, (void *) &custID[i]);
if(test != 0){
printf("error creating thread %d\n", i);
exit(0);
}
}
for(i = 0; i < numCustomers; i++){
test = pthread_join(threadCustId[i], NULL);
if(test != 0){
printf("error joining thread %d\n", i);
exit(0);
}
}
for(i = 0; i < 2; i++){
test = pthread_join(threadClerkId[i], NULL);
if(test != 0){
printf("error joining thread %d\n", i);
exit(0);
}
}
double final = (double)overall_waiting_time/numCustomers;
printf("The average waiting time for all customers in the system is: %.2f seconds\n", final);
} //end while
}
|
C
|
#include "types.h"
#include "stat.h"
#include "user.h"
void
regular_demo()
{
int pid = getpid();
int *x = (int *)malloc(sizeof(int));
int *grade = (int*)malloc(sizeof(int));
*grade = 100;
*x = 0;
int *y = (int *)malloc(sizeof(int));
*y = 100; // GRADE?!#!##$
printf(1, "pid : %d x: %d y: %d grade: %d \n\n", pid, *x, *y, *grade);
printf(1, "Fater Process <procdump> Before Forking \n\n");
//output will be from page 1 and we can see that there is a readonly page.
procdump();
//child
if (fork() == 0)
{
printf(1, "CHILD before changing X same address -copied\n");
printf(1,"pid is : %d x: %d y: %d, grade: %d \n\n", getpid(), *x, *y, *grade);
procdump();
*x=2;
printf(1, "CHILD after changing X address\n");
printf(1,"pid is : %d x: %d y: %d, grade: %d \n\n", getpid(), *x, *y, *grade);
procdump();
// // now we can see that before changing x it was a shared memory
// printf(1,"pid is : %d x: %d , y: %d, grade: %d \n\n\n\n", getpid(), *x, *y, *grade);
} else {
wait();
printf(1, "Fater Process <procdump> After Cow_Forking \n\n");
procdump();
}
}
void
cow_demo()
{
int pid = getpid();
int *x = (int *)malloc(sizeof(int));
int *grade = (int*)malloc(sizeof(int));
*grade = 100;
*x = 0;
int *y = (int *)malloc(sizeof(int));
*y = 100; // GRADE?!#!##$
printf(1, "pid : %d x: %d y: %d grade: %d \n\n", pid, *x, *y, *grade);
printf(1, "Fater Process <procdump> Before Forking \n\n");
//output will be from page 1 and we can see that there is a readonly page.
procdump();
//child
if (cowfork() == 0)
{
printf(1, "CHILD before changing X same address -copied\n");
printf(1,"pid is : %d x: %d y: %d, grade: %d \n\n", getpid(), *x, *y, *grade);
procdump();
*x=2;
printf(1, "CHILD after changing X same address\n");
printf(1,"pid is : %d x: %d y: %d, grade: %d \n\n", getpid(), *x, *y, *grade);
procdump();
// // now we can see that before changing x it was a shared memory
// printf(1,"pid is : %d x: %d , y: %d, grade: %d \n\n\n\n", getpid(), *x, *y, *grade);
} else {
wait();
printf(1, "Fater Process <procdump> After Cow_Forking \n\n");
procdump();
}
exit();
}
int
main(int argc, char *argv[])
{
printf(1,"Regular fork demonstration:\n\n");
regular_demo();
printf(1,"COW demonstration:\n\n");
cow_demo();
exit();
}
|
C
|
#include <stdio.h>
#include "valuenoise.h"
#include "vectors.h"
#define width 256
#define height 256
int main () {
struct double3 value;
FILE* fp = fopen ("valuenoise.pgm", "w");
fprintf (fp, "P2\n%d %d\n255\n", width, height);
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
value = ValueNoise2D (x, y, 0.05, 5, 2, 0.5);
fprintf (fp, "%u ", (unsigned)(value.x * 255));
}
fprintf (fp, "\n");
}
fclose (fp);
return 0;
}
|
C
|
#pragma once
//prototypes des fonctions utilises dans l'exercice 1
int initTab(int* tab, int size);
int afficheTab(int* tab, int size, int nbElts);
int unavingtTab(int* tab, int size, int nbElts);
int* ajoutElementDansTableau(int* tab, int* size, int* nbElts, int element);
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include "skip.h"
//Trabalho Pratico 1 de AEDS2 *** Guilherme Saulo Alves *** 20 de Novembro de 2013
int main(int argc, char **argv){
/*....................declaração das variaveis e processos iniciais......................*/
int nivel; //nivel que ira inserir uma chave(0 a 4)
char opcao; //I-(Inserir) R-(Remover) B-(Busca) P-(Imprime Nivel h) A-(Imprime Todos Nivel)
TipoItem item; //cria tipo item para ler do arquivo um item.chave
TipoLista lista; //cria lista do skip list
Apontador listah[NIVEIS+1]; //criar um vetor de ponteiros
FLVazia(&lista); //faz a slip list ficar vazia
/*.................................entrada e saida.......................................*/
while(scanf("%c", &opcao) > 0){ //condicao para ir lendo as entradas do arquivo
switch(opcao){
case 'I': //inserir
scanf(" %d %d", &item.Chave, &nivel); //lê a chave que quer inserir e o nivel hierarquico
if(Insere(item, nivel, &lista)==1)
printf("true\n"); //inserido com sucesso
else
printf("false\n"); //falha ao inserir
break;
case 'R': //remover
scanf(" %d", &item.Chave); //lê a chave a remover
if(Remove(item.Chave, &lista)==1)
printf("true\n"); //removido com sucesso
else
printf("false\n"); //falha ao remover
break;
case 'B': //busca
scanf(" %d",&item.Chave);
if(Busca(item.Chave, &lista, listah, 1)==1)
printf("true\n"); //busca realizada com sucesso
else
printf("false\n"); //busca falhou
break;
case 'P': //imprime nivel hierarquico h
scanf(" %d", &nivel); //lê o nivel
Imprime(lista, nivel); //imprime o nivel
break;
case 'A': //imprime todos niveis
ImprimeTodos(lista);
break;
}
}
return 0;
}
|
C
|
/*
* Copyright (c) 2014
*
* "License"
*
* Bug reports and issues: <"Email">
*
* This file is part of cwfragment.
*/
#include "timer.h"
#include <unistd.h>
#include <stdio.h>
int main(int argc, char *argv[])
{
struct timer *timer = timer_new();
sleep(1);
printf("Elapsed: %lu ms\n", timer_elapsed(timer, NULL));
timer_stop(timer);
sleep(1);
printf("Elapsed: %lu ms\n", timer_elapsed(timer, NULL));
timer_continue(timer);
sleep(1);
printf("Elapsed: %lu ms\n", timer_elapsed(timer, NULL));
timer_destroy(&timer);
return 0;
}
|
C
|
#include<string.h>
#include<stdio.h>
#include<stdlib.h>
#include <unistd.h>
#include "curl.h"
#include "error_msg.h"
#include "log_api.h"
#include "misc_api.h"
#define CURL_METHOD_GET 0
#define CURL_METHOD_POST 1
#define BUFF_MAX_LEN 4096
/*动作*/
typedef struct curl_buff_s
{
/*缓存*/
unsigned char aucBuff[BUFF_MAX_LEN];
/*长度*/
unsigned int uiLen;
}curl_buff_t;
size_t curl_write_data_cb(void *buffer, size_t size, size_t nmemb, void *userp)
{
size_t iLen = size * nmemb;
if (userp)
{
curl_buff_t *pstCurlBuff = (curl_buff_t *)userp;
//DEBUG("Len = %d, Date = %s\n", iLen, buffer);
if(pstCurlBuff->uiLen + iLen < BUFF_MAX_LEN)
{
memcpy(pstCurlBuff->aucBuff + pstCurlBuff->uiLen, buffer, iLen);
pstCurlBuff->uiLen += iLen;
}
}
return iLen;
}
size_t curl_write_file_cb(void *buffer, size_t size, size_t nmemb, void *userp)
{
size_t iLen = size * nmemb;
if (userp)
{
FILE *fp = NULL;
if (access((char*)userp, F_OK) == -1)
{
fp = fopen((char*)userp, "wb");
}
else
{
fp = fopen((char*)userp, "ab");
}
if (NULL == fp)
{
HY_DEBUG("open file(%s) failed\n", (char*)userp);
return iLen;
}
fwrite(buffer, size, nmemb, fp);
fclose(fp);
}
return iLen;
}
/*
http get func
*/
int curl_http_get(char *pcUrl, char *pcResult, int *piLen)
{
int iLenMax = *piLen;
*piLen = 0;
CURL *pstCurl;
CURLcode curlRet;
curl_buff_t stCurlBuff;
memset(&stCurlBuff, 0x0, sizeof(curl_buff_t));
//curl初始化
pstCurl = curl_easy_init();
if (!pstCurl)
{
HY_ERROR("curl easy init failed\n");
return GeneralErr;
}
if (0 == strncmp(pcUrl, "https://", 8))
{
//设定为不验证证书和HOST
curl_easy_setopt(pstCurl, CURLOPT_SSL_VERIFYPEER, 0L);
curl_easy_setopt(pstCurl, CURLOPT_SSL_VERIFYHOST, 0L);
}
curl_easy_setopt(pstCurl, CURLOPT_HEADER, 0); //设置httpheader 解析, 不需要将HTTP头写传入回调函数
curl_easy_setopt(pstCurl, CURLOPT_URL, pcUrl); //设置远端地址
curl_easy_setopt(pstCurl, CURLOPT_VERBOSE, 1L); // TODO: 打开调试信息
curl_easy_setopt(pstCurl, CURLOPT_FOLLOWLOCATION, 1); //设置允许302 跳转
curl_easy_setopt(pstCurl, CURLOPT_WRITEFUNCTION, curl_write_data_cb); //执行写入文件流操作 的回调函数
curl_easy_setopt(pstCurl, CURLOPT_WRITEDATA, &stCurlBuff); // 设置回调函数的第4 个参数
curl_easy_setopt(pstCurl, CURLOPT_CONNECTTIMEOUT, 5); //设置连接超时,单位s, CURLOPT_CONNECTTIMEOUT_MS 毫秒
curl_easy_setopt(pstCurl, CURLOPT_NOSIGNAL, 1); //linux多线程情况应注意的设置(防止curl被alarm信号干扰)
curlRet = curl_easy_perform(pstCurl);
if (CURLE_OK != curlRet)
{
HY_ERROR("curl_easy_perform() failed: %s\n", curl_easy_strerror(curlRet));
curl_easy_cleanup(pstCurl);
return GeneralErr;
}
curl_easy_cleanup(pstCurl);
if(NULL != pcResult && NULL != piLen)
{
*piLen = stCurlBuff.uiLen > iLenMax ? iLenMax : stCurlBuff.uiLen;
memcpy(pcResult, stCurlBuff.aucBuff, *piLen);
}
return NoErr;
}
int curl_http_post(char *pcUrl, char*pcData, char *pcResult, int *piLen)
{
int iLenMax = *piLen;
*piLen = 0;
CURL *pstCurl;
CURLcode curlRet;
curl_buff_t stCurlBuff;
memset(&stCurlBuff, 0x0, sizeof(curl_buff_t));
//curl初始化
pstCurl = curl_easy_init();
if (!pstCurl)
{
HY_ERROR("curl easy init failed\n");
return GeneralErr;
}
if (0 == strncmp(pcUrl, "https://", 8))
{
//设定为不验证证书和HOST
curl_easy_setopt(pstCurl, CURLOPT_SSL_VERIFYPEER, 0L);
curl_easy_setopt(pstCurl, CURLOPT_SSL_VERIFYHOST, 0L);
}
curl_easy_setopt(pstCurl, CURLOPT_URL, pcUrl);
curl_easy_setopt(pstCurl, CURLOPT_POST, 1);
curl_easy_setopt(pstCurl, CURLOPT_WRITEFUNCTION, curl_write_data_cb);
curl_easy_setopt(pstCurl, CURLOPT_WRITEDATA, &stCurlBuff);
curl_easy_setopt(pstCurl, CURLOPT_POSTFIELDS, pcData);
curlRet = curl_easy_perform(pstCurl);
if (CURLE_OK != curlRet)
{
HY_ERROR("curl_easy_perform() failed: %s\n", curl_easy_strerror(curlRet));
curl_easy_cleanup(pstCurl);
return GeneralErr;
}
curl_easy_cleanup(pstCurl);
if(NULL != pcResult && NULL != piLen)
{
*piLen = stCurlBuff.uiLen > iLenMax ? iLenMax : stCurlBuff.uiLen;
memcpy(pcResult, stCurlBuff.aucBuff, *piLen);
}
return NoErr;
}
int curl_http_post_json(char *pcUrl, char*pcJson, char *pcResult, int *piLen)
{
int iLenMax = *piLen;
*piLen = 0;
CURL *pstCurl;
CURLcode curlRet;
curl_buff_t stCurlBuff;
memset(&stCurlBuff, 0x0, sizeof(curl_buff_t));
//curl初始化
pstCurl = curl_easy_init();
if (!pstCurl)
{
HY_ERROR("curl easy init failed\n");
return GeneralErr;
}
if (0 == strncmp(pcUrl, "https://", 8))
{
//设定为不验证证书和HOST
curl_easy_setopt(pstCurl, CURLOPT_SSL_VERIFYPEER, 0L);
curl_easy_setopt(pstCurl, CURLOPT_SSL_VERIFYHOST, 0L);
}
curl_easy_setopt(pstCurl, CURLOPT_URL,pcUrl);
curl_easy_setopt(pstCurl, CURLOPT_POST, 1);
struct curl_slist *plist = curl_slist_append(NULL, "Content-Type:application/json;charset=UTF-8");
curl_easy_setopt(pstCurl, CURLOPT_HTTPHEADER, plist);
curl_easy_setopt(pstCurl, CURLOPT_WRITEFUNCTION, curl_write_data_cb);
curl_easy_setopt(pstCurl, CURLOPT_WRITEDATA,&stCurlBuff);
curl_easy_setopt(pstCurl, CURLOPT_POSTFIELDS, pcJson);
curlRet = curl_easy_perform(pstCurl);
if (CURLE_OK != curlRet)
{
HY_ERROR("curl_easy_perform() failed: %s\n", curl_easy_strerror(curlRet));
curl_easy_cleanup(pstCurl);
return GeneralErr;
}
curl_easy_cleanup(pstCurl);
if(NULL != pcResult && NULL != piLen)
{
*piLen = stCurlBuff.uiLen > iLenMax ? iLenMax : stCurlBuff.uiLen;
memcpy(pcResult, stCurlBuff.aucBuff, *piLen);
}
return NoErr;
}
int curl_download_file(char *pcUrl, char *pcPath, char *pcMd5)
{
int iCount = 0;
CURL *pstCurl;
CURLcode curlRet;
if (0 == access(pcPath, F_OK))
{
remove(pcPath);
}
//curl初始化
pstCurl = curl_easy_init();
if (!pstCurl)
{
HY_ERROR("curl easy init failed\n");
return GeneralErr;
}
if (0 == strncmp(pcUrl, "https://", 8))
{
//设定为不验证证书和HOST
curl_easy_setopt(pstCurl, CURLOPT_SSL_VERIFYPEER, 0L);
curl_easy_setopt(pstCurl, CURLOPT_SSL_VERIFYHOST, 0L);
}
curl_easy_setopt(pstCurl, CURLOPT_HEADER, 0); //设置httpheader 解析, 不需要将HTTP头写传入回调函数
curl_easy_setopt(pstCurl, CURLOPT_URL, pcUrl); //设置远端地址
curl_easy_setopt(pstCurl, CURLOPT_VERBOSE, 1L); // TODO: 打开调试信息
curl_easy_setopt(pstCurl, CURLOPT_FOLLOWLOCATION, 1); //设置允许302 跳转
curl_easy_setopt(pstCurl, CURLOPT_WRITEFUNCTION, curl_write_file_cb); //执行写入文件流操作 的回调函数
curl_easy_setopt(pstCurl, CURLOPT_WRITEDATA, pcPath); // 设置回调函数的第4 个参数
curl_easy_setopt(pstCurl, CURLOPT_CONNECTTIMEOUT, 5); //设置连接超时,单位s, CURLOPT_CONNECTTIMEOUT_MS 毫秒
curl_easy_setopt(pstCurl, CURLOPT_NOSIGNAL, 1); //linux多线程情况应注意的设置(防止curl被alarm信号干扰)
iCount = 3;
while(iCount)
{
curlRet = curl_easy_perform(pstCurl);
if (CURLE_OK != curlRet)
{
HY_ERROR("curl_easy_perform() failed: %s\n", curl_easy_strerror(curlRet));
iCount--;
continue;
}
if(NULL != pcMd5)
{
/*MD5校验*/
char acMd5[MD5_MAX_LEN] = {0};
MD5_File(pcPath, acMd5);
if(!strcasecmp(pcMd5, acMd5))
{
break;
}
else
{
HY_ERROR("File MD5 check exception.\n");
iCount--;
continue;
}
}
else
{
break;
}
}
curl_easy_cleanup(pstCurl);
return NoErr;
}
int curl_init(void)
{
curl_global_init(CURL_GLOBAL_ALL);
return NoErr;
}
int curl_cleanup(void)
{
curl_global_cleanup();
return NoErr;
}
|
C
|
#include "hexchat-plugin.h"
#include <string.h>
#define PNAME "Promiscuous"
#define PDESC "View all conversations in one tab"
#define PVERSION "0.1"
#define SERV "freenode" /* whose tab? */
static hexchat_plugin *ph; /* plugin handle */
/* https://stackoverflow.com/a/7666577 */
unsigned char hash(unsigned char *str)
{
unsigned long hash = 5381;
int c;
while (c = *str++)
hash = ((hash << 5) + hash) + c; /* hash * 33 + c */
return hash;
}
static int privmsg_cb(char *word[], char *word_eol[], void *userdata)
{
/* to be shown */
char nick[16];
char msg[512] = "\3";
/* extract nick */
char i;
for (i = 1; word[1][i] != '!'; i++) {
nick[i - 1] = word[1][i];
}
nick[i - 1] = 0;
/* set msg color according to hash of chan */
char const map[] = { 1, 2, 3, 4, 5, 6, 7, 10, 11, 12, 13, 14 };
char const color = map[hash(word[3] + 1) % 12];
msg[1] = '0' + color / 10;
msg[2] = '0' + color % 10;
/* extract msg */
strcpy(msg + 3, word_eol[4] + 2);
/* it's time */
hexchat_set_context(ph, hexchat_find_context(ph, SERV, SERV));
hexchat_emit_print(ph, "Channel Message", nick, msg, NULL);
/* better not tell other plugins */
return HEXCHAT_EAT_PLUGIN;
}
void
hexchat_plugin_get_info(char **name, char **desc, char **version,
void **reserved)
{
*name = PNAME;
*desc = PDESC;
*version = PVERSION;
}
int
hexchat_plugin_init(hexchat_plugin * plugin_handle, char **plugin_name,
char **plugin_desc, char **plugin_version, char *arg)
{
/* we need to save this for use with any hexchat_* functions */
ph = plugin_handle;
/* tell HexChat our info */
*plugin_name = PNAME;
*plugin_desc = PDESC;
*plugin_version = PVERSION;
/* what we're interested in */
hexchat_hook_server(ph, "PRIVMSG", HEXCHAT_PRI_NORM, privmsg_cb, NULL);
hexchat_print(ph, "PromiscuousPlugin loaded successfully!\n");
/* return 1 for success */
return 1;
}
int hexchat_plugin_deinit(hexchat_plugin * plugin_handle)
{
hexchat_print(ph, "Unloading PromiscuousPlugin");
return 1; /* return 1 for success */
}
|
C
|
// Trabalho Pratico Programacao - LEI
// DEIS-ISEC 2020-2021
// Tomás Gomes Silva - 2020143845
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include "../headers/utils.h"
void initRandom(){
srand(time(NULL));
}
int intUniformRnd(int a, int b){
return a + rand()%(b-a+1);
}
int probEvento(float prob){
return prob > ((float)rand()/RAND_MAX);
}
int existeFicheiro(){
FILE *f;
f = fopen("jogo.bin", "rb");
if(f == NULL) return 0;
fclose(f);
return 1;
}
void mostrarASCII(){
system("@cls||clear");
printf(" _____ ____ \n");
printf(" / ___/___ ____ ___ ____ _/ __/___ _________ _____\n");
printf(" |__ \\/ _ \\/ __ `__ \\/ __ `/ /_/ __ \\/ ___/ __ \\/ ___/\n");
printf(" ___/ / __/ / / / / / /_/ / __/ /_/ / / / /_/ (__ ) \n");
printf("/____/\\___/_/ /_/ /_/\\__,_/_/ \\____/_/ \\____/____/ \n");
printf(" \n");
printf("Jogo dos Sem\u00E1foros - Trabalho Pr\u00E1tico de Programa\u00E7\u00E3o\n\n\n");
}
void howToPlay();
int menu(){
mostrarASCII();
int escolha = - 1;
printf("1 - Jogador vs Jogador\n");
printf("2 - Jogador vs Computador\n");
printf("3 - Instru\u00E7ões de como jogar\n");
printf("0 - Sair do jogo\n\n");
printf("Op\u00E7\u00E3o: ");
fflush(stdin);
scanf("%d", &escolha);
if(escolha == 1) return 0;
else if(escolha == 2) return 1;
else if(escolha == 3) howToPlay();
else if(escolha == 0) exit(0);
else menu();
}
void howToPlay(){
mostrarASCII();
printf("");
printf("> O jogo do Sem\u00E1foro \u00E9 um jogo de tabuleiro entre 2 pessoas que efetuam jogadas alternadas ");
printf("at\u00E9 que uma delas ven\u00E7a ou que se verifique um empate.\n\n");
printf("> \u00C9 gerado um tabuleiro quadrado com dimens\u00E3o aleat\u00F3ria (entre 3 e 5 linhas) e cada jogador ");
printf("pode escolher jogar uma pe\u00E7a ou utilizar uma habilidade especial.\n\n");
char continuar;
printf("\nPressione a tecla ENTER para continuar");
fflush(stdin);
getchar();
mostrarASCII();
printf("> Alternadamente, os jogadores v\u00E3o colocando pe\u00E7as de cor\nVERDE (G), AMARELA (Y) ou VERMELHA (R)\n\n");
printf("> Ganha o jogador que coloque uma pe\u00E7a que permita formar uma linha, coluna ou diagonal completa com pe\u00E7as da mesma cor\n\n");
printf("\nPressione a tecla ENTER para continuar");
fflush(stdin);
getchar();
mostrarASCII();
printf("> As jogadas v\u00E1lidas relativas a colocar uma pe\u00E7a s\u00E3o as seguintes:\n\n");
printf("1. Colocar uma pe\u00E7a VERDE numa c\u00E9lula vazia\n");
printf("2. Trocar uma pe\u00E7a VERDE por uma pe\u00E7a AMARELA\n");
printf("3. Trocar uma pe\u00E7a AMARELA por uma pe\u00E7a VERMELHA\n\n");
printf("\nPressione a tecla ENTER para continuar");
fflush(stdin);
getchar();
mostrarASCII();
printf("> Para além de jogarem pe\u00E7as, os jogadores podem tamb\u00E9m utilizar habilidades especiais:\n\n");
printf("1. Colocar uma pedra numa c\u00E9lula vazia (limitada a 1 por jogo)\n");
printf("2. Adicionar uma nova linha ou coluna ao final do tabuleiro (limitada a 2 por jogo)\n\n");
printf("\nPressione a tecla ENTER para continuar");
fflush(stdin);
getchar();
return;
}
|
C
|
#include <stdio.h>
#include <signal.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <errno.h>
#include <sys/stat.h>
#include <fcntl.h>
char *p_1 ="ls";
char *p_2 ="-la";
char *s_1 ="tr";
char *s_2="'d'";
char *s_3="'D'";
int main(int argc, char *argv[])
{
//inicializamos el pid para hacer el fork()
pid_t pid;
//Creamos matriz de flujo de lectura y escritura del pipe
int fd[2];
//Creamos el pipe
pipe(fd);
//Creamos el primer hijo
pid = fork();
if(pid==0)
{ //Hijo 1
dup2(fd[1], STDOUT_FILENO);
close(fd[0]);
close(fd[1]);
execlp(p_1,p_1,p_2,(char*) NULL);
}
else
{
//Creamos el segundo hijo
pid=fork();
if(pid==0)
{ //hijo 2
dup2(fd[0], STDIN_FILENO);
close(fd[1]);
close(fd[0]);
execlp(s_1, s_1, s_2, s_3,(char*) NULL);
}
else
{ //Padre
int status;
close(fd[0]);
close(fd[1]);
waitpid(pid, &status, 0);
}
}
}
|
C
|
#include<istdio.h>
// declaring all required variables
struct process{
int process_name,
arrival_time,
burst_time,
waiting_time,
turning_time,
priority,
burst_time_copy;
}queuea[20],queueb[20];
int main(){
struct process code;
// for keeping values safe we need copy of every value, as we would manupulate the input values which may cause problem at the end
int a,
b,
c,
time=0,
t1,
t2,
bu_t=0,
largest,
totalProcess,
count=0,
pf2=0,
totalProcess2,
n,
pos,
flag=0,
y;
float wait_time=0,
turnaround_time= 0,
average_waiting_time,
average_turnaround_time;
printf("********Written by Rithik sharma********\n");
printf("**** k18AZB49 11800883 **************\n");
printf("\nENTER TOTAL NUMBER OF PROCESSES = ");
//saving reference value to other var
scanf("%d",&totalProcess);
n=totalProcess;
for(a=0;a<totalProcess;a++){
printf("\nENTER PROCESS NAME = ");
scanf("%d",&queuea[a].process_name);
printf("\nENTER DETAILS FOR PROCESS = %d:\n",queuea[a].process_name);
printf("ENTER ARRIVAL TIME = ");
scanf("%d",&queuea[a].arrival_time);
printf("ENTER BURST TIME = ");
scanf("%d",&queuea[a].burst_time);
queuea[a].burst_time_copy=queuea[a].burst_time;
printf("ENTER PRIORITY = \t");
scanf("%d",&queuea[a].priority);
}
//some things are fixed throughout the program
//time quantum for fixed priority
//time quantum for round robin
printf("\nTIME QUANTUM FOR FIXED QUEUE SCHEDULING = ");
scanf("%d",&t1);
printf("\nTIME QUANTUM FOR ROUND ROBIN = ");
scanf("%d",&t2);
printf("\n\nPROCESS\t|TURNAROND TIME |WAITING TIME\n\n");
//input complete
//to calculate
//average waiting time
//average turn around time
for(a=0;a<totalProcess;a++){
pos=a;
for(b=a+1;b<totalProcess;b++)
{
if(queuea[b].arrival_time<queuea[pos].arrival_time)
pos=b;
}
code=queuea[a];
queuea[a]=queuea[pos];
queuea[pos]=code;
}
time=queuea[0].arrival_time;
//traversing queue and checking if the current position is less than equal to the ath index of queuea
for(a=0;totalProcess!=0;a++)
{
while(count!=t1)
{
//traversing the queue according to the arrival time and priority
count++;
if(queuea[a].arrival_time<=time)
{
for(b=a+1;b<totalProcess;b++)
{
if(queuea[b].arrival_time==time&&queuea[b].priority<queuea[a].priority)
{
queueb[pf2]=queuea[a];
pf2++;
for(c=a;c<totalProcess-1;c++)
queuea[c]=queuea[c+1];
totalProcess--;
count=0;
a=b-1;
b--;
}
}
}
time++;
queuea[a].burst_time--;
if(queuea[a].burst_time==0)
{//finding turn around time = time taken - arriavl time
//analysing the waiting time = turning time - burst time
queuea[a].turning_time=time-queuea[a].arrival_time;
queuea[a].waiting_time=queuea[a].turning_time-queuea[a].burst_time_copy;
printf("%d\t|\t%d\t|\t%d\n",queuea[a].process_name,queuea[a].turning_time,queuea[a].waiting_time);
wait_time+=time-queuea[a].arrival_time-queuea[a].burst_time_copy;
turnaround_time+=time-queuea[a].arrival_time;
for(c=a;c<totalProcess-1;c++)
queuea[c]=queuea[c+1];a--;
totalProcess--;
count=t1;break;
}
}
count=0;
//traversing via burst times to finish every process
if(queuea[a].burst_time!=0)
{
queueb[pf2]=queuea[a];
pf2++;
for(c=a;c<totalProcess-1;c++)
queuea[c]=queuea[c+1];
totalProcess--;
}
if(a==totalProcess-1)
a=-1;
}
//traversing the second queue with burst time
totalProcess2=pf2;
for(count=0;totalProcess2!=0;)
{
if(queueb[count].burst_time<=t2&&queueb[count].burst_time>0)
{
time+=queueb[count].burst_time;
queueb[count].burst_time=0;
flag=1;
}
else if(queueb[count].burst_time>0)
{
queueb[count].burst_time-=t2;
time+=t2;
}
if(queueb[count].burst_time==0&&flag==1)
{
//calculating turnaround time and waiting time
totalProcess2--;
queueb[count].turning_time=time-queueb[count].arrival_time;
queueb[count].waiting_time=queueb[count].turning_time-queueb[count].burst_time_copy;
printf("%d\t|\t%d\t|\t%d\n",queueb[count].process_name,queueb[count].turning_time,queueb[count].waiting_time);
turnaround_time+=time-queueb[count].arrival_time;
wait_time+=time-queueb[count].arrival_time-queueb[count].burst_time_copy;
for(c=count;c<totalProcess2;c++)
queueb[c]=queueb[c+1];count--;
flag=0;
}
if(count==totalProcess2-1)
count=0;
else
count++;
}
printf("\nAVERAGE WAITING TIME = %f\n",wait_time*1.0/n);
printf("AVERAGE TURNAROUND TIME = %f",turnaround_time*1.0/n);
}
|
C
|
#include "header.h"
int main(int argc, char** argv)
{
int server_port, client_port, server_fd, client_fd, n;
char node_id;
node_id = argv[1][0];
char *buffer = malloc(80 * sizeof(char));
size_t *t = 0;
//printf("Please enter node id:\n");
//scanf("%c", node_id);
if(DEBUG) printf("Node id: %c\n", node_id);
printf("Please enter the port to run the server on:\n");
while((n = getline(&buffer, &t, stdin)) < 0);
server_port = atoi(buffer);
if(DEBUG) printf("Server port: %d\n", server_port);
printf("Please enter the port to connect as a client on:\n");
while((n = getline(&buffer, &t, stdin)) < 0);
client_port = atoi(buffer);
if(DEBUG) printf("Client port: %d\n", client_port);
if(node_id == 'c')
{
client_fd = Client(client_port);
server_fd = Server(server_port);
}
else
{
server_fd = Server(server_port);
client_fd = Client(client_port);
}
for(;;)
{
if(node_id == 'a')
{
while((n = getline(&buffer, &t, stdin)) < 0);
write(client_fd, buffer, n);
if(strncmp(buffer, "!!quit!!", 8) == 0)
{
break;
}
}
else if(node_id == 'b')
{
n = read(server_fd, buffer, 80);
printf("%s\n", buffer);
write(client_fd, buffer, n);
if(strncmp(buffer, "!!quit!!", 8) == 0)
{
break;
}
}
else
{
n = read(server_fd, buffer, 80);
printf("%s\n", buffer);
if(strncmp(buffer, "!!quit!!", 8) == 0)
{
break;
}
}
}
free(buffer);
close(server_fd);
close(client_fd);
return 0;
}
|
C
|
/*
** double_left_redir.c for 42sh in /home/lejeun_m/Projets/PSU_2014_42sh
**
** Made by Matthew LEJEUNE
** Login <lejeun_m@epitech.net>
**
** Started on Sat May 2 19:10:52 2015 Matthew LEJEUNE
** Last update Sat May 30 15:51:08 2015 Matthew LEJEUNE
*/
#include "42sh.h"
char *get_str_stop(t_cmd *cmd)
{
int cur_case;
cur_case = -1;
while (cmd->params[++cur_case])
if (my_strcmp(cmd->params[cur_case], "<<") == 0)
return (cmd->params[cur_case + 1]);
return (NULL);
}
void change_cmd_left_redir(t_cmd *cmd)
{
int cur_char;
char *cmd_str;
char **split;
cur_char = get_index_of(cmd->entire_cmd, '<');
cmd_str = my_substr(cmd->entire_cmd, -1, cur_char);
cmd_str = epur_str(cmd_str);
cmd->entire_cmd = my_strdup(cmd_str);
split = my_split(cmd->entire_cmd, ' ');
cmd->name = my_strdup(split[0]);
cmd->params = array_cpy(split);
free_tab(split);
free(cmd_str);
}
void double_left_redir2(t_cmd *cmd, int *pipefd)
{
char *str;
char *str_stop;
int done;
close(pipefd[0]);
done = 0;
while (done == 0)
{
my_putstr("> ");
if ((str_stop = get_str_stop(cmd)) == NULL)
{
close(pipefd[1]);
exit(EXIT_FAILURE);
}
if ((str = get_cmd(0)) == NULL)
exit(EXIT_FAILURE);
if (my_strcmp(str, str_stop) == 0)
{
close(pipefd[1]);
done = 1;
}
write(pipefd[1], str, my_strlen(str));
write(pipefd[1], "\n", 1);
}
exit(-1);
}
int double_left_redir(t_cmd *cmd, char **path, char **env)
{
int pipefd[2];
int status;
pid_t pid;
pipe(pipefd);
path = path;
if ((pid = fork()) == -1)
return (0);
if (pid == 0)
double_left_redir2(cmd, pipefd);
else
{
wait(&status);
close(pipefd[1]);
dup2(pipefd[0], 0);
change_cmd_left_redir(cmd);
return (prep_exec(cmd, path, env));
}
return (0);
}
int prep_double_left_redir(t_cmd *cmd, char **path, char **env)
{
sig_def_exec();
double_left_redir(cmd, path, env);
return (0);
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* loadnewUpload.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: jguyet <jguyet@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2017/05/06 07:33:42 by jguyet #+# #+# */
/* Updated: 2017/05/06 07:33:43 by jguyet ### ########.fr */
/* */
/* ************************************************************************** */
#include "ftp_upload.h"
#include "libfile.h"
#include "printf.h"
static BOOLEAN is_correct_file(char *path)
{
if (!file_exists(path))
return (false);
if (!is_regular(path))
return (false);
if (!(get_file_mode(path) & S_IRUSR))
return (false);
return (true);
}
t_upload *loadnewupload(char *filename, char *path)
{
struct stat buf;
t_upload *upload;
int fd;
void *ptr;
if (!is_correct_file(path))
return (NULL);
if (!(upload = (t_upload*)malloc(sizeof(t_upload))))
return (NULL);
stat(path, &buf);
upload->size = buf.st_size;
upload->path = ft_strdup(path);
upload->filename = ft_strdup(filename);
upload->currentpart = 0;
upload->maxpart = getmaxpart(upload);
upload->offset = 0;
upload->type = UPLOAD;
upload->dest = NULL;
upload->part = NULL;
fd = open(upload->path, O_RDONLY);
ptr = mmap(0, upload->size, PROT_READ, MAP_SHARED, fd, 0);
upload->content = ft_strnew(upload->size);
ft_memcpy(upload->content, ptr, upload->size);
munmap(ptr, upload->size);
return (upload);
}
|
C
|
////////////////////////////////////////////////////////////////////////////////
//
// File : shellex.c
// Description : This is the source code for a Shell implementation
//
// Author : Jesus Ayala
// Last Modified : December 6th, 2019
//
// $begin shellmain
#include "csapp.h"
#define MAXARGS 128
// Function prototypes
void eval(char *cmdline);
int parseline(char *buf, char **argv);
int builtin_command(char **argv);
void sigHandler(int sig) { // This function makes it so ctrl+C does not exit shell
signal(SIGINT, sigHandler);
fflush(stdout);
}
int main(int argc, char** argv) {
signal(SIGINT, sigHandler);
char cmdline[MAXLINE]; // Command line
while (1) {
if (argc == 3 && (strcmp(argv[1],"-p")== 0)) {
printf("%s>", argv[2]); // Check if there is a valid prompt
}
else {
printf("my257sh>"); // If not, then default to this string
}
Fgets(cmdline, MAXLINE, stdin);
if (feof(stdin)) {
exit(0);
}
eval(cmdline); //Evaluate
}
}
// $end shellmain
// $begin eval
// eval - Evaluate a command line
void eval(char *cmdline) {
char *argv[MAXARGS]; // Argument list execve()
char buf[MAXLINE]; // Holds modified command line
int bg; // Should the job run in bg or fg?
pid_t pid; // Process id
strcpy(buf, cmdline);
bg = parseline(buf, argv);
if (argv[0] == NULL)
return; // Ignore empty lines
if (!builtin_command(argv)) {
if ((pid = Fork()) == 0) { // Child runs user job
if (execvp(argv[0], argv) < 0) {
printf("Execution failed (in fork)\n");
printf(": No such file or directory\n");
exit(1); // the child status is 1 for invalid commands
}
}
// Parent waits for foreground job to terminate
if (!bg) {
int status;
if (waitpid(pid, &status, 0) < 0) {
unix_error("waitfg: waitpid error");
}
waitpid(pid, &status, 0);
if (WIFEXITED(status)) {
int exit_status = WEXITSTATUS(status);
printf("Child exit status: %d\n", exit_status);
// Grab status of the child
}
}
else
printf("%d %s", pid, cmdline);
}
return;
}
// If first arg is a builtin command, run it and return true
int builtin_command(char **argv) {
if (!strcmp(argv[0], "exit")) { // quit command
printf("Terminated\n");
exit(0);
}
if (!strcmp(argv[0], "&")) { // Ignore singleton %
return 1;
}
if (!strcmp(argv[0], "pid")) { // Grab process id
printf("%d\n", getpid());
return 1;
}
if (!strcmp(argv[0], "ppid")) { // Grab parent process id
printf("%d\n", getppid());
return 1;
}
if (!strcmp(argv[0], "cd")) {
if (argv[1] == NULL) { // If no option inputted after cd, then printcurrent directory
char str[1000];
printf("%s\n", getcwd(str, 1000));
return 1;
}
else { // Otherwise go to the option inputted
chdir(argv[1]);
return 1;
}
}
if (!strcmp(argv[0], "help")) { // Help command prints useful info
printf("Shell created by Jesus Ayala\n");
printf("Useful commands:\n");
printf("exit: Exits the shell\n");
printf("pid: prints the process id of the shell\n");
printf("ppid: prints the parent process id of the shell\n");
printf("cd: print current working directory\n");
printf("cd <path>: change current working directory\n");
printf("Refer to man for other commands\n");
return 1;
}
return 0; // Only reach here if not a built in command
}
// $end eval
// $begin parseline
// parseline - Parse the command line and build the argv array
int parseline(char *buf, char **argv) {
char *delim; // Points to first space delimiter
int argc; // Number of args
int bg; // Background job?
buf[strlen(buf)-1] = ' '; // Replace trailing '\n' with space
while (*buf && (*buf == ' ')) // Ignore leading spaces
buf++;
// Build the argv list
argc = 0;
while ((delim = strchr(buf, ' '))) {
argv[argc++] = buf;
*delim = '\0';
buf = delim + 1;
while (*buf && (*buf == ' ')) // Ignore spaces
buf++;
}
argv[argc] = NULL;
if (argc == 0) // Ignore blank line
return 1;
// Should the job run in the background?
if ((bg = (*argv[argc-1] == '&')) != 0)
argv[--argc] = NULL;
return bg;
}
// $end parseline
|
C
|
#include<stdio.h>
int main ()
{
int a;
int b;
int x;
int y;
a = 20;
b = 39;
x = a+b;
y = b%2;
printf("\nOur sum of %d and %d is %d", a,b,x);
printf("\nWe analyze a new function, for %d and %d, a value assigned %d", a,b,y);
return 0;
}
|
C
|
// Fig. 5.16: fig05_16.c
// Scoping.
//Todo: Modify the code to print memory addresses of all variables/array elements and
//explain the impact of "static" keyword. Also use an extern variable and discuss how
//it impacts the memory address. Why?
#include <stdio.h>
void useLocal(void); // function prototype
void useStaticLocal(void); // function prototype
void useGlobal(void); // function prototype
//static has the ability to limit the scope of variables
extern int j;//extern variable changes the memory address of x extern takes up memory
int x = 1; // global variable
int main(void)
{
int x = 5; // local variable to main
printf("local x in outer scope of main is %p\n", &x);
{ // start new scope
int x = 7; // local variable to new scope
printf("local x in inner scope of main is %p\n", &x);
} // end new scope
printf("local x in outer scope of main is %p\n", &x);
useLocal(); // useLocal has automatic local x
useStaticLocal(); // useStaticLocal has static local x
useGlobal(); // useGlobal uses global x
useLocal(); // useLocal reinitializes automatic local x
useStaticLocal(); // static local x retains its prior value
useGlobal(); // global x also retains its value
printf("\nlocal x in main is %p\n", &x);
}
// useLocal reinitializes local variable x during each call
void useLocal(void)
{
int x = 25; // initialized each time useLocal is called
printf("\nlocal x in useLocal is %p after entering useLocal\n", &x);
++x;
printf("local x in useLocal is %p before exiting useLocal\n", &x);
}
// useStaticLocal initializes static local variable x only the first time
// the function is called; value of x is saved between calls to this
// function
void useStaticLocal(void)
{
// initialized once
static int x = 50;
printf("\nlocal static x is %p on entering useStaticLocal\n", &x);
++x;
printf("local static x is %p on exiting useStaticLocal\n", &x);
}
// function useGlobal modifies global variable x during each call
void useGlobal(void)
{
printf("\nglobal x is %p on entering useGlobal\n", &x);
x *= 10;
printf("global x is %p on exiting useGlobal\n", &x);
}
|
C
|
/***************************************************************
main.c
Program entrypoint.
***************************************************************/
#include <nusys.h>
#include "config.h"
#include "stages.h"
#include "assets.h"
/*********************************
Function Prototypes
*********************************/
static void callback_stage00(int callback_vsync);
static void callback_stage01(int callback_vsync);
static void callback_prenmi(void);
/*********************************
Globals
*********************************/
volatile int global_stage;
NUContData controller;
char texture[4096];
/*==============================
mainproc
Initializes the game
==============================*/
void mainproc(void * dummy)
{
// Start by selecting the proper television
switch(TV_TYPE)
{
case PAL:
osViSetMode(&osViModeTable[OS_VI_FPAL_LAN1]);
osViSetYScale(0.833);
nuPreNMIFuncSet((NUScPreNMIFunc)callback_prenmi);
break;
case MPAL:
osViSetMode(&osViModeTable[OS_VI_MPAL_LAN1]);
break;
default:
break;
}
// Initialize the game
nuGfxInit();
nuContInit();
debug_initialize();
global_stage = 0;
// Create a callback function for when the reset button is pressed
nuPreNMIFuncSet((NUScPreNMIFunc)callback_prenmi);
// Loop forever to keep the idle thread busy
while(1)
{
// If we had a stage change, then initialize it and set the callback function
switch (global_stage)
{
case 0:
stage00_init();
nuGfxFuncSet((NUGfxFunc)callback_stage00);
break;
case 1:
stage01_init();
nuGfxFuncSet((NUGfxFunc)callback_stage01);
break;
default:
break;
}
// Turn on the screen and reset the stage variable
nuGfxDisplayOn();
global_stage = -1;
// Spin until the stage changes
while (global_stage == -1)
;
// Turn off the screen and print that we're changing stage
debug_printf("Changing stage to %02d\n", global_stage);
nuGfxDisplayOff();
}
}
/*==============================
callback_stage00
Code that runs on the graphics thread for stage 00
@param The number of tasks left to execute
==============================*/
void callback_stage00(int callback_vsync)
{
// Update the stage
stage00_update();
// If the RCP ran out of drawing tasks, redraw the stage
if (callback_vsync < 1)
stage00_draw();
}
/*==============================
callback_stage01
Code that runs on the graphics thread for stage 01
@param The number of tasks left to execute
==============================*/
void callback_stage01(int callback_vsync)
{
// Update the stage
stage01_update();
// If the RCP ran out of drawing tasks, redraw the stage
if (callback_vsync < 1)
stage01_draw();
}
/*==============================
callback_prenmi
Code that runs when the reset button
is pressed. Exists to prevent crashing
when the reset button is pressed on PAL
systems.
==============================*/
void callback_prenmi(void)
{
nuGfxDisplayOff();
osViSetYScale(1);
}
|
C
|
/*
Matrix and vector definition
Copyright (C) 2009 Zdenek Tosner
This file is part of the SIMPSON General NMR Simulation Package
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Matrix definition and implementation. Data structure according to BLAS,
i.e. Column major. Vector is just a single column.
*/
#include <stdlib.h>
#include <stdio.h>
#include "complx.h"
#include "matrix_new.h"
/* this I keep for ease...
1-based vectors with the length saved in the 0-element */
int * int_vector(int len)
{
int * v;
v = (int*)malloc((len+1)*sizeof(int));
if (!v) {
fprintf(stderr,"Can not allocate int vector (%i)\n",len);
exit(1);
}
*(int*)v = len;
return v;
}
double * double_vector(int len)
{
double * v;
v = (double*)malloc((len+1)*sizeof(double));
if (!v) {
fprintf(stderr,"Can not allocate double vector (%i)\n",len);
exit(1);
}
*(int*)v = len;
return v;
}
complx * complx_vector(int len)
{
complx * v;
v = (complx*)malloc((len+1)*sizeof(complx));
if (!v) {
fprintf(stderr,"Can not allocate complx vector (%i)\n",len);
exit(1);
}
*(int*)v = len;
return v;
}
/* I would like to get rid of this but don't have time... */
complx ** complx_matrix(int nrow, int ncol)
{
int i;
complx **m;
m = (complx**)malloc(((nrow+1)*sizeof(complx*)));
if (!m) {
fprintf(stderr,"old complx_matrix error: unable to allocate pointers\n");
exit(1);
}
m[0] = (complx*)malloc(2*sizeof(int));
((int*)m[0])[0] = nrow;
((int*)m[0])[1] = ncol;
m[1] = (complx*)malloc(((nrow*ncol+1)*sizeof(complx)));
if (!m[1]) {
fprintf(stderr,"old complx_matrix error: unable to allocate matrix\n");
exit(1);
}
for (i=2; i<=nrow; i++) m[i] = m[i-1]+ncol;
return m;
}
void free_complx_matrix(complx** m)
{
free((char*)m[0]);
free((char*)m[1]);
free((char*)m);
}
void free_int_vector(int *v)
{
free((char*)v);
}
void free_double_vector(double *v)
{
free((char*)v);
}
void free_complx_vector(complx *v)
{
free((char*)v);
}
void m_zerov(complx * v)
{
memset(&v[1],0,LEN(v)*sizeof(complx));
}
/***
* complex
***/
mv_complx * complx_matrix_alloc(int rows, int cols)
{
mv_complx * obj;
obj = (mv_complx*)(malloc(sizeof(mv_complx)));
obj->row = rows;
obj->col = cols;
obj->data = (complx*)(malloc(rows*cols*sizeof(complx)));
if (!(obj->data)) {
fprintf(stderr,"Can not allocate complex matrix (%i x %i)\n",rows, cols);
exit(1);
}
return obj;
}
void complx_matrix_free(mv_complx * obj)
{
free((char*)(obj->data));
obj->row = obj->col = 0;
free((char*)obj);
}
mv_complx * complx_vector_alloc(int len)
{
mv_complx * obj;
obj = (mv_complx*)(malloc(sizeof(mv_complx)));
obj->col = 1;
obj->row = len;
obj->data = (complx*)(malloc(len*sizeof(complx)));
if (!(obj->data)) {
fprintf(stderr,"Can not allocate complex vector (%i)\n",len);
exit(1);
}
return obj;
}
void complx_vector_free(mv_complx * obj)
{
free((char*)(obj->data));
obj->row = obj->col = 0;
free((char*)obj);
}
/* is it good idea to have this 1-based??? */
void complx_put_elem(mv_complx * obj, int row, int col, complx z)
{
int k;
if ( (obj->row < row) || (obj->col < col) ) {
fprintf(stderr,"complx_put_elem error: wrong element indeces\n");
exit(1);
}
k = row-1 + (col-1)*(obj->row);
obj->data[k].re = z.re;
obj->data[k].im = z.im;
}
/* is it good idea to have this 1-based??? */
complx complx_get_elem(mv_complx * obj, int row, int col)
{
complx z;
if ( (obj->row < row) || (obj->col < col) ) {
fprintf(stderr,"complx_get_elem error: wrong element indeces\n");
exit(1);
}
z = obj->data[row-1 + (col-1)*(obj->row)];
return z;
}
/***
* double
*/
mv_double * double_matrix_alloc(int rows, int cols)
{
mv_double * obj;
obj = (mv_double*)(malloc(sizeof(mv_double)));
obj->row = rows;
obj->col = cols;
obj->data = (double*)(malloc(rows*cols*sizeof(double)));
if (!(obj->data)) {
fprintf(stderr,"Can not allocate double matrix (%i x %i)\n",rows, cols);
exit(1);
}
return obj;
}
void double_matrix_free(mv_double * obj)
{
free((char*)(obj->data));
obj->row = obj->col = 0;
free((char*)obj);
}
mv_double * double_vector_alloc(int len)
{
mv_double * obj;
obj = (mv_double*)(malloc(sizeof(mv_double)));
obj->col = 1;
obj->row = len;
obj->data = (double*)(malloc(len*sizeof(double)));
if (!(obj->data)) {
fprintf(stderr,"Can not allocate double vector (%i)\n",len);
exit(1);
}
return obj;
}
void double_vector_free(mv_double * obj)
{
free((char*)(obj->data));
obj->row = obj->col = 0;
free((char*)obj);
}
/* is it good idea to have this 1-based??? */
void double_put_elem(mv_double * obj, int row, int col, double z)
{
int k;
if ( (obj->row < row) || (obj->col < col) ) {
fprintf(stderr,"double_put_elem error: wrong element indeces\n");
exit(1);
}
k = row-1 + (col-1)*(obj->row);
obj->data[k] = z;
}
/* is it good idea to have this 1-based??? */
double double_get_elem(mv_double * obj, int row, int col)
{
double z;
if ( (obj->row < row) || (obj->col < col) ) {
fprintf(stderr,"double_get_elem error: wrong element indeces\n");
exit(1);
}
z = obj->data[row-1 + (col-1)*(obj->row)];
return z;
}
/* is it good idea to have this 1-based??? */
double * dm_row(mv_double *obj, int row)
{
double *res, *sl1, *sl2;
int i, Nr, Nc;
Nr = obj->row;
if ( row > Nr ) {
fprintf(stderr,"dm_row error: row out of obj. size\n");
exit(1);
}
Nc = obj->col;
res = (double*)malloc(Nc*sizeof(double));
sl1 = res;
sl2 = obj->data + row-1;
for (i=0; i<Nc; i++) {
*sl1 = *sl2;
sl1++;
sl2 += Nr;
}
return res;
}
/* is it good idea to have this 1-based??? */
double * dm_col(mv_double *obj, int col)
{
double *res;
int N;
if (col > obj->col) {
fprintf(stderr,"dm_col error: col out of obj. range\n");
exit(1);
}
N = obj->row;
res = (double*)malloc(N*sizeof(double));
memcpy(res,obj->data+N*(col-1),N*sizeof(double));
return res;
}
/***
* float is missing here...
***/
/***
* int
*/
mv_int * int_matrix_alloc(int rows, int cols)
{
mv_int * obj;
obj = (mv_int*)(malloc(sizeof(mv_int)));
obj->row = rows;
obj->col = cols;
obj->data = (int*)(malloc(rows*cols*sizeof(int)));
if (!(obj->data)) {
fprintf(stderr,"Can not allocate int matrix (%i x %i)\n",rows, cols);
exit(1);
}
return obj;
}
void int_matrix_free(mv_int * obj)
{
free((char*)(obj->data));
obj->row = obj->col = 0;
free((char*)obj);
}
mv_int * int_vector_alloc(int len)
{
mv_int * obj;
obj = (mv_int*)(malloc(sizeof(mv_int)));
obj->col = 1;
obj->row = len;
obj->data = (int*)(malloc(len*sizeof(int)));
if (!(obj->data)) {
fprintf(stderr,"Can not allocate int vector (%i)\n",len);
exit(1);
}
return obj;
}
void int_vector_free(mv_int * obj)
{
free((char*)(obj->data));
obj->row = obj->col = 0;
free((char*)obj);
}
/* is it good idea to have this 1-based??? */
void int_put_elem(mv_int * obj, int row, int col, int z)
{
int k;
if ( (obj->row < row) || (obj->col < col) ) {
fprintf(stderr,"int_put_elem error: wrong element indeces\n");
exit(1);
}
k = row-1 + (col-1)*(obj->row);
obj->data[k] = z;
}
/* is it good idea to have this 1-based??? */
int int_get_elem(mv_int * obj, int row, int col)
{
int z;
if ( (obj->row < row) || (obj->col < col) ) {
fprintf(stderr,"int_get_elem error: wrong element indeces\n");
exit(1);
}
z = obj->data[row-1 + (col-1)*(obj->row)];
return z;
}
|
C
|
#include "http.h"
#include <stdio.h>
#include <string.h>
#include "vector.h"
/**
* @brief splits path into fields
*
* @param path the path to be split
* @param identifier the identifier to split
* @return char** vector of strings
*/
char **path2vec(char *path, char *identifier) {
char **vec = NULL;
char *token = strtok(path, identifier);
while (token != NULL) {
vector_push_back(vec, token);
token = strtok(NULL, identifier);
}
return vec;
}
/**
* @brief HTTP error 400
*
* @param ctx CGI context
* @return int success value
*/
int bad_request(struct CgiContext *ctx) {
printf("Status: 400 Bad Request\r\n");
printf("Content-Type: text/html\r\n\r\n");
printf("<h1>Bad Request</h1>\n");
printf("Bad request\n");
printf("The requested URL is badly formed.\n");
return 0;
}
/**
* @brief HTTP error 404
*
* @param ctx CGI context
* @return int success value
*/
int not_found(struct CgiContext *ctx) {
printf("Status: 404 Not Found\r\n");
printf("Content-Type: text/html\r\n\r\n");
printf("<h1>Not Found</h1>\n");
printf("Not Found\n");
printf("The requested URL %s was not found on this server.\n", ctx->path);
return 0;
}
/**
* @brief HTTP error 403
*
* @param ctx CGI context
* @return int success value
*/
int forbidden(struct CgiContext *ctx) {
printf("Status: 403 Forbidden\r\n");
printf("Content-Type: text/html\r\n\r\n");
printf("<h1>Forbidden</h1>\n");
printf("The requested URL %s was forbidden.\n", ctx->path);
;
return 0;
}
/**
* @brief HTTP error 406
*
* @param ctx CGI context
* @return int success value
*/
int not_acceptable(struct CgiContext *ctx) {
printf("Status: 406 Not Acceptable\r\n");
printf("Content-Type: text/html\r\n\r\n");
printf("<h1>Not Acceptable</h1>\n");
printf("Not Acceptable\n");
return 0;
}
/**
* @brief HTTP error 500
*
* @param ctx CGI context
* @return int success value
*/
int internal_server_error(struct CgiContext *ctx) {
printf("Status: 500 Internal Server Error\r\n");
printf("Content-Type: text/html\r\n\r\n");
printf("<h1>Internal server error</h1>\n");
return 0;
}
/**
* @brief HTTP error 501
*
* @param ctx CGI context
* @return int success value
*/
int not_implemented(struct CgiContext *ctx) {
printf("Status: 501 Not Implemented\r\n");
printf("Content-Type: text/html\r\n\r\n");
printf("<h1>Not Implemented</h1>");
return 0;
}
/**
* Prints the content type and charset
*/
void content_type_json() {
printf("Content-Type: application/yang-data+json;charset=utf-8;\n");
}
/**
* prints the characters to end the header
*/
void headers_end() { printf("\n\n"); }
int is_OPTIONS(const char* method) {
return strcmp(method, "OPTIONS") == 0;
}
int is_GET(const char* method) {
return strcmp(method, "GET") == 0;
}
int is_HEAD(const char* method) {
return strcmp(method, "HEAD") == 0;
}
int is_POST(const char* method) {
return strcmp(method, "POST") == 0;
}
int is_DELETE(const char* method) {
return strcmp(method, "DELETE") == 0;
}
int is_PUT(const char* method) {
return strcmp(method, "PUT") == 0;
}
|
C
|
/*
* Stack Min: Design a stack that returns the min value in O(1)
*/
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
/* Define the structure for the stack */
struct Stack {
int *arr;
int top;
int size;
/*
* The idea is that for every "top"
* keep a track of the min value in the elements
* below it
*/
int *min; //This holds the minimum value
int min_value; //The overall minimum value
};
/* Initialize the stack */
struct Stack* stackInit(int size) {
struct Stack* stack = malloc(sizeof(struct Stack));
int i = 0;
stack->size = size;
stack->top = -1;
stack->arr = malloc(sizeof(int) * size);
stack->min = malloc(sizeof(int) * size);
for(i=0; i<size; i++) {
stack->min[i] = 618618;
}
stack->min_value = 618618;
return stack;
}
/* Check if the stack is full */
bool isStackFull(struct Stack* stack) {
return (stack->top >= stack->size);
}
/* Check of the stack is empty */
bool isStackEmpty(struct Stack* stack) {
return (stack->top < 0);
}
/* Push an element onto the stack */
void Push(struct Stack* stack, int item) {
if(isStackFull(stack)) {
printf("Overflow\n");
return;
}
/* Increment the top and then push */
stack->top++;
printf("Inserting %d at %d\n", item, stack->top);
stack->arr[stack->top] = item;
/* Check that the value is smaller than the min */
if(item<stack->min_value) {
stack->min_value = item;
}
stack->min[stack->top] = stack->min_value;
printf("Min value is %d and stac->min[%d] is %d\n", stack->min_value, stack->top, stack->min[stack->top]);
}
/* Pop and return element from the stack */
int Pop(struct Stack* stack) {
if(isStackEmpty(stack)) {
printf("Underflow\n");
return -777;
}
int pop_item = -1;
/* pop the item and then decrement the top */
pop_item = stack->arr[stack->top--];
return pop_item;
}
/* Print the stack elements */
void printer(struct Stack* stack) {
int topper = stack->top;
int i = 0;
if(stack->top == -1) {
printf("The stack is empty\n");
return;
}
printf("Top is %d\n", topper);
for(i=0;i<=topper;i++)
printf("%d\n", stack->arr[i]);
}
/* Return the minimum value */
int minValue(struct Stack* stack) {
int min_value = stack->min[stack->top];
return min_value;
}
int main() {
struct Stack* stack = NULL;
int popper = 0;
int min_value = 0;
/* Init the stack */
stack = stackInit(5);
/* Push Elements into the stack */
Push(stack, 5);
Push(stack, 2);
Push(stack, 3);
Push(stack, 2);
Push(stack, 1);
printer(stack);
/* Get the minimum value on the stack */
min_value = minValue(stack);
printf("The minumum value is %d\n", min_value);
// Pop from the stack
popper = Pop(stack);
printf("popped %d from the stack \n", popper);
popper = Pop(stack);
printf("popped %d from the stack \n", popper);
/* Get the minimum value on the stack */
min_value = minValue(stack);
printf("The minumum value is %d\n", min_value);
printer(stack);
return 0;
}
|
C
|
#include <stdio.h>
// control structures part 3
// loops
int main ()
{
int x =0;
int y = 0;
int z = 0;
while (x<3)
{
printf ("%d\n", x);
x++;
}
do
{
printf ("%d\n", y);
y++;
} while (y !=3);
for ( z = 0; z <3; z++)
{
printf ("%d\n", z);
}
return 0;
}
|
C
|
#include <stdio.h>
#include <fcntl.h>
#include <string.h>
int main()
{
FILE *fp;
int fd;
char str[100] = "fdopen test string\n";
fd = open("fdopen.txt", O_RDONLY);
fp = fopen("fdopen.txt", "w");
if (fp == NULL)
return -1;
fwrite(str, strlen(str), 1, fp);
fclose(fp);
}
|
C
|
// C implementation of Radix Sort
#include<stdio.h>
#include<stdlib.h>
// This function gives maximum value in array[]
int getMax(int A[], int n)
{
int i;
int max = A[0];
for (i = 1; i < n; i++){
if (A[i] > max)
max = A[i];
}
return max;
}
// Main Radix Sort sort function
void radixSort(int A[], int n)
{
int i,digitPlace = 1;
int result[n]; // resulting array
// Find the largest number to know number of digits
int largestNum = getMax(A, n);
//we run loop until we reach the largest digit place
while(largestNum/digitPlace >0){
int count[10] = {0};
//Store the count of "keys" or digits in count[]
for (i = 0; i < n; i++)
count[ (A[i]/digitPlace)%10 ]++;
// Change count[i] so that count[i] now contains actual
// position of this digit in result[]
// Working similar to the counting sort algorithm
for (i = 1; i < 10; i++)
count[i] += count[i - 1];
// Build the resulting array
for (i = n - 1; i >= 0; i--)
{
result[count[ (A[i]/digitPlace)%10 ] - 1] = A[i];
count[ (A[i]/digitPlace)%10 ]--;
}
// Now main array A[] contains sorted
// numbers according to current digit place
for (i = 0; i < n; i++)
A[i] = result[i];
// Move to next digit place
digitPlace *= 10;
}
}
// Function to print an array
void printArray(int A[], int n)
{
int i;
for (i = 0; i < n; i++)
printf("%d ", A[i]);
printf("\n");
}
// Driver program to test above functions
int main()
{
int a[] = {209,3,48,91,66,101,30,795};
int n = sizeof(a)/sizeof(a[0]);
printf("Unsorted Array: ");
printArray(a, n);
radixSort(a, n);
printf("Sorted Array: ");
printArray(a, n);
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
unsigned int csrng() {
unsigned int number;
FILE* f = fopen("/dev/urandom", "r");
if (!f) {
printf("Could not open /dev/urandom!\n");
exit(1);
}
size_t read = fread(&number, 1, sizeof number, f);
if (read != sizeof number) {
printf("Could not read enough randomness!\n");
exit(1);
}
return number;
}
int is_interactive() {
unsigned int a, b, c;
a = csrng();
b = csrng();
printf("%u + %u = ", a, b);
fscanf(stdin, "%u", &c);
return a + b == c;
}
void print_flag() {
seteuid(0);
char flag[256];
FILE* f = fopen("/flag.txt", "r");
if (!f) {
printf("Could not open the flag file!\n");
exit(1);
}
size_t read = fread(flag, 1, sizeof flag, f);
flag[read] = (char) 0;
printf("%s\n", flag);
}
int main() {
setvbuf(stdin, NULL, _IONBF, 0);
setvbuf(stdout, NULL, _IONBF, 0);
setvbuf(stderr, NULL, _IONBF, 0);
if (is_interactive()) {
print_flag();
} else {
printf("Wrong!\n");
exit(1);
}
}
|
C
|
#pragma once
enum class DebugOutputLevel { DEBUG_OUTPUT_NONE, DEBUG_OUTPUT_PROGRESS, DEBUG_OUTPUT_DIAGNOSTIC, DEBUG_OUTPUT_WARNINGS };
struct Options
{
// number of threads to use
int num_threads;
// terminate recursive ray tracing at this depth and return Black
int max_ray_depth;
// use distribution tracing(trace diffuse rays)
bool use_distribution_tracing;
// Build and use the global photon map
bool use_photon_mapping;
// Number of photons to use when populating the global photon map
int global_photon_map_photon_count;
// Number of photons to use when sampling from the global photon map
int global_photon_map_sample_count;
// Maximum distance to sample photon map
double photon_map_max_sample_distance;
// Use the photon map to evaluate all rays
bool use_photon_map_approximation;
// Use the caustics photon map to evaluate all rays
bool use_caustics_photon_map_approximation;
// Build and use the photon map for caustics
bool use_caustics;
// Number of photons to use when populating the global photon map
int caustics_photon_map_photon_count;
// Number of photons to use when sampling from the caustics photon map
int caustics_photon_map_sample_count;
// Debug visualization of the caustics photon map
bool debug_caustics_photon_map;
// Number of rays to sample at each pixel
int num_samples;
// Maximum number of objects allowed per octtree node
unsigned int max_objects_per_octtree_node;
DebugOutputLevel debugOutputLevel;
Options()
{
// Default values
num_threads = 1;
max_ray_depth = 10;
use_distribution_tracing = false;
use_photon_mapping = false;
global_photon_map_photon_count = 100000;
global_photon_map_sample_count = 500;
use_photon_map_approximation = false;
use_caustics_photon_map_approximation = false;
use_caustics = false;
caustics_photon_map_photon_count = 20000;
caustics_photon_map_sample_count = 20;
debug_caustics_photon_map = false;
photon_map_max_sample_distance = 0.3;
num_samples = 100;
max_objects_per_octtree_node = 10;
debugOutputLevel = DebugOutputLevel::DEBUG_OUTPUT_PROGRESS;
}
};
extern Options global_options;
|
C
|
/** @file test_macros.h
* @brief
*
* @author
* @bug
* @date 17-Feb-2019
*/
#ifndef TEST_MACROS_H
#define TEST_MACROS_H
#ifdef __cplusplus
extern "C" {
#endif
#include <stdint.h>
#include <stddef.h>
#include <limits.h>
#include <stdio.h>
#define TEST_FAILED(X, Y) \
do { \
printf("Test #%zu failed at line %d, file %s with RESULT = %s.\n", (X), \
__LINE__, __FILE__, (Y)); \
} while (0);
#define TEST_PASSED(X) \
do { \
printf("Test #%zu passed.\n", (X)); \
} while (0);
#ifdef __cplusplus
}
#endif
#endif // TEST_MACROS_H
|
C
|
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
main() {
int ile,fd;
char nazwa[14];
printf("Podaj nazwe pliku do utworzenia: "); scanf("%s",nazwa);
if ((fd=creat(nazwa,S_IRWXU))==-1)
printf("Utworzenie pliku %s nie powiodlo sie\n",nazwa);
else
printf("Plik %s utworzono poprawnie, deskryptor %d\n",nazwa,fd);
if ((ile=write(fd,"Ala ma kota\n",12))==-1)
printf("Zapisu do pliku %s nie dokonano\n",nazwa);
else{
printf("Do pliku %s zapisano %d znakow\n",nazwa,ile);
}
close(fd);
}
|
C
|
// calcula e soma 2 valores
#include <stdio.h>
#include <stdlib.h>
int main()
{
/* exemplo1 IF ELSE
int val1, val2, soma;
printf("digite o primeiro valor \n");
scanf("%d",&val1);
printf("digite o segundo valor \n");
scanf("%d",&val2);
if(val1 <0 || val2<0){
printf("\n erro: numero negativo");
}
else{
soma = val1 + val2;
printf("resultado da soma: %d",soma);
}
*/
// exemplo2 WHILE
//inicializar as variaveis
/*
int val1 = -1;
int val2 = -1;
int soma;
//antes do uso
while( val1 <=0 || val2 <= 0){
printf("digite o primeiro valor \n");
scanf("%d",&val1);
printf("digite o segundo valor \n");
scanf("%d",&val2);
}
soma = val1 + val2;
printf("resultado da soma: %d",soma);
*/
// exemplo3 DO WHILE
int val1 ;
int val2;
int soma;
do{
printf("digite o primeiro valor \n");
scanf("%d",&val1);
printf("digite o segundo valor \n");
scanf("%d",&val2);
}
while( val1 <=0 || val2 <= 0);
soma = val1 + val2;
printf("resultado da soma: %d",soma);
return 0;
}
|
C
|
/**
* Name: Eyal Cohen.
**/
#include <stdio.h>
#include <string.h>
#include<stdlib.h>
#include<unistd.h>
#include<sys/types.h>
#include<sys/wait.h>
#include<signal.h>
#define BG "&"
#define AMPERSENT "&"
#define BUFF_SIZED 1500
#define SPACE " "
#define NUM_ELEMENTS 512
#define NUM_COMMANDS 3
#define NUM_JOBS 512
#define TRUE 1
typedef struct {
int id;
char string_command[NUM_ELEMENTS];
} Job;
/**
* parse the input to after parsed array.
* @param input to parse
* @param after_parsed save the parsed with space.
*/
void stringParser(char *input, char **after_parsed, int *size) {
char delimeter[2] = SPACE;
int local_size = 0;
/* get the first token */
char *token = strtok(input, delimeter);
while (token != NULL) {
after_parsed[local_size] = (char *) malloc((sizeof(char) * strlen(token)) + 1);
strcpy(after_parsed[local_size], token);
local_size++;
token = strtok(NULL, delimeter);
}
after_parsed[local_size - 1] = strtok(after_parsed[local_size - 1], "\n");
/* remove the last space */
*size = local_size;
}
/**
* get jobs array and print all the jobs that still running.
* @param jobs array of jobs.
* @param capacity of the array.
*/
void printJobs(Job *jobs, int capacity) {
for (int i = 0; i < capacity; ++i) {
printf("%d %s\n", jobs[i].id, jobs[i].string_command);
}
}
/**
* init a new job by parameters and add it to the jobs array.
* @param pid of the job.
* @param string_command string of the job;
* @param jobs the array of the jobs.
* @param capacity
*/
void addJob(int pid, char *string_command, Job *jobs, int *capacity) {
int current_capacity = *capacity;
Job job;
job.id = pid;
// clean the "&" at the end.
char *current_command = strtok(string_command, AMPERSENT);
strcpy(job.string_command, current_command);
jobs[current_capacity] = job;
++current_capacity;
*capacity = current_capacity;
}
/**
* delete all jobs that are done.
* @param jobs array of jobs.
* @param capacity size of capacity.
*/
void deleteDeadJobs(Job *jobs, int *capacity) {
int terminated_pid;
int status;
int current_capacity = *capacity;
//find element and switch it with the last, equal to delete it.
for (int i = 0; i < current_capacity; ++i) {
//find the id in the array.
terminated_pid = waitpid(jobs[i].id, &status, WNOHANG);
if (jobs[i].id == terminated_pid) {
//edge case when we need to delete last element
if (i != current_capacity - 1) {
jobs[i] = jobs[current_capacity - 1];
}
--current_capacity;
*capacity = current_capacity;
} else if (terminated_pid == -1) {
printf("error in reading child process status");
}
}
}
void executeJobCommand(Job *jobs, int *capacity) {
deleteDeadJobs(jobs, capacity);
printJobs(jobs, *capacity);
}
/**
* Get parsered array and delete the aloccated strings in it.
* @param parse words.
* @param size size of array.
*/
void freeParsered(char **parse, int size) {
for (int i = 0; i < size; ++i) {
free(parse[i]);
parse[i] = NULL;
}
}
/**
* get the input command and save.
* @param buffer to get input to.
* @return 1 if succeed
*/
int getInput(char *buffer) {
printf("> ");
fgets(buffer, BUFF_SIZED, stdin);
if (buffer[0] == '\n') getInput(buffer);
}
/**
* execute the parsered command with execvp
* @param parsed input, first arg is the name of the command, others are the parameters.
*/
void executeRegularCommand(char *buffer, char **parsed, int *size, Job *jobs, int *job_capacity) {
// current size.
int local_size = (*size);
int back_ground = 0;
if (strcmp(parsed[local_size - 1], BG) == 0) {
parsed[local_size - 1] = NULL;
back_ground = 1;
}
// Forking a new child.
pid_t pid = fork();
// check if fork failed.
if (pid == -1) {
printf("Failed to forked the child\n");
return;
} else if (pid == 0) {
// only the child will be here.
if (execvp(parsed[0], parsed) < 0) {
fprintf(stderr, "Error in system call\n");
}
freeParsered(parsed, *size);
exit(0);
} else {
// father waiting for child to terminate
printf("%d\n", pid);
if (back_ground) {
addJob(pid, buffer, jobs, job_capacity);
} else {
wait(NULL);
}
return;
}
}
/**
* init the command array.
* @param command_array to init.
*/
void initCommandArray(char **command_array) {
command_array[0] = "cd";
command_array[1] = "exit";
command_array[2] = "jobs";
}
/**
* check if the command is a special command. return 1 if it does.
* @param command_array to check the command from.
* @param parsed parsered line.
* @return 1 if special 0 otherwise.
*/
int isSpecialCommand(char **command_array, char **parsed) {
char *command_name = parsed[0];
for (int i = 0; i < NUM_COMMANDS; ++i) {
if (strcmp(command_name, command_array[i]) == 0) {
return 1;
}
}
return 0;
}
/**
* execute command, spacial or regular.
* @param parsed line parsered.
* @param size of the parsered line.
* @param Job jobs array.
* @param jobs_capacity pointer to the capacity.
*/
void executeSpecialCommand(char **parsed, int *size, Job *jobs, int *jobs_capacity, char **command_array) {
// choose of the spacial command if it is.
int choose = 0;
// spacial command array.
// name of command
char *command_name = parsed[0];
for (int i = 0; i < NUM_COMMANDS; ++i) {
if (strcmp(command_name, command_array[i]) == 0) {
choose = i + 1;
break;
}
}
switch (choose) {
case 1:
//edge cases for different cases.
if (parsed[1] == NULL) {
chdir(getenv("HOME"));
} else if (strcmp(parsed[1], "~") == 0) {
chdir(getenv("HOME"));
} else if (chdir(parsed[1]) == -1) {
fprintf(stderr, "Error in system call\n");
}
printf("%d\n", getpid());
break;
case 2:
freeParsered(parsed, *size);
printf("%d\n", getpid());
int jobs_size = *jobs_capacity;
// kill the children running processes
for (int i = 0; i < jobs_size; ++i) {
int terminated_pid = waitpid(jobs[i].id, NULL, WNOHANG);
if (terminated_pid == 0) {
kill(jobs[i].id, SIGKILL);
}
}
exit(0);
case 3:
executeJobCommand(jobs, jobs_capacity);
default:
// executeRegularCommand(parsed, size);
break;
}
}
/**
* print all the parsered words.
* @param parse lines.
* @param size of the parsered array.
*/
void printParsered(char **parse, int size) {
for (int i = 0; i < size; ++i) {
printf("%s\n", parse[i]);
}
}
int main() {
Job jobs[NUM_JOBS];
int jobs_capacity = 0;
char *command_array[NUM_COMMANDS];
initCommandArray(command_array);
while (TRUE) {
int size = 0;
char *parsed[NUM_ELEMENTS];
char buffer[NUM_JOBS];
getInput(buffer);
char *buffer_copy = (char *) malloc(sizeof(char) * strlen(buffer) + 1);
strcpy(buffer_copy, buffer);
stringParser(buffer, parsed, &size);
// check whether is special command or regular and execute the kind of command.
if (isSpecialCommand(command_array, parsed)) {
executeSpecialCommand(parsed, &size, jobs, &jobs_capacity, command_array);
} else {
// do regular command.
executeRegularCommand(buffer_copy, parsed, &size, jobs, &jobs_capacity);
}
freeParsered(parsed, size);
free(buffer_copy);
buffer_copy = NULL;
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.