language
large_stringclasses 1
value | text
stringlengths 9
2.95M
|
|---|---|
C
|
#include <stdio.h>
int residuo, numero;
main(){
printf("Ingresa un numero entero positivo\n");
scanf("%d",&numero);
if(numero>0){
printf("La conversion a binario es: ");
residuo= numero%2;
if(residuo == 0){
while( numero > 0){
if(numero%2 == 0){printf("1");}
else{printf("0");}numero = numero/2;}
}
else{
while( numero > 0){
if(numero%2 == 0){printf("0");}
else{printf("1");}numero = numero/2;}}}
else if (numero==0){
printf("La convercion a binario es: 0");}
else{printf("Numero invalido\n");}
}
|
C
|
/****************************************************************************
* $MCI Módulo de implementação: Módulo CIDADES
*
* Arquivo gerado: CIDADES.C
* Letras identificadoras: CID
*
* Projeto: Projeto Cidade
* Autores: jpp - João Pedro Paiva
*
* $LIM Limites da implementação:
* Número de vizinhos: 0 até 32.
* Número de cidades: 0 até 255.
* Número de casos: 0 até 4,294,967,295.
* Tamanho dos nomes dos arquivos de input e output: 0 até 59
* caracteres, excluindo a extensão (.txt).
* Comprimento de cada linha do arquivo de input: 0 até 63 caracteres.
*
* $HA Histórico de evolução:
* Versão Autor Data Observações
* 1.00 jpp 26/01/2020 Início do desenvolvimento
* 2.00 jpp 28/01/2020 stringCopia e ParseCidadesEQuantidades
* 3.00 jpp 29/01/2020 Tipo conteudo, função de criação da
* lista, função de impressão da lista
* função pow, função de destruição.
*
* 4.00 jpp 30/01/2020 Função de armazenamento de quantidades
* dos vizinhos de cada nó até a camada
* desejada, função de ordenação.
*
****************************************************************************/
#include "LISTA.H"
#include "CIDADES.H"
#include <stdlib.h>
#include <stdio.h>
#include <time.h>
/********************* Variáveis encapuladas no módulo *********************/
typedef struct CID_tagConteudoCidade
{
char *pStringNomeCidade;
unsigned long vConjuntoVizinhos;
unsigned int vQuantidadeNucleo;
unsigned int vQuantidadeCamadasDeVizinhos;
} * CID_tppConteudoCidade;
/************** Protótipos das funções encapuladas no módulo ***************/
CID_tpCondRet CID_stringParseCidadesEQuantidades(char pString[], char **ppStringNomeCidade, char **ppStringQuantidade);
CID_tpCondRet CID_stringParseVizinhos(char *pStringVizinhos, unsigned char *pCidadeAtual, unsigned long *pConjuntoVizinhos);
CID_tpCondRet CID_somaQuantidadeVizinhosPorConjunto(CID_tppCabecaCidade pListaDeCidades, unsigned char vNumTotalDeCidades, unsigned char vCidadeAtual, unsigned long vConjuntoVizinhos, unsigned int *pSomaQuantidadesVizinhos, unsigned long *pConjuntoVizinhosCamada, unsigned char vCamadas);
unsigned char CID_stringComprimento(char pString[]);
CID_tpCondRet CID_stringCopia(char pString1[], char pString2[]);
CID_tpCondRet CID_vaiPara(CID_tppCabecaCidade pLista, unsigned char vPos);
unsigned int CID_pow(unsigned int vBase, unsigned int vPower);
unsigned int CID_converteStringParaUInt(char *pString);
CID_tpCondRet CID_destruirConteudoDeCidade(CID_tppConteudoCidade pConteudoCidade);
/**************** Código das funções exportadas pelo módulo ****************/
/****************************************************************************
*
* $FC Função:
* CID Armazena várias cidades de um arquivo txt em uma lista.
*
****************************************************************************/
CID_tpCondRet CID_criarListaDeCidades(CID_tppCabecaCidade *ppListaDeCidades, char *pStringArquivoDeCidades, unsigned char *pNumTotalDeCidades)
{
FILE *pArquivoDeCidades;
CID_tppConteudoCidade pConteudoCidade;
unsigned int vQuantidadeConvertida;
char pStringCidade[64], *pStringNomeCidade, *pStringQuantidade;
if (LIS_criarLista((void (*)(void *))CID_destruirConteudoDeCidade, ppListaDeCidades) != LIS_CondRetOK)
return CID_CondRetFaltouMemoria;
pArquivoDeCidades = fopen(pStringArquivoDeCidades, "r");
if (!pArquivoDeCidades)
return CID_CondRetFaltouMemoria;
*pNumTotalDeCidades = 0;
while (fgets(pStringCidade, 64, pArquivoDeCidades))
{
if (CID_stringParseCidadesEQuantidades(pStringCidade, &pStringNomeCidade, &pStringQuantidade) != CID_CondRetOK)
return CID_CondRetFaltouMemoria;
vQuantidadeConvertida = CID_converteStringParaUInt(pStringQuantidade);
free(pStringQuantidade);
pConteudoCidade = (CID_tppConteudoCidade)malloc(sizeof(struct CID_tagConteudoCidade));
pConteudoCidade->pStringNomeCidade = pStringNomeCidade;
pConteudoCidade->vQuantidadeNucleo = vQuantidadeConvertida;
pConteudoCidade->vQuantidadeCamadasDeVizinhos = 0;
pConteudoCidade->vConjuntoVizinhos = 0;
if (LIS_InserirNoApos(*ppListaDeCidades, (void *)pConteudoCidade) != LIS_CondRetOK)
return CID_CondRetFaltouMemoria;
++*pNumTotalDeCidades;
}
fclose(pArquivoDeCidades);
if (LIS_vaiParaPrimeiroNo(*ppListaDeCidades) != LIS_CondRetOK)
return CID_CondRetProblemaDeLista;
return CID_CondRetOK;
}
/****************************************************************************
*
* $FC Função:
* CID Armazena conjunto de vizinhos descritos no txt.
*
****************************************************************************/
CID_tpCondRet CID_armazenarConjuntosVizinhos(CID_tppCabecaCidade pListaDeCidades, char *pStringArquivoDeVizinhos)
{
FILE *pArquivoDeVizinhos;
CID_tppConteudoCidade pConteudoCidade;
char pStringVizinhos[64];
unsigned long vConjuntoVizinhos;
unsigned char vCidadeAtual;
if (LIS_vaiParaPrimeiroNo(pListaDeCidades) != LIS_CondRetOK)
return CID_CondRetProblemaDeLista;
pArquivoDeVizinhos = fopen(pStringArquivoDeVizinhos, "r");
if (!pArquivoDeVizinhos)
return CID_CondRetFaltouMemoria;
while (fgets(pStringVizinhos, 64, pArquivoDeVizinhos))
{
CID_stringParseVizinhos(pStringVizinhos, &vCidadeAtual, &vConjuntoVizinhos);
CID_vaiPara(pListaDeCidades, vCidadeAtual);
if (LIS_obterConteudo(pListaDeCidades, (void **)&pConteudoCidade) != LIS_CondRetOK)
return CID_CondRetProblemaDeLista;
pConteudoCidade->vConjuntoVizinhos = vConjuntoVizinhos;
}
fclose(pArquivoDeVizinhos);
if (LIS_vaiParaPrimeiroNo(pListaDeCidades) != LIS_CondRetOK)
return CID_CondRetProblemaDeLista;
return CID_CondRetOK;
}
/****************************************************************************
*
* $FC Função:
* CID Armazena a soma das quantidades dos vizinhos até a camada
* desejada.
*
****************************************************************************/
CID_tpCondRet CID_armazenarSomasVizinhos(CID_tppCabecaCidade pListaDeCidades, unsigned char vNumTotalDeCidades, unsigned char vCamadas)
{
CID_tppConteudoCidade pConteudoCidade;
unsigned long vConjuntoVizinhosCamada;
unsigned int vSomaQuantidadesVizinhos;
unsigned char vCidadeAtual;
if (LIS_vaiParaPrimeiroNo(pListaDeCidades) != LIS_CondRetOK)
return CID_CondRetProblemaDeLista;
vCidadeAtual = 0;
do
{
if (LIS_obterConteudo(pListaDeCidades, (void **)&pConteudoCidade) != LIS_CondRetOK)
return CID_CondRetProblemaDeLista;
if (!vCamadas)
{
pConteudoCidade->vQuantidadeCamadasDeVizinhos = pConteudoCidade->vQuantidadeNucleo;
continue;
}
if (CID_somaQuantidadeVizinhosPorConjunto(pListaDeCidades, vNumTotalDeCidades, vCidadeAtual, pConteudoCidade->vConjuntoVizinhos, &vSomaQuantidadesVizinhos, &vConjuntoVizinhosCamada, vCamadas) != CID_CondRetOK)
return CID_CondRetProblemaDeLista;
pConteudoCidade->vQuantidadeCamadasDeVizinhos = vSomaQuantidadesVizinhos;
vCidadeAtual++;
} while (LIS_vaiParaProximoNo(pListaDeCidades) == LIS_CondRetOK);
if (LIS_vaiParaPrimeiroNo(pListaDeCidades) != LIS_CondRetOK)
return CID_CondRetProblemaDeLista;
return CID_CondRetOK;
}
/****************************************************************************
*
* $FC Função:
* CID Ordena lista de cidades da maior soma das quantidades dos
* vizinhos para a menor soma das quantidades dos vizinhos
* utilizando o método bubble sort.
*
****************************************************************************/
CID_tpCondRet CID_ordenarListaDeCidades(CID_tppCabecaCidade pListaDeCidades)
{
CID_tppConteudoCidade pConteudoCidadeUm, pConteudoCidadeDois;
struct CID_tagConteudoCidade pConteudoCidadeAux;
unsigned char vHouveTroca;
vHouveTroca = 0;
if (LIS_vaiParaPrimeiroNo(pListaDeCidades) != LIS_CondRetOK)
return CID_CondRetProblemaDeLista;
do
{
if (LIS_obterConteudo(pListaDeCidades, (void **)&pConteudoCidadeUm) != LIS_CondRetOK)
return CID_CondRetProblemaDeLista;
else if (LIS_vaiParaProximoNo(pListaDeCidades) != LIS_CondRetOK)
if (!vHouveTroca)
return CID_CondRetOK;
else if (LIS_vaiParaPrimeiroNo(pListaDeCidades) != LIS_CondRetOK)
return CID_CondRetProblemaDeLista;
else
vHouveTroca = 0;
else
{
if (LIS_obterConteudo(pListaDeCidades, (void **)&pConteudoCidadeDois) != LIS_CondRetOK)
return CID_CondRetProblemaDeLista;
else if (pConteudoCidadeUm->vQuantidadeCamadasDeVizinhos < pConteudoCidadeDois->vQuantidadeCamadasDeVizinhos)
{
pConteudoCidadeAux = *pConteudoCidadeUm;
*pConteudoCidadeUm = *pConteudoCidadeDois;
*pConteudoCidadeDois = pConteudoCidadeAux;
vHouveTroca = 1;
}
}
} while (1);
if (LIS_vaiParaPrimeiroNo(pListaDeCidades) != LIS_CondRetOK)
return CID_CondRetProblemaDeLista;
return CID_CondRetOK;
}
/****************************************************************************
*
* $FC Função:
* CID Imprime lista de cidades.
*
****************************************************************************/
CID_tpCondRet CID_imprimirListaDeCidades(CID_tppCabecaCidade pListaDeCidades)
{
CID_tppConteudoCidade pConteudoCidade;
if (LIS_vaiParaPrimeiroNo(pListaDeCidades) != LIS_CondRetOK)
return CID_CondRetProblemaDeLista;
do
{
if (LIS_obterConteudo(pListaDeCidades, (void **)&pConteudoCidade) != LIS_CondRetOK)
return CID_CondRetProblemaDeLista;
printf("%s : %u\n", pConteudoCidade->pStringNomeCidade, pConteudoCidade->vQuantidadeCamadasDeVizinhos);
} while (LIS_vaiParaProximoNo(pListaDeCidades) == LIS_CondRetOK);
if (LIS_vaiParaPrimeiroNo(pListaDeCidades) != LIS_CondRetOK)
return CID_CondRetProblemaDeLista;
return CID_CondRetOK;
}
/****************************************************************************
*
* $FC Função:
* CID Destrói lista de cidades.
*
****************************************************************************/
CID_tpCondRet CID_destruirListaDeCidades(CID_tppCabecaCidade pListaDeCidades)
{
LIS_DestruirLista(pListaDeCidades);
return CID_CondRetOK;
}
/****************************************************************************
*
* $FC Função:
* CID Copia pString1 para pString2.
*
****************************************************************************/
CID_tpCondRet CID_stringCopia(char pString1[], char pString2[])
{
int vCont;
vCont = 0;
do
if (pString1[vCont] != '\n')
pString2[vCont] = pString1[vCont];
while (pString1[vCont++]);
return CID_CondRetOK;
}
/**************** Código das funções encapsuladas no módulo ****************/
/****************************************************************************
*
* $FC Função:
* CID Quebra string do arquivo txt em uma string com o nome da cidade e
* uma string com a quantidade.
*
*
* $AE Assertivas de entrada esperadas:
* Valem as assertivas estruturais do vetor de caracteres.
*
*
* $EP Parâmetros
* $P pString - O parâmetro que receberá o endereço do primeiro caractere
* da string que deseja-se quebrar.
* Este parâmetro é passado por referência.
* $P pStringNomeCidade - O parâmetro que receberá o ponteiro para o
* endereço do primeiro caractere da string de nome.
* Este parâmetro é passado por referência.
* $P pStringQuantidades - O parâmetro que receberá o ponteiro para o
* endereço do primeiro caractere da string de qunatidade.
* Este parâmetro é passado por referência.
*
****************************************************************************/
CID_tpCondRet CID_stringParseCidadesEQuantidades(char pString[], char **ppStringNomeCidade, char **ppStringQuantidade)
{
int vTamString;
char *pPrimeiroCharStringQtd;
for (vTamString = 0; pString[vTamString]; vTamString++)
if (pString[vTamString] == ':')
{
pString[vTamString - 1] = '\0';
*ppStringNomeCidade = (char *)malloc(vTamString - 1);
if (!*ppStringNomeCidade)
return CID_CondRetFaltouMemoria;
CID_stringCopia(pString, *ppStringNomeCidade);
pPrimeiroCharStringQtd = pString + vTamString + 2;
}
*ppStringQuantidade = (char *)malloc(pString + vTamString - pPrimeiroCharStringQtd);
if (!*ppStringQuantidade)
return CID_CondRetFaltouMemoria;
CID_stringCopia(pPrimeiroCharStringQtd, *ppStringQuantidade);
return CID_CondRetOK;
}
/****************************************************************************
*
* $AS Assertivas de saída esperadas:
* O nome da cidade e a quantidade foram retornados por referência.
* Valem as assertivas estruturais do vetor de caracteres.
*
*
* $FV Valor retornado
* CID_CondRetOK - Condição de retorno de teste bem sucedido.
* CID_CondRetFaltouMemoria - Malloc falhou.
*
****************************************************************************/
/****************************************************************************
*
* $FC Função:
* CID Analiza string do arquivo txt para somar quantidades de vizinhos.
*
*
* $AE Assertivas de entrada esperadas:
* Lista pode estar em qualquer posição.
* Valem as assertivas estruturais da lista duplamente encadeada com
* cabeça.
*
*
* $EP Parâmetros
* $P pListaDeCidades - O parâmetro que receberá o endereço da cabeça da
* lista de cidades.
* Este parâmetro é passado por referência.
* $P pStringVizinhos - O parâmetro que receberá o endereço do primeiro
* caractere da string que deseja-se aalisar.
* Este parâmetro é passado por referência.
*
****************************************************************************/
CID_tpCondRet CID_stringParseVizinhos(char *pStringVizinhos, unsigned char *pCidadeAtual, unsigned long *pConjuntoVizinhos)
{
unsigned char vVizinhoAtual;
int vTamString;
char vTamStringNum;
vTamString = 0;
while (pStringVizinhos[vTamString] >= '0' && pStringVizinhos[vTamString] <= '9')
vTamString++;
pStringVizinhos[vTamString] = '\0';
*pCidadeAtual = (unsigned char)CID_converteStringParaUInt(pStringVizinhos);
*pConjuntoVizinhos = (unsigned long)0x1 << *pCidadeAtual;
while (pStringVizinhos[vTamString] < '0' || pStringVizinhos[vTamString] > '9')
vTamString++;
vTamStringNum = 0;
while (pStringVizinhos[vTamString])
{
vTamStringNum++;
if (pStringVizinhos[vTamString] == ' ' || pStringVizinhos[vTamString] == '\n')
{
pStringVizinhos[vTamString] = '\0';
vVizinhoAtual = (unsigned char)CID_converteStringParaUInt(pStringVizinhos + vTamString - vTamStringNum + 1);
*pConjuntoVizinhos |= (unsigned long)0x1 << vVizinhoAtual;
vTamStringNum = 0;
}
vTamString++;
}
return CID_CondRetOK;
}
/****************************************************************************
*
* $AS Assertivas de saída esperadas:
* A soma das quantidades dos vizinhos de uma cidade foi determinada.
* Lista está na posição da cidade atual.
* Valem as assertivas estruturais da lista duplamente encadeada com
* cabeça.
*
*
* $FV Valor retornado
* CID_CondRetOK - Condição de retorno de teste bem sucedido.
*
****************************************************************************/
/****************************************************************************
*
* $FC Função:
* CID Retorna a soma das quantidades dos vizinhos marcados no conjunto.
*
*
* $AE Assertivas de entrada esperadas:
* Lista está na posição da cidade atual.
* Um dos vizinhos marcados no conjunto pode ser igual à cidade atual.
* Valem as assertivas estruturais da lista duplamente encadeada com
* cabeça.
*
*
* $EP Parâmetros
* $P pListaDeCidades - O parâmetro que receberá o endereço da cabeça da
* lista de cidades.
* Este parâmetro é passado por referência.
* $P vCidadeAtual - O parâmetro que receberá o valor numérico da cidade
* atual para que possamos navegar na lista e retornar à posição
* inicial.
* Este parâmetro é passado por valor.
* $P vConjuntoVizinhos - O parâmetro que receberá o conjunto de vizinhos
* cuja soma das quantidades deseja-se determinar.
* Este parâmetro é passado por valor.
* $P vSomaQuantidadesVizinhos - O parâmetro que receberá a soma das
* quantidades dos vizinhos.
* Este parâmetro é passado por referência.
*
****************************************************************************/
CID_tpCondRet CID_somaQuantidadeVizinhosPorConjunto(CID_tppCabecaCidade pListaDeCidades, unsigned char vNumTotalDeCidades, unsigned char vCidadeAtual, unsigned long vConjuntoVizinhos, unsigned int *pSomaQuantidadesVizinhos, unsigned long *pConjuntoVizinhosCamada, unsigned char vCamadas)
{
CID_tppConteudoCidade pConteudoCidade;
short vDirecaoEPassos;
unsigned char vVizinhoAnterior, vVizinhoAtual;
if (!vCamadas)
return CID_CondRetOK;
*pConjuntoVizinhosCamada = vConjuntoVizinhos;
*pSomaQuantidadesVizinhos = 0;
vVizinhoAnterior = vCidadeAtual;
for (int i = 0; i < vNumTotalDeCidades; i++)
{
if (((vConjuntoVizinhos >> i) & (unsigned long)0x1) == (unsigned long)0x0)
continue;
vVizinhoAtual = i;
vDirecaoEPassos = (short)(vVizinhoAtual - vVizinhoAnterior);
if (vDirecaoEPassos > 0)
{
while (vDirecaoEPassos--)
if (LIS_vaiParaProximoNo(pListaDeCidades) != LIS_CondRetOK)
return CID_CondRetProblemaDeLista;
if (LIS_obterConteudo(pListaDeCidades, (void **)&pConteudoCidade) != LIS_CondRetOK)
return CID_CondRetProblemaDeLista;
*pSomaQuantidadesVizinhos += pConteudoCidade->vQuantidadeNucleo;
*pConjuntoVizinhosCamada |= pConteudoCidade->vConjuntoVizinhos;
}
else
{
while (vDirecaoEPassos++)
if (LIS_vaiParaNoAnterior(pListaDeCidades) != LIS_CondRetOK)
return CID_CondRetProblemaDeLista;
if (LIS_obterConteudo(pListaDeCidades, (void **)&pConteudoCidade) != LIS_CondRetOK)
return CID_CondRetProblemaDeLista;
*pSomaQuantidadesVizinhos += pConteudoCidade->vQuantidadeNucleo;
*pConjuntoVizinhosCamada |= pConteudoCidade->vConjuntoVizinhos;
}
vVizinhoAnterior = vVizinhoAtual;
}
vDirecaoEPassos = (short)(vVizinhoAnterior - vCidadeAtual);
if (vDirecaoEPassos > 0)
{
while (vDirecaoEPassos--)
if (LIS_vaiParaNoAnterior(pListaDeCidades) != LIS_CondRetOK)
return CID_CondRetProblemaDeLista;
}
else
{
while (vDirecaoEPassos++)
if (LIS_vaiParaProximoNo(pListaDeCidades) != LIS_CondRetOK)
return CID_CondRetProblemaDeLista;
}
if (CID_somaQuantidadeVizinhosPorConjunto(pListaDeCidades, vNumTotalDeCidades, vCidadeAtual, *pConjuntoVizinhosCamada, pSomaQuantidadesVizinhos, pConjuntoVizinhosCamada, --vCamadas) != CID_CondRetOK)
return CID_CondRetProblemaDeLista;
return CID_CondRetOK;
}
/****************************************************************************
*
* $AS Assertivas de saída esperadas:
* Lista está na posição da cidade atual.
* A soma das quantidades dos vizinhos demarcados no conjunto foi
* determinada.
* Valem as assertivas estruturais da lista duplamente encadeada com
* cabeça.
*
*
* $FV Valor retornado
* CID_CondRetOK - Condição de retorno de teste bem sucedido.
* CID_CondRetProblemaDeLista
*
****************************************************************************/
/****************************************************************************
*
* $FC Função:
* CID Anda um certo número de passos para frente ou para trás numa
* lista.
*
* $AE Assertivas de entrada esperadas:
* Valem as assertivas estruturais da lista duplamente encadeada.
*
*
* $EP Parâmetros
* $P pLista - O parâmetro que receberá o ponteiro para a cabeça da
* lista duplamente encadeada.
* Este parâmetro é passado por referência.
* $P vPos - O parâmetro que receberá a posição desejada da lista.
* Este parâmetro é passado por valor.
*
****************************************************************************/
CID_tpCondRet CID_vaiPara(CID_tppCabecaCidade pLista, unsigned char vPos)
{
LIS_vaiParaPrimeiroNo(pLista);
while (vPos)
{
LIS_vaiParaProximoNo(pLista);
vPos--;
}
return CID_CondRetOK;
}
/****************************************************************************
*
* $AS Assertivas de saída esperadas:
* Lista está na posição desejada.
* Valem as assertivas estruturais da lista duplamente encadeada com
* cabeça.
*
*
* $FV Valor retornado
* CID_CondRetOK - Condição de retorno de teste bem sucedido.
*
****************************************************************************/
/****************************************************************************
*
* $FC Função:
* CID Determina o comprimento de uma string.
*
*
* $AE Assertivas de entrada esperadas:
* Valem as assertivas estruturais do vetor de caracteres.
*
*
* $EP Parâmetros
* $P string - O parâmetro que receberá o endereço do primeiro caractere
* da string cujo tamanho deseja-se determinar.
* Este parâmetro é passado por referência.
*
****************************************************************************/
unsigned char CID_stringComprimento(char pString[])
{
unsigned char vSoma;
int vCont;
vSoma = (unsigned char)0;
vCont = 0;
do
if (pString[vCont] != '\n')
vSoma++;
while (pString[vCont++]);
return vSoma;
}
/****************************************************************************
*
* $AS Assertivas de saída esperadas:
* O comprimento da string foi determinado.
* Valem as assertivas estruturais da lista duplamente encadeada com
* cabeça.
*
*
* $FV Valor retornado
* vSoma - o comprimento da string.
*
****************************************************************************/
/****************************************************************************
*
* $FC Função:
* CID Determina vBase ^ vPower.
*
*
* $AE Assertivas de entrada esperadas:
* vBase e vPower são valores inteiros.
*
*
* $EP Parâmetros
* $P vBase - O parâmetro que receberá o valor que deseja-se elevar.
* Este parâmetro é passado por valor.
* $P vPower - O parâmetro que receberá o valor ao qual deseja-se
* elevar a base.
* Este parâmetro é passado por valor.
*
****************************************************************************/
unsigned int CID_pow(unsigned int vBase, unsigned int vPower)
{
unsigned int vRes;
vRes = 1;
while (--vPower)
vRes *= vBase;
return vRes;
}
/****************************************************************************
*
* $AS Assertivas de saída esperadas:
* vBase ^ vPower foi retornado.
*
*
* $FV Valor retornado
* vBase = vBase ^ vPower
*
****************************************************************************/
/****************************************************************************
*
* $FC Função:
* CID Converte uma string numérica para o UInt equivalente.
*
*
* $AE Assertivas de entrada esperadas:
* Todos os caracteres da string são números.
* O valor equivalente à string está no intervalo 0..4,294,967,295
*
*
* $EP Parâmetros
* $P pString - O parâmetro que receberá o endereço do primeiro
* caractere da string a ser convertida.
* Este parâmetro é passado por referência.
*
****************************************************************************/
unsigned int CID_converteStringParaUInt(char *pString)
{
unsigned int vConvertido, vTamString;
vTamString = (unsigned int)CID_stringComprimento(pString);
vTamString--;
vConvertido = (unsigned int)0;
for (int i = 0; pString[i]; i++)
vConvertido += (unsigned int)(pString[i] - '0') * CID_pow((unsigned int)10, vTamString - (unsigned int)i);
return vConvertido;
}
/****************************************************************************
*
* $AS Assertivas de saída esperadas:
* O valor numérico equivalente à string foi determinado.
*
*
* $FV Valor retornado
* vConvertido - O valor numérico equivalente à string.
*
****************************************************************************/
/****************************************************************************
*
* $FC Função:
* CID Destrói conteúdo de cada cidade.
*
*
* $AE Assertivas de entrada esperadas:
* Conteúdo não é nulo.
*
*
* $EP Parâmetros
* $P pConteudoCidade - O parâmetro que receberá o endereço do conteúdo
* de um nó da lista de cidades.
* Este parâmetro é passado por referência.
*
****************************************************************************/
CID_tpCondRet CID_destruirConteudoDeCidade(CID_tppConteudoCidade pConteudoCidade)
{
free(pConteudoCidade->pStringNomeCidade);
free(pConteudoCidade);
return CID_CondRetOK;
}
/****************************************************************************
*
* $AS Assertivas de saída esperadas:
* O conteúdo da cidade foi destruído.
*
*
* $FV Valor retornado
* CID_CondRetOK - Condição de retorno de teste bem sucedido.
*
****************************************************************************/
|
C
|
#include <stdlib.h>
#include <stdio.h>
#include <mpi.h>
#include <time.h>
#include "lib/buffer_lib.h"
int main(int argc, char** argv) {
int MPI_COMM_SIZE, MPI_COMM_RANK;
MPI_Init(&argc, &argv);
MPI_Comm_size(MPI_COMM_WORLD, &MPI_COMM_SIZE);
MPI_Comm_rank(MPI_COMM_WORLD, &MPI_COMM_RANK);
if (argc != 4) {
if (MPI_COMM_RANK == 0) printf("program arguments: <vector length> <value range start> <value range end>\n");
MPI_Finalize();
return (EXIT_SUCCESS);
}
int *buf, **bufs, *lens, *inds, *lbuf;
int len = atoi(argv[1]);
int st = atoi(argv[2]);
int en = atoi(argv[3]);
if (MPI_COMM_RANK == 0) {
buf = (int*) malloc(len * sizeof(int));
lens = (int*) malloc(MPI_COMM_SIZE * sizeof(int));
inds = (int*) malloc(MPI_COMM_SIZE * sizeof(int));
buffer_distribute(len, lens, inds, MPI_COMM_SIZE);
printf("distributed lengths "); buffer_print(lens, MPI_COMM_SIZE);
printf("distributed indexes "); buffer_print(inds, MPI_COMM_SIZE);
srand(time(NULL)); buffer_fill(buf, len, st, en); buffer_print(buf, len);
bufs = (int**) malloc(MPI_COMM_SIZE * sizeof(int*));
for (int i = 0; i < MPI_COMM_SIZE; i ++) {
bufs[i] = buffer_slice(buf, len, inds[i], lens[i]);
MPI_Send(&lens[i], 1, MPI_INT, i, 0, MPI_COMM_WORLD);
MPI_Send(bufs[i], lens[i], MPI_INT, i, 1, MPI_COMM_WORLD); free(bufs[i]);
} free(buf);
}
MPI_Status lstt, stt;
int llen; MPI_Recv(&llen, 1, MPI_INT, 0, 0, MPI_COMM_WORLD, &lstt);
if (llen > 0) {
lbuf = (int*) malloc(llen * sizeof(int));
MPI_Recv(lbuf, llen, MPI_INT, 0, 1, MPI_COMM_WORLD, &stt);
printf("thread(%d): ", MPI_COMM_RANK); buffer_print(lbuf, llen);
MPI_Send(lbuf, llen, MPI_INT, 0, 0, MPI_COMM_WORLD); free(lbuf);
} else {
MPI_Send((void*) 0, 0, MPI_INT, 0, 0, MPI_COMM_WORLD);
}
if (MPI_COMM_RANK == 0) {
buf = (int*) malloc(len * sizeof(int));
MPI_Status *sts; sts = (MPI_Status*) malloc(MPI_COMM_SIZE * sizeof(MPI_Status));
for (int i = 0; i < MPI_COMM_SIZE; i ++) {
bufs[i] = (int*) malloc(len * sizeof(int));
MPI_Recv(bufs[i], len, MPI_INT, MPI_ANY_SOURCE, 0, MPI_COMM_WORLD, &sts[i]);
if (lens[sts[i].MPI_SOURCE] > 0) printf("from thread(%d): ", sts[i].MPI_SOURCE); buffer_print(bufs[i], lens[sts[i].MPI_SOURCE]);
buffer_copy(buf, bufs[i], lens[sts[i].MPI_SOURCE], inds[sts[i].MPI_SOURCE]);
}
buffer_print(buf, len); free(buf);
for (int i = 0; i < MPI_COMM_SIZE; i ++) if (lens[i] > 0) free(bufs[i]);
free(bufs); free(lens); free(inds); free(sts);
}
MPI_Finalize();
return (EXIT_SUCCESS);
}
|
C
|
/* File: exponent.c
* By: Edler Espiritu
* Login: edler
* Team: Alpha Squad
* Date: 11/12/2012
*/
#include "exponent.h"
#include "tfdef.h"
float pos_power(float base, int exponent)
{
/* Initilized Variable */
float x = 1;
float pos_power;
while(exponent != 0)
{
x = x * base;
exponent = exponent - 1;
#ifdef DEBUG
printf("deebug: Enter pos_power: base = %f exponent = %d\n",base, exponent);
#endif
}
#ifdef DEBUG
printf("debug:Exit pos_power: result = %f\n",x);
#endif
return x;
}
int is_exp(char ch)
{
switch(ch)
{
case '!':
case '@':
case '#':
case '$':
case '%':
case '^':
case '&':
case '*':
case '(':
case ')': return TRUE;
default: return FALSE;
}
}
char exp_value(char ch)
{
switch(ch)
{
case '!': return '1';
case '@': return '2';
case '#': return '3';
case '$': return '4';
case '%': return '5';
case '^': return '6';
case '&': return '7';
case '*': return '8';
case '(': return '9';
case ')': return '0';
}
}
|
C
|
/*
Author: Genaro Martínez S.
id: A01566055
date: 13/03/2020
display the size of union types and use the function sizeof().
*/
#include <stdio.h>
// initialize data union to store data types.
union Data {
int i;
double d;
char str[100];
} data;
int main(int argc, char const *argv[])
{
char str[100];
printf("int type\n");
scanf("%d", &data.i);
printf("double type\n");
scanf("%lf", &data.d);
printf("string type:\n");
scanf("%s", &str);
strcpy(data.str, str);
// sizeof evaluates the size of a variable
printf("Your integer <%d> storage size is => %ld bytes\n", data.i, sizeof(data.i));
printf("Your double <%f> storage size is => %ld bytes\n", data.d, sizeof(data.d));
printf("Your string <%s> storage size is => %ld byte\n", data.str, sizeof(data.str));
printf("Your data union storage size => %ld bytes\n", sizeof(data));
return 0;
}
|
C
|
///////////////////////////////////////////////////////////////////////////////
// Tyler Perkins
// 9-29-21
// Markov chain implementation
//
#include "chain.h"
m_node* m_next(const m_node* rhs){
int i = 1;
long v = rand() % UINT16_MAX - 1;
//printf("v : %li\n", v);
long total = rhs->_conns[i]._probability;
while(v >= total){
//printf("prob : %u\n", rhs->_conns[i]._probability);
total += rhs->_conns[i]._probability;
++i;
}
return rhs->_conns[i - 1]._node;
}
|
C
|
#include <structtdio.h>
struct time
{
int h,m,struct;
}structtime;
int time_to_structec(struct time t1);
int structec_to_time(int structec)
{
structtime.h = (structec/3600);
structtime.m = (structec-(3600*structtime.h))/60;
structtime.struct = (structec -(3600*structtime.h)-(structtime.m*60));
printf("HH:MM:SS - %d:%d:%d\n",structtime.h,structtime.m,structtime.struct);
return 0;
}
int time_to_structec(struct time structtime1)
{
float timeinstructec = structtime1.struct + (structtime1.m * 60) + (structtime1.h * 60 * 60);
printf("Total structecondstruct in %dH:%dM:%dS istruct %f\n", structtime1.h, structtime1.m, structtime1.struct, timeinstructec);
return 0;
}
int main()
{
struct time t2;
int structec=10;
printf("enter valuestruct for time in HH:MM:SS format\n");
structcanf("%d:%d:%d",&t2.h,&t2.m,&t2.struct);
if((t2.h>=0&&t2.h<24)&&(t2.m>=0&&t2.m<60)&&(t2.struct>=0&&t2.struct<60))
printf("Valid\n");
elstructe
printf("Invalid\n");
time_to_structec(t2);
structec_to_time(structec);
return 0;
}
|
C
|
#include <stdio.h>
int main(void)
{
int a, b;
a = 1;
b = 2;
printf("%d", a + b);
return 0;
}
|
C
|
/********************************************************/
/* This program count even and odd numbers in an array */
/*******************************************************/
#include<stdio.h>
#define SIZE 10
int main(void){
int i, even=0, odd=0, arr[SIZE];
printf("Enter the elements of the array\n");
for(i=0; i<10; i++){
scanf("%d", &arr[i]);
if(arr[i]%2==0)
even++;
else
odd++;
}
printf("Number of odd elements : %d and no of even elements : %d\n",
odd, even);
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
// -------- If we are compiling on Windows compile these functions
#ifdef _WIN32
#include <string.h>
// Declare a buffer for user input of size 2048
// static makes this global variable local only for this file!
static char buffer[2048];
// Fake readline function
char* readline(char* prompt) {
fputs(prompt, stdout);
fgets(buffer, 2048, stdin);
char* cpy = malloc(strlen(buffer)+1);
strcpy(cpy, buffer);
cpy[strlen(cpy)-1] = '\0';
return cpy;
}
// Fake add_history function
void add_history(char* unused) {}
// -------- Otherwise include the editline headers
#else
#include <editline/readline.h>
#include <editline/history.h>
#endif
int main(int argc, char** argv) {
// Print version and exit information
puts("Lispy Version 0.0.0.0.1");
puts("Press [Ctrl+c] to Exit\n");
while(1) {
// Output our prompt
char* input = readline("lispy> ");
add_history(input);
// Echo input back to user
printf("You used command:%s\n", input);
free(input);
}
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct knoop knoop;
struct knoop {
char *woord;
knoop *next;
};
void print_lijst(const knoop *l) {
while (l) {
printf("%s ", l->woord);
l = l->next;
}
}
knoop *woorden_lijst() {
knoop *l, *h;
char buf[81];
int lengte;
printf("Eerste woord: ");
scanf("%80s", buf);
if (strcmp(buf, "STOP") == 0) {
l = 0;
} else {
/*eerste woord toevoegen*/
l = malloc(sizeof(knoop));
h = l;
lengte = strlen(buf) + 1;
h->woord = malloc(lengte * sizeof(char));
strcpy(h->woord, buf);
/*volgend woord inlezen*/
printf("\nVolgende: ");
scanf("%80s", buf);
while (strcmp(buf, "STOP") != 0) {
printf("ingelezen woord: %s\n", buf);
/*volgende knoop maken*/
h->next = malloc(sizeof(knoop));
h = h->next;
/*woord toevoegen*/
lengte = strlen(buf) + 1;
h->woord = malloc(lengte * sizeof(char));
strcpy(h->woord, buf);
/*volgend inlezen*/
printf("\nVolgende: ");
scanf("%80s", buf);
}
h->next = 0;
}
return l;
}
void print_lijst_array(knoop **arr) {
while (*arr) {
print_lijst(*arr);
printf("\n");
arr++;
}
}
knoop **geef_array_van_lijst(int aantal) {
knoop **arr = malloc((aantal + 1) * sizeof(knoop *));
int x;
/*allemaal op 0 zetten */
for (x = 0; x < aantal + 1; x++) {
arr[x] = 0;
}
int i = 0;
int lengte;
char buf[81];
knoop **helper = malloc(sizeof(knoop *) * aantal);
/*eerste woord inlezen*/
printf("Eerste woord: ");
scanf("%80s", buf);
if (strcmp(buf, "STOP") == 0) {
} else {
i = 0;
while (strcmp(buf, "STOP") != 0) {
/* checken of output langer is en zodanig vrijmaken*/
if (buf[strlen(buf) - 1] == '\n') {
buf[strlen(buf) - 1] = 0;
} else {
while (getchar() != '\n')
;
}
/*eerste koppen aanmaken*/
if (arr[i] == 0) {
/* eerste knoop aanmaken en helper naar wijzen */
arr[i] = malloc(sizeof(knoop));
helper[i] = arr[i];
} else {
/*volgende knoop maken*/
helper[i]->next = malloc(sizeof(knoop));
helper[i] = helper[i]->next;
}
/*woord toevoegen*/
lengte = strlen(buf) + 1;
helper[i]->woord = malloc(lengte * sizeof(char));
strcpy(helper[i]->woord, buf);
/*volgend inlezen*/
printf("\nVolgende: ");
scanf("%80s", buf);
/*teller omhoog*/
i++;
/*teller resetten*/
if (i == aantal) {
i = 0;
}
}
/*alle laatste knopen op 0 zetten*/
for (i = 0; i < aantal; i++) {
helper[i]->next = 0;
}
}
free(helper);
return arr;
}
int main() {
knoop **arr = geef_array_van_lijst(3);
//knoop *l = woorden_lijst();
//print_lijst(l);
printf("\n");
print_lijst_array(arr);
return 0;
}
|
C
|
#include <stdio.h>
#define M 1000000007
int n,k,i,c,d;
long long y,z,u,v,r;
int F(int a,int b){
int r=1;
for (;b;b>>=1,a=(long long)a*a%M){
if (b&1)r=(long long)r*a%M;
}
return r;
}
int main(int argc, char *argv[]){
scanf("%d%d",&n,&k);
if (n<=++k){for(i=1;i<=n;i++)r+=F(i,k-1);}
else{
for (u=v=1;i<=k;i++){u=(u*(n-i))%M;if (i)v=((v*-i)%M+M)%M;}
for (i=0,c=1,d=k;i<=k;i++,c++,d--){
z=(z+F(i,k-1))%M;
y=u*z%M*F(n-i,M-2)%M*F(v,M-2)%M;
v=v*c%M*F(d,M-2)%M;
if(i&1)y=M-y;
r+=y;
}
}
if (!--k&&n>1)r--;
printf("%lld\n",r%M);
}
|
C
|
#include <stdio.h>
#include <fcntl.h>
#include <stdlib.h>
#include <semaphore.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <time.h>
#include <stdio.h>
#include <sys/time.h>
#include <memory.h>
#include <errno.h>
#include <math.h>
#include <stdbool.h>
#include <string.h>
#include <sys/shm.h>
#include <sys/stat.h>
#include <sys/mman.h>
#define EGGS 1
#define FLOUR 2
#define BUTTER 3
#define SUGAR 4
#define NUMBER 6
#define SIZE 1024
struct chef{
int id;
int processID;
int eksik1;
int eksik2;
};
const char *name = "sharedMemName";
sem_t *eggs=NULL;
sem_t *flour=NULL;
sem_t *butter=NULL;
sem_t *sugar=NULL;
sem_t *sem=NULL;
struct chef chefs[NUMBER];
int shm_fd;
void *ptr;
static void ctrl_c(int signum){
if (signum == SIGINT) {
printf("process get SIGINT\n");
close(shm_fd);
sem_close(sem);
sem_close(eggs);
sem_close(flour);
sem_close(butter);
sem_close(sugar);
exit(1);
} else {
printf("Not a SIGINT signal: %d (%s)\n", signum, strsignal(signum));
}
}
int execute();
int getID(int pid){
for(int i=0;i<NUMBER;i++){
if(chefs[i].processID==pid)
return i;
}
return -1;
}
int main(int argc,char *argv[]){
srand(time(NULL));
execute(NUMBER);
return 0;
}
char *getItem(int i){
char *res;
switch(i){
case 1:res="eggs";break;
case 2:res="flour";break;
case 3:res="butter";break;
case 4:res="sugar";break;
default:res="non";break;
}
return res;
}
void *proc_create(int *parent) {
*parent=getpid();
for (int i = 0; i < NUMBER; i++) {
int pid = fork();
if (pid < 0) {
perror("Fork Failed!");
exit(1);
} else if (pid == 0) {
chefs[i].processID = getpid();
chefs[i].id=i;
return NULL;
} else {
}
}
}
void duzenle(){
chefs[0].eksik1=1;chefs[0].eksik2=2;
chefs[1].eksik1=1;chefs[1].eksik2=3;
chefs[2].eksik1=1;chefs[2].eksik2=4;
chefs[3].eksik1=2;chefs[3].eksik2=3;
chefs[4].eksik1=2;chefs[4].eksik2=4;
chefs[5].eksik1=3;chefs[5].eksik2=4;
}
int isEmptySharedMem(){
sem_wait(sem);
char *res;
/*
ptr = mmap(0,SIZE, PROT_READ | PROT_WRITE, MAP_SHARED, shm_fd, 0);
if (ptr == MAP_FAILED) {
printf("Map failed(isEmpty)\n");
return -1;
}*/
res=ptr;
char x;
x=*res;
sem_post(sem);
//printf("okunandeger(isEmpty):%d\n",(int)x-48);
if(((int)x-48)==0){
return 1;
}else
return 0;
}
int returnValueOfSharedMem(int *eksik1,int *eksik2){
sem_wait(sem);
char *res;
/*
ptr = mmap(0,SIZE, PROT_READ | PROT_WRITE, MAP_SHARED, shm_fd, 0);
if (ptr == MAP_FAILED) {
printf("Map failed(returnvalueofsharedmem)\n");
return -1;
}*/
res=ptr;
char x;
x=*res;
//printf("%d\n",(int)x-48);
if(((int)x-48)!=0){
//printf("asdad\n");
char a,b;
a=*res;res++;
b=*res;
*eksik1=((int)a-48);
*eksik2=((int)b-48);
}
sem_post(sem);
return 1;
}
int isMatched(int pid,int id,int eksik1,int eksik2,int *returnid){
//printf("pid:%d,id:%d,eks1:%d,eks2:%d\n",pid,id,eksik1,eksik2);
if((eksik1==chefs[getID(getpid())].eksik1 && eksik2==chefs[getID(getpid())].eksik2) ||
(eksik2==chefs[getID(getpid())].eksik1 && eksik1==chefs[getID(getpid())].eksik2)){
//printf("pid:%d,id:%d,eks1:%d,eks2:%d\n",pid,id,eksik1,eksik2);
{
*returnid=getID(getpid());
return 1;
}
}
else
return 0;
}
void clearMem(){
sem_wait(sem);
void *temp=ptr;
/*
ptr = mmap(0,SIZE, PROT_READ | PROT_WRITE, MAP_SHARED, shm_fd, 0);
if (ptr == MAP_FAILED) {
printf("Map failed(clearMem)\n");
return ;
}*/
sprintf(temp,"%d",0);
sem_post(sem);
}
int postSem(int val){
int temp;
if(val==1){
sem_getvalue(eggs,&temp);
//printf("%d de postBefore.degeri:%d\n",val,temp);
sem_post(eggs);
sem_getvalue(eggs,&temp);
//printf("%d den postAfter.degeri:%d\n",val,temp);
}
if(val==2){
sem_getvalue(flour,&temp);
//printf("%d de postBefore.degeri:%d\n",val,temp);
sem_post(flour);
sem_getvalue(flour,&temp);
//printf("%d den postAfter.degeri:%d\n",val,temp);
}
if(val==3){
sem_getvalue(butter,&temp);
//printf("%d de postBefore.degeri:%d\n",val,temp);
sem_post(butter);
sem_getvalue(butter,&temp);
//printf("%d den postAfter.degeri:%d\n",val,temp);
}
if(val==4){
sem_getvalue(sugar,&temp);
//printf("%d de postBefore.degeri:%d\n",val,temp);
sem_post(sugar);
sem_getvalue(sugar,&temp);
//printf("%d den postAfter.degeri:%d\n",val,temp);
}
}
int waitSem(int val){
int temp;
if(val==1){
sem_getvalue(eggs,&temp);
//printf("%d de tikandi.degeri:%d\n",val,temp);
sem_wait(eggs);
sem_getvalue(eggs,&temp);
//printf("%d den gecti.degeri:%d\n",val,temp);
}
if(val==2){
sem_getvalue(flour,&temp);
//printf("%d de tikandi.degeri:%d\n",val,temp);
sem_wait(flour);
sem_getvalue(flour,&temp);
//printf("%d den gecti.degeri:%d\n",val,temp);
}
if(val==3){
sem_getvalue(butter,&temp);
//printf("%d de tikandi.degeri:%d\n",val,temp);
sem_wait(butter);
sem_getvalue(butter,&temp);
//printf("%d den gecti.degeri:%d\n",val,temp);
}
if(val==4){
sem_getvalue(sugar,&temp);
//printf("%d de tikandi.degeri:%d\n",val,temp);
sem_wait(sugar);
sem_getvalue(sugar,&temp);
//printf("%d den gecti.degeri:%d\n",val,temp);
}
}
void whosalerPut(){
sem_wait(sem);
void *tempPtr=ptr;
int r=rand()%5;
int flag=1;
while(flag){
if(r!=0)
flag=0;
else{
r=rand()%5;
}
}
sprintf(tempPtr,"%d",r);
waitSem(r);///karısık yazma duclearrumu bunlardan cıkıyor olabılır
tempPtr++;
int r2=rand()%5;
int flag2=1;
while(flag2){
if(r2!=r && r2!=0){
flag2=0;
}
else{
r2=rand()%5;
}
}
sprintf(tempPtr,"%d",r2);
waitSem(r2);
printf("whosaler delivers %s and %s\n",getItem(r),getItem(r2));
sem_post(sem);
}
int semcontrol(){
int sem1,sem2,sem3,sem4;
sem_getvalue(eggs,&sem1);
sem_getvalue(flour,&sem2);
sem_getvalue(butter,&sem3);
sem_getvalue(sugar,&sem4);
int res=0;
int eksik1=chefs[getID(getpid())].eksik1;
int eksik2=chefs[getID(getpid())].eksik2;
if(sem1==0 && (eksik1==1 || eksik2==1))
res++;
if(sem2==0 && (eksik1==2 || eksik2==2))
res++;
if(sem3==0 && (eksik1==3 || eksik2==3))
res++;
if(sem4==0 && (eksik1==4 || eksik2==4))
res++;
if(res==2)
return 1;//bekle
else
return 0;//silmeden devam
}
bool isAllSemCLear(){
int sem1,sem2,sem3,sem4;
sem_getvalue(eggs,&sem1);
sem_getvalue(flour,&sem2);
sem_getvalue(butter,&sem3);
sem_getvalue(sugar,&sem4);
if(sem1==1 && sem2==1 && sem3==1 && sem4==1)
return true;
else
return false;
}
int execute(int N){
struct sigaction act2;
memset (&act2, '\0', sizeof(act2));
act2.sa_handler = &ctrl_c;
if (sigaction(SIGINT, &act2, NULL) < 0) {
perror ("sigaction");
return 1;
}
int parentID;//wholesaler id
shm_fd = shm_open(name, O_CREAT | O_RDWR, 0666);
ftruncate(shm_fd,8);
ptr=mmap(0,SIZE, PROT_READ | PROT_WRITE, MAP_SHARED, shm_fd, 0);
sprintf(ptr,"%d",0);
sem = sem_open("sem", O_CREAT|O_EXCL, 1, 1);
eggs = sem_open("eggs", O_CREAT|O_EXCL, 1, 1);
flour = sem_open("flour", O_CREAT|O_EXCL, 1, 1);
butter = sem_open("butter", O_CREAT|O_EXCL, 1, 1);
sugar = sem_open("sugar", O_CREAT|O_EXCL, 1, 1);
sem_unlink("sem");
sem_unlink("eggs");
sem_unlink("flour");
sem_unlink("butter");
sem_unlink("sugar");
proc_create(&parentID);
duzenle();
int count=0;
int eksik1;
int eksik2;
ptr = mmap(0,SIZE, PROT_READ | PROT_WRITE, MAP_SHARED, shm_fd, 0);
if (ptr == MAP_FAILED) {
printf("Map failed\n");
return -1;
}
while(1){
if(isEmptySharedMem()){
if(getpid()!=parentID){
if(isAllSemCLear()){
printf("chef%d is waiting for %s and %s \n",chefs[getID(getpid())].id,
getItem(chefs[getID(getpid())].eksik1),
getItem(chefs[getID(getpid())].eksik2));
fflush(stdout);
}else{
}
}else{
whosalerPut();
}
}else{
if(getpid()!=parentID){
returnValueOfSharedMem(&eksik1,&eksik2);
int returnID;
if(semcontrol()){
int returnID;
if(isMatched(getpid(),getID(getpid()),eksik1,eksik2,&returnID)){
sem_wait(sem);
void *temp=ptr;
sprintf(temp,"%d",0);
printf("chef%d is preparing the dessert\n",chefs[getID(getpid())].id);
printf("chef%d has delivered the dessert to the wholesaler\n",getID(getpid()));
printf("wholesaler has obtained the dessert and left to sell it\n");
//printf("postedItem:%s,%s\n",getItem(chefs[getID(getpid())].eksik1),getItem(chefs[getID(getpid())].eksik2));
postSem(chefs[getID(getpid())].eksik1);
postSem(chefs[getID(getpid())].eksik2);
sem_post(sem);
}else{
}
}
}else{
if(isAllSemCLear()){
printf("wholesaler is waiting for the dessert\n");
}else{
}
}
}
count++;
}
if(getpid()!=parentID){
sleep(1);
printf("pid %d process death \n", getpid());
}
if(getpid()==parentID){
if (shm_unlink(name) == -1) {
printf("Error removing %s\n",name);
exit(-1);
}
for(int i=0;i<N;i++){
wait(NULL);
}
printf("pid %d process death \n", getpid());
}
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
typedef struct node{
char data;
struct node *prev;
struct node *next;
}node_t;
typedef struct linkedlist{
node_t *head;
node_t *tail;
}linkedlist_t;
void printList(node_t *head)
{
node_t *current;
for(current = head; current != NULL; current = current->next)
{
printf("%c",current->data);
}
printf("\n");
}
void deleteList(node_t *head)
{
node_t *current;
node_t *temp;
current = head;
do
{
temp = current;
current = current->next;
free(temp);
}while(current != NULL);
}
int isPalindrome(linkedlist_t *list)
{
node_t *front;
node_t *rear;
int loop;
int palindrome;
front = list->head;
rear = list->tail;
loop = 1;
palindrome = 1;
do
{
if(front->data != rear->data)
{
loop = 0;
palindrome = 0;
}
else
{
if(front->next == rear->prev)
{
loop = 0;
}
else if(front->next == rear)
{
loop = 0;
}
else
{
front = front->next;
rear = rear->prev;
}
}
}while(loop);
return palindrome;
}
int main(void)
{
int i;
char data;
linkedlist_t dList;
node_t *element;
dList.head = dList.tail = NULL;
while(1)
{
printf("Enter one character if 'q', stop:");
scanf("%c",&data);
getchar();
if(data == 'q')
break;
element = malloc(sizeof(node_t));
assert(element != NULL);
element->data = data;
element->prev = NULL;
element->next = NULL;
if(dList.head == NULL)
{
dList.head = element;
dList.tail = element;
}
else
{
dList.tail->next = element;
element->prev = dList.tail;
dList.tail = element;
}
}
printList(dList.head);
if(isPalindrome(&dList))
{
printf("Palindrome\n");
}
else
{
printf("Not Palindrome\n");
}
deleteList(dList.head);
return 0;
}
|
C
|
#include <stdio.h>
#include <string.h>
struct SET {
char w[3];
char m[3];
char x[3];
} set;
int i;
FILE *fp;
int main() {
strcpy(set.x,"ab");
fgets(set.w,5*sizeof(char),stdin);
printf("w %s\n", set.w);
printf("m %s\n", set.m);
printf("x %s\n",set.x);
printf("\n");
fgets(set.m,5*sizeof(char),stdin);
printf("w %s\n", set.w);
printf("m %s\n", set.m);
printf("x %s\n",set.x);
}
|
C
|
#include <stdio.h>
int main(){
int contador;
int calificacion;
int total;
float promedio;
total =0;
contador =0;
printf("introdusca -1 para terminar\n");
scanf("%d",&calificacion );
while(calificacion != -1){
contador = contador +1;
printf("introdusca -1 para terminar\n");
scanf("%d",&calificacion);
}
if(contador != 0){
promedio = (float)total/contador;
printf("el promedio del grupo es %2f \n",promedio );
}
else{
printf("no se introgeron calificaciones\n");
}
return 0;
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* opt_rotations.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: rcammaro <rcammaro@student.s19.be> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/04/15 16:30:20 by rcammaro #+# #+# */
/* Updated: 2021/04/15 16:30:28 by rcammaro ### ########.fr */
/* */
/* ************************************************************************** */
#include "push_swap.h"
int del_rot_a(int new_op, t_stacks *s)
{
int past_op;
t_list *lst;
lst = s->ops;
if (!lst)
return (0);
past_op = *(int *)lst->content;
while (past_op == op_sb || past_op == op_rb || past_op == op_rrb)
{
lst = lst->next;
if (!lst)
return (0);
past_op = *(int *)lst->content;
}
if ((new_op == op_ra && past_op == op_rra)
|| (new_op == op_rra && past_op == op_ra))
{
lst_rmv_elem(&s->ops, lst);
return (1);
}
return (0);
}
int del_rot_b(int new_op, t_stacks *s)
{
int past_op;
t_list *lst;
lst = s->ops;
if (!lst)
return (0);
past_op = *(int *)lst->content;
while (past_op == op_sa || past_op == op_ra || past_op == op_rra)
{
lst = lst->next;
if (!lst)
return (0);
past_op = *(int *)lst->content;
}
if ((new_op == op_rb && past_op == op_rrb)
|| (new_op == op_rrb && past_op == op_rb))
{
lst_rmv_elem(&s->ops, lst);
return (1);
}
return (0);
}
int delete_opposite_rot(int op, t_stacks *s)
{
if (op == op_ra || op == op_rra)
return (del_rot_a(op, s));
if (op == op_rb || op == op_rrb)
return (del_rot_b(op, s));
return (0);
}
int opt_rotations(int new_op, t_stacks *s)
{
if (delete_opposite_rot(new_op, s))
return (1);
if (new_op == op_ra)
return (replace_2_rr(s, op_rb, op_sb, op_rrb));
if (new_op == op_rb)
return (replace_2_rr(s, op_ra, op_sa, op_rra));
if (new_op == op_rra)
return (replace_2_rrr(s, op_rrb, op_sb, op_rb));
if (new_op == op_rrb)
return (replace_2_rrr(s, op_rra, op_sa, op_ra));
return (0);
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_strtrim.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: sgaudin <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2015/11/26 15:55:27 by sgaudin #+# #+# */
/* Updated: 2016/02/03 10:34:12 by sgaudin ### ########.fr */
/* */
/* ************************************************************************** */
#include "includes/libft.h"
static int count_spaces(char const *s)
{
int i;
size_t spaces;
i = 0;
spaces = 0;
while (s[i] == ' ' || s[i] == '\n' || s[i] == '\t')
{
i++;
spaces++;
}
if (spaces == ft_strlen(s))
return (spaces);
while (s[i] != '\0')
i++;
i--;
while (s[i] == ' ' || s[i] == '\n' || s[i] == '\t')
{
i--;
spaces++;
}
return (spaces);
}
char *ft_strtrim(char const *s)
{
int spaces;
char *new_string;
unsigned int i;
unsigned int j;
if (!s)
return (NULL);
spaces = count_spaces(s);
i = 0;
j = 0;
new_string = (char*)malloc(sizeof(new_string) * (ft_strlen(s) - spaces));
if (new_string == NULL)
return (NULL);
if (spaces == 0)
new_string = ft_strcpy(new_string, s);
while (s[i] == ' ' || s[i] == '\t' || s[i] == '\n')
i++;
while (j < (ft_strlen(s) - spaces))
new_string[j++] = s[i++];
new_string[j] = '\0';
return (new_string);
}
|
C
|
#include "test_fs.h"
#include "fs.h"
#include "stdio.h"
#include "string.h"
#include "syscall.h"
static char buff[64];
void test_fs(void)
{
int i, j;
int fd = sys_fopen("1.txt", O_RDWR);
// printf("===============%d\n", fd);
sys_fseek(fd, 0x409F6A);
// write 'hello world!' * 10
for (i = 0; i < 5; i++)
{
sys_fwrite(fd, "hello world!\n", 13);
}
sys_move_cursor(0, 0);
sys_fseek(fd, 0x409F6A);
// read
for (i = 0; i < 5; i++)
{
sys_fread(fd, buff, 13);
for (j = 0; j < 13; j++)
{
printf("%c", buff[j]);
}
}
sys_move_cursor(0, 1);
sys_fclose(fd);
sys_exit();
}
|
C
|
#include<stdio.h>
#include<math.h>
int main()
{
int temp;
int a,b,c,i,j;
while(1)
{
scanf("%d %d",&a,&b);
if(!a&&!b) break;
if(a==1||b==1) printf("%d knights may be placed on a %d row %d column board.\n",a*b,a,b);
else if(a==2 || b==2)
{
temp=ceil((a*b)/8.0)*4;
if(a>3)
{
if(a%4==1)
{
temp-=2;
}
}
if(b>3)
{
if(b%4==1)
{
temp-=2;
}
}
printf("%d knights may be placed on a %d row %d column board.\n",temp,a,b);
}
else printf("%d knights may be placed on a %d row %d column board.\n",(a*b+1)/2,a,b);
}
return 0;
}
|
C
|
#include "separator.h"
// Estrutura de strings
stringStruct *binStringStruct[MAX_WORDS];
// Variável global de contagem de uso da estrurura
int usageBinCounter = 0;
int binarySearch(int min, int max, char *word){
// variável de chute, que será a posição media do vetor
int guess;
// Pega a media entre o maior tamanho da estrurura e o menor tamanho
guess = floor((max + min) / 2);
if(max == 0) return binInjection(word);
// Equando o maior valor for maior ou igual ao menor
if (max >= min) {
// Compara se a palavra da estrurua é igual a palavra passada
if (strcmp(binStringStruct[guess]->word, word) == 0) {
// Soma o contador dessa palavra
binStringStruct[guess]->usageCounter++;
return 0;
}
else if (strcmp(binStringStruct[guess]->word, word) < 0) {
// Soma o contador de uso da estrura
usageBinCounter++;
// chama a função novamente
return binarySearch(guess + 1, max, word);
}
else {
usageBinCounter++;
return binarySearch(min, guess - 1, word);
}
}
// chama a função de inserir a palavra quando não achamos
return binInjection(word);
}
int binInjection(char *word) {
int position = getUnicWords();
// aloca o espaço da palavra
binStringStruct[position] = (stringStruct *) malloc(sizeof(stringStruct));
// verifica se está nulo
if(binStringStruct[position] == NULL){
printf("Error");
exit(0);
}
// copia a palavra para e estrutura
strcpy(binStringStruct[position]->word, word);
binStringStruct[position]->usageCounter = 1;
binStringStruct[position]->next = NULL;
return 1;
}
// função para retornar a contagem de uso da estrurura
int getUsageBinCounter (){
return usageBinCounter;
}
// Função para impimir a estrutura
void printBinSearch(int totalWords){
int i;
for(i=0; i < totalWords; i++){
printf("\n%-20s\t->\t %d", binStringStruct[i]->word, binStringStruct[i]->usageCounter);
}
}
|
C
|
//
// Created by sids on 1/9/19.
//
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int upgrade(char *argv[],char versionNumber[]);
int main(int argc, char *argv[]){
char currentVersionNumber="v1.0.0";
upgrade(argv,currentVersionNumber); //call it if there is an upgrade argument provided
return 0;
}
int upgrade(char *argv[],char versionNumber[]){
char command[300]; //make it larger than required to idiot-proof against users calling command with a long argument {argv[0])
sprintf(command, "export currentlyInstalledVersion=%s; export calledCommand=%s; $(curl -s {upstream upgrade script link} > /tmp/upgradeScript); bash /tmp/upgradeScript; rm -rf /tmp/upgradeScript",versionNumber,argv[0]); //argv[0] gives the argument of the program & version number is current version number
system(command);
return 0;
}
|
C
|
// matrix.h
#pragma once
#include "maths/mathstypes.h"
#include "render/vgl.h"
vector matrix_vecMul(matrix m, const vector* v);
// Get the inverse of a 4x4 matrix
void matrix_inverse( matrix dst, matrix src );
void matrix_setColumn(matrix m, int col, const vector* v);
void matrix_setRow(matrix m, int row, const vector* v);
void matrix_setRotation( matrix dst, matrix src );
const vector* matrix_getCol( matrix m, int i );
// Set the translation component of a 4x4 matrix
void matrix_setTranslation(matrix m, const vector* v);
void matrix_clearTranslation( matrix m );
const vector* matrix_getTranslation(matrix m);
quaternion matrix_getRotation( matrix m );
// Initialise a matrix to the identity
void matrix_setIdentity(matrix m);
// Convert a V matrix to an OpenGL matrix
const GLfloat* matrix_getGlMatrix(matrix m);
// Multiply two matrices together ( A * B )
void matrix_mul(matrix dst, matrix a, matrix b);
// Build a matrix from a rotation and translation
void matrix_fromRotationTranslation( matrix m, quaternion rotation, vector translation );
// Copy one matrix to another
void matrix_cpy(matrix dst, matrix src);
// Build a rotation matrix from given Euler Angles
void matrix_fromEuler( matrix m, vector* euler_angles );
// Normalize a matrix (so the 3x3 rotation component consists of 3 unit axes)
void matrix_normalize( matrix m );
// Create a rotation matrix (leaving scale and translation as before - unset if it's a new matrix)
void matrix_rotX( matrix dst, float angle );
void matrix_rotY( matrix dst, float angle );
void matrix_rotZ( matrix dst, float angle );
// Build a rotation matrix (no translation) from a quaternion
void matrix_fromQuaternion( matrix dst, quaternion q );
void matrix_look( matrix m, vector forward );
void matrix_copyRotation( matrix dst, matrix src );
// Print a matrix to the output
void matrix_print( matrix src );
#ifdef UNIT_TEST
void test_matrix();
#endif // UNIT_TEST
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "my_struct.h"
#include "my_define.h"
void del(tel **plist,int *cnt){
int i,j;
char a[210]={'\0'};
if(*cnt==0){
printf("NO MEMBER\n");//ϵ ó
}
if(*cnt!=0){
printf("Name:");
scanf("%s",a);// ó ̸ Է
for(i=0;i<=(*cnt);i++){
if(strcmp(a,plist[i]->name)==0){
free(plist[i]->name);//ü
free(plist[i]->phone);
free(plist[i]->birth);
free(plist[i]);//ü
for(j=i;j<(*cnt)-1;j++){
plist[j] = plist[j+1];//ĭڷ ̵
}
plist[(*cnt)-1]=NULL;// ƹ ȰŰ
(*cnt)--;//ó
break;
}//ó̵
}
}
}
|
C
|
/* Faça um programa que um número inteiro n e inteiros a1, ... , an. E calcula
recursivamente a seguinte função para i de 0 a n:
F(n) = {0, se n=0; max(0, a1), se n=1; ai + max(F(n-1), F(n-2)). se n > 1;} */
#include<stdio.h>
int funcao(int *vetor, int n){
if(n == 0){
return 0;
}
else if(n == 1){
if(vetor[n-1] > 0){
return vetor[n-1];
}
else{
return 0;
}
}
else{
if(funcao(vetor, n-1) > funcao(vetor, n-2)){
return vetor[n-1] + funcao(vetor, n-1);
}
else{
return vetor[n-1] + funcao(vetor, n-2);
}
}
}
int main (){
int n,i;
scanf("%d", &n);
int vetor[n];
for(i=0; i<n; i++){
scanf("%d", &vetor[i]);
}
for(i=0; i<=n; i++){
printf("F(%d) = %d\n", i, funcao(vetor, i));
}
return 0;
}
|
C
|
// this test case checks wether struct copies are handled
struct s { int x; };
int main() {
struct s a;
struct s b;
a.x = 4;
b.x = 8;
a = b;
if (a.x != b.x) {
ERROR:
goto ERROR;
}
}
|
C
|
#include <stdlib.h>
#include <stdio.h>
#include "mysql.h"
MYSQL my_connection;
MYSQL_RES *res_ptr;
MYSQL_ROW sqlrow;
void display_header();
void display_row();
int main(int argc, char *argv[]) {
int res;
int first_row = 1; /* Used to ensure we display the row header exactly once when data is successfully retrieved */
mysql_init(&my_connection);
if (mysql_real_connect(&my_connection, "localhost", "rick",
"secret", "foo", 0, NULL, 0)) {
printf("Connection success\n");
res = mysql_query(&my_connection, "SELECT childno, fname, age FROM children WHERE age > 5");
if (res) {
fprintf(stderr, "SELECT error: %s\n", mysql_error(&my_connection));
} else {
res_ptr = mysql_use_result(&my_connection);
if (res_ptr) {
while ((sqlrow = mysql_fetch_row(res_ptr))) {
if (first_row) {
display_header();
first_row = 0;
}
display_row();
}
if (mysql_errno(&my_connection)) {
fprintf(stderr, "Retrive error: %s\n",
mysql_error(&my_connection));
}
mysql_free_result(res_ptr);
}
}
mysql_close(&my_connection);
} else {
fprintf(stderr, "Connection failed\n");
if (mysql_errno(&my_connection)) {
fprintf(stderr, "Connection error %d: %s\n",
mysql_errno(&my_connection),
mysql_error(&my_connection));
}
}
return EXIT_SUCCESS;
}
void display_header() {
MYSQL_FIELD *field_ptr;
printf("Column details:\n");
while ((field_ptr = mysql_fetch_field(res_ptr)) != NULL) {
printf("\t Name: %s\n", field_ptr->name);
printf("\t Type: ");
if (IS_NUM(field_ptr->type)) {
printf("Numeric field\n");
} else {
switch(field_ptr->type) {
case FIELD_TYPE_VAR_STRING:
printf("VARCHAR\n");
break;
case FIELD_TYPE_LONG:
printf("LONG\n");
break;
default:
printf("Type is %d, check in mysql_com.h\n", field_ptr->type);
} /* switch */
} /* else */
printf("\t Max width %ld\n", field_ptr->length); /* Note on versions of MySQL before 4.0 the format should be %d, rather than %ld */
if (field_ptr->flags & AUTO_INCREMENT_FLAG)
printf("\t Auto increments\n");
printf("\n");
} /* while */
}
void display_row() {
unsigned int field_count;
field_count = 0;
while (field_count < mysql_field_count(&my_connection)) {
if (sqlrow[field_count]) printf("%s ", sqlrow[field_count]);
else printf("NULL");
field_count++;
}
printf("\n");
}
|
C
|
/*
** castmania.c for azd in /home/debrau_c/cours/piscine/cpp_d02m/ex04
**
** Made by Carl DEBRAUWERE
** Login <debrau_c@epitech.net>
**
** Started on Thu Jan 5 12:29:33 2017 Carl DEBRAUWERE
** Last update Thu Jan 5 19:44:52 2017 Carl DEBRAUWERE
*/
#include <stdio.h>
#include "castmania.h"
void exec_operation(t_instruction_type inst, void *data){
if (inst == ADD_OPERATION){
t_instruction *tmp = (t_instruction *)data;;
exec_add((t_add *)tmp->operation);
if (tmp->output_type == VERBOSE)
printf("%d\n", ((t_add *)tmp->operation)->add_op.res);
}
else if (inst == DIV_OPERATION){
t_instruction *tmp = (t_instruction *)data;;
exec_div((t_div *)tmp->operation);
if (tmp->output_type == VERBOSE){
if (((t_div *)tmp->operation)->div_type == INTEGER)
printf("%d\n", ( (t_integer_op *)((t_div *)tmp->operation)->div_op)->res);
else if (((t_div *)tmp->operation)->div_type == DECIMALE)
printf("%f\n", ((t_decimale_op *) ((t_div *)tmp->operation)->div_op)->res);
}
}
}
void exec_instruction(t_instruction_type inst, void *data){
if (inst == PRINT_INT)
printf("%d\n", *((int *)data));
else if(inst == PRINT_FLOAT)
printf("%f\n", *((float *)data));
else
exec_operation(inst, data);
}
|
C
|
/*-------------------------------------------------------------------------
*
* incRecycler.c
*
*
* IDENTIFICATION
* src/backend/executor/incRecycler.c
*
*-------------------------------------------------------------------------
*/
#include "postgres.h"
#include "executor/incinfo.h"
#include "executor/incRecycler.h"
#include <float.h>
static void IncreaseIFactor(IncInfo *incInfo);
static int CalculateTrueCost(IncInfo *incInfo);
static void CalculateBenefit(Recycler *recycler);
static void DecideCacheState(Recycler *recycler);
static void UpdateState(IncInfo *incInfo, int iFactor, bool increase);
Recycler * InitializeRecycler(IncInfo **incInfo_array, int numIncInfo, int incMemory)
{
IncInfo *incInfo;
for (int i = 0; i < numIncInfo; i++)
{
incInfo = incInfo_array[i];
incInfo->true_cost[LEFT_STATE] = 0;
incInfo->true_cost[RIGHT_STATE] = 0;
incInfo->iFactor[LEFT_STATE] = 1;
incInfo->iFactor[RIGHT_STATE] = 1;
}
Recycler *recycler = (Recycler *)palloc(sizeof(Recycler));
recycler->incInfo_array = incInfo_array;
recycler->numIncInfo = numIncInfo;
recycler->memoryBudget = incMemory;
recycler->usedMemory = 0;
recycler->numStateCache = numIncInfo * MAX_STATE;
StateCache **stateCache_array = (StateCache **)palloc(sizeof(StateCache *) * recycler->numStateCache);
for (int i = 0; i < recycler->numStateCache; i++)
{
stateCache_array[i] = (StateCache *)palloc(sizeof(StateCache));
int j = i / MAX_STATE;
bool left = (i % MAX_STATE == 0);
stateCache_array[i]->incInfo = incInfo_array[j];
stateCache_array[i]->left = left;
if (left)
stateCache_array[i]->memory_size = incInfo_array[j]->memory_cost[LEFT_STATE];
else
stateCache_array[i]->memory_size = incInfo_array[j]->memory_cost[RIGHT_STATE];
stateCache_array[i]->benefit = -DBL_MAX;
stateCache_array[i]->cacheState = STATE_DROP;
}
recycler->stateCache_array = stateCache_array;
return recycler;
}
/* We update recycler when the query is invoked another time */
void UpdateRecycler(Recycler *recycler)
{
StateCache **stateCache_array = recycler->stateCache_array;
IncInfo **incInfo_array = recycler->incInfo_array;
int numStateCache = recycler->numStateCache;
StateCache *stateCache;
IncInfo *incInfo;
bool hasDelta;
int usedMem;
/* 1) Update memory size of every state
* 2) If a state has a delta, change its state to STATE_DROP; Set iFactor to 1
* 3) If a state does not have a delta, check its state; if kept, add to usedMem
* */
for (int i = 0; i < numStateCache; i++)
{
stateCache = stateCache_array[i];
incInfo = stateCache->incInfo;
stateCache->memory_size = stateCache->left ? incInfo->memory_cost[LEFT_STATE] : incInfo->memory_cost[RIGHT_STATE];
hasDelta = stateCache->left ? incInfo->leftUpdate : incInfo->rightUpdate;
if (hasDelta)
{
stateCache->cacheState = STATE_DROP;
if (stateCache->left)
incInfo->iFactor[LEFT_STATE] = 1;
else
incInfo->iFactor[RIGHT_STATE] = 1;
}
else
{
if (stateCache->cacheState == STATE_KEEPMEM)
usedMem += stateCache->memory_size;
}
}
recycler->usedMemory = usedMem;
/*
* Traverse IncInfo tree, increase iFactor for state without delta
* */
IncreaseIFactor(recycler->incInfo_array[recycler->numIncInfo - 1]);
/*
* Update state keep/drop in IncInfo using cacheState
* */
for (int i = 0; i < numStateCache; i++)
{
stateCache = stateCache_array[i];
if (stateCache->left)
stateCache->incInfo->incState[LEFT_STATE] = stateCache->cacheState;
else
stateCache->incInfo->incState[RIGHT_STATE] = stateCache->cacheState;
}
}
void ExecRecycler(Recycler *recycler)
{
IncInfo **incInfo_array = recycler->incInfo_array;
int numIncInfo = recycler->numIncInfo;
(void) CalculateTrueCost(incInfo_array[numIncInfo - 1]);
CalculateBenefit(recycler);
DecideCacheState(recycler);
}
void DestroyRecycler(Recycler *recycler)
{
}
/* The following functions are used to support UpdateRecycler */
static void IncreaseIFactor(IncInfo *incInfo)
{
if (incInfo == NULL)
return;
if (!incInfo->leftUpdate)
{
incInfo->iFactor[LEFT_STATE]++;
if (incInfo->incState[LEFT_STATE] == STATE_DROP)
IncreaseIFactor(incInfo->lefttree);
}
if (!incInfo->rightUpdate)
{
incInfo->iFactor[RIGHT_STATE]++;
if (incInfo->incState[RIGHT_STATE] == STATE_DROP)
IncreaseIFactor(incInfo->righttree);
}
}
/* The following functions are used to support ExecRecycler */
static int CalculateTrueCost(IncInfo *incInfo)
{
int true_cost = 0;
if (incInfo->lefttree != NULL && incInfo->righttree != NULL) /* Join */
{
int left_true_cost = CalculateTrueCost(incInfo->lefttree);
int right_true_cost = CalculateTrueCost(incInfo->righttree);
incInfo->true_cost[LEFT_STATE] = incInfo->keep_cost[LEFT_STATE] + left_true_cost;
incInfo->true_cost[RIGHT_STATE] = incInfo->prepare_cost[RIGHT_STATE] + right_true_cost;
if (incInfo->incState[LEFT_STATE] == STATE_DROP)
true_cost += left_true_cost;
if (incInfo->incState[RIGHT_STATE] == STATE_DROP)
true_cost += incInfo->true_cost[RIGHT_STATE];
true_cost += incInfo->compute_cost;
}
else if (incInfo->lefttree != NULL && incInfo->righttree == NULL) /* Aggregate/Material/Sort */
{
if (incInfo->type == INC_AGGHASH || incInfo->type == INC_SORT || incInfo->type == INC_MATERIAL)
{
int left_true_cost = CalculateTrueCost(incInfo->lefttree);
incInfo->true_cost[LEFT_STATE] = incInfo->prepare_cost[LEFT_STATE] + left_true_cost;
if (incInfo->incState[LEFT_STATE] == STATE_DROP)
true_cost += incInfo->true_cost[LEFT_STATE];
true_cost += incInfo->compute_cost;
}
else if (incInfo->type == INC_AGGSORT)
{
true_cost += CalculateTrueCost(incInfo->lefttree) + incInfo->prepare_cost[LEFT_STATE] + incInfo->compute_cost;
}
}
else /* Scan */
{
true_cost = incInfo->prepare_cost[LEFT_STATE] + incInfo->compute_cost;
}
return true_cost;
}
static void CalculateBenefit(Recycler *recycler)
{
StateCache **stateCache_array = recycler->stateCache_array;
int numStateCache = recycler->numStateCache;
StateCache *stateCache;
IncInfo *incInfo;
double benefit;
for (int i = 0; i < recycler->numStateCache; i++)
{
stateCache = stateCache_array[i];
incInfo = stateCache->incInfo;
if (stateCache->memory_size != 0)
{
if (stateCache->left)
stateCache->benefit = (double)(incInfo->true_cost[LEFT_STATE] * incInfo->iFactor[LEFT_STATE])/(double)stateCache->memory_size;
else
stateCache->benefit = (double)(incInfo->true_cost[RIGHT_STATE] * incInfo->iFactor[RIGHT_STATE])/(double)stateCache->memory_size;
}
}
}
static int BenefitComparator(const void * a, const void *b)
{
StateCache *a_SC = *(StateCache **)a;
StateCache *b_SC = *(StateCache **)b;
double a_benefit = a_SC->benefit, b_benefit = b_SC->benefit;
if (a_benefit <= b_benefit)
return -1;
else
return 1;
}
static void DecideCacheState(Recycler *recycler)
{
StateCache **stateCache_array = recycler->stateCache_array;
int numStateCache = recycler->numStateCache;
StateCache *stateCache;
int memoryBudget = recycler->memoryBudget;
int remainMem = recycler->memoryBudget - recycler->usedMemory;
/* Sort by benefit */
qsort((void *)stateCache_array, (size_t)numStateCache, sizeof(StateCache *), BenefitComparator);
for (int i = 0; i < numStateCache; i++)
{
stateCache = stateCache_array[i];
if (stateCache->memory_size == 0)
continue;
if (stateCache->cacheState == STATE_DROP)
{
if (stateCache->memory_size <= remainMem)
{
remainMem -= stateCache->memory_size;
stateCache->cacheState = STATE_KEEPMEM;
}
else
{
int memory_sum = 0;
double benefit_sum = 0;
int cur_memory = stateCache->memory_size;
double cur_benefit = stateCache->benefit;
double stateCount = 0;
for (int j = 0; j < numStateCache; j++)
{
if (stateCache_array[j]->cacheState == STATE_KEEPMEM)
{
stateCount++;
memory_sum += stateCache_array[j]->memory_size;
benefit_sum += stateCache_array[j]->benefit;
/* Let's keep the current state and kick out some states with smaller benefits */
if ((memory_sum + remainMem) >= cur_memory && benefit_sum/stateCount < cur_benefit)
{
for (int k = 0; k <= j; k++)
stateCache_array[k]->cacheState = STATE_DROP;
stateCache->cacheState = STATE_KEEPMEM;
remainMem = remainMem + memory_sum - cur_memory;
break;
}
}
} /* End of for loop */
}
}
}
recycler->usedMemory = memoryBudget - remainMem;
/* Now we get a new set of state configuration, update state and iFactor in the incInfo tree */
IncInfo *incInfo;
for (int i = 0; i < numStateCache; i++)
{
stateCache = stateCache_array[i];
incInfo = stateCache->incInfo;
if ((stateCache->left && stateCache->cacheState != incInfo->incState[LEFT_STATE]) || \
(!stateCache->left && stateCache->cacheState != incInfo->incState[RIGHT_STATE]))
{
if (stateCache->left)
{
incInfo->incState[LEFT_STATE] = stateCache->cacheState;
UpdateState(incInfo->lefttree, incInfo->iFactor[LEFT_STATE], (stateCache->cacheState == STATE_DROP));
}
else
{
incInfo->incState[RIGHT_STATE] = stateCache->cacheState;
UpdateState(incInfo->righttree, incInfo->iFactor[RIGHT_STATE], (stateCache->cacheState == STATE_DROP));
}
}
}
}
static void UpdateState(IncInfo *incInfo, int iFactor, bool increase)
{
if (incInfo == NULL)
return;
if (increase)
{
incInfo->iFactor[LEFT_STATE] += iFactor;
incInfo->iFactor[RIGHT_STATE] += iFactor;
}
else
{
incInfo->iFactor[LEFT_STATE] -= iFactor;
incInfo->iFactor[RIGHT_STATE] -= iFactor;
}
if (incInfo->incState[LEFT_STATE] != STATE_KEEPMEM)
UpdateState(incInfo->lefttree, iFactor, increase);
if (incInfo->incState[RIGHT_STATE] != STATE_KEEPMEM)
UpdateState(incInfo->righttree, iFactor, increase);
}
|
C
|
///*
// ֵĵ
//*/
//# include <stdio.h>
//int main()
//{
// int a[7] = { 1,2,3,4,5,6,7 };
// int i, j, t;
//
// i = 0;
// j = 6;
// while (i < j) //whileѭ
// {
// t = a[i]; //еֵ
// a[i] = a[j];
// a[j] = t;
// ++i; //ѭ
// --j;
// }
//
// for (i = 0; i < 7; ++i) //forѭ
// printf("%d\n",a[i]); //ִһߵ
//
// return 0;
//}
|
C
|
/**
* TOPPERS/EV3 サンプル 「黒い線に沿って進む」.
* 動作説明 白と黒の境界線に沿って進む。
* カラーセンサの出力の目標値を白と黒の中間値としている
*/
#include "ev3api.h"
#include "app.h"
/**
* ポートの接続対応
* Touch sensor: Port 2
* Color sensor: Port 3
* USonic sensor: Port 4
* Left motor: Port B
* Right motor: Port C
*/
const int touch_sensor = EV3_PORT_2;
const int color_sensor = EV3_PORT_3;
const int u_sonic_sensor = EV3_PORT_4;
const int left_motor = EV3_PORT_B;
const int right_motor = EV3_PORT_C;
//メインタスク
void main_task(intptr_t unused) {
//モーターポートを設定
ev3_motor_config(left_motor, LARGE_MOTOR);
ev3_motor_config(right_motor, LARGE_MOTOR);
//センサーポートを設定
ev3_sensor_config(touch_sensor, TOUCH_SENSOR);
ev3_sensor_config(color_sensor, COLOR_SENSOR);
ev3_sensor_config(u_sonic_sensor, ULTRASONIC_SENSOR);
//変数宣言
const int mid_point = 50; //明るさの目標値
const int power = 30; //モーターパワーj
int steer = 0; //ハンドル操作量
while(1){
//明るさ取得
int reflect_val = ev3_color_sensor_get_reflect(color_sensor);
//ハンドル操作量決定
if(reflect_val > mid_point){ //目標値より白い
steer = 50; //右に曲がる
}else{ //目標値より黒い
steer = -50; //左に曲がる
}
//モータ操作量を更新
ev3_motor_steer(left_motor, right_motor, power, steer);
//明るさとハンドル操作量を表示
char msg[256]= {0};
sprintf(msg, "reflect_val:%03d steer:%03d", reflect_val, steer);
ev3_lcd_draw_string(msg,0,20);
tslp_tsk(10); //スリープ 10[ms]
}
return;
}
|
C
|
// gaus2d is for 2d gaussian function.
Double_t gaus2d( Double_t* t, Double_t* par ) {
double x = t[0];
double y = t[1];
double a_x = par[0];
double c_x = par[1];
double s_x = par[2];
double a_y = par[3];
double c_y = par[4];
double s_y = par[5];
double termx = a_x * TMath::Exp( -0.5*(x-c_x)*(x-c_x) /s_x /s_x );
double termy = a_y * TMath::Exp( -0.5*(y-c_y)*(y-c_y) /s_y /s_y );
return termx * termy;
}
void _03_fit_2D() {
//======================================================
// Step 1
// prepare a TH2F histo for source data.
//
TH2F* histo2D = new TH2F( "histo2D", "histo2D",
200, 0, 200,
200, 0, 200 );
double width_x[3], width_y[3];
double center_x[3], center_y[3];
for( int i=0; i<10000; i++) {
histo2D->Fill( gRandom->Gaus( 100, 5),
gRandom->Gaus( 150, 3) );
}
// let's visualize the data
TCanvas* c1 = new TCanvas("c1","c1", 500, 375);
histo2D->Draw( "colz" );
//======================================================
// Step 2
// prepare a TF2 for the fitting.
TF2* f2 = new TF2( "f2", gaus2d, 50, 150, 50, 200, 6 );
// the syntax is very similar
// xMin, xMax, yMin, yMax, parN
// it is important to set inital values for fitting.
f2->SetParameters( 1000, 80, 8, 1000, 120, 3 );
f2->SetParLimits( 2, 0, 10); // for sigma_x
f2->SetParLimits( 5, 0, 10); // for sigma_y
f2->SetParNames( "height_x", "center_x", "sigma_x",
"height_y", "center_y", "sigma_y" );
// show the fit results.
histo2D->Fit( f2, "MN" );
// "R" for using the range defined in TF2
cout << "==================\n" << endl;
printf( "center is at x=%6.3f, y=%6.3f\n",
f2->GetParameter(1), f2->GetParameter(4));
printf( "sigma_x = %6.3f, sigma_y = %6.3f\n",
f2->GetParameter(2), f2->GetParameter(5) );
histo2D->Draw();
f2->Draw( "same");
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "tp3.h"
/* Nom: NF16 - TP03
* Sujet: Listes chaînées.
* Auteurs: Akim Sadaoui et Antoine Hars
* Section: GI01
*/
int main()
{
char id[MAX_NOM+1], filename[100];
int nb, i, choix, indice = 0;
task * T[MAX_LIST] = {NULL,NULL,NULL,NULL,NULL};
do {
printf("\n\n********************** Menu Listes **********************\n\n"
"0 - Quitter.\n"
"1 - Creer une liste de taches.\n"
"2 - Charger une liste de taches.\n"
"3 - Afficher les listes.\n"
"4 - Acceder aux taches d'une liste.\n"
"5 - Liberer une liste de taches\n"
"6 - Fusionner deux listes.\n"
"\nChoix : ");
scanf("%d", &choix);
printf("\n");
switch(choix) {
/* Quitter. */
case 0 :
printf("\n\n********************** FIN **********************\n\n");
break;
/* Creer une liste de taches. */
case 1 :
while (indice < MAX_LIST && T[indice] != NULL) {
indice++;
}
if (indice < MAX_LIST)
T[indice] = cree_liste(T[indice]);
break;
/* Charger une liste de taches. */
case 2 :
printf("Le nom du fichier de taches : ");
scanf("%s", filename);
printf("Le nombre de tâches à charger : ");
scanf("%d", &i);
printf("L'indice de la liste à modifier : ");
scanf("%d", &indice);
T[indice] = load_data(filename, i);
break;
/* Afficher les listes. */
case 3 :
for (i = 0; i < MAX_LIST; i++) {
printf("liste (%d) :\n",i);
affiche_liste(T[i]);
printf("\n");
}
break;
/* Accéder aux tâches d'une liste. */
case 4 :
printf("Choix de la liste numero : ");
scanf("%d", &indice);
if (T[indice] != NULL) {
do {
printf("\n\n********************** Menu Taches **********************\n\n"
"0 - Quitter.\n"
"1 - Afficher la liste de taches.\n"
"2 - Ajouter une tache.\n"
"3 - Annuler une tache.\n"
"4 - Executer une tache en FIFO.\n"
"5 - Executer une tache en LIFO.\n"
"6 - Inserer une tache dans la liste selon la durée.\n"
"7 - Inserer une tache dans la liste selon la priorité.\n"
"8 - Mettre à jour la priorité des taches.\n"
"9 - Revenir au menu des listes.\n"
"\nChoix : ");
scanf("%d", &choix);
printf("\n");
switch(choix) {
/* Quitter. */
case 0 :
printf("\n\n********************** FIN **********************\n\n");
break;
/* Afficher la liste de tâches. */
case 1 :
affiche_liste(T[indice]);
break;
/* Ajouter une tâche. */
case 2 :
printf("id tache : ");
scanf("%s", id);
printf("duree tache : ");
scanf("%d", &nb);
nb = ajoute_tache(T[indice], cree_tache(id,nb));
if (nb == 1)
printf("Ajout reussi.\n");
else
printf("Erreur ajout.\n");
break;
/* Annuler une tâche. */
case 3 :
printf("Tache a supprimer : ");
scanf("%s", id);
T[indice] = annule_tache(T[indice], id);
break;
/* Exécuter une tâche en FIFO. */
case 4 :
printf("Nombre de taches a executer : ");
scanf("%d", &nb);
printf("\n");
if (nb > 0) {
for (i = 0; i < nb; i++)
T[indice] = execute_tache_FIFO(T[indice]);
}
else
printf("Erreur du nombre de taches a executer.\n");
break;
/* Exécuter une tâche en LIFO. */
case 5 :
printf("Nombre de taches a executer : ");
scanf("%d", &nb);
printf("\n");
if (nb > 0) {
for (i = 0; i <nb; i++)
T[indice] = execute_tache_LIFO(T[indice]);
}
else
printf("Erreur du nombre de taches a executer.\n");
break;
/* Insérer une tâche dans la liste selon la durée. */
case 6 :
printf("id tache : ");
scanf("%s", id);
printf("duree tache : ");
scanf("%d", &nb);
T[indice] = insere_tache(T[indice], cree_tache(id,nb));
break;
/* Insérer une tâche dans la liste selon la priorite. */
case 7 :
printf("id tache : ");
scanf("%s", id);
printf("duree tache : ");
scanf("%d", &nb);
T[indice] = insere_tache_priorite(T[indice], cree_tache(id,nb));
break;
/* Mettre à jour la priorité des taches */
case 8 :
printf("Priorités décrémentés de 1.\n");
MAJ_priorite(T[indice]);
break;
/* Revenir au menu des listes. */
case 9 :
break;
default :
printf("Commande incorrecte.\n");
break;
}
} while (choix != 0 && choix != 9);
}
break;
/* Libérer la liste de tâches. */
case 5 :
printf("Choix de la liste à libérer : ");
scanf("%d", &indice);
T[indice] = libere_liste(T[indice]);
break;
/* Fusionner deux listes. */
case 6 :
printf("Indice de la premiere liste :");
scanf("%d", &nb);
printf("Indice de la seconde liste :");
scanf("%d", &indice);
T[nb] = fusion_listes(T[nb],T[indice]);
break;
default :
printf("Commande incorrecte.\n");
break;
}
} while (choix != 0);
return 0;
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_checker.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: smortier <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2017/11/20 15:22:41 by smortier #+# #+# */
/* Updated: 2017/11/24 15:45:43 by jcaille ### ########.fr */
/* */
/* ************************************************************************** */
#include "fillit.h"
static int check_column(char *str)
{
int column;
column = 0;
while (*str)
{
while (*str != '\n' && *str)
{
column += 1;
str++;
}
if (column == 0)
column = 4;
if (column != 4)
return (0);
column = 0;
if (*str)
str++;
}
return (1);
}
static int check_line(char *str)
{
int i;
int line;
i = 0;
line = 0;
while (*str)
{
while (ft_strncmp(str, "\n\n", 2) && *str)
{
str++;
line += 1;
}
if (line != 19 && line != 20)
return (0);
line = -1;
if (*str)
str++;
}
return (1);
}
static int check_char(char *str)
{
int i;
i = -1;
while (str[++i])
{
if (str[i] != '.' && str[i] != '#' && str[i] != '\n')
return (0);
}
return (1);
}
static int check_tetri(char *str)
{
int nb_hash;
int link_hash;
link_hash = 0;
while (*str)
{
nb_hash = 0;
while (ft_strncmp(str, "\n\n", 2) && *str)
{
if (*str == '#')
{
nb_hash++;
link_hash = (*(str + 5) == *str) ? link_hash += 1 : link_hash;
link_hash = (*(str + 1) == *str) ? link_hash += 1 : link_hash;
}
str++;
if (link_hash < 3 && nb_hash > 3)
return (0);
}
if (nb_hash != 4)
return (0);
link_hash = 0;
str = (*str) ? str += 1 : str;
}
return (1);
}
int ft_checker(char *str)
{
if (str == NULL)
return (0);
if (str[0] == '\0')
return (0);
if (!(check_column(str)))
return (0);
if (!(check_line(str)))
return (0);
if (!(check_char(str)))
return (0);
if (!(check_tetri(str)))
return (0);
return (1);
}
|
C
|
#include "main.h"
#include <stdio.h>
/**
* _isupper - Entry point
* Description - A function that checks for upper character
* *@c: the function accepts an input saved into c
* Return: Always 0 (Success)
*/
int _isupper(int c)
{
int letter = c;
if (letter >= 'A' && letter <= 'Z')
{
return (1);
}
else
{
return (0);
}
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_lstmap.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: idcornua <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2018/11/15 11:49:50 by idcornua #+# #+# */
/* Updated: 2018/11/15 12:45:23 by idcornua ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
t_list *ft_lstmap(t_list *lst, t_list *(*f)(t_list *))
{
void (*del)(void *, size_t);
t_list *head;
t_list *cursor;
del = ft_del;
if (!lst || !f)
return (NULL);
head = (*f)(lst);
cursor = head;
lst = lst->next;
while (lst)
{
cursor->next = (*f)(lst);
if (!cursor->next)
{
ft_lstdel(&head, del);
return (NULL);
}
lst = lst->next;
cursor = cursor->next;
}
cursor->next = NULL;
return (head);
}
/*
** === MAN ft_lstmap ===
** -
** DESCRIPTION:
** -
** ft_lstmap cree une nouvelle liste fraiche faite du resultat de
** l'application de la fonction f sur chacun des maillons de la liste
** d'origine.
** -
** ARGUMENTS:
** -
** [t_list *lst]:
** le premier maillon de la liste.
** [void (*f)(t_list *)]:
** un pointeur sur la fonction a appliquer sur les maillons de la liste.
** -
** RETOUR:
** -
** [t_list *]:
** ft_lstmap renvoie le premier maillon de la nouvelle liste.
** -
*/
|
C
|
#include <stdio.h>
void rev_intary(int v[], int n);
void printArray(int v[], int n); // 配列の中身を表示する
void main(){
int v[5] = {1, 2, 3, 4, 5};
int n = sizeof(v) / sizeof(v[0]);
printf("before : ");
printArray(v, n);
rev_intary(v, n);
printf("After : ");
printArray(v, n);
}
void rev_intary(int v[], int n){
int v2[5]; // 変更前のvの要素を保持する配列
for(int i = 0; i < n; i++){
v2[i] = v[i];
}
for(int i = 0; i < n; i++){
v[i] = v2[n - 1 - i];
}
}
void printArray(int v[], int n){
for(int i = 0; i < n; i++){
printf("%d",v[i]);
if(i != n-1) {
printf(", ");
}
}
printf("\n");
}
|
C
|
//task 1.2.8
#include <stdio.h>
#include <math.h>
double s2(unsigned n){
double y = 0;
for(unsigned i=0;i<n;++i){
y =sqrt(2+y);
}
return y;
}
int main(){
double x,y;
unsigned n;
printf("n=");
scanf("%u",&n);
y = s2(n);
printf("y=%lf",y);
}
|
C
|
/*
* fiwix/fs/ext2/namei.c
*
* Copyright 2018, Jordi Sanfeliu. All rights reserved.
* Distributed under the terms of the Fiwix License.
*/
#include <fiwix/types.h>
#include <fiwix/fs.h>
#include <fiwix/filesystems.h>
#include <fiwix/fs_ext2.h>
#include <fiwix/buffer.h>
#include <fiwix/mm.h>
#include <fiwix/errno.h>
#include <fiwix/stdio.h>
#include <fiwix/string.h>
int ext2_lookup(const char *name, struct inode *dir, struct inode **i_res)
{
__blk_t block;
unsigned int blksize;
unsigned int offset, doffset;
struct buffer *buf;
struct ext2_dir_entry_2 *d;
__ino_t inode;
blksize = dir->sb->s_blocksize;
inode = offset = 0;
dir->count++;
while(offset < dir->i_size && !inode) {
if((block = bmap(dir, offset, FOR_READING)) < 0) {
return block;
}
if(block) {
if(!(buf = bread(dir->dev, block, blksize))) {
return -EIO;
}
doffset = 0;
do {
d = (struct ext2_dir_entry_2 *)(buf->data + doffset);
if(d->inode) {
if(d->name_len == strlen(name)) {
if(strncmp(d->name, name, d->name_len) == 0) {
inode = d->inode;
}
}
doffset += d->rec_len;
} else {
doffset += sizeof(struct ext2_dir_entry_2);
}
} while((doffset < blksize) && (!inode));
brelse(buf);
offset += blksize;
if(inode) {
/*
* This prevents a deadlock in iget() when
* trying to lock '.' when 'dir' is the same
* directory (ls -lai <dir>).
*/
if(inode == dir->inode) {
*i_res = dir;
return 0;
}
if(!(*i_res = iget(dir->sb, inode))) {
return -EACCES;
}
iput(dir);
return 0;
}
} else {
break;
}
}
iput(dir);
return -ENOENT;
}
|
C
|
/*
* sockopt_loop.c - IP_MULTICAST_LOOP socket option test
* Copyright (C) 2012 Red Hat Inc.
*
* Author: Radek Pazdera (rpazdera@redhat.com)
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301, USA.
*/
#include "sockopt_utils.h"
void test_loop()
{
int value;
size_t size = sizeof(value);
value = 1;
test_getsockopt("IP_MULTICAST_LOOP default value",
IP_MULTICAST_LOOP, &value, size, 4);
value = 0;
test_sockopt_value("IP_MULTICAST_LOOP set to zero",
IP_MULTICAST_LOOP, &value, size, 4);
/* Errors */
test_setsockopt_error("IP_MULTICAST_LOOP bad optlen",
IP_MULTICAST_LOOP, &value, 0, EINVAL, 4);
}
void test_loop_v6()
{
int value;
size_t size = sizeof(value);
value = 1;
test_getsockopt("IPV6_MULTICAST_LOOP default value",
IPV6_MULTICAST_LOOP, &value, size, 6);
value = 0;
test_sockopt_value("IPV6_MULTICAST_LOOP set to zero",
IPV6_MULTICAST_LOOP, &value, size, 6);
/*Error*/
test_setsockopt_error("IPV6_MULTICAST_LOOP bad optlen",
IPV6_MULTICAST_LOOP, &value, 0, EINVAL, 6);
value = 2;
test_setsockopt_error("IPV6_MULTICAST_LOOP set to 2",
IPV6_MULTICAST_LOOP, &value, size, EINVAL, 6);
value = -1;
test_setsockopt_error("IPV6_MULTICAST_LOOP set to -1",
IPV6_MULTICAST_LOOP, &value, size, EINVAL, 6);
}
int main(int argc, char* argv[])
{
int version=4;
parse_args(argc, argv, &version);
if ( version !=4 && version != 6)
{
usage(argv[0]);
return 1;
}
initialize(version);
version == 4?test_loop():test_loop_v6();
report_and_exit();
return 0;
}
|
C
|
// C02EX05.C
#include <stdio.h>
int main(void)
{
char PAUSA;
int A, B, R;
printf("Informe um valor para a variavel <A>: ");
scanf("%3i", &A);
while((getchar() != '\n') && (!EOF));
printf("Informe um valor para a variavel <B>: ");
scanf("%3d", &B);
while((getchar() != '\n') && (!EOF));
R = A + B;
printf("Resultado = %i\n", R);
printf("\n");
printf("Tecle <Enter> para encerrar... ");
PAUSA = getchar();
return 0;
}
|
C
|
#include <stdio.h>
int main()
{
int case_num;
scanf("%d%*c", &case_num);
while (case_num--) {
int ans = 0;
int continuous = 0;
int ch;
ch = getchar();
while (ch != '\n' && ch != EOF) {
if (ch == 'X') {
continuous = 0;
}
else if (ch == 'O') {
++continuous;
ans += continuous;
}
ch = getchar();
}
printf("%d\n", ans);
}
return 0;
}
|
C
|
//
// Created by tomco on 27/09/2021.
//
#ifndef ING3_MESFONCTIONS_H
#define ING3_MESFONCTIONS_H
int getmax(int a, int b);
/*
* Fonction qui permet de donner le plus grand nombre entre deux
* in : deux entier
* out : le plus grand des deux
*/
int calculPerimetre(int l, int L);
/*
* Fonction qui permet de calculer le perimetre d'un rectangle
* in : la longueur et la largeur
* out : le perimetre
*/
int SaisirEntier();
/*
* Fonction qui permet de saisir un entier
* in : rien
* out : l'entier saisis
*/
int calculaire(int l, int L);
/*
* Fonction qui permet de calculer l'aire d'un rectangle
* in : la longueur et la largeur
* out : l'aire
*/
void CalculEX3(int a);
/*
* Fonction qui permet de voir si un nombre est divisible par 3 et si il est supérieur à 10
* in : un entier
* out : rien
*/
int calculmoyenne(int a, int b, int c);
/*
* Fonction qui êrmet de calculer la moyenne de 3 notes
* in : les 3 notes saisie
* out: la moyenne
*/
int compare(int a, int b);
/*
* Fonction qui permet de voir si deux nombre sont multiple entre eux
* in : deux entier
* out : 0 ou 1
*/
void calculexo8(int n);
/*
* Fonction qui permet de savoir si un nombre est multiple de deux ou de 7
* in : un entier
* out : rien
*/
void calculexo9(int nbBlock);
/*
* fonction qui permet de savoir combien d'etage on peut construire et combien de block il nous restes
* in : le nombre de block
* out : rien
*/
int calculexo10();
/*
* fonction qui nous permet de calculer la moyenne de notes saisie et se coupe quand une note est négative
* in : rien
* out : la moyenne
*/
#endif //ING3_MESFONCTIONS_H
|
C
|
/*
* eeprom.h
*
* Created on: May 7, 2019
* Author: shahira ibrahim
*/
#ifndef EEPROM_H_
#define EEPROM_H_
#include "i2c.h"
/***************************************preprocessors*********************************************/
#define ERROR 0 /*it's used as an indication in case of some thing went wrong through transaction process*/
#define SUCCESS 1 /*it's used as an indication that the process of sending or receiving data is correct*/
/****************************************************************************************************/
/********************************************functions prototypes***********************************/
/* function description: initiating EEPROM by initiating I2C module*/
void EEPROM_init(void);
/*function description: function for receiving one byte of data through EEPROM*/
uint8 EEPROM_readByte(uint16 address,uint8*data);
/*function description: function for sending one byte of data through EEPROM*/
uint8 EEPROM_writeByte(uint16 address,uint8 data);
#endif /* EEPROM_H_ */
|
C
|
/*
C Implementation of Tom7-fselect stream cipher.
This code is distributed under the GNU public license;
see http://www.gnu.org/copyleft/gpl.html.
I can't make any claims about the security of this algorithm because
I am not a trained cryptographer, though it produces (as far as I can
tell) statistically random output. This code should be thought about,
but not used unless you know more about this than me.
The biggest fault I see with this is that the generators are not
all relatively prime in length -- Applied Cryptography did not have
enough given for me to pick 7 that were. The period is still something
pretty huge, at least 2^127 bits before it repeats.
Tom 7
http://www.andrew.cmu.edu/~twm/
*/
#include <stdio.h>
typedef struct {
unsigned long data;
unsigned long mask;
unsigned char len;
} LFSR;
int func_thresh(char * bits);
int func_xor(char * bits);
int func_sum(char * bits);
int func_notthresh(char * bits);
unsigned char generator(LFSR * gen);
int (*func[])(char * bits) = {
func_thresh,
func_xor,
func_sum,
func_notthresh,
};
LFSR G[7] ={
{0,(1<<31)|(1<<6)|(1<<4)|(1<<2)|(1<<1)|1,31},
{0,(1<<29)|(1<<5)|(1<<3)|1,29},
{0,(1<<30)|(1<<12),30},
{0,(1<<18)|(1<<4)|(1<<1)|1,18},
{0,(1<<16)|(1<<4),16},
{0,(1<<12)|(1<<3)|(1<<2)|1,12},
{0,(1<<31)|(1<<6)|(1<<2)|(1<<1)|1,31},
/* {0,(1<<22)|(1<<4),22}, */
/* {1329078,(1<<10)|(1<<1),10}, */
};
unsigned char SUM_CARRY=0;
#define CARRY_LEN 7 /* that's 111 binary, not 7 bits. */
/* G[5], G[6] are selector bits for the functions.
G[0] through G[4] are the inputs for f[0,1,2,3] */
main (int argc, char**argv) {
unsigned char bits[5], output, *key;
unsigned int x,z,a,s,c;
if (argc>=2) key = argv[1]; else { printf("%s key\n",argv[0]); exit(-1); }
s = strlen(key);
for (x=c=0;x<7;x++) {
G[x].data |= key[c++%s] << 24;
G[x].data |= key[c++%s] << 16;
G[x].data |= key[c++%s] << 8 ;
G[x].data |= key[c++%s] ;
a = key[c++%s]; while (a--) generator(&G[x]);
}
if (argc>=3) z = atoi(argv[2]); else z=1000;
if (argc>=4) a = atoi(argv[3]); else a=-1;
if (a == -1) {
/* for (x=0;x<4;x++) init[x](); */
while (z--) {
for(x=0;x<5;x++) bits[x] = generator(&G[x]);
output = func[(generator(&G[5])<<1)|generator(&G[6])](bits);
putchar('0'+output);
}
} else while (z--) {
putchar('0' +generator(&G[a%7]));
}
}
int func_thresh(char * bits) {
int c=0,x;
for(x=0;x<5;x++) if (bits[x]) if (++c==3) return 1;
return 0;
}
int func_xor(char * bits) {
int c=0,x;
for(x=0;x<5;x++) c ^= bits[x];
return c&1;
}
int func_sum(char * bits) {
int c=0,x;
for(x=0;x<5;x++)
if (bits[x]) if (++SUM_CARRY>CARRY_LEN) SUM_CARRY=0;
return SUM_CARRY&1;
}
int func_notthresh(char * bits) {
int c=0,x;
for(x=0;x<5;x++) if (!bits[x]) if (++c==3) return 1;
return 0;
}
unsigned char generator(LFSR * g) {
if (!g->data) g->data++; /* keys of all 0's would ruin this algorithm! */
if (g->data & 1) {
g->data = ((g->data ^ g->mask) >> 1)
| (1<<g->len); /* g->len is already len-1 */
return 1;
} else {
g->data>>=1; return 0;
}
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* nelsonac.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: lmeyre <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2018/03/03 23:01:22 by lmeyre #+# #+# */
/* Updated: 2018/03/03 23:07:19 by lmeyre ### ########.fr */
/* */
/* ************************************************************************** */
#include "../../includes/push_swap.h"
static void fill_nelson_two(t_env *env, int size)
{
while (size)
{
if (VAL_A->content > VAL_A->next->content
&& VAL_B->content > VAL_B->next->content)
env->tab_order[2](env);
else if (VAL_A->content > VAL_A->next->content)
env->tab_order[0](env);
else if (VAL_B->content > VAL_B->next->content)
env->tab_order[1](env);
env->tab_order[7](env);
env->tab_order[7](env);
size -= 2;
}
}
static void nelson_two(t_env *env)
{
int size;
int exception;
exception = 0;
size = ft_lst_size(env->list_b);
size = (size / 2) * 2;
if ((ft_lst_size(env->list_a) - (size)) == 2)
exception = 1;
fill_nelson_two(env, size);
if (exception == 1)
{
if (VAL_A->content > VAL_A->next->content)
env->tab_order[0](env);
env->tab_order[7](env);
env->tab_order[5](env);
}
if ((ft_lst_size(env->list_a) % ((ft_lst_size(env->list_a) / 2) * 2)) == 1)
{
if ((ft_lst_size(env->list_b) % ((ft_lst_size(env->list_b) / 2)
* 2)) == 1)
env->tab_order[7](env);
else
env->tab_order[5](env);
}
}
static void put_b_except_trash(t_env *env, int stack_a, int stack_b)
{
while (stack_a || stack_b)
{
if (stack_b && ((VAL_B->content < VAL_A->content)
|| stack_a == 0))
{
--stack_b;
env->tab_order[3](env);
}
else
--stack_a;
env->tab_order[5](env);
}
}
static void merge_trash(t_env *env, int ltl_trash, int total, int trash_b)
{
if (ltl_trash > 0)
{
while (total--)
{
if (trash_b == 0 ||
(ltl_trash > 0 && VAL_A->content < VAL_B->content))
{
env->tab_order[4](env);
--ltl_trash;
}
else
--trash_b;
(ft_lst_size(env->list_b) > 1) ? env->tab_order[6](env) : 0;
}
}
total = ft_lst_size(env->list_a);
while (env->list_b || total)
{
if (env->list_b && ((VAL_B->content < VAL_A->content)
|| total == 0))
env->tab_order[3](env);
else
--total;
env->tab_order[5](env);
}
}
void launch_nelson(t_env *env, int ltl_trash, int stack, int size)
{
size = ft_lst_size(env->list_a) / 2;
while (size)
{
env->tab_order[4](env);
size--;
}
size = ft_lst_size(env->list_a);
nelson_two(env);
stack = 4;
size = ft_lst_size(env->list_b);
while (stack <= size)
{
nelson_grow(env, stack, stack / 2);
stack *= 2;
}
stack /= 2;
ltl_trash = ft_lst_size(env->list_a) - stack;
put_b_except_trash(env, stack, stack);
merge_trash(env, ltl_trash, (ft_lst_size(env->list_b) + ltl_trash),
ft_lst_size(env->list_b));
}
|
C
|
/* Consideracoes so far: talvez remover a cabeca seja melhor */
#include<stdio.h>
#include "TMemoria.h"
void zeraMemoria(TMemoria* pMemoria){
int i;
// Inicializando parametros da lista
pMemoria->priCelulaDisp = 0;
pMemoria->primeiro = -1;
pMemoria->ultimo = -1;
pMemoria->numOcupadas = 0;
// Inicializando indices vazios
for (i = 0; i < MAX_SIZE-1; i++) {
pMemoria->items[i].prox = i+1;
pMemoria->items[i].ant = i-1;
}
pMemoria->items[MAX_SIZE-1].prox = -1;
pMemoria->items[MAX_SIZE-1].ant = MAX_SIZE-2;
//pMemoria->ultCelulaDisp = MAX_SIZE-1;
}
int memoriaVazia(TMemoria* pMemoria){
if(!pMemoria->numOcupadas) return 1;
return 0;
}
int numeroOcupadas(TMemoria* pMemoria){
return pMemoria->numOcupadas;
}
/* encontraLugar e uma funcao auxiliar para encontrar o lugar
de um Item na sequencia de chaves. O indice retornado corresponde
ao item depois do qual a sequencia deve ser deslocada para a direita. */
int encontraAnterior(TMemoria* pMemoria, int chave){
int i, ichave, anti;
if(memoriaVazia(pMemoria)) return -1;
anti = -1;
i = pMemoria->primeiro;
ichave = pMemoria->items[i].item.chave;
while((chave > ichave) && (i != -1)){
anti = i;
i = pMemoria->items[i].prox;
if(i!=-1) ichave = pMemoria->items[i].item.chave;
}
return anti;
}
int insereItem(TMemoria* pMemoria, TItem* pItem){
int idx, antidx, proxidx;
if(pMemoria->numOcupadas==MAX_SIZE) return 0; // Uma das formas de verificar se ha espaco livre
idx = pMemoria->priCelulaDisp;
pMemoria->items[idx].item = *pItem;
pMemoria->priCelulaDisp = pMemoria->items[idx].prox;
if(!(pMemoria->priCelulaDisp==-1)) pMemoria->items[pMemoria->priCelulaDisp].ant = -1;
if(memoriaVazia(pMemoria)){
pMemoria->primeiro = idx;
pMemoria->ultimo = idx;
pMemoria->items[idx].prox = -1;
pMemoria->items[idx].ant = -1;
pMemoria->numOcupadas++;
return 1;
}
// Encontra lugar na sequencia de chaves
antidx = encontraAnterior(pMemoria, pItem->chave);
pMemoria->items[idx].ant = antidx;
// Caso o item ocupe a primeira posicao
if(antidx == -1){
proxidx = pMemoria->primeiro;
pMemoria->primeiro = idx;
} else{
proxidx = pMemoria->items[antidx].prox;
pMemoria->items[antidx].prox = idx;
}
pMemoria->items[idx].prox = proxidx;
if(!(proxidx == -1)) pMemoria->items[proxidx].ant = idx;
if(pItem->chave>pMemoria->items[pMemoria->ultimo].item.chave) pMemoria->ultimo = idx;
pMemoria->numOcupadas++;
return 1;
}
int removePrimeiro(TMemoria* pMemoria, TItem* out_item){
int pri_idx, novopri_idx;
pri_idx = pMemoria->primeiro; // Indice do item a ser removido
if(pri_idx==-1) return 0;
novopri_idx = pMemoria->items[pri_idx].prox; // Indice do novo primeiro item
// Atualizando primeiro
pMemoria->primeiro = novopri_idx;
if(!novopri_idx==-1) pMemoria->items[novopri_idx].ant = -1;
// Atualizando lista de memoria livre
pMemoria->items[pri_idx].prox = pMemoria->priCelulaDisp;
pMemoria->priCelulaDisp = pri_idx;
// Setando valor de retorno em out_item
*out_item = pMemoria->items[pri_idx].item;
pMemoria->numOcupadas--;
return 1;
}
int removeUltimo(TMemoria* pMemoria, TItem* out_item){
int ult_idx, novoult_idx;
ult_idx = pMemoria->ultimo; // Indice do item a ser removido
if(ult_idx==-1) return 0;
novoult_idx = pMemoria->items[ult_idx].ant; // Indice do novo primeiro item
// Atualizando ultimo
pMemoria->ultimo = novoult_idx;
if(novoult_idx!=-1) pMemoria->items[novoult_idx].prox = -1;
// Atualizando lista de memoria livre
pMemoria->items[ult_idx].prox = pMemoria->priCelulaDisp;
pMemoria->priCelulaDisp = ult_idx;
// Setando valor de retorno em out_item
*out_item = pMemoria->items[ult_idx].item;
pMemoria->numOcupadas--;
return 1;
}
/* Fancy output:
Imprime sequencia da lista.
Para fins de ser lindo. Ou quase. */
void imprimeSequencia(TMemoria *pMemoria){
int i;
if(memoriaVazia(pMemoria)){
printf("Memoria toda vazia.\n");
return;
}
i=pMemoria->primeiro;
printf("Tamanho total: %d\n", pMemoria->numOcupadas);
printf("addr key value\n");
while(i!=-1){
printf("%4d %4d %4d\n", i, pMemoria->items[i].item.chave,
pMemoria->items[i].item.data);
i = pMemoria->items[i].prox;
}
}
/* Raw output:
Imprime na sequencia da memoria, sem diferenciar livre de ocupado.
Para fins de depuracao. */
void rawPrint(TMemoria *pMemoria){
int i;
for(i=0; i<MAX_SIZE; i++){
printf("%4d %4d %4d %4d %4d\n", i, pMemoria->items[i].item.chave,
pMemoria->items[i].item.data,
pMemoria->items[i].ant,
pMemoria->items[i].prox);
}
}
|
C
|
/*
Check whether the given binary tree is sum tree or not
Sum tree is the one where sum of values in the LST and sum of values in the RST is equal to the root.
This is valid for all the nodes except the tree
METHOD:
We do post order traversal of the tree where first we compute LST, then RST then we compare if root value
is equal to LST value and RST value sum else we return -1. If equal we return sum of RST, LST and root->data
Time complexity: O(n)
Space complexity: O(n)
*/
#include <stdio.h>
#include <stdlib.h>
struct node{
int data;
struct node *left;
struct node *right;
};
struct node *newNode(int data){
struct node *temp = (struct node *)malloc(sizeof(struct node));
temp->data = data;
temp->left = temp->right= NULL;
return temp;
}
int checkSum(struct node *root){
if(!root){
return 0;
}
if(!root->left && !root->right){
return root->data;
}
int left = checkSum(root->left);
int right = checkSum(root->right);
if(root->data == left + right){
return 2*root->data;
}
return -1;
}
int main(){
struct node *root = newNode(50);
root->left = newNode(15);
root->left->left = newNode(10);
root->left->right = newNode(5);
root->right = newNode(10);
root->right->left = newNode(7);
root->right->right = newNode(3);
int isSumTree = checkSum(root);
if(isSumTree > 0){
printf("given tree is a sum tree\n");
}else{
printf("given tree is not a sum tree\n");
}
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include "ChannelsAndJunctions.h"
#include "mathfunctions.h"
/***************************************************************************************//**
* @file computeL.c
*
* This file contains code to evaluate the right hand side of the following discrete ODE
* obtained from the DG discretization of the 1-D St. Venant equations:
*
* \f$\frac{\partial \hat{\mathbf{w}}}{\partial t} = M^{-1} L(\hat{\mathbf{w}}, t)\f$
*
********************************************************************************************/
/* @cond FUNCTION_PROTOTYPES */
extern const double g;
extern void Compute1DInnerProducts(struct channel *Chan, int el, double *IP);
extern void RoeFlux1D(double A_L, double A_R, double Q_L, double Q_R, double b, double g, double beta, double *Fhat);
extern void LF(double A_L, double A_R, double Q_L, double Q_R, double b, double g, double *Fhat);
extern double getBeta(struct channel *Chan, int edge, int channelNumber, double time);
/* @endcond */
/***************************************************************************************//**
* Function for evaluating the right hand side of the discrete ODE obtained from the DG
* discretization of the 1-D St. Venant equations
* @param [in] Chan a pointer to the channel structure corresponding to the channel that is
* currently being worked on
* @param [in] time a double representing the current time of the simulation
* @param [in] channelNumber an integer number designated for the channel that is currently
* being worked on. This is only there for debugging purposes and we might not need it anymore.
* @param [out] RHSA a pointer to an array of size NumEl x 2 in which the right hand side for
* the wet cross-sectional area will be stored
* @param [out] RHSQ a pointer to an array of size NumEl x 2 in which the right hand side for
* the volumetric discharge will be stored
*
* *********************************************************************************************/
void computeL(struct channel *Chan, double time, int channelNumber, double *RHSA, double *RHSQ)
{
/************** Compute the flux (Roe's flux) at the faces *****************/
int NumNodes = Chan->NumNodes;
int NumEl = Chan->NumEl;
double Fhat1L[NumNodes];
double Fhat2L[NumNodes];
double Fhat1R[NumNodes];
double Fhat2R[NumNodes];
double beta = 1;
//getBeta(Chan, NumNodes-1,channelNumber, time);
for (int i=0; i < NumNodes; ++i)
{
double A_L, Q_L, A_R, Q_R, b;
b = Chan->b[i];
double tmpF[2];
#ifdef WDON
// Check to see if the elements separated by this boundary are both dry
if (i > 0 && i < NumNodes-1)
{
if (Chan->WD[i-1] == 0 && Chan->WD[i] == 0)
{
// Reflection flux for the left element
A_L = Chan->A[2*i];
A_R = A_L;
Q_L = Chan->Q[2*i];
Q_R = -Q_L;
RoeFlux1D(A_L, A_R, Q_L, Q_R, b,0,beta,tmpF);
Fhat1L[i] = tmpF[0];
Fhat2L[i] = tmpF[1];
// Reflection flux for the right element
A_R = Chan->A[2*i+1];
A_L = A_R;
Q_R = Chan->Q[2*i+1];
Q_L = -Q_R;
RoeFlux1D(A_L, A_R, Q_L, Q_R, b, 0,beta,tmpF);
Fhat1R[i] = tmpF[0];
Fhat2R[i] = tmpF[1];
if (isnan(tmpF[0]) || isnan(tmpF[1]))
{
printf("1D both element dry flux not a number, edge %d\n",i);
exit(EXIT_FAILURE);
}
}
}
// if the elements are not both dry
if (i == 0 || i == NumEl || Chan->WD[i-1] == 1 || Chan->WD[i] == 1)
{
A_L = Chan->A[2*i];
A_R = Chan->A[2*i+1];
Q_L = Chan->Q[2*i];
Q_R = Chan->Q[2*i+1];
RoeFlux1D(A_L, A_R, Q_L, Q_R, b, g,beta,tmpF);
if (isnan(tmpF[0]) || isnan(tmpF[1]))
{
printf("1D both elements wet flux not a number, edge %d\n", i);
exit(EXIT_FAILURE);
}
if (i == 0 || Chan->WD[i-1] == 1)
{
Fhat1L[i] = tmpF[0];
Fhat2L[i] = tmpF[1];
}
else
{
double newtmpF[2];
RoeFlux1D(A_L, A_R, Q_L, Q_R, b, 0,beta, newtmpF);
Fhat1L[i] = newtmpF[0];
Fhat2L[i] = newtmpF[1];
if (isnan(newtmpF[0]) || isnan(newtmpF[1]))
{
printf("1D Left element dry flux not a number, edge %d\n", i);
exit(EXIT_FAILURE);
}
}
if (i == NumEl || Chan->WD[i] == 1)
{
Fhat1R[i] = tmpF[0];
Fhat2R[i] = tmpF[1];
}
else
{
RoeFlux1D(A_L, A_R, Q_L, Q_R, b, 0, beta, tmpF);
Fhat1R[i] = tmpF[0];
Fhat2R[i] = tmpF[1];
if (isnan(tmpF[0]) || isnan(tmpF[1]))
{
printf("1D right element dry flux not a number, edge %d\n", i);
exit(EXIT_FAILURE);
}
}
}
#else
A_L = Chan->A[2*i];
A_R = Chan->A[2*i+1];
Q_L = Chan->Q[2*i];
Q_R = Chan->Q[2*i+1];
//beta = getBeta(Chan,i,channelNumber,time);
//Chan->beta = 1.5;
//double beta = Chan->beta[i];
// printf("beta = %e\t channelNumber = %d\n",beta, channelNumber);
RoeFlux1D(A_L, A_R, Q_L, Q_R, b, g,beta,tmpF);
//LF(A_L, A_R, Q_L, Q_R, b, g, tmpF);
if (isnan(tmpF[0]) || isnan(tmpF[1]))
{
printf("1D numerical flux not a number, channelNumber %d edge %d\n", channelNumber,i);
printf("A_L = %e, A_R = %e, Q_L = %e, Q_R = %e \n", A_L, A_R, Q_L, Q_R);
exit(EXIT_FAILURE);
}
Fhat1L[i] = tmpF[0];
Fhat2L[i] = tmpF[1];
Fhat1R[i] = tmpF[0];
Fhat2R[i] = tmpF[1];
#endif
/*****************************************************************************/
double u_L = Q_L/A_L;
double u_R = Q_R/A_R;
double c_L = sqrt(g*A_L/b);
double c_R = sqrt(g*A_R/b);
if (i==0)
Chan->max_lambda = fmax((fabs(u_L)+c_L), (fabs(u_R)+c_R));
// Compute maximum eigenvalue for the next time step
double current_max =fmax((fabs(u_L) + c_L), (fabs(u_R) + c_R));
Chan->max_lambda = max((Chan->max_lambda),(current_max));
}
// Compute the right hand side
for (int k=0; k < NumEl; ++k)
{
double IP[10];
Compute1DInnerProducts(Chan, k, IP);
double x1 = Chan->x[k];
double x2 = Chan->x[k+1];
double y1 = Chan->y[k];
double y2 = Chan->y[k+1];
double h = sqrt((x2-x1)*(x2-x1)+(y2-y1)*(y2-y1));
double F_el1[2] = {Fhat1R[k], Fhat1L[k+1]};
double F_el2[2] = {Fhat2R[k], Fhat2L[k+1]};
double invMrow1[2] = {4/h, -2/h};
double invMrow2[2] = {-2/h, 4/h};
//double invM[2][2] = {{4/(b-a), 2/(a-b)},{2/(a-b), 4/(b-a)}};
double S1 = IP[0] + F_el1[0];
double S2 = IP[1] - F_el1[1];
double S3 = IP[2] + F_el2[0] + IP[3] + IP[4] - IP[5];
double S4 = IP[6] - F_el2[1] + IP[7] + IP[8] - IP[9];
// Compute RHSA = invM*[S1;S2] and RHSQ = invM*[S3;S4]
RHSA[2*k + 1] = invMrow1[0]*S1 + invMrow1[1]*S2;
RHSA[2*k + 2] = invMrow2[0]*S1 + invMrow2[1]*S2;
RHSQ[2*k + 1] = invMrow1[0]*S3 + invMrow1[1]*S4;
RHSQ[2*k + 2] = invMrow2[0]*S3 + invMrow2[1]*S4;
}
// The value at the ghost nodes will be the same as the values at the other side of the face
RHSA[0] = RHSA[1];
RHSA[2*Chan->NumNodes - 1] = RHSA[2*Chan->NumNodes - 2];
RHSQ[0] = RHSQ[1];
RHSQ[2*Chan->NumNodes - 1] = RHSQ[2*Chan->NumNodes - 2];
}
|
C
|
//
// Created by FF on 2020-10-07.
//
#include "elevator.h"
#include "priorityqueue.h"
#include <stdio.h>
/*
* Internal Use Only
* The function determines whether the elevator can respond all calls if the elevator turn direction in current floor
* Input: Elevator *
* Output: 1 if true, 0 false
*/
int can_arrive(Elevator *elevator) {
return elevator->direction ? elevator->current_floor <= pqueue_top(elevator->second)->request.floor : elevator->current_floor >= pqueue_top(elevator->second)->request.floor;
}
/*
* Internal Use Only
* The function writes a message to output file when the elevator finish a pick-up call
* Input: Elevator *, Request *
* Output: None
*/
void print_pickup(Elevator *elevator, Request *request) {
fprintf(elevator->fp, "Time %d: The elevator picked up %d passengers at floor %d.\n", elevator->timestamp, request->passengers, elevator->current_floor);
}
/*
* Internal Use Only
* The function writes a message to output file when the elevator finish a drop-off call
* Input: Elevator *, Request *
* Output: None
*/
void print_arrive(Elevator *elevator, Request *request) {
fprintf(elevator->fp, "Time %d: The elevator dropped off %d passengers at floor %d.\n", elevator->timestamp, request->passengers, elevator->current_floor);
}
/*
* Internal Use Only
* The function will turn the direction of the elevator
* Input: Elevator *
* Output: None
*/
void turn_direction(Elevator *elevator) {
elevator->direction ^= 1;
// move all elements from second to first
while (!pqueue_is_empty(elevator->second)) {
QNode *node = pqueue_top(elevator->second);
pqueue_pop(elevator->second);
pqueue_push(elevator->first, node->key * -1, &node->request);
}
// move all elements from third to second
while (!pqueue_is_empty(elevator->third)) {
QNode *node = pqueue_top(elevator->third);
pqueue_pop(elevator->third);
pqueue_push(elevator->second, node->key * -1, &node->request);
}
}
/*
* Internal Use Only
* The function determines the elevator condition for next timestamp
* Input: Elevator *
* Output: None
*/
void set_condition(Elevator *elevator) {
/*
* Case 1: No remaining call left, rest the elevator
* Case 2: Only remaining calls are in the same direction and already passed by, change direction and call the function again
* Case 3: All calls in the same direction and can process in current round are finished and elevator can
* respond all calls if the elevator turn direction in current floor, just turn the direction
* Case 4: All calls in the same direction and can process in current round are finished but elevator cannot
* respond all calls. Need to go to the floor that can respond all calls before turning direction.
* Default case: set counter to 0
*/
if (pqueue_is_empty(elevator->first) && pqueue_is_empty(elevator->second) && pqueue_is_empty(elevator->third)) {
elevator->status = 2;
} else if (pqueue_is_empty(elevator->first) && pqueue_is_empty(elevator->second)) {
turn_direction(elevator);
set_condition(elevator);
} else if (pqueue_is_empty(elevator->first) && can_arrive(elevator)) {
turn_direction(elevator);
elevator->status = 0;
} else if (pqueue_is_empty(elevator->first)) {
Request *internal_request = request_init(elevator->timestamp, pqueue_top(elevator->second)->request.floor, 0, 0, 2);
int dir = elevator->direction ? -1 : 1;
pqueue_push(elevator->first, dir * internal_request->floor, internal_request);
elevator->status = 1;
}
elevator->counter = 0;
}
/*
* Internal Use Only
* The functions process all calls happen in current floor in current directions
* Input: Elevator *
* Output: None;
*/
void process_current_floor(Elevator *elevator) {
while (!pqueue_is_empty(elevator->first) && pqueue_top(elevator->first)->request.floor == elevator->current_floor) {
QNode *cur_node = pqueue_top(elevator->first);
pqueue_pop(elevator->first);
if (cur_node->request.status == 0) {
// set request status from pick-up to drop-down
elevator->wait_time += (elevator->timestamp - cur_node->request.start_time) * cur_node->request.passengers;
elevator->total_passengers += cur_node->request.passengers;
cur_node->request.floor = cur_node->request.to;
cur_node->key = cur_node->key > 0 ? cur_node->request.floor : -cur_node->request.floor;
cur_node->request.status = 1;
pqueue_push(elevator->first, cur_node->key, &cur_node->request);
print_pickup(elevator, &cur_node->request);
} else if (cur_node->request.status == 1) {
// if the request is already a drop-down, the entire request is finished
elevator->turn_around_time += (elevator->timestamp - cur_node->request.start_time) * cur_node->request.passengers;
print_arrive(elevator, &cur_node->request);
}
}
}
/*
* API
* The function handle a call request
* Input: Elevator *, Request *
* Output: None
*/
void handle_call(Elevator *elevator, Request *request) {
// If the request is going up
if (request->floor < request->to) {
if (!elevator->direction) {
if (request->floor < elevator->current_floor || (request->floor == elevator->current_floor && elevator->status == 1)) {
pqueue_push(elevator->third, request->floor, request);
} else {
pqueue_push(elevator->first, request->floor, request);
}
} else {
pqueue_push(elevator->second, -request->floor, request);
}
} else {
if (elevator->direction) {
if (request->floor > elevator->current_floor || (request->floor == elevator->current_floor && elevator->status == 1)) {
pqueue_push(elevator->third, -request->floor, request);
} else {
pqueue_push(elevator->first, -request->floor, request);
}
} else {
pqueue_push(elevator->second, request->floor, request);
}
}
}
/*
* API
* The function simulates the elevator in one timestamp
* Input: Elevator *
* Output: None
*/
void tick(Elevator *elevator) {
// When the elevator is resting
if (elevator->status == 2 ) {
// Handle special case when the pick up floor is the current floor
if (!pqueue_is_empty(elevator->first) && pqueue_top(elevator->first)->request.floor == elevator->current_floor) {
QNode *node = pqueue_top(elevator->first);
pqueue_pop(elevator->first);
print_pickup(elevator, &node->request);
elevator->direction = node->request.floor > node->request.to;
elevator->total_passengers += node->request.passengers;
node->request.floor = node->request.to;
node->key = node->key > 0 ? node->request.floor : -node->request.floor;
node->request.status = 1;
pqueue_push(elevator->first, node->key, &node->request);
elevator->status = 0;
elevator->counter = 0;
} else {
set_condition(elevator);
}
} else {
elevator->counter++; // increment counter
// if completes a move
if (elevator->counter == 5 && elevator->status == 1) {
elevator->current_floor = elevator->direction ? elevator->current_floor - 1 : elevator->current_floor + 1;
if (!pqueue_is_empty(elevator->first) && pqueue_top(elevator->first)->request.floor == elevator->current_floor) {
process_current_floor(elevator);
set_condition(elevator);
}
elevator->counter = 0;
} else if (elevator->status == 0 && elevator->counter == 2) {
// if finishes a stop-move transition
process_current_floor(elevator);
elevator->status = 1;
elevator->counter = 0;
}
// otherwise, just waiting...
}
elevator->timestamp++; // increment timestamp
}
|
C
|
#pragma GCC optimize "-O3"
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<math.h>
#include<assert.h>
#include<stdbool.h>
#include<limits.h>
#define clr(arr)do{ memset(arr, 0, sizeof(arr)); }while(0)
typedef struct{
int first, second;
}pair;
pair newpair(int a, int b){
return(pair){a,b};
}
#define pb(zpv, zvv) zpv.ptr = pushback(zpv.ptr, &zpv.sz, zvv)
#define resizeArray(ptr, type, size) ((type*)realloc(ptr, (size) * sizeof(type)))
int *pushback(int *array, int *size, int value) {
int *output = resizeArray(array, int, *size + 1);
output[(*size)++] = value;
return output;
}
typedef struct{
int*ptr;
int sz;
}vec;
vec newVec() {
vec rez;
rez.ptr = NULL;
rez.sz = 0;
return rez;
}
///////////////////
void solve(){
int n;
scanf("%d", &n);
int A[n]; clr(A);
for(int i=0; i<n; i++){
int x;
scanf("%d", &x);
x--;
A[x]++;
}
int lol =(int)1e9;
vec v=newVec();
for(int i=0; i<n; i++){
if(A[i]>0){
pb(v, A[i]);
lol = fmin(lol, A[i]);
}
}
pair worked(int s, int num){
int c = num / s;
int rem = num % s;
if (rem == 0)
return newpair(true, c);
if (s - 1 - rem <= c)
return newpair(true, c + 1);
return newpair(false, 0);
}
int res =(int)1e9;
for(int s=2; s<=lol+1; s++){
int tot = 0;
bool good = true;
for(int z=0;z<v.sz;z++){int num = v.ptr[z];
pair rv = worked(s, num);
bool bul=rv.first;
int cnt=rv.second;
good &= bul;
tot += cnt;
}
if(good)
res = fmin(res, tot);
}
printf("%d\n", res);
}
int main(){
int t;
scanf("%d", &t);
while(t--)
solve();
return 0;
}
|
C
|
#include <sys/types.h>
#include <unistd.h>
#include <fcntl.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main(int argc, char** argv){
int f = open(argv[1], O_RDONLY);
int k = open(argv[2], O_CREAT | O_WRONLY | O_TRUNC);
int N = atoi(argv[3]);
if(f < 0 || k < 0){
perror("Error opening files!");
return 1;
}
char b[N];
int n;
while( (n = read(f,b,N)) > 0 )
write(k,b,n);
close(f);
close(k);
return 0;
}
|
C
|
/* PThread Creation & Tremination without pthread_exit routine */
#include <pthread.h>
#include <stdio.h>
#include <unistd.h>
// Thread created will execute the following routine
void * thread_routine (void *p)
{
printf("\nHello World!\n");
}
int main ()
{
// Object to hold thread ID
pthread_t thread;
int rv;
// Routine shell create a new thread
rv = pthread_create(&thread, NULL, thread_routine, NULL);
if(rv)
puts("Failed to create thread");
puts("Exit Main");
pthread_exit(NULL);
}
|
C
|
inherit "room/room";
#include <ansi.h>
#define PATH "/players/dreamspeakr/mesa/"
reset(arg) {
int i;
i = random(2);
if(i == 1){
for(i=0 ; i < random(2)+1 ; i++){
move_object(clone_object("/players/dreamspeakr/mesa/NPC/anasazi.c"),this_object());
}
}
if(arg)return;
set_light(1);
short_desc = HIG+"Atop Mesa Verde"+NORM;
long_desc =
"\n"+
"\tThe long journey to the top of this majestic mesa has \n"+
"finally ended. A breathtaking sight to behold, the landscape \n"+
"below seems so small and distant down in the canyon. Trees \n"+
"and lush green grass compliment the canyon slope just off the \n"+
"side of the cliff palaces built into the rock to the north, \n"+
"northeast and northwest. In front of the homes there is what \n"+
"appears to be a kiva. \n"+
"\n"
;
items = ({
"mesa","Colors spring at you from every direction you look \n"+
"The thriving people of the mesa must never want to leave \n"+
"the beauty and tranquility of this heavenly place",
"landscape","Over 7,000 feet below you, you can barely make \n"+
"out where you came from. The view is so captivating you \n"+
"could almost get lost in it",
"canyon","As you look down at the canyon below all you can \n"+
"make out are the beautiful colors of the landscape",
"slope","The blanket of grass and towering trees take your \n"+
"breath away as you look down this mountain slope",
"trees","Beautiful Douglas Fir, Gambel Oak Serviceberry and \n"+
"Mountain Mahogany trees stand high above the mountain brush \n"+
"along the mesa top",
"grass","Healthy Cheatgrass blankets the ground in shades of \n"+
"green, swaying to and fro as the strong winds wisk it around",
"palaces","Connected together these three story homes, known as \n"+
"Cliff Palace, could probably house over 50 people",
"rock","Gritty hard stone alcoves formed in the side of the \n"+
"mountain top give shelter to the homes built within its \n"+
"confinement",
"kiva","Large sandstone bricks border this large covered pit. \n"+
"There appears to be some kind of ritual going on inside it",
"bricks","Placed along the edge of the Kiva large hand chipped \n"+
"bricks decorate the temple below",
});
dest_dir = ({
PATH+"mv7.c","north",
PATH+"mv10.c","northwest",
PATH+"mv13.c","northeast",
PATH+"mv16.c","kiva",
PATH+"mv5.c","descend",
});
}
listen() {
write("You close your eyes and listen.... you hear the chant \n"+
"of the Anasazi tribesmen performing an ancient tribal \n"+
"ceremony. The wind whistles as it moves its way thru \n"+
"the trees. \n");
return 1;
}
|
C
|
#include <sys/types.h>
#include <sys/wait.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <signal.h>
int main(int argc, char *argv[])
{
printf("Hello World\n");
pid_t child;
child = fork();
switch(child) {
case 0:
printf("i am child!!\n");
sleep(1);
break;
case -1:
printf("Fork Error !! (%d)\n", child);
break;
default:
printf("I am parenet process !!\n");
printf("I am Waiting for child finish\n");
int child_result = 0;
pid_t finished_child = wait(&child_result);
printf("Child (%d) Finished!!\n", (int)finished_child);
}
return 0;
}
|
C
|
/*
timer_function_without_time.h_v1.c by Dragan Milicev
Idea is to make timer function without the use of timer.h header file.
In function
void my_sleep( int milliseconds )
I use 3 nested for loops i, j and k,
to make the required time delay during the run.
But, required time delay depends on the speed of your machine's processor.
So I temporarily use header file time.h to set my function to the speed of my processor.
You do the same.
Setup:
Important information for your computer processor is CLOCKS_PER_SEC.
The program will print to you its value, which you will write
instead of CLOCKS_PER_SEC in function my_sleep(milliseconds);
main() is set to have a time delay of 10 seconds.
Change the #define SETUP_NUMBER 400
until you get an approximate time of 10,000 milliseconds.
Write the resulting value of SETUP_NUMBER
into the function my_sleep(milliseconds);
After this setup, you will get the my_sleep(milliseconds);
function which will work accurately enough on your computer
without heder file time.h .
You can find all my C programs at Dragan Milicev's pastebin:
https://pastebin.com/u/dmilicev
https://www.facebook.com/dmilicev
*/
#include <stdio.h>
#include <time.h>
#define SETUP_NUMBER 400
void my_sleep( int milliseconds )
{
int i, j, k;
for(i=0; i<milliseconds; i++)
for(j=0; j<SETUP_NUMBER; j++)
for(k=0; k<CLOCKS_PER_SEC; k++);
}
int main () {
clock_t start_t, end_t, total_t;
int milliseconds = 10000; // main() is set to have a time delay of 10 seconds.
start_t = clock();
printf("\n Starting of the my_sleep(%d) function, start_t = %ld \n", milliseconds, start_t );
printf("\n Wait 10 seconds ... \n");
my_sleep(milliseconds); // to delay (wait, sleep) 10 seconds
end_t = clock();
printf("\n End of the my_sleep(%d) function, end_t = %ld \n", milliseconds, end_t );
total_t = (double)(end_t - start_t) / CLOCKS_PER_SEC;
printf("\n Total time taken by CPU: %ld \n", total_t );
printf("\n start_t = %ld \t end_t = %ld \t total_t = %ld \n", start_t, end_t, total_t );
printf("\n CLOCKS_PER_SEC = %5ld \n", CLOCKS_PER_SEC );
printf("\n SETUP_NUMBER = %5d \n", SETUP_NUMBER );
return(0);
}
|
C
|
#define _CRT_SECURE_NO_WARNINGS
//题目描述
//每个人都想成为大V (VIP:Very Important Person),但要一点一点积累才行,先从小v做起。要求输出由小写字母v组成的大V。
//输入描述:
//无
//输出描述:
//v v
// v v
// v
//
//备注:
//换行使用转义字符‘\n’
//方法一
#include <stdio.h>
//代码1
int main()
{
printf("v v\n");
printf(" v v\n");
printf(" v\n");
return 0;
}
//方法二
#include<stdio.h>
int main()
{
printf("v v\n v v\n v\n");
return 0;
}
//答案解析:
//这个题也是没有输入要求的题目,所以相对比较简单。
//题目中只要能够找到输出的规律和掌握 \n 的使用就没问题。
//这里简单提及:转义字符,可以做一个拓展。
|
C
|
/**
* @file main.c
* @author Duarte Melo e João Diogo
* @brief Código em C relativo à questão 14
* @version 0.1
* @date 2020-11-25
*
* @copyright Copyright (c) 2020
*
*/
#include <stdio.h>
int verificaPrimo(int numero);
int verificaPrimoLimites(int limiteInferior, int limiteSuperior);
int main(){
int limiteInferior, limiteSuperior;
printf("Escreva o limite inferior: ");
scanf("%d", &limiteInferior);
printf("Escreva o limite superior: ");
scanf("%d", &limiteSuperior);
printf("%d", verificaPrimoLimites(limiteInferior, limiteSuperior));
}
/**
* @brief Verifica quantos numeros primos existem num determinado intervalo
*
* @param limiteInferior Limite inferior do intervalo
* @param limiteSuperior Limite superior do intervalo
* @return int - Retorna o contador de numeros primos
*/
int verificaPrimoLimites(int limiteInferior, int limiteSuperior){
int contador = 0;
for (int i = limiteInferior; i <= limiteSuperior; i++){
if(verificaPrimo(i) == 1){
contador++;
}
}
return contador;
}
/**
* @brief Verifica se um determinado número é primo
*
* @param numero Recebe o número para o qual a verificação será feita
* @return int Retorna 1 se for primo, 0 se não for primo
*/
int verificaPrimo(int numero){
// 1 e 0 sao nao primos
if (numero == 0 || numero == 1)
{
return 0;
}
// nao é primo se for divisivel por algum numero entre 2 e num-1, e quebra assim que for divisivel por algum numero
for (int i = 2; i < numero; i++)
{
if (numero % i == 0)
{
return 0;
}
}
//caso não tenha retornado nada anteriormente, o numero é primo
return 1;
}
|
C
|
#include <stdio.h>
int main()
{
int t;
scanf("%d",&t);
while(t--)
{
long long int n,m,i;
scanf("%lld",&n);
m=n;
if(n==0) printf("1\n");
else{
for (i=1;i<m;i++)
{
n=n*i;
}
printf("%lld\n",n);
}
}
}
|
C
|
#include <ctype.h>
#include <string.h>
#include "constants.h"
#include "stringParsing.h"
/*function to check if the given number of bytes in the string are only whitespace characters. goes over string character by character.*/
int isStringEmpty (char *str, int bytes) {
while (bytes--) {
if (!isspace(*str)) {
return 0;
}
str++;
}
return 1;
}
/*function that returns the position of the first non-whitespace character in a string. assumes string is not only whitespace
(does not check string boundaries)*/
static int getFirstNonWhiteSpaceCharacter(char *str) {
int currPos = 0;
while (isspace(str[currPos]))
currPos++;
return currPos;
}
/*function that returns the position of the last non-whitespace character in a string. assumes string is not only whitespace
(does not check string boundaries)*/
static int getLastNonWhiteSpaceCharacter(char *str, int strLen) {
int currPos = strLen - 1;
while (isspace(str[currPos]))
currPos--;
return currPos;
}
/*function that accepts a string, the string's length and a destination string, and copies the original string into the destination without surrounding
whitespace characters*/
void trimString (char *src, char *dest, int srcLen) {
if (isStringEmpty(src, srcLen)) {
*dest = '\0';
}
else {
int firstChar = getFirstNonWhiteSpaceCharacter(src);
int lastChar = getLastNonWhiteSpaceCharacter(src, srcLen);
strncpy(dest, src+firstChar, lastChar-firstChar+1);
dest[lastChar-firstChar+1] = '\0';
}
}
/*Function that looks for the first appearance of a given character in a string. returns a pointer to the corresponding location in the string*/
char* getNextDelimiterPos(char *str, char delimiter) {
char *delimiterPos = strchr(str, delimiter);
if (!delimiterPos) {
delimiterPos = str + strlen(str);
}
return delimiterPos;
}
/*Function to split a string into tokens by a given delimiter character. the found tokens are copied into the targetArray. Returns the total
number of tokens copied. Function uses the getNextDelimiterPos on the string until no more delimiters are found. for each delimiter position, the
string from the last delimiter position (not including) is copied until the position of the current delimiter position*/
int splitString(char *str, char targetArray[][MAX_TOKEN_LEN+1], char delimiter) {
int currTargetArrayPos, totalParsed;
char *prevDelimPos, *currDelimPos;
currTargetArrayPos = totalParsed = 0;
prevDelimPos = str-1;
currDelimPos = str;
while (*currDelimPos != '\0') {
currDelimPos = getNextDelimiterPos(str, delimiter);
strncpy(targetArray[currTargetArrayPos], prevDelimPos+1, currDelimPos-(prevDelimPos+1));
targetArray[currTargetArrayPos][currDelimPos-(prevDelimPos+1)] = '\0';
prevDelimPos = currDelimPos;
str = currDelimPos + 1;
totalParsed++;
currTargetArrayPos++;
}
if (*currDelimPos != '\0') { /*delimiter at end of string*/
*targetArray[currTargetArrayPos] = '\0';
totalParsed++;
}
return totalParsed;
}
/*Function to search for string in given string array. return first position in array, or -1 if not found */
int indexOf (char stringArray[][MAX_TOKEN_LEN+1], int arrayLen, char searchString[]) {
int foundIndex = -1;
int currPosition = 0;
while (foundIndex < 0 && currPosition < arrayLen) {
if (strcmp(searchString, stringArray[currPosition]) == 0) {
foundIndex = currPosition;
}
currPosition++;
}
return foundIndex;
}
/*Function to check if a string contains any whitespace characters. returns 1 if any whitespace found, otherwise returns 0.
Goes over string character by character*/
int hasWhitespace (char *str) {
while (*str != '\0') {
if (isspace(*str)) {
return 1;
}
str++;
}
return 0;
}
|
C
|
#include <stdio.h>
#include <mpi.h>
int gvar = 12345;
int main( int argc, char **argv ) {
int rank;
MPI_Init( &argc, &argv );
MPI_Comm_rank( MPI_COMM_WORLD, &rank );
gvar = rank;
MPI_Barrier( MPI_COMM_WORLD );
printf( "[%d] gvar=%d\n", rank, gvar );
MPI_Finalize();
return 0;
}
|
C
|
/****************************************************************************
BM
M* Module : LsFilesDirs.c
*
D* Description : List all files with its size from a start directory.
*
I* Import :
*
E* Export :
*
P* Author : Wilhelm Ruesing
*
U* Updates :
EM
****************************************************************************/
#include <stdio.h>
#include <sys/types.h>
#include <dirent.h>
#include <sys/stat.h>
#define DIR_ENTRY (0)
#define FILE_ENTRY (1)
#define FAIL (2)
void PrintEntry ( char* );
int TestIfDir ( char*, char* );
void SelectFiles( char* );
FILE *fpOutput;
/* ======================================================================== */
int main(int argc, char **argv )
/* ======================================================================== */
{
if( argc < 2 || argc > 3 )
{
fprintf( stderr, "\nusage : FileSize <StartPath> [OutFile]\n\n" );
exit(-1);
}
else if( argc == 2 )
{
fpOutput = stdout;
}
else
{
if( !(fpOutput = fopen(argv[2], "w")) )
{
perror( "fopen ERROR" );
exit(-1);
}
fprintf( stderr, "\nscanning for files in %s.\n",argv[1] );
}
SelectFiles( argv[1] );
fclose( fpOutput );
exit(0);
}
/* ======================================================================== */
void PrintEntry( char *cpFilePath )
/* ======================================================================== */
{
struct stat spInfoBuf;
int iStatRtn;
if( stat(cpFilePath, &spInfoBuf) )
{
fprintf( fpOutput, "\nCan't get size of %s !\n", cpFilePath );
perror( "stat ERROR" );
exit(-1);
}
else
fprintf( fpOutput, "%d#%s\n",spInfoBuf.st_size, cpFilePath );
}
/* ======================================================================== */
int TestIfDir( char *cpDirPath, char *cpDirNameToTest )
/* ======================================================================== */
{
struct stat stStatusBuffer;
if( *cpDirNameToTest == '.' )
return( FAIL );
if( !stat( cpDirPath, &stStatusBuffer ) )
{
if( S_ISDIR( (mode_t)stStatusBuffer.st_mode ) )
return( DIR_ENTRY );
else
return( FILE_ENTRY );
}
perror( "stat ERROR" );
exit(-1);
}
/* ======================================================================== */
void SelectFiles( char *cpStartDir )
/* ======================================================================== */
{
int iIsDirReturn,
iBufferReturn,
iFileCount;
DIR *dirPtr;
char caNowFileName[257];
struct dirent *dirDirEntry;
if( dirPtr = opendir( cpStartDir ) )
{
for( dirDirEntry = readdir( dirPtr );
dirDirEntry != NULL;
dirDirEntry = readdir( dirPtr ) )
{
sprintf( caNowFileName,"%s/%s", cpStartDir,
dirDirEntry->d_name );
if( (iIsDirReturn = TestIfDir(caNowFileName,
dirDirEntry->d_name ))
== DIR_ENTRY )
SelectFiles( caNowFileName );
else if( iIsDirReturn == FILE_ENTRY )
PrintEntry( caNowFileName );
}
if( closedir(dirPtr) )
{
perror( "closedir ERROR" );
exit(-1);
}
return;
}
perror("opendir ERROR");
exit(-1);
}
|
C
|
#include "search_algos.h"
/**
* binary_search - Function that search a value using
* Binary Search algorithm
*
* @array: Array with values to compare
* @size: Size of array
* @value: value to search
*
* Return: index when is founded, -1 if not
*/
int binary_search(int *array, size_t size, int value)
{
int idx = 0, m = 0, i = 0;
int len = (int)size - 1;
if (array == NULL)
return (-1);
/* iterate over array */
while (idx <= len)
{
/* set pivot point*/
m = (idx + len) / 2;
/* printing subarray*/
printf("Searching in array: ");
for (i = idx; i <= len; i++)
{
if (i != len)
printf("%d, ", array[i]);
else
printf("%d\n", array[i]);
}
/* validate value in position is less than the value*/
if (array[m] < value)
/* increment index to right*/
idx = m + 1;
/* validate value in position is greather than the value*/
else if (array[m] > value)
/* decrement index to left*/
len = m - 1;
else
return (m);
}
return (-1);
}
|
C
|
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
#include "src/allocator.h"
void print_array(int *array, int size) {
printf("[");
for (int j = 0; j < size; j++) {
printf(" %i ", array[j]);
}
printf("]\n");
}
int main (int argc, char *argv[]) {
srand(time(NULL));
mem_pool_alloc();
int number_of_arrays = rand() % 4 + 1;
int **arrays = malloc(number_of_arrays * sizeof(int *));
int arrays_size[number_of_arrays];
printf(" ALLOC\n");
for (int i = 0; i < number_of_arrays; i++) {
arrays_size[i] = rand() % 65 + 1;
arrays[i] = mem_alloc(arrays_size[i] * sizeof(int));
printf("Alloc array №%i with size %i.\n", i, arrays_size[i]);
for (int j = 0; j < arrays_size[i]; j++) {
arrays[i][j] = rand() % 100;
}
print_array(arrays[i], arrays_size[i]);
mem_dump();
}
printf(" REALLOC\n");
for (int i = 0; i < number_of_arrays; i++) {
size_t new_size = rand() % 65 + 1;
printf("Realloc array №%i with size %i to size %ld.\n", i, arrays_size[i], new_size);
arrays_size[i] = new_size;
arrays[i] = mem_realloc(arrays[i], new_size * sizeof(int));
print_array(arrays[i], arrays_size[i]);
mem_dump();
}
printf(" FREE\n");
for (int i = 0; i < number_of_arrays; i++) {
printf("Free array №%i with size %i.\n", i, arrays_size[i]);
print_array(arrays[i], arrays_size[i]);
mem_free(arrays[i]);
mem_dump();
}
mem_pool_free();
return 0;
}
|
C
|
#ifndef RBTREE_H
#define RBTREE_H
typedef enum NodeColor
{
Enum_Red,
Enum_Black,
Enum_ColorCount,
}NodeColor;
typedef int KeyType;
typedef int ValueType;
typedef struct RBTreeNode
{
KeyType m_key;
ValueType m_value;
NodeColor m_color;
struct RBTreeNode *m_parent;
struct RBTreeNode *m_left;
struct RBTreeNode *m_right;
}RBTreeNode;
typedef RBTreeNode *RBTreeNodePtr;
typedef void (*rbvisit)(RBTreeNodePtr ptr);
RBTreeNodePtr MakeRBTreeNode(KeyType key);
typedef struct RBTree
{
RBTreeNodePtr m_null;
RBTreeNodePtr m_root;
}RBTree;
typedef RBTree *RBTreePtr;
void InitializeRBTree(RBTreePtr pTree);
void DestructRBTree(RBTreePtr pTree);
void DestructRBSubTree(RBTreePtr pTree, RBTreeNodePtr ptr);
RBTreeNodePtr IterativeRBTreeMinimum(RBTreePtr pTree, RBTreeNodePtr ptr);
RBTreeNodePtr IterativeRBTreeMaximum(RBTreePtr pTree, RBTreeNodePtr ptr);
RBTreeNodePtr RBTreeSuccessor(RBTreePtr pTree, RBTreeNodePtr ptr);
RBTreeNodePtr RBTreePredecessor(RBTreePtr pTree, RBTreeNodePtr ptr);
void RBTreeInOrderVisit(RBTreePtr pTree, RBTreeNodePtr ptr, rbvisit pVisit);
RBTreeNodePtr IterativeRBTreeSearch(RBTreePtr pTree, RBTreeNodePtr ptr, KeyType key);
void RBLeftRotate(RBTreePtr pTree, RBTreeNodePtr x);
void RBRightRotate(RBTreePtr pTree, RBTreeNodePtr y);
void RBTreeInsert(RBTreePtr pTree, RBTreeNodePtr z);
void RBTreeInsertFixup(RBTreePtr pTree, RBTreeNodePtr z);
RBTreeNodePtr RBTreeDelete(RBTreePtr pTree, RBTreeNodePtr z);
void RBTreeDeleteFixup(RBTreePtr pTree, RBTreeNodePtr x);
void TestRBTree();
#endif // RBTREE_H
|
C
|
#include<stdio.h>
#include<stdlib.h>
main()
{
int i, j,account;
double balance, charges, credits,limit;
while (1)
{
printf("Enter account number(-1 to end):");
scanf_s("%d", &account);
if(account==-1)
{
break;
}
printf("Enter beginning balance:");
scanf_s("%lf", &balance);
printf("Enter total charges:");
scanf_s("%lf", & charges);
printf("Enter total credits:");
scanf_s("%lf", &credits);
printf("Enter total credits limit:");
scanf_s("%lf", &limit);
balance = balance + charges - credits;
printf("account:%d\n", account);
printf("credit limit:%.2lf\n", limit);
printf("balance:%.2lf\n", balance);
if (balance > limit)
{
printf("credit limit Exceeded\n");
}
else
{
printf("credit limit NOT Exceeded");
}
}
}
|
C
|
/*
** EPITECH PROJECT, 2019
** cpp_d03_2019
** File description:
** Created by thomas1.bastien@epitech.eu
*/
#include "string.h"
void join_c(string_t *this, char delim, const char * const * tab)
{
char separator[2];
separator[0] = delim;
separator[1] = '\0';
if (!this || !tab)
return;
if (this->str) {
free(this->str);
this->str = NULL;
}
for (int i = 0; tab[i] != NULL; i++) {
if (i == 0)
assign_c(this, tab[i]);
else
append_c(this, tab[i]);
if (tab[i + 1])
append_c(this, separator);
}
}
void join_s(string_t *this, char delim, const string_t * const * tab)
{
char separator[2];
separator[0] = delim;
separator[1] = '\0';
if (!this || !tab)
return;
if (this->str) {
free(this->str);
this->str = NULL;
}
for (int i = 0; tab[i] && tab[i]->str; i++) {
if (i == 0)
assign_s(this, tab[i]);
else
append_s(this, tab[i]);
if (tab[i + 1])
append_c(this, separator);
}
}
|
C
|
#include <sys/types.h>
#include <stdio.h>
#include <string.h>
#include <time.h>
#include "merc.h"
void do_weaponenhance(CHAR_DATA *ch, char *argument)
{
OBJ_DATA *obj;
if (!IS_SPHERE(ch, SPHERE_ENCHANTMENT))
{
send_to_char("You need the Enhancement Sphere for this.\n\r",ch);
return;
}
if ( ch->practice < 1500)
{
send_to_char("It costs 1500 primal to enhance a weapon.\n\r",ch);
return;
}
if (argument[0] == '\0')
{
send_to_char("Which item do you wish to forge?\n\r", ch);
return;
}
if ( (obj = get_obj_carry(ch, argument)) == NULL)
{
send_to_char("You are not carrying that item.\n\r", ch);
return;
}
/* if (IS_SET(obj->quest,QUEST_RELIC) || IS_SET(obj->quest,QUEST_ARTIFACT))
{
send_to_char("Not on a Relic.\n\r",ch);
return;
}
*/
if (IS_SET(obj->quest,QUEST_RITUAL))
{
send_to_char("This item has already been through the Ritual!\n\r",ch);
return;
}
if (obj->item_type == ITEM_WEAPON)
{
obj->value[1] += 100;
obj->value[2] += 100;
obj->level = 50;
oset_affect(ch,obj,50,APPLY_HITROLL,TRUE);
oset_affect(ch,obj,50,APPLY_DAMROLL,TRUE);
SET_BIT(obj->quest,QUEST_RITUAL);
obj->condition = 100;
obj->toughness = 100;
obj->resistance = 1;
act("You bestow power into $p through the Dark Ritual.", ch, obj, NULL, TO_CHAR);
act("$n bestows power into $p through the Dark Ritual.", ch, obj, NULL, TO_ROOM);
if(!IS_SET(obj->weapflags, WEAPON_FLAMING)) SET_BIT(obj->weapflags, WEAPON_FLAMING);
ch->practice -= 1500;
WAIT_STATE(ch, 8);
return;
}
}
void do_armorenhance(CHAR_DATA *ch, char *argument)
{
OBJ_DATA *obj;
if (!IS_SPHERE(ch, SPHERE_ENCHANTMENT))
{
send_to_char("You need the Enhancement Sphere for this.\n\r",ch);
return;
}
if ( ch->practice < 1500)
{
send_to_char("It costs 1500 primal to enhance a weapon.\n\r",ch);
return;
}
if (argument[0] == '\0')
{
send_to_char("Which item do you wish to forge?\n\r", ch);
return;
}
if ( (obj = get_obj_carry(ch, argument)) == NULL)
{
send_to_char("You are not carrying that item.\n\r", ch);
return;
}
/* if (IS_SET(obj->quest,QUEST_RELIC) || IS_SET(obj->quest,QUEST_ARTIFACT))
{
send_to_char("Not on a Relic.\n\r",ch);
return;
}
*/
if (IS_SET(obj->quest,QUEST_RITUAL))
{
send_to_char("This item has already been through the Ritual!\n\r",ch);
return;
}
if (obj->item_type == ITEM_ARMOR)
{
obj->value[0] += 50;
oset_affect(ch,obj,30,APPLY_HITROLL,TRUE);
oset_affect(ch,obj,30,APPLY_DAMROLL,TRUE);
oset_affect(ch,obj,-50,APPLY_AC,TRUE);
SET_BIT(obj->quest,QUEST_RITUAL);
obj->condition = 100;
obj->toughness = 100;
obj->resistance = 1;
act("You bestow power into $p through the Dark Ritual.", ch, obj, NULL, TO_CHAR);
act("$n bestows power into $p through the Dark Ritual.", ch, obj, NULL, TO_ROOM);
ch->practice -= 1500;
WAIT_STATE(ch, 8);
return;
}
}
void do_caust(CHAR_DATA * ch, char *argument)
{
OBJ_DATA *obj;
if (!IS_SPHERE(ch, SPHERE_ENCHANTMENT))
{
send_to_char("You need the Enhancement Sphere for this.\n\r",ch);
return;
}
if (argument[0] == '\0')
{
send_to_char("Which item do you wish to caust?\n\r", ch);
return;
}
if ((obj = get_obj_carry(ch, argument)) == NULL)
{
send_to_char("You are not carrying that item.\n\r", ch);
return;
}
if (obj->item_type != ITEM_WEAPON)
{
send_to_char("That is not a weapon!\n\r", ch);
return;
}
if (dice(1, 100) == 1)
{
act("$p is disintegrated by $n's poison.", ch, obj, NULL,
TO_ROOM);
act("Your poison eats through $p.", ch, obj, NULL, TO_CHAR);
extract_obj(obj);
return;
}
if (IS_WEAP(obj, WEAPON_POISON))
{
act("$p is already coated with deadly poison.", ch, obj, NULL,
TO_CHAR);
return;
}
act("You run your tongue along $p, coating it with a sickly venom.",
ch, obj, NULL, TO_CHAR);
act("$n runs $m tongue along $p, coating it with a sickly venom.", ch,
obj, NULL, TO_ROOM);
WAIT_STATE(ch, 8);
SET_BIT(obj->weapflags, WEAPON_POISON);
obj->value[1] += 10 - ch->generation;
obj->value[2] += 10 - ch->generation;
}
void do_immolate(CHAR_DATA * ch, char *argument)
{
OBJ_DATA *obj;
if (!IS_SPHERE(ch, SPHERE_ENCHANTMENT))
{
send_to_char("You need the Enhancement Sphere for this.\n\r",ch);
return;
}
if (argument[0] == '\0')
{
send_to_char("Which item do you wish to immolate?\n\r", ch);
return;
}
if ((obj = get_obj_carry(ch, argument)) == NULL)
{
send_to_char("You are not carrying that item.\n\r", ch);
return;
}
if (obj->item_type != ITEM_WEAPON)
{
send_to_char("That is not a weapon!\n\r", ch);
return;
}
/* if (dice(1, 100) == 1)
{
act("$p explodes in a burst of flames.", ch, obj, NULL,
TO_ROOM);
act("$p explodes in a burst of flames.", ch, obj, NULL,
TO_CHAR);
damage(ch, ch, 500, gsn_inferno);
extract_obj(obj);
return;
}
*/
if (IS_WEAP(obj, WEAPON_FLAMING))
{
act("$p is already flaming.", ch, obj, NULL, TO_CHAR);
return;
}
act("$p bursts into flames.", ch, obj, NULL, TO_CHAR);
act("$p, carried by $n bursts into flames.", ch, obj, NULL, TO_ROOM);
WAIT_STATE(ch, 8);
SET_BIT(obj->weapflags, WEAPON_FLAMING);
}
void do_wfreeze(CHAR_DATA * ch, char *argument)
{
OBJ_DATA *obj;
if (!IS_SPHERE(ch, SPHERE_ENCHANTMENT))
{
send_to_char("You need the Enhancement Sphere for this.\n\r",ch);
return;
}
if (argument[0] == '\0')
{
send_to_char("Which item do you wish to freeze?\n\r", ch);
return;
}
if ((obj = get_obj_carry(ch, argument)) == NULL)
{
send_to_char("You are not carrying that item.\n\r", ch);
return;
}
if (obj->item_type != ITEM_WEAPON)
{
send_to_char("That is not a weapon!\n\r", ch);
return;
}
if (dice(1, 100) == 1)
{
act("$p freezes and shatters.", ch, obj, NULL, TO_ROOM);
act("$p freezes and shatters.", ch, obj, NULL, TO_CHAR);
extract_obj(obj);
return;
}
if (IS_WEAP(obj, WEAPON_FROST))
{
act("$p is already frozen.", ch, obj, NULL, TO_CHAR);
return;
}
act("$p is surrounded by ice crystals.", ch, obj, NULL, TO_CHAR);
act("$p, carried by $n is surrounded by ice crystals.", ch, obj, NULL,
TO_ROOM);
WAIT_STATE(ch, 8);
SET_BIT(obj->weapflags, WEAPON_FROST);
}
void do_poisonblade(CHAR_DATA * ch, char *argument)
{
OBJ_DATA *obj;
char arg[MAX_INPUT_LENGTH];
argument = one_argument(argument, arg);
if (IS_NPC(ch))
return;
if (!IS_SPHERE(ch, SPHERE_ENCHANTMENT))
{
send_to_char("You need the Enhancement Sphere for this.\n\r",ch);
return;
}
if (arg[0] == '\0')
{
stc("Poison What?\n\r", ch);
return;
}
if ((obj = get_obj_carry(ch, arg)) == NULL)
{
send_to_char("You dont have that item.\n\r", ch);
return;
}
if (obj->item_type != ITEM_WEAPON)
{
send_to_char("You can only poison weapons!\n\r", ch);
return;
}
if (IS_SET(obj->quest, QUEST_WWPOISON))
{
send_to_char
("#0This item has already been #gP#Goisone#gd!#n.\n\r",
ch);
return;
}
SET_BIT(obj->quest, QUEST_WWPOISON);
stc("#0You coat your weapon in foul smelling #gp#Goiso#gn!#n\n\r",
ch);
obj->timer = 35;
return;
}
|
C
|
#include "utilities.h"
#include "data_link.h"
FILE* imagem;
void sendData(char* data) {
int i;
if(data[0] == 0x02) {
char* filename = (char*) malloc(data[8] + 1);
for(i = 0; i < data[8]; i++) {
filename[i] = data[9 + i];
}
imagem = fopen(filename,"wb");
if(imagem == NULL) {
exit(0);
}
free(filename);
}
if(data[0] == 0x03) {
fclose(imagem);
char* filename = (char*) malloc(data[8] + 1);
for(i = 0; i < data[8]; i++) {
filename[i] = data[9 + i];
}
}
else if(data[0] == 0x01) {
char* packet = (char *) malloc((data[2]*256) + data[3]);
for(i = 0; i < ((data[2]*256) + data[3]); i++) {
packet[i] = data[4 + i];
}
fwrite(packet, 1, ((data[2]*256) + data[3]), imagem);
free(packet);
}
}
int main(int argc, char** argv)
{
int c, res;
struct termios oldtio,newtio;
char buf[255];
int i, sum = 0, speed = 0;
if ( (argc < 2) ||
((strcmp("/dev/ttyS0", argv[1])!=0) &&
(strcmp("/dev/ttyS1", argv[1])!=0) )) {
printf("Usage:\tnserial SerialPort\n\tex: nserial /dev/ttyS1\n");
exit(1);
}
int fd;
fd = open(argv[1], O_RDWR | O_NOCTTY );
if (fd <0) {perror(argv[1]); exit(-1); }
if ( tcgetattr(fd,&oldtio) == -1) {
perror("tcgetattr");
exit(-1);
}
bzero(&newtio, sizeof(newtio));
newtio.c_cflag = BAUDRATE | CS8 | CLOCAL | CREAD;
newtio.c_iflag = IGNPAR;
newtio.c_oflag = 0;
newtio.c_lflag = 0;
newtio.c_cc[VTIME] = 10;
newtio.c_cc[VMIN] = 0;
tcflush(fd, TCIOFLUSH);
if ( tcsetattr(fd,TCSANOW,&newtio) == -1) {
perror("tcsetattr");
exit(-1);
}
if(!llopen(fd)){
close(fd);
exit(0);
}
llread(fd);
llclose(fd);
if ( tcsetattr(fd,TCSANOW,&oldtio) == -1) {
perror("tcsetattr");
exit(-1);
}
close(fd);
return 0;
}
|
C
|
/* Author - Ayush Agrawal
File - matrix_acc.c*/
#include <stdio.h>
#include <stdlib.h>
#include <sys/time.h>
#define N 1000
float A[N][N], B[N][N], C[N][N]; // declaring matrices of NxN size
int main ()
{
int i, j, m; // indices for matrix multiplication
struct timeval start_time, stop_time, elapsed_time; // timers
for(i=0;i<N;i++) {
for(j=0;j<N;j++) {
A[i][j]= 1;
B[i][j]= 1;
}
}
gettimeofday(&start_time,NULL); // Unix timer
// Compute matrix multiplication.
#pragma acc kernels copyin(A,B) copy(C)
for (i = 0; i < N; ++i) {
for (j = 0; j < N; ++j) {
for (m = 0; m < N; ++m) {
C[i][j] += A[i][m] * B[m][j];
}
}
}
gettimeofday(&stop_time,NULL);
timersub(&stop_time, &start_time, &elapsed_time); // Unix time subtract routine
printf("Total time was %f seconds.\n", elapsed_time.tv_sec+elapsed_time.tv_usec/1000000.0);
/*for(i=0;i<N;i++) {
for(j=0;j<N;j++) {
printf("%f\n",C[i][j]);
}
}*/
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include "utils.h"
#include "bitarray.h"
#include "search.h"
#include "parse.h"
int main(int argc, char *argv[])
{
invertedIndex *index;
char *dirname = argv[1], *string = argv[2];
if(argc <= 2) {
printf("USAGE: ./search <DIRNAME> <STRING>\n");
exit(-1);
}
index = (invertedIndex *) malloc(sizeof(invertedIndex));
index->noTerms = index->noFiles = 0;
index->terms = getTerms(string, &index->noTerms);
index->noFiles = countFiles(dirname);
index->filenames = (char **) malloc(index->noFiles * sizeof(char *));
if(index->filenames == NULL) {
freeIndex(index);
fprintf(stderr, "ERROR: Could not allocate memory\n");
exit(-1);
}
index->found = (bitarray *) malloc(index->noTerms * sizeof(bitarray));
if(index->found == NULL) {
freeIndex(index);
fprintf(stderr, "ERROR: Could not allocate memory\n");
exit(-1);
}
index->tfidf = (float **) malloc(index->noTerms * sizeof(float *));
if(index->tfidf == NULL) {
freeIndex(index);
fprintf(stderr, "ERROR: Could not allocate memory\n");
exit(-1);
}
for(size_t i = 0; i < index->noTerms; i++) {
index->found[i] = (bitarray) calloc(INDEX(index->noFiles), sizeof(size_t));
index->tfidf[i] = (float *) calloc(index->noFiles, sizeof(float *));
}
if(searchDir(index, dirname)) {
fprintf(stderr, "ERROR: Could not open directory \"%s\"\n", dirname);
exit(-1);
}
parseString(string, index);
showResults(index);
return 0;
}
|
C
|
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include "socket.h"
#include "../config.h"
// configure_tcp_socket creates a tcp socket socket according to config and cli args.
// Socket is bound and listening ready to accept connections.
int create_tcp_socket(in_addr_t host, int port)
{
int sock_fd = -1;
if ((sock_fd = socket(AF_INET, SOCK_STREAM, 0)) == -1)
{
perror("Socket openning failed");
exit(EXIT_FAILURE);
}
struct sockaddr_in serv_addr;
// preallocating the memory
memset(&serv_addr, '0', sizeof(serv_addr));
serv_addr.sin_port = htons(port);
serv_addr.sin_addr.s_addr = host;
serv_addr.sin_family = AF_INET;
// for some reason they call it that
int yes = 1;
if (setsockopt(sock_fd, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(int)) == -1)
{
perror("Socket options setting failed");
exit(EXIT_FAILURE);
}
if (bind(sock_fd, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) == -1)
{
perror("Socket binding failed");
close(sock_fd);
exit(EXIT_FAILURE);
}
if (listen(sock_fd, CONNECTION_QUEUE) == -1)
{
char *err_buff;
sprintf(err_buff, "Could not listen on port %d", port);
perror(err_buff);
close(sock_fd);
exit(EXIT_FAILURE);
}
return sock_fd;
}
// send_all sends all the data from buff via socket fd,
// len initially is a length of buff aka the number of bytes to be sent
// then len is set to the number of bytes actually sent.
int send_all(int fd, const char *buff, int *len)
{
int total = 0; // bytes send
int bytes_left = *len;
int n;
while (total < *len)
{
n = send(fd, buff + total, bytes_left, 0);
if (n == -1)
{
perror("An error occurred during sending data via socket");
break;
}
total += n;
bytes_left -= n;
}
*len = total;
return n == -1 ? -1 : 0; // 0 on success, -1 on error
}
|
C
|
int env(char *argsList) {
int i = 0;
for (i = 0; i < 4; i++)
if (argsList[i] == NULL) {
printf("Missing argument %d. \n Usage: setenv [Name] [value] [flag]\n", i);
return 0;
}
return setenv(argsList[1], argsList[2], (int) argsList[3]);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include "../dictionary.h"
#include "test_dictionary.h"
void init_table(int size, node *table[size])
{
for (int i = 0; i < size; i++)
{
table[i] = NULL;
}
}
void test_check_list(void)
{
{
node *n0 = NULL;
assert(!check_list(n0, "abc"));
}
{
node n1 = {.word = "foo", .next = NULL};
assert(check_list(&n1, "foo"));
assert(check_list(&n1, "FoO"));
assert(!check_list(&n1, "bar"));
node n2 = {.word = "bar", .next = &n1};
assert(check_list(&n2, "foo"));
assert(check_list(&n2, "fOo"));
assert(check_list(&n2, "bar"));
assert(check_list(&n2, "bAR"));
}
}
void test_check_hash_table(void)
{
{
int size = 10;
node *table[size];
init_table(size, table);
assert(!check_hash_table(size, table, "foo"));
}
{
int size = 10;
node *table[size];
init_table(size, table);
node node1 = {.word = "foobar", .next = NULL};
node node2 = {.word = "abc", .next = NULL};
table[hash_with_djb2(node1.word, size)] = &node1;
table[hash_with_djb2(node2.word, size)] = &node2;
assert(check_hash_table(size, table, "abc"));
}
}
void test_hash_with_array_size(void)
{
assert(hash_with_array_size("", 1) == 0);
assert(hash_with_array_size("abc", 1) == 0);
assert(hash_with_array_size("sfsdgsd'sdfdsfsd'sfd", 1) == 0);
unsigned int pre_code;
pre_code = 1 + 2 * 31 + 3 * 31 * 31;
assert(hash_with_array_size("abc", 11) == pre_code % 11);
pre_code = 1 + 2 * 31 + 3 * 31 * 31 + 4 * 31 * 31 * 31 + 5 * 31 * 31 * 31 * 31;
assert(hash_with_array_size("abcde", 11) == pre_code % 11);
}
void test_store_in_table(void)
{
{
node *table[10];
int hash_code = 0;
node new_node = {.word = "abc", .next = NULL};
assert(store_in_table(table, hash_code, &new_node));
assert(table[hash_code] == &new_node);
}
{
node *table[10];
node node_in_table = {.word = "foobar", .next = NULL};
node new_node = {.word = "abc", .next = NULL};
int hash_code = 5;
table[hash_code] = &node_in_table;
assert(store_in_table(table, hash_code, &new_node));
assert(table[hash_code] == &new_node);
assert(table[hash_code]->next == &node_in_table);
}
}
// integration test
void test_load_file_into_table(void)
{
{
int size = 10;
node *table[size];
init_table(size, table);
node node_array[size];
char dict[] = "foo\nbar\n";
assert(load_file_into_table(size, table, node_array, dict));
assert(check_hash_table(size, table, "foo"));
assert(check_hash_table(size, table, "Foo"));
assert(!check_hash_table(size, table, "abc"));
}
}
void test_dictionary(void)
{
test_check_list();
test_check_hash_table();
test_hash_with_array_size();
test_store_in_table();
test_load_file_into_table();
}
|
C
|
#ifndef VEC_H
#define VEC_H
struct Vec2i {
int x,y;
};
struct Vec2f
{
float x,y;
};
bool operator==(Vec2f a, Vec2f b);
Vec2f operator+(Vec2f a, Vec2f b);
Vec2f operator+=(Vec2f &a, Vec2f b);
Vec2f operator-(Vec2f v);
Vec2f operator-(Vec2f a, Vec2f b);
Vec2f operator-=(Vec2f &a, Vec2f b);
Vec2f operator*(float c, Vec2f a);
Vec2f operator*(Vec2f a, Vec2f b);
Vec2f operator*=(Vec2f &v, float c);
Vec2f Normalize(Vec2f v);
float Length(Vec2f v);
float Distance(Vec2f a, Vec2f b);
struct Vec3f
{
float x,y,z;
};
Vec3f operator+(Vec3f a, Vec3f b);
Vec3f operator+=(Vec3f &a, Vec3f b);
Vec3f operator-(Vec3f v);
Vec3f operator-(Vec3f a, Vec3f b);
Vec3f operator-=(Vec3f &a, Vec3f b);
Vec3f operator*(float c, Vec3f a);
Vec3f OrthonormalVector(Vec3f v);
Vec3f Cross(Vec3f a, Vec3f b);
Vec3f Normalize(Vec3f v);
float Length(Vec3f v);
float Distance(Vec3f a, Vec3f b);
struct Vec4f {
float x,y,z,w;
};
Vec4f operator*(float c, Vec4f a);
struct Mat3f {
float xx, xy, xz;
float yx, yy, yz;
float zx, zy, zz;
};
Mat3f operator*(Mat3f a, Mat3f b);
Vec3f operator*(Mat3f mat, Vec3f vec);
struct Mat4f {
float xx, xy, xz, xw;
float yx, yy, yz, yw;
float zx, zy, zz, zw;
float wx, wy, wz, ww;
};
Vec4f operator*(Mat4f mat, Vec4f vec);
Mat4f operator*(Mat4f a, Mat4f b);
Mat4f transpose(Mat4f a);
struct Rect
{
Vec2f pos;
Vec2f size;
};
bool PointInRect(Rect rect, Vec2f point);
#endif
|
C
|
#include<stdio.h>
int main()
{
int a[20],i,n1,n2,n;
printf("\n enter number of elements");
scanf("%d",&n);
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
printf("the array is ");
for(i=0;i<n;i++)
{
printf("%d ",a[i]);
}
printf("\n enter the number you want to replace");
scanf("%d",&n1);
printf("\n enter the number which you want to place ");
scanf("%d",&n2);
for(i=0;i<n;i++)
{
if(a[i]==n1)
{
a[i] = n2;
}
}
printf("\n updated array");
for(i=0;i<n;i++)
{
printf("%d ",a[i]);
}
return 0;
}
|
C
|
/*
-------------------------------------------------------------------------
OBJECT NAME: map_std_name.c
FULL NAME: VarDB merge
ENTRY POINTS: main()
STATIC FNS: none
DESCRIPTION: Take Standard Name information from master file and map
into an existing file.
VarDB. This allows indivdual copies to be brought upto
date quickly and easily.
INPUT: FileName
COPYRIGHT: University Corporation for Atmospheric Research, 2005
-------------------------------------------------------------------------
*/
#include <stdio.h>
#include <sys/types.h>
#include <vardb.h>
#include <portable.h>
struct vardb_hdr VarDB_Hdr1, VarDB_Hdr2;
struct var_v2 VarDB1[1000], VarDB2;
/* -------------------------------------------------------------------- */
int main(int argc, char *argv[])
{
FILE *fp1, *fp2;
int rc, masterCount, slaveCount;
int i, j;
if (argc != 2)
{
fprintf(stderr, "Usage: map_std_name VarDB_filename\n");
exit(1);
}
if ((fp1 = fopen(argv[1], "r+b")) == NULL)
{
fprintf(stderr, "VarDB: can't open %s\n", argv[1]);
return(ERR);
}
if ((fp2 = fopen("/jnet/tmp/chris/raf/proj/defaults/VarDB", "rb")) == NULL)
{
fprintf(stderr, "VarDB: can't open $JLOCAL/proj/defaults/VarDB\n");
fclose(fp1);
return(ERR);
}
fread((char *)&VarDB_Hdr1, sizeof(struct vardb_hdr), 1, fp1);
fread((char *)&VarDB_Hdr2, sizeof(struct vardb_hdr), 1, fp2);
VarDB_Hdr1.Version = VarDB_Hdr2.Version;
slaveCount = ntohl(VarDB_Hdr1.nRecords);
masterCount = ntohl(VarDB_Hdr2.nRecords);
fread((char *)VarDB1, sizeof(struct var_v2), slaveCount, fp1);
for (i = 0; i < masterCount; ++i)
{
fread((char *)&VarDB2, sizeof(struct var_v2), 1, fp2);
for (j = 0; j < slaveCount; ++j)
if (strcmp(VarDB1[j].Name, VarDB2.Name) == 0)
{
VarDB1[j].standard_name = VarDB2.standard_name;
VarDB1[j].reference = VarDB2.reference;
}
}
rewind(fp1);
fwrite((char *)&VarDB_Hdr1, sizeof(struct vardb_hdr), 1, fp1);
fwrite((char *)VarDB1, sizeof(struct var_v2), slaveCount, fp1);
fclose(fp1);
fclose(fp2);
return(0);
} /* END MAIN */
/* END VDBMERGE.C */
|
C
|
/*
** vider la list_double
*/
#include "list_double.h"
void erase_elem_list(t_list *list)
{
t_list *elem;
t_list *nextelem;
elem = list->next;
while (elem != list)
{
nextelem = elem->next; /*enregistre le pointeur sur l.elem suiv avant de supprimer */
free(elem);
elem = nextelem;
}
}
void erase_list(t_list **list)
{
erase_elem_list(*list);
free(*list);
*list = NULL;
}
|
C
|
/* ************************************************************************** */
/* */
/* :::::::: */
/* get_coords.c :+: :+: */
/* +:+ */
/* By: ivork <ivork@student.codam.nl> +#+ */
/* +#+ */
/* Created: 2021/05/05 16:58:19 by ivork #+# #+# */
/* Updated: 2021/05/06 19:39:19 by ivork ######## odam.nl */
/* */
/* ************************************************************************** */
#include "../minirt.h"
#include "../libft/libft.h"
#include <stdio.h>
t_coordinates get_coords(t_coordinates coordinates, char *str)
{
char **info;
info = ft_split(str, ',');
if (info[0] == NULL || info[1] == NULL || info[2] == NULL)
{
printf("Error\nCould not read camera coordinates\n");
exit(0);
}
if (info[3] != NULL)
{
printf("Error\nToo may arguments camera coordinates\n");
exit(0);
}
coordinates.x = ft_atod(info[0]);
coordinates.y = ft_atod(info[1]);
coordinates.z = ft_atod(info[2]);
free_2d_array(info);
return (coordinates);
}
|
C
|
#include <stdlib.h>
#include <stdio.h>
#if defined(_OPENMP)
#include <omp.h>
#endif
#include "fma_omp.h"
#include "fma_host.h"
int
fma_host_initialize (int N, int T, float **a)
{
if (!N) {
*a = NULL;
}
else {
*a = (float *) malloc (N * sizeof (float));
if (!*a) {
printf ("Failed to allocate a\n");
return 1;
}
#pragma omp parallel for schedule(static)
for (int i = 0; i < N; i++) {
(*a)[i] = (float) i;
}
}
return 0;
}
int
fma_host_free (int N, int T, float **a)
{
free (*a);
*a = NULL;
return 0;
}
int
fma_host_start (int N, int T, float *a, float b, float c)
{
#pragma omp parallel
{
int num_threads, my_thread;
int my_start, my_end;
int my_N;
#if defined(_OPENMP)
my_thread = omp_get_thread_num();
num_threads = omp_get_num_threads();
#else
my_thread = 0;
num_threads = 1;
#endif
/* get thread intervals */
my_start = ((size_t) my_thread * (size_t) N) / (size_t) num_threads;
my_end = ((size_t) (my_thread + 1) * (size_t) N) / (size_t) num_threads;
my_N = my_end - my_start;
#if 0
printf ("[%d/%d]: [%d, %d)\n", my_thread, num_threads, my_start, my_end);
#endif
/* execute the loop */
fma_loop_host (my_N, T, &a[my_start], b, c);
}
return 0;
}
int
fma_host_end (int N, int T, float *a, float b, float c)
{
return 0;
}
|
C
|
#include <linux/init.h>
#include <linux/module.h>
#include <linux/proc_fs.h>
MODULE_LICENSE("GPL");
static struct file_operations file_ops;
static ssize_t write(struct file *file, const char *buf, size_t count, loff_t *pos) {
printk("%.*s", count, buf); return count;
}
static int hello_init(void)
{
struct proc_dir_entry *entry = proc_create("hello", 0, NULL, &file_ops);
if(!entry) return -ENOENT;
file_ops.owner = THIS_MODULE;
file_ops.write = write;
printk(KERN_ALERT "Hllo, world\n");
return 0;
}
static void hello_exit(void)
{
remove_proc_entry("hello", NULL);
printk(KERN_ALERT "Nikal laude\n");
}
module_init(hello_init);
module_exit(hello_exit);
|
C
|
/**
* \file graphics_select.c
* Implementação do arquivo graphics_select.h
*/
#include "graphics_select.h"
// borda lateral e superior e inferior da janela
#define WINDOWBORDERLATERAL '|'
#define WINDOWBORDERUPDOWN '-'
// nome da janela
#define WINDOWNAME "options"
// altura de uma opção
#define OPTIONHEIGHT 3
// borda lateral e superior e inferior de uma opção selecionada
#define OPTIONBORDERLATERAL '*'
#define OPTIONBORDERUPDOWN '*'
/************************************************************************************
* Estruturas
************************************************************************************/
/**
* Estrutura de uma opção
*/
typedef struct option Option;
struct option{
char name[30];
WINDOW* window;
int page;
Option *next;
Option *previous;
};
/**
* Estrutura de um menu de seleção
*/
struct graphicSelect{
int positionX;
int positionY;
int width;
int height;
WINDOW* window;
int totalOptions;
Option* sentinel;
};
/************************************************************************************
* Funções privadas
************************************************************************************/
/**
* Libera opções
*/
void GRAPHICSSELECT_freeOptions(Option** option, Option** sentinel){
if(!option || !(*option) || ((*option)==(*sentinel))) return;
Option* current = (*option);
(*option) = (*option)->next;
free(current);
GRAPHICSSELECT_freeOptions(&(*option),&(*sentinel));
}
/**
* Desenha caixa em volta da janela
*/
void GRAPHICSSELECT_drawBoxWindow(GraphicSelect** graphic){
if(!graphic || !(*graphic)) return;
box((*graphic)->window, WINDOWBORDERLATERAL,WINDOWBORDERUPDOWN);
mvwprintw((*graphic)->window,0,1,WINDOWNAME);
wrefresh((*graphic)->window);
}
/************************************************************************************
* Funções públicas
************************************************************************************/
/**
* Cria uma janela de seleção. Desenha o espaço da janela.
* \return Ponteiro para a memória alocada, ou NULL em caso de falha de alocação
* \param positionX Posição x da janela
* \param positionY Posição y da janela
* \param width Largura da janela (que será a largura de cada opção)
* \param height Altura da janela (não de cada opção; as opções estarão contidas na janela).
*/
GraphicSelect* GRAPHICSSELECT_create(int positionX, int positionY, int width, int height){
GraphicSelect* graphic = malloc(sizeof(GraphicSelect));
if(!graphic) return NULL;
graphic->window = newwin(height, width, positionY, positionX);
if(!graphic->window){
free(graphic);
return NULL;
}
graphic->sentinel = malloc(sizeof(Option));
if(!graphic->sentinel){
delwin(graphic->window);
free(graphic);
return NULL;
}
graphic->sentinel->next = graphic->sentinel;
graphic->sentinel->previous = graphic->sentinel;
graphic->positionX = positionX;
graphic->positionY = positionY;
graphic->width = width;
graphic->height = height;
graphic->totalOptions = 0;
GRAPHICSSELECT_drawBoxWindow(&graphic);
return graphic;
}
/**
* Libera memória alocada no objeto GraphicSelect
* \return NULL
* \param graphic Ponteiro para GraphicSelect
*/
GraphicSelect* GRAPHICSSELECT_free(GraphicSelect* graphic){
if(!graphic) return NULL;
GRAPHICSSELECT_freeOptions(&(graphic->sentinel->next),&(graphic->sentinel));
free(graphic->sentinel);
wclear(graphic->window);
wrefresh(graphic->window);
delwin(graphic->window);
free(graphic);
return NULL;
}
/**
* Adiciona uma opção no menu de opções. As opções aparecem na ordem de adição
* \return 1 em caso de sucesso, ou 0 em caso de falha
* \param graphic Ponteiro duplo para GraphicSelect
* \param optionName Nome da opção a ser adicionada (no máximo até 30 caracteres)
*/
int GRAPHICSSELECT_addOption(GraphicSelect** graphic, const char* optionName){
if(!graphic || !(*graphic)) return 0;
Option* oldLast = (*graphic)->sentinel->previous;
oldLast->next = malloc(sizeof(Option));
if(!(oldLast->next)) {
oldLast->next = (*graphic)->sentinel;
return 0;
}
oldLast->next->next = (*graphic)->sentinel;
oldLast->next->previous = oldLast;
strcpy(oldLast->next->name, optionName);
oldLast->next->window = NULL;
(*graphic)->sentinel->previous = oldLast->next;
((*graphic)->totalOptions)++;
return 1;
}
/**
* Remove uma opção com maior índice do menu de opções.
* \param graphic Ponteiro duplo para GraphicSelect
*/
void GRAPHICSSELECT_removeOption(GraphicSelect** graphic){
if(!graphic || !(*graphic) || ((*graphic)->sentinel->previous == (*graphic)->sentinel)) return;
Option* oldLast = (*graphic)->sentinel->previous;
oldLast->previous->next = oldLast->next;
oldLast->next->previous = oldLast->previous;
free(oldLast);
((*graphic)->totalOptions)--;
}
/**
* Apaga todas as opções do menu de opções
* \param graphic Ponteiro duplo para GraphicSelect
*/
void GRAPHICSSELECT_clearOptions(GraphicSelect** graphic){
if(!graphic || !(*graphic) || ((*graphic)->sentinel->next == (*graphic)->sentinel)) return;
GRAPHICSSELECT_freeOptions(&(*graphic)->sentinel->next, &(*graphic)->sentinel);
(*graphic)->sentinel->next = (*graphic)->sentinel;
(*graphic)->sentinel->previous = (*graphic)->sentinel;
(*graphic)->totalOptions = 0;
}
/**
* Abre opções e o usuário poderá escolher com ENTER.
* \param graphic Ponteiro duplo para GraphicSelect
* \param optionName Variável a ser preenchida com o nome da opção escolhida
*/
void GRAPHICSSELECT_selectOption(GraphicSelect** graphic, char *optionName){
if(!graphic || !(*graphic) || ((*graphic)->sentinel->next == (*graphic)->sentinel)) return;
// opção atual
Option* currentOption = (*graphic)->sentinel->next;
// posição x e y da subjanela de cada opção
int optionPosX=(*graphic)->positionX+1, optionPosY=(*graphic)->positionY +1;
// largura de cada opção
int optionWidth = (*graphic)->width - 2;
// define a página atual
int currentPage=1;
// cria as subjanelas de opções
while(currentOption!=(*graphic)->sentinel){
// a opção passou do limite da janela, colocar na próxima página
if(optionPosY + OPTIONHEIGHT > (*graphic)->positionY + (*graphic)->height - 1){
currentPage++;
optionPosY = (*graphic)->positionY+1;
}
// cria a janela
currentOption->window = newwin(OPTIONHEIGHT,optionWidth,optionPosY,optionPosX);
// define sua página
currentOption->page = currentPage;
// se a página é a primeira, mostra opção
if(currentOption->page == 1){
mvwprintw(currentOption->window,1,1,currentOption->name);
if(currentOption->previous == (*graphic)->sentinel)
box(currentOption->window,OPTIONBORDERLATERAL,OPTIONBORDERUPDOWN);
else
box(currentOption->window,' ',' ');
wrefresh(currentOption->window);
}
// incrementa posição y da próxima opção
optionPosY+=OPTIONHEIGHT;
// vai para a próxima opção
currentOption = currentOption->next;
}
// guarda última página
int lastPage = currentPage;
// adiciona legenda no rodapé da página
mvwprintw((*graphic)->window,(*graphic)->height-1,
(*graphic)->width/2,"page %d/%d",1,lastPage);
wrefresh((*graphic)->window);
// habilita teclado
keypad(stdscr,TRUE);
cbreak();
// variável de controle do pressionamento de tecla
int keyPressed=0;
currentOption = (*graphic)->sentinel->next;
// variável auxiliar
Option* iterator = NULL;
// lista de opções da página atual
Option *listCurrentPage = currentOption;
// lista de opções da página anterior
Option *listOldPage = listCurrentPage;
// enquanto não pressionar ENTER...
while(keyPressed!=10){
// se a lista de opções da página atual for diferente da página anterior...
if(listCurrentPage != listOldPage){
// limpa opções anteriores
iterator = listOldPage;
while(iterator!=(*graphic)->sentinel &&
iterator->page==listOldPage->page){
wclear(iterator->window);
wrefresh(iterator->window);
iterator = iterator->next;
}
// escreve opções atuais
iterator = listCurrentPage;
while(iterator!=(*graphic)->sentinel &&
iterator->page == listCurrentPage->page){
mvwprintw(iterator->window, 1,1,iterator->name);
if(iterator == currentOption)
box(iterator->window,OPTIONBORDERLATERAL,OPTIONBORDERUPDOWN);
else
box(iterator->window,' ',' ');
wrefresh(iterator->window);
iterator = iterator->next;
}
// lista anterior igual a atual
listOldPage = listCurrentPage;
}
// recebe pressionamento de tecla
keyPressed = getch();
// retira marcação da opção atual
if(keyPressed!=10){
box(currentOption->window,' ',' ');
wrefresh(currentOption->window);
}
switch(keyPressed){
case KEY_UP:
if(currentOption->previous == (*graphic)->sentinel)
currentOption = (*graphic)->sentinel->previous;
else
currentOption = currentOption->previous;
break;
case KEY_DOWN:
if(currentOption->next == (*graphic)->sentinel)
currentOption = (*graphic)->sentinel->next;
else
currentOption = currentOption->next;
break;
}
// muda a lista da página atual se a opção atual tiver página diferente
if(currentOption->page != listCurrentPage->page){
listCurrentPage = currentOption;
// faz a lista apontar para o início da lista
while(listCurrentPage->previous != (*graphic)->sentinel &&
listCurrentPage->previous->page==currentOption->page)
listCurrentPage = listCurrentPage->previous;
}
// marca opção atual, atualiza página
if(keyPressed!=10){
box(currentOption->window,OPTIONBORDERLATERAL,OPTIONBORDERUPDOWN);
mvwprintw((*graphic)->window,(*graphic)->height-1,
(*graphic)->width/2,"page %d/%d",listCurrentPage->page,lastPage);
wrefresh((*graphic)->window);
wrefresh(currentOption->window);
}
}
// guarda opção escolhida
strcpy(optionName,currentOption->name);
// libera subjanelas de opções
currentOption = (*graphic)->sentinel->next;
while(currentOption != (*graphic)->sentinel){
delwin(currentOption->window);
currentOption->window = NULL;
currentOption = currentOption->next;
}
// atualiza janela de opções
GRAPHICSSELECT_drawBoxWindow(&(*graphic));
}
/**
* Pega posição x da janela
* \return Posição x da janela
* \param graphic Ponteiro para GraphicSelect
*/
int GRAPHICSSELECT_getPositionX(GraphicSelect** graphic){
return (*graphic)->positionX;
}
/**
* Pega posição y da janela
* \return Posição y da janela
* \param graphic Ponteiro para GraphicSelect
*/
int GRAPHICSSELECT_getPositionY(GraphicSelect** graphic){
return (*graphic)->positionY;
}
/**
* Pega largura da janela
* \return Largura da janela
* \param graphic Ponteiro para GraphicSelect
*/
int GRAPHICSSELECT_getWidth(GraphicSelect** graphic){
return (*graphic)->width;
}
/**
* Pega altura da janela
* \return Altura da janela
* \param graphic Ponteiro para GraphicSelect
*/
int GRAPHICSSELECT_getHeight(GraphicSelect** graphic){
return (*graphic)->height;
}
|
C
|
#include <stdlib.h>
#include <stdio.h>
#include "lists.h"
/**
*
*/
int is_palindrome(listint_t **head)
{
listint_t *curr = *head, *start = *head; /* count nodes */
if ((*head == NULL) || (*head)->next == NULL)
return (1);
return(helper(curr, &start));
}
int helper(listint_t *curr, listint_t **start)
{
if (curr->next) /* recursive case */
{
if (!helper(curr->next, start))
return (0);
if (curr->n != (*start)->n)
return (0);
*start = (*start)->next;
}
else
{
if ((*start)->n != curr->n)
return (0);
*start = (*start)->next;
return (1);
}
return (1);
}
|
C
|
#include "lcd.h"
#include "keypad.h"
#include <avr/io.h>
#include <avr/interrupt.h>
#include <avr/sleep.h>
#define NUMBER_OF_OVERFLOWS_PER_SECOND 4
unsigned char g_tick = 0;
ISR(TIMER0_OVF_vect)
{
g_tick++;
if(g_tick == NUMBER_OF_OVERFLOWS_PER_SECOND)
{
PORTD ^= (1<<PD7); //toggle led every 1 second
buzzer_on();
g_tick = 0; //clear the tick counter again to count a new 1 second
}
}
/* Description :
* For clock=1Mhz and prescale F_CPU/1024 every count will take 1ms
* so put initial timer counter=0 0 --> 255 (256ms per overflow)
* so we need timer to overflow 2 times to get a 0.5 second
*/
void timer0_init_normal_mode(void)
{
TCNT0 = 0; //timer initial value
TIMSK |= (1<<TOIE0); //enable overflow interrupt
/* Configure the timer control register
* 1. Non PWM mode FOC0=1
* 2. Normal Mode WGM01=0 & WGM00=0
* 3. Normal Mode COM00=0 & COM01=0
* 4. clock = F_CPU/1024 CS00=1 CS01=0 CS02=1
*/
TCCR0 = (1<<FOC0) | (1<<CS02) | (1<<CS00);
}
/* External INT0 Interrupt Service Routine */
ISR(INT0_vect)
{
if(BIT_IS_SET(PORTD,PD2))
{
set_sleep_mode(SLEEP_MODE_IDLE);
sleep_mode();
}
}
/* External INT0 enable and configuration function */
void INT0_Init(void)
{
SREG &= ~(1<<7); // Disable interrupts by clearing I-bit
DDRD &= (~(1<<PD2)); // Configure INT0/PD2 as input pin
GICR |= (1<<INT0); // Enable external interrupt pin INT0
MCUCR |= (1<<ISC00) | (1<<ISC01); // Trigger INT0 with the raising edge
SREG |= (1<<7); // Enable interrupts by setting I-bit
}
//Function to initialize Buzzer
void buzzer_pin_config (void)
{
DDRD |= (1<< PD5) ; //Setting PORTC 3 as output
PORTD &=~(1<<PD5); //Setting PORTC 3 logic low to turnoff buzzer
}
//Function to Initialize PORTS
void port_init (void)
{
buzzer_pin_config();
}
void buzzer_on (void)
{
unsigned char port_restore = 0;
port_restore = PIND;
port_restore = port_restore | 0x20;
PORTD = port_restore;
}
void buzzer_off (void)
{
unsigned char port_restore = 0;
port_restore = PIND;
port_restore &=~(0x20);
PORTD = port_restore;
}
void init_devices (void)
{
cli(); //Clears the global interrupts
port_init();
sei(); //Enables the global interrupts
}
int main(void)
{
init_devices();
buzzer_off(); //Turn off buzzer
int trial_times = 0;
LCD_init();
LCD_displayStringRowColumn(0,0,"Enter your password");
INT0_Init(); // Enable external INT0
DDRB |= (1<<PB0); //green led
DDRD |= (1<<PD7); //red led
/* configure pin PD0 and PD1 as output pins MOTOR */
DDRD |= (1<<PD0);
DDRD |= (1<<PD1);
/* Motor is stop at the beginning */
PORTD &= ~(1<<PD0);
PORTD &= ~(1<<PD1);
//red led initially off
PORTD &=~ (1<<PD7);
DDRC |= (1<<PC0); //configure the led pin to be output pin.
PORTC &= ~(1<<PC0); //LED is off at the beginning(Positive Logic).
SREG |= (1<<7); //enable global interrupts in MC by setting the I-Bit.
while(1)
{
unsigned char key1;
unsigned char key2;
unsigned char key3;
/* if any switch pressed for more than 500 ms it counts more than one press */
key1 = KeyPad_getPressedKey(); /* get the pressed key number */
if((key1 <= 9) && (key1 >= 0))
{
LCD_goToRowColumn(1,0);
LCD_displayString("*");
}
_delay_ms(500); /* Press time */
key2 = KeyPad_getPressedKey(); /* get the pressed key number */
if((key2 <= 9) && (key2 >= 0))
{
LCD_goToRowColumn(1,1);
LCD_displayString("*");
}
_delay_ms(500); /* Press time */
key3 = KeyPad_getPressedKey(); /* get the pressed key number */
if((key3 <= 9) && (key3 >= 0))
{
LCD_goToRowColumn(1,2);
LCD_displayString("*");
}
_delay_ms(500); /* Press time */
/* check if the password is correct (Rotate clock wise) */
if((key1 == 1)&& (key2 == 2)&& (key3 == 3))
{
PORTD &= (~(1<<PD0));
PORTD |= (1<<PD1);
LCD_clearScreen();
LCD_goToRowColumn(0,0);
LCD_displayString("Correct");
PORTB |= (1<<PB0); //green led on
}
/* check if the password is incorrect (turn off the motor) */
else if ((key1 != 1)&& (key2 != 2)&& (key3 != 3))
{
PORTD &= (~(1<<PD0));
PORTD &= (~(1<<PD1));
trial_times ++;
LCD_goToRowColumn(0,0);
if (trial_times >= 3)
{
LCD_clearScreen();
LCD_displayString("Alarm");
timer0_init_normal_mode(); //start the timer.
}
else
{
LCD_clearScreen();
LCD_displayString("Wrong ,Re-enter the password");
}
}
}
}
|
C
|
#include "misstake.h"
int shellcommandNOcall(int fd,char* name)
{
if(fd < 0 || NULL == name)
{
return -1;
}
write(fd,"No call shell command ",22);
write(fd,name,strlen(name));
write(fd," !! \n",5);
return 0;
}
int Nodir_or_file(int fd,char* dir)
{
if(fd < 0 || NULL == dir)
{
return -1;
}
write(fd,"No such file or directory : ",28);
write(fd,dir,strlen(dir));
write(fd," !\n",3);
return 0;
}
int Nooptions(int fd, char* commandname, int mark[], char** arg)
{
int i = 0;
int times = 0;
int retstate = 0;
if(NULL == commandname || NULL == mark || NULL == arg || fd < 0)
{
return -1;
}
for(i = 0; arg[i] != NULL ;i++)
{
if(0 == mark[i])
{
retstate++;
if(0 == times)
{
times = 1;
write(fd,"command \"",9);
write(fd,commandname,strlen(commandname));
write(fd,"\"cann\'t to handle parameter :",29);
}
write(fd,"[",1);
write(fd,arg[i],strlen(arg[i]));
write(fd,"] ",2);
}
}
if(0 != times)
{
write(fd,"\n",1);
}
return retstate;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/time.h>
#include <pthread.h>
#define NOT_COMPLETED 0
#define COMPLETED 1
#define MAX_VALUE 200000
#define STEP 50
#define THREADS 1
pthread_mutex_t mutex[THREADS];
void *threadFunction(void *input);
volatile int *memory;
volatile sig_atomic_t current_index = 0;
int main(int argc, char *argv[])
{
struct timeval begin, end;
gettimeofday(&begin, 0);
memory = malloc(sizeof(int) * THREADS);
memset(memory, 0, sizeof(int) * THREADS);
pthread_t handle[THREADS];
for (int i = 0; i < THREADS; i++)
{
mutex[i] = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_lock(&mutex[i]);
}
for (int n = 0; n < THREADS; n++)
{
pthread_create(&handle[n], NULL, threadFunction, (int *)n);
}
for (int n = 0; n < THREADS; n++)
{
pthread_join(handle[n], NULL);
}
gettimeofday(&end, 0);
for (int i = 0; i < current_index; i++)
{
printf("Memory at index %d:\t%d\n", i, memory[i]);
}
printf("Execution time: %.3f seconds\n", (end.tv_sec - begin.tv_sec) + (end.tv_usec - begin.tv_usec) * 1e-6);
printf("Press enter to exit...\n");
getchar();
free(memory);
return EXIT_SUCCESS;
}
void *threadFunction(void *input)
{
int id = (int)input;
int idx = current_index++;
pthread_mutex_unlock(&mutex[id]);
while (1)
{
for (int i = 0; i < (idx + 1) * STEP; ++i)
{
pthread_mutex_lock(&mutex[id]);
++memory[idx];
pthread_mutex_unlock(&mutex[id]);
}
for (int i = 0; i < THREADS; i++)
{
pthread_mutex_lock(&mutex[i]);
}
if (current_index >= MAX_VALUE / STEP)
{
for (int i = 0; i < THREADS; i++)
{
pthread_mutex_unlock(&mutex[i]);
}
break;
}
idx = current_index++;
memory = realloc(memory, sizeof(int) * current_index);
memory[current_index - 1] = 0;
for (int i = 0; i < THREADS; i++)
{
pthread_mutex_unlock(&mutex[i]);
}
}
return NULL;
}
|
C
|
#ifndef PARTICLE_MANAGER_H
#define PARTICLE_MANAGER_H
#include "Particle.h"
#include "../System.h"
static Particle * Create_Thrust_Particle() {
Particle * thrust_particle = new Particle();
return thrust_particle;
}
static Particle * Create_Smoke_Particle() {
Particle * temp_particle = new Particle();
//Drawable Init
temp_particle->texture = surface_manager->smoke;
temp_particle->draw_angle = temp_particle->angle = 0.0;
temp_particle->draw_scale = 16.0;
temp_particle->drawing_box.w = temp_particle->drawing_box.h = 2 * temp_particle->draw_scale;
//RigidBody Init
temp_particle->velocity = 50.0;
temp_particle->dx = temp_particle->dy = temp_particle->force = temp_particle->torque = temp_particle->rotation = 0.0;
temp_particle->mass = 1.0;
temp_particle->Set_Inertia(temp_particle->draw_scale);
temp_particle->x = temp_particle->y = temp_particle->drawing_box.x = temp_particle->drawing_box.y = 0.0;
//Motor Init
temp_particle->velocity_limit = temp_particle->velocity;
temp_particle->rotation_limit = temp_particle->reverse_modifier = temp_particle->force_motor = temp_particle->torque_motor = 0.0;
//Particle Init
temp_particle->age_timer.Set_Interval(2.0);
temp_particle->range = 500.0;
return temp_particle;
}
static Particle * Create_Shatter_Particle() {
Particle * temp_particle = new Particle();
//Drawable Init
temp_particle->texture = surface_manager->shatter;
temp_particle->draw_angle = temp_particle->angle = 0.0;
temp_particle->draw_scale = 4.0;
temp_particle->drawing_box.w = temp_particle->drawing_box.h = 2 * temp_particle->draw_scale;
//RigidBody Init
temp_particle->velocity = 100.0;
temp_particle->dx = temp_particle->dy = temp_particle->force = temp_particle->torque = temp_particle->rotation = 0.0;
temp_particle->mass = 1.0;
temp_particle->Set_Inertia(temp_particle->draw_scale);
temp_particle->x = temp_particle->y = temp_particle->drawing_box.x = temp_particle->drawing_box.y = 0.0;
//Motor Init
temp_particle->velocity_limit = temp_particle->velocity;
temp_particle->torque_motor = 30.0;
temp_particle->rotation_limit = 45.0;
temp_particle->reverse_modifier = temp_particle->force_motor = 0.0;
//Particle Init
temp_particle->age_timer.Set_Interval(1.0);
temp_particle->range = 500.0;
return temp_particle;
}
static Particle * Create_Explosion_Particle() {
Particle * explosion_particle = new Particle();
return explosion_particle;
}
static Particle * Create_Laser_Particle() {
Particle * temp_particle = new Particle();
//Drawable Init
temp_particle->texture = surface_manager->laser;
temp_particle->draw_angle = temp_particle->angle = 0.0;
temp_particle->draw_scale = 8.0;
temp_particle->drawing_box.w = temp_particle->drawing_box.h = 2 * temp_particle->draw_scale;
//RigidBody Init
temp_particle->velocity = 200.0;
temp_particle->dx = temp_particle->dy = temp_particle->force = temp_particle->torque = temp_particle->rotation = 0.0;
temp_particle->mass = 1.0;
temp_particle->Set_Inertia(temp_particle->draw_scale);
temp_particle->x = temp_particle->y = temp_particle->drawing_box.x = temp_particle->drawing_box.y = 0.0;
//Motor Init
temp_particle->velocity_limit = temp_particle->velocity;
temp_particle->force_motor = 200.0;
temp_particle->rotation_limit = temp_particle->reverse_modifier = temp_particle->torque_motor = 0.0;
//Particle Init
temp_particle->age_timer.Set_Interval(5.0);
temp_particle->range = 200.0;
temp_particle->Set_Group(BULLET_GROUP);
return temp_particle;
}
static Particle * Create_Gauss_Particle() {
Particle * temp_particle = new Particle();
//Drawable Init
temp_particle->texture = surface_manager->bullet;
temp_particle->draw_angle = temp_particle->angle = 0.0;
temp_particle->draw_scale = 8.0;
temp_particle->drawing_box.w = temp_particle->drawing_box.h = 2 * temp_particle->draw_scale;
//RigidBody Init
temp_particle->velocity = 200.0;
temp_particle->dx = temp_particle->dy = temp_particle->force = temp_particle->torque = temp_particle->rotation = 0.0;
temp_particle->mass = 1.0;
temp_particle->Set_Inertia(temp_particle->draw_scale);
temp_particle->x = temp_particle->y = temp_particle->drawing_box.x = temp_particle->drawing_box.y = 0.0;
//Motor Init
temp_particle->velocity_limit = temp_particle->velocity;
temp_particle->force_motor = 200.0;
temp_particle->rotation_limit = temp_particle->reverse_modifier = temp_particle->torque_motor = 0.0;
//Particle Init
temp_particle->age_timer.Set_Interval(5.0);
temp_particle->range = 400.0;
temp_particle->Set_Group(BULLET_GROUP);
return temp_particle;
}
static Particle * Create_Rocket_Particle() {
Particle * temp_particle = new Particle();
//Drawable Init
temp_particle->texture = surface_manager->missle;
temp_particle->draw_angle = temp_particle->angle = 0.0;
temp_particle->draw_scale = 8.0;
temp_particle->drawing_box.w = temp_particle->drawing_box.h = 2 * temp_particle->draw_scale;
//RigidBody Init
temp_particle->dx = temp_particle->dy = temp_particle->force = temp_particle->torque = temp_particle->velocity = temp_particle->rotation = 0.0;
temp_particle->mass = 1.0;
temp_particle->Set_Inertia(temp_particle->draw_scale);
temp_particle->x = temp_particle->y = temp_particle->drawing_box.x = temp_particle->drawing_box.y = 0.0;
//Motor Init
temp_particle->velocity_limit = 200.0;
temp_particle->force_motor = 200.0;
temp_particle->rotation_limit = temp_particle->reverse_modifier = temp_particle->torque_motor = 0.0;
//Particle Init
temp_particle->age_timer.Set_Interval(5.0);
temp_particle->range = 400.0;
temp_particle->Set_Group(BULLET_GROUP);
return temp_particle;
}
static Particle * Create_Mine_Particle() {
Particle * temp_particle = new Particle();
//Drawable Init
temp_particle->texture = surface_manager->mine;
temp_particle->draw_angle = temp_particle->angle = 0.0;
temp_particle->draw_scale = 8.0;
temp_particle->drawing_box.w = temp_particle->drawing_box.h = 2 * temp_particle->draw_scale;
//RigidBody Init
temp_particle->dx = temp_particle->dy = temp_particle->force = temp_particle->torque = temp_particle->rotation = 0.0;
temp_particle->mass = 1.0;
temp_particle->Set_Inertia(temp_particle->draw_scale);
temp_particle->x = temp_particle->y = temp_particle->drawing_box.x = temp_particle->drawing_box.y = 0.0;
//Motor Init
temp_particle->velocity = temp_particle->velocity_limit = 100.0;
temp_particle->rotation_limit = temp_particle->reverse_modifier = temp_particle->force_motor = temp_particle->torque_motor = 0.0;
//Particle Init
temp_particle->age_timer.Set_Interval(90.0);
temp_particle->range = 100.0;
temp_particle->Set_Group(BULLET_GROUP);
return temp_particle;
}
#endif
|
C
|
#include<stdio.h>
#include<stdlib.h>
struct node
{
int data;
struct node *left;
struct node *right;
};
int search(char [],int,int,char);
struct node* newNode(int data)
{
struct node *nd=(struct node*)malloc(sizeof(struct node));
nd->data=data;
nd->left=NULL;
nd->right=NULL;
return nd;
}
struct node* buildTree(char in[],char pre[],int inStart,int inEnd)
{
static int preIndex=0;
if(inStart>inEnd)
return NULL;
struct node* nd=newNode(pre[preIndex++]);
if(inStart==inEnd)
return nd;
int inIndex=search(in,inStart,inEnd,nd->data);
nd->left=buildTree(in,pre,inStart,inIndex-1);
nd->right=buildTree(in,pre,inIndex+1,inEnd);
return nd;
}
int search(char in[],int inStart,int inEnd,char data)
{
int i;
for(i=inStart;i<=inEnd;i++)
{
if(data==in[i])
return i;
}
}
void inOrder(struct node *nd)
{
if(nd==NULL)
return;
inOrder(nd->left);
printf("%c ",nd->data);
inOrder(nd->right);
}
int main()
{
char in[] = "DBEAFC";
char pre[] = "ABDECF";
int len = sizeof(in)/sizeof(in[0]);
struct node *root = buildTree(in, pre, 0, len - 1);
/* Let us test the built tree by printing Inorder traversal */
printf("\n Inorder traversal of the constructed tree is \n");
inOrder(root);
getchar();
}
|
C
|
#include <stdio.h>
void mySort(int d[], unsigned int n)
{
/* insertion sort*/
int j;
for (j = 0; j< n; j++){
int key = d[j];
int i = j-1;
while (i>-1 && d[i]>key){
d[i+1] = d[i];
i = i-1;
d[i+1] = key;
}
}
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#define MAX_BUF 256
/*
This program print all file's element and show line of this element.
First, it check whether argc is 2. if not print this Usage and exit this program.
Second, it open argv[1] file as "read text". if can't open this file, print error and exit this program.
Third, it get lines from argv[1] file untill end of file or can't read this file.
and print line number and argv[1]'s line
*/
void main(int argc, char *argv[]) {
FILE *fp;
char buf[MAX_BUF];
int line;
if (argc != 2) {
printf("Usage: %s filename\n", argv[0]);
exit(1);
}
if ((fp = fopen(argv[1], "rt")) == NULL) {
perror("fopen");
exit(1);
}
line =1;
while(fgets(buf, MAX_BUF, fp) != NULL){
printf("%4d: %s", line++, buf);
}
fclose(fp);
}
|
C
|
#include "variadic_functions.h"
#include <stdarg.h>
#include <stdio.h>
/**
* print_strings - print the string
* @separator: separator char
* @n: number of all parameters
* Return void
*/
void print_strings(const char *separator, const unsigned int n, ...)
{
unsigned int i;
va_list parameter;
char *print;
va_start(parameter, n);
for (i = 0; i < n; i++)
{
print = va_arg(parameter, char *);
/*Mirar que el string exista*/
if (print)
printf("%s", print);
else
printf("(nil)");
if (i < n - 1 && separator != NULL)
{
printf("%s", separator);
}
}
printf("\n");
va_end(parameter);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "pack.h"
int main(int argc, char *argv[]){
FILE *ifp, *ofp;
int i = 0;
char c;
char byte[4];
int packed,j;
if (argc != 2){
printf("Usage: %s filename\n",argv[0]);
exit(1);
}
ifp = fopen(argv[1],"r");
strcat(argv[1],".packed");
ofp = fopen(argv[1],"wb");
while((c=getc(ifp)) !=EOF){
byte[i] = c;
i++;
if ( i == 4){
packed = pack(byte[0],byte[1],byte[2],byte[3]);
i = 0;
fwrite(&packed,sizeof(packed),1,ofp);
}
}
// deal with the overhang
if (i > 0){
for (j = 3; j >= i; --j )
byte[j]=0;
packed = pack(byte[0],byte[1],byte[2],byte[3]);
printf("Byte %s Packed:%d\n",byte,packed);
i = 0;
fwrite(&packed,sizeof(packed),1,ofp);
}
fclose(ifp);
fclose(ofp);
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
/* function prototypes */
/* Step 1a - Allocate the memory function declaration */
/* Step 2a - Print the memory function declaration */
/* Step 3a - Free the Memory function declaration */
int main()
{
/* Variables */
int* int_dyn_arr;
long unsigned int num_elements ;
long unsigned int iterator;
int factorial;
fprintf( stdout, "Enter number of elements in integer values (greater than 0): ") ;
fscanf( stdin, "%lu", &num_elements) ;
/* Check for memory leak */
if (num_elements == 0){
fprintf(stderr, "Must be greater than 0\n") ;
exit(-1);
}
/* 1c - Call the memory allocation function in main */
/* Lets use the memory as an arrray */
int_dyn_arr[0] = 1;
factorial = 2;
for (iterator = 1; iterator < num_elements; ++iterator){
int_dyn_arr[iterator] = factorial * int_dyn_arr[iterator-1] ;
++factorial;
}
/* 2c - Print the memory addresses and data */
/* 3c - Free the memory */
return 0;
}
/* Step 1b - Allocate the memory function definition */
/* Step 2b - Print the memory function definition */
/* Step 3b - Free the Memory function definition */
|
C
|
/*
|
|
II | I
|
------------------------->
|
III | IV
|
|
Программа показывает в какой четверти
находятся точки х,у*/
#include <stdio.h>
#include <iso646.h>
int main(int argc, char* argv[]){
float x,y;
printf("Введите х,у:\n");
scanf("%d%d",&x,&y);
if(y>0 and x>0)
printf("В первой части.\n");
else if(y>0 and x<0)
printf("Во второй части.\n");
else if(y<0 and x<0)
printf("В третий части.\n");
else if(y<0 and x>0)
printf("В четвертой части.\n");
else
printf("Точки на одной оси.\n");
}
|
C
|
#include "monty.h"
/**
* addnode - add node to head of list
* @stack: head
* @opcode: opcode push and value
* @line_number: line number
*
* Return: pointer to head
*/
stack_t *addnode(char *opcode, stack_t **stack, unsigned int line_number)
{
stack_t *newnode;
char contents[1020];
int i;
if (strcmp(opcode, "push -\0") == 0 || strcmp(opcode, "push -\n") == 0)
free_for_exit_push(line_number, *stack);
newnode = malloc(sizeof(stack_t));
if (newnode == NULL)
{
fprintf(stderr, "Error: malloc failed\n");
return (NULL);
}
for (i = 0; opcode[i + 5] != '\0'; i++)
{
if (_isdigit(opcode[i + 5]) || opcode[i + 5] == '-')
contents[i] = opcode[i + 5];
else
{
free(newnode);
free_for_exit_push(line_number, *stack);
}
}
contents[i] = '\0';
newnode->n = atoi(contents);
newnode->prev = NULL;
if ((*stack) == NULL)
{
newnode->next = NULL;
(*stack) = newnode;
}
else
{
newnode->next = (*stack);
(*stack)->prev = newnode;
(*stack) = newnode;
}
return (*stack);
}
|
C
|
#include <stdio.h>
int main() {
printf("integer 123456789 = %d (Too long will be automatically converted into long)\n", 123456789);
printf("long integer 123456789L = %d\n", 123456789L);
printf("unsigned integer 11U = %d\n", 11U);
printf("unsigned integer 11u = %d\n", 11u);
printf("unsigned integer 88888888ul = %d\n", 88888888ul);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
// Represents a node
typedef struct node
{
int number;
struct node *next;
}
node;
int main(void)
{
// List of size 0, initially not pointing to anything
node *list = NULL;
// Add number to list
node *n = malloc(sizeof(node));
if (n == NULL)
{
return 1;
}
n->number = 1;
n->next = NULL;
// We create our first node, store the value 1 in it, and leave the next
// pointer to point to nothing. Then, our list variable can point to it.
list = n;
// Add number to list
n = malloc(sizeof(node));
if (n == NULL)
{
return 1;
}
n->number = 2;
n->next = NULL;
// Now, we go our first node that list points to, and sets the next pointer
// on it to point to our new node, adding it to the end of the list:
list->next = n;
// Add number to list
n = malloc(sizeof(node));
if (n == NULL)
{
return 1;
}
n->number = 3;
n->next = NULL;
// We can follow multiple nodes with this syntax, using the next pointer
// over and over, to add our third new node to the end of the list:
list->next->next = n;
// Normally, though, we would want a loop and a temporary variable to add
// a new node to our list.
// Print list
// Here we can iterate over all the nodes in our list with a temporary
// variable. First, we have a temporary pointer, tmp, that points to the
// list. Then, our condition for continuing is that tmp is not NULL, and
// finally, we update tmp to the next pointer of itself.
for (node *tmp = list; tmp != NULL; tmp = tmp->next)
{
// Within the node, we'll just print the number stored:
printf("%i\n", tmp->number);
}
// Free list
// Since we're freeing each node as we go along, we'll use a while loop
// and follow each node's next pointer before freeing it, but we'll see
// this in more detail in Problem Set 5.
while (list != NULL)
{
node *tmp = list->next;
free(list);
list = tmp;
}
}
|
C
|
#include "20162004.h" // my header
// global variables
unsigned char MEMORY[MEGA] = "";
struct opcodeNode* HASHTABLE[HASHSIZE]; // Operation Code Table
struct symbolNode* SYMTAB[SYMHASHSIZE]; // Symbol Table
int SYMTABCOUNT = 0; // keeps count of entries added to SYMTAB
int main(void){
char command[MAXBUF] = ""; // input buffer
char **args; // will point to input arguments
int status = 0; // keeps track of correct/incorrect arguments from input
if(!(status = opInsert())) printf("failed to read opcode.txt");
// main loop
do{
printf("sicsim> ");
getInput(command);
args = parseInput(command, &status);
if(args) status = runCommand(args, status);
// only adds to history if the command is correct
if(status == 1){
addHistory(command);
}
if(args) freeArguments(args);
}while(status);
freeHistory();
freeHashtable();
initializeASM(0);
resetESTAB();
llClearBP(0);
return 1;
}
int runCommand(char **args, int n){
int status = -2;
// n is amount of arguments in args
if(n > 0){
if(!(strcmp(args[0], "dump")) || !(strcmp(args[0], "du"))){
status = memDump(args, n);
}
else if(!(strcmp(args[0], "e")) || !(strcmp(args[0], "edit"))){
status = memEdit(args, n);
}
else if(!(strcmp(args[0], "f")) || !(strcmp(args[0], "fill"))){
status = memFill(args, n);
}
else if(n == 2 && !(strcmp(args[0], "opcode"))){
status = opMnem(args);
}
else if(n == 2 && !(strcmp(args[0], "type"))){
status = funcType(args[1]);
}
else if(n == 2 && !(strcmp(args[0], "assemble"))){
status = asmAssemble(args[1]);
}
else if((n == 2 || n == 1) && !(strcmp(args[0], "progaddr"))){
if(n == 2) status = llSetProgaddr(args[1]);
if(n == 1) status = llSetProgaddr("0");
}
else if(n >= 2 && !(strcmp(args[0], "loader"))){
status = llLoadProgram(args, n);
}
else if(n <= 2 && !(strcmp(args[0], "bp"))){
status = llBreakPoint(args, n);
}
// commands that should only take 1 argument
else if(args[1] == NULL){
if(!(strcmp(args[0], "help")) || !(strcmp(args[0], "h")))
status = funcHelp();
else if(!(strcmp(args[0], "dir")) || !(strcmp(args[0], "d")))
status = funcDir();
else if(!(strcmp(args[0], "quit")) || !(strcmp(args[0], "q")))
status = funcQuit();
else if(!(strcmp(args[0], "history")) || !(strcmp(args[0], "hi"))){
status = funcHistory(args[0]);
}
else if(!(strcmp(args[0], "opcodelist"))) status = opPrintOpcodelist();
else if(!(strcmp(args[0], "reset"))) status = memReset();
else if(!(strcmp(args[0], "symbol"))) status = asmPrintSymTab();
else if(!(strcmp(args[0], "run"))) status = llRun();
else status = -1;
}
// if no match
else status = -1;
}
if(n < 0){
printError(n);
status = n;
}
else if(status < 0) printError(status);
return status;
}
|
C
|
#include <stdio.h>
#include <math.h>
struct coordenada
{
float x, y, z;
};
struct ortoedro
{
struct coordenada vertice1, vertice2;
} orto;
void main()
{
float delta1, delta2, delta3, volumen;
/* Ingresando las coordenadas de vertice1 */
printf("\nIngrese la primera coordenada de vertice1: ");
scanf("%f", &orto.vertice1.x);
printf("Ingrese la segunda coordenada de vertice1: ");
scanf("%f", &orto.vertice1.y);
printf("Ingrese la tercera coordenada de vertice1: ");
scanf("%f", &orto.vertice1.z);
/* Ingresando las coordenadas de vertice2 */
printf("\nIngrese la primera coordenada de vertice2: ");
scanf("%f", &orto.vertice2.x);
printf("Ingrese la segunda coordenada de vertice2: ");
scanf("%f", &orto.vertice2.y);
printf("Ingrese la tercera coordenada de vertice2: ");
scanf("%f", &orto.vertice2.z);
/* Calculando y mostrando el volumen de orto */
delta1 = fabs(orto.vertice1.x - orto.vertice2.x);
delta2 = fabs(orto.vertice1.y - orto.vertice2.y);
delta3 = fabs(orto.vertice1.z - orto.vertice2.z);
volumen = delta1*delta2*delta3;
printf("\n\n El volumen es de %f unidades.\n\n", volumen);
/* mostrando los vertices de orto */
printf("======== Imprimiendo los vertices");
printf(" de orto =========\n\n");
printf(" (%f,%f,%f)\n", orto.vertice1.x, orto.vertice1.y, orto.vertice1.z);
printf(" (%f,%f,%f)\n", orto.vertice1.x, orto.vertice1.y, orto.vertice2.z);
printf(" (%f,%f,%f)\n", orto.vertice1.x, orto.vertice2.y, orto.vertice1.z);
printf(" (%f,%f,%f)\n", orto.vertice1.x, orto.vertice2.y, orto.vertice2.z);
printf(" (%f,%f,%f)\n", orto.vertice2.x, orto.vertice1.y, orto.vertice1.z);
printf(" (%f,%f,%f)\n", orto.vertice2.x, orto.vertice1.y, orto.vertice2.z);
printf(" (%f,%f,%f)\n", orto.vertice2.x, orto.vertice2.y, orto.vertice1.z);
printf(" (%f,%f,%f)\n\n", orto.vertice2.x, orto.vertice2.y, orto.vertice2.z);
}
|
C
|
#include <stdio.h>
#define N 30
#define I 5
void print_Matrix(char arr[I][N]);
void InsertMatrix(char arr[I][N]);
int main() {
char arr[N][N];
InsertMatrix(arr);
print_Matrix(arr);
return 0;
}
void InsertMatrix(char arr[I][N]) { //Set Value on the 2D array
printf("Enter your names:\n");
for (int i = 0; i < I; i++) {
scanf("%s", &arr[i]);
}
}
void print_Matrix(char arr[I][N]) { //print_matrix
printf("\nThe final 2D array is:\n");
for (int i = 0; i < I; i++) {
for (int j = 0; j < N; j++) {
if (arr[i][j] == '\0') {// if its the end of the string so print \n and then break
printf("\n");
break;
}
else {
printf("%c", arr[i][j]);
}
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.