language
large_stringclasses 1
value | text
stringlengths 9
2.95M
|
---|---|
C
|
//greatest of 2 integers
#include<stdio.h>
void main()
{
int a,b;
printf("Enter 1st number: ");
scanf("%d", &a);
printf("Enter 2nd number: ");
scanf("%d", &b);
if(a>b)
printf("First number is greater");
else if(b>a)
printf("Second number is greatest");
else
printf("Both are same");
}
|
C
|
/*
* Copyright 2011-12 ARM Limited
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* NE10 Library : inc/NE10_types.h
*/
/** NE10 defines a number of types for use in its function signatures.
* The types are defined within this header file.
*/
#ifndef NE10_TYPES_H
#define NE10_TYPES_H
#include <stdio.h>
#include <assert.h>
/////////////////////////////////////////////////////////
// constant values that are used across the library
/////////////////////////////////////////////////////////
#define NE10_OK 0
#define NE10_ERR -1
/////////////////////////////////////////////////////////
// some external definitions to be exposed to the users
/////////////////////////////////////////////////////////
typedef float arm_float_t; // a single float value
typedef int arm_result_t; // resulting [error-]code
typedef struct
{
float x;
float y;
} arm_vec2f_t; // a 2-tuple of float values
typedef struct
{
float x;
float y;
float z;
} arm_vec3f_t; // a 3-tuple of float values
typedef struct
{
float x;
float y;
float z;
float w;
} arm_vec4f_t; // a 4-tuple of float values
typedef struct { float r1; float r2; } __attribute__((packed)) arm_mat_row2f;
typedef struct
{
arm_mat_row2f c1;
arm_mat_row2f c2;
} __attribute__((packed)) arm_mat2x2f_t; // a 2x2 matrix
static inline void createColumnMajorMatrix2x2( arm_mat2x2f_t * outMat, arm_float_t m11, arm_float_t m21, arm_float_t m12, arm_float_t m22)
{
assert( NULL != outMat );
outMat->c1.r1 = m11;
outMat->c1.r2 = m21;
outMat->c2.r1 = m12;
outMat->c2.r2 = m22;
}
typedef struct { float r1; float r2; float r3; } __attribute__((packed)) arm_mat_row3f;
typedef struct
{
arm_mat_row3f c1;
arm_mat_row3f c2;
arm_mat_row3f c3;
} __attribute__((packed)) arm_mat3x3f_t; // a 3x3 matrix
static inline void createColumnMajorMatrix3x3( arm_mat3x3f_t * outMat, arm_float_t m11, arm_float_t m21, arm_float_t m31,
arm_float_t m12, arm_float_t m22, arm_float_t m32,
arm_float_t m13, arm_float_t m23, arm_float_t m33)
{
assert( NULL != outMat );
outMat->c1.r1 = m11;
outMat->c1.r2 = m21;
outMat->c1.r3 = m31;
outMat->c2.r1 = m12;
outMat->c2.r2 = m22;
outMat->c2.r3 = m32;
outMat->c3.r1 = m13;
outMat->c3.r2 = m23;
outMat->c3.r3 = m33;
}
typedef struct { float r1; float r2; float r3; float r4; } __attribute__((packed)) arm_mat_row4f;
typedef struct
{
arm_mat_row4f c1;
arm_mat_row4f c2;
arm_mat_row4f c3;
arm_mat_row4f c4;
} __attribute__((packed)) arm_mat4x4f_t; // a 4x4 matrix
static inline void createColumnMajorMatrix4x4( arm_mat4x4f_t * outMat, arm_float_t m11, arm_float_t m21, arm_float_t m31, arm_float_t m41,
arm_float_t m12, arm_float_t m22, arm_float_t m32, arm_float_t m42,
arm_float_t m13, arm_float_t m23, arm_float_t m33, arm_float_t m43,
arm_float_t m14, arm_float_t m24, arm_float_t m34, arm_float_t m44)
{
assert( NULL != outMat );
outMat->c1.r1 = m11;
outMat->c1.r2 = m21;
outMat->c1.r3 = m31;
outMat->c1.r4 = m41;
outMat->c2.r1 = m12;
outMat->c2.r2 = m22;
outMat->c2.r3 = m32;
outMat->c2.r4 = m42;
outMat->c3.r1 = m13;
outMat->c3.r2 = m23;
outMat->c3.r3 = m33;
outMat->c3.r4 = m43;
outMat->c4.r1 = m14;
outMat->c4.r2 = m24;
outMat->c4.r3 = m34;
outMat->c4.r4 = m44;
}
#endif
|
C
|
#include <stdlib.h>
#include <math.h>
#include <stdio.h>
#include "blobsBack.h"
#include <time.h>
#include <string.h>
static void llenaTablero (tTablero * tablero);
static int validaMovimiento (tMovimiento * movimiento, tTablero * tablero, int turno);
static size_t longSalto (tPosicion desde, tPosicion hasta);
static int ejecutaMovimiento (tMovimiento * movimiento, tTablero * tablero, size_t salto, int turno, size_t * cantManchas);
static int analizaMovimiento (tMovimiento * movimiento, tTablero * tablero, int turno);
static void completaTablero( tTablero * tablero, int turno, size_t * cantManchas);
static void realizaCaptura (tMovimiento * movimiento, tTablero * tablero, size_t * cantManchas, int turno);
static int estaEnElTablero (tPosicion posicion, tTablero * tablero);
static tTablero * creaTTablero (size_t alto, size_t ancho);
static int validaOpciones(tDatosJuego * datosJuego);
static char**
creaMatrizDin (size_t alto, size_t ancho) {
int i;
char **m;
m = malloc((alto)*sizeof(char *));
if (m == NULL)
return NULL;
for (i = 0; i<alto; i++) {
m[i] = malloc((ancho)*sizeof(char));
if (m[i] == NULL)
return NULL;
}
return m;
}
static tTablero*
creaTTablero (size_t alto, size_t ancho) {
tTablero* tablero;
tablero = malloc(sizeof(tTablero));
if (tablero == NULL)
return NULL;
tablero->tablero = creaMatrizDin(alto, ancho);
if (tablero->tablero == NULL)
return NULL;
tablero->ancho = ancho;
tablero->alto = alto;
return tablero;
}
tTablero*
creaTablero (size_t alto, size_t ancho) {
tTablero * tablero;
tablero = creaTTablero(alto, ancho);
llenaTablero(tablero);
return tablero;
}
void
liberaTablero (tTablero * tablero) {
int i;
for (i = 0; i < tablero->alto; i++)
free (tablero->tablero[i]);
free(tablero->tablero);
free(tablero);
}
static void
llenaTablero (tTablero * tablero) {
int i, j, ancho, alto;
ancho = tablero->ancho;
alto = tablero->alto;
for(i=0;i<alto;i++)
for(j=0;j<ancho;j++) {
if(ES_CENTINELA(i,j))
tablero->tablero[i][j] = CHAR_CENT;
else
tablero->tablero[i][j] = CHAR_BLANK;
}
tablero->tablero[OFFSET_CENT][OFFSET_CENT] = CHAR_J1;
tablero->tablero[alto-OFFSET_CENT-1][OFFSET_CENT] = CHAR_J1;
tablero->tablero[OFFSET_CENT][tablero->ancho-OFFSET_CENT-1] = CHAR_J2;
tablero->tablero[alto-OFFSET_CENT-1][tablero->ancho-OFFSET_CENT-1] = CHAR_J2;
}
int
moverCpu(tTablero * tablero, int turno, tMovimiento * mov) {
/*a) Si puede mover a una posicion que capture manchas enemigas, debera elegir la que
*capture mas manchas. Si hay mas de una posicion que capture dicha cantidad, elegir
*una al azar.
*b) Si puede mover una mancha a un casillero contiguo, lo hace.
*c) Si no se cumple ninguna de las anteriores, se elegira una posicion valida al azar.
* Esta ultima condicion nunca se da, por eso no esta programada.
*Una celda ofensiva convierte manchas enemigas.
*Una celda defensiva no convierte manchas enemigas y salta 1 celda.
*/
tPosicion celdaOrigen, celdaDestino;
tMovimiento * vecMovOfensivos = NULL;
tMovimiento * vecMovDefensivos = NULL;
int enemigosMax = 0, enemigosCelda = 0, x, y, i, j, m, n, dimOf = 0, dimDf = 0;
for(y = OFFSET_CENT; y < tablero->alto - OFFSET_CENT; y++) //Busco celdas del CPU en el Tablero
for(x = OFFSET_CENT; x < tablero->ancho - OFFSET_CENT; x++)
{ if(tablero->tablero[y][x] == CHAR_JUGADOR(turno)) /*Busca el caracter del CPU, el turno es del CPU*/
{ for(i = y-2; i <= y+2; i++) //Busco celdas vacias alrededor de una celda del CPU
for(j = x-2; j<= x+2; j++)
if(tablero->tablero[i][j] == CHAR_BLANK)
{ for(m = i-1; m <= i+1; m++) //Busco celdas enemigas alrededor de cada posible movimiento
for(n = j-1; n <= j+1; n++)
if(tablero->tablero[m][n] == CHAR_JUGADOR(siguienteTurno(turno))) /*El turno siguiente es del jugador*/
enemigosCelda++;
if(enemigosMax <= enemigosCelda && enemigosCelda != 0) // Creo un vector dinamico que guardara
{ if(enemigosMax < enemigosCelda) // todos los movimientos que convierten
{ enemigosMax = enemigosCelda; // la misma cantidad de manchas.
free(vecMovOfensivos);
vecMovOfensivos = NULL; //Inicializo en NULL para poder usar realloc como malloc.
dimOf = 1;
}
else
dimOf++;
if((vecMovOfensivos = realloc(vecMovOfensivos, sizeof(tMovimiento) * dimOf)) == NULL) //Si no existe lo creo, si ya existia el vector, lo agrando.
return ERR_NO_MEMORY;
vecMovOfensivos[dimOf - 1].desde.x = x; // Copio el movimiento al vector.
vecMovOfensivos[dimOf - 1].desde.y = y;
vecMovOfensivos[dimOf - 1].hasta.x = j;
vecMovOfensivos[dimOf - 1].hasta.y = i;
}
enemigosCelda = 0; // Reinicio la variable para la proxima celda vacia que encuentre.
celdaOrigen.x = x; //Le doy valores a una celda auxiliar para medir la longitud del salto.
celdaOrigen.y = y;
celdaDestino.x = j;
celdaDestino.y = i;
if(longSalto(celdaOrigen, celdaDestino)==1) // Verifica si es una celda defensiva de salto simple,
{ dimDf++;
if((vecMovDefensivos = realloc(vecMovDefensivos, sizeof(tMovimiento) * dimDf)) == NULL)
return ERR_NO_MEMORY;
vecMovDefensivos[dimDf - 1].desde.x = x; // Copio el movimiento al vector.
vecMovDefensivos[dimDf - 1].desde.y = y;
vecMovDefensivos[dimDf - 1].hasta.x = j;
vecMovDefensivos[dimDf - 1].hasta.y = i;
}
}
}
}
if(dimOf != 0) // Si encontro una ofensiva, prioriza ese movimiento.
{ * mov = vecMovOfensivos[randomBetween(0,dimOf-1,time(NULL))];
free(vecMovOfensivos);
free(vecMovDefensivos);
return OK;
}
else if(dimDf != 0) // Si no encontro una ofensiva pero si una defensiva simple (contigua), realiza este movimiento.
{ * mov = vecMovDefensivos[randomBetween(0,dimDf-1,time(NULL))];
free(vecMovDefensivos);
free(vecMovOfensivos);
return OK;
}
else
return ERR_UNKNOWN;
}
int randomBetween(int min, int max, int seed) {
srand(seed);
return (int)((max - min + 1.0)*(rand()/((RAND_MAX + 1.0)))) + min;
}
static int
analizaMovimiento (tMovimiento * movimiento, tTablero * tablero, int turno) {
/* Devuelve 1 o 2 si el movimiento es valido y 0 si no
* Devuelve 1 si es un movimiento de una celda o 2 si es de 2
* Recibe ademas que jugador ('A' o 'Z') haciendo ese movimiento para analizar si
* es correcto o no.
*/
int salto;
int aux;
if ((aux = validaMovimiento(movimiento,tablero, turno)) <= 0)
return aux;
salto = longSalto(movimiento->desde, movimiento->hasta);
if ( salto == 1 || salto == 2 )
return salto;
else
return ERR_MOV_INVALIDO;
}
static int
validaMovimiento (tMovimiento * movimiento, tTablero * tablero, int turno){
//ACORTAR LA LINEA DE ABAJO (NO SEPARAR EN 2 IFS)
if (!estaEnElTablero(movimiento->desde, tablero) || !estaEnElTablero(movimiento->hasta, tablero))
return ERR_FUERA_DEL_TABLERO;
if (!(tablero->tablero[movimiento->desde.y][movimiento->desde.x] == CHAR_JUGADOR(turno))) /*Valido que la casilla origen sea del jugador actual*/
return ERR_MANCHA_AJENA;
if (!(tablero->tablero[movimiento->hasta.y][movimiento->hasta.x] == CHAR_BLANK))
return ERR_CELDA_OCUPADA;
return 1;
}//en esta funcion habria que cambiar el parametro tMovimiento por un tPosicion, es mas general y solo trabaja conun par ordenado.
static int
estaEnElTablero (tPosicion posicion, tTablero * tablero) {
if (ESTA_ENTRE(posicion.x, OFFSET_CENT, tablero->ancho-OFFSET_CENT-1))
if (ESTA_ENTRE(posicion.y, OFFSET_CENT, tablero->alto-OFFSET_CENT-1))
return 1;
return 0;
}
static size_t
longSalto (tPosicion desde, tPosicion hasta){
// Utiliza la Norma Infinito para calcular la distancia entre celdas.
size_t a,b;
a = abs(hasta.x - desde.x);
b = abs(hasta.y - desde.y);
return (a > b)? a : b;
}
static int
ejecutaMovimiento (tMovimiento * movimiento, tTablero * tablero, size_t salto, int turno, size_t * cantManchas) {
/* Modifica el tablero con un movimiento valido
* Recibe el movimiento a ejecutar, el tablero a modificar, cuantas celdas
* salta la mancha (1 o 2 celdas).
* Realiza capturas (creo).*/
if (salto == ERR_COM_INVALIDO)
return ERR_COM_INVALIDO;
if (salto == 2)
tablero->tablero[movimiento->desde.y][movimiento->desde.x] = CHAR_BLANK; /*Si el salto es doble, no se duplica*/
if (salto == 1)
cantManchas[turno-1]++; //Solo si se replica aumenta en 1 la cantidad de manchas
tablero->tablero[movimiento->hasta.y][movimiento->hasta.x] = CHAR_JUGADOR(turno); /*Coloco la pieza del jugador*/
return 1;
}
int
analizaTablero (tDatosJuego * datosJuego) {
/* Devuelve 0 si la partida no termino y el jugador ganador en el caso que si
* El valor de cada jugador esta determinado por las constantes JUG1 y JUG2 en blobsBack.h
*/
{
int i, j, x, y;
for (i=OFFSET_CENT; i < datosJuego->tablero->alto-OFFSET_CENT; i++)
for (j=OFFSET_CENT; j < datosJuego->tablero->ancho-OFFSET_CENT; j++)
if (datosJuego->tablero->tablero[i][j] == CHAR_JUGADOR(datosJuego->turno))
for(y = i-2; y <= i+2; y++)
for(x = j-2; x <= j+2; x++) {
if(datosJuego->tablero->tablero[y][x] == CHAR_BLANK)
return INCONCLUSO;
}
}
completaTablero(datosJuego->tablero, datosJuego->turno, datosJuego->cantManchas);
return ((datosJuego->cantManchas[JUG1] > datosJuego->cantManchas[JUG2])?JUG1:JUG2);
}
static void
completaTablero( tTablero * tablero, int turno, size_t * cantManchas){
// Completa el tablero y devuelve el jugador ganador
int i,j;
for (i=OFFSET_CENT; i < tablero->alto-OFFSET_CENT ; i++)//Busca posiciones vacias
for (j=OFFSET_CENT; j < tablero->ancho-OFFSET_CENT; j++)
if (tablero->tablero[i][j] == CHAR_BLANK)
{
tablero->tablero[i][j] = CHAR_JUGADOR(siguienteTurno(turno));
cantManchas[siguienteTurno(turno)-1]++;
}
return;
}
int
moverMancha(tMovimiento * movimiento, tTablero * tablero, size_t * cantManchas, int turno) {
int salto;
int aux;
salto = analizaMovimiento(movimiento, tablero, turno);
if (salto < 0)
return salto;
aux = ejecutaMovimiento(movimiento, tablero, salto, turno, cantManchas);
realizaCaptura(movimiento, tablero, cantManchas, turno);
return aux;
}
int
cargarJuego (tDatosJuego * datosJuego, FILE * archivo) {
int i, j, alto, ancho, aux, cant[2]={0,0};
aux = fread((void*) datosJuego, sizeof(tDatosJuego) - sizeof(tTablero *), 1, archivo);
if (aux != 1)
return ERR_IMP_LEER;
aux = validaOpciones(datosJuego);
if (aux != OK)
return ERR_ARCH_CORRUPTO;
tTablero * nuevoTablero;
nuevoTablero = creaTTablero(datosJuego->altoReal+2*OFFSET_CENT, datosJuego->anchoReal+2*OFFSET_CENT);
alto = nuevoTablero->alto;
ancho = nuevoTablero->ancho;
for(i=0;i<alto;i++)
for(j=0;j<ancho;j++) {
if(ES_CENTINELA(i,j))
nuevoTablero->tablero[i][j] = CHAR_CENT;
else {
nuevoTablero->tablero[i][j]=fgetc(archivo);
if (ferror(archivo))
return ERR_IMP_LEER;
if (feof(archivo))
return ERR_ARCH_CORRUPTO;
if (nuevoTablero->tablero[i][j] == CHAR_J1)
cant[0]++;
else if (nuevoTablero->tablero[i][j] == CHAR_J2)
cant[1]++;
else if (nuevoTablero->tablero[i][j] != CHAR_BLANK)
return ERR_TAB_MAL_FORMADO;
}
}
if ((datosJuego->cantManchas[0] != cant[0]) || (datosJuego->cantManchas[1] != cant[1]))
return ERR_ARCH_CORRUPTO;
datosJuego->tablero = nuevoTablero;
return OK;
}
static int
validaOpciones(tDatosJuego * datosJuego)
{ if ((datosJuego->modo/2 == 0) && ((datosJuego->turno-1)/2 == 0) &&
datosJuego->anchoReal >= DIM_MIN && datosJuego->altoReal >= DIM_MIN &&
datosJuego->anchoReal <= ANCHO_MAX && datosJuego->altoReal <= ANCHO_MAX)
return OK;
return 1;
}
int
guardarJuego (tDatosJuego * datosJuego, FILE * archivo) {
int i, j, aux;
aux = fwrite((void*) datosJuego, (sizeof(tDatosJuego) - sizeof(tTablero *)), 1, archivo); //Escribe todo menos el tablero.
if (aux != 1)
return ERR_IMP_WRITE;
for (i = OFFSET_CENT; i < datosJuego->tablero->alto-OFFSET_CENT; i++)
for (j = OFFSET_CENT; j < datosJuego->tablero->ancho-OFFSET_CENT; j++)
fputc(datosJuego->tablero->tablero[i][j], archivo); //Escribe el tablero
return OK;
}
static void
realizaCaptura (tMovimiento * movimiento, tTablero * tablero, size_t * cantManchas, int turno)
{
int i;
int deltaX[]= {-1,0,1,-1,1,-1,0,1};
int deltaY[]= {-1,-1,-1,0,0,1,1,1};
for (i=0 ; i < 8; i++)
{
if (tablero->tablero[movimiento->hasta.y + deltaY[i]][movimiento->hasta.x + deltaX[i]] == CHAR_JUGADOR(siguienteTurno(turno)))
{
cantManchas[turno-1]++;
cantManchas[siguienteTurno(turno)-1]--;
tablero->tablero[movimiento->hasta.y + deltaY[i]][movimiento->hasta.x + deltaX[i]] = CHAR_JUGADOR(turno);
}
}
return;
}
int
siguienteTurno(int turno)
{ if (turno==1)
return 2;
else if (turno == 2)
return 1;
else
return 0;
}
|
C
|
#include <stdio.h>
#include <string.h>
#include <conio.h>
void main()
{
int i, n = 0;
int item;
char x[10] [12];
char temp[12];
clrscr();
printf("Enter each string on a separate line \n\n");
printf("Type 'END' when over \n\n");
/* Read in the list of strings */
do
{
printf("String %d: ", n + 1);
scanf("%s", x[n]);
} while (strcmp(x[n++], "END"));
/*Reorder the list of strings */
n = n - 1;
for(item = 0; item < n - 1; ++item)
{
/* Find lowest of remaining strings */
for(i = item + 1; i < n; ++i)
{
if(strcmp(x[item], x[i]) > 0)
{
/*Interchange two strings*/
strcpy(temp, x[item]);
strcpy(x[item], x[i]);
strcpy(x[i], temp);
}
}
}
/* Display the arranged list of strings */
printf("Recorded list of strings: \n");
for(i = 0; i < n; ++i)
{
printf("\nString %D is %s", i + 1, x[i]);
}
}
|
C
|
#include <stdio.h> //inclusão da biblioteca que contem as funções de printf e scanf
void main (){ //declarando a função principal;
int numero, somaMultiplos = 0; //declarando variaveis como inteiras;
do{ //iniciado antes da execução de cada interação do laço
printf("digite um numero: "); //entrada de usuario;
scanf("%d", &numero); //captura da entrada digitada;
if(numero % 5 == 0){ //condicional para capturar apenas os multiplos de 5
somaMultiplos = somaMultiplos + numero; // somando cada multiplo de 5
}
}
while(numero != 0); //condição de parada do laço
printf("a soma dos multiplos de 5 sera: %d", somaMultiplos); //resultado do programa.
}
|
C
|
/*
* Name: MicroEMACS
* Buffer handling.
* Version: 30
* Last edit: 17-Feb-86
* By: rex::conroy
* decvax!decwrl!dec-rhea!dec-rex!conroy
*/
#include "def.h"
/*
* Attach a buffer to a window. The
* values of dot and mark come from the buffer
* if the use count is 0. Otherwise, they come
* from some other window.
*/
usebuffer(f, n, k)
{
register BUFFER *bp;
register WINDOW *wp;
register int s;
char bufn[NBUFN];
if ((s=ereply("Use buffer: ", bufn, NBUFN)) != TRUE)
return (s);
if ((bp=bfind(bufn, TRUE)) == NULL)
return (FALSE);
if (--curbp->b_nwnd == 0) { /* Last use. */
curbp->b_dotp = curwp->w_dotp;
curbp->b_doto = curwp->w_doto;
curbp->b_markp = curwp->w_markp;
curbp->b_marko = curwp->w_marko;
}
curbp = bp; /* Switch. */
curwp->w_bufp = bp;
curwp->w_linep = bp->b_linep; /* For macros, ignored. */
curwp->w_flag |= WFMODE|WFFORCE|WFHARD; /* Quite nasty. */
if (bp->b_nwnd++ == 0) { /* First use. */
curwp->w_dotp = bp->b_dotp;
curwp->w_doto = bp->b_doto;
curwp->w_markp = bp->b_markp;
curwp->w_marko = bp->b_marko;
return (TRUE);
}
wp = wheadp; /* Look for old. */
while (wp != NULL) {
if (wp!=curwp && wp->w_bufp==bp) {
curwp->w_dotp = wp->w_dotp;
curwp->w_doto = wp->w_doto;
curwp->w_markp = wp->w_markp;
curwp->w_marko = wp->w_marko;
break;
}
wp = wp->w_wndp;
}
return (TRUE);
}
/*
* Dispose of a buffer, by name.
* Ask for the name. Look it up (don't get too
* upset if it isn't there at all!). Get quite upset
* if the buffer is being displayed. Clear the buffer (ask
* if the buffer has been changed). Then free the header
* line and the buffer header. Bound to "C-X K".
*/
killbuffer(f, n, k)
{
register BUFFER *bp;
register BUFFER *bp1;
register BUFFER *bp2;
register int s;
char bufn[NBUFN];
if ((s=ereply("Kill buffer: ", bufn, NBUFN)) != TRUE)
return (s);
if ((bp=bfind(bufn, FALSE)) == NULL) /* Easy if unknown. */
return (TRUE);
if (bp->b_nwnd != 0) { /* Error if on screen. */
eprintf("Buffer is being displayed");
return (FALSE);
}
if ((s=bclear(bp)) != TRUE) /* Blow text away. */
return (s);
free((char *) bp->b_linep); /* Release header line. */
bp1 = NULL; /* Find the header. */
bp2 = bheadp;
while (bp2 != bp) {
bp1 = bp2;
bp2 = bp2->b_bufp;
}
bp2 = bp2->b_bufp; /* Next one in chain. */
if (bp1 == NULL) /* Unlink it. */
bheadp = bp2;
else
bp1->b_bufp = bp2;
free((char *) bp); /* Release buffer block */
return (TRUE);
}
/*
* Display the buffer list. This is done
* in two parts. The "makelist" routine figures out
* the text, and puts it in the buffer whoses header is
* pointed to by the external "blistp". The "popblist"
* then pops the data onto the screen. Bound to
* "C-X C-B".
*/
listbuffers(f, n, k)
{
register int s;
if ((s=makelist()) != TRUE)
return (s);
return (popblist());
}
/*
* Pop the special buffer whose
* buffer header is pointed to by the external
* variable "blistp" onto the screen. This is used
* by the "listbuffers" routine (above) and by
* some other packages. Returns a status.
*/
popblist()
{
register WINDOW *wp;
register BUFFER *bp;
if (blistp->b_nwnd == 0) { /* Not on screen yet. */
if ((wp=wpopup()) == NULL)
return (FALSE);
bp = wp->w_bufp;
if (--bp->b_nwnd == 0) {
bp->b_dotp = wp->w_dotp;
bp->b_doto = wp->w_doto;
bp->b_markp = wp->w_markp;
bp->b_marko = wp->w_marko;
}
wp->w_bufp = blistp;
++blistp->b_nwnd;
}
wp = wheadp;
while (wp != NULL) {
if (wp->w_bufp == blistp) {
wp->w_linep = lforw(blistp->b_linep);
wp->w_dotp = lforw(blistp->b_linep);
wp->w_doto = 0;
wp->w_markp = NULL;
wp->w_marko = 0;
wp->w_flag |= WFMODE|WFHARD;
}
wp = wp->w_wndp;
}
return (TRUE);
}
/*
* This routine rebuilds the
* text in the special secret buffer
* that holds the buffer list. It is called
* by the list buffers command. Return TRUE
* if everything works. Return FALSE if there
* is an error (if there is no memory).
*/
makelist()
{
register char *cp1;
register char *cp2;
register int c;
register BUFFER *bp;
register LINE *lp;
register int nbytes;
register int s;
char b[6+1];
char line[128];
blistp->b_flag &= ~BFCHG; /* Blow away old. */
if ((s=bclear(blistp)) != TRUE)
return (s);
strcpy(blistp->b_fname, "");
if (addline("C Size Buffer File") == FALSE
|| addline("- ---- ------ ----") == FALSE)
return (FALSE);
bp = bheadp; /* For all buffers */
while (bp != NULL) {
cp1 = &line[0]; /* Start at left edge */
if ((bp->b_flag&BFCHG) != 0) /* "*" if changed */
*cp1++ = '*';
else
*cp1++ = ' ';
*cp1++ = ' '; /* Gap. */
nbytes = 0; /* Count bytes in buf. */
lp = lforw(bp->b_linep);
while (lp != bp->b_linep) {
nbytes += llength(lp)+1;
lp = lforw(lp);
}
itoa_(b, 6, nbytes); /* 6 digit buffer size. */
cp2 = &b[0];
while ((c = *cp2++) != 0)
*cp1++ = c;
*cp1++ = ' '; /* Gap. */
cp2 = &bp->b_bname[0]; /* Buffer name */
while ((c = *cp2++) != 0)
*cp1++ = c;
cp2 = &bp->b_fname[0]; /* File name */
if (*cp2 != 0) {
while (cp1 < &line[1+1+6+1+NBUFN+1])
*cp1++ = ' ';
while ((c = *cp2++) != 0) {
if (cp1 < &line[128-1])
*cp1++ = c;
}
}
*cp1 = 0; /* Add to the buffer. */
if (addline(line) == FALSE)
return (FALSE);
bp = bp->b_bufp;
}
return (TRUE); /* All done */
}
/*
* Used above.
*/
itoa_(buf, width, num)
register char buf[];
register int width;
register int num;
{
buf[width] = 0; /* End of string. */
while (num >= 10) { /* Conditional digits. */
buf[--width] = (num%10) + '0';
num /= 10;
}
buf[--width] = num + '0'; /* Always 1 digit. */
while (width != 0) /* Pad with blanks. */
buf[--width] = ' ';
}
/*
* The argument "text" points to
* a string. Append this line to the
* buffer list buffer. Handcraft the EOL
* on the end. Return TRUE if it worked and
* FALSE if you ran out of room.
*/
addline(text)
char *text;
{
register LINE *lp;
register int i;
register int ntext;
ntext = strlen(text);
if ((lp=lalloc(ntext)) == NULL)
return (FALSE);
for (i=0; i<ntext; ++i)
lputc(lp, i, text[i]);
blistp->b_linep->l_bp->l_fp = lp; /* Hook onto the end */
lp->l_bp = blistp->b_linep->l_bp;
blistp->b_linep->l_bp = lp;
lp->l_fp = blistp->b_linep;
if (blistp->b_dotp == blistp->b_linep) /* If "." is at the end */
blistp->b_dotp = lp; /* move it to new line */
return (TRUE);
}
/*
* Look through the list of
* buffers. Return TRUE if there
* are any changed buffers. Special buffers
* like the buffer list buffer don't count, as
* they are not in the list. Return FALSE if
* there are no changed buffers.
*/
anycb()
{
register BUFFER *bp;
bp = bheadp;
while (bp != NULL) {
if ((bp->b_flag&BFCHG) != 0)
return (TRUE);
bp = bp->b_bufp;
}
return (FALSE);
}
/*
* Search for a buffer, by name.
* If not found, and the "cflag" is TRUE,
* create a buffer and put it in the list of
* all buffers. Return pointer to the BUFFER
* block for the buffer.
*/
BUFFER *
bfind(bname, cflag)
register char *bname;
{
register BUFFER *bp;
bp = bheadp;
while (bp != NULL) {
if (strcmp(bname, bp->b_bname) == 0)
return (bp);
bp = bp->b_bufp;
}
if (cflag!=FALSE && (bp=bcreate(bname))!=NULL) {
bp->b_bufp = bheadp;
bheadp = bp;
}
return (bp);
}
/*
* Create a buffer, by name.
* Return a pointer to the BUFFER header
* block, or NULL if the buffer cannot
* be created. The BUFFER is not put in the
* list of all buffers; this is called by
* "edinit" to create the buffer list
* buffer.
*/
BUFFER *
bcreate(bname)
register char *bname;
{
register BUFFER *bp;
register LINE *lp;
if ((bp=(BUFFER *)malloc(sizeof(BUFFER))) == NULL)
return (NULL);
if ((lp=lalloc(0)) == NULL) {
free((char *) bp);
return (NULL);
}
bp->b_bufp = NULL;
bp->b_dotp = lp;
bp->b_doto = 0;
bp->b_markp = NULL;
bp->b_marko = 0;
bp->b_flag = 0;
bp->b_nwnd = 0;
bp->b_linep = lp;
strcpy(bp->b_fname, "");
strcpy(bp->b_bname, bname);
lp->l_fp = lp;
lp->l_bp = lp;
return (bp);
}
/*
* This routine blows away all of the text
* in a buffer. If the buffer is marked as changed
* then we ask if it is ok to blow it away; this is
* to save the user the grief of losing text. The
* window chain is nearly always wrong if this gets
* called; the caller must arrange for the updates
* that are required. Return TRUE if everything
* looks good.
*/
bclear(bp)
register BUFFER *bp;
{
register LINE *lp;
register int s;
if ((bp->b_flag&BFCHG) != 0 /* Changed. */
&& (s=eyesno("Discard changes")) != TRUE)
return (s);
bp->b_flag &= ~BFCHG; /* Not changed */
while ((lp=lforw(bp->b_linep)) != bp->b_linep)
lfree(lp);
bp->b_dotp = bp->b_linep; /* Fix "." */
bp->b_doto = 0;
bp->b_markp = NULL; /* Invalidate "mark" */
bp->b_marko = 0;
return (TRUE);
}
|
C
|
#include "../../inc/ush.h"
static int check_name_alias(t_alias *als, char *name, char *value) {
t_alias *tmp = als;
while (tmp && name && value) {
if (mx_strcmp(tmp->name, name) == 0){
mx_strdel(&(tmp->value));
tmp->value = mx_strdup(value);
return 1;
}
tmp = tmp->next;
}
return 0;
}
t_alias *mx_create_als(t_alias **als, char *alias, t_info *i) {
char *name = mx_get_name_als(&alias, i, 0);
char *value = NULL;
t_alias *start = NULL;
mx_get_value_als(*als, &alias, 0);
alias ? value = mx_strdup(alias) : 0;
if (value && name && mx_strcmp(value, " ") != 0
&& check_name_alias(i->alias, name, value) == 0) {
start = (t_alias *)malloc(sizeof(t_alias));
start->name = mx_strdup(name);
start->value = mx_strdup(value);
start->next = NULL;
}
mx_strdel(&name);
mx_strdel(&value);
return start;
}
void mx_add_newnode_als(t_alias **als, char *alias, t_info *i) {
t_alias *new = mx_create_als(als, alias, i);
if (*als) {
t_alias *tmp = *als;
while (tmp->next)
tmp = tmp->next;
tmp->next = new;
}
else
*als = new;
}
int mx_replace_als_to_cmd(t_alias *als, char **line, int i) {
t_alias *tmp = NULL;
char **arr_line = NULL;
int count = 0;
if (*line && (arr_line = mx_strsplit(*line, ' ')) != NULL)
for (i = 0; arr_line[i]; i++) {
tmp = als;
for (; tmp; tmp = tmp->next){
if (mx_strcmp(arr_line[i], tmp->name) == 0) {
mx_strdel(&(arr_line[i]));
arr_line[i] = mx_strdup(tmp->value);
count++;
}
}
}
*line = mx_strarr_to_str(arr_line, 0);
mx_del_strarr(&arr_line);
if (count == 0)
return 0;
return 1;
}
|
C
|
#include<stdio.h>
#include<stdlib.h>
#include<stdbool.h>
#include<math.h>
void check(int b,const char* msg)
{
if(!b)
{
fprintf(stderr,"error: %s\n\n",msg);
exit(-1);
}
}
void* long_new_array(const size_t N,const char* error_msg)
{
void* ptr;
int err;
/*if (_deviceType == 3){
err = posix_memalign(&ptr,ACL_ALIGNMENT,N * sizeof(int));
check(err == 0,error_msg);
}
else{
ptr = malloc(N * sizeof(int));
check(ptr != NULL,error_msg);
}*/
ptr = malloc(N * sizeof(long));
check(ptr != NULL,error_msg);
return ptr;
}
void* float_new_array(const size_t N,const char* error_msg)
{
void* ptr;
int err;
/*if (_deviceType == 3){
err = posix_memalign(&ptr,ACL_ALIGNMENT,N * sizeof(float));
check(!err,error_msg);
}
else{
ptr = malloc(N * sizeof(float));
check(ptr != NULL,error_msg);
}*/
ptr = malloc(N * sizeof(float));
check(ptr != NULL,error_msg);
return ptr;
}
int main(int argc, char *argv[])
{
int num_row=5000;
int num_len=5000;
long num_nonzero=125002;
unsigned long *row_ptr;
unsigned long *col_idx;
float *val;
//row_ptr=malloc((num_row+1) * sizeof(unsigned long));
row_ptr=long_new_array(num_row+1,"sparse_formats.read_csr() - Heap Overflow! Cannot allocate space for row_ptr");
printf("row_ptr alloced %d\n",num_row+1);
//col_idx=malloc(num_nonzero * sizeof(unsigned long));
col_idx=long_new_array(num_nonzero,"sparse_formats.read_csr() - Heap Overflow! Cannot allocate space for col_idx");
printf("col_idx alloced %ld\n",num_nonzero);
//val=malloc(num_nonzero * sizeof(float));
val=float_new_array(num_nonzero,"sparse_formats.read_csr() - Heap Overflow! Cannot allocate space for val");
printf("val alloced %ld\n",num_nonzero);
free(row_ptr);
free(col_idx);
free(val);
printf("freed\n");
return 0;
}
|
C
|
// Oisin Murphy - D00191700
#include <stdlib.h>
#include <stdio.h>
#include <stdint.h>
#include <string.h>
#include "./valhex.h"
void validate_hexcodes(int argc, char *filename[]) {
// if(argc <= 1) {
// printf("Invalid or insufficient number of arguments. Please try again.\n");
// exit(1);
// }
// get file with name given in args
// line by line, output
char hexcode[10];
while(fgets(hexcode, 10, stdin)) {
}
//printf("%s\n", filename[1]);
// // only get 6 & 8 bit hex
// uint8_t len = strlen(hexcode[1]);
// if(len == 7 || len == 9) {
// // print hex
// printf("%s\n", hexcode[1]);
// }
// exit(0);
}
int main(int argc, char *argv[]) {
validate_hexcodes(argc, argv);
return 0;
}
|
C
|
/* _getcwd.c
Author: BSS9395
Update: 2021-10-29T22:47:00+08@China-Guangdong-Shenzhen+08
Design: Windows C Library: _getcwd
*/
/* Windows API
#include <direct.h>
int _mkdir(const char *dirname);
int _rmdir(const char *dirname);
int _chdir(const char *dirname);
char *_getcwd(char *buffer, int maxlen);
*/
#define _CRT_SECURE_NO_WARNINGS
#include <direct.h> // Windows API
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char *argv[]) {
char dir[] = "E:/temp/test/";
if (_mkdir(dir) != 0) {
fprintf(stderr, "%s [%d] %s""\n", "_mkdir(dir) != 0", errno, strerror(errno));
if (_rmdir(dir) != 0) {
fprintf(stderr, "%s [%d] %s""\n", "_rmdir(dir) != 0", errno, strerror(errno));
}
}
else if (_chdir(dir) != 0) {
fprintf(stderr, "%s [%d] %s""\n", "_chdir(dir) != 0", errno, strerror(errno));
}
fprintf(stderr, "%s""\n", _getcwd(NULL, 0));
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "MiLibreria.h"
int main()
{
char seguir='s';
int opcion=0,indice,dni,validar;
EIndice aux;
EPersona lista[20];
inicializarLista(lista);
while(seguir=='s')
{
printf("Elija la opcion que desea: \n\n");
printf("1- Agregar persona\n");
printf("2- Borrar persona\n");
printf("3- Imprimir lista ordenada por nombre\n");
printf("4- Imprimir grafico de edades\n\n");
printf("5- Salir\n");
scanf("%d",&opcion);
validar=validarRango(opcion,1,5);
while(validar!=1)
{
printf("\nError, opcion no valida ");
printf("\nReingrese por favor(1-5): ");
scanf("%d",&opcion);
validar=validarRango(opcion,1,5);
}
switch(opcion)
{
case 1:
system("cls");
indice=obtenerEspacioLibre(lista);
if(indice==-1)
{
printf("\n No hay lugar \n");
system("pause");
}
else
{
printf("Ingrese dni: ");
scanf("%d",&dni);
validar=validarRango(dni,1000000,99999999);
while(validar!=1)
{
printf("\nError, el dni debe tener entre 7 y 8 digitos");
printf("\nReingrese por favor: ");
scanf("%d",&dni);
validar=validarRango(dni,1000000,99999999);
}
aux=buscarPorDni(lista,dni);
if(aux.flag==-1)
{
printf("Empleado ya ingresado\n");
}
else
{
lista[indice].dni=dni;
printf("Ingrese Nombre: ");
fflush(stdin);
gets(lista[indice].nombre);
printf("Ingrese edad: ");
scanf("%d", &lista[indice].edad);
validar=validarRango(lista[indice].edad,1,99);
while(validar!=1)
{
printf("\nError, la edad no es valida (1-99) ");
printf("\nReingrese por favor: ");
scanf("%d",&lista[indice].edad);
validar=validarRango(lista[indice].edad,1,99);
}
lista[indice].estado=1;
printf("Empleado ingresado correctamente\n");
}
}
system("pause");
break;
case 2:
system("cls");
printf("Ingrese dni: ");
scanf("%d",&dni);
validar=validarRango(dni,1000000,99999999);
while(validar!=1)
{
printf("\nError, el dni debe tener entre 7 y 8 digitos");
printf("\nReingrese por favor: ");
scanf("%d",&dni);
validar=validarRango(dni,1000000,99999999);
}
aux= buscarPorDni(lista,dni);
if(aux.flag==-1)
{
borrarEmpleado(lista,aux.indice);
printf("Empleado borrado\n");
}
else
{
printf("El empleado no se ha podido borrar debido a que no esta ingresado\n");
}
system("pause");
break;
case 3:
system("cls");
ordenarLista(lista);
mostrarLista(lista);
system("pause");
break;
case 4:
system("cls");
mostrarGrafico(lista);
system("pause");
break;
case 5:
seguir = 'n';
break;
}
system("cls");
}
return 0;
}
|
C
|
// Write a program to add first seven terms of the following series
// 1/1! + 2/2! + 3/3! .........
// using a for loop:
#include<stdio.h>
int main(){
int num=1,limit,i;
float sum=0,factorial;
printf("Enter the limit = ");
scanf("%d", &limit);
for(num=1;num<=limit;num++)
{
factorial= 1;
for(i=1; i<=num; i++)
{
factorial =factorial*i;
}
sum = sum + num/factorial;
}
printf("The value of the series is = %f", sum);
return 0;
}
|
C
|
#include <stdio.h>
void main(void)
{
int IdadeAnos, IdadeDias;
printf("\nDigite sua idade em anos: ");
scanf("%i", &IdadeAnos);
while (IdadeAnos > 0)
{
IdadeDias = IdadeAnos * 365;
printf("Sua idade em dias: %i", IdadeDias);
printf("\nDigite sua idade em anos: ");
scanf("%i", &IdadeAnos);
}
}
|
C
|
#include <stdio.h>
char *find_first_occurance(char *string, char character);
int main()
{
char *string = "abcdefghijklmnopq";
for (char character = 'a'; character <= 'z'; character++)
printf("%p\n", find_first_occurance(string, character));
return 0;
}
char *find_first_occurance(char *string, char character)
{
while (*string != '\0') {
if (*string == character) return string;
string++;
}
return NULL;
}
|
C
|
/*
** my_factorielle_rec.c for my_factorielle_rec in /home/ungaro_l/rendu/Piscine_C_J05
**
** Made by Luca Ungaro
** Login <[email protected]>
**
** Started on Fri Oct 2 09:24:26 2015 Luca Ungaro
** Last update Fri Oct 2 13:28:41 2015 Luca Ungaro
*/
int my_factorielle_rec(int nb)
{
if (nb < 0 || nb > 2147483647)
return (0);
if (nb == 0)
return (1);
return (nb * my_factorielle_rec(nb - 1));
}
|
C
|
#ifndef LAB3_DYNAMIC_PROGRAMMING_PART1_UTILS_H
#define LAB3_DYNAMIC_PROGRAMMING_PART1_UTILS_H
#include <stdlib.h>
int max_of_two(int a, int b) {
return a > b ? a : b;
}
int max_of_three(int a, int b, int c) {
if (a > b) {
if (a > c) {
return a;
} else {
return c;
}
} else if (b > c) {
return b;
} else {
return c;
}
}
void zero_array(int len, int* v) {
for (int i = 0; i < len; i++) {
v[i] = 0;
}
}
void free_matrix(int rows, int** matrix) {
for (int i = 0; i < rows; i++) {
free(matrix[i]);
}
free(matrix);
}
void print_matrix(int rows, int cols, int** matrix) {
for (int i = 0; i < rows; i++) {
printf("[");
for (int j = 0; j < cols; j++) {
printf("%d ", matrix[i][j]);
}
printf("]\n");
}
}
void print_array(int len, int* v) {
for (int i = 0; i < len; i++) {
printf("%d ", v[i]);
}
printf("\n");
}
int** matrix_alloc(int rows, int cols) {
int** dp = (int **) calloc(rows, sizeof(int *));
for (int i = 0; i < rows; i++) {
dp[i] = (int *) calloc(cols, sizeof(int));
}
return dp;
}
#endif //LAB3_DYNAMIC_PROGRAMMING_PART1_UTILS_H
|
C
|
#define NULL ((void*)0)
typedef unsigned long size_t; // Customize by platform.
typedef long intptr_t; typedef unsigned long uintptr_t;
typedef long scalar_t__; // Either arithmetic or pointer type.
/* By default, we understand bool (as a convenience). */
typedef int bool;
#define false 0
#define true 1
/* Forward declarations */
/* Type definitions */
typedef int /*<<< orphan*/ output ;
typedef int /*<<< orphan*/ input ;
typedef int /*<<< orphan*/ FILE ;
/* Variables and functions */
int EPERM ;
int /*<<< orphan*/ TEST_ASSERT_EQUAL (int,int) ;
int /*<<< orphan*/ TEST_ASSERT_EQUAL_STRING_LEN (char const*,char*,int) ;
int /*<<< orphan*/ TEST_ASSERT_NOT_NULL (int /*<<< orphan*/ *) ;
int errno ;
int fclose (int /*<<< orphan*/ *) ;
int /*<<< orphan*/ * fopen (char const*,char*) ;
int fprintf (int /*<<< orphan*/ *,char const*) ;
int fread (char*,int,int,int /*<<< orphan*/ *) ;
int /*<<< orphan*/ memset (char*,int /*<<< orphan*/ ,int) ;
int strlen (char const*) ;
int truncate (char const*,int) ;
void test_fatfs_truncate_file(const char* filename)
{
int read = 0;
int truncated_len = 0;
const char input[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
char output[sizeof(input)];
FILE* f = fopen(filename, "wb");
TEST_ASSERT_NOT_NULL(f);
TEST_ASSERT_EQUAL(strlen(input), fprintf(f, input));
TEST_ASSERT_EQUAL(0, fclose(f));
// Extending file beyond size is not supported
TEST_ASSERT_EQUAL(-1, truncate(filename, strlen(input) + 1));
TEST_ASSERT_EQUAL(errno, EPERM);
TEST_ASSERT_EQUAL(-1, truncate(filename, -1));
TEST_ASSERT_EQUAL(errno, EPERM);
// Truncating should succeed
const char truncated_1[] = "ABCDEFGHIJ";
truncated_len = strlen(truncated_1);
TEST_ASSERT_EQUAL(0, truncate(filename, truncated_len));
f = fopen(filename, "rb");
TEST_ASSERT_NOT_NULL(f);
memset(output, 0, sizeof(output));
read = fread(output, 1, sizeof(output), f);
TEST_ASSERT_EQUAL(truncated_len, read);
TEST_ASSERT_EQUAL_STRING_LEN(truncated_1, output, truncated_len);
TEST_ASSERT_EQUAL(0, fclose(f));
// Once truncated, the new file size should be the basis
// whether truncation should succeed or not
TEST_ASSERT_EQUAL(-1, truncate(filename, truncated_len + 1));
TEST_ASSERT_EQUAL(EPERM, errno);
TEST_ASSERT_EQUAL(-1, truncate(filename, strlen(input)));
TEST_ASSERT_EQUAL(EPERM, errno);
TEST_ASSERT_EQUAL(-1, truncate(filename, strlen(input) + 1));
TEST_ASSERT_EQUAL(EPERM, errno);
TEST_ASSERT_EQUAL(-1, truncate(filename, -1));
TEST_ASSERT_EQUAL(EPERM, errno);
// Truncating a truncated file should succeed
const char truncated_2[] = "ABCDE";
truncated_len = strlen(truncated_2);
TEST_ASSERT_EQUAL(0, truncate(filename, truncated_len));
f = fopen(filename, "rb");
TEST_ASSERT_NOT_NULL(f);
memset(output, 0, sizeof(output));
read = fread(output, 1, sizeof(output), f);
TEST_ASSERT_EQUAL(truncated_len, read);
TEST_ASSERT_EQUAL_STRING_LEN(truncated_2, output, truncated_len);
TEST_ASSERT_EQUAL(0, fclose(f));
}
|
C
|
#include "circular_buf.h"
#include <assert.h> /* assert */
#include <stdlib.h> /* strtol */
#include <stdio.h> /* perror, printf */
void test_push(int capacity)
{
circular_buf *cbuf;
cbuf = new_circular_buf(capacity);
if (cbuf == NULL)
{
fprintf(stderr, "%s: Failed to allocate memory for buffer\n", __func__);
return;
}
int *nums = calloc(capacity, sizeof(int));
if (nums == NULL)
{
perror("calloc");
fprintf(stderr, "%s: Failed to allocate memory\n", __func__);
delete_circular_buf(cbuf);
return;
}
int a, b, *c;
for (int i = 0; i < capacity; i++)
{
nums[i] = i + 1;
a = cbuf->pos;
b = cbuf->size;
cbuf->push(cbuf, nums + i);
c = (int *)(cbuf->get(cbuf, i));
assert(cbuf->pos == a);
assert(cbuf->size == b + 1);
assert(*c == nums[i]);
}
assert(cbuf->size == capacity);
for (int i = 0; i < capacity; i++)
{
a = cbuf->pos;
nums[i] = nums[i] * 2;
cbuf->push(cbuf, nums + i);
c = (int *)(cbuf->get(cbuf, i));
assert(cbuf->size == capacity);
assert(cbuf->pos == ((a + 1) % capacity));
assert(*c == nums[i]);
}
}
void test_pop(int capacity)
{
circular_buf *cbuf;
cbuf = new_circular_buf(capacity);
if (cbuf == NULL)
{
fprintf(stderr, "%s: Failed to allocate memory for buffer\n", __func__);
return;
}
int *nums = calloc(capacity, sizeof(int));
if (nums == NULL)
{
perror("calloc");
fprintf(stderr, "%s: Failed to allocate memory\n", __func__);
delete_circular_buf(cbuf);
return;
}
int a, b, *c;
for (int i = 0; i < capacity; i++)
{
nums[i] = i + 1;
cbuf->push(cbuf, nums + i);
}
for (int i = 0; i < capacity; i++)
{
a = cbuf->pos;
b = cbuf->size;
c = (int *)(cbuf->pop(cbuf));
assert(cbuf->pos == (a + 1) % capacity);
assert(cbuf->size == b - 1);
assert(*c == nums[i]);
}
}
int main(int argc, char **argv)
{
int capacity;
if (argc < 2)
capacity = 100;
else
capacity = strtol(argv[1], NULL, 10);
test_push(capacity);
test_pop(capacity);
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "cJSON.h"
int MakeJsonNameAge(char *pszJsonContent, int iJsonLen);
int MakeJsonPersonInfo(char *pszJsonContent, int iJsonLen);
int MakeJsonTwoPersonInfo(char *pszJsonContent, int iJsonLen);
int MakeJsonIDPersonInfo(char *pszJsonContent, int iJsonLen);
int MakeJsonPersonNameInfo(char *pszJsonContent, int iJsonLen);
int MakeJsonIDPersonNameInfo(char *pszJsonContent, int iJsonLen);
int MakeJsonAgePersonNameInfo(char *pszJsonContent, int iJsonLen);
int MakeJsonPersonsInfo(char *pszJsonContent, int iJsonLen);
/****************************************************************
* :
* :
* :
* ֵ : 0-ִ
* ˵:
* 汾
*-------------------------------------------------------------
* 20170427 V1.0 Zhou Zhaoxiong
****************************************************************/
int main(void)
{
int iRetVal = 0;
char szJsonData[500] = {0};
iRetVal = MakeJsonNameAge(szJsonData, sizeof(szJsonData)-1);
if (iRetVal == 0)
{
printf("JsonData=%s\n", szJsonData);
}
else
{
printf("Exec MakeJsonNameAge failed!\n");
return -1;
}
// -----------
memset(szJsonData, 0x00, sizeof(szJsonData));
iRetVal = MakeJsonPersonInfo(szJsonData, sizeof(szJsonData)-1);
if (iRetVal == 0)
{
printf("JsonData=%s\n", szJsonData);
}
else
{
printf("Exec MakeJsonPersonInfo failed!\n");
return -1;
}
// -----------
memset(szJsonData, 0x00, sizeof(szJsonData));
iRetVal = MakeJsonTwoPersonInfo(szJsonData, sizeof(szJsonData)-1);
if (iRetVal == 0)
{
printf("JsonData=%s\n", szJsonData);
}
else
{
printf("Exec MakeJsonTwoPersonInfo failed!\n");
return -1;
}
// -----------
memset(szJsonData, 0x00, sizeof(szJsonData));
iRetVal = MakeJsonIDPersonInfo(szJsonData, sizeof(szJsonData)-1);
if (iRetVal == 0)
{
printf("JsonData=%s\n", szJsonData);
}
else
{
printf("Exec MakeJsonIDPersonInfo failed!\n");
return -1;
}
// -----------
memset(szJsonData, 0x00, sizeof(szJsonData));
iRetVal = MakeJsonPersonNameInfo(szJsonData, sizeof(szJsonData)-1);
if (iRetVal == 0)
{
printf("JsonData=%s\n", szJsonData);
}
else
{
printf("Exec MakeJsonPersonNameInfo failed!\n");
return -1;
}
// -----------
memset(szJsonData, 0x00, sizeof(szJsonData));
iRetVal = MakeJsonIDPersonNameInfo(szJsonData, sizeof(szJsonData)-1);
if (iRetVal == 0)
{
printf("JsonData=%s\n", szJsonData);
}
else
{
printf("Exec MakeJsonIDPersonNameInfo failed!\n");
return -1;
}
// -----------
memset(szJsonData, 0x00, sizeof(szJsonData));
iRetVal = MakeJsonAgePersonNameInfo(szJsonData, sizeof(szJsonData)-1);
if (iRetVal == 0)
{
printf("JsonData=%s\n", szJsonData);
}
else
{
printf("Exec MakeJsonAgePersonNameInfo failed!\n");
return -1;
}
// -----------
memset(szJsonData, 0x00, sizeof(szJsonData));
iRetVal = MakeJsonPersonsInfo(szJsonData, sizeof(szJsonData)-1);
if (iRetVal == 0)
{
printf("JsonData=%s\n", szJsonData);
}
else
{
printf("Exec MakeJsonPersonsInfo failed!\n");
return -1;
}
return 0;
}
/****************************************************************
* : ֻJSONϢ
* : iJsonLen-JSONϢ峤
* : pszJsonContent-JSONϢ
* ֵ : 0-ִгɹ -1-ִʧ
* ˵:
* 汾
*-------------------------------------------------------------
* 20170427 V1.0 Zhou Zhaoxiong
****************************************************************/
/*
{
name:"zhou",
age:30
}
*/
int MakeJsonNameAge(char *pszJsonContent, int iJsonLen)
{
cJSON *root = NULL;
char *out = NULL;
// жϺǷϷ
if (pszJsonContent == NULL)
{
printf("MakeJsonNameAge: pszJsonContent is NULL!");
return -1;
}
root = cJSON_CreateObject();
if(NULL == root)
{
printf("MakeJsonNameAge: exec cJSON_CreateObject to get root failed!");
return -1;
}
cJSON_AddStringToObject(root, "name", "zhou");
cJSON_AddNumberToObject(root, "age", 30);
out=cJSON_Print(root);
strncpy(pszJsonContent, out, iJsonLen - 1);
pszJsonContent[iJsonLen - 1] = '\0';
cJSON_Delete(root);
free(out);
return 0;
}
/****************************************************************
* : ֻ1ԱϢJSONϢ
* : iJsonLen-JSONϢ峤
* : pszJsonContent-JSONϢ
* ֵ : 0-ִгɹ -1-ִʧ
* ˵:
* 汾
*-------------------------------------------------------------
* 20170428 V1.0 Zhou Zhaoxiong
****************************************************************/
/*
{
personinfo:{
name:"zhou",
age:30
}
}
*/
int MakeJsonPersonInfo(char *pszJsonContent, int iJsonLen)
{
cJSON *root = NULL;
cJSON *JsonLevel1 = NULL;
char *out = NULL;
// жϺǷϷ
if (pszJsonContent == NULL)
{
printf("MakeJsonPersonInfo: pszJsonContent is NULL!");
return -1;
}
root = cJSON_CreateObject();
if(NULL == root)
{
printf("MakeJsonPersonInfo: exec cJSON_CreateObject to get root failed!");
return -1;
}
JsonLevel1 = cJSON_CreateObject();
if(NULL == JsonLevel1)
{
printf("MakeJsonPersonInfo: exec cJSON_CreateObject to get JsonLevel1 failed!");
cJSON_Delete(root);
return -1;
}
cJSON_AddStringToObject(JsonLevel1, "name", "zhou");
cJSON_AddNumberToObject(JsonLevel1, "age", 30);
cJSON_AddItemToObject(root, "personinfo", JsonLevel1);
out=cJSON_Print(root);
strncpy(pszJsonContent, out, iJsonLen - 1);
pszJsonContent[iJsonLen - 1] = '\0';
cJSON_Delete(root);
free(out);
return 0;
}
/****************************************************************
* : ֻ2ԱϢJSONϢ
* : iJsonLen-JSONϢ峤
* : pszJsonContent-JSONϢ
* ֵ : 0-ִгɹ -1-ִʧ
* ˵:
* 汾
*-------------------------------------------------------------
* 20170428 V1.0 Zhou Zhaoxiong
****************************************************************/
/*
{
personinfo1:{
name:"zhou",
age:30
},
personinfo2:{
name:"zhang",
age:41
}
}
*/
int MakeJsonTwoPersonInfo(char *pszJsonContent, int iJsonLen)
{
cJSON *root = NULL;
cJSON *JsonLevel1 = NULL;
char *out = NULL;
// жϺǷϷ
if (pszJsonContent == NULL)
{
printf("MakeJsonTwoPersonInfo: pszJsonContent is NULL!");
return -1;
}
root = cJSON_CreateObject();
if(NULL == root)
{
printf("MakeJsonTwoPersonInfo: exec cJSON_CreateObject to get root failed!");
return -1;
}
//---------------
JsonLevel1 = cJSON_CreateObject();
if(NULL == JsonLevel1)
{
printf("MakeJsonTwoPersonInfo: exec cJSON_CreateObject to get JsonLevel1 failed 1!");
cJSON_Delete(root);
return -1;
}
cJSON_AddStringToObject(JsonLevel1, "name", "zhou");
cJSON_AddNumberToObject(JsonLevel1, "age", 30);
cJSON_AddItemToObject(root, "personinfo1", JsonLevel1);
//---------------
JsonLevel1 = cJSON_CreateObject();
if(NULL == JsonLevel1)
{
printf("MakeJsonTwoPersonInfo: exec cJSON_CreateObject to get JsonLevel1 failed 2!");
cJSON_Delete(root);
return -1;
}
cJSON_AddStringToObject(JsonLevel1, "name", "zhang");
cJSON_AddNumberToObject(JsonLevel1, "age", 40);
cJSON_AddItemToObject(root, "personinfo2", JsonLevel1);
out=cJSON_Print(root);
strncpy(pszJsonContent, out, iJsonLen - 1);
pszJsonContent[iJsonLen - 1] = '\0';
cJSON_Delete(root);
free(out);
return 0;
}
/****************************************************************
* : idpersoninfoJSONϢ
* : iJsonLen-JSONϢ峤
* : pszJsonContent-JSONϢ
* ֵ : 0-ִгɹ -1-ִʧ
* ˵:
* 汾
*-------------------------------------------------------------
* 20170428 V1.0 Zhou Zhaoxiong
****************************************************************/
/*
{
id:"123456",
personinfo:{
name:"zhou",
age:30
}
}
*/
int MakeJsonIDPersonInfo(char *pszJsonContent, int iJsonLen)
{
cJSON *root = NULL;
cJSON *JsonLevel1 = NULL;
char *out = NULL;
// жϺǷϷ
if (pszJsonContent == NULL)
{
printf("MakeJsonIDPersonInfo: pszJsonContent is NULL!");
return -1;
}
root = cJSON_CreateObject();
if(NULL == root)
{
printf("MakeJsonIDPersonInfo: exec cJSON_CreateObject to get root failed!");
return -1;
}
cJSON_AddStringToObject(root, "id", "123456");
JsonLevel1 = cJSON_CreateObject();
if(NULL == JsonLevel1)
{
printf("MakeJsonIDPersonInfo: exec cJSON_CreateObject to get JsonLevel1 failed!");
cJSON_Delete(root);
return -1;
}
cJSON_AddStringToObject(JsonLevel1, "name", "zhou");
cJSON_AddNumberToObject(JsonLevel1, "age", 30);
cJSON_AddItemToObject(root, "personinfo", JsonLevel1);
out=cJSON_Print(root);
strncpy(pszJsonContent, out, iJsonLen - 1);
pszJsonContent[iJsonLen - 1] = '\0';
cJSON_Delete(root);
free(out);
return 0;
}
/****************************************************************
* : personnameJSONϢ
* : iJsonLen-JSONϢ峤
* : pszJsonContent-JSONϢ
* ֵ : 0-ִгɹ -1-ִʧ
* ˵:
* 汾
*-------------------------------------------------------------
* 20170428 V1.0 Zhou Zhaoxiong
****************************************************************/
/*
{
personname:[
"zhou",
"zhang"
]
}
*/
int MakeJsonPersonNameInfo(char *pszJsonContent, int iJsonLen)
{
cJSON *root = NULL;
cJSON *JsonLevel1 = NULL;
cJSON *JsonLevel2 = NULL;
char *out = NULL;
// жϺǷϷ
if (pszJsonContent == NULL)
{
printf("MakeJsonPersonNameInfo: pszJsonContent is NULL!");
return -1;
}
root = cJSON_CreateObject();
if (NULL == root)
{
printf("MakeJsonPersonNameInfo: exec cJSON_CreateObject to get root failed!");
return -1;
}
JsonLevel1 = cJSON_CreateArray();
if (NULL == JsonLevel1)
{
printf("MakeJsonPersonNameInfo: exec cJSON_CreateArray to get JsonLevel1 failed!");
cJSON_Delete(root);
return -1;
}
cJSON_AddItemToObject(root, "personname", JsonLevel1);
JsonLevel2 = cJSON_CreateString("zhou");
cJSON_AddItemToArray(JsonLevel1, JsonLevel2);
JsonLevel2 = cJSON_CreateString("zhang");
cJSON_AddItemToArray(JsonLevel1, JsonLevel2);
out=cJSON_Print(root);
strncpy(pszJsonContent, out, iJsonLen - 1);
pszJsonContent[iJsonLen - 1] = '\0';
cJSON_Delete(root);
free(out);
return 0;
}
/****************************************************************
* : id/personname/personinfoJSONϢ
* : iJsonLen-JSONϢ峤
* : pszJsonContent-JSONϢ
* ֵ : 0-ִгɹ -1-ִʧ
* ˵:
* 汾
*-------------------------------------------------------------
* 20170428 V1.0 Zhou Zhaoxiong
****************************************************************/
/*
{
id:"123456",
personname:[
"zhou",
"zhang"
],
personinfo:{
phonenumber:"15696192591",
age:30
}
}
*/
int MakeJsonIDPersonNameInfo(char *pszJsonContent, int iJsonLen)
{
cJSON *root = NULL;
cJSON *JsonLevel1 = NULL;
cJSON *JsonLevel2 = NULL;
char *out = NULL;
// жϺǷϷ
if (pszJsonContent == NULL)
{
printf("MakeJsonIDPersonNameInfo: pszJsonContent is NULL!");
return -1;
}
root = cJSON_CreateObject();
if (NULL == root)
{
printf("MakeJsonIDPersonNameInfo: exec cJSON_CreateObject to get root failed!");
return -1;
}
cJSON_AddStringToObject(root, "id", "123456");
JsonLevel1 = cJSON_CreateArray();
if (NULL == JsonLevel1)
{
printf("MakeJsonIDPersonNameInfo: exec cJSON_CreateArray to get JsonLevel1 failed 1!");
cJSON_Delete(root);
return -1;
}
cJSON_AddItemToObject(root, "personname", JsonLevel1);
JsonLevel2 = cJSON_CreateString("zhou");
cJSON_AddItemToArray(JsonLevel1, JsonLevel2);
JsonLevel2 = cJSON_CreateString("zhang");
cJSON_AddItemToArray(JsonLevel1, JsonLevel2);
//-----------------
JsonLevel1 = cJSON_CreateObject();
if(NULL == JsonLevel1)
{
printf("MakeJsonIDPersonNameInfo: exec cJSON_CreateObject to get JsonLevel1 failed 2!");
cJSON_Delete(root);
return -1;
}
cJSON_AddStringToObject(JsonLevel1, "name", "zhou");
cJSON_AddNumberToObject(JsonLevel1, "age", 30);
cJSON_AddItemToObject(root, "personinfo", JsonLevel1);
out=cJSON_Print(root);
strncpy(pszJsonContent, out, iJsonLen - 1);
pszJsonContent[iJsonLen - 1] = '\0';
cJSON_Delete(root);
free(out);
return 0;
}
/****************************************************************
* : age/personname/personinfoJSONϢ
* : iJsonLen-JSONϢ峤
* : pszJsonContent-JSONϢ
* ֵ : 0-ִгɹ -1-ִʧ
* ˵:
* 汾
*-------------------------------------------------------------
* 20170428 V1.0 Zhou Zhaoxiong
****************************************************************/
/*
{
personinfo:{
personname:[
"zhou",
"zhang"
],
age:30
}
}
*/
int MakeJsonAgePersonNameInfo(char *pszJsonContent, int iJsonLen)
{
cJSON *root = NULL;
cJSON *JsonLevel1 = NULL;
cJSON *JsonLevel2 = NULL;
cJSON *JsonLevel3 = NULL;
char *out = NULL;
// жϺǷϷ
if (pszJsonContent == NULL)
{
printf("MakeJsonAgePersonNameInfo: pszJsonContent is NULL!");
return -1;
}
root = cJSON_CreateObject();
if (NULL == root)
{
printf("MakeJsonAgePersonNameInfo: exec cJSON_CreateObject to get root failed!");
return -1;
}
JsonLevel1 = cJSON_CreateObject();
if(NULL == JsonLevel1)
{
printf("MakeJsonAgePersonNameInfo: exec cJSON_CreateObject to get JsonLevel1 failed!");
cJSON_Delete(root);
return -1;
}
cJSON_AddItemToObject(root, "personinfo", JsonLevel1);
//------------------
JsonLevel2 = cJSON_CreateArray();
if (NULL == JsonLevel2)
{
printf("MakeJsonAgePersonNameInfo: exec cJSON_CreateArray to get JsonLevel2 failed!");
cJSON_Delete(root);
return -1;
}
cJSON_AddItemToObject(JsonLevel1, "personname", JsonLevel2);
JsonLevel3 = cJSON_CreateString("zhou");
cJSON_AddItemToArray(JsonLevel2, JsonLevel3);
JsonLevel3 = cJSON_CreateString("zhang");
cJSON_AddItemToArray(JsonLevel2, JsonLevel3);
//------------------
cJSON_AddNumberToObject(JsonLevel1, "age", 30);
out=cJSON_Print(root);
strncpy(pszJsonContent, out, iJsonLen - 1);
pszJsonContent[iJsonLen - 1] = '\0';
cJSON_Delete(root);
free(out);
return 0;
}
/****************************************************************
* : personinfoJSONϢ
* : iJsonLen-JSONϢ峤
* : pszJsonContent-JSONϢ
* ֵ : 0-ִгɹ -1-ִʧ
* ˵:
* 汾
*-------------------------------------------------------------
* 20170503 V1.0 Zhou Zhaoxiong
****************************************************************/
/*
{
personinfo:[
{
name:"zhou",
age:30
},
{
name:"zhang",
age:41
}
]
}
*/
int MakeJsonPersonsInfo(char *pszJsonContent, int iJsonLen)
{
cJSON *root = NULL;
cJSON *JsonLevel1 = NULL;
cJSON *JsonLevel2 = NULL;
char *out = NULL;
// жϺǷϷ
if (pszJsonContent == NULL)
{
printf("MakeJsonPersonsInfo: pszJsonContent is NULL!");
return -1;
}
root = cJSON_CreateObject();
if (NULL == root)
{
printf("MakeJsonPersonsInfo: exec cJSON_CreateObject to get root failed!");
return -1;
}
JsonLevel1 = cJSON_CreateArray();
if (NULL == JsonLevel1)
{
printf("MakeJsonPersonsInfo: exec cJSON_CreateArray to get JsonLevel1 failed!");
cJSON_Delete(root);
return -1;
}
cJSON_AddItemToObject(root, "personinfo", JsonLevel1);
//---------------
JsonLevel2 = cJSON_CreateObject();
if(NULL == JsonLevel2)
{
printf("MakeJsonPersonsInfo: exec cJSON_CreateObject to get JsonLevel2 failed 1!");
cJSON_Delete(root);
return -1;
}
cJSON_AddItemToArray(JsonLevel1, JsonLevel2);
cJSON_AddStringToObject(JsonLevel2, "name", "zhou");
cJSON_AddNumberToObject(JsonLevel2, "age", 30);
//---------------
JsonLevel2 = cJSON_CreateObject();
if(NULL == JsonLevel2)
{
printf("MakeJsonPersonsInfo: exec cJSON_CreateObject to get JsonLevel2 failed 2!");
cJSON_Delete(root);
return -1;
}
cJSON_AddItemToArray(JsonLevel1, JsonLevel2);
cJSON_AddStringToObject(JsonLevel2, "name", "zhang");
cJSON_AddNumberToObject(JsonLevel2, "age", 41);
//---------------
out=cJSON_Print(root);
strncpy(pszJsonContent, out, iJsonLen - 1);
pszJsonContent[iJsonLen - 1] = '\0';
cJSON_Delete(root);
free(out);
return 0;
}
|
C
|
/*****************************************************************************
FileName: main.c
Processor: PIC24HJ128GP502
Compiler: XC16 ver 1.30
Created on: 14 listopada 2017, 09:37
Description: SPI MASTER
******************************************************************************/
#include "xc.h"
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h> /*dyrektywy uint8_t itp*/
#include <string.h>
#include "ustaw_zegar.h" /*tutaj m.in ustawione FCY*/
#include <libpic30.h> /*dostep do delay-i,musi byc po zaincludowaniu ustaw_zegar.h*/
#include "dogm204.h"
void spi_config_master(void);
uint8_t Transfer_SPI(uint8_t bajt);
volatile uint8_t SPI_receive_data ;
#define LED1_TOG PORTA ^= (1<<_PORTA_RA1_POSITION) /*zmienia stan bitu na przeciwny*/
int main(void) {
ustaw_zegar(); /*odpalamy zegar wewnetrzny na ok 40MHz*/
__delay_ms(50); /*stabilizacja napiec*/
/*
* wylaczamy ADC , wszystkie piny chcemy miec cyfrowe
* pojedynczo piny analogowe wylaczamy w rejestrze AD1PCFGL
* Po resecie procka piny oznaczone ANx sa w trybie analogowych wejsc.
*/
PMD1bits.AD1MD = 1; /*wylaczamy ADC*/
/*
* ustawiamy wszystkie piny analogowe (oznacznone ANx) jako cyfrowe
* do zmiany mamy piny AN0-AN5 i AN9-AN12 co daje hex na 16 bitach = 0x1E3F
*/
AD1PCFGL = 0x1E3F;
TRISAbits.TRISA1 = 0 ; // RA1 jako wyjscie tu mamy LED
/*remaping pinow na potrzeby SPI
SDO --> pin 11
SDI --> pin 14
SCK --> pin 15
*/
RPOR2bits.RP4R = 7; /*inaczej _RP4R = 7*/
RPINR20bits.SDI1R = 5; /*inaczej _SDI1R = 5*/
RPOR3bits.RP6R = 8; /*inaczej _RP6R = 8*/
WlaczLCD(); /*LCD Init*/
UstawKursorLCD(1,6);
WyswietlLCD("TEST SPI");
UstawKursorLCD(2,1);
WyswietlLCD("Send data :");
UstawKursorLCD(3,1);
WyswietlLCD("Receive data :");
spi_config_master();
SPI_receive_data = 0;
while (1) {
if(Transfer_SPI(49) == 50) LED1_TOG ; /*Send and Receive data to be transmitted*/
WyswietlLCD(" ");
if(SPI_receive_data){ /*jesli cos odebrane*/
UstawKursorLCD(3,16);
lcd_int(SPI_receive_data); /*daj na ekran odebrany bajt*/
SPI_receive_data = 0;
}
__delay_ms(1000) ; /*bee*/
}
}
/*konfiguracja SPI dla Mastera*/
void spi_config_master(void) {
IFS0bits.SPI1IF = 0; /*Clear the Interrupt Flag*/
IEC0bits.SPI1IE = 0; /*Disable the Interrupt*/
/*Set clock SPI on SCK, 40 MHz / (4*2) = 5 MHz*/
SPI1CON1bits.PPRE = 0b10; /*Set Primary Prescaler 1:4*/
SPI1CON1bits.SPRE = 0b110; /*Set Secondary Prescaler 2:1*/
SPI1CON1bits.MODE16 = 0; /*Communication is word-wide (8 bits)*/
SPI1CON1bits.MSTEN = 1; /*Master Mode Enabled*/
SPI1STATbits.SPIEN = 1; /*Enable SPI Module*/
SPI1BUF = 0x0000;
IFS0bits.SPI1IF = 0; /*Clear the Interrupt Flag*/
IEC0bits.SPI1IE = 1; /*Enable the Interrupt*/
}
uint8_t Transfer_SPI(uint8_t bajt){
SPI1BUF = bajt; /*wysylamy bajt*/
UstawKursorLCD(2,16);
lcd_int(bajt); /*daj na ekran wysylany bajt*/
while(SPI1STATbits.SPITBF); /*czekamy na zakonczenie transferu*/
return SPI1BUF ; /*odczytujemy dane*/
}
/*Obsluga wektora przerwania dla SPI1 , przerwanie zglaszane po zakonczeniu transferu*/
void __attribute__((interrupt, no_auto_psv))_SPI1Interrupt(void)
{
SPI_receive_data = SPI1BUF; /*pobieramy dane przychodzace*/
IFS0bits.SPI1IF = 0 ; /*Clear SPI1 Interrupt Flag*/
}
|
C
|
#include "posix_sem.h"
#include "misc.h"
#include <stdio.h>
#include <semaphore.h>
#include <errno.h>
/*
POSIX Semaphore related functions
*/
enum decision sandbox_check_sem_create(const char *name)
{
sem_t *existing_sem = sem_open(name, 0);
if (existing_sem != SEM_FAILED) {
// There already is such a semaphore, we cannot decide whether
// we are allowed to create a new one. We therefore
// attempt to unlink the existing one, so we can create a new
// one. If this fails, we return -1 to indicate we cannot
// decide what the sandbox'd do.
if (sem_unlink(name) != 0)
return DECISION_ERROR;
} else if (errno == EPERM) {
return DECISION_ERROR;
}
sem_t *semaphore = sem_open(name, O_CREAT, 0777, 1);
if (semaphore == SEM_FAILED) {
PRINT_ERROR("Cannot create semaphore");
if (errno == EPERM)
return DECISION_DENY;
else
return DECISION_ERROR;
}
sem_close(semaphore);
return 0;
}
/* STUB: TODO */
enum decision sandbox_check_sem_open(const char *name)
{
return DECISION_ERROR;
}
enum decision sandbox_check_sem_post(const char *name)
{
sem_t *semaphore = sem_open(name, 0);
if (semaphore == SEM_FAILED) {
PRINT_ERROR("Cannot open semaphore");
return DECISION_ERROR;
}
int success = sem_post(semaphore);
return (success != 0) ? DECISION_DENY : DECISION_ALLOW;
}
enum decision sandbox_check_sem_wait(const char *name)
{
sem_t *semaphore = sem_open(name, 0);
if (semaphore == SEM_FAILED) {
PRINT_ERROR("Cannot open semaphore");
return DECISION_ERROR;
}
int success = sem_trywait(semaphore);
return ((success != 0) && (errno != EAGAIN)) ? DECISION_DENY : DECISION_ALLOW;
}
enum decision sandbox_check_sem_unlink(const char *name)
{
/*
Note: this fails if the semaphore does not exist.
We cannot really work around this here, because
first opening to check whether the semaphore exists
triggers another sandbox operation that might be denied.
*/
int success = sem_unlink(name);
if (success == -1) {
if (errno == EPERM)
return DECISION_DENY;
}
return (success == 0) ? DECISION_ALLOW : DECISION_ERROR;
}
|
C
|
#include <msp430.h>
/**
* File: main.c
* Author: William Cronin
* Date Created: October 1st 2018
* Date of Last Revision: October 3rd 2018
*/
int timerdelay;
void main(void)
{
WDTCTL = WDTPW | WDTHOLD; // stop watchdog timer
P1SEL = 0; //Sets Pin 1 as a GPIO
P1DIR &= ~BIT3; //Sets P1.3 as an input
P1IN &= ~BIT3;
P1REN |= BIT3; //Sets a pull-up resistor on P1.3
P1DIR |= BIT0; //Sets P1.0 as an output
P1OUT &= ~BIT0; //Sets the LED on P1.0 to off
P1IE |= BIT3; //Enables Interrupt on P1.3
P1IES |= BIT3; //
P1IFG &= ~BIT3; //Reset flag
_BIS_SR(GIE); //Enable global interrupt
TA0CTL = TASSEL_1 + MC_0 + TAIE; //Sets Timer in AClock configured in stop mode with interrupt enabled
TA0CCR0 = 40000;
timerdelay = 1;
while(1)
{
}
}
#pragma vector=TIMER0_A1_VECTOR
__interrupt void Timer_A(void)
{
switch(TA0IV)
{
case 2:
break;
case 4:
break;
case 10:
timerdelay = 1;
TA0CTL = TACLR; //Clear timer
TA0CTL = TASSEL_1 + MC_0; //Sets Timer in AClock configured in stop mode with interrupt enabled
break;
}
}
#pragma vector=PORT1_VECTOR
__interrupt void Port1(void)
{
if(timerdelay)
{
P1OUT ^= BIT0; //Flip LED
TA0CTL = TACLR; //Clear timer
TA0CTL = TASSEL_1 + MC_1 + TAIE; //Sets Timer in AClock configured in up mode with interrupt enabled
timerdelay = 0;
}
P1IFG &= ~BIT3; //Clear interrupt flag on Pin 1.3
}
|
C
|
#ifndef __MAIN_LIST_H
#define __MAIN_LIST_H
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include "list.h"
void createList(struct list** l);
//List 생성
void dumpdataList(struct list* l);
//List 데이터 순서대로 모두 출력
bool list_less(const struct list_elem* a, const struct list_elem* b, void*aux);
//List 비교 함수 a data < b data -> true 아니면 false
void deleteList(struct list** l);
//List 데이터 모두 해제
void listSwap(struct list* l, int idx_a, int idx_b);
//swap btween index idx_a, idx_b each other
void listShuffle(struct list* l);
//List를 무작위로 섞는다.
void otherListFuncs(struct list **l, char str[]);
//dumpdata delete create 이외의 명령어에 대한 기능 수행
#endif
|
C
|
#include <stdio.h>
#include <stdlib.h>
int a[100],n,i,j,temp;
heapsort(int *a,int n)
{
int heapsize=n;
for(i=n/2;i>=1;i--)
{
maxheapify(a,i,n);
}
for(i=n;i>=2;i--)
{
temp=a[1];
a[1]=a[i];
a[i]=temp;
heapsize=heapsize-1;
maxheapify(a,1,heapsize);
}
}
maxheapify(int *a, int i,int n)
{
int l,r,largest;
l=2*i;
r=2*i+1;
if(l<=n&&a[l]>a[i])
largest=l;
else largest=i;
if(r<=n&&a[r]>a[largest])
largest=r;
if(largest!=i)
{
temp=a[i];
a[i]=a[largest];
a[largest]=temp;
maxheapify(a,largest,n);
}
}
int main() {
int t,k;
scanf("%d",&t);
for(j=1;j<=t;j++)
{
scanf("%d",&n);
for(i=1;i<=n;i++)
{
scanf("%d",&a[i]);
}
scanf("%d",&k);
heapsort(a,n);
printf("%d\n",a[k]);
}
return 0;
}
|
C
|
/*
Devolver o índice i de um dado vetor v com n inteiros tal que v[i]==k ou -1 caso tal
índice inexista. k é dado.
*/
#include <stdio.h>
#include <string.h>
//funçao abaixo nao copie acima
int retInd(int vet[], int tam, int i, int k)
{
if (i > tam - 1) return -1;
if (vet[i] == k) return i;
return retInd(vet, tam, i+1, k);
}
//funçao acima nao copie abaixo
int main(){ //casos testes
int na[10] = {1,2,3,4,5,6,7,8,9,10};
printf("%d\n", retInd(na, 10, 0, 5)); // passou
int ma[20] = {51,51,471,58892,8941,98,51,562,51,5812,51,581,581,51,581,3,5,7,58,56};
printf("%d\n", retInd(ma, 20, 0, 581)); // passou
}
|
C
|
#include <stdio.h>
#include <mm_malloc.h>
#include <stdlib.h>
#define MAX_SIZE 5
typedef struct queue
{
int value[MAX_SIZE];
int front;
int rear;
}QUEUE,* PQUEUE;
_Bool push(PQUEUE,int);
_Bool pop(PQUEUE );
_Bool is_empty(PQUEUE);
_Bool is_full(PQUEUE);
void initQueue(PQUEUE);
void show_queue(PQUEUE);
void initQueue(PQUEUE pQueue)
{
pQueue->front = 0;
pQueue->rear = 0;
}
_Bool is_empty(PQUEUE pQueue)
{
return pQueue->rear == pQueue->front;
}
_Bool is_full(PQUEUE pQueue)
{
return (pQueue->rear + 1) % MAX_SIZE == pQueue->front;
}
_Bool push(PQUEUE pQueue,int nums)
{
if (is_full(pQueue))
return 0;
pQueue->value[pQueue->rear] = nums;
pQueue->rear = (pQueue->rear + 1) % MAX_SIZE;
return 1;
}
_Bool pop(PQUEUE pQueue)
{
if (is_empty(pQueue))
return 0;
printf("弹出的值为%d\n",pQueue->value[pQueue->front]);
pQueue->front= (pQueue->front + 1) % MAX_SIZE;
return 1;
}
void show_queue(PQUEUE pQueue)
{
int pos = pQueue->front;
if(is_empty(pQueue))
printf("队列为空\n");
while (pos != pQueue->rear)
{
printf("%d ",pQueue->value[pos]);
pos = (pos + 1) % MAX_SIZE;
}
printf("\n");
}
int main(void)
{
PQUEUE pQueue = (PQUEUE)malloc(sizeof(QUEUE));
initQueue(pQueue);
push(pQueue,1);
push(pQueue,2);
push(pQueue,3);
push(pQueue,4);
push(pQueue,5);
pop(pQueue);
pop(pQueue);
show_queue(pQueue);
return 0;
}
|
C
|
#include <stdio.h>
#include <string.h>
int main(int argc, char *argv[])
{
int i = 0;
int count = 0;
char *b[256];
char a[] = "I like this game !";
char *p, *q;
char *s = NULL;
//if (argc < 1)
//{
//printf("please input a separator !\n");
//return 0;
//}
p = q = a;
while (1)
{
//s = strtok_r(p, argv[1], &q);
s = strtok_r(p, " ", &q);
if (s == NULL)
{
break;
}
b[count] = s;
count++;
//printf("s = %s\n",s);
//printf("q = %s\n\n",q);
p = q;
}
for (i = 0; i < count; i++)
{
printf("%s\n",*(b + i));
}
return 0;
}
|
C
|
#include<stdio.h>
void main(){
int a;
scanf("%d",&a);
if(a>=0&&a<=100){
printf("赤贫打工人");
}
else if(a>=101&&a<=1000){
printf("普通打工人");
}
else if(a>=1001&&a<20000){
printf("土豪打工人");
}
else{
printf("错了");
}
}
|
C
|
/**************************************************************************//**
* @file
* @brief GPIO Interrupt Example
* @author Energy Micro AS
* @version 1.0.0
******************************************************************************
* @section License
* <b>(C) Copyright 2014 Silicon Labs, http://www.silabs.com</b>
*******************************************************************************
*
* This file is licensed under the Silicon Labs Software License Agreement. See
* "http://developer.silabs.com/legal/version/v11/Silicon_Labs_Software_License_Agreement.txt"
* for details. Before using this software for any purpose, you must agree to the
* terms of that agreement.
*
******************************************************************************/
#include "efm32.h"
#include "em_chip.h"
#include "em_cmu.h"
#include "em_emu.h"
#include "em_gpio.h"
/* Since the code can be run on both Giant Gecko and Tiny Gecko we need the following
if statement since the pins for Push Button 0 and Push Button 1 are different for
the two chips */
#if defined(_EFM32_GIANT_FAMILY)
/* Defines for Push Button 0 */
#define PB0_PORT gpioPortB
#define PB0_PIN 9
/* Defines for the LED */
#define LED_PORT gpioPortE
#define LED_PIN 2
#else
/* Defines for Push Button 0 */
#define PB0_PORT gpioPortD
#define PB0_PIN 8
/* Defines for the LED */
#define LED_PORT gpioPortD
#define LED_PIN 7
#endif
bool enableLed = 0;
/**************************************************************************//**
* @brief GPIO Handler
* Interrupt Service Routine
*****************************************************************************/
void GPIO_IRQHandler(void)
{
/* Clear flag for Push Button 0 interrupt. The interrupt is called as
* long as the interrupt flag is not cleared, so failing to do so here would
* lock the program at the first interrupt.
*
* All the ports share a total of 16 interrupts - one per pin number - i.e.
* pin 9 of port A and D share one interrupt, so to clear interrupts produced by
* either one of them we have to clear bit 9 */
GPIO_IntClear(1 << PB0_PIN);
/* Toggle value */
enableLed = !enableLed;
if (enableLed)
{
/* Turn off LED */
GPIO_PinOutSet(LED_PORT, LED_PIN);
}
else
{
/* Turn off LED )*/
GPIO_PinOutClear(LED_PORT, LED_PIN);
}
}
/**************************************************************************//**
* @brief GPIO_EVEN Handler
* Interrupt Service Routine for even GPIO pins
*****************************************************************************/
void GPIO_EVEN_IRQHandler(void)
{
GPIO_IRQHandler();
}
/**************************************************************************//**
* @brief GPIO_ODD Handler
* Interrupt Service Routine for odd GPIO pins
*****************************************************************************/
void GPIO_ODD_IRQHandler(void)
{
GPIO_IRQHandler();
}
/**************************************************************************//**
* @brief Main function
*****************************************************************************/
int main(void)
{
/* Initialize chip */
CHIP_Init();
/* Enable clock for GPIO module, we need this because
* the button and the LED are connected to GPIO pins. */
CMU_ClockEnable(cmuClock_GPIO, true);
/* Configure push button 1 as an input,
* so that we can read its value. */
GPIO_PinModeSet(PB0_PORT, PB0_PIN, gpioModeInput, 1);
/* Configure LED as a push pull, so that we can
* set its value - 1 to turn on, 0 to turn off */
GPIO_PinModeSet(LED_PORT, LED_PIN, gpioModePushPull, 0);
/* Enable GPIO_ODD interrupt vector in NVIC. We want Push Button 1 to
* send an interrupt when pressed. GPIO interrupts are handled by either
* GPIO_ODD or GPIO_EVEN, depending on wheter the pin number is odd or even,
* PB1 is therefore handled by GPIO_EVEN for Tiny Gecko (D8) and by GPIO_ODD for
* Giant Gecko (B9). */
#if defined(_EFM32_GIANT_FAMILY)
NVIC_EnableIRQ(GPIO_ODD_IRQn);
#else
NVIC_EnableIRQ(GPIO_EVEN_IRQn);
#endif
/* Configure PD8 (Push Button 1) interrupt on falling edge, i.e. when it is
* pressed, and rising edge, i.e. when it is released. */
GPIO_IntConfig(PB0_PORT, PB0_PIN, true, true, true);
while (1)
{
/* Go to EM3 */
EMU_EnterEM3(true);
}
}
|
C
|
#include <stdio.h>
int main(int argc, char const *argv[])
{
int a[10] = {3,2,3,4,5,6,7,8,9,10};
int *p1 = a;
int *p2 = &a[5];
printf("p1 apunta a %d\n", *p1);
printf("p2 apunta a %d\n", *p2);
p1 = p1 + 9;
printf("p1 ahora apunta a %d\n", *p1);
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "../jsmn.h"
/*
* A small example of jsmn parsing when JSON structure is known and number of
* tokens is predictable.
*/
static const char *JSON_STRING =
"{\"user\": \"johndoe\", \"admin\": false, \"uid\": 1000,\n "
"\"groups\": [\"users\", \"wheel\", \"audio\", \"video\"]}";
static int jsoneq(const char *json, jsmntok_t *tok, const char *s) {
if (tok->type == JSMN_STRING && (int) strlen(s) == tok->end - tok->start &&
strncmp(json + tok->start, s, tok->end - tok->start) == 0) {
return 0;
}
return -1;
}
// read txt file(json file)
// edit here to change reading data.json file
//
// char* readJSONFile(){
// char* JSON_STRING;
// char oneline[255];
// int count = 0;
//
// FILE *fp;
// fp = fopen("data3.json", "r");
//
// while(1){
// fgets(oneline, 255, fp);
// if(feof(fp)) break;
// count = count + strlen(oneline) + 1;
// JSON_STRING = (char*)realloc(JSON_STRING, count*sizeof(char));
// strcat(JSON_STRING, oneline);
// }
// return JSON_STRING;
// }
// read txt file upgrade (Example 12 ~ )
char *readJSONFile(){
int count = 0;
char oneline[255];
char fileName[200];
char *JSON_STRING = (char*)malloc(sizeof(char));
printf("파일명 입력 (확장자명 제외) : ");
scanf("%s", fileName); //
strcat(fileName, ".json");
FILE *fp = fopen(fileName, "r");
if(fp == NULL){
printf("%s 파일이 존재하지 않습니다.\n", fileName);
return NULL;
}
while(1){
fgets(oneline, 255, fp);
if(feof(fp)) break;
count = count + strlen(oneline) + 1;
JSON_STRING = (char*)realloc(JSON_STRING, count*sizeof(char));
strcat(JSON_STRING, oneline);
}
return JSON_STRING;
}
// Example 4
// void jsonNameList(char *jsonstr, jsmntok_t *t, int tokcount){
// int num = 1;
// int i = 0;
//
// printf("-----Name List-----\n");
//
// while(i < tokcount){
// if(t[i].type == JSMN_STRING && t[i].size >= 1){
// printf("[NAME%2d] %.*s\n", num, t[i].end - t[i].start, jsonstr + t[i].start);
// num++;
// }
// i++;
// }
// }
// Example 5
// void jsonNameList(char *jsonstr, jsmntok_t *t, int tokcount, int *nameTokIndex){
// int num = 1;
// int i = 0;
// while(i < tokcount){
// if(t[i].type == JSMN_STRING && t[i].size >= 1){
// nameTokIndex[num] = i;
// num++;
// }
// i++;
// }
// nameTokIndex[0]= num-1;
// }
// void printNameList(char *jsonstr, jsmntok_t *t, int *nameTokIndex){
// int i = 1;
// printf("-----Name List-----\n");
// while(i <= nameTokIndex[0]){
// printf("[NAME%2d] %.*s\n", i, t[nameTokIndex[i]].end - t[nameTokIndex[i]].start, jsonstr + t[nameTokIndex[i]].start);
// i++;
// }
// }
// Example 6
// void jsonNameList(char *jsonstr, jsmntok_t *t, int tokcount, int *nameTokIndex){
// int num = 1;
// int i = 0;
// while(i < tokcount){
// if(t[i].type == JSMN_STRING && t[i].size >= 1){
// nameTokIndex[num] = i;
// num++;
// }
// i++;
// }
// nameTokIndex[0] = num - 1;
// }
// void selectNameList(char *jsonstr, jsmntok_t *t, int *nameTokIndex){
// while(1){
// int number;
// int valueTok;
//
// printf("Select Name's no (exit : 0) >> ");
// scanf("%d", &number);
// if(number == 0)
// break; //exit
// if(number <= nameTokIndex[0] - 1){
// int index = number + 1;
// printf("[NAME%2d] %.*s\n", number , t[nameTokIndex[index]].end - t[nameTokIndex[index]].start, jsonstr + t[nameTokIndex[index]].start);
//
//
// valueTok = nameTokIndex[index] + 1;
// printf("%.*s\n", t[valueTok].end - t[valueTok].start, jsonstr + t[valueTok].start);
// }
// else
// printf("No contents, Max indext is %d\n",nameTokIndex[0] - 1);
//
// }
// }
// Example 7
// void jsonNameList(char *jsonstr, jsmntok_t *t, int tokcount, int *nameTokIndex){
// int num = 1;
// int i = 0;
// while(i < tokcount){
// if(t[i].type == JSMN_STRING && t[i].size >= 1){
// nameTokIndex[num] = i;
// num++;
// }
// i++;
// }
// nameTokIndex[0]= num-1;
// }
// void printNameList(char *jsonstr, jsmntok_t *t, int *nameTokIndex){
// int i = 1;
// printf("-----Name List-----\n");
// while(i <= nameTokIndex[0] - 1){
// printf("[NAME%2d] %.*s\n", i, t[nameTokIndex[i+1]].end - t[nameTokIndex[i+1]].start, jsonstr + t[nameTokIndex[i+1]].start);
// i++;
//
// }
// }
//
// void selectNameList(char *jsonstr, jsmntok_t *t, int *nameTokIndex){
// while(1){
// int number;
// int valueTok;
//
// printf("\nSelect Name's no (exit : 0) >> ");
// scanf("%d", &number);
// if(number == 0)
// break; //exit
// if(number <= nameTokIndex[0] - 1){
// int index = number + 1;
// printf("[NAME%2d] %.*s\n", number , t[nameTokIndex[index]].end - t[nameTokIndex[index]].start, jsonstr + t[nameTokIndex[index]].start);
//
//
// valueTok = nameTokIndex[index] + 1;
// printf("%.*s\n", t[valueTok].end - t[valueTok].start, jsonstr + t[valueTok].start);
// }
// else
// printf("No contents, Max indext is %d\n",nameTokIndex[0] - 1);
//
// }
// }
#define JSMN_PARENT_LINKS
// Example 8
// void jsonObjectList(char *jsonstr, jsmntok_t *t, int tokcount, int *objectTokIndex){
// int i = 1;
// int j = 1;
// printf("****** Object List ******\n");
// while(i < tokcount){
// if(t[i].size >= 1 && t[i].type == JSMN_OBJECT){ //객체의 첫번째 데이터 value
// if(t[i].parent == 2){ // object 안의 또 다른 object를 거르기 위한 조건
// objectTokIndex[j] = i + 2;
// printf("[NAME%2d] %.*s\n", j, t[objectTokIndex[j]].end - t[objectTokIndex[j]].start, jsonstr + t[objectTokIndex[j]].start);
// j++;
// }
// }
// i++;
// }
// objectTokIndex[0] = j - 1; //각 객체의 첫 번째 데이터의 개수
// }
// Example 9
// void jsonObjectList(char *jsonstr, jsmntok_t *t, int tokcount, int *objectTokIndex, int *valueTokIndex){
// int i = 1;
// int j = 1; // object tok 저장변수
// int k = 1; // value tok 저장변수
// printf("****** Object List ******\n");
// while(i < tokcount){
// if(t[i].size >= 1 && t[i].type == JSMN_OBJECT){ //객체의 첫번째 데이터 value
// if(t[i].parent == 2){ // object 안의 또 다른 object를 거르기 위한 조건
// objectTokIndex[j] = i;
// // 저장된 수에 +2 를 해주어야 첫 오브젝트의 value값이 나오게 된다.
// printf("[NAME%2d] %.*s\n", j, t[objectTokIndex[j]+2].end - t[objectTokIndex[j]+2].start, jsonstr + t[objectTokIndex[j]+2].start);
// j++;
// }
// }
// if(t[i].size >= 1 && t[i].type == JSMN_STRING){ //child를 가진 string 저장하기위한 조건
// valueTokIndex[k] = i;
// // 저장된 수에 +2 를 해주어야 첫 오브젝트의 value값이 나오게 된다.
// // printf("[Value%2d] %.*s\n", k, t[valueTokIndex[k]].end - t[valueTokIndex[k]].start, jsonstr + t[valueTokIndex[k]].start);
// k++;
// }
// i++;
// }
// objectTokIndex[0] = j - 1; //각 객체의 첫 번째 데이터의 개수
// valueTokIndex[0] = k - 1;
// }
// void selectObject(char *jsonstr, jsmntok_t *t, int tokcount,int *objectTokIndex, int *valueTokIndex){
// int num = 0;
// int valueCount = 0;
//
// printf("---------------------------------\n");
//
// while(1){
// int i = 2;
// printf("원하는 번호 입력 (exit : 0) ");
// scanf("%d", &num);
// if(num == 0) break;
//
// else if(num > objectTokIndex[0]){
// printf("Too big\n");
// }
// else if(num > 0){
// while(t[valueTokIndex[num+i]].end <= t[objectTokIndex[num]].end){
// printf("[%.*s]", t[valueTokIndex[i]].end - t[valueTokIndex[i]].start, jsonstr + t[valueTokIndex[i]].start);
// printf("%.*s\n", t[valueTokIndex[i]+1].end - t[valueTokIndex[i]+1].start, jsonstr + t[valueTokIndex[i]+1].start);
//
// i++;
// //
// // if(t[objectTokIndex[num]].type == JSMN_OBJECT && t[objectTokIndex[num]].size > 0){
// // printf("%d", (t[objectTokIndex[num]+i].start - t[objectTokIndex[num]+(i-1)].start) - 1);
// // printf("[%.*s]", (t[objectTokIndex[num]+i].start - t[objectTokIndex[num]+(i-1)].start) - 1, jsonstr + t[objectTokIndex[num]+(i-1)].start + 5);
// // }
// // // printf("%.*s\n", t[objectTokIndex[num+1]].end - t[objectTokIndex[num]].start, jsonstr + t[objectTokIndex[num]-1].start);
// // i++;
// // printf("\n");
// }
// }
// }
// }
// Example 10
// void jsonList(char *jsonstr, jsmntok_t *t, int tokcount, int *objectTokIndex){
// int i = 1;
// int j = 1;
// int k = 1;
// while(i < tokcount){
// if(t[i].size >= 1 && t[i].type == JSMN_STRING){ //객체의 첫번째 데이터 value
// if(t[i].parent < 1){ // object 안의 또 다른 object를 거르기 위한 조건
// objectTokIndex[j] = i;
// // 저장된 수에 +2 를 해주어야 첫 오브젝트의 value값이 나오게 된다.
// j++;
// }
// }
// if(t[i].size >= 1 && t[i].type == JSMN_STRING){ //child를 가진 string 저장하기위한 조건
// valueTokIndex[k] = i;
// // 저장된 수에 +2 를 해주어야 첫 오브젝트의 value값이 나오게 된다.
// k++;
// }
// i++;
// }
// objectTokIndex[0] = j - 1; //각 객체의 첫 번째 데이터의 개수
// valueTokIndex[0] = k - 1;
// }
// void printList(char *jsonstr, jsmntok_t *t, int tokcount, int *objectTokIndex){
// int i = 1;
//
// printf("****** Name List ******\n");
//
// while(i <= objectTokIndex[0]){
// printf("[NAME %2d] %.*s\n", i, t[objectTokIndex[i]].end - t[objectTokIndex[i]].start, jsonstr + t[objectTokIndex[i]].start);
// i++;
// }
// printf("\n\n****** Object List ******\n");
// i = 1;
// printf("[NAME %d] %.*s\n", i, t[objectTokIndex[i]+1].end - t[objectTokIndex[i]+1].start, jsonstr + t[objectTokIndex[i]+1].start);
// }
// void printselectList(char *jsonstr, jsmntok_t *t, int tokcount, int *objectTokIndex){
// int num;
// printf("\n원하는 번호를 입력 (Exit : 0)");
// scanf("%d", &num);
//
// printf("%.*s : %.*s\n", t[objectTokIndex[num]].end - t[objectTokIndex[num]].start, jsonstr + t[objectTokIndex[num]].start,
// t[objectTokIndex[num]+1].end - t[objectTokIndex[num]+1].start, jsonstr + t[objectTokIndex[num]+1].start);
//
// if(num <= objectTokIndex[0] && num > 0){
// int i = num + 1;
// while(i < objectTokIndex[0]){
// printf("\t[%.*s]%.*s\n", t[objectTokIndex[i]].end - t[objectTokIndex[i]].start, jsonstr + t[objectTokIndex[i]].start,
// t[objectTokIndex[i]+1].end - t[objectTokIndex[i]+1].start, jsonstr + t[objectTokIndex[i]+1].start);
//
// i++;
// }
// }
// }
// Example 11
// void jsonList(char *jsonstr, jsmntok_t *t, int tokcount, int *nameTokIndex,
// int *objectTokIndex){
//
// int i = 1, nameCount = 1;
//
// for(i = 1; i < tokcount; i++){
// if(t[i].type == JSMN_STRING && t[i].size > 0){
// nameTokIndex[nameCount] = i;
// nameCount++;
// }
// }
// nameTokIndex[0] = nameCount - 1;
//
// int objectCount = 1;
// int object;
//
// for(i = 1; i < tokcount; i++){
// if(t[i].type == JSMN_OBJECT){
// objectTokIndex[objectCount] = i;
// objectCount++;
// }
// }
// objectTokIndex[0] = objectCount - 1;
// }
//
// void printList(char *jsonstr, jsmntok_t *t, int tokcount, int *nameTokIndex,
// int *objectTokIndex){
//
// int i = 1;
// int j = 1;
//
// printf("****** Name List ******\n");
//
// while(i <= nameTokIndex[0]){
// printf("[NAME%2d] %.*s\n", i, t[nameTokIndex[i]].end - t[nameTokIndex[i]].start,
// jsonstr + t[nameTokIndex[i]].start);
// i++;
// }
//
// printf("\n****** Object List ******\n");
// while(j <= objectTokIndex[0]){
// printf("[Object%2d] %.*s\n", j, t[objectTokIndex[j]+2].end - t[objectTokIndex[j]+2].start,
// jsonstr + t[objectTokIndex[j]+2].start);
// j++;
// }
// printf("\n");
// }
//
// void printselectList(char *jsonstr, jsmntok_t *t, int tokcount, int *nameTokIndex, int *objectTokIndex){
// int num;
//
// while(1){
// printf("원하는 번호 입력 (Exit:0) : ");
// scanf("%d", &num);
//
// if(num <= objectTokIndex[0] && num > 0){
// printf("%.*s : %.*s\n", t[objectTokIndex[num]+1].end - t[objectTokIndex[num]+1].start, jsonstr + t[objectTokIndex[num]+1].start,
// t[objectTokIndex[num]+2].end - t[objectTokIndex[num]+2].start, jsonstr + t[objectTokIndex[num]+2].start);
//
// int i = num;
// int j = 2;
// while(t[nameTokIndex[i]+j].start < t[objectTokIndex[i]].end){
// printf("\t[%.*s]%.*s\n", t[nameTokIndex[i]+j].end - t[nameTokIndex[i]+j].start, jsonstr + t[nameTokIndex[i]+j].start,
// t[nameTokIndex[i]+j+1].end - t[nameTokIndex[i]+j+1].start, jsonstr + t[nameTokIndex[i]+j+1].start);
// j = j + 2;
// }
// }
// else if(num == 0) break; // quit comdition
// else printf("No object\n"); // objectTokIndex의 범위를 넘어간 condition
//
// }
// }
// Example 12
// void jsonList(char *jsonstr, jsmntok_t *t, int tokcount, int *nameTokIndex,
// int *objectTokIndex){
//
// int i = 1, nameCount = 1;
// int initial;
//
// for(i = 1; t[i].type != JSMN_ARRAY; i++){
// initial = i + 1; // ARRAY 다음 토큰부터 저장하기 위한 변수
// }
// for(i = initial; i < tokcount; i++){
// if(t[i].type == JSMN_STRING && t[i].size > 0){
// nameTokIndex[nameCount] = i;
// nameCount++;
// }
// }
// nameTokIndex[0] = nameCount - 1;
//
// int objectCount = 1;
// int object;
//
// for(i = initial; i < tokcount; i++){
// if(t[i].type == JSMN_OBJECT){
// objectTokIndex[objectCount] = i;
// objectCount++;
// }
// }
// objectTokIndex[0] = objectCount - 1;
// }
//
// void printList(char *jsonstr, jsmntok_t *t, int tokcount, int *nameTokIndex, int *objectTokIndex){
// int i = 1;
// int j = 1;
//
// printf("****** Name List ******\n");
// while(i <= nameTokIndex[0]){
// printf("[NAME%2d] %.*s\n", i, t[nameTokIndex[i]].end - t[nameTokIndex[i]].start,
// jsonstr + t[nameTokIndex[i]].start);
// i++;
// }
//
// printf("\n****** Object List ******\n");
// while(j <= objectTokIndex[0]){
// printf("[Object%2d] %.*s\n", j, t[objectTokIndex[j]+2].end - t[objectTokIndex[j]+2].start,
// jsonstr + t[objectTokIndex[j]+2].start);
// j++;
// }
// printf("\n");
// }
//
// void printselectList(char *jsonstr, jsmntok_t *t, int tokcount, int *nameTokIndex, int *objectTokIndex){
// int num;
//
// while(1){
// printf("원하는 번호 입력 (Exit:0) : ");
// scanf("%d", &num);
//
// if(num <= objectTokIndex[0] && num > 0){
// printf("%.*s : %.*s\n", t[objectTokIndex[num]+1].end - t[objectTokIndex[num]+1].start, jsonstr + t[objectTokIndex[num]+1].start,
// t[objectTokIndex[num]+2].end - t[objectTokIndex[num]+2].start, jsonstr + t[objectTokIndex[num]+2].start);
//
// int i = num;
// int j = 2;
// while(t[nameTokIndex[i]+j].start < t[objectTokIndex[i]].end){
// printf("\t[%.*s]%.*s\n", t[nameTokIndex[i]+j].end - t[nameTokIndex[i]+j].start, jsonstr + t[nameTokIndex[i]+j].start,
// t[nameTokIndex[i]+j+1].end - t[nameTokIndex[i]+j+1].start, jsonstr + t[nameTokIndex[i]+j+1].start);
// j = j + 2;
// }
// }
// else if(num == 0) break; // quit comdition
// else printf("No object\n"); // objectTokIndex의 범위를 넘어간 condition
// }
// }
// Example 13
// Example 15
typedef enum{
NONGSHIM = 0,
PALDO = 1,
SAMYANG = 2,
OTTUGI = 3,
} company_t;
typedef struct{
company_t company; // 제조사
char name[20]; // 제품명
int price; // 가격
int like; // 찜하기
int evaluation; // 상품평가 수
} product_t;
// int makeProduct(const char *json, jsmntok_t *t, int tokcount, product_t *p[]){
//
// }
int main() {
char* string;
char* jsonstr;
string = (char*)malloc(sizeof(readJSONFile())+1);
string = readJSONFile();
if(string == NULL) return EXIT_SUCCESS;
//puts(string);
int i;
int r;
int array[100];
jsmn_parser p;
jsmntok_t t[128]; /* We expect no more than 128 tokens */
jsmn_init(&p);
r = jsmn_parse(&p, string, strlen(string), t, sizeof(t)/sizeof(t[0]));
if (r < 0) {
printf("Failed to parse JSON: %d\n", r);
return 1;
}
/* Assume the top-level element is an object */
if (r < 1 || t[0].type != JSMN_OBJECT) {
printf("Object expected\n");
}
// Example 3
//
// /* Loop over all keys of the root object */
// for (i = 1; i < r; i++) {
// if (jsoneq(string, &t[i], "name") == 0) {
// /* We may use strndup() to fetch string value */
// printf("- name: %.*s\n", t[i+1].end-t[i+1].start,
// string + t[i+1].start);
// i++;
// } else if (jsoneq(string, &t[i], "keywords") == 0) {
// /* We may additionally check if the value is either "true" or "false" */
// printf("- keywords: %.*s\n", t[i+1].end-t[i+1].start,
// string + t[i+1].start);
// i++;
// } else if (jsoneq(string, &t[i], "description") == 0) {
// /* We may want to do strtol() here to get numeric value */
// printf("- UID: %.*s\n", t[i+1].end-t[i+1].start,
// string + t[i+1].start);
// i++;
// } else if (jsoneq(string, &t[i], "examples") == 0) {
// int j;
// printf("- exsmples:\n");
// if (t[i+1].type != JSMN_ARRAY) {
// continue; /* We expect groups to be an array of strings */
// }
// for (j = 0; j < t[i+1].size; j++) {
// jsmntok_t *g = &t[i+j+2];
// printf(" * %.*s\n", g->end - g->start, string + g->start);
// }
// i += t[i+1].size + 1;
// }
// }
// Example 4
//jsonNameList(string, t, r);
//Example 5
// jsonNameList(string, t, r, array);
// printNameList(string, t, array);
//Example 6
// jsonNameList(string, t, r, array);
// selectNameList(string, t, array);
//Example 7
// jsonNameList(string, t, r, array);
// printNameList(string, t, array);
// selectNameList(string, t, array);
// Example 8
// jsonObjectList(string, t, r, array);
int name[50];
int object[50];
// Example 9
/*
1. malloc assert, realloc, free (t[i].size)
*/
// jsonObjectList(string, t, r, object, value);
// selectObject(string, t, r,object, value);
// Example 10
// jsonList(string, t, r, object);
// printList(string, t, r, object);
// printselectList(string, t, r, object);
// Example 11
// jsonList(string, t, r, name, object);
// printList(string, t, r, name, object);
// printselectList(string, t, r, name, object);
// Example 12
jsonList(string, t, r, name, object);
printList(string, t, r, name, object);
printselectList(string, t, r, name, object);
free(string);
return EXIT_SUCCESS;
}
|
C
|
#include "libft.h"
int ft_voidlen(unsigned int *src)
{
int i;
int counter;
counter = 0;
i = -1;
while (src[++i])
counter += nbr_bytes(src[i]);
return (counter);
}
|
C
|
#include <stdio.h>
#define SIZE 6
int A[SIZE] = {10, 9, 8, 7, 1, 5}; // = {6, 9, 4, 15, 5, 7};
void swap(int *a, int *b)
{
int temp = *a;
*a = *b;
*b = temp;
}
int
getPos(int a[], int low, int high)
{
int pivot = a[high];
int i = (low -1);
for (int p = low; p <= high - 1; p++)
{
if (a[p] <= pivot) {
i++;
swap(&a[i], &a[p]);
}
}
swap(&a[i + 1], &a[high]);
return i + 1;
}
void
QuickSort(int a[], int low, int high)
{
if (low < high)
{
int pi = getPos(a, low, high);
QuickSort(a, low, pi - 1);
QuickSort(a, pi + 1, high);
}
}
int
printArray (int a[], int n)
{
for (int i = 0; i < n; i++) {
printf("%d ", a[i]);
}
printf("\n");
}
int main(int argc, char const *argv[]) {
printArray(A, SIZE);
QuickSort(A, 0, SIZE-1);
printArray(A, SIZE);
return 0;
}
|
C
|
/**********************************************************************
wn_enter_vect(vect,len_i)
wn_enter_mat(mat,len_i,len_j)
wn_print_vect(vect,len_i)
wn_print_mat(mat,len_i,len_j)
**********************************************************************/
/****************************************************************************
COPYRIGHT NOTICE:
The source code in this directory is provided free of
charge to anyone who wants it. It is in the public domain
and therefore may be used by anybody for any purpose. It
is provided "AS IS" with no warranty of any kind
whatsoever. For further details see the README files in
the wnlib parent directory.
AUTHOR:
Will Naylor
****************************************************************************/
#include "wnlib.h"
#include "wnmat.h"
local void read_double(pd)
double *pd;
{
double f;
scanf("%lf",&f);
*pd = f;
}
void wn_enter_vect(vect,len_i)
double vect[];
int len_i;
{
int i;
for(i=0;i<len_i;i++)
{
printf("enter element[%d]: ",i);
read_double(&(vect[i]));
}
}
void wn_enter_mat(mat,len_i,len_j)
double **mat;
int len_i,len_j;
{
int i,j;
for(i=0;i<len_i;++i)
for(j=0;j<len_j;++j)
{
printf("enter element[%d][%d]: ",i,j);
read_double(&(mat[i][j]));
}
}
void wn_print_vect(vect,len_i)
double vect[];
int len_i;
{
int i;
printf("[ ");
for(i=0;i<len_i;i++)
{
printf("%f ",vect[i]);
}
printf("]\n");
}
void wn_print_mat(mat,len_i,len_j)
double **mat;
int len_i,len_j;
{
int i;
printf("-----------\n");
for(i=0;i<len_i;i++)
{
wn_print_vect(mat[i],len_j);
}
printf("-----------\n");
}
|
C
|
#include <stdio.h> // abrindo biblioteca
#include <stdlib.h>
#include <locale.h>
int main(void){
/*Programadores Lohan e Marcelo*/
setlocale(LC_ALL, "Portuguese");
float f, c, p, mm;
printf("programa de converso de Fahrenheit em Celsius \n");
printf("Digite o valor em Fahrenheit:");
scanf("%f", &f);
printf("Digite a quantidade de chuva em polegadas:");
scanf("%f", &p);
c=(5*f-160)/9;
mm=(p*25.4);
printf("A temperatura em fahrenheit : %.2f\n", c);
printf("A quantidade de chuvas em milimitros : %.2f\n", mm);
system("pause");
return 0;
}
|
C
|
/*
** tp3_firstimage.c for tp3_fisrtimage in /home/RODRIG_1/rendu/Minilibx-TP.3
**
** Made by rodriguez gwendoline
** Login <[email protected]>
**
** Started on Thu Nov 13 10:09:32 2014 rodriguez gwendoline
** Last update Mon Nov 13 16:05:47 2017 Gwendoline Rodriguez
*/
#include "header.h"
void mlx_pixel_put_to_image(t_ptr *lx, int x, int y, int color)
{
int i;
i = x * (lx->bpp / 8) + y * lx->sizeline;
lx->data[i] = (color & 0xFF);
lx->data[i + 1] = (color & 0xFF00) >> 8;
lx->data[i + 2] = (color & 0xFF0000) >> 16;
}
int my_gere_expose(t_ptr *lx)
{
mlx_put_image_to_window(lx->mlx_ptr, lx->win_ptr, lx->img, 0, 0);
return (0);
}
int gere_key(int keycode)
{
if (keycode == 65307)
exit(0);
printf("%d\n",keycode);
putchar('\n');
return (0);
}
int main()
{
t_ptr lx;
lx.mlx_ptr = mlx_init();
lx.win_ptr = mlx_new_window(lx.mlx_ptr, WIDTH, HEIGHT, "Raytracer");
lx.img = mlx_new_image(lx.mlx_ptr, WIDTH, HEIGHT);
lx.data = mlx_get_data_addr(lx.img, &lx.bpp, &lx.sizeline, &lx.endian);
mlx_expose_hook(lx.win_ptr, my_gere_expose, &lx);
my_env(&lx);
mlx_key_hook(lx.win_ptr, &gere_key, &lx);
mlx_put_image_to_window(lx.mlx_ptr, lx.win_ptr, lx.img, 0, 0);
mlx_loop(lx.mlx_ptr);
return (0);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include<math.h>
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
int main() {
int l=0,c=0;
scanf("%d",&l);
scanf("%d",&c);
l = l%2;
c = c%2;
int cor = (l==c) ? 1 : 0; //COR DA CASA DO XADREZ 1(BRANCO) 0(PRETO)
printf("%d\n",cor);
return 0;
}
|
C
|
#include <stdlib.h>
#include <unistd.h>
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <time.h>
#include <mpi.h>
#include <sys/time.h>
// Длина стержня
#define L 20
// Параметр теплопроводности
#define Lamb 0.5
// Временные узлы
#define TIME 10
// Шаг по времени
#define dT 1
int main(int argc, char **argv) {
int myrank, total;
// Используется только в root
double *T;
// Лента матрицы [mxn], вектор [n], рез-т [m]
double *t;
int i, j;
// Инициализация
MPI_Init(&argc, &argv);
MPI_Comm_size(MPI_COMM_WORLD, &total);
MPI_Comm_rank(MPI_COMM_WORLD, &myrank);
// Число шагов по времени
int n = TIME / dT + 1;
// Длины на процесс
int m = (L) / total;
// В нулевом процессе
if (!myrank) {
// Выделение памяти под весь результат
T = (double *) malloc(sizeof(double) * n * L);
// Граничные условие первого рода
T[0] = 20;
T[L - 1] = 50;
};
// Выделение памяти под полосу каждого процесса
t = malloc(n * m * sizeof(double));
struct timeval start, end;
MPI_Scatter((void *) T,
m,
MPI_DOUBLE,
(void *) t,
m,
MPI_DOUBLE,
0,
MPI_COMM_WORLD); // Разделение начальных условий по процессам
// gettimeofday(&start, 0);
// Расчет цикл по времени
for (i = 1; i < n; i++) {
double left, right;
MPI_Status s1, s2;
// Обмен данными с соседними полосами
if (myrank != 0) {
MPI_Sendrecv(&t[(i - 1) * m],
1,
MPI_DOUBLE,
myrank - 1,
0,
&left,
1,
MPI_DOUBLE,
myrank - 1,
MPI_ANY_TAG,
MPI_COMM_WORLD,
&s1);
}
if (myrank != total - 1) {
MPI_Sendrecv(&t[(i - 1) * m + (m - 1)],
1,
MPI_DOUBLE,
myrank + 1,
1,
&right,
1,
MPI_DOUBLE,
myrank + 1,
MPI_ANY_TAG,
MPI_COMM_WORLD,
&s2);
}
// Цикл по полосе
for (j = 0; j < m; j++) {
if (j == 0) {
// Левая граница
if (myrank == 0) {
t[i * m + j] = t[(i - 1) * m + j];
} else {
t[i * m + j] = Lamb * (t[(i - 1) * m + j + 1] - 2 * t[(i - 1) * m + j] + left) * dT + t[(i - 1) * m + j];
}
}
// Правая граница
else if (j == m - 1) {
if (myrank == total - 1) {
t[i * m + j] = t[(i - 1) * m + j];
} else {
t[i * m + j] = Lamb * (right - 2 * t[(i - 1) * m + j] + t[(i - 1) * m + j - 1]) * dT + t[(i - 1) * m + j];
}
} else //внутренние узлы
{
t[i * m + j] =
Lamb * (t[(i - 1) * m + j + 1] - 2 * t[(i - 1) * m + j] + t[(i - 1) * m + j - 1]) * dT + t[(i - 1) * m + j];
}
}
}
gettimeofday(&end, 0);
// if (!myrank)
// printf("%u.%u\n",
// (unsigned int) end.tv_sec - (unsigned int) start.tv_sec,
// (unsigned int) end.tv_usec - (unsigned int) start.tv_usec);
// Сбор всех результатов нулевой процесс
for (i = 1; i < n; i++) {
MPI_Gather((void *) (t + i * m), m, MPI_DOUBLE, (void *) (T + i * L), m, MPI_DOUBLE, 0, MPI_COMM_WORLD);
}
// Вывод в файл
if (!myrank) {
FILE *file;
file = fopen("lab6.dat", "a");
for (i = 0; i < n; i++) {
for (j = 0; j < L; j++) {
fprintf(file, "%d %f\n", j, T[i * L + j]);
printf("%.2f ", T[i * L + j]);
}
printf("\n");
fprintf(file, "\n\n");
}
fclose(file);
// Файл для gnuplot
file = fopen("grapth", "w");
fprintf(file, "set yrange [0:100]\n");
fprintf(file, "do for [i=0:%d]{\n", n - 1);
fprintf(file, "plot 'lab6.dat' index i using 1:2 with lines\n");
fprintf(file, "pause 0.5}\n pause -1");
}
// Завершение
MPI_Finalize();
exit(0);
}
|
C
|
#include <unistd.h>
#include <stdio.h>
#include <fcntl.h>
#include <linux/fb.h>
#include <sys/mman.h>
#include "framebuffer_info.h"
int getDisplayInfo() {
int fbfd = 0;
struct fb_var_screeninfo vinfo;
struct fb_fix_screeninfo finfo;
long int screensize = 0;
char *fbp = 0;
int x = 0, y = 0,i;
long int location = 0;
/* Open the file for reading and writing */
fbfd = open("/dev/fb0", O_RDWR);
if (fbfd < 0) {
printf("Error: cannot open framebuffer device.\n");
return -1;
}
printf("The framebuffer device was opened successfully.\n");
/* Get fixed screen information */
if (ioctl(fbfd, FBIOGET_FSCREENINFO, &finfo)) {
printf("Error reading fixed information.\n");
return -1;
}
/* Get variable screen information */
if (ioctl(fbfd, FBIOGET_VSCREENINFO, &vinfo)) {
printf("Error reading variable information.\n");
return -1;
}
printf ("The mem is %d\n", finfo.smem_len);
printf("The line_length is :%d\n",finfo.line_length);
printf("The xres is :%d\n",vinfo.xres);
printf("The yres is :%d\n",vinfo.yres);
printf("bits_per_pixel is :%d\n",vinfo.bits_per_pixel);
close(fbfd);
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_POLYS 100
#define BUFFER_LENGTH 100
struct term
{
int coef;
int expo;
struct term *next;
};
typedef struct term Term;
typedef struct polynomial
{
char name;
Term *first;
int size;
}
Polynomial;
Polynomial *polys[MAX_POLYS];
int n = 0;
int read_line(char buffer[], int bufferLen) {
int i = 0;
for (; i < bufferLen; i++) {
scanf_s("%c", &buffer[i]);
if (buffer[i] == '\n') {
buffer[i] = '\0';
break;
}
}
return i;
}
Term *create_term_instance() {
Term *t = (Term *)malloc(sizeof(Term));
t->coef = 0;
t->expo = 0;
t->next = NULL;
return t;
}
Polynomial *create_polynomial_instance(char name) {
Polynomial *ptr_poly = (Polynomial *)malloc(sizeof(Polynomial));
ptr_poly->name = name;
ptr_poly->size = 0;
ptr_poly->first = NULL;
return ptr_poly;
}
void add_term(int c, int e, Polynomial *poly) {
if (c == 0)return;
Term *p = poly->first, *q = NULL;
while (p != NULL && p->expo > e) {
q = p;
p = p->next;
}
if (p != NULL && p->expo == e) {
p->coef += c;
if (p->coef == 0) {
if (q == NULL)poly->first = p->next;
else q->next = p->next;
poly->size--;
free(p);
}
return;
}
Term *term = create_term_instance();
term->coef = c;
term->expo = e;
if (q == NULL) {
term->next = poly->first;
poly->first = term;
}
else
{
term->next = p;
q->next = term;
}
poly->size++;
}
int eval(Polynomial *poly, int x) {
int result = 0;
Term *t = poly->first;
while (t != NULL) {
result += eval_term(t, x);
t = t->next;
}
return result;
}
int eval_term(Term *term, int x) {
int result = term->coef;
for (int i = 0; i < term->expo; i++) {
result *= x;
}
return result;
}
void print_term(Term *pTerm) {//TODO printing term
if (pTerm->coef == 0 && pTerm->expo == 0) {
printf("0");
return;
}
if (pTerm->coef == -1)printf(" - ");
else if (pTerm->coef == 1 && pTerm->expo == 0)printf(" 1");
else if (pTerm->coef < 0) printf(" - %d", pTerm->coef*-1);
else if (pTerm->coef != 1) printf(" %d", pTerm->coef);
if (pTerm->expo == 1)printf("x");
else if (pTerm->expo != 0)printf("x^%d", pTerm->expo);
}
void print_poly(Polynomial *p) {
printf("%c(x) =", p->name);
Term *t = p->first;
while (t != NULL) {
print_term(t);
t = t->next;
if(t!=NULL&&t->coef>0)printf(" +");
}
printf("\n");
}
void handle_print(char name) {
for (int i = 0; i < n; i++) {
if (polys[i]->name == name) print_poly(polys[i]);
}
}
void print_all() {
for (int i = 0; i < n; i++) {
print_poly(polys[i]);
}
}
void handle_calc(char name, char *x_str) {
Polynomial* p = NULL;
for (int i = 0; i < n; i++) {
if (polys[i]->name == name)p = polys[i];
}
if (p == NULL) {
printf("invalid polynomial\n");
return;
}
int ret = 0, inserted = atoi(x_str);
Term* pointer = p->first;
while (1) {
if (pointer == NULL)break;
int pow = 1;
for (int i = 0; i < pointer->expo; i++) {
pow *= inserted;
}
ret += (pointer->coef*pow);
pointer = pointer->next;
}
printf("%d\n", ret);
}
void erase_blanks(char *expression) {//TODO erase_blanks
int length = strlen(expression);
for (int i = 0; i < length; i++) {
if (expression[i] == ' ') {
for (int j = i--; j < length; j++) {
expression[j] = expression[j + 1];
}
continue;
}
}
}
void destroy_polynomial(Polynomial *ptr_poly) {
if (ptr_poly == NULL)
return;
Term *t = ptr_poly->first, *tmp;
while (t != NULL) {
tmp = t;
t = t->next;
free(tmp);
}
free(ptr_poly);
}
void insert_polynomial(Polynomial *ptr_poly) {
for (int i = 0; i < n; i++) {
if (polys[i]->name == ptr_poly->name) {
destroy_polynomial(polys[i]);
polys[i] = ptr_poly;
return;
}
}
polys[n++] = ptr_poly;
}
void handle_definition(char *expression) {
erase_blanks(expression);
char *f_name = strtok(expression, "=");
if (f_name == NULL || strlen(f_name) != 1) {
printf("Unsupported command.");
return;
}
char *exp_body = strtok(NULL, "=");
if (exp_body == NULL || strlen(exp_body) <= 0) {
printf("Invalid expression format.--");
return;
}
if (exp_body[0] >= 'a' && exp_body[0] <= 'z' && exp_body[0] != 'x') {
char opt[2] = { exp_body[1],'\0' };
char *former = strtok(exp_body,opt);
if (former == NULL || strlen(former) != 1) {
printf("Invalid expression format.");
return;
}
char *later = strtok(NULL,opt);
if (later == NULL || strlen(later) != 1) {
printf("Invalid expression format.");
return;
}
Polynomial *pol;
if(strcmp(opt,"+")==0)pol = create_by_add_two_polynomials(f_name[0], former[0], later[0]);
else if (strcmp(opt, "*") == 0)pol = create_by_mult_two_polynomials(f_name[0], former[0], later[0]);
else pol = NULL;
if (pol == NULL) {
printf("Invalid expression format.");
return;
}
insert_polynomial(pol);
}
else
{
Polynomial *pol = create_by_parse_polynomial(f_name[0], exp_body);
if (pol == NULL) {
printf("Invalid expression format."
);
return;
}
insert_polynomial(pol);
}
}
int create_by_parse_polynomial(char name, char *body) {
Polynomial* ptr_poly = create_polynomial_instance(name);
int i = 0, begin_term = 0;
while (i < strlen(body)) {
if (body[i] == '+' || body[i] == '-')
i++;
while (i < strlen(body) && body[i] != '+' &&body[i] != '-')
i++;
int result = parse_and_add_term(body, begin_term, i, ptr_poly);
if (result == 0)
{
destroy_polynomial(ptr_poly);
return NULL;
}
begin_term = i;
}
return ptr_poly;
}
int parse_and_add_term(char *expr, int begin, int end, Polynomial *p_poly) {
int i = begin;
int sign_coef = 1, coef = 0, expo = 1;
if (expr[i] == '+')
i++;
else if (expr[i] == '-') {
sign_coef = -1;
i++;
}
while (i < end && expr[i] >= '0' && expr[i] <= '9') {
coef = coef * 10 + (int)(expr[i] - '0');
i++;
}
if (coef == 0)coef = sign_coef;
else coef *= sign_coef;
if (i >= end) {
add_term(coef, 0, p_poly);
return 1;
}
if (expr[i] != 'x')return 0;
i++;
if (i >= end) {
add_term(coef, 1, p_poly);
return 1;
}
if (expr[i] != '^')return 0;
i++;
expo = 0;
while (i < end && expr[i] >= '0' && expr[i] <= '9') {
expo = expo * 10 + (int)(expr[i] - '0');
i++;
}
add_term(coef, expo, p_poly);
return 1;
}
int create_by_add_two_polynomials(char name, char f, char g) {//TODO adding
Term *former = NULL, *later = NULL;
Polynomial* ret = create_polynomial_instance(name);
for (int i = 0; i < n; i++) {
if (polys[i]->name == f) former = polys[i]->first;
else if (polys[i]->name == g) later = polys[i]->first;
}
while (1) {
if (former == NULL && later == NULL) return (Polynomial*) ret;
if (former == NULL || former->expo < later->expo) {
add_term(later->coef, later->expo, ret);
later = later->next;
}
else if (later==NULL||former->expo>later->expo) {
add_term(former->coef, former->expo, ret);
former = former->next;
}
else if (later->expo == former->expo) {
add_term(later->coef+former->coef, later->expo, ret);
later = later->next;
former= former->next;
}
}
}
int create_by_mult_two_polynomials(char name, char f, char g) {
Polynomial *former = NULL, *later = NULL;
Polynomial* ret = create_polynomial_instance(name);
for (int i = 0; i < n; i++) {
if (polys[i]->name == f) former = polys[i];
else if (polys[i]->name == g) later = polys[i];
}
Term *formerPointer = former->first, *laterPointer=later->first;
while (1) {
int tCoef = formerPointer->coef*laterPointer->coef;
int tExpo = formerPointer->expo+laterPointer->expo;
add_term(tCoef, tExpo, ret);
laterPointer = laterPointer->next;
if (laterPointer == NULL) {
formerPointer = formerPointer->next;
laterPointer = later->first;
}
if (formerPointer == NULL)break;
}
return ret;
}
void process_command() {
char command_line[BUFFER_LENGTH];
char copied[BUFFER_LENGTH];
char *command, *arg1, *arg2;
while (1) {
printf("$ ");
if (read_line(command_line, BUFFER_LENGTH) <= 0)
continue;
strcpy(copied, command_line);
command = strtok(command_line, " ");
if (strcmp(command, "print") == 0) {
arg1 = strtok(NULL, " ");
if (arg1 == NULL) {
printf("Invalid arguments.\n");
continue;
}
handle_print(arg1[0]);
}
else if (strcmp(command, "printall") == 0) {
print_all();
}
else if (strcmp(command, "calc") == 0) {
arg1 = strtok(NULL, " ");
if (arg1 == NULL) {
printf("Invalid arguments.\n");
continue;
}
arg2 = strtok(NULL, " ");
if (arg2 == NULL) {
printf("Invalid arguments.\n");
continue;
}
handle_calc(arg1[0], arg2);
}
else if (strcmp(command, "exit") == 0)
break;
else {
handle_definition(copied);
}
}
}
int main() {
while (1) {
process_command();
}
}
|
C
|
void MergeOne(int a[],int b[],int n,int len) //完成一遍合并的函数
{
int i,j,k,s,e;
s=0;
while(s+len<n)
{
e=s+2*len-1;
if(e>=n)//最后一段可能少于len个结点
{
e=n-1;
}//相邻有序段合并
k=s;
i=s;
j=s+len;
while(i<s+len && j<=e)//如果两个有序表都未结束时,循环比较
{
if(a[i]<=a[j])//如果较小的元素复制到数组b中
{
b[k++]=a[i++];
}
else
{
b[k++]=a[j++];
}
}
while(i<s+len)//未合并的部分复制到数组b中
{
b[k++]=a[i++];
}
while(j<=e)
{
b[k++]=a[j++]; //未合并的部分复制到数组b中
}
s=e+1; //下一对有序段中左段的开始下标
}
if(s<n) //将剩余的一个有序段从数组a中复制到数组b中
{
for(;s<n;s++)
{
b[s]=a[s];
}
}
}
void MergeSort(int a[],int n)//合并排序
{
int *p;
int h,count,len,f;
count=0;//排序步骤
len=1; //有序序列的长度
f=0; //变量f作标志
if(!(p=(int *)malloc(sizeof(int)*n))) //分配内存空间
{
printf("内存分配失败!\n");
exit(0);
}
while(len<n)
{
if(f= =1)//交替在a和P之间合并
{
MergeOne(p,a,n,len);//p合并到a
}
else
{
MergeOne(a,p,n,len);//a合并到p
}
len=len*2; //增加有序序列长度
f=1-f; //使f值在0和1之间切换
count++;
printf("第%d步排序结果:",count);//输出每步排序的结果
for(h=0;h<SIZE;h++)
{
printf("%d ",a[h]); //输出
}
printf("\n");
}
if(f)//如果进行了排序
{
for(h=0;h<n;h++)//将内存p中的数据复制到数组a中
{
a[h]=p[h];
}
}
free(p); //释放内存
}
|
C
|
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
int main() {
long int eps, i, j, perguntas, res, ep, pipoca;
scanf("%ld", &eps);
long int duracao[eps];
for(i = 0; i < eps; i++)
{
scanf("%ld", &duracao[i]);
}
scanf("%ld", &perguntas);
i = 0;
while(i < perguntas)
{
scanf("%ld %ld", &ep, &pipoca);
if(duracao[ep-1] <= pipoca)
{
for(j = ep-1; j < eps; j++)
{
pipoca = pipoca - duracao[j];
if(pipoca < 0)
{
break;
}
res = j+1;
}
}
else if(duracao[ep-1] > pipoca)
{
res = -1;
}
printf("%ld\n", res);
i++;
}
return 0;
}
|
C
|
#include <stdio.h>
#include <unistd.h>
#include <termios.h>
#include <signal.h>
#include <stdlib.h>
#include <memory.h>
#include <errno.h>
#include <wait.h>
#include <stdbool.h>
#define ROWS (20 + 2)
#define COLS 20
void printBoard();
void initBoard();
void startRound();
void updateShapeToBoard();
void playOneTurn();
void clear();
void refresh();
void wRecieved();
void sRecieved();
void dRecieved();
void aRecieved();
void handle_alarm( int sig );
void sig_handler(int num);
//Indicate '-' (part of shape) coordinate
typedef struct coordinate {
int row;
int col;
}coordinate;
//Indicate shape
typedef struct shape {
coordinate top; // Also The most Right
coordinate mid;
coordinate low; // Also The most Left
}shape;
char board[ROWS][COLS]; //The board
shape s; // The Shape
volatile sig_atomic_t print_flag = true; //Flag that indicates if board should play one turn
/**
* Init the empty board without shape
*/
void initBoard() {
int i, j;
//Init all with space
for (i = 0; i < ROWS; i++)
for(j=0; j < COLS; j++)
board[i][j] = ' ';
for(i = 0; i < ROWS; i ++) {
board[i][0] = '*';
board[i][COLS - 1] = '*';
board[ROWS - 1][i] = '*';
}
}
/**
* Print the board
*/
void printBoard() {
int i, j;
for (i = 2; i < ROWS; i++) {
for(j=0; j < COLS; j++)
printf("%c",board[i][j]);
printf("\n");
}
}
/**
* Randomize a starting col and update shape location
*/
void startRound() {
int r = (rand() % (COLS -1)) + 1; //Generate col between 1 to cols-1, means not in the edges
//Set shape rows
s.top.col = r;
s.mid.col = r;
s.low.col = r;
//Set shape cols
s.top.row = 0;
s.mid.row = 1;
s.low.row = 2;
}
/**
* Update the location of the shape to the board
*/
void updateShapeToBoard() {
//If we reach to bottom - start again
if ((s.low.row >= (ROWS - 1)) || (s.mid.row >= (ROWS - 1)) || s.top.row >= (ROWS - 1)) {
startRound();
}
board[s.top.row][s.top.col] = '-';
board[s.mid.row][s.mid.col] = '-';
board[s.low.row][s.low.col] = '-';
}
/**
* Move shape 1 step down
*/
void playOneTurn() {
s.top.row = s.top.row + 1;
s.mid.row = s.mid.row + 1;
s.low.row = s.low.row + 1;
}
/**
* When pressed d - move shape 1 step right if possible
*/
void dRecieved() {
if(s.top.col >= (COLS - 2))
return;
s.top.col++;
s.mid.col++;
s.low.col++;
refresh();
}
/**
* When pressed a - move shape 1 step left if possible
*/
void aRecieved() {
if(s.low.col <= 1)
return;
s.top.col--;
s.mid.col--;
s.low.col--;
refresh();
}
/**
* When pressed s - move shape 1 step down if possible. If reached to bottom - start again
*/
void sRecieved() {
if(s.low.row >= (ROWS - 1)) {
startRound();
refresh();
return;
}
s.top.row++;
s.mid.row++;
s.low.row++;
refresh();
}
/**
* When pressed w - rotate the shape if possible
*/
void wRecieved() {
if(s.low.row == s.top.row) {
if(s.low.row + 1 == (ROWS - 1))
return;
s.low.row++;
s.low.col++;
s.top.row--;
s.top.col--;
refresh();
return;
}
if(s.low.col == s.top.col) {
if ((s.low.col -1 == 0) || (s.top.col + 1) == (COLS-1))
return;
s.low.row--;
s.low.col--;
s.top.row++;
s.top.col++;
refresh();
}
}
/**
* Clear the board
*/
void clear() {
pid_t status;
if ( (status = fork()) == -1) {
//SuperError
printf("Couldn\'t \'fork()\' the current process into a child: %s\n", strerror(errno));
exit(-1);
}
if(status == 0) {
//Child
if(execvp("clear", (char *const[]){"clear", NULL}) == -1)
{
printf("Couldn\'t \'exec()\' the command: %s\n", strerror(errno));
exit(EXIT_FAILURE);
}
exit(EXIT_SUCCESS);
}
//Father
wait(&status);
}
/**
* Handle sigusr2
* @param num
*/
void sig_handler(int num) {
char c = getchar();
if (c == 'q') {
close(0);
close(1);
exit(0);
}
if(c == 'd')
dRecieved();
else if(c == 'a')
aRecieved();
else if(c == 'w')
wRecieved();
else if(c == 's')
sRecieved();
}
/**
* Handle alarm
* @param sig
*/
void handle_alarm( int sig ) {
print_flag = true;
}
/**
* Refresh the board and print it again
*/
void refresh() {
clear();
initBoard();
updateShapeToBoard();
printBoard();
}
int main() {
signal( SIGALRM, handle_alarm ); // Install handler first,
signal(SIGUSR2,sig_handler);
startRound();
while(1) {
if ( print_flag ) {
print_flag = false;
refresh();
playOneTurn();
alarm(1);
}
}
}
|
C
|
#include <assert.h>
#include <stdlib.h>
typedef struct st
{
struct st *next;
int data;
} st_t;
st_t dummy;
st_t *func();
void main()
{
st_t *st = func();
assert(st != NULL);
assert(st->next != NULL);
assert(st->next->next != NULL);
assert(st->next->next->next == NULL);
assert(st != &dummy);
assert(st->next != &dummy);
assert(st->next->next != &dummy);
}
|
C
|
#ifndef MIDI_H
#define MIDI_H 1
#include <stdio.h>
#define MAX_TRACKS 128
#define MAX_EVENTS 128
#define EVENT_TYPES X(NOTE_ON), X(NOTE_OFF), X(PROGRAM_CHANGE), X(CONTROL_CHANGE), X(SYSEX), X(TEMPO_CHANGE), X(AFTERTOUCH), X(PITCH_WHEEL)
typedef enum {
#define X(x) x
EVENT_TYPES
#undef X
} MIDI_ev_type;
extern char *event_names[];
typedef struct {
MIDI_ev_type type;
unsigned char channel;
unsigned char data[4]; //Note: may need to make this bigger if we want to use sysex messages to configure the voices
} MIDI_ev;
typedef struct {
char *data; //Data read in from file
int len; //Bytes in data
unsigned format;
unsigned divisions; //us per quarter note
unsigned tracks;
//For each track keep track of our position in the data,
//the length of the data in the track, and the time left
//until the next event
//int num_tracks;
int track_pos[MAX_TRACKS];
int track_end[MAX_TRACKS];
int deltas[MAX_TRACKS];
unsigned char running_status[MAX_TRACKS];
//Internal queue of events
int num_ev; //Number of events in the array
int ev_pos; //User's "cursor" into the events array
MIDI_ev events[MAX_EVENTS];
} MIDI;
//Allocates and initializes a MIDI struct on success.
//Returns NULL on failure
MIDI *midi_open(char *filename);
void midi_close(MIDI *m);
//Tells MIDI object how many ticks have elapsed. Although I don't plan to use
//this technique, this would allow more complex user code to gracefulyl handle
//the case when a tick signal is missed
int step_ticks(MIDI *m, int ticks);
//Returns number of events read (i.e. 0 or 1)
int getEvent(MIDI *m, MIDI_ev **ev);
//Should enable you to write while(getEvent(m, &ev)) {do_something_with(ev);}
#endif
|
C
|
/* acmicpc.net - 2523 - 13 */
#include <stdio.h>
int main(){
int i, j, N;
scanf("%d", &N);
for (i=1; i<=N; i++){
for (j=1; j<=i; j++) printf("*");
printf("\n");
}
for (i=N-1; i>=1; i--){
for (j=1; j<=i; j++) printf("*");
printf("\n");
}
return 0;
}
|
C
|
#include<stdio.h>
#include<stdlib.h>
struct node{
int data;
struct node *next;
};
struct node *start=NULL,*tail=NULL;
int size();
void push_front(int n);
int pop_front();
void display();
int empty();
int value_at(int loc);
void push_back(int item);
int pop_back();
int front();
int back();
void inserts(int, int);
void erase(int);
int value_at_end(int);
void reverse();
void removes(int);
int main()
{
int ch,n,loc,item;
while(1)
{
printf("\n Enter the choice\n 1.Display\n 2.size \n 3 check empty \n 4.value at particular location\n 5 pushing at front\n 6 poping at front\n 7 exit\n 8. deleting item from last\n 9 inserting an item at end\n 10 returning first item\n 11. returning last item \n 12.inserting item at particular location\n 13.remove node at a particular index \n 14 the value of the node at nth position from the end of the list\n 15. reversing the list\n 16 replacing the element");
scanf("%d",&ch);
switch(ch)
{
case 1:
display();
break;
case 2:
n=size();
printf("size of list:%d\n",n);
break;
case 3:
n=empty();
if(n==1)
printf("list is not empty");
else
printf("list is empty");
break;
case 4:
printf("enter location of item to find\n");
scanf("%d",&loc);
n=value_at(loc);
printf("value at given location is %d\n",n);
break;
case 5:
printf("Enter item to be pushed\n");
scanf("%d",&n);
push_front(n);
break;
case 6:
n= pop_front();
printf("removed item %d\n",n);
break;
case 7:
exit(0);
break;
case 8:
n=pop_back();
printf("deleted item:%d",n);
break;
case 9:
printf("enter item to insert at last\n");
scanf("%d",&item);
push_back(item);
break;
case 10:
n=front();
printf("first item of the list:%d\n",n);
break;
case 11:
n=back();
printf("last item of the list:%d\n",n);
break;
case 12:
printf("enter item and index to be inserted\n");
scanf("%d",&item);
scanf("%d",&n);
inserts(item,n);
break;
case 13:
printf("enter the index\n");
scanf("%d",&n);
erase(n);
break;
case 14:
printf("enter position from last\n");
scanf("%d",&n);
item=value_at_end(n);
printf("value at %d position from last %d",n,item);
break;
case 15:
reverse();
break;
case 16:
printf("enter the new item for replacement\n");
scanf("%d",&item);
removes(item);
break;
default:
printf("wrong choice");
}
}
}
void push_front(int item)
{
struct node *temp;
temp=(struct node*)malloc(sizeof(struct node));
temp->data=item;
if (start==NULL)
{start=tail=temp;
temp->next=NULL;
}
else
{
temp->next=start;
start=temp;
}
}
void display()
{
struct node *temp=start;
while(temp!=NULL)
{
printf("%d\t",temp->data);
temp=temp->next;
}
}
int size()
{
struct node *temp=start;
int count=0;
while(temp!=NULL)
{
count++;
temp=temp->next;
}
return count;
}
int empty()
{
int n=1;
if (start==NULL)
{
n=0;
return n;
}
else
return n;
}
int value_at(int loc)
{
int count=0;
struct node *temp=start;
while(count!=loc)
{
temp=temp->next;
count++;
}
return temp->data;
}
int pop_front()
{int n;
struct node *temp;
if (start==NULL)
{printf("string is empty");
return -1;
}
else
{
n=start->data;
temp=start;
start=temp->next;
free(temp);
return n;
}
}
int pop_back()
{int n;
struct node *temp=start,*t;
if (start==NULL)
{printf("string is empty");
return -1;
}
while(temp!=tail)
{
t=temp;
temp=temp->next;
}
tail=t;
t->next=NULL;
n=temp->data;
free(temp);
return n;
}
void push_back(int item)
{
struct node *temp;
temp=(struct node*)malloc(sizeof(struct node));
if(temp==NULL)
printf("no memory is allocated");
else
{
temp->data=item;
if(start==NULL)
{
start=tail=temp;
temp->next=NULL;
}
else{
tail->next=temp;
tail=temp;
temp->next=NULL;
}
}
}
void inserts(int item, int n)
{
struct node *temp=start,*p;
int count=1;
while(count<=n-1);
{
count++;
temp=temp->next;
}
p=(struct node *)malloc(sizeof(struct node));
p->next=temp->next;
temp->next=p;
p->data=item;
}
void reverse()
{
struct node *initial=start, *prev=NULL, *temp=NULL;
while(initial!=NULL)
{
temp=initial->next;
initial->next=prev;
prev=initial;
initial=temp;
}
tail=start;
start=prev;
}
void removes(int item)
{
start->data=item;
}
void erase(int n)
{
int count=0;
struct node *temp=start,*t;
if(n==1)
start=start->next;
else{
while(count<n)
{count++;
t=temp;
temp=temp->next;
}
t->next=temp->next;
free(temp);
}
}
int value_at_end(int pos)
{
int t,n;
t=size();
n=t-pos+1;
t=value_at(n-1);
return t;
}
int front(){
return(start->data);
}
int back()
{
return(tail->data);
}
|
C
|
/*
===========================================================================
FILE: timetickLegacy.c
DESCRIPTION:
This is the file with wrapper functions accessing Timetick DAL.
===========================================================================
*/
/*=============================================================================
INCLUDE FILES
=============================================================================*/
#include "timetick.h"
#include "DalTimetick.h"
/*
* phDalTimetickLegacyHandle
*
* Handle for communicating with the Timetick DAL.
*/
static DalDeviceHandle *phDalTimetickLegacyHandle = NULL;
/*=========================================================================
Data Definitions
==========================================================================*/
/*=============================================================================
FUNCTION timetick_attach
DESCRIPTION
Attaches to the Timetick DAL if it was not already done
DEPENDENCIES
None
RETURN VALUE
None
SIDE EFFECTS
Gives a handle to the Timetick DAL
=============================================================================*/
static void timetick_attach(void)
{
/* Check if the handle for timetick DAL already exists */
if (phDalTimetickLegacyHandle == NULL)
{
if(DAL_SUCCESS == DalTimetick_Attach("SystemTimer", &phDalTimetickLegacyHandle))
{
/* Open a connection */
DalDevice_Open(phDalTimetickLegacyHandle, DAL_OPEN_SHARED);
}
}
}
/*=============================================================================
FUNCTION TIMETICK_GET_MIN_REARM_SCLK
DESCRIPTION
Returns the MIN_REARM_SCLK value
DEPENDENCIES
Regional function. It may only be called from time*.c
RETURN VALUE
MIN_REARM_SCLK value
SIDE EFFECTS
None
=============================================================================*/
timetick_type timetick_get_min_rearm_sclk (void)
{
timetick_type min_rearm = 0;
timetick_attach();
if (phDalTimetickLegacyHandle != NULL)
{
DalTimetick_GetMinRearmSclk(phDalTimetickLegacyHandle, &min_rearm);
}
return min_rearm;
}
/*=============================================================================
FUNCTION TIMETICK_CVT_TO_SCLK
DESCRIPTION
Converts the given time value to slow clocks
DEPENDENCIES
Valid sclk estimate
RETURN VALUE
# of slow clocks which corresponds to the given time value
SIDE EFFECTS
None
=============================================================================*/
timetick_type timetick_cvt_to_sclk
(
/* Time interval to convert to slow clocks */
timetick_type time,
/* Units of time interval */
timer_unit_type unit
)
{
timetick_type time_ret = 0;
timetick_attach();
if (phDalTimetickLegacyHandle != NULL)
{
DalTimetick_CvtToTimetick32(phDalTimetickLegacyHandle, time, unit, &time_ret);
}
return time_ret;
} /* timetick_cvt_to_sclk */
/*=============================================================================
FUNCTION TIMETICK_SCLK_TO_PREC_US
DESCRIPTION
Converts the given slow clock value to precision microseconds. This function
also supports the full range of sclk values.
DEPENDENCIES
Valid sclk estimate
RETURN VALUE
# of microseconds which corresponds to the given time value
SIDE EFFECTS
None
=============================================================================*/
uint64 timetick_sclk_to_prec_us
(
uint32 sclks
/* Duration in sclks to be converted into microseconds */
)
{
uint64 microseconds = 0;
timetick_attach();
if (phDalTimetickLegacyHandle != NULL)
{
DalTimetick_CvtFromTimetick64(phDalTimetickLegacyHandle, sclks, T_USEC, µseconds);
}
return microseconds;
} /* timetick_sclk_to_prec_us */
/*=============================================================================
FUNCTION TIMETICK_CVT_FROM_SCLK
DESCRIPTION
Converts the slow clock time value to the given unit
DEPENDENCIES
Valid sclk estimate
RETURN VALUE
Time in the unit requested
SIDE EFFECTS
None
=============================================================================*/
timetick_type timetick_cvt_from_sclk
(
/* Time interval to convert to slow clocks */
timetick_type time,
/* Units of time interval */
timer_unit_type unit
)
{
timetick_type time_ret = 0;
timetick_attach();
if (phDalTimetickLegacyHandle != NULL)
{
DalTimetick_CvtFromTimetick32(phDalTimetickLegacyHandle, time, unit, &time_ret);
}
return time_ret;
} /* timetick_cvt_from_sclk */
/*=============================================================================
FUNCTION TIMETICK_GET
DESCRIPTION
Provides an intlocked context for reading the SLEEP_XTAL_TIMETICK/AGPT timer
counter.Returns the current count.
DEPENDENCIES
None.
RETURN VALUE
Slow clock timetick counter value
SIDE EFFECTS
None
=============================================================================*/
timetick_type timetick_get( void )
{
/* Sleep Xtal Time Tick count */
timetick_type count = 0;
timetick_attach();
if (phDalTimetickLegacyHandle != NULL)
{
DalTimetick_Get(phDalTimetickLegacyHandle, &count);
}
return count;
} /* timetick_get */
/*=============================================================================
FUNCTION TIMETICK_INIT_SCLK64
DESCRIPTION
This function initializes the 64-bit timetick system by defining a timer to
track the rollover of the slow clock. This should ONLY be called once upon
boot, preferably before the first rollover of the slock clock (~36.5 hrs.)
DEPENDENCIES
None
RETURN VALUE
None
SIDE EFFECTS
After this is called timetick_get_sclk64 can be used.
=============================================================================*/
void timetick_init_sclk64( void )
{
timetick_attach();
if (phDalTimetickLegacyHandle != NULL)
{
DalTimetick_InitTimetick64(phDalTimetickLegacyHandle);
}
} /* timetick_init_sclk64 */
/*=============================================================================
FUNCTION TIMETICK_GET_SCLK64
DESCRIPTION
Read the SLEEP_XTAL_TIMETICK counter. Adds the rollover offset to provide
64 bit dynamic range.
DEPENDENCIES
TIMETICK_INIT_SCLK64 must be called first to initialize the timer.
RETURN VALUE
64-bit tick count
SIDE EFFECTS
None
=============================================================================*/
uint64 timetick_get_sclk64( void )
{
/* timetick in 64 bits */
uint64 sclk64 = 0;
timetick_attach();
if (phDalTimetickLegacyHandle != NULL)
{
DalTimetick_GetTimetick64(phDalTimetickLegacyHandle, &sclk64);
}
/* Return 64-bit sclk */
return sclk64;
} /* timetick_get_sclk64 */
/*=============================================================================
FUNCTION TIMETICK_GET_ELAPSED
DESCRIPTION
Compute the time elapsed from a previous timetick value
DEPENDENCIES
Valid slow clock estimate.
RETURN VALUE
Elapsed time, in the unit provided
SIDE EFFECTS
None
=============================================================================*/
timetick_type timetick_get_elapsed
(
/* Time tick value at start of interval */
timetick_type start,
/* Units to return time interval in */
timer_unit_type unit
)
{
timetick_type diff = 0;
timetick_attach();
if (phDalTimetickLegacyHandle != NULL)
{
DalTimetick_GetElapsed(phDalTimetickLegacyHandle, start, unit, &diff);
}
return diff;
} /* timetick_get_elapsed */
/*=============================================================================
FUNCTION TIMETICK_DIFF
DESCRIPTION
Compute the difference between two slow clock tick counts
DEPENDENCIES
Valid slow clock estimate.
RETURN VALUE
Time difference between the two slow clock tick counts, in the unit given
SIDE EFFECTS
None
=============================================================================*/
timetick_type timetick_diff
(
/* Time tick value at start of interval */
timetick_type start,
/* Time tick value at end of interval */
timetick_type end,
/* Units to return time interval in */
timer_unit_type unit
)
{
timetick_type diff = 0;
timetick_attach();
if (phDalTimetickLegacyHandle != NULL)
{
DalTimetick_Diff(phDalTimetickLegacyHandle, start, end, unit, &diff);
}
return diff;
} /* timetick_diff */
/*=============================================================================
FUNCTION TIMETICK_GET_MS
DESCRIPTION
Returns a monotonically increasing millisecond count.
The value returned is unrelated to CDMA, GPS, HDR, or Time of Day
time-stamps. It will drift with respect to the above time references.
*** This function sacrifices accuracy for speed ***
DEPENDENCIES
None
RETURN VALUE
Millisecond tick count
SIDE EFFECTS
None
=============================================================================*/
timetick_type timetick_get_ms( void )
{
/* Milliseconds since origin time */
timetick_type msecs = 0;
timetick_attach();
if (phDalTimetickLegacyHandle != NULL)
{
DalTimetick_GetMs(phDalTimetickLegacyHandle, &msecs);
}
return msecs;
} /* timetick_get_ms */
/*=============================================================================
FUNCTION TIMETICK_UPDATE_FREQ
DESCRIPTION
Stores the sclk frequency in Hz for use during timetick calculations.
DEPENDENCIES
None.
RETURN VALUE
None.
SIDE EFFECTS
Updates timetick.ms_info.freq information
=============================================================================*/
void timetick_update_freq
(
/* The new slow clock frequency (in Hz) */
uint32 freq
)
{
timetick_attach();
if (phDalTimetickLegacyHandle != NULL)
{
DalTimetick_UpdateFreq(phDalTimetickLegacyHandle, freq);
}
} /* timetick_update_freq */
/*==========================================================================
FUNCTION TIMETICK_GET_FREQ
DESCRIPTION Returns the sclk frequency in Hz.
PARAMETERS None.
DEPENDENCIES None.
RETURN VALUE slow clk frequency.
SIDE EFFECTS None.
==========================================================================*/
uint32 timetick_get_freq (void)
{
uint32 freq = 0;
timetick_attach();
if (phDalTimetickLegacyHandle != NULL)
{
DalTimetick_GetFreq(phDalTimetickLegacyHandle, &freq);
}
return freq;
} /* timetick_get_freq */
/*=============================================================================
FUNCTION TIMETICK_SET_SCLK_OFFSET REGIONAL
DESCRIPTION
Stores the offset between application and modem processors' sclk counters.
The application and modem processors' sclk h/w counters, while both count
slow clocks, will have an offset w.r.t. each other, due to application
processor power collapse. This difference is eliminated by adding an offset
to the value read from the application processor's sclk counter.
DEPENDENCIES
Regional function. It may only be called from time*.c
RETURN VALUE
None
SIDE EFFECTS
None
=============================================================================*/
void timetick_set_sclk_offset
(
/* Difference between application and modem processor's sclk counters. */
timetick_type sclk_delta
)
{
timetick_attach();
if (phDalTimetickLegacyHandle != NULL)
{
DalTimetick_SetOffset(phDalTimetickLegacyHandle, sclk_delta);
}
} /* timetick_set_sclk_offset */
/*=============================================================================
FUNCTION TIMETICK_GET_SCLK_OFFSET REGIONAL
DESCRIPTION
Retrieves the offset between application and modem processors' sclk counters.
The application and modem processors' sclk h/w counters, while both count
slow clocks, will have an offset w.r.t. each other, due to application
processor power collapse. This difference is eliminated by adding an offset
to the value read from the application processor's sclk counter.
DEPENDENCIES
Regional function. It may only be called from time*.c
RETURN VALUE
None
SIDE EFFECTS
None
=============================================================================*/
timetick_type timetick_get_sclk_offset (void)
{
timetick_type sclk_delta = 0;
timetick_attach();
if (phDalTimetickLegacyHandle != NULL)
{
DalTimetick_GetOffset(phDalTimetickLegacyHandle, &sclk_delta);
}
return sclk_delta;
} /* timetick_get_sclk_offset */
/*=============================================================================
FUNCTION TIMETICK_GET_RAW
DESCRIPTION
Read the SLEEP_XTAL_TIMETICK counter, and return the current count.
DEPENDENCIES
Regional function. It may only be called from time*.c
RETURN VALUE
Slow clock timetick counter value
SIDE EFFECTS
None
=============================================================================*/
timetick_type timetick_get_raw( void )
{
timetick_type nCount = 0;
timetick_attach();
if (phDalTimetickLegacyHandle != NULL)
{
DalTimetick_GetRaw(phDalTimetickLegacyHandle, &nCount);
}
return (nCount);
} /* timetick_get_raw */
/*=============================================================================
FUNCTION TIMETICK_GET_SAFE
DESCRIPTION
Returns the SLEEP_XTAL_TIMETICK/AGPT timer count.
DEPENDENCIES
Must be called from an INTLOCK'd context.
Use TIMETICK_GET from non-INTLOCK'd context
RETURN VALUE
Slow clock timetick counter value
SIDE EFFECTS
None
=============================================================================*/
timetick_type timetick_get_safe( void )
{
/* Sleep Xtal Time Tick count */
timetick_type tick = 0;
timetick_attach();
if (phDalTimetickLegacyHandle != NULL)
{
DalTimetick_Get(phDalTimetickLegacyHandle, &tick);
}
return tick;
} /* timetick_get_safe */
/*=============================================================================
FUNCTION TIMETICK_SET_NEXT_INTERRUPT
DESCRIPTION
Programs the SLEEP_XTAL_TIMETICK/AGPT timer to generate an interrupt at the
given value
DEPENDENCIES
Must be called from INTLOCKED context.
RETURN VALUE
matchvalue set
SIDE EFFECTS
Interrupt when slow clock counter reaches given value
=============================================================================*/
timetick_type timetick_set_next_interrupt
(
/* Slow clock count at which next interrupt will occur */
timetick_type match_count,
/* Current slow clock count */
timetick_type ticks_now
)
{
timetick_type match_value = 0;
timetick_attach();
if (phDalTimetickLegacyHandle != NULL)
{
DalTimetick_SetNextInterrupt(phDalTimetickLegacyHandle, match_count, ticks_now, &match_value);
}
return match_value;
} /* timetick_set_next_interrupt */
/*=============================================================================
FUNCTION TIMETICK_ENABLE
DESCRIPTION
Enables the Timetick module
DEPENDENCIES
None
RETURN VALUE
None
SIDE EFFECTS
None
=============================================================================*/
void timetick_enable (void)
{
timetick_attach();
if (phDalTimetickLegacyHandle != NULL)
{
DalTimetick_Enable(phDalTimetickLegacyHandle, TRUE);
}
} /* timetick_enable */
/*=============================================================================
FUNCTION TIMETICK_CVT_TO_SCLK64
DESCRIPTION
Converts the given time value to slow clocks
DEPENDENCIES
Valid sclk estimate
RETURN VALUE
# of slow clocks which corresponds to the given time value
SIDE EFFECTS
None
=============================================================================*/
uint64 timetick_cvt_to_sclk64
(
/* Time interval to convert to slow clocks */
uint64 time,
/* Units of time interval */
timer_unit_type unit
)
{
uint64 time_ret = 0;
timetick_attach();
if (phDalTimetickLegacyHandle != NULL)
{
DalTimetick_CvtToTimetick64(phDalTimetickLegacyHandle, time, unit, &time_ret);
}
return time_ret;
} /* timetick_cvt_to_sclk */
/*=============================================================================
FUNCTION TIMETICK_CVT_FROM_SCLK64
DESCRIPTION
Converts the slow clock time value to the given unit
DEPENDENCIES
Valid sclk estimate
RETURN VALUE
Time in the unit requested
SIDE EFFECTS
None
=============================================================================*/
uint64 timetick_cvt_from_sclk64
(
/* Time interval to convert to slow clocks */
uint64 time,
/* Units of time interval */
timer_unit_type unit
)
{
uint64 time_ret = 0;
timetick_attach();
if (phDalTimetickLegacyHandle != NULL)
{
DalTimetick_CvtFromTimetick64(phDalTimetickLegacyHandle, time, unit, &time_ret);
}
return time_ret;
} /* timetick_cvt_from_sclk64 */
/*=============================================================================
FUNCTION TIMETICK_CVT_FROM_USEC
DESCRIPTION
Converts the slow clock time value to the given unit
DEPENDENCIES
Valid sclk estimate
RETURN VALUE
Time in the unit requested
SIDE EFFECTS
None
=============================================================================*/
timetick_type timetick_cvt_from_usec
(
/* Time interval to convert to slow clocks */
uint64 time,
/* Units of time interval */
timer_unit_type unit
)
{
timetick_type time_ret = 0;
timetick_attach();
if (phDalTimetickLegacyHandle != NULL)
{
DalTimetick_CvtFromUsec(phDalTimetickLegacyHandle, time, unit, &time_ret);
}
return time_ret;
} /* timetick_cvt_from_usec */
/*=============================================================================
FUNCTION TIMETICK_CVT_TO_USEC
DESCRIPTION
Converts the given time value to slow clocks
DEPENDENCIES
Valid sclk estimate
RETURN VALUE
# of slow clocks which corresponds to the given time value
SIDE EFFECTS
None
=============================================================================*/
uint64 timetick_cvt_to_usec
(
/* Time interval to convert to slow clocks */
timetick_type time,
/* Units of time interval */
timer_unit_type unit
)
{
uint64 time_ret = 0;
timetick_attach();
if (phDalTimetickLegacyHandle != NULL)
{
DalTimetick_CvtToUsec(phDalTimetickLegacyHandle, time, unit, &time_ret);
}
return time_ret;
} /* timetick_cvt_to_usec */
/*=============================================================================
FUNCTION TIMETICK_UPDATE_BLAST_SIGNAL_ID
DESCRIPTION
Updates the timetick driver with the blast signal id for rgpt timer.
DEPENDENCIES
None
RETURN VALUE
None
SIDE EFFECTS
None
=============================================================================*/
void timetick_update_blast_signal_id(uint32 sig_id)
{
timetick_attach();
if (phDalTimetickLegacyHandle != NULL)
{
DalTimetick_UpdateBlastSigId(phDalTimetickLegacyHandle, sig_id);
}
}/* timetck_update_blast_signal_id */
|
C
|
/*
* Data la dimensione del lato, disegnare un quadrato a schermo
* mettendo dove sui lati i caratteri "*"
* Input: lato x
* Output: quadrato disegnato con lato x
*
* (c) Marco Aceti, 2017. Some rights reserved.
* See LICENSE file for more details.
* THE SOFTWARE IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND.
*/
#include <stdio.h>
int main() {
int x;
int i, h;
printf("Inserisci le dimensioni del lato del quadrato: ");
scanf("%d", &x);
for (i=0; i < x; i++) {
for (h=0; h < x; h++) {
if ((h == 0 || h == (x - 1)) || (i == 0 || i == (x - 1))) {
printf("*");
}
else {
printf(" ");
}
}
printf("\n");
}
return 0;
}
|
C
|
#include<stdio.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<netinet/ip.h>
#include<stdlib.h>
#include<string.h>
#include<unistd.h>
#include<arpa/inet.h>
void main(){
int sockfd = socket(AF_INET, SOCK_STREAM, 0);
if(sockfd == -1) {
printf("socket error\n");
exit(1);
}
struct sockaddr_in server_addr;
memset(&server_addr, 0, sizeof(struct sockaddr_in));
union{
unsigned int addr;
unsigned char c[4];
}un;
un.c[0] = 1;
un.c[1] = 0;
un.c[2] = 0;
un.c[3] = 127;
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(80);
// server_addr.sin_port = un;
server_addr.sin_addr.s_addr = inet_addr("172.217.31.228");
// if(inet_pton(AF_INET, "127.0.0.1", &server_addr.sin_addr)<=0)
// {
// printf("\nInvalid address/ Address not supported \n");
// exit(1);
// }
int err = connect(sockfd, (const struct sockaddr *)&server_addr, sizeof(struct sockaddr_in));
if(err == -1){
printf("connect error\n");
exit(1);
}
struct hostent *h;
char buf[10000];
while(1){
memset(buf, 0, 10000);
fgets(buf, 999, stdin);
printf("%s", buf);
if(!strcmp(buf,"exit"))
exit(1);
write(sockfd ,buf, strlen(buf));
memset(buf, 0 , 10000);
unsigned int sz = read(sockfd, buf, 10000);
buf[sz] = '\0';
char* start = strstr(buf, "\r\n\r\n");
//printf("%p",start);
//printf("%p\n", start);
//write(stdout,start,sz);
printf("%s\n", start);
}
close(sockfd);
}
|
C
|
#include <stdio.h>
#include <string.h>
#include "Entidade.h"
#include "Validacoes.h"
#include <stdlib.h>
#define true 1
#define false 0
#include <time.h>
#define MAX_Detentos 200
#define Max_Penas 100
#define Max_Atividade 100
#define Max_FuncAtividade 500
#define Max_Visitantes 200
#define Max_Visitas 500
int validaString(char String[]){
int a = 0;
if(strcmp(String, "") != 0){
a = 1;
}
return a;
}
int validaIntPositivo(int numero){
int a = 0;
if(numero >= 0){
a = 1;
}
return a;
}
void limpaVetor(char string[]){
strcpy(string, "");
}
int retornarIDaleatorio(){
srand(time(NULL));
int rando = rand()%200;
return rando;
}
int verificaDetentoExiste(char stringN[], Detentos denVec[]){
int index, result = 0;
for(index = 0; index <= MAX_Detentos; index++){
if(strcmp(denVec[index].Nome, stringN) == 0){
result = 1;
break;
}
}
return result;
}
int verificaDetentoExisteID(int IDden, Detentos denVec[]){
int index, result = 0;
for(index = 0; index <= MAX_Detentos; index++){
if(denVec[index].ID == IDden){
result = 1;
break;
}
}
return result;
}
int verificaDetentoExisteCPF(long int CPF, Detentos denVec[], int atual){
int index, result = 0;
for(index = 0; index <= MAX_Detentos; index++){
if(CPF == denVec[index].loginCPF){
if(index == atual){
result = 0;
}else{
result = 1;
}
break;
}
}
return result;
}
int verificaDetentoExisteCPFcdt(long int CPF, Detentos denVec[]){
int index, result = 0;
for(index = 0; index <= MAX_Detentos; index++){
if(CPF == denVec[index].loginCPF){
result = 1;
break;
}
}
return result;
}
void copiaDetentoParaVetor(Detentos den, Detentos denVec[]){
int ID = den.ID;
strcpy(denVec[ID].Nome, den.Nome);
denVec[ID].ID = den.ID;
strcpy(denVec[ID].dataNascimento, den.dataNascimento);
strcpy(denVec[ID].dataSaida, den.dataSaida);
strcpy(denVec[ID].dataEntrada, den.dataEntrada);
strcpy(denVec[ID].nomeMae, den.nomeMae);
strcpy(denVec[ID].escolaridade, den.escolaridade);
denVec[ID].numeroAla = den.numeroAla;
denVec[ID].telefone = den.telefone;
denVec[ID].IDpena = den.IDpena;
denVec[ID].ativo = den.ativo;
denVec[ID].preenchido = den.preenchido;
strcpy(denVec[ID].Profissao, den.Profissao);
denVec[ID].numeroQuarto = den.numeroQuarto;
denVec[ID].loginCPF = den.loginCPF;
}
int verificaPenaExiste(int IDpena, Penas penVec[]){
int index, result = 0;
for(index = 0; index <= Max_Penas; index++){
if(penVec[index].ID == IDpena){
result = 1;
break;
}
}
return result;
}
int verificaDecsPenaExiste(char stringP[], Penas penVec[]){
int index, result = 0;
for(index = 0; index <= Max_Penas; index++){
if(strcmp(penVec[index].descricao, stringP) == 0){
result = 1;
break;
}
}
return result;
}
void copiaPenaParaVetor(Penas pen, Penas penVec[]){
int ID = pen.ID;
strcpy(penVec[ID].descricao, pen.descricao);
penVec[ID].ID = pen.ID;
strcpy(penVec[ID].Regiume, pen.Regiume);
penVec[ID].grau = pen.grau;
penVec[ID].preenchido = pen.preenchido;
}
int verificaAtividadeExiste(int ID, Atividade atvVec[]){
int result = 0, cont;
for(cont = 0; cont <= Max_Atividade; cont++){
if(atvVec[cont].ID == ID){
result++;
break;
}
}
return result;
}
int verificaAtividadeExisteDesc(char stringA[], Atividade atvVec[]){
int index, result = 0;
for(index = 0; index <= Max_Atividade; index++){
if(strcmp(atvVec[index].descricao, stringA) == 0){
result = 1;
break;
}
}
return result;
}
void copiaAtividadeParaVetor(Atividade atv, Atividade atvVec[]){
int ID = atv.ID;
strcpy(atvVec[ID].descricao, atv.descricao);
atvVec[ID].ID = atv.ID;
atvVec[ID].avaliacao = atv.avaliacao;
atvVec[ID].remuneracao = atv.remuneracao;
atvVec[ID].preenchido = atv.preenchido;
atvVec[ID].ativo = atv.ativo;
}
int verificaAtividadeAlocada(FuncAtividade funatv[], FuncAtividade atv){
int result = 0, cont;
for(cont = 0; cont <= Max_FuncAtividade; cont++){
if(funatv[cont].IDdetento == atv.IDdetento && funatv[cont].IDatividade == atv.IDatividade && (strcmp(funatv[cont].diaSemana, atv.diaSemana) == 0) && funatv[cont].Ativa == true && funatv[result].turno == atv.turno) {
result++;
}
}
return result;
}
void copiaFuncAtividadeParaVetor(FuncAtividade funcAtv, FuncAtividade funcAtvVec[]){
int ID = funcAtv.IDfuncAtv;
strcpy(funcAtvVec[ID].dataAtividade, funcAtv.dataAtividade);
strcpy(funcAtvVec[ID].diaSemana, funcAtv.diaSemana);
funcAtvVec[ID].turno = funcAtv.turno;
funcAtvVec[ID].IDatividade = funcAtv.IDatividade;
funcAtvVec[ID].IDdetento = funcAtv.IDdetento;
funcAtvVec[ID].preenchido = funcAtv.preenchido;
funcAtvVec[ID].Ativa = funcAtv.Ativa;
}
int verificaVisitanteExisteNome(char stringN[], Visitantes visVec[]){
int index, result = 0;
for(index = 0; index <= Max_Visitantes; index++){
if(strcmp(visVec[index].Nome , stringN) == 0){
result = 1;
break;
}
}
return result;
}
int verificaVisitantesExisteCPF(long int CPF, Visitantes visVec[]){
int result = 0, cont;
for(cont = 0; cont <= Max_Visitantes; cont++){
if(visVec[cont].CPF == CPF){
result++;
break;
}
}
return result;
}
int verificaVisitantesExisteID(int ID, Visitantes visVec[]){
int result = 0, cont;
for(cont = 0; cont <= Max_Visitantes; cont++){
if(visVec[cont].ID == ID){
result++;
break;
}
}
return result;
}
void copiaVisitantesParaVetor(Visitantes vis, Visitantes visVec[]){
int ID = vis.ID;
strcpy(visVec[ID].Nome, vis.Nome);
visVec[ID].ID = vis.ID;
strcpy(visVec[ID].dataNascimento, vis.dataNascimento);
strcpy(visVec[ID].escolaridade, vis.escolaridade);
strcpy(visVec[ID].profissao, vis.profissao);
visVec[ID].preenchido = vis.preenchido;
visVec[ID].ativo = vis.ativo;
}
int verificaVisitaAgendadaPorSala(char data[], int sala, Visitas vecVis[]){
int cont = 0;
int retorno = 0;
for(cont = 0; cont <= Max_Visitas; cont++){
if((strcmp(data, vecVis[cont].dataVisita) == 0) && sala == vecVis[cont].salaVisista && sala <= 15){
retorno = 1;
break;
}
}
return retorno;
}
void copiaVisitasParaVetor(Visitas vis, Visitas visVec[]){
int ID = vis.IDvisitas;
visVec[ID].IDdetento = vis.IDdetento;
visVec[ID].IDvisitantes = vis.IDvisitantes;
strcpy(visVec[ID].dataVisita, vis.dataVisita);
visVec[ID].salaVisista = vis.salaVisista;
visVec[ID].preenchido = vis.preenchido;
}
int verificaVisitaExisteID(int ID, Visitas visVec[]){
int result = 0, cont;
for(cont = 0; cont <= Max_Visitas; cont++){
if(visVec[cont].IDvisitas == ID){
result++;
break;
}
}
return result;
}
int verificaDataMenorMaior(char data1[20], char data2[20]){
/* 1 - Data 1 menor que data 2 */
/* 2 - Data 1 maior que data 2 */
/* 3 - Data 1 igual a data 2 */
int cont = 0;
time_t t1;
time_t t2;
struct tm tm;
int ano, mes;
sscanf( data1, "%d.%d.%d", &tm.tm_mday, tm.tm_mon, tm.tm_year);
t1 = mktime(&tm);
sscanf( data2, "%d.%d.%d", &tm.tm_mday, tm.tm_mon, tm.tm_year);
t1 = mktime(&tm);
if(data1 < data2){
cont = 1;
} else if(data1 > data2){
cont = 2;
}else{
cont = 3;
}
return cont;
}
|
C
|
#ifndef LAB1_STUDENT_H
#define LAB1_STUDENT_H
struct value {
unsigned int age;
unsigned int weight;
value( unsigned int a, unsigned int b ) {
age = a;
weight = b;
}
value() {
age = 0;
weight = 0;
}
~value() {}
friend bool operator!=( const value& a, const value& b ) {
if ( a.age != b.age || a.weight != b.weight ) {
return true;
}
return false;
}
friend bool operator==( const value& a, const value& b ) {
if ( a != b ) {
return false;
}
return true;
}
};
#endif //LAB1_STUDENT_H
|
C
|
// C Program for Message Queue (Writer Process)
#include <stdio.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <string.h>
// structure for message queue
struct user {
long message_type;
char account_number[100];
int cash_amt;
} stru1;
int main()
{
key_t key;
int messagesgid;
printf(" Welcome.. \n Please Enter your account number : ");
gets(stru1.account_number);
printf("\nEnter the amount to be deposited :");
scanf("%d",&stru1.cash_amt);
// ftok to generate unique key
key = ftok("progfile", 65);
// msgget creates a message queue
// and returns identifier
messagesgid = msgget(key, 0666 | IPC_CREAT);
stru1.message_type = 1;
// msgsnd to send message
msgsnd(messagesgid, &stru1, sizeof(stru1), 0);
// display the message
printf(" Data send Sucessfully... \n Data send is : %d %s \n", stru1.cash_amt,stru1.account_number);
return 0;
}
|
C
|
#include "utils.h"
#include <ctype.h>
/* Skip everything that is not alphanumeric value before that start of the word */
int skipDelim(FILE *file){
int input;
while(!(isalnum(input = fgetc(file)))){
/* We check if we reached a necessary char */
if(input == '\n')
return NEWLINE;
if(input == EOF)
return EOF;
}
return input;
}
/* Gets a word from the specified file
* We assume that a word will not exceed 2000 chars */
int getWord(FILE *file, char *word){
int input,i;
for(i = 0; (isalnum(input = fgetc(file))); i++){
*word++ = (char)input;
}
/* We reached a non alphanumeric char so we can close the word */
word[i] = '\0';
/* We check if we reached a necessary char */
if(input == '\n'){
return NEWLINE;
}
if(input == EOF){
return EOF;
}
return 1;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main() {
char *buffer = NULL;
size_t size1;
size_t size2;
FILE *filedes;
filedes = fopen("out.txt", "w+");
if (filedes == NULL){
printf("Could not open file\n");
}
/* A total of 6 characters including the null byte can be copied into buffer */
size1 = 6;
buffer = (char *)calloc( 1, size1);
if (buffer == NULL) {
printf("Could not allocate memory\n");
}
/* Copies 8 characters of the alphabet string into the buffer. Note that byte 5 is a null byte here. */
buffer[0]= 'a';
buffer[1]= 'b';
buffer[2]= 'c';
buffer[3]= 'd';
buffer[4]= '\0';
buffer[5]= 'f';
buffer[6]= 'g';
buffer[7]= 'p';
/* Despite the null byte being there at byte 5, fwrite ignores it and just copies 8 bytes into buffer and hence out.txt.
Verify this using wc -c out.txt or hexdump -C out.txt
*/
size2= 8;
/*
Always set the amount to write based on the size of the buffer you are writing
*/
//size2= strlen(buffer)+1;
fwrite(buffer, 1, size2, filedes);
free(buffer);
buffer = NULL;
fclose(filedes);
/*
This could be a problem IF there is some program which reads the file and uses all of the information inside to do something with it
but ignores the null character.
*/
}
|
C
|
#include <stdlib.h>
#include <gba.h>
#include "obj_utils.h"
void InitObj(OBJ_UTILS* oud) {
oud->obj = (OBJATTR*)malloc(sizeof(OBJATTR) * OBJ_MAX);
}
void FinishObj(OBJ_UTILS* oud) {
free(oud->obj);
}
void SetObjChr(OBJ_UTILS* oud, const void* tiles_adr, const void* pal_adr) {
// グラフィックデータをメモリへコピー
dmaCopy((u16*)tiles_adr, BITMAP_OBJ_BASE_ADR, 8192);
dmaCopy((u16*)pal_adr, OBJ_COLORS, 512);
}
void objReg(OBJATTR** attrp, OBJ_UTILS* oud, int n){
*attrp = &oud->obj[n];
}
// 移動
void objMove(OBJATTR* attr, int x, int y){
attr->attr0 &= 0xFF00;
attr->attr1 &= 0xFE00;
attr->attr0 |= OBJ_Y(y);
attr->attr1 |= OBJ_X(x);
}
// 4まとまりを一度に操作
void obj4draw(OBJATTR* attr, int chr, int x, int y){
int x2 = x + 8;
int y2 = y + 8;
attr[0].attr0 = OBJ_Y(y ) | OBJ_16_COLOR;
attr[0].attr1 = OBJ_X(x ) | 0 | OBJ_VFLIP;
attr[0].attr2 = OBJ_CHAR(chr);
attr[1].attr0 = OBJ_Y(y ) | OBJ_16_COLOR;
attr[1].attr1 = OBJ_X(x2) | OBJ_HFLIP | OBJ_VFLIP;
attr[1].attr2 = OBJ_CHAR(chr);
attr[2].attr0 = OBJ_Y(y2) | OBJ_16_COLOR;
attr[2].attr1 = OBJ_X(x) | 0 | 0;
attr[2].attr2 = OBJ_CHAR(chr);
attr[3].attr0 = OBJ_Y(y2) | OBJ_16_COLOR;
attr[3].attr1 = OBJ_X(x2) | OBJ_HFLIP | 0;
attr[3].attr2 = OBJ_CHAR(chr);
}
// 2まとまりを一度に操作
void obj2draw(OBJATTR* attr, int chr, int x, int y) {
int x2 = x + 8;
attr[0].attr0 = OBJ_Y(y ) | OBJ_16_COLOR;
attr[0].attr1 = OBJ_X(x ) | 0 | OBJ_VFLIP;
attr[0].attr2 = OBJ_CHAR(chr);
attr[1].attr0 = OBJ_Y(y ) | OBJ_16_COLOR;
attr[1].attr1 = OBJ_X(x2) | OBJ_HFLIP | 0;
attr[1].attr2 = OBJ_CHAR(chr);
}
void obj2pal(OBJATTR* attr, int pal) {
attr[0].attr2 &= 0x0FFF;
attr[0].attr2 |= OBJ_PALETTE(pal);
attr[1].attr2 &= 0x0FFF;
attr[1].attr2 |= OBJ_PALETTE(pal);
}
void obj2chr(OBJATTR* attr, int chr) {
attr[0].attr2 &= 0xFC00;
attr[0].attr2 |= OBJ_CHAR(chr);
attr[1].attr2 &= 0xFC00;
attr[1].attr2 |= OBJ_CHAR(chr);
}
void obj4pal(OBJATTR* attr, int pal) {
attr[0].attr2 &= 0x0FFF;
attr[0].attr2 |= OBJ_PALETTE(pal);
attr[1].attr2 &= 0x0FFF;
attr[1].attr2 |= OBJ_PALETTE(pal);
attr[2].attr2 &= 0x0FFF;
attr[2].attr2 |= OBJ_PALETTE(pal);
attr[3].attr2 &= 0x0FFF;
attr[3].attr2 |= OBJ_PALETTE(pal);
}
void objdraw(OBJATTR* attr, int chr, int x, int y) {
attr[0].attr0 = OBJ_Y(y ) | OBJ_16_COLOR;
attr[0].attr1 = OBJ_X(x ) ;
attr[0].attr2 = OBJ_CHAR(chr);
}
void objchr(OBJATTR* attr, int chr) {
attr[0].attr2 &= 0xFC00;
attr[0].attr2 |= OBJ_CHAR(chr);
}
void objattr(OBJATTR* attr, int h, int v) {
h &= 1; v &= 1;
attr[0].attr1 &= 0xCFFF;
attr[0].attr1 |= (h << 12) | (v << 13) ;
}
void objInit(OBJATTR* attr, int chr, int col256) {
col256 &= 1;
attr->attr0 = 0 | (col256 ? ATTR0_COLOR_256 : 0);
attr->attr1 = 0;
attr->attr2 = OBJ_CHAR(chr);
}
// バッファからSpriteRAMに書き込み
void FlushSprite(OBJ_UTILS* oud) {
// 実際のOBJ情報メモリに書き込み
dmaCopy(oud->obj, (u16*)OAM, sizeof(OBJATTR) * OBJ_MAX);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int agrc, char *argv[]){
char input[200];
int len;
int ans;
int pow[32];
int i;
pow[0] = 1;
for(i=1; i<32; i++){
pow[i] = pow[i-1] * 2;
}
while(1){
gets(input);
if(strcmp(input, "0") == 0){
break;
}
ans = 0;
len = strlen(input);
for(i=1; i<=len; i++){
if(input[len-i] != '0'){
ans += (input[len-i] - 48) * (pow[i] - 1);
}
}
printf("%d\n", ans);
}
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h> /* atoi */
#include <string.h>
int main()
{
char *str = "12, 0";
char *pc = strchr(str, ',');
int first, second;
printf("*pc:%c\n", *pc);
first = atoi(str);
second = atoi(pc + 1);
printf("first:%d\n", first);
printf("second:%d\n", second);
return 0;
}
|
C
|
#include "config/output_format.h"
#include <getopt.h>
#include <stdlib.h>
#include <string.h>
#include "log.h"
#include "config/str.h"
#define OFM_VALUE_CSV "csv"
#define OFM_VALUE_JSON "json"
#define DEREFERENCE(void_value) (*((enum output_format *) void_value))
static void
print_output_format(struct option_field const *field, void *value)
{
char const *str = "<unknown>";
switch (DEREFERENCE(value)) {
case OFM_CSV:
str = OFM_VALUE_CSV;
break;
case OFM_JSON:
str = OFM_VALUE_JSON;
break;
}
pr_op_info("%s: %s", field->name, str);
}
static int
parse_argv_output_format(struct option_field const *field, char const *str,
void *result)
{
if (strcmp(str, OFM_VALUE_CSV) == 0)
DEREFERENCE(result) = OFM_CSV;
else if (strcmp(str, OFM_VALUE_JSON) == 0)
DEREFERENCE(result) = OFM_JSON;
else
return pr_op_err("Unknown output format %s: '%s'",
field->name, str);
return 0;
}
static int
parse_json_output_format(struct option_field const *opt, json_t *json,
void *result)
{
char const *string;
int error;
error = parse_json_string(json, opt->name, &string);
return error ? error : parse_argv_output_format(opt, string, result);
}
const struct global_type gt_output_format = {
.has_arg = required_argument,
.size = sizeof(enum output_format),
.print = print_output_format,
.parse.argv = parse_argv_output_format,
.parse.json = parse_json_output_format,
.arg_doc = OFM_VALUE_CSV "|" OFM_VALUE_JSON,
};
|
C
|
/*
gcc -std=c17 -lc -lm -pthread -o ../_build/c/numeric_math_fabs.exe ./c/numeric_math_fabs.c && (cd ../_build/c/;./numeric_math_fabs.exe)
https://en.cppreference.com/w/c/numeric/math/fabs
*/
#include <stdio.h>
#include <math.h>
/* This numerical integration assumes all area is positive. */
#define PI 3.14159
double num_int (double a, double b,
double f(double),
unsigned n) {
if (a == b) return 0.0;
if (n == 0) n=1; /* avoid division by zero */
double h = (b-a)/n;
double sum = 0.0;
for (unsigned k=0; k < n; ++k)
sum += h*fabs(f(a+k*h));
return sum;
}
int main(void)
{
printf("fabs(+3) = %f\n", fabs(+3.0));
printf("fabs(-3) = %f\n", fabs(-3.0));
// special values
printf("fabs(-0) = %f\n", fabs(-0.0));
printf("fabs(-Inf) = %f\n", fabs(-INFINITY));
printf("%f\n", num_int(0.0,2*PI,sin,100000));
}
|
C
|
#ifndef TCPHELPER_H
#define TCPHELPER_H
#include "util.h"
typedef struct tcpHeader{
uint16_t sourcePort;
uint16_t destPort;
uint32_t seqNumber;
uint32_t ackNumber;
uint8_t headerLength;
uint8_t reserved;
uint8_t TCPFLAGS;
uint16_t window;
uint16_t checksum;
} tcpHeader;
int readTcp(const u_char* packet, tcpHeader* tcp){
tcp->sourcePort = my_ntohs(packet);
tcp->destPort = my_ntohs(packet + 2);
tcp->seqNumber = my_ntohl(packet + 4);
tcp->ackNumber = my_ntohl(packet + 8);
tcp->headerLength = packet[12]>>4;
tcp->reserved = my_ntohs(packet+12) & 0xFC0;
tcp->TCPFLAGS = my_ntohs(packet+12) & 0x3F;
tcp->window = my_ntohs(packet + 14);
tcp->checksum = my_ntohs(packet + 16);
return tcp->headerLength* 4;
}
void printTcp(tcpHeader* tcp){
printf("\t===== tcp header =====\n");
printf("\tsource port : %u\n", tcp->sourcePort);
printf("\tdest port : %u\n", tcp->destPort);
//printf("\tseq number : %u\n", tcp->seqNumber);
//printf("\tack number : %u\n", tcp->ackNumber);
}
#endif // TCPHELPER_H
|
C
|
/* output the sum of squares of numbers
filename: Ch5Ex6.c
ver 1.0
Alexandr Kravtsov */
#include <stdio.h>
int main()
{
int correct_enter;
int number = 0, sum = 0;
int limit;
printf("Enter limit(integer number): ");
correct_enter = scanf("%d", &limit);
if(correct_enter != 1) {
printf("Error enter. Exit...\n");
return 1;
}
while(number++ < limit)
sum += number*number;
printf("sum = %d\n", sum);
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
int f[20000000];
int
find_len(m)
{
int times = 0;
int n = m;
while (n>1)
{
if (f[n] != 0)
{
times += f[n];
return times;
}
if (n % 2 == 0)
n = n / 2;
else n= n * 3 + 1;
times++;
}
f[m] = times;
return(times);
}
int
main()
{
int max = 1, x = 0;
int now = 0, i;
for (i=0;i<1000000;i++)
f[i] = 0;
f[1] = 1;
for (i=1000; i>0;i--)
{
now = find_len(i);
if (max<now)
{
max = now;
x = i;
}
//printf("%d %d\n", i ,now);
}
printf("%d %d\n", x, max);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include<time.h>
/* [v L */
#define LOOP 10
/* Ԓl 0: not prime, 1: prime */
long int isPrimeFermat(long int);
long int input() {
long int val; char buf[100]={0};
printf("Tf͈̔͂߂ĉi)\n");
fgets(buf, 50, stdin);
sscanf(buf, "%ld", &val);
return val;
}
main() {
long int p = 0, flag = 0; /* flag=1 Ȃf */
float start,end;
// while(p <= 1) p = input();
scanf("%d",&p);
start=((float)clock())/CLOCKS_PER_SEC;
srand(p);
if(p == 2)
flag = 1;
else
flag = isPrimeFermat(p);
printf("p = %ld is %s.\n", p, flag ? "prime" : "not prime");
end=(((float)clock())/CLOCKS_PER_SEC)-start;
printf("oߎԁ%.5f\n",end);
}
/* |Z̕MZ */
long int calcMul(long int x, long int y, long int z) {
long int i, v = 0;
if(x < y) {i = x; x = y; y = i;}
if(y == 1) return x;
for(i = 31; i >= 0; i--) {
v = (v * 2) % z;
if((x >> i) % 2 == 1) v = (v + y) % z;
}
return v % z;
}
/* x^y mod z @ŋ߂ */
long int calcSqMul(long int x, long int y, long int z) {
long int i, v = 1;
for(i = 31; i >= 0; i--) {
v = calcMul(v, v, z);
if((y >> i) % 2 == 1) v = calcMul(v, x, z);
}
return v % z;
}
/* Fermat@ɂf */
long int isPrimeFermat(long int p) {
long int i;
for(i = 0; i < LOOP; i++) {
long int a = rand() % (p -2) +2, b = 1;
b = calcSqMul(a, p-1, p);
if(b % p != 1) return 0;
}
return 1;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <locale.h>
int comparacao(int num1,int num2){
if(num1<num2){
printf("\n\nO seu nmero menor que o nmero sorteado!");
return 1;
}
else if(num1>num2){
printf("\n\nO seu nmero maior que o nmero sorteado!");
return 1;
}
else{
return 0;
}
}
int main(void){
srand(time(NULL));
int i=1, jogador, numero, retorno;
setlocale(LC_ALL,"");
numero = rand() % 101;
printf("--Jogo de Adivinhao--");
printf("\nVoc tem 5 chances para acertar o nmero que foi sorteado entre 0 e 100!");
while(i<6){
if(i<6){
printf("\nEscolha um nmero(Entre 0 e 100): ");
scanf("%d",&jogador);
retorno = comparacao(jogador,numero);
}
if(retorno==1){
i++;
}
else{
printf("\nParabns, voc ganhou!");
return 0;
}
if(i==6){
printf("\n\nSinto muito, voc no acertou!");
}
}
}
|
C
|
#include <stdio.h>
int if_num_is_magic(int n){
int num = n;
while(n>0){
if(n%10 == 0)return 0;
if(num % (n%10) != 0)return 0;
n = n/10;
}
return 1;
}
int main(){
int num;
scanf("%d", &num);
printf("%d\n", if_num_is_magic(num));
return 0;
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* move.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: zhasni <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2015/03/01 23:12:31 by zhasni #+# #+# */
/* Updated: 2015/03/01 23:16:40 by zhasni ### ########.fr */
/* */
/* ************************************************************************** */
#include "../includes/game.h"
static void ft_init(t_env *env)
{
ft_add_in_tab(env);
env->score = 0;
env->move = 0;
}
static void ft_cpy_tab(t_env *env)
{
int x;
int y;
x = 0;
y = 0;
while (y < 4)
{
x = 0;
while (x < 4)
{
env->game_tab2[x][y] = env->game_tab[x][y];
x++;
}
y++;
}
}
static int ft_check_tab2(t_env *env)
{
int x;
int y;
x = 0;
y = 0;
while (y < 4)
{
x = 0;
while (x < 4)
{
if (env->game_tab2[x][y] == env->game_tab[x][y])
x++;
else
return (1);
}
y++;
}
return (0);
}
static int ft_check_tab3(t_env *env)
{
int x;
int y;
x = 0;
y = 0;
while (y < 4)
{
while (x < 4)
{
if (env->game_tab[x][y] > 0)
x++;
else
return (1);
}
x = 0;
y++;
}
return (0);
}
void ft_move(t_env *env, int ch)
{
ft_cpy_tab(env);
if (ft_check_tab3(env) == 0 && ft_loose(env) == 0)
env->loose = 1;
if (ch == 'w')
ft_move_up(env);
else if (ch == 'a')
ft_move_left(env);
else if (ch == 'd')
ft_move_right(env);
if (ch == 's')
ft_move_down(env);
if (ch == 'r')
ft_init(env);
if ((ch == 's' || ch == 'a' || ch == 'd' || ch == 'w') &&\
ft_check_tab2(env) == 1)
{
env->move++;
ft_add_in_tab2(env);
}
}
|
C
|
#include "estructuras_arbol.h"
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <stdio.h>
#include <stab.h>
#include <stdlib.h>
#include <sharksCommons/protocolo.h>
#include <sys/dir.h>
#include <dirent.h>
#include <aio.h>
#include <curses.h>
#include <ncurses.h>
int dato;
/*void main(void) {
int y, opc;
arbol* p_arbol;
do{
clear();
y = 10;
gotoxy(10, y++);
printf("0 - Salir \n");
gotoxy(10, y++);
printf("1 - Buscar \n");
gotoxy(10, y++);
printf("2 - Insertar \n");
gotoxy(10, y);
printf("3 - Borrar \n");
gotoxy(10, y += 5);
printf("Cual es su opcion: ");
getch();
scanf ("%d", &opc);
//fgets (opc, 2, stdin);
//opc = getch();
switch (opc) {
case 0:
break;
case 1:
printf("\n\nDato a buscar: ");
p_arbol->dato = getch();
scanf ("%d", &opc);
if (buscar())
printf("\n\nDato existe");
else
printf("\n\nDato inexistente");
break;
case 2:
printf("\n\nDato a insertar: ");
scanf ("%s", &p_arbol->dato);
p_arbol->dato = getch();
insertar();
printf("\n\nDato Insertado");
break;
case 3:
printf("\n\nDato a borrar: ");
p_arbol->dato = getch();
eliminar();
break;
default:
printf("\n\nOpcion incorrecta");
};
if (opc)
getch();
}while(opc);
}*/
void gotoxy(int x, int y){
printf("\033|[%d;%df",y,x);
}
int buscar(void) {
/*if (!cabecera) {
printf("No hay arbol");
return (0);
}
ant = NULL;
aux = cabecera;
while (aux) {
if (dato == aux->dato)
return (1);
else {
ant = aux;
if (dato > aux->dato)
aux = aux->d;
else
aux = aux->i;
}
}*/
return (0);
}
void insertar(void) {
if (!cabecera) {
cabecera = malloc(sizeof(arbol));
cabecera->dato = dato;
cabecera->d = NULL;
cabecera->i = NULL;
return;
}
if (!buscar()) {
aux = malloc(sizeof(arbol));
aux->dato = dato;
aux->i = NULL;
aux->d = NULL;
if (dato > ant->dato)
ant->d = aux->d;
else
ant->i = aux->i;
} else
printf("\n\nDato existente");
}
void buscarmenmay(void) {
aux2->d = aux->d;
ant2 = aux;
while (aux2->i) {
ant2 = aux2;
}
aux->dato = aux2->dato;
if (aux2->d)
ant2->i = aux2->d;
free(aux2);
ant2->d = NULL;
}
void buscarmaymen(void) {
aux2->i = aux->i;
ant2 = aux;
while (aux2->d) {
ant2 = aux2;
aux->d = aux2->d;
}
aux->dato = aux2->dato;
if (aux2->i)
ant2->d = aux2->i;
free(aux2);
ant2->i = NULL;
}
void eliminar(void) {
if (!buscar()) {
printf("\n\nElemento no encontrado.");
liberarA();
return;
}
if (aux->d == NULL && aux->i == NULL) {
if (ant->dato > dato)
ant->i = NULL;
else
ant->d = NULL;
free(aux);
} else if (aux->d != NULL)
buscarmenmay();
else
buscarmaymen();
printf("\n\nElemento Borrado");
}
void liberarA() {
free(cabecera->d);
//free(cabecera->dato);
free(cabecera->i);
free(cabecera);
free(aux->d);
//free(aux->dato);
free(aux->i);
free(aux);
//free(p_arbol->dato);
//free(p_arbol->d);
//free(p_arbol->i);
}
|
C
|
/*
* meansquarediff.c
* by Samuel Weaver (sweave05) and Ross Kamen (rkamen02)
* October 21, 2016
* HW 4
*
* The implementation of a function to compare two images.
*/
#include "meansquarediff.h"
#include <assert.h>
#include <math.h>
#include <stdlib.h>
/*
* closure structure
* used to carry information for the image difference calculation
*
* sum: running sum of square differences
* denom1: rgb denominator of image1
* denom2: rgb denominator of image2
* small_width: the smaller of the two image widths
* small_height: the smaller of the two image heights
* Pnm_ppm: the second image
*/
typedef struct closure {
float *sum;
unsigned *denom1;
unsigned *denom2;
unsigned *small_width;
unsigned *small_height;
Pnm_ppm *img2;
} *closure;
/*
* sumDiffs
* purp: an A2Methods_applyfun that is meant to be called on an
* and given a properly created and populated closure structure.
* Adds the squared differences of the pixels' rgb value to sum.
* Compares the pixel its on to the pixel at (x,y) in img2
* from clousre.
* args: (x,y) of *pix in array2, a UArray2 of rgb pixels.
* void *cl is a pointer to a closure structure that has been
* properly formatted and populated
* rets: void
*/
void sumDiffs( int x,
int y,
A2Methods_UArray2 array2,
A2Methods_Object *pix,
void *cl)
{
(void) array2;
unsigned width = *( ((closure)cl) -> small_width );
unsigned height = *( ((closure)cl) -> small_height );
/* If out of the bounds of either photo, do nothing */
if (( (unsigned)x >= width) || ( (unsigned)y >= height)) {
return;
}
struct Pnm_rgb *pix1 = (struct Pnm_rgb *)pix;
Pnm_ppm *img2 = ((closure)cl) -> img2;
A2Methods_T methods = (A2Methods_T)( (*img2) -> methods);
struct Pnm_rgb *pix2 = (*methods).at( (*img2) -> pixels, x, y);
float denom1 = *( ((closure)cl) -> denom1);
float denom2 = *( ((closure)cl) -> denom2);
/* scale the rbg values */
float r1 = pix1 -> red / denom1;
float r2 = pix2 -> red / denom2;
float g1 = pix1 -> green / denom1;
float g2 = pix2 -> green / denom2;
float b1 = pix1 -> blue / denom1;
float b2 = pix2 -> blue / denom2;
/* Add the sum of the squared differences in rgb values to sum */
( *((closure)cl) -> sum) += pow( r1 - r2, 2) +
pow( g1 - g2, 2) +
pow( b1 - b2, 2);
}
/*
* min
* purp: returns the minimum of the two given unsigned integers,
* CRE if either is NULL
* args: two unsigned integers
* rets: their minimum
*/
unsigned min( unsigned uint1, unsigned uint2)
{
assert( uint1 && uint2);
return uint1 < uint2 ? uint1 : uint2;
}
/*
* meanSquareDiff
* purp: calculate the difference between the two given Pnm_ppms using
* mean square difference. returns 1.0 if either of the widths
* or heights differ by more than 1. CRE if either width, height
* or denominator is not natural. CRE if either image is null.
* args: two Pnm_ppms
* rets: a float representation of the mean square difference between
* the two images
*/
float meanSquareDiff( Pnm_ppm image1, Pnm_ppm image2)
{
assert( image1 && image2);
unsigned small_width = min( (image1 -> width), (image2 -> width));
unsigned small_height = min( (image1 -> height), (image2 -> height));
assert( min( small_width, small_height) > 0);
assert( min( image1 -> denominator, image2 -> denominator) > 0);
int width_diff = (image1 -> width) - (image2 -> width);
int height_diff = (image1 -> height) - (image2 -> height);
closure cl;
float sum = 0;
A2Methods_T methods = (A2Methods_T)image1 -> methods;
if ( (abs(width_diff) > 1) || (abs(height_diff) > 1)) {
fprintf( stderr, "Images not of compatible sizes.\n");
return 1;
}
/* Create and populate the closure structure */
cl = malloc( sizeof(struct closure));
cl -> sum = ∑
cl -> small_width = &small_width;
cl -> small_height = &small_height;
cl -> denom1 = &(image1 -> denominator);
cl -> denom2 = &(image2 -> denominator);
cl -> img2 = &image2;
/*
* Run the mapping function to calculate the sum of
* squared differences
*/
methods -> map_default( image1 -> pixels, sumDiffs, cl);
/*
* closure structs exclusively hold pointers so we can free it
* and still have the value calculated with sumDiffs
*/
free( cl);
return sqrtf( sum / ((float)( small_width * small_height * 3)));
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "fnctl.h"
#include "ramdisk.h"
#include "vfs.h"
DISK disk = {
.dev_id = 0xFF,
.data = NULL,
.size = 0,
.write = writeRamdisk,
.read = readRamdisk,
.init = createRamdiskDevice,
.deinit = removeRamdiskDevice
};
int removeRamdiskDevice()
{
free(disk.data); //free disk
disk.data = NULL;
disk.size = 0;
}
int createRamdiskDevice(unsigned int diskSize)
{
if (disk.data == NULL) {
disk.data = (unsigned char *)malloc(diskSize); //Size in bytes
memset(disk.data, 0x00, diskSize);
printf("fat init\n");
} else {
printf("Ram disk allocated");
free(disk.data); //free disk
disk.data = (unsigned char *)malloc(diskSize); //Size in bytes
memset(disk.data, 0x00, diskSize);
}
return disk.dev_id;
}
int getRamDiskSize()
{
return disk.size;
}
int writeRamdisk(unsigned char *ptr, int offset, int size)
{
memcpy(disk.data + offset, ptr, size);
return size;
}
int readRamdisk(unsigned char *ptr, int offset, int size)
{
memcpy(ptr, disk.data + offset, size);
return size;
}
|
C
|
/**
* @file k210_gpio.c
* @brief
* @author sksat <[email protected]>
* @version 0.1
* @date 2020-08-15
*/
#include <assert.h>
#include <util/log.h>
#include <embox/unit.h>
#include <util/bit.h>
#include <util/array.h>
#include <drivers/gpio/gpio_driver.h>
#include <drivers/gpio/k210.h>
#include <drivers/gpio/k210/fpioa.h>
EMBOX_UNIT_INIT(k210_gpio_init);
#define K210_GPIO_CHIP_ID OPTION_GET(NUMBER,gpio_chip_id)
volatile k210_gpio_t* const gpio = (volatile k210_gpio_t*) K210_GPIO_BASE_ADDR;
extern volatile sysctl_clock_enable_central* const clk_en_cent;
extern volatile sysctl_clock_enable_peripheral* const clk_en_peri;
static struct gpio_chip k210_gpio_chip = {
.setup_mode = k210_gpio_setup_mode,
.get = k210_gpio_get,
.set = k210_gpio_set,
.nports = K210_GPIO_PORTS_COUNT
};
static int k210_gpio_setup_mode(unsigned char port, gpio_mask_t pins, int mode){
assert(port < K210_GPIO_PORTS_COUNT);
if(mode & GPIO_MODE_OUT) {
k210_gpio_set_dir(pins, 1);
} else if (mode & GPIO_MODE_IN){
log_error("GPIO input mode is not implemented");
return -1;
} else {
log_error("GPIO mode %x is not implemented", mode);
return -1;
}
return 0;
}
static void k210_gpio_set(unsigned char port, gpio_mask_t pins, char level){
volatile uint32_t *reg_dir = gpio->dir.reg32;
volatile uint32_t *reg = gpio->data_out.reg32;
uint32_t input = ~(*reg_dir);
assert(port < K210_GPIO_PORTS_COUNT);
// direction check
input = (uint32_t)pins & input;
if (input) {
log_error("input pin cannot set level: pin mask=%x, level=%d", input, level);
}
if (level == GPIO_PIN_HIGH) {
*reg &= ~(uint32_t)pins;
log_debug("gpio_set high: %x", pins);
} else if (level == GPIO_PIN_LOW){
*reg |= ((uint32_t)pins);
log_debug("gpio_set low: %x", pins);
} else {
log_error("unknown GPIO pin level");
}
log_debug("gpio_set result: %x", *reg);
}
static gpio_mask_t k210_gpio_get(unsigned char port, gpio_mask_t pins){
volatile uint32_t *reg_dir = gpio->dir.reg32;
gpio_mask_t res = 0;
assert(port < K210_GPIO_PORTS_COUNT);
uint32_t dir = *reg_dir;
int bit;
bit_foreach(bit, (uint32_t)pins){
uint32_t reg;
reg = (dir & (1 << bit)) ? gpio->data_out.reg32[0] : gpio->data_in.reg32[0];
log_debug("bit: %d dir: 0x%x reg: 0x%x", bit, dir, reg);
if (!(reg & (1 << bit))) {
res |= (1 << bit);
}
}
log_debug("state: %x", res);
return res;
}
static void maix_bit_gpio_config(void){
// builtin RGB LEDs
k210_fpioa_set_func(MAIXBIT_IO_LED_R, FN_GPIO0);
k210_fpioa_set_pull(MAIXBIT_IO_LED_R, FPIOA_PULL_DOWN);
k210_gpio_setup_mode(0, 1 << 0, GPIO_MODE_OUT);
k210_fpioa_set_func(MAIXBIT_IO_LED_G, FN_GPIO1);
k210_fpioa_set_pull(MAIXBIT_IO_LED_G, FPIOA_PULL_DOWN);
k210_gpio_setup_mode(0, 1 << 1, GPIO_MODE_OUT);
k210_fpioa_set_func(MAIXBIT_IO_LED_B, FN_GPIO2);
k210_fpioa_set_pull(MAIXBIT_IO_LED_B, FPIOA_PULL_DOWN);
k210_gpio_setup_mode(0, 1 << 2, GPIO_MODE_OUT);
// IO24
k210_fpioa_set_func(MAIXBIT_IO24, FN_GPIO3);
k210_fpioa_set_pull(MAIXBIT_IO24, FPIOA_PULL_DOWN);
k210_gpio_setup_mode(0, 1 << 3, GPIO_MODE_OUT);
/* we set up GPIO 0..3 to low level */
k210_gpio_set(0, 0x0F, GPIO_PIN_LOW);
}
static int k210_gpio_init(void){
//k210_fpioa_set_func(24, FN_GPIO3);
// enable bus clock
clk_en_cent->apb0 = 1;
// enable device clock
clk_en_peri->gpio = 1;
maix_bit_gpio_config();
return gpio_register_chip(&k210_gpio_chip, K210_GPIO_CHIP_ID);
}
void k210_gpio_set_dir(gpio_mask_t pins, bool dir){
volatile uint32_t *reg = gpio->dir.reg32;
if(dir) {
*reg |= (uint32_t)pins;
} else{
*reg &= ~((uint32_t)pins);
}
}
|
C
|
/* runp, runvp -- execute process and wait for it to exit
*
* Usage:
* i = runp (file, arg1, arg2, ..., argn, 0);
* i = runvp (file, arglist);
*
* Runp and runvp have argument lists exactly like the corresponding
* routines, execlp and execvp. The runp routines perform a fork, then:
* IN THE NEW PROCESS, an execlp or execvp is performed with the
* specified arguments. The process returns with a -1 code if the
* exec was not successful.
* IN THE PARENT PROCESS, the signals SIGQUIT and SIGINT are disabled,
* the process waits until the newly forked process exits, the
* signals are restored to their original status, and the return
* status of the process is analyzed.
* Runp and runvp return: -1 if the exec failed or if the child was
* terminated abnormally; otherwise, the exit code of the child is
* returned.
*
**********************************************************************
* HISTORY
* 22-Nov-85 Glenn Marcy (gm0w) at Carnegie-Mellon University
* Added check and kill if child process was stopped.
*
* 30-Apr-85 Steven Shafer (sas) at Carnegie-Mellon University
* Adapted to 4.2 BSD UNIX. Conforms to new signals and wait.
*
* 15-July-82 Mike Accetta (mja) and Neal Friedman (naf)
* at Carnegie-Mellon University
* Added a return(-1) if vfork fails. This should only happen
* if there are no more processes available.
*
* 28-Jan-80 Steven Shafer (sas) at Carnegie-Mellon University
* Added setuid and setgid for system programs' use.
*
* 21-Jan-80 Steven Shafer (sas) at Carnegie-Mellon University
* Changed fork to vfork.
*
* 20-Nov-79 Steven Shafer (sas) at Carnegie-Mellon University
* Created for VAX. The proper way to fork-and-execute a system
* program is now by "runvp" or "runp", with the program name
* (rather than an absolute pathname) as the first argument;
* that way, the "PATH" variable in the environment does the right
* thing. Too bad execvp and execlp (hence runvp and runp) don't
* accept a pathlist as an explicit argument.
*
**********************************************************************
*/
#include <stdio.h>
#include <signal.h>
#include <sys/wait.h>
int runp (name,argv)
char *name,*argv;
{
return (runvp (name,&argv));
}
int runvp (name,argv)
char *name,**argv;
{
int wpid;
register int pid;
struct sigvec ignoresig,intsig,quitsig;
union wait status;
if ((pid = fork()) == -1)
return(-1); /* no more process's, so exit with error */
if (pid == 0) { /* child process */
setgid (getgid());
setuid (getuid());
execvp (name,argv);
fprintf (stderr,"runp: can't exec %s\n",name);
_exit (0377);
}
ignoresig.sv_handler = SIG_IGN; /* ignore INT and QUIT signals */
ignoresig.sv_mask = 0;
ignoresig.sv_onstack = 0;
sigvec (SIGINT,&ignoresig,&intsig);
sigvec (SIGQUIT,&ignoresig,&quitsig);
do {
wpid = wait3 (&status.w_status, WUNTRACED, 0);
if (WIFSTOPPED (status)) {
kill (0,SIGTSTP);
wpid = 0;
}
} while (wpid != pid && wpid != -1);
sigvec (SIGINT,&intsig,0); /* restore signals */
sigvec (SIGQUIT,&quitsig,0);
if (WIFSIGNALED (status) || status.w_retcode == 0377)
return (-1);
return (status.w_retcode);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char key[50] = "\x79\x17\x46\x55\x10\x53\x5f\x5d\x55\x10\x58\x55\x42\x55\x10\x44\x5f\x3a";
void win(void)
{
system("/bin/sh");
}
void main(void)
{
char input[50];
fgets(input, sizeof(input) - 1, stdin);
if (strlen(input) == strlen(key)) {
for (int i = 0; i < strlen(key); i++) {
if ((input[i] ^ 0x30) != key[i]) {
exit(0);
}
}
system("/bin/sh");
}
}
|
C
|
#include<stdio.h>
#include "holberton.h"
/**
* print_to_98 - prints to 98 from n
* @n: starting point
*
* Description: prints from a starting point to 98
* in a cool way
* Return: void
*/
void print_to_98(int n)
{
while (n <= 98 || n >= 98)
{
if (n == 98)
{
printf("%d\n", n);
break;
}
printf("%d, ", n);
if (n < 98)
n++;
else
n--;
}
}
|
C
|
#include <stdio.h>
#include <windows.h>
/*
y = [435048], x = [43504C];
map = [434C21];
004051A6 CMP EAX,100; [esp+4] == WM_KEYDOWN
*/
int main() {
char soko[16][20];
int x,y; HWND target;
unsigned long proc_id; HANDLE souko;
int i = 0x434C20; char sokox, sokoy;
printf("Soukoban Teleporter v1.0 by BoR0\n written 25.05.2007 in 2 hours\n\
--------------------------------\n\n");
target = FindWindow(0, "Soukoban");
if (!target) {
printf("Unable to find window: \"Soukoban\".\n");
return 0;
}
GetWindowThreadProcessId(target, &proc_id);
souko = OpenProcess(PROCESS_ALL_ACCESS, FALSE, proc_id);
if (!souko) {
printf("Unable to gain privileges for application.\n");
return 0;
}
for (y=0;y<16;y++) for (x=0;x<20;x++)
ReadProcessMemory(souko, (LPVOID)i++, &soko[y][x], 1, 0);
ReadProcessMemory(souko, (LPVOID)0x435048, &sokoy, 1, 0);
ReadProcessMemory(souko, (LPVOID)0x43504C, &sokox, 1, 0);
soko[sokoy][sokox] = 6;
printf("Current map status:\n");
for (y=0;y<16;y++) {
for (x=0;x<20;x++)
if (soko[y][x] == 0) printf(" ");
else printf("%c", soko[y][x]+64);
printf("\n");
}
printf("Scheme:\nA = Wall\nB = Path\nC = Box destination\nD = Box\nE = Box on it's place\nF = \
Current location \n\nYour current location coords: (%d, %d)\nDo you want to change coords? [y/N] \
", sokox, sokoy);
scanf("%c", &sokoy);
if (sokoy == 'y' || sokoy == 'Y') {
printf("Enter new coords: \n");
scanf("%d%d", &x, &y);
if ((x > 19) || (x < 0) || (y > 15) || (y < 0)) {
printf("Invalid coordinates!\n");
goto done;
}
if (WriteProcessMemory(souko, (LPVOID)0x435048, &y, 1, 0) == 0 || \
WriteProcessMemory(souko, (LPVOID)0x43504C, &x, 1, 0) == 0)
printf("Error in writing to memory!");
else {
printf("Successfully written new coords (%d, %d)\n", x, y);
InvalidateRect(target, 0, 0);
}
}
done:
printf("All done.\n");
CloseHandle(souko);
return 0;
}
|
C
|
#pragma once
#define SORTED_VECTOR_INITIAL_CAPACITY 1
typedef unsigned int sortedVectorType;
typedef struct {
sortedVectorType *elements;
unsigned int size, capacity;
} sortedVector;
void sortedVectorCreate(sortedVector *vector);
void sortedVectorFree(sortedVector *vector);
void sortedVectorAddUnique(sortedVector *vector, sortedVectorType element);
void sortedVectorRemove(sortedVector *vector, sortedVectorType element);
unsigned int sortedVectorIndex(sortedVector *vector, sortedVectorType element);
|
C
|
/**************************************************************
* modul: system memory freeing routines
*
* copyright: Yafra.org
**************************************************************/
static char rcsid[]="$Header: /yafraorg/cvsroot/foundation/ansic/libs/pssys/source/free.c,v 1.1.1.1 2002-10-26 20:49:54 mwn Exp $";
/* system includes */
#include <stdio.h>
#include <stdlib.h>
/* piso includes */
#include <pssys.h>
/************************************************************
* free up memory
*
* free up memory at pointer aPtr
*
* returns nothing
*
* library: libpssys.a
*
* copyright: Yafra.org, Switzerland, 1994
*
* author: Administrator, 1994
**************************************************************/
void PSSYSfree(void *aPtr /* pointer for freeing memory */)
{
if (aPtr != NULL)
free(aPtr);
aPtr = NULL;
}
/************************************************************
* free up a memory object
*
* free up a memory object
*
* returns nothing
*
* library: libpssys.a
*
* copyright: Yafra.org, Switzerland, 1994
*
* author: Administrator, 1994
**************************************************************/
void PSSYSfreeobj(PSmemobj *aMemobj /* memory object to free */)
{
if (aMemobj->buffer != NULL)
free(aMemobj->buffer);
aMemobj->buffer = 0;
aMemobj->datalen = 0;
aMemobj->alloclen = 0;
}
/************************************************************
* free up a memory array with all it's pointer
*
* free up all elements in an dynamic allocated array
* and at last free up the array memory at pointer aPtr
*
* returns nothing
*
* library: libpssys.a
*
* copyright: Yafra.org, Switzerland, 1994
*
* author: Administrator, 1994
**************************************************************/
void PSSYSfreearray(char **aPtr, /* pointer of array to free */
int aArraysize /* count of elements in thist array */)
{
int i;
/*!!! on other than HP-UX bugy !!! */
/* free arrays */
for (i=0; i < aArraysize; i++)
{
if (aPtr[i] != NULL)
free((void *)aPtr[i]);
}
/* free pointer to arrays */
if (aPtr != NULL)
free((void *)aPtr);
}
|
C
|
// common.c -- Defines some global functions.
// From JamesM's kernel development tutorials.
#include "common.h"
// write a byte out to the specified port.
void outb(u8int value, u16int port) {
__asm__ __volatile__("outb %1, %0" : : "dN"(port), "a"(value));
}
// write a word (16 bit) out to the specified port.
void outw(u16int value, u16int port) {
__asm__ __volatile__("outw %1, %0" : : "dN"(port), "a"(value));
}
// "l" meaning long (32bits)
void outl(u32int value, u16int port) {
__asm__ __volatile__("outl %1, %0" : : "dN"(port), "a"(value));
}
// read a byte from the specified port.
u8int inb(u16int port) {
u8int ret;
__asm__ __volatile__("inb %1, %0" : "=a"(ret) : "dN"(port));
return ret;
}
// read a word from the specified port.
u16int inw(u16int port) {
u16int ret;
__asm__ __volatile__("inw %1, %0" : "=a"(ret) : "dN"(port));
return ret;
}
// read a word from the specified port.
u32int inl(u16int port) {
u32int ret;
__asm__ __volatile__("inl %1, %0" : "=a"(ret) : "dN"(port));
return ret;
}
// copy len bytes from src to dest.
void k_memcpy(u8int *dest, const u8int *src, u32int len) {
const u8int *sp = (const u8int *)src;
u8int *dp = (u8int *)dest;
for (; len != 0; len--) {
*dp++ = *sp++;
}
}
// write len copies of val into dest.
void k_memset(u8int *dest, u8int val, u32int len) {
u8int *temp = (u8int *)dest;
for (; len != 0; len--) {
*temp++ = val;
}
}
// compare two strings. Should return -1 if
// str1 < str2, 0 if they are equal or 1 otherwise.
int k_strcmp(char *str1, char *str2) {
int i = 0;
int failed = 0;
while (str1[i] != '\0' && str2[i] != '\0') {
if (str1[i] != str2[i]) {
failed = 1;
break;
}
i++;
}
// why did the loop exit?
if ((str1[i] == '\0' && str2[i] != '\0') ||
(str1[i] != '\0' && str2[i] == '\0')) {
failed = 1;
}
return failed;
}
// copy the NULL-terminated string src into dest, and
// return dest.
char *k_strcpy(char *dest, const char *src) {
do {
*dest++ = *src++;
} while (*src != 0);
}
// concatenate the NULL-terminated string src onto
// the end of dest, and return dest.
char *k_strcat(char *dest, const char *src) {
while (*dest != 0) {
*dest = *dest++;
}
do {
*dest++ = *src++;
} while (*src != 0);
return dest;
}
// clear the screen and initialize VIDEO, XPOS and YPOS.
void k_cls(void) {
int i;
video = (unsigned char *)VIDEO;
for (i = 0; i < COLUMNS * LINES * 2; i++)
*(video + i) = 0;
xpos = 0;
ypos = 0;
}
// Convert the integer D to a string and save the string in BUF. If
// BASE is equal to 'd', interpret that D is decimal, and if BASE is
// equal to 'x', interpret that D is hexadecimal.
void k_itoa(char *buf, int base, int d) {
char *p = buf;
char *p1, *p2;
unsigned long ud = d;
int divisor = 10;
// If %d is specified and D is minus, put `-' in the head.
if (base == 'd' && d < 0) {
*p++ = '-';
buf++;
ud = -d;
} else if (base == 'x') {
divisor = 16;
}
// Divide UD by DIVISOR until UD == 0.
do {
int remainder = ud % divisor;
*p++ = (remainder < 10) ? remainder + '0' : remainder + 'a' - 10;
} while (ud /= divisor);
// Terminate BUF.
*p = 0;
// Reverse BUF.
p1 = buf;
p2 = p - 1;
while (p1 < p2) {
char tmp = *p1;
*p1 = *p2;
*p2 = tmp;
p1++;
p2--;
}
}
// Put the character C on the screen.
void k_putchar(int c) {
if (c == '\n' || c == '\r') {
newline:
xpos = 0;
ypos++;
if (ypos >= LINES)
ypos = 0;
return;
}
*(video + (xpos + ypos * COLUMNS) * 2) = c & 0xFF;
*(video + (xpos + ypos * COLUMNS) * 2 + 1) = ATTRIBUTE;
xpos++;
if (xpos >= COLUMNS)
goto newline;
}
// Format a string and print it on the screen, just like the libc
// function printf.
//
// Does not support float or double.
//
// Is buggy when using more than one format specifier in the same format
// string.
//
void k_printf(const char *format, ...) {
vga_index += 80;
char **arg = (char **)&format;
int c;
char buf[20];
arg++;
while ((c = *format++) != 0) {
if (c != '%') {
k_putchar(c);
} else {
char *p;
// read next character
c = *format++;
switch (c) {
// all numerics
case 'd':
case 'u':
case 'x':
// encode the current argument into the buffer
k_itoa(buf, c, *((int *)arg++));
p = buf;
goto string;
break;
case 's':
p = *arg++;
if (!p)
p = "(null)";
string:
// output a string
while (*p) {
k_putchar(*p++);
}
break;
default:
k_putchar(*((int *)arg++));
break;
}
}
}
}
void k_clear_screen(void) {
int index = 0;
// there are 25 lines each of 80 columns; each element takes 2 bytes
while (index < 80 * 25 * 2) {
terminal_buffer[index] = ' ';
index += 2;
}
}
void k_print_string(char *str, unsigned char color) {
int index = 0;
while (str[index]) {
terminal_buffer[vga_index] =
(unsigned short)str[index] | (unsigned short)color << 8;
index++;
vga_index++;
}
}
void k_print_float(float data) {
char int_part_buf[20];
for (int i = 0; i < 20; i++) {
int_part_buf[i] = 0;
}
char fraction_part_buf[20];
for (int i = 0; i < 20; i++) {
fraction_part_buf[i] = 0;
}
int int_part = (int)data;
float temp = data - (float)int_part;
unsigned int max_fractions = 3;
while ((temp - (int)temp) > 0.0f && max_fractions > 0) {
temp *= 10.0f;
max_fractions--;
}
int float_part = temp;
// printf("int %d frac %d\n", int_part, float_part);
k_itoa(int_part_buf, 10, int_part);
k_itoa(fraction_part_buf, 10, float_part);
// printf("int_part_buf %s\n", int_part_buf);
// printf("fraction_part_buf %s\n", fraction_part_buf);
char total_buf[41];
int total_buf_index = 0;
for (int i = 0; i < 41; i++) {
total_buf[i] = 0;
}
// printf("inserting int part\n");
// insert the integral part of the floating point number into the full array
for (int i = 0; i < 20; i++) {
if (int_part_buf[i] == 0) {
continue;
}
total_buf[total_buf_index] = int_part_buf[i];
total_buf_index++;
}
// printf("inserting dot\n");
total_buf[total_buf_index] = '.';
total_buf_index++;
// printf("inserting frac part\n");
// insert the fractional part of the floating point number into the full array
for (int i = 0; i < 20; i++) {
if (fraction_part_buf[i] == 0) {
continue;
}
total_buf[total_buf_index] = fraction_part_buf[i];
total_buf_index++;
}
// printf("output total_buf_index %d\n", total_buf_index);
// printf("float %s\n", total_buf);
// k_putchar segfaults during mockito tests because it accesses video memory
// which is off limits for cmockito user space applications on modern linux
// systems with paging enabled!
for (int i = 0; i <= total_buf_index; i++) {
k_putchar(total_buf[i]);
}
}
extern void panic(const char *message, const char *file, u32int line) {
// We encountered a massive problem and have to stop.
__asm__ __volatile__("cli"); // Disable interrupts.
k_printf("PANIC(");
k_printf("%s", message);
k_printf(") at ");
k_printf("%s", file);
k_printf(":");
k_printf("%d", line);
k_printf("\n");
// Halt by going into an infinite loop.
for (;;)
;
}
|
C
|
/*
En la fotocopiadora de docentes de la facultad, cada vez que un
profesor retira copias, se registra el código de departamento , la cantidad de copias doble
faz y la cantidad de copias simple faz . La lista se elabora por cada uno de los veinte días
laborables del mes.
Suponer que hay sólo tres departamentos, identificados cada uno con ódigos tipo caracter:
‘M’: Matemática, ‘F’: Física y ‘R’: Representación gráfica.
Cuando termina la actividad de un día, se ingresa un código de departamento igual a @.
Al finalizar cada día , se desea saber:
1) El total de fotocopias realizadas en cada departamento (tener en cuenta que cada
fotocopia doble faz equivale a dos fotocopias).
2) El total de fotocopias realizadas doble faz y simple faz, y la cantidad de hojas utilizadas en
ese día.
Al finalizar los 20 días laborables , se deberá informar:
1) El total de fotocopias realizadas en el mes en cada departamento.
2) La cantidad de hojas utilizadas en el mes.
3) En qué día se realizaron más fotocopias y dicha cantidad. Considerar que no existe más de
un departamento con el mismo valor máximo.
*/
/*
PSEUDOCODIGO
Algoritmo: Registro_Fotocopias_Departamentos
Variables
Enteros: M_simples, F_simples, R_simples, M_dobles, F_dobles, R_dobles, simples, dobles, i,
M_total_dia, F_total_dia, R_total_dia, total_simples_dia, total_dobles_dia, hojas_dia,
M_total_mes, F_total_mes, R_total_mes, hojas_mes, total_fotocopias_dia, max, dia
Caracter: depto
Inicio
i <- 1
M_total_mes <- 0
F_total_mes <- 0
R_total_mes <- 0
hojas_mes <- 0
Repetir Mientras (i<=20) hacer
M_simples <-0
F_simples <- 0
R_simples <- 0
M_dobles <- 0
F_dobles <- 0
R_dobles <- 0
M_total_dia <- 0
F_total_dia <- 0
R_total_dia <- 0
total_simples_dia <- 0
total_dobles_dia <- 0
total_fotocopias_dia <- 0
hojas_dia <- 0
Escribir("Dia ", i)
Escribir("Ingrese el departamento que realiza las fotocopias: ")
Leer (depto)
Repetir Mientras (depto <> "@") hacer
Escribir("Ingrese la cantidad de copias doble faz")
Leer(dobles)
Escribir("Ingrese la cantidad de copias simple faz")
Leer(simples)
Segun Sea (depto)
'M': M_simples <- M_simples + simples
M_dobles <- M_dobles + dobles
'F': F_simples <- F_simples + simples
F_dobles <- F_dobles + dobles
'R': R_simples <- R_simples + simples
R_dobles <- R_dobles + dobles
Sino
Escribir("ERROR. Por favor ingrese M, F o R.")
Fin Segun
Escribir("Ingrese el departamento que realiza copias: ")
Leer(depto)
Fin Mientras
Escribir("Usted ha terminado de ingresar las copias del dia",i)
Escribir("Estos son los datos del dia",i)
M_total_dia <- 2*M_dobles + M_simples
F_total_dia <- 2*F_dobles + F_simples
R_total_dia <- 2*R_dobles + R_simples
Escribir("Total de fotocopias realizadas por el departamento de Matematica: ",M_total_dia)
Escribir("Total de fotocopias realizadas por el departamento de Fisica: ",F_total_dia)
Escribir("Total de fotocopias realizadas por el departamento de Sist. de Representacion: ",R_total_dia)
total_simples_dia <- M_simples + F_simples + R_simples
total_dobles_dia <- M_dobles + F_dobles + R_dobles
hojas_dia <- total_dobles_dia + total_simples_dia
Escribir("Total de fotocopias simple faz realizadas: ",total_simples_dia)
Escribir("Total de fotocopias doble faz realizadas: ",2*total_dobles_dia)
Escribir("La cantidad de hojas utilizadas en el dia es: ", hojas_dia, "hojas")
M_total_mes <- M_total_mes + M_total_dia
F_total_mes <- F_total_mes + F_total_dia
R_total_mes <- R_total_mes + R_total_dia
hojas_mes <- hojas_mes + hojas_dia
total_fotocopias_dia <- 2*total_dobles_dia + total_simples_dia
Si(i=1) Entonces
max <- total_fotocopias_dia
dia <- i
Sino
Si(max<total_fotocopias_dia) Entonces
max <- total_fotocopias_dia
dia <- i
Fin Si
Fin Si
i++;
Fin Mientras
Escribir("Ha finalizado el mes. Estos son los datos del mes:")
Escribir("Total de fotocopias realizadas en el mes por departamento:")
Escribir("Matematica: ", M_total_mes)
Escribir("Fisica: ", F_total_mes)
Escribir("Sistemas de Representacion: ", R_total_mes)
Escribir("La cantidad de hojas utilizadas en el mes: ", hojas_mes)
Escribir("El dia", dia, "del mes se realizaron", max,"fotocopias, siendo el dia donde mas fotocopias se realizaron.")
Fin
*/
#include<stdio.h>
//#include<stdlib.h>
//#include<conio.h>
main(){
int M_simples, F_simples, R_simples, M_dobles, F_dobles, R_dobles, simples, dobles, i;
int M_total_dia, F_total_dia, R_total_dia, total_simples_dia, total_dobles_dia, hojas_dia;
int M_total_mes, F_total_mes, R_total_mes, hojas_mes, total_fotocopias_dia, max, dia;
char depto;
i=1;
/// Reinicio contadores para el mes:
M_total_mes=0;
F_total_mes=0;
R_total_mes=0;
hojas_mes=0;
while(i<=20){
/// Reinicio contadores para el dia:
M_simples=0;
F_simples=0;
R_simples=0;
M_dobles=0;
F_dobles=0;
R_dobles=0;
M_total_dia=0;
F_total_dia=0;
R_total_dia=0;
total_simples_dia=0;
total_dobles_dia=0;
total_fotocopias_dia=0;
hojas_dia=0;
printf("\n\tDia %i:",i);
printf("\n\tIngrese el departamento que realiza las fotocopias: ");
scanf(" %c", &depto);
while(depto!='@'){
printf("\n\tIngrese la cantidad de copias doble faz (depto %c): ",depto);
scanf("%i", &dobles);
printf("\n\tIngrese la cantidad de copias simple faz (depto %c): ",depto);
scanf("%i", &simples);
printf("\n\tPresione cualquier tecla para continuar...");
getch(); ///Cosas amigables al usuario (:
system("cls");
switch (depto){
case 'M':
M_simples+= simples;
M_dobles+= dobles;
break;
case 'F':
F_simples+= simples;
F_dobles+= dobles;
break;
case 'R':
R_simples+= simples;
R_dobles+= dobles;
break;
default:
printf("\n\tERROR. Por favor ingrese M, F o R.");
}
printf("\n\tIngrese el departamento que realiza copias: ");
scanf(" %c", &depto);
}
printf("\n\tUsted ha terminado de ingresar las copias del dia %i.\n\n\tEstos son los datos del dia %i:",i,i);
M_total_dia= 2*M_dobles+M_simples;
F_total_dia= 2*F_dobles+F_simples;
R_total_dia= 2*R_dobles+R_simples;
printf("\n\tTotal de fotocopias realizadas por el departamento de Matematica: %i",M_total_dia);
printf("\n\tTotal de fotocopias realizadas por el departamento de Fisica: %i",F_total_dia);
printf("\n\tTotal de fotocopias realizadas por el departamento de Sist. de Representacion: %i",R_total_dia);
total_simples_dia= M_simples + F_simples + R_simples;
total_dobles_dia= M_dobles + F_dobles + R_dobles;
hojas_dia= total_dobles_dia + total_simples_dia;
printf("\n\tTotal de fotocopias simple faz realizadas: %i",total_simples_dia);
printf("\n\tTotal de fotocopias doble faz realizadas: %i",2*total_dobles_dia);
printf("\n\tLa cantidad de hojas utilizadas en el dia es: %i hojas", hojas_dia);
printf("\n\tPresione cualquier tecla para continuar...");
getch(); ///Cosas amigables al usuario (:
system("cls");
/// Preparo datos para el mes:
M_total_mes+= M_total_dia;
F_total_mes+= F_total_dia;
R_total_mes+= R_total_dia;
hojas_mes+= hojas_dia;
///DIA CON MAXIMA CANTIDAD DE FOTOCOPIAS
total_fotocopias_dia= 2*total_dobles_dia + total_simples_dia;
if(i==1){
max= total_fotocopias_dia;
dia= i;
}else{
if(max<total_fotocopias_dia){
max= total_fotocopias_dia;
dia= i;
}
}
i++;
}
printf("\n\tHa finalizado el mes. Estos son los datos del mes: ");
printf("\n\tTotal de fotocopias realizadas en el mes por departamento:");
printf("\n\tMatematica: %i", M_total_mes);
printf("\n\tFisica: %i", F_total_mes);
printf("\n\tSistemas de Representacion: %i", R_total_mes);
printf("\n\tLa cantidad de hojas utilizadas en el mes: %i", hojas_mes);
printf("\n\tEl dia %i del mes se realizaron %i fotocopias, siendo el dia donde mas fotocopias se realizaron.", dia, max);
return 0;
}
|
C
|
//https://blog.csdn.net/k1ang/article/details/80397173
/*
* Copyright reserved. <== Correct
* file
* author
* date
* version
*/
#include "sdk_hc595.h"
static void DelayTime(void)
{
for (uint16_t t=5; t>0; t--);
}
static void GPIO_WRITE(uint16_t hc595_Pin, uint8_t val)
{
if(!val)
{
HAL_GPIO_WritePin(HC595_PORT, hc595_Pin, GPIO_PIN_RESET);
}
else
{
HAL_GPIO_WritePin(HC595_PORT, hc595_Pin, GPIO_PIN_SET);
}
}
static void HC595_shcp(uint8_t val)
{
GPIO_WRITE(HC595_SHCP_PIN, val);
}
static void HC595_stcp(uint8_t val)
{
GPIO_WRITE(HC595_STCP_PIN, val);
}
static void HC595_data(uint8_t val)
{
GPIO_WRITE(HC595_DATA_PIN, val);
}
static void HC595_cs(void)
{
/*** 3STCPһأλĴȫ洢Ĵ ***/
HC595_stcp(0);
DelayTime();
HC595_stcp(1);
}
static void HC595_Send(uint32_t val)
{
uint32_t data = val;
uint32_t data_bit = HC595_BIT;
for(uint32_t i=0; i<data_bit; i++)
{
/*** 1ݴDSţжҪ͵λ10Ȼ595 DSӵ͵ƽ ***/
if(data & 0x80000000)
{
HC595_data(1);
}
else
{
HC595_data(0);
}
/*** 2SHCPÿһأǰbitͱλĴ ***/
HC595_shcp(0);
DelayTime();
HC595_shcp(1);
DelayTime();
data <<= 1; //һλλλƣͨif(data & 0x80000000)жϵλǷΪ1
}
}
void ExtHC595_Send(uint32_t val)
{
HC595_Send(val);
HC595_cs();
}
void ExtHC595_Init(void)
{
// GPIO_SetFunc(HC595_SHCP_PIN, 0);
// GPIO_SetDir(HC595_SHCP_PIN, 1);
//
// GPIO_SetFunc(HC595_STCP_PIN, 0);
// GPIO_SetDir(HC595_STCP_PIN, 1);
//
// GPIO_SetFunc(HC595_DATA_PIN, 0);
// GPIO_SetDir(HC595_DATA_PIN, 1);
//
// GPIO_SetFunc(HC595_MR_PIN, 0);
// GPIO_SetDir(HC595_MR_PIN, 1);
// GPIO_WRITE(HC595_MR_PIN, 1);
//
// GPIO_SetFunc(HC595_OE_PIN, 0);
// GPIO_SetDir(HC595_OE_PIN, 1);
// GPIO_WRITE(HC595_OE_PIN, 0);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <limits.h>
#include <unistd.h>
#include <pthread.h>
struct Queue{
int front, rear, size;
int capacity;
int *array;
};
/* Function to create a queue with a given capacity.
* starts with a size of queue as 0
*/
struct Queue *createQueue(int capacity){
struct Queue *queue = (struct Queue*) malloc(sizeof(struct Queue));
queue->capacity = capacity;
queue->front = queue->size = 0;
queue->rear = capacity - 1;
queue->array = (int*) malloc(queue->capacity * sizeof(int));
return queue;
}
// Queue is full when size becomes equal to the capacity
int isFull(struct Queue *queue){
return (queue->size == queue->capacity);
}
// Queue is empty when size is 0
int isEmpty(struct Queue *queue){
if(queue==NULL){
return INT_MIN;
}
return (queue->size == 0);
}
/* Function to add an item to the queue.
* changes rear and size
*/
void enqueue(struct Queue *queue, int item){
if (isFull(queue)){
printf("customer %d leaves with a long shaggy mop of hair!\n", item);
return;
}
queue->rear = (queue->rear + 1)%queue->capacity;
queue->array[queue->rear] = item;
queue->size = queue->size + 1;
printf("customer %d is waiting for a haircut\n", item);
}
/* Function to remove an item from queue.
* changes front and size
*/
int dequeue(struct Queue *queue){
if(queue==NULL){
return INT_MIN;
}
if (isEmpty(queue)){
return INT_MIN;
}
int item = queue->array[queue->front];
queue->front = (queue->front + 1)%queue->capacity;
queue->size = queue->size - 1;
return item;
}
// Function to get front of queue
int front(struct Queue *queue){
if (isEmpty(queue)){
return INT_MIN;
}
return queue->array[queue->front];
}
// Function to get rear of queue
int rear(struct Queue *queue){
if (isEmpty(queue)){
return INT_MIN;
}
return queue->array[queue->rear];
}
static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
struct thread_args{
struct Queue * queue;
int barber_f;
int haircut_time;
};
void * barber(void * argp){
struct thread_args *args = argp;
struct Queue * queue = args->queue;
int flag = args->barber_f;
int haircut_time = args->haircut_time;
int s;
if(!isEmpty(queue)){
// if(flag==0){
flag = 1;
pthread_mutex_lock(&mutex);
s = dequeue(queue);
pthread_mutex_unlock(&mutex);
if(s>0){ //meaning dequeue did not fail
printf("customer %d is styling a fresh haircut :)\n", s);
}
sleep(haircut_time);
flag = 0;
// }
}else{
flag = 0;
}
//return 0;
}
void customer(struct Queue * customers, int barber_flag, struct thread_args *args, int id, int end_time, int cust_freq, int haircut_time){
if(barber_flag==0){
enqueue(customers, id);
args->queue = customers;
args->barber_f = barber_flag;
args->haircut_time = haircut_time;
barber(args);
}else{
enqueue(customers, id);
}
sleep(cust_freq);
}
int main(int argc, char* argv[]){
if(argc!=7){
printf("Please enter -c -n -s");
return 0;
}
int wr_cnum; //number of chairs in the waiting room
int cust_freq;//how often a customer arrives
int end_time; //how long the program will run for
sscanf(&argv[1][3], "%i", &wr_cnum);
sscanf(&argv[2][5], "%i", &cust_freq);
sscanf(&argv[3][8], "%i", &end_time);
int barber_chairs[3]; //array of barber chairs, will take on 1 occupied and 0 as not occupied
memset(barber_chairs, 0, sizeof(barber_chairs));
int barber_flag = 0; //flag to check if barber is asleep. 0 if free 1 if occupied
int wr_chairs[wr_cnum]; //array of waiting room chairs, will take on the id's of the customers
memset(wr_chairs, 0, sizeof(wr_chairs));
int haircut_time; //length of haircut (5-7s)
srand(time(NULL));
int cap = wr_cnum;
struct Queue *customers = createQueue(cap); //will take on customer id
struct thread_args *args = malloc(sizeof *args);
if(args==NULL){
printf("Error allocating memory");
return 0;
}
pthread_t thread1;
pthread_t thread2;
pthread_t thread3;
pthread_create(&thread1, NULL, &barber, args);
pthread_create(&thread2, NULL, &barber, args);
pthread_create(&thread3, NULL, &barber, args);
time_t endwait;
time_t start = time(NULL);
time_t seconds = end_time;
endwait = start + seconds;
int id = 0;
while(start < endwait){
cust_freq = rand() % (cust_freq + 1);
haircut_time = rand() % (7 + 1 - 5) + 5;
args->queue = customers;
args->barber_f = barber_flag;
args->haircut_time = haircut_time;
barber(args);
endwait = endwait-haircut_time;
sleep(cust_freq);
endwait-=cust_freq;
enqueue(customers, id++);
//customer(customers, barber_flag, args, id++, end_time, cust_freq, haircut_time);
start = time(NULL);
}
pthread_join(thread1, NULL);
pthread_join(thread2, NULL);
pthread_join(thread3, NULL);
pthread_mutex_destroy(&mutex);
free(args);
return 0;
}
|
C
|
#define T_DIR 1 // Directory
#define T_FILE 2 // File
#define T_DEV 3 // Device
struct stat {
short type; // Type of file
int dev; // File system's disk device
uint ino; // Inode number
short nlink; // Number of links to file
uint size; // Size of file in bytes
uint second;
uint minute;
uint hour;
uint day;
uint month;
uint year;
};
|
C
|
#include <stdio.h>
#include <netdb.h>
#include <sys/socket.h>
#include <strings.h>
#include <string.h>
#include <unistd.h>
int main(){
struct sockaddr_in serverAddress;
serverAddress.sin_family = AF_INET; //IPv4
serverAddress.sin_port = htons(2727); //Los primeros 1024 puertos requieren privilegios de administrador
serverAddress.sin_addr.s_addr = htonl(INADDR_ANY); //Cualquier IP que tenga asignada la máquina, podría haber varias
int sockfd = socket(AF_INET, SOCK_STREAM, 0); //Crear socket, TCP
bind(sockfd,(const struct sockaddr *)&serverAddress,sizeof(serverAddress)); //Avisa al sistema operativo de mandarle las solicitudes que lleguen a ese puerto
listen(sockfd,5); //listen al socket, número máximo de clientes
while(1){
struct sockaddr_in clientAddress;
int clientSize = sizeof( clientAddress); //ciclo visto en clase (accept, read/write, close)
int clientSocket = accept(sockfd, (struct sockaddr *)&clientAddress,(unsigned int*) &clientSize); //duerme al servidor hasta que se conecte un cliente
char c;
char *message = "HTTP/1.1 200 OK\r\nContent-Type: text/html; charset=ISO-8859-1\n\n Hello desde gitpod";
write(clientSocket,message,strlen(message));
close(clientSocket);
}
}
|
C
|
//RESUMOS
//Least Recently Used (LRU) page replacement algorithm works on the concept that the pages that are heavily used in previous instructions are likely
//to be used heavily in next instructions. And the page that are used very less are likely to be used less in future. Whenever a page fault occurs,
//the page that is least recently used is removed from the memory frames. Page fault occurs when a referenced page in not found in the memory frames.
#include <stdio.h>
#include <stdlib.h>
/*************************/
// Struct noh da fila que tem sucessor e antecessor.
// O tamanho máximo da fila será o tamanho do cache.
// As páginas usadas mais recentemente estarão próximas da extremidade inicial.
// As páginas usadas menos recentemente estarão próximas da extremidade final.
typedef struct QNode
{
struct QNode *prev;
struct QNode *next;
unsigned pageNumber; //Numero da pagina
} QNode;
// A propria fila pra auxiliar ao pegar o primeiro e ultimo e o numero total e totalaté agora além de hits e miss
//Ela eh diferente, pois as alterações sao feitas ao contrario. Quem sai eh o fim da fila e quem entra eh no inicio da fila, caso a fila esteja cheia
typedef struct Queue
{
unsigned count;
unsigned numberOfFrames;
unsigned hit;
unsigned miss;
QNode *front, *rear;
} Queue;
//Structure que representa a tabelha hash que ira ser as paginas
//No hash o número da página sera a chave e endereço do nó da fila correspondente eh o valor da hash.
typedef struct Hash
{
int capacity; // Total de paginas
QNode* *array; // Cada pagina tem um array que representa a posicao da memoria
} Hash;
/** Funcoes utilitarias para criacao, remocao e outras utilidades de filas e hash**/
//Cria um novo no e retorna ele
QNode* newQNode( unsigned pageNumber )
{
// Aloca memoria para criar o noh
QNode* temp = (QNode *)malloc( sizeof( QNode ) );
temp->pageNumber = pageNumber; //numero da pagina
// Initialize prev and next as NULL
//No criado sem estar anexado a ninguem
temp->next = NULL;
temp->prev = temp->next;
return temp;
}
//Cria a fila e retorna ela
Queue* createQueue( int numberOfFrames )
{
printf("CRIANDO PAGINACAO FISICA...\n");
//Aloca memoria para criar a fila
Queue* queue = (Queue *)malloc( sizeof( Queue ) );
// A fila eh criada vazia sem miss e hit
queue->count = 0;
queue->hit = 0;
queue->miss = 0;
queue->front = queue->rear = NULL;
// Numero total de frames por paginas
queue->numberOfFrames = numberOfFrames;
printf("PAGINACAO CRIADA...\n\n\n");
return queue;
}
//Cria a hash e retorna ela
Hash* createHash( int capacity )
{
printf("CRIANDO PAGINACAO VIRTUAL...\n");
// Aloca memoria para a hash
Hash* hash = (Hash *) malloc( sizeof( Hash ) );
//Tamanho total da hash ou seja o total de paginas
hash->capacity = capacity;
// Crea o array que representa os fremas de cada pagina
hash->array = (QNode **) malloc( hash->capacity * sizeof( QNode* ) );
// Inicializa a hash vazia
for( int i = 0; i < hash->capacity; ++i ) hash->array[i] = NULL;
printf("PAGINACAO CRIADA...\n\n\n");
return hash;
}
//print da fila
void printQueue(Queue* q) {
struct QNode*ptr = q->front;
//start from the beginning
if(ptr == NULL) printf("FILA VAZIA..\n");
while(ptr != NULL) {
printf("|%d|",ptr->pageNumber);
ptr = ptr->next;
if(ptr!= NULL) printf("<==");
}
printf("\n");
}
//Verifica se a fila esta vazia
int isQueueEmpty( Queue* queue )
{
return queue->rear == NULL;
}
//Remove o utlimo elemento da fila
void deQueue( Queue* queue )
{
//Um elemento só pode ser deletado quando houver pelo menos um elemento para deletar
if( isQueueEmpty( queue ) ) return; //fila vazia n faz nada so retorna
// Se ela eh o unico elemento remove o front dela e coloca null e isto faz a fila ficar vazia novamente sem front e rear
if (queue->front == queue->rear) queue->front = NULL;
// Criar um noh temporario para salvar o ultimo elemento da fila
QNode* temp = queue->rear;
//Retorna quem vem antes dele na fila e coloca no final, teoricamente eh feito um shift removendo o
queue->rear = queue->rear->prev;
//Como removeu o "rabo" anterior tem q colocar um novo e tromover o ponteiro para o anterior
if (queue->rear)
queue->rear->next = NULL;
//liberar o no criado, ou seja matou o antigo rabo
free( temp );
// como tirou 1 da fila eh decrementado
queue->count--;
}
// Verifica se o frame esta cheio para remover o rabo
int AreAllFramesFull( Queue* queue )
{
return queue->count == queue->numberOfFrames;
}
// Adicionar um novo elemento a fila
void Enqueue( Queue* queue, Hash* hash, unsigned pageNumber )
{
printf("\n\n\nAdicionando novo elemento,%d, na memoria fisica...\n",pageNumber);
printQueue(queue);
//Fila cheia
// Fila cheia remove o "rabo"
if ( AreAllFramesFull ( queue ) )
{
printf("Fila cheia... Removendo o ultimo elemento: %d\n", queue->rear->pageNumber);
// remove page from hash
hash->array[ queue->rear->pageNumber ] = NULL;
deQueue( queue );
printQueue(queue);
}
// Cria um novo no para adicionar na frente
QNode* temp = newQNode( pageNumber );
temp->next = queue->front;
// Fila vazia
//o rabo e o inicio ambos estao apontando para um mesmo local
if ( isQueueEmpty( queue ) ){
printf("Fila vazia...\n");
queue->front = temp;
queue->rear = queue->front;
printQueue(queue);
}
else // Caso a fila nao esteja vazia eh só adicionar no incio e teoricamente dar um shift em todos os restos
{
printf("Adicionando novo elemento, %d, no inicio da fila\n",pageNumber);
queue->front->prev = temp;
queue->front = temp;
printQueue(queue);
}
// Adicionar a nova entrada ao hash
printf("Adicionando valor, %d, na memoria virtual...\n", temp->pageNumber);
hash->array[ pageNumber ] = temp;
// Adicionou mais um? Aumenta a conta
queue->count++;
}
/**Fim das funções utilitarias**/
/**Funcoes para o LRU**/
// Se Frame não está lá na memória, trazemos na memória e adicionamos na frente da fila - miss
// O frame está lá na memória, nós movemos o frame para frente da fila - hit
// Sempre movos para o inicio da fila, assim temos que desvincular este no da sua posição para movermos para o inicio da fila
void ReferencePage( Queue* queue, Hash* hash, unsigned pageNumber )
{
printf("\n\nNova pagina de no. %d requisitada...\n",pageNumber);
//Cria um noh para representar a pagina requisitada
QNode* reqPage = hash->array[ pageNumber ];
// Miss, pois a page nao esta e ele vai buscar
if ( reqPage == NULL ){
//Teve um miss na queue
printf("\nMiss da pagina %d\n", pageNumber);
queue->miss++;
//Vai colocar na fila, mas usa os algoritmos para verificar que esta cheio ou nao, como já foi explicado
Enqueue( queue, hash, pageNumber );
}
//Hit
else if (reqPage != queue->front)
{
//Teve um hit na queue
printf("\nHIT da pagina %d\n", pageNumber);
queue->hit++;
//Desvincular a página solicitada de sua localização atual na fila.
//Nesses dois comandos ele apenas tira da fila o noh requisitado
printf("Fila antes...\n");
printQueue(queue);
printf("Removenda a pagina %d da posicao atual q eh entre: %d",pageNumber,reqPage->prev->pageNumber);
reqPage->prev->next = reqPage->next;
if (reqPage->next) {
printf(" e %d\n",reqPage->next->pageNumber);
reqPage->next->prev = reqPage->prev;
}
else{
printf(" e NULL\n");
}
printQueue(queue);
printf("Colocando a pagina %d no inicio...\n",pageNumber);
// Caso esse no seja o ultimo vai para o inicio
if (reqPage == queue->rear)
{
queue->rear = reqPage->prev;
queue->rear->next = NULL;
}
// Colocando o no no inicio do noh inicial
reqPage->next = queue->front;
reqPage->prev = NULL;
// Faz com que o antigo primeiro agr aponte para o novo primeiro
reqPage->next->prev = reqPage;
// modifica a front para a pagina requisitada
queue->front = reqPage;
printf("Pagina %d agora no inicio...\n",pageNumber);
printQueue(queue);
}
}
/**Fim das funcoes para trabalhar com LRU**/
//When a page is referenced, the required page may be in the memory. If it is in the memory, we need to detach the node of the list and bring it to
//the front of the queue.
//If the required page is not in the memory, we bring that in memory. In simple words, we add a new node to the front of the queue and update the
//corresponding node address in the hash. If the queue is full, i.e. all the frames are full, we remove a node from the rear of queue, and add the new
//node to the front of queue.
/**Funcao main onde sera chamado as paginas ja preditas**/
int alreadSeq()
{
// Memoria fisica com 8 paginas
//frame = block of consecutive physical memory
Queue* q = createQueue( 8 );
// Memoria virtual com 16 paginas ( 0 a 9)
//page = block of consecutive virtual memory
Hash* hash = createHash( 16 );
//p1
ReferencePage( q, hash, 1);
ReferencePage( q, hash, 2);
ReferencePage( q, hash, 4);
ReferencePage( q, hash, 3);
//p2
ReferencePage( q, hash, 1);
ReferencePage( q, hash, 2);
ReferencePage( q, hash, 5);
ReferencePage( q, hash, 6);
//p3
ReferencePage( q, hash, 2);
ReferencePage( q, hash, 9);
ReferencePage( q, hash, 4);
ReferencePage( q, hash, 5);
//p4
ReferencePage( q, hash, 8);
ReferencePage( q, hash, 7);
ReferencePage( q, hash, 8);
ReferencePage( q, hash, 9);
// So os prints
printf("\n\n\nFINALMENTE TEMOS...\n");
printQueue(q);
printf("Total de hits : %d\n", q->hit);
printf("Total de miss : %d\n", q->miss);
}
int main(){
randomSeq();
return 0;
}
|
C
|
#include <signal.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <opencv/cv.h>
#include <mapper/mapper.h>
#include <xdo.h>
#include <lo/lo.h>
#define MAX_NOPOSITION 30
#define CLICK_SPEED 5
#define CLICK_LENGTH 5
#define MARKER_SIZE 128
#define WIDTH 1024.f
#define HEIGHT 768.f
int gIsRunning;
/*************/
typedef void state_on_enter_handler(void** state, void* from, void* user_data);
typedef void state_on_leave_handler(void** state, void* to, void* user_data);
typedef struct
{
char* name;
state_on_enter_handler* enter;
state_on_leave_handler* leave;
int nbr;
char** signals;
void** states;
} State_t;
State_t* state_new(char* name)
{
State_t* state = (State_t*)malloc(sizeof(State_t));
state->name = name;
state->enter = NULL;
state->leave = NULL;
state->nbr = 0;
state->signals = (char**)malloc(sizeof(char*));
state->states = (void**)malloc(sizeof(State_t*));
}
State_t* state_free(State_t* state)
{
free(state->signals);
free(state->states);
free(state);
}
void state_add_signal(State_t* state, char* signal, State_t* output_state)
{
if (state == NULL || signal == NULL || output_state == NULL)
return;
state->signals = (char**)realloc(state->signals, (state->nbr + 2) * sizeof(char*));
state->signals[state->nbr] = signal;
state->states = (void**)realloc(state->states, (state->nbr + 2) * sizeof(void*));
state->states[state->nbr] = (void*)output_state;
state->nbr++;
}
void state_set_enter_handler(State_t* state, state_on_enter_handler* handler)
{
if (state == NULL || handler == NULL)
return;
state->enter = handler;
}
void state_set_leave_handler(State_t* state, state_on_leave_handler* handler)
{
if (state == NULL || handler == NULL)
return;
state->leave = handler;
}
void state_send_signal(State_t** state, char* signal, void* user_data)
{
if (state == NULL || signal == NULL)
return;
State_t* st = *state;
for (int i = 0; i < st->nbr; ++i)
{
if (strcmp(signal, st->signals[i]) == 0)
{
State_t* destination = st->states[i];
if (st->leave != NULL)
st->leave((void**)&st, destination, user_data);
if (((State_t*)st->states[i])->enter != NULL)
((State_t*)st->states[i])->enter((void**)&destination, st, user_data);
*state = destination;
return;
}
}
}
/*************/
typedef struct
{
xdo_t* display;
float x, y;
int contact;
int updated;
} Data_t;
typedef struct
{
int set;
float x, y;
} Calib_t;
/*************/
void on_enter_move(void** state, void* from, void* user_data)
{
State_t* curr = *(State_t**)state;
State_t* prev = (State_t*)from;
Data_t* data = user_data;
xdo_mousemove(data->display, data->x, data->y, 0);
}
/*************/
void on_enter_click(void** state, void* from, void* user_data)
{
State_t* curr = *(State_t**)state;
State_t* prev = (State_t*)from;
Data_t* data = user_data;
static int frames = 0;
if (strcmp(prev->name, "move") == 0)
{
xdo_mousemove(data->display, data->x, data->y, 0);
frames = 0;
}
else if (strcmp(prev->name, "click") == 0)
{
xdo_mousemove(data->display, data->x, data->y, 0);
frames++;
if (frames == CLICK_SPEED)
xdo_mousedown(data->display, CURRENTWINDOW, 1);
}
}
/*************/
void on_leave_click(void** state, void* to, void* user_data)
{
State_t* curr = *(State_t**)state;
State_t* next = (State_t*)to;
Data_t* data = user_data;
if (strcmp(next->name, "click") != 0)
xdo_mouseup(data->display, CURRENTWINDOW, 1);
}
/*************/
State_t* init_state_machine()
{
State_t* root = state_new("root");
State_t* click = state_new("click");
State_t* move = state_new("move");
state_set_enter_handler(click, on_enter_click);
state_set_leave_handler(click, on_leave_click);
state_add_signal(root, "position", move);
state_add_signal(move, "contact", click);
state_add_signal(move, "no_position", root);
state_add_signal(click, "position", move);
state_add_signal(click, "contact", click);
state_add_signal(click, "no_position", root);
return root;
}
/*************/
void free_state_machine(State_t* root)
{
}
/*************/
void mousemsg_handler(mapper_signal msig, mapper_db_signal props, int instance_id, void *value, int count, mapper_timetag_t* tt)
{
Data_t* data = (Data_t*)props->user_data;
int x, y, contact;
x = ((float*)value)[1];
y = ((float*)value)[2];
contact = ((float*)value)[5];
data->x = x;
data->y = y;
data->contact = contact;
data->updated = 1;
}
/*************/
void calibmsg_handler(mapper_signal msig, mapper_db_signal props, int instance_id, void* value, int count, mapper_timetag_t* tt)
{
Calib_t* calib = (Calib_t*)props->user_data;
int id, x, y;
id = ((float*)value)[0];
x = ((float*)value)[1];
y = ((float*)value)[2];
if (id < 4)
{
calib[id].set = 1;
calib[id].x = x;
calib[id].y = y;
}
}
/*************/
void oscErrorHandler(int num, const char* msg, const char* path)
{
printf("Liblo server error: %s\n", msg);
}
/*************/
int oscMouseHandler(const char* path, const char* types, lo_arg** argv, int argc, void* data, void* user_data)
{
if (argc != 6)
{
printf("%s - Received message seems to be wrongly formed\n", __FUNCTION__);
return -1;
}
float values[5];
for (int i = 0; i < argc; ++i)
{
if (types[i] == 'f')
values[i] = argv[i]->f;
else if (types[i] == 'i')
values[i] = argv[i]->i;
else if (types[i] == 'd')
values[i] = argv[i]->d;
else
{
printf("%s - Received something which is not a number\n", __FUNCTION__);
return -1;
}
}
Data_t* mouseData = (Data_t*)user_data;
if (values[0] != 0)
return 1;
int x, y, contact;
x = values[1];
y = values[2];
contact = values[5];
mouseData->x = x;
mouseData->y = y;
mouseData->contact = contact;
mouseData->updated = 1;
}
/*************/
int oscCalibrationHandler(const char* path, const char* types, lo_arg** argv, int argc, void* data, void* user_data)
{
if (argc != 4)
{
printf("%s - Received message seems to be wrongly formed\n", __FUNCTION__);
return -1;
}
float values[4];
for (int i = 0; i < argc; ++i)
{
if (types[i] == 'f')
values[i] = argv[i]->f;
else if (types[i] == 'i')
values[i] = argv[i]->i;
else if (types[i] == 'd')
values[i] = argv[i]->d;
else
{
printf("%s - Received something which is not a number\n", __FUNCTION__);
return -1;
}
}
Calib_t* calib = (Calib_t*)user_data;
int id, x, y;
id = values[0];
x = values[1];
y = values[2];
if (id < 4)
{
calib[id].set = 1;
calib[id].x = x;
calib[id].y = y;
}
}
/*************/
void leave(int sig)
{
gIsRunning = 0;
}
/*************/
int main(int argc, char** argv)
{
(void) signal(SIGINT, leave);
int msgLength = 4;
int useOSC = 0;
if (argc > 1)
{
if (strcmp(argv[1], "--osc") == 0)
useOSC = 1;
else
msgLength = atoi(argv[1]);
}
State_t* root = init_state_machine();
State_t* current = root;
xdo_t* xdo_display = xdo_new(NULL);
Data_t data;
data.display = xdo_display;
data.x = 0.f;
data.y = 0.f;
data.contact = 0;
data.updated = 0;
Calib_t calib[4];
for (int i = 0; i < 4; ++i)
calib[i].set = 0;
// libmapper objects
mapper_device receiver = NULL;
mapper_signal sigMouse = NULL, sigCalib = NULL;
// liblo objects
lo_server_thread oscServer = NULL;
if (useOSC == 0)
{
receiver = mdev_new("oscToMouse", 9700, 0);
sigMouse = mdev_add_input(receiver, "/mouse", 6, 'f', 0, 0, 0, mousemsg_handler, &data);
sigCalib = mdev_add_input(receiver, "/calibration", 4, 'f', 0, 0, 0, calibmsg_handler, &calib);
}
else if (useOSC == 1)
{
oscServer = lo_server_new("9000", oscErrorHandler);
if (oscServer == NULL)
{
printf("%s - Error while creating liblo server\n", __FUNCTION__);
return 0;
}
lo_server_add_method(oscServer, "/blobserver/depthtouch", NULL, oscMouseHandler, &data);
lo_server_add_method(oscServer, "/blobserver/fiducialtracker", NULL, oscCalibrationHandler, &calib);
}
gIsRunning = 1;
CvMat* perspectiveMatrix = NULL;
int isCalibrated = 0;
int noPosition = 0;
while(gIsRunning)
{
if (useOSC == 0)
mdev_poll(receiver, 25);
else if (useOSC == 1)
lo_server_recv(oscServer);
int value;
int allSet = 1;
for (int i = 0; i < 4; ++i)
{
if (calib[i].set)
printf("%i - %f %f\n", i, calib[i].x, calib[i].y);
else
allSet = 0;
}
if (allSet && !isCalibrated)
{
CvPoint2D32f points[4];
for (int i = 0; i < 4; ++i)
{
points[i].x = calib[i].x;
points[i].y = calib[i].y;
}
CvPoint2D32f outPoints[4];
outPoints[0].x = MARKER_SIZE;
outPoints[0].y = MARKER_SIZE;
outPoints[1].x = WIDTH - MARKER_SIZE;
outPoints[1].y = MARKER_SIZE;
outPoints[2].x = MARKER_SIZE;
outPoints[2].y = HEIGHT - MARKER_SIZE;
outPoints[3].x = WIDTH - MARKER_SIZE;
outPoints[3].y = HEIGHT - MARKER_SIZE;
perspectiveMatrix = cvCreateMat(3, 3, CV_64F);
cvGetPerspectiveTransform(points, outPoints, perspectiveMatrix);
isCalibrated = 1;
}
else if (isCalibrated && data.updated)
{
CvMat* p = cvCreateMat(1, 1, CV_64FC2);
CvMat* h = cvCreateMat(1, 1, CV_64FC2);
CvScalar currentPos;
currentPos.val[0] = data.x;
currentPos.val[1] = data.y;
cvSet2D(p, 0, 0, currentPos);
cvPerspectiveTransform(p, h, perspectiveMatrix);
currentPos = cvGet2D(h, 0, 0);
if (currentPos.val[0] > 0.f && currentPos.val[0] < WIDTH)
data.x = currentPos.val[0];
else
data.x = WIDTH / 2.f;
if (currentPos.val[1] > 0.f && currentPos.val[1] < HEIGHT)
data.y = currentPos.val[1];
else
data.y = HEIGHT / 2.f;
printf("--- %f %f\n", currentPos.val[0], currentPos.val[1]);
if (data.contact)
state_send_signal(¤t, "contact", &data);
else if (data.updated)
state_send_signal(¤t, "position", &data);
if (data.updated)
xdo_mousemove(data.display, data.x, data.y, 0);
data.updated = 0;
noPosition = 0;
}
else
{
noPosition++;
if (noPosition >= MAX_NOPOSITION)
{
state_send_signal(¤t, "no_position", &data);
noPosition = MAX_NOPOSITION;
}
}
printf("%f %f - %i - %s\n", data.x, data.y, data.contact, current->name);
}
free_state_machine(root);
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* parse_texture.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: fmehdaou <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2020/12/01 20:51:28 by fmehdaou #+# #+# */
/* Updated: 2020/12/01 20:54:20 by fmehdaou ### ########.fr */
/* */
/* ************************************************************************** */
#include "../../header/cub3d.h"
int null_text(char *path)
{
return ((path != NULL));
}
int pngend(char *png)
{
int len;
len = ft_strlen(png) - 1;
return (png[len] == 'm'
&& png[len - 1] == 'p'
&& png[len - 2] == 'x'
&& png[len - 3] == '.');
}
char *ft_each_texture(char *path, t_cub3d *cub)
{
int len;
int fd;
if (null_text(path))
ft_errors(g_micub_err[DUP_LINE], g_micub_err[TEXTURE]);
if (cub->getl.spaces > 0)
ft_errors(g_micub_err[NOSPACESNEEDED], g_micub_err[TEXTURE]);
len = ft_len(cub->getl.newline);
if (len != 2)
ft_errors(g_micub_err[NUM_ARG], g_micub_err[TEXTURE]);
else if ((fd = open(cub->getl.newline[1], O_RDONLY)) == -1)
ft_errors(g_micub_err[INVALID_PATH], g_micub_err[TEXTURE]);
path = ft_strdup(cub->getl.newline[1]);
if (!pngend(path))
ft_errors(g_micub_err[EXTENSION], g_micub_err[MAP_FILE]);
return (path);
}
void ft_textures(t_cub3d *cub)
{
int len;
int fd;
cub->getl.newline = ft_split(cub->getl.line, ' ');
if (ft_strcmp(cub->getl.newline[0], "NO") == 0)
cub->tex.north = ft_each_texture(cub->tex.north, cub);
else if (ft_strcmp(cub->getl.newline[0], "SO") == 0)
cub->tex.south = ft_each_texture(cub->tex.south, cub);
else if (ft_strcmp(cub->getl.newline[0], "WE") == 0)
cub->tex.west = ft_each_texture(cub->tex.west, cub);
else if (ft_strcmp(cub->getl.newline[0], "EA") == 0)
cub->tex.east = ft_each_texture(cub->tex.east, cub);
else if (ft_strcmp(cub->getl.newline[0], "S") == 0)
cub->tex.sprite = ft_each_texture(cub->tex.sprite, cub);
else
ft_errors(g_micub_err[INVALID_LINE], g_micub_err[TEXTURE]);
ft_free(cub->getl.newline);
}
|
C
|
// Sameh Shahin ew20b001
#include <stdio.h>
// prototypes
void read_input_array(int l, int arr[l][l]);
void calculate_output_matrix(int l, int arr_output[l][l], int arr1[l][l], int arr2[l][l]);
void print_result_matrix(int l, int arr_output[l][l]);
int main()
{
int array_length = 0;
int input_matrix_1[50][50];
int input_matrix_2[50][50];
// read input Matrices length
scanf("%d", &array_length);
// read input Matrices
read_input_array(array_length, input_matrix_1);
read_input_array(array_length, input_matrix_2);
// define and calculate output matrix
int output_matrix[array_length][array_length];
calculate_output_matrix(array_length, output_matrix, input_matrix_1, input_matrix_2);
// print output matrix
print_result_matrix(array_length, output_matrix);
return 0;
}
//****** Procedures ******//
// loop to read every array position value based on it's size (square so row = cols = array_length);
void read_input_array(int l, int arr[l][l])
{
// j col, r rows, l array lenght
for (int r = 0; r < l; r++)
{
for (int c = 0; c < l; c++)
{
// read array values (space & enter will just skip to the next loop iteration! .. perfect)
scanf("%d", &arr[r][c]);
}
}
}
// calculates the sum of 2 given square arrays and puts the result in a third array
void calculate_output_matrix(int l, int arr_output[l][l], int arr1[l][l], int arr2[l][l])
{
int sum = 0;
for (int r = 0; r < l; r++)
{ // output rows loop
for (int c = 0; c < l; c++)
{ //output cols loop
//reset sum
sum = 0;
for (int i = 0; i < l; i++)
{ // calc sum loop
sum += arr1[r][i] * arr2[i][c];
}
arr_output[r][c] = sum;
}
}
}
// prints a given array based on it's size in a rows/cols manner
void print_result_matrix(int l, int arr_output[l][l])
{
for (int r = 0; r < l; r++)
{ // output rows loop
for (int c = 0; c < l; c++)
{ //output cols loop
printf("%3d", arr_output[r][c]);
}
printf("\n");
}
}
//****** end Procedures ******//
|
C
|
/* Author: Chris Bradley (635 847)
* Contact: [email protected] */
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include "list.h"
// Private function! Here instead of header.
node_t *get_node_for(list_t *list, void *data);
/* Creates a new list of size zero and returns a pointer
* to it.
*
* Returns a pointer to list_t, a new list. */
list_t *list_new()
{
list_t *list = malloc(sizeof(*list));
list->head = list->foot = NULL;
list->node_count = 0;
return list;
}
/* Destroys a list! The list is only responsible for it's own
* memory. If there are any complex structs inside data then
* they won't be freed...luckily I'm not using any of those :D
*
* list: List we're destroying. */
void list_destroy(list_t *list)
{
node_t *cur = list->head;
while (list->head != NULL) {
cur = list->head;
list->head = cur->next;
free(cur->data);
free(cur);
}
free(list);
}
/* Adds an item onto the list at the end. Useful if
* FIFO behavior is required.
*
* list: List to append to
* data: Data to append to the list. Can be anything! */
void list_push(list_t *list, void *data)
{
node_t *node = malloc(sizeof(*node));
node->data = data;
node->next = NULL;
if (list->head == NULL)
list->head = list->foot = node;
else
{
list->foot->next = node;
list->foot = node;
}
list->node_count++;
}
/* Inserts into the given list using a specific ordering
* as specified in a given comparison function.
*
* list: List to insert into
* data: Item to insert into list
* cmp: Function to used to keep ordering in list */
void list_insert(list_t *list, void *data, cmp_func cmp)
{
node_t *new, *cur, *pre;
new = malloc(sizeof(*new));
assert(new != NULL);
new->data = data;
new->next = NULL;
// We've inserted an item! Acknowledge that.
list->node_count++;
// If the list is empty then just insert at the top
if (list->head == NULL) {
list->head = list->foot = new;
return;
}
// If the list is not empty then search until the cmp function is -1,
// in other words search until the item we have is larger than the
// items already in the list.
pre = NULL;
cur = list->head;
while (cur != NULL && cmp(data, cur->data) == 1) {
pre = cur;
cur = cur->next;
}
if (pre == NULL) {
// Item is at start of list
list->head = new;
new->next = cur;
} else if(cur == NULL) {
// Item is at end of list
pre->next = new;
list->foot = new;
} else {
// Item is between two other items.
pre->next = new;
new->next = cur;
}
}
/* Remove the first item from the head of the list and return it.
* If the list is empty then return NULL.
*
* list: List to pop from */
void *list_pop(list_t *list)
{
void *res;
// Could cause a crash here, but let caller handle it.
if (list_is_empty(list))
return NULL;
// Return the current item and set head to be
// the next item
node_t *next = list->head->next;
res = list->head->data;
// Free the node but don't free the data, we need the data!
// We just fetched it! No seriously. What sort of genius
// would even code that free in the first place...whoops
//free(list->head->data);
free(list->head);
list->head = next;
list->node_count--;
return res;
}
/* Executes a function using the data stored at each element in the
* list. Useful for print functions!
* list: List to interate over
* list_with: Function to iterate with. Executes for each data in list. */
void list_for_each(list_t *list, iter_func list_with)
{
node_t *cur = list->head;
assert(cur != NULL);
do {
list_with(cur->data);
} while((cur = cur->next));
}
/* Seek to modify items in the the list by comparing them to a specified
* item (data) using a specified function (modify). Can modify more than
* one item, if modification of any item succeeds we tell the caller.
*
* list: List to modify
* data: Item to compare against
* modify: Function that modifies given list items
*
* Return 1 if any item is modified, else 0. */
int list_modify(list_t *list, void *data, modify_func modify)
{
int success = 0;
node_t *cur = list->head;
assert(cur != NULL);
do {
if(modify(list, cur->data, data))
success = 1;
} while((cur = cur->next));
return success;
}
/* Iterates over a list and compares all values against an (optional) static
* value using the specified match function, and also compares values against
* the current best value using the specified select function.
*
* list: List to iterate over
* data: Static data to compare against (Optional)
* match: Function to use when comparing to data (Optional)
* select: Function to use when comparing to best selected value so far
*
* Returns pointer to the data of value which best matches given criteria. */
void *list_select(list_t *list, void *data, match_func match, select_func sel)
{
void *res = NULL;
node_t *cur = list->head;
assert(cur != NULL);
do {
// Might not want to always compare to a static value,
// This data and match may be NULL. If so ignore them.
if (match == NULL || match(cur->data, data))
res = sel(res, cur->data);
} while ((cur = cur->next));
return res;
}
/* Similar to list_select however it starts iterating from any item that is
* a match to the given start item. Iteration will then cover all items in the
* list and wrap around again. All items will be covered, it's just the start
* point is modified.
*
* list: Item to select from
* start: Data value where iteration should start from
* data: Static data to compare against. (Optional)
* match: Function to use to compare to static data. (Optional)
* sel: Function to use when comparing against best selected item so far.
*
* Returns a pointer to the selected item. */
void *list_select_from(list_t *list, void *start, void *data, match_func match, select_func sel)
{
void *res = NULL;
node_t *cur = NULL;
int first_iter = 1;
if (list_is_empty(list))
return NULL;
// If no start point was specified start from the beginning.
if (start == NULL)
cur = list->head;
else
{
// Start from given start point
cur = get_node_for(list,start);
// Want to cover the whole list even if don't start at start.
// Set foot->next to head to make a loop
list->foot->next = list->head;
}
assert(cur != NULL);
do {
// If we reach the start point again then break
if (start != NULL && !first_iter && cur->data == start)
break;
first_iter = 0;
// Might not want to always compare to a static value,
// This data and match may be NULL. If so ignore them.
if (match == NULL || match(cur->data, data))
res = sel(res, cur->data);
} while ((cur = cur->next));
// Reset foot->next to NULL to break infinite loop we made to
// cover all items earlier.
list->foot->next = NULL;
return res;
}
/* Get the list node associated with a particular piece of data.
* INTERNAL USE ONLY.
* list: List to fetch node from
* data: Data point to be present in list
*
* Returns a pointer to the node where the data is present at.
* If not present then return NULL. */
node_t *get_node_for(list_t *list, void *data)
{
node_t *cur = list->head;
assert(cur != NULL);
do {
if (cur->data == data)
return cur;
} while ((cur = cur->next));
return NULL;
}
/* Remove an item from the list that corresponds to the given data value
*
* list: List to remove from
* data: item to remove. */
void list_remove(list_t *list, void *data)
{
node_t *pre = NULL;
node_t *cur = list->head;
assert(cur != NULL);
do {
if (cur->data == data)
{
// Keep the count accurate.
list->node_count--;
// If item is not at head then update previous item,
// else update head of list.
if (pre != NULL)
pre->next = cur->next;
else
list->head = cur->next;
// If item is at the end of the list then update the foot
if (cur->next == NULL)
{
list->foot = pre;
// This should usually run. list->foot will
// only be NULL if list is empty.
if (list->foot != NULL)
list->foot->next = NULL;
}
return;
}
pre = cur;
} while((cur = cur->next));
}
/* Function to 'reduce' a list down to one value. Inspired by using
* reduce when learning ruby! Total is directly written into accum
* rather than returned.
*
* list: List to reduce
* accum: Variable to accumulate list items into
* reduce: Function to use while accumulating. */
void list_reduce(list_t *list, void *accum, reduce_func reduce)
{
node_t *cur = list->head;
assert(cur != NULL);
do {
reduce(accum, cur->data);
} while ((cur = cur->next));
}
/* Get the item in the list that occurs after a given item.
* Note: Returns data and not node_t itself, gotta keep that
* encapsulation.
*
* list: List to iterate over
* data: Item we're searching for...to get the next item
*
* Returns a pointer to the next item, or NULL if there is no next. */
void *list_get_next(list_t *list, void *data)
{
node_t *cur = list->head;
assert(cur != NULL);
do {
if(cur->data == data && cur->next)
return cur->next->data;
} while((cur = cur->next));
return NULL;
}
/* Check if a given list is empty (no nodes) or not.
*
* list: List to check
*
* Returns 1 if list is empty or 0 if it contains at least 1 item. */
int list_is_empty(list_t *list)
{
return list->node_count == 0;
}
|
C
|
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <assert.h>
#include "item.h"
#include "utils.h"
typedef struct shelf shelf_t;
// -------------------------------
// Structs & Enums
// -------------------------------
typedef struct shelf {
char *name;
int amount;
} shelf_t;
struct item {
char *name;
char *desc;
int cost;
list_t *shelves;
};
// -------------------------------
// Declarations
// -------------------------------
static shelf_t *shelf_new(char *name, int amount);
// static void shelf_delete(obj elem);
static shelf_t *get_shelf(list_t *shelves, char *shelf_name, int *shelf_index);
static bool count_shelves_amount(obj elem, void *data);
static void item_destructor(obj object);
static void shelf_destructor(obj object);
// -------------------------------
// Public
// -------------------------------
item_t *item_new() {
item_t *item = allocate(sizeof(item_t), item_destructor);
if (item) {
item->shelves = list_new(NULL, NULL, NULL);
retain(item->shelves);
}
return item;
}
item_t *item_copy(item_t *item) {
item_t *copy = item_new();
if (item) {
copy->name = string_duplicate(item->name);
copy->desc = string_duplicate(item->desc);
copy->cost = item->cost;
retain(copy->name);
retain(copy->desc);
list_t *shelves_orig = item->shelves;
for (int i = 0; i < list_length(shelves_orig); i++) {
obj elem;
if (list_get(shelves_orig, i, &elem)) {
shelf_t *shelf_orig = elem;
char *name = shelf_orig->name;
int amount = shelf_orig->amount;
shelf_t *shelf_copy = shelf_new(name, amount);
list_prepend(copy->shelves, shelf_copy);
}
}
}
return copy;
}
int item_total(item_t *item) {
int total = 0;
if (item) {
list_apply(item->shelves, count_shelves_amount, &total);
}
return total;
}
bool item_set_name(item_t *item, char *name) {
if (item && strlen(name) > 0) {
if (item->name) release(item->name);
item->name = string_duplicate(name);
retain(item->name);
return true;
}
return false;
}
char *item_get_name(item_t *item) {
if (item) {
return item->name;
}
return NULL;
}
bool item_set_desc(item_t *item, char *desc) {
if (strlen(desc) > 0) {
if (item->desc) release(item->desc);
item->desc = string_duplicate(desc);
retain(item->desc);
return true;
}
return false;
}
char *item_get_desc(item_t *item) {
if (item) {
return item->desc;
}
return NULL;
}
bool item_set_cost(item_t *item, int cost) {
if (item && cost >= 0) {
item->cost = cost;
return true;
}
return false;
}
int item_get_cost(item_t *item) {
if (item && item) {
return item->cost;
}
return 0;
}
void item_set_shelves(item_t *item, char *shelf_name, int amount, bool overwrite) {
if (item && shelf_name && strlen(shelf_name) > 0) {
int index = -1;
list_t *shelves = item->shelves;
shelf_t *shelf = get_shelf(shelves, shelf_name, &index);
if (shelf == NULL) {
if (amount > 0) {
shelf = shelf_new(shelf_name, amount);
list_prepend(shelves, shelf);
}
} else {
if (amount > 0) {
shelf->amount = (overwrite) ? amount : shelf->amount + amount;
} else {
list_remove(shelves, index, true);
}
}
}
}
int item_total_amount(item_t *item) {
int amount = 0;
if (item) {
list_t *shelves = item->shelves;
int size = list_length(shelves);
for (int i = 0; i < size; i++) {
obj elem;
if (list_get(shelves, i, &elem)) {
shelf_t *shelf = elem;
amount = amount + shelf->amount;
}
}
}
return amount;
}
bool item_has_shelves(item_t *item) {
if (item) {
int size = list_length(item->shelves);
return size > 0;
}
return false;
}
bool item_has_shelf(item_t *item, char *shelf) {
if (item) {
list_t *shelves = item->shelves;
if (get_shelf(shelves, shelf, NULL) != NULL) {
return true;
}
}
return false;
}
bool item_apply_on_shelves(item_t *item, item_shelf_apply_fun fun, void *data) {
bool result = false;
if (item) {
list_t *shelves = item->shelves;
int size = list_length(shelves);
for (int index = 0; index < size; index++) {
obj elem;
if (list_get(shelves, index, &elem)) {
shelf_t *shelf = elem;
char *name = shelf->name;
int amount = shelf->amount;
if (shelf && fun(name, amount, data)) {
result = true;
}
}
}
}
return result;
}
int item_number_of_shelves(item_t *item) {
if (item) {
return list_length(item->shelves);
}
return 0;
}
char **item_get_shelves(item_t *item) {
if (item) {
int size = list_length(item->shelves);
char **shelves = allocate_array(size, sizeof(char *), NULL);
for (int i = 0; i < size; i++) {
obj elem;
if (list_get(item->shelves, i, &elem)) {
shelf_t *shelf = elem;
shelves[i] = shelf->name;
}
}
return shelves;
}
return NULL;
}
// -------------------------------
// Private
// -------------------------------
static shelf_t *shelf_new(char *name, int amount) {
shelf_t *shelf = allocate(sizeof(shelf_t), shelf_destructor);
if (shelf) {
shelf->name = string_duplicate(name);
shelf->amount = amount;
retain(shelf->name);
}
return shelf;
}
static shelf_t *get_shelf(list_t *shelves, char *shelf_name, int *shelf_index) {
if (shelves && strlen(shelf_name) > 0) {
for (int i = 0; i < list_length(shelves); i++) {
obj elem;
if (list_get(shelves, i, &elem)) {
shelf_t *shelf = elem;
if (strcmp(shelf->name, shelf_name) == 0) {
if (shelf_index) {
*shelf_index = i;
}
return shelf;
}
}
}
}
return NULL;
}
static bool count_shelves_amount(obj elem, void *data) {
shelf_t *shelf = elem;
if (shelf) {
int *count = data;
(*count) += shelf->amount;
return true;
}
return false;
}
void item_destructor(obj object) {
item_t *item = (item_t *)object;
release(item->shelves);
release(item->name);
release(item->desc);
}
void shelf_destructor(obj object) {
shelf_t *shelf = (shelf_t *)object;
release(shelf->name);
}
|
C
|
#ifndef UNTITLED_FIRST_COVER_H
#define UNTITLED_FIRST_COVER_H
/* first_cover is called from main after getting a line from the file. The function is the "headquarter" of most of the program's functions.
* It trims the line, and delivers the desired arguments to the responsible functions. It checks if line is empty, or if it holds a comment.
* If none of the above is found, it calls for is_label function to check if there is a label in the beginning of the line.
* It checks if it has a directive or instruction commands, and deliver it's arguments to the caring functions. The function also deters if the command is not recognized.
* The function will return the first encountered error in any of the steps,if error is found. The function will return value 1 if the line is valid, back to the main function.*/
int first_cover(char * _line);
/* The following function gets an argument '_current_arg' and deters if the argument is a valid label. returns -1 on error*/
int is_label(char* _current_arg);
/*he following function gets the inspected line '_line', its line position '_line_pos'. It stores inside 'num' a validated number. returns -1 on error*/
short analyze_number(char* _line, int* _line_pos, short* num);
#endif
|
C
|
/*
Name:Abid Ahmed
Reg No:2018831062
Sub:Data Structure
Course Name:SWE127,SWE128
Program Topic:String Processing
Substring
Indexing
Length
Insert
Replace
Delete
Concatenate
*/
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
void pattern(char s[],char r[],char r1[])
{
int k=-1;
char temp1[1000];
for(int i=0;i<strlen(s);i++)
{
int j=0;
char temp[1000];
k=i;
for(int p=i;p<i+strlen(r);p++){
temp[j]=s[p];
j++;
}
temp[j]='\0';
if(strcmp(r,temp)==0)
{
break;
}
temp1[i]=s[i];
}
if(k!=-1)
{
int j=0;
int h=k;
printf("The new string is: ");
while(1)
{
if(j==strlen(r1))
break;
temp1[k]=r1[j];
j++;k++;
}
for(int i=h+strlen(r);i<strlen(s);i++){
temp1[k]=s[i];
k++;
}
temp1[k]='\0';
printf("%s\n\n",temp1);
}
else
{
printf("There is no such pattern in the string\n\n");
}
return ;
}
void addSubstring(char s[],char sub[],int c)
{
char temp[1000];
for(int i=0;i<c;i++){
temp[i]=s[i];
}
for(int i=0;i<strlen(sub);i++)
temp[i+c]=sub[i];
int i;
for( i=c+strlen(sub);i<strlen(sub)+strlen(s);i++){
temp[i]=s[i-strlen(sub)];
}
temp[i]='\0';
printf("The new string after inserting the substring is: %s\n\n",temp);
return ;
}
void deleteSubstring(char s[],char sub[],int c,int size)
{
char temp[strlen(s)-size];
for(int i=0;i<c;i++){
temp[i]=s[i];
}
int i;
for( i=c;i<strlen(s)-size;i++){
temp[i]=s[i+size];
}
temp[i]='\0';
printf("The new string after deleting the substring %s is %s\n\n",sub,temp);
return ;
}
void substring(char s[],int p,int size)
{
char subString[size];
int j=0;
for(int i=p;i<=size;i++){
subString[j]=s[i];
j++;
}
printf("The Substring is: %s\n\n",subString);
return ;
}
void findingIndex(char s[],char sub[])
{
for(int i=0;i<strlen(s);i++)
{
int j=0;
char temp[strlen(sub)];
int k=i;
for(int p=i;p<i+strlen(sub);p++){
temp[j]=s[p];
j++;
}
temp[j]='\0';
if(strcmp(sub,temp)==0)
{
printf("The first index of your substring is: %d\n\n",k);
break;
}
}
return ;
}
void findingLength(char s[])
{
printf("The length of the string you entered is: %d\n",strlen(s));
return ;
}
void addingStrings(char s[],char sub[])
{
printf("The new string after adding %s and %s strings are: %s\n\n",s,sub,strcat(s,sub));
return ;
}
int main()
{
while(1){
printf("\n\n1.Finding a substring\n2.Finding the Index of a Substring\n3.Adding a substring\n4.Deleting A Substring\n5.Replacing a pattern with another pattern\n6.Finding The Length Of The String\n7.Adding Two Substring\n8.Quit\nWhat would you like to do?\n\n ");
int input;
scanf("%d",&input);
if(input==0||input>8)
{
printf("Invalid Input.Try Again\n");
printf("\n\n1.Finding a substring\n2.Finding the Index of a Substring\n3.Adding a substring\n4.Deleting A Substring\n5.Replacing a pattern with another pattern\n6.Finding The Length Of The String\n7.Adding Two Substring\nWhat would you like to do?\n\n ");
for(int i=0;;i++){
scanf("%d",&input);
if(input<0&&input<=7)
break;
printf("\n\n1.Finding a substring\n2.Finding the Index of a Substring\n3.Adding a substring\n4.Deleting A Substring\n5.Replacing a pattern with another pattern\n6.Finding The Length Of The String\n7.Adding Two Substring\nWhat would you like to do?\n\n ");
}
}
if(input==8){
printf("Thank You!!!See You Again");
break;
}
char s[1000];
printf("Enter Your String: ");
getchar();
gets(s);
if(input==1){
printf("Enter the starting position and size of substring: ");
int p,size;
scanf("%d %d",&p,&size);
substring(s,p,size);
}
else if(input==2)
{
printf("Enter The String You Want To Find: ");
char sub[1000];
gets(sub);
findingIndex(s,sub);
}
else if(input==3)
{
printf("Enter the substring you want to add: ");
char sub[1000];
gets(sub);
int choice;
printf("Enter the position: ");
scanf("%d",&choice);
addSubstring(s,sub,choice);
}
else if(input==4)
{
printf("Enter the substring you want to delete: ");
char sub[1000];
gets(sub);
int choice;
printf("Enter the position: ");
scanf("%d",&choice);
deleteSubstring(s,sub,choice,strlen(sub));
}
else if(input==5)
{
printf("Enter The Pattern You Want To Replace: ");
char re[1000];
gets(re);
printf("Enter The Pattern You Want To Add: ");
char replace[1000];
gets(replace);
pattern(s,re,replace);
}
else if(input==6)
{
findingLength(s);
}
else if(input==7)
{
printf("Enter the string you want to add: ");
char sub[1000];
gets(sub);
addingStrings(s,sub);
}
}
return 0;
}
|
C
|
void check_Key(int k)
{
if((k >= 32 && k < 127))
printf("The character < %c > entered is NORMAL" ,k);
else if ((k >= 128 && k <= 255))
printf("The character < %c > entered is EXTENDED" ,k);
else
printf("The key pressed < %c > is a control key" ,k);
}
|
C
|
/*
Alexandro Francisco Marcelo Gonzalez A01021383
Credits to Gilberto Echeverria
01/03/2019
*/
#include "sockets_tools.h"
int prepareServer(char * port, int max_queue)
{
struct addrinfo hints;
struct addrinfo * address_info = NULL;
int server_fd;
// Clear the structure before filling the data
bzero(&hints, sizeof hints);
// Configure the structure to search for addresses
hints.ai_family = AF_INET;
hints.ai_socktype = SOCK_STREAM;
hints.ai_flags = AI_PASSIVE;
// Get the list of addresses for the server machine
if (getaddrinfo(NULL, port, &hints, &address_info) == -1)
{
perror("ERROR: getaddrinfo");
exit(EXIT_FAILURE);
}
// Open the socket
server_fd = socket(address_info->ai_family, address_info->ai_socktype, address_info->ai_protocol);
if (server_fd == -1)
{
perror("ERROR: socket");
exit(EXIT_FAILURE);
}
int yes = 1;
if (setsockopt(server_fd, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof (int)) == -1)
{
close(server_fd);
freeaddrinfo(address_info);
perror("ERROR: setsockopt");
exit(EXIT_FAILURE);
}
// Bind the socket to an address and port
if (bind(server_fd, address_info->ai_addr, address_info->ai_addrlen) == -1)
{
close(server_fd);
freeaddrinfo(address_info);
perror("ERROR: bind");
exit(EXIT_FAILURE);
}
// Free the list of addresses
freeaddrinfo(address_info);
// Configure the socket to listen for incoming connections
if (listen(server_fd, max_queue) == -1)
{
close(server_fd);
perror("ERROR: listen");
exit(EXIT_FAILURE);
}
return server_fd;
}
int connectToServer(char * address, char * port)
{
struct addrinfo hints;
struct addrinfo * address_info = NULL;
int server_fd;
// Clear the structure before filling the data
bzero(&hints, sizeof hints);
// Configure the structure to search for addresses
hints.ai_family = AF_INET;
hints.ai_socktype = SOCK_STREAM;
hints.ai_flags = AI_PASSIVE;
// Get the list of addresses for the server machine
if (getaddrinfo(address, port, &hints, &address_info) == -1)
{
perror("ERROR: getaddrinfo");
exit(EXIT_FAILURE);
}
// Open the socket
server_fd = socket(address_info->ai_family, address_info->ai_socktype, address_info->ai_protocol);
if (server_fd == -1)
{
perror("ERROR: socket");
exit(EXIT_FAILURE);
}
// Connect to the server
if (connect(server_fd, address_info->ai_addr, address_info->ai_addrlen) == -1)
{
close(server_fd);
freeaddrinfo(address_info);
perror("ERROR: bind");
exit(EXIT_FAILURE);
}
// Free the list of addresses
freeaddrinfo(address_info);
return server_fd;
}
int recvMessage(int connection_fd, void * buffer, int buffer_size)
{
int chars_read;
// Read the request
bzero(buffer, buffer_size);
chars_read = recv(connection_fd, buffer, buffer_size, 0);
// An error in the communication
if (chars_read == -1)
{
perror("ERROR: recv");
}
// Connection closed by the client
if (chars_read == 0)
{
printf("Client has disconnected\n");
}
return chars_read;
}
|
C
|
#include "stdio.h"
#include "math.h"
int main(int argc, char* argv[])
{
int n = 0, i = 0;
__int64 s = 0;
double x = 0.0;
#ifndef ONLINE_JUDGE
freopen("input.txt", "rt", stdin);
freopen("output.txt", "wt", stdout);
#endif
scanf("%d", &n);
/* f(n) = 1 + n*(n-1)/2 */
for(i = 0; i < n; i++){
scanf("%I64d\n", &s);
x = sqrt((double)(8*s-7));
if((x - (int)x) == 0.0 && (int)x%2 == 1)
printf("1 ");
else printf("0 ");
}
return 0;
}
|
C
|
#include <stdbool.h>
#include <stddef.h>
#include <stdio.h>
#include <stdint.h>
#include <string.h>
#include "RingBuffer.h"
#define MAX_TEXT 1000
#define ASSERT_TRUE(expr, result) \
if (result.success && !(expr)) { \
result.success = false; \
result.line = __LINE__; \
strncpy(result.e, #expr, MAX_TEXT); \
}
typedef struct test_result_t {
bool success;
int line;
char e[MAX_TEXT];
} test_result_t;
typedef struct test_definition_t {
const char *name;
test_result_t (*function)();
} test_definition_t;
test_result_t test_empty(void);
test_result_t test_basic(void);
test_result_t test_wrap(void);
test_result_t test_full(void);
test_result_t test_fill_consume_all_refill(void);
test_result_t test_fill_consume_part_refill(void);
test_result_t test_lag(void);
static test_definition_t all_tests[] = {
{"Empty", &test_empty},
{"Basic", &test_basic},
{"Wrap", &test_wrap},
{"Full", &test_full},
{"Fill, consume all and refill", &test_fill_consume_all_refill},
{"Fill, consume some and refill", &test_fill_consume_part_refill},
{"Lag", &test_lag}
};
void
init_result(test_result_t *result)
{
result->success = true;
result->line = 0;
};
/**
* Can't rb_get() from an empty buffer
*/
test_result_t
test_empty(void) {
test_result_t result;
init_result(&result);
ring_buffer_t *buffer;
RB_Status stat = rb_init(&buffer, 3);
ASSERT_TRUE(stat == RB_OK, result);
int32_t val = 99;
stat = rb_get(buffer, &val);
ASSERT_TRUE(stat == RB_ERROR, result);
ASSERT_TRUE(val == 99, result);
return result;
}
/**
* Case that doesn't wrap
*/
test_result_t
test_basic(void) {
test_result_t result;
init_result(&result);
ring_buffer_t *buffer;
RB_Status stat = rb_init(&buffer, 3);
ASSERT_TRUE(stat == RB_OK, result);
stat = rb_put(buffer, 22);
ASSERT_TRUE(stat == RB_OK, result);
stat = rb_put(buffer, 33);
ASSERT_TRUE(stat == RB_OK, result);
int32_t val;
stat = rb_get(buffer, &val);
ASSERT_TRUE(stat == RB_OK, result);
ASSERT_TRUE(val == 22, result);
stat = rb_get(buffer, &val);
ASSERT_TRUE(stat == RB_OK, result);
ASSERT_TRUE(val == 33, result);
stat = rb_get(buffer, &val);
ASSERT_TRUE(stat == RB_ERROR, result);
ASSERT_TRUE(val == 33, result);
return result;
}
/**
* Wrapping works when buffer doesn't fill
*/
test_result_t
test_wrap(void) {
test_result_t result;
init_result(&result);
ring_buffer_t *buffer;
RB_Status stat = rb_init(&buffer, 3);
ASSERT_TRUE(stat == RB_OK, result);
for (int32_t i = 0; i < 20; i++) {
int32_t input = 1000 + i;
// printf("put %d\n", i);
stat = rb_put(buffer, input);
ASSERT_TRUE(stat == RB_OK, result);
// if (stat != RB_OK) printf("bad\n");
int32_t output;
// printf("get %d\n", i);
stat = rb_get(buffer, &output);
// if (stat != RB_OK) printf("bad\n");
ASSERT_TRUE(stat == RB_OK, result);
// if (output != input) printf("bad data\n");
ASSERT_TRUE(output == input, result);
}
return result;
}
/**
* Can fill and empty without wrap
*/
test_result_t
test_full(void) {
test_result_t result;
init_result(&result);
ring_buffer_t *buffer;
RB_Status stat = rb_init(&buffer, 3);
ASSERT_TRUE(stat == RB_OK, result);
stat = rb_put(buffer, 11);
ASSERT_TRUE(stat == RB_OK, result);
stat = rb_put(buffer, 22);
ASSERT_TRUE(stat == RB_OK, result);
stat = rb_put(buffer, 33);
ASSERT_TRUE(stat == RB_OK, result);
stat = rb_put(buffer, 44);
ASSERT_TRUE(stat == RB_ERROR, result);
int32_t val;
stat = rb_get(buffer, &val);
ASSERT_TRUE(stat == RB_OK, result);
ASSERT_TRUE(val == 11, result);
stat = rb_get(buffer, &val);
ASSERT_TRUE(stat == RB_OK, result);
ASSERT_TRUE(val == 22, result);
stat = rb_get(buffer, &val);
ASSERT_TRUE(stat == RB_OK, result);
ASSERT_TRUE(val == 33, result);
stat = rb_get(buffer, &val);
ASSERT_TRUE(stat == RB_ERROR, result);
ASSERT_TRUE(val == 33, result);
return result;
}
/**
* Fill a buffer, consume all and then fill again
*/
test_result_t
test_fill_consume_all_refill(void) {
test_result_t result;
init_result(&result);
ring_buffer_t *buffer;
RB_Status stat = rb_init(&buffer, 3);
ASSERT_TRUE(stat == RB_OK, result);
stat = rb_put(buffer, 11);
ASSERT_TRUE(stat == RB_OK, result);
stat = rb_put(buffer, 22);
ASSERT_TRUE(stat == RB_OK, result);
stat = rb_put(buffer, 33);
ASSERT_TRUE(stat == RB_OK, result);
stat = rb_put(buffer, 44);
ASSERT_TRUE(stat == RB_ERROR, result);
// now full
int32_t val;
stat = rb_get(buffer, &val);
ASSERT_TRUE(stat == RB_OK, result);
ASSERT_TRUE(val == 11, result);
stat = rb_get(buffer, &val);
ASSERT_TRUE(stat == RB_OK, result);
ASSERT_TRUE(val == 22, result);
stat = rb_get(buffer, &val);
ASSERT_TRUE(stat == RB_OK, result);
ASSERT_TRUE(val == 33, result);
stat = rb_get(buffer, &val);
ASSERT_TRUE(stat == RB_ERROR, result);
ASSERT_TRUE(val == 33, result);
// now empty
stat = rb_put(buffer, 55);
ASSERT_TRUE(stat == RB_OK, result);
stat = rb_put(buffer, 66);
ASSERT_TRUE(stat == RB_OK, result);
stat = rb_put(buffer, 77);
ASSERT_TRUE(stat == RB_OK, result);
stat = rb_put(buffer, 88);
ASSERT_TRUE(stat == RB_ERROR, result);
// now full again
stat = rb_get(buffer, &val);
ASSERT_TRUE(stat == RB_OK, result);
ASSERT_TRUE(val == 55, result);
stat = rb_get(buffer, &val);
ASSERT_TRUE(stat == RB_OK, result);
ASSERT_TRUE(val == 66, result);
stat = rb_get(buffer, &val);
ASSERT_TRUE(stat == RB_OK, result);
ASSERT_TRUE(val == 77, result);
stat = rb_get(buffer, &val);
ASSERT_TRUE(stat == RB_ERROR, result);
ASSERT_TRUE(val == 77, result);
// now empty again
return result;
}
/**
* Fill a buffer, consume some and then fill again
*/
test_result_t
test_fill_consume_part_refill(void) {
test_result_t result;
init_result(&result);
ring_buffer_t *buffer;
RB_Status stat = rb_init(&buffer, 3);
ASSERT_TRUE(stat == RB_OK, result);
stat = rb_put(buffer, 11);
ASSERT_TRUE(stat == RB_OK, result);
stat = rb_put(buffer, 22);
ASSERT_TRUE(stat == RB_OK, result);
stat = rb_put(buffer, 33);
ASSERT_TRUE(stat == RB_OK, result);
stat = rb_put(buffer, 44);
ASSERT_TRUE(stat == RB_ERROR, result);
// now full
int32_t val;
stat = rb_get(buffer, &val);
ASSERT_TRUE(stat == RB_OK, result);
ASSERT_TRUE(val == 11, result);
stat = rb_get(buffer, &val);
ASSERT_TRUE(stat == RB_OK, result);
ASSERT_TRUE(val == 22, result);
// now has one left, so put two more
stat = rb_put(buffer, 55);
ASSERT_TRUE(stat == RB_OK, result);
stat = rb_put(buffer, 66);
ASSERT_TRUE(stat == RB_OK, result);
stat = rb_put(buffer, 77);
ASSERT_TRUE(stat == RB_ERROR, result);
// now full again
stat = rb_get(buffer, &val);
ASSERT_TRUE(stat == RB_OK, result);
ASSERT_TRUE(val == 33, result);
stat = rb_get(buffer, &val);
ASSERT_TRUE(stat == RB_OK, result);
ASSERT_TRUE(val == 55, result);
stat = rb_get(buffer, &val);
ASSERT_TRUE(stat == RB_OK, result);
ASSERT_TRUE(val == 66, result);
stat = rb_get(buffer, &val);
ASSERT_TRUE(stat == RB_ERROR, result);
ASSERT_TRUE(val == 66, result);
// now empty again
return result;
}
/**
* Always two values in buffer
* @return
*/
test_result_t
test_lag(void) {
test_result_t result;
init_result(&result);
ring_buffer_t *buffer;
RB_Status stat = rb_init(&buffer, 3);
ASSERT_TRUE(stat == RB_OK, result);
int32_t limit = 20;
for (int32_t i = 0; i < limit; i++) {
int32_t input = 1000 + i;
stat = rb_put(buffer, input);
ASSERT_TRUE(stat == RB_OK, result);
if (i > 0) {
int32_t output;
int32_t expected = input - 1;
stat = rb_get(buffer, &output);
ASSERT_TRUE(stat == RB_OK, result);
ASSERT_TRUE(output == expected, result);
}
}
int32_t output;
int32_t expected = 1000 + limit - 1;
stat = rb_get(buffer, &output);
ASSERT_TRUE(stat == RB_OK, result);
ASSERT_TRUE(output == expected, result);
// now empty
stat = rb_get(buffer, &output);
ASSERT_TRUE(stat == RB_ERROR, result);
ASSERT_TRUE(output == expected, result);
return result;
}
int
main (int argc, char** argv) {
size_t test_count = sizeof(all_tests) / sizeof(test_definition_t);
uint16_t skip_count = 0;
uint16_t fail_count = 0;
for (uint8_t i = 0; i < test_count; i++) {
test_definition_t *test = all_tests + i;
fprintf(stdout, "[%u] %-40s ", i + 1, test->name);
test_result_t result = (test->function)();
fprintf(stdout, "%s \n", result.success ? "PASS" : "FAIL");
if (!result.success) {
fprintf(stdout, "........ Line: %d\n", result.line);
fprintf(stdout, "........ Condition: %s\n", result.e);
fail_count++;
}
}
if (fail_count == 0) {
fprintf(stdout, "All %lu tests passed\n", test_count);
} else {
fprintf(stdout, "%d of %lu tests failed\n", fail_count, test_count);
}
if (skip_count != 0) {
fprintf(stderr, "%d tests skipped\n", skip_count);
} else {
fprintf(stdout, "No tests were skipped\n");
}
return 0;
}
|
C
|
#include "inc/syscall.h"
int global=100;
int main(void){
int local=0;
if(fork()==0){
fork();
fork();
while(local<10){
uart_printf("pid: %d, local: 0x%x %d, global: 0x%x %d\n",getpid(),&local,local,&global,global);
local++;
global--;
delay(1000000);
}
}else{
int* a=0;
uart_printf("%d\n",*a);
uart_printf("Should not be printed\n");
}
exit();
}
|
C
|
#include<stdio.h>
#include<stdlib.h>
static int count;
int check(int** chess_board,int n,int row,int col){
if(row<0 || row>=n || col<0 || col>=n)
return 0;
if(chess_board[row][col]==1)
return 0;
for(int i=0;i<n;i++)
if(chess_board[row][i]==1)
return 0;
for(int i=0;i<n;i++)
if(chess_board[i][col])
return 0;
for(int i=0;i<n;i++){
if((row+i)<n && (col+i)<n)
if(chess_board[row+i][col+i]==1)
return 0;
if((row+i)<n && (col-i)>=0)
if(chess_board[row+i][col-i]==1)
return 0;
if((row-i)>=0 && (col-i)>=0)
if(chess_board[row-i][col-i]==1)
return 0;
if((row-i)>=0 && (col+i)<n)
if(chess_board[row-i][col+i]==1)
return 0;
}
return 1;
}
void printboard(int** chess_board,int n){
for(int i=0;i<n;i++){
for(int j=0;j<n;j++){
printf("%*d",5,chess_board[i][j]);
}
printf("\n");
}
printf("\n");
}
void clearboard(int** chess_board,int n){
for(int i=0;i<n;i++)
for(int j=0;j<n;j++)
chess_board[i][j]=0;
}
void n_queen(int** chess_board,int n,int row,int col,int flag){
if(((check(chess_board,n,row,col)==1 && (row<n) && (col<n))) || flag==1){
if(row>=0 && row<n && col>=0 && col<n)
chess_board[row][col]=1;
if(row==n-1){
printboard(chess_board,n);
count++;
}
if(row<n)
for(int i=0;i<n;i++)
n_queen(chess_board,n,row+1,i,0);
if(row<n && row>=0 && col<n && col>=0)
chess_board[row][col]=0;
}
}
int main(){
int n;
printf("Enter the n value\n");
scanf("%d",&n);
int** chess_board=(int**)malloc(n*sizeof(int**));
for(int i=0;i<n;i++)
chess_board[i]=(int*)malloc(n*sizeof(int*));
clearboard(chess_board,n);
n_queen(chess_board,n,-1,-1,1);
printf("Ans is %d\n",count);
return 0;
}
|
C
|
#include "list.h"
void list_pop(list** root) {
// stack is empty
if (!*root) return;
// delete top and update stack
list* old_root = *root;
*root = old_root->next;
free(old_root);
}
void list_prepend(list** root, tree* node) {
// create new node
list* new_item = (list*)malloc(sizeof(list));
new_item->node = node;
new_item->next = *root;
// update the list
*root = new_item;
}
void list_append(list** root, tree* node) {
// go to last element
if (*root) {
// create new item with NULL list
list* new_item = NULL;
list_prepend(&new_item, node);
// find end and set it's next member to be the new item
list* current_node = *root;
while (current_node->next) {
current_node = current_node->next;
}
current_node->next = new_item;
} else {
// if list is empty, behavior is identical to prepend
list_prepend(root, node);
}
}
|
C
|
#include <stdio.h>
int age(int n, int level)
{
int tmp = 0;
int i = 0;
//输出不同递归层次的制表符
for (i = 0; i < level; i++)
{
printf("\t");
}
printf("--->age(%d)\n", n);
if (1 == n)
{
tmp = 10;
return tmp;
}
tmp = age(n - 1, level + 1) + 2;
//输出不同递归层次的制表符
for (i = 0; i < level; i++)
{
printf("\t");
}
printf("<---age(%d)\n", n);
return tmp;
}
int main(void)
{
printf("age(5): %d\n", age(5, 0));
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
// Ƽ带
#include <pthread.h>
// udp tcpʹ ٸ 迭 ũ⸦ ũ ȵ.
#define BUF_LEN 128
// udp tcp ٸ Ŭ̾Ʈ Ǵ ƴ ְ ޱ
// 带 ʿ .
int s, len, msg_size;
char buf[BUF_LEN];
struct sockaddr_in server_addr, client_addr;
// udp 带 Լ .
void *udpRxThread(void *);
int main(int argc, char **argv) {
pthread_t udp_s_thread;
if(argc != 2) {
printf("usage: %s port thread_num\n", argv[0]);
exit(0);
}
if((s=socket(PF_INET, SOCK_DGRAM, 0)) < 0) {
printf("Server: Can't open udp socket.");
exit(0);
}
bzero((char *)&server_addr, sizeof(server_addr));
bzero((char *)&client_addr, sizeof(client_addr));
server_addr.sin_family = AF_INET;
server_addr.sin_addr.s_addr = htonl(INADDR_ANY);
server_addr.sin_port = htons(atoi(argv[1]));
if(bind(s, (struct sockaddr *)&server_addr, sizeof(server_addr)) <0) {
printf("Server: Can't bind local address.\n");
exit(0);
}
len = sizeof(struct sockaddr);
/* Iterative echo */
while(1) {
printf("Server : waiting request.\n");
// recvfrom Լ Ͱ Ŵ.
if((msg_size=recvfrom(s, buf, BUF_LEN, 0, (struct sockaddr*)&client_addr, &len)) < 0) {
printf("recvfrom error\n");
exit(0);
}
// client_addr ڷ Ѱܼ 带 .
if(pthread_create(&udp_s_thread, NULL, udpRxThread, (void *)&client_addr) != 0) {
printf("pthread_create() error\n");
continue;
}
printf("Sendto complete\n\n");
}
close(s);
return 0;
}
void *udpRxThread(void *arg) {
pthread_t id;
id = pthread_self();
printf("==================================================\n");
/* Client ip, port */
printf("Server : [ip: %s] [port: %d] client data received.\n", inet_ntoa(client_addr.sin_addr), ntohs(client_addr.sin_port));
/* Server port */
printf("Server [port: %d]\n", ntohs(server_addr.sin_port));
/* recvfrom Լ ڱ ޱ ڸ NULL Ͽ ڿ ǥ */
buf[msg_size-1] = '\0';
// ĺȣ ڿ .
printf("Thread [%ud]-Rx Msg : %s\n", id, buf);
printf("==================================================\n");
// sendto Լ ٽ echo.
if(sendto(s, buf, msg_size, 0, (struct sockaddr*)&client_addr, len)<0) {
printf("sendto error\n");
exit(0);
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.