language
large_stringclasses 1
value | text
stringlengths 9
2.95M
|
---|---|
C
|
#include <stdbool.h>
#include <stdint.h>
#include <stddef.h>
#pragma once
#define MAX_MICROPHONES 8
struct AudioStream;
struct SoundData;
typedef struct Source Source;
typedef struct Microphone Microphone;
typedef enum {
SOURCE_STATIC,
SOURCE_STREAM
} SourceType;
typedef enum {
UNIT_SECONDS,
UNIT_SAMPLES
} TimeUnit;
bool lovrAudioInit(void);
void lovrAudioDestroy(void);
void lovrAudioUpdate(void);
void lovrAudioAdd(struct Source* source);
void lovrAudioGetDopplerEffect(float* factor, float* speedOfSound);
void lovrAudioGetMicrophoneNames(const char* names[MAX_MICROPHONES], uint32_t* count);
void lovrAudioGetOrientation(float* orientation);
void lovrAudioGetPosition(float* position);
void lovrAudioGetVelocity(float* velocity);
float lovrAudioGetVolume(void);
bool lovrAudioHas(struct Source* source);
bool lovrAudioIsSpatialized(void);
void lovrAudioPause(void);
void lovrAudioSetDopplerEffect(float factor, float speedOfSound);
void lovrAudioSetOrientation(float* orientation);
void lovrAudioSetPosition(float* position);
void lovrAudioSetVelocity(float* velocity);
void lovrAudioSetVolume(float volume);
void lovrAudioStop(void);
Source* lovrSourceCreateStatic(struct SoundData* soundData);
Source* lovrSourceCreateStream(struct AudioStream* stream);
void lovrSourceDestroy(void* ref);
SourceType lovrSourceGetType(Source* source);
uint32_t lovrSourceGetBitDepth(Source* source);
uint32_t lovrSourceGetChannelCount(Source* source);
void lovrSourceGetCone(Source* source, float* innerAngle, float* outerAngle, float* outerGain);
void lovrSourceGetOrientation(Source* source, float* orientation);
size_t lovrSourceGetDuration(Source* source);
void lovrSourceGetFalloff(Source* source, float* reference, float* max, float* rolloff);
float lovrSourceGetPitch(Source* source);
void lovrSourceGetPosition(Source* source, float* position);
void lovrSourceGetVelocity(Source* source, float* velocity);
uint32_t lovrSourceGetSampleRate(Source* source);
float lovrSourceGetVolume(Source* source);
void lovrSourceGetVolumeLimits(Source* source, float* min, float* max);
bool lovrSourceIsLooping(Source* source);
bool lovrSourceIsPlaying(Source* source);
bool lovrSourceIsRelative(Source* source);
void lovrSourcePause(Source* source);
void lovrSourcePlay(Source* source);
void lovrSourceSeek(Source* source, size_t sample);
void lovrSourceSetCone(Source* source, float inner, float outer, float outerGain);
void lovrSourceSetOrientation(Source* source, float* orientation);
void lovrSourceSetFalloff(Source* source, float reference, float max, float rolloff);
void lovrSourceSetLooping(Source* source, bool isLooping);
void lovrSourceSetPitch(Source* source, float pitch);
void lovrSourceSetPosition(Source* source, float* position);
void lovrSourceSetRelative(Source* source, bool isRelative);
void lovrSourceSetVelocity(Source* source, float* velocity);
void lovrSourceSetVolume(Source* source, float volume);
void lovrSourceSetVolumeLimits(Source* source, float min, float max);
void lovrSourceStop(Source* source);
void lovrSourceStream(Source* source, uint32_t* buffers, size_t count);
size_t lovrSourceTell(Source* source);
Microphone* lovrMicrophoneCreate(const char* name, size_t samples, uint32_t sampleRate, uint32_t bitDepth, uint32_t channelCount);
void lovrMicrophoneDestroy(void* ref);
uint32_t lovrMicrophoneGetBitDepth(Microphone* microphone);
uint32_t lovrMicrophoneGetChannelCount(Microphone* microphone);
struct SoundData* lovrMicrophoneGetData(Microphone* microphone, size_t samples, struct SoundData* soundData, size_t offset);
const char* lovrMicrophoneGetName(Microphone* microphone);
size_t lovrMicrophoneGetSampleCount(Microphone* microphone);
uint32_t lovrMicrophoneGetSampleRate(Microphone* microphone);
bool lovrMicrophoneIsRecording(Microphone* microphone);
void lovrMicrophoneStartRecording(Microphone* microphone);
void lovrMicrophoneStopRecording(Microphone* microphone);
|
C
|
// General bit utilities
#define sbi(PORT, bit) (PORT|=(1<<bit)) // set bit in PORT
#define cbi(PORT, bit) (PORT&=~(1<<bit)) // clear bit in PORT
#define tgl(PORT, bit) (PORT^=(1<<bit)) // toggle bit in PORT
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include "indexes.h"
char** createText(char* fileName, int* totalLines){
char aux; //Variável auxiliar de leitura. Lê '\n' e garante a mudança de linha do ponteiro do arquivo.
int lineNumber;
/*Inicialização do Arquivo de Entrada*/
FILE* input = fopen(fileName, "r");
while(input == NULL){
printf("Arquivo %s inexistente. Entre com o nome correto.\n", fileName);
scanf("%s", fileName);
input = fopen(fileName, "r");
}
/*Contagem do número de linhas do arquivo de entrada.*/
while(!feof(input)){
aux = fgetc(input);
if(aux == '\n'){
*totalLines = *totalLines + 1;
}
}
/*Volta o ponteiro ao início do arquivo de entrada.*/
rewind(input);
char** txt = (char**)malloc(*totalLines * sizeof(char*));
for(lineNumber = 0; lineNumber < *totalLines; lineNumber++){
txt[lineNumber] = (char*)calloc(1, X * sizeof(char) + 1); //As linhas possuem X (constante) caracteres.
fscanf(input, "%[^\n]s", txt[lineNumber]); //Lê uma linha completa.
fscanf(input, "%c", &aux); //Lê '\n'
}
fclose(input);
return txt;
}
void destroyText(char** txt, int totalLines){
int i;
for(i = 0; i < totalLines; i++){
free(txt[i]);
}
free(txt);
}
void saveText(char* fileName, char** txt, int totalLines){
int lineNumber;
/*Inicialização do Arquivo de Saida*/
FILE* output = fopen(fileName, "w");
while(output == NULL){
printf("Arquivo %s inexistente. Entre com o nome correto.\n", fileName);
scanf("%s", fileName);
output = fopen(fileName, "w");
}
for(lineNumber = 0; lineNumber < totalLines; lineNumber++){
fprintf(output, "%s\n", txt[lineNumber]);
}
fclose(output);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define MAX (int)1e4
void generateRandomInput(int n, int input[]) {
for(int i = 0; i<n; i++)
input[i] = rand()%MAX;
}
void generateSortedInput(int n, int input[]) {
for(int i = 0; i<n; i++)
input[i] = i;
}
int main() {
srand(time(0));
int n;
printf("Enter size of input > ");
scanf("%d", &n);
int input[n];
int k;
printf("\n");
printf("1. Randomly Generated\n");
printf("2. Already Sorted\n");
printf("Enter type of input 1/2 > ");
scanf("%d", &k);
switch(k) {
case 1:
generateRandomInput(n, input);
break;
case 2:
generateSortedInput(n, input);
break;
default:
printf("Incorrect option\n");
return 0;
break;
}
FILE *inputFile = fopen("input.txt", "w");
if (inputFile != NULL) {
printf("Input File Generation Successfull !\n");
}
else {
printf("Input File Generation Failed.\n");
return -1;
}
fprintf(inputFile, "%d\n", n);
for(int i = 0; i<n; i++) fprintf(inputFile, "%d ", input[i]);
fclose(inputFile);
return 0;
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* swap.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: dhyeon <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/05/16 04:16:12 by dhyeon #+# #+# */
/* Updated: 2021/05/21 15:32:47 by dhyeon ### ########.fr */
/* */
/* ************************************************************************** */
#include "push_swap.h"
int sa(t_info *info)
{
int tmp;
if (info->a->size > 1)
{
tmp = info->a->top->num;
info->a->top->num = info->a->top->next->num;
info->a->top->next->num = tmp;
tmp = info->a->top->rank;
info->a->top->rank = info->a->top->next->rank;
info->a->top->next->rank = tmp;
info->count++;
return (1);
}
return (0);
}
int sb(t_info *info)
{
int tmp;
if (info->b->size > 1)
{
tmp = info->b->top->num;
info->b->top->num = info->b->top->next->num;
info->b->top->next->num = tmp;
tmp = info->b->top->rank;
info->b->top->rank = info->b->top->next->rank;
info->b->top->next->rank = tmp;
info->count++;
return (1);
}
return (0);
}
int ss(t_info *info)
{
if (sa(info) && sb(info))
{
info->count--;
return (1);
}
return (0);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include "stack.h"
#define PRINT_STACK_STATUS(ps) \
printf("empty: %d full: %d\n", stack_empty(ps), stack_full(ps))
int main()
{
int i;
struct stack *ps = stack_init(10);
PRINT_STACK_STATUS(ps);
for(i=0; i<10; i++){
stack_push(ps, &i);
PRINT_STACK_STATUS(ps);
}
for(i=0; i<10; i++){
printf("%d\n", *stack_top(ps));
stack_pop(ps);
PRINT_STACK_STATUS(ps);
}
stack_destroy(ps);
return 0;
}
|
C
|
/** \file */
#ifndef __BML_MULTIPLY_H
#define __BML_MULTIPLY_H
#include "bml_types.h"
// Multiply - C = alpha * A * B + beta * C
void bml_multiply(
const bml_matrix_t * A,
const bml_matrix_t * B,
bml_matrix_t * C,
const double alpha,
const double beta,
const double threshold);
// Multiply X^2 - X2 = X * X
void bml_multiply_x2(
const bml_matrix_t * X,
bml_matrix_t * X2,
const double threshold);
// Multiply - C = A * B
void bml_multiply_AB(
const bml_matrix_t * A,
const bml_matrix_t * B,
bml_matrix_t * C,
const double threshold);
// Multiply with threshold adjustment - C = A * B
void bml_multiply_adjust_AB(
const bml_matrix_t * A,
const bml_matrix_t * B,
bml_matrix_t * C,
const double threshold);
#endif
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
/*Her opretter vi de forskellige funktioner som vi kommer til at bruge*/
double diskriminanten(double, double, double);
double matRod1(double, double, double);
double matRod2(double, double, double);
void SolveQuadraticEquation(double, double, double);
int main(void)
{
double a, b, c;
/*her opretter vi et punkt som vi kan g tilbage til hvis vi har brug for det*/
start:
/* her bedes vores bruger indtaste de forskellige vrdier af deres andengradslinje*/
printf("indtast din a vrdi: ");
scanf("%lf", &a);
printf("\nindtast din b vrdi: ");
scanf("%lf", &b);
printf("\nindtast din c vrdi: ");
scanf("%lf", &c);
/*Eftersom a ikke m vre 0 i en andengradslining, tjekker vi det her fr vi gr vidre */
if (a == 0)
{
/* hvis a er 0, gives der en bedsked at det m den ikke vre,
og her efter bruger vi goto til at komme tilbage til den linje hvor vi havde skrevet start p
*/
printf("\na m ikke vre 0");
goto start;
}
else
{
/*hvis alt s stemmer overens s gr vi ned til vores funktion som regner alt matematiken ud*/
SolveQuadraticEquation(a,b,c);
}
return 0;
}
void SolveQuadraticEquation(double a, double b, double c)
{
double d, root1, root2;
/* her finder vi frest ud af hvad om dikriminanten er*/
d = diskriminanten(a, b, c);
printf("\ndiskriminanten er %lf\n", d);
/*hvis den er under 0 ved vi at der ikke er nogen rodder til den,
og dette vil s blive sagt til brugen*/
if (d < 0)
{
printf("Intet at finde her, din rod er i et andet slot\n");
}
/*hvis den er lig 0 s ved vi der kun er en rod*/
else if (d == 0)
{
/*her kalder man s funktion til at regner roden ud og s printer vi svaret til brugen*/
root1 = matRod1(a,b, d);
printf("Der er en rod som er %f\n", root1);
}
/*ellers ved vi der er to lsninger*/
else
{
/*her kalder man s funktion til at regner roderne ud og s printer vi svaret til brugen*/
root1 = matRod1(a,b, d);
root2 = matRod2(a,b, d);
printf("Der er to rod som er %f og %f\n", root1, root2);
}
}
double diskriminanten(double a, double b, double c){
return ((b)*(b)) - 4 *(a)*(c);
}
double matRod1(double a, double b, double d){
return(-(b) + sqrt(d)) / 2*(a);
}
double matRod2(double a, double b, double d){
return(-(b) - sqrt(d)) / 2*(a);
}
|
C
|
#ifndef _CPU_IDT_H_
#define _CPU_IDT_H_
#include <cpu/types.h>
/* Segment Selectors */
#define KERNEL_CS 0x08
typedef struct IDT_Gate
{
u16 low_offset; /* Lower 16 bits of handler function address */
u16 sel; /* Kernel segment selector */
u8 always0;
/* First byte
Bit 7 : "Interrupt is present"
Bits 6-5: Privilege level of call (0=kernel..3=user)
Bit 4 : Set to 0 for interrupt gates
Bits 3-0: bits 1110 = decimal 14 = "32 bi interrupt gate" */
u8 flags;
u16 high_offset; /* Higher 16 bits of handler function address */
} __attribute((packed)) IDT_Gate;
/* A pointer to the array of interrupt handlers.
* Assembly instruction 'lidt; will read it */
typedef struct IDT_Register
{
u16 limit;
u32 base;
} __attribute__((packed)) IDT_Register;
#define IDT_ENTRIES 256
static IDT_Gate idt[IDT_ENTRIES];
static IDT_Register idt_reg;
void set_idt_gate(int n, u32 handler);
void set_idt();
#endif
|
C
|
#include<stdio.h>
int main(){
int a,b;
char c;
scanf("%d%c%d",&a,&c,&b);
if(c=='+'){
printf("%d",a+b);
}
else if(c=='-')
printf("%d",a-b);
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char *inputString(FILE* fp) {
char *str;
int ch;
size_t size = 16;
size_t len = 0;
str = realloc(NULL, sizeof(char) * size);
if (!str)
return str;
while (EOF != (ch = fgetc(fp)) && ch != '\n') {
str[len++] = ch;
if (len == size) {
str = realloc(str, sizeof(char) * (size += 16));
if (!str)
return str;
}
}
str[len++] = '\0';
return realloc(str, sizeof(char) * len);
}
int main() {
FILE *file1 = fopen("file", "r");
FILE *file2 = fopen("file", "r");
if (file1 != NULL && file2 != NULL) {
char * str1;
char * str2;
char flag = 0;
char nn;
str1 = inputString(file1);
while (str1 != EOF) {
str2 = inputString(file2);
while (str2 != EOF) {
if (!strcmp(str1, str2)) {
flag++;
if (flag == 2) {
break;
}
}
free(str2);
nn = fgetc(file2);
if (nn == EOF) {
str2 = nn;
}
else {
str2 = inputString(file2);
}
}
if (flag == 2) {
fclose(file2);
fopen("file", "r");
}
else {
printf("%s\n", str1);
free(str1);
break;
}
nn = fgetc(file1);
flag = 0;
if (nn == EOF) {
str1 = nn;
}
else {
str1 = inputString(file1);
}
}
fclose(file1);
fclose(file2);
}
else {
printf("Couldn't open file\n");
}
return 0;
}
|
C
|
#include "List.h"
/*
Init List
*/
void kInitializeList(LIST* pstList)
{
pstList->iItemCount = 0;
pstList->pvHeader = NULL;
pstList->pvTail = NULL;
}
/*
Return List count
*/
int kGetListCount(const LIST* pstList)
{
return pstList->iItemCount;
}
/*
Add List to Tail
*/
void kAddListToTail(LIST* pstList, void* pvItem)
{
LISTLINK* pstLink;
pstLink = (LISTLINK*)pvItem;
pstLink->pvNext = NULL;
// empty list
if (pstList->pvHeader == NULL) {
pstList->pvHeader = pvItem;
pstList->pvTail = pvItem;
pstList->iItemCount = 1;
return;
}
// else add to tail
pstLink = (LISTLINK*)pstList->pvTail;
pstLink->pvNext = pvItem;
pstList->pvTail = pvItem;
pstList->iItemCount++;
}
/*
Add List to Header
*/
void kAddListToHeader(LIST* pstList, void* pvItem)
{
LISTLINK* pstLink;
pstLink = (LISTLINK*)pvItem;
pstLink->pvNext = pstList->pvHeader;
// empty list
if (pstList->pvHeader == NULL) {
pstList->pvHeader = pvItem;
pstList->pvTail = pvItem;
pstList->iItemCount = 1;
return;
}
pstList->pvHeader = pvItem;
pstList->iItemCount++;
}
/*
Remove List
*/
void* kRemoveList(LIST* pstList, QWORD qwID)
{
LISTLINK* pstLink;
LISTLINK* pstPreviousLink;
pstPreviousLink = (LISTLINK*)pstList->pvHeader;
for (pstLink = pstPreviousLink; pstLink != NULL; pstLink = pstLink->pvNext) {
if (pstLink->qwID == qwID) {
// only node
if ((pstLink == pstList->pvHeader) &&
(pstLink == pstList->pvTail)) {
pstList->pvHeader = NULL;
pstList->pvTail = NULL;
}
// if first node
else if (pstLink == pstList->pvHeader) {
pstList->pvHeader = pstLink->pvNext;
}
// if last node
else if (pstLink == pstList->pvTail) {
pstList->pvTail = pstPreviousLink;
}
// middle
else {
pstPreviousLink->pvNext = pstLink->pvNext;
}
pstList->iItemCount--;
return pstLink;
}
// goto next node
pstPreviousLink = pstLink;
}
// not found
return NULL;
}
/*
Remove List From Header
*/
void* kRemoveListFromHeader(LIST* pstList)
{
LISTLINK* pstLink;
// nothing
if (pstList->iItemCount == 0) {
return NULL;
}
// remove header and return
pstLink = (LISTLINK*)pstList->pvHeader;
return kRemoveList(pstList, pstLink->qwID);
}
/*
Remove List From Tail
*/
void* kRemoveListFromTail(LIST* pstList)
{
LISTLINK* pstLink;
// nothing
if (pstList->iItemCount == 0) {
return NULL;
}
// remove tail and return
pstLink = (LISTLINK*)pstList->pvTail;
return kRemoveList(pstList, pstLink->qwID);
}
/*
Find List
*/
void* kFindList(const LIST* pstList, QWORD qwID)
{
LISTLINK* pstLink;
for (pstLink = (LISTLINK*)pstList->pvHeader; pstLink != NULL; pstLink = pstLink->pvNext) {
if (pstLink->qwID == qwID) {
return pstLink;
}
}
return NULL;
}
/*
Get Header
*/
void* kGetHeaderFromList(const LIST* pstList)
{
return pstList->pvHeader;
}
/*
Get Tail
*/
void* kGetTailFromList(const LIST* pstList)
{
return pstList->pvTail;
}
/*
Get Next
*/
void* kGetNextFromList(const LIST* pstList, void* pstCurrent)
{
LISTLINK* pstLink;
pstLink = (LISTLINK*)pstCurrent;
return pstLink->pvNext;
}
|
C
|
#include "p18cxxx.h"
#include "HardwareConfig.h"
#if defined (__PIC18F4520__)
#include <pic18f4520.h>
#endif
#if defined (__PIC18F4620__)
#include <p18f4620.h>
#endif
#include "uart.h"
void UARTInit(void)
{
// Procedimiento que inicializa la comunicacion serie
// Inicializamos la comunicacion con una velocidad de 9600 bps
// para ello asignamos un Baud rate de alta velocidad
// y cargamos el registro SPBRG con 25 en decimal
SPBRG = 25;
// Configuramos los pines de salida
TRISCbits.TRISC6 = 1;
TRISCbits.TRISC7 = 1;
// Comenzamos con la configuracion de la transmicion
// modificando el registro de estado de la transmicion TXSTA
TXSTA = 0b00100100;
// Configuramos una comunicacion asincronica de 8 bits
// en alta velocidad
// Configuramos un generador de baudios de 8 bits
BAUDCONbits.BRG16 = 0;
RCSTAbits.SPEN = 1; // Habilitamos el Port Serial
}
void UARTPutChar(char Dato)
{ // esta funcion envia caracteres por el puerto serie
PIR1bits.TXIF = 0; // Borramos flag de transmision
TXREG = Dato; // Enviamos dato
while(TXSTAbits.TRMT == 0); // esperamos a que se termine
// la transmicion
}
void UART_String(char * _string){
while(*_string!=0x00)UARTPutChar(*_string++);
}
|
C
|
#include <stdio.h>
int main(){
int a=0,b=0,c=0,d=0;
printf("Input a 3-digit integer: ");
scanf("%d", &a);
b = (a/100) % 10;
c = (a/10) % 10;
d = a % 10;
printf("%d is composed of [%d,%d,%d]\n",a,b,c,d);
return 0;
}
|
C
|
#define NULL ((void*)0)
typedef unsigned long size_t; // Customize by platform.
typedef long intptr_t; typedef unsigned long uintptr_t;
typedef long scalar_t__; // Either arithmetic or pointer type.
/* By default, we understand bool (as a convenience). */
typedef int bool;
#define false 0
#define true 1
/* Forward declarations */
typedef struct TYPE_2__ TYPE_1__ ;
/* Type definitions */
typedef int /*<<< orphan*/ u32 ;
struct tg3_firmware_hdr {int /*<<< orphan*/ len; } ;
struct tg3 {int fw_len; TYPE_1__* fw; } ;
struct TYPE_2__ {int size; } ;
/* Variables and functions */
int TG3_FW_HDR_LEN ;
int be32_to_cpu (int /*<<< orphan*/ ) ;
__attribute__((used)) static int tg3_fw_data_len(struct tg3 *tp,
const struct tg3_firmware_hdr *fw_hdr)
{
int fw_len;
/* Non fragmented firmware have one firmware header followed by a
* contiguous chunk of data to be written. The length field in that
* header is not the length of data to be written but the complete
* length of the bss. The data length is determined based on
* tp->fw->size minus headers.
*
* Fragmented firmware have a main header followed by multiple
* fragments. Each fragment is identical to non fragmented firmware
* with a firmware header followed by a contiguous chunk of data. In
* the main header, the length field is unused and set to 0xffffffff.
* In each fragment header the length is the entire size of that
* fragment i.e. fragment data + header length. Data length is
* therefore length field in the header minus TG3_FW_HDR_LEN.
*/
if (tp->fw_len == 0xffffffff)
fw_len = be32_to_cpu(fw_hdr->len);
else
fw_len = tp->fw->size;
return (fw_len - TG3_FW_HDR_LEN) / sizeof(u32);
}
|
C
|
#include <stdio.h>
int main()
{
long white_c, other_c, total_c;
white_c = other_c, total_c = 0;
char c;
long num_c_bucket[10];
for (int i = 0; i <= 9; i++)
num_c_bucket[i] = 0;
// input loop
while ((c = getchar()) != EOF) {
total_c++;
if (c >= '0' && c <= '9')
num_c_bucket[c - '0']++;
else if (c == ' ' || c == '\t' || c == '\n')
white_c++;
else
other_c++;
}
printf("\n#################Input char statistic show as below###############\n");
printf("white spaces: ");
for (; white_c > 0; white_c--)
printf("#");
printf("\n");
printf("other characters input: ");
for (; other_c > 0; other_c--)
printf("#");
printf("\n");
printf("\n");
printf("---------And numeric chars statistic show as below-----------------\n");
for (int i = 0; i <= 9; i++) {
printf("Number %d input: ", i);
for (; num_c_bucket[i] > 0; num_c_bucket[i]--)
printf("#");
printf("\n");
}
}
|
C
|
#include <nds.h>
#include <nds/memory.h>
#include <unistd.h> //sbrk()
//coto: small memory handler given POSIX LIBNDS memory allocation is broken when different MPU mapping is in use.
#include "mem_handler.h"
//at start 0
__attribute__((section(".dtcm"))) u32 * this_heap_ptr = 0;
__attribute__((section(".dtcm"))) int free_allocable_mem = 0;
int calc_remaining_kernel_mem(){
return (int)( (u32)this_heap_ptr - ((u32)&__end__) );
}
u32 * sbrk_init(){
return (u32*)sbrk(0);
}
u32 * sbrk_alloc(int size){
this_heap_ptr = (u32*)sbrk(size); // + allocs / - frees
free_allocable_mem = calc_remaining_kernel_mem();
DC_FlushRange((u32*)this_heap_ptr,size);
return this_heap_ptr;
}
u32 * sbrk_dealloc(int size){
this_heap_ptr = (u32*)sbrk(-size); // + allocs / - frees
free_allocable_mem = calc_remaining_kernel_mem();
DC_FlushRange((u32*)(this_heap_ptr-size),size);
return this_heap_ptr;
}
|
C
|
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
};
struct qnode {
int layer;
struct TreeNode *tree_node;
struct qnode *next;
};
#include <stdlib.h>
#define STEP 8
int *rightSideView(struct TreeNode *root, int *n)
{
int nr, *buf, bufsz;
struct qnode *head, *tail;
struct qnode *tmp;
if (!root) {
*n = 0;
return NULL;
}
nr = 0;
bufsz = STEP;
buf = malloc(bufsz * sizeof(int));
/* put tree root into queue */
head = tail = malloc(sizeof(struct qnode));
head->tree_node = root;
head->layer = 0;
head->next = NULL;
/* while queue not empty */
while (head) {
tmp = head;
/* put sons into queue */
if (tmp->tree_node->left) {
tail->next = malloc(sizeof(struct qnode));
tail = tail->next;
tail->layer = tmp->layer + 1;
tail->tree_node = tmp->tree_node->left;
tail->next = NULL;
}
if (tmp->tree_node->right) {
tail->next = malloc(sizeof(struct qnode));
tail = tail->next;
tail->layer = tmp->layer + 1;
tail->tree_node = tmp->tree_node->right;
tail->next = NULL;
}
/* dequeue */
head = head->next;
if (!head)
tail = NULL;
if (!head || tmp->layer != head->layer) {
if (bufsz <= nr) {
bufsz += STEP;
buf = realloc(buf, bufsz * sizeof(int));
}
buf[nr++] = tmp->tree_node->val;
}
free(tmp);
}
*n = nr;
return buf;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <arpa/inet.h>
#include <time.h>
#define exit_on_error(msg) \
do { perror(msg); exit(EXIT_FAILURE); } while(0)
#define nexit_on_error(r, msg) \
do { errno = r; perror(msg); exit(EXIT_FAILURE); } while(0)
#define scast(x) (struct sockaddr*)x
int main(int argc, char const *argv[])
{
if(argc<3){
fprintf(stderr, "%s <host address> <port>\n", argv[0]);
exit(EXIT_FAILURE);
}
int port = atoi(argv[2]);
int fd = socket(PF_INET, SOCK_DGRAM, 0);
struct sockaddr_in fAdd = { .sin_family = AF_INET, .sin_port = htons(port) };
memset(fAdd.sin_zero, 0, 8);
int rt = inet_aton(argv[1], &fAdd.sin_addr);
if(rt==0){
fprintf(stderr, "Invalid address\n");
exit(EXIT_FAILURE);
}
time_t t;
int sz = sizeof(struct sockaddr_in);
ssize_t r;
if(connect(fd, scast(&fAdd), sz)==-1) exit_on_error("connect");
puts("YES");
r = send(fd, "RUN", 4, 0);
if(r==-1) exit_on_error("send");
r = recv(fd, &t, sizeof t, 0);
if(r==-1) exit_on_error("recv");
printf("Time: %s", ctime(&t));
return 0;
}
/* In case of UDP protocol, if you use connect no handshake will be performed but it will enable you to use recv and
send directly without specifying the address each time */
|
C
|
#include<stdio.h>
int main(){
float n=0;
while(scanf("%f",&n)!=EOF){
n=n*1.8+32;
printf("%.1f\n",n);
}
return 0;
}
|
C
|
#include "bloom.h"
/* Create a new empty bloom filter */
BF BF_empty() {
BF b;
memset(b.filter, 0, _FILTER_SIZE);
return b;
}
/* Add more data to the filter */;
void BF_add(char *data, int size, BF *b, int print, int debug) {
uint32_t hash[_HASH_NUM+(4-(_HASH_NUM%4))];
for(int i = 0; i < _HASH_NUM; i+=4)
MurmurHash3_x64_128(data, size, i, &hash[i]);
for(int i = 0; i < _HASH_NUM; i++) {
int bit = hash[i]%(_FILTER_SIZE*8);
b->filter[bit/64] |= 1L<<(bit%64);
}
if(print) printf("ADD : %s has been added to the filter\n", data);
if(debug) {
printf("\nDEBUG INFO :\n");
BF_debug_hash(hash);
BF_debug_filter(*b);
printf("\n");
}
}
/* Filter requested data */
int BF_query(char *data, int size, BF b, int print) {
uint32_t hash[_HASH_NUM+(4-(_HASH_NUM%4))];
for(int i = 0; i < _HASH_NUM; i+=4)
MurmurHash3_x64_128(data, size, i, &hash[i]);
for(int i = 0; i < _HASH_NUM; i++) {
int bit = hash[i]%(_FILTER_SIZE*8);
if((b.filter[bit/64]&(1L<<(bit%64))) != (1L<<(bit%64))) {
if(print) printf("QUERY : %s is not in filter\n", data);
return 0;
}
}
if(print) printf("QUERY : %s is in filter\n", data);
return 1;
}
void BF_debug_hash(uint32_t *hash) {
for(int i = 0; i < _HASH_NUM; i++) {
int bit = hash[i]%(_FILTER_SIZE*8);
int line = bit/64;
int num = bit%64;
printf("Hash %d (%u)\t| Bit number %d on line %d of filter\n", i+1, hash[i], num, line);
}
}
void BF_debug_filter(BF b) {
printf("BEGIN FILTER\n");
for(int i = 0; i < _FILTER_SIZE/8; i++) {
printf("%d\t", i+1);
print_binary(b.filter[i]);
}
printf("END FILTER\n");
}
void print_binary(uint64_t num) {
for(int i = 63; i >= 0; i--) {
if(num >= pow(2.0,(double)i)) {
printf("1");
num -= pow(2.0,(double)i);
} else {
printf("0");
}
}
printf("\n");
}
|
C
|
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <errno.h>
#include <arpa/inet.h>
#define PORT 9877
#define MAXLINE 100
#define LISTENQ 10
int connect_num;
int connfd[LISTENQ];
char NAME[10][20];
void list(int n){
char tmp[] = {"User Online"};
send(connfd[n],tmp,sizeof(tmp),0);
int i;
for(i=0;i<LISTENQ;i++){
if(connfd[i]!=-1){
char msg[MAXLINE]={};
sprintf(msg,"%s",NAME[i]);
printf("%s\n",NAME[i]);
// strcat(msg,"\n");
printf("%s",msg);
send(connfd[n],msg,sizeof(msg),0);
}
}
char tmp2[MAXLINE]={};
sprintf(tmp2,"%s",NAME[n]);
strcat(tmp,">");
send(connfd[n],tmp2,strlen(tmp2),0);
}
void sendmsgall(char *msg,int n){
int i;
strcat(msg,"\n");
for(i=0;i<LISTENQ;i++){
if(connfd[i]!=-1 && i!=n){
send(connfd[i],msg,strlen(msg),0);
char tmp[MAXLINE] = {};
sprintf(tmp,"%s",NAME[i]);
strcat(tmp,">");
send(connfd[i],tmp,strlen(tmp),0);
}
}
}
void* service_thread(void* data){
int n = *((int *) data);
char buf[MAXLINE];
memset(buf,0,sizeof(buf));
recv(connfd[n],buf,sizeof(buf),0);
sprintf(NAME[connect_num++],"%s",buf);
printf("client %s connected\n",buf);
while(1){
memset(buf,0,sizeof(buf));
if(recv(connfd[n],buf,sizeof(buf),0)<=0){
int i;
for(i=0;i<LISTENQ;i++){
if(i==n){
printf("client %d exit\n",connfd[n]);
connfd[i]=-1;
break;
}
}
pthread_exit((void*)i);
}
printf("%s\n",buf);
if(strcmp(buf,"./list")==0) list(n);
else sendmsgall(buf,n);
}
}
int main(){
pthread_t thread;
int listenfd,i;
struct sockaddr_in serveradd;
listenfd = socket(AF_INET,SOCK_STREAM,0);
if(listenfd<0) perror("socket");
bzero(&serveradd,sizeof(serveradd));
serveradd.sin_family = AF_INET;
serveradd.sin_addr.s_addr = inet_addr("127.0.0.1");
serveradd.sin_port = htons(PORT);
if(bind(listenfd,(struct sockaddr*) &serveradd, sizeof(serveradd))==-1) printf("bind error\n");
listen(listenfd,LISTENQ);
for(i=0;i<LISTENQ;i++) connfd[i] = -1;
connect_num=0;
while(1){
struct sockaddr_in cliadd;
socklen_t len = sizeof(cliadd);
int fd = accept(listenfd,(struct sockaddr*)&cliadd,&len);
if(fd == -1){
printf("Client Connect Failed\n");
continue;
}
for(i=0;i<LISTENQ;i++){
if(connfd[i]==-1){
connfd[i] = fd;
pthread_t tid;
pthread_create(&tid,NULL,service_thread,&i);
break;
}
}
}
}
|
C
|
#include <stdio.h>
#include <conio.h>
#include <math.h>
int main()
{
int a, b, count;
printf("Enter a and b- ");
scanf("%i%i", &a, &b);
while (a>=b){
a=a-b;
count++;
printf("a1=%i\nb1=%i\n",a, count);
}
printf("a=%i\nb=%i",a, count);
getch();
return 0;
}
|
C
|
/*
input_file -- 入力ファイルから取得したデータ
2つの現在の文字はcur_charとnext_charに格納される
各業は組み立てられた後、画面に出力可能なように
バッファに蓄えられる
関数
in_open -- 入力ファイルをオープン
in_close -- 入力ファイルをクローズ
read_char -- 次の文字を読む
in_char_char -- 現在の文字を返す
in_next_char -- 次の文字を返す
in_flush -- 行を画面に表示する
*/
/* in_open
parameters name -- ディスク・ファイルの名前
戻り値
0 -- 正しくオープンできた
nonzero -- オープンできなかった
*/
extern int in_open(const char name[]);
/* in_close ファイルをクローズ */
extern void in_close(void);
/* in_read_char 次の文字を読む
*/
extern void in_read_char(void);
/* in_cur_char
戻り値
現在の文字
*/
extern int in_cur_char(void);
/* in_next_char
戻り値
次の文字
*/
extern int in_next_char(void);
/* in_flush -- バッファに蓄えた入力業を画面にフラッシュ
*/
extern void in_flush(void);
|
C
|
#include "snprintf.h"
#include "types.h"
#include "uart.h"
static u32 strlen(const char *s)
{
u32 len = 0;
while (s[len] != '\0') len++;
return len;
}
static u32 itoa(i32 value, u32 radix, u32 uppercase, u32 unsig, char * buffer, u32 zero_pad)
{
char * pbuffer = buffer;
int negative = 0;
if (radix > 16) {
return 0;
}
if (value < 0 && !unsig) {
negative = 1;
value = -value;
}
do {
i32 digit = value % radix;
*(pbuffer++) = (digit < 10 ? '0' + digit : (uppercase ? 'A' : 'a') + digit - 10);
value /= radix;
} while (value > 0);
for (i32 i = (pbuffer - buffer); i < zero_pad; i++) {
*(pbuffer++) = '0';
}
if (negative) {
*(pbuffer++) = '-';
}
*(pbuffer) = '\0';
u32 len = (pbuffer - buffer);
for (i32 i = 0; i < len / 2; i++) {
char j = buffer[i];
buffer[i] = buffer[len-i-1];
buffer[len-i-1] = j;
}
return len;
}
struct mini_buff {
char * buffer;
char * pbuffer;
u32 buffer_len;
};
static int putc(i32 ch, struct mini_buff * b)
{
if ((u32)((b->pbuffer - b->buffer) + 1) >= b->buffer_len) {
return 0;
}
*(b->pbuffer++) = ch;
*(b->pbuffer) = '\0';
return 1;
}
static int puts(char * s, u32 len, struct mini_buff * b)
{
u32 i;
if (b->buffer_len - (b->pbuffer - b->buffer) - 1 < len) {
len = b->buffer_len - (b->pbuffer - b->buffer) - 1;
}
for (i = 0; i < len; i++) {
*(b->pbuffer++) = s[i];
}
*(b->pbuffer) = '\0';
return len;
}
i32 vsnprintf(char * buffer, u32 buffer_len, const char * fmt, __builtin_va_list va)
{
struct mini_buff b = {};
char bf[24] = {};
char ch = 0;
uart_puts("Hej");
b.buffer = buffer;
b.pbuffer = buffer;
b.buffer_len = buffer_len;
while ((ch = *(fmt++))) {
if ((u32)((b.pbuffer - b.buffer) + 1) >= b.buffer_len) {
break;
}
if (ch != '%') {
putc(ch, &b);
} else {
char zero_pad = 0;
char * ptr = NULL;
u32 len = 0;
ch = *(fmt++);
if (ch == '0') {
ch =* (fmt++);
if (ch == '\0') {
goto end;
}
if (ch >= '0' && ch <= '9') {
zero_pad = ch - '0';
}
ch = *(fmt++);
}
switch (ch) {
case 0:
goto end;
case 'u':
case 'd':
len = itoa(__builtin_va_arg(va, u32), 10, 0, (ch=='u'), bf, zero_pad);
puts(bf, len, &b);
break;
case 'x':
case 'X':
len = itoa(__builtin_va_arg(va, u32), 16, (ch=='X'), 1, bf, zero_pad);
puts(bf, len, &b);
break;
case 'c' :
putc((char)(__builtin_va_arg(va, int)), &b);
break;
case 's' :
ptr = __builtin_va_arg(va, char *);
puts(ptr, strlen(ptr), &b);
break;
default:
putc(ch, &b);
break;
}
}
}
end:
return b.pbuffer - b.buffer;
}
i32 snprintf(char * buffer, u32 buffer_len, const char *fmt, ...)
{
uart_puts("Hej");
__builtin_va_list va;
__builtin_va_start(va, fmt);
i32 ret = vsnprintf(buffer, buffer_len, fmt, va);
__builtin_va_end(va);
return ret;
}
|
C
|
/* Задача 5. Дефинирайте потребителски тип към масив.
Инициализирайте масива, изведете наконзолата. */
#include <stdio.h>
typedef char t_hText[64];
typedef char t_lText[2048];
int main() {
t_hText title = "The Life and Grievances of a Dead Man";
t_lText synopsis = "In present-day Salem, a serial killer known as the Bell Killer begins murdering\n"
"seemingly unconnected victims. Police Detective Ronan O'Connor is able to track down\n"
"the Bell Killer, but is thrown out of a window and shot to death during a fight.\n"
"He returns in the form of a ghost, and learns that in order to reach the afterlife\n"
"and meet his wife Julia, he must first discover the identity of his killer.\n"
"With the help of Abigail, the ghost of a Puritan child, Ronan is able to use\n"
"his ghostly abilities to return to the fight scene, and discovers that a medium\n"
"named Joy witnessed the fight, and is now hiding in a church.";
printf("Book: %s\nPlot: %s", title, synopsis);
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include "curve.h"
double find_amplitude(double* data, int size)
{
float max=0, min=0, amplitude;
for(int i=0;i<size;i++)
{
if(data[i]>max)
{
max=data[i];
}
}
for(int i=0;i<size;i++)
{
if(data[i]<min)
{
min=data[i];
}
}
amplitude = (max-min)/2;
return (amplitude);
}
|
C
|
#include <string.h>
int _dx8_strcmp(s1, s2)
char* s1;
char* s2;
{
return strcmp(s1, s2);
}
int _dx8_strlen(s)
char* s;
{
return strlen(s);
}
int _dx8_isalpha(c)
char c;
{
return isalpha(c);
}
int _dx8_islower(c)
char c;
{
return islower(c);
}
int _dx8_isspace(c)
char c;
{
return isspace(c);
}
int _dx8_toupper(c)
char c;
{
return toupper(c);
}
int _dx8_tolower(c)
char c;
{
return tolower(c);
}
|
C
|
#include <stdio.h>
#include <string.h>
#define MAX_WORD_LENGTH 50
#define MAX_WORD_PER_LINE 80
#define CHARACTER_PER_LINE 80
char line[80][50];
int main() {
FILE *read, *write;
char buffer[MAX_WORD_LENGTH];
fopen_s(&read, "harry.txt", "r");//
fopen_s(&write, "aligned.txt", "w");//
int wInd = 0, lLength = 0;
while (fscanf_s(read, "%s ", &buffer, MAX_WORD_LENGTH) != EOF) {//Ѵܾ
if (lLength+strlen(buffer) > CHARACTER_PER_LINE-wInd) {//ϳ ̹ܾ ̹
int spaces = CHARACTER_PER_LINE - lLength;//ʿ
for (int i = 0; i < wInd-1; i++) {// ܾ
fprintf(write,"%s", line[i]);
for (int j = 0; j < spaces / (wInd-1); j++)//յϰ
fprintf(write, " ");
if (spaces%(wInd-1) > 0) {//ʺ ĭ ִ
fprintf(write, " ");
spaces -= 1;
}
}
fprintf(write,line[wInd - 1]);// ܾ
fprintf(write,"\n");//ٹٲ
wInd = 0;
lLength = 0;
}
lLength += strlen(buffer);
strcpy_s(line[wInd++], 50, buffer);
}
for (int i = 0; i < wInd; i++) {//
fprintf(write, "%s", line[i]);
fprintf(write, " ");
}
fclose(read);
fclose(write);
printf("finished");
getchar();
}
|
C
|
#ifdef CHCORE
#include <mm/kmalloc.h>
#include <common/kprint.h>
#include <common/macro.h>
#include <common/radix.h>
#endif
#include <common/errno.h>
struct radix *new_radix(void)
{
struct radix *radix;
radix = kzalloc(sizeof(*radix));
BUG_ON(!radix);
return radix;
}
void init_radix(struct radix *radix)
{
radix->root = kzalloc(sizeof(*radix->root));
BUG_ON(!radix->root);
radix->value_deleter = NULL;
lock_init(&radix->radix_lock);
}
void init_radix_w_deleter(struct radix *radix, void (*value_deleter)(void *))
{
init_radix(radix);
radix->value_deleter = value_deleter;
}
static struct radix_node *new_radix_node(void)
{
struct radix_node *n = kzalloc(sizeof(struct radix_node));
if (!n) {
kwarn("run-out-memoroy: cannot allocate radix_new_node whose size is %ld\n",
sizeof(struct radix_node));
return ERR_PTR(-ENOMEM);
}
return n;
}
#ifndef FBINFER
int radix_add(struct radix *radix, u64 key, void *value)
{
int ret;
struct radix_node *node;
struct radix_node *new;
u16 index[RADIX_LEVELS];
int i;
int k;
lock(&radix->radix_lock);
if (!radix->root) {
new = new_radix_node();
if (IS_ERR(new)) {
ret = -ENOMEM;
goto fail_out;
}
radix->root = new;
}
node = radix->root;
/* calculate index for each level */
for (i = 0; i < RADIX_LEVELS; ++i) {
index[i] = key & RADIX_NODE_MASK;
key >>= RADIX_NODE_BITS;
}
/* the intermediate levels */
for (i = RADIX_LEVELS - 1; i > 0; --i) {
k = index[i];
if (!node->children[k]) {
new = new_radix_node();
if (IS_ERR(new)) {
ret = -ENOMEM;
goto fail_out;
}
node->children[k] = new;
}
node = node->children[k];
}
/* the leaf level */
k = index[0];
if ((node->values[k] != NULL) && (value != NULL)) {
kwarn("Radix: add an existing key\n");
BUG_ON(1);
}
node->values[k] = value;
unlock(&radix->radix_lock);
return 0;
fail_out:
unlock(&radix->radix_lock);
return ret;
}
void *radix_get(struct radix *radix, u64 key)
{
void *ret;
struct radix_node *node;
u16 index[RADIX_LEVELS];
int i;
int k;
lock(&radix->radix_lock);
if (!radix->root) {
ret = NULL;
goto out;
}
node = radix->root;
/* calculate index for each level */
for (i = 0; i < RADIX_LEVELS; ++i) {
index[i] = key & RADIX_NODE_MASK;
key >>= RADIX_NODE_BITS;
}
/* the intermediate levels */
for (i = RADIX_LEVELS - 1; i > 0; --i) {
k = index[i];
if (!node->children[k]) {
ret = NULL;
goto out;
}
node = node->children[k];
}
/* the leaf level */
k = index[0];
ret = node->values[k];
out:
unlock(&radix->radix_lock);
return ret;
}
/* FIXME(MK): We should allow users to store NULL in radix... */
int radix_del(struct radix *radix, u64 key)
{
return radix_add(radix, key, NULL);
}
static void radix_free_node(struct radix_node *node, int node_level,
void (*value_deleter)(void *))
{
int i;
WARN_ON(!node, "should not try to free a node pointed by NULL");
if (node_level == RADIX_LEVELS - 1) {
if (value_deleter) {
for (i = 0; i < RADIX_NODE_SIZE; i++)
{
if (node->values[i])
value_deleter(node->values[i]);
}
}
} else {
for (i = 0; i < RADIX_NODE_SIZE; i++)
{
if (node->children[i])
radix_free_node(node->children[i],
node_level + 1, value_deleter);
}
}
}
#endif
int radix_free(struct radix *radix)
{
lock(&radix->radix_lock);
if (!radix || !radix->root) {
WARN("trying to free an empty radix tree");
return -EINVAL;
}
// recurssively free nodes and values (if value_deleter is not NULL)
radix_free_node(radix->root, 0, radix->value_deleter);
unlock(&radix->radix_lock);
return 0;
}
|
C
|
/*
* token.c
*
* Created on: May 30, 2015
* Author: sudipta
*/
const char *token_next(const char *str, int *pos) {
const char *ret;
while (str[*pos] == ' ') {
(*pos)++;
}
ret = str+*pos;
/* Advance to the next space or end of string. */
while (str[*pos] != ' ' && str[*pos] != '\0') {
(*pos)++;
}
return ret;
}
void handle_serial_input(const char *line) {
int pos = 0;
const char *token;
/* Consume the first token. */
token = token_next(line, &pos);
printf("Recv frm master: %s\n",token);
// switch (token[0]) {
// case 'c':
// chlm.current_channel = atoi(token_next(line, &pos));
// printf("Setting current channel to %u.\n",chlm.current_channel);
// //radio_set_txpower(config.txpower);
// break;
// case 'p':
// chlm.current_power = atoi(token_next(line, &pos));
// printf("Setting current power to %u.\n",chlm.current_power);
// break;
// case 'd':
// chlm.current_data_packet_size = atoi(token_next(line, &pos));
// printf("Setting current data packet size to %u.\n",chlm.current_data_packet_size);
// break;
// default:
// printf("?\n");
// break;
// }
}
// void print_observer_input(const char *line) {
// int pos = 0;
// const char *token;
// /* Consume the first token. */
// token = token_next(line, &pos);
// switch (token[0]) {
// case '1':printf("1\n"); // sender side human
// break;
// case '2':printf("2\n"); // sender side small vehicle
// break;
// case '3':printf("3\n"); // sender side medium vehicle
// break;
// case '4':printf("4\n"); // sender side large vehicle
// break;
// case '5':printf("5\n"); // receiver side human
// break;
// case '6':printf("6\n"); // receiver side small vehicle
// break;
// case '7':printf("7\n"); // receiver side medium vehicle
// break;
// case '8':printf("8\n"); // receiver side large vehicle
// break;
// case '15':printf("15\n"); // combination
// break;
// case '16':printf("16\n"); // combination
// break;
// case '17':printf("17\n"); // combination
// break;
// case '18':printf("18\n"); // combination
// break;
// case '25':printf("15\n"); // combination
// break;
// case '26':printf("16\n"); // combination
// break;
// case '27':printf("17\n"); // combination
// break;
// case '28':printf("18\n"); // combination
// break;
// case '35':printf("15\n"); // combination
// break;
// case '36':printf("16\n"); // combination
// break;
// case '37':printf("17\n"); // combination
// break;
// case '38':printf("18\n"); // combination
// break;
// case '45':printf("15\n"); // combination
// break;
// case '46':printf("16\n"); // combination
// break;
// case '47':printf("17\n"); // combination
// break;
// case '48':printf("18\n"); // combination
// break;
// default:
// printf("0\n");
// break;
// }
// }
#endif
|
C
|
#include <stdio.h>
#include <stdlib.h>
struct Scomplex
{
double real;
double img;
};
int main()
{
struct Scomplex x,y,sum;
printf("for 1st complex number\n");
printf("Enter the real and imgainary respectively: ");
fflush(stdin); fflush(stdout);
scanf("%lf %lf", &x.real,&x.img);
printf("for 2nd complex number\n");
printf("Enter the real and imgainary respectively: ");
fflush(stdin); fflush(stdout);
scanf("%lf %lf", &y.real, &y.img);
sum.real = x.real + y.real;
sum.img = x.img + y.img;
printf("sum = %.1lf+%.1lfi",sum.real, sum.img);
return 0;
}
|
C
|
/*
Курсовой проект по дисциплине "Вычислительные сети"
Демонстрация выполнения задания лабораторной работы № 3
"Отправление пакетов типа ECHO протокола ICMP, получение пакетов типа ECHO-REPLY протокола ICMP"
Подготовил: Акинин М.В.
01.12.2010
*/
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <linux/ip.h>
#include <netinet/in.h>
#include <linux/icmp.h>
#define BUF_SIZE 4096
/*
Функция подсчета контрольной суммы
Параметры:
buf - буфер, контрольную сумму содержимого которого необходимо подсчитать
buf_size - размер буфера в байтах
Возвращаемое значение:
Контрольная сумма
*/
uint16_t checksum(uint16_t *buf, uint16_t buf_size);
/* Главная функция программы */
int main(const int argc, const char *argv[])
{
if(argc != 3)
{
fprintf(stderr, "\nПрограмме передано недостаточное количество аргументов\n\n\
Формат вызова: ./program IP NUM\n\nЗдесь:\n\n\
\tIP\t-\tIPv4-адрес сетевого узла - получателя пакетов типа ECHO протокола ICMP;\n\
\tNUM\t-\tколичество отправляемых пакетов типа ECHO протокола ICMP.\n\n");
return -1;
}
/* Создание сырого (SOCK_RAW) сокета для обмена по протоколу ICMP (IPPROTO_ICMP) */
int sock = socket(AF_INET, SOCK_RAW, IPPROTO_ICMP);
if(sock == -1)
{
fprintf(stderr, "\nОшибка при создании сокета\n\n");
return -1;
}
unsigned u, max_u = atoi(argv[2]) + 1;
ssize_t size;
uint8_t echo_buf[BUF_SIZE], echo_reply_buf[BUF_SIZE];
struct sockaddr_in addr;
struct icmphdr *echo_hdr = (struct icmphdr *) echo_buf, *echo_reply_hdr = (struct icmphdr *) echo_reply_buf + sizeof(struct iphdr);
/* Заполнение полей заголовка пакета типа ECHO протокола ICMP */
echo_hdr->type = ICMP_ECHO; // Тип отправляемого пакета - ECHO
echo_hdr->code = 0; // Для пакетов типа ECHO поле code не учитывается
echo_hdr->un.echo.id = 53890; // Идентификатор последовательности пакетов
/* Заполнение описателя IP-адреса сетевого узла - получателя пакетов типа ECHO протокола ICMP */
addr.sin_family = AF_INET; // Семейство протоколов (стек протоколов TCP/IPv4)
addr.sin_port = 0; // Порт назначения (для протокола ICMP устанавливается 0, так как протокол ICMP не оперирует портами)
inet_aton(argv[1], & addr.sin_addr); // IP-адрес сетевого узла в сетевом порядке байт
printf("\n");
/* Главный цикл программы */
for(u = 1; u < max_u; u++)
{
/* В поле заголовка ICMP-ECHO-пакета, хранящее номер пакета в последовательности, записывается номер отправляемого пакета */
echo_hdr->un.echo.sequence = u << 8;
/* Подсчет контрольной суммы ICMP-ECHO-пакета (контрольная сумма подсчитывается при поле контрольной суммы, установленном в 0) */
echo_hdr->checksum = 0;
echo_hdr->checksum = checksum((uint16_t *) echo_hdr, sizeof(struct icmphdr));
/* Отправление ICMP-ECHO-пакета целевому сетевому узлу */
sendto(sock, echo_buf, sizeof(struct icmphdr) + 100, 0, (struct sockaddr *) & addr, sizeof(struct sockaddr_in));
printf("Пакет %u отправлен -> ", u);
do
{
sleep(1);
/* Получение ответного ICMP-ECHO_REPLY-пакета. Операция получения ответа не блокируется */
size = recv(sock, echo_reply_buf, BUF_SIZE, MSG_DONTWAIT);
}
while (size < 0);
if(size > 0)
if(echo_reply_hdr->type == ICMP_ECHOREPLY)
printf("ответ получен\n");
}
printf("\n");
/* Уничтожение сокета */
close(sock);
return 0;
}
/*
Функция подсчета контрольной суммы
Параметры:
buf - буфер, контрольную сумму содержимого которого необходимо подсчитать
buf_size - размер буфера в байтах
Возвращаемое значение:
Контрольная сумма
*/
uint16_t checksum(uint16_t *buf, uint16_t buf_size)
{
unsigned u;
uint32_t sum = 0;
buf_size /= 2;
for(u = 0; u < buf_size; u++)
sum += buf[u];
return ~ ((sum & 0xFFFF) + (sum >> 16));
}
|
C
|
#include "Stack.h"
#define _CRT_SECURE_NO_WARNINGS 1
#include <stdlib.h>
#include <assert.h>
#include <stdio.h>
#include <errno.h>
#include <string.h>
#include <stdbool.h>
void StackInit(Stack* ps)
{
assert(ps != NULL);
ps->_capacity = DEFAULT_STACK_CAPACITY;
ps->_pa = (STDataType*)malloc(ps->_capacity * sizeof(STDataType));
if (ps->_pa == NULL)
{
puts(strerror(errno));
exit(-1);
}
ps->_top = 0;
}
static bool isFull(Stack* ps)
{
assert(ps != NULL);
return ps->_capacity == ps->_top;
}
static void ReallocStack(Stack* ps)
{
assert(ps != NULL);
ps->_capacity *= 2;
STDataType* p = (STDataType*)realloc(ps->_pa, ps->_capacity * sizeof(STDataType));
if (p == NULL)
{
puts(strerror(errno));
free(ps->_pa);
exit(-1);
}
ps->_pa = p;
}
void StackPush(Stack* ps, STDataType item)
{
assert(ps != NULL);
if (isFull(ps))
{
ReallocStack(ps);
}
ps->_pa[ps->_top++] = item;
}
static bool isEmpty(Stack* ps)
{
assert(ps != NULL);
return ps->_top == 0;
}
void StackPop(Stack* ps)
{
assert(ps != NULL);
if (isEmpty(ps))
{
printf("ջ,ɾ\n");
}
else
{
ps->_top--;
}
}
int StackLen(Stack* ps)
{
assert(ps != NULL);
return ps->_top;
}
//Ϊշط,ǿշ0
int StackEmpty(Stack* ps)
{
assert(ps != NULL);
if (ps->_top)
{
return 0;
}
else
{
return 1;
}
}
STDataType StackTop(Stack* ps)
{
assert(ps != NULL);
if (StackEmpty(ps))
{
printf("ջ,ջûԪ\n");
exit(-1);
}
return ps->_pa[ps->_top - 1];
}
void StackDestroy(Stack* ps)
{
assert(ps != NULL);
free(ps->_pa);
ps->_pa = NULL;
ps->_capacity = 0;
ps->_top = 0;
}
|
C
|
/**************************************************************************************************/
/* Copyright (C) JG14225101, SSE@USTC, 2014-2015 */
/* */
/* FILE NAME : SE_Lab1.c */
/* PRINCIPAL AUTHOR : Baodi */
/* SUBSYSTEM NAME : SE_Lab1 */
/* MODULE NAME : SE_Lab1 */
/* LANGUAGE : C */
/* TARGET ENVIRONMENT : ANY */
/* DATE OF FIRST RELEASE : 2014/09/11 */
/* DESCRIPTION : This is a menu program */
/**************************************************************************************************/
/*
* Revision log:
*
* Created by Baodi(JG14225101), 2014/09/11
*
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int Help();
int Writer();
#define DESC_LEN 1024
#define CMD_NUM 10
#define CMD_MAX_LEN 128
typedef struct DataNode
{
char* cmd;
char* desc;
int (*handler)();
struct DataNode *next;
}tDataNode;
static tDataNode head[] =
{
{"help","this is help cmd",Help,&head[1]},
{"version","menu program v1.0",NULL,&head[2]},
{"writer", "Show the information of writer",Writer, NULL}
};
main()
{
/*cmd line begins*/
while(1)
{
char cmd[CMD_MAX_LEN];
printf("Input a cmd > ");
gets(cmd);
tDataNode *p = head;
for(; p!=NULL; p=p->next)
{
if(!strcmp(p->cmd, cmd))
{
printf("%s - %s\n", p->cmd,p->desc);
if(p->handler != NULL)
{
p->handler();
}
break;
}
}
if(p == NULL)
{
printf("This is a wrong cmd !\n ");
}
}
}
int Help()
{
printf("Menu List:\n");
tDataNode *p = head;
while(p != NULL)
{
printf("%s - %s\n",p->cmd, p->desc);
p = p->next;
}
return 0;
}
int Writer()
{
printf("This code is written by Baodi(JG14225101)\n");
return 0;
}
|
C
|
/*====================================================================*
*
* dash1.c - place double-dashed arguments on single lines;
*
*. Motley Tools by Charles Maier;
*: Copyright (c) 2001-2006 by Charles Maier Associates Limited;
*; Licensed under the Internet Software Consortium License;
*
*--------------------------------------------------------------------*/
#define _GETOPT_H
/*====================================================================*
* custom header files;
*--------------------------------------------------------------------*/
#include <stdio.h>
#include <ctype.h>
#include <sys/stat.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
/*====================================================================*
* custom header files;
*--------------------------------------------------------------------*/
#include "../tools/cmassoc.h"
#include "../files/files.h"
/*====================================================================*
* custom source files;
*--------------------------------------------------------------------*/
#ifndef MAKEFILE
#include "../tools/getoptv.c"
#include "../tools/putoptv.c"
#include "../tools/version.c"
#include "../tools/error.c"
#endif
#ifndef MAKEFILE
#include "../files/vfopen.c"
#include "../files/makepath.c"
#include "../files/splitpath.c"
#include "../files/mergepath.c"
#endif
/*====================================================================*
*
* void function (flag_t flags);
*
* read from ifp and write to ofp; detect double-dashed arguments
* and move each one to a new line; replace leading whitespace on
* each line with one horizontal tab character;
*. Motley Tools by Charles Maier;
*: Copyright (c) 2001-2006 by Charles Maier Associates Limited;
*; Licensed under the Internet Software Consortium License;
*
*--------------------------------------------------------------------*/
void function (flag_t flags)
{
signed c;
signed o;
while ((c = getc (stdin)) != EOF)
{
switch (c)
{
case '#':
do
{
putc (c, stdout);
c = getc (stdin);
}
while (nobreak (c));
putc ('\n', stdout);
break;
case '\\':
c = getc (stdin);
if (c == '\n')
{
do
{
c = getc (stdin);
}
while (isblank (c));
ungetc (c, stdin);
}
else if (c == EOF)
{
putc ('\\', stdout);
putc ('\n', stdout);
}
else
{
putc ('\\', stdout);
putc (c, stdout);
}
break;
case '\"':
case '\'':
o = c;
do
{
putc (c, stdout);
o = getc (stdin);
if (c == '\\')
{
putc (c, stdout);
c = getc (stdin);
putc (c, stdout);
c = getc (stdin);
}
}
while ((c != EOF) && (c != o));
putc (o, stdout);
break;
case '-':
c = getc (stdin);
if (c == '-')
{
putc ('\\', stdout);
putc ('\n', stdout);
putc ('\t', stdout);
putc ('-', stdout);
}
else
{
ungetc (c, stdin);
}
putc ('-', stdout);
break;
default:
putc (c, stdout);
break;
}
}
return;
}
/*====================================================================*
* main program;
*--------------------------------------------------------------------*/
int main (int argc, char const * argv [])
{
static char const * optv [] =
{
"break double-dashed arguments out onto individual lines;",
PUTOPTV_S_FILTER,
"h",
(char *) (0)
};
flag_t flags = (flag_t) (0);
signed c;
while (~ (c = getoptv (argc, argv, optv)))
{
switch (c)
{
case 'h':
putoptv (optv);
exit (0);
case ':':
exit (1);
case '?':
exit (1);
default:
break;
}
}
argc -= optind;
argv += optind;
if (! argc)
{
function (flags);
}
while ((argc) && (* argv))
{
if (vfopen (* argv))
{
function (flags);
}
argc--;
argv++;
}
exit (0);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
char command[80],temp[80];
int i,j;
for(;;){
printf("\nOperation? \n");
gets(command);
if(!strcmp(command,"quit")) break;
printf("Enter your first number: ");
gets(temp);
i=atoi(temp);
printf("Enter your second number: ");
gets(temp);
j=atoi(temp);
if(!strcmp(command,"add"))
printf("\n%d",i+j);
else if(!strcmp(command,"subtract"))
printf("\n%d",i-j);
else if(!strcmp(command,"divide")){
if(j)
printf("\n%d",i/j);
}
else if(!strcmp(command,"multiply"))
printf("\n%d\n",i*j);
else printf("\nUnknown command.\n");
}
return 0;
}
|
C
|
#ifndef WAD_HEADER
#define WAD_HEADER
#define LE_FOURCC(a, b, c, d) ( \
((unsigned)(a)) | \
((unsigned)(b) << 8) | \
((unsigned)(c) << 16) | \
((unsigned)(d) << 24) \
)
#define WAD_HEADER_SIZE (4 + 4 + 4)
#define WAD_DENTRY_SIZE (4 + 4 + 8)
enum wad_error {
WAD_SUCCESS = 0,
WAD_ERROR_FILE_OPEN = -1,
WAD_ERROR_FILE_READ = -2,
WAD_ERROR_FILE_SEEK = -3
};
enum wad_type {
WAD_TYPE_IWAD = LE_FOURCC('I', 'W', 'A' , 'D'),
WAD_TYPE_PWAD = LE_FOURCC('P', 'W', 'A' , 'D')
};
struct wad_header {
enum wad_type type;
int lump_count;
int directory_offset;
};
struct wad {
void *fd;
struct wad_header hd;
};
struct wad_dentry {
int offset;
int size;
char name[8 + 1];
};
int wad_open(struct wad *wad, const char *path);
void wad_close(struct wad *wad);
int wad_seek_first_dentry(const struct wad *wad);
int wad_read_next_dentry(const struct wad *wad, struct wad_dentry *dentry);
#endif // WAD_HEADER
|
C
|
#include <stdio.h>
#include "matriks.h"
/* DEFINISI PROTOTIPE PRIMITIF */
/*** Konstruktor ***/
void MakeMatriks (int NB, int NK, Matriks *M) {
/* I.S. NB dan NK adalah valid untuk memori matriks yang dibuat */
/* F.S. Matriks M sesuai dengan definisi di atas terbentuk */
//Algoritma
NBrsEff(*M)=NB;
NKolEff(*M)=NK;
}
/*** Selektor ***/
boolean IsIdxMatriksValid (int i, int j) {
/* Mengirimkan true jika i, j adalah indeks yang valid untuk matriks apa pun */
return(i>=IdxBrsMin && i<=IdxBrsMax && j>=IdxKolMin && j<=IdxKolMax);
}
indeks GetFirstIdxBrs (Matriks M) {
/* Mengirimkan indeks baris terkecil M */
return IdxBrsMin;
}
indeks GetFirstIdxKol (Matriks M) {
/* Mengirimkan indeks kolom terkecil M */
return IdxKolMin;
}
indeks GetLastIdxBrs (Matriks M) {
/* Mengirimkan indeks baris terbesar M */
return(NBrsEff(M));
}
indeks GetLastIdxKol (Matriks M) {
/* Mengirimkan indeks kolom terbesar M */
return(NKolEff(M));
}
boolean IsIdxMatriksEff (Matriks M, indeks i, indeks j) {
/* Mengirimkan true jika i, j adalah indeks efektif bagi M */
return(i>=GetFirstIdxBrs(M) && j>=GetFirstIdxKol(M) && i<=GetLastIdxBrs(M) && j<=GetLastIdxKol(M));
}
/* KELOMPOK BACA/TULIS */
void BacaUkuranMatriks (Matriks * M) {
/* I.S. Matriks Matriks belum memiliki ukuran */
/* F.S. Ukuran matriks terdefinisi dan valid */
/* Matriks yang valid berukuran 10<=NB<=20 dan 10<=NK<=30 */
// Kamus lokal
int NB, NK;
// Algoritma
printf("Masukkan ukuran matriks (baris x kolom)\n");
scanf("%d %d",&NB,&NK);
while(!IsIdxMatriksValid(NB,NK)){
scanf("%d %d",NB,NK);
}
MakeMatriks(NB, NK, M);
}
void TulisMatriksPeta (Matriks M, TabBangunan T){
/* I.S. M terdefinisi */
/* F.S. Menuliskan matriks sesuai dengan lokasi bangunan */
/* Contoh: Menuliskan matriks berukuran 5x5
╔═════╗
║ ║
║ ║
║ ║
║ ║
║ ║
╚═════╝
*/
// Kamus lokal
int i, j, lenPad;
// Algoritma
// Get left pad
lenPad = (69 - (GetLastIdxKol(M)*2+1 - GetFirstIdxKol(M) + 1 + 2)) / 2;
// Print left pad
for (i = 1; i <= lenPad; i++) {
printf(" ");
}
// Print
print_cyan_s("╔");
for (i = GetFirstIdxKol(M); i <= GetLastIdxKol(M)*2 + 1; i++) {
print_cyan_s("═");
}
print_cyan_s("╗\n");
for (i = GetFirstIdxBrs(M); i <= GetLastIdxBrs(M); i++) {
// Print left pad
for (j = 1; j <= lenPad; j++) {
printf(" ");
}
// Print matriks
print_cyan_s("║ ");
for (j = GetFirstIdxKol(M); j <= GetLastIdxKol(M); j++) {
if (ElmtMatriks(M, i, j) != 0) {
if (Pemilik(ElmtTab(T, ElmtMatriks(M, i, j))) == 1) {
print_green(Tipe(ElmtTab(T, ElmtMatriks(M, i, j))));
} else if (Pemilik(ElmtTab(T, ElmtMatriks(M, i, j))) == 2) {
print_red(Tipe(ElmtTab(T, ElmtMatriks(M, i, j))));
} else {
print_yellow(Tipe(ElmtTab(T, ElmtMatriks(M, i, j))));
}
printf(" ");
} else {
printf(" ");
}
}
print_cyan_s("║\n");
}
// Print left pad
for (i = 1; i <= lenPad; i++) {
printf(" ");
}
// Print
print_cyan_s("╚");
for (i = GetFirstIdxKol(M); i <= GetLastIdxKol(M) * 2 + 1; i++) {
print_cyan_s("═");
}
print_cyan_s("╝");
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#define NUM_ITERATIONS (100000)
/* Calls getpid() in a loop */
int main()
{
int i = 0;
for (i = 0; i < NUM_ITERATIONS ; ++i) {
getpid();
}
return 0;
}
|
C
|
///////////////////////////////////////////////////////////////////////////////////
// File : coff_browser.c
// Contains: coff file browser
//
// Written by: Jean-François DEL NERO
///////////////////////////////////////////////////////////////////////////////////
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <stdint.h>
#include "coff_format.h"
#include "coff_access.h"
int coff_get_str_symbol_name(char * n_name, uint8_t * strings_buffer,int strings_buffer_size,char* str)
{
int i;
int lessthan8;
uint32_t stringoffset;
char tmp_buf[8];
char *ptr;
str[0] = 0;
lessthan8 = 0;
for(i=0;i<4;i++)
{
if(n_name[i])
{
lessthan8 = 1;
}
}
if(lessthan8)
{
if( n_name[0] == '/' )
{
memcpy(tmp_buf,&n_name[1], 7);
tmp_buf[7] = 0;
ptr = &tmp_buf[0];
if( *ptr >= '0' && *ptr <= '9' )
{
stringoffset = strtol (tmp_buf, &ptr, 10);
if(stringoffset >= 0 && (*ptr == '\0') )
{
i = 0;
while( ((int)(stringoffset + i) < strings_buffer_size) && strings_buffer[stringoffset + i] )
{
str[i] = strings_buffer[stringoffset + i];
i++;
}
return 1;
}
}
return 0;
}
i = 0;
while(n_name[i] && i < 8)
{
str[i] = n_name[i];
i++;
}
str[i] = 0;
return 1;
}
stringoffset = 0;
for(i=0;i<4;i++)
{
stringoffset |= (((uint32_t)(n_name[i+4]&0xFF)) << (i*8));
}
i = 0;
while( ((int)(stringoffset + i) < strings_buffer_size) && strings_buffer[stringoffset + i] )
{
str[i] = strings_buffer[stringoffset + i];
i++;
}
str[i] = 0;
return 1;
}
int coff_set_str_symbol_name(char * n_name, uint8_t * strings_buffer,int strings_buffer_size,char* str)
{
int i,maxsize;
int lessthan8;
uint32_t stringoffset;
lessthan8 = 0;
for(i=0;i<4;i++)
{
if(n_name[i])
{
lessthan8 = 1;
}
}
if(lessthan8)
{
i = 0;
while(str[i] && i < 8)
{
n_name[i] = str[i];
i++;
}
if( i < 8)
n_name[i] = 0;
return 1;
}
stringoffset = 0;
for(i=0;i<4;i++)
{
stringoffset |= (((uint32_t)(n_name[i+4]&0xFF)) << (i*8));
}
i = 0;
maxsize = 0;
while( ((int)(stringoffset + i) < strings_buffer_size) && strings_buffer[stringoffset + i] )
{
maxsize++;
i++;
}
i = 0;
while( ((stringoffset + i) < (stringoffset+maxsize)) && str[i] )
{
strings_buffer[stringoffset + i] = str[i];
i++;
}
strings_buffer[stringoffset + i] = 0;
return 1;
}
obj_state * coff_load_obj(char * path)
{
int i;
FILE * in_file;
obj_state * object;
object = NULL;
in_file = fopen(path,"rb");
if(!in_file)
{
printf("ERROR : Can't open input file %s !\n",path);
goto fatal_error;
}
object = malloc(sizeof(obj_state));
if(object)
{
memset(object,0,sizeof(obj_state));
object->file_path = malloc(strlen(path) + 1);
if(!object->file_path)
goto fatal_error;
strcpy(object->file_path, path);
fseek(in_file,0,SEEK_END);
object->obj_file_size = ftell(in_file);
fseek(in_file,0,SEEK_SET);
if( fread(&object->file_header,sizeof(coff_file_header),1,in_file) != 1 )
{
printf("ERROR : Can't read input file %s !\n",path);
goto fatal_error;
}
if(object->file_header.f_magic != 0x014C &&
object->file_header.f_magic != 0x8664
)
{
printf("not a coff/pe-i386 file !\n");
goto fatal_error;
}
object->string_table_offset = object->file_header.f_symptr + ( object->file_header.f_nsyms * sizeof( coff_symbol_table ) );
if( ( ( object->string_table_offset + sizeof(uint32_t) ) >= object->obj_file_size ) || ( object->string_table_offset < sizeof(coff_file_header) ) )
{
printf("invalid coff/pe-i386 file !\n");
goto fatal_error;
}
fseek(in_file,object->string_table_offset,SEEK_SET);
if( fread(&object->string_table_size,sizeof(uint32_t),1,in_file) != 1)
{
printf("string buffer size loading error !\n");
goto fatal_error;
}
if( ( ( object->string_table_offset + object->string_table_size ) > object->obj_file_size ) || ( object->string_table_offset < sizeof(coff_file_header) ) )
{
printf("invalid coff/pe-i386 file (string table)!\n");
goto fatal_error;
}
object->strings_buffer = malloc(object->string_table_size);
if(!object->strings_buffer)
{
printf("string buffer alloc error !\n");
goto fatal_error;
}
memset(object->strings_buffer,0,object->string_table_size);
fseek(in_file,object->string_table_offset,SEEK_SET);
if( fread(object->strings_buffer,object->string_table_size,1,in_file) != 1 )
{
printf("string buffer loading error !\n");
goto fatal_error;
}
// Loading sections
object->sections = malloc( sizeof( coff_section_header ) * object->file_header.f_nscns );
if(!object->sections)
{
printf("sections array alloc error !\n");
goto fatal_error;
}
fseek(in_file,sizeof(coff_file_header) + object->file_header.f_opthdr,SEEK_SET);
for(i=0;i<object->file_header.f_nscns;i++)
{
if( fread(&object->sections[i],sizeof(coff_section_header),1,in_file) != 1)
{
printf("section loading error ! (%d)\n",i);
goto fatal_error;
}
}
// Loading symbols
object->symbols = malloc( sizeof( coff_symbol_table ) * object->file_header.f_nsyms );
if(!object->symbols)
{
printf("symbols array alloc error !\n");
goto fatal_error;
}
fseek(in_file,object->file_header.f_symptr,SEEK_SET);
for(i=0;i<object->file_header.f_nsyms;i++)
{
if( fread(&object->symbols[i],sizeof(coff_symbol_table),1,in_file) != 1)
{
printf("symbol loading error ! (%d)\n",i);
goto fatal_error;
}
}
}
fclose(in_file);
return object;
fatal_error:
if(in_file)
fclose(in_file);
if(object)
{
if(object->file_path)
free(object->file_path);
if(object->strings_buffer)
free(object->strings_buffer);
if(object->symbols)
free(object->symbols);
if(object->sections)
free(object->sections);
free(object);
}
return NULL;
}
void coff_print_obj_stat(obj_state * obj)
{
int auxcnt;
int i,j;
char tmp_string[1024];
if(obj)
{
printf("f_magic : %.4X\n",obj->file_header.f_magic);
printf("f_nscns : %.4X\n",obj->file_header.f_nscns);
printf("f_timdat : %.8X\n",obj->file_header.f_timdat);
printf("f_symptr : %.8X\n",obj->file_header.f_symptr);
printf("f_nsyms : %.8X\n",obj->file_header.f_nsyms);
printf("f_opthdr : %.4X\n",obj->file_header.f_opthdr);
printf("f_flags : %.4X\n",obj->file_header.f_flags);
printf("Strings table offsets : 0x%x\n",obj->string_table_offset);
printf("Strings table size : 0x%x\n",obj->string_table_size);
printf("Section table :\n");
for(i=0;i<obj->file_header.f_nscns;i++)
{
printf("-------------\n");
printf("Section n°%d : ",i + 1);
coff_get_str_symbol_name((char*)&obj->sections[i].s_name, obj->strings_buffer,obj->string_table_size,(char*)&tmp_string);
printf("%s\n",tmp_string);
printf("Physical Address : 0x%X\n",obj->sections[i].s_paddr);
printf("Virtual Address : 0x%X\n",obj->sections[i].s_vaddr);
printf("Section Size in Bytes : %d\n",obj->sections[i].s_size);
printf("Section file offset : 0x%X\n",obj->sections[i].s_scnptr);
printf("Reloc table file offset : 0x%X\n",obj->sections[i].s_relptr);
printf("Reloc table entries : %d\n",obj->sections[i].s_nreloc);
printf("Line number table file offset : 0x%X\n",obj->sections[i].s_lnnoptr);
printf("Line number table entries : 0x%X\n",obj->sections[i].s_nlnno);
printf("Flags for this section : 0x%.4X\n",obj->sections[i].s_flags);
printf("-------------\n");
}
printf("Symbol table :\n");
auxcnt = 0;
for(i=0;i<obj->file_header.f_nsyms;i++)
{
if(!auxcnt)
{
printf("-------------\n");
printf("Symbol n°%d : ",i);
for(j=0;j<8;j++)
printf("%.2X",obj->symbols[i].n_name[j]);
printf(" - ");
coff_get_str_symbol_name((char*)&obj->symbols[i].n_name, obj->strings_buffer,obj->string_table_size,(char*)&tmp_string);
printf("%s\n",tmp_string);
printf("n_value : 0x%X\n",obj->symbols[i].n_value);
printf("n_scnum : %d",obj->symbols[i].n_scnum);
if(obj->symbols[i].n_scnum && (obj->symbols[i].n_scnum < obj->file_header.f_nscns))
{
coff_get_str_symbol_name((char*)&obj->sections[obj->symbols[i].n_scnum-1].s_name, obj->strings_buffer,obj->string_table_size,(char*)&tmp_string);
printf(" - %s\n",tmp_string);
}
else
{
printf("\n");
}
printf("n_type : 0x%X\n",obj->symbols[i].n_type);
printf("n_sclass: 0x%X\n",obj->symbols[i].n_sclass);
printf("n_numaux: 0x%X\n",obj->symbols[i].n_numaux);
switch( obj->symbols[i].n_sclass )
{
case 2:
if(!obj->symbols[i].n_scnum)
{
if(!obj->symbols[i].n_value)
printf("Type: Unresolved external Symbol\n");
else
printf("Type: Uninitialised global variable (not included in BSS)\n");
}
else
{
coff_get_str_symbol_name((char*)&obj->sections[obj->symbols[i].n_scnum-1].s_name, obj->strings_buffer,obj->string_table_size,(char*)&tmp_string);
if(!strncmp(tmp_string,".text",5))
printf("Type: Function entry point\n");
if(!strncmp(tmp_string,".data",5))
printf("Type: Initialised global variable\n");
}
break;
case 3:
if(!obj->symbols[i].n_value)
{
if(
!strncmp(tmp_string,".text",5) ||
!strncmp(tmp_string,".data",5) ||
!strncmp(tmp_string,".rdata",6) ||
!strncmp(tmp_string,".xdata",6) ||
!strncmp(tmp_string,".pdata",6) ||
!strncmp(tmp_string,".bss",4) )
{
printf("Type: Section Symbol indicating start of Section\n");
}
}
else
{
if(
!strcmp(tmp_string,".data") ||
!strcmp(tmp_string,".rdata") ||
!strcmp(tmp_string,".xdata") ||
!strcmp(tmp_string,".pdata")
)
{
printf("Type: Initialised static variable\n");
}
if( !strcmp(tmp_string,".bss") )
{
printf("Type: Unitialised static variable\n");
}
}
break;
}
printf("-------------\n");
}
else
{
auxcnt--;
}
if(!auxcnt)
auxcnt = obj->symbols[i].n_numaux;
}
}
}
int coff_get_next_symbol(obj_state * obj, int type, int index)
{
int i;
int auxcnt,ltype;
char tmp_string[1024];
auxcnt = 0;
if(!obj)
return -1;
if(index >= obj->file_header.f_nsyms)
return -1;
if(index < 0)
{
index = 0;
}
else
{
auxcnt = obj->symbols[index].n_numaux;
if(!auxcnt)
index++;
if(index >= obj->file_header.f_nsyms)
return -1;
}
for(i=index;i<obj->file_header.f_nsyms;i++)
{
if(!auxcnt)
{
ltype = -1;
switch( obj->symbols[i].n_sclass )
{
case 2:
if(!obj->symbols[i].n_scnum)
{
if(!obj->symbols[i].n_value)
ltype = SYMBOL_UNRESOLVED_EXT_SYMBOL_TYPE;
else
ltype = SYMBOL_UNINITIALISED_GLOBAL_VARIABLE_TYPE;
}
else
{
coff_get_str_symbol_name((char*)&obj->sections[obj->symbols[i].n_scnum-1].s_name, obj->strings_buffer,obj->string_table_size,(char*)&tmp_string);
if(!strncmp(tmp_string,".text",5))
ltype = SYMBOL_FUNCTION_ENTRYPOINT_TYPE;
if(!strncmp(tmp_string,".data",5))
ltype = SYMBOL_INITIALISED_GLOBAL_VARIABLE_TYPE;
}
break;
case 3:
if(!obj->symbols[i].n_value)
{
if(
!strncmp(tmp_string,".text",5) ||
!strncmp(tmp_string,".data",5) ||
!strncmp(tmp_string,".rdata",6) ||
!strncmp(tmp_string,".xdata",6) ||
!strncmp(tmp_string,".pdata",6) ||
!strncmp(tmp_string,".bss",4) )
{
ltype = SYMBOL_SECTION_TYPE;
}
}
else
{
if(
!strcmp(tmp_string,".data") ||
!strcmp(tmp_string,".rdata") ||
!strcmp(tmp_string,".xdata") ||
!strcmp(tmp_string,".pdata")
)
{
ltype = SYMBOL_INITIALISED_STATIC_VARIABLE_TYPE;
}
if( !strcmp(tmp_string,".bss") )
{
ltype = SYMBOL_UNINITIALISED_STATIC_VARIABLE_TYPE;
}
}
break;
}
if( ltype == type || (type == SYMBOL_ALL_TYPE))
{
return i;
}
}
else
{
auxcnt--;
}
if(!auxcnt)
auxcnt = obj->symbols[i].n_numaux;
}
return -1;
}
int coff_get_symbol_name(obj_state * obj, int index, char *name)
{
if(index >= obj->file_header.f_nsyms)
return -1;
coff_get_str_symbol_name((char*)&obj->symbols[index].n_name, obj->strings_buffer,obj->string_table_size,name);
return 0;
}
int coff_set_symbol_name(obj_state * obj, int index, char *name)
{
if(index >= obj->file_header.f_nsyms)
return -1;
coff_set_str_symbol_name((char*)&obj->symbols[index].n_name, obj->strings_buffer,obj->string_table_size,name);
obj->modified = 1;
return 0;
}
int coff_update_obj_file(obj_state * object)
{
FILE * out_file;
out_file = NULL;
if(object)
{
if(object->modified)
{
printf("Updating %s ...\n",object->file_path);
out_file = fopen(object->file_path,"rb+");
if(!out_file)
{
printf("ERROR : Can't open output file %s !\n",object->file_path);
goto fatal_error;
}
if(fseek(out_file,object->file_header.f_symptr,SEEK_SET))
{
printf("ERROR : Error while seeking file %s !\n",object->file_path);
goto fatal_error;
}
if(fwrite(object->symbols,sizeof(coff_symbol_table) * object->file_header.f_nsyms,1,out_file) != 1)
{
printf("ERROR : Error while writing file %s !\n",object->file_path);
goto fatal_error;
}
if(fseek(out_file,object->string_table_offset,SEEK_SET))
{
printf("ERROR : Error while seeking file %s !\n",object->file_path);
goto fatal_error;
}
if(fwrite(object->strings_buffer,object->string_table_size,1,out_file) != 1)
{
printf("ERROR : Error while writing file %s !\n",object->file_path);
goto fatal_error;
}
fclose(out_file);
return 1;
}
return 0;
}
fatal_error:
if(out_file)
fclose(out_file);
return -1;
}
void coff_free_obj(obj_state * object)
{
if(object)
{
if(object->file_path)
free(object->file_path);
if(object->strings_buffer)
free(object->strings_buffer);
if(object->symbols)
free(object->symbols);
if(object->sections)
free(object->sections);
free(object);
}
}
|
C
|
#define N 5
#define LEFT (i+N-1)%N
#define RIGHT (i+1)%N
#define THINKING 0
#define HUNGRY 1
#define EATING 2
typedef int semaphore;
int state[N];
semaphore mutex = 1;
semaphore s[N];
void philosopher(int i)
{
while (true)
{
think():
take_forks(i);
eat();
put_forks(i);
}
}
void take_forks(int i)
{
down(&mutex);
state[i] = HUNGRY;
test(i);
up(&mutex);
down(&s[i]);
}
void put_forks(int i)
{
down(&mutex);
state[i] = THINKING;
test(LEFT);
test(RIGHT);
up(&mutex);
}
void test(i)
{
if (state[i] == HUNGRY && state[RIGHT]!=EATING && state[LEFT]!=EATING)
{
state[i] = EATING;
up(&s[i]);
}
}
|
C
|
#include <stdio.h>
void sieve(int a[], int n)
{
int i,j,k;
for(i=3,k=3;i<n/2;i++,k+=2) {
if(a[i]) continue;
for(j=i+k;j<n;j+=k) a[j]=1;
}
printf("2 ");
for(i=3, j=3;i<n;i++,j+=2) {
if(a[i]) continue;
else printf("%d ", j);
}
printf("\n");
}
int main()
{
int a[100]={0};
sieve(a, 99);
}
|
C
|
#include "symbolTable.h"
#include <regex.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void pop_entry(SymbolTable* table)
{
int i;
TableEntry* ptr;
for (i = 0; i < table->position; i++)
{
ptr = table->Entries[i];
if (ptr->level == table->current_level)
{
free(ptr);
if (i < (table->position) - 1)
{
table->Entries[i] = table->Entries[--(table->position)];
i--;
continue;
}
else
{
table->position--;
}
}
}
}
void pop_entry_name(SymbolTable* table, char* name)
{
int i;
TableEntry* ptr;
for (i = 0; i < table->position; i++)
{
ptr = table->Entries[i];
if (ptr->level == table->current_level && strcmp(ptr->name, name) == 0)
{
free(ptr);
if (i < (table->position) - 1)
{
table->Entries[i] = table->Entries[--(table->position)];
i--;
continue;
}
else
{
table->position--;
}
}
}
}
|
C
|
#include <stdio.h>
#include <limits.h>
#include <stdlib.h>
#include <conio.h>
#include "include.h"
struct nodo *raiz = NULL;
struct nodo *fondo = NULL;
void push(int x){
struct nodo * new;
new = malloc(sizeof(struct nodo));
new ->informacion = x;
new-> sig = NULL;
if(is_empty()){
raiz = new;
fondo = new;
}else {
fondo->sig = new;
fondo = new;
}
}
int pop(){
if(!is_empty()){
int informacion = raiz->informacion;
struct nodo * bor = raiz;
if (raiz == fondo) {
raiz=NULL;
fondo=NULL;
}else{
raiz =raiz->sig;
}
free(bor);
return informacion;
}
else
return -1;
}
void display(){
if (!is_empty()){
struct nodo *reco = raiz;
system("cls");
printf("\n\n==========================\n");
printf(" >>listado de la Cola<<\n");
while(reco !=NULL){
printf("%i\n",reco->informacion);
reco=reco->sig;
}
printf("==========================\n");
getch();
}else{
system("cls");
printf("\n\n==========================\n");
printf(" >>La pila esta vacia<<\n");
printf("==========================\n");
getch();
}
}
void destroy(){
struct nodo *reco=raiz;
struct nodo *bor;
while (reco !=NULL){
bor =reco;
reco = reco->sig;
free(bor);
}
}
int peek(){
if(!is_empty()){
int informacion = fondo->informacion;
return informacion;
}
else
return -1;
}
int is_empty(){
if (raiz == NULL)
return 1;
else
return 0;
}
|
C
|
#include "../striVe_defs.h"
// --------------------------------------------------------
/*
GPIO Test
Tests PU and PD on the lower 8 pins while being driven from outside
Tests Writing to the upper 8 pins
Tests reading from the lower 8 pins
*/
void main()
{
int i;
/* Lower 8 pins are input and upper 8 pins are o/p */
reg_gpio_data = 0;
reg_gpio_ena = 0x00ff;
// change the pull up and pull down (checked by the TB)
reg_gpio_data = 0xA000;
reg_gpio_pu = 0x000f;
reg_gpio_pd = 0x00f0;
reg_gpio_data = 0x0B00;
reg_gpio_pu = 0x00f0;
reg_gpio_pd = 0x000f;
reg_gpio_pu = 0x000f;
reg_gpio_pd = 0x00f0;
// read the lower 8 pins, add 1 then o/p the result
// checked by the TB
reg_gpio_data = 0xAB00;
while (1){
int x = reg_gpio_data & 0xff;
reg_gpio_data = (x+1) << 8;
}
}
|
C
|
#ifndef __MAIN_H__
#define __MAIN_H__
/* System Header Files*/
#include <stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<stdbool.h>
#include<string.h>
#include <getopt.h>
#include <stdint.h>
/* Structure to store the input arguments from the terminal */
struct handler
{
char name[19]; // Array to store the Authors name [Suraj Bajrang Thite]
char *input_file; //Pointer for input file name
int f_size; // Size of input file
char *output_file; // Pointer to output file name.
int merge_sort;
int quick_sort;
};
/*
Name : file_to_array
Description : Function to read the unsorted data from file to an array
INput: handler and array where the data is to be stored from the file
Return: -1 if error in opening a file , 0 if data has been sucessfully copied from file to an array
*/
int file_to_array(struct handler handler_t, int buffer[]);
/*
Name : array_to_file
Description : Function to write the sorted data to the file*
INput: handler and array where the data is to be written to the file
Return: -1 if error in opening a file , 0 if data has been sucessfully written from array to the specified file
*/
int array_to_file(struct handler handler_t, int buffer[]);
#endif
|
C
|
#include<stdio.h>
#include<stdlib.h>
int count,top,bottom;
int *stack;
int depth_fs(int **,int *,int,int);
int main()
{
int t,temp;
int **adjacent,*visit;
scanf("%d",&t);
while(t--)
{
int flag=0;
top=0;
bottom=1;
int out=0;
int i,j,n;
temp=0;
scanf("%d",&n);
adjacent=(int **)malloc(sizeof(int *)*n);
visit=(int *)calloc(n,sizeof(int));
stack=(int *)malloc(sizeof(int)*n);
for(i=0;i<n;i++)
{
adjacent[i]=(int *)malloc(sizeof(int)*n);
for(j=0;j<n;j++)
{
scanf("%d",&adjacent[i][j]);
// printf("%d\n",adjacent[i][j]);
}
}
// printf("%d\n",adjacent[2][1]);
// scanf("%d",&v);
// key++;
// queue[key]=v;
for(temp=0;temp!=-1;)
{
count=1;
flag=0;
// printf("Halou\n");
top=0;
bottom=1;
visit[temp]=1;
stack[top]=temp;
depth_fs(adjacent,visit,temp,n);
if(count>out)
{
out=count;
}
for(i=0;i<n;i++)
{
if(visit[i]==0)
{
flag=1;
temp=i;
}
}
if(flag!=1)
{
temp=-1;
}
// printf("1%d\n",temp);
}
printf("%d\n",out);
}
return 0;
}
int depth_fs(int **adjacent,int *visit, int temp,int n)
{
if(top>=bottom)
return;
int j;
for(j=0;j<n;j++)
{
// printf("Halou\n");
if(adjacent[temp][j]==1 && j!=temp && visit[j]==0)
{
printf("Halou\n");
visit[j]=1;
count++;
stack[bottom++]=j;
depth_fs(adjacent,visit,temp,n);
}
}
printf("1 %d\n",count);
bottom = bottom - 1;
}
|
C
|
#include "set.h"
int set_create(set_t* self, int index) {
self-> index = index;
for (int i = 0; i < block_count; i++) {
self->blocks[i] = NULL;
}
return SUCESS;
}
int set_destroy(set_t* self) {
for (int i = 0; i < block_count; i++) {
if (self->blocks[i]) {
block_destroy(self->blocks[i]);
free(self->blocks[i]);
}
}
self->index = -1;
return SUCESS;
}
block_t* set_get_block(set_t* self, int tag) {
for (int i = 0; i < block_count; i++) {
if (self->blocks[i]) {
if (block_get_tag(self->blocks[i]) == tag) {
self->last_recent_used = i;
return self->blocks[i];
}
}
}
return NULL;
}
int set_insert_block(set_t* self, block_t* block) {
for (int i = 0; i < block_count; i++) {
if (!self->blocks[i]) {
self->blocks[i] = (block_t*) malloc(sizeof(block_t));
memcpy(self->blocks[i], block, sizeof(block_t));
self->last_recent_used = i;
return SUCESS;
}
}
// LRU
int index;
if (self->last_recent_used == 0) {
// remplaza el segundo
index = 1;
} else { index = 0; }
// Write Back
if (block_get_dirty_bit(self->blocks[index])) {
// si esta dirty lo escribe en memoria
for (int i = 0; i < block_size; i++) {
// se esbriben 4 bytes comenzando en address con offset 0
int address = metadata_build(block_get_tag(self->blocks[index]), self->index, 0);
block_get_data(self->blocks[index], i, &memory[address]);
}
}
block_destroy(self->blocks[index]);
memcpy(self->blocks[index], block, sizeof(block_t));
return SUCESS;
}
|
C
|
// Shell.
#include "types.h"
#include "user.h"
#include "fcntl.h"
// Parsed command representation
#define EXEC 1
#define REDIR 2
#define PIPE 3
#define LIST 4
#define BACK 5
#define MAXARGS 10
struct cmd {
int type;
};
struct execcmd {
int type;
char *argv[MAXARGS];
char *eargv[MAXARGS];
};
struct redircmd {
int type;
struct cmd *cmd;
char *file;
char *efile;
int mode;
int fd;
};
struct pipecmd {
int type;
struct cmd *left;
struct cmd *right;
};
struct listcmd {
int type;
struct cmd *left;
struct cmd *right;
};
struct backcmd {
int type;
struct cmd *cmd;
};
int cu(int argc, char *argv1, char* argv2);
int fork1(void); // Fork but panics on failure.
void panic(char*);
struct cmd *parsecmd(char*);
// Execute cmd. Never returns.
void
runcmd(struct cmd *cmd)
{
int p[2];
struct backcmd *bcmd;
struct execcmd *ecmd;
struct listcmd *lcmd;
struct pipecmd *pcmd;
struct redircmd *rcmd;
if(cmd == 0)
exit();
switch(cmd->type){
default:
panic("runcmd");
case EXEC:
ecmd = (struct execcmd*)cmd;
if(ecmd->argv[0] == 0)
exit();
exec(ecmd->argv[0], ecmd->argv);
printf(2, "exec %s failed\n", ecmd->argv[0]);
break;
case REDIR:
rcmd = (struct redircmd*)cmd;
close(rcmd->fd);
if(open(rcmd->file, rcmd->mode) < 0){
printf(2, "open %s failed\n", rcmd->file);
exit();
}
runcmd(rcmd->cmd);
break;
case LIST:
lcmd = (struct listcmd*)cmd;
if(fork1() == 0)
runcmd(lcmd->left);
wait();
runcmd(lcmd->right);
break;
case PIPE:
pcmd = (struct pipecmd*)cmd;
if(pipe(p) < 0)
panic("pipe");
if(fork1() == 0){
close(1);
dup(p[1]);
close(p[0]);
close(p[1]);
runcmd(pcmd->left);
}
if(fork1() == 0){
close(0);
dup(p[0]);
close(p[0]);
close(p[1]);
runcmd(pcmd->right);
}
close(p[0]);
close(p[1]);
wait();
wait();
break;
case BACK:
bcmd = (struct backcmd*)cmd;
if(fork1() == 0)
runcmd(bcmd->cmd);
break;
}
exit();
}
int
getcmd(char *buf, int nbuf)
{
getUser();
printf(2, "$ ");//output for shell
memset(buf, 0, nbuf);
gets(buf, nbuf);
if(buf[0] == 0) // EOF
return -1;
return 0;
}
int
main(void)
{
static char buf[100];
int fd;
// Ensure that three file descriptors are open.
while((fd = open("console", O_RDWR)) >= 0){
if(fd >= 3){
close(fd);
break;
}
}
// Login process
static int isLogin = 0;
if (isLogin == 0)
{
char name[64];
char password[64];
do
{
printf(1,"Please enter your user name & password.\n");
printf(1,"User name: ");
gets(name,sizeof(name));
printf(1,"Password: ");
gets(password,sizeof(password));
} while (cu(3,name,password) != 1);
isLogin = 1;
}
// Read and run input commands. (original)
/*
while(getcmd(buf, sizeof(buf)) >= 0){
if(buf[0] == 'c' && buf[1] == 'd' && buf[2] == ' '){
// Chdir must be called by the parent, not the child.
buf[strlen(buf)-1] = 0; // chop \n
if(chdir(buf+3) < 0)
printf(2, "cannot cd %s\n", buf+3);
continue;
}
if(fork1() == 0)
runcmd(parsecmd(buf));
wait();
}
*/
// Read and run input commands.
while(getcmd(buf, sizeof(buf)) >= 0){
if(buf[0] == 'c' && buf[1] == 'd' && buf[2] == ' '){
// Chdir must be called by the parent, not the child.
buf[strlen(buf)-1] = 0; // chop \n
if(chdir(buf+3) < 0)
printf(2, "cannot cd %s\n", buf+3);
continue;
}
if(fork1() == 0)
runcmd(parsecmd(buf));
wait();
}
exit();
}
void
panic(char *s)
{
printf(2, "%s\n", s);
exit();
}
int
fork1(void)
{
int pid;
pid = fork();
if(pid == -1)
panic("fork");
return pid;
}
//PAGEBREAK!
// Constructors
struct cmd*
execcmd(void)
{
struct execcmd *cmd;
cmd = malloc(sizeof(*cmd));
memset(cmd, 0, sizeof(*cmd));
cmd->type = EXEC;
return (struct cmd*)cmd;
}
struct cmd*
redircmd(struct cmd *subcmd, char *file, char *efile, int mode, int fd)
{
struct redircmd *cmd;
cmd = malloc(sizeof(*cmd));
memset(cmd, 0, sizeof(*cmd));
cmd->type = REDIR;
cmd->cmd = subcmd;
cmd->file = file;
cmd->efile = efile;
cmd->mode = mode;
cmd->fd = fd;
return (struct cmd*)cmd;
}
struct cmd*
pipecmd(struct cmd *left, struct cmd *right)
{
struct pipecmd *cmd;
cmd = malloc(sizeof(*cmd));
memset(cmd, 0, sizeof(*cmd));
cmd->type = PIPE;
cmd->left = left;
cmd->right = right;
return (struct cmd*)cmd;
}
struct cmd*
listcmd(struct cmd *left, struct cmd *right)
{
struct listcmd *cmd;
cmd = malloc(sizeof(*cmd));
memset(cmd, 0, sizeof(*cmd));
cmd->type = LIST;
cmd->left = left;
cmd->right = right;
return (struct cmd*)cmd;
}
struct cmd*
backcmd(struct cmd *subcmd)
{
struct backcmd *cmd;
cmd = malloc(sizeof(*cmd));
memset(cmd, 0, sizeof(*cmd));
cmd->type = BACK;
cmd->cmd = subcmd;
return (struct cmd*)cmd;
}
//PAGEBREAK!
// Parsing
char whitespace[] = " \t\r\n\v";
char symbols[] = "<|>&;()";
int
gettoken(char **ps, char *es, char **q, char **eq)
{
char *s;
int ret;
s = *ps;
while(s < es && strchr(whitespace, *s))
s++;
if(q)
*q = s;
ret = *s;
switch(*s){
case 0:
break;
case '|':
case '(':
case ')':
case ';':
case '&':
case '<':
s++;
break;
case '>':
s++;
if(*s == '>'){
ret = '+';
s++;
}
break;
default:
ret = 'a';
while(s < es && !strchr(whitespace, *s) && !strchr(symbols, *s))
s++;
break;
}
if(eq)
*eq = s;
while(s < es && strchr(whitespace, *s))
s++;
*ps = s;
return ret;
}
int
peek(char **ps, char *es, char *toks)
{
char *s;
s = *ps;
while(s < es && strchr(whitespace, *s))
s++;
*ps = s;
return *s && strchr(toks, *s);
}
struct cmd *parseline(char**, char*);
struct cmd *parsepipe(char**, char*);
struct cmd *parseexec(char**, char*);
struct cmd *nulterminate(struct cmd*);
struct cmd*
parsecmd(char *s)
{
char *es;
struct cmd *cmd;
es = s + strlen(s);
cmd = parseline(&s, es);
peek(&s, es, "");
if(s != es){
printf(2, "leftovers: %s\n", s);
panic("syntax");
}
nulterminate(cmd);
return cmd;
}
struct cmd*
parseline(char **ps, char *es)
{
struct cmd *cmd;
cmd = parsepipe(ps, es);
while(peek(ps, es, "&")){
gettoken(ps, es, 0, 0);
cmd = backcmd(cmd);
}
if(peek(ps, es, ";")){
gettoken(ps, es, 0, 0);
cmd = listcmd(cmd, parseline(ps, es));
}
return cmd;
}
struct cmd*
parsepipe(char **ps, char *es)
{
struct cmd *cmd;
cmd = parseexec(ps, es);
if(peek(ps, es, "|")){
gettoken(ps, es, 0, 0);
cmd = pipecmd(cmd, parsepipe(ps, es));
}
return cmd;
}
struct cmd*
parseredirs(struct cmd *cmd, char **ps, char *es)
{
int tok;
char *q, *eq;
while(peek(ps, es, "<>")){
tok = gettoken(ps, es, 0, 0);
if(gettoken(ps, es, &q, &eq) != 'a')
panic("missing file for redirection");
switch(tok){
case '<':
cmd = redircmd(cmd, q, eq, O_RDONLY, 0);
break;
case '>':
cmd = redircmd(cmd, q, eq, O_WRONLY|O_CREATE, 1);
break;
case '+': // >>
cmd = redircmd(cmd, q, eq, O_WRONLY|O_CREATE, 1);
break;
}
}
return cmd;
}
struct cmd*
parseblock(char **ps, char *es)
{
struct cmd *cmd;
if(!peek(ps, es, "("))
panic("parseblock");
gettoken(ps, es, 0, 0);
cmd = parseline(ps, es);
if(!peek(ps, es, ")"))
panic("syntax - missing )");
gettoken(ps, es, 0, 0);
cmd = parseredirs(cmd, ps, es);
return cmd;
}
struct cmd*
parseexec(char **ps, char *es)
{
char *q, *eq;
int tok, argc;
struct execcmd *cmd;
struct cmd *ret;
if(peek(ps, es, "("))
return parseblock(ps, es);
ret = execcmd();
cmd = (struct execcmd*)ret;
argc = 0;
ret = parseredirs(ret, ps, es);
while(!peek(ps, es, "|)&;")){
if((tok=gettoken(ps, es, &q, &eq)) == 0)
break;
if(tok != 'a')
panic("syntax");
cmd->argv[argc] = q;
cmd->eargv[argc] = eq;
argc++;
if(argc >= MAXARGS)
panic("too many args");
ret = parseredirs(ret, ps, es);
}
cmd->argv[argc] = 0;
cmd->eargv[argc] = 0;
return ret;
}
// NUL-terminate all the counted strings.
struct cmd*
nulterminate(struct cmd *cmd)
{
int i;
struct backcmd *bcmd;
struct execcmd *ecmd;
struct listcmd *lcmd;
struct pipecmd *pcmd;
struct redircmd *rcmd;
if(cmd == 0)
return 0;
switch(cmd->type){
case EXEC:
ecmd = (struct execcmd*)cmd;
for(i=0; ecmd->argv[i]; i++)
*ecmd->eargv[i] = 0;
break;
case REDIR:
rcmd = (struct redircmd*)cmd;
nulterminate(rcmd->cmd);
*rcmd->efile = 0;
break;
case PIPE:
pcmd = (struct pipecmd*)cmd;
nulterminate(pcmd->left);
nulterminate(pcmd->right);
break;
case LIST:
lcmd = (struct listcmd*)cmd;
nulterminate(lcmd->left);
nulterminate(lcmd->right);
break;
case BACK:
bcmd = (struct backcmd*)cmd;
nulterminate(bcmd->cmd);
break;
}
return cmd;
}
int cu(int argc, char* argv1, char* argv2)
{
int loginSuccess = 0;
int fd = open("UserList", O_RDONLY);
char *targetUser = argv1;
char nameList[128];
char buf[512];
int checkReadFile = read(fd, buf,sizeof buf);
if(checkReadFile < 0)
{
printf(1,"Can't find user list\n");
}
else
{
int i = 0; // buffer iterator
int n = 0; // name iterator
char c;
do
{
c=buf[i];
i++;
if(c==':')
{
// compare string
//printf(1, "names: %s\n", names);
char* j = targetUser;
char* k = nameList;
while(n > 0 && *j && *j == *k)
{
//printf(1,"n=%d\n",n);
n--;
j++;
k++;
}
if(n == 0)
{
//printf(1, "name found\n");
// add password verification here
char password[128];
int p = 0; // password iterator
do
{
c = buf[i];
i++;
if (c == ':')
{
// compare password string
j = argv2;
k = password;
while (p > 0 && *j && *j == *k)
{
p--;
j++;
k++;
}
if (p == 0)
{
if (argv1[strlen(argv1)-1] == '\n')
{
argv1[strlen(argv1)-1] = '\0';
}
changeUser(argv1);
printf(1,"User changed.\n");
loginSuccess = 1;
}
else
{
printf(1,"Incorrect password. Please try again.\n");
}
break;
}
else
{
password[p] = c;
p++;
}
} while (c != ':');
break;
}
else
{
// skip the password part
do
{
c = buf[i];
i++;
} while (c != ':');
}
n = 0;
}
else
{
//printf(1,"n: %d\n",n);
nameList[n]=c;
n++;
}
}while(c != '\0');
if(c == '\0')
{
printf(1,"User not found\n");
}
}
close(fd);
return loginSuccess;
}
|
C
|
#include<stdio.h>
#define SIZE 5
int main()
{
char aray[SIZE],a;
int pass,temp;
printf("Enter 5 characters : \n");
for(a=0;a<SIZE;++a)
{
scanf("%c",&aray[a]);
}
printf("The characters you entered in ARAY are : \n");
for(a=0;a<SIZE;++a)
{
printf("array[%d]=%c\n",a,aray[a]);
}
for(pass=1;pass<SIZE;++pass)
{
for(a=0;a<SIZE-1;++a)
{
if(aray[a]>aray[a+1])
{
temp=aray[a];
aray[a]=aray[a+1];
aray[a+1]=temp;
}
}
}
for(a=0;a<SIZE;++a)
{
printf("aray[%d]=%c\n",a,aray[a]);
}
}
|
C
|
/*****************************************************************************
* PSRGEOM
* Sam McSweeney, 2018
*
* This program prints out a series of points (in the magnetic frame)
* representing the line of sight as the pulsar rotates.
*
****************************************************************************/
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <math.h>
#include <time.h>
#include "psrgeom.h"
struct opts
{
double al_deg; // alpha angle in deg
double ze_deg; // zeta angle in deg
char *outfile; // name of output file (NULL means stdout)
};
void usage();
void parse_cmd_line( int argc, char *argv[], struct opts *o );
void print_col_headers( FILE *f );
int main( int argc, char *argv[] )
{
// Seed the random number generator
srand( time( NULL ) );
// Generic counter:
int i;
// Set up struct for command line options and set default values
struct opts o;
o.al_deg = NAN;
o.ze_deg = NAN;
o.outfile = NULL;
parse_cmd_line( argc, argv, &o );
// Set up output file
FILE *f;
if (o.outfile == NULL)
f = stdout;
else
{
f = fopen( o.outfile, "w" );
if (f == NULL)
{
fprintf( stderr, "error: could not open file %s\n", o.outfile );
exit(EXIT_FAILURE);
}
}
// Set up pulsar
pulsar psr;
psr_angle al;
psr_angle ze;
set_psr_angle_deg( &al, o.al_deg );
set_psr_angle_deg( &ze, o.ze_deg );
// The following values don't affect the output of this program
double P = 1.0;
double r = 1e4;
set_pulsar( &psr, NULL, NULL, P, r, &al, &ze );
// Write the file header
print_psrg_header( f, argc, argv );
// Write the column headers
print_col_headers( f );
point LoS, LoS_mag;
psr_angle LoS_ph;
for (i = 0; i < 360; i++)
{
// Set up angle
set_psr_angle_deg( &LoS_ph, (double)i );
// Create point in the observer frame, on a unit sphere
set_point_sph( &LoS, 1.0, &(psr.ze), &LoS_ph, POINT_SET_ALL );
// Convert it into the magnetic frame
obs_to_mag_frame( &LoS, &psr, NULL, &LoS_mag );
// Print out the result
fprintf( f, "%.15e %.15e %.15e\n",
LoS_ph.deg,
LoS_mag.th.deg,
LoS_mag.ph.deg );
}
// Clean up
free( o.outfile );
if (o.outfile != NULL)
fclose( f );
return 0;
}
void usage()
{
printf( "usage: psr_visiblepoints [OPTIONS]\n\n" );
printf( "REQUIRED OPTIONS:\n" );
printf( " -a alpha The angle between the rotation axis and the "
"magnetic axis in degrees (required)\n" );
printf( " -z zeta The angle between the rotation axis and the line "
"of sight in degrees (required)\n" );
printf( " -h Display this help and exit\n" );
printf( " -o outfile The name of the output file to write to. If not "
"set, output will be written to stdout.\n" );
}
void parse_cmd_line( int argc, char *argv[], struct opts *o )
{
// Collect the command line arguments
int c;
while ((c = getopt( argc, argv, "a:ho:z:")) != -1)
{
switch (c)
{
case 'a':
o->al_deg = atof(optarg);
break;
case 'h':
usage();
exit(EXIT_SUCCESS);
break;
case 'o':
o->outfile = strdup(optarg);
break;
case 'z':
o->ze_deg = atof(optarg);
break;
case '?':
fprintf( stderr, "error: unknown option character '-%c'\n",
optopt );
exit(EXIT_FAILURE);
break;
default:
fprintf( stderr, "error: couldn't parse command line\n" );
exit(EXIT_FAILURE);
}
}
// Check that all the arguments are valid
if (isnan(o->al_deg) || isnan(o->ze_deg))
{
fprintf( stderr, "error: -a and -z options required"
"\n" );
usage();
exit(EXIT_FAILURE);
}
}
void print_col_headers( FILE *f )
{
// Print out a line to file handle f
fprintf( f, "# phase_deg th_deg ph_deg\n" );
}
|
C
|
/* 48.
Scrivere un programma che, letta una matrice di interi o reali, individui la colonna con somma degli elementi
massima.
*/
#include <stdio.h>
#define LEN 100
int main (int argc, char const *argv[])
{
int colIndex; /* indice della colonna maggiore */
int rows; /* righe di mat */
int cols; /* colonne di mat */
int i, j; /* contatori */
float mat[LEN][LEN]; /* matrice */
float colSumMax; /* somma colonna massima */
float colSum; /* somma colonna singola colonna */
/* inizializzazione rows */
printf ("Numero di righe > ");
scanf ("%d", &rows);
/* inizializzazione cols */
printf ("Numero di colonne > ");
scanf ("%d", &cols);
/* costruzione mat */
for (i = 0; i < rows; i++)
{
for (j = 0; j < cols; j++)
{
printf ("Colonna [%d] Riga [%d] > ", j, i);
scanf ("%f", &mat[i][j]);
}
printf ("\n");
}
/* inizializzazione colSumMax */
for (colSumMax = i = j = 0, colIndex = 1; i < rows; i++)
colSumMax += mat[i][j];
printf ("Colonna 1 >> %.f\n", colSumMax);
/* determinazione colIndex e colSumMax */
for (i = 1; i < cols; i++)
{
for (colSum = j = 0; j < rows; j++)
colSum += mat[j][i];
if (colSum > colSumMax)
{
colSumMax = colSum;
colIndex = i + 1;
}
}
/* stampa mat */
for (i = 0; i < rows; i++)
{
printf ("{");
for (j = 0; j < cols; j++)
{
printf ("%5.1f", mat[i][j]);
}
printf ("};\n");
}
/* esito */
printf ("\n\nColonna maggiore >> %d;", colIndex);
printf ("\nSomma colonna %d >> %.2f;", colIndex, colSumMax);
printf ("\n");
return 0;
}
// Marco Fiorillo 9/07/2021
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* fta_append.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: rnugroho <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2015/12/04 17:53:40 by rnugroho #+# #+# */
/* Updated: 2018/04/15 21:12:10 by rnugroho ### ########.fr */
/* */
/* ************************************************************************** */
#include "ft_array.h"
#include "libft.h"
/*
** Array::apppend
** -
** Could be called "add all" like in Java.
** Adds _datalen_ elements to _self_.
** May fail if malloc does.
** -
** _data_ should be a variable of type T* casted to void*.
** _datalen_ should be the number of elements stored in _data_.
** -
** Returns a status :
** 0 in case of success,
** 1 if malloc failed.
*/
int fta_append(t_array *self, void const *data, size_t datalen)
{
if (fta_reserve(self, datalen))
return (1);
ft_memcpy(ARRAY_END(self), data, ARRAY_OFFSET(self, datalen));
self->size += datalen;
return (0);
}
/*
** Array::apppend_free
** -
** Could be called "add all" like in Java.
** Adds _datalen_ elements to _self_. then free _data_
** May fail if malloc does.
** -
** _data_ should be a variable of type T* casted to void*.
** _datalen_ should be the number of elements stored in _data_.
** -
** Returns a status :
** 0 in case of success,
** 1 if malloc failed.
*/
int fta_append_free(t_array *self, void *data, size_t datalen)
{
if (fta_reserve(self, datalen))
return (1);
ft_memcpy(ARRAY_END(self), data, ARRAY_OFFSET(self, datalen));
self->size += datalen;
free(data);
return (0);
}
/*
** Array::insert
** -
** Adds _datalen_ elements at index _index_ to _self_.
** May fail if malloc does.
** -
** _data_ should be a variable of type T* casted to void*.
** _datalen_ should be the number of elements stored in _data_.
** _index_ is the future index of the first element of _data_.
** -
** Returns a status :
** 0 in case of success,
** 1 if malloc failed or if the index isn't valid.
*/
int fta_insert(
t_array *self, void const *data, size_t datalen, size_t index)
{
if (self->size < index || fta_reserve(self, datalen))
return (1);
ft_memmove(ARRAY_GET(self, index + datalen),
ARRAY_GET(self, index),
ARRAY_OFFSET(self, self->size - index));
ft_memcpy(ARRAY_GET(self, index),
data,
ARRAY_OFFSET(self, datalen));
self->size += datalen;
return (0);
}
/*
** Array::apppend_char
** -
** Could be called "add all" like in Java.
** Adds 1 elements to _self_.
** May fail if malloc does.
** -
** _data_ should be a variable of type char
** -
** Returns a status :
** 0 in case of success,
** 1 if malloc failed.
*/
int fta_append_char(t_array *self, char data)
{
if (fta_reserve(self, 1))
return (1);
ft_memcpy(ARRAY_END(self), &data, ARRAY_OFFSET(self, 1));
self->size += 1;
return (0);
}
|
C
|
// Name - Shubhkarman Sohi
// Student Number - 11219687
// NISD - sss669
#ifndef CGR_PLOT_H
#define CGR_PLOT_H
#include "cgr_aux.h"
//global variable Plot as pointer pointer to char
extern bit** Plot;
/*
* function to print the plot with values from Plot[i][j]
* with bottom left most point to be (0,0) top left most
* top left point(0,1), top right point(1,1) and bottom
* left to be (1,0) as on an ideal graph.
*/
void output_plot(void);
/*
* function to compute the points at which the
* value in Plot to be changed to *
* takes argument one point x or y and returns an unsigned int
* the return value has to be in between 0 and Scale
*/
unsigned scale_coord(coord_t);
/*
* function to change the value Plot to *
* at the points computed by scale_coord
*/
void plot_point(point_t);
#endif
|
C
|
#include "helpers.h"
typedef struct
{
int x, y;
} Node;
void start_game(int len, int n_apples)
{
nib_init();
/*Constants*/
const int screenSize = 50;
const int maxLen = 50;
const int maxApples = 100;
const int sleepTime = 10000;
int currentLength = len;
int direction = 0;
int hit = 0;
int done = 0;
int input = -1;
Node body[maxLen];
Node apples[maxApples];
/*Init snake body*/
int i;
for (i = 0; i < len; i++)
{
body[i].y = screenSize/2;
body[i].x = screenSize/2 - i;
}
/*Init apples*/
for (i = 0; i < n_apples; i++)
{
apples[i].x = rand() % screenSize;
apples[i].y = rand() % screenSize;
}
while(!done)
{
/*Update*/
Node pos = body[0];
if (direction == 0)
{
body[0].x++;
}
else if (direction == 1)
{
body[0].y--;
}
else if (direction == 2)
{
body[0].x--;
}
else if (direction == 3)
{
body[0].y++;
}
/*Collision detection with apples*/
hit = 0;
for (i = 0; i < maxApples; i++)
{
if (apples[i].x == body[0].x &&
apples[i].y == body[0].y )
{
hit = 1;
apples[i].x = rand() % screenSize;
apples[i].y = rand() % screenSize;
break;
}
}
if (hit)
{
body[currentLength] = body[currentLength-1];
}
for (i = 1; i < currentLength; i++)
{
//xor swapping
Node temp;
temp = body[i];
body[i] = pos;
pos = temp;
}
if (hit)
{
currentLength++;
}
/*Collision detection with self*/
for (i = 1; i < currentLength; i++)
{
if (body[i].x == body[0].x &&
body[i].y == body[0].y )
{
done = 1;
break;
}
}
/*Collision detection with walls*/
for (i = 0; i < screenSize; i++)
{
if ((body[0].x == i && (body[0].y == 0 || body[0].y == screenSize)) ||
(body[0].y == i && (body[0].x == 0 || body[0].x == screenSize))
)
{
done = 1;
break;
}
}
/*Draw snake*/
for (i = 0; i < currentLength; i++)
{
nib_put_scr(body[i].x, body[i].y, 'O');
}
/*Draw apples*/
for (i = 0; i < maxApples; i++)
{
nib_put_scr(apples[i].x, apples[i].y, '*');
}
/*Draw game borders*/
for (i = 0; i < screenSize; i++)
{
nib_put_scr(i, 0, '-');
nib_put_scr(i, screenSize, '-');
nib_put_scr(0, i, '|');
nib_put_scr(screenSize, i, '|');
}
/*Get input while sleeping*/
for (i = 0; i < 10; i++)
{
/*Get input*/
input = nib_poll_kbd();
if (input != -1)
{
if (input == 261)
{
direction = 0;
}
else if (input == 259)
{
direction = 1;
}
else if (input == 260)
{
direction = 2;
}
else if (input == 258)
{
direction = 3;
}
break;
}
/*Sleep*/
usleep(sleepTime);
}
usleep(sleepTime*(10-i));
clear();
}
nib_end();
}
|
C
|
#include <stdio.h>
#include <string.h>
#include <stdbool.h>
int lengthofStr(char string[]) {
int len=0;
while(string[len]!='\0')
len++;
return len;
}
bool isPalindrome(char string[]) {
int length=lengthofStr(string)-1;
int start=0;
bool result=true;
while(start<length) {
if (string[start]!=string[length])
{
result=false;
}
start++;
length--;
}
return result;
}
void sub_string(char s[], char sub[], int i, int len){
int j = 0;
while (j < len) {
sub[j] = s[i+j];
j++;
}
sub[j] = '\0';
}
int main()
{
char c[1000],str[100]="hello";
int i, j, len =lengthofStr(str);
for(i = 0; i < len; i++)
{
for(j = 1; j <= len-i; j++)
{
//printf("i=%d, j=%d\n", i,j);
sub_string(str,c,i,j);
if (isPalindrome(c))
{
printf("%s ",c);
}
}
}
return 0;
}
|
C
|
#include <stdio.h>
#include "biblioteca.h"
/** \brief Funcion que pide al usuario ingresar datos y los toma.
*
* \param void No recibe parametros.
* \return int retorna la opcion ingresada por el usuario.
*
*/
int tomarDato(void)
{
int opcion;
printf(" Ingrese una opcion: ");
scanf("%d", & opcion);
return opcion;
}
/** \brief Funcion que pide al usuario ingresar el valor A.
*
* \param void No recibe parametros.
* \return float Retorna el valor A ingresado por el usuario.
*
*/
float operadorA(void)
{
float valorA;
printf(" Ingrese valor A: ");
scanf("%f", & valorA);
return valorA;
}
/** \brief Funcion que pide al usuario ingresar el valor B.
*
* \param void No recibe parametros.
* \return float Retorna el valor A ingresado por el usuario.
*
*/
float operadorB(void)
{
float valorB;
printf(" Ingrese valor B: ");
scanf("%f", & valorB);
return valorB;
}
/** \brief Funcion que suma el valor A y el valor B.
*
* \param x float Representa el valor A.
* \param y float Representa el valor B.
* \return float Retorna el resultado de la suma.
*
*/
float suma(float x, float y)
{
float resultadoSuma;
resultadoSuma = x + y ;
return resultadoSuma;
}
/** \brief Funcion que resta el valor A y el valor B.
*
* \param x float Representa el valor A.
* \param y float Representa el valor B.
* \return float Retorna el resultado de la resta.
*
*/
float resta(float x, float y)
{
float resultadoResta;
resultadoResta = x - y ;
return resultadoResta;
}
/** \brief Funcion que multiplica el valor A por el valor B.
*
* \param x float Representa el valor A.
* \param y float Representa el valor B.
* \return float Retorna el resultado de la multiplicacion.
*
*/
float multiplicacion(float x, float y)
{
float resultadoMulti;
resultadoMulti = x * y ;
return resultadoMulti;
}
/** \brief Funcion que divide el valor A por el valor B.
*
* \param x float Representa el valor A.
* \param y float Representa el valor B.
* \return float Retorna el resultado de la division.
*
*/
float division(float x, float y)
{
float resultadoDiv;
if(y!=0)
{
resultadoDiv = x / y ;
}
else
{
printf(" No es posible dividir por 0\n");
}
return resultadoDiv;
}
/** \brief Funcion que da el factorial del valor A.
*
* \param x float Representa el valor A.
* \return float Retorna el resultado factorial del valor A.
*
*/
float factorialA(float x)
{
float factA;
factA = 1;
float factorialUno;
if (x>=0)
{
for (factorialUno=x; factorialUno>1; factorialUno--)
{
factA =factA*factorialUno;
}
}
return factA;
}
/** \brief Funcion que da el factorial del valor B.
*
* \param y float Representa el valor B.
* \return float Retorna el resultado factorial del valor B.
*
*/
float factorialB(float y)
{
float factB;
factB = 1;
float factorialDos;
if (y>=0)
{
for (factorialDos=y; factorialDos>1; factorialDos--)
{
factB =factB*factorialDos;
}
}
return factB;
}
|
C
|
#include<stdio.h>
void main()
{
int n,i,j,k,m;
printf("enter the value : ");
scanf("%d",&n);
for(i=n;i>=0;i--)
{
for(m=0;m<n+1;m++)
if(i<m)printf(" ");
for(j=i;j>=0;j--)
printf("O");
for(k=i;k>=0;k--)
printf("K");
if(i!=0)
printf("\n");
}
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* fractol_coloring.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: gkessler <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2019/02/02 20:46:25 by gkessler #+# #+# */
/* Updated: 2019/02/03 18:37:10 by gkessler ### ########.fr */
/* */
/* ************************************************************************** */
#include "fractol.h"
int ft_color(t_fr *fr)
{
if (fr->iter > 99)
return (0);
if (fr->iter > 13)
return (16777215);
if (fr->iter > 2 && fr->iter < 13)
return (65535);
if (fr->iter <= 2)
return (255);
return (0);
}
int color2(t_fr *fr)
{
float part;
part = (float)fr->iter / (float)fr->max_iter;
if (part == 1.0)
return (0xFFFFFF);
return ((RGB(100, part * 255, 100)));
}
int fr_coloring2(t_fr *fr)
{
int r;
int g;
int b;
(void)fr->max_iter;
r = 100;
g = (int)(fr->iter * 255.0 / 4.0);
b = 100;
return (RGB(r, g, b));
}
int ft_coloring(t_fr *fr)
{
if (fr->iter == fr->max_iter)
return (0);
else
{
return ((RGB(
127.5 * (cos((double)fr->iter) + 1),
127.5 * (sin((double)fr->iter) + 1),
127.5 * (1 - sin((double)fr->iter)))));
}
}
int ft_coloring_blue_yellow(t_fr *fr)
{
if (fr->iter == fr->max_iter)
return (255);
else
{
return ((RGB(
127.5 * (sin((double)fr->iter) + 1),
127.5 * (sin((double)fr->iter) + 1),
127.5 * (1 - sin((double)fr->iter)))));
}
}
|
C
|
/* Program to implement the shell sort */
#include<stdio.h>
void shell_sort(int nums[], int array_size);
void main(){
int nums[10], i, n;
printf("Enter the number of elements: ");
scanf("%d", &n);
printf("Enter %d elements one by one :", n);
for(i=0; i < n; i++){
scanf("%d", &nums[i]);
}
shell_sort(nums, n);
printf("Sorted list are as follows: ");
for(i=0; i<n; i++){
printf("%d ", nums[i]);
}
printf("\n");
}
void shell_sort(int nums[], int array_size){
int i, j, increment, temp;
increment = 3;
while(increment > 0 ){
for(i=0; i<array_size; i++){
j = i;
temp = nums[i];
while((j >= increment) && (nums[j-increment] > temp)){
nums[j] = nums[j-increment];
j = j-increment;
}
nums[j] = temp;
}
if(increment / 2 != 0 )
increment = increment/2;
else if(increment == 1)
increment = 0;
else
increment = 1;
}
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int totalComparacoes = 0, totalTrocas = 0;
int totalComparacoesSentinel = 0, totalTrocasSentinel = 0;
void imprime_vetor(int *vetor, int tamanho_vetor) {
printf("\nVETOR = {");
for (int x = 0; x < tamanho_vetor; x++) {
printf("%d", vetor[x]);
if (x != tamanho_vetor - 1) printf(",");
if (x == tamanho_vetor - 1) printf("}");
}
printf("\n");
}
void shell_sort_sentinela(int *vetor, int tamanho_vetor) {
int chave = 0, j = 1, h = 1, i = 1, aux = 0, aux2 = 0;
while (h < tamanho_vetor) {
h = 3 * h + 1;
}
while (h > 1) {
h = (h - 1) / 3;
i = h;
while (i < tamanho_vetor) {
aux = vetor[i];
j = i - h;
while (j >= 0 && aux < vetor[j]) {
aux2++;
// comparacao
totalComparacoesSentinel++;
vetor[j + h] = vetor[j];
j = j - h;
}
vetor[j + h] = aux;
// troca
totalTrocasSentinel++;
i++;
}
}
}
void shell_sort(int *vetor, int tamanho_vetor) {
FILE *write;
write = fopen("../resultados/shellSort.json", "w+");
fprintf(write, "%s%s", "{\n\n", " \"estados\": [\n");
int chave = 0, j = 1, h = 1, i = 1, aux = 0, aux2 = 0;
while (h < tamanho_vetor) {
h = 3 * h + 1;
}
while (h > 1) {
h = (h - 1) / 3;
i = h;
while (i < tamanho_vetor) {
aux = vetor[i];
j = i - h;
while (j >= 0 && aux < vetor[j]) {
aux2++;
// comparacao
totalComparacoes++;
fprintf(write, " {");
if (aux2 == 1) {
fprintf(write, " \"estado\": [");
for (int x = 0; x < tamanho_vetor; x++) {
fprintf(write, "%d", vetor[x]);
if (x != tamanho_vetor - 1) fprintf(write, "%s", ",");
}
fprintf(write, "],");
}
fprintf(write, "%s%d%s%d%s", "\"comparacao\":[", i, ",", j,
"]}");
if ((totalComparacoes + totalTrocas) ==
(totalComparacoesSentinel + totalTrocasSentinel)) {
fprintf(write, "%s", "],\n");
} else {
fprintf(write, "%s", ",\n");
}
vetor[j + h] = vetor[j];
j = j - h;
}
vetor[j + h] = aux;
// troca
totalTrocas++;
fprintf(write, " {\"estado\": [");
for (int x = 0; x < tamanho_vetor; x++) {
fprintf(write, "%d", vetor[x]);
if (x != tamanho_vetor - 1) fprintf(write, "%s", ",");
}
fprintf(write, "%s%d%s%d%s", "], \"troca\":[", j + h, ",", i, "]}");
if ((totalComparacoes + totalTrocas) ==
(totalComparacoesSentinel + totalTrocasSentinel)) {
fprintf(write, "%s", "],\n");
} else {
fprintf(write, "%s", ",\n");
}
i++;
}
}
fprintf(write, "%s%d%s", "\t\"totalComparacoes\":", totalComparacoes,
",\n");
fprintf(write, "%s%d%s", "\t\"totalTrocas\":", totalTrocas, "\n");
fprintf(write, "\n}");
}
void readFile(int *values) {
// Abrindo arquivo
FILE *archive;
archive = fopen("dados.dat", "r");
if (!archive) {
printf("Houve um erro ao abrir o arquivo");
} else {
char c;
char aux[30];
int i = 0, w = 0;
// Leitura e armazenamento dos valores
while ((c = fgetc(archive)) != EOF) {
if (c != ',') {
aux[w++] = c;
} else {
values[i] = atoi(aux);
i++;
w = 0;
strcpy(aux, " ");
}
}
values[i] = atoi(aux);
strcpy(aux, " ");
pclose(archive);
}
}
int counter_elements() {
int cont_elements = 1;
// Abrindo arquivo 'dados.dat'
FILE *archive;
archive = fopen("dados.dat", "r");
// Contagem dos números
if (!archive) {
printf("Houve um erro ao abrir o arquivo.\n");
} else {
char c;
while ((c = fgetc(archive)) != EOF) {
if (c == ',') {
cont_elements++;
}
}
}
fclose(archive);
return cont_elements;
}
int main(int argc, char const *argv[]) {
int num_elementos_s = counter_elements();
int *values_s = (int *)malloc(num_elementos_s * sizeof(int));
readFile(values_s);
shell_sort_sentinela(values_s, num_elementos_s);
int num_elementos = counter_elements();
int *values = (int *)malloc(num_elementos * sizeof(int));
readFile(values);
shell_sort(values, num_elementos);
free(values);
free(values_s);
// for (int i = 100; i > 0; i--) {
// printf("%d,", i);
// }
return 0;
}
|
C
|
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
int main(int argc, char **argv)
{
char ch;
int fd,fd0,fd1,fd2;
int tmp;
int tmpFd;
int val = 0;
char retChar[12];
fd = open("/dev/leds", O_RDWR);
fd0 = open("/dev/led0", O_RDWR);
fd1 = open("/dev/led1", O_RDWR);
fd2 = open("/dev/led2", O_RDWR);
printf("JZ2440 leds control\n");
printf("1:all\n");
printf("2:led0\n");
printf("3:led1\n");
printf("4:led2\n");
while( (ch=getchar()) != '\n')
{
tmp = ch-48;
}
if(tmp == 1)
tmpFd = fd;
else if(tmp == 2)
tmpFd = fd0;
else if(tmp == 3)
tmpFd = fd1;
else if(tmp == 4)
tmpFd = fd2;
printf("1.on\n");
printf("2.off\n");
while( (ch=getchar()) != '\n')
{
tmp = ch-48;
}
if(tmp == 1)
val = 1;
else if(tmp == 2)
val = 0;
//write(tmpFd, &val, 4);
ioctl(tmpFd, val ,0);
int ret = read(tmpFd , retChar ,12);
retChar[ret] = '\0';
printf("ret=%d\n",ret);
if(ret == 12)
{
printf("%d %d %d\n",*(int *)retChar,*(int *)(retChar+4),*(int *)(retChar+8));
}
else
{
printf("%d\n",*(int *)retChar);
}
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include "mysql.h"
MYSQL my_connection;
MYSQL_RES *res_ptr;
MYSQL_ROW sqlrow;
// c语言连接MySQL数据库,操作系统linux
int main(int argc,char *argv[]){
int res;
mysql_init(&my_connection);
if(mysql_real_connect(&my_connection,"localhost","root",NULL,"test",0,NULL,0)){
printf("Connection success\n");
res=mysql_query(&my_connection,"select * from a");
if(res){
printf("select error: %s\n",mysql_error(&my_connection));
}else{
res_ptr=mysql_store_result(&my_connection);
if(res_ptr){
printf("Retrieved %lu rows\n",(unsigned long)mysql_num_rows(res_ptr));
while(sqlrow=mysql_fetch_row(res_ptr));
printf("Fetched data...\n");
}
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;
}
|
C
|
#include<stdio.h>
int fibonacci(int n)
{
if (n==0)
{
return 0;
}
else if (n==1)
{
return 1;
}
else
{
return fibonacci(n-1) + fibonacci(n-2);
}
}
void main()
{
int i,n;
printf("Enter the number of terms in the fibonacci series to be printed: ");
scanf("%d",&n);
printf("Fibonacci series:\n");
for(i=0;i<n;i++)
{
printf("%d\n",fibonacci(i));
}
printf("\n");
}
|
C
|
#ifndef __FUNCIONESSTRINGS_H__
#define __FUNCIONESSTRINGS_H__
#include <string.h>
#include "grafo.h"
//dado un nombre y un numero, insertamos en nuestra estructura grafo
//el nombre recibido en la posicion establecida
//la utilizamos para poder recibir strings como nombres de veritices
//y sin problema trabajar con sus posiciones en vez de comparar
//strings en cada momento que tengamos conexiones para verificar donde asignarla
struct grafo* agregar_string(struct grafo* grafo ,char* nombre,int posicion);
//recibimos un string y un grafo en el cual buscaremos donde esta posicionado
//el string dentro de nuestra estructura, que posee un array de strings
//a el indice encontrado se le suma una unidad porque en principio
//desarrolle el programa con posiciones > 0 para ver los indices a partir de 1
int posicion_string(struct grafo* grafo ,char* nombre);
//Recibe un string y cuenta la cantidad de ',' encontradas en el
//En este Trabajo Practico nos sirve porque dado la cantidad de ','
//Podemos adicionarle 3 y ese numero obtenido sera nuestra
//cantidad total de puntos de interseccion de nuestro grafo
int contar_comas(char* puntos);
#endif /* __FUNCIONESSTRINGS_H__ */
|
C
|
#include <stdio.h>
#include <stdbool.h>
#include "Stack.h"
bool StackInit(pSStack stack) {
stack = (pSStack)malloc(sizeof(SStack));
if (stack) {
for (int i = 0; i < MAX_SIZE; i++) {
stack->data[i] = 0;
}
stack->bottom = 0;
stack->top = 0;
stack->length = 0;
return true;
}
else {
return false;
}
}
bool StackDestroy(pSStack stack) {
if (stack && stack->length == 0) {
free(stack);
return true;
}
else {
return false;
}
}
bool StackPush(pSStack stack, int element) {
if (stack->length < MAX_SIZE) {
stack->top++;
stack->data[stack->top] = element;
return true;
}
else {
return false;
}
}
|
C
|
#include "../Entity.h"
#include "../Data.h"
#include "../Globals.h"
#include "../network/Synchronizer.h"
void tickEntityItem(Entity *e, PlayerData *nearestPlayer);
Entity newEntityItem(Item item, int x, int y, int level) {
Entity e;
e.type = ENTITY_ITEM;
e.level = level;
e.entityItem.age = 0;
e.entityItem.item = item;
e.x = x;
e.y = y;
e.xr = 3;
e.yr = 3;
e.canPass = false;
e.tickFunction = &tickEntityItem;
e.entityItem.xx = x;
e.entityItem.yy = y;
e.entityItem.zz = 2;
e.entityItem.xa = gaussrand(false) * 0.1;
e.entityItem.ya = gaussrand(false) * 0.1;
e.entityItem.za = ((float)rand() / RAND_MAX) * 0.45 + 1;
return e;
}
void tickEntityItem(Entity *e, PlayerData *nearestPlayer) {
++e->entityItem.age;
if(e->entityItem.age == 630){
removeEntityFromList(e, e->level, &eManager);
/*
Programming pro tip:
Remember to put a return statement after you remove the entity,
or else your going to have a very bad time like I did.
*/
return;
}
e->entityItem.xx += e->entityItem.xa;
e->entityItem.yy += e->entityItem.ya;
e->entityItem.zz += e->entityItem.za;
if (e->entityItem.zz < 0) {
e->entityItem.zz = 0;
e->entityItem.za *= -0.5;
e->entityItem.xa *= 0.6;
e->entityItem.ya *= 0.6;
}
e->entityItem.za -= 0.15;
int ox = e->x;
int oy = e->y;
int nx = (int) e->entityItem.xx;
int ny = (int) e->entityItem.yy;
int expectedx = nx - e->x;
int expectedy = ny - e->y;
move(e, nx - e->x, ny - e->y);
int gotx = e->x - ox;
int goty = e->y - oy;
e->entityItem.xx += gotx - expectedx;
e->entityItem.yy += goty - expectedy;
}
|
C
|
#include<stdio.h>
int f91(int n);
int main()
{
int num;
while(scanf("%d",&num) == 1) {
if(num == 0)
break;
printf("f91(%d) = %d\n",num,f91(num));
}
return 0;
}
int f91(int n)
{
if(n >= 101)
return n-10;
else
return f91(f91(n+11));
}
|
C
|
#include<stdlib.h>
#include<stdio.h>
struct student{
int code;
int birth;
int grade;
};
struct student fill(struct student student,int code,int birth,int grade){
student.code=code;
student.birth=birth;
student.grade=grade;
return student;
}
void main(void){
struct student student;
student=fill(student,21,1999,100);
printf("%d\t %d\t %d",student.code,student.birth,student.grade);
}
|
C
|
/*
* Tutorial for printf() and scanf() functions
*/
#include <stdio.h>
int main (void)
{
char name[100];
printf("Please enter your name: ");
scanf("%s", name);
printf("Hello %s!\n", name);
}
|
C
|
#include "../headerFiles/keyValueList.h"
int findKV(kvList_t list, string key, kvNode_t** result) {
for (int i = 0; i < list.bufferSize; i++) {
if (list.buffer[i].key.content != NULL && stringCmp(list.buffer[i].key, key) == 0) {
*result = &(list.buffer[i]);
return 0;
}
}
kvNode_t* current = list.additional.next;
while (current != NULL) {
if (stringCmp(current->key, key) == 0) {
*result = current;
return 0;
}
current = current->next;
}
return -1;
}
|
C
|
/******************************************************************************
@file shell_token.c
@brief
DESCRIPTION: utility to extract ash compatible tokens.
<command>[params][operators]
****************************************************************************/
#include <stddef.h>
/* Redirection operators */
enum shell_redir {
SOP_REDIR_NONE,
SOP_REDIR_OUT_APPEND, /* >> */
SOP_REDIR_OUT, /* > */
SOP_REDIR_IN, /* < */
SOP_REDIR_INOUT, /* <> */
};
/* Control operators */
enum shell_operator {
SOP_NONE,
SOP_AND, /* logical && */
SOP_OR, /* logical || */
SOP_BG, /* background */
SOP_PIPE, /* | */
SOP_NEXT, /* ; */
};
/**
* Split a simple form of shell input command string. Given the input string
* mark various offsets for command, parameter and i/o redirection and
* continuation operators.
*
* Form of input string comprises of
* <command> [ params][redirecton][control operators]
*
* Token separator is
* - blanks : spaces and tabs
* - control operators
* {'&', '|', '&&', '||', ';'}
* - redirection operators
* {'>', '>>', '<', '<>'}
*
* Quoting makes an exception to the token separator. Matching
* double quotes or single quotes
*
* USAGE:
*
* const char *cmdb, *cmde, *paramsb, *paramse, *redir_begin, *redir_end;
* const char* context = NULL;
* enum shell_redir r;
* enum shell_operator o;
*
* const char* input = "echo 1 > /dev/foo && echo 2 > /dev/bar";
* do {
* o = shell_command_param_split(input, &cmdb, &cmde, ¶msb, ¶mse, &r, &redir_begin, &redir_end, &context);
* // handle the command
* input = NULL;
* } while (o != SOP_NONE);
*
*
* @param input : input string
* @param cmd_begin
* @param cmd_end
* @param params_begin
* @param params_end
* @param sop_redir
* @param redir_begin
* @param redir_end
* @param context
*
* @return enum shell_operator
*/
enum shell_operator shell_command_param_split(const char* input,
const char** cmd_begin, const char** cmd_end,
const char** params_begin, const char** params_end,
enum shell_redir* sop_redir, const char** redir_begin, const char** redir_end,
const char** context);
/* IMPLEMENTATION */
#define EAT_BLANK(p) while (p && (*p == ' ' || *p == '\t')) p++;
#define GET_CHAR(p, c) while (p && *p && *p != c) p++;
#define GET_SEPER(p) while (p && *p && *p != ' ' && *p != '\t' && *p != '>' && *p != '<' && *p != '|' && *p != '&' && *p != ';') { if (*p == '\"') { p++; GET_CHAR(p, '\"'); if (*p) p++; } else p++; }
enum shell_operator shell_command_param_split(const char* input, const char** cmd_begin, const char** cmd_end,
const char** params_begin, const char** params_end, enum shell_redir* sop_redir, const char** redir_begin,
const char** redir_end, const char** context)
{
enum shell_operator o = SOP_NONE;
const char* cp = (input != NULL) ? input : *context;
*cmd_begin = NULL;
*cmd_end = NULL;
*params_begin = NULL;
*params_end = NULL;
*sop_redir = SOP_REDIR_NONE;
*redir_begin = NULL;
*redir_end = NULL;
EAT_BLANK(cp); /* seek command */
*cmd_end = *cmd_begin = cp; /* initialize command begin and end here */
if (*cp) {
GET_SEPER(cp); /* seek to end of command */
*cmd_end = cp;
if (*cp && *cp == ' ') {
EAT_BLANK(cp); /* seek parameter */
*params_end = *params_begin = cp;
if (*cp) {
GET_SEPER(cp);
*params_end = cp;
while (*cp && *cp == ' ') {
EAT_BLANK(cp); /* seek next */
GET_SEPER(cp);
if (*cp && *cp == ' ') {
*params_end = cp;
}
}
}
}
switch (*cp) {
case '>':
*sop_redir = SOP_REDIR_OUT;
cp++;
if (cp && *cp && *cp == '>') {
*sop_redir = SOP_REDIR_OUT_APPEND;
cp++;
}
break;
case '<':
*sop_redir = SOP_REDIR_IN;
cp++;
if (cp && *cp && *cp == '>') {
*sop_redir = SOP_REDIR_INOUT;
cp++;
}
break;
default:
*sop_redir = SOP_REDIR_NONE;
}
if (*sop_redir != SOP_REDIR_NONE && *cp) {
EAT_BLANK(cp); /* seek */
*redir_end = *redir_begin = cp;
if (*cp) {
GET_SEPER(cp);
*redir_end = cp;
EAT_BLANK(cp);
}
}
switch (*cp) {
case '&':
o = SOP_BG;
cp++;
if (cp && *cp && *cp == '&') {
o = SOP_AND;
cp++;
}
break;
case '|':
o = SOP_PIPE;
cp++;
if (cp && *cp && *cp == '|') {
o = SOP_OR;
cp++;
}
break;
case ';':
o = SOP_NEXT;
cp++;
break;
default:
o = SOP_NONE;
}
}
*context = cp;
return o;
}
#ifdef BUILD_TEST
#if 0
void shell_next_token(const char* input, const char** token_begin, const char** token_end, const char** context)
{
const char* cp = (input != NULL) ? input : *context;
EAT_BLANK(cp); /* seek */
*token_end = *token_begin = cp;
if (*cp) {
GET_SEPER(cp);
*token_end = cp;
}
*context = cp;
}
#endif
#include <stdio.h>
#include <string.h>
#define MAX_CMDS_IN_ONE_INPUT 4
#define MAX_INPUT_BUFSIZ 400
#define MAX_FRAG_BUFSIZ 200
#define NELEMS(x) (sizeof(x) / sizeof((x)[0]))
int main()
{
const char* cmdb;
const char* cmde;
const char* paramsb;
const char* paramse;
enum shell_redir r;
const char* redir_begin;
const char* redir_end;
const char* context = NULL;
enum shell_operator o;
struct {
char input[MAX_INPUT_BUFSIZ];
struct {
char cmd[MAX_FRAG_BUFSIZ];
char params[MAX_INPUT_BUFSIZ];
enum shell_operator oper;
enum shell_redir redir_kind;
char redir[MAX_FRAG_BUFSIZ];
} shell_cmd[MAX_CMDS_IN_ONE_INPUT];
} t[] = {
{"echo 2 > /proc/sys/net/ipv4/conf/bridge0.1/arp_ignore",
{"echo", "2", SOP_NONE, SOP_REDIR_OUT, "/proc/sys/net/ipv4/conf/bridge0.1/arp_ignore"}},
{"", {"", "", SOP_NONE, SOP_REDIR_NONE, ""}}, /* no cmd */
{" ", {"", "", SOP_NONE, SOP_REDIR_NONE, ""}}, /* empty cmd */
{" echo >", {"echo", "", SOP_NONE, SOP_REDIR_OUT, ""}}, /* no param and no redir value */
{" z", {"z", "", SOP_NONE, SOP_REDIR_NONE, ""}},
{" zzz ", {"zzz", "", SOP_NONE, SOP_REDIR_NONE, ""}},
{" zzz z+ ", {"zzz", "z+", SOP_NONE, SOP_REDIR_NONE, ""}},
{" [ hello there ] ", {"[", "hello there ]", SOP_NONE, SOP_REDIR_NONE, ""}},
{" echo hello there ", {"echo", "hello there", SOP_NONE, SOP_REDIR_NONE, ""}},
{"\t echo hello - the=; ", {"echo", "hello - the=", SOP_NEXT, SOP_REDIR_NONE, ""}},
{"\t echo hello - \"the=; \" ", {"echo", "hello - \"the=; \"", SOP_NONE, SOP_REDIR_NONE, ""}},
{" echo hello there > foo.txt ", {"echo", "hello there", SOP_NONE, SOP_REDIR_OUT, "foo.txt"}},
{" echo -ne hello > 1 ", {"echo", "-ne hello", SOP_NONE, SOP_REDIR_OUT, "1"}},
{" echo hello > foo .txt ; ", { "echo", "hello", SOP_NONE, SOP_REDIR_OUT, "foo"}},
{" echo ttha> foo.txt d ", {"echo", "ttha", SOP_NONE, SOP_REDIR_OUT, "foo.txt"}},
{" echo \"hello there\" >foo.txt & ", {"echo", "\"hello there\"", SOP_BG, SOP_REDIR_OUT, "foo.txt"}},
{" echo \"; echo he>l\" >foo.txt 1", {"echo", "\"; echo he>l\"", SOP_NONE, SOP_REDIR_OUT, "foo.txt"}},
{" echo \"\" >", {"echo", "\"\"", SOP_NONE, SOP_REDIR_OUT, ""}}, /* no redir value */
{"|", {"", "", SOP_PIPE, SOP_REDIR_NONE, ""}}, /* empty separator */
{"echo>", {"echo", "", SOP_NONE, SOP_REDIR_OUT, ""}}, /* redir to empty */
{"echo>/dev/null", {"echo", "", SOP_NONE, SOP_REDIR_OUT, "/dev/null"}}, /* no space between separator */
{"echo >> /dev/null && cat foo", {{ "echo", "", SOP_AND, SOP_REDIR_OUT_APPEND, "/dev/null"}, { "cat", "foo", SOP_NONE, SOP_REDIR_NONE, ""}}},
{"more < /dev/null && cat foo", {{"more", "", SOP_AND, SOP_REDIR_IN, "/dev/null"}, { "cat", "foo", SOP_NONE, SOP_REDIR_NONE, ""}}},
{"more <> /dev/null && cat foo", {{"more", "", SOP_AND, SOP_REDIR_INOUT, "/dev/null"}, { "cat", "foo", SOP_NONE, SOP_REDIR_NONE, ""}}},
{"echo 1 > /dev/foo "
" && echo 2 > /dev/bar&&echo 3 >>tree"
"&& cat foo", {{ "echo", "1", SOP_AND, SOP_REDIR_OUT, "/dev/foo"},
{ "echo", "2", SOP_AND, SOP_REDIR_OUT, "/dev/bar"},
{ "echo", "3", SOP_AND, SOP_REDIR_OUT_APPEND, "tree"},
{ "cat", "foo", SOP_NONE, SOP_REDIR_NONE, ""}}},
{"echo dnsmasq --conf-file=/etc/data/dnsmasq.conf"
" --dhcp-leasefile=/var/run/data/dnsmasq.leases"
" --addn-hosts=/etc/data/hosts --pid-file=/var/run/data/dnsmasq.pid"
" -i bridge0 -I lo -z --dhcp-script=/bin/dnsmasq_script.sh type_inst=dnsv4"
" > /var/run/data/dnsmasq_env.conf", {"echo", "dnsmasq --conf-file=/etc/data/dnsmasq.conf --dhcp-leasefile=/var/run/data/dnsmasq.leases"
" --addn-hosts=/etc/data/hosts --pid-file=/var/run/data/dnsmasq.pid -i bridge0 -I lo -z"
" --dhcp-script=/bin/dnsmasq_script.sh type_inst=dnsv4",
SOP_NONE, SOP_REDIR_OUT, "/var/run/data/dnsmasq_env.conf"}},
{"echo QCMAP:qcmap_netlink_thread Entry for pid:922, tid:1035, ppid:1 > /dev/kmsg",
{"echo", "QCMAP:qcmap_netlink_thread Entry for pid:922, tid:1035, ppid:1",
SOP_NONE, SOP_REDIR_OUT, "/dev/kmsg"}},
{"echo 0 > /proc/sys/net/ipv4/conf/bridge5/proxy_arp"
" && echo 0 > /proc/sys/net/ipv4/conf/bridge5/forwarding"
" && echo 1 > /proc/sys/net/ipv4/neigh/default/neigh_probe"
" && echo 1 > /proc/sys/net/ipv6/neigh/default/neigh_probe",
{{ "echo", "0", SOP_AND, SOP_REDIR_OUT, "/proc/sys/net/ipv4/conf/bridge5/proxy_arp"},
{ "echo", "0", SOP_AND, SOP_REDIR_OUT, "/proc/sys/net/ipv4/conf/bridge5/forwarding"},
{ "echo", "1", SOP_AND, SOP_REDIR_OUT, "/proc/sys/net/ipv4/neigh/default/neigh_probe"},
{ "echo", "1", SOP_NONE, SOP_REDIR_OUT, "/proc/sys/net/ipv6/neigh/default/neigh_probe"}}},
};
for (int i = 0; i < NELEMS(t); i++) {
int j = 0;
const char* input = t[i].input;
printf("\n %d : ", i);
do {
o = shell_command_param_split(input, &cmdb, &cmde, ¶msb, ¶mse, &r, &redir_begin, &redir_end, &context);
if (r != SOP_REDIR_NONE) {
printf(" %s %.*s", 0 == strncmp(t[i].shell_cmd[j].cmd, cmdb, cmde - cmdb)
&& 0 == strncmp(t[i].shell_cmd[j].params, paramsb, paramse - paramsb)
&& 0 == strncmp(t[i].shell_cmd[j].redir, redir_begin, redir_end - redir_begin)
&& r == t[i].shell_cmd[j].redir_kind
&& o == t[i].shell_cmd[j].oper ? "PASS" : "FAIL", (int)(redir_end - redir_begin), redir_begin);
}
else {
printf(" %s", 0 == strncmp(t[i].shell_cmd[j].cmd, cmdb, cmde - cmdb) && 0 == strncmp(t[i].shell_cmd[j].params, paramsb, paramse - paramsb) && o == t[i].shell_cmd[j].oper ? "PASS" : "FAIL");
}
input = NULL;
} while (o != SOP_NONE && ++j < MAX_CMDS_IN_ONE_INPUT);
}
return 0;
}
#endif
|
C
|
/**
*
* Take the line
* split the time
* put in format dakika saat * * * play komutu filename
*
*
* /
*/
#include "birdakika.h"
#include "consts.h"
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
void crontab(char* command){
FILE *fptr;
if((fptr = fopen(CRON_FILE_NAME, "a")) == NULL){
perror("Error opening file\n");
return;
}
int min, hour;
char song_path[MAX_LINE];
char real_song_path[MAX_LINE];
char c[MAX_LINE];
char dot;
sscanf(command, "%s %d%c%d %[^\t\n]", c, &hour, &dot, &min, song_path);
if (strncmp("/", song_path, 1) == 0 || strncmp("~", song_path, 1) == 0) {
strcpy(real_song_path, song_path);
}
else {
char cwd[MAX_LINE];
getcwd(cwd, MAX_LINE);
sprintf(real_song_path, "%s/%s", cwd, song_path);
}
fprintf(fptr, "%d %d * * * timeout 60 /usr/bin/mpg321 \"%s\"\n", min, hour, real_song_path);
char cron_command[MAX_LINE];
sprintf(cron_command, "%s %s", "crontab", CRON_FILE_NAME);
char* comm[4] = {"/bin/bash", "-c", cron_command, NULL};
fclose(fptr);
execv("/bin/bash", comm);
}
|
C
|
/**********************************************************************
Dr_VNAF.c:
Dr_VNAF.c is a subroutine to calculate the derivative, with
respect to R, of neutral atom potential of one atom specified
by "Gensi".
Log of Dr_VNAF.c:
22/Nov/2001 Released by T.Ozaki
***********************************************************************/
#include <stdio.h>
#include <math.h>
#include "openmx_common.h"
double Dr_VNAF(int Gensi, double R)
{
int mp_min,mp_max,m,po;
double h1,h2,h3,f1,f2,f3,f4;
double g1,g2,x1,x2,y1,y2,f,df;
double rm,a,b,y12,y22,result;
mp_min = 0;
mp_max = Spe_Num_Mesh_VPS[Gensi] - 1;
if (Spe_VPS_RV[Gensi][Spe_Num_Mesh_VPS[Gensi]-1]<R){
result = 0.0;
}
else if (R<Spe_VPS_RV[Gensi][0]){
po = 1;
m = 4;
rm = Spe_VPS_RV[Gensi][m];
h1 = Spe_VPS_RV[Gensi][m-1] - Spe_VPS_RV[Gensi][m-2];
h2 = Spe_VPS_RV[Gensi][m] - Spe_VPS_RV[Gensi][m-1];
h3 = Spe_VPS_RV[Gensi][m+1] - Spe_VPS_RV[Gensi][m];
f1 = Spe_Vna[Gensi][m-2];
f2 = Spe_Vna[Gensi][m-1];
f3 = Spe_Vna[Gensi][m];
f4 = Spe_Vna[Gensi][m+1];
g1 = ((f3-f2)*h1/h2 + (f2-f1)*h2/h1)/(h1+h2);
g2 = ((f4-f3)*h2/h3 + (f3-f2)*h3/h2)/(h2+h3);
x1 = rm - Spe_VPS_RV[Gensi][m-1];
x2 = rm - Spe_VPS_RV[Gensi][m];
y1 = x1/h2;
y2 = x2/h2;
y12 = y1*y1;
y22 = y2*y2;
f = y22*(3.0*f2 + h2*g1 + (2.0*f2 + h2*g1)*y2)
+ y12*(3.0*f3 - h2*g2 - (2.0*f3 - h2*g2)*y1);
df = 2.0*y2/h2*(3.0*f2 + h2*g1 + (2.0*f2 + h2*g1)*y2)
+ y22*(2.0*f2 + h2*g1)/h2
+ 2.0*y1/h2*(3.0*f3 - h2*g2 - (2.0*f3 - h2*g2)*y1)
- y12*(2.0*f3 - h2*g2)/h2;
a = 0.5*df/rm;
b = f - a*rm*rm;
result = 2.0*a*R;
}
else{
do{
m = (mp_min + mp_max)/2;
if (Spe_VPS_RV[Gensi][m]<R)
mp_min = m;
else
mp_max = m;
}
while((mp_max-mp_min)!=1);
m = mp_max;
if (m<2)
m = 2;
else if (Spe_Num_Mesh_VPS[Gensi]<=m)
m = Spe_Num_Mesh_VPS[Gensi] - 2;
/****************************************************
Spline like interpolation
****************************************************/
h1 = Spe_VPS_RV[Gensi][m-1] - Spe_VPS_RV[Gensi][m-2];
h2 = Spe_VPS_RV[Gensi][m] - Spe_VPS_RV[Gensi][m-1];
h3 = Spe_VPS_RV[Gensi][m+1] - Spe_VPS_RV[Gensi][m];
f1 = Spe_Vna[Gensi][m-2];
f2 = Spe_Vna[Gensi][m-1];
f3 = Spe_Vna[Gensi][m];
f4 = Spe_Vna[Gensi][m+1];
/****************************************************
Treatment of edge points
****************************************************/
if (m==1){
h1 = -(h2+h3);
f1 = f4;
}
if (m==(Spe_Num_Mesh_VPS[Gensi]-1)){
h3 = -(h1+h2);
f4 = f1;
}
/****************************************************
Calculate the value at R
****************************************************/
g1 = ((f3-f2)*h1/h2 + (f2-f1)*h2/h1)/(h1+h2);
g2 = ((f4-f3)*h2/h3 + (f3-f2)*h3/h2)/(h2+h3);
x1 = R - Spe_VPS_RV[Gensi][m-1];
x2 = R - Spe_VPS_RV[Gensi][m];
y1 = x1/h2;
y2 = x2/h2;
f = y2*y2*(3.0*f2 + h2*g1 + (2.0*f2 + h2*g1)*y2)
+ y1*y1*(3.0*f3 - h2*g2 - (2.0*f3 - h2*g2)*y1);
df = 2.0*y2/h2*(3.0*f2 + h2*g1 + (2.0*f2 + h2*g1)*y2)
+ y2*y2*(2.0*f2 + h2*g1)/h2
+ 2.0*y1/h2*(3.0*f3 - h2*g2 - (2.0*f3 - h2*g2)*y1)
- y1*y1*(2.0*f3 - h2*g2)/h2;
result = df;
}
return result;
}
|
C
|
#include <stdio.h>
#include "Lab1_1.h"
void Part1()
{
printf("\nPart 1: Data Type and their Sizes\n");
printf("========================\n");
printf("Byte Size: %lu\n", sizeof(unsigned char));
printf("Short Int Size: %lu\n", sizeof(short int));
printf("Integer Size: %lu\n", sizeof(int));
printf("Long Integer Size: %lu\n", sizeof(long int));
printf("========================\n\n");
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <time.h>
#include <unistd.h>
#include <wiringPi.h>
#include "Nokia/Nokia.h"
#include "Nokia/Images.h"
#define BUF_SIZE 500
/////////////////////////
// Game of Life functions
/////////////////////////
int** gol_alloc_cells(){
int** cells = (int **) malloc(HEIGHT*sizeof(int*));
for(int h=0; h<HEIGHT; h++){
cells[h] = (int *) malloc(WIDTH*sizeof(int));
if(cells[h] == 0){
printf("Error :c could not allocate memory\n");
exit(-1);
}
}
return cells;
}
void gol_whipe_cells(int**cells){
for(int h=0; h<HEIGHT; h++)
for(int w=0; w<WIDTH; w++)
cells[h][w] = 0;
}
void gol_init_cells_rand(int**cells){
for(int h=0; h<HEIGHT; h++)
for(int w=0; w<WIDTH; w++)
cells[h][w] = rand() & 0x1;
}
int gol_count_neighbours(int**cells, int x, int y){
int count = 0;
if(y+1 < HEIGHT) count = (cells[y+1][x])? count+1: count; // Look up
if(y-1 >= 0) count = (cells[y-1][x])? count+1: count; // Look down
if(x+1 < WIDTH) count = (cells[y][x+1])? count+1: count; // Look right
if(x-1 >= 0) count = (cells[y][x-1])? count+1: count; // Look left
if(y+1 < HEIGHT && x+1 < WIDTH) count = (cells[y+1][x+1])? count+1: count; // Look up right
if(y-1 >= 0 && x+1 < WIDTH) count = (cells[y-1][x+1])? count+1: count; // Look down right
if(y+1 < HEIGHT && x-1 >= 0) count = (cells[y+1][x-1])? count+1: count; // Look up left
if(y-1 >= 0 && x-1 >= 0) count = (cells[y-1][x-1])? count+1: count; // Look down left
return count;
}
int gol_next_cell_state(int cell_state, int neighbours_count){
if(neighbours_count >= 4){
return 0;
}
else if(neighbours_count < 2){
return 0;
}
else if(neighbours_count == 3 && cell_state == 0){
return 1;
}
else{
return cell_state;
}
}
void gol_compute_step(int**cells, int**temp_cells){
for(int h=0; h<HEIGHT; h++)
for(int w=0; w<WIDTH; w++)
temp_cells[h][w] = gol_next_cell_state(cells[h][w],gol_count_neighbours(cells, w, h));
for(int h=0; h<HEIGHT; h++)
for(int w=0; w<WIDTH; w++)
cells[h][w] = temp_cells[h][w];
}
void gol_draw_screen(int**cells){
for(int h=0; h<HEIGHT; h++)
for(int w=0; w<WIDTH; w++)
gr_setPixel(cells[h][w], w, h);
}
void gol_print_debug(int**cells){
for(int h=0; h<HEIGHT; h++){
for(int w=0; w<WIDTH; w++)
printf("%c", (cells[h][w])? '#':' ');
printf("\n");
}
}
void gol_print_debug_nei(int**cells){
for(int h=0; h<HEIGHT; h++){
for(int w=0; w<WIDTH; w++)
printf("%d", gol_count_neighbours(cells,w,h));
printf("\n");
}
}
////////////////////////
int main(int argc, char*argv[]) {
wiringPiSetup();
lcdInit();
srand(time(0));
int **gol_cells = gol_alloc_cells();
int **temp_cells = gol_alloc_cells();
gol_init_cells_rand(gol_cells);
gol_print_debug_nei(gol_cells);
gol_draw_screen(gol_cells);
delay(4000);
while(1){
gol_compute_step(gol_cells, temp_cells);
gol_draw_screen(gol_cells);
}
return 0;
}
|
C
|
/******************************************************************************
* Programa: Sudoku
* Programador: Jesus Urrutia (16.073.876-6)
* Ramo: Fundamentos de Programacion
* Profesora: Francia Jimenez
* Comentarios:
* Si bien los numeros del tablero de sudoku son numeros enteros, estos son
* numeros enteros entre el rango 1-9 con lo cual una variable int hubiera sido
* inecesaria ya que no se requiete de 4 bytes para almacenar numeros en ese
* rango, por eso tome la decision de utilizar un arreglo de unsigned char
* que tienen un tamano de 1 byte permitiendome almacenar numeros en el rango
* que necesitaba y me sobraba, lo que al final significa un importante ahorro
* de memoria, tal vez al nivel de este programa no sea significativo ya que el
* arreglo no es relativamente grande y las computadoras de hoy en dia poseen
* suficiente memoria ram, pero me parecio bien introducir esta optimizacion.
*****************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include "librerias/gnrlslib.h"
#include "librerias/mistrlib.h"
#include "librerias/printlib.h"
#include "librerias/sudokulib.h"
int main (){
uchar tablero[N][N][I]; // Tablero de Sudoku
uchar valor = 0, fila = 0, columna = 0; // Variables
uchar mensaje[100]; // Para almacenar y mostrar mensajes de estado
logo_sudoku(); // Mostramos el logo del juego
llenar_tablero(tablero); // Inicializamos la matriz a una matriz nula
sudoku_ini(tablero,4); // Inicializamos el tablero con 4 valores
instrucciones(); // Mostramos las instrucciones
// Comienza el Juego
while(True){
cls(); // Limpiamos la pantalla
mostrar_tablero(tablero); // Mostramos el tablero al usuario
valor = pedir_caracter(); // Solicitamos un valor
if(valor == 's') break; // Respuesta para salir, rompemos el ciclo
else if(valor == 'r'){ // Respuesta para reiniciar
llenar_tablero(tablero);
sudoku_ini(tablero,4);
}else if(valor >= '0' && valor <= '9'){ // Respuesta para ingresar valor
valor = chrtonum(valor); // Convertimos el caracter en numero
fila = pedir_coord("Dame la fila: "); // Solicitamos fila
columna = pedir_coord("Dame la columna: "); // solicitamos columna
if(!error_edicion(tablero,fila,columna)){ // Verificamos que sea una casilla editable
if(valor == 0) fijar_valor(tablero,valor,fila,columna); // Si valor igual a 0 (Borrar casilla) fijamos el valor
else{
if(!val_error_msj(tablero,valor,fila,columna,mensaje)){
fijar_valor(tablero,valor,fila,columna); // Verificamos las reglas, si cumple fijamos
if(tablero_lleno(tablero)){ // Verifico si completo el juego
printf("Felicidades! haz completado el juego!\n");
valor = pregunta_yn("Desea comenzar otra partida?");
if(valor == 'y'){ // Si responde afimativamente, reinicio el tablero
llenar_tablero(tablero);
sudoku_ini(tablero,4);
}else break; // De lo contrario salgo
}
}else{
printf("\n%s",mensaje); // Mostramos el error si es que lo hay
pausa(); // Introduce una pausa a la ejecucion
}
}
}else{
printf("\nError, casilla no editable"); // Mostramos el error si es que lo hay
pausa(); // Introduce una pausa a la ejecucion
}
}else{
printf("\nError, opcion no valida"); // Mostramos el error si es que lo hay
pausa(); // Introduce una pausa a la ejecucion
}
}
return 0;
}
|
C
|
#include <stdio.h>
#include <string.h>
#include <stdbool.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#define MAX_LEN_LINE 100
#define BUFSIZE 10000
int main(void)
{
char argv[MAX_LEN_LINE];
char command[MAX_LEN_LINE];
char *args[] = {command, argv, NULL}; //command ּ, ex /bin/ls
char rootdir[BUFSIZ];
int ret, status;
pid_t pid, cpid;
getcwd(rootdir, sizeof(rootdir));
while (true) {
char *s;
int rd;
int len;
int bufsize;
char buf[BUFSIZE]; // ɰ
char chbuf[BUFSIZE];
getcwd(buf, sizeof(buf));
strcpy(chbuf, buf);
printf("\033[1;32m MyShell: %s $\033[0m", buf);
s = fgets(command, MAX_LEN_LINE, stdin);
// printf("%s", s); ߰
if (s == NULL) {
fprintf(stderr, "fgets failed\n");
exit(1);
}
len = strlen(command);
printf("command length : %d\n", len);
if (command[len - 1] == '\n') {
command[len - 1] = '\0';
}
printf("\033[1;33m [%s]\033[0m\n", command);
if (!strncmp(command, "cd", 2)) {
//printf("")////--------------------------------change directory----------------- buf
if (!strcmp(command, "cd ..")) {
strcat(chbuf, "/..");
rd = chdir(chbuf);
if (!rd)
printf("-- change dir -- \n");
//getcwd(buf, sizeof(buf));
//printf("\033[1;32m)) MyShell: %s $\033[0m\n\n", buf);
}
else {
//strcpy(chbuf, command[3:len]);
for (int i = 3; i < len; i++)
chbuf[i - 3] = command[i];
rd = chdir(chbuf);
if (!rd)
printf("-- change dir -- \n");
else
printf("check your path");
}
}
pid = fork();
if (pid < 0) {
fprintf(stderr, "fork failed\n");
exit(1);
}
if (pid != 0) { /* parent */
if (!strcmp(command, "exit")) {
//printf("")////-----------------exit
printf("exit shell\n");
break;
}
cpid = waitpid(pid, &status, 0); //ڽ ڽ ٷ
if (cpid != pid) {
fprintf(stderr, "waitpid failed\n");
}
printf("Child process terminated\n"); // exitstauts
strcpy(command, "NULL");
strcpy(args[1], "NULL");
if (WIFEXITED(status)) {
printf("Exit status is %d\n", WEXITSTATUS(status));
}
}
else { /* child */
//printf("child process ID : %d", pid);
//-------------------------bj
if (strncmp(command, "ls", 2) == 0) { ////------------------list
if (!strcmp(command, "ls -i")) {
strcat(rootdir, "/list");
strcpy(command, rootdir);
strcpy(args[1], "-i");
printf("1\n");
ret = execve(args[0], args, NULL);
}
if (!strcmp(command, "ls -l")) {
strcat(rootdir, "/list");
strcpy(command, rootdir);
strcpy(args[1], "-l");
printf("2\n");
ret = execve(args[0], args, NULL);
}
if (!strcmp(command, "ls")) {
strcat(rootdir, "/list");
strcpy(command, rootdir);
strcpy(args[1], "NULL");
printf("3\n");
ret = execve(args[0], args, NULL);
}
else
printf("\npress -help for info\n");
}
if (!strcmp(command, "pwd")) { ////-----------------pwd
strcat(rootdir, "/pwd");
strcpy(command, rootdir);
//strcpy(command, "./pwd");
ret = execve(args[0], args, NULL);
strcpy(command, "NULL");
}
if (!strcmp(command, "-help")) { ////-----------------help
strcat(rootdir, "/help");
strcpy(command, rootdir);
//strcpy(command, "./help");
ret = execve(args[0], args, NULL);
strcpy(command, "NULL");
}
if (!strcmp(command, "clear")) {
system("clear");
ret = 0;
}
//else { ////----------------- ʴ°
// ret = execve(args[0], args, NULL);
// printf("\npress -help for info\n");
// strcpy(command, "NULL");
//}
//---------------------------------------------
ret = execve(args[0], args, NULL); // ɾ Է½
if (!strncmp(command, "cd", 2)) {
ret = 0;
printf("ret : %d\n", ret);
}
if (ret < 0) {
printf("\npress -help for info\n");
fprintf(stderr, "execve failed\n");
return 1;
}
}
}
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
#include <time.h>
// Definitions
#define MALLOC_MAX_SIXE 1024
#define SUCCESS (char *)haystack
#define FAILURE (void *)NULL
#define UBUNTU
//#define WINDOWS
// Support functions
void delay(int milliseconds);
int exist(int argc, char** argv, char* item);
int min(int a, int b);
char* connect_strings(char* first, char* second);
char* read_by_terminal(char* input);
char* choppy(char* s);
void check_pip_package_version();
void get_setup();
char *str_replace(char *haystack, size_t haystacksize, const char *oldneedle, const char *newneedle); // By: https://stackoverflow.com/questions/4408170/for-string-find-and-replace
static bool locate_forward(char **needle_ptr, char *read_ptr, const char *needle, const char *needle_last);
static bool locate_backward(char **needle_ptr, char *read_ptr, const char *needle, const char *needle_last);
// Action functions
void help();
void set_verbose();
void version();
void login();
void createstructure();
// Global variables
bool verbose = false;
char* TOKEN;
//char* SOURCES;
char* ORGANIZATION_NAME;
char* IGNORE;
int main(int argc, char **argv)
{
if (exist(argc, argv, "-h") || exist(argc, argv, "--help"))
{
help(argc, argv);
return 0;
}
if (exist(argc, argv, "-v") || exist(argc, argv, "--verbose"))
{
set_verbose();
//return 0;
}
if (exist(argc, argv, "-V") || exist(argc, argv, "--version"))
{
version();
return 0;
}
if (exist(argc, argv, "-l") || exist(argc, argv, "--login"))
{
login();
return 0;
}
// check_pip_package_version(); // Not necessary
get_setup();
createstructure(); // Run core
// End
return 0;
}
void delay(int milliseconds)
{
long pause;
clock_t now,then;
pause = milliseconds*(CLOCKS_PER_SEC/1000);
now = then = clock();
while( (now-then) < pause )
now = clock();
}
int exist (int argc, char **argv, char *item)
{
for (int i = 0; i < argc; ++i)
if (strncmp(argv[i], item, min(strlen(argv[i]), strlen(argv[i]))) == 0)
return i;
return 0;
}
int min(int a, int b)
{
if (a > b)
return a;
return b;
}
char* connect_strings(char* first, char* second)
{
char* final = malloc(strlen(first) + strlen(second) + 1);
strcpy(final, first);
strcat(final, second);
return final;
}
char* read_by_terminal(char* input)
{
FILE *cmd = popen(input, "r");
char *result = malloc(MALLOC_MAX_SIXE); // max return size
char *result2 = malloc(MALLOC_MAX_SIXE); // max return size
result2 = "";
while (fgets(result, sizeof(result), cmd) !=NULL)
result2 = connect_strings(result2, result);
pclose(cmd);
return choppy(result2);
}
char* choppy(char *s)
{
char *n = malloc(MALLOC_MAX_SIXE); // max return size
if( s )
strcpy( n, s );
n[strlen(n)-1]='\0';
return n;
}
void check_pip_package_version()
{
if(read_by_terminal("dpkg -s createstructure | grep -i version | sed 's/Version: //'") != read_by_terminal("pip3 freeze | grep createstructure | sed 's/createstructure==//'"))
{
char* install_string = connect_strings("pip3 install createstructure==", read_by_terminal("dpkg -s createstructure | grep -i version | sed 's/Version: //'"));
if (verbose)
system(install_string);
else
read_by_terminal(install_string);
}
}
char *str_replace(char *haystack, size_t haystacksize,
const char *oldneedle, const char *newneedle)
{
size_t oldneedle_len = strlen(oldneedle);
size_t newneedle_len = strlen(newneedle);
char *oldneedle_ptr; // locates occurences of oldneedle
char *read_ptr; // where to read in the haystack
char *write_ptr; // where to write in the haystack
const char *oldneedle_last = // the last character in oldneedle
oldneedle +
oldneedle_len - 1;
// Case 0: oldneedle is empty
if (oldneedle_len == 0)
return SUCCESS; // nothing to do; define as success
// Case 1: newneedle is not longer than oldneedle
if (newneedle_len <= oldneedle_len) {
// Pass 1: Perform copy/replace using read_ptr and write_ptr
for (oldneedle_ptr = (char *)oldneedle,
read_ptr = haystack, write_ptr = haystack;
*read_ptr != '\0';
read_ptr++, write_ptr++)
{
*write_ptr = *read_ptr;
bool found = locate_forward(&oldneedle_ptr, read_ptr,
oldneedle, oldneedle_last);
if (found) {
// then perform update
write_ptr -= oldneedle_len;
memcpy(write_ptr+1, newneedle, newneedle_len);
write_ptr += newneedle_len;
}
}
*write_ptr = '\0';
return SUCCESS;
}
// Case 2: newneedle is longer than oldneedle
else {
size_t diff_len = // the amount of extra space needed
newneedle_len - // to replace oldneedle with newneedle
oldneedle_len; // in the expanded haystack
// Pass 1: Perform forward scan, updating write_ptr along the way
for (oldneedle_ptr = (char *)oldneedle,
read_ptr = haystack, write_ptr = haystack;
*read_ptr != '\0';
read_ptr++, write_ptr++)
{
bool found = locate_forward(&oldneedle_ptr, read_ptr,
oldneedle, oldneedle_last);
if (found) {
// then advance write_ptr
write_ptr += diff_len;
}
if (write_ptr >= haystack+haystacksize)
return FAILURE; // no more room in haystack
}
// Pass 2: Walk backwards through haystack, performing copy/replace
for (oldneedle_ptr = (char *)oldneedle_last;
write_ptr >= haystack;
write_ptr--, read_ptr--)
{
*write_ptr = *read_ptr;
bool found = locate_backward(&oldneedle_ptr, read_ptr,
oldneedle, oldneedle_last);
if (found) {
// then perform replacement
write_ptr -= diff_len;
memcpy(write_ptr, newneedle, newneedle_len);
}
}
return SUCCESS;
}
}
// locate_forward: compare needle_ptr and read_ptr to see if a match occured
// needle_ptr is updated as appropriate for the next call
// return true if match occured, false otherwise
static inline bool
locate_forward(char **needle_ptr, char *read_ptr,
const char *needle, const char *needle_last)
{
if (**needle_ptr == *read_ptr) {
(*needle_ptr)++;
if (*needle_ptr > needle_last) {
*needle_ptr = (char *)needle;
return true;
}
}
else
*needle_ptr = (char *)needle;
return false;
}
// locate_backward: compare needle_ptr and read_ptr to see if a match occured
// needle_ptr is updated as appropriate for the next call
// return true if match occured, false otherwise
static inline bool
locate_backward(char **needle_ptr, char *read_ptr,
const char *needle, const char *needle_last)
{
if (**needle_ptr == *read_ptr) {
(*needle_ptr)--;
if (*needle_ptr < needle) {
*needle_ptr = (char *)needle_last;
return true;
}
}
else
*needle_ptr = (char *)needle_last;
return false;
}
void get_setup()
{
if (verbose)
puts("\u2139 Getting setup");
#ifdef UBUNTU
TOKEN = read_by_terminal("cat /etc/createstructure.conf | grep 'token' | sed 's/token=//' | sed 's/token= //'");
//SOURCES = read_by_terminal("cat /etc/createstructure.conf | grep 'sources' | sed 's/sources=//' | sed 's/sources= //'");
ORGANIZATION_NAME = read_by_terminal("cat /etc/createstructure.conf | grep 'organization_name' | sed 's/organization_name=//' | sed 's/organization_name= //'");
IGNORE = read_by_terminal("cat /etc/createstructure.conf | grep 'ignore' | sed 's/ignore=//' | sed 's/ignore= //'");
#endif // UBUNTU
#ifdef WINDOWS
char* TO_DELATE = read_by_terminal("powershell -command \"& {echo ''}\"");
TOKEN = read_by_terminal("powershell -command \"& {get-content $Env:HOMEDRIVE\\Progra~1\\createstructure\\createstructure.conf | where { $_ -match 'token'} | %{$_ -replace 'token=',''} | %{$_ -replace 'token= ',''} }\"");
TOKEN = str_replace(TOKEN, sizeof(TOKEN), TO_DELATE, "");
//SOURCES = read_by_terminal("powershell -command \"& {get-content $Env:HOMEDRIVE\\Progra~1\\createstructure\\createstructure.conf | where { $_ -match 'sources'} | %{$_ -replace 'sources=',''} | %{$_ -replace 'sources= ',''} }\"");
//SOURCES = str_replace(SOURCES, sizeof(SOURCES), TO_DELATE, "");
ORGANIZATION_NAME = read_by_terminal("powershell -command \"& {get-content $Env:HOMEDRIVE\\Progra~1\\createstructure\\createstructure.conf | where { $_ -match 'organization_name'} | %{$_ -replace 'organization_name=',''} | %{$_ -replace 'organization_name= ',''} }\"");
ORGANIZATION_NAME = str_replace(ORGANIZATION_NAME, sizeof(ORGANIZATION_NAME), TO_DELATE, "");
IGNORE = read_by_terminal("powershell -command \"& {get-content $Env:HOMEDRIVE\\Progra~1\\createstructure\\createstructure.conf | where { $_ -match 'ignore'} | %{$_ -replace 'ignore=',''} | %{$_ -replace 'ignore= ',''} }\"");
IGNORE = str_replace(IGNORE, sizeof(IGNORE), TO_DELATE, "");
#endif // WINDOWS
}
void help(int argc, char **argv)
{
if (exist(argc, argv, "-v") || exist(argc, argv, "--verbose"))
{
printf("---Help---\n");
#ifdef UBUNTU
printf("Open man...\n");
#endif // UBUNTU
}
#ifdef UBUNTU
system("man createstructure");
#endif // UBUNTU
#ifdef WINDOWS
printf("%s\n\t%s\n\n%s\n\t%s\n\t%s\n\t%s\n\t%s\n\t%s\n\n%s\n\t%s\n\n%s\n\t%s",
"NAME",
"createstructure",
"SYNOPSIS",
"createstructure - runs the creator",
"createstructure [-h | --help] - Help",
"createstructure [-v | --verbose] - You will see more infos",
"createstructure [-V | --version] - Show you the version",
"createstructure [-l | --login] - Do the login (NEEDS ADMINISTRATOR RIGHTS)",
"DESCRIPTION",
"With this programm you can easily create a repository on GitHub with a basic template, personalized for your use.",
"AUTHORS",
"Castellani Davide: owner"
);
#endif // WINDOWS
}
void set_verbose()
{
printf("---Verbose---\n");
verbose = true;
printf("Enabled verbose\n");
}
void version()
{
if (verbose)
printf("---Version---\n");
if (verbose)
#ifdef UBUNTU
system("apt-cache policy createstructure");
#endif // UBUNTU
#ifdef WINDOWS
system("choco outdated | find \"createstructure\"");
#endif // WINDOWS
else
#ifdef UBUNTU
system("dpkg -s createstructure | grep -i version | sed 's/Version: //'");
#endif // UBUNTU
#ifdef WINDOWS
system("choco outdated | find \"createstructure|\"");
#endif // WINDOWS
}
void login()
{
char TEMP_AUTO[50] = {'\0'};
char *TEMP_TOKEN_AUTO = "";
char TEMP_TOKEN[50] = {'\0'};
//char TEMP_SOURCES[200] = {'\0'};
char TEMP_ORGANIZATION_NAME[100] = {'\0'};
char TEMP_IGNORE[100] = {'\0'};
if (verbose)
printf("---Login---\n");
printf("\u2753 Want you use auto-gen token (Max 1 PC for user): ");
scanf("%50s", TEMP_AUTO);
if (!strcmp(TEMP_AUTO, "Y") || !strcmp(TEMP_AUTO, "y") || !strcmp(TEMP_AUTO, "Yes") || !strcmp(TEMP_AUTO, "yes"))
{
// Auto-generate token
char TEMP_CODE[50] = {'\0'};
#ifdef UBUNTU
system("sensible-browser 'https://github.com/login/oauth/authorize?client_id=9cf3c3790cc8c718aada&scope=user%20repo%20admin:org'");
#endif // UBUNTU
#ifdef WINDOWS
system("powershell -command \"& {Start-Process 'https://github.com/login/oauth/authorize?client_id=9cf3c3790cc8c718aada&scope=user%20repo%20admin:org'}\"");
#endif // WINDOWS
printf("\u2753 Insert given token: ");
}
else
{
printf("\u2753 Insert your token: ");
}
scanf("%50s", TEMP_TOKEN);
//printf("\u2753 Insert your sources (format [item1,item2,...]): ");
//scanf("%200s", TEMP_SOURCES);
printf("\u2753 Insert your organization name or 'p' if you want to use your personal account: ");
scanf("%100s", TEMP_ORGANIZATION_NAME);
if (TEMP_ORGANIZATION_NAME[0] == 'p')
TEMP_ORGANIZATION_NAME[0] = '\0';
printf("\u2753 Insert the folder to ignore (format [item1,item2,...]): ");
scanf("%100s", TEMP_IGNORE);
if (verbose)
//printf("\n---Infos---\n\u2139 TOCKEN: %s%s\n\u2139 SOURCES: %s\n\u2139 ORGANIZATION_NAME (empty if you will use your personal account): %s\n\u2139 IGNORE: %s\n", &TEMP_TOKEN, TEMP_TOKEN_AUTO, &TEMP_SOURCES, &TEMP_ORGANIZATION_NAME, &TEMP_IGNORE);
printf("\n---Infos---\n\u2139 TOCKEN: %s%s\n\u2139 ORGANIZATION_NAME (empty if you will use your personal account): %s\n\u2139 IGNORE: %s\n", &TEMP_TOKEN, TEMP_TOKEN_AUTO, &TEMP_ORGANIZATION_NAME, &TEMP_IGNORE);
// Save insert options
char execution_string[2048] = {'\0'};
#ifdef UBUNTU
//sprintf(execution_string, "sudo echo 'token=%s%s\nsources=%s\norganization_name=%s\nignore=%s' > /etc/createstructure.conf", TEMP_TOKEN, TEMP_TOKEN_AUTO, TEMP_SOURCES, TEMP_ORGANIZATION_NAME, TEMP_IGNORE);
sprintf(execution_string, "sudo echo 'token=%s%s\norganization_name=%s\nignore=%s' > /etc/createstructure.conf", TEMP_TOKEN, TEMP_TOKEN_AUTO, TEMP_ORGANIZATION_NAME, TEMP_IGNORE);
#endif // UBUNTU
#ifdef WINDOWS
//sprintf(execution_string, "echo token=%s%s > %HOMEDRIVE%\\Progra~1\\createstructure\\createstructure.conf && echo sources=%s >> %HOMEDRIVE%\\Progra~1\\createstructure\\createstructure.conf && echo organization_name=%s >> %HOMEDRIVE%\\Progra~1\\createstructure\\createstructure.conf && echo ignore=%s >> %HOMEDRIVE%\\Progra~1\\createstructure\\createstructure.conf", TEMP_TOKEN, TEMP_TOKEN_AUTO, TEMP_SOURCES, TEMP_ORGANIZATION_NAME, TEMP_IGNORE);
sprintf(execution_string, "echo token=%s%s > %HOMEDRIVE%\\Progra~1\\createstructure\\createstructure.conf && echo organization_name=%s >> %HOMEDRIVE%\\Progra~1\\createstructure\\createstructure.conf && echo ignore=%s >> %HOMEDRIVE%\\Progra~1\\createstructure\\createstructure.conf", TEMP_TOKEN, TEMP_TOKEN_AUTO, TEMP_ORGANIZATION_NAME, TEMP_IGNORE);
#endif // WINDOWS
system(execution_string);
if (verbose)
printf("%s", "Configuration saved");
}
void createstructure()
{
if (verbose)
printf("---Run-code---\n");
// Compose my string
char execution_string[2048] = {'\0'};
#ifdef UBUNTU
//sprintf (execution_string, "python3 -c \"exec(\\\"from createstructure import createstructure;createstructure()\\\")\" -t=%s -s=%s -o=%s -i=%s %s", TOKEN, SOURCES, ORGANIZATION_NAME, IGNORE, (verbose ? "-v" : ""));
sprintf (execution_string, "python3 -c \"exec(\\\"from createstructure import createstructure;createstructure()\\\")\" -t=%s -o=%s -i=%s %s", TOKEN, ORGANIZATION_NAME, IGNORE, (verbose ? "-v" : ""));
#endif // UBUNTU
#ifdef WINDOWS
//sprintf (execution_string, "python.exe -c \"exec(\\\"from createstructure import createstructure;createstructure()\\\")\" -t=%s -s=%s -o=%s -i=%s %s", TOKEN, SOURCES, ORGANIZATION_NAME, IGNORE, (verbose ? "-v" : ""));
sprintf (execution_string, "python.exe -c \"exec(\\\"from createstructure import createstructure;createstructure()\\\")\" -t=%s -o=%s -i=%s %s", TOKEN, ORGANIZATION_NAME, IGNORE, (verbose ? "-v" : ""));
#endif // WINDOWS
if (verbose)
printf("%s\n", execution_string);
system(execution_string);
}
|
C
|
/*
* Copyright (c) 2022 HPMicro
*
* SPDX-License-Identifier: BSD-3-Clause
*
*/
#include "hpm_mchtmr_drv.h"
void mchtmr_init_counter(MCHTMR_Type *ptr, uint64_t v)
{
volatile uint32_t *p = (volatile uint32_t *) &ptr->MTIME;
/*
* When [31:29] == 7, low 32 bits need to be set to 0 first,
* then set high 32 bits and low 32 bits; otherwise,
* low 32 bit can be set firstly then high 32 bits.
*/
if ((v & 0xE0000000) == 0xE0000000) {
*p = 0;
*(p + 1) = v >> 32;
*p = v & 0xFFFFFFFF;
} else {
*p = v & 0xFFFFFFFF;
*(p + 1) = v >> 32;
}
}
|
C
|
// AsyncHTTPRequest request;
#include <ESPAsyncTCP.h>
#define SERVER_HOST_NAME "161.35.28.53"
#define TCP_PORT 3500
static void replyToServer(void* arg) {
AsyncClient* client = reinterpret_cast<AsyncClient*>(arg);
// send reply
if (client->space() > 32 && client->canSend()) {
char message[32];
sprintf(message, "this is from %s", WiFi.localIP().toString().c_str());
client->add(message, strlen(message));
client->send();
}
}
static void handleData(void *arg, AsyncClient *client, void *data, size_t len)
{
Serial.printf("\n data received from %s \n", client->remoteIP().toString().c_str());
Serial.write((uint8_t *)data, len);
}
void onConnect(void *arg, AsyncClient *client)
{
Serial.printf("\n client has been connected to %s on port %d \n", SERVER_HOST_NAME, TCP_PORT);
replyToServer(client);
}
void logger_logDataToserver(String body)
{
AsyncClient *client = new AsyncClient;
client->onData(&handleData, client);
client->onConnect(&onConnect, client);
client->connect(SERVER_HOST_NAME, TCP_PORT);
// request.setDebug(false);
// request.onReadyStateChange([](void *optParm, AsyncHTTPRequest *request, int readyState) {
// Serial.println('[REQUEST STATE CHANGE CALLBACK]');
// if (readyState == readyStateDone)
// {
// Serial.println("\n**************************************");
// Serial.println(request->responseText());
// Serial.println("**************************************");
// request->setDebug(false);
// }
// });
// Serial.println("[BODY TO BE SENT]: " + body);
// request.open("GET", "http://161.35.28.53/");
// request.send();
}
|
C
|
/*
* Academic License - for use in teaching, academic research, and meeting
* course requirements at degree granting institutions only. Not for
* government, commercial, or other organizational use.
* File: cholesky.c
*
* MATLAB Coder version : 4.3
* C/C++ source code generated on : 10-Feb-2020 20:17:58
*/
/* Include Files */
#include "cholesky.h"
#include <math.h>
#include <string.h>
/* Function Definitions */
/*
* Returns the Cholesky decomposition of a Hermitian
* positive-definite matrix A
* Arguments : const double A_data[]
* const int A_size[2]
* double R_data[]
* int R_size[2]
* Return Type : void
*/
void cholesky(const double A_data[], const int A_size[2], double R_data[], int
R_size[2])
{
int jmax;
int n;
int info;
int j;
boolean_T exitg1;
int idxAjj;
double ssq;
int ix;
int iy;
int i;
int idxAjp1j;
int b_i;
int iac;
double c;
int i1;
int ia;
R_size[0] = A_size[0];
R_size[1] = A_size[1];
jmax = A_size[0] * A_size[1];
if (0 <= jmax - 1) {
memcpy(&R_data[0], &A_data[0], jmax * sizeof(double));
}
n = A_size[1];
if (A_size[1] != 0) {
info = 0;
j = 0;
exitg1 = false;
while ((!exitg1) && (j <= n - 1)) {
idxAjj = j + j * n;
ssq = 0.0;
if (j >= 1) {
ix = j;
iy = j;
for (jmax = 0; jmax < j; jmax++) {
ssq += R_data[ix] * R_data[iy];
ix += n;
iy += n;
}
}
ssq = R_data[idxAjj] - ssq;
if (ssq > 0.0) {
ssq = sqrt(ssq);
R_data[idxAjj] = ssq;
if (j + 1 < n) {
jmax = (n - j) - 1;
i = j + 2;
idxAjp1j = idxAjj + 2;
if ((jmax != 0) && (j != 0)) {
ix = j;
b_i = (j + n * (j - 1)) + 2;
for (iac = i; n < 0 ? iac >= b_i : iac <= b_i; iac += n) {
c = -R_data[ix];
iy = idxAjj + 1;
i1 = (iac + jmax) - 1;
for (ia = iac; ia <= i1; ia++) {
R_data[iy] += R_data[ia - 1] * c;
iy++;
}
ix += n;
}
}
ssq = 1.0 / ssq;
b_i = idxAjj + jmax;
for (jmax = idxAjp1j; jmax <= b_i + 1; jmax++) {
R_data[jmax - 1] *= ssq;
}
}
j++;
} else {
R_data[idxAjj] = ssq;
info = j + 1;
exitg1 = true;
}
}
if (info == 0) {
jmax = A_size[1];
} else {
jmax = info - 1;
}
for (j = 2; j <= jmax; j++) {
for (i = 0; i <= j - 2; i++) {
R_data[i + R_size[0] * (j - 1)] = 0.0;
}
}
}
}
/*
* Arguments : void
* Return Type : void
*/
void cholesky_initialize(void)
{
}
/*
* Arguments : void
* Return Type : void
*/
void cholesky_terminate(void)
{
/* (no terminate code required) */
}
/*
* File trailer for cholesky.c
*
* [EOF]
*/
|
C
|
#include <vitasdk.h>
#include "font.h"
int vsnprintf(char *s, size_t n, const char *format, va_list arg);
#define MAX_STRING_LENGTH 512
static SceDisplayFrameBuf frameBuf;
static uint8_t fontScale = 1;
static uint32_t colorFg = 0xFFFFFFFF;
static uint32_t colorBg = 0xFF000000;
uint32_t osdBlendColor(uint32_t fg, uint32_t bg) {
unsigned int alpha = ((fg >> 24) & 0xFF) + 1;
unsigned int inv_alpha = 256 - ((fg >> 24) & 0xFF);
uint32_t result = 0;
result |= ((alpha * (fg & 0xFF) + inv_alpha * (bg & 0xFF)) >> 8) & 0xFF;
result |= (((alpha * ((fg >> 8) & 0xFF) + inv_alpha * ((bg >> 8) & 0xFF)) >> 8) & 0xFF) << 8;
result |= (((alpha * ((fg >> 16) & 0xFF) + inv_alpha * ((bg >> 16) & 0xFF)) >> 8) & 0xFF) << 16;
result |= 0xFF << 24;
return result;
}
void osdUpdateFrameBuf(const SceDisplayFrameBuf *pParam) {
memcpy(&frameBuf, pParam, sizeof(SceDisplayFrameBuf));
}
void osdSetTextColor(uint8_t r, uint8_t g, uint8_t b, uint8_t a) {
colorFg = (a << 24) + (b << 16) + (g << 8) + r;
}
void osdSetBgColor(uint8_t r, uint8_t g, uint8_t b, uint8_t a) {
colorBg = (a << 24) + (b << 16) + (g << 8) + r;
}
void osdSetTextScale(uint8_t scale) {
fontScale = scale;
}
uint32_t osdGetTextWidth(const char *str) {
return strlen(str) * FONT_WIDTH * fontScale;
}
void osdClearScreen() {
if (!((colorBg >> 24) & 0xFF)) // alpha == 0
return;
if (((colorBg >> 24) & 0xFF) == 0xFF) { // alpha == 255
memset(frameBuf.base, colorBg, sizeof(uint32_t) * (frameBuf.pitch * frameBuf.height));
} else {
for (int y = 0; y < frameBuf.height; y++) {
for (int x = 0; x < frameBuf.width; x++) {
uint32_t *frameBufPtr = (uint32_t *)frameBuf.base + y * frameBuf.pitch + x;
*frameBufPtr = osdBlendColor(colorBg, *frameBufPtr);
}
}
}
}
void osdDrawCharacter(int character, int x, int y) {
for (int yy = 0; yy < FONT_HEIGHT * fontScale; yy++) {
int yy_font = yy / fontScale;
uint32_t displacement = x + (y + yy) * frameBuf.pitch;
uint32_t *screenPos = (uint32_t *)frameBuf.base + displacement;
if (displacement >= frameBuf.pitch * frameBuf.height)
return; // out of bounds
for (int xx = 0; xx < FONT_WIDTH * fontScale; xx++) {
if (x + xx >= frameBuf.width)
return; // oob
// Get px 0/1 from font.h
int xx_font = xx / fontScale;
uint32_t charPos = character * (FONT_HEIGHT * ((FONT_WIDTH / 8) + 1));
uint32_t charPosH = charPos + (yy_font * ((FONT_WIDTH / 8) + 1));
uint8_t charByte = font[charPosH + (xx_font / 8)];
uint32_t clr = ((charByte >> (7 - (xx_font % 8))) & 1) ? colorFg : colorBg;
if ((clr >> 24) & 0xFF) { // alpha != 0
if (((clr >> 24) & 0xFF) != 0xFF) { // alpha < 0xFF
*(screenPos + xx) = osdBlendColor(clr, *(screenPos + xx)); // blend FG/BG color
} else {
*(screenPos + xx) = clr;
}
}
}
}
}
void osdDrawString(int x, int y, const char *str) {
for (size_t i = 0; i < strlen(str); i++)
osdDrawCharacter(str[i], x + i * FONT_WIDTH * fontScale, y);
}
void osdDrawStringF(int x, int y, const char *format, ...) {
char buffer[MAX_STRING_LENGTH] = "";
va_list va;
va_start(va, format);
vsnprintf(buffer, MAX_STRING_LENGTH, format, va);
va_end(va);
osdDrawString(x, y, buffer);
}
|
C
|
#ifndef ARCA_STONE_H
#define ARCA_STONE_H
enum stone {
S_NONE,
S_BLACK,
S_WHITE,
S_OFFBOARD,
S_MAX,
};
static char stone2char(enum stone s);
static enum stone char2stone(char s);
char *stone2str(enum stone s); /* static string */
enum stone str2stone(char *str);
static enum stone stone_other(enum stone s);
static inline char
stone2char(enum stone s)
{
return ".XO#"[s];
}
static inline enum stone
char2stone(char s)
{
switch (s) {
case '.': return S_NONE;
case 'X': return S_BLACK;
case 'O': return S_WHITE;
case '#': return S_OFFBOARD;
}
return S_NONE; // XXX
}
/* 奇怪的是,gcc不愿意内联这个;我已经确认有性能上的好处。 */
static inline enum stone __attribute__((always_inline))
stone_other(enum stone s)
{
static const enum stone o[S_MAX] = { S_NONE, S_WHITE, S_BLACK, S_OFFBOARD };
return o[s];
}
#endif
|
C
|
#include "my_server.h"
#include "my.h"
#include "xlib.h"
#include "buf_size.h"
void set_other(char *abso, int i, mode_t *mode)
{
if (abso[i] == '1')
*mode |= S_IXOTH;
if (abso[i] == '2')
*mode |= S_IWOTH;
if (abso[i] == '4')
*mode |= S_IROTH;
if (abso[i] == '5')
*mode |= (S_IROTH | S_IXOTH);
if (abso[i] == '6')
*mode |= (S_IROTH | S_IWOTH);
if (abso[i] == '7')
*mode |= S_IRWXO;
}
void set_group(char *abso, int i, mode_t *mode)
{
if (abso[i] == '1')
*mode |= S_IXGRP;
if (abso[i] == '2')
*mode |= S_IWGRP;
if (abso[i] == '4')
*mode |= S_IRGRP;
if (abso[i] == '5')
*mode |= (S_IRGRP | S_IXGRP);
if (abso[i] == '6')
*mode |= (S_IRGRP | S_IWGRP);
if (abso[i] == '7')
*mode |= S_IRWXG;
}
void set_owner(char *abso, int i, mode_t *mode)
{
if (abso[i] == '1')
*mode |= S_IXUSR;
if (abso[i] == '2')
*mode |= S_IWUSR;
if (abso[i] == '4')
*mode |= S_IRUSR;
if (abso[i] == '5')
*mode |= (S_IRUSR | S_IXUSR);
if (abso[i] == '6')
*mode |= (S_IRUSR | S_IWUSR);
if (abso[i] == '7')
*mode |= S_IRWXU;
}
int find_chmod(char *abso, int *i, struct s_static_socket *br, mode_t *mode)
{
if ((abso[*i] < '0' || abso[*i] > '7')
|| (abso[*i + 1] < '0' || abso[*i + 1] > '7')
|| (abso[*i + 2] < '0' || abso[*i + 2] > '7'))
{
xwrite(br->cs, "501 Syntax error\n", 17);
return (-1);
}
set_owner(abso, *i, mode);
set_group(abso, *i + 1, mode);
set_other(abso, *i + 2, mode);
return (0);
}
int get_chmod(mode_t *mode, char *abso, int *i, struct s_static_socket *br)
{
if (my_strlen(&(abso[*i])) < 3)
{
xwrite(br->cs, "501 Syntax error\n", 17);
return (-1);
}
if (find_chmod(abso, i, br, mode) == -1)
return (-1);
*i = *i + 3;
if (abso[*i] != ' ')
{
xwrite(br->cs, "501 Syntax error\n", 17);
return (-1);
}
return (0);
}
|
C
|
#define NULL ((void*)0)
typedef unsigned long size_t; // Customize by platform.
typedef long intptr_t; typedef unsigned long uintptr_t;
typedef long scalar_t__; // Either arithmetic or pointer type.
/* By default, we understand bool (as a convenience). */
typedef int bool;
#define false 0
#define true 1
/* Forward declarations */
typedef struct TYPE_12__ TYPE_3__ ;
typedef struct TYPE_11__ TYPE_2__ ;
typedef struct TYPE_10__ TYPE_1__ ;
/* Type definitions */
typedef int /*<<< orphan*/ cmsCIExyY ;
struct TYPE_10__ {double X; double Y; double Z; } ;
typedef TYPE_1__ cmsCIEXYZ ;
struct TYPE_11__ {double L; double a; double b; } ;
typedef TYPE_2__ cmsCIELab ;
struct TYPE_12__ {double L; double C; double h; } ;
typedef TYPE_3__ cmsCIELCh ;
/* Variables and functions */
int /*<<< orphan*/ cmsLab2LCh (TYPE_3__*,TYPE_2__*) ;
int /*<<< orphan*/ cmsXYZ2Lab (int /*<<< orphan*/ *,TYPE_2__*,TYPE_1__*) ;
int /*<<< orphan*/ cmsXYZ2xyY (int /*<<< orphan*/ *,TYPE_1__*) ;
scalar_t__ lShowLCh ;
scalar_t__ lShowLab ;
scalar_t__ lShowXYZ ;
int /*<<< orphan*/ printf (char*,double,...) ;
double sqrt (int) ;
__attribute__((used)) static
void ShowWhitePoint(cmsCIEXYZ* WtPt)
{
cmsCIELab Lab;
cmsCIELCh LCh;
cmsCIExyY xyY;
cmsXYZ2Lab(NULL, &Lab, WtPt);
cmsLab2LCh(&LCh, &Lab);
cmsXYZ2xyY(&xyY, WtPt);
if (lShowXYZ) printf("XYZ=(%3.1f, %3.1f, %3.1f)\n", WtPt->X, WtPt->Y, WtPt->Z);
if (lShowLab) printf("Lab=(%3.3f, %3.3f, %3.3f)\n", Lab.L, Lab.a, Lab.b);
if (lShowLCh) printf("LCh=(%3.3f, %3.3f, %3.3f)\n", LCh.L, LCh.C, LCh.h);
{
double Ssens = (LCh.C * 100.0 )/ sqrt(LCh.C*LCh.C + LCh.L * LCh.L) ;
printf("Sens = %f\n", Ssens);
}
}
|
C
|
#include<stdio.h>
#include<stdlib.h>
int data;
void display();
struct node
{
int info;
struct node *next;
}*start=NULL;
void add_beg()
{
printf("\nEnter element to add ");
scanf("%d",&data);
struct node *newnode;
newnode=(struct node*)malloc(sizeof(struct node));
newnode->info=data;
newnode->next=start;
start=newnode;
display();
}
void add_end()
{
printf("\nEnter element to add ");
scanf("%d",&data);
struct node *temp;
struct node *newnode;
newnode=(struct node*)malloc(sizeof(struct node));
newnode->info=data;
newnode->next=NULL;
temp=start;
while(temp->next!=NULL)
{
temp=temp->next;
}
temp->next=newnode;
display();
}
void del_beg()
{
struct node *temp;
temp=start;
start=start->next;
free(temp);
display();
}
void del_end()
{
struct node *temp,*ptr;
temp=start;
while(temp->next->next!=NULL)
temp=temp->next;
ptr=temp->next;
temp->next=NULL;
free(ptr);
display();
}
void display()
{
struct node *temp;
temp=start;
if(start==NULL)
printf("list is empty");
else
while(temp!=NULL)
{
printf("\ndata=%d\tpresent add=%u\tnext add=%u\n",temp->info,temp,temp->next);
temp=temp->next;
}
}
void search()
{
int key;
printf("Element to be searched");
scanf("%d",&key);
struct node *temp;
temp=start;
if(start==NULL)
printf("list is empty");
else
while(temp->info!=key)
{
temp=temp->next;
}
printf("Element found at present add=%u",temp);
}
int main()
{
int a;
while(1)
{
printf("\n1.Add at beginning\n2.Add at end\n3.Delete from beginning\n4.Delete from end\n5.Search\nEnter choice ");
scanf("%d",&a);
switch(a)
{
case 1:add_beg();
break;
case 2:add_end();
break;
case 3:del_beg();
break;
case 4:del_end();
break;
case 5:search();
break;
}
}
}
|
C
|
#include <stdio.h>
#include "./recognition.h"
#include "./resample/resample.h"
#include "./params.h"
#include "./util/io.h"
void outputFaceIndex(int faceIndex) {
printf("face index: %d\n", faceIndex);
}
int main() {
// read input image size
int imgSizes[2];
readInts("../data/input_size.txt", 2, imgSizes);
int imgR = imgSizes[0];
int imgC = imgSizes[1];
// read input image
int inputImg[imgR * imgC];
readImg(imgR, imgC, "../data/input.txt", inputImg);
// resample input image
int resizedInput[imgLen];
resample(imgR, imgC, inputImg, resizedInput);
// read training set size
int trainingSetSize = readInt("../data/training_count.txt");
int faceIndex = recognizeImage(resizedInput);
// output result
outputFaceIndex(faceIndex);
return 0;
}
|
C
|
#include <string.h>
#include "utils.h"
short sfabs(short i)
{
return (i > 0) ? i : -i;
}
/* Source: Wikipédia */
/* reverse: reverse string s in place */
void reverse(char s[])
{
int i, j;
char c;
for (i = 0, j = strlen(s) - 1; i < j; i++, j--)
{
c = s[i];
s[i] = s[j];
s[j] = c;
}
}
/* Source: Wikipédia */
/* itoa: convert n to characters in s */
void itoa(int n, char s[])
{
int i, sign;
if ((sign = n) < 0) /* record sign */
n = -n; /* make n positive */
i = 0;
do /* generate digits in reverse order */
{
s[i++] = n % 10 + '0'; /* get next digit */
} while ((n /= 10) > 0); /* delete it */
if (sign < 0)
s[i++] = '-';
s[i] = '\0';
reverse(s);
}
int only_numbers(const char* str, char eol)
{
int i = 0;
while (str[i] != eol)
{
if (str[i] < '0' || str[i] > '9')
return 0;
i++;
}
return 1;
}
int str_to_int(const char* str, char eol)
{
int value = 0, i = 0, tmp;
while (str[i] != eol)
{
tmp = str[i];
if (str[i] <= '9' && str[i] >= '0')
tmp -= '0';
else if (str[i] <= 'F' && str[i] >= 'A')
tmp = tmp - 'A' + 10;
else if (str[i] <= 'f' && str[i] >= 'a')
tmp = tmp - 'a' + 10;
value = 16 * value + tmp;
i++;
}
return value;
}
int char33_to_int(char c)
{
if (c >= '0' && c <= '9')
return c - '0';
else if (c >= 'A' && c <= 'W')
return c - 'A' + 10;
else if (c >= 'a' && c <= 'w')
return c - 'a' + 10;
return 0;
}
char hex_to_char(char hex)
{
if (hex >= 0 && hex < 10)
return hex + '0';
else if (hex >= 10 && hex < 16)
return hex - 10 + 'A';
return 0;
}
void str_to_hex_str(char* hex_str, const char* str, int limit)
{
int i = 0;
while (str[i] != 0)
{
if (2 * i + 1 > limit)
return;
hex_str[2 * i + 0] = hex_to_char((str[i] & 0xf0) >> 4);
hex_str[2 * i + 1] = hex_to_char(str[i] & 0x0f);
i++;
}
}
int atoi(char* s)
{
int val = 0;
int sign = 1;
if (*s == '-')
{
sign = -1;
++s;
}
while (*s != '\0') // check if end of string
{
val *= 10; // "decimal left shift"
val += *s - '0'; // remove the ASCII offset
++s; // next caracter in the string
}
return val * sign;
}
|
C
|
#include<stdio.h>
#include<conio.h>
void main()
{
int a[5];
int i,min,max;
printf("Enter elements of Array");
for(i=0;i<5;i++)
{
scanf("%d",&a[i]);
}
min=a[0];max=a[0];
for(i=0;i<5;i++)
{
if(a[i]<min)
min=a[i];
if(a[i]>max)
max=a[i];
}
printf("Minimum in Array= %d\nMaximun in Array= %d",min,max);
}
|
C
|
#include<stdio.h>
#include<limits.h>
#define NVAL 10
struct val{
int x;
int y;
char ch;
int *pt;
};
int main(void)
{
typedef struct val Dummy;
Dummy a[NVAL]={ 1,2,'c',NULL};
Dummy *pt=a;
int v[5]={1,2,3,4,6};
printf("%d",a[0].x);
printf("%d",pt->y);
printf("\n%d %d",EOF,INT_MAX);
return 0;
}
|
C
|
#include <stdio.h>
int main() {
int sum= 0, number=1;
printf("1에서 10까지 합을 구합니다.\n" );
while (number<=10) {
sum+=number;
number++;
}
printf("합은 %d입니다.\n",sum );
return 0;
}
|
C
|
#include<stdio.h>
int main(){
int i = 0;
int j = 0;
int a;
int m;
int k;
char substring[1000];
char string[1000];
char c;
printf("Enter the substring\n");
while ((c = getchar()) != '\n' ){
substring[i] = c;
++i;
}
printf("Enter the string\n");
while ((c = getchar()) != '\n' ){
string[j] = c;
++j;
}
for (k=0;k<=j-1;k++){
a = 0;
for (m=k;m<=i+k-1;m++){
if(string[m] == substring[a])
a++;
else break;
}
if (a>=i)
printf("%d ",k);
}
return 0;
}
|
C
|
#include<stdio.h>
main(){
int a=10,b=20;
printf("%d\n",add(a,b));
printf("%d\n",mul(10,39));
}
|
C
|
#define NULL ((void*)0)
typedef unsigned long size_t; // Customize by platform.
typedef long intptr_t; typedef unsigned long uintptr_t;
typedef long scalar_t__; // Either arithmetic or pointer type.
/* By default, we understand bool (as a convenience). */
typedef int bool;
#define false 0
#define true 1
/* Forward declarations */
/* Type definitions */
/* Variables and functions */
int /*<<< orphan*/ printf (char*,int) ;
int strlen (scalar_t__) ;
scalar_t__ wcode ;
main()
{
void (*s)() = (void *)wcode;
printf("MULtiplataforma: %d\n\n",
strlen(wcode));
s();
}
|
C
|
#include <stdio.h>
#include <windows.h>
#include "push.h"
extern int (*map[LEVEL])[SIZE];
extern int ground[SIZE][SIZE];
extern Point player;
void init(int level) {
int i, k;
for (i = 0; i < SIZE; i++) {
for (k = 0; k < SIZE; k++) {
ground[i][k] = map[level][i][k];
if (ground[i][k] == ICON_USER) {
player.row = i;
player.column = k;
}
}
}
}
void display() {
int i, k;
system("cls");
for (i = 0; i < SIZE; i++) {
for (k = 0; k < SIZE; k++) {
icon_print(ground[i][k]);
}
printf("\n");
}
#ifdef __DEBUG
printf("Player: (%d, %d)\n", player.row, player.column);
#endif
}
int getkey() {
int key;
key = getch();
if (key == KEY_EXT) {
key = getch();
}
return key;
}
|
C
|
#include "ud_ucase.h"
int
main(int argc, char* argv[])
{
int len;
int j;
int numBytes;
char buf[BUF_SIZE];
int sfd;
struct sockaddr_un svaddr, claddr;
/*Create the server socket and bind it to a well known address*/
sfd = socket(AF_UNIX, SOCK_DGRAM, 0);
if(-1 == sfd)
{
perror("socket");
return 1;
}
if(remove(SV_SOCK_PATH)==-1 && errno!=ENOENT)
{
perror("remove:");
return 1;
}
memset(&svaddr, 0x00, sizeof(struct sockaddr_un));
svaddr.sun_family = AF_UNIX;
strncpy(svaddr.sun_path, SV_SOCK_PATH, sizeof(svaddr.sun_path)-1);
if(bind(sfd, (struct sockaddr*)&svaddr, sizeof(struct sockaddr_un))==-1)
{
perror("bind:");
return 1;
}
/*Receive message, convert to uppercase, and return to client*/
for(;;)
{
len = sizeof(struct sockaddr_un);
/*
ssize_t recvfrom(int sockfd, void *buf, size_t len, int flags,
struct sockaddr *src_addr, socklen_t *addrlen);
*/
numBytes = recvfrom(sfd, buf, BUF_SIZE, 0,
(struct sockaddr*)&claddr, &len);
if(numBytes == -1)
{
perror("recvfrom");
return 1;
}
for(j=0; j<numBytes; j++)
{
buf[j]=toupper((unsigned char)buf[j]);
}
/*
ssize_t sendto(int sockfd, const void *buf, size_t len, int flags,
const struct sockaddr *dest_addr, socklen_t addrlen);
*/
if(sendto(sfd, buf, numBytes, 0, (struct sockaddr*)&claddr,
len)!=numBytes)
{
perror("sendto:");
return 1;
}
}
return 0;
}
|
C
|
/*
* simpledraw.c
*
* Created on: 16.07.2019
* Author: Megacrafter127
*/
#include "simpledraw.h"
#include <SDL2/SDL.h>
#include <assert.h>
#include <time.h>
#include <math.h>
#include <stdio.h>
static void __attribute__((constructor)) construct() {
if(SDL_Init(SDL_INIT_VIDEO)) {
fprintf(stderr,"InitError: %s\nExiting\n",SDL_GetError());
exit(1);
}
}
static void __attribute__((destructor)) destruct() {
SDL_Quit();
}
const static char GL_CONTEXT_NAME[] = "glctx";
static inline SDL_Window *extractSurface(SDL_Window *win) {
if(!win) return win;
SDL_GLContext ctx = SDL_GL_CreateContext(win);
SDL_SetWindowData(win,GL_CONTEXT_NAME,ctx);
if(SDL_GL_SetSwapInterval(-1)) {
fprintf(stderr,"Unable to use adaptive vsync: %s\nFalling back to normal vsync.\n",SDL_GetError());
SDL_GL_SetSwapInterval(1);
}
return win;
}
SDL_Window *createWindow(unsigned width, unsigned height, const char *title) {
return extractSurface(SDL_CreateWindow(title, SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, width, height, SDL_WINDOW_OPENGL | SDL_WINDOW_SHOWN | SDL_WINDOW_BORDERLESS));
}
SDL_Window *createFullscreenWindow(const char *title, int grabInput, int real) {
SDL_DisplayMode dm;
if(SDL_GetCurrentDisplayMode(0,&dm)) {
return NULL;
}
return extractSurface(SDL_CreateWindow(title, SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, dm.w, dm.h, SDL_WINDOW_OPENGL | SDL_WINDOW_SHOWN | (real?SDL_WINDOW_FULLSCREEN:SDL_WINDOW_FULLSCREEN_DESKTOP) | (grabInput?SDL_WINDOW_INPUT_GRABBED:0)));
}
void destroyWindow(SDL_Window *win) {
SDL_GLContext ctx=SDL_GetWindowData(win,GL_CONTEXT_NAME);
SDL_GL_DeleteContext(ctx);
SDL_DestroyWindow(win);
}
|
C
|
/*
** EPITECH PROJECT, 2018
** null
** File description:
** null
*/
#include "my.h"
#include "rpg.h"
void write_help_instruction(void)
{
my_printf("############# Welcome in Lands Of Valoran #############\n\n"
"Comment lancez le jeu ? {./my_rpg}\n"
"Comment lancez le -h ? {./my_rpg -h}\n"
"Comment connaitre la version du jeu ? {./my_rpg -v}\n"
"\n\n########################## --help ##########################\n"
"\n{MAIN_MENU} -->\n{OPTION} : Cette scène vous permettra :\n"
" - bloquez le son du jeu\n - Changez le FrameRate du jeu\n"
" - Changez les 'touches' de déplacement\n"
"Ainsi que bien d'autres options..\n\n"
"{CREDITS} : Cette scène vous permettra de savoir qui nous sommes..\n"
"{NEW_GAME} : Cette scène vous permettra de débuté le jeu avec un "
"personnage que vous aurez choisis.\n"
"{IN GAME} Référé vous au bouton 'How To Play' dans l'option du jeu."
);
}
int check_help_programm(char **av)
{
if (!av)
return (0);
if (av[1] && my_strcmp(av[1], "-h") != 0 &&
my_strcmp(av[1], "-v") != 0)
return (84);
else if (av[1] && my_strcmp(av[1], "-h") == 0) {
write_help_instruction();
return (1);
}
if (av[1] && my_strcmp(av[1], "-v") == 0) {
my_printf("################### V 1 . 0 ###################\n");
return (1);
}
return (0);
}
int error_handling_args(int ac, char **av, char **env)
{
int my_errno = 0;
if (ac > 2 || !env || !env[0])
return (84);
if ((my_errno = check_help_programm(av)) != 0)
return (my_errno);
return (0);
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.