language
large_stringclasses 1
value | text
stringlengths 9
2.95M
|
---|---|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
#define BUFSIZE 1024
char buf[BUFSIZE];
int main(int argc, char **argv)
{
int ret = -1;
FILE *bin = 0;
FILE *out = 0;
char *name = 0;
if (argc != 4) goto cleanup;
out = fopen(argv[1], "w");
if (!out) goto cleanup;
name = argv[2];
bin = fopen(argv[3], "rb");
if (!bin) goto cleanup;
uint16_t load;
int c;
if ((c = fgetc(bin)) < 0) goto cleanup;
load = (unsigned char) c;
if ((c = fgetc(bin)) < 0) goto cleanup;
load |= ((unsigned char)c << 8);
fprintf(out, "#include <stdint.h>\n\n"
"static const uint16_t %s_load = 0x%04x;\n"
"static const uint8_t %s[] = {", name, (unsigned)load, name);
int first = 1;
size_t b;
while ((b = fread(buf, 1, BUFSIZE, bin)))
{
for (size_t i = 0; i < b; ++i)
{
if (!first) fputc(',', out);
first = 0;
fprintf(out, "0x%02x", (uint8_t)buf[i]);
}
}
fputs("};\n", out);
ret = 0;
cleanup:
if (bin) fclose(bin);
if (out) fclose(out);
return ret;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
int pedirOpcionesMenu(char texto[]);
int main()
{
int opcion;
char seguir = 's';
do
{
opcion = pedirOpcionesMenu("1. suma \n 2. Baja \n 3. restar: \n 4. Informes: \n 5. Salir: \n Elija una opcion: \n");
switch(opcion)
{
case 1:
printf("estoy dando de alta \n");
break;
case 2:
printf("estoy dando de baja \n");
break;
case 3:
printf("estoy modificando \n");
break;
case 4:
printf("estoy informando \n");
break;
case 5:
seguir = 'n';
break;
default:
printf("opcion icorrecta \n");
break;
}
system("pause");
system("cls");
}while(seguir == 's');
return 0;
}
int pedirOpcionesMenu(char texto[])
{
int opcion;
printf("%s", texto);
scanf("%d", &opcion);
return opcion;
}
/*
a = x
x luego va a ser reemplazado por el numero
*/
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include "Employee.h"
#include "parser.h"
#include "controller.h"
#include "input.h"
#include "LinkedList.h"
int main()
{
int opcion= 0;
int flag=0;
LinkedList* listaEmpleados = ll_newLinkedList();
opcion=menu();
do{
switch(opcion)
{
case 1:
system("cls");
if (flag == 1){
printf ("\n\nSolo se puede cargar una vez\n\n");
}else{
controller_loadFromText("data.csv",listaEmpleados);
}
flag = 1;
break;
case 2:
system("cls");
if (flag == 1){
printf ("\n\nSolo se puede cargar una vez\n\n");
}else{
//controller_loadFromBinary("bin.dat",listaEmpleados);
}
flag = 1;
break;
case 3:
if (flag == 1){
system("cls");
//controller_addEmployee(listaEmpleados);
}
break;
case 4:
if (flag == 1){
system("cls");
//controller_editEmployee(listaEmpleados);
}
break;
case 5:
if (flag == 1){
system("cls");
// controller_removeEmployee(listaEmpleados);
}
break;
case 6:
if (flag == 1){
system("cls");
controller_ListEmployee(listaEmpleados);
system("pause");
system("cls");
}
break;
case 7:
system("cls");
// controller_sortEmployee(listaEmpleados);
break;
case 8:
system("cls");
controller_saveAsText("data.csv", listaEmpleados);
break;
case 9:
system("cls");
controller_saveAsBinary("bin.dat",listaEmpleados);
break;
case 10:
system("cls");
//controller_saveAsTexTo("data.txt",listaEmpleados);
controller_saveAstxt("data.txt", listaEmpleados);
break;
}
opcion = menu();
}while(opcion != 11);
return 0;
}
|
C
|
/*********************************************************************
Thanks to Adafruit for their GFX and SSD1306 libraries
*********************************************************************/
#include "Adafruit_GFX.h"
#include "Adafruit_SSD1306.h"
Adafruit_SSD1306 display(-1);
#define FONT_SIZE 4
#define EEPROM_ADDR 0x00
#define AM_PM_FORMAT 0x00
#define HR_FORMAT 0x01
#define DISPLAY_I2C_ADDR 0x3C
bool flag = FALSE;
int timeHour, timeMin, timeSec, timeNow, timeInPreviousReading, timeFormat;
/* These must be of int type if we want to use Particle.variable function */
int backupVariable;
int watchMode(String cmd);
void setTimeZoneIndia(void);
void setTimeZoneGlobal(uint8_t value);
void setup()
{
/* Expose internal variables */
Particle.variable("Hour", timeHour);
Particle.variable("Minute", timeMin);
Particle.variable("Second", timeSec);
Particle.variable("TimeFormat", backupVariable);
/* Expose function to set 12h or 24H mode from the APP or Web Console */
Particle.function("WatchMode", watchMode);
/* Initialize the display */
display.begin(SSD1306_SWITCHCAPVCC, DISPLAY_I2C_ADDR);
/* Get data from the EEPROM and load into the structure */
EEPROM.get(EEPROM_ADDR, backupVariable);
/* if the value from the EEPROM is unexpected then update the EEPROM */
if((backupVariable != 1) && (backupVariable != 0))
{
backupVariable = 0;
EEPROM.put(EEPROM_ADDR, backupVariable);
}
/* Set the time zone of India */
setTimeZoneIndia();
/* Disable the RGB LED's default function and control manually */
RGB.control(true);
RGB.color(0,0,20);
}
void loop()
{
timeNow = Time.now();
if(timeNow != timeInPreviousReading)
{
timeInPreviousReading = timeNow;
timeSec = Time.second(timeNow);
/* Draw lines to indicate seconds */
display.drawLine(4, 1, ((timeSec << 1) + 4), 1, WHITE);
display.drawLine(4, 3, ((timeSec << 1) + 4), 3, WHITE);
display.drawLine((124 - (timeSec << 1)), 61, 123, 61, WHITE);
display.drawLine((124 - (timeSec << 1)), 63, 123, 63, WHITE);
display.display();
}
if(timeMin != Time.minute(timeNow))
{
timeMin = Time.minute(timeNow);
timeHour = Time.hour(timeNow);
display.clearDisplay();
display.setTextSize(FONT_SIZE);
display.setTextColor(WHITE);
display.setCursor(0, 15);
display.println(Time.format("%H:%M"));
display.display();
}
}
/* Set to Indian time zone */
void setTimeZoneIndia(void)
{
/* India is +5.5Hrs from the UTC */
Time.zone(5.5);
}
/* Set to any other global time zone */
void setTimeZoneGlobal(uint8_t value)
{
Time.zone(value);
}
/* This function is called when the time mode
is change and the function is called */
int watchMode(String cmd)
{
/* Fill timeMin with some unexpected value to that
doesn't match with the value from Time.minute function
and therefore get's updated and printed on the display */
timeMin = 0xFF;
if((cmd == "12H") || (cmd == "12h") || (cmd == "12"))
{
/* Update the variable and store it in EEPROM */
backupVariable = AM_PM_FORMAT;
EEPROM.put(EEPROM_ADDR, backupVariable);
return 12;
}
else if((cmd == "24H") || (cmd == "24h") || (cmd == "24"))
{
backupVariable = HR_FORMAT;
EEPROM.put(EEPROM_ADDR, backupVariable);
return 24;
}
else
{
return 0;
}
}
|
C
|
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
void cutSticks(int * stick, int count){
//printf("started cutSticks\n");
int min = - 1;
int i = 0;
while(i < count){
if((stick[i] < min) || (min < 0)){
min = stick[i];
}
i++;
}
int sticks_left = count;
int cuts = 0;
int new_min = -1;
while(sticks_left > 0){
//printf("Cutting sticks...\n");
sticks_left = 0;
for(i=0;i < count; i++){
if(stick[i] > 0){
cuts++;
//printf("stick[i] bc: %d\n",stick[i]);
stick[i] -= min;
//printf("stick[i] ac: %d\n",stick[i]);
if(stick[i]>0){
//printf("sticks_left++\n");
sticks_left++;
if((new_min > stick[i]) || new_min < 0){
new_min = stick[i];
}
}
}
}
printf("%d\n",cuts);
cuts = 0;
min = new_min;
new_min = -1;
}
}
int main() {
int count;
scanf("%d",&count);
int stick[count];
int i = 0;
while(i<count){
scanf("%d",&stick[i]);
i++;
}
cutSticks(stick,count);
return 0;
}
|
C
|
#include <stdio.h>
extern void print_all(int n, char **s);
int main(int argc, char **argv) {
printf("hello world!\n");
print_all(argc,argv);
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
int main(void){
int i = 0;
char str[256];
int Character = getchar();
while(Character != EOF){
while(Character != '\n'){
str[i] = Character;
i++;
Character = getchar();
}
int j = i - 1;
while(j >= 0){
printf("%c", str[j]);
j--;
}
i = 0;
printf("\n");
Character = getchar();
}
}
|
C
|
/* System-wide header files. */
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include "wHeapUtil.h"
#include "wHeap.h"
#define TRUE 1
#define FALSE 0
#define HEAPSIZE 3
#define FILENAME 2
int insertRecord(FILE *inFile, File* heapFile, int pageSize)
{
int i,endOfFile = FALSE; /* EndOfFile = last line of data */
int pageCount =1; /* No. of page in heapfile */
char line[300]; /* Array for records read in */
char *tok; /* String tokening each fields */
Page *currentPage; /* Ptr of current page */
Record *page_records; /* Ptr of current array of records */
hrtime_t start;
hrtime_t tmp;
hrtime_t fin;
start = gethrtime();
while(!endOfFile) {
/* Allocate New record array to store records */
Record *new_page_records = (Record*)calloc(sizeof(Record),pageSize);
page_records = new_page_records;
for(i=0; i <pageSize; i++) {
if((fgets(line,300,inFile))==NULL) {
endOfFile = TRUE;
break;
}
/* Insert data retrieve from file to Record struct */
Record newRecord;
tok = strtok(line,DELIM);
strcpy(newRecord.NAME,tok);
tok = strtok(NULL, DELIM);
newRecord.RACE = atoi(tok);
tok = strtok(NULL, DELIM);
newRecord.CLASS = atoi(tok);
tok = strtok(NULL, DELIM);
newRecord.ID=atoi(tok);
tok = strtok(NULL, DELIM);
/* Check if field is empty */
if( tok != NULL) {
strcpy(newRecord.GUILD,tok);
}
else {
strcpy(newRecord.GUILD,"");
}
page_records[i] =newRecord;
}
/* Create new page */
currentPage = callocNewPage();
/* Attach record array to page */
currentPage->pageRecords =page_records;
/* Start extending page array from page2 onwards */
if(pageCount > 1) {
heapFile->page=reallocPages(heapFile->page,pageCount);
heapFile->pageCount++;
}
/* Assign the newly created page to page array */
heapFile->page[pageCount-1] = currentPage;
/* Increase page count */
pageCount++;
}
/* convert to millisecond */
tmp = (fin - start)*0.000001;
printf("time: %lld ms\n",tmp);
return 0;
}
int main(int argc, char** argv)
{
File heapFile; /* Heapfile */
FILE *inFile; /* Data_2011 */
FILE *outFile; /* Binary out file */
unsigned int pageSize; /* User define pagesize */
int i;
/* check for arguments */
if(argc !=4) {
printf("Invalid number of input argument \n");
exit(EXIT_FAILURE);
}
/* Open file for reading */
if((inFile=fopen(argv[1],"r"))==NULL) {
printf("cannot open textfile \n");
exit(EXIT_FAILURE);
}
/* init page size */
pageSize = atoi(argv[HEAPSIZE]);
/* Init pages array for heapfile*/
mallocPages(&heapFile);
/* Read in data and load into heap memory */
insertRecord(inFile,&heapFile,pageSize);
fclose(inFile);
/* Create binary file */
if((outFile=fopen(argv[FILENAME],"wb"))==NULL) {
printf("cannot write binary file\n");
exit(EXIT_FAILURE);
}
#if 0
Record retrieve = (Record)heapFile.page[0]->pageRecords[0];
printf("%s",retrieve.NAME);
#endif
/* Write out 1 page per loop */
for(i =0; i < heapFile.pageCount; i++) {
fwrite(heapFile.page[i]->pageRecords,sizeof(Record),pageSize,outFile);
}
fclose(outFile);
for(i =0; i < heapFile.pageCount; i++) {
/* Free records array */
free(heapFile.page[i]->pageRecords);
/* Free page */
free(heapFile.page[i]);
}
/* Free pages pointers */
free(heapFile.page);
exit(EXIT_SUCCESS);
}
|
C
|
#include<stdio.h>
int main()
{
int a[10][10],i,j,n,m;
float avg,sum=0;
scanf("%d",&n);
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
scanf("%d",&a[i][j]);
}
}
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
sum=sum+a[i][j];
}
}
m=n*n;
avg=sum/m;
printf("%f",avg);
return 0;
}
|
C
|
#include "population.h"
//creates a new population of genes and stores them in head_population
void createPop(){
//initialize headpointer
head_population=(popptr)malloc(sizeof(struct population));
head_population->n=0;
popptr h1=head_population;
//create genes
for(int i=0;i<NO_POP;i++){
printf("\nCreating Gene:%d",i);
geneptr t1=create_gene();
generate_random_containers(t1);
first_fit(t1);
fitness(t1);
integrity_all_containers(t1);
addGene(h1,t1);
printStats(t1);
printf("\n\nFinished creating Gene:%d\n",i);
}
printBestGene(h1);
}
//generates random combinations of containers and stores them in gene->test_containers.
void generate_random_containers(geneptr t1){
int i=0;
int n=CNT_SIZE;
int check_bucket[n];
while(i<n){
check_bucket[i]=0;
i++;
}
i=0;
int max_no_of_random_tries=CNT_SIZE/2;
while(i<n){
int ran=(rand()%n);
int tries=0;
while(check_bucket[ran]!=0){
ran=(rand()%n);
if( tries > max_no_of_random_tries ){
for(int j = 0 ; j < n ; j++){
if( check_bucket[j] == 0 ){
ran=j;
break;
}
}
}
tries++;
}
t1->test_containers[i]=ran;
check_bucket[ran]=1;
//printf("\n%d added in test_containers\n",ran);
i++;
}
}
void elitism(popptr h1){
geneptr gene_list[ELITISM_COUNT];
for(int i=0;i<ELITISM_COUNT;i++){
geneptr best_gene=searchBestGeneUtlz(h1);
gene_list[i]=createCopyGene(best_gene);
fitness1(gene_list[i]);
removeGene(h1,best_gene);
}
emptyPopulation(h1);
for(int i=0;i<ELITISM_COUNT;i++){
addGene(h1,gene_list[i]);
}
}
void emptyPopulation(popptr h1){
for(int i=0;i<h1->n;i++){
free(h1->gene_list[i]);
h1->gene_list[i]=NULL;
}
h1->n=0;
}
|
C
|
/*
* File: main.c
* Author: Igor de Souza Rosler
*
* Created on 3 de Abril de 2019, 10:50
*/
#include <stdio.h>
#include <stdlib.h>
typedef struct grafo {
int eh_ponderado; // Indica se o grafo é ou não ponderado
int grau_max; // Indica o grau máximo que cada vértice pode possuir
int num_vertices; // Quantidade total de vértices
int** arestas; // Matriz de arestas
float** pesos; // Matriz dos pesos das arestas
int* grau; // Grau contido em cada vértice
} Grafo;
Grafo* cria_grafo(int num_vertices, int grau_max, int eh_ponderado);
int inserir_aresta(Grafo* gr, int orig, int dest, int eh_digrafo, float peso);
void liberar_grafo(Grafo* gr);
int procura_menor_distancia(float* dist, int* visitado, int nv);
void menor_caminho(Grafo* gr, int ini, int* ant, float* dist);
void alg_guloso(Grafo *gr, int ini, int* ant, float* dist);
int menor_guloso(Grafo* gr, int ini, int* visitado);
int main() {
//int num_vertices, grau_max, eh_ponderado, inserir, orig, dest, eh_digrafo;
int v_origem, v_destino, aux;
float peso = 1.0;
Grafo *gr;
/*printf("Digite a quantidade de vertices do grafo: ");
scanf("%d", &num_vertices);
printf("Digite a quantidade maxima de arestas que os vertices podem ter: ");
scanf("%d", &grau_max);
printf("O grafo e ponderado?(1 - SIM | 0 - NAO): ");
scanf("%d", &eh_ponderado);
gr = cria_grafo(num_vertices, grau_max, eh_ponderado);
printf("Inserir aresta(1 - SIM | 0 - NAO): ");
scanf("%d", &inserir);
inserir = (inserir != 1) ? 0 : 1; // Qualquer escolha diferente de 1 será considerado como alternativa 'NÃO'
do {
if (inserir) {
printf("Informe o vertice origem e o vertice de destino da aresta: ");
scanf("%d %d", &orig, &dest);
printf("O grafo e digrafo?(1 - SIM | 0 - NAO): ");
scanf("%d", &eh_digrafo);
eh_digrafo = (eh_digrafo != 1) ? 0 : 1; // Qualquer escolha diferente de 1 será considerado como alternativa 'NÃO'
if (eh_ponderado) {
printf("Informe o peso da aresta: ");
scanf("%f", &peso);
}
inserir_aresta(gr, orig, dest, eh_digrafo, peso);
printf("Inserir outra aresta(1 - SIM | 0 - NAO): ");
scanf("%d", &inserir);
inserir = (inserir != 1) ? 0 : 1; // Qualquer escolha diferente de 1 será considerado como alternativa 'NÃO'
}
} while (inserir);*/
gr = cria_grafo(4, 3, 1);
inserir_aresta(gr, 0, 1, 1, 3);
inserir_aresta(gr, 0, 2, 1, 2);
inserir_aresta(gr, 1, 3, 1, 2);
inserir_aresta(gr, 2, 1, 1, 2);
inserir_aresta(gr, 2, 3, 1, 3);
printf("\nInforme o vertice origem e o vertice destino para o calculo do menor caminho: ");
scanf("%d %d", &v_origem, &v_destino);
int v_anterior[gr->num_vertices];
float distancia[gr->num_vertices];
menor_caminho(gr, v_origem, v_anterior, distancia);
printf("\n---------- DIJKSTRA -----------");
printf("\nA menor distancia do vertice[%d] ate o vertice[%d] e: %.f", v_origem, v_destino, distancia[v_destino]);
printf("\nCaminho: ");
aux = v_anterior[v_destino];
while (aux != -1) {
printf("Vertice[%d]\t", aux);
aux = v_anterior[aux];
}
alg_guloso(gr, v_origem, v_anterior, distancia);
printf("\n\n---------- GULOSO -----------");
printf("\nA menor distancia do vertice[%d] ate o vertice[%d] e: %.f", v_origem, v_destino, distancia[v_destino]);
printf("\nCaminho: ");
aux = v_anterior[v_destino];
while (aux != -1) {
printf("Vertice[%d]\t", aux);
aux = v_anterior[aux];
}
liberar_grafo(gr);
return 0;
}
Grafo* cria_grafo(int num_vertices, int grau_max, int eh_ponderado) {
Grafo *gr = (Grafo *) malloc(sizeof (Grafo));
if (gr != NULL) {
int i;
gr->num_vertices = num_vertices;
gr->grau_max = grau_max;
gr->eh_ponderado = (eh_ponderado != 0) ? 1 : 0; // Estrutura simplificada para if(eh_ponderado != 0) então retorna 1 caso contrario 0
gr->grau = (int *) calloc(num_vertices, sizeof (int));
gr->arestas = (int **) malloc(num_vertices * sizeof (int *));
for (i = 0; i < num_vertices; i++) {
gr->arestas[i] = (int *) malloc(grau_max * sizeof (int));
}
gr->pesos = (float **) malloc(num_vertices * sizeof (float *));
for (i = 0; i < num_vertices; i++) {
gr->pesos[i] = (float *) malloc(grau_max * sizeof (float));
}
}
return gr;
}
void liberar_grafo(Grafo* gr) {
if (gr != NULL) {
int i;
for (i = 0; i < gr->num_vertices; i++) {
free(gr->arestas[i]);
}
free(gr->arestas);
for (i = 0; i < gr->num_vertices; i++) {
free(gr->pesos[i]);
free(gr->pesos);
}
free(gr->grau);
free(gr);
}
}
int inserir_aresta(Grafo* gr, int orig, int dest, int eh_digrafo, float peso) {
if (gr == NULL) return 0;
if (orig < 0 || orig >= gr->num_vertices) return 0;
if (dest < 0 || dest >= gr->num_vertices) return 0;
gr->arestas[orig][gr->grau[orig]] = dest;
gr->pesos[orig][gr->grau[orig]] = peso;
gr->grau[orig]++;
if (eh_digrafo == 0) { // 1 - Indica que é dígrafo (direcional) / 0 - Indica que não é digrafo (não direcinado)
inserir_aresta(gr, dest, orig, 1, peso);
}
return 1;
}
void menor_caminho(Grafo* gr, int ini, int* ant, float* dist) {
int i, cont, nv, ind, *visitado, u;
cont = nv = gr->num_vertices;
visitado = (int*) malloc(nv * sizeof (int));
for (i = 0; i < nv; i++) { // Inicialização
ant[i] = -1;
dist[i] = -1;
visitado[i] = 0;
}
dist[ini] = 0;
while (cont > 0) {
u = procura_menor_distancia(dist, visitado, nv);
if (u == -1)
break;
visitado[u] = 1;
cont--;
for (i = 0; i < gr->grau[u]; i++) {
ind = gr->arestas[u][i];
if (dist[ind] < 0) {
dist[ind] = dist[u] + gr->pesos[u][i];
ant[ind] = u;
} else {
if (dist[ind] > dist[u] + gr->pesos[u][i]) {
dist[ind] = dist[u] + gr->pesos[u][i];
ant[ind] = u;
}
}
}
}
free(visitado);
}
int procura_menor_distancia(float* dist, int* visitado, int nv) {
int i, menor = -1, primeiro = 1;
for (i = 0; i < nv; i++) {
if (dist[i] >= 0 && visitado[i] == 0) {
if (primeiro) {
menor = i;
primeiro = 0;
} else {
if (dist[menor] > dist[i])
menor = i;
}
}
}
return menor;
}
void alg_guloso(Grafo* gr, int ini, int *ant, float* dist) {
int i, prox = ini, cont, u;
int *visitado;
cont = gr->num_vertices;
visitado = (int *) malloc(gr->num_vertices * sizeof (int));
for (i = 0; i < gr->num_vertices; i++) {
ant[i] = -1;
dist[i] = -1;
visitado[i] = 0;
}
visitado[ini] = 1;
dist[ini] = 0;
while (cont > 0) {
u = menor_guloso(gr, ini, visitado);
if (u == -1) break;
prox = gr->arestas[ini][u];
ant[prox] = ini;
visitado[prox] = 1;
cont--;
if (gr->eh_ponderado) {
dist[prox] = dist[ant[prox]] + gr->pesos[ini][u];
} else {
dist[prox] = dist[ant[prox]] + 1;
}
ini = prox;
}
}
int menor_guloso(Grafo* gr, int ini, int* visitado) {
int i, menor_dist = 1, primeiro = 1, menor = -1;
for (i = 0; i < gr->grau[ini]; i++) {
if (primeiro) {
if (visitado[gr->arestas[ini][i]] != 1) {
menor_dist = gr->pesos[ini][i];
primeiro = 0;
menor = i;
}
} else if (menor_dist > gr->pesos[ini][i] && visitado[gr->arestas[ini][i]] != 1) {
menor = gr->pesos[ini][i];
menor = i;
}
}
return menor;
}
|
C
|
/*************************************/
/* Author : AHMED ASHRY */
/* DATE : 17 AUG 19 */
/* VERSION : 001 */
/*************************************/
/* HEADER FILE GUARDIAN */
#ifndef STD_TYPES_H_
#define STD_TYPES_H_
/* Defined Data Types */
/*type of unsigned 8 bits */
typedef unsigned char uint8;
/*type of unsigned 16 bits */
typedef unsigned short int uint16;
/*type of unsigned 32 bits */
typedef unsigned long int uint32;
/*type of unsigned 64 bits */
typedef unsigned long long int uint64;
/*type of signed 8 bits */
typedef signed char sint8;
/*type of signed 16 bits */
typedef signed short int sint16;
/*type of signed 32 bits */
typedef signed long int sint32;
/*type of signed 64 bits */
typedef signed long int sint64;
#endif
|
C
|
/*
** EPITECH PROJECT, 2018
** str_to_tab
** File description:
** str_to_tab
*/
#include "n4s.h"
static int num_word(char *str, char charact)
{
int i = 0;
int nb = 0;
while (str[i] != '\0') {
while (str[i] == charact || str[i] == '\t')
i++;
if (str[i] != '\0')
nb++;
while (str[i] != charact && str[i] \
!= '\t' && str[i] != '\0')
i++;
}
return (nb);
}
static char **to_wordtab(char *str, char **tab, char charact, int num)
{
int j = 0;
int k;
for (int i = 0; str[i] != '\0' || j < num;) {
for (;str[i] == charact || str[i] == '\t'; i++);
if (str[i] == '\0') {
tab[j] = "\0";
j++;
} else {
tab[j] = malloc(sizeof(char) * ((my_strlen(str) + 1)));
if (tab[j] == NULL)
return (NULL);
k = 0;
while (str[i] != charact && str[i] != '\0' && str[i] != '\t')
tab[j][k++] = str[i++];
tab[j++][k] = '\0';
}
}
tab[j] = NULL;
return (tab);
}
char* *my_str_to_tab(char *str, char charact)
{
char **tab;
int num = num_word(str, charact);
if (num == 0)
num = 1;
tab = malloc(sizeof(char *) * num + 1);
if (tab == NULL)
return (NULL);
tab = to_wordtab(str, tab, charact, num);
return (tab);
}
|
C
|
#include <stdio.h>
void f(int a,int b)
{
if(a>b)
return;
if(a%2==1)
{
printf("%d ",a);
}
f(++a,b);
}
int main()
{
int n,k;
scanf("%d %d",&n,&k);
f(n,k);
}
|
C
|
#pragma once
#define s_buffer 256
#define b_buffer 1024
bool fly_gra = false; // fly/gravety = false // Default makes flying / no gravity imposible
bool onc_wallz = false; // makes it so you cannot go pass the broder +256x and -256x
void readInput(string in) {
if (in == ".spawn") {
x = 1;
z = 1;
cout << "You Have Been moved to spawn!" << endl;
}
else if (in == ".moveToWallPositive") {
x = 255;
z = 1;
}
else if (in == ".moveToWallNegative") {
x = -255;
z = 1;
}
else if (in == ".cheat-fly") {
fly_gra = true;
}
else if (in == ".cheat-noclip") {
fly_gra = true;
onc_wallz = true;
}
else if (in == ".help") {
const char *syntax =
" * -------[Normal] Syntax------- // Nothing before syntax (For Example a dot)\n"
" * forward : walks forwards [f, forwards]\n"
" * backward : walks backwards [b, backwards]\n"
" * jump : jumps [j]\n"
" * clear : clears all the text on the screen [cls]\n"
" * exit : exits the program []\n"
" * clex : clears screen and exits and cleans up program (recomended) [clearexit]\n";
const char *dotsyntax =
" * -------[DOT] Syntax-------\n"
" * .help : help menu\n"
" * .spawn : retrun you to spawn\n"
" * .cheat-noclip : Removes Gravity And Walls\n"
" * .cheat-fly : Removes Gravity\n"
" * .moveToWallPositive : Makes you go to the corner of the positive x cordinet!\n"
" * .moveToWallNegative : Makes you go to the corner of the negative x cordinet!\n";
cout << "Alternetive Commands Are Refured to with []!" << endl << endl;
cout << syntax << endl;
cout << endl; // Seperator
cout << dotsyntax << endl;
}
else {
cout << "INVALID [DOT] COMMAND" << endl;
}
return;
}
|
C
|
#include <linux/types.h>
#include <pthread.h>
#include "test_util.h"
void * threadWork(void * p);
void testPutRemoveOne(){
putval(1,5);
removval(1);
printf("%s\n","...testPutRemoveOne successful!" );
}
void testNoObject(uint8_t key){
uint8_t *val;
ssize_t ret;
ret = hashtable_get(key,(void** )&val);
if(ret != 0){
printf("%s\n","...testNoObject failed while getting value from the hashtable" );
fail();
}
printf("%s\n","...testNoObject successful!" );
}
void testOneObject(){
uint8_t val = 10;
uint8_t * ret;
uint8_t key = 1;
putval(key,val);
ret = getval(key);
if(val != ret[0]){
printf("%s%d%s%d\n","...testOneObject failed while getting value from the hashtable, was ", ret[0]," should be ",val );
fail();
}
removval(key);
testNoObject(key);
printf("%s\n","...testOneObject successful!" );
}
void testTwoObjects(){
uint8_t val = 10;
uint8_t val2 = 15;
uint8_t * ret;
uint8_t * ret2;
putval(1,val);
putval(2,val2);
ret = getval(1);
ret2 = getval(2);
if(ret[0] != val){
printf("%s %d %s %d\n","...testTwoObject failed. Was",ret[0],"expected",val );
fail();
}
if(ret2[0] != val2){
printf("%s %d %s %d\n","...testTwoObject failed. Was",ret2[0],"expected",val );
fail();
}
removval(1);
removval(2);
printf("%s\n","...tesTwoObjects successful!" );
}
void testSeveralGetCalls(){
int count = 10;
for (int i = 0; i < count; ++i){
putval(i+1, i+2);
}
uint8_t * ret;
for (int i = 0; i < count; ++i){
ret = getval(i+1);
if(ret[0] != i+2){
printf("%s %d %s %d\n","...testSeveralGetCalls failed. Was",ret[0],"expected",i+2 );
fail();
}
}
for (int i = 0; i < count; ++i){
removval(i+1);
}
printf("%s\n","..testSeveralGetCalls successful!" );
}
void testRemoveNonExisting(){
int err;
err = hashtable_remove(1);
if(err!=1){
printf("%s\n","...removeNonExisting actually removed something!" );
fail();
}
printf("%s\n","...removeNonExisting successful!" );
}
void testOverwriteValue(){
uint8_t * ret;
uint8_t * ret2;
uint8_t * ret3;
putval(2,10);
ret = getval(2);
if(10 != ret[0]){
printf("%s%d%s%d\n","...testOneObject failed while getting value from the hashtable, was ", ret[0]," should be ",10 );
fail();
}
putval(2,15);
ret2 = getval(2);
if(15 != ret2[0]){
printf("%s%d%s%d\n","...testOneObject failed while getting value from the hashtable, was ", ret[0]," should be ",15 );
fail();
}
removval(2);
ret3 = getval(2);
if(10 != ret3[0]){
printf("%s%d%s%d\n","...testOneObject failed while getting value from the hashtable, was ", ret[0]," should be ",10 );
fail();
}
removval(2);
printf("%s\n","...overwriteValue() successful" );
}
int valuesPerThread = 200;
void testThreadedGet(int nrThreads){
pthread_t threads[nrThreads];
int count = valuesPerThread*nrThreads;
void *retVal[nrThreads];
for (int i = 0; i < count; ++i){
putval(i,i);
}
for (int i = 0; i < nrThreads; ++i){
int * j = malloc(sizeof(*j));
*j = (i*valuesPerThread);
if(pthread_create(&threads[i],0,threadWork,(void *)j)){
perror("...Thread create failure");
}
}
for (int i = 0; i < nrThreads; ++i){
if(pthread_join(threads[i], &retVal[i] )){
perror("...Thread join failure");
}
}
for (int i = 0; i < count; ++i){
removval(i);
}
for (int i = 0; i < nrThreads; ++i){
if((int*)retVal[i] != 0){
printf("%s%d%s%d\n","...testThreadedGet, thread: ",i," failed: ",*(int*)retVal[i] );
}
}
printf("%s\n","...testThreadedGet() successful" );
}
void * threadWork(void * p){
int start = *(int *)p;
free(p);
int end = start+valuesPerThread;
int *error = malloc(sizeof(int));
error = 0;
int *ret[end-start];
for(int i = start;i<end;i++){
ret[i-start] = (int *)getval(i);
}
for(int i = 0;i<end-start;i++){
if(*ret[i] != start+i){
printf("%s%d%s%d\n","....Wrong value found, was: ",*ret[i]," expected: " ,start+i );
*error = 1;
}
}
return error;
}
void testStringValue(){
uint8_t * value = "helloworld";
int key = 1;
int err;
err = hashtable_put(key,value,10);
if(err == -1){
printf("%s\n","...hashtable_put failed while putting to the hashtable" );
fail();
}
uint8_t *val;
ssize_t ret;
ret = hashtable_get(key,(void** )&val);
if(ret == 0){
printf("%s\n","...error in testStringValue, value does not exist!" );
fail();
}else if (ret == -1){
printf("%s\n","...error in testStringValue, error code returned from hashtable_get" );
fail();
}
if(compareStrings(value,val,ret) == -1){
printf("%s\n","...compareStrings returned not equal" );
fail();
}
printf("%s\n","...testStringValue() successful" );
}
int main() {
printf("%s\n","STARTED TESTING!" );
printf("\n%s\n","TESTING testNoObject:" );
testNoObject(1);
printf("\n%s\n","TESTING testRemoveNonExisting:" );
testRemoveNonExisting();
printf("\n%s\n","TESTING testPutRemoveOne:" );
testPutRemoveOne();
printf("\n%s\n","TESTING testOneObject:" );
testOneObject();
printf("\n%s\n","TESTING testTwoObjects:" );
testTwoObjects();
printf("\n%s\n","TESTING testSeveralGetCalls:" );
testSeveralGetCalls();
printf("\n%s\n","TESTING testOverwriteValue:" );
testOverwriteValue();
printf("\n%s\n","TESTING testStringValue:" );
testStringValue();
int threads = 4;
printf("\n%s%d%s\n","TESTING testThreadedGet with ",threads, " threads:" );
testThreadedGet(4);
printf("\n%s\n","TESTING DONE!" );
return 0;
}
|
C
|
#include "user_info.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <pwd.h>
#include <unistd.h>
/**
* Gets the username
*/
void get_user() {
uid_t uid = geteuid();
struct passwd *pw = getpwuid(uid);
if (pw) {
strcpy(USERNAME, pw->pw_name);
}
}
/**
* Gets the hostname of the system
*/
void get_hostname() {
char buff[BUFF];
int hostname;
hostname = gethostname(buff, sizeof(buff));
if (hostname != -1) {
strcpy(HOSTNAME, buff);
} else {
perror("Hostname is invalid.");
}
}
/**
* Gets the home directory of the account
*/
void get_home_dir() {
struct passwd *pw = getpwuid(getuid());
strcpy(HOME, pw->pw_dir);
}
|
C
|
// mah.c ... generate multi-attribute hash values
#include <stdio.h>
#include <stdlib.h>
#include "bits.h"
#include "chvec.h"
#include "tuple.h"
void exitUsage(char *);
// main ... process args and run simulation
int main(int argc, char **argv)
{
char *cv, *tup;
ChVec chvec;
// collect argv values
if (argc < 3) { exitUsage(argv[0]); }
cv = argv[1];
tup = argv[2];
// count number of attributes
int nattrs = 1;
for (char *c = tup; *c != '\0'; c++) {
if (*c == ',') nattrs++;
}
// build choice vector
if (!parseChVec(nattrs, cv, chvec)) {
fprintf(stderr, "Invalid choice vector: %s\n", cv);
exit(1);
}
// form MAH value
Bits hash = tupleHash(chvec, nattrs, tup);
// display result
char buf[MAXBITS+1];
bitsString(hash,buf);
printf("hash(%s) = %s\n", tup, buf);
exit(0);
}
void exitUsage(char *prog)
{
fprintf(stderr, "Usage: %s ChoiceVector Tuple\n", prog);
exit(1);
}
|
C
|
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
#include<unistd.h>
#include<pthread.h>
# define BUFFER_SIZE 8
int produceCount = 0;
int consumeCount = 0;
int buffer_array[BUFFER_SIZE];
pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
void* producer (void* arg) {
int itemProd = 0;
int i = 0;
while (1) {
++itemProd;
while (produceCount - consumeCount == BUFFER_SIZE);
buffer_array[produceCount % BUFFER_SIZE] = itemProd;
sleep(1);
pthread_mutex_lock(&lock);
++produceCount;
printf("\nProducing an item: %d and count is: %d", itemProd,(produceCount - consumeCount));
pthread_mutex_unlock(&lock);
}
}
void* consumer (void* arg) {
int itemCons;
int i = 0;
while (1) {
while (produceCount - consumeCount == 0);
itemCons = buffer_array[consumeCount % BUFFER_SIZE];
sleep(1);
pthread_mutex_lock(&lock);
++consumeCount;
printf("\nConsuming item: %d and count is: %d", itemCons,(produceCount - consumeCount));
pthread_mutex_unlock(&lock);
}
}
int main() {
pthread_t producer_thread, consumer_thread;
pthread_create(&producer_thread, NULL, producer, NULL);
//sleep(1);
pthread_create(&consumer_thread, NULL, consumer, NULL);
pthread_join(producer_thread, NULL);
pthread_join(consumer_thread, NULL);
return 0;
}
|
C
|
/*
* rs232_buffer.c
*
* Created on: 5 . 2017 .
* Author: dmsvo
*/
#include "rs232_buffer.h"
/* ASCII. 16.
* , ,
* , .
* , , (, , ) . */
char digToChar(int num, char base)
{
/* , */
char dig = num % base;
if ((dig >= 0) && (dig <= 9))
{
return NUM0 + dig;
}
if ((dig >=10) && (dig <= 15))
{
return DIFA + dig; /* 41 A, B, ... , F; 0x41 - 0xA = 0x37*/
}
return FSTATUS_NOTDIGIT; /* - */
}
/* .
* , , .
* ascii
* _var - ,
* _tmp - unsigned int,
* _len - ,
* _ptr - ,
* _crc -
* _base - . (10 16)
*/
#define WRITE_TO_BUF(_var, _tmp, _len, _ptr, _crc, _base) \
{ \
(_tmp) = (_var); \
for (int i = 0; i < (_len); i++) \
{ \
(_ptr)[(_len)-i-1] = digToChar((_tmp),(_base)); \
(_crc) ^= (_ptr)[(_len)-i-1]; \
(_tmp) = (_tmp) / (_base); \
} \
(_ptr) += (_len); \
}
/*
* .
* ( ):
* ( - - . , )
* SOH - 1 -
* + TRK_No - 2 -
* + Command - 1 -
* STX - 1 -
* + Price 6 - - ,
* + Volume - 6 -
* + Status - 4 - /
* ETX - 1 -
* CRC - 1 -
* - 23
*/
int fill_buffer (uint8* buf, struct Message msg)
{
/*
* , .
* , ,
* ,
*/
if (msg.trkNo > MAX_TRKNO || msg.trkNo < 0) return FSTATUS_BOUND;
if (msg.command < 0 || msg.command > MAX_COM || msg.command == 2 || msg.command == 8) return FSTATUS_BOUND;
/* 2 8.
* ? , */
if (msg.price > MAX_PRC || msg.price < 0) return FSTATUS_BOUND;
if (msg.volume > MAX_VOL || msg.price < 0) return FSTATUS_BOUND;
/*
* .
* , #3 ("") (- ,
* -, )
* 0 #9 (" ") (- ,
* , ).
* ,
*/
if (msg.command == 3 /* */
&& msg.status == 0) return FSTATUS_WRONGSPC;
if (msg.command == 9 /* */
&& msg.volume != 0) return FSTATUS_WRONGSPC;
/*
*
*/
/* */
uint8* ptr = buf;
unsigned char crc;
/* */
*ptr = 0x1; ptr++;
/* */
*ptr = digToChar(msg.trkNo / 16, 16);
crc = *ptr; ptr++; /* crc , */
*ptr = digToChar(msg.trkNo % 16, 16);
crc ^= *ptr; ptr++;
/* */
*ptr = digToChar(msg.command, 16);
crc ^= *ptr; ptr++;
/* */
*ptr = 0x2;
crc ^= *ptr; ptr++;
unsigned int tmp;
/* */
WRITE_TO_BUF(msg.price, tmp, PRC_LEN, ptr, crc, 10);
/* */
WRITE_TO_BUF(msg.volume, tmp, VOL_LEN, ptr, crc, 10);
/* . */
WRITE_TO_BUF(msg.status, tmp, STS_LEN, ptr, crc, 16);
/* */
*ptr = 0x3;
crc ^= *ptr; ptr++;
/* . , ,
* , . */
*ptr = crc;
return FSTATUS_OK;
}
|
C
|
/***************************************************************************/
/* This module provides all the necessary resources to represent polygons. */
/* This includes displaying polygons and repreenting verticies. */
/***************************************************************************/
#ifndef POLYGON_H
#define POLYGON_H
/********************************************************************/
/* The library used for OpenGL context creation is included here. */
/* This can include any library based off of the GLUT API. However, */
/* it is reccomended to use FreeGLUT as this code is optimised for */
/* FreeGLUT extensions. */
/********************************************************************/
#ifdef __APPLE__
# include "GLUT/glut.h"
#else
# include "GL/glut.h"
#endif
/*************************************************************************/
/* OpenGL headers are included here. The compiler considers the platform */
/* the compiler is aimed at, adjusting it's include paths appropriately. */
/*************************************************************************/
#if __APPLE__
# include <OpenGL/gl.h>
# include <OpenGL/glu.h>
#else
# include <GL/gl.h>
# include <GL/glu.h>
#endif
/********************************************************/
/* This vertex structure is used to represent the shape */
/* of a polygon as a one dimensional array. */
/********************************************************/
typedef struct Vertex{
float x;
float y;
}Vertex;
/****************************************************************/
/* This ConcavePolygon structure represents a 2D complex shape. */
/* While the structure does not need to represent a polygon */
/* which is Concave, it is able to represent both Concave and */
/* Convex polygons. */
/****************************************************************/
typedef struct ConcavePolygon{
/******************************************/
/* This vertex array points to the */
/* verticies which represent the polygon. */
/******************************************/
Vertex *verticies;
/**************************************/
/* This integer holds the size of the */
/* vertex array. */
/**************************************/
int size;
}ConcavePolygon;
/************************************************************************************/
/* This function draws a polygon. It can be modified to change rendering behaviour. */
/* Currently, this function is essentially a front end to DrawVerticies(). */
/************************************************************************************/
void DrawPolygon(ConcavePolygon *polygon);
/*******************************************************************/
/* This function draws an array of Verticies as a polygon outline. */
/*******************************************************************/
void DrawVerticies(Vertex *pointer, int size);
#endif /* POLYGON_H */
|
C
|
#include "position.h"
int position_equal(char *a, char *b) {
return a[0] == b[0] && a[1] == b[1];
}
int position_valid(char *position) {
return position[0] != '-' && position[1] != '-';
}
void position_copy(char *src, char *dst) {
dst[0] = src[0];
dst[1] = src[1];
}
int position_to_x(char file) {
return file - 'a';
}
int position_to_y(char rank) {
return (rank - '8') * -1;
}
char position_to_file(int x) {
return x + 'a';
}
char position_to_rank(int y) {
return y * -1 + '8';
}
int position_get_x(char *position) {
return position_to_x(position[0]);
}
int position_get_y(char *position) {
return position_to_y(position[1]);
}
void position_invalidate(char *position) {
position[0] = '-';
position[1] = '-';
}
void position_set_file_rank(char *position, int x, int y) {
position[0] = position_to_file(x);
position[1] = position_to_rank(y);
}
|
C
|
/*
04. Escreva uma função que receba um vetor de inteiros e retorne
o maior elemento e o menor elemento. Observe que a função deve
retornar ao local da chamada os dois valores (não imprimir ao usuário). Portanto,
você precisará usar passagem de parâmetro por referência.
*/
#include<stdio.h>
void busca(int v[], int *pmaior, int *pmenor, int size){
int i;
*pmaior = v[0];
*pmenor = v[0];
for(i = 1; i < size; i++){
if(v[i] > *pmaior){
*pmaior = v[i];
}
if(v[i] < *pmenor){
*pmenor = v[i];
}
}
}
int main(void){
int v[] = {4, 5, 6, 3, 1};
int size = sizeof(v) / sizeof(v[0]);
int maior, menor;
busca(v, &maior, &menor, size);
printf("MAIOR: %d\n", maior);
printf("MENOR: %d\n", menor);
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <locale.h>
typedef struct dataNode {
char dataRef[10];
int codReg;
char informante[30];
char desc[30];
float qttProd;
}DataNode;
typedef struct node {
DataNode *data;
struct node* next;
}Node;
typedef struct list {
Node *head;
int size;
}List;
List* createList();
FILE* open(char fileName[]);
void read(FILE *arq, List* list);
void push(List *list, Node *no);
void showInfo(List *list);
int main(void){
setlocale(LC_ALL, "Portuguese");
char fileName[] = "csv_mapa.csv";
FILE * csv = open(fileName);
if(csv == NULL)
{
printf("No foi possvel abrir o arquivo especificado!");
return 1;
}
List *lista = createList();
read(csv, lista);
showInfo(lista);
free(lista);
fclose(csv);
return 0;
}
void read(FILE *arq, List* list){
char parsedLine[1088];
while(fgets(parsedLine, 1088, arq) != NULL)
{
Node* n = (Node*)malloc(sizeof(Node));
DataNode *d = (DataNode*)malloc(sizeof(DataNode));
char *rest;
char *dr = strtok_r(parsedLine, ";", &rest);
strcpy(d->dataRef, dr);
char *cr = strtok_r(rest, ";",&rest);
int crInt = atoi(cr);
d->codReg = crInt;
char *inf = strtok_r(rest, ";",&rest);
strcpy(d->informante, inf);
char *desc = strtok_r(rest, ";",&rest);
strcpy(d->desc, desc);
char *qtt = strtok_r(rest, ";",&rest);
float qttFloat = atof(qtt);
d->qttProd = qttFloat;
n->data = d;
n->next = NULL;
push(list, n);
}
}
void showInfo(List *list)
{
printf("Trabalho Mapa Yuri Barbosa Perira - RA:1869040-5\n");
printf("Curso: BACHARELADO EM ENGENHARIA DE SOFTWARE\n");
printf("Dataset ");
printf("A - Movimentao de derivados de petrleo, gs natural e biocombustveis - Combustveis de aviao \n\n");
printf("Total de itens: %d \n\n", list->size);
Node *head = list->head;
while(head->next != NULL)
{
printf("Data de Referncia :%c%c%c%c/%c%c\n", head->data->dataRef[0],head->data->dataRef[1],head->data->dataRef[2],head->data->dataRef[3], head->data->dataRef[4],head->data->dataRef[5]);
printf("Cdigo Regulado :%d\n", head->data->codReg);
printf("Informante :%s\n", head->data->informante);
printf("Descrio do produto :%s\n", head->data->desc);
printf("Quantidade do produto :%.2f\n", head->data->qttProd);
printf("\n\n");
head = head->next;
}
}
void push(List* list, Node *no)
{
if(list->head == NULL)
{
list->head = no;
}else{
Node *aux = (Node*)malloc(sizeof(Node));
aux = list->head;
while(aux->next != NULL)
{
aux = aux->next;
}
aux->next = no;
}
list->size += 1;
}
List* createList()
{
List* l = (List*)malloc(sizeof(List));
l->head = NULL;
l->size = 0;
return l;
}
FILE* open(char fileName[])
{
FILE *f = fopen(fileName, "r");
return f;
}
|
C
|
#include<iostream>
#include<stack>
#include<stdlib.h>
using namespace std;
struct Point
{
int x,y;
}
Point p0;
Point nextToTop(stack<Point> &S)
{
Point p=S.top();
S.pop();
Point r=S.top();
S.push(p);
return r;
}
int swap(Point &p1, Point &p2)
{
Point temp = p1;
p1 = p2;
p2 = temp;
}
int distSq(Point p1, Point p2)
{
return (p1.x - p2.x)*(p1.x - p2.x) +
(p1.y - p2.y)*(p1.y - p2.y);
}
int angle(Point p, Point q, Point r)
{
int val = (q.y - p.y) * (r.x - q.x) -
(q.x - p.x) * (r.y - q.y);
if (val == 0) return 0; // colinear
return (val > 0)? 1: 2; // clock or counterclock wise
}
int compare(const void *vp1, const void *vp2)
{
Point *p1 = (Point *)vp1;
Point *p2 = (Point *)vp2;
int o = orientation(p0, *p1, *p2);
if (o == 0)
return (distSq(p0, *p2) >= distSq(p0, *p1))? -1 : 1;
return (o == 2)? -1: 1;
}
void convexHull(Points point[],int n)
{
int ymin=points[0].y,min=0;
for(int i=1;i<n;i++)
{
int y=points[i].y;
if(y<ymin || (ymin==y) && points[i].x<points[min].x))
{
ymin = points[i].y;
min=i;
}
}
swap(point[0],point[min]);
p0=point[0];
qsort(&point[1], n-1, sizeof(Point), compare);
int m=1;
for(int i=1;i<n;i++)
{
while(i < n-1 && angle(p0,point[i],point[i+1]==0))
{
i++;
points[m]=point[i];
m++;
}
}
if(m<3) return;
stack<Point>S;
S.push(points[0]);
S.push(points[1]);
S.push(points[2]);
for (int i = 3; i < m; i++)
{
while (angle(nextToTop(S), S.top(), points[i]) != 2)
S.pop();
S.push(points[i]);
}
while (!S.empty())
{
Point p = S.top();
cout << "(" << p.x << ", " << p.y <<")" << endl;
S.pop();
}
}
}
int main()
{
Point point[]={{0,3},{1,4},{2,4},{4,5}};
int n=sizeof(points)/sizeof(point[0]);
convexHull(points,n);
return 0;
}
|
C
|
#include <string.h>
/*
* store c througout unsigned char s[n]
*/
void * Memset(void *s, int c, size_t n) {
const unsigned char uc = c;
unsigned char *su;
for (su = s; 0 < n; --n)
*su = uc;
return (s);
}
|
C
|
void ft_swap_char(char *a, char *b)
{
char c;
c = *a;
*a = *b;
*b = c;
}
|
C
|
#include <crisp/env.h>
#include <crisp/gc.h>
#include <crisp/list.h>
void cr_env_free_binds(cr_env * env){
cr_map * map = env->binds;
for(int i = 0; i < map->capacity; i++){
cr_list * bucket = map->buckets[i];
if(bucket){
for(cr_node * node = bucket->head; node; node = node->next){
cr_entry * entry = (cr_entry *) node->value;
cr_free(entry->key);
cr_free(entry->value);
}
}
}
cr_map_destroy(map);
env->binds = NULL;
}
void cr_env_destroy(cr_env * env){
if(env->binds){
cr_env_free_binds(env);
}
if(env->parent) cr_free(env->parent);
}
cr_env * cr_env_new(cr_env * parent){
cr_env * env = cr_mallocS(sizeof(cr_env), cr_env_destroy);
env->parent = parent;
if(parent != NULL){
cr_ref(parent);
}
env->binds = cr_map_newS(cr_symbol_hash, cr_symbol_cmp);
return env;
}
void cr_env_set(cr_env * env, cr_symbol * symbol, cr_object * value){
cr_map_set(env->binds, cr_ref(symbol), cr_ref(value));
}
cr_object * cr_env_get(cr_env * env, cr_symbol * symbol){
cr_object * obj = NULL;
while(obj == NULL && env != NULL){
obj = cr_map_get(env->binds, symbol);
env = env->parent;
}
if(obj != NULL){
return obj;
}else{
return (cr_object *) cr_symbol_null;
}
}
void cr_env_show(cr_env * env){
printf("Symbol:\t Value:\n");
char buf[256];
for(int i = 0; i < env->binds->capacity; i++){
cr_list * bucket = env->binds->buckets[i];
if(bucket != NULL){
for(cr_node * node = bucket->head; node; node = node->next){
cr_entry * entry = node->value;
cr_symbol * sym = (cr_symbol *) entry->key;
cr_object * obj = (cr_object *) entry->value;
cr_show(buf, obj);
printf("%s\t-> %s\n", sym->name, buf);
}
}
}
}
|
C
|
#include <stdio.h>
/**
* main - Entry point
*
* Return: void (Success)
*/
int main(void)
{
int g;
for (g = 1; g <= 100; g++)
{
if ((g % 3 == 0) && (g % 5 == 0))
{
printf("FizzBuzz");
}
else if (g % 3 == 0)
{
printf("Fizz");
}
else if (g % 5 == 0)
{
printf("Buzz");
}
else
{
printf("%i", g);
}
if (g != 100)
{
printf(" ");
}
}
printf("\n");
return (0);
}
|
C
|
#include <stdlib.h>
#include <stdio.h>
struct clientData {
unsigned int numeroConto;
char cognome[35];
char nome[35];
double saldo;
};
typedef struct clientData ClientData;
int main(void){
FILE *cfPtr;
char insert = 'i';
int count = 0;
if ((cfPtr = fopen("accounts.dat", "rb+")) == NULL){
if ((cfPtr = fopen("accounts.dat", "wb+")) == NULL){
puts("Non riesco ad aprire il file.");
return (-1);
}
}
struct clientData cliente = {0, "", "", 0.0};
printf("%s", "Inserisci un numero di conto (da 1 a 100, 0 per terminare): ");
scanf("%d", &cliente.numeroConto);
while (cliente.numeroConto != 0){
if (insert == 'i') {
printf("%s","Inserisci cognome, nome e saldo: ");
fscanf(stdin, "%14s%9s%lf", cliente.cognome, cliente.nome, &cliente.saldo);
count++;
} else {
cliente.cognome[0] = '\0';
cliente.nome[0] = '\0';
cliente.saldo = 0;
}
fseek(cfPtr, (cliente.numeroConto - 1)*sizeof(struct clientData), SEEK_SET);
fwrite(&cliente, sizeof(struct clientData), 1, cfPtr);
printf("%s", "Inserisci il numero di conto (i o d): ");
scanf("%d%c", &cliente.numeroConto, &insert);
}
fseek(cfPtr, 0, SEEK_END);
int sz = ftell(cfPtr) / sizeof(struct clientData);
ClientData vettore[sz];
fseek(cfPtr, 0, SEEK_SET);
fread(vettore, sizeof(struct clientData), sz, cfPtr);
for (int i = 0; i < sz; i++){
printf("%-10s%-13s%f \n", vettore[i].cognome, vettore[i].nome, vettore[i].saldo);
fclose(cfPtr);
}
}
|
C
|
void lud_base(float *a, int size)
{
int i,j,k;
float sum;
for (i=0; i<size; i++){
for (j=i; j<size; j++){
sum=a[i*size+j];
for (k=0; k<i; k++) sum -= a[i*size+k]*a[k*size+j];
a[i*size+j]=sum;
}
for (j=i+1;j<size; j++){
sum=a[j*size+i];
for (k=0; k<i; k++) sum -=a[j*size+k]*a[k*size+i];
a[j*size+i]=sum/a[i*size+i];
}
}
}
|
C
|
#include "mod.h"
//Ľڵģ
void mod(Book* head) {
system("cls");
//Ϊգʼ
if (head) {
Book* p; //ָ
int id1, id2, inventory1; //num1鼮Ϣ,num2
char name1[50], author1[20];
float price1;
printf("Ҫĵͼţ");
//Ҫĵͼ
scanf_s("%d", &id1);
p = head->next;
while (p != NULL) {
if (p->id == id1) { //жǷҵ鼮
printf("鱾Ϣʽ ۸\n");
//ΪʱͼϢ
scanf("%d %s %s %d %f", &id2, name1, author1, &inventory1, &price1);
p->id = id2;
strcpy(p->name, name1);
strcpy(p->author, author1);
p->inventory = inventory1;
p->price = price1;
break;
}
else {
//Ϊʱ
p = p->next;//ָ
}
}
if (p == NULL) {//ҵһڵ㻹δ鵽ҪıʱϢ
printf("δҵͼ\n");
//ʹҳͣڵǰҳ
printf("......");
getch();
}
}
else {
printf("δͼ봴!\n");
//ʹҳͣڵǰҳ
printf("......");
getch();
}
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* rush01 :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/08/08 07:06:00 by #+# #+# */
/* Updated: 2021/08/08 07:28:00 by ### ########.fr */
/* */
/* ************************************************************************** */
int up(int board[4][4], int col, int num)
{
int i;
int max;
int count;
i = 0;
count = 1;
max = board[i][col];
while (i < 4)
{
if (board[i][col] > max)
{
max = board[i][col];
count++;
}
i++;
}
if (count == num)
return (1);
return (0);
}
int down(int board[4][4], int col, int num)
{
int i;
int max;
int count;
i = 3;
count = 1;
max = board[i][col];
while (i >= 0)
{
if (board[i][col] > max)
{
max = board[i][col];
count++;
}
i--;
}
if (count == num)
return (1);
return (0);
}
int left(int board[4][4], int row, int num)
{
int i;
int max;
int count;
i = 0;
count = 1;
max = board[row][i];
while (i < 4)
{
if (board[row][i] > max)
{
max = board[row][i];
count++;
}
i++;
}
if (count == num)
return (1);
return (0);
}
int right(int board[4][4], int row, int num)
{
int i;
int max;
int count;
i = 3;
count = 1;
max = board[row][i];
while (i >= 0)
{
if (board[row][i] > max)
{
max = board[row][i];
count++;
}
i--;
}
if (count == num)
return (1);
return (0);
}
int checkboard(int board[4][4], int *in_num)
{
int i;
i = 0;
while (in_num[i])
{
if (i >= 0 && i <= 3)
if (!up(board, i, in_num[i]))
return (0);
if (i >= 4 && i <= 7)
if (!down(board, i - 4, in_num[i]))
return (0);
if (i >= 8 && i <= 11)
if (!left(board, i - 8, in_num[i]))
return (0);
if (i >= 12 && i <= 15)
if (!right(board, i - 12, in_num[i]))
return (0);
i++;
}
return (1);
}
|
C
|
#include "stdio.h"
#include "stdlib.h"
#include "string.h"
#define MIN(x,y) (((x)<(y)) ? (x) : (y))
void* my_realloc(void* ptr, size_t new)
{
if (ptr == NULL)
{
return malloc(new);
}
if (new == 0)
{
free(ptr);
}
void* newPtr = malloc(new);
size_t current = ((size_t*)ptr)[-1];
memcpy(ptr, newPtr, MIN((int) current,new));
free(ptr);
return newPtr;
}
int main(int argc, char const *argv[])
{
int n = 3; // set size
int* a = (int*)malloc(n*sizeof(int));
printf("before realloc:\n");
for (int i = 0; i < n; ++i)
{
*(a+i) = i;
printf("%d\n",*(a+i));
}
int new_size = 5; // set another size
my_realloc(a,5);
printf("after realloc:\n");
for (int i = 0; i < new_size; ++i)
{
*(a+i) = 0;
printf("%d\n", *(a+i));
}
return 0;
}
|
C
|
#include "holberton.h"
/**
* _strpbrk - return pointer to byte in s that matches a byte in accept
* @s: string to search
* @accept: target matches
* Return: pointer to index of string at first occurence
*/
char *_strpbrk(char *s, char *accept)
{
int i;
while (*s)
{
for (i = 0; accept[i]; i++)
{
if (*s == accept[i])
return (s);
}
s++;
}
return ('\0');
}
|
C
|
#include<stdio.h>
#include<string.h>
int main(){
int i = 1, False = 0, targetTrue = 1;
char target[1000003] = {}, temp[1000003] = {}, input[4];
fgets(target+1, 500003, stdin);
while(fgets(input, 4, stdin) != NULL){
if(input[0] == '\\'){
if(target[i-1] != temp[i-1]){
False --;
temp[i-1] = 0;
}
if(i == 1) i = 1;
else i--;
}
else{
temp[i] = input[0];
if(target[i] != temp[i]) False ++;
i++;
}
if(False) printf("0\n");
else printf("1\n");
}
for(int t = 1; target[t] != '\n'; t++){
if(target[t] != temp[t]){
targetTrue = 0;
}
}
if(targetTrue && (!False)) puts("Correct");
else puts("Incorrect");
}
|
C
|
//fgetc(), getchar(), fputc(), putc(), putchar(), ungetc()
//getwc(), fgetwc(), getwchar(), putwc(), fputwc(), putwchar(), ungetwc()
#include <stdio.h>
int getc(FILE* fp);
FILE* inputs[16];
int i = 0;
do {
int nextchar = getc(inputs[i++]);
} while(i < 16);
for(int i = 0; i < 16; i++){
int nextchar = getc(input[i]);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <math.h>
typedef struct
{
int heap_size;
int max_size;
int *nodo;
}heap;
int kN(int dim)
{
int k, low;
low = 0.5*dim;
k = low + rand()%(dim - low);
return k;
}
int kLog_N(int dim)
{
double l = log((double)dim);
int low = (int)l*0.5;
int high = (int)l*20;
int k = low + rand()%(high-low);
//printf("%d\n", k);
return k;
}
void swap(int *a, int *b)
{
int s;
s = *b;
*b = *a;
*a = s;
}
int parent(int i)
{
return (i - 1) / 2;
}
int left(int i)
{
return 2 * i+1 ;
}
int right(int i)
{
return 2 * i +2;
}
int randomizedPartition(int arr[], int p, int r)
{
int pivotIndex = p + rand()%(r - p + 1); //genero un pivot casuale
int pivot;
int i = p - 1;
int j;
pivot = arr[pivotIndex];
swap(&arr[pivotIndex], &arr[r]);
for (j = p; j < r; j++)
{
if (arr[j] <= pivot)
{
i++;
swap(&arr[i], &arr[j]);
}
}
swap(&arr[i+1], &arr[r]);
return i + 1;
}
void randomizedQuickSort(int A[], int p, int r)
{
int q;
if (p < r)
{
q = randomizedPartition(A, p, r);
randomizedQuickSort(A, p, q - 1);
randomizedQuickSort(A, q + 1, r);
}
}
int kSort(int A[], int p, int r, int KEY)
{
randomizedQuickSort(A, p, r-1);
return A[KEY];
}
int kPartition(int A[], int p, int r, int KEY)
{
int pivot;
if (p < r)
{
pivot = randomizedPartition(A, p, r);
if (pivot == KEY)
return A[KEY];
else if (pivot < KEY)
return kPartition(A, pivot, r, KEY);
else
return kPartition(A, p, pivot - 1, KEY);
}
}
void minHeap(heap *A, int i)
{
int l = left(i);
int r = right(i);
int smallest = i;
if (l < A->heap_size && A->nodo[l] < A->nodo[i])
smallest = l;
if (r < A->heap_size && A->nodo[r] < A->nodo[smallest])
smallest = r;
if (smallest != i)
{
swap(&A->nodo[i], &A->nodo[smallest]);
minHeap(&*A, smallest);
}
}
int extractMin(heap *A)
{
int min;
if (A->heap_size < 1)
printf("underflow");
min = A->nodo[0];
A->nodo[0] = A->nodo[A->heap_size-1];
A->heap_size--;
minHeap(&*A, 0);
return min;
}
void buildMinHeap(heap *A, int dim)
{
int i;
int n = (A->heap_size / 2);
for (i = n; i >= 0; i--)
minHeap(&*A, i);
}
int kMinHeap(heap *A, int KEY)
{
int i;
A->heap_size = A->max_size;
buildMinHeap(A, A->heap_size);
for (i = 0; i < KEY; i++)
extractMin(&*A);
return extractMin(&*A);
}
void maxHeapify(heap *B, int i)
{
int l = left(i);
int r = right(i);
int max = i;
if (l < B->heap_size && B->nodo[l] > B->nodo[i])
max = l;
if (r < B->heap_size && B->nodo[r] > B->nodo[max])
max = r;
if (max != i)
{
swap(&B->nodo[i], &B->nodo[max]);
maxHeapify(B, max);
}
}
int maxElem(heap *A)
{
return A->nodo[0];
}
void buildMaxHeap(heap *B)
{
int i;
int n = (B->heap_size-1) / 2;
for (i = n; i >= 0; i--)
maxHeapify(B, i);
}
void decreaseKey(heap *A, int i, int priority)
{
if (priority > A->nodo[i])
printf("error");
A->nodo[i] = priority;
while (i > 0 && A->nodo[parent(i)] > A->nodo[i])
{
int p = parent(i);
swap(&i, &p);
i = p;
}
}
int kMaxHeap(int *A, int dim, int KEY)
{
heap B;
B.max_size = dim;
B.heap_size = KEY;
B.nodo = malloc(sizeof(heap)*KEY);
int i;
for (i = 0; i < KEY; i++)
{
B.nodo[i] = A[i];
}
buildMaxHeap(&B);
for (i = KEY; i < dim; i++)
{
if (A[i] < maxElem(&B))
{
decreaseKey(&B, 0, A[i]);
maxHeapify(&B, 0);
}
}
return maxElem(&B);
}
int OrdinaArray(int dim, int KEY)
{
int array[dim];
int array2[dim];
int i;
int differenza = 0;
clock_t t1, t2;
heap A;
A.max_size = dim;
A.nodo = malloc(sizeof(int)*dim);
for (i = 0; i < dim; i++) //creo array di grandezza dim
{
array[i] = rand() %10000+1;
A.nodo[i] = array[i];
}
t1 = clock();
//kMaxHeap(array, dim, KEY);
//kPartition(array, 0, dim, KEY);
//kSort(array, 0, dim, KEY);
kMinHeap(&A, KEY);
/*if(check(array, 0, dim)) //verifico se array è ordinato
printf("non ordinato\n");
else
printf("ordinato\n");*/
t2 = clock();
differenza = t2 - t1; //valore di ritorno per la media
free(A.nodo);
return differenza;
}
int main()
{
int i = 100;
int media = 0;
int j = 0;
int key;
while (i <= 10000 ) //ciclo che scorre la grandezza dell'array
{
//key = 60;
//key = kN(i);
key = kLog_N(i);
while (j < 10) //ciclo che incrementerà il valore media
{
media = media + OrdinaArray(i, key); //funzione Ordina riceve grandezza array che andrà a creare nella funzione
j++;
}
media = media / 10; //media
printf("%d\n", media); //stampa tempi medi
media = 0;
i = i + 100; //incremento indice array
j = 0;
}
}
|
C
|
#include <stdio.h>
#include <sys/socket.h> //For Sockets
#include <stdlib.h>
#include <netinet/in.h> //For the AF_INET (Address Family)
#include <string.h>
#include <netdb.h>
#define MSG_BUF 1024
int main(int argc, char* argv[]){
struct sockaddr_in serv_addr;
int fd;
char buffer[MSG_BUF];
//domain name
struct hostent *host_entry;
int host_ip=0;
if(argc != 3){
printf("check : %s [ip] and %s [port] \n", argv[1], argv[2]);
exit(1);
}
fd = socket(AF_INET, SOCK_STREAM, 0);
memset(&serv_addr, 0x00, sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
serv_addr.sin_port = htons(atoi(argv[2]));
if(inet_addr(argv[1]) != INADDR_NONE)
{
serv_addr.sin_addr.s_addr = inet_addr(argv[1]);
}
else
{
host_entry = gethostbyname(argv[1]); // if fail -> NULL
if(host_entry != NULL){
printf("host entry address : %lu \n",*((unsigned long *)(host_entry->h_addr_list[0])));
host_ip = *((unsigned long *)(host_entry->h_addr_list[0]));
}
serv_addr.sin_addr.s_addr = host_ip;
}
if(connect(fd, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) < 0){
printf("system: connect failed \n");
exit(1);
}
while(1){
//memory initialize...
memset(buffer, 0x00, MSG_BUF);
printf("Enter a message: ");
fgets(buffer, MSG_BUF, stdin);
if(strlen(buffer) <= 0 ){
close(fd);
return 0;
}
send(fd, buffer, sizeof(buffer), 0);
memset(buffer, 0x00, MSG_BUF);
read(fd, buffer, MSG_BUF);
printf("Server said: %s", buffer);
}
close(fd);
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
char *filename;
if( argc > 1 )
{
filename = argv[1];
}
else
{
fprintf(stderr,"Filename argument required\n");
exit(1);
}
printf("The filename is %s\n",filename);
return(0);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include "object.h"
#include "list.h"
#include "string_util.h"
DECLARE_OBJECT(Integer, int);
void printInt(int x) { printf("%d", x); }
int main()
{
Scope scope = newScope();
Integer p = newInteger(scope);
*objectRawPtr(p) = 100;
ListInt lst = newListInt(scope, 10);
for (int i = 0; i < listSize(lst); i++)
{
listAt(lst, i) = i;
}
printf("%d\n", listPop(lst));
printList(lst, printInt);
printf("%d\n", *objectRawPtr(p));
freeScope(scope);
return 0;
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_conv_char.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: alecott <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2017/12/21 09:01:16 by alecott #+# #+# */
/* Updated: 2018/01/16 10:48:32 by alecott ### ########.fr */
/* */
/* ************************************************************************** */
#include "../printf.h"
static int ft_width_wchar(t_list *l, wchar_t wc, int i)
{
char *s;
if (ft_atoi(l->width) > 1)
{
s = (char*)malloc(sizeof(s) * (ft_atoi(l->width) - 1));
if (ft_strchr(l->flags, '0'))
s = ft_memset(s, '0', (ft_atoi(l->width) - 1));
else
s = ft_memset(s, ' ', (ft_atoi(l->width) - 1));
if (ft_strchr(l->flags, '-') == 0)
{
ft_putstr(s);
i = ft_putwchar(wc, i);
}
else
{
i = ft_putwchar(wc, i);
ft_putstr(s);
}
return (i + ft_atoi(l->width) - 1);
}
else
i = ft_putwchar(wc, i);
return (i);
}
int ft_conv_char(t_list *l, va_list ap, int i)
{
wchar_t wc;
if (l->spec == 'C' || (ft_strequ(l->length, "l") && l->spec == 'c'))
wc = (wchar_t)va_arg(ap, wint_t);
else
wc = (unsigned char)va_arg(ap, int);
i = ft_width_wchar(l, wc, i);
return (i + 1);
}
|
C
|
#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
#include <sys/types.h>
#include <sys/mman.h>
#include <sys/sysinfo.h>
#include <sched.h>
#include <semaphore.h>
#include "util.h"
sem_t mutex;
void fileToArray(char *filename, double *f, int array_size) {
FILE *file = fopen(filename, "r");
if (file == NULL) {
perror("fileToArray()");
exit(EXIT_FAILURE);
}
for (int i = 0; i < array_size; i++) {
fscanf(file, "%lf", &f[i]);
}
}
void setPartialSum(double *f, int l, int r, int array_size) {
if (r == array_size) r-=1;
while (l+1 < r) {
f[l+1] += f[l];
l++;
}
/* since a race condition is not possible when each process
is access its own section of the array, we just take the
unnecessary step of always summing at one specific index. */
sem_wait(&mutex);
f[array_size-1] += f[l]; // critical section
sem_post(&mutex);
}
int main(int argc, char *argv[]) {
char *filename = argv[1];
int array_size, m;
size_t size;
m = get_nprocs(); // number of theads/processes
double start, time1, time2;
double *f;
sem_init(&mutex, 0, 1);
struct sched_param sp;
cpu_set_t *set;
set = CPU_ALLOC(m);
if (set == NULL) {
perror("CPU_ALLOC()");
exit(EXIT_FAILURE);
}
/* initialize cpu sets */
size = CPU_ALLOC_SIZE(m);
CPU_ZERO_S(size, set);
for (int i = 0; i < m; i++) {
CPU_SET_S(i, size, set);
}
/* configure scheduler */
sp.sched_priority = sched_get_priority_max(SCHED_FIFO);
if (sched_setscheduler(0, SCHED_FIFO, &sp) < 0) {
perror("sched_setscheduler()");
exit(EXIT_FAILURE);
}
/* parse arguments */
sscanf(argv[2], "%i", &array_size);
f = mmap(NULL, array_size*sizeof(double), PROT_READ | PROT_WRITE, MAP_SHARED | MAP_ANONYMOUS, -1, 0);
if (f < 0) {
perror("mmap()");
exit(EXIT_FAILURE);
}
fileToArray(filename, f, array_size);
int stride = array_size / m;
double compareTotal = 0;
start = gethrtime_x86();
for (int i = 0; i < array_size; i++) {
compareTotal += f[i];
}
time1 = gethrtime_x86()-start;
/* fork processes and get partial sums */
start = gethrtime_x86();
for (int id = 0; id < m; id++) {
if (fork() == 0) {
/* set processor to child */
if (sched_setaffinity(getpid(), sizeof(set), set) < 0) {
perror("sched_setaffinity()");
exit(EXIT_FAILURE);
}
setPartialSum(f, id*stride, (id+1)*stride, array_size);
exit(0);
} else {
wait(NULL);
time2 = gethrtime_x86()-start;
}
}
double total = f[array_size-1];
/* check sum */
printf("\nResults: \n");
printf("No. of Cores: %d\n", m);
printf("Target sum: %f\n", compareTotal);
printf("=======================================\n");
if (total == compareTotal) {
printf("Successfully summed numbers to: %f\n", total);
printf("Single thread time: %.06fs\n", time1);
printf("Multi-thread time: %.06fs\n", time2);
} else {
printf("Something went wrong.\n");
printf("Total should be: %f, but is %f\n", compareTotal, total);
}
printf("\n");
return 0;
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* utilities.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: llachgar <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2018/10/24 10:06:16 by llachgar #+# #+# */
/* Updated: 2018/11/03 00:39:55 by llachgar ### ########.fr */
/* */
/* ************************************************************************** */
#include "fillit.h"
int ft_sqrt(int x)
{
int i;
int result;
i = 1;
result = 1;
if (x == 0 || x == 1)
return (x);
while (result <= x)
{
i++;
result = i * i;
}
return (i - 1);
}
void ft_list_remove(t_tetris *list)
{
t_tetris *t;
if (list == NULL)
return ;
t = list;
while (list)
{
list = list->next;
free(t);
t = list;
}
}
int count_tab_points(char *tab, int size)
{
int i;
int count;
i = 0;
count = 0;
while (i < size)
{
if (tab[i] == '.')
count++;
i++;
}
return (count);
}
int optimal_check(char **tab, int size, int len)
{
int i;
int count;
i = 0;
count = 0;
while (i < size)
{
count += count_tab_points(tab[i], size);
i++;
}
if (count < (len * 4))
return (0);
return (1);
}
|
C
|
#include <stdio.h>
int main(void){
long long n;
int d[] = { 1, 2, 3, 4, 5, 6 };
int tmp;
scanf( "%lld", &n );
for( int i=0; i<n%30; ++i ){
tmp = d[i%5];
d[i%5] = d[i%5+1];
d[i%5+1] = tmp;
}
for( int i=0; i < 6; ++i ){
printf("%d",d[i]);
}
printf("\n");
}
|
C
|
/* unicode.h - Header file for Unicode library.
Copyright (C) 1999, 2000 Tom Tromey
The Gnome Library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public License as
published by the Free Software Foundation; either version 2 of the
License, or (at your option) any later version.
The Gnome Library 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
Library General Public License for more details.
You should have received a copy of the GNU Library General Public
License along with the Gnome Library; see the file COPYING.LIB. If not,
write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
Boston, MA 02111-1307, USA. */
#ifndef UNICODE_H
#define UNICODE_H
#ifdef __cplusplus
extern "C"
{
#endif
#include <stdlib.h> /* For size_t */
#include <sys/types.h> /* For ssize_t */
/* We need the error codes so we can see if EILSEQ exists. */
#include <errno.h>
#ifndef EILSEQ
/* On some systems, like SunOS and NetBSD, EILSEQ is not defined. */
# define EILSEQ -2323
#endif
/* FIXME: assumes 32-bit int. */
typedef unsigned int unicode_char_t;
/* These are the possible character classifications. */
#define UNICODE_CONTROL 0
#define UNICODE_FORMAT 1
#define UNICODE_UNASSIGNED 2
#define UNICODE_PRIVATE_USE 3
#define UNICODE_SURROGATE 4
#define UNICODE_LOWERCASE_LETTER 5
#define UNICODE_MODIFIER_LETTER 6
#define UNICODE_OTHER_LETTER 7
#define UNICODE_TITLECASE_LETTER 8
#define UNICODE_UPPERCASE_LETTER 9
#define UNICODE_COMBINING_MARK 10
#define UNICODE_ENCLOSING_MARK 11
#define UNICODE_NON_SPACING_MARK 12
#define UNICODE_DECIMAL_NUMBER 13
#define UNICODE_LETTER_NUMBER 14
#define UNICODE_OTHER_NUMBER 15
#define UNICODE_CONNECT_PUNCTUATION 16
#define UNICODE_DASH_PUNCTUATION 17
#define UNICODE_CLOSE_PUNCTUATION 18
#define UNICODE_FINAL_PUNCTUATION 19
#define UNICODE_INITIAL_PUNCTUATION 20
#define UNICODE_OTHER_PUNCTUATION 21
#define UNICODE_OPEN_PUNCTUATION 22
#define UNICODE_CURRENCY_SYMBOL 23
#define UNICODE_MODIFIER_SYMBOL 24
#define UNICODE_MATH_SYMBOL 25
#define UNICODE_OTHER_SYMBOL 26
#define UNICODE_LINE_SEPARATOR 27
#define UNICODE_PARAGRAPH_SEPARATOR 28
#define UNICODE_SPACE_SEPARATOR 29
/* Call this to initialize the library. */
void unicode_init (void);
/* Returns 1 if current locale uses UTF-8 charset. If CHARSET is
not null, sets *CHARSET to the name of the current locale's
charset. This value is statically allocated. */
int unicode_get_charset (char **charset);
/* These are all analogs of the <ctype.h> functions. */
int unicode_isalnum (unicode_char_t c);
int unicode_isalpha (unicode_char_t c);
int unicode_iscntrl (unicode_char_t c);
int unicode_isdigit (unicode_char_t c);
int unicode_isgraph (unicode_char_t c);
int unicode_islower (unicode_char_t c);
int unicode_isprint (unicode_char_t c);
int unicode_ispunct (unicode_char_t c);
int unicode_isspace (unicode_char_t c);
int unicode_isupper (unicode_char_t c);
int unicode_isxdigit (unicode_char_t c);
int unicode_istitle (unicode_char_t c);
int unicode_isdefined (unicode_char_t c);
int unicode_iswide (unicode_char_t c);
/* More <ctype.h> functions. These convert between the three cases.
See the Unicode book to understand title case. */
unicode_char_t unicode_toupper (unicode_char_t c);
unicode_char_t unicode_tolower (unicode_char_t c);
unicode_char_t unicode_totitle (unicode_char_t c);
/* If C is a digit (according to `unicode_isdigit'), then return its
numeric value. Otherwise return -1. */
int unicode_digit_value (unicode_char_t c);
/* If C is a hex digit (according to `unicode_isxdigit'), then return
its numeric value. Otherwise return -1. */
int unicode_xdigit_value (unicode_char_t c);
/* Return the Unicode character type of a given character. */
int unicode_type (unicode_char_t c);
/* If P points to the middle of a Utf-8 character, this function
returns a pointer to the first byte of the character. If P points
to the start of a Utf-8 character, this function returns a pointer
to the first byte of the previous character. If P does not point
to a Utf-8 character, NULL is returned. START bounds the search;
in no case will a value before START be returned. */
char *unicode_previous_utf8 (const char *start, const char *p);
/* Return a pointer to the first byte of the next Utf-8 character
after P. This works whether P points to the start or to the middle
of a Utf-8 character. P is assumed to be nul-terminated. */
char *unicode_next_utf8 (const char *p);
/* Return the length, in characters, of P, a UTF-8 string. MAX is the
maximum number of bytes to examine. If MAX is less than 0, then P
is assumed to be nul-terminated. */
int unicode_strlen (const char *p, int max);
/* Returns the visual width, in character-size units, of P, a string.
This value may be used for tabulation. */
int unicode_string_width (const char *p);
/* Fetch the next Utf-8 character from P into RESULT, and return a
pointer to the start of the next Utf-8 character. If P is not well
formed, will return NULL. */
char *unicode_get_utf8 (const char *p, unicode_char_t *result);
/* Returns the offset within the string, in bytes, of the character offset
given. */
size_t unicode_offset_to_index(const char *p, int offset);
/* Returns the offset within the string, in characters, of the byte offset
given. */
size_t unicode_index_to_offset(const char *p, int offset);
/* Returns a pointer to the _last_ non-NULL utf-8 within the string */
char *unicode_last_utf8(const char *p);
/* Copies n characters from src to dest */
char *unicode_strncpy(char *dest, const char *src, size_t n);
/* Find the UTF-8 character corresponding to ch, in string p. These
functions are equivilants to strchr and strrchr */
char *unicode_strchr(const char *p, unicode_char_t ch);
char *unicode_strrchr(const char *p, unicode_char_t ch);
/* Pads a string to fill out a requested visual width */
void unicode_pad_string(char *dest, int right, int width, const char *string);
/* Compute canonical ordering of a string in-place. This rearranges
decomposed characters in the string according to their combining
classes. See the Unicode manual for more information. */
void unicode_canonical_ordering (unicode_char_t *string, size_t len);
/* Compute canonical decomposition of a character. Returns malloc()d
string of Unicode characters. RESULT_LEN is set to the resulting
length of the string. */
unicode_char_t *unicode_canonical_decomposition (unicode_char_t ch,
size_t *result_len);
/* An opaque type used by the iconv workalike. */
typedef struct unicode_iconv_i *unicode_iconv_t;
/* Create a new iconv conversion instance. TOCODE is the destination
charset, FROMCODE is the source charset. Returns -1 if a charset
name is not recognized or if out of memory. Can set errno to
ENOMEM or EINVAL. */
unicode_iconv_t unicode_iconv_open (const char *tocode, const char *fromcode);
/* Close an iconv conversion instance. */
int unicode_iconv_close (unicode_iconv_t cd);
/* Convert characters from INBUF into OUTBUF. Parameters are in/out
and are updated by this function. Returns -1 and sets errno on
error (including E2BIG if not enough room left in output buffer).
Otherwise returns number of conversions performed; this can be 0.
Note that on some systems EILSEQ (a possible error code) is not
defined. On such systems we use EBADMSG instead. */
ssize_t unicode_iconv (unicode_iconv_t cd,
const char **inbuf, size_t *inbytesleft,
char **outbuf, size_t *outbytesleft);
#ifdef __cplusplus
}
#endif
#endif /* UNICODE_H */
|
C
|
#include<stdio.h>
#include<math.h>
//Input seconds, output ??Hours ??minutes ??seconds,
//
void main()
{
long input_seconds;
long output_hours, output_minutes,output_seconds;
printf("Input the Total seconds that will be converted to HH:MM:SS \n");
scanf("%d",&input_seconds);
output_hours = input_seconds / 3600;
output_minutes = input_seconds % 3600 /60 ;
output_seconds = input_seconds %60;
printf("the seconds %d is %d hours %d minutes %d seconds.\n",input_seconds ,output_hours,output_minutes,output_seconds);
}
|
C
|
/*
* app.c
*
* Created on: 3 févr. 2020
* Author: eleve
*/
#include "app.h"
#include "square.h"
Uint32 _AppAnimateCallBack(Uint32 interval, void*pParam);
void _AppCreateSquare(int x, int y);
void _AppMouseButtonUp(SDL_Event*pEvent);
enum APP_STATUS {
ST_ALL_CLEARED = 0x00000000,
ST_ALL_SETTED = 0xFFFFFFFF,
};
static struct {
Uint32 nStatus;
Uint32 nWindowID;
SDL_Window * pWindow;
SDL_Renderer * pRenderer;
SDL_Color colorBkgnd;
SDL_Point windowSize;
SDL_TimerID nTimerID;
int nbSquares;
//struct s_square * pSquares[NB_SQUARES];
struct s_square * pSquares;
}app;
int AppNew(char*strWinTitle){
app.nStatus = ST_ALL_CLEARED;
app.nWindowID = -1;
app.pRenderer = NULL;
app.pWindow = NULL;
app.colorBkgnd.r = 0;
app.colorBkgnd.g = 0;
app.colorBkgnd.b = 0;
app.colorBkgnd.a = 255;
app.pSquares = NULL;
app.nbSquares = 0;
srand((unsigned int)time(NULL));
if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_TIMER) != 0) {
fprintf(stderr, "SDL video init failed: %s\n", SDL_GetError());
return EXIT_FAILURE;
}
app.pWindow = SDL_CreateWindow(
strWinTitle,
SDL_WINDOWPOS_UNDEFINED,
SDL_WINDOWPOS_UNDEFINED,
SCREEN_WIDTH,
SCREEN_HEIGHT,
SDL_WINDOW_SHOWN
);
if (app.pWindow == NULL) {
fprintf(stderr, "Window could not be created: %s\n", SDL_GetError());
SDL_Quit();
return EXIT_FAILURE;
}
app.nWindowID = SDL_GetWindowID(app.pWindow);
SDL_GetWindowSize(app.pWindow, &app.windowSize.x, &app.windowSize.y);
app.pRenderer = SDL_CreateRenderer(app.pWindow,-1, SDL_RENDERER_ACCELERATED);
if(app.pRenderer==NULL) {
fprintf(stderr, "Failed to create accelerated renderer.\n");
app.pRenderer = SDL_CreateRenderer(app.pWindow,-1, SDL_RENDERER_SOFTWARE);
if(app.pRenderer==NULL){
fprintf(stderr, "Failed to create software renderer.\n");
SDL_DestroyWindow(app.pWindow);
SDL_Quit();
app.pWindow = NULL;
return EXIT_FAILURE;
}
fprintf(stderr, "Software renderer created instead!\n");
}
/*SDL_Point speed;
for(int nbCreateSquares = 0; nbCreateSquares < NB_SQUARES; nbCreateSquares++) {
do {
speed.x = rand() % (SPEED_MAX - SPEED_MIN + 1) - SPEED_MAX;
speed.y = rand() % (SPEED_MAX - SPEED_MIN + 1) - SPEED_MAX;
} while(speed.x == 0 || speed.y == 0);
app.pSquares[nbCreateSquares] = SquareNew(NULL,
rand() % (app.windowSize.x - SQUARE_SIZE),
rand() % (app.windowSize.y - SQUARE_SIZE),
SQUARE_SIZE,
speed.x,
speed.y,
rand() % (COLOR_MAX - COLOR_MIN + 1) - COLOR_MIN,
rand() % (COLOR_MAX - COLOR_MIN + 1) - COLOR_MIN,
rand() % (COLOR_MAX - COLOR_MIN + 1) - COLOR_MIN,
rand() % (COLOR_MAX - COLOR_MIN + 1) - COLOR_MIN);
app.pSquares[nbCreateSquares] = SquareDraw(app.pSquares[nbCreateSquares], app.pRenderer);
}*/
SDL_RenderPresent(app.pRenderer);
app.nTimerID = SDL_AddTimer(ANIMATION_TICK, _AppAnimateCallBack, NULL);
return 0;
}
int AppDel(void){
/*for(int k = 0; k < NB_SQUARES; k++){
if(app.pSquares[k] != NULL)
app.pSquares[k] = SquareDel(app.pSquares[k], app.pRenderer, app.colorBkgnd);
}*/
while(app.pSquares != NULL)
{
app.pSquares = SquareDel(app.pSquares, app.pRenderer, app.colorBkgnd);
}
SDL_RemoveTimer(app.nTimerID);
if(app.pWindow){
SDL_DestroyWindow(app.pWindow);
app.pWindow = NULL;
}
if(app.pRenderer){
SDL_DestroyRenderer(app.pRenderer);
app.pRenderer = NULL;
}
app.nWindowID = -1;
SDL_Quit();
return 0;
}
int AppRun(void){
int quit;
SDL_Event event;
quit = 0;
while(!quit){
while(SDL_PollEvent(&event)) {
switch(event.type) {
case SDL_WINDOWEVENT:
if (event.window.windowID != app.nWindowID) break;
switch (event.window.event) {
case SDL_WINDOWEVENT_CLOSE:
event.type = SDL_QUIT;
SDL_PushEvent(&event);
break;
default:
break;
}
break;
case SDL_QUIT:
quit = 1;
break;
case SDL_KEYUP:
switch(event.key.keysym.sym) {
case SDLK_ESCAPE:
quit =1;
break;
case SDLK_SPACE:
_AppCreateSquare(rand() % (app.windowSize.x - SQUARE_SIZE), rand() % (app.windowSize.y - SQUARE_SIZE));
break;
default:
break;
}
break;
case SDL_MOUSEBUTTONUP:
_AppMouseButtonUp(&event);
break;
default:
break;
}
}
}
return 0;
}
Uint32 _AppAnimateCallBack(Uint32 interval, void*pParam){
/*for(int k = 0; k < NB_SQUARES; k++){
if(app.pSquares[k] != NULL)
SquareMove(app.pSquares[k], app.pRenderer, app.colorBkgnd, SCREEN_WIDTH, SCREEN_HEIGHT);
}*/
struct s_square* pScan, *pNext;
char buf[8];
int k = 0;
pScan = app.pSquares;
while(pScan != NULL) {
pScan = SquareMove(pScan, app.pRenderer, app.colorBkgnd, SCREEN_WIDTH, SCREEN_HEIGHT);
k++;
}
/*sprintf(buf, "%d", k);
SDL_SetWindowTitle(app.pWindow, buf);*/
pScan = app.pSquares;
while(pScan != NULL) {
pNext = SquareNext(pScan);
while (pNext != NULL) {
pNext = SquareCollision(pScan, pNext, app.pSquares, app.pRenderer, app.colorBkgnd);
}
pScan = SquareNext(pScan);
}
SDL_RenderPresent(app.pRenderer);
return interval;
}
void _AppCreateSquare(int x, int y){
SDL_Point speed;
speed.x = rand() % (SPEED_MAX - SPEED_MIN + 1) - SPEED_MAX;
speed.y = rand() % (SPEED_MAX - SPEED_MIN + 1) - SPEED_MAX;
if(app.pSquares == NULL) {
app.pSquares = SquareNew(
NULL,
x,
y,
SQUARE_SIZE,
speed.x,
speed.y,
rand() % (COLOR_MAX - COLOR_MIN + 1) - COLOR_MIN,
rand() % (COLOR_MAX - COLOR_MIN + 1) - COLOR_MIN,
rand() % (COLOR_MAX - COLOR_MIN + 1) - COLOR_MIN,
255
);
} else {
struct s_square* pScan;
pScan = app.pSquares;
while(SquareNext(pScan) != NULL) { pScan = SquareNext(pScan); }
SquareAdd(pScan, SquareNew(
NULL,
x,
y,
SQUARE_SIZE,
speed.x,
speed.y,
rand() % (COLOR_MAX - COLOR_MIN + 1) - COLOR_MIN,
rand() % (COLOR_MAX - COLOR_MIN + 1) - COLOR_MIN,
rand() % (COLOR_MAX - COLOR_MIN + 1) - COLOR_MIN,
255
)
);
}
}
void _AppMouseButtonUp(SDL_Event*pEvent) {
int x, y;
x = pEvent->motion.x;
y = pEvent->motion.y;
if (pEvent->button.button == SDL_BUTTON_LEFT) { _AppCreateSquare(x, y); }
else {
if (app.pSquares != NULL) {
app.pSquares = SquareDel(app.pSquares, app.pRenderer, app.colorBkgnd);
}
}
}
|
C
|
/**
* @file game.c
* @author Adam Sinclair
* @created Tues March 27 2018
* @purpose Entry point for Dog Gone Wild
**/
#include "game.h"
#include "debug.h"
void animationDone(char* animation)
{
return;
}
void setupAnimations(AnimatedSprite* as)
{
int frameCount = 4;
Vector2 left_location = {0, 60};
Vector2 left_size = {20,24};
Vector2 left_offset = {0, 0};
addAnimation(as, "walkLeft", frameCount, left_location, left_size, left_offset);
Vector2 right_location = {0, 90};
Vector2 right_size = left_size;
Vector2 right_offset = left_offset;
addAnimation(as, "walkRight", frameCount, right_location, right_size, right_offset);
Vector2 crouch_left_location = {110, 140};
Vector2 crouch_left_size = {20, 20};
Vector2 crouch_left_offset = {0, 0};
addAnimation(as, "crouchLeft", 1, crouch_left_location, crouch_left_size, crouch_left_offset);
Vector2 crouch_right_location = {110, 120};
Vector2 crouch_right_size = {20, 20};
Vector2 crouch_right_offset = {0, 0};
addAnimation(as, "crouchRight", 1, crouch_right_location, crouch_right_size, crouch_right_offset);
// Set animation to idle position
strcpy(as->currentAnimation, "walkRight");
strcpy(as->lastAnimation, "");
}
void updateSprite()
{
return;
}
void deleteSprite()
{
return;
}
Game initializeGame(int width, int height)
{
if(SDL_Init(SDL_INIT_EVERYTHING)) {
log_error_exit("Failed to initialize SDL. %s\n", SDL_GetError());
}
Game game;
game.width = width;
game.height = height;
game.graphics = initializeGraphics(game.width, game.height);
game.input = initializeInput();
game.player = createAnimatedSprite(
&game.graphics,
"assets/sprites/ff6-sabin.png",
4, // # of animations a sprite has
3,62, // Location in spritesheet
16,24, // Size
100,100, // Position in game
100, // Time to update (in ms)
&updateSprite,
&deleteSprite,
&setupAnimations,
&animationDone
);
return game;
}
void destroyGame(Game* game)
{
if(game == NULL) {
log_error_exit("Game pointer is NULL. %s\n", SDL_GetError());
}
printf("Destroying game ... was exit requested? [%d]\n", game->input.exitRequested);
destroyInput(&game->input);
destroyGraphics(&game->graphics);
SDL_Quit();
}
void runGame(Game* game)
{
loopGame(game, &game->input, &game->graphics);
}
void loopGame(Game* game, Input* input, Graphics* graphics)
{
if(input == NULL) {
log_error_exit("Input is NULL. %s\n", SDL_GetError());
}
// ===================================================
// == Initialize animations before game loop starts ==
// ===================================================
game->player.setupAnimations(&game->player);
// Keep track of time
double currentTime = SDL_GetTicks();
while(true)
{
double newTime = SDL_GetTicks();
double deltaTime = newTime - currentTime;
if(deltaTime < 13) {
continue;
}
printf("Delta time: %.2f\n", deltaTime);
currentTime = newTime;
// TODO: Safe shutdown when user wants to exit
if(wasKeyPressed(input, SDL_SCANCODE_ESCAPE) || wasExitRequested(input)) {
return;
}
else if(isKeyHeld(input, SDL_SCANCODE_S) && isKeyHeld(input, SDL_SCANCODE_D)) {
game->player.facingLeft = false;
playAnimation(&game->player, "crouchRight", false);
}
else if(isKeyHeld(input, SDL_SCANCODE_S) && isKeyHeld(input, SDL_SCANCODE_A)) {
game->player.facingLeft = true;
playAnimation(&game->player, "crouchLeft", false);
}
else if(isKeyHeld(input, SDL_SCANCODE_D)) {
game->player.facingLeft = false;
playAnimation(&game->player, "walkRight", false);
}
else if(isKeyHeld(input, SDL_SCANCODE_A)) {
game->player.facingLeft = true;
playAnimation(&game->player, "walkLeft", false);
}
else if(isKeyHeld(input, SDL_SCANCODE_S)) {
if(game->player.facingLeft)
playAnimation(&game->player, "crouchLeft", false);
else
playAnimation(&game->player, "crouchRight", false);
}
// TODO: Create idle animation
else {
if(game->player.facingLeft)
playAnimation(&game->player, "walkLeft", false);
else
playAnimation(&game->player, "walkRight", false);
}
updateGame(game, input, MIN(deltaTime, MAX_FRAME_TIME));
drawGame(game, graphics);
}
}
void updateGame(Game* game, Input* input, float elapsedTime)
{
if(game == NULL) {
log_error_exit("Game pointer is NULL. %s\n", SDL_GetError());
}
updateInput(input);
updateAnimatedSprite(&game->player, elapsedTime);
return;
}
void drawGame(Game* game, Graphics* graphics)
{
if(graphics == NULL)
log_error_exit("Graphics pointer is NULL. %s\n", SDL_GetError());
if(game == NULL)
log_error_exit("Game pointer is NULL. %s\n", SDL_GetError());
clearGraphics(graphics);
Vector2 location = {100, 100};
drawAnimatedSprite(graphics, &game->player, location);
renderGraphics(graphics);
}
|
C
|
#include "common.h"
#include <string.h>
static int setbootcounter_emmc(unsigned char val);
static int setbootcounter_nvram(unsigned char val);
int gethwcode()
{
static int hw_code = -1;
// return cached value if already called
if (hw_code != -1)
return hw_code;
int hc = -1;
char cmdline[MAXPATHLENGTH];
memset(cmdline, 0, MAXPATHLENGTH);
if (sysfs_read(CMDLINEPATH,"cmdline",cmdline,MAXPATHLENGTH-1))
return -1;
char * pch;
pch = strstr(cmdline, "hw_code=") + strlen("hw_code=");
if (pch == NULL)
return -1;
if (sscanf (pch,"%d %*s", &hc) < 1)
return -1;
hw_code = hc;
fprintf(stderr, "Detected hw_code: %d\n", hw_code);
return hw_code;
}
int setbootcounter(unsigned char val)
{
int hw_code = gethwcode();
switch (hw_code)
{
case PGDXCA16_VAL:
case PGDXCA18_VAL:
fprintf(stderr, "Setting boot counter %d in eMMC\n", val);
return setbootcounter_emmc(val);
default:
fprintf(stderr, "Setting boot counter %d in NVRAM\n", val);
return setbootcounter_nvram(val);
}
}
/***********************************************************************************************************
Set the bootcounter (in eMMC) to the specified value
***********************************************************************************************************/
#define BOOT1DEVICE "/dev/mmcblk1boot1"
#define BOOT1ROSYSFS "/sys/block/mmcblk1boot1/force_ro"
static int setbootcounter_emmc(unsigned char val)
{
#define BC_MAGIC 0xbc
unsigned char buff[2];
buff[0] = BC_MAGIC;
buff[1] = val;
FILE* sysfs_ro = fopen(BOOT1ROSYSFS, "w");
FILE* fp = fopen(BOOT1DEVICE, "wb");
if(fp == NULL || sysfs_ro == NULL)
{
fprintf(stderr,"setbootcounter cannot open file -> %s \n",BOOT1DEVICE);
return -1;
}
if (fseek(fp, 0x80000, SEEK_SET))
{
fprintf(stderr,"setbootcounter cannot open file -> %s \n",BOOT1DEVICE);
return -1;
}
fputs("0", sysfs_ro);
fflush(sysfs_ro);
fwrite(buff,1,2,fp);
fflush(fp);
fclose(fp);
fputs("1", sysfs_ro);
fflush(sysfs_ro);
fclose(sysfs_ro);
return 0;
}
/***********************************************************************************************************
Set the bootcounter (in NVRAM) to the specified value
***********************************************************************************************************/
#define NVRAMDEVICE "/sys/class/rtc/rtc0/device/nvram"
static int setbootcounter_nvram(unsigned char val)
{
#define NVRAM_MAGIC 0xbc
unsigned char buff[2];
buff[0] = NVRAM_MAGIC;
buff[1] = val;
// Opens the nvram device and updates the bootcounter
FILE* fp;
if((fp = fopen(NVRAMDEVICE, "w"))==NULL)
{
fprintf(stderr,"setbootcounter cannot open file -> %s \n",NVRAMDEVICE);
return -1;
}
fwrite(buff,1,2,fp);
fflush(fp); //Just in case ... but not really needed
fclose(fp);
return 0;
}
//Helper function for reading a parameter from sysfs
int sysfs_read(char* pathto, char* fname, char* value, int n)
{
char str[MAXPATHLENGTH];
FILE* fp;
strncpy(str,pathto,MAXPATHLENGTH);
strncat(str,fname,MAXPATHLENGTH);
if((fp = fopen(str, "rb"))==NULL)
{
fprintf(stderr,"Cannot open sysfs file -> %s \n",str);
return -1;
}
rewind(fp);
fread (value, 1, n, fp);
fclose(fp);
return 0;
}
//Helper function for writing a parameter to sysfs
int sysfs_write(char* pathto, char* fname, char* value)
{
char str[MAXPATHLENGTH];
FILE* fp;
strncpy(str,pathto,MAXPATHLENGTH);
strncat(str,fname,MAXPATHLENGTH);
if((fp = fopen(str, "ab"))==NULL)
{
fprintf(stderr,"Cannot open sysfs file -> %s \n",str);
return -1;
}
rewind(fp);
fwrite(value,1,strlen(value),fp);
fclose(fp);
return 0;
}
|
C
|
static struct rico_physics *make_physics(struct vec3 min_size)
{
struct rico_physics *phys = calloc(1, sizeof(struct rico_physics));
phys->min_size = min_size;
return phys;
}
static void free_physics(struct rico_physics *phys)
{
free(phys);
phys = NULL;
}
static void update_physics(struct rico_physics *phys, int bucket_count)
{
for (int i = 0; i < bucket_count; i++)
{
phys->vel.x += phys->acc.x;
phys->vel.y += phys->acc.y;
phys->vel.z += phys->acc.z;
phys->pos.x += phys->vel.x;
phys->pos.y += phys->vel.y;
phys->pos.z += phys->vel.z;
}
}
|
C
|
#include <stdio.h>
//Inventory of Phone Tech Specs owned by
//CMSC11 students v2.0
//includes new structure for student owner
struct phone{//forward referencing structure
int phoneID;
char brandName[10];
float price;
char phoneOS[10];
struct student *owner;
};
struct student{
int studentID;
char lastName[20];
char firstName[20];
};
struct phone updateInfo(struct phone inputPhone);
void displayInfo(struct phone *inputPhonePtr);
int main(void){
struct student s1 = {
10,
"Simpson",
"Bart"
};
struct phone p1 = {
111,
"Huawei",
34.5,
"Android",
&s1
};
/*display phone masterlist before any updates to student record*/
displayInfo(&p1);
/*Update first name the second time and display if changes are reflected*/
printf("\n\nUpdate again First Name of student: ");
scanf("%19[^\n]s", &s1.firstName);
displayInfo(&p1);
/*Update first name the second time and display if changes are reflected*/
printf("\n\nUpdate again First Name of student: ");
scanf("%19[^\n]s", &s1.firstName);
displayInfo(&p1);
return 0;
}
void displayInfo(struct phone *inputPhonePtr){
printf("\n\nPHONE MASTERLIST\nPhoneID\t\tBrand Name\tPrice\t\tOS\t\tOwner's First Name\n");
printf("%d\t\t", inputPhonePtr->phoneID);
printf("%s\t\t", inputPhonePtr->brandName);
printf("%f\t\t", inputPhonePtr->price);
printf("%s\t\t", inputPhonePtr->phoneOS);
printf("%s\t\t", inputPhonePtr->owner->firstName);
}
|
C
|
/**
* _strspn - compute length of matching contiguous bytes
* @s: string to calculate substring length from
* @accept: string containing bytes to match
* Return: length of matching contiguous bytes
*/
unsigned int _strspn(char *s, char *accept)
{
unsigned int count = 0, match = 0, i;
while (*s)
{
for (i = 0; accept[i]; i++)
{
if (*s == accept[i])
{
count++;
match = 1;
}
}
if (!match)
return (count);
match = 0;
s++;
}
return (count);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <arpa/inet.h>
#include <sys/wait.h>
#include <signal.h>
#define MYPORT "9999"
#define BACKLOG 10
void sigchld_handler(int s){
while(waitpid(-1,NULL,WNOHANG)>0);
}
void *get_in_addr(struct sockaddr *sa){
if(sa->sa_family==AF_INET){
return &((( struct sockaddr_in*)sa)->sin_addr );
}
return &((( struct sockaddr_in6*)sa)->sin6_addr );
}
int main(void){
int sockfd,new_fd;
struct addrinfo hints,*servinfo,*p;
struct sockaddr_storage their_addr;
socklen_t sin_size;
struct sigaction sa;
int yes=1;
char s[INET6_ADDRSTRLEN];
int rv;
memset(&hints,0,sizeof hints);
hints.ai_family=AF_UNSPEC;
hints.ai_socktype=SOCK_STREAM;
hints.ai_flags=AI_PASSIVE;
if( (rv=getaddrinfo(NULL,MYPORT,&hints,&servinfo)) !=0){
fprintf(stderr,"getaddrinfo:%s\n",gai_strerror(rv));
return 1;
}
for(p=servinfo;p!=NULL;p=p->ai_next){
if((sockfd=socket(p->ai_family,p->ai_socktype,p->ai_protocol)) ==-1){
perror("erver:socket");
continue;
}
if(setsockopt(sockfd,SOL_SOCKET,SO_REUSEADDR,&yes,sizeof(int))==-1){
perror("setsockopt");
exit(1);
}
if(bind(sockfd,p->ai_addr,p->ai_addrlen)==-1){
close(sockfd);
perror("server:bind");
continue;
}
break;
}
if(p==NULL){
fprintf(stderr,"server:failed to bind\n");
return 2;
}
freeaddrinfo(servinfo);
if(listen(sockfd,BACKLOG)==-1){
perror("listen");
exit(1);
}
sa.sa_handler=sigchld_handler;
sigemptyset(&sa.sa_mask);
sa.sa_flags=SA_RESTART;
if(sigaction(SIGCHLD,&sa,NULL)==-1){
perror("sigaction");
exit(1);
}
printf("server:waiting for connections....");
while(1){
sin_size=sizeof their_addr;
new_fd=accept(sockfd,(struct sockaddr *)&their_addr,&sin_size);
if(new_fd==-1){
perror("accept");
continue;
}
inet_ntop(their_addr.ss_family,get_in_addr(( struct sockaddr *)&their_addr),s,sizeof s);
printf("server:got connection from %s \n",s);
if( !fork()){
close(sockfd);
if(send(new_fd,"Hello world!",13,0)==-1)
perror("send");
close(new_fd);
exit(0);
}
close(new_fd);
}
return 0;
}
|
C
|
/*
write a program to count number of zero and one's bit in a given number
*/
#include<stdio.h>
int countZeroBits(int no);
int countOneBits(int no);
int main(){
int no;
printf("Enter the number:\n");
scanf("%d",&no);
printf("Count of Zero bits is:%d\n",countZeroBits(no));
printf("Count of One bits is:%d\n",countOneBits(no));
return 0;
}
int countZeroBits(int no){
int x=1;
int count=0;
while(x!=0)
{
if((no&x)==0)
count++;
x=x<<1;
}
return count;
}
int countOneBits(int no){
int x=1;
int count=0;
while(x!=0)
{
if((no&x)!=0)
count++;
x=x<<1;
}
return count;
}
|
C
|
#include<stdio.h>
double exchange (int n, double expenses[]);
double mean( int n, double numbers[]);
int main(){
int numberOfStudents;
while( scanf("%d", &numberOfStudents) ){
if(numberOfStudents == 0 ){
break;
}
double expenses[numberOfStudents];
for(int i = 0; i < numberOfStudents; i++){
scanf("%lf", &expenses[i]);
}
double result = exchange( numberOfStudents, expenses );
result = (double)((int)(result*100.0)) / 100.0;
printf("$%.2lf\n",result);
}
}
double exchange (int n, double expenses[]){
double ans, avg, result;
avg = mean(n, expenses);
for(int i =0; i < n; i++){
if(expenses[i] < avg){
ans = avg - expenses[i];
result += ans;
}
}
return result;
}
double mean( int n, double numbers[]){
double avg;
for(int i = 0; i < n; i++) {
avg += numbers[i];
}
return avg / (double)n;
}
/*
OUTPUT=
3
10
20
30
$10.00
4
15
15.01
3.01
3
$11.99
0
*/
|
C
|
/*
HTTP Request Parser
Parses HTTP requests into appropriate data structs
Synax to be parsed is defines as EXPECTED_FORMAT where [x] and [y] are
double and [z] is an integer
trueFalse.h contains defines to emulate boolean variables, and must be
included with this file
By: Jumail Mundekkat
*/
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#include "trueFalse.h"
#include "parser.h"
#define DOUBLE_BUFFER_SIZE 32
#define INT_BUFFER_SIZE 8
#define EXPECTED_FORMAT "/tile_x[x]_y[y]_z[z].bmp"
int decodeRequest (char * request, int requestSize, char * decodeArray, int decodeSize) {
int decodeResult = 0;
int requestEndFlag = FALSE;
int requestArrayCounter = 0;
int decodeArrayCounter = 0;
int decodeArrayEnd = 0;
assert ( requestSize > 4 );
if ( request[0] == 'G' &&
request[1] == 'E' &&
request[2] == 'T' &&
request[3] == ' ' &&
request[4] == '/') {
requestArrayCounter = 4;
while (requestArrayCounter < requestSize && requestEndFlag == FALSE) {
if (request[requestArrayCounter] != ' ') {
assert (decodeArrayCounter < decodeSize);
decodeArray[decodeArrayCounter] = request[requestArrayCounter];
requestArrayCounter++;
decodeArrayCounter++;
} else {
requestEndFlag = TRUE;
}
}
decodeArrayEnd = decodeArrayCounter - 1;
if (requestEndFlag == FALSE) {
decodeResult = BAD_REQUEST;
} else if (decodeArrayCounter > 4) {
if ( decodeArray[decodeArrayEnd - 3] == '.' &&
decodeArray[decodeArrayEnd - 2] == 'b' &&
decodeArray[decodeArrayEnd - 1] == 'm' &&
decodeArray[decodeArrayEnd] == 'p' ) {
decodeResult = BMP_REQUEST;
} else {
decodeResult = HTML_REQUEST;
}
} else {
decodeResult = HTML_REQUEST;
}
} else {
decodeResult = BAD_REQUEST;
}
return decodeResult;
}
int parseMandelbrot (char * decodedRequest, int decodedSize, MandelbrotRequest * outRequest) {
int parseResult = TRUE;
char * expectedString = EXPECTED_FORMAT;
int decodedCounter = 0;
int expectedCounter = 0;
int expectedSize = strlen(expectedString);
assert ( expectedSize > 0 );
assert ( decodedSize > 0 );
while ( decodedCounter < decodedSize && expectedCounter < expectedSize && parseResult != FALSE) {
if ( expectedString[expectedCounter] == '[') {
expectedCounter++;
assert ( expectedCounter + 1 < expectedSize );
assert ( expectedString[expectedCounter] == 'x' ||
expectedString[expectedCounter] == 'y' ||
expectedString[expectedCounter] == 'z');
char * returnAddr = NULL;
if ( expectedString[expectedCounter] == 'x' ) {
outRequest -> x = strtod(&decodedRequest[decodedCounter], &returnAddr);
} else if ( expectedString[expectedCounter] == 'y' ) {
outRequest -> y = strtod(&decodedRequest[decodedCounter], &returnAddr);
} else if ( expectedString[expectedCounter] == 'z' ) {
outRequest -> z = strtol(&decodedRequest[decodedCounter], &returnAddr, 10);
}
decodedCounter += returnAddr - &decodedRequest[decodedCounter];
expectedCounter += 2;
} else if (decodedRequest[decodedCounter] == expectedString[expectedCounter] || expectedString[expectedCounter] == '\0') {
expectedCounter++;
decodedCounter++;
} else {
parseResult = FALSE;
}
}
return parseResult;
}
|
C
|
/*
* upb - a minimalist implementation of protocol buffers.
*
* Copyright (c) 2011 Google Inc. See LICENSE for details.
* Author: Josh Haberman <jhaberman@gmail.com>
*
* A simple example that demonstrates creating a standard message object
* and parsing into it, using a dynamic reflection-based approach.
*
* Note that with this approach there are no strongly-typed struct or class
* definitions to use from C -- this is essentially a reflection-based
* interface. Note that parsing and serializing are still very fast since
* they are JIT-based.
*
* If this seems a bit verbose, you may prefer an approach that generates
* strongly-typed struct definitions (upb will likely provide this, but it is
* not yet implemented).
*
* TODO: make this file compiled as part of "make examples"
* TODO: test that this actually works (WARNING: UNTESTED!)
*/
#include "upb/msg.h"
#include "upb/pb/glue.h"
const char *descfile = "example.proto.pb";
const char *type = "example.SampleMessage";
const char *msgfile = "sample_message.pb";
int main() {
// First we load the descriptor that describes the message into a upb_msgdef.
// This could come from a string that is compiled into the program or from a
// separate file as we do here. Since defs always live in a symtab, we
// create one of those also.
upb_symtab *s = upb_symtab_new();
upb_status status = UPB_STATUS_INIT;
if (!upb_load_descriptor_file_into_symtab(s, descfile, &status)) {
fprintf(stderr, "Couldn't load descriptor file '%s': %s\n", descfile,
upb_status_getstr(&status));
return -1;
}
const upb_msgdef *md = upb_symtab_lookupmsg(s, type);
if (!md) {
fprintf(stderr, "Descriptor did not contain type '%s'\n", type);
return -1;
}
// Parse a file into a new message object.
void *msg = upb_filetonewmsg(msgfile, md, &status);
if (!msg) {
fprintf(stderr, "Error parsing message file '%s': %s\n", msgfile,
upb_status_getstr(&status));
return -1;
}
// TODO: Inspect some fields.
return 0;
}
|
C
|
#include <stdio.h>
int main()
{int a[100],b[100],i,j,n,k=0,l=0,m,z=0;
printf ("Introduceti dimensiunea vectorului: ");
scanf ("%d",&n);
printf ("Introduceti valorile vectorului: \n");
for (i=0;i<n;i++)
scanf ("%d",&a[i]);
printf ("Vectorul: \n");
for (i=0;i<n;i++)
printf ("a[%d]=%d ",i,a[i]);
printf ("\n");
for (i=0;i<n;i++)
if(a[i]==a[i+1])
k++;
if(k==n-1)
printf ("toate identice\n");
for (i=0;i<n;i++)
{for(j=0;i<n;i++)
if(i!=j)
if(a[i]==a[j])
l++;}
printf("%d",l);
printf("\n");
if(l!=0 && l<n-1)
printf ("oarecare\n");
else
if(l==0)
printf ("toate distincte\n");
for (i=0;i<n;i++)
{j=0;
//if(i!=j)
if(a[i]!=a[j])
{z++;
b[i]=a[j];
}}
printf("%d",z);
printf("\n");
for (i=0;i<z;i++)
printf ("b[%d]=%d ",i,b[i]);
printf ("\n");
}
|
C
|
#include "../headers/find_first_group.h"
#include "../headers/sort.h"
#include "../headers/neh.h"
#include "../headers/nearest_neighbor.h"
#include "../headers/calculate_tardiness.h"
#include <stdlib.h>
/*! Cette macro retourne le maximum entre @c x et @c y. */
#define MAX(x,y) ( (x) >= (y) ? (x) : (y) )
/*! Un comparateur de jobs
* @param first_job Un job, casté en <tt>void *</tt>
* @param second_job Un job, casté en <tt>void *</tt>
* @return La valeur du booléen : <tt>job_get_due_date((job) first_job) < job_get_due_date((job) second_job)</tt>
* @note Utilisé dans @ref sort(), ce comparateur permet de trier des jobs par date due croissante (tri @em EDD).
*/
static int job_comparator(void * first_job, void * second_job)
{
return job_get_due_date((job) first_job) < job_get_due_date((job) second_job);
}
unsigned int * find_first_group(instance data)
{
const unsigned int nb_jobs = instance_get_nb_jobs(data),
nb_machines = instance_get_nb_machines(data);
unsigned int * job_to_group = (unsigned int *) malloc(nb_jobs * sizeof(unsigned int)),
* job_position_to_group = (unsigned int *) malloc(nb_jobs * sizeof(unsigned int)),
id_job,
job_position,
last_group,
nb_jobs_in_last_group,
first_position_in_last_group;
job * jobs = (job *) malloc(nb_jobs * sizeof(unsigned int));
site factory = instance_extract_site(data, SITE_ID_FACTORY),
first_site_of_new_group;
flowshop fs_last, fs_insert, fs_create;
routing r_last, r_insert, r_create;
unsigned int tardiness_last, tardiness_insert, tardiness_create;
job * jobs_insert;
site * sites_insert;
unsigned int loop;
/* Extraction des jobs */
for(id_job = 1; id_job <= nb_jobs; ++id_job)
{
jobs[id_job - 1] = instance_extract_job(data, id_job);
}
/* 1. Tri EDD des jobs */
sort(nb_jobs, (void **) jobs, job_comparator);
/* 2. Création du premier groupe pour le premier job */
job_position = 1;
last_group = 1;
job_position_to_group[job_position - 1] = last_group;
first_position_in_last_group = job_position;
fs_last = flowshop_new(nb_machines, 1);
// for(loop = 1; loop <= nb_machines; ++loop) { flowshop_set_availability_date(fs_last, loop, 0); } // 0 est la valeur par défaut.
flowshop_insert_job(fs_last, jobs[job_position - 1]);
first_site_of_new_group = instance_extract_site(data, job_get_id_delivery_site(jobs[job_position - 1]));
r_last = routing_new(1, factory);
routing_set_departure_date(r_last, flowshop_get_date(fs_last, nb_machines, 1));
routing_insert_site(r_last, first_site_of_new_group);
tardiness_last = calculate_tardiness(fs_last, &(jobs[job_position - 1]), r_last, &first_site_of_new_group);
/* 3. Simulations pour les autres jobs */
jobs_insert = (job *) malloc((nb_jobs + 1) * sizeof(job));
sites_insert = (site *) malloc((nb_jobs + 1) * sizeof(site));
for(job_position = 2; job_position <= nb_jobs; ++job_position)
{
nb_jobs_in_last_group = job_position - 1 - first_position_in_last_group + 1;
/* 3.a Simulation de l'insertion dans le dernier groupe */
for(loop = 1; loop <= nb_jobs_in_last_group + 1; ++loop) { jobs_insert[loop - 1] = jobs[first_position_in_last_group - 1 + loop - 1]; }
fs_insert = flowshop_new(nb_machines, nb_jobs_in_last_group + 1);
for(loop = 1; loop <= nb_machines; ++loop) { flowshop_set_availability_date(fs_insert, loop, flowshop_get_availability_date(fs_last, loop)); }
neh(fs_insert, jobs_insert);
for(loop = 1; loop <= nb_jobs_in_last_group + 1; ++loop) { sites_insert[loop - 1] = instance_extract_site(data, job_get_id_delivery_site(jobs[first_position_in_last_group - 1 + loop - 1])); }
r_insert = routing_new(nb_jobs_in_last_group, factory);
routing_set_departure_date(r_insert, MAX(routing_get_departure_date(r_last), flowshop_get_date(fs_insert, nb_machines, nb_jobs_in_last_group + 1)));
nearest_neighbor(r_insert, sites_insert);
tardiness_insert = calculate_tardiness(fs_insert, jobs_insert, r_insert, sites_insert);
/* 3.b Simulation de la création d'un nouveau groupe */
fs_create = flowshop_new(nb_machines, 1);
for(loop = 1; loop <= nb_machines; ++loop) { flowshop_set_availability_date(fs_insert, loop, flowshop_get_date(fs_last, loop, flowshop_get_nb_jobs(fs_last))); }
flowshop_insert_job(fs_create, jobs[job_position - 1]);
first_site_of_new_group = instance_extract_site(data, job_get_id_delivery_site(jobs[job_position - 1]));
r_create = routing_new(1, factory);
routing_set_departure_date(r_insert, MAX(routing_get_arrival_date(r_last), flowshop_get_date(fs_create, nb_machines, 1)));
routing_insert_site(r_create, first_site_of_new_group);
tardiness_create = calculate_tardiness(fs_create, &(jobs[job_position - 1]), r_create, &first_site_of_new_group);
/* 3.c Conservation de la meilleure simulation */
flowshop_delete(fs_last);
routing_delete(r_last);
if(tardiness_insert <= tardiness_last + tardiness_create)
{
tardiness_last = tardiness_insert;
job_position_to_group[job_position - 1] = last_group;
fs_last = fs_insert;
flowshop_delete(fs_create);
r_last = r_insert;
routing_delete(r_create);
}
else
{
tardiness_last = tardiness_create;
job_position_to_group[job_position - 1] = ++last_group;
first_position_in_last_group = job_position;
flowshop_delete(fs_insert);
fs_last = fs_create;
routing_delete(r_insert);
r_last = r_create;
}
}
free(jobs_insert);
free(sites_insert);
/* Conversion : 'position -> ID, groupe' vers 'ID -> groupe' */
for(job_position = 1; job_position <= nb_jobs; ++job_position)
{
job_to_group[job_get_id(jobs[job_position - 1]) - 1] = job_position_to_group[job_position - 1];
}
/* Libération des ressources mémoire */
free(job_position_to_group);
free(jobs);
flowshop_delete(fs_last);
routing_delete(r_last);
return job_to_group;
}
|
C
|
#include "zbaselib_queue.h"
#define QUEUE_RETURN_VAL_IF_NULL(queue, val) \
if(queue == NULL || queue->list == NULL) \
{ \
return val; \
}
struct _zbaselib_queue
{
zbaselib_list* list;
};
zbaselib_queue* zbaselib_queue_create(destroy_data_func ddfunc)
{
zbaselib_queue* thiz = (zbaselib_queue*)malloc(sizeof(zbaselib_queue));
if(thiz != NULL)
{
if((thiz->list = zbaselib_list_create(ddfunc)) == NULL)
{
free(thiz);
thiz = NULL;
}
}
return thiz;
}
void zbaselib_queue_destroy(zbaselib_queue* thiz)
{
if(thiz != NULL)
{
if(thiz->list != NULL)
{
zbaselib_list_destroy(&thiz->list);
}
free(thiz);
}
}
static void zbaselib_queue_ddfunc(void* data, void* ctx)
{
destroy_data_func ddfunc = (destroy_data_func)ctx;
ddfunc(data);
}
// zbaselib_queue_createʱddfunc=NULLô˺queueڴй¶
void zbaselib_queue_destroy1(zbaselib_queue* thiz, destroy_data_func ddfunc)
{
if(thiz != NULL)
{
if(thiz->list != NULL)
{
zbaselib_list_foreach(thiz->list, zbaselib_queue_ddfunc, ddfunc);
zbaselib_list_destroy(&thiz->list);
}
free(thiz);
}
}
int zbaselib_queue_push(zbaselib_queue* thiz, void* data)
{
QUEUE_RETURN_VAL_IF_NULL(thiz, -1);
zbaselib_list_addtail(thiz->list, data);
return 0;
}
int zbaselib_queue_pop(zbaselib_queue* thiz)
{
QUEUE_RETURN_VAL_IF_NULL(thiz, -1);
zbaselib_list_delhead(thiz->list);
return 0;
}
void* zbaselib_queue_pop1(zbaselib_queue* thiz)
{
void* data = NULL;
QUEUE_RETURN_VAL_IF_NULL(thiz, NULL);
data = zbaselib_list_gethead(thiz->list);
zbaselib_list_delhead(thiz->list);
return data;
}
void* zbaselib_queue_peek(zbaselib_queue* thiz)
{
QUEUE_RETURN_VAL_IF_NULL(thiz, NULL);
return zbaselib_list_gethead(thiz->list);
}
int zbaselib_queue_size(zbaselib_queue* thiz)
{
QUEUE_RETURN_VAL_IF_NULL(thiz, 0);
return zbaselib_list_size(thiz->list);
}
int zbaselib_queue_empty(zbaselib_queue* thiz)
{
return zbaselib_list_empty(thiz->list);
}
zbaselib_list_iterater* zbaselib_queue_iterater_create(zbaselib_queue* thiz)
{
QUEUE_RETURN_VAL_IF_NULL(thiz, NULL);
return zbaselib_list_iterater_create(thiz->list);
}
|
C
|
//
// main.c
// ExampleC
//
// Created by Matthew Lu on 6/06/2014.
// Copyright (c) 2014 Matthew Lu. All rights reserved.
//
#include <stdio.h>
#define MAXLINE 1000 // maximum input line size
int myGetline(char line[], int maxline);
void copy(char to[], char from[]);
//print longest input line
int main(int argc, const char * argv[])
{
int len; // current line length
int max; // maximum length seen so far
char line[MAXLINE]; // current input line
char longest[MAXLINE]; //longest line saved here
max = 0;
while ((len = myGetline(line, MAXLINE)) > 0) {
printf("%d, %s",len-1,line);
if (len > max) {
max = len;
copy(longest, line);
}
}
if (max > 0) { // there was a line
printf("length : %d the line: %s",max-1, longest);
}
return 0;
}
// myGetline: read a line into s, return length
int myGetline(char s[], int lim)
{
int c=0,i,j;
j=0;
for (i=0; (c=getchar()) != EOF && c!= '\n'; ++i) {
if (i < lim-2) {
s[i]=c;
++j;
}
}
if (c == '\n') {
s[i]=c;
++j;
++i;
}
s[i] = '\0';
return i;
}
//copy: copy 'from' into 'to', assume to is big enough
void copy(char to[],char from[])
{
int i;
i=0;
while ((to[i] = from[i]) !='\0' ) {
++i;
}
}
|
C
|
//
// Created by 唐艺峰 on 2017/12/11.
//
#include "expr4.h"
void traversalCurDir(char *dirName) {
DIR *curDir = opendir(dirName);
chdir(dirName);
struct dirent *each;
long fileSize = 0;
long long maxSize = 0;
while ((each = readdir(curDir)) != 0) {
if (each->d_name[0] == '.') {
continue;
}
struct stat *buf = (struct stat *) malloc(sizeof(struct stat));
stat(each->d_name, buf);
fileSize += buf->st_blocks * S_BLKSIZE;
if (buf->st_size > maxSize) {
maxSize = buf->st_size;
}
free(buf);
}
handleDirs(dirName, fileSize / 512);
closedir(curDir);
curDir = opendir(dirName);
while ((each = readdir(curDir)) != 0) {
if (each->d_name[0] == '.') {
continue;
}
struct stat *buf = (struct stat *) malloc(sizeof(struct stat));
stat(each->d_name, buf);
handleFiles(buf, each->d_name, maxSize);
free(buf);
}
closedir(curDir);
curDir = opendir(dirName);
while ((each = readdir(curDir)) != 0) {
if (each->d_name[0] == '.') {
continue;
}
if (each->d_type == DT_DIR) {
char *addrs = (char *) malloc(sizeof(char) * (strlen(dirName) + strlen(each->d_name) + 2));
strcpy(addrs, dirName);
strcat(addrs, "/");
strcat(addrs, each->d_name);
traversalCurDir(addrs);
free(addrs);
}
}
closedir(curDir);
}
void handleDirs(char *address, long fileSize) {
printf("\n%s:\n", address);
if (fileSize != 0) {
printf("total %ld\n", fileSize);
}
}
void handleFiles(struct stat *file, char *name, long long maxSize) {
handleFileKind(file->st_mode);
handleFilePermission(file->st_mode);
handleFileUser(file->st_uid);
handleFileSize(file->st_size, maxSize);
handleDate(file->st_mtimespec);
printf("%s\n", name);
}
void handleDate(struct timespec birth) {
struct tm t;
char date_time[64];
strftime(date_time, sizeof(date_time), "%Y-%m-%d %H:%M:%S", localtime_r(&birth.tv_sec, &t));
printf("%s ", date_time);
}
void handleFileUser(uid_t st_uid) {
struct passwd *user;
struct group *group;
user = getpwuid(st_uid);
group = getgrgid(user->pw_gid);
printf("%s %s ", user->pw_name, group->gr_name);
}
void handleFileSize(off_t st_size, off_t maxSize) {
char maxArrays[50], curArrays[50];
sprintf(maxArrays, "%lld", maxSize);
sprintf(curArrays, "%lld", st_size);
size_t blank = strlen(maxArrays) - strlen(curArrays);
for (int i = 0; i < blank; i++) {
putchar(' ');
}
printf("%s ", curArrays);
}
void handleFilePermission(int fileMode) {
int filePermission = fileMode & 0777;
int readMask = 0400;
int writeMask = 0200;
int executeMask = 0100;
for (int i = 0; i < 3; i++) {
if (filePermission & readMask) {
putchar('r');
} else {
putchar('-');
}
if (filePermission & writeMask) {
putchar('w');
} else {
putchar('-');
}
if (filePermission & executeMask) {
putchar('x');
} else {
putchar('-');
}
readMask >>= 3;
writeMask >>= 3;
executeMask >>= 3;
}
putchar(' ');
}
void handleFileKind(int fileMode) {
int fileKind = fileMode & 0770000;
switch (fileKind) {
case S_IFDIR: {
putchar('d');
break;
}
case S_IFCHR: {
putchar('c');
break;
}
case S_IFBLK: {
putchar('b');
break;
}
case S_IFREG: {
putchar('-');
break;
}
case S_IFLNK: {
putchar('l');
break;
}
case S_IFSOCK: {
putchar('s');
break;
}
case S_IFIFO: {
putchar('p');
break;
}
default:
break;
}
}
int main(int argc, char *args[]) {
traversalCurDir(args[1]);
}
|
C
|
#include "argparser.h"
SpecNode *argParser(int argc, char **argv)
{
SpecNode *specifications = initSpecNode();
if (argc > 6)
{
errorReport("TOO MANY ARGUMENTS");
}
int opt;
while ((opt = getopt(argc, argv, "-:p:m:")) != -1)
{
switch (opt)
{
case 'p':
if (optarg != 0x0)
{
if (optarg[0] - '-' == 0)
{
if (isAllDigit(optarg))
{
errorReport("NEGATIVE PAGE SIZE SPECIFIED");
}
else
{
errorReport("NON NUMERICAL PAGE SIZE SPECIFIED");
}
}
if (!(isAllDigit(optarg)))
{
errorReport("NON NUMERICAL PAGE SIZE SPECIFIED");
}
unsigned long num = strtoul(optarg, NULL, 10);
if (isPowerOfTwo(num))
{
specifications->pageSize = num;
}
else
{
errorReport("PAGE SIZE SPECIFIED IS NOT POWER OF 2");
}
}
else
{
errorReport("INVALID PAGE SIZE SPECIFIED");
}
break;
case 'm':
if (optarg != 0x0)
{
if (optarg[0] - '-' == 0)
{
errorReport("NEGATIVE REAL MEMORY SIZE SPECIFIED");
}
if (!(isAllDigit(optarg)))
{
errorReport("NON NUMERICAL REAL MEMORY SIZE SPECIFIED");
}
unsigned long num = strtoul(optarg, NULL, 10);
num = num * 1048576;
specifications->memSize = num;
}
else
{
errorReport("INVALID PAGE NUMBER SPECIFIED");
}
break;
case ':':
printf("Missing arg for %c\n", optopt);
exit(-1);
break;
default:
specifications->traceFile = optarg;
}
}
return specifications;
}
SpecNode *initSpecNode()
{
SpecNode *specifications = malloc(sizeof(SpecNode));
if (specifications == NULL)
{
errorReport("BAD MALLOC OR UNABLE TO MALLOC");
}
specifications->memSize = 1048576;
specifications->pageSize = 4096;
return specifications;
}
bool isPowerOfTwo(unsigned long n)
{
if (n == 0)
return false;
return (ceil(log2(n)) == floor(log2(n)));
}
|
C
|
#include<stdio.h>
#include<stdlib.h>
typedef struct linkList{
int num;
struct linkList *next;
}LINKLIST;
//生成链表
LINKLIST *createLinklist()
{
LINKLIST *h=(LINKLIST *)malloc(sizeof(LINKLIST));
h->next=NULL;
return h;
}
//插入数据
void insertData(LINKLIST *h,int data)
{
LINKLIST *p=(LINKLIST *)malloc(sizeof(LINKLIST));
p->num=data;
p->next=h->next;
h->next=p;
}
//打印链表
void printLinklist(LINKLIST *h)
{
LINKLIST *p;
p=h->next;
while(p){
printf("%d ",p->num);
p=p->next;
}
printf("\n");
}
//直接插入排序
void insertSort(LINKLIST *h)
{
LINKLIST *key,*bkey,*p;//bkey: before key记录key前面一个节点。bp同理
p=h;
bkey=h->next;
key=bkey->next;
while(key){//key从第二个节点开始遍历链表
while(p->next!=key){
if(key->num < p->next->num){
bkey->next=key->next;//取出key节点,将Key节点的next节点接到bkey节点
key->next=p->next;
p->next=key;
break;
}else{
p=p->next;
}
}
//插入完一次,重置p节点的位置
p=h;
//key节点回到bkey的下一节点位置
key=bkey->next;
}
}
//直接插入排序2
void insertSort2(LINKLIST *h)
{//链表直接插入排序
LINKLIST *p,*q,*t;
q=h->next;
h->next=NULL;//断开头节点
while(q){
t=q->next;//保存待插入节点的后一个节点
p=h;
while((p->next)&&(q->num>p->next->num))
p=p->next;
q->next=p->next;//插入到P后
p->next=q;
q=t;//q移到下一个节点
}
}
void linkListIverse(LINKLIST *h)
{//链表倒置
LINKLIST *p,*q;
p=h->next;
h->next=NULL;//断开头节点
while(p){
q=p->next;
//重新插入一次
p->next=h->next;
h->next=p;
p=q;
}
}
int main()
{
LINKLIST *h=createLinklist();
int a[]={1,2,3,4,5};
int len=sizeof(a)/sizeof(a[0]);
int i;
for(i=0;i<len;i++){
insertData(h,a[i]);
}
printf("排序前:\n");
printLinklist(h);
linkListIverse(h);
printf("排序后:\n");
printLinklist(h);
free(h);
return 0;
}
|
C
|
#include <stdio.h>
#include <stdbool.h>
int main () {
int last_char, current_char;
bool single_comment;
bool multi_comment;
last_char = 'a';
while ((current_char = getchar()) != EOF) {
if (current_char == '\n')
single_comment = false;
else if ((current_char == '/' && last_char == '*') && !(single_comment))
multi_comment = false;
if ((current_char == '/' && last_char == '/') && !(multi_comment)) {
putchar('\b');
single_comment = true;
}
else if ((current_char == '*' && last_char == '/') && !(single_comment)) {
putchar('\b');
multi_comment = true;
}
if (!((single_comment || multi_comment)) && current_char != '/')
putchar(current_char);
last_char = current_char;
}
return 0;
}
|
C
|
/*
============================================================================
Name : coordinador.c
Author : Los Simuladores
Version : Alpha
Copyright : Todos los derechos reservados
Description : Proceso Coordinador
============================================================================
*/
#include "coordinador.h"
int buscarClaveEnListaDeClaves(void* structClaveVoid, void* claveVoid) {
Clave* structClave = (Clave*) structClaveVoid;
return strcmp(structClave->nombre, (char*) claveVoid) == 0;
}
int buscarInstanciaConClave(void* instanciaVoid, void* claveVoid) {
Instancia* instancia = (Instancia*) instanciaVoid;
return list_find_with_param(instancia->claves, claveVoid, buscarClaveEnListaDeClaves) != NULL;
}
int buscarClaveDeEsi(void* structClaveVoid, void* nombreEsiVoid) {
Clave* structClave = (Clave*) structClaveVoid;
return strcmp(structClave->nombreEsi, (char*) nombreEsiVoid) == 0;
}
int buscarInstanciaConEsi(void* instanciaVoid, void* nombreEsiVoid) {
Instancia* instancia = (Instancia*) instanciaVoid;
return list_find_with_param(instancia->claves, nombreEsiVoid, buscarClaveDeEsi) != NULL;
}
int buscarNombreDeLaInstancia(void* instancia, void* nombre) {
return strcmp(((Instancia*)instancia)->nombre, (char*)nombre) == 0;
}
void manejarInstancia(int socketInstancia, int largoMensaje) {
int tamanioInformacionEntradas = sizeof(InformacionEntradas);
InformacionEntradas * entradasInstancia = (InformacionEntradas*) malloc(tamanioInformacionEntradas);
t_config* configuracion;
char* nombreInstancia;
ContentHeader* headerEntradasLibres;
int entradasLibres;
Instancia* instanciaConectada;
void* instanciaVoid;
nombreInstancia = malloc(largoMensaje + 1);
configuracion = config_create(ARCHIVO_CONFIGURACION);
//recibimos el nombre de la instancia que se conecto
recibirMensaje(socketInstancia, largoMensaje, &nombreInstancia);
// Logueo la informacion recibida
log_trace(logCoordinador, "Se conectó la instancia de nombre: %s", nombreInstancia);
//leo cantidad entradas y su respectivo tamanio del archivo de configuracion
entradasInstancia->cantidad = config_get_int_value(configuracion, "CANTIDAD_ENTRADAS");
entradasInstancia->tamanio = config_get_int_value(configuracion, "TAMANIO_ENTRADA");
//enviamos cantidad de entradas y su respectivo tamanio a la instancia
enviarInformacion(socketInstancia, entradasInstancia, &tamanioInformacionEntradas);
//Logueamos el envio de informacion
log_trace(logCoordinador, "Enviamos a la Instancia: Cant. de Entradas = %d; Tam. de Entrada = %d", entradasInstancia->cantidad, entradasInstancia->tamanio);
// Verifico si tengo que agregar la instancia o si solo se reincorporó
pthread_mutex_lock(&mutexListaInstancias);
// Como se reincorporó, capaz ya tiene entradas usadas, por lo que recibo las libres siempre
headerEntradasLibres = recibirHeader(socketInstancia);
entradasLibres = headerEntradasLibres->id;
free(headerEntradasLibres);
instanciaVoid = list_find_with_param(listaInstancias, (void*)nombreInstancia, buscarNombreDeLaInstancia);
if (instanciaVoid == NULL) {
instanciaConectada = (Instancia*) malloc(sizeof(Instancia));
instanciaConectada->nombre = malloc(strlen(nombreInstancia) + 1);
strcpy(instanciaConectada->nombre, nombreInstancia);
instanciaConectada->nombre[strlen(nombreInstancia)] = '\0';
instanciaConectada->socket = socketInstancia;
instanciaConectada->claves = list_create();
instanciaConectada->entradasLibres = entradasLibres;
list_add(listaInstancias, (void*) instanciaConectada);
// Logueo que llegó una instancia nueva
log_trace(logCoordinador, "Se ingresó la instancia nueva <%s> con %d entradas libres", nombreInstancia, instanciaConectada->entradasLibres);
} else {
// Guardo el nuevo socket
instanciaConectada = (Instancia*)instanciaVoid;
close(instanciaConectada->socket);
instanciaConectada->socket = socketInstancia;
// Guardo las entradas libres
instanciaConectada->entradasLibres = entradasLibres;
// Logueo que se reincorporó una instancia
log_trace(logCoordinador, "Se reincorporó la instancia <%s> con %d entradas libres", nombreInstancia, instanciaConectada->entradasLibres);
}
pthread_mutex_unlock(&mutexListaInstancias);
// Libero memoria
free(entradasInstancia);
free(nombreInstancia);
config_destroy(configuracion);
}
void closeInstancia(void* instanciaVoid) {
Instancia* instancia = (Instancia*)instanciaVoid;
free(instancia->nombre);
close(instancia->socket);
free(instancia);
}
void cerrarInstancias() {
list_destroy_and_destroy_elements(listaInstancias, (void*) closeInstancia);
}
void loguearOperacion(char* nombre, char* mensaje) {
pthread_mutex_lock(&mutexLog);
FILE *f = fopen("log.txt", "a");
if (f == NULL) {
pthread_mutex_unlock(&mutexLog);
// Logueamos que no se pudo loguear la operacion
log_error(logCoordinador, "No se pudo loguear la operación");
return;
}
fprintf(f, "%s || %s\n", nombre, mensaje);
fclose(f);
pthread_mutex_unlock(&mutexLog);
// Logueo que loguié
log_trace(logCoordinador, "Se pudo loguear: %s || %s", nombre, mensaje);
}
int tiempoRetardoFicticio() {
t_config* configuracion;
int retardo;
configuracion = config_create(ARCHIVO_CONFIGURACION);
retardo = config_get_int_value(configuracion, "RETARDO");
config_destroy(configuracion);
// La funcion usleep usa microsegundos (1 miliseg = 1000 microseg)
return retardo * 1000;
}
void manejarEsi(int socketEsi, int socketPlanificador, int largoMensaje) {
char* nombre;
char* mensaje;
char** mensajeSplitted;
ContentHeader * header;
// Recibo nombre esi
nombre = malloc(largoMensaje + 1);
recibirMensaje(socketEsi, largoMensaje, &nombre);
// Recibo mensaje del esi
header = recibirHeader(socketEsi);
mensaje = malloc(header->largo + 1);
recibirMensaje(socketEsi, header->largo, &mensaje);
// Logueo la operación
loguearOperacion(nombre, mensaje);
// Logueo el mensaje
log_trace(logCoordinador, "Recibimos el mensaje: Nombre = %s; Mensaje = %s", nombre, mensaje);
// Retraso ficticio de la ejecucion
int retardo = tiempoRetardoFicticio();
log_trace(logCoordinador, "Hago un retardo de %d microsegundos", retardo);
usleep(retardo);
// Ejecuto
mensajeSplitted = string_split(mensaje, " ");
if (strcmp(mensajeSplitted[0], "GET") == 0) {
// Se ejecuta un GET
getClave(mensajeSplitted[1], socketPlanificador, socketEsi, nombre);
log_trace(logCoordinador, "Se ejecuto un GET");
} else if (strcmp(mensajeSplitted[0], "SET") == 0 || strcmp(mensajeSplitted[0], "STORE") == 0) {
// EL SET y el STORE se manejan a través del ejecutarSentencia
ejecutarSentencia(socketEsi, socketPlanificador, mensaje, nombre);
log_trace(logCoordinador, "Se ejecuto un %s", mensajeSplitted[0]);
if (strcmp(mensajeSplitted[0], "SET") == 0) {
free(mensajeSplitted[2]);
}
} else {
log_error(logCoordinador, "Error en el mensaje enviado por el ESI");
}
// Libero memoria
free(header);
free(nombre);
free(mensaje);
free(mensajeSplitted[0]);
free(mensajeSplitted[1]);
free(mensajeSplitted);
close(socketEsi);
}
void manejarConexion(void* socketsNecesarios) {
SocketHilos socketsConectados = *(SocketHilos*) socketsNecesarios;
ContentHeader * header;
header = recibirHeader(socketsConectados.socketComponente);
switch (header->id) {
case INSTANCIA:
log_trace(logCoordinador, "Se conectó una instancia");
manejarInstancia(socketsConectados.socketComponente, header->largo);
llegoUnaInstancia = 1;
break;
case ESI:
log_trace(logCoordinador, "Se conectó un ESI");
manejarEsi(socketsConectados.socketComponente, socketsConectados.socketPlanificador, header->largo);
break;
}
free(header);
}
int correrEnHilo(SocketHilos socketsConectados) {
pthread_t idHilo;
if (pthread_create(&idHilo, NULL, (void*) manejarConexion, (void*) &socketsConectados)) {
log_error(logCoordinador, "No se pudo crear el hilo");
return 0;
}
log_trace(logCoordinador, "Hilo asignado");
pthread_join(idHilo, NULL);
return 1;
}
char* obtenerValorClaveInstancia(int socketInstancia, char* nombreClave){
ContentHeader* header;
char* valorClave;
// Envio la clave de la cual quiero su contenido
enviarHeader(socketInstancia, nombreClave, COMANDO_STATUS);
enviarMensaje(socketInstancia, nombreClave);
// Recibo contenido de la instancia
header = recibirHeader(socketInstancia);
switch(header->id){
case COMANDO_STATUS_VALOR_CLAVE_OK: // Si hay un valor en esa clave
valorClave = malloc(header->largo + 1);
recibirMensaje(socketInstancia, header->largo, &valorClave);
valorClave[header->largo] = '\0';
break;
case COMANDO_STATUS_VALOR_CLAVE_NULL: // Si no hay un valor en esa clave
valorClave = NULL;
break;
}
free(header);
return valorClave;
}
void manejarComandoStatus(int socketPlanificador, int largoMensaje){
char* nombreClave = malloc(largoMensaje +1);
char* valorClave;
char* nombreInstancia;
Instancia* instanciaNueva = malloc(sizeof(Instancia));
char* nombreInstanciaNueva;
Instancia* instancia;
void* instanciaVoid;
Clave* clave;
void* claveVoid;
// Recibo nombre de la clave
recibirMensaje(socketPlanificador, largoMensaje, &nombreClave);
//TODO Busco clave y paso sus datos (valor, instancia en la que se guardaria)
// Busco la clave en la lista de instancias
pthread_mutex_lock(&mutexListaInstancias);
instanciaVoid = list_find_with_param(listaInstancias, (void*) nombreClave, buscarInstanciaConClave);
// Si encontré una instancia, busco la clave
claveVoid = (instanciaVoid != NULL ? list_find_with_param(((Instancia*) instanciaVoid)->claves, (void*) nombreClave, buscarClaveEnListaDeClaves) : NULL);
pthread_mutex_unlock(&mutexListaInstancias);
if(instanciaVoid != NULL){
instancia = (Instancia*) instanciaVoid;
clave = (Clave*) claveVoid;
// Obtengo nombre de la instancia que contiene la clave
nombreInstancia = malloc(strlen(instancia->nombre) + 1);
strcpy(nombreInstancia, instancia->nombre);
nombreInstancia[strlen(instancia->nombre)] = '\0';
// Obtengo contenido de la clave, necesito recibirlo de la instancia
valorClave = obtenerValorClaveInstancia(instancia->socket, clave->nombre);
} else {
// En caso de que la clave no se encuentre en una instancia, por ende no tiene valor
valorClave = NULL;
nombreInstancia = NULL;
}
// Vuelvo a calcular en que instancia ubicaria ahora a la clave
instanciaNueva = seleccionarInstanciaAlgoritmoDistribucion(clave);
// Obtengo nombre de la instancia que contendria a la clave
nombreInstanciaNueva = malloc(strlen(instanciaNueva->nombre) + 1);
strcpy(nombreInstanciaNueva, instanciaNueva->nombre);
nombreInstanciaNueva[strlen(instanciaNueva->nombre)] = '\0';
//Le envio uno por uno la informacion obtenida al planificador
// Envio valor de la clave
enviarHeader(socketPlanificador, valorClave, COMANDO_STATUS);
enviarMensaje(socketPlanificador, valorClave);
// Envio instancia en la que se encuentra la clave
enviarHeader(socketPlanificador, nombreInstancia, COMANDO_STATUS);
enviarMensaje(socketPlanificador, nombreInstancia);
// Envio instancia en la que se guardaria actualmente la clave
enviarHeader(socketPlanificador, nombreInstanciaNueva, COMANDO_STATUS);
enviarMensaje(socketPlanificador, nombreInstanciaNueva);
// Libero memoria
if(valorClave != NULL){
free(valorClave);
}
free(nombreInstancia);
free(nombreInstanciaNueva);
free(nombreClave);
free(instanciaNueva);
}
void desbloquearClavesQueTenganEsi(void* nombreEsi, void* clave) {
if (strcmp(((Clave*) clave)->nombreEsi, (char*) nombreEsi) == 0) {
log_trace(logCoordinador, "Desbloqueo la clave %s del esi %s", ((Clave*) clave)->nombre, ((Clave*) clave)->nombreEsi);
((Clave*) clave)->bloqueado = 0;
}
}
void manejarComandoKill(int socketPlanificador, int largoMensaje){
void* instanciaVoid;
char* nombreEsi = malloc(largoMensaje +1);
// Recibo nombre del esi
recibirMensaje(socketPlanificador, largoMensaje, &nombreEsi);
// Busco instancias con claves del esi
pthread_mutex_lock(&mutexListaInstancias);
// Duplico la lista de instancias, voy recorriendolas y desbloqueo todas las claves
t_list* duplicada = list_duplicate(listaInstancias);
while ((instanciaVoid = list_remove_by_condition_with_param(duplicada, (void*) nombreEsi, buscarInstanciaConEsi)) != NULL){
// Busco claves del esi en la instancia
list_iterate_with_param(((Instancia*) instanciaVoid)->claves, (void*) nombreEsi, desbloquearClavesQueTenganEsi);
}
list_destroy(duplicada);
pthread_mutex_unlock(&mutexListaInstancias);
free(nombreEsi);
}
void manejarBloquearClaveManual(int socketPlanificador, int largoMensaje) {
char** claves;
char* todasLasClaves = malloc(largoMensaje +1);
// Recibo las claves que tengo que bloquear
recibirMensaje(socketPlanificador, largoMensaje, &todasLasClaves);
// Logueo la recepción
log_trace(logCoordinador, "Se recibieron las claves <%s> para bloquear", todasLasClaves);
// Espero hasta que llegue una instancia
while(llegoUnaInstancia == 0);
if (guardarClavesBloqueadasAlIniciar) {
// Recorro todas las claves y bloqueo una por una
claves = string_split(todasLasClaves, ",");
for (int i = 0; claves[i] != NULL; i++) {
asignarClaveAInstancia(claves[i], "");
free(claves[i]);
}
free(claves);
}
free(todasLasClaves);
}
void manejarDesbloquearClaveManual(int socketPlanificador, int largoMensaje){
void* instanciaVoid;
void* claveVoid;
Clave* clave;
char* claveDesbloquear = malloc(largoMensaje +1);
// Recibo la clave que tengo que desbloquear
recibirMensaje(socketPlanificador, largoMensaje, &claveDesbloquear);
// Busco instancias con claves del esi
pthread_mutex_lock(&mutexListaInstancias);
if ((instanciaVoid = list_find_with_param(listaInstancias, (void*) claveDesbloquear, buscarInstanciaConClave)) != NULL){
// Busco claves del esi en la instancia
if ((claveVoid = list_find_with_param(((Instancia*) instanciaVoid)->claves, (void*) claveDesbloquear, buscarClaveEnListaDeClaves)) != NULL){
// Desbloqueo clave del esi
clave = (Clave*) claveVoid;
clave->bloqueado = 0;
}
}
pthread_mutex_unlock(&mutexListaInstancias);
free(claveDesbloquear);
}
void consolaPlanificador(void* socketPlanificadorVoid){
int socketPlanificador = *(int*) socketPlanificadorVoid;
ContentHeader * header;
while(true){
header = recibirHeader(socketPlanificador);
switch (header->id) {
case COMANDO_KILL:
log_trace(logCoordinador, "Se recibio kill de esi desde el planificador");
manejarComandoKill(socketPlanificador, header->largo);
break;
case COMANDO_STATUS:
log_trace(logCoordinador, "Se recibio status de clave desde el planificador");
manejarComandoStatus(socketPlanificador, header->largo);
break;
case BLOQUEAR_CLAVE_MANUAL:
manejarBloquearClaveManual(socketPlanificador, header->largo);
break;
case DESBLOQUEAR_CLAVE_MANUAL:
manejarDesbloquearClaveManual(socketPlanificador, header->largo);
break;
}
free(header);
}
}
void cerrarCoordinador(int sig) {
guardarClavesBloqueadasAlIniciar = 0;
llegoUnaInstancia = 1;
close(socketEscucha);
exit(1);
}
int main() {
puts("Iniciando Coordinador.");
int socketComponente, socketConectadoPlanificador;
SocketHilos socketsNecesarios;
t_config* configuracion;
int puerto;
int maxConexiones;
char* ipPlanificador;
indexInstanciaEL = 0;
// Claves bloqueadas por defecto
guardarClavesBloqueadasAlIniciar = 1;
llegoUnaInstancia = 0;
signal(SIGTSTP, &cerrarCoordinador);
// Inicio el log
logCoordinador = log_create(ARCHIVO_LOG, "Coordinador", LOG_PRINT, LOG_LEVEL_TRACE);
// Leo puertos e ips de archivo de configuracion
configuracion = config_create(ARCHIVO_CONFIGURACION);
puerto = config_get_int_value(configuracion, "PUERTO");
ipPlanificador = config_get_string_value(configuracion, "IP");
maxConexiones = config_get_int_value(configuracion, "MAX_CONEX");
// Comienzo a escuchar conexiones
socketEscucha = socketServidor(puerto, ipPlanificador, maxConexiones);
// Se conecta el planificador
socketConectadoPlanificador = servidorConectarComponente(&socketEscucha, "coordinador", "planificador");
// Logueo la conexion
log_trace(logCoordinador, "Se conectó el planificador: Puerto=%d; Ip Planificador=%d; Máximas conexiones=%d", puerto, ipPlanificador, maxConexiones);
// Creo hilo para esperar mensajes de consola del planificador
pthread_t idHilo;
if (pthread_create(&idHilo, NULL, (void*) consolaPlanificador, (void*) &socketConectadoPlanificador)) {
log_error(logCoordinador, "No se pudo crear el hilo para recibir mensajes del Planificador");
//Libero memoria
close(socketEscucha);
close(socketConectadoPlanificador);
free(ipPlanificador);
config_destroy(configuracion);
cerrarInstancias();
return 0;
}
log_trace(logCoordinador, "Hilo asignado para recibir mensajes del Planificador");
// Instancio la lista de instancias
listaInstancias = list_create();
// Espero conexiones de ESIs e instancias
while ((socketComponente = servidorConectarComponente(&socketEscucha, "", ""))) {
log_trace(logCoordinador, "Se conectó un componente");
socketsNecesarios.socketComponente = socketComponente;
socketsNecesarios.socketPlanificador = socketConectadoPlanificador;
if (!correrEnHilo(socketsNecesarios)) {
close(socketComponente);
}
}
// Libero memoria
close(socketEscucha);
close(socketConectadoPlanificador);
free(ipPlanificador);
config_destroy(configuracion);
cerrarInstancias();
return 0;
}
// Cosas para el GET
int sePuedeComunicarConLaInstancia(Instancia* instancia) {
// Si se puede comunicar devuelve 1, si no -1
return enviarHeader(instancia->socket, "", 0);
}
bool instanciasNoCaidas(void* instanciaVoid) {
return sePuedeComunicarConLaInstancia((Instancia*) instanciaVoid) != -1;
}
Instancia* seleccionarInstanciaAlgoritmoDistribucion(Clave* clave){
char* algoritmo_distribucion;
t_config* configuracion;
Instancia* instancia;
t_list* listaInstanciasNoCaidas;
// Leo del archivo de configuracion
configuracion = config_create(ARCHIVO_CONFIGURACION);
algoritmo_distribucion = config_get_string_value(configuracion, "ALG_DISTR");
pthread_mutex_lock(&mutexListaInstancias);
// Filtro instancias que no se encuentren caidas
listaInstanciasNoCaidas = list_filter(listaInstancias, instanciasNoCaidas);
pthread_mutex_unlock(&mutexListaInstancias);
if (list_is_empty(listaInstanciasNoCaidas)) {
log_error(logCoordinador, "No se puede seleccionar algoritmo de distribucion, todas las instancias se encuentran caidas");
return NULL;
}
// Selecciono algoritmo de distribucion de instancias
if (strcmp(algoritmo_distribucion, "EL") == 0) {
log_trace(logCoordinador, "Utilizo algoritmo de distribucion de instancias EL");
instancia = algoritmoDistribucionEL(listaInstanciasNoCaidas);
} else if (strcmp(algoritmo_distribucion, "LSU") == 0) {
log_trace(logCoordinador, "Utilizo algoritmo de distribucion de instancias LSU");
instancia = algoritmoDistribucionLSU(listaInstanciasNoCaidas);
} else if (strcmp(algoritmo_distribucion, "KE") == 0) {
log_trace(logCoordinador, "Utilizo algoritmo de distribucion de instancias KE");
instancia = algoritmoDistribucionKE(listaInstanciasNoCaidas, clave->nombre);
}
// Libero memoria
config_destroy(configuracion);
list_destroy(listaInstanciasNoCaidas);
return instancia;
}
int asignarClaveAInstancia(char* key, char* nombreEsi) {
Instancia* instancia;
// Creo la clave
Clave* clave;
clave = malloc(sizeof(Clave));
clave->bloqueado = 1;
clave->nombre = malloc(strlen(key) + 1);
strcpy(clave->nombre, key);
clave->nombre[strlen(key)] = '\0';
clave->nombreEsi = malloc(strlen(nombreEsi) + 1);
strcpy(clave->nombreEsi, nombreEsi);
clave->nombreEsi[strlen(nombreEsi)] = '\0';
instancia = seleccionarInstanciaAlgoritmoDistribucion(clave);
if(instancia == NULL){
// Libero memoria, ya loguie antes
free(clave->nombre);
free(clave->nombreEsi);
free(clave);
return 0;
}
list_add(instancia->claves, clave);
return 1;
}
void getClave(char* key, int socketPlanificador, int socketEsi, char* nombreEsi) {
Clave* clave;
void* claveVoid;
Instancia* instancia;
void* instanciaVoid;
int respuestaGET;
// Busco la clave en la lista de claves
pthread_mutex_lock(&mutexListaInstancias);
instanciaVoid = list_find_with_param(listaInstancias, (void*) key, buscarInstanciaConClave);
// Si encontré una instancia, busco su clave
claveVoid = (instanciaVoid != NULL ? list_find_with_param(((Instancia*) instanciaVoid)->claves, (void*) key, buscarClaveEnListaDeClaves) : NULL);
pthread_mutex_unlock(&mutexListaInstancias);
clave = (Clave*) claveVoid;
if (instanciaVoid != NULL) {
instancia = (Instancia*) instanciaVoid;
// Se tiene que verificar si la instancia no está caída
if (sePuedeComunicarConLaInstancia(instancia) != -1) {
// Se fija si la clave se encuentra bloqueada
if (clave->bloqueado) {
log_trace(logCoordinador, "La clave se encuentra bloqueada");
respuestaGET = COORDINADOR_ESI_BLOQUEADO;
avisarA(socketEsi, "", respuestaGET);
avisarA(socketPlanificador, key, respuestaGET);
} else {
// No esta bloqueada, entonces la bloqueo
log_trace(logCoordinador, "La clave no se encuentra bloqueada, se bloquea");
respuestaGET = COORDINADOR_ESI_BLOQUEAR;
clave->bloqueado = 1;
// Asigno que esi la bloqueo
free(clave->nombreEsi);
clave->nombreEsi = malloc(strlen(nombreEsi) + 1);
strcpy(clave->nombreEsi, nombreEsi);
clave->nombreEsi[strlen(nombreEsi)] = '\0';
// Aviso
avisarA(socketEsi, "", respuestaGET);
avisarA(socketPlanificador, clave->nombre, respuestaGET);
}
pthread_mutex_unlock(&mutexListaInstancias);
} else {
// Instancia está caída
respuestaGET = COORDINADOR_INSTANCIA_CAIDA;
log_error(logCoordinador, "La clave que intenta acceder existe en el sistema pero se encuentra en una instancia que esta desconectada");
//Le aviso al planificador y esi del error
avisarA(socketEsi, "", respuestaGET);
avisarA(socketPlanificador, "", respuestaGET);
}
} else {
// Le asigno la nueva clave a la instancia
if (asignarClaveAInstancia(key, nombreEsi)) {
respuestaGET = COORDINADOR_ESI_CREADO;
log_trace(logCoordinador, "Se asigna la nueva clave a la instancia");
} else {
respuestaGET = NO_HAY_INSTANCIAS;
log_trace(logCoordinador, "No hay instancias disponibles");
}
avisarA(socketEsi, "", respuestaGET);
avisarA(socketPlanificador, key, respuestaGET);
}
}
// Cosas para el SET y para el STORE
void avisarA(int socketAvisar, char* mensaje, int error) {
enviarHeader(socketAvisar, mensaje, error);
if (strlen(mensaje) >= 1) {
enviarMensaje(socketAvisar, mensaje);
}
}
void ejecutarSentencia(int socketEsi, int socketPlanificador, char* mensaje, char* nombreESI) {
void* instanciaVoid;
Instancia* instancia;
ContentHeader *headerEstado, *headerEntradas, *headerCompactacion;
void* claveVoid;
Clave* clave;
char** mensajeSplitted;
mensajeSplitted = string_split(mensaje, " ");
// Valido que la clave no exceda el máximo
if (esSET(mensajeSplitted[0]) && strlen(mensajeSplitted[1]) > 40) {
// Logueo el error
log_error(logCoordinador, "Error, la clave excede el tamaño máximo de 40 caracteres");
// Le aviso al planificador por el error
avisarA(socketPlanificador, "", COORDINADOR_ESI_ERROR_TAMANIO_CLAVE);
//Tambien le aviso al esi para que no se quede esperando
avisarA(socketEsi, "", COORDINADOR_ESI_ERROR_TAMANIO_CLAVE);
// Libero memoria
free(mensajeSplitted[0]);
free(mensajeSplitted[1]);
free(mensajeSplitted[2]);
free(mensajeSplitted);
return;
}
// Busco la clave en la lista de claves, devuelvo la instancia que la tenga
pthread_mutex_lock(&mutexListaInstancias);
instanciaVoid = list_find_with_param(listaInstancias, (void*) mensajeSplitted[1], buscarInstanciaConClave);
if (instanciaVoid == NULL) {
pthread_mutex_unlock(&mutexListaInstancias);
// Logueo el error
log_error(logCoordinador, "Clave no identificada");
// Le aviso al planificador
avisarA(socketPlanificador, "", COORDINADOR_ESI_ERROR_CLAVE_NO_IDENTIFICADA);
//Tambien le aviso al esi para que no se quede esperando
avisarA(socketEsi, "", COORDINADOR_ESI_ERROR_CLAVE_NO_IDENTIFICADA);
// Libero memoria
free(mensajeSplitted[0]);
free(mensajeSplitted[1]);
free(mensajeSplitted[2]);
free(mensajeSplitted);
return;
}
instancia = (Instancia*) instanciaVoid;
if(sePuedeComunicarConLaInstancia(instancia) == -1) {
pthread_mutex_unlock(&mutexListaInstancias);
log_error(logCoordinador, "La instancia que se intenta acceder se encuentra caida.");
// Le aviso al planificador
avisarA(socketPlanificador, "", INSTANCIA_COORDINADOR_DESCONECTADA);
//Tambien le aviso al esi para que no se quede esperando
avisarA(socketEsi, "", INSTANCIA_COORDINADOR_DESCONECTADA);
// Libero memoria
free(mensajeSplitted[0]);
free(mensajeSplitted[1]);
free(mensajeSplitted[2]);
free(mensajeSplitted);
return;
}
// Si encontré una instancia, busco su clave
claveVoid = list_find_with_param(((Instancia*) instanciaVoid)->claves, (void*) mensajeSplitted[1], buscarClaveEnListaDeClaves);
// Valido que la clave esté bloqueada
clave = (Clave*) claveVoid;
if (!clave->bloqueado || strcmp(clave->nombreEsi, nombreESI) != 0) {
pthread_mutex_unlock(&mutexListaInstancias);
// Logueo el error
log_error(logCoordinador, "La clave que intenta acceder no se encuentra tomada");
// Le aviso al planificador
avisarA(socketPlanificador, "", COORDINADOR_ESI_ERROR_CLAVE_NO_TOMADA);
//Tambien le aviso al esi para que no se quede esperando
avisarA(socketEsi, "", COORDINADOR_ESI_ERROR_CLAVE_NO_TOMADA);
// Libero memoria
free(mensajeSplitted[0]);
free(mensajeSplitted[1]);
free(mensajeSplitted[2]);
free(mensajeSplitted);
return;
}
if (esSTORE(mensajeSplitted[0])) {
// Si es STORE, tengo que desbloquear la clave
clave->bloqueado = 0;
// Logueo -\_('.')_/-
log_trace(logCoordinador, "Desbloqueo la clave %s", clave->nombre);
}
pthread_mutex_unlock(&mutexListaInstancias);
// Si llega hasta acá es porque es válido, le mando el mensaje a la instancia
enviarHeader(instancia->socket, mensaje, COORDINADOR);
enviarMensaje(instancia->socket, mensaje);
if (esSET(mensajeSplitted[0])) {
// Espero saber si necesita compactar
headerCompactacion = recibirHeader(instancia->socket);
if (headerCompactacion->id == COMPACTAR) compactar();
free(headerCompactacion);
}
// Espero la respuesta de la instancia
headerEstado = recibirHeader(instancia->socket);
switch (headerEstado->id) {
case INSTANCIA_SENTENCIA_OK_SET:
// Espero cantidad de entradas libres de la instancia
headerEntradas = recibirHeader(instancia->socket);
pthread_mutex_lock(&mutexListaInstancias);
instancia->entradasLibres = headerEntradas->id;
pthread_mutex_unlock(&mutexListaInstancias);
free(headerEntradas);
// Si está OK, le aviso al ESI y al planificador
log_trace(logCoordinador, "La sentencia se ejecutó correctamente");
avisarA(socketEsi, "", INSTANCIA_SENTENCIA_OK_SET);
avisarA(socketPlanificador, "", INSTANCIA_SENTENCIA_OK_SET);
break;
case INSTANCIA_SENTENCIA_OK_STORE:
// Si está OK, le aviso al ESI y al planificador
log_trace(logCoordinador, "La sentencia se ejecutó correctamente");
avisarA(socketEsi, "", INSTANCIA_SENTENCIA_OK_STORE);
avisarA(socketPlanificador, mensajeSplitted[1], INSTANCIA_SENTENCIA_OK_STORE);
break;
case INSTANCIA_CLAVE_NO_IDENTIFICADA:
// Cuando hay un error, le aviso al planificador
log_error(logCoordinador, "Clave no identificada");
// Le aviso al planificador
avisarA(socketPlanificador, "", COORDINADOR_ESI_ERROR_CLAVE_NO_IDENTIFICADA);
//Tambien le aviso al esi para que no se quede esperando
avisarA(socketEsi, "", COORDINADOR_ESI_ERROR_CLAVE_NO_IDENTIFICADA);
break;
case INSTANCIA_ERROR:
log_error(logCoordinador, "Error no contemplado");
// Le aviso al planificador
avisarA(socketPlanificador, "", INSTANCIA_ERROR);
// Tambien le aviso al esi para que no se quede esperando
avisarA(socketEsi, "", INSTANCIA_ERROR);
break;
}
// Libero memoria
free(mensajeSplitted[0]);
free(mensajeSplitted[1]);
free(mensajeSplitted[2]);
free(mensajeSplitted);
free(headerEstado);
}
int esSET(char* sentencia) {
return strcmp(sentencia, "SET") == 0;
}
int esSTORE(char* sentencia) {
return strcmp(sentencia, "STORE") == 0;
}
// Compactacion
void compactar() {
pthread_mutex_lock(&mutexListaInstancias);
list_iterate(listaInstancias, compactarInstancia);
pthread_mutex_unlock(&mutexListaInstancias);
}
void compactarInstancia(void* instancia) {
enviarHeader(((Instancia*)instancia)->socket, "", COMPACTAR);
}
|
C
|
#ifndef STATE_H
#define STATE_H
#include "card.h"
// State contains information about the last change that occured in the game.
// State either describes a play, a discard, or the start of a new round.
// The fields player and card are not relevant if the action is NewRound.
enum Action { Play, Discard, NewRound };
struct State {
Action action;
int player;
Card card;
};
#endif
|
C
|
/************************************************************
* Filename: part1a-mandelbrot.c
* Student name: Wang, Michelle Yih-chyan
* Student no.: 3035124441
* Date: Nov 2, 2017
* version: 1.1
* Development platform: Course VM
* Compilation: gcc part1b-Mandelbrot.c l SDL2 -lm
*************************************************************/
//Using SDL2 and standard IO
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/resource.h>
#include <sys/wait.h>
#include <sys/types.h>
#include "Mandel.h"
#include "draw.h"
typedef struct message {
int row_index;
float rowdata[IMAGE_WIDTH];
} MSG;
int main( int argc, char* args[] )
{
//data structure to store the start and end times of the whole program
struct timespec start_time, end_time;
//get the start time
clock_gettime(CLOCK_MONOTONIC, &start_time);
//data structure to store the start and end times of the computation
struct timespec start_compute, end_compute;
//generate mandelbrot image and store each pixel for later display
//each pixel is represented as a value in the range of [0,1]
//store the 2D image as a linear array of pixels (in row-major format)
float * pixels;
pixels = (float *) malloc(sizeof(float) * IMAGE_WIDTH * IMAGE_HEIGHT);
if (pixels == NULL) {
printf("Out of memory!!\n");
exit(1);
}
int fd[2];
//Obtain the number of child processes the user wants to create
int num_child = 0;
int k=0;
while(args[1][k]!='\0'){
num_child = num_child * 10 + ( (int) args[1][k] - '0');
k++;
}
int part_image_height = IMAGE_HEIGHT / num_child;
int to_cal[11]={0};
int i;
//calculate the number of task each child should complete
for(i=1;i<=num_child;i++){
to_cal[i] = part_image_height * i;
if(i==num_child)
to_cal[i] = IMAGE_HEIGHT + 1;
}
//open the pipe arguments
pid_t pids[10];
pipe(fd);
for(i=0;i<num_child;i++){
if((pids[i] = fork()) < 0){
perror("fork");
abort();
}else if(pids[i] ==0){
//in child
close(fd[0]);
//sleep(2);
//compute the mandelbrot image
//keep track of the execution time - we are going to parallelize this part
printf("Child(%ld): Start the computation ...\n", (long)getpid());
clock_gettime(CLOCK_MONOTONIC, &start_compute);
int x, y;
float difftime;
MSG to_return;
for (y=to_cal[i]; y<to_cal[i+1]; y++) {
for (x=0; x<IMAGE_WIDTH; x++) {
//compute a value for each point c (x, y)
to_return.row_index = y;
to_return.rowdata[x] = Mandelbrot(x, y);
//Mandelbrot(x,y);
//Only send data
}
if (write(fd[1], &to_return, sizeof(MSG)) == -1) {
printf("Error writing to the pipe");
}
}
close(fd[1]);//Close write end
//get the ending time of finishing child process
clock_gettime(CLOCK_MONOTONIC, &end_compute);
difftime = (end_compute.tv_nsec - start_compute.tv_nsec)/1000000.0 + (end_compute.tv_sec - start_compute.tv_sec)*1000.0;
printf("Child(%ld) ... completed. Elapse time = %.3f ms\n", (long)getpid(), difftime);
//Report timing
clock_gettime(CLOCK_MONOTONIC, &end_time);
difftime = (end_time.tv_nsec - start_time.tv_nsec)/1000000.0 + (end_time.tv_sec - start_time.tv_sec)*1000.0;
printf("Total elapse time measured by the process = %.3f ms\n", difftime);
exit(0);
}
}
MSG to_receive;
printf("This is parent process.\n");
close(fd[1]); //Only receive data
//char readed[500] = "";
while(read(fd[0], &to_receive, sizeof(MSG)) != 0) { // -1 for reserving space for terminating null-character
//printf("Line %d: \n", to_receive.row_index);
for(i=0;i<IMAGE_WIDTH;i++){
pixels[to_receive.row_index * IMAGE_WIDTH + i] = to_receive.rowdata[i];
}
}
printf("Done reading");
close(fd[0]);
struct rusage usage_children, usage_self;
struct timespec now_time;
int status, n = num_child;
pid_t pid;
//wait for all child process to end
while(n>0){
pid = wait(&status);
//printf("Child with PID %ld exited with status 0x%x.\n", (long)pid, status);
--n;
}
//calculate the processing time by parent process and children process
printf("All Child processes have complete\n");
getrusage(RUSAGE_CHILDREN, &usage_children);
getrusage(RUSAGE_SELF, &usage_self);
//print the information
printf("Total time spent by all child processes in user mode = %.3f ms \n", usage_children.ru_utime.tv_sec * 1000.0+usage_children.ru_utime.tv_usec/1000.0);
printf("Total time spent by all child processes in system mode = %.3f ms \n", usage_children.ru_stime.tv_sec * 1000.0+usage_children.ru_stime.tv_usec/1000.0);
printf("Total time spent by parent processes in user mode = %.3f ms \n", usage_self.ru_utime.tv_sec * 1000.0+usage_self.ru_utime.tv_usec/1000.0);
printf("Total time spent by parent processes in system mode = %.3f ms \n", usage_self.ru_stime.tv_sec * 1000.0+usage_self.ru_stime.tv_usec/1000.0);
//get the time now and print the total elapse time
clock_gettime(CLOCK_MONOTONIC, &now_time);
printf("Total elapse time measured by parent process = %.3f ms\n", (now_time.tv_nsec - start_time.tv_nsec)/1000000.0 + (now_time.tv_sec - start_time.tv_sec)*1000.0);
printf("Draw the image\n");
//Draw the image by using the SDL2 library
DrawImage(pixels, IMAGE_WIDTH, IMAGE_HEIGHT, "Mandelbrot demo", 3000);
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "cliente.h"
#include "pedido.h"
#include "residuos.h"
#include "utn_strings.h"
int ped_initPedido(Pedido* pPedido,int len)
{
int i;
if(pPedido!=NULL && len>0)
{
for(i=0; i<len;i++)
{
pPedido[i].idPedido=i+1;
pPedido[i].isEmpty=1;
}
}
return 0;
}
int ped_findFree(Pedido* pPedido, int len)
{
int i;
int ret=-1;
for(i=0;i<len;i++)
{
if(pPedido[i].isEmpty==1)
{
ret=i;
break;
}
}
return ret;
}
int ped_addPedido(Pedido* pPedido,int len,int pIndex,char* msgE,int tries)
{
char bufferIdCliente[20];
int auxKilos;
int auxEstado;
int auxIdCliente;
int retorno=-1;
if((pPedido!=NULL)&&(len>0)&&(pIndex!=-1))
{
if(getStringNumeros(bufferIdCliente,"\nIngrese el id del Cliente:",msgE,tries)==0)
{
getIntInRange(&auxKilos,"\nIngrese la cantidad de Kilos totales que se le recolectaran al cliente:",msgE,1,100,tries);
getIntInRange(&auxEstado,"\nEl Estado de su pedido quedara Pendiente Presione 1 para continuar:\n 1)(Pendiente): \n ",msgE,1,1,tries);
auxIdCliente = atoi(bufferIdCliente);
pPedido[pIndex].idCliente=auxIdCliente;
pPedido[pIndex].estado=auxEstado;
pPedido[pIndex].kilos=auxKilos;
pPedido[pIndex].isEmpty=0;
fflush(stdin);
retorno=0;
}
}
return retorno;
}
int ped_findPedidoById(Pedido* pPedido, int len, int idE)
{
int i;
int ret=-1;
for(i=0;i<len;i++)
{
if(pPedido[i].idPedido==idE)
{
ret=i;
break;
}
}
return ret;
}
int ped_buscarID(Pedido *pedidos, int cant, int valorBuscado, int* posicion)
{
int retorno=-1;
int i;
if(pedidos!= NULL && cant>=0)
{
for(i=0;i<cant;i++)
{
if(pedidos[i].isEmpty==1)
{
continue;
}
else
{
if(pedidos[i].idPedido==valorBuscado)
{
retorno=0;
*posicion=i;
break;
}
}
}
}
return retorno;
}
int ped_removePedido(Pedido* pPedido, int len,char* msgE,int tries)
{
int auxID;
int posOfID;
int retorno=-1;
if(pPedido!=NULL && len>0)
{
auxID=ped_getID(pPedido,len,msgE,tries);
if(auxID>=0)
{
posOfID=ped_findPedidoById(pPedido,len,auxID);
if(posOfID!=-1)
{
pPedido[posOfID].isEmpty=1;
retorno=0;
}
}
}
return retorno;
}
int ped_getID (Pedido* pPedido,int len,char* msgE,int tries)
{
int retorno=-1;
char bufferID[20];
int auxID;
if(pPedido!=NULL && len>0)
{
if(!getStringNumeros(bufferID,"\nIngrese ID: ",msgE,tries))
{
auxID=atoi(bufferID);
retorno=auxID;
}
}
return retorno;
}
int ped_printPedido(Pedido* pPedido,int len)
{
int i;
int flag=1;
for(i=0;i<len;i++)
{
if(pPedido[i].isEmpty!=1)
{
printf("\nID: %d\nEstado: %d\nKilos: %d\n-------",
pPedido[i].idPedido,pPedido[i].estado,pPedido[i].kilos);
fflush(stdin);
flag=0;
}
}
if(flag)
{
printf("\n----El listado se encuentra vacio----\n");
}
system("Pause");
system("CLS");
return 0;
}
int ped_orderByID(Pedido* pPedido, int len)
{
int i;
int j;
Pedido buffer;
for(i=0;i<len-1;i++)
{
if(pPedido[i].isEmpty==1)
{
continue;
}
for(j=i+1;j<len;j++)
{
if(pPedido[j].isEmpty==1)
{
continue;
}
if(pPedido[i].idPedido>pPedido[j].idPedido)
{
buffer=pPedido[i];
pPedido[i]=pPedido[j];
pPedido[j]=buffer;
}
}
}
return 0;
}
/*
void ped_tipoStr(Pedido* pPedido,int posicion, char* tipoPedido)
{
if(pPedido!=NULL && tipoPedido!=NULL && posicion>=0)
{
switch(pPedido[posicion].tipo)
{
case 1:
strncpy(tipoPedido,"Cuerdas",TEXT_SIZE);
break;
case 2:
strncpy(tipoPedido,"Viento-Madera",TEXT_SIZE);
break;
case 3:
strncpy(tipoPedido,"Viento-Metal",TEXT_SIZE);
break;
case 4:
strncpy(tipoPedido,"Percusion",TEXT_SIZE);
break;
}
}
}
*/
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <sys/file.h>
#include <unistd.h>
int main()
{
int file = open("neptunkod.txt",O_RDWR); //int pufferbe olvassuk be a txt-t
if (file > 0) //ellenőrizzük a beolvasás sikerességét
{
printf("sikeres beolvasas\n\n");
}
else
{
printf("hiba tortent a fajl beolvasasnal\n");
}
char txt[50];
ssize_t x = read(file,&txt,50); //karakter tömbben tároljuk a beolvasott szöveget és az x változóban a read() visszatérési értékét
if (x < 0) printf("hiba a fajl kiolvasasnal\n");
else printf("%s\nbeolvasott byte: %ld\n",txt,x); //majd kiiratjuk
lseek(file,0,SEEK_SET); //kurzort mozgatjuk az lseek-el; 0 - a fájl eleje
read(file,&txt,50);
ssize_t w = write(1,&txt,42);
if(w < 0) printf("hiba a kiiratasnal\n");
else printf("kiirt byte mennyiseg: %ld",w);
return 0;
}
|
C
|
#include <stdio.h>
unsigned long int factorial(int);
int fibonacci(int);
int print_odds(int);
int print_numbers(int, int, int);
int print_evens(int);
int multiplication_table(int, int);
int sum_of_n_numbers(int, int);
int product_of_n_numbers(int, int);
int print_odd_numbers(int,int);
int print_nth_number(int, int ,int);
int sum_of_even_numbers(int, int);
int print_odd_backwards(int);
unsigned long int factorial(int number)
{
unsigned long int fact = 1;
for (int num = 1; num <= number; num++)
{
fact = fact * num;
}
return fact;
}
int fibonacci(int fibonacciTerm)
{
int firstNumber = -1;
int secondNumber = 1;
for (int term = 1; term <= fibonacciTerm; term++)
{
int sum = firstNumber + secondNumber;
firstNumber = secondNumber;
secondNumber = sum;
printf("%d \n", secondNumber);
}
return 0;
}
int print_numbers(int start_from, int upto, int addition)
{
while(start_from <= upto)
{
printf("%d\n", start_from);
start_from += addition;
}
return 0;
}
int print_odds(int number)
{
return print_numbers(1, number, 2);
}
int print_evens(int number)
{
return print_numbers(2, number, 2);
}
int multiplication_table(int mth_term, int nth_term)
{
for(int num =1; num <= nth_term; num++)
{
printf("%d * %d = %d\n", mth_term, num, mth_term*num);
}
return 0;
}
int sum_of_n_numbers(int start_number, int end_number)
{
int sum = 0;
while(start_number < end_number)
{
sum = sum + start_number;
start_number++;
}
return sum;
}
int product_of_n_numbers(int start_number, int end_number)
{
int product = 1;
while(start_number < end_number)
{
product = product * start_number;
start_number++;
}
return product;
}
int print_odd_numbers(int start_number, int end_number)
{
int current_number = start_number % 2 ? start_number: start_number + 1;
return print_numbers(current_number, end_number, 2);
}
int print_nth_number(int start_number, int end_number, int addition)
{
return print_numbers(start_number, end_number, addition);
}
int sum_of_even_numbers(int start_number, int end_number)
{
int sum = 0;
int current_number = start_number % 2 ? start_number + 1: start_number;
while(current_number <= end_number)
{
sum = sum + current_number;
current_number += 2;
}
return sum;
}
int print_odd_backwards(int number)
{
int current_number = number % 2 ? number : number -1;
while(current_number >= 1)
{
printf("%d\n", current_number);
current_number -= 2;
}
return 0;
}
int main(void)
{
int number, number1, number2;
printf("Enter a number for calculating factorial: ");
scanf("%d", &number);
printf("Factorial of %d is %lu \n", number, factorial(number));
printf("Enter a number for printing series: ");
scanf("%d", &number);
printf("Fibonacci Series: \n");
fibonacci(number);
printf("Odd series: \n");
print_odds(number);
printf("Even series: \n");
print_evens(number);
printf("Enter two numbers for multiplication table:\n");
printf("Enter first number: ");
scanf("%d", &number1);
printf("Enter second number: ");
scanf("%d", &number2);
multiplication_table(number1, number2);
printf("Enter two numbers for sum all numbers b/w them:\n");
printf("Enter starting range: ");
scanf("%d", &number1);
printf("Enter ending range: ");
scanf("%d", &number2);
printf("Sum of all numbers b/w %d and %d is %d\n", number1, number2, sum_of_n_numbers(number1, number2));
printf("Enter two numbers for product all numbers b/w them:\n");
printf("Enter starting range: ");
scanf("%d", &number1);
printf("Enter ending range: ");
scanf("%d", &number2);
printf("Product of all numbers b/w %d and %d is %d\n", number1, number2, product_of_n_numbers(number1, number2));
printf("Enter two number for printing odd numbers b/w them:\n");
printf("Enter starting range: ");
scanf("%d", &number1);
printf("Enter ending range: ");
scanf("%d", &number2);
print_odd_numbers(number1,number2);
printf("Enter range and addition: \n");
printf("Enter starting range: ");
scanf("%d", &number1);
printf("Enter ending range: ");
scanf("%d", &number2);
printf("Enter addition: ");
scanf("%d", &number);
print_nth_number(number1, number2, number);
printf("Enter two numbers: \n");
printf("Enter starting range: ");
scanf("%d", &number1);
printf("Enter ending range: ");
scanf("%d", &number2);
printf("Sum of all even number is %d \n", sum_of_even_numbers(number1, number2));
printf("Enter number:");
scanf("%d", &number);
printf("Odd series in backwards: \n");
print_odd_backwards(number);
return 0;
}
|
C
|
#include<stdio.h>
#include<stdlib.h>
int main()
{
int x, y;
int temp_x, temp_y;
int n;
int i;
if (n < 2) {
for (i = 0; i < n; i++) {
scanf("%d %d", &x, &y);
}
printf("-1");
}else if(n == 3 || n == 4) {
for (i = 0; i < n; i++) {
scanf("%d %d", &x, &y);
}
printf("1");
}else{
scanf("%d %d", &x, &y);
scanf("%d %d", &temp_x, &temp_y);
x ^= temp_x;
y ^= temp_y;
if (x != 0 && y != 0) {
printf("1");
}else {
printf("-1");
}
}
}
|
C
|
#include<stdio.h>
#define m 5
int s[m-1],top=-1;
int pop()
{
int d;
if (top==-1)
{
printf("Underflow");
}
else
{
d=s[top];
top=top-1;
}
return d;
}
void push(int a)
{
if(top==m-1)
{
printf("Overflow");
}
else
{
top=top+1;
s[top]=a;
}
}
int palin()
{
int n,i,f;
printf("Enter the number of elements:");
scanf("%d",&n);
printf("Enter the elements:");
int a[n];
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
push(a[i]);
}
for(i=0;i<n;i++)
{
if(a[i]==pop())
f=1;
else
{
f=0;
break;
}
}
return f;
}
void display()
{
int i;
for(i=top;i>-1;i--)
{
printf("%d ",s[i]);
}
}
int status()
{
int r=top;
return r;
}
int main()
{
int ch,f;
while(1)
{ printf("\n\tMENU\n1.Push\n2.Pop\n3.Palindrome\n4.Display\n5.Exit");
printf("\nEnter your choice:");
scanf("%d",&ch);
switch(ch)
{
case 1:printf("Enter the element to be entered:");
int e;
scanf("%d",&e);
push(e);
break;
case 2:printf("The popped element is :");
int d;
d=pop();
printf("%d",d);
break;
case 3:f=palin();
if(f==0)
printf("The entered array is not a palindrome");
else
printf("The entered array is a palindrome");
break;
case 4:display();
break;
case 5:printf("Status");
int s=status();
case 6:return 0;
default:printf("The entered choice is invalid");
}
}
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* type_x.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: vyunak <vyunak@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2019/04/02 14:59:19 by vyunak #+# #+# */
/* Updated: 2019/04/10 15:29:04 by vyunak ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
static intmax_t cast_x(va_list args, t_main tm)
{
intmax_t n;
if (tm.castm != 0 || tm.type == 'p')
n = va_arg(args, size_t);
else
n = (unsigned int)va_arg(args, unsigned long);
if (tm.castm == H)
n = (unsigned short)n;
else if (tm.castm == HH)
n = (unsigned char)n;
return (n);
}
static void hand_flags(t_sp *sp, t_main tm, char *str, intmax_t nbr)
{
*sp = set_space();
(*sp).zero = tm.rigor - ft_strlen(str);
((*sp).zero < 0) ? ((*sp).zero = 0) : 0;
(*sp).start = tm.width - (*sp).zero - ft_strlen(str);
((*sp).start < 0) ? ((*sp).start = 0) : 0;
if ((tm.hash > 0 && nbr != 0) || tm.type == 'p')
{
(tm.type == 'x' || tm.type == 'p') ? ((*sp).prefix = "0x") : 0;
(tm.type == 'X') ? ((*sp).prefix = "0X") : 0;
(*sp).start -= ft_strlen((*sp).prefix);
}
(tm.minus > 0) ? ((*sp).end = (*sp).start) &&
((*sp).start -= (*sp).start) : 0;
(tm.zero > 0 && (*sp).start > 0 && tm.rigor == 0) ?
((*sp).zero = (*sp).start) &&
((*sp).start -= (*sp).start) : 0;
}
static int print_h(t_sp sp, char *str)
{
int res;
res = 0;
while (sp.start-- > 0)
res += printf_putchar(' ');
(sp.prefix) ? res += printf_putstr(sp.prefix) : 0;
while (sp.zero-- > 0)
res += printf_putchar('0');
res += printf_putstr(str);
while (sp.end-- > 0)
res += printf_putchar(' ');
free(str);
return (res);
}
int type_x(va_list args, t_main tm)
{
intmax_t nbr;
t_sp sp;
char *str;
nbr = cast_x(args, tm);
if (nbr == 0 && tm.rigor < 0)
str = ft_strdup("");
else if (tm.type == 'x' || tm.type == 'p')
str = ft_itoa_base(nbr, 16, 0);
else
str = ft_itoa_base(nbr, 16, 1);
hand_flags(&sp, tm, str, nbr);
return (print_h(sp, str));
}
|
C
|
#include <stdio.h>
#include <string.h>
int main(){
int i;
for(i=0;i<3 && i< 10;i++) {
printf("%i",i);
}
if(i==3) {
printf("es el mismo");
}
return 0;
}
void Directorio(EXT_ENTRADA_DIR *directorio, EXT_BLQ_INODOS *inodos){ //COMANDO dir
//Se iterara sobre los directorios usados o borrados hasta llegar a uno vacio (o al maximo de ellos en su defecto).
//Esta expresion aparecera repetidas veces durante el codigo.
// SOP BORRADO , i<MAX
// 00 01 11 10
// NULL 0 0 1 1 0
// 1 0 0 1 0
int i = 0;
while( (directorio->dir_inodo != NULL_INODO || strcmp(directorio->dir_nfich, "" ) == 0) && i++ < MAX_INODOS ) {
//Si el nombre de
if( strcmp(directorio->dir_nfich, "") == 0 || strcmp(directorio->dir_nfich, ".") == 0 )
++directorio;
else {
//Info de directorio.
printf("[%s]\t| tamaino: %i\t| inodo: %i bloques: ", directorio->dir_nfich, inodos->blq_inodos[directorio->dir_inodo].size_fichero, directorio->dir_inodo);
//Bloques que ocupa el directorio.
printf(" [%i]\n",ContarBloques(inodos->blq_inodos[(directorio++)->dir_inodo].i_nbloque,1,NULL));
}
}
}
|
C
|
#include<pthread.h>
#include<stdio.h>
int ticketcount = 10;
pthread_mutex_t lock; //互斥锁
pthread_cond_t cond; //条件变量
void* salewinds1(void* args)
{
while(1)
{
pthread_mutex_lock(&lock); //因为要访问全局的共享变量ticketcount,所以就要加锁
if(ticketcount > 0) //如果有票
{
printf("windows1 start sale ticket!the ticket is:%d\n",ticketcount);
ticketcount --;//则卖出一张票
if(ticketcount == 0)
pthread_cond_signal(&cond); //通知没有票了
printf("sale ticket finish!,the last ticket is:%d\n",ticketcount);
}
else //如果没有票了,就解锁退出
{
pthread_mutex_unlock(&lock);
break;
}
pthread_mutex_unlock(&lock);
sleep(1); //要放到锁的外面
}
}
void* salewinds2(void* args)
{
while(1)
{
pthread_mutex_lock(&lock);
if(ticketcount > 0)
{
printf("windows2 start sale ticket!the ticket is:%d\n",ticketcount);
ticketcount --;
if(ticketcount == 0)
pthread_cond_signal(&cond); //发送信号
printf("sale ticket finish!,the last ticket is:%d\n",ticketcount);
}
else
{
pthread_mutex_unlock(&lock);
break;
}
pthread_mutex_unlock(&lock);
sleep(1);
}
}
void *setticket(void *args) //重新设置票数
{
pthread_mutex_lock(&lock); //因为要访问全局变量ticketcount,所以要加锁
if(ticketcount > 0)
pthread_cond_wait(&cond,&lock); //如果有票就解锁并阻塞,直到没有票就执行下面的
ticketcount = 10; //重新设置票数为10
pthread_mutex_unlock(&lock); //解锁
sleep(1);
pthread_exit(NULL);
}
main()
{
pthread_t pthid1,pthid2,pthid3;
pthread_mutex_init(&lock,NULL); //初始化锁
pthread_cond_init(&cond,NULL); //初始化条件变量
pthread_create(&pthid1,NULL, salewinds1,NULL); //创建线程
pthread_create(&pthid2,NULL, salewinds2,NULL);
pthread_create(&pthid3,NULL, setticket,NULL);
pthread_join(pthid1,NULL); //等待子线程执行完毕
pthread_join(pthid2,NULL);
pthread_join(pthid3,NULL);
pthread_mutex_destroy(&lock); //销毁锁
pthread_cond_destroy(&cond); //销毁条件变量
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void change(char* text)
{
int i=0,n=strlen(text);
for(;i<n;i++)
{
switch(text[i])
{
case 'a':
case 'b':
case 'c':
case 'A':
case 'B':
case 'C':
text[i]='X';
break;
case 'd':
case 'e':
case 'f':
case 'D':
case 'E':
case 'F':
text[i]='Y';
break;
}
}
printf("%s",text);
}
int main()
{
char arr[100];
scanf("%s",arr);
change(arr);
return 0;
}
|
C
|
/*=============================================================================
The LLL-Reduction Algorithm
Authors
-------
* Grady Williams (gradyrw@gmail.com)
* Chris Swierczewski (cswiercz@gmail.com)
=============================================================================*/
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
/*
gram_schmidt
Numerically stable Gram-Schmidt algorithm.
Given a set of `n` vectors `b_1, ..., b_n` construct a collection of
orthogonal vectors `b*_1, ..., b*_n` spanning the same space. The vectors are
stored as **columns** of b. THIS SHOULD BE CHANGED IN THE FUTURE TO FOLLOW
STANDARD C PRACTICES FOR STORING VECTORS.
Parameters
----------
b : double[:]
An array of `n` vectors each of size `n`.
n : int
Returns
-------
b : double[:]
Orthogonalized vectors.
mu : double[:]
Matrix of orthogonalization parameters
mu_ij = <bi, b*j> / <b*j, b*j>
B : double[:]
Square norms of orthogonalized vectors.
*/
void gram_schmidt(double* b, double* mu, double* B, int n)
{
double numerator;
double dot;
int i,j,k;
double* b_star = (double*)malloc(n*n*sizeof(double));
double* temp = (double*)malloc(n*sizeof(double));
for (i = 0; i < n; i++)
{
// (1) copy non-orthogonal vector: b*_i = b_i
for (k = 0; k < n; k++)
b_star[k*n + i] = b[k*n + i];
// temp keeps track of the shift in the gram schmidt algorithm
for (k = 0; k < n; k++)
temp[k] = 0;
// for each previously computed b*j perform the steps:
//
// (2) mu_ij = <bi, b*j> / B[j] (compute shift coefficient)
// (3) b*i = b*i - mu_ij*b*j (shift by each previous b*j)
//
// note that this is not performed in the first iteration when i=0
for (j = 0; j < i; j++)
{
// (2) compute mu_ij = <b_i, b*_j> / <b*_j, b*_j>
numerator = 0;
for (k = 0; k < n; k++)
numerator += b[k*n + i] * b_star[k*n + j];
mu[i*n + j] = numerator / B[j];
// printf("\nnumerator = %f \t B[%d] = %f", numerator, j, B[j]);
// (3) shift b*i by - mu_ij b*j
for (k = 0; k < n; k++)
b_star[k*n + i] -= mu[i*n + j] * b_star[k*n + j];
}
// (4) store the dot product Bi = <b*i, b*i>
dot = 0;
for (k = 0; k < n; k++)
dot += b_star[k*n + i]*b_star[k*n + i];
B[i] = dot;
}
free(b_star);
free(temp);
}
/*
nearest_integer_shift
Performs operation (*) on p. 521 of [LLL].
Parameters
----------
mu : double[:,:]
b : double[:,:]
k,l : int
n : int
Size of each vector.
lc : double
LLL parameter.
*/
void nearest_integer_shift(double* mu, double* b, int k, int l,
int n, double lc)
{
int i,j;
double r = round(mu[k*n + l]);
if (fabs(mu[k*n+l]) > lc)
{
// shift bk by (-r*bl)
for (i = 0; i < n; i++)
b[i*n + k] -= r*b[i*n + l];
// shift mu_kj by (-r*mu_lj) for j=0,...,l-2
for (j = 0; j < l-1; j++)
mu[k*n + j] -= r*mu[l*n + j];
// shift mu_kl by (-r)
mu[k*n + l] -= r;
}
}
/*
lll_reduce
Performs Lenstra-Lenstra-Lovasv reduction on a given lattice n in
n-dimensional real space. The input matrix b is in the usual C-ordering but
the algorithm works on the columns. (This should be rewritten in a future
update for performance purposes.)
Parameters
----------
b : double[:]
Input array / `n x n` matrix.
n : int
lc,uc : double
The LLL parameters.
Returns
-------
b : double[:]
The LLL reduction of the columns of the input `b`.
*/
void lll_reduce(double* b, int n, double lc, double uc)
{
int i,j,k,l;
double tmp, B_tmp, mu_tmp;
double swap_condition;
double* mu = (double*)calloc(n*n, sizeof(double));
double* B = (double*)calloc(n, sizeof(double));
// initialize mu and B with zeros
for (i = 0; i < n*n; i++)
mu[i] = 0;
for (i = 0; i < n; i++)
B[i] = 0;
// orthogonalize the columns of b and obtain the scaling factors B and mu
gram_schmidt(b,mu,B,n);
k = 1;
while (k < n)
{
nearest_integer_shift(mu, b, k, k-1, n, lc);
swap_condition = (uc - mu[k*n + (k-1)]*mu[k*n + (k-1)])*B[k-1];
if (B[k] < swap_condition)
{
// set the "constant parameters" for this round
mu_tmp = mu[k*n + (k-1)];
B_tmp = B[k] + mu_tmp*mu_tmp*B[k-1];
// scale and swap mu and B values
mu[k*n + (k-1)] = mu_tmp*B[k-1] / B_tmp;
B[k] = B[k-1]*B[k] / B_tmp;
B[k-1] = B_tmp;
// swap b_(k-1) and b_k
for (i = 0; i < n; i++)
{
tmp = b[i*n + k];
b[i*n + k] = b[i*n + (k-1)];
b[i*n + (k-1)] = tmp;
}
// swap mu_(k-1),j and mu_k,j for j = 0,...,k-3
for (j = 0; j < k-2; j++)
{
tmp = mu[k*n + j];
mu[k*n + j] = mu[(k-1)*n + j];
mu[(k-1)*n + j] = tmp;
}
// perform the linear transformation for i = k,...,n-1
for (i = k; i < n; i++)
{
tmp = mu[i*n + (k-1)] - mu_tmp*mu[i*n + k];
mu[i*n + (k-1)] = mu[i*n + k] + mu[k*n + (k-1)] * tmp;
mu[i*n + k] = tmp;
}
if (k > 1)
k -= 1;
}
else
{
// perform the integer shift for l = k-3, ..., 0
for (l = k-3; l >= 0; l--)
{
nearest_integer_shift(mu, b, k, l, n, lc);
}
k += 1;
}
}
free(mu);
free(B);
}
|
C
|
/*
Ryan Sprowles
fork_and_exec.c - forks the program and uses the execvp fucntion to
fork off the current function and then execute using the fork instead
of the master
*/
#include "fork_and_exec.h"
void fork_and_exec(char **args, char fullcmd [])
{
int pid, status;
int i;
/*
* Get a child process.
*/
//printf("%p \n", *buf);
//printf("%p \n", *args);
if ((pid = fork ()) < 0) {
perror ("fork");
printf("%s", "failed at fork");
exit (1);
/* NOTE: perror() produces a short error message on the standard
error describing the last error encountered during a call to
a system or library function.
*/
}
/*
* The child executes the code inside the if.
*/
if (pid == 0) {
printf("fullcmd in fork %s \n", fullcmd);
i = 0;
while (args[i] != NULL) {
printf("fork args %d = %s\n",i, args[i]);
i++;
}
execv (fullcmd, args);
// printf("%p \n", **args);
// printf("%s \n", *buf);
//printf("Success?");
perror (*args);
printf("%s", "failed at 0 \n");
exit (1);
}
/*
* The parent executes the wait.
*/
while (wait (&status) != pid) {
}
}
|
C
|
//problema 2
//Determina si un cuerpo esta en reposo o no
#include<stdio.h>
#define TAM 50
int suma_terminos (int n,int p[])
{
int i,s=0;
for(i=0;i<p[n];i++){
s+=p[i];
}
return s;
}
int vectores (int n,int a[],int b[],int c[])
{
int x,y,z;
x=suma_terminos(n,a);
y=suma_terminos(n,b);
z=suma_terminos(n,c);
if(x==0&&y==0&&z==0){
return 1;}
else{
return 0;}
}
int main (void)
{
int n,i,r;
int a[TAM+1],b[TAM+1],c[TAM+1];
printf("Numero de fuerzas sobre el punto: ");
scanf("%d",&n);
for(i=0;i<n;i++){
printf("Ingresar vector %d --> x y z : ",i+1);
scanf("%d%d%d",&a[i],&b[i],&c[i]);
}
r=vectores(n,a,b,c);
if(r==0)
printf("NO\n");
else
printf("SI\n");
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
#include <libgen.h>
#include "answer05.h"
#define TRUE 1
#define FALSE 0
#define BITS_PER_PIXEL 8
/*
typedef struct ImageHeader_st {
uint32_t magic_number; // Should be ECE264_IMAGE_MAGIC_NUMBER
uint32_t width; // [width x height], cannot be zero
uint32_t height;
uint32_t comment_len; // A comment embedded in the file
} ImageHeader;
typedef struct Image_st {
int width;
int height;
char * comment;
uint8_t * data;
} Image;
*/
/**
* Loads an ECE264 image file, returning an Image structure.
* Will return NULL if there is any error.
*
* Hint: Please see the README for extensive hints
*/
Image * Image_load(const char * filename) {
FILE * file = NULL;
size_t read;
ImageHeader header;
Image * ImageTemp = NULL;
Image * ImageMain = NULL;
size_t n_bytes = 0;
int error = FALSE;
if (!error) { //Try to open image file stream
file = fopen(filename, "rb"); //Open file with non-text read
if (!file) { //File is null
fprintf(stderr, "Failed to open file '%s'\n", filename);
error = TRUE;
}
}
if (!error) { //Try to read image header
//Read header
read = fread(&header, sizeof(ImageHeader), 1, file);
if (read != 1) { //Header read failure
fprintf(stderr, "Failed to read header from '%s'\n", filename);
error = TRUE;
}
}
if (!error) { //print out header info
printf("Printing EE264 header information:\n");
printf(" file type (should be %x): %x\n", ECE264_IMAGE_MAGIC_NUMBER, header.magic_number);
printf(" file width: %d\n", header.width);
printf(" file height: %d\n", header.height);
printf(" file comment size: %d\n", header.comment_len);
}
if (!error) { //check file validity of header vals
if (header.magic_number != ECE264_IMAGE_MAGIC_NUMBER) {
fprintf(stderr, "Invalid header in '%s'\n", filename);
error = TRUE;
}
if ((header.width <= 0) || (header.height <= 0)) {
fprintf(stderr, "Invalid dimensions in '%s'\n", filename);
error = TRUE;
}
if ((header.comment_len <= 0) || (header.comment_len > 2000)) {
fprintf(stderr, "Invalid comment length in '%s'\n", filename);
error = TRUE;
}
if ((header.width > 2000) || (header.height > 2000)) {
fprintf(stderr, "Invalid dimensions in '%s'\n", filename);
error = TRUE;
}
}
//So far...
//File exists
//File header exists
//Header # OK
//Header dim input OK
//Header com len input OK
if (!error) {//Allocate Image struct
ImageTemp = malloc(sizeof(Image));
if (ImageTemp == NULL) {
fprintf(stderr, "Failed to allocate image structure.\n");
error = TRUE;
}
}
printf("Allocated image struct\n");
if (!error) { //Initialize the image struct
ImageTemp->width = header.width;
ImageTemp->height = header.height;
//deal with the file comment
char * file_comment = malloc(sizeof(char) * header.comment_len);
read = fread(file_comment, sizeof(char), header.comment_len, file);
//temp
printf( "file comment: %s\n file comment length: %d\n", file_comment, strlen(file_comment));
n_bytes = sizeof(char) * (strlen(file_comment) + 1);
ImageTemp->comment = malloc(n_bytes);
if (ImageTemp->comment == NULL) {
fprintf(stderr, "Failed to allocate %zd bytes for comment\n", n_bytes);
error = TRUE;
} else {
sprintf(ImageTemp->comment, "%s", file_comment);
}
free(file_comment);
printf("dealt with file comment\n");
/*//find the comment in the header
char * filenameCopy = strdup(filename);
char * file_basename = basename(filenameCopy);
const char * prefix = "Original bmp file: ";
n_bytes = sizeof(char) * (strlen(prefix) + strlen(file_basename) + 1);
//n_bytes = sizeof(char) * header.comment_len + 1;
ImageTemp->comment = malloc(n_bytes);
if (ImageTemp->comment == NULL) { //there is no comment area
fprintf(stderr, "Failed to allocate %zd bytes for comment\n", n_bytes);
error = TRUE;
}
else {
sprintf(ImageTemp->comment, "%s%s", prefix, file_basename);
}
free(filenameCopy); //the free of strdup's malloc
*/
//Handle image data
n_bytes = (sizeof(uint8_t) * header.width * header.height);
ImageTemp->data = malloc(n_bytes);
if (ImageTemp->data == NULL) {
//No image data space
fprintf(stderr, "Failed to allocate %zd bytes for image data\n", n_bytes);
error = TRUE;
}
}
if (!error) { //Read pixel data
size_t bytes_per_row = ((BITS_PER_PIXEL * header.width + 31) / 32) * 4;
//size_t bytes_per_row = (header.width);
n_bytes = bytes_per_row * header.height;
uint8_t * rawEE264 = malloc(n_bytes);
if (rawEE264 == NULL) { //Image byte data not allocated
fprintf(stderr, "Could not allocate %zd bytes of image data\n", n_bytes);
error = TRUE;
} else { //Image byte data allocation attempted
read = fread(rawEE264, sizeof(uint8_t), n_bytes, file);
if (n_bytes != read) {//Not reading entire data chunk
fprintf(stderr, "Only read %zd of %zd bytes of image data\n", read, n_bytes);
error = TRUE;
} else {//convert to Grayscale
uint8_t * write_ptr = ImageTemp->data;
uint8_t * read_ptr;
int intensity;
int row;
int column;
for (row = 0; row < header.height; ++row) {
read_ptr = &rawEE264[row * bytes_per_row];
for (column = 0; column < header.width; ++column) {
intensity = *read_ptr++; //blue
//intensity += *read_ptr++; //green
//intensity += *read_ptr++; //red
*write_ptr++ = intensity;// / 3; //now grayscale
}
}
}
}
free(rawEE264);
}
if (!error) { //Should be at the end
uint8_t byte;
read = fread(&byte, sizeof(uint8_t), 1, file);
if (read != 0) {
fprintf(stderr, "Stray bytes at the end of bmp file '%s'\n", filename);
error = TRUE;
}
}
if (!error) { //Set up data return
ImageMain = ImageTemp; //EE264 image will be returned
ImageTemp = NULL; //and not cleaned up
}
if (ImageTemp != NULL) { //clean up
free(ImageTemp->comment);
free(ImageTemp->data);
free(ImageTemp);
}
if (file) { //file stream still open
fclose(file);
}
if (error) { // NULL on error, image data on success
return(NULL);
} else {
return(ImageMain);
}
}
/**
* Save an image to the passed filename, in ECE264 format.
* Return TRUE if this succeeds, or FALSE if there is any error.
*
* Hint: Please see the README for extensive hints
*/
int Image_save(const char * filename, Image * image) {
int error = FALSE;
FILE * file = NULL;
uint8_t * buffer = NULL;
size_t written = 0;
//Attempt to open file for writing
file = fopen(filename, "wb");
if (file == NULL) {
fprintf(stderr, "Failed to open '%s' for writing\n", filename);
return(FALSE);
}
//Number of bytes stored on each row
//8 bits per pixel
size_t bytes_per_row = ((8 * image->width + 31) / 32) * 4;
//Prep header
ImageHeader header;
header.magic_number = ECE264_IMAGE_MAGIC_NUMBER;
header.width = image->width;
header.height = image->height;
header.comment_len = strlen(image->comment) + 1;
if (!error) {//write header
written = fwrite(&header, sizeof(ImageHeader), 1, file);
if (written != 1) {
fprintf(stderr, "Error: only wrote %zd of %zd of file header tp '%s'\n", written, sizeof(ImageHeader), filename);
error = TRUE;
}
}
if (!error) { //print out header info
printf("Printing EE264 header information:\n");
printf(" file type (should be %x): %x\n", ECE264_IMAGE_MAGIC_NUMBER, header.magic_number);
printf(" file width: %d\n", header.width);
printf(" file height: %d\n", header.height);
printf(" file comment size: %d\n", header.comment_len);
printf(" file comment: %s\n", image->comment);
printf(" file comment strlen: %d\n", strlen(image->comment));
}
fwrite(image->comment, sizeof(char), strlen(image->comment)+1, file);
if (!error) {//write buffer
buffer = malloc(bytes_per_row);
if (buffer == NULL) {
fprintf(stderr, "Error: failed to allocate write buffer\n");
error = TRUE;
} else {
memset(buffer, 0, bytes_per_row);
}
}
if (!error) {
uint8_t * read_ptr = image->data;
int row;
int col;
for (row = 0; row < header.height && !error; ++row) {
uint8_t * write_ptr = buffer;
for (col = 0; col < header.width; ++col) {
*write_ptr++ = *read_ptr; //blue
//*write_ptr++ = *read_ptr; //green
//*write_ptr++ = *read_ptr; //red
read_ptr++; //go to next pixel
}
//write line to file
written = fwrite(buffer, sizeof(uint8_t), bytes_per_row, file);
if (written != bytes_per_row) {
fprintf(stderr, "Failed to write pixel data to file\n");
error = TRUE;
}
}
}
free(buffer);
if (file) {
fclose(file);
}
return(!error);
}
/**
* Free memory for an image structure
*
* Image_load(...) (above) allocates memory for an image structure.
* This function must clean up any allocated resources. If image is
* NULL, then it does nothing. (There should be no error message.) If
* you do not write this function correctly, then valgrind will
* report an error.
*/
void Image_free(Image * image) {
if (image != NULL) {
free(image->comment);
free(image->data);
free(image);
}
}
/**
* Performs linear normalization, see README
*/
void linearNormalization(int width, int height, uint8_t * intensity) {
uint8_t maxIntensity = 0;
uint8_t minIntensity = 255;
int curPixel;
int n_pixels = width * height;
for (curPixel = 0; curPixel < n_pixels; curPixel++) {
if (intensity[curPixel] < minIntensity) {
minIntensity = intensity[curPixel];
}
if (intensity[curPixel] > maxIntensity) {
maxIntensity = intensity[curPixel];
}
}
for (curPixel = 0; curPixel < n_pixels; curPixel++) {
intensity[curPixel] = (intensity[curPixel] - minIntensity) * 255.0 / (maxIntensity - minIntensity);
}
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#define MAX_TREE_HT 50
struct Node {
char item;
int freq;
struct Node *left, *right;
};
struct Heap {
int size;
int capacity;
struct Node **array;
};
struct Node *init(char item, int freq) {
struct Node *n = (struct Node *)malloc(sizeof(struct Node));
n->left = NULL;
n->right = NULL;
n->item = item;
n->freq = freq;
return n;
}
struct Heap *createHeap(int capacity) {
struct Heap *heap = (struct Heap *)malloc(sizeof(struct Heap));
heap->size = 0;
heap->capacity = capacity;
heap->array = (struct Node **)malloc(heap->capacity * sizeof(struct Node *));
return heap;
}
void Heapify(struct Heap *h, int idx) {
int smallest = idx;
int left = 2 * idx + 1;
int right = 2 * idx + 2;
if (left < h->size && h->array[left]->freq < h->array[smallest]->freq)
smallest = left;
if (right < h->size && h->array[right]->freq < h->array[smallest]->freq)
smallest = right;
if (smallest != idx) {
struct Node *temp = h->array[smallest];
h->array[smallest] = h->array[idx];
h->array[idx] = temp;
Heapify(h, smallest);
}
}
struct Node *extractMin(struct Heap *h) {
struct Node *temp = h->array[0];
h->array[0] = h->array[h->size - 1];
--h->size;
Heapify(h, 0);
return temp;
}
void insertHeap(struct Heap *Heap, struct Node *HeapNode) {
++Heap->size;
int i = Heap->size - 1;
while (i && HeapNode->freq < Heap->array[(i - 1) / 2]->freq) {
Heap->array[i] = Heap->array[(i - 1) / 2];
i = (i - 1) / 2;
}
Heap->array[i] = HeapNode;
}
void buildHeap(struct Heap *h) {
int n = h->size - 1;
int i;
for (i = (n - 1) / 2; i >= 0; --i)
Heapify(h, i);
}
int isLeaf(struct Node *root) {
return !(root->left) && !(root->right);
}
struct Heap *createAndBuildHeap(char item[], int freq[], int size) {
struct Heap *Heap = createHeap(size);
for (int i = 0; i < size; ++i)
Heap->array[i] = init(item[i], freq[i]);
Heap->size = size;
buildHeap(Heap);
return Heap;
}
struct Node *buildHuffmanTree(char item[], int freq[], int size) {
struct Node *left, *right, *top;
struct Heap *Heap = createAndBuildHeap(item, freq, size);
while (Heap->size != 1) {
left = extractMin(Heap);
right = extractMin(Heap);
top = init('$', left->freq + right->freq);
top->left = left;
top->right = right;
insertHeap(Heap, top);
}
return extractMin(Heap);
}
void printHCodes(struct Node *root, int arr[], int top) {
if (root->left) {
arr[top] = 0;
printHCodes(root->left, arr, top + 1);
}
if (root->right) {
arr[top] = 1;
printHCodes(root->right, arr, top + 1);
}
if (isLeaf(root)) {
printf(" %c | ", root->item);
int i;
for (i = 0; i < top; ++i)
printf("%d", arr[i]);
printf("\n");
}
}
void HuffmanCodes(char item[], int freq[], int size) {
struct Node *root = buildHuffmanTree(item, freq, size);
int arr[MAX_TREE_HT], top = 0;
printHCodes(root, arr, top);
}
int main() {
char arr[] = {'A', 'B', 'C', 'D'};
int freq[] = {8, 5, 3, 6};
int size = sizeof(arr) / sizeof(arr[0]);
printf("Text = ABCCDABDADADBCADBADABA\n");
printf("Before Compress = 10111100011101000101001001001111111101111000101110001000110011000010110010010"
"110101001100000011000110001110111110100111111010001000000011100011001\n");
printf(" Char - code \n");
printf("--------------------\n");
HuffmanCodes(arr, freq, size);
printf("After Compress = 01111101101001111001001011111001011101001110");
return 0;
}
|
C
|
#include "stm32f4xx.h"
#include <string.h>
#include<stdio.h>
void printAnd(const int a)
{
char Msg[100];
char *ptr;
sprintf(Msg,"\n____AND FUNCTION__________");
ptr = Msg ;
while(*ptr != '\0')
{
ITM_SendChar(*ptr);
++ptr;
}
sprintf(Msg, "%x", a);
ptr = Msg ;
}
void printOr(const int a)
{
char Msg[100];
char *ptr;
sprintf(Msg,"\n____OR FUNCTION___________");
ptr = Msg ;
while(*ptr != '\0')
{
ITM_SendChar(*ptr);
++ptr;
}
sprintf(Msg, "%x", a);
ptr = Msg ;
}
void printNot(const int a)
{
char Msg[100];
char *ptr;
sprintf(Msg,"\n____NOT FUNCTION__________");
ptr = Msg ;
while(*ptr != '\0')
{
ITM_SendChar(*ptr);
++ptr;
}
sprintf(Msg, "%x", a);
ptr = Msg ;
}
void printNand(const int a)
{
char Msg[100];
char *ptr;
sprintf(Msg,"\n____NAND FUNCTION_________");
ptr = Msg ;
while(*ptr != '\0')
{
ITM_SendChar(*ptr);
++ptr;
}
sprintf(Msg, "%x", a);
ptr = Msg ;
}
void printNor(const int a)
{
char Msg[100];
char *ptr;
sprintf(Msg,"\n____NOR FUNCTION__________");
ptr = Msg ;
while(*ptr != '\0')
{
ITM_SendChar(*ptr);
++ptr;
}
sprintf(Msg, "%x", a);
ptr = Msg ;
}
void printMsg4p(const int a, const int b, const int c, const int d)
{
char Msg[100];
char *ptr;
// Printing the first input X0
sprintf(Msg,"\n ");
ptr = Msg ;
while(*ptr != '\0')
{
ITM_SendChar(*ptr);
++ptr;
}
sprintf(Msg, "%x", a);
ptr = Msg ;
while(*ptr != '\0')
{
ITM_SendChar(*ptr);
++ptr;
}
// Printing the second input X1
sprintf(Msg,"\t ");
ptr = Msg ;
while(*ptr != '\0')
{
ITM_SendChar(*ptr);
++ptr;
}
sprintf(Msg, "%x", b);
ptr = Msg ;
while(*ptr != '\0')
{
ITM_SendChar(*ptr);
++ptr;
}
// Printing the third input X2
sprintf(Msg,"\t ");
ptr = Msg ;
while(*ptr != '\0')
{
ITM_SendChar(*ptr);
++ptr;
}
sprintf(Msg, "%x", c);
ptr = Msg ;
while(*ptr != '\0')
{
ITM_SendChar(*ptr);
++ptr;
}
// Printing the OUTPUT
sprintf(Msg,"\t ");
ptr = Msg ;
while(*ptr != '\0')
{
ITM_SendChar(*ptr);
++ptr;
}
sprintf(Msg, "%x", d);
ptr = Msg ;
while(*ptr != '\0')
{
ITM_SendChar(*ptr);
++ptr;
}
}
|
C
|
#include <stdio.h>
#include <string.h>
int main()
{
char a[100];
int length;
printf("Enter a string to calculate it's length: \n");
scanf(" %s", a);
length = strlen(a);
printf("The length of the string is %d. \n", length);
return 0;
}
|
C
|
#include <stdio.h>
#include <string.h>
#include <sds.h>
sds matrix_show(int **matrix, int matrixSize, int *matrixColSize) {
sds str = sdsnew("[");
for (int i = 0; i < matrixSize; ++i) {
str = sdscat(str, "[");
for (int j = 0; j < *(matrixColSize + i); ++j) {
if (j == 0) {
str = sdscatprintf(str, "%d", matrix[i][j]);
} else {
str = sdscatprintf(str, ", %d", matrix[i][j]);
}
if (j == *(matrixColSize + i) - 1) {
str = sdscat(str, "]");
}
}
if (i != matrixSize - 1) {
str = sdscat(str, ", ");
}
}
str = sdscat(str, "]");
return str;
}
|
C
|
/* See LICENSE file for copyright and license details. */
#include "common.h"
#ifndef TEST
void *
libsimple_rawmemrchr_inv(const void *s_, int c_, size_t n)
{
char *s = *(char **)(void *)&s_, c = (char)c_;
while (s[--n] == c);
return &s[n];
}
#else
#include "test.h"
int
main(void)
{
assert(!strcmpnul(libsimple_rawmemrchr_inv("aabbaabb", 'b', 8), "abb"));
assert(!strcmpnul(libsimple_rawmemrchr_inv("aabbaabb", 'B', 8), "b"));
assert(!strcmpnul(libsimple_rawmemrchr_inv("AABBAABB", 'b', 8), "B"));
assert(!strcmpnul(libsimple_rawmemrchr_inv("AABBAABB", 'B', 8), "ABB"));
assert(!strcmpnul(libsimple_rawmemrchr_inv("aabbaabb", 'a', 8), "b"));
assert(!strcmpnul(libsimple_rawmemrchr_inv("aabbbb\0", '\0', 8), "b"));
return 0;
}
#endif
|
C
|
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/wait.h>
#define MSIZE 128
int main(){
char inBuffer[MSIZE];
int p[2], nbytes, pid;
if (pipe(p) < 0)
{
perror("Pipe error");
exit(1);
}
pid = fork();
if (pid < 0)
exit(2);
//Child beler a pipe-ba
if (pid == 0)
{
printf("Child: pipe-ba iras\n");
write(p[1], "SzM WJFAOO", MSIZE);
printf("Child: sikeres pipe-ba iras\n");
}
//Parent kiolvassa
else if (pid > 0 )
{
wait(NULL);
printf("Parent: kiolvasok a pipe-bol\n");
read(p[0], inBuffer, MSIZE);
printf("ezt olvastam ki: %s\n", inBuffer);
printf("Parent: finished\n");
}
return 0;
}
|
C
|
#ifndef __DEQUE_H__
#define __DEQUE_H__
// std
#include "stdio.h"
#include "stdlib.h"
// sys
#include "pthread.h"
// local
#include "product.h"
#include "utilities.h"
#include "semaphore.h"
typedef struct product_deque_t {
pthread_mutex_t mutex;
sem_t full, empty;
product_t *products;
unsigned size, max_size;
} product_deque_t;
/** @brief Initializes the given double ended queue.
*
* @param deque Pointer to a double ended queue instance.
*
* @param max_size The fixed size of the queue.
*
* @returns void.
*/
void product_deque_init(product_deque_t *deque, unsigned max_size);
/** @brief Attempts to add the given product to the end of the double ended queue.
*
* @param deque Pointer to a double ended queue instance.
*
* @param to_add Pointer to a product instance.
*
* @returns int Returns 0 if the given product was successfully added to the double ended queue, -1 otherwise.
*/
int product_deque_push(product_deque_t *deque, product_t *to_add);
/** @brief Returns and removes the product from the front of the double ended queue.
*
* @param deque Pointer to a double ended queue instance.
*
* @returns product_t Returns the product which was at the front of the double ended queue, if the queue is empty at the time of invocation, a product with an id of -1 is returned.
*/
product_t product_deque_pop(product_deque_t *deque);
/** @brief Removes all products from the double ended queue.
*
* @param deque Pointer to a double ended queue instance.
*
* @returns void.
*/
void product_deque_clear(product_deque_t *deque);
#endif //__DEQUE_H__
|
C
|
/*
* Copyright (c) 2019-2022, Arm Limited. All rights reserved.
*
* SPDX-License-Identifier: BSD-3-Clause
*
*/
#include "crt_impl_private.h"
void *memcpy(void *dest, const void *src, size_t n)
{
union composite_addr_t p_dst, p_src;
p_dst.uint_addr = (uintptr_t)dest;
p_src.uint_addr = (uintptr_t)src;
/* Byte copy for unaligned address. check the last bit of address. */
while (n && (ADDR_WORD_UNALIGNED(p_dst.uint_addr) ||
ADDR_WORD_UNALIGNED(p_src.uint_addr))) {
*p_dst.p_byte++ = *p_src.p_byte++;
n--;
}
/* Quad byte copy for aligned address. */
while (n >= sizeof(uint32_t)) {
*(p_dst.p_word)++ = *(p_src.p_word)++;
n -= sizeof(uint32_t);
}
/* Byte copy for the remaining bytes. */
while (n--) {
*p_dst.p_byte++ = *p_src.p_byte++;
}
return dest;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
main()
{
int v1,v2,v3,v;
printf("digite o primeiro valor\n");
scanf("%d",&v1);
printf("digite o segundo valor\n");
scanf("%d",&v2);
printf("digite o terceiro valor\n");
scanf("%d",&v3);
if(v1>=v2){
if(v3>v2)
v=v1+v3;
else
v=v1+v2;
printf("%d\n",v);
}
if(v2>=v1){
if(v1>v3)
v=v2+v1;
else
v=v2+v3;
printf("%d\n",v);
}
system("pause");
}
|
C
|
/*
* Copyright (C) 2017 - 2020 Christoph Muellner
*
* 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, see <http://www.gnu.org/licenses/>.
*/
#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
#include <errno.h>
#include <sys/ioctl.h>
#include <debuglog.h>
#include <linux/i2c-dev.h>
#include "helpers.h"
#include "hali2c.h"
struct hali2c_kernel_dev
{
/* Embed halgpio device */
struct hali2c_dev device;
/* I2C related state. */
char *i2c_device; /* I2C device (e.g. "/dev/i2c-0") */
int i2c_addr; /* I2C slave addr (e.g. 0x20) */
int i2c_fd; /* File descriptor to I2C device */
};
/*
* Parse the information encoded in a string with
* the following pattern: "<i2c_device>:<i2c_addr>"
*/
static int hali2c_kernel_parse(struct hali2c_kernel_dev *dev, char* config)
{
char *p = config;
char *endptr;
/* Advance p after the first ':' in
* the pattern "<i2c_device>:<i2c_addr>" */
p = strchr(p, ':');
if (!p) {
Log2(PCSC_LOG_ERROR, "No I2C slave address defined in '%s'", config);
return -EINVAL;
}
dev->i2c_device = strndup(config, p - config);
Log2(PCSC_LOG_DEBUG, "i2c_device: %s", dev->i2c_device);
p++;
/* Parse i2c_addr from the pattern "<i2c_addr>" */
errno = 0;
dev->i2c_addr = (int)strtol(p, &endptr, 0);
if (errno != 0 || p == endptr) {
Log2(PCSC_LOG_ERROR, "Parser error: invalid I2C address in '%s'", p);
return -EINVAL;
}
Log2(PCSC_LOG_DEBUG, "i2c_addr: %d", dev->i2c_addr);
return 0;
}
static int hali2c_kernel_open(struct hali2c_kernel_dev *dev)
{
int ret;
/* Open I2C device */
dev->i2c_fd = open(dev->i2c_device, O_RDWR);
if (dev->i2c_fd < 0) {
Log3(PCSC_LOG_ERROR, "Could not open I2C device %s (%d)",
dev->i2c_device, dev->i2c_fd);
return dev->i2c_fd;
}
Log3(PCSC_LOG_DEBUG, "I2C fd (%s): %d", dev->i2c_device, dev->i2c_fd);
/* Set the slave address */
ret = ioctl(dev->i2c_fd, I2C_SLAVE, dev->i2c_addr);
if (ret < 0) {
Log2(PCSC_LOG_ERROR, "Could not set I2C address: %d",
dev->i2c_addr);
close(dev->i2c_fd);
dev->i2c_fd = -1;
return -errno;
}
return 0;
}
static int hali2c_kernel_read(struct hali2c_dev* device, unsigned char* buf, size_t len)
{
struct hali2c_kernel_dev *dev = container_of(device, struct hali2c_kernel_dev, device);
ssize_t sret = read(dev->i2c_fd, buf, len);
if (sret < 0)
return -errno;
return (int)sret;
}
static int hali2c_kernel_write(struct hali2c_dev* device, const unsigned char* buf, size_t len)
{
struct hali2c_kernel_dev *dev = container_of(device, struct hali2c_kernel_dev, device);
ssize_t sret = write(dev->i2c_fd, buf, len);
if (sret < 0)
return -errno;
return (int)sret;
}
void hali2c_kernel_close(struct hali2c_dev* device)
{
struct hali2c_kernel_dev *dev = container_of(device, struct hali2c_kernel_dev, device);
if (dev->i2c_fd >= 0) {
close(dev->i2c_fd);
dev->i2c_fd = -1;
}
}
struct hali2c_dev* hali2c_open_kernel(char* config)
{
int ret;
struct hali2c_kernel_dev *dev;
if (!config)
return NULL;
Log2(PCSC_LOG_DEBUG, "Trying to create device with config: '%s'", config);
dev = calloc(1, sizeof(*dev));
if (!dev) {
Log1(PCSC_LOG_ERROR, "Not enough memory!");
return NULL;
}
/* Parse device string from reader.conf */
ret = hali2c_kernel_parse(dev, config);
if (ret) {
Log1(PCSC_LOG_ERROR, "device string can't be parsed!");
free(dev);
return NULL;
}
ret = hali2c_kernel_open(dev);
if (ret) {
Log1(PCSC_LOG_ERROR, "device can't be opened!");
free(dev);
return NULL;
}
dev->device.read = hali2c_kernel_read;
dev->device.write = hali2c_kernel_write;
dev->device.close = hali2c_kernel_close;
return &dev->device;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
#include "config.h"
#include "my_msgq.h"
int main(int argc, char *argv[])
{
printf("Compile time:%s %s\n", COMPILE_DATE, COMPILE_TIME);
printf("GCC version:%s\n", GCC_VERSION);
printf("--------Git--------\n%s\n",GIT_ALL);
my_msgq_t msg;
msgq_constuctor(&msg);
if(argc == 2){
if(*argv[1]=='s'){
char message[100]="[sender]:This is the sender";
printf("send message is\n");
printf("%s\n",message);
msgq_send(&msg, message, 100, 1);
}else if(*argv[1]=='r'){
char message[100]="\0";
msgq_rcv_wait(&msg, message, 100, 0);
printf("receiver message is\n");
printf("%s\n",message);
}else{
printf("error input!\n");
}
}else{
printf("----HOW TO RUN----\n");
printf("s-send\nt-receive\n");
}
return 0;
}
|
C
|
#include <gtk/gtk.h>
#include <string.h>
#include <ctype.h>
#include<stdlib.h>
#include<time.h>
int loadAllHints();
char *strupr(char *str);
void genAlert(char message[]);
void on_btn_rehint_clicked();
void on_btn_main_menu_clicked();
GtkWidget *window;
GtkWidget *g_lbl_hint;
GtkWidget *g_btn_submit;
GtkWidget *g_lbl_answer;
GtkWidget *g_txt_letter;
GtkWidget *g_btn_start;
GtkWidget *g_btn_rehint;
GtkWidget *g_btn_main_menu;
GtkWidget *g_img_init;
GtkWidget *g_img_1;
GtkWidget *g_img_2;
GtkWidget *g_img_3;
GtkWidget *g_img_4;
GtkWidget *g_img_5;
char allHints[50][100];
char allAnswers[50][50];
int numHints=0;
char currAns[50];
char currHint[50];
char encrAns[50];
int quitGame=0;
int rehinted=0;
int gameStage=0;
char enteredLetters[50];
int numLetters=0;
void init_game(int argc, char *argv[])
{
quitGame=0;
numLetters=0;
rehinted=0;
gameStage=0;
for(int i=0;i<50;i++){
enteredLetters[i]=' ';
encrAns[i]=' ';
}
GtkBuilder *builder;
gtk_init(&argc, &argv);
builder = gtk_builder_new();
gtk_builder_add_from_file (builder, "window_main1.glade", NULL);
window = GTK_WIDGET(gtk_builder_get_object(builder, "window_main"));
gtk_builder_connect_signals(builder, NULL);
// get pointers to the widgets
g_lbl_hint = GTK_WIDGET(gtk_builder_get_object(builder, "lbl_hint"));
g_btn_submit = GTK_WIDGET(gtk_builder_get_object(builder, "btn_submit"));
g_btn_start = GTK_WIDGET(gtk_builder_get_object(builder, "btn_start"));
g_txt_letter = GTK_WIDGET(gtk_builder_get_object(builder, "txt_letter"));
g_lbl_answer=GTK_WIDGET(gtk_builder_get_object(builder,"lbl_answer"));
g_btn_rehint=GTK_WIDGET(gtk_builder_get_object(builder,"btn_rehint"));
g_btn_main_menu=GTK_WIDGET(gtk_builder_get_object(builder,"btn_main_menu"));
g_img_init= GTK_WIDGET(gtk_builder_get_object(builder, "img_init"));
g_img_1 = GTK_WIDGET(gtk_builder_get_object(builder, "img_1"));
g_img_2 = GTK_WIDGET(gtk_builder_get_object(builder, "img_2"));
g_img_3 = GTK_WIDGET(gtk_builder_get_object(builder, "img_3"));
g_img_4 = GTK_WIDGET(gtk_builder_get_object(builder, "img_4"));
g_img_5 = GTK_WIDGET(gtk_builder_get_object(builder, "img_5"));
g_object_unref(builder);
gtk_widget_show(window);
gtk_main();
}
int main(int argc, char *argv[])
{
numHints=loadAllHints();
do{
init_game(argc, argv);
}while(quitGame);
return 0;
}
void showGame()
{
gtk_widget_show(g_lbl_hint);
gtk_widget_show(g_btn_rehint);
gtk_widget_show(g_btn_submit);
gtk_widget_show(g_lbl_answer);
gtk_widget_show(g_txt_letter);
gtk_widget_show(g_btn_main_menu);
gtk_widget_show(g_lbl_answer);
gtk_widget_hide(g_btn_start);
gtk_widget_hide(g_img_init);
}
int confirmExit()
{
GtkWidget *dialog;
dialog=gtk_message_dialog_new(GTK_WINDOW(window),
GTK_DIALOG_DESTROY_WITH_PARENT,
GTK_MESSAGE_QUESTION,
GTK_BUTTONS_YES_NO,
"Are you sure you want to quit?" );
gtk_window_set_title(GTK_WINDOW(dialog), "Quit Game");
int quit=gtk_dialog_run(GTK_DIALOG(dialog));
gtk_widget_destroy(dialog);
if (quit==GTK_RESPONSE_YES)
return 1;
else
return 0;
}
int winMessage()
{
GtkWidget *dialog;
dialog=gtk_message_dialog_new(GTK_WINDOW(window),
GTK_DIALOG_DESTROY_WITH_PARENT,
GTK_MESSAGE_QUESTION,
GTK_BUTTONS_YES_NO,
"Congrats, You Won!!\n Play Again?" );
gtk_window_set_title(GTK_WINDOW(dialog), "Congratulations!");
int playAgain=gtk_dialog_run(GTK_DIALOG(dialog));
gtk_widget_destroy(dialog);
if (playAgain==GTK_RESPONSE_YES)
return 1;
else
return 0;
}
int loseMessage(){
GtkWidget *dialog;
dialog=gtk_message_dialog_new(GTK_WINDOW(window),
GTK_DIALOG_DESTROY_WITH_PARENT,
GTK_MESSAGE_QUESTION,
GTK_BUTTONS_YES_NO,
"You lost all your lives!!\n Play Again with a new hint?" );
gtk_window_set_title(GTK_WINDOW(dialog), "You Lost!!");
int playAgain=gtk_dialog_run(GTK_DIALOG(dialog));
gtk_widget_destroy(dialog);
if (playAgain==GTK_RESPONSE_YES)
return 1;
else
return 0;
}
void setStage()
{
int playAgain;
if(strcmp(encrAns,currAns)==0){
if(rehinted)
return;
playAgain=winMessage();
if(playAgain)
on_btn_rehint_clicked();
else
on_btn_main_menu_clicked();
return;
}
if (gameStage==0){
gtk_widget_hide(g_img_2);
gtk_widget_hide(g_img_3);
gtk_widget_hide(g_img_4);
gtk_widget_hide(g_img_5);
gtk_widget_show(g_img_1);
}
else if(gameStage==1){
gtk_widget_hide(g_img_1);
gtk_widget_show(g_img_2);
}
else if(gameStage==2){
gtk_widget_hide(g_img_2);
gtk_widget_show(g_img_3);
}
else if(gameStage==3){
gtk_widget_hide(g_img_3);
gtk_widget_show(g_img_4);
}
else if(gameStage==4){
gtk_widget_hide(g_img_4);
gtk_widget_show(g_img_5);
playAgain=loseMessage();
if(playAgain)
on_btn_rehint_clicked();
else
on_btn_main_menu_clicked();
}
}
int loadAllHints(){ /*Abhir Raj - load all hints from notepad to char array */
int i=0;
FILE *hints,*answers;
answers=fopen("answers","r");
hints=fopen("hints","r");
while(!(feof(answers))){
fscanf(answers," %[^\n]s",allAnswers[i]);
strupr(allAnswers[i]);
i++;
}
fclose(answers);
i=0;
while(!(feof(hints))){
fscanf(hints," %[^\n]%*c",allHints[i]);
i++;
}
fclose(answers);
return ++i;
}
int genHint(void){ /*Abhir Raj - pick a random hint from array of hints*/
srand(time(NULL));
int upper=numHints-1;
int lower=0;
return ((rand()%(upper-lower))+lower);
}
void dispHint(void){ /*EG Harshal - use genHint and put the generated hint in label*/
int i=genHint();
gtk_label_set_text((GtkLabel *)g_lbl_hint,(const gchar *)allHints[i]);
strcpy(currAns,allAnswers[i]);
}
void dispAnswer(void){ /*EG Harshal - use display the encr. ans in label*/
int i;
for(i=0; i<strlen(currAns);i++){
if(isalpha(currAns[i])){
encrAns[i]='_';
}
else
encrAns[i]=currAns[i];
}
encrAns[i]='\0';
gtk_label_set_text ((GtkLabel *)g_lbl_answer,(const gchar *)encrAns);
}
int isCharRepeated(char c) /*Raj - Checks if char has already been entered by user*/
{
int i,r=0;
for(i=0;i<numLetters;i++)
{
if(enteredLetters[i]==c)
{
r++;
}
}
if(r==0)
return 0;
else
return 1;
}
int isRightChar(char c){ /*Raj- Checks if the char is present in answer*/
int i,r=0;
for(i=0;i<strlen(currAns);i++)
{
if(currAns[i]==c)
{
r++;
}
}
if(r==0)
return 0;
else
return 1;
}
void processChar(char c){ /*EG Harshal - uses isCharRepeated and isRightChar to check char and
displays char in label if correct else takes one life from user */
rehinted=0;
c=toupper(c);
int i;
if(isCharRepeated(c)){
genAlert(" You've already entered that Letter! ");
return;
}
else{
enteredLetters[numLetters]=c;
numLetters++;
}
if(isRightChar(c)){
for(i=0;i<strlen(currAns);i++){
if(currAns[i]==c){
encrAns[i]=c;
}
}
gtk_label_set_text((GtkLabel *)g_lbl_answer,(const gchar *)encrAns);
setStage();
}
else{
gameStage++;
setStage();
}
}
int isValidText(char text[])
{
int n=strlen(text);
if(n!=1){
return 0;
}
else if(!(isalpha(text[0]))){
return 0;
}
else
return 1;
}
void genAlert(char message[])
{
GtkWidget *dialog;
dialog=gtk_message_dialog_new(GTK_WINDOW(window),
GTK_DIALOG_DESTROY_WITH_PARENT,
GTK_MESSAGE_INFO,
GTK_BUTTONS_OK,
message );
gtk_window_set_title(GTK_WINDOW(dialog), "Alert!");
gtk_dialog_run(GTK_DIALOG(dialog));
gtk_widget_destroy(dialog);
return;
}
char *strupr(char *str)
{
unsigned char *p = (unsigned char *)str;
while (*p) {
*p = toupper((unsigned char)*p);
p++;
}
return str;
}
void on_btn_start_clicked()
{
dispHint();
dispAnswer();
gameStage=0;
setStage();
for(int i=0;i<50;i++){
enteredLetters[i]='\0';
} showGame();
return;
}
void on_btn_main_menu_clicked()
{
gtk_window_close(GTK_WINDOW(window));
quitGame=1;
return;
}
void on_btn_rehint_clicked()
{
rehinted=1;
numLetters=0;
for(int i=0;i<50;i++){
enteredLetters[i]='\0';
}
strcpy(encrAns,"");
dispHint();
dispAnswer();
gameStage=0;
setStage();
return;
}
void on_btn_submit_clicked()
{
char message1[]="You can only enter alphabets (one at a time)!";
char ip_text[20];
strcpy(ip_text,gtk_entry_get_text(GTK_ENTRY(g_txt_letter)));
gtk_entry_set_text(GTK_ENTRY(g_txt_letter),"");
gtk_widget_grab_focus(g_txt_letter);
if (isValidText(ip_text)){
processChar(ip_text[0]);
return;
}
else{
genAlert(message1);
return;
}
}
void on_btn_quit_clicked()
{
int quit=confirmExit();
if (quit)
gtk_main_quit();
return;
}
// called when window is closed
void on_window_main_destroy()
{
gtk_main_quit();
}
|
C
|
/* ================================================================== *
Universidade Federal de Sao Carlos - UFSCar, Sorocaba
Disciplina: Estruturas de Dados 1
Prof. Tiago A. Almeida
Exercício 04 - Ultima Carta
Instrucoes
----------
Este arquivo contem o codigo que auxiliara no desenvolvimento do
exercicio. Voce precisara completar as funcoes requisitadas.
Voce nao podera criar nenhuma outra funcao. Complete apenas as
rotinas fornecidas.
* ==================================================================
Dados do aluno:
RA: 726500
Nome: Bruno Morii Borges
* ================================================================== */
#include <stdio.h>
#include <stdlib.h>
// Frase exibida quando houver erro nas operacoes
#define FRASE_ERRO_ALOC "Erro de alocacao!\n"
// === TAD E DEMAIS REGISTROS ===
// <<< DEFINA AQUI O TAD >>>
typedef struct _carta{
int valor;
struct _carta *prox;
}Carta;
typedef struct _fila{
Carta *inicio;
Carta *fim;
}Fila;
/* ================================================================== */
/* ===================== PREAMBULO DAS FUNCOES ====================== */
/* ================================================================== */
// <<< COLOQUE O PREAMBULO DAS FUNCOES >>>
int enfileira(Fila *cartas, int valor);
int desenfileira(Fila *cartas);
Fila *inicializa();
void imprime(Fila *cartas);
void libera(Fila *cartas);
void recebe_cartas(Fila *cartas);
int descobre_carta(Fila *cartas);
/* ================================================================== */
/* ======================== ROTINA PRINCIPAL ======================== */
/* ================================================================== */
int main(){
// <<< IMPLEMENTE AQUI A ROTINA PRINCIPAL>>>
Fila *conjunto_cartas;
conjunto_cartas = inicializa();
if(conjunto_cartas == NULL){
printf(FRASE_ERRO_ALOC);
exit(1);
}
recebe_cartas(conjunto_cartas); //rotina para enfileirar as cartas
//imprime retorno da funcao que descobre a ultima carta
printf("%d\n", descobre_carta(conjunto_cartas));
free(conjunto_cartas);
return (0);
}
/* ================================================================== */
/* ========== FUNCOES QUE DETERMINAM AS OPERACOES POSSIVEIS ========= */
/* ================================================================== */
// <<< IMPLEMENTE AQUI AS FUNCOES >>>
Fila *inicializa(){
Fila *aux;
aux = (Fila *) malloc (sizeof(Fila));
//inicializa os ponteiro de inicio e fim de fila
aux->inicio = NULL;
aux->fim = NULL;
return(aux);
}
int enfileira(Fila *cartas, int valor){
Carta *aux;
aux = (Carta *) malloc (sizeof(Carta));
if(aux == NULL){ //verifica de alocou corretamente
return(0);
}
//da valor a carta
aux->valor = valor;
aux->prox = NULL;
if(cartas->inicio == NULL){ //se fila esta vazia
cartas->inicio = aux;
cartas->fim = aux;
}else{ //se nao esta vazia
cartas->fim->prox = aux;
cartas->fim = aux;
}
return(1);
}
int desenfileira(Fila *cartas){
Carta *aux;
int valor_recuperado;
if(cartas->inicio == NULL){ //verifica se fila esta vaiza
return(0);
}
aux = (Carta *) malloc (sizeof(Carta));
//move o inicio da fila
aux = cartas->inicio;
cartas->inicio = cartas->inicio->prox;
//recupera valor da carta
valor_recuperado = aux->valor;
free(aux); //libera memmoria
return(valor_recuperado);
}
void recebe_cartas(Fila *cartas){
int n;
do{
scanf("%d", &n);
if(n != 0){
enfileira(cartas, n);
}
}while(n != 0);
}
int descobre_carta(Fila *cartas){
Fila *descarte;
//cria pilha de descarte
descarte = inicializa();
if(descarte == NULL){
printf(FRASE_ERRO_ALOC);
exit(1);
}
//realiza operaçoes de descarte e mover
while(cartas->inicio->prox != NULL){
enfileira(descarte, desenfileira(cartas));
enfileira(cartas, desenfileira(cartas));
}
imprime(descarte);
return(cartas->inicio->valor);
}
void imprime(Fila *cartas){
Carta *aux = cartas->inicio;
while(aux != NULL){
printf("%d ", aux->valor);
aux = aux->prox;
}
printf("\n");
}
void libera(Fila *cartas){
Carta *aux = cartas->inicio, *aux2;
while(aux != NULL){
aux2 = aux;
aux = aux->prox;
free(aux2);
}
}
|
C
|
/*
** pointer.c for pointer in /home/lnanaay/projets/PSU_2016_my_printf
**
** Made by Nathan Lebon
** Login <lnanaay@epitech.net>
**
** Started on Fri Nov 11 16:16:13 2016 Nathan Lebon
** Last update Fri Nov 18 12:47:14 2016 Nathan Lebon
*/
#include <stdarg.h>
#include "my.h"
void convert_long(unsigned long nbr, unsigned long b, char *base)
{
unsigned long r;
unsigned long q;
r = nbr % b;
q = nbr / b;
if (q == 0)
{
my_putchar(base[r]);
return ;
}
convert_long(q, b, base);
if (r < b)
my_putchar(base[r]);
}
void get_adress(unsigned int c)
{
unsigned long b;
b = 16;
my_putchar('0');
my_putchar('x');
convert_long(c, b, "0123456789abcdef");
}
void adress(va_list valist)
{
if (va_arg(valist, unsigned int) == 0)
{
my_putstr("(nil)");
return ;
}
get_adress(va_arg(valist, unsigned int));
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
/**Função que recebe uma sopa de letras a e um array b de coordenadas e escreve em s os caracteres das coordenadas.*/
void descobrir(char **a, int b[], int N, char s[]){
int i, j = 0;
int tam = N/2;
int e, d;
for (i=0; i < tam; i++){
e = b[j]-1;
d = b[j+1]-1;
s[i] = a[e][d];
if (i != N-2) j += 2;
}
s[i] = '\0';
}
int main () {
int nl, nc, nl1, n, i = 0, j, *coord, k;
char palavra[100];
char *linha, **sopa;
k = scanf("%d %d", &nl, &nc);
nl1 = nl;
linha = (char *) malloc(nc * sizeof(char));
/**Memoria da matriz:*/
sopa = (char **) malloc(nl * sizeof(char*));
for(j=0; j < nl; j++)
sopa[j] = (char *) malloc(nc*sizeof(char));
/**Guardar cada linha inserida, na matriz:*/
while(nl1 > 0){
k = scanf("%s", linha);
for (j=0; j < nc; j++)
sopa[i][j] = linha[j];
nl1--;
i++;
}
/**Tratamento das coordenadas*/
k = scanf("%d", &n);
coord = malloc(n*2*sizeof(int));
for(i = 0; i < n*2; i++)
k = scanf("%d", &coord[i]);
descobrir(sopa, coord, n*2, palavra);
printf("String: %s\n", palavra);
if (k) {};
return 0;
}
|
C
|
#include "stdio.h"
/***********第2题***********/
void practice2()
{
int Ascii = 0;
printf("please enter the Value of ASCII:");
scanf("%d",&Ascii);
printf("\nyour enter value is:%d",Ascii);
printf("\nthe character:%c.\n",(char)Ascii);
getchar();
}
/************第3题**************/
void practice3()
{
printf("\a\nStartled by the sund, Sally shouted,\n");
printf("\"By the Great Pumpkin, what was that!\"");
}
/***********第4题****************/
void practice4()
{
float fl;
printf("Enter a floating-point value: ");
scanf("%f",&fl);
printf("\nfixed-ponit notation: %f",fl);
printf("\nexponential notation: %e",fl);
printf("\np notation: %a",fl);
getchar();
}
/************第5题*****************/
void practice5()
{
float year_second = 3.156e7;
int age = 0;
printf("\nPlease enter you age:");
scanf("%d",&age);
printf("\nyour age is %e seconds.",age*year_second);
getchar();
}
/************第6题***************/
void practice6()
{
double water_wight = 3.0e-23;
int kuake = 950;
int kuake_water = 0;
printf("\nPlease enter the wate kuake:");
scanf("%d",&kuake_water);
printf("the water can was:%le",(kuake_water*kuake/water_wight));
getchar();
}
/****************第7题**************/
void practice7()
{
float inch_to_cm = 2.54;
float height_in_inch = 0.0;
printf("\nPlease enter you height in inch:");
scanf("%f",&height_in_inch);
printf("you height in cm:%f cm",height_in_inch*inch_to_cm);
getchar();
}
/****************第8题**************/
void practice8()
{
float pints = 0.0;
float ounces = 0.0;
float big_spoons = 0.0;
float tea_spoons = 0.0;
printf("\nPlease enter you cups:");
int cup = 0;
scanf("%d",&cup);
pints = cup/2;
ounces = cup*8;
big_spoons = cup*8*2;
tea_spoons = cup*8*2*3;
printf("\nPints= %f ,Cups= %d , Ounces= %f ,Big_spoons= %f ,Tea_spoons= %f ",
pints ,cup,ounces ,big_spoons ,tea_spoons );
getchar();
}
int main(void)
{
practice2();
practice3();
practice4();
practice5();
practice6();
practice7();
practice8();
getchar();
return 0;
}
|
C
|
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/time.h>
#include <sys/wait.h>
#include <string.h>
#include <signal.h>
#include <fcntl.h>
#include <time.h>
int main(){
int pid;
if((pid = fork()) < 0){
printf("fork fail\n");
}
if(pid == 0){
sleep(199);
printf("free now!!!\n");
exit(-1);
}else{
printf("%d\n", pid);
wait(0);
}
}
|
C
|
/*Faça um algoritmo que receba uma data no formato DDMMAAAA e escreva qual
a estação do ano correspondente (Primavera, Verão, Outono, Inverno).
Outono
Mar a maio 2019 - 18:58h
Inverno
Jun a agosto2019 - 12:54h
Primavera
Set a novemb 2019 - 04:50h
Verão
Dez a fevereiro 2019 - 01:19h*/
#include <stdio.h>
#include <stdlib.h>
main ()
{
int dia, mes, ano;
printf ("\n Informe o dia:");
scanf ("%f",&dia);
printf ("\n Informe o mês: ");
scanf ("%f",&mes);
printf ("\n Informe o ano: ");
scanf ("%f",&ano);
if (&mes==8)
system:(0);
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.