language
large_stringclasses 1
value | text
stringlengths 9
2.95M
|
---|---|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#define MAX_COUNT 10000000
void count(void);
pthread_mutex_t mutex1 = PTHREAD_MUTEX_INITIALIZER;
int counter = 0;
int main (void) {
int rc1, rc2;
pthread_t thread1, thread2;
if ((rc1 = pthread_create(&thread1, NULL, (void *)count, NULL))) {
printf("Thread creation faild: %d\n", rc1);
}
if ((rc2 = pthread_create(&thread2, NULL, (void *)count, NULL))) {
printf("Thread creation faild: %d\n", rc2);
}
pthread_join( thread1, NULL);
pthread_join( thread2, NULL);
return 0;
}
void count(void) {
int i, j;
pthread_mutex_lock( &mutex1 );
for ( i = 0; i < MAX_COUNT; ++i) {
for (j = 0; j < MAX_COUNT; ++j) {
counter++;
}
}
printf("Counter value: %d\n", counter);
pthread_mutex_unlock( &mutex1 );
}
|
C
|
/*
* * mm.c - The fastest, least memory-efficient malloc package.
* */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#include <unistd.h>
#include "mm.h"
#include "memlib.h"
/****DEFINING MACROS************/
/* single word (4) or double word (8) alignment */
#define ALIGNMENT 8
/* rounds up to the nearest multiple of ALIGNMENT */
#define ALIGN(size) (((size) + (ALIGNMENT-1)) & ~0x7)
#define SIZE_T_SIZE (ALIGN(sizeof(size_t)))
#define Blk_Hdr_Size (ALIGN(sizeof(blockHdr)))
#define Blk_Fdr_Size (ALIGN(sizeof(blockFdr)))
#define Free_Blk_Size (ALIGN(sizeof(blockHdr)+sizeof(blockFdr)))
#define Min_Size 32 // For split purpose
/****DEFINING FUNCTIONS*********/
void print_heap();
void *find_fit (size_t size);
void split();
void coalesce();
/*******DEFINING STRUCT********/
typedef struct footer blockFdr;
struct footer{
size_t size;
};
typedef struct header blockHdr;
struct header{
size_t size;
blockHdr *next;
blockHdr *prior;
};
/*
* * mm_init - initialize the malloc package.
* */
int mm_init(void)
{
/*initiate header*/
blockHdr *p = mem_sbrk((Free_Blk_Size));
p->size = Free_Blk_Size;
p->next = p;
p->prior = p;
/*initiate footer*/
blockFdr *fp = (blockFdr*)( (char*)p + Blk_Hdr_Size);
fp->size = Free_Blk_Size;
return 0;
}
void print_heap(){
blockHdr *bp = mem_heap_lo();
while (bp < (blockHdr*)mem_heap_hi()){
printf("%s block at %p, size %d\n",
(bp->size&1)? "allocated":"free",
bp,
(int) (bp->size & ~1));
bp = (blockHdr *) ((char *) bp + (bp->size & ~1));
}
}
/*
* * mm_malloc - Allocate a block by incrementing the brk pointer.
* * Always allocate a block whose size is a multiple of the alignment.
* */
void *mm_malloc(size_t size)
{
if (size>100 && size<128){
size =128;
}
if (size>400 && size <512){
size = 512;
}
int newsize = ALIGN(size + Free_Blk_Size);
/* blockHdr *bp =NULL; */
if (size <=0) return NULL;
/*else if (newsize==4095) newsize=8190; */
blockHdr *bp = find_fit(newsize);
blockFdr *fp = NULL;
if (bp == NULL ) {
/*Did not find the right size*/
bp = mem_sbrk(newsize); // low level malloc
if ( (long)bp == -1 ){
return NULL;
} /* error exception */
else {
/*new block allocated */
bp-> size = newsize|1;
fp = (blockFdr*) ((char*)bp + newsize - Blk_Fdr_Size);
fp -> size = newsize |1;
}
}
else {
if ( bp->size > 2*newsize ){
split (bp,fp,newsize); /* hardcode */
}
else{
fp = (blockFdr*) ((char*)bp + bp->size - Blk_Fdr_Size);
fp -> size |=1;
/*find fit found a size block;*/
bp-> size |=1;
/* Get rid of current free_block */
bp->prior -> next = bp->next;
bp->next ->prior = bp->prior;
}
}
return (void * ) ((char *) bp + Blk_Hdr_Size) ;
}
/* newsize is required_payload + sizeof(headrer) + sizeof(footer) */
void split(blockHdr* bp, blockFdr* fp, size_t newsize){
size_t freespace = bp->size - newsize;
blockHdr* freehead = NULL;
blockFdr* freefoot = NULL;
freehead = (blockHdr*) ((char*)bp + newsize);
freehead->size= freespace & ~1;
freefoot = (blockFdr*) ((char*)freehead + freespace - Blk_Fdr_Size);
freefoot->size = freespace & ~1;
fp =(blockFdr*) ((char*)freehead - Blk_Fdr_Size);
fp->size = newsize|1;
bp->size = newsize|1;
bp->next->prior = bp->prior;
bp->prior->next = bp->next;
blockHdr* p = NULL ;
p = mem_heap_lo();
freehead->next = p-> next;
freehead -> prior = p;
p->next = freehead;
freehead->next->prior = freehead;
}
void *find_fit (size_t size)
{
blockHdr *p;
for (p = ((blockHdr *)mem_heap_lo())-> next;
p != mem_heap_lo() && p->size < size;
p = p->next);
if(p != mem_heap_lo())
{
return p;
}
else{
return NULL;
}
}
/*
* * mm_free - Freeing a block does nothing.
* */
void mm_free(void *ptr)
{
blockHdr *bp = ptr - Blk_Hdr_Size;
blockHdr *head = mem_heap_lo();
bp->size &= ~1;
bp->next = head->next;
bp->prior = head;
head->next = bp;
bp ->next->prior = bp;
/* coalesce()+ append back to the list ; */
blockFdr *fp = (blockFdr*) ((char*)bp +bp->size - Blk_Fdr_Size);
fp->size &= ~1;
coalesce(bp);
}
/*
* *coalesce
* *
* */
void coalesce (blockHdr* bp) {
/*Previous*/
blockFdr *pr_fp = (blockFdr*)((char*) bp- Blk_Fdr_Size);
int pr_al;
/*next*/
blockHdr *nx_bp = (blockHdr*)((char*) bp+ bp->size);
int ne_al ;
if((char*)nx_bp+Free_Blk_Size < (char*) mem_heap_hi()){
ne_al=nx_bp->size & 1;
}
else{
ne_al = 1;
}
if((char*)pr_fp > (char*) mem_heap_lo()+Free_Blk_Size){
pr_al = pr_fp->size & 1;
}
else {
pr_al = 1;
}
if (pr_al && ne_al )
{
return;
}
else if (ne_al && !pr_al){
((blockHdr*)((char*)bp - pr_fp->size))->size += bp->size;
((blockHdr*)((char*)bp + bp->size - Blk_Fdr_Size))->size = ((blockHdr*)((char*)bp - pr_fp->size))->size;
bp->next->prior = bp->prior;
bp->prior->next = bp->next;
}
else if (pr_al && !ne_al) {
bp->size += nx_bp->size;
((blockFdr *)((char *)nx_bp + nx_bp->size - Blk_Fdr_Size))->size = bp->size;
nx_bp->next->prior = nx_bp->prior;
nx_bp->prior->next = nx_bp->next;
}
else if (!pr_al && !ne_al){
((blockHdr *)((char*)bp - pr_fp->size))->size += (bp->size + nx_bp->size);
((blockHdr*)((char*)bp + bp->size - Blk_Fdr_Size))->size = ((blockHdr *)((char*)bp - pr_fp->size))->size;
((blockFdr*)((char*)nx_bp+nx_bp->size - Blk_Fdr_Size))->size = ((blockHdr*)((char *)bp-pr_fp->size))->size;
bp->next->prior = bp->prior;
bp->prior -> next = bp->next;
nx_bp->next->prior = nx_bp->prior;
nx_bp->prior->next = nx_bp->next;
}
return;
}
/*
* * mm_realloc - Implemented simply in terms of mm_malloc and mm_free
* */
void *mm_realloc(void *ptr, size_t size)
{
blockHdr *bp = ptr - Blk_Hdr_Size;
void *newptr = NULL;
size_t _size = ALIGN(size + Free_Blk_Size);
size_t oldsize = bp->size;
if(_size ==0){
mm_free(ptr);
return 0;
}
if (oldsize > _size){
return ptr;
}
if (ptr == NULL) {
return mm_malloc(_size);
}
newptr = mm_malloc(_size);
if (!newptr){
return 0;
}
int copySize = bp->size-Blk_Hdr_Size;
if(size < copySize) copySize = _size;
memcpy(newptr, ptr, copySize);
mm_free(ptr);
return newptr;
}
|
C
|
#include "mcp7940m.h"
/* Declaring an instance of twim Peripheral. */
static const nrf_drv_twi_t twim = NRF_DRV_TWI_INSTANCE(BOARD_TWI);
void MCP79GetTime(uint8_t *recvTime)
{
uint8_t *buff = recvTime;
/* Set address of first byte */
buff[0] = MCP79_REG_RTCSEC;
nrf_drv_twi_tx(&twim, ADDR_MCP7940M, buff, 1, 1);
/* Read Time */
nrf_drv_twi_rx(&twim, ADDR_MCP7940M, buff, 3);
/* Mask the Oscillator enabled bit. */
buff[0] = buff[0] & 0x7F;
}
void MCP79SetTime(uint8_t *time)
{
uint8_t buff[4];
buff[0] = MCP79_REG_RTCSEC;
buff[1] = time[0];
/* Start the Oscillator */
buff[1] |= (1<<7);
buff[2] = time[1];
buff[3] = time[2];
nrf_drv_twi_tx(&twim, ADDR_MCP7940M, buff, 4, 0);
}
void MCP79GetSecs(uint8_t *ss)
{
MCP79ReadByte(MCP79_REG_RTCSEC, ss);
}
void MCP79SetSecs(uint8_t ss)
{
MCP79WriteByte(MCP79_REG_RTCSEC, ss);
}
void MCP79GetMins(uint8_t *mm)
{
MCP79ReadByte(MCP79_REG_RTCMIN, mm);
}
void MCP79SetMins(uint8_t mm)
{
MCP79WriteByte(MCP79_REG_RTCMIN, mm);
}
void MCP79GetHrs(uint8_t *hh)
{
MCP79ReadByte(MCP79_REG_RTCHOUR, hh);
}
void MCP79SetHrs(uint8_t hh)
{
MCP79WriteByte(MCP79_REG_RTCHOUR, hh);
}
void MCP79GetFullDate(uint8_t *recvDate)
{
uint8_t *buff = recvDate;
/* Set address of first byte */
buff[0] = MCP79_REG_RTCWKDAY;
nrf_drv_twi_tx(&twim, ADDR_MCP7940M, buff, 1, 1);
/* Read Full Date */
nrf_drv_twi_rx(&twim, ADDR_MCP7940M, buff, 4);
}
void MCP79SetFullDate(uint8_t *date)
{
uint8_t buff[5];
buff[0] = MCP79_REG_RTCWKDAY;
buff[1] = date[0];
buff[2] = date[1];
buff[3] = date[2];
buff[4] = date[3];
nrf_drv_twi_tx(&twim, ADDR_MCP7940M, buff, 5, 0);
}
void MCP79GetDay(uint8_t *d)
{
MCP79ReadByte(MCP79_REG_RTCWKDAY, d);
}
void MCP79SetDay(uint8_t d)
{
MCP79WriteByte(MCP79_REG_RTCWKDAY, d);
}
void MCP79GetDate(uint8_t *dd)
{
MCP79ReadByte(MCP79_REG_RTCDATE, dd);
}
void MCP79SetDate(uint8_t dd)
{
MCP79WriteByte(MCP79_REG_RTCDATE, dd);
}
void MCP79GetMonth(uint8_t *mm)
{
MCP79ReadByte(MCP79_REG_RTCMTH, mm);
}
void MCP79SetMonth(uint8_t mm)
{
MCP79WriteByte(MCP79_REG_RTCMTH, mm);
}
void MCP79GetYear(uint8_t *yy)
{
MCP79ReadByte(MCP79_REG_RTCYEAR, yy);
}
void MCP79SetYear(uint8_t yy)
{
MCP79WriteByte(MCP79_REG_RTCYEAR, yy);
}
void MCP79SetCtrlReg(uint8_t val)
{
MCP79WriteByte(MCP79_REG_CONTROL, val);
}
void MCP79GetCtrlReg(uint8_t *val)
{
MCP79ReadByte(MCP79_REG_CONTROL, val);
}
void MCP79WriteByte(uint8_t reg, uint8_t data)
{
uint8_t buff[2];
buff[0] = reg;
buff[1] = data;
/* Write Single Register */
nrf_drv_twi_tx(&twim, ADDR_MCP7940M, buff, 2, 0);
}
void MCP79ReadByte(uint8_t reg, uint8_t *recvData)
{
uint8_t buff = reg;
/* Write Single Register */
nrf_drv_twi_tx(&twim, ADDR_MCP7940M, &buff, 1, 1);
/* Read single register */
nrf_drv_twi_rx(&twim, ADDR_MCP7940M, recvData, 1);
}
|
C
|
#include<stdio.h>
void display();
int x=5; //GLOBAL VARIABLE
void main()
{
int x=10; //LOCAL VARIABLE
printf("%d\n",x);
display();
}
void display()
{
printf("%d",x);
}
|
C
|
#define _CRT_SECURE_NO_WARNINGS 1
#include <stdio.h>
int main()
{
//FILE * pf;
char str[1024] = {0};
sprintf(str, "%d", 12345);
printf("%s\n",str); //12345
//pf = fopen("test.txt","w");
//if(pf != NULL)
//{
// fputs("fopen example",pf);
// fclose(pf);
//}
//pf = fopen("test.txt", "a");
//fputs(" dede",pf);
//fclose(pf);
//pf = fopen("test.txt","r");
//fread(str, sizeof(str), 1, pf);
//fclose(pf);
//printf("%s\n",str);
//pf = fopen("test.txt","r");
//fgets(str, 1024, pf);
////fread(str,sizeof(str),1,pf);
//fclose(pf);
//printf("%s\n",str);
return 0;
}
|
C
|
#include "queens.h"
//zamiana pionkow na krolowe
void swap_to_queen(char board[8][8])
{
int i=7;
for(int j=0;j<7;j+=2)
{
if(board[i][j]=='O') board[i][j]='o';
}
i=0;
for(int j=1;j<8;j+=2)
{
if(board[i][j]=='X') board[i][j]='x';
}
}
|
C
|
#include <stdio.h>
int main()
{
int a[5] = {1,2,3,4,5};
int result = 0;
int Sum(int [], int);
result = Sum(a,5);
printf("Sum = %d\n", result);
return 0;
}
int Sum(int a[], int b)
{
int i, rst = 0;
for(i=0;i<b;i++)
rst += a[i];
return rst;
}
|
C
|
/*
* TTScheduler.c
*
* Created on: Feb 14, 2019
* Author: Administrator
*/
#include <stdint.h>
#include <stdlib.h>
#include <stdbool.h>
#include "Timer_driver/Timer.h"
#include "TTScheduler.h"
static bool g_bIsValidToRun;
static Task_t *g_ptTaskArray;
static uint32_t g_ui32NumOfTasks;
static uint32_t g_ui32TicksInMillis;
static uint32_t g_ui32TickPeriodInMillis;
static uint32_t g_ui32CyclePeriodInMillis;
static void _TickTimerCallBack(void)
{
uint32_t i;
g_ui32TicksInMillis += g_ui32TickPeriodInMillis;
for (i = 0; i < g_ui32NumOfTasks; i++)
{
if (((g_ui32TicksInMillis % g_ptTaskArray[i].ui32PeriodInMillis) == 0)
&& (g_ptTaskArray[i].bEnabled == 1))
{
if (g_ptTaskArray[i].pfnTaskFun != NULL)
{
/*
*
* Run this task in a specific time intervals to minimize Jitter for the next Hard RealTime Task.
*
*/
HardExecTimer_start(g_ptTaskArray[i].ui32WorstCaseExecTimeInMillis);
g_ptTaskArray[i].pfnTaskFun();
while (!HardExecTimer_isTimeOut())
{
}
}
}
}
if (g_ui32TicksInMillis == g_ui32CyclePeriodInMillis)
{
g_ui32TicksInMillis = 0;
}
}
bool TTScheduler_init(Task_t *ptTaskArray, uint32_t ui32NumOfTasks)
{
uint32_t i, j, ui32Max = 0, ui32Min = UINT32_MAX;
g_ui32NumOfTasks = ui32NumOfTasks;
g_ptTaskArray = ptTaskArray;
if (g_ptTaskArray == NULL)
{
g_bIsValidToRun = false;
return g_bIsValidToRun;
}
for (i = 0; i < g_ui32NumOfTasks; i++)
{
g_ptTaskArray[i].bEnabled = true;
if (g_ptTaskArray[i].ui32PeriodInMillis < ui32Min)
{
ui32Min = g_ptTaskArray[i].ui32PeriodInMillis;
}
if (g_ptTaskArray[i].ui32PeriodInMillis > ui32Max)
{
ui32Max = g_ptTaskArray[i].ui32PeriodInMillis;
}
if (g_ptTaskArray[i].ui32PeriodInMillis
< g_ptTaskArray[i].ui32WorstCaseExecTimeInMillis)
{
g_bIsValidToRun = false;
return g_bIsValidToRun;
}
for (j = i + 1; j < g_ui32NumOfTasks; j++)
{
if (g_ptTaskArray[i].ui32ID == g_ptTaskArray[j].ui32ID)
{
g_bIsValidToRun = false;
return g_bIsValidToRun;
}
}
}
for (i = ui32Min; i > 0; i--)
{
for (j = 0; j < g_ui32NumOfTasks; j++)
{
if ((g_ptTaskArray[j].ui32PeriodInMillis % i) != 0)
{
break;
}
}
if (j == g_ui32NumOfTasks) /* when all tasks periods are divided by (i) (period / i) */
{
g_ui32TickPeriodInMillis = i;
break;
}
}
for (i = ui32Max; i < UINT32_MAX; i++)
{
for (j = 0; j < g_ui32NumOfTasks; j++)
{
if ((i % g_ptTaskArray[j].ui32PeriodInMillis) != 0)
{
break;
}
}
if (j == g_ui32NumOfTasks) /* when (i) is divided by all tasks periods (i / period) */
{
g_ui32CyclePeriodInMillis = i;
break;
}
}
HardExecTimer_init();
TickTimer_init(g_ui32TickPeriodInMillis, _TickTimerCallBack);
g_bIsValidToRun = true;
return g_bIsValidToRun;
}
void TTScheduler_start(void)
{
if (g_bIsValidToRun)
{
TickTimer_start();
}
while (1)
{
}
}
bool TTScheduler_resumeTask(uint32_t ui32ID)
{
uint32_t i;
bool bTaskFound;
for (i = 0; i < g_ui32NumOfTasks; i++)
{
if (g_ptTaskArray[i].ui32ID == ui32ID)
{
g_ptTaskArray[i].bEnabled = true;
bTaskFound = true;
break;
}
}
if (i == g_ui32NumOfTasks)
{
bTaskFound = false;
}
return bTaskFound;
}
bool TTScheduler_suspendTask(uint32_t ui32ID)
{
uint32_t i;
bool bTaskFound;
for (i = 0; i < g_ui32NumOfTasks; i++)
{
if (g_ptTaskArray[i].ui32ID == ui32ID)
{
g_ptTaskArray[i].bEnabled = false;
bTaskFound = true;
break;
}
}
if (i == g_ui32NumOfTasks)
{
bTaskFound = false;
}
return bTaskFound;
}
uint32_t TTScheduler_getTicks(void)
{
return g_ui32TicksInMillis;
}
uint32_t TTScheduler_getTickPeriod(void)
{
return g_ui32TickPeriodInMillis;
}
uint32_t TTScheduler_getCyclePeriod(void)
{
return g_ui32CyclePeriodInMillis;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
#include "list.h"
/**
* Print the value of *ev
*/
void print_chars (void* ev) {
char* e = ev;
printf ("%s\n", e);
}
void print_ints (void* ev) {
intptr_t e = (intptr_t) ev;
printf ("%ld\n", e);
}
void str_to_int(void** vdst, void* vinput) {
char* input = (char*) vinput;
intptr_t* dst = (intptr_t*) vdst;
char** ptr = &input;
*dst = strtol(input, ptr, 10);
if (*dst == 0 && *ptr != NULL)
*dst = -1;
}
void nullify_num(void** vdst, void* vinput_str,
void* vinput_int) {
char* input_str = (char*) vinput_str;
intptr_t input_int = (intptr_t) vinput_int;
char** dst = (char**) vdst;
if (input_int == -1)
*dst = input_str;
else {
char n = '\0';
*dst = &n;
}
}
/**
* Return true iff *av is positive.
*/
int isPositive (void* av) {
intptr_t a = (intptr_t) av;
if(a >= 0){
return 1;
}
else
return 0;
}
/**
* Return 1 iff *av is NULL.
*/
int isNotNull (void* av) {
char* a = (char*) av;
if (*a){
return 1;
}
else
return 0;
}
/**
* Set *rv to maximum value
*/
void greaterthan (void** rv, void* av, void* bv) {
intptr_t a = (intptr_t) av;
intptr_t b = (intptr_t) bv;
intptr_t* r = (intptr_t*) rv;
if (a > b)
*r = a;
else
*r = b;
}
void truncateStrings(void** vdst, void* vinput_str,
void* vinput_int) {
char* input_str = (char*) vinput_str;
intptr_t input_int = (intptr_t) vinput_int;
char** dst = (char**) vdst;
*dst = malloc(input_int + 1);
strncpy(*dst, input_str, input_int);
(*dst)[input_int] = '\0';
}
int main(int argc, char** argv) {
list_t input_list = list_create();
for (int i = 1; i < argc; i++) {
list_append(input_list, argv[i]);
}
list_t num_list = list_create();
list_map1(str_to_int, num_list, input_list);
list_t nullified_list = list_create();
list_map2(nullify_num, nullified_list, input_list, num_list);
list_t pos_list = list_create();
list_filter(isPositive, pos_list, num_list);
list_t nonull_list = list_create();
list_filter(isNotNull, nonull_list, nullified_list);
// list_foreach(print_ints, pos_list);
// list_foreach(print_chars, nonull_list);
list_t truncated = list_create();
list_map2(truncateStrings, truncated,
nonull_list, pos_list);
list_foreach(print_chars, truncated);
intptr_t s = 0;
list_foldl (greaterthan, (void**) &s, pos_list);
printf ("%ld\n", s);
list_destroy(input_list);
list_destroy(num_list);
list_destroy(nullified_list);
list_destroy(pos_list);
list_destroy(nonull_list);
list_destroy(truncated);
}
|
C
|
/*
* koar/nodes/reson.c
* copyright (c) 2014 Frano Perleta
*/
#include "buf.h"
#include "patchvm.h"
#include "nodes/active.h"
// state {{{
typedef struct reson_s* reson_t;
struct reson_s {
enum {
PURE_2POLE = 0,
RES_GAIN,
PEAK_GAIN,
LOWPASS,
HIGHPASS
} mode;
samp_t gain;
samp_t h1, h2;
};
// }}}
// processing loop {{{
static void
reson_loop (reson_t rs, const samp_t* xs, const samp_t* fs, const samp_t* qs,
samp_t* ys, size_t len)
{
size_t i;
samp_t h1 = rs->h1, h2 = rs->h2;
switch (rs->mode)
{
case PURE_2POLE: // unnormalized 2-pole filter {{{
for (i = 0; i < len; i++)
{
samp_t x = xs[i];
samp_t y = x + h1;
samp_t f = fs[i];
samp_t r = 1 - M_PI * f / qs[i];
samp_t a1 = -2 * r * cos (2*M_PI*f);
samp_t a2 = r * r;
h1 = -a1 * y + h2;
h2 = -a2 * y;
ys[i] = rs->gain * y;
}
break; // }}}
case RES_GAIN: // constant resonance gain (zeros at ±R) {{{
for (i = 0; i < len; i++)
{
samp_t x = xs[i];
samp_t y = x + h1;
samp_t f = fs[i];
samp_t r = 1 - M_PI * f / qs[i];
samp_t a1 = -2 * r * cos (2*M_PI*f);
samp_t a2 = r * r;
h1 = -a1 * y + h2;
h2 = -r * x - a2 * y;
ys[i] = rs->gain * (1 - r) * y;
}
break; // }}}
case PEAK_GAIN: // constant peak gain (zeroes at ±1) {{{
for (i = 0; i < len; i++)
{
samp_t x = xs[i];
samp_t y = x + h1;
samp_t f = fs[i];
samp_t r = 1 - M_PI * f / qs[i];
samp_t a1 = -2 * r * cos (2*M_PI*f);
samp_t a2 = r * r;
h1 = -a1 * y + h2;
h2 = -x - a2 * y;
ys[i] = rs->gain * 0.5 * (1 - r*r) * y;
}
break; // }}}
case LOWPASS: // lowpass (both zeros at -1) {{{
for (i = 0; i < len; i++)
{
samp_t x = xs[i];
samp_t y = x + h1;
samp_t f = fs[i];
samp_t r = 1 - M_PI * f / qs[i];
samp_t a1 = -2 * r * cos (2*M_PI*f);
samp_t a2 = r * r;
h1 = 2 * x - a1 * y + h2;
h2 = x - a2 * y;
// H(1) = 4/(1 + a1 + a2)
ys[i] = rs->gain * (1 + a1 + a2) * 0.25 * y;
}
break; // }}}
case HIGHPASS: // highpass (both zeros at 1) {{{
for (i = 0; i < len; i++)
{
samp_t x = xs[i];
samp_t y = x + h1;
samp_t f = fs[i];
samp_t r = 1 - M_PI * f / qs[i];
samp_t a1 = -2 * r * cos (2*M_PI*f);
samp_t a2 = r * r;
h1 = -2 * x - a1 * y + h2;
h2 = x - a2 * y;
// H(-1) = 2/(1 - a1 + a2)
ys[i] = rs->gain * (1 - a1 + a2) * 0.5 * y;
}
break; // }}}
default:
panic ("this should never happen");
}
rs->h1 = h1; rs->h2 = h2;
}
// }}}
// callbacks {{{
static void
reson_tick (patch_t p, anode_t an, patch_stamp_t now, size_t delta)
{
reson_t rs = anode_state (an);
pnode_t src = anode_get_source (an, 0);
buf_t in = { .p = pnode_read (src, now).p };
pnode_t fsig = anode_get_source (an, 1);
buf_t f = { .p = pnode_read (fsig, now).p };
pnode_t qsig = anode_get_source (an, 2);
buf_t q = { .p = pnode_read (qsig, now).p };
buf_t b = buf_alloc (p->bufpool);
reson_loop (rs, in.xs, f.xs, q.xs, b.xs, delta);
buf_release (in);
buf_release (f);
buf_release (q);
pnode_t snk = anode_get_sink (an, 0);
patch_datum_t out = { .b = b };
pnode_write (p, snk, out, now);
}
static struct ainfo_s
reson_ainfo = {
.name = "reson",
.init = NULL,
.exit = NULL,
.tick = reson_tick,
.ins = 3,
.outs = 1,
.size = sizeof (struct reson_s)
};
// }}}
// make {{{
anode_t
N_reson_make (patch_t p, pnode_t src, pnode_t fsig, pnode_t qsig, pnode_t snk)
{
anode_t an = anode_create (p, &reson_ainfo);
anode_source (an, 0, src);
anode_source (an, 1, fsig);
anode_source (an, 2, qsig);
anode_sink (an, 0, snk);
reson_t rs = anode_state (an);
rs->mode = PURE_2POLE;
rs->gain = 1;
rs->h1 = rs->h2 = 0;
return an;
}
void
PATCHVM_reson_make (patchvm_t vm, instr_t instr)
{
patch_t p = patchvm_patch (vm);
pnode_t src = patchvm_get (vm, instr->args[1].reg).pn;
pnode_t fsig = patchvm_get (vm, instr->args[2].reg).pn;
pnode_t qsig = patchvm_get (vm, instr->args[3].reg).pn;
pnode_t snk = patchvm_get (vm, instr->args[4].reg).pn;
reg_t val = { .tag = T_RESON, .an = N_reson_make (p, src, fsig, qsig, snk) };
patchvm_set (vm, instr->args[0].reg, val);
}
// }}}
// pure {{{
void
N_reson_pure (anode_t an, samp_t gain)
{
reson_t rs = anode_state (an);
rs->mode = PURE_2POLE;
rs->gain = gain;
}
void
PATCHVM_reson_pure (patchvm_t vm, instr_t instr)
{
anode_t an = patchvm_get (vm, instr->args[0].reg).an;
samp_t gain = instr->args[1].dbl;
N_reson_pure (an, gain);
}
// }}}
// res {{{
void
N_reson_res (anode_t an, samp_t gain)
{
reson_t rs = anode_state (an);
rs->mode = RES_GAIN;
rs->gain = gain;
}
void
PATCHVM_reson_res (patchvm_t vm, instr_t instr)
{
anode_t an = patchvm_get (vm, instr->args[0].reg).an;
samp_t gain = instr->args[1].dbl;
N_reson_res (an, gain);
}
// }}}
// peak {{{
void
N_reson_peak (anode_t an, samp_t gain)
{
reson_t rs = anode_state (an);
rs->mode = PEAK_GAIN;
rs->gain = gain;
}
void
PATCHVM_reson_peak (patchvm_t vm, instr_t instr)
{
anode_t an = patchvm_get (vm, instr->args[0].reg).an;
samp_t gain = instr->args[1].dbl;
N_reson_peak (an, gain);
}
// }}}
// lowpass {{{
void
N_reson_lowpass (anode_t an, samp_t gain)
{
reson_t rs = anode_state (an);
rs->mode = LOWPASS;
rs->gain = gain;
}
void
PATCHVM_reson_lowpass (patchvm_t vm, instr_t instr)
{
anode_t an = patchvm_get (vm, instr->args[0].reg).an;
samp_t gain = instr->args[1].dbl;
N_reson_lowpass (an, gain);
}
// }}}
// highpass {{{
void
N_reson_highpass (anode_t an, samp_t gain)
{
reson_t rs = anode_state (an);
rs->mode = HIGHPASS;
rs->gain = gain;
}
void
PATCHVM_reson_highpass (patchvm_t vm, instr_t instr)
{
anode_t an = patchvm_get (vm, instr->args[0].reg).an;
samp_t gain = instr->args[1].dbl;
N_reson_highpass (an, gain);
}
// }}}
// vim:fdm=marker:
|
C
|
/*
** EPITECH PROJECT, 2021
** B-CPE-200-BER-2-1-matchstick-pablo-elias.herrmann
** File description:
** print
*/
#include "my.h"
void print_takes(int player, int nb, int line)
{
if (player == 1)
my_putstr("Player removed ");
if (player == -1)
my_putstr("AI removed ");
my_put_nbr(nb);
my_putstr(" match(es) from line ");
my_put_nbr(line + 1);
my_putstr("\n");
}
void print_manager(char **map, char *top)
{
my_putstr(top);
my_putstr("\n");
for (int i = 0; map[i] != NULL; i++) {
my_putstr("*");
my_putstr(map[i]);
my_putstr("*");
my_putstr("\n");
}
my_putstr(top);
if (over(map) != 0)
my_putstr("\n");
my_putstr("\n");
}
instruct_t *set_instruct(char **map)
{
instruct_t *list = malloc(sizeof(instruct_t));
for (int i = 0; (map)[i] != NULL; i++) {
list->nim = count_line((map)[i]);
list->fours += list->nim / 4;
list->twos += (list->nim % 4) / 2;
list->ones += list->nim % 2;
}
return (list);
}
|
C
|
#include<stdio.h>
#include<string.h>
int main(){
char s1[1000000],s2[1000000];
int i,j,t,n;
scanf("%d",&t);
while(t--){
scanf("%s",s1);
fflush(stdin);
scanf("%s",s2);
int count[256]={0};
for(i=0;s1[i]!='\0';i++){
count[s1[i]]++;
}
for(i=0;s2[i]!='\0';i++){
if(count[s2[i]]!=0)
break;
}
if(s2[i]){
printf("YES\n");
}
else{
printf("NO\n");
}
}
return 0;
}
|
C
|
#include "../inc/fdf.h"
t_point **realloc_pts(t_point **pts, t_point *point)
{
unsigned int i;
unsigned int nb_pts;
t_point **pts_tmp;
nb_pts = 0;
while (pts[nb_pts])
nb_pts++;
if (!(pts_tmp = (t_point**)malloc(sizeof(t_point*) * (nb_pts + 2))))
return (NULL);
i = -1;
while (++i < nb_pts)
pts_tmp[i] = pts[i];
free(pts);
pts_tmp[i] = point;
pts_tmp[i + 1] = NULL;
return (pts_tmp);
}
t_point *ft_realloc(t_point *old, t_point point, int nb_pts)
{
t_point *new;
int i;
if (!(new = (t_point*)malloc(sizeof(t_point) * (nb_pts + 2))))
return (NULL);
i = -1;
while (++i < nb_pts)
new[i] = old[i];
new[i] = point;
ft_bzero((new + i + 1), sizeof(t_point));
return (new);
}
static int die(char **buffer, char **stock)
{
ft_strdel(buffer);
ft_strdel(stock);
return (-1);
}
int ft_set(char *tmp, char **stk, char **buffer)
{
ft_strdel(stk);
if (!(*stk = ft_strdup(tmp)))
return (die(buffer, stk));
ft_strdel(&tmp);
return (1);
}
|
C
|
#include <stdlib.h>
#include <stdio.h>
typedef void (*FuncionVisitante) (int dato);
typedef enum {
BTREE_RECORRIDO_IN,
BTREE_RECORRIDO_PRE,
BTREE_RECORRIDO_POST
} BTreeOrdenDeRecorrido;
typedef struct _BTNodo {
int dato;
struct _BTNodo *left;
struct _BTNodo *right;
} BTNodo;
typedef BTNodo * BTree;
//////////
// COLA //
//////////
typedef struct _SNodo {
BTree dato;
struct _SNodo *sig;
} SNodo;
typedef SNodo * SList;
typedef struct _Cola {
SList primero;
SList ultimo;
} _Cola;
typedef _Cola * Cola;
Cola cola_crear(){
Cola a = malloc(sizeof(_Cola));
a->primero = NULL;
a->ultimo = NULL;
return a;
}
int cola_es_vacia(Cola a){
return a == NULL || a->primero == NULL;
}
BTree cola_primero(Cola a){
if(!cola_es_vacia(a)){
return a->primero->dato;
}
return NULL;
}
void cola_encolar(Cola a,BTree dato){
SList nodo = malloc(sizeof(SNodo));
nodo->dato = dato;
nodo->sig = a->ultimo;
a->ultimo = nodo;
if(cola_es_vacia(a)){
a->primero = nodo;
}
}
void cola_desencolar(Cola a){
if(cola_es_vacia(a)) return;
if(a->ultimo->sig==NULL){
free(a->ultimo);
a->primero=NULL;
a->ultimo=NULL;
return;
}
SList nodo = a->ultimo;
for(;nodo->sig->sig!=NULL;nodo=nodo->sig);
free(a->primero);
nodo->sig = NULL;
a->primero = nodo;
}
/////////////
// ARBOLES //
/////////////
static void imprimir_entero(int data) {
printf("%d ", data);
}
BTree btree_crear() {
return NULL;
}
void btree_destruir(BTree nodo) {
if (nodo != NULL) {
btree_destruir(nodo->left);
btree_destruir(nodo->right);
free(nodo);
}
}
BTree btree_unir(int dato, BTree left, BTree right) {
BTree nuevoNodo = malloc(sizeof(BTNodo));
nuevoNodo->dato = dato;
nuevoNodo->left = left;
nuevoNodo->right = right;
return nuevoNodo;
}
void btree_recorrer(BTree raiz, BTreeOrdenDeRecorrido orden, FuncionVisitante visit){
if(raiz==NULL) return;
if(orden==1) visit(raiz->dato);
btree_recorrer(raiz->left,orden,visit);
if(orden==0) visit(raiz->dato);
btree_recorrer(raiz->right,orden,visit);
if(orden==2) visit(raiz->dato);
}
void btree_bfs(BTree raiz, FuncionVisitante visit){
BTree temp = raiz;
Cola a = cola_crear();
while(temp){
visit(temp->dato);
if(temp->left){
cola_encolar(a,temp->left);
}
if(temp->right){
cola_encolar(a,temp->right);
}
temp = cola_primero(a);
cola_desencolar(a);
}
}
int main() {
BTree ll = btree_unir(1, btree_crear(), btree_crear());
BTree l = btree_unir(2, ll, btree_crear());
BTree r = btree_unir(3, btree_crear(), btree_crear());
BTree raiz = btree_unir(4, l, r);
btree_recorrer(raiz, BTREE_RECORRIDO_PRE, imprimir_entero);
printf("\n");
btree_bfs(raiz,imprimir_entero);
puts("");
btree_destruir(raiz);
return 0;
}
|
C
|
#include <stdio.h>
int main()
{
long nc;
int c, blanks, tabs, new_lines;
new_lines = 0;
tabs = 0;
blanks = 0;
nc = 0;
while (getchar() != EOF)
++nc;
printf("%ld\n", nc);
while ((c = getchar()) != EOF) {
if (c == '\n')
++new_lines;
else if (c == '\t')
++tabs;
else if (c == ' ')
++blanks;
}
printf("New Lines; %d, Tabs: %d, Blanks: %d\n", new_lines,tabs,blanks);
return 0;
}
|
C
|
#include<stdio.h>
struct company{
char name[30];
//float term_marks[3];
float income;
float cost;
float profit;
};
int main()
{
struct company s[3];
int i,j,n;
float profit;
//float sum[3]={0,0,0};
printf("Enter how many companies:");
scanf("%d", &n);
for(j=0;j<n;j++)
{
printf("Name:");
gets(s[j].name);
getchar();
printf("Income:");
scanf("%f",&s[j].income);
printf("Cost:");
scanf("%f",&s[j].cost);
//printf("Profit:");
// scanf("%d",&s[j].cost);
//getchar();
}
for(j=0;j<n;j++)
// for(i=0;i<n;i++)
s[j].profit=s[j].income-s[j].cost;
//sum[j]+=s[j].term_marks[i];
//for(j=0;j<3;j++)
//s[j].avg=sum[j]/3;
for(j=0;j<n;j++)
printf("Company %s, Income:%f, Cost %f Profit %f \n",s[j].name,s[j].income,s[j].cost,s[j].profit);
return 0;
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* color.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: jcanteau <jcanteau@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2019/10/14 20:32:58 by jcanteau #+# #+# */
/* Updated: 2019/10/18 20:14:28 by jcanteau ### ########.fr */
/* */
/* ************************************************************************** */
#include "../includes/fdf.h"
void ft_contrast_level(t_env *fdf)
{
int r;
int c;
r = 0;
while (r < fdf->map.nbl)
{
c = 0;
while (c < fdf->map.nbcol)
{
if (fdf->map.tab[r][c].z < 0)
fdf->map.tab[r][c].color = CYAN;
else if (fdf->map.tab[r][c].z == 0)
fdf->map.tab[r][c].color = WHITE;
else if (fdf->map.tab[r][c].z > 0)
fdf->map.tab[r][c].color = GREEN;
c++;
}
r++;
}
}
void ft_default_color(t_env *fdf)
{
int r;
int c;
r = 0;
while (r < fdf->map.nbl)
{
c = 0;
while (c < fdf->map.nbcol)
{
fdf->map.tab[r][c].color = fdf->map.tab[r][c].defcolor;
c++;
}
r++;
}
}
void ft_map_real_2(t_env *fdf, int r, int c)
{
if (fdf->map.tab[r][c].z < fdf->map.max * 0.05)
fdf->map.tab[r][c].color = DARK_GREEN;
else if (fdf->map.tab[r][c].z < fdf->map.max * 0.1)
fdf->map.tab[r][c].color = DARKER_GREEN;
else if (fdf->map.tab[r][c].z < fdf->map.max * 0.2)
fdf->map.tab[r][c].color = OLIVE;
else if (fdf->map.tab[r][c].z < fdf->map.max * 0.3)
fdf->map.tab[r][c].color = BROWN;
else if (fdf->map.tab[r][c].z <= fdf->map.max * 1)
fdf->map.tab[r][c].color = WHITE;
}
void ft_map_real(t_env *fdf)
{
int r;
int c;
r = 0;
while (r < fdf->map.nbl)
{
c = 0;
while (c < fdf->map.nbcol)
{
if (fdf->map.tab[r][c].z < fdf->map.min * 0.7)
fdf->map.tab[r][c].color = DARK_BLUE;
else if (fdf->map.tab[r][c].z < fdf->map.min * 0.2)
fdf->map.tab[r][c].color = MED_BLUE;
else if (fdf->map.tab[r][c].z < 1)
fdf->map.tab[r][c].color = BLUE;
else if (fdf->map.tab[r][c].z < fdf->map.max * 0.005)
fdf->map.tab[r][c].color = SAND;
else if (fdf->map.tab[r][c].z < fdf->map.max * 0.02)
fdf->map.tab[r][c].color = GREEN;
else
ft_map_real_2(fdf, r, c);
c++;
}
r++;
}
}
void ft_color_choice(t_env *fdf)
{
if (fdf->colormod == DEFAULT_MAP_COLOR)
ft_default_color(fdf);
else if (fdf->colormod == CARTOGARPHY)
ft_map_real(fdf);
else if (fdf->colormod == CONTRAST)
ft_contrast_level(fdf);
}
|
C
|
/* Copyright (C) 2016 Leonard Ding <dingxiaoyun88@gmail.com> */
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
#include <stdio.h>
int uniquePaths(int m, int n) {
if(m == 1 && n == 1){
return 1;
}
int r[m][n];
int i = 0, j = 0;
for(i = 1; i < m; i++){
r[i][0] = 1;
}
for(i = 1; i < n; i++){
r[0][i] = 1;
}
r[0][0] = 0;
for(i = 1; i < m; i++){
for(j = 1; j < n; j++){
r[i][j] = r[i - 1][j] + r[i][j - 1];
}
}
return r[m - 1][n - 1];
}
int main(){
printf("%d\n", uniquePaths(3, 7));
return 0;
}
|
C
|
/*
/Names: Matthew Crepea, Thomas Haumersen
/Pledge: I pledge my honor that I have abided by the Stevens Honor System. Matthew Crepea Thomas Haumersen
*/
#include "../../include/my.h"
#include <stdlib.h>
/*Help function to my_str2vect
* Returns copy of string up to the next space, tab, newline, or
* string end.
*/
char* copy_to_ws(char* str){
char *temp = str;
int accum = 0; /*Holds number of characters up to next blank space*/
int i = 0; /*Iterates through str, putting values into temp*/
/*Count values to next whitespace - stored in accum*/
while (*temp != ' ' && *temp != '\n' && *temp != '\t' && *temp != '\0'){
temp++;
accum++;
}
temp = (char*) malloc (accum + 1); /*Allocate new memory for temp*/
/*Iterate through str, copying values into temp*/
for(i = 0; i < accum; ++i){
temp[i] = str[i];
}
temp[accum] = '\0';
return temp;
}
|
C
|
/*
** EPITECH PROJECT, 2020
** my_strncpy
** File description:
** Copy some string letter by letter
*/
char *my_strncpy(char *dest, char const *src, int n)
{
for (int i = 0; i < n; i++) {
dest[i] = src[i];
}
return dest;
}
|
C
|
/*
** EPITECH PROJECT, 2019
** panel
** File description:
** panel
*/
#include <stdlib.h>
#include "../include/my.h"
#include "../include/defender.h"
void parse_element(game_t *gt, int x, int y)
{
if (x == -1)
x = 0;
if (y == -1)
y = 0;
switch (gt->win.position_map[y][x]) {
case 0:
panel_tower(gt, x, y);
break;
case 1:
upgrade_castle(gt, x, y);
break;
case 4:
upgrade_tower(gt, x, y);
break;
}
}
void display_panel(game_t *gt)
{
if (gt->info.panel_display == 0) {
gt->info.panel_pos.x = gt->win.clic_vect.x / 140;
gt->info.panel_pos.y = gt->win.clic_vect.y / 140;
}
parse_element(gt, gt->info.panel_pos.x, gt->info.panel_pos.y);
}
|
C
|
#include <stdio.h>
#include <mem.h>
#include "house.h"
int main() {
house_t houses[2];
house_t house1;
strcat(house1.adress,"kossuth6");
house1.area_m2 = 200;
house1.number_of_rooms = 10;
house1.price = 60000;
houses[0] = house1;
house_t house2;
strcat(house2.adress, "kossuth7");
house2.area_m2 = 300;
house2.number_of_rooms = 8;
house2.price = 130000;
houses[1] = house2;
printf("%s", worth_to_buy(&house1) == 1 ? "This house is worth to buy!\n" : "This house is not worth to buy!\n");
printf("%s", worth_to_buy(&house2) == 1 ? "This house is worth to buy!\n" : "This house is not worth to buy!\n");
printf("%d", houses_worth_to_buy(houses, 2));
return 0;
}
|
C
|
/*
* André D. Carneiro e Victória Simonetti
*/
#include <stdio.h>
#include "tokens.h"
extern FILE* yyin;
extern int yylex();
extern int isRunning();
extern int hashPrint();
extern int initMe();
int main(){
int token;
yyin = fopen("teste.ling", "r");
initMe();
while(isRunning()){
token = yylex();
switch (token) {
case KW_BYTE: fprintf(stderr, "KW_BYTE\n"); break;
case KW_SHORT: fprintf(stderr, "KW_SHORT\n"); break;
case KW_LONG: fprintf(stderr, "KW_LONG\n"); break;
case KW_FLOAT: fprintf(stderr, "KW_FLOAT\n"); break;
case KW_DOUBLE: fprintf(stderr, "KW_DOUBLE\n"); break;
case KW_IF: fprintf(stderr, "KW_IF\n"); break;
case KW_THEN: fprintf(stderr, "KW_THEN\n"); break;
case KW_ELSE: fprintf(stderr, "KW_ELSE\n"); break;
case KW_WHILE: fprintf(stderr, "KW_WHILE\n"); break;
case KW_FOR: fprintf(stderr, "KW_FOR\n"); break;
case KW_READ: fprintf(stderr, "KW_READ\n"); break;
case KW_RETURN: fprintf(stderr, "KW_RETURN\n"); break;
case KW_PRINT : fprintf(stderr, "KW_PRINT\n"); break;
case OPERATOR_LE: fprintf(stderr, "OPERATOR_LE\n"); break;
case OPERATOR_GE : fprintf(stderr, "OPERATOR_GE\n"); break;
case OPERATOR_EQ: fprintf(stderr, "OPERATOR_EQ\n"); break;
case OPERATOR_NE: fprintf(stderr, "OPERATOR_NE\n"); break;
case OPERATOR_AND: fprintf(stderr, "OPERATOR_AND\n"); break;
case OPERATOR_OR: fprintf(stderr, "OPERATOR_OR\n"); break;
case TK_IDENTIFIER: fprintf(stderr, "TK_IDENTIFIER\n"); break;
case LIT_INTEGER: fprintf(stderr, "LIT_INTEGER\n"); break;
case LIT_REAL: fprintf(stderr, "LIT_REAL\n"); break;
case LIT_CHAR: fprintf(stderr, "LIT_CHAR\n"); break;
case LIT_STRING: fprintf(stderr, "LIT_STRING\n"); break;
case TOKEN_ERROR: fprintf(stderr, "TOKEN_ERROR\n"); break;
default: fprintf(stderr, "OPERATOR\n");
}
//fprintf(stderr, "tok = %d\n", token);
}
fprintf(stderr, "------------------hashPrint()------------------\n");
hashPrint();
return 0;
}
|
C
|
/*
* ColorUtils.h
* Gui
*
* Created by Marek Bereza on 05/05/2010.
*
*/
// gets the R, G or B component out of a hex colour
#define hexValR(A) ((A >> 16) & 0xff)
#define hexValG(A) ((A >> 8) & 0xff)
#define hexValB(A) ((A >> 0) & 0xff)
int blendColor(int color1, int color2, float amt = 0.5);
int colorFloat255ToHex(float r, float g, float b);
|
C
|
/*====================================================================*
*
* void syslog_error (int priority, errno_t number, char const *format, ...);
*
* syslog.h
*
* print user message and system error message using the syslogd
* priority;
*
*. Motley Tools by Charles Maier
*: Published 1982-2005 by Charles Maier for personal use
*; Licensed under the Internet Software Consortium License
*
*--------------------------------------------------------------------*/
#ifndef SYSLOG_ERROR_SOURCE
#define SYSLOG_ERROR_SOURCE
#include <stdio.h>
#include <stdarg.h>
#include <string.h>
#include <errno.h>
#include "../linux/syslog.h"
#include "../tools/sizes.h"
#ifdef __GNUC__
__attribute__ ((format (printf, 3, 4)))
#endif
void syslog_error (int priority, errno_t number, char const *format, ...)
{
va_list arglist;
va_start (arglist, format);
if (number)
{
char buffer [strlen (format) + ERRORMSG_MAX];
snprintf (buffer, sizeof (buffer), "%s: %s", format, strerror (number));
vsyslog (priority, buffer, arglist);
}
else
{
vsyslog (priority, format, arglist);
}
va_end (arglist);
return;
}
#endif
|
C
|
/*
* Jacopo Del Granchio
* #093-2 12.02.2020
*/
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include <locale.h>
#include <stdarg.h>
#include <stdbool.h>
#include <string.h>
// Costanti
#define NC 10
#define NS 50
#define LS 20
// Macro
#define chiedi(msg, format, ...) \
printf(msg); \
scanf(format, __VA_ARGS__);
typedef struct {
int anno;
int mese;
int giorno;
} data;
typedef struct {
char nome[LS];
int sesso;
data data;
char luogo[LS];
} studente;
typedef struct {
char nome[LS];
studente studenti[NS];
int numStudenti;
} classe;
// Prototipi
int menu();
void aggiungiClasse(classe [NC], int *);
int cercaClasse(classe [NC], int);
void rimuoviClasse(classe [NC], int *);
void stampaClassi(classe [NC], int);
int menuClasse(classe);
void aggiungiStudente(classe *);
int cercaStudente(classe);
void rimuoviStudente(classe *);
void stampaStudenti(classe);
void stampaStudente(studente);
// Funzioni
int main() {
setlocale(LC_ALL, "");
classe classi[NC];
int numClassi = 0;
int s;
do {
s = menu();
switch (s) {
case 1:
aggiungiClasse(classi, &numClassi);
break;
case 2:
printf("\n");
int classeIndice = cercaClasse(classi, numClassi);
if (classeIndice == -1) {
printf("Classe non trovata.\n");
break;
}
printf("Classe trovata.\n");
classe *c = &classi[classeIndice];
do {
s = menuClasse(*c);
switch (s) {
case 1:
aggiungiStudente(c);
break;
case 2:
printf("\n");
int studenteIndice = cercaStudente(*c);
printf("\n");
printf("%-*s%-*s%-*s%-*s\n", LS, "Nome", LS / 2, "Sesso", LS, "Data di nascita", LS, "Citta di nascita");
stampaStudente(c->studenti[studenteIndice]);
break;
case 3:
rimuoviStudente(c);
break;
case 4:
stampaStudenti(*c);
break;
case 0:
printf("Esco dalla classe %s\n", c->nome);
break;
default:
printf("Scelta non valida.\n");
}
} while (s != 0);
s = -1;
break;
case 3:
rimuoviClasse(classi, &numClassi);
break;
case 4:
stampaClassi(classi, numClassi);
break;
case 0:
printf("Arrivederci.\n");
break;
default:
printf("Scelta non valida.\n");
}
} while (s != 0);
// getchar();
// system("pause");
return 0;
}
int menu() {
printf("\n");
printf(" Menu Principale \n");
printf("1) Aggiungi classe \n");
printf("2) Cerca classe \n");
printf("3) Rimuovi classe \n");
printf("4) Stampa riepilogo\n");
printf("0) Esci \n");
printf("Scelta: ");
int s;
char nl;
scanf("%d", &s);
scanf("%c", &nl);
printf("\n");
return s;
}
void aggiungiClasse(classe classi[NC], int *numClassi) {
if (*numClassi >= NC) {
printf("Massimo numero di classi raggiunto.\n");
return;
}
printf("Inserire il nome della nuova classe: ");
classi[*numClassi].numStudenti = 0;
gets(classi[(*numClassi)++].nome);
}
int cercaClasse(classe classi[NC], int numClassi) {
char buffer[LS];
printf("Inserire il nome della classe da cercare: ");
gets(buffer);
for (int i = 0; i < numClassi; i++)
if (strcmp(buffer, classi[i].nome) == 0) return i;
return -1;
}
void rimuoviClasse(classe classi[NC], int *numClassi) {
if (*numClassi <= 0) {
printf("Non ci sono classi.\n");
return;
}
int classe = cercaClasse(classi, *numClassi);
if (classe == -1) {
printf("Classe non trovata.\n");
return;
}
for (int i = classe; i < *numClassi - 1; i++)
classi[i] = classi[i + 1];
printf("Classe rimossa.\n");
(*numClassi)--;
}
void stampaClassi(classe classi[NC], int numClassi) {
if (numClassi == 0) {
printf("Non ci sono classi.\n");
return;
}
for (int i = 0; i < numClassi; i++)
printf("%-*s", LS, classi[i].nome);
putchar('\n');
int max = classi[0].numStudenti;
for (int i = 1; i < numClassi; i++)
if (classi[i].numStudenti > max) max = classi[i].numStudenti;
for (int j = 0; j < max; j++) {
for (int i = 0; i < numClassi; i++)
printf("%-*s", LS, classi[i].numStudenti >= j ? classi[i].studenti[j].nome : "");
putchar('\n');
}
}
int menuClasse(classe classe) {
printf("\n");
printf(" Menu di \"%s\"\n", classe.nome);
printf("1) Aggiungi studente\n");
printf("2) Cerca studente \n");
printf("3) Rimuovi studente \n");
printf("4) Stampa riepilogo \n");
printf("0) Esci \n");
printf("Scelta: ");
int s;
char nl;
scanf("%d", &s);
scanf("%c", &nl);
printf("\n");
return s;
}
void aggiungiStudente(classe *classe) {
if (classe->numStudenti >= NS) {
printf("Massimo numero di studenti raggiunto.\n");
return;
}
studente *s = &classe->studenti[classe->numStudenti];
char nl;
printf("Inserire il nome dello studente: ");
gets(s->nome);
do {
printf("Inserire il sesso (0: Maschio, 1:Femmina) dello studente: ");
scanf("%d", &s->sesso); // TODO: input migliorato.
scanf("%c", &nl);
if (s->sesso < 0 || s->sesso > 1) {
printf("Input non valido.\n");
}
} while (s->sesso < 0 || s->sesso > 1);
do {
printf("Inserire la data di nascita (Formato: YYYY.MM.DD) dello studente: ");
scanf("%d.%d.%d", &s->data.anno, &s->data.mese, &s->data.giorno);
scanf("%c", &nl);
if (s->data.mese < 0 || s->data.mese > 12 || s->data.giorno < 0 || s->data.giorno > 31) {
printf("Data inserita non valida.\n");
}
} while (s->data.mese < 0 || s->data.mese > 12 || s->data.giorno < 0 || s->data.giorno > 31); // 31 Febbraio. GG.
printf("Inserire la citta di nascita dello studente: ");
gets(s->luogo);
(classe->numStudenti)++;
}
int cercaStudente(classe classe) {
char buffer[LS];
printf("Inserire il nome dello studente da cercare: ");
gets(buffer);
for (int i = 0; i < classe.numStudenti; i++)
if (strcmp(buffer, classe.studenti[i].nome) == 0) return i;
return -1;
}
void rimuoviStudente(classe *classe) {
if (classe->numStudenti <= 0) {
printf("Non esistono studenti.\n");
return;
}
int studente = cercaStudente(*classe);
if (studente == -1) {
printf("Studente non trovato.\n");
return;
}
for (int i = studente; i < classe->numStudenti; i++)
classe->studenti[i] = classe->studenti[i + 1];
printf("Studente rimosso.\n");
(classe->numStudenti)--;
}
void stampaStudenti(classe classe) {
if (classe.numStudenti <= 0) {
printf("Non ci sono studenti.\n");
return;
}
printf("Classe: %-*s\n", LS, classe.nome);
printf("%-*s%-*s%-*s%-*s\n", LS, "Nome", LS / 2, "Sesso", LS, "Data di nascita", LS, "Citta di nascita");
for (int i = 0; i < classe.numStudenti; i++) {
stampaStudente(classe.studenti[i]);
}
}
void stampaStudente(studente s) {
printf("%-*s", LS, s.nome);
printf("%-*s", LS / 2, s.sesso ? "Maschio" : "Femmina");
char buffer[LS];
sprintf(buffer, "%02d.%02d.%d", s.data.giorno, s.data.mese, s.data.anno);
printf("%-*s", LS, buffer);
printf("%-*s", LS, s.luogo);
printf("\n");
}
|
C
|
#define max(a, b) (((a) > (b)) ? (a) : (b))
#define min(a, b) (((a) < (b)) ? (a) : (b))
int maxProductPath(int** grid, int gridSize, int* gridColSize)
{
static const int MOD = 1e9 + 7;
int M = gridSize, N = *gridColSize;
long dp[M][N][2];
for (int i = 0; i < M; ++i)
{
for (int j = 0; j < N; ++j)
{
if (i == 0 && j == 0)
dp[i][j][0] = dp[i][j][1] = grid[0][0];
else if (i == 0)
dp[i][j][0] = dp[i][j][1] = grid[i][j] * dp[i][j - 1][0];
else if (j == 0)
dp[i][j][0] = dp[i][j][1] = grid[i][j] * dp[i - 1][j][0];
else
{
long a = grid[i][j] * max(dp[i][j - 1][0], dp[i - 1][j][0]);
long b = grid[i][j] * min(dp[i][j - 1][1], dp[i - 1][j][1]);
dp[i][j][0] = max(a, b);
dp[i][j][1] = min(a, b);
}
}
}
return dp[M - 1][N - 1][0] < 0 ? -1 : dp[M - 1][N - 1][0] % MOD;
}
|
C
|
/*---------------------------------------------------------------------------------
METRIC.C
-Helper functions for metric tensors
-Compute 4x4 matrix minor, adjoint, determinant and inverse
-Compute connection coefficients
-Raise and lower rank-1 tensors
-Take dot product of a contravariant and covariant rank-1 tensor
---------------------------------------------------------------------------------*/
#include "decs.h"
double MINOR(double m[16], int r0, int r1, int r2, int c0, int c1, int c2);
void adjoint(double m[16], double adjOut[16]);
double determinant(double m[16]);
inline double gcon_func(double gcov[NDIM][NDIM], double gcon[NDIM][NDIM])
{
double gdet = invert(&gcov[0][0],&gcon[0][0]);
return sqrt(fabs(gdet));
}
inline void get_gcov(struct GridGeom *G, int i, int j, int loc, double gcov[NDIM][NDIM]) {
DLOOP2 gcov[mu][nu] = G->gcov[loc][mu][nu][j][i];
}
inline void get_gcon(struct GridGeom *G, int i, int j, int loc, double gcon[NDIM][NDIM])
{
DLOOP2 gcon[mu][nu] = G->gcon[loc][mu][nu][j][i];
}
// Calculate connection coefficient
inline void conn_func(struct GridGeom *G, int i, int j)
{
double tmp[NDIM][NDIM][NDIM];
double X[NDIM], Xh[NDIM], Xl[NDIM];
double gh[NDIM][NDIM];
double gl[NDIM][NDIM];
coord(i, j, CENT, X);
for (int mu = 0; mu < NDIM; mu++) {
for (int kap = 0; kap < NDIM; kap++) {
Xh[kap] = X[kap];
}
for (int kap = 0; kap < NDIM; kap++) {
Xl[kap] = X[kap];
}
Xh[mu] += DELTA;
Xl[mu] -= DELTA;
gcov_func(Xh, gh);
gcov_func(Xl, gl);
for (int lam = 0; lam < NDIM; lam++) {
for (int nu = 0; nu < NDIM; nu++) {
G->conn[lam][nu][mu][j][i] = (gh[lam][nu] - gl[lam][nu])/(Xh[mu] -
Xl[mu]);
}
}
}
// Rearrange to find \Gamma_{lam nu mu}
for (int lam = 0; lam < NDIM; lam++) {
for (int nu = 0; nu < NDIM; nu++) {
for (int mu = 0; mu < NDIM; mu++) {
tmp[lam][nu][mu] = 0.5 * (G->conn[nu][lam][mu][j][i] +
G->conn[mu][lam][nu][j][i] -
G->conn[mu][nu][lam][j][i]);
}
}
}
// now mu nu kap
// Raise index to get \Gamma^lam_{nu mu}
for (int lam = 0; lam < NDIM; lam++) {
for (int nu = 0; nu < NDIM; nu++) {
for (int mu = 0; mu < NDIM; mu++) {
G->conn[lam][nu][mu][j][i] = 0.;
for (int kap = 0; kap < NDIM; kap++)
G->conn[lam][nu][mu][j][i] += G->gcon[CENT][lam][kap][j][i]*
tmp[kap][nu][mu];
}
}
}
}
// Lower a contravariant rank-1 tensor to a covariant one
inline void lower_grid(GridVector vcon, GridVector vcov, struct GridGeom *G, int i,
int j, int loc)
{
for (int mu = 0; mu < NDIM; mu++) {
vcov[mu][j][i] = 0.;
for (int nu = 0; nu < NDIM; nu++) {
vcov[mu][j][i] += G->gcov[loc][mu][nu][j][i]*vcon[nu][j][i];
}
}
}
// Lower the grid of contravariant rank-1 tensors to covariant ones
void lower_grid_vec(GridVector vcon, GridVector vcov, struct GridGeom *G, int jstart, int jstop, int istart, int istop, int loc)
{
#pragma omp parallel for simd collapse(3)
DLOOP1 {
ZSLOOP(jstart, jstop, istart, istop) vcov[mu][j][i] = 0.;
}
#pragma omp parallel for simd collapse(4)
DLOOP2 {
ZSLOOP(jstart, jstop, istart, istop) vcov[mu][j][i] += G->gcov[loc][mu][nu][j][i]*vcon[nu][j][i];
}
}
inline void raise_grid(GridVector vcov, GridVector vcon, struct GridGeom *G, int i, int j, int loc)
{
for (int mu = 0; mu < NDIM; mu++) {
vcon[mu][j][i] = 0.;
for (int nu = 0; nu < NDIM; nu++) {
vcon[mu][j][i] += G->gcon[loc][mu][nu][j][i]*vcov[nu][j][i];
}
}
}
// Take dot product of a contravariant and covariant rank-1 tensor
inline double dot(double vcon[NDIM], double vcov[NDIM])
{
double dot = 0.;
for (int mu = 0; mu < NDIM; mu++) {
dot += vcon[mu]*vcov[mu];
}
return dot;
}
// Minor of a 4x4 matrix
inline double MINOR(double m[16], int r0, int r1, int r2, int c0, int c1, int c2)
{
return m[4*r0+c0]*(m[4*r1+c1]*m[4*r2+c2] - m[4*r2+c1]*m[4*r1+c2]) -
m[4*r0+c1]*(m[4*r1+c0]*m[4*r2+c2] - m[4*r2+c0]*m[4*r1+c2]) +
m[4*r0+c2]*(m[4*r1+c0]*m[4*r2+c1] - m[4*r2+c0]*m[4*r1+c1]);
}
inline void adjoint(double m[16], double adjOut[16])
{
adjOut[ 0] = MINOR(m,1,2,3,1,2,3);
adjOut[ 1] = -MINOR(m,0,2,3,1,2,3);
adjOut[ 2] = MINOR(m,0,1,3,1,2,3);
adjOut[ 3] = -MINOR(m,0,1,2,1,2,3);
adjOut[ 4] = -MINOR(m,1,2,3,0,2,3);
adjOut[ 5] = MINOR(m,0,2,3,0,2,3);
adjOut[ 6] = -MINOR(m,0,1,3,0,2,3);
adjOut[ 7] = MINOR(m,0,1,2,0,2,3);
adjOut[ 8] = MINOR(m,1,2,3,0,1,3);
adjOut[ 9] = -MINOR(m,0,2,3,0,1,3);
adjOut[10] = MINOR(m,0,1,3,0,1,3);
adjOut[11] = -MINOR(m,0,1,2,0,1,3);
adjOut[12] = -MINOR(m,1,2,3,0,1,2);
adjOut[13] = MINOR(m,0,2,3,0,1,2);
adjOut[14] = -MINOR(m,0,1,3,0,1,2);
adjOut[15] = MINOR(m,0,1,2,0,1,2);
}
// Computes determinant of 4x4 tensor
inline double determinant(double m[16])
{
return m[0]*MINOR(m,1,2,3,1,2,3) -
m[1]*MINOR(m,1,2,3,0,2,3) +
m[2]*MINOR(m,1,2,3,0,1,3) -
m[3]*MINOR(m,1,2,3,0,1,2);
}
// Computes inverse of a 4x4 matrix
inline double invert(double *m, double *invOut)
{
adjoint(m, invOut);
double det = determinant(m);
double inv_det = 1. / det;
for (int i = 0; i < 16; ++i) {
invOut[i] = invOut[i]*inv_det;
}
return det;
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* insertsort_step1.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: aulopez <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2019/04/10 11:53:16 by aulopez #+# #+# */
/* Updated: 2019/04/11 16:17:42 by aulopez ### ########.fr */
/* */
/* ************************************************************************** */
#include <pushswap.h>
static inline int needs_pb(t_pushswap *ps)
{
t_stack *elem;
if (ps->a < 1)
return (0);
elem = ps->top_a;
while (elem)
{
if (elem->val == 0)
return (1);
elem = elem->prev;
}
return (0);
}
static inline int needs_sa(t_pushswap *ps, size_t best,
size_t (*mode)(t_pushswap *, size_t))
{
size_t i;
size_t j;
if (ps->a < 2)
return (0);
if (!ps_operand(ps, SA, 1))
return (-1);
j = mode(ps, best);
if (!ps_operand(ps, SA, 1))
return (-1);
i = mode(ps, best);
if (i < j)
return (1);
return (0);
}
static inline int is_it_done(t_pushswap *ps, int option)
{
t_stack *tmp;
tmp = (option == 'a') ? ps->top_a : ps->top_b;
while (tmp)
{
if (!tmp->prev)
return (1);
else if (option == 'a' && tmp->prev->index < tmp->index)
return (0);
else if (option == 'b' && tmp->prev->index > tmp->index)
return (0);
tmp = tmp->prev;
}
return (1);
}
int sort_step1(t_pushswap *ps, size_t best_index,
size_t (*mode)(t_pushswap *, size_t))
{
int i;
while (needs_pb(ps))
{
if ((i = needs_sa(ps, best_index, mode)))
{
if (i == -1 || !ps_operand(ps, SA, 1))
return (0);
mode(ps, best_index);
}
else if (ps->top_a->val == 0)
{
if (!ps_operand(ps, PB, 1))
return (0);
}
else if (!ps_operand(ps, RA, 1))
return (0);
if (is_it_done(ps, 'a'))
return (1);
}
return (1);
}
|
C
|
/* Pointers programs */
#include<stdio.h>
// malloc functions
#include<stdlib.h>
#include<string.h>
void print_char_array(char *c);
void print_2d_array(int number[][2] );
int main() {
char *c = "venu";
int num[2][2] ;
int (*p)[2] = num;
for (int i=0 ; i<2; i++ ){
for (int j=0; j<2; j++ ) {
num[i][j] = 0;
}
}
// print the character array
print_char_array (c);
print_2d_array( num );
}
// prints the character array by incrementing the pointer
// and dereferencing it till it hits the end of string character
void print_char_array(char *c ){
while ( *c != '\0' ){
printf("%c", *c);
c++;
}
}
// prints a 2d array, the method argument should have the column
// specified ahead of time so that the pointer arithmetic can be done right
void print_2d_array(int number[][2] ){
printf ("Address of 0'th is %p\n", number );
printf ("Value at 0th pointer is %d\n", **number );
printf ("Address of 1st pointer is %p\n", number + 1 );
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <malloc.h>
#include "dk_tool.h"
void swap(int *a, int *b);
void generation(int *darray, int dsize)
{
int i;
for (i = 0; i < dsize ; ++i)
{
*(darray+i)=rand() % 10000;
}
return;
}
void bubbleSort(int *darray, int dsize)
{
int i,j;
for (i = 0; i < dsize-1; ++i) {
for (j = 0; j < dsize-i-1; ++j) {
if(*(darray+j)>*(darray+j+1))
{
swap((darray+j),(darray+j+1));
}
}
}
return;
}
void selectionSort(int *darray, int dsize)
{
int temp;
int i,j;
for (i = 0; i < dsize-1; i++) {
temp=i;
for (j = i+1; j < dsize; j++) {
if (*(darray+j)<*(darray+temp))
{
temp=j;
}
}
swap((darray+temp), (darray+i));
}
return;
}
void insertSort(int *darray, int dsize)
{
int temp;
int prev_ind;
int i;
for (i = 1; i < dsize; ++i) {
temp=*(darray+i);
prev_ind=i-1;
while(prev_ind>=0 && *(darray+prev_ind) >temp)
{
*(darray+prev_ind+1) = *(darray+prev_ind);
*(darray+prev_ind) = temp;
prev_ind--;
}
}
return;
}
void shellSort(int *darray, int dsize)
{ int i, j,x;
for (x = dsize/2; x > 0; x/=2) {
for (i = x; i < dsize; ++i) {
for (j = i; j >= x && *(darray+j)<=*(darray+j-x); j-=x) {
swap((darray+j),(darray+j-x));
}
}
}
return;
}
void quickSort(int *darray, int dfirst, int dlast)
{
int i=dfirst, j=dlast, t=(dfirst+dlast)/2, x=*(darray+t);
do{
while (*(darray+i)<x) i++;
while (*(darray+j)>x) j--;
if (i<=j)
{
if (*(darray+i)>*(darray+j)) swap((darray+i),(darray+j));
i++;
j--;
}
}
while (i<=j);
if (i < dlast)
quickSort(darray, i, dlast);
if (dfirst < j)
quickSort(darray, dfirst, j);
return;
}
int scanSize()
{
int sc_sym, t;
printf("Введите размер массива(0-10000):\n");
do
{
t=scanf("%d",&sc_sym);
fflush(stdin);
if(!(t!=1 || sc_sym<0 || sc_sym>100000000)) break;
printf("%s","Неправильный ввод. Попробуйте еще раз.\n");
}
while(1);
return sc_sym;
}
void swap(int *a, int *b)
{
int c=*a;
*a=*b;
*b=c;
}
void overstoreArray(int *array_A, int *array_B, int dsize)
{
int i;
for (i = 0; i < dsize; ++i) {
*(array_B+i)=*(array_A+i);
}
}
void makeHeaderFile(FILE *d_f_save)
{
fprintf(d_f_save, "ID;P\n");
fprintf(d_f_save, "C;Y1;X2;K\"initial mass\"\n");
fprintf(d_f_save, "C;Y1;X3;K\"sort_bubble\"\n");
fprintf(d_f_save, "C;Y1;X4;K\"sort selection\"\n");
fprintf(d_f_save, "C;Y1;X5;K\"sort insert\"\n");
fprintf(d_f_save, "C;Y1;X6;K\"sort Shell\"\n");
fprintf(d_f_save, "C;Y1;X7;K\"sort Quick Sort\"\n");
fprintf(d_f_save, "C;Y2;X1;K\"Time\"\n");
return;
}
void writeTime(FILE *d_f_save, int x, int time)
{
fprintf(d_f_save, "C;Y2;X%x;K%i\n", x, time);
return;
}
void makeFutterFile(FILE *d_f_save)
{
fprintf(d_f_save, "E\n");
return;
}
void writeInFile(FILE *d_f_save, int x, int dsize, int *d_array)
{
int y=3;
int i;
for (i = 0; i < dsize; ++i, ++y) {
fprintf(d_f_save, "C;Y%i;X%i;K%i\n", y, x, *(d_array+i));
}
return;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <unistd.h>
#include "rpi-gpio.h"
// both are "nobody" on my system
#define UID_AFTER_DROP 99
#define GID_AFTER_DROP 99
static void drop_privileges(void) {
if(chdir("/") == -1) {
perror("chdir");
exit(1);
}
if(setgid(GID_AFTER_DROP) == -1) {
perror("setgid");
exit(1);
}
if(setuid(UID_AFTER_DROP) == -1) {
perror("setuid");
exit(1);
}
}
static FILE *number_file;
static unsigned int read_and_increment_number(void) {
// if it is not open, don't use the number
if(number_file == NULL) {
return 0;
}
unsigned int number;
int result = fscanf(number_file, "%u", &number);
if(result != 1) {
fprintf(stderr, "fscanf failed\n");
return 0;
}
// the first 200 are already gone
if(number <= 200)
return 0;
rewind(number_file);
fprintf(number_file, "%u", number + 1);
rewind(number_file);
return number;
}
// for testing
#define PRINTER_PATH "/dev/usb/lp0"
#define BUTTON_PIN 17
int main(void) {
gpio_init();
// init printer connection
FILE *printer = fopen(PRINTER_PATH, "w");
if(printer == NULL) {
perror("cannot open printer connection");
return 1;
}
// open number file, error handling happens in read_and_increment_number
number_file = fopen(NUMBER_FILE, "r+");
drop_privileges();
gpio_fsel(BUTTON_PIN, GPIO_INPUT);
gpio_pull(BUTTON_PIN, GPIO_PULL_UP);
// Set output lines for easier templating
const char line1[] = "\xd5\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xb8";
const char line2[] = "\xb3 \xb3";
const char line3[] = "\xb3 Du bist raus. \xb3";
const char line4pre[] = "\xb3 #";
const char line4post[] = " \xb3";
const char line5[] = "\xb3 \xb3";
const char line6[] = "\xd4\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xbe";
const int default_level = 0; // we use a pull up and an opening switch
while(1) {
int current_level = gpio_level(BUTTON_PIN);
if(current_level != default_level) {
fprintf(printer, line1);
fprintf(printer, "\r\n");
fprintf(printer, line2);
fprintf(printer, "\r\n");
fprintf(printer, line3);
fprintf(printer, "\r\n");
fprintf(printer, line4pre);
unsigned int number = read_and_increment_number();
if(number != 0) {
fprintf(printer, "%u", number);
}
fprintf(printer, line4post);
fprintf(printer, "\r\n");
fprintf(printer, line5);
fprintf(printer, "\r\n");
fprintf(printer, line6);
fprintf(printer, "\r\n");
fprintf(printer, "\r\n\r\n\r\n");
fflush(printer);
sleep(10); // don't overuse
}
// wait for 2ms
nanosleep(&(const struct timespec){.tv_sec = 0, .tv_nsec = 2000000}, NULL);
}
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>
int in=0, out=0;
int buffer[10000];
int count = 0;
int mutex = 1;
void wait(int *semaphore)
{
while(*semaphore <= 0) ;
*semaphore -= 1;
}
void signal(int *semaphore)
{
*semaphore += 1;
}
void *producer()
{
int next = 0;
while(1)
{
wait(&mutex);
next++;
printf("Producer : Produced item %d\n", next);
buffer[in++] = next;
signal(&count);
signal(&mutex);
sleep(2);
}
}
void *consumer()
{
int next;
while(1)
{
wait(&count);
wait(&mutex);
next = buffer[out++];
printf("Consumer : Consumed item %d\n", next);
signal(&mutex);
sleep(2);
}
}
int main()
{
pthread_t p_thread, c_thread;
pthread_create(&p_thread, NULL, producer, NULL);
pthread_create(&c_thread, NULL, consumer, NULL);
pthread_join(p_thread, NULL);
pthread_join(c_thread, NULL);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void mostrarEmpleados(char[][20], int[], char[], float[], int);
void mostrarEmpleado(char[], int, char, float);
void ordenamiento(char[][20], int[], char[], float[], int);
int main()
{
char nombres[5][20];
int legajos[5];
char sexo[5];
float sueldo[5];
int i;
for(i=0;i<5;i++)
{
printf("Ingrese un nombre\n");
fflush(stdin);
gets(nombres[i]);
printf("Ingrese un legajo\n");
scanf("%d", &legajos[i]);
printf("Ingrese un sexo f o m\n");
fflush(stdin);
scanf("%c", &sexo[i]);
printf("Ingrese el sueldo\n");
scanf("%f", &sueldo[i]);
}
mostrarEmpleados(nombres, legajos, sexo, sueldo, i);
ordenamiento(nombres, legajos, sexo, sueldo, i);
mostrarEmpleados(nombres, legajos, sexo, sueldo, i);
return 0;
}
void mostrarEmpleados(char nombres[][20], int legajo[], char sexo[], float sueldo[], int tam)
{
int i;
printf("Nombres Legajo Sexo Sueldo \n");
for(i=0;i<tam;i++)
{
mostrarEmpleado(nombres[i], legajo[i], sexo[i], sueldo[i]);
}
}
void mostrarEmpleado(char nombres[], int legajo, char sexo, float sueldo)
{
printf("%s %3d %5c %.2f \n", nombres, legajo, sexo, sueldo);
}
void ordenamiento(char nombres[][20], int legajo[], char sexo[], float sueldo[], int tam)
{
int i;
int j;
int auxI;
float auxF;
char auxS[20];
char auxC;
for(i=0;i<tam-1;i++)
{
for(j=i+1;j<tam;j++)
{
if(strcmp(nombres[i], nombres[j]) > 0)
{
strcpy(auxS, nombres[i]);
strcpy(nombres[i], nombres[j]);
strcpy(nombres[j], auxS);
auxI = legajo[i];
legajo[i] = legajo[j];
legajo[j] = auxI;
auxC = sexo[i];
sexo[i] = sexo[j];
sexo[j] = auxC;
auxF = sueldo[i];
sueldo[i] = sueldo[j];
sueldo[j] = auxF;
}
}
}
}
|
C
|
#include "comm.h"
int Command(int size,int flag)
{
key_t key = ftok(".",1);
if(key < 0)
{
perror("ftok");
exit(1);
}
int shmid = shmget(key,size,flag);
if(shmid < 0)
{
perror("shmget");
exit(1);
}
return shmid;
}
int CreateShm(int size)
{
return Command(size,IPC_CREAT | IPC_EXCL | 0666);
}
int OpenShm()
{
return Command(0,IPC_CREAT);
}
int DestoryShm(int shmid)
{
if(shmctl(shmid,IPC_RMID,0) < 0)
{
perror("shmctl");
exit(1);
}
return 0;
}
|
C
|
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
//structure
typedef struct account
{
int id;
char name[20];
float abal;
char bday[10];
char addrs[50];
float trns;
struct transform
{
char mode[25];
char transdate[10];
float money;
char cmnt[20];
}trans[100];
}acc;
//create account <account operation>
void create()
{
acc *s;
int num;
puts("how many account need to create:");
scanf("%d",&num);
s=(acc*)calloc(num,sizeof(acc));
//file open
FILE *fp;
fp=fopen("bank.txt","a");
//data storing ...
for(int i=0;i<num;i++)
{
puts("Enter Below details:");
sleep(1);
fflush(stdin);
s[i].trns=0.0;
puts("Enter ID number for Account:");
scanf("%d",&s[i].id);
fflush(stdin);
puts("Enter BIRTHDAY:(dd/mm/yy)");
scanf("%10s",s[i].bday);
puts("Enter ADDRESS:");
scanf("%s",s[i].addrs);
fflush(stdin);
puts("Enter NAME for Account:");
scanf("%[^\n]s",s[i].name);
//fflush(stdin);
for(int j=0;j<1;j++)
{
fflush(stdin);
puts("Enter MODE of transaction:Deposite");
//s[i].trans[j].mode=str;
scanf("%s",s[i].trans[j].mode);
fflush(stdin);
puts("Enter transaction date(dd/mm/yyyy):");
scanf("%s",s[i].trans[j].transdate);
puts("Enter MONEY:");
scanf("%f",&s[i].trans[j].money);
s[i].abal=0;
s[i].abal +=s[i].trans[j].money;
fflush(stdin);
puts("Enter comment(if any):");
scanf("%s",s[i].trans[j].cmnt);
}
fwrite(&s[i],sizeof(acc),1,fp);
{
puts("\n-----Account details-----");
printf("\nID :%i",s[i].id);
printf("\nName :%s",s[i].name);
printf("\nAvailable Balance:%.2f",s[i].abal);
printf("\nBirthday :%s",s[i].bday);
printf("\nAddress :%s",s[i].addrs);
printf("\nTotal Transaction:%.0f\n\n",s[i].trns+1);
}
}
fclose(fp);
}
//display acoount details:<account operation>
void dispaccs()
{
acc s1;
FILE *fp;
fp=fopen("bank.txt","r");
int id;
puts("Enter ID to Detail of ACCOUNT:");
scanf("%i",&id);
int flag=0;
while(fread(&s1,sizeof(acc),1,fp))
{
if(s1.id==id)
{
puts("\n-----Account details-----");
printf("\nID :%i",s1.id);
printf("\nName :%s",s1.name);
printf("\nAvailable Balance:%.2f",s1.abal);
printf("\nBirthday :%s",s1.bday);
printf("\nAddress :%s",s1.addrs);
printf("\nTotal Transaction:%.0f\n\n",s1.trns+1);
}
}
fclose(fp);
}
//del account<account operation>
void delacc()
{
acc s1;
FILE *fp,*fp1;
fp=fopen("bank.txt","r");
fp1=fopen("temp.txt","w");
int id;
puts("Enter ID to DELETE:");
scanf("%i",&id);
int flag=0;
while(fread(&s1,sizeof(acc),1,fp))
{
if(s1.id==id)
{
flag=1;
printf("account id:%d is deleted!",id);
}
else{
fwrite(&s1,sizeof(acc),1,fp1);
}
}
fclose(fp);
fclose(fp1);
if(flag==1)
{
fp=fopen("bank.txt","w");
fp1=fopen("temp.txt","r");
while(fread(&s1,sizeof(acc),1,fp1))
{
fwrite(&s1,sizeof(acc),1,fp);
}
fclose(fp);
fclose(fp1);
}
else
{
puts("data not available!");
}
}
//edit account<account operation>
void editacc()
{
acc s1;
FILE *fp,*fp1;
fp=fopen("bank.txt","r");
fp1=fopen("temp.txt","w");
int id;
puts("Enter ID to EDIT:");
scanf("%i",&id);
int flag=0;
while(fread(&s1,sizeof(acc),1,fp))
{
if(s1.id==id)
{
flag=1;
puts("Enter Below details:");
sleep(1);
fflush(stdin);
//s1.trns=;
puts("Enter ID number for Account:");
scanf("%d",&s1.id);
fflush(stdin);
puts("Enter NAME number for Account:");
scanf("%[^\n]s",s1.name);
fflush(stdin);
puts("Enter ADDRESS:");
scanf("%[^\n]s",s1.addrs);
fflush(stdin);
puts("Enter BIRTHDAY:(dd/mm/yy)");
scanf("%s",s1.bday);
fwrite(&s1,sizeof(acc),1,fp1);
//display
{
puts("\n-----Account details-----");
printf("\nID :%i",s1.id);
printf("\nName :%s",s1.name);
printf("\nAvailable Balance:%.2f",s1.abal);
printf("\nBirthday :%s",s1.bday);
printf("\nAddress :%s",s1.addrs);
printf("\nTotal Transaction:%.0f\n\n",s1.trns+1);
}
}
else{
fwrite(&s1,sizeof(acc),1,fp1);
}
}
fclose(fp);
fclose(fp1);
if(flag==1)
{
fp=fopen("bank.txt","w");
fp1=fopen("temp.txt","r");
while(fread(&s1,sizeof(acc),1,fp1))
{
fwrite(&s1,sizeof(acc),1,fp);
}
fclose(fp);
fclose(fp1);
}
else
{
puts("ACCOUNT details not available!");
}
}
//transaction detail<account operation>
void trans_det()
{
acc s1;
FILE *fp;
fp=fopen("bank.txt","r");
int id;
puts("Enter ID to Find Transaction:");
scanf("%i",&id);
int flag=0;
while(fread(&s1,sizeof(acc),1,fp))
{
if(s1.id==id)
{
flag=1;
puts("\n-----Account details-----");
printf("\nID :%i",s1.id);
printf("\nName :%s",s1.name);
printf("\nAvailable Balance:%.2f",s1.abal);
printf("\nBirthday :%s",s1.bday);
printf("\nAddress :%s",s1.addrs);
printf("\nTotal Transaction:%.0f\n\n",s1.trns+1);
puts("\n----Transaction details----");
for(int i=0;i<s1.trns+1;i++)
{
printf("\t\nTransaction :%i",i+1);
printf("\t\nMode :%s",s1.trans[i].mode);
printf("\t\nTranaction money :%.2f",s1.trans[i].money);
printf("\t\nTransaction date :%s",s1.trans[i].transdate);
printf("\t\nComments :%s",s1.trans[i].cmnt);
puts("\n-----------------------------");
}
}
}
if(flag==0){
puts("\ndata not available!");
}
fclose(fp);
}
//account operation
void accoper()
{
int i;
do
{
puts("\n-----ACCOUNT OPERATION-----");
puts("\n1.CREATE ACCOUNT");
puts("2.DELETE ACCOUNT");
puts("3.TRANSACTION DETAILS OF ACCOUNT");
puts("4.EDIT ACCOUNT");
puts("5.DISPLAY ACCOUNT");
puts("0.EXIT");
puts("\n-----^^^^^^^^^^^^^^^-----");
puts("Choose operation need to perform:");
scanf("%d",&i);
switch(i)
{
case 1:
{
create();
break;
}
case 2:
{
delacc();
break;
}
case 3:
{
trans_det();
break;
}
case 4:
{
editacc();
break;
}
case 5:
{
dispaccs();
break;
}
}
}while(i!=0);
}
//1.deposite<transaction_operation>
void deposite()
{
acc s1;
FILE *fp,*fp1;
fp=fopen("bank.txt","r");
fp1=fopen("temp.txt","w");
int id;
puts("Enter ID to DEPOSITE:");
scanf("%i",&id);
int flag=0;
while(fread(&s1,sizeof(acc),1,fp))
{
if(s1.id==id)
{
flag=1;
puts("Enter Below details:");
for(int j=s1.trns+1;j<s1.trns+2;j++)
{
fflush(stdin);
puts("Enter MODE of transaction:Deposite");
scanf("%s",s1.trans[j].mode);
fflush(stdin);
puts("Enter transaction date(dd/mm/yyyy):");
scanf("%s",s1.trans[j].transdate);
puts("Enter MONEY:");
scanf("%f",&s1.trans[j].money);
s1.abal +=s1.trans[j].money;
fflush(stdin);
puts("Enter comment(if any):");
scanf("%s",s1.trans[j].cmnt);
}
s1.trns +=1;
fwrite(&s1,sizeof(acc),1,fp1);
{
puts("\n-----Account details-----");
printf("\nID :%i",s1.id);
printf("\nName :%s",s1.name);
printf("\nAvailable Balance:%.2f",s1.abal);
printf("\nBirthday :%s",s1.bday);
printf("\nAddress :%s",s1.addrs);
printf("\nTotal Transaction:%.0f\n\n",s1.trns+1);
}
}
else{
fwrite(&s1,sizeof(acc),1,fp1);
}
}
fclose(fp);
fclose(fp1);
if(flag==1)
{
fp=fopen("bank.txt","w");
fp1=fopen("temp.txt","r");
while(fread(&s1,sizeof(acc),1,fp1))
{
fwrite(&s1,sizeof(acc),1,fp);
}
fclose(fp);
fclose(fp1);
}
else
{
puts("ACCOUNT not available!");
}
}
//withdrawoperation<transaction_operation>
void withdraw()
{
acc s1;
FILE *fp,*fp1;
fp=fopen("bank.txt","r");
fp1=fopen("temp.txt","w");
int id;
puts("Enter ID to WITHDRAW:");
scanf("%i",&id);
int flag=0;
while(fread(&s1,sizeof(acc),1,fp))
{
if(s1.id==id)
{
flag=1;
puts("Enter Below details:");
for(int j=s1.trns+1;j<s1.trns+2;j++)
{
fflush(stdin);
puts("Enter MODE of transaction:<WITHDRAW>");
scanf("%s",s1.trans[j].mode);
fflush(stdin);
puts("Enter transaction date(dd/mm/yyyy):");
scanf("%s",s1.trans[j].transdate);
puts("Enter MONEY to wthdraw:");
scanf("%f",&s1.trans[j].money);
if(s1.abal >= s1.trans[j].money +500)
{
s1.abal -=s1.trans[j].money;
}
else
{
puts("your are not ENTITLED to withdraw check your balance its crossing minimum balance");
break;
}
fflush(stdin);
puts("Enter comment(if any):");
scanf("%s",s1.trans[j].cmnt);
}
s1.trns +=1;
{
puts("\n-----Account details-----");
printf("\nID :%i",s1.id);
printf("\nName :%s",s1.name);
printf("\nAvailable Balance:%.2f",s1.abal);
printf("\nBirthday :%s",s1.bday);
printf("\nAddress :%s",s1.addrs);
printf("\nTotal Transaction:%.0f\n\n",s1.trns+1);
}
fwrite(&s1,sizeof(acc),1,fp1);
}
else{
fwrite(&s1,sizeof(acc),1,fp1);
}
}
fclose(fp);
fclose(fp1);
if(flag==1)
{
fp=fopen("bank.txt","w");
fp1=fopen("temp.txt","r");
while(fread(&s1,sizeof(acc),1,fp1))
{
fwrite(&s1,sizeof(acc),1,fp);
}
fclose(fp);
fclose(fp1);
}
else
{
puts("ACCOUNT details not available!");
}
}
//acc_to_acc_transfer<transaction_operation>
void acc_to_acc_transfer()
{
//withdraw account
acc s1;
FILE *fp,*fp1;
float mon;
fp=fopen("bank.txt","r");
fp1=fopen("temp.txt","w");
int id;
puts("Enter ID to WITHDRAW:");
scanf("%i",&id);
int flag=0;
while(fread(&s1,sizeof(acc),1,fp))
{
if(s1.id==id)
{
puts("Enter Below details:");
for(int j=s1.trns+1;j<s1.trns+2;j++)
{
fflush(stdin);
puts("Enter MODE of transaction:<WITHDRAW>");
scanf("%s",s1.trans[j].mode);
fflush(stdin);
puts("Enter transaction date(dd/mm/yyyy):");
scanf("%s",s1.trans[j].transdate);
puts("Enter MONEY to wthdraw:");
scanf("%f",&mon);
s1.trans[j].money=mon;
if(s1.abal >= s1.trans[j].money +500)
{
s1.abal -=s1.trans[j].money;
flag=1;
}
else
{
puts("your are not ENTITLED to withdraw check your balance its crossing minimum balance");
break;
}
fflush(stdin);
puts("Enter comment(if any):");
scanf("%s",s1.trans[j].cmnt);
}
s1.trns +=1;
{
puts("\n-----Account details-----");
printf("\nID :%i",s1.id);
printf("\nName :%s",s1.name);
printf("\nAvailable Balance:%.2f",s1.abal);
printf("\nBirthday :%s",s1.bday);
printf("\nAddress :%s",s1.addrs);
printf("\nTotal Transaction:%.0f\n\n",s1.trns+1);
}
fwrite(&s1,sizeof(acc),1,fp1);
}
else{
fwrite(&s1,sizeof(acc),1,fp1);
}
}
fclose(fp);
fclose(fp1);
if(flag==1)
{
fp=fopen("bank.txt","w");
fp1=fopen("temp.txt","r");
while(fread(&s1,sizeof(acc),1,fp1))
{
fwrite(&s1,sizeof(acc),1,fp);
}
fclose(fp);
fclose(fp1);
}
else
{
puts("ACCOUNT details not available!");
}
//deposite
//acc s1;
//FILE *fp,*fp1;
fp=fopen("bank.txt","r");
fp1=fopen("temp.txt","w");
//int id;
if(flag==1)
{
puts("Enter ID to DEPOSITE:");
scanf("%i",&id);
//int flag=0;
while(fread(&s1,sizeof(acc),1,fp))
{
if(s1.id==id)
{
flag=1;
puts("Enter Below details:");
for(int j=s1.trns+1;j<s1.trns+2;j++)
{
fflush(stdin);
puts("Enter MODE of transaction:Deposite");
scanf("%s",s1.trans[j].mode);
fflush(stdin);
puts("Enter transaction date(dd/mm/yyyy):");
scanf("%s",s1.trans[j].transdate);
//puts("Enter MONEY:");
//scanf("%f",&s1.trans[j].money);
s1.trans[j].money=mon;
s1.abal +=s1.trans[j].money;
fflush(stdin);
puts("Enter comment(if any):");
scanf("%s",s1.trans[j].cmnt);
}
s1.trns +=1;
{
puts("\n-----Account details-----");
printf("\nID :%i",s1.id);
printf("\nName :%s",s1.name);
printf("\nAvailable Balance:%.2f",s1.abal);
printf("\nBirthday :%s",s1.bday);
printf("\nAddress :%s",s1.addrs);
printf("\nTotal Transaction:%.0f\n\n",s1.trns+1);
}
fwrite(&s1,sizeof(acc),1,fp1);
}
else{
fwrite(&s1,sizeof(acc),1,fp1);
}
}
fclose(fp);
fclose(fp1);
if(flag==1)
{
fp=fopen("bank.txt","w");
fp1=fopen("temp.txt","r");
while(fread(&s1,sizeof(acc),1,fp1))
{
fwrite(&s1,sizeof(acc),1,fp);
}
fclose(fp);
fclose(fp1);
}
/*else
{
puts("ACCOUNT not available!");
}*/
}
}
//transaction_operation
void transaction_operation()
{
int i;
do
{
puts("\n-----TRANSACTION OPERATION-----");
puts("\n1.DEPOSITE ACCOUNT");
puts("2.WITHDRAW ACCOUNT");
puts("3.ACCOUNT TO ACCOUNT TRANSFER");
puts("0.EXIT");
puts("\n-----^^^^^^^^^^^^^^^-----");
puts("Choose Operation Need To Perform:");
scanf("%d",&i);
switch(i)
{
case 1:
{
deposite();
break;
}
case 2:
{
withdraw();
break;
}
case 3:
{
acc_to_acc_transfer();
break;
}
}
}while(i!=0);
}
//short_byBal<filter>
void short_byBal()
{
acc *s,s1;
FILE *fp;
fp=fopen("bank.txt","r");
fseek(fp,0,SEEK_END);
int n=ftell(fp)/sizeof(acc);
rewind(fp);
s=(acc*)calloc(n,sizeof(acc)) ;
for(int i=0;i<n;i++)
{
fread(&s[i],sizeof(acc),1,fp);
}
fclose(fp);
for(int i=1;i<n;i++)
{
for(int j=0;j<n;j++)
{
if(s[i].abal>s[j].abal)
{
s1=s[j];
s[j]=s[i];
s[i]=s1;
}
}
}
//print shorted
for(int i=0;i<n;i++)
{
puts("\n-----Account details-----");
printf("\nID :%i",s[i].id);
printf("\nName :%s",s[i].name);
printf("\nAvailable Balance:%.2f",s[i].abal);
printf("\nBirthday :%s",s[i].bday);
printf("\nAddress :%s",s[i].addrs);
printf("\nTotal Transaction:%.0f\n\n",s[i].trns+1);
}
}
//short_byName<filter>
void short_byName()
{
acc *s,s1;
FILE *fp;
fp=fopen("bank.txt","r");
fseek(fp,0,SEEK_END);
int n=ftell(fp)/sizeof(acc);
rewind(fp);
s=(acc*)calloc(n,sizeof(acc)) ;
for(int i=0;i<n;i++)
{
fread(&s[i],sizeof(acc),1,fp);
}
fclose(fp);
for(int i=1;i<n;i++)
{
for(int j=0;j<n;j++)
{
if(s[i].name[0]>s[j].name[0])
//if(strcmp(s[i].name,s[j].name)>0)
//if(strcmp(s[i]name,s[j].name)>0)
{
//strcmp
s1=s[j];
s[j]=s[i];
s[i]=s1;
}
}
}
//print shorted
for(int i=0;i<n;i++)
{
puts("\n-----Account details-----");
printf("\nID :%i",s[i].id);
printf("\nName :%s",s[i].name);
printf("\nAvailable Balance:%.2f",s[i].abal);
printf("\nBirthday :%s",s[i].bday);
printf("\nAddress :%s",s[i].addrs);
printf("\nTotal Transaction:%.0f\n\n",s[i].trns+1);
}
}
//short_byTransaction<filter>
void short_byTransaction()
{
acc *s,s1;
FILE *fp;
fp=fopen("bank.txt","r");
fseek(fp,0,SEEK_END);
int n=ftell(fp)/sizeof(acc);
rewind(fp);
s=(acc*)calloc(n,sizeof(acc)) ;
for(int i=0;i<n;i++)
{
fread(&s[i],sizeof(acc),1,fp);
}
fclose(fp);
for(int i=1;i<n;i++)
{
for(int j=0;j<n;j++)
{
if(s[i].trns>s[j].trns)
{
s1=s[j];
s[j]=s[i];
s[i]=s1;
}
}
}
//print shorted
for(int i=0;i<n;i++)
{
puts("\n-----Account details-----");
printf("\nID :%i",s[i].id);
printf("\nName :%s",s[i].name);
printf("\nAvailable Balance:%.2f",s[i].abal);
printf("\nBirthday :%s",s[i].bday);
printf("\nAddress :%s",s[i].addrs);
printf("\nTotal Transaction:%.0f\n\n",s[i].trns+1);
}
}
//filter
void shortr()
{
int i;
do
{
puts("\n-----SHORT OPERATION-----");
puts("\n1.SHORT BY BALANCE");
puts("2.SHORT BY NAME");
puts("3.SHORT BY TRANSACTION");
puts("0.EXIT");
puts("\n-----^^^^^^^^^^^^^^^-----");
puts("Choose operation need to perform:");
scanf("%d",&i);
switch(i)
{
case 1:
{
short_byBal();
break;
}
case 2:
{
short_byName();
break;
}
case 3:
{
short_byTransaction();
break;
}
case 4:
{
editacc();
break;
}
case 5:
{
dispaccs();
break;
}
}
}while(i!=0);
}
//account_data<branch_det>
void account_data()
{
acc s1;
FILE *fp;
fp=fopen("bank.txt","r");
while(fread(&s1,sizeof(acc),1,fp))
{
{
//flag=1;
puts("\n-----Account details-----");
printf("\nID :%i",s1.id);
printf("\nName :%s",s1.name);
printf("\nAvailable Balance:%.2f",s1.abal);
printf("\nBirthday :%s",s1.bday);
printf("\nAddress :%s",s1.addrs);
printf("\nTotal Transaction:%.0f\n\n",s1.trns+1);
puts("\n----Transaction details----");
for(int i=0;i<s1.trns+1;i++)
{
printf("\t\t\nTransaction :%i",i+1);
printf("\t\t\nMode :%s",s1.trans[i].mode);
printf("\t\t\nTranaction money :%.2f",s1.trans[i].money);
printf("\t\t\nTransaction date :%s",s1.trans[i].transdate);
printf("\t\t\nComments :%s",s1.trans[i].cmnt);
puts("\t\t\n-----------------------------");
}
}
}
fclose(fp);
}
//avail_bal<branch_det>
void avail_bal()
{
acc s1;
FILE *fp;
fp=fopen("bank.txt","r");
float total_avlbal=0;
while(fread(&s1,sizeof(acc),1,fp))
{
total_avlbal +=s1.abal;
}
puts("\n-----AVILABLE BALANCE-----");
printf("\nTotal AVILABLE BALANCE:%.2f\n\n",total_avlbal);
puts("\n-----^^^^^^^^^^^^^^^-----");
fclose(fp);
}
//total_avail_accounts<branch_det>
void total_avail_accounts()
{
acc *s,s1;
FILE *fp;
fp=fopen("bank.txt","r");
fseek(fp,0,SEEK_END);
int n=ftell(fp)/sizeof(acc);
puts("\n-----AVILABLE BALANCE-----");
printf("\nTotal AVILABLE ACCOUNT:%i\n\n",n);
puts("\n-----^^^^^^^^^^^^^^^-----");
fclose(fp);
}
//branch_det
void branch_det()
{
int i;
do
{
puts("\n-----BRANCH DETAILS-----");
puts("\n1.ACCOUNT DATA");
puts("2.TOTAL AVILABLE BALANCE");
puts("3.TOTAL AVILABLE ACCOUNT");
puts("0.EXIT");
puts("\n-----^^^^^^^^^^^^^^^-----");
puts("Choose operation need to perform:");
scanf("%d",&i);
switch(i)
{
case 1:
{
account_data();
break;
}
case 2:
{
avail_bal();
break;
}
case 3:
{
total_avail_accounts();
break;
}
case 4:
{
editacc();
break;
}
case 5:
{
dispaccs();
break;
}
}
}while(i!=0);
}
int main()
{
puts("------- WELCOME -------");
int ch;//option chooser
do
{
//menu starts
puts("\n-----BANK OPERATION-----");
puts("1.ACCOUNT OPERATION");
puts("2.TRANSACTION OPERATION");
puts("3.SHORT OPERATION");
puts("4.BRANCH DETAILS");
///puts("5.OTHERS");
puts("0.EXIT");//menu ends
puts("\n-----^^^^^^^^^^^^^^^-----");
puts("Choose operation need to perform:");
scanf("%d",&ch);
switch(ch)
{
case 1:
{
accoper();
break;
}
case 2:
{
transaction_operation();
break;
}
case 3:
{
shortr();
break;
}
case 4:
{
branch_det();
break;
}
}
}while(ch !=0);
return 0;
}
|
C
|
#include<stdio.h>
int main()
{
int a[50][50],i,j,sum=0;
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
scanf("%d",&a[i][j]);
}
}
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
if(i==j)
{
sum=sum+a[i][j];
}
}
}
printf("sum is : %d",sum);
}
|
C
|
/*Finding the value of function
f(x)=sqrt(3x^3 + 2x^2 + 4)using
pow() and sqrt() function*/
#include<stdio.h>
#include<math.h>
int main()
{
double x, result;
printf("Enter the value of x:");
scanf("%lf", &x);
//using sqrt() and Pow() function for getting the result
result = sqrt(3*pow(x,3)+2*pow(x,2)+4);
printf("f(x)\n=(3x^3 + 2x^2 + 4)^(1/2)\n=(3(%lf)^3 + 2(%lf)^2 + 4)^(1/2)\n=(%lf)", x, x, result);
return 0;
}
|
C
|
//编写一段程序,输入6名学生2门课程(语文、数学)的分数,
//显示各门课程的总分和平均分,以及各个学生的总分和平均分。
#include <stdio.h>
int main(void) {
int stu[6][2];
int i, j;
int sum1 = 0;
int sum2 = 0;
printf("输入学生分数: \n");
for (i = 0; i < 6; i++)
for (j = 0; j < 2; j++) {
printf("No.%d学生第%d门成绩: ", i + 1, j + 1);
scanf("%d", &stu[i][j]);
}
for (i = 0; i < 6; i++) {
sum1 = stu[i][0] + stu[i][1];
printf("第%d名学生成绩两门总分 %d,平均分%f\n", i, sum1,(double)sum1 / 2);
}
for (i = 0; i < 6; i++) {
sum2 += stu[i][0];
}
printf("第一门总分%d,平均分%f\n", sum2,(double)sum2 / 6);
for (i = 0; i < 6; i++) {
sum2 += stu[i][1];
}
printf("第二门总分%d\n", sum2);
return 0;
}
|
C
|
#include "hash_tables.h"
/**
* hash_table_get - retrieves a value associated with a key.
* @ht: Hash table
* @key: key
* Return: The value associated to the key
*/
char *hash_table_get(const hash_table_t *ht, const char *key)
{
int index;
hash_node_t *temp = NULL;
char *value = NULL;
/* check if table exist */
if (ht == NULL || key == NULL)
return (NULL);
/* assign the index */
index = key_index((const unsigned char *)key, ht->size);
/* start the search into array 🚀 */
temp = ht->array[index];
while (temp != NULL)
{
if (strcmp(temp->key, key) == 0)
{
value = temp->value;
break;
}
temp = temp->next;
}
/* does not exist the key */
if (temp == NULL)
return (NULL);
/** the key exist ✅ */
return (value);
}
|
C
|
//#include <stdio.h>
//
//int main(void)
//{
// int nInput = 0;
// const int nCUTOFF = 70;
//
// printf(" Էϼ. : ");
// scanf_s("%d", &nInput);
// /*printf("%d", nInput);*/
//
// if (nInput >= nCUTOFF) printf("հԴϴ.\n");
// else printf("հԴϴ.\n");
//
// nCUTOFF = 80;
//
// return 0;
//}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* vectors_ops.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: ikrkharb <ikrkharb@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2020/01/02 20:20:14 by ikrkharb #+# #+# */
/* Updated: 2020/02/23 20:49:46 by ikrkharb ### ########.fr */
/* */
/* ************************************************************************** */
#include "../includes/rtv1.h"
float vec_dot(t_vector v1, t_vector v2)
{
return ((v1.x * v2.x) + (v1.y * v2.y) + (v1.z * v2.z));
}
t_vector vec_sub(t_vector v1, t_vector v2)
{
return ((t_vector){v1.x - v2.x, v1.y - v2.y, v1.z - v2.z});
}
t_vector vec_sum(t_vector v1, t_vector v2)
{
return ((t_vector){v1.x + v2.x, v1.y + v2.y, v1.z + v2.z});
}
t_vector vec_cross(t_vector v1, t_vector v2)
{
t_vector res;
res.x = (v1.y * v2.z) - (v1.z * v2.y);
res.y = (v1.z * v2.x) - (v1.x * v2.z);
res.z = (v1.x * v2.y) - (v1.y * v2.x);
return (res);
}
t_vector vec_normalize(t_vector v)
{
float norme;
t_vector r;
norme = sqrt((v.x * v.x) + (v.y * v.y) + (v.z * v.z));
if (!norme)
return ((t_vector){0.0, 0.0, 0.0});
r.x = v.x / norme;
r.y = v.y / norme;
r.z = v.z / norme;
return (r);
}
|
C
|
/*
* Copyright 2021 Aaron Barany
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#pragma once
#include <DeepSea/Core/Config.h>
#include <DeepSea/Render/Export.h>
#include <DeepSea/Render/Types.h>
#ifdef __cplusplus
extern "C"
{
#endif
/**
* @file
* @brief Functions for initializing and using shadow cull volumes.
*
* A shadow cull volume can either be for a directional light or a light projection. The light
* projection would either be used for a spot light or one portion of a point light.
*
* The cull volume not only tests if a shape is inside the volume, but also clamps the points of the
* shape to the volume for building the shadow projection.
*
* @see dsShadowCullVolume
*/
/**
* @brief Builds a shadow cull volume for a directional light.
* @remark errno will be set on failure.
* @param volume The cull volume to initialize.
* @param viewFrustum The frustum defining the view in world space. This frustum should be
* normalized.
* @param toLight The direction to the light.
* @return False if the parameters are invalid.
*/
DS_RENDER_EXPORT bool dsShadowCullVolume_buildDirectional(dsShadowCullVolume* volume,
const dsFrustum3f* viewFrustum, const dsVector3f* toLight);
/**
* @brief Builds a shadow cull volume for a spot light.
*
* This can also be used for a cube face for a point light.
*
* @remark errno will be set on failure.
* @param volume The cull volume to initialize.
* @param viewFrustum The frustum defining the view in world space. This frustum should be
* normalized.
* @param lightFrustum The frustum defining the light in world space. The near plane will be
* ignored since a non-zero near is required to create a well-formed frustum and conceptually
* the light starts at a point, This frustum should be normalized.
* @return False if the parameters are invalid.
*/
DS_RENDER_EXPORT bool dsShadowCullVolume_buildSpot(dsShadowCullVolume* volume,
const dsFrustum3f* viewFrustum, const dsFrustum3f* lightFrustum);
/**
* @brief Intersects an aligned box with a shadow cull volume.
* @param volume The cull volume to intersect.
* @param box The aligned box to intersect with.
* @param shadowProj Optional shadow projection to add the results to. If not NULL, and the box
* intersects with the volume, the corners will be clamped to the volume and added to the
* projection.
* @param clampToVolume Whether or not to clamp the bounds to the cull volume when adding points to
* the shadow projection. This can be error prone in some situations, so it's only recommended
* for larger bounds that could expand the shadow projection too much.
* @return The intersection result. Inside and outside is with respect to the volume. If the box
* fully contains the frustum, dsIntersectResult_Intersects will be returned.
*/
DS_RENDER_EXPORT dsIntersectResult dsShadowCullVolume_intersectAlignedBox(
const dsShadowCullVolume* volume, const dsAlignedBox3f* box, dsShadowProjection* shadowProj,
bool clampToVolume);
#if DS_HAS_SIMD
/**
* @brief Intersects an aligned box with a shadow cull volume using SIMD operations.
* @remark This can be used when dsSIMDFeatures_Float4 is available.
* @param volume The cull volume to intersect.
* @param box The aligned box to intersect with.
* @param shadowProj Optional shadow projection to add the results to. If not NULL, and the box
* intersects with the volume, the corners will be clamped to the volume and added to the
* projection.
* @param clampToVolume Whether or not to clamp the bounds to the cull volume when adding points to
* the shadow projection. This can be error prone in some situations, so it's only recommended
* for larger bounds that could expand the shadow projection too much.
* @return The intersection result. Inside and outside is with respect to the volume. If the box
* fully contains the frustum, dsIntersectResult_Intersects will be returned.
*/
DS_RENDER_EXPORT dsIntersectResult dsShadowCullVolume_intersectAlignedBoxSIMD(
const dsShadowCullVolume* volume, const dsAlignedBox3f* box, dsShadowProjection* shadowProj,
bool clampToVolume);
/**
* @brief Intersects an aligned box with a shadow cull volume using fused multiply-add operations.
* @remark This can be used when dsSIMDFeatures_FMA is available.
* @param volume The cull volume to intersect.
* @param box The aligned box to intersect with.
* @param shadowProj Optional shadow projection to add the results to. If not NULL, and the box
* intersects with the volume, the corners will be clamped to the volume and added to the
* projection.
* @param clampToVolume Whether or not to clamp the bounds to the cull volume when adding points to
* the shadow projection. This can be error prone in some situations, so it's only recommended
* for larger bounds that could expand the shadow projection too much.
* @return The intersection result. Inside and outside is with respect to the volume. If the box
* fully contains the frustum, dsIntersectResult_Intersects will be returned.
*/
DS_RENDER_EXPORT dsIntersectResult dsShadowCullVolume_intersectAlignedBoxFMA(
const dsShadowCullVolume* volume, const dsAlignedBox3f* box, dsShadowProjection* shadowProj,
bool clampToVolume);
#endif
/**
* @brief Intersects an oriented box with a shadow cull volume.
* @param volume The cull volume to intersect.
* @param box The oriented box to intersect with.
* @param shadowProj Optional shadow projection to add the results to. If not NULL, and the box
* intersects with the volume, the corners will be clamped to the volume and added to the
* projection.
* @param clampToVolume Whether or not to clamp the bounds to the cull volume when adding points to
* the shadow projection. This can be error prone in some situations, so it's only recommended
* for larger bounds that could expand the shadow projection too much.
* @return The intersection result. Inside and outside is with respect to the volume. If the box
* fully contains the frustum, dsIntersectResult_Intersects will be returned.
*/
DS_RENDER_EXPORT dsIntersectResult dsShadowCullVolume_intersectOrientedBox(
const dsShadowCullVolume* volume, const dsOrientedBox3f* box, dsShadowProjection* shadowProj,
bool clampToVolume);
#if DS_HAS_SIMD
/**
* @brief Intersects an oriented box with a shadow cull volume using SIMD operations.
* @remark This can be used when dsSIMDFeatures_Float4 is available.
* @param volume The cull volume to intersect.
* @param box The oriented box to intersect with.
* @param shadowProj Optional shadow projection to add the results to. If not NULL, and the box
* intersects with the volume, the corners will be clamped to the volume and added to the
* projection.
* @param clampToVolume Whether or not to clamp the bounds to the cull volume when adding points to
* the shadow projection. This can be error prone in some situations, so it's only recommended
* for larger bounds that could expand the shadow projection too much.
* @return The intersection result. Inside and outside is with respect to the volume. If the box
* fully contains the frustum, dsIntersectResult_Intersects will be returned.
*/
DS_RENDER_EXPORT dsIntersectResult dsShadowCullVolume_intersectOrientedBoxSIMD(
const dsShadowCullVolume* volume, const dsOrientedBox3f* box, dsShadowProjection* shadowProj,
bool clampToVolume);
/**
* @brief Intersects an oriented box with a shadow cull volume using FMA operations.
* @remark This can be used when dsSIMDFeatures_FMA is available.
* @param volume The cull volume to intersect.
* @param box The oriented box to intersect with.
* @param shadowProj Optional shadow projection to add the results to. If not NULL, and the box
* intersects with the volume, the corners will be clamped to the volume and added to the
* projection.
* @param clampToVolume Whether or not to clamp the bounds to the cull volume when adding points to
* the shadow projection. This can be error prone in some situations, so it's only recommended
* for larger bounds that could expand the shadow projection too much.
* @return The intersection result. Inside and outside is with respect to the volume. If the box
* fully contains the frustum, dsIntersectResult_Intersects will be returned.
*/
DS_RENDER_EXPORT dsIntersectResult dsShadowCullVolume_intersectOrientedBoxFMA(
const dsShadowCullVolume* volume, const dsOrientedBox3f* box, dsShadowProjection* shadowProj,
bool clampToVolume);
#endif
/**
* @brief Intersects a box in matrix form with a shadow cull volume.
* @param volume The cull volume to intersect.
* @param boxMatrix The oriented box to intersect with.
* @param shadowProj Optional shadow projection to add the results to. If not NULL, and the box
* intersects with the volume, the corners will be clamped to the volume and added to the
* projection.
* @param clampToVolume Whether or not to clamp the bounds to the cull volume when adding points to
* the shadow projection. This can be error prone in some situations, so it's only recommended
* for larger bounds that could expand the shadow projection too much.
* @return The intersection result. Inside and outside is with respect to the volume. If the box
* fully contains the frustum, dsIntersectResult_Intersects will be returned.
*/
DS_RENDER_EXPORT dsIntersectResult dsShadowCullVolume_intersectBoxMatrix(
const dsShadowCullVolume* volume, const dsMatrix44f* boxMatrix, dsShadowProjection* shadowProj,
bool clampToVolume);
#if DS_HAS_SIMD
/**
* @brief Intersects a box in matrix form with a shadow cull volume using SIMD operations.
* @remark This can be used when dsSIMDFeatures_Float4 is available.
* @param volume The cull volume to intersect.
* @param boxMatrix The oriented box to intersect with.
* @param shadowProj Optional shadow projection to add the results to. If not NULL, and the box
* intersects with the volume, the corners will be clamped to the volume and added to the
* projection.
* @param clampToVolume Whether or not to clamp the bounds to the cull volume when adding points to
* the shadow projection. This can be error prone in some situations, so it's only recommended
* for larger bounds that could expand the shadow projection too much.
* @return The intersection result. Inside and outside is with respect to the volume. If the box
* fully contains the frustum, dsIntersectResult_Intersects will be returned.
*/
DS_RENDER_EXPORT dsIntersectResult dsShadowCullVolume_intersectBoxMatrixSIMD(
const dsShadowCullVolume* volume, const dsMatrix44f* boxMatrix, dsShadowProjection* shadowProj,
bool clampToVolume);
/**
* @brief Intersects a box in matrix form with a shadow cull volume using FMA operations.
* @remark This can be used when dsSIMDFeatures_FMA is available.
* @param volume The cull volume to intersect.
* @param boxMatrix The oriented box to intersect with.
* @param shadowProj Optional shadow projection to add the results to. If not NULL, and the box
* intersects with the volume, the corners will be clamped to the volume and added to the
* projection.
* @param clampToVolume Whether or not to clamp the bounds to the cull volume when adding points to
* the shadow projection. This can be error prone in some situations, so it's only recommended
* for larger bounds that could expand the shadow projection too much.
* @return The intersection result. Inside and outside is with respect to the volume. If the box
* fully contains the frustum, dsIntersectResult_Intersects will be returned.
*/
DS_RENDER_EXPORT dsIntersectResult dsShadowCullVolume_intersectBoxMatrixFMA(
const dsShadowCullVolume* volume, const dsMatrix44f* boxMatrix, dsShadowProjection* shadowProj,
bool clampToVolume);
#endif
/**
* @brief Intersects a sphere a shadow cull volume.
* @param volume The cull volume to intersect.
* @param center The center of the sphere.
* @param radius The radius of the sphere.
* @param shadowProj Optional shadow projection to add the results to. If not NULL, and the sphere
* intersects with the volume, the corners of a box fitting the sphere will be clamped to the
* volume and added to the projection.
* @param clampToVolume Whether or not to clamp the bounds to the cull volume when adding points to
* the shadow projection. This can be error prone in some situations, so it's only recommended
* for larger bounds that could expand the shadow projection too much.
* @return The intersection result. Inside and outside is with respect to the volume. If the sphere
* fully contains the frustum, dsIntersectResult_Intersects will be returned.
*/
DS_RENDER_EXPORT dsIntersectResult dsShadowCullVolume_intersectSphere(
const dsShadowCullVolume* volume, const dsVector3f* center, float radius,
dsShadowProjection* shadowProj, bool clampToVolume);
#ifdef __cplusplus
}
#endif
|
C
|
int main()
{
int *p;
f(p);
}
void f(int *p)
{
printf("%d\n", *p);
}
|
C
|
/**
* @file HuffmanDecoder.c
* @brief The implementation of the huffman decoder (NeXaS flavor).
* @copyright Covered by 2-clause BSD, please refer to license.txt.
* @author CloudiDust
* @date 2010.02
*/
#include <stdlib.h>
#include <string.h>
#include "Logger.h"
#include "BitStream.h"
#include "HuffmanCode.h"
/**
* Using an compact array representation of the huffman tree,
* which can have at most 256 leaves, and 256 - 1 = 255 internal nodes.
* As the only valuable information about leaves are the byte value
* they represent, we can just store that value in their parents' lchild
* and rchild links. So these links serve two purposes, either they are
* links to child internal nodes (in this case their value will be the
* child's index) or they represent the child leaf nodes' value.
* (between 0 + 1024 and 255 + 1024)
*/
struct TreeNode {
u16 lchild;
u16 rchild;
};
typedef struct TreeNode TreeNode;
static bool subTreeCreationWorker(const wchar_t* treeName, TreeNode tree[], BitStream* bs, u16* subTreeRoot, u16* freeSlotIndex) {
byte rbyte = 0;
if (!bsNextBit(bs, &rbyte)) {
writeLog(LOG_QUIET, L"ERROR: Unable to generate huffman tree for %s: encoded data exhausted!", treeName);
return false;
}
if (rbyte) {
/**
* An '1' means we should recursively generate the subtrees of the
* current node (preorder traversal indeed).
* "Allocate space" for the current node then recur.
*/
*subTreeRoot = (*freeSlotIndex)++;
if (*subTreeRoot == 256) {
writeLog(LOG_QUIET, L"ERROR: Unable to generate huffman tree for %s: encoded data corrupted!", treeName);
return false;
}
u16 childRoot = 0;
if (!subTreeCreationWorker(treeName, tree, bs, &childRoot, freeSlotIndex))
return false;
tree[*subTreeRoot].lchild = childRoot;
if (!subTreeCreationWorker(treeName, tree, bs, &childRoot, freeSlotIndex))
return false;
tree[*subTreeRoot].rchild = childRoot;
return true;
} else {
/**
* A '0' means the current node is a leaf node and the 8-bit
* data following is the byte value of this leaf.
* A Leaf node's value is stored directly in its parent's links.
* So for this subtree we just return the byte value + 1024.
*/
if (!bsNextByte(bs, &rbyte)) {
writeLog(LOG_QUIET,L"ERROR: Cannot generate huffman tree for %s: encoded data exhausted!", treeName);
return false;
}
*subTreeRoot = rbyte + 1024;
return true;
}
return false;
}
static bool createTree(const wchar_t* treeName, TreeNode tree[], BitStream* bs) {
writeLog(LOG_VERBOSE, L"Creating huffman tree for %s...", treeName);
u16 treeRoot = 0;
u16 freeSlotIndex = 0;
subTreeCreationWorker(treeName, tree, bs, &treeRoot, &freeSlotIndex);
/**
* The return tree root will not be 0 if it is a tree with only one node,
* which means the tree is corrupted.
* The freeSlotIndex doesn't have to be 256 in the end, as the original
* data may not contain all 256 byte values, and the tree will be smaller,
* thus taking up less than 255 slots.
*/
if (treeRoot != 0) {
writeLog(LOG_QUIET, L"ERROR: Cannot generate huffman tree for %s: encoded data exhausted!", treeName);
return false;
}
writeLog(LOG_VERBOSE, L"The huffman tree for %s is created, node count: %u.", treeName, freeSlotIndex);
return true;
}
static ByteArray* decodeWithTree(const wchar_t* treeName, TreeNode tree[], BitStream* data, u32 originalLen) {
u16 treeIndex = 0;
u32 resIndex = 0;
byte rbyte = 0;
ByteArray* result = newByteArray(originalLen);
while (true) {
if (!bsNextBit(data, &rbyte)) {
writeLog(LOG_QUIET, L"ERROR: Cannot decode the huffman code for %s: encoded data exhausted!", treeName);
return false;
}
if (rbyte) {
treeIndex = tree[treeIndex].rchild;
} else {
treeIndex = tree[treeIndex].lchild;
}
if (treeIndex >= 1024) {
/// Byte value
baData(result)[resIndex++] = treeIndex - 1024;
treeIndex = 0;
/**
* The encoded data may not take up whole bytes, so there would be
* some unused bits in the source array. To determine whether we have
* decoded all the data we needed, we just do the following:
*/
if (resIndex == originalLen) {
return result;
}
}
}
return NULL;
}
ByteArray* huffmanDecode(const wchar_t* treeName, const byte* compressedData, u32 compressedLen, u32 originalLen) {
TreeNode tree[256];
BitStream* bs = newBitStream((byte*)compressedData, compressedLen);
memset(tree, 0, sizeof(TreeNode) * 256);
if (!createTree(treeName, tree, bs)) {
deleteBitStream(bs);
return NULL;
}
ByteArray* result = decodeWithTree(treeName, tree, bs, originalLen);
deleteBitStream(bs);
return result;
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_putstr_non_printable.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: mlagares <mlagares@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/07/06 10:55:35 by mlagares #+# #+# */
/* Updated: 2021/07/07 15:23:54 by mlagares ### ########.fr */
/* */
/* ************************************************************************** */
#include <unistd.h>
#include <stdio.h>
int ft_char_is_printable (char c)
{
int ret;
ret = 0;
if (c > 31 && c < 127)
ret = 1;
return (ret);
}
unsigned char ft_print_hex_digit(unsigned char c )
{
if (c <= 9)
return (c + 48);
else
return (c + 87);
}
void ft_print_hex_char(char c)
{
unsigned char local_c;
unsigned char result_c;
if (c < 0)
local_c = c + 256;
else
local_c = c;
result_c = ft_print_hex_digit(local_c / 16);
write (1, &result_c, 1);
result_c = ft_print_hex_digit(local_c % 16);
write (1, &result_c, 1);
}
void ft_putstr_non_printable(char *str)
{
int pos;
pos = 0;
while (str[pos] != '\0')
{
if (!ft_char_is_printable(str[pos]))
{
write (1, "\\", 1);
ft_print_hex_char(str[pos]);
}
else
write (1, &str[pos], 1);
pos++;
}
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include "pqueue.h"
#include "graph.h"
#include "union_find.h"
graph_t kruskal(graph_t graph) {
graph_t result = graph_empty(graph_vertices_count(graph));
unsigned int L, R, num_edges = graph_edges_count(graph);
vertex_t l = NULL, r = NULL;
pqueue_t Q = pqueue_empty(num_edges);
union_find_t C = union_find_create(graph_vertices_count(graph));
edge_t E = NULL, *edges = graph_edges(graph);
for (unsigned int i = 0; i < num_edges; i++) {
pqueue_enqueue(Q, edges[i]);
}
free(edges);
edges = NULL;
while (!pqueue_is_empty(Q) && union_find_count(C) > 1) {
E = edge_copy(pqueue_fst(Q));
l = edge_left_vertex(E);
r = edge_right_vertex(E);
L = union_find_find(C, vertex_label(l));
R = union_find_find(C, vertex_label(r));
if (L != R) {
union_find_union(C, L, R);
E = edge_set_primary(E, true);
} else {
E = edge_set_primary(E, false);
}
result = graph_add_edge(result, E);
pqueue_dequeue(Q);
}
while (!pqueue_is_empty(Q)) {
E = edge_copy(pqueue_fst(Q));
pqueue_dequeue(Q);
E = edge_set_primary(E, false);
result = graph_add_edge(result, E);
}
Q = pqueue_destroy(Q);
C = union_find_destroy(C);
return result;
}
/* Computes a MST of the given graph.
*
* This function returns a copy of the input graph in which
* only the edges of the MST are marked as primary. The
* remaining edges are marked as secondary.
*
* The input graph does not change.
*
*/
unsigned int mst_total_weight(graph_t mst) {
unsigned int result = 0, num_edges;
edge_t *edges;
num_edges = graph_edges_count(mst);
edges = graph_edges(mst);
for (unsigned int i = 0; i < num_edges; i++) {
if (edge_is_primary(edges[i])) {
result += edge_weight(edges[i]);
}
edges[i] = edge_destroy(edges[i]);
}
free(edges);
return result;
}
/* Returns the sum of the weights of all the primary
* edges of the given graph.
*/
/** STAR 1
bool graph_has_cycle(graph_t g);
unsigned int graph_connected_components(graph_t g);
**/
#ifndef TEST /* keep this line above main function */
int main(void) {
/* read graph from stdin */
graph_t graph = graph_from_file(stdin);
assert(graph != NULL);
/* run kruskal */
graph_t mst = kruskal(graph);
/* dump graph */
graph_dump(mst, stdout);
/* dump total weight */
printf("\n# MST : %u\n", mst_total_weight(mst));
/* destroy both graphs */
graph = graph_destroy(graph);
mst = graph_destroy(mst);
}
#endif /* keep this line below main function */
|
C
|
#include <stdio.h>
int main() {
/**
* Escreva a sua solução aqui
* Code your solution here
* Escriba su solución aquí
*/
int x,y,i, sum=0;
scanf("%d", &x);
scanf("%d", &y);
if(y>x){
i = x;
x = y;
y = i;
}
for(i=y;i<=x;i++){
if(i%13 != 0){
sum+=i;
}
}
printf("%d\n", sum);
return 0;
}
|
C
|
#include <time.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#define MAX_FILE_NAME 100
int main() {
srand(time(NULL));
FILE *fp;
int count = 1; // Line counter (result)
unsigned int line_count = 0;
char filename[MAX_FILE_NAME];
char c; // To store a character read from file
// Get file name from user. The file should be
// either in current folder or complete path should be provided
printf("Enter file name: ");
scanf("%s", filename);
// Open the file
fp = fopen(filename, "r");
// Check if file exists
if (fp == NULL)
{
printf("Could not open file %s", filename);
return 0;
}
clock_t inicio = clock();
// Extract characters from file and store in character c
// for (c = getc(fp); c != EOF; c = getc(fp))
// if (c == '\n') // Increment count if this character is newline
// count = count + 1;
while (EOF != (fscanf(fp, "%*[^\n]"), fscanf(fp,"%*c")))
++count;
clock_t fim = clock();
// Calcula Tempo
double tempoProc = (double)(fim - inicio) / CLOCKS_PER_SEC;
rewind(fp);
while (fgets(filename, MAX_FILE_NAME, fp))
{
/* Print each line */
printf("line[%06d]: %s", ++line_count, filename);
/* Add a trailing newline to lines that don't already have one */
if (filename[strlen(filename) - 1] != '\n')
printf("\n");
}
printf("Tempo decorrido %.6fs",tempoProc);
printf("\n");
// Close the file
fclose(fp);
printf("The file has %d lines\n ", count);
return 0;
}
|
C
|
/*
* buffer.h
*
* Created on: Jan 31, 2016
* Author: suma
*/
#ifndef BUFFER_H_
#define BUFFER_H_
//#include <stdio.h>
//#include <stdlib.h> /* malloc, free, rand */
//#include <assert.h>
//#include <stdbool.h>
//
//
//
//typedef struct circular_buffer
//{
// void *buffer; // data buffer
// void *buffer_end; // end of data buffer
// size_t capacity; // maximum number of items in the buffer
// size_t count; // number of items in the buffer
// size_t sz; // size of each item in the buffer
// void *head; // pointer to head
// void *tail; // pointer to tail
//} circular_buffer;
//
//
////typedef struct lineElm
////{
//// unsigned short lenght;
//// unsigned char pwm;
//// bool lase;
////
////} lineElm;
//
//void cb_init(circular_buffer *cb, size_t capacity, size_t sz);
//
//void cb_free(circular_buffer *cb);
//
//void cb_push_back(circular_buffer *cb, const void *item);
//
//void cb_pop_front(circular_buffer *cb, void *item);
#endif /* BUFFER_H_ */
|
C
|
#include <stdlib.h>
#include <string.h>
#include "Qsort.h"
#include "utile.h" /* pour IN et OUT */
#include "temps.h" /* pour Chrono */
/* #define useChrono */
#undef useChrono
/************************************************************************/
/* tri des donnees */
/************************************************************************/
int Qsort (void* data,
unsigned int lgel,
unsigned int nbel,
int reverse,
int* outIndex,
int (compare (void*, void*)))
{
char nomFonction[] = "Qsort";
int ret = 0;
char** localData = NULL;
char* ptr = NULL;
unsigned int i;
unsigned int ld = 0;
#ifdef useChrono
Chrono* chrono = NULL;
#endif
IN(nomFonction);
#ifdef useChrono
chrono = newChrono();
#endif
/* si aucune donnée */
if (!data || !lgel || !nbel || !compare) {
ret = -1;
goto XIT;
}
/* il y a un index (outIndex) à sortir */
if (outIndex) {
/* taille d'une ligne dans le tableau localData:
une ligne de donnees en entree + un entier + 0x00 */
ld = (lgel+sizeof (int)+1);
/* allocation memoire */
if ((localData = (char**) calloc (nbel, sizeof (char*))) == NULL) {
ret = -1;
goto XIT;
}
if ((ptr = (char*) calloc (nbel, ld)) == NULL) {
ret = -1;
goto XIT;
}
for (i=0; i<nbel; i++) {
localData[i] = ptr+(i*ld);
}
/* preparation des donnees pour le tri */
for (i=0; i<nbel; i++) {
memcpy (localData[i], ((char*)data+(i*lgel)), lgel);
/* on recopie l'indice ensuite */
memcpy ((localData[i]+lgel), &i, sizeof (int));
*(localData[i]+ld-1) = 0x00;
}
#ifdef useChrono
startChrono(chrono);
#endif
/* tri des données */
qsort (localData[0], nbel, ld, (int(*)(const void*, const void*))compare);
#ifdef useChrono
afficheMessage(1,LOG,"Duree qsort() : %ld",getChronoMicroSec(chrono));
#endif
/* on recupere les indices ordonnes selon les data */
if (!reverse) {
for (i=0; i<nbel; i++) {
memcpy (&outIndex[i], (localData[i]+lgel), sizeof (int));
}
}
else {
unsigned int j;
for ((j=nbel-1, i=0); (j>=0, i<nbel); (j--, i++)) {
memcpy (&outIndex[j], (localData[i]+lgel), sizeof (int));
}
}
}
/* il n'y a pas d'index (outIndex) à sortir */
else {
afficheMessage(2,LOG,"Sans outIndex");
/* taille d'une ligne dans le tableau localData:
une ligne de donnees en entree + 0x00 */
ld = (lgel+1);
/* allocation memoire */
if ((localData = (char**) calloc (nbel, sizeof (char*))) == NULL) {
ret = -1;
goto XIT;
}
if ((ptr = (char*) calloc (nbel, ld)) == NULL) {
ret = -1;
goto XIT;
}
for (i=0; i<nbel; i++) {
localData[i] = ptr+(i*ld);
}
/* preparation des donnees pour le tri */
for (i=0; i<nbel; i++) {
memcpy (localData[i], ((char*)data+(i*lgel)), lgel);
*(localData[i]+ld-1) = 0x00;
}
#ifdef useChrono
startChrono(chrono);
#endif
/* tri des données */
qsort (localData[0], nbel, ld, (int(*)(const void*, const void*))compare);
#ifdef useChrono
afficheMessage(1,LOG,"Duree qsort() : %.3f milli-sec",(float)topChrono(chrono)/(float)1000);
#endif
}
/* on recopie les donnees ordonnees dans le buffer de sortie */
if (!reverse) { /* dans l'ordre */
for (i=0; i<nbel; i++) {
memcpy (((char*)data+(i*lgel)), localData[i], lgel);
}
}
else { /* dans l'ordre inverse */
for (i=0; i<nbel; i++) {
memcpy (((char*)data+(i*lgel)), localData[outIndex[i]], lgel);
}
}
XIT:
/* desallocation */
if (ptr) free (ptr);
if (localData) free (localData);
#ifdef useChrono
if (chrono) free(chrono);
#endif
OUT(nomFonction,ret);
return (ret);
}
/************************************************************************/
/* equivalent de la fonction uniq d'unix sur un tableau en memoire */
/* dedoublonnage, les données sont supposées ordonnées en entrant */
/************************************************************************/
int Uniq (void* data, /* in out */
unsigned int lgel, /* in */
unsigned int* nbel, /* in out */
int* outIndex) /* out */
{
char nomFonction[] = "Uniq";
char** localData = NULL;
char* localDataPrec = NULL;
char* ptr = NULL;
unsigned int i;
unsigned int iq;
unsigned int ld = 0;
int ret = 0;
IN(nomFonction);
/* si aucune donnée */
if (!data || !lgel || !nbel || !*nbel) return (-1);
/* taille d'une ligne dans le tableau localData:
une ligne de donnees en entree + 0x00 */
ld = (lgel+1);
/* allocation memoire */
if ((localDataPrec = (char*) calloc (lgel, sizeof (char))) == NULL) {
ret = -1;
goto XIT;
}
if ((localData = (char**) calloc (*nbel, sizeof (char*))) == NULL) {
ret = -1;
goto XIT;
}
if ((ptr = (char*) calloc (*nbel, ld)) == NULL) {
ret = -1;
goto XIT;
}
for (i=0; i<*nbel; i++) {
localData[i] = ptr+(i*ld);
}
/* on recopie les données dans localData[] */
for (i=0; i<*nbel; i++) {
memcpy (localData[i], ((char*)data+(i*lgel)), lgel);
*(localData[i]+ld-1) = 0x00;
}
/* on dedoublonne */
iq = 0; /* indice dans tableau dedoublonné */
localDataPrec[0] = 0x00;
for (i=0; i<*nbel; i++) {
if (strcmp (localData[i], localDataPrec) != 0) {
if (!outIndex) memcpy (((char*)data+(iq*lgel)), localData[i], lgel);
iq++;
strcpy (localDataPrec, localData[i]);
}
else {
/* c'est un doublon */
if (outIndex) outIndex[i] = 1;
}
}
/* le nb d'éléments dédoublonnés */
*nbel = iq;
XIT:
/* desallocation */
if (ptr) free (ptr);
if (localData) free (localData);
if (localDataPrec) free (localDataPrec);
OUT(nomFonction,ret);
return (ret);
}
|
C
|
// glob.h - pathname pattern-matching types
// #include <glob.h>
// The <glob.h> header shall define the structures and symbolic
// constants used by the glob() function.
// The <glob.h> header shall define the glob_t structure type, which
// shall include at least the following members:
typedef struct
{
size_t gl_pathc; // Count of paths matched by pattern.
char **gl_pathv; // Pointer to a list of matched pathnames.
size_t gl_offs; // Slots to reserve at the beginning of gl_pathv.
} glob_t;
// The <glob.h> header shall define the size_t type as described in
// <sys/types.h>.
#include <sys/types.h>
// The <glob.h> header shall define the following symbolic constants as
// values for the flags argument:
enum
{
// Append generated pathnames to those previously obtained.
GLOB_APPEND,
#define GLOB_APPEND GLOB_APPEND
// Specify how many null pointers to add to the beginning of
// gl_pathv.
GLOB_DOOFFS,
#define GLOB_DOOFFS GLOB_DOOFFS
// Cause glob() to return on error.
GLOB_ERR,
#define GLOB_ERR GLOB_ERR
// Each pathname that is a directory that matches pattern has a
// <slash> appended.
GLOB_MARK,
#define GLOB_MARK GLOB_MARK
// If pattern does not match any pathname, then return a list
// consisting of only pattern.
GLOB_NOCHECK,
#define GLOB_NOCHECK GLOB_NOCHECK
// Disable backslash escaping.
GLOB_NOESCAPE,
#define GLOB_NOESCAPE GLOB_NOESCAPE
// Do not sort the pathnames returned.
GLOB_NOSORT
#define GLOB_NOSORT GLOB_NOSORT
};
// The <glob.h> header shall define the following symbolic constants as
// error return values:
enum
{
// The scan was stopped because GLOB_ERR was set or (*errfunc)()
// returned non-zero.
GLOB_ABORTED,
#define GLOB_ABORTED GLOB_ABORTED
// The pattern does not match any existing pathname, and
// GLOB_NOCHECK was not set in flags.
GLOB_NOMATCH,
#define GLOB_NOMATCH GLOB_NOMATCH
// An attempt to allocate memory failed.
GLOB_NOSPACE
#define GLOB_NOSPACE GLOB_NOSPACE
};
// The following shall be declared as functions and may also be defined
// as macros. Function prototypes shall be provided.
int glob(
const char *restrict,
int,
int(*)(const char *, int),
glob_t *restrict);
void globfree(glob_t *);
|
C
|
/*
ID: wind1900
LANG: C
TASK: castle
*/
#include <stdio.h>
int m, n;
char square[50][50];
int id[50][50] = {0}, sid = 1;
int area[2501], ta;
int r = 0, ri, rj;
char rc;
void search(int i, int j) {
if (id[i][j]) return;
ta++;
id[i][j] = sid;
if ((1 & square[i][j]) == 0) {
search(i, j - 1);
}
if ((2 & square[i][j]) == 0) {
search(i - 1, j);
}
if ((4 & square[i][j]) == 0) {
search(i, j + 1);
}
if ((8 & square[i][j]) == 0) {
search(i + 1, j);
}
}
void update(int x1, int y1, int x2, int y2, char c) {
int t;
if (x2 < 0 || x2 >= n) return;
if (y2 < 0 || y2 >= m) return;
if (id[x1][y1] == id[x2][y2]) return;
t = area[id[x1][y1]] + area[id[x2][y2]];
if (t > r) {
r = t;
ri = x1;
rj = y1;
rc = c;
} else if (t == r) {
if (y1 < rj || (rj == y1 && ri < x1)) {
r = t;
ri = x1;
rj = y1;
rc = c;
}
}
}
int main() {
int i, j, tm;
freopen("castle.in", "r", stdin);
freopen("castle.out", "w", stdout);
scanf("%d %d", &m, &n);
for (i = 0; i < n; i++) {
for (j = 0; j < m; j++) {
scanf("%d", &tm);
square[i][j] = tm;
}
}
for (i = 0; i < n; i++) {
for (j = 0; j < m; j++) {
if (id[i][j]) continue;
ta = 0;
search(i, j);
area[sid] = ta;
sid++;
}
}
tm = 0;
for (i = 1; i < sid; i++) {
tm = tm > area[i] ? tm : area[i];
}
printf("%d\n%d\n", sid - 1, tm);
for (i = 0; i < n; i++) {
for (j = 0; j < m; j++) {
if ((1 & square[i][j])) {
update(i, j, i, j - 1, 'W');
}
if ((2 & square[i][j])) {
update(i, j, i - 1, j, 'N');
}
if ((4 & square[i][j])) {
update(i, j, i, j + 1, 'E');
}
if ((8 & square[i][j])) {
update(i, j, i + 1, j, 'S');
}
}
}
printf("%d\n%d %d %c\n", r, ri + 1, rj + 1, rc);
return 0;
}
|
C
|
/* See LICENSE file for copyright and license details. */
/*
name: TEST007
description: basic while test
error:
output:
G2 I F "main
{
\
A3 I "x
A3 #IA :I
j L6
e
L4
A3 A3 #I1 -I :I
L6
y L4 A3 #I0 !I
b
L5
h A3
}
*/
int
main()
{
int x;
x = 10;
while (x)
x = x - 1;
return x;
}
|
C
|
/*
* linemeans calculates the mean and variance of each scan line
* in one frame of a 3150 pixel TM quart scene.
* Leading and trailing bytes are unchanged.
* Output is a one-column HIPS file with one or two frames.
* If variance is output, output is bandinterleaved (mean,var,mean,var,..).
*
* Header-lines are detected in a naive fashion.
*
* Allan Aasbjerg Nielsen, IMSOR
*/
#include <hipl_format.h>
#define MAX_LS 1024
char *usage="usage - linemeans [-s] [-v] [-tm]";
int main(argc,argv)
int argc;
char **argv;
{
struct header hd;
int i,j,fr;
int nr,nc,nf,ncr;
byte *frame;
int *linestart;
int ls,linesum,linesum2;
char text[128];
int sumflag=0,varflag=0,tmflag=0;
float aux;
Progname = strsave(*argv);
for (i=1;i<argc;i++) {
if (argv[i][0]=='-') {
switch(argv[i][1]) {
case 's': sumflag=1;
break;
case 't': tmflag=1;
break;
case 'v': varflag=1;
break;
default: fprintf(stderr,"%s: %s\n",Progname,usage);
exit(1);
break;
}
}
}
read_header(&hd);
if (hd.pixel_format != PFBYTE) {
fprintf(stderr,"%s: image must be byte format\n",Progname);
exit(1);
}
if ((nf=hd.num_frame) != 1) {
fprintf(stderr,"%s: one frame at a time\n",Progname);
exit(1);
}
if (findparam(&hd,"Interleaving") != NULLPAR) {
fprintf(stderr,"%s: bandinterleaved images not allowed\n",Progname);
exit(1);
}
if (findparam(&hd,"Irregular") != NULLPAR) {
fprintf(stderr,"%s: irregular images not allowed\n",Progname);
exit(1);
}
nr=hd.orows;
if ((nc=hd.cols) < 3150 && tmflag==1) {
fprintf(stderr,"%s: with -tm image must have at least 3150 columns\n",Progname);
exit(1);
}
hd.pixel_format = PFFLOAT;
hd.orows=nr;
hd.rows=nr;
hd.ocols=1;
hd.cols=1;
/*setparam(&hd,"Irregular",PFBYTE,1,1);*/
if (varflag==1) {
setparam(&hd,"Interleaving",PFBYTE,1,1);
hd.num_frame=2;
}
update_header(&hd,argc,argv);
write_header(&hd);
/* frame holds one row at a time only */
frame = (byte *) malloc(nr*sizeof(byte));
for (fr=0;fr<nf;fr++) {
for (i=0;i<nr;i++) {
if (fread(frame,sizeof(byte),nc,stdin) != nc) {
fprintf(stderr,"%s: error reading row %d in frame %d\n",Progname,i,fr);
exit(1);
}
if (tmflag==1) {
ncr=3150;
linestart=(int *)(frame+24);
ls=(*linestart)+=32;
/*fprintf(stderr,"%d\n",ls);*/
}
else {
ls=0;
ncr=nc;
}
/*Check if line is header*/
if (ls<MAX_LS) {
for (j=ls,linesum=0;j<ls+ncr;j++) linesum+=(int)frame[j];
/*
fprintf(stderr,"%s: frame %d line %d\n",Progname,fr,i);
if (j==ls+ncr-1) fprintf(stderr,"\n");
*/
if (sumflag==1) {
aux=(float)linesum;
if ((fwrite(&aux,sizeof(float),1,stdout))!=1) {
fprintf(stderr,"%s: error writing sum of row %d\n",Progname,i);
exit(1);
}
}
else {
aux=(float)linesum/ncr;
if ((fwrite(&aux,sizeof(float),1,stdout))!=1) {
fprintf(stderr,"%s: error writing mean of row %d\n",Progname,i);
exit(1);
}
}
if (varflag==1) {
for (j=ls,linesum2=0;j<ls+ncr;j++)
linesum2+=((int)frame[j])*((int)frame[j]);
aux=(linesum2-(float)linesum*linesum/ncr)/(ncr-1);
if ((fwrite(&aux,sizeof(float),1,stdout))!=1) {
fprintf(stderr,"%s: error writing variance of row %d\n",Progname,i);
exit(1);
}
}
}
else {
for (j=0;j<128;j++) text[j]=(char)frame[j];
fprintf(stderr,"%s: header in line %d %s\n",Progname,i,text);
}
}
}
exit(0);
}
|
C
|
#include <stdio.h>
#include <cs50.h>
long get_right_num(string prompt);
long ten_ntimes(int n);
int company(long num);
int if_valid(long num);
int main(void)
{
long num = get_right_num("Number: ");
if (company(num) == 1)
{
printf("AMEX\n");
}
else if (company(num) == 2)
{
printf("MASTERCARD\n");
}
else if (company(num) == 3)
{
printf("VISA\n");
}
else
{
printf("INVALID\n");
}
}
//input n will be 10^n as output
long ten_ntimes(int n)
{
long ten = 1;
for (int i = 0; i < n; i++)
{
ten *= 10;
}
return ten;
}
//get number from user until right input comes
long get_right_num(string prompt)
{
long n;
do
{
n = get_long("%s", prompt);
}
while (n < 0);
return n;
}
//check validation and a kind of company
int company(long num)
{
long check = num / ten_ntimes(14);
if ((num / ten_ntimes(13) == 34 || num / ten_ntimes(13) == 37) && if_valid(num))
{
return 1;
}
else if ((check == 51 || check == 52 || check == 53 || check == 54 || check == 55) && if_valid(num))
{
return 2;
}
else if ((num / ten_ntimes(12) == 4 || num / ten_ntimes(15) == 4) && if_valid(num))
{
return 3;
}
else
{
return 0;
}
}
//check validation(sum should be n times 10)
int if_valid(long num)
{
int n1 = 0, n2 = 0;
for (int i = 1; i < 16; i += 2)
{
n1 += (num / ten_ntimes(i) % 10 * 2) / 10 + (num / ten_ntimes(i) % 10 * 2) % 10;
}
for (int i = 0; i < 16; i += 2)
{
n2 += (num / ten_ntimes(i) % 10) / 10 + (num / ten_ntimes(i) % 10) % 10;
}
if (((n1 + n2) % 10) == 0)
{
return 1;
}
return 0;
}
|
C
|
#include "stm32f10x_gpio.h"
void Init()
{
GPIO_InitTypeDef GPIO_InitStruct;
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB | RCC_APB2Periph_GPIOA | RCC_APB2Periph_GPIOE, ENABLE);
GPIO_InitStruct.GPIO_Pin = GPIO_Pin_2 | GPIO_Pin_3 | GPIO_Pin_4;
GPIO_InitStruct.GPIO_Mode = GPIO_Mode_IPU;
GPIO_Init(GPIOE, &GPIO_InitStruct);
GPIO_InitStruct.GPIO_Pin = GPIO_Pin_0;
GPIO_InitStruct.GPIO_Mode = GPIO_Mode_IPD;
GPIO_Init(GPIOA, &GPIO_InitStruct);
GPIO_InitStruct.GPIO_Pin = GPIO_Pin_5;
GPIO_InitStruct.GPIO_Mode = GPIO_Mode_Out_PP;
GPIO_InitStruct.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(GPIOE, &GPIO_InitStruct);
GPIO_InitStruct.GPIO_Pin = GPIO_Pin_5;
GPIO_InitStruct.GPIO_Mode = GPIO_Mode_Out_PP;
GPIO_InitStruct.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(GPIOB, &GPIO_InitStruct);
GPIO_SetBits(GPIOB, GPIO_Pin_5);
GPIO_SetBits(GPIOE, GPIO_Pin_5);
}
void Sleep(u32 ms)
{
u32 temp;
SysTick_Type *Tick = SysTick;
ms *= 8000;
Tick->LOAD = ms;
Tick->VAL = 0;
Tick->CTRL |= SysTick_CTRL_ENABLE_Msk;
do {
temp = Tick->CTRL;
} while ((temp & SysTick_CTRL_ENABLE_Msk) &&
!(temp & SysTick_CTRL_COUNTFLAG_Msk));
Tick->VAL = 0;
Tick->CTRL &= ~SysTick_CTRL_ENABLE_Msk;
}
/* 4-0: KEY0 KEY1 KEY2 WKUP */
#define KEY0 0x8
#define KEY1 0x4
#define KEY2 0x2
#define WKUP 0x1
u8 KEY_State()
{
u8 State = 0;
if (GPIO_ReadInputDataBit(GPIOA, GPIO_Pin_0) == 1) State |= WKUP;
if (GPIO_ReadInputDataBit(GPIOE, GPIO_Pin_2) == 0) State |= KEY2;
if (GPIO_ReadInputDataBit(GPIOE, GPIO_Pin_3) == 0) State |= KEY1;
if (GPIO_ReadInputDataBit(GPIOE, GPIO_Pin_4) == 0) State |= KEY0;
return State;
}
void ChangeLED0()
{
if (1 == GPIO_ReadOutputDataBit(GPIOB, GPIO_Pin_5))
{
GPIO_ResetBits(GPIOB, GPIO_Pin_5);
}
else
{
GPIO_SetBits(GPIOB, GPIO_Pin_5);
}
}
void ChangeLED1()
{
if (1 == GPIO_ReadOutputDataBit(GPIOE, GPIO_Pin_5))
{
GPIO_ResetBits(GPIOE, GPIO_Pin_5);
}
else
{
GPIO_SetBits(GPIOE, GPIO_Pin_5);
}
}
int main()
{
u8 LastTempState = 0, NowTempState = 0, ChangeState = 0, KeyUp = 0xF;
Init();
GPIO_ResetBits(GPIOB, GPIO_Pin_5);
GPIO_ResetBits(GPIOE, GPIO_Pin_5);
Sleep(500);
GPIO_SetBits(GPIOB, GPIO_Pin_5);
GPIO_SetBits(GPIOE, GPIO_Pin_5);
Sleep(500);
GPIO_ResetBits(GPIOB, GPIO_Pin_5);
GPIO_ResetBits(GPIOE, GPIO_Pin_5);
Sleep(500);
GPIO_SetBits(GPIOB, GPIO_Pin_5);
GPIO_SetBits(GPIOE, GPIO_Pin_5);
Sleep(500);
GPIO_ResetBits(GPIOB, GPIO_Pin_5);
GPIO_ResetBits(GPIOE, GPIO_Pin_5);
Sleep(500);
GPIO_SetBits(GPIOB, GPIO_Pin_5);
GPIO_SetBits(GPIOE, GPIO_Pin_5);
while (1)
{
NowTempState = KEY_State();
ChangeState = KeyUp & LastTempState & NowTempState;
KeyUp = (~LastTempState & ~NowTempState) |
((~LastTempState | ~NowTempState) & KeyUp);
LastTempState = NowTempState;
if (ChangeState & KEY2) ChangeLED0();
if (ChangeState & KEY0) ChangeLED1();
if (ChangeState & KEY1)
{
ChangeLED0();
ChangeLED1();
}
if (ChangeState & WKUP)
{
GPIO_ResetBits(GPIOB, GPIO_Pin_5);
GPIO_ResetBits(GPIOE, GPIO_Pin_5);
}
Sleep(10);
}
}
|
C
|
#include<stdio.h>
int main()
{
long long int n1=0,n2=1,n3=0,i,number;
printf("Enter the number of elements:");
scanf("%lld",&number);
for(i=2;i<number;++i)//loop starts from 2 because 0 and 1 are already printed
{
n3=n1+n2;
n1=n2;
n2=n3;
}
printf("Last Fibonacci number in the sequence: %lld",n3);
return 0;
}
//////FOR FIBONACCI SEQ
// int fib(int n)
// {
// int x,y;
// if(n<2)return n;
// #pragma omp task shared(x)
// x=fib(n-1);
// #pragma omp task shared(y)
// y=fib(n-2);
// #pragma omp taskwait
// return x+y;
// }
|
C
|
/*
* Header file that defines various functions and structs for reading the
* lang.txt file that defines the programming language to be compiled.
*/
#ifndef _LANG_H
#define _LANG_H
#define SCANNER_TAG ("SCANNER")
#define PARSER_TAG ("PARSER")
#define CFG_TAG ("CFG")
#define ILCGEN_TAG ("ILCGEN")
#define CGEN_TAG ("CGEN")
#define MACRO_REPLACE ("replace")
// put back the ifdef __cplusplus later
#ifdef __cplusplus
extern "C" {
#endif
typedef enum var_type {
LANG_STR_CONST = 1,
LANG_STR_ARRAY = 2
} var_type;
typedef struct lang_var {
var_type type;
char **value; // Pointer to the value
unsigned int length; // Length of the array if value points to an array
} lang_var_t;
// Tags are required to be in the order: SCANNER, PARSER, CFG, ILCGEN, CGEN
typedef struct lang_state {
list_t *tok_list;
FILE *fp;
const char *file_name;
int scanner_index;
int parser_index;
int cfg_index;
int ilcgen_index;
int cgen_index;
} lang_state_t;
// Parses a buffer that is conformant to the lang.txt format.
lang_state_t *lang_txt_parse_buffer(const char *buf, int length);
list_t *lang_txt_preprocess(const char *buf, int length); // to be removed once the function can be made static.
cfg_t *lang_get_cfg(lang_state_t *state);
lang_var_t *lang_get_var(char *name);
void lang_free(lang_state_t *state);
#ifdef __cplusplus
}
#endif
#endif // _LANG_H
|
C
|
#include <stdio.h>
#include <stdlib.h>
void main(int argc, char **argv) {
FILE *fp;
int char_read;
char *filename = *(argv+1);
char *format = *(argv+2);
fp = fopen(filename, "r");
if (fp == NULL) {
printf("File not found\n");
exit(0);
}
do {
char_read = fgetc(fp);
if ((strcmp(format,"windows")==0) && (char_read == 10)) {
printf("\\r\\n");
}
if ((strcmp(format,"unix")==0) && (char_read == 13)) {
fgetc(fp);
printf("\\n");
}
printf("%c", char_read);
} while(char_read != EOF);
fclose(fp);
}
|
C
|
#include "node1_memory_map.h"
#ifndef NODE1_JOYSTICK_H_
#define NODE1_JOYSTICK_H_
//Vil legge inn enumen inne i structen så jeg bare kan legge inn en variable av type struct inne i funksjonen
//vil så sammen funksjonene til en stor funksjon
typedef enum joystick_direction{
LEFT, RIGHT, UP, DOWN, NEUTRAL
}joystick_direction;
typedef struct JOYSTICK{
uint8_t x_analog;
uint8_t y_analog;
joystick_direction x_direction;
joystick_direction y_direction;
int joystick_pos;
}JOYSTICK;
void get_joystick_values(JOYSTICK *joystick);
#endif
|
C
|
#include "log.h"
#include <errno.h>
#include <stdarg.h>
#include <stdbool.h>
#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <syslog.h>
#include <time.h>
#include <unistd.h>
#include "common.h"
#include "time.h"
const char *level_desc[__LOG_LEVEL_MAX] = { "INFO", "WARN", "ERR!" };
const int level_syslog[__LOG_LEVEL_MAX] = { LOG_INFO, LOG_WARNING, LOG_ERR };
static pid_t pid;
static char *domain = NULL;
static bool to_syslog;
void log_init(const char *name, bool to_syslog_)
{
pid = getpid();
domain = sstrdup(name);
to_syslog = to_syslog_;
if (to_syslog_)
openlog(name, LOG_PID, LOG_USER);
}
void log_reinit(const char *name)
{
pid = getpid();
if (name) {
sfree(domain);
domain = sstrdup(name);
}
}
#define MAX_LOG 1024
int log_stderr(int level, const char *format, va_list ap)
{
time_t t;
char buf[MAX_LOG];
int pos;
t = time(NULL);
pos = strftime(buf, sizeof(buf), "%F %T", localtime(&t));
pos += snprintf(buf + pos, MAX_LOG - pos,
" %s [%s:%d] ", level_desc[level], domain, pid);
if (pos >= MAX_LOG)
pos = MAX_LOG - 1;
pos += vsnprintf(buf + pos, MAX_LOG - pos, format, ap);
if (pos >= MAX_LOG)
pos = MAX_LOG - 1;
if (pos == MAX_LOG - 1)
pos--;
if (pos && buf[pos - 1] != '\n')
buf[pos++] = '\n';
write(2, buf, pos);
/* Don't care about incomplete writes. */
return 0;
}
int log_msg(int level, const char *format, ...)
{
va_list ap;
int res = 0;
if (level < 0 || level >= __LOG_LEVEL_MAX)
level = 0;
va_start(ap, format);
if (to_syslog)
vsyslog(level_syslog[level], format, ap);
else
res = log_stderr(level, format, ap);
va_end(ap);
return res;
}
void log_raw(char *buf, size_t size)
{
static bool need_nl = false;
if (size) {
write(2, buf, size);
need_nl = buf[size - 1] != '\n';
} else if (need_nl) {
char x = '\n';
write(2, &x, 1);
need_nl = false;
}
}
|
C
|
/* Copyright Statement:
*
*/
/**
* @file pwm.h
*
* Pulse Width Modulation.
* */
#ifndef __PWM_H__
#define __PWM_H__
#include "hal_platform.h"
#ifdef HAL_PWM_MODULE_ENABLED
#include "pinmux.h"
#ifdef __cplusplus
extern "C" {
#endif
#define PWM_CLK_SRC_32K (0)
#define PWM_CLK_SRC_2M (1)
#define PWM_CLK_SRC_XTAL (2)
#define PWM_CLK_SRC_NUM (3)
/**
* @brief Configure clock source of all PWM module.
*
* @param clock_source [IN] 0:32KHz, 1:2MHz, 2:XTAL(depending on XTAL, ex. 40MHz) are supported.
*
* @return >=0 means success, <0 means fail.
*
* @note Clock source should be selected based on PWM frequency. */
int32_t pwm_init(uint8_t clock_source);
/**
* @brief Configure specific PWM with indicated frequency and duty cycle.
*
* @param index [IN] Indicate specific PWM module.
* @param frequency [IN] In unit of Hz.
* @param duty_cycle [IN] In 256 steps.
* @param enable [IN]
* 1: PWM is enabled and will be active after pwm_set done.
* 0: PWM is disabled, frequency and duty cycle setting are cleared as 0.
*
* @return >=0 means success, <0 means fail.
* */
int32_t pwm_set(uint8_t index, uint32_t frequency, uint16_t duty_cycle, uint8_t enable);
/**
* @brief Get frequency, duty cycle and on/off status of specific PWM.
*
* @param index [IN] Indicate specific PWM module.
* @param frequency [IN] In unit of Hz.
* @param duty_cycle [IN] In 256 steps.
* @param enable [IN]
* 1: PWM is enabled.
* 0: PWM is disabled.
*
* @return >=0 means success, <0 means fail.
* */
int32_t pwm_get(uint8_t index, uint32_t *frequency, uint16_t *duty_cycle, uint8_t *status);
/** @brief Get PWM module index from GPIO number.
*
* @param index [IN] Indicate specific GOIP number.
* @param frequency [IN] In unit of Hz.
*
* @return >=0 means success and PWM module index, <0 means fail.
* */
#ifdef __cplusplus
}
#endif
#endif
#endif /* __PWM_H__ */
|
C
|
#include <stdio.h>
#include "joueur.h"
joueur_t * Creer_Joueur(char * nom, int pa, objet_t inventaire[4], int statut[7]){
joueur_t * joueur = malloc(sizeof(joueur_t));
int i;
joueur->nom = nom;
joueur->pa = pa;
for(i=0; i<4; i++){
joueur->inventaire[i] = inventaire[i];
}
for(i=0; i<7; i++){
joueur->statut[i] = statut[i];
}
return joueur;
}
void Supprimer_Joueur(joueur_t * joueur){
free(joueur);
joueur = NULL;
}
int Est_Clair(joueur_t * joueur){
return joueur->statut[0];
}
int Est_Soif(joueur_t * joueur){
return joueur->statut[1];
}
int Est_Fatigue(joueur_t * joueur){
return joueur->statut[2];
}
int Est_Blessure(joueur_t * joueur){
return joueur->statut[3];
}
int Est_Drogue(joueur_t * joueur){
return joueur->statut[4];
}
int Est_Rassasie(joueur_t * joueur){
return joueur->statut[5];
}
int Est_Immunise(joueur_t * joueur){
return joueur->statut[6];
}
|
C
|
/* I pledge my honor that I have abided by the Stevens Honor System.
* Brandon Patton
* Assignment 3
*/
#include "cs392_log.h"
void logH(char *in){
FILE *file;
file = fopen("cs392_shell.log", "a"); //sets up a pointer to log file
if(file == NULL){
perror("Error: Failed to open file.\n");
} else {
fprintf(file, "%s\n", in); //prints commands entered to log file
}
fclose(file);
}
|
C
|
/* Includes ------------------------------------------------------------------*/
#include "random.h"
/* Private typedef -----------------------------------------------------------*/
/* Private define ------------------------------------------------------------*/
/* Private macro -------------------------------------------------------------*/
/* Private variables ---------------------------------------------------------*/
/* Extern variables ----------------------------------------------------------*/
/* Private function prototypes -----------------------------------------------*/
/* Private functions ---------------------------------------------------------*/
/*******************************************************************************
* Function Name : RandomInit
* Description : Initialize random number generator
*******************************************************************************/
void RandomInit()
{
GPIO_InitTypeDef GPIO_InitStructure;
ADC_InitTypeDef ADC_InitStructure;
RCC_APB2PeriphClockCmd( RCC_APB2Periph_ADC1, ENABLE );
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_0 | GPIO_Pin_1;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AIN;
GPIO_Init(GPIOA, &GPIO_InitStructure);
ADC_InitStructure.ADC_Mode = ADC_Mode_Independent;
ADC_InitStructure.ADC_ScanConvMode = DISABLE; // Single Channel
ADC_InitStructure.ADC_ContinuousConvMode = DISABLE; // Scan on Demand
ADC_InitStructure.ADC_ExternalTrigConv = ADC_ExternalTrigConv_None;
ADC_InitStructure.ADC_DataAlign = ADC_DataAlign_Right;
ADC_InitStructure.ADC_NbrOfChannel = 1;
ADC_Init(ADC1, &ADC_InitStructure);
//ADC1->CR2 |= ((uint32_t)0x00800000); //Enable temperature sensor
/* ADC1 regular channel1 configuration */
ADC_RegularChannelConfig(ADC1, ADC_Channel_1, 1, ADC_SampleTime_1Cycles5);
/* Enable ADC1 */
ADC_Cmd(ADC1, ENABLE);
#if 0
/* Enable ADC1 reset calibration register */
ADC_ResetCalibration(ADC1);
/* Check the end of ADC1 reset calibration register */
while(ADC_GetResetCalibrationStatus(ADC1));
/* Start ADC1 calibaration */
ADC_StartCalibration(ADC1);
/* Check the end of ADC1 calibration */
while(ADC_GetCalibrationStatus(ADC1));
#endif
/* Start ADC1 Software Conversion */
ADC_SoftwareStartConvCmd(ADC1, ENABLE);
}
/*******************************************************************************
* Function Name : GetRandom
* Description : Generates a random number
* Output : 12-bit random number
*******************************************************************************/
uint16_t GetRandom()
{
uint32_t adc;
while(ADC_GetFlagStatus(ADC1, ADC_FLAG_EOC) == RESET);
adc = ADC_GetConversionValue(ADC1);
/* Probably overkill */
ADC_ClearFlag(ADC1, ADC_FLAG_EOC);
/* Start ADC1 Software Conversion */
ADC_SoftwareStartConvCmd(ADC1, ENABLE);
return adc;
}
uint16_t GetRandomBig()
{
uint32_t adc[4];
while(ADC_GetFlagStatus(ADC1, ADC_FLAG_EOC) == RESET);
adc[0] = ADC_GetConversionValue(ADC1);
ADC_ClearFlag(ADC1, ADC_FLAG_EOC);
ADC_SoftwareStartConvCmd(ADC1, ENABLE);
while(ADC_GetFlagStatus(ADC1, ADC_FLAG_EOC) == RESET);
adc[1] = ADC_GetConversionValue(ADC1);
ADC_ClearFlag(ADC1, ADC_FLAG_EOC);
ADC_SoftwareStartConvCmd(ADC1, ENABLE);
while(ADC_GetFlagStatus(ADC1, ADC_FLAG_EOC) == RESET);
adc[2] = ADC_GetConversionValue(ADC1);
ADC_ClearFlag(ADC1, ADC_FLAG_EOC);
ADC_SoftwareStartConvCmd(ADC1, ENABLE);
while(ADC_GetFlagStatus(ADC1, ADC_FLAG_EOC) == RESET);
adc[3] = ADC_GetConversionValue(ADC1);
ADC_ClearFlag(ADC1, ADC_FLAG_EOC);
ADC_SoftwareStartConvCmd(ADC1, ENABLE);
adc[0] = adc[0] %10;
adc[1] = adc[1] %10;
adc[2] = adc[2] %10;
adc[3] = adc[3] %10;
return adc[0]*1000+adc[2]*100+adc[1]*10+adc[0];
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
/*
int *counting_sort_stable(int *array, int n, int min, int max) {
int i, j, z;
int sorted[n];
int range = max - min + 1;
int *count = malloc(range * sizeof(*array));
for (i = 0; i < range; i++) count[i] = 0;
for (i = 0; i < n; i++) count[array[i] - min]++;
for (i = 1; i < range; i++) count[i] = count[i] + count[i-1];
for (i = n-1; i >= 0; i--) {
sorted[count[array[i]]] = array[i];
count[array[i]]--;
}
free(count);
return sorted;
}
*/
void counting_sort_stable(int *array, int n, int min, int max) {
int i, j, z;
int range = max - min + 1;
int *count = malloc(range * sizeof(*array));
int *sorted = malloc(n * sizeof(*array));
for (i = 0; i < range; i++) count[i] = 0;
for (i = 0; i < n; i++) count[array[i] - min]++;
for (i = 1; i < range; i++) count[i] = count[i] + count[i-1];
for (i = n-1; i >= 0; i--) {
sorted[count[array[i]]] = array[i];
count[array[i]]--;
}
for (i = 0; i < n; i++) array[i] = sorted[i];
free(count);
free(sorted);
}
void counting_sort_instable(int *array, int n, int min, int max) {
int i, j, z;
int range = max - min + 1;
int *count = malloc(range * sizeof(*array));
for (i = 0; i < range; i++) count[i] = 0;
for (i = 0; i < n; i++) count[array[i] - min]++;
z = 0;
for (i = 0; i < range; i++) {
if (count[i] != 0) {
for (j = 0; j < count[i]; j++) {
array[z++] = i;
}
}
}
free(count);
}
void find_min_max(int *array, int n) {
int i, min, max;
for (i = 0; i < n; i++) {
if (array[i] < min) {
min = array[i];
} else if (array[i] > max) {
max = array[i];
}
}
}
#define N 10
#define MAX 1000
int main() {
int arr[N], i;
for (i = 0; i < N; i++) arr[i] = rand() % MAX;
counting_sort_stable(arr, N, 0, MAX);
for (i = 0; i < N; i++) printf("%d\n", arr[i]);
return EXIT_SUCCESS;
}
|
C
|
#ifndef _STDIO_H
#include <stdio.h>
#endif
void astreiheAusgeben(int mitte, int breite) {
int i;
for(i = 0; i < (mitte - (breite/2)); i++) {
printf(" ");
}
for(i = 0; i < breite; i++) {
printf("*");
}
printf("\n");
}
void stumpfAusgeben(int mitte) {
int i;
for(i = 0; i < (mitte-2); i++) {
printf(" ");
}
printf("| | |\n");
}
|
C
|
// The common code for the eval functions is here.
// This is meant to be included into the eval functions in board.c
u64 taken = black | white;
u64 empty = ~taken;
// Corners
double eeC = 0;
// Poison squares (squares that give up corner, or risky x-squares)
// This computation is finished in the C-squares section
u64 poisonBlack = 0;
u64 poisonWhite = 0;
u64 xPoisonBlack = 0;
u64 xPoisonWhite = 0;
// X-square check
#define XSQC(b) \
if (black & (b)) {eeC-=2;}\
else if (white & (b)) {eeC+=2;}\
else {xPoisonBlack |= (b); xPoisonWhite |= (b);}
// C squares
// More isolated c-squares are worse
// Macro for modifying c-square score based on corner a and adjacent c-square b
#define CSQS(b, c, shifter) \
if ((taken & ((b) | (c))) == (c)) {\
if (white & (c)) poisonBlack |= (b);\
else poisonWhite |= (b);\
}\
else if (black & (b)) {\
u64 c_region = b;\
c_region |= shifter(c_region) & black;\
c_region |= shifter(c_region) & black;\
c_region |= shifter(c_region) & black;\
c_region |= shifter(c_region) & black;\
c_region |= shifter(c_region) & black;\
if (PC(c_region) < 6) {\
eeC -= 2 * (0.8 - PC(c_region) * 0.1);\
c_region = shifter(c_region) & empty & ~CORNERS;\
if (c_region && (shifter(c_region) & white)) poisonBlack |= c_region;\
}\
}\
else if (white & (b)) {\
u64 c_region = (b);\
c_region |= shifter(c_region) & white;\
c_region |= shifter(c_region) & white;\
c_region |= shifter(c_region) & white;\
c_region |= shifter(c_region) & white;\
c_region |= shifter(c_region) & white;\
if (PC(c_region) < 6) {\
eeC += 2 * (0.8 - PC(c_region) * 0.1);\
c_region = shifter(c_region) & empty & ~CORNERS;\
if (c_region && (shifter(c_region) & black)) poisonWhite |= c_region;\
}\
}
// Score for corner patterns
#define SCPB(x) ((black & (x)) == (x))
#define SCPW(x) ((white & (x)) == (x))
if (taken & A1) {
if (black & A1) {
eeC += 2 + 2 * SCPB(A1 | B1);
eeC += 2 * SCPB(A1 | A2);
eeC += SCPB(A1 | B1 | C1);
eeC += SCPB(A1 | A2 | A3);
eeC += SCPB(A1 | B1 | C1 | D1);
eeC += SCPB(A1 | A2 | A3 | A4);
}
else {
eeC -= 2 + 2 * SCPW(A1 | B1);
eeC -= 2 * SCPW(A1 | A2);
eeC -= SCPW(A1 | B1 | C1);
eeC -= SCPW(A1 | A2 | A3);
eeC -= SCPW(A1 | B1 | C1 | D1);
eeC -= SCPW(A1 | A2 | A3 | A4);
}
}
else {
XSQC(B2);
CSQS(B1, C1, SHIFT_RIGHT);
CSQS(A2, A3, SHIFT_DOWN);
}
if (taken & H1) {
if (black & H1) {
eeC += 2 + 2 * SCPB(H1 | G1);
eeC += 2 * SCPB(H1 | H2);
eeC += SCPB(H1 | G1 | F1);
eeC += SCPB(H1 | H2 | H3);
eeC += SCPB(H1 | G1 | F1 | E1);
eeC += SCPB(H1 | H2 | H3 | H4);
}
else {
eeC -= 2 + 2 * SCPW(H1 | G1);
eeC -= 2 * SCPW(H1 | H2);
eeC -= SCPW(H1 | G1 | F1);
eeC -= SCPW(H1 | H2 | H3);
eeC -= SCPW(H1 | G1 | F1 | E1);
eeC -= SCPW(H1 | H2 | H3 | H4);
}
}
else {
XSQC(G2);
CSQS(G1, F1, SHIFT_LEFT);
CSQS(H2, H3, SHIFT_DOWN);
}
if (taken & A8) {
if (black & A8) {
eeC += 2 + 2 * SCPB(A8 | B8);
eeC += 2 * SCPB(A8 | A7);
eeC += SCPB(A8 | B8 | C8);
eeC += SCPB(A8 | A7 | A6);
eeC += SCPB(A8 | B8 | C8 | D8);
eeC += SCPB(A8 | A7 | A6 | A5);
}
else {
eeC -= 2 + 2 * SCPW(A8 | B8);
eeC -= 2 * SCPW(A8 | A7);
eeC -= SCPW(A8 | B8 | C8);
eeC -= SCPW(A8 | A7 | A6);
eeC -= SCPW(A8 | B8 | C8 | D8);
eeC -= SCPW(A8 | A7 | A6 | A5);
}
}
else {
XSQC(B7);
CSQS(B8, C8, SHIFT_RIGHT);
CSQS(A7, A6, SHIFT_UP);
}
if (taken & H8) {
if (black & H8) {
eeC += 2 + 2 * SCPB(H8 | G8);
eeC += 2 * SCPB(H8 | H7);
eeC += SCPB(H8 | G8 | F8);
eeC += SCPB(H8 | H7 | H6);
eeC += SCPB(H8 | G8 | F8 | E8);
eeC += SCPB(H8 | H7 | H6 | H5);
}
else {
eeC -= 2 + 2 * SCPW(H8 | G8);
eeC -= 2 * SCPW(H8 | H7);
eeC -= SCPW(H8 | G8 | F8);
eeC -= SCPW(H8 | H7 | H6);
eeC -= SCPW(H8 | G8 | F8 | E8);
eeC -= SCPW(H8 | H7 | H6 | H5);
}
}
else {
XSQC(G7);
CSQS(G8, F8, SHIFT_LEFT);
CSQS(H7, H6, SHIFT_UP);
}
// Scale down corner and c-square scores
eeC /= (1 + PC(EDGES & ~CORNERS & taken)) / 1.2;
// Frontier
// Idea: double frontier (2 away and unshielded)?
// Old idea: simple frontier ratio
//double blackFrontierRatio = PC(frontier(black, white)) / (double) PC(black);
//double whiteFrontierRatio = PC(frontier(white, black)) / (double) PC(white);
// New idea: Weighted frontiers
double eeF = frontierScore(white, black, poisonBlack | xPoisonBlack) - frontierScore(black, white, poisonWhite | xPoisonWhite);
// Mobility
u64 lmWhite = findLegalMoves(white, black);
int lmNumBlack = PC(lmBlack);
int lmNumWhite = PC(lmWhite);
int diff = lmNumBlack - lmNumWhite - 1; // The -1 is a penalty for having to move
double eeM = 4 * mobilityConstant[35 * lmNumBlack + lmNumWhite];
eeM = (diff > 0) ? eeM : -eeM;
// Putting it all together
double cornerWeight = 0.51;
double remainingWeight = (1 - cornerWeight);
double frontierWeight = (0.3 / 0.85) * remainingWeight;
double mobilityWeight = (0.55 / 0.85) * remainingWeight;
double ee = 1024 * (eeF * frontierWeight + eeC * cornerWeight + eeM * mobilityWeight);
double eeSumAbs = 1024 * (fabs(eeF) * frontierWeight + fabs(eeC) * cornerWeight + fabs(eeM) * mobilityWeight);
|
C
|
#include <stdio.h>
int fact(int n);
int powr(int x,int n);
double sin(double x);
int main()
{
printf("sin30: %f\nsin31: %f\nsin32: %f\nsin33: %f\nsin34: %f\nsin35: %f\n",sin(30*3.14/180),sin(31*3.14/180),sin(32*3.14/180),sin(33*3.14/180),sin(34*3.14/180),sin(35*3.14/180)); /*To convert the values ??to radians, multiply by pi and divide by 180.*/
return 0;
}
int fact(int n)
{
int result=1;
int i;
for(i=1;i<=n;i++)
{
result*=i; /* to get factorial, i multiplied by "result" until "n" */
}
return result;
}
int powr(int x,int n)
{
x/=10;
int result=1; /* I wanted the base function to multiply "x" by as small as "i", "n" */
int i;
for(i=1;i<=n;i++)
{
result*=x;
}
return result;
}
double sin(double x)
{
double result=0;
int i;
x*=10000000;
for(i=0;i<10;i++)
{
result += ((double)powr(-1,i) * (double)powr(x,2*i+1) / fact(2*i+1))/1000000; /*I arranged the necessary functions in accordance with the Taylor expansion equation.*/
}
return result;
}
|
C
|
#include "hash_aux.h"
// Function documentation is available at the header file
unsigned int djb2(unsigned char *str){
unsigned int hash = 5381;
int c;
while ((c = *str++))
hash = ((hash << 5) + hash) + c;
return hash;
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* b_cd.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: tkobb <tkobb@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2018/11/19 15:37:31 by tkobb #+# #+# */
/* Updated: 2018/11/23 08:24:38 by tkobb ### ########.fr */
/* */
/* ************************************************************************** */
#include <ft_sh.h>
#include <env.h>
static int special_cases(char **dst)
{
if (*dst == NULL)
{
MCK(*dst = ft_getenv("HOME"), 1);
}
else if ((*dst)[0] == '-')
{
if (((*dst) = ft_getenv("OLDPWD")) == NULL)
{
ft_dprintf(2, "%s: OLDPWD not set\n", "42sh");
return (1);
}
ft_printf("%s\n", (*dst));
}
return (0);
}
int b_cd(char **av)
{
char *dst;
char *curpwd;
if (av == NULL || av[0] == NULL)
return (1);
dst = av[1];
if (special_cases(&dst))
return (1);
MCK(curpwd = ft_getenv("PWD"), 1);
if (ft_setenv("OLDPWD", curpwd, 1))
;
if (chdir(dst) == -1)
return (error("cd"));
if ((curpwd = getcwd(NULL, 0)) == NULL)
return (error("getcwd"));
ft_setenv("PWD", curpwd, 1);
free(curpwd);
return (0);
}
|
C
|
/**
* helpers.c
*
* Helper functions for Problem Set 3.
*/
#include <cs50.h>
#include <stdio.h>
#include "helpers.h"
/**
* Returns true if value is in array of n values, else false.
*/
//binary search algorithm
bool search(int value, int values[], int n)
{
//checks if there are any values in the array
if(n < 1)
{
return false;
}
int indexLower = 0;
int indexUpper = n - 1;
int indexPosition;
//loops as long as the last index in the array is larger than the start position in the array on each iteration
while(indexUpper >= indexLower)
{
//sets the index position to the middle index of the array
indexPosition = indexLower + (int)((indexUpper - indexLower) / 2);
//returns true if a specific value in the array matches the search criteria else changes the search index range
if(value == values[indexPosition])
{
return true;
}
else if(value > values[indexPosition])
{
indexLower = indexPosition + 1;
}
else
{
indexUpper = indexPosition - 1;
}
}
return false;
}
/**
* Sorts array of n values.
*/
//bubble sort
void sort(int values[], int n)
{
// TODO: implement an O(n^2) sorting algorithm
int endIndex = n - 1;
int swapCounter;
//loop while swaps still need to occur
do
{
swapCounter = 0;
//iterate through the values in the array
for(int i = 0; i < endIndex; i++)
{
int leftIndexValue = values[i];
int rightIndexValue = values[i + 1];
//check if the current index position and the position right of it need swapping
if(rightIndexValue < leftIndexValue)
{
values[i] = rightIndexValue;
values[i + 1] = leftIndexValue;
swapCounter++;
}
}
}
while(swapCounter > 0);
return;
}
|
C
|
void main()
{
char a[3600];
gets(a);
char *p;
int len,n;
len=strlen(a);
n=0;
for(p=a;p<=a+len;p++)
{
if(*p!=' ')
{
n=n+1;
}
else if(*p==' '&&n!=0)
{
printf("%d,",n);
n=0;
}
}
printf("%d",n-1);
}
|
C
|
#include
void swapnum ( int *var1, int *var2 )
{
int tempnum ;
tempnum = *var1 ;
*var1 = *var2 ;
*var2 = tempnum ;
}
int main( )
{
int num1 = 35, num2 = 45 ;
printf("Before swapping:");
printf("\nnum1 value is %d", num1);
printf("\nnum2 value is %d", num2);
/*calling swap function*/
swapnum( &num1, &num2 );
printf("\nAfter swapping:");
printf("\nnum1 value is %d", num1);
printf("\nnum2 value is %d", num2);
return 0;
}
|
C
|
#include "holberton.h"
/**
* swap_int - Swap two integeres
* @a: Integer
* @b: Integer
*/
void swap_int(int *a, int *b)
{
int aux;
aux = *a;
*a = *b;
*b = aux;
}
/**
* reverse_array - reverses the content of an array of integers
* @a: varable to be used
* @n: number of elements in array
*/
void reverse_array(int *a, int n)
{
int pos;
pos = 0;
while (pos < n / 2)
{
swap_int(a + pos, a + n - pos - 1);
pos++;
}
}
|
C
|
#include<stdio.h>
#include<stdlib.h>
struct Node
{
int data;
struct Node* left;
struct Node* right;
};
struct Node* newnode(int data)
{
struct Node* root=(struct Node*)malloc(sizeof(struct Node));
root->left=NULL;
root->right=NULL;
root->data=data;
return root;
}
struct Node* queue[100];
int rear=0;
int front=-1;
void enqueue(struct Node* node)
{
queue[rear++]=node;
}
struct Node* dequeue()
{
return queue[++front];
}
void levelOrder(struct Node* root)
{
struct Node* temp=root;
while(temp)
{
printf("%d\t",temp->data);
if(temp->left)
enqueue(temp->left);
if(temp->right)
enqueue(temp->right);
temp=dequeue();
}
}
int main()
{
struct Node* root=newnode(2);
root->left = newnode(3);
root->right = newnode(4);
root->left->left = newnode(7);
root->left->left->left = newnode(1);
levelOrder(root);
return 0;
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* add_prefix.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: rnoriko <rnoriko@student.21-school.ru> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/06/08 09:53:36 by rnoriko #+# #+# */
/* Updated: 2021/06/14 11:35:50 by rnoriko ### ########.fr */
/* */
/* ************************************************************************** */
#include "ft_printf.h"
char *ft_sharp(char *save, t_format_arg *format_arg)
{
char *prefix;
char *tmp;
if ((format_arg->spec_type == 'x' || format_arg->spec_type == 'X')
&& *save && *save != '0')
format_arg->sharp_x = 1;
if (format_arg->spec_type == 'o' && *save != '0')
prefix = ft_strdup("0");
else if (format_arg->spec_type == 'x' && format_arg->sharp_x)
prefix = ft_strdup("0x");
else if (format_arg->spec_type == 'X' && format_arg->sharp_x)
prefix = ft_strdup("0X");
else
return (save);
tmp = save;
save = ft_strjoin(prefix, save);
free(prefix);
free(tmp);
return (save);
}
char *ft_addplus_space(char *save, t_format_arg format_arg)
{
char *join_result;
char *pre_sign;
long c;
c = (long)format_arg.plus;
pre_sign = ft_chrdup(c);
join_result = ft_strjoin(pre_sign, save);
free(pre_sign);
free(save);
return (join_result);
}
|
C
|
#pragma once
#include "sort_util.h"
void heap_adjust(data_t* datas, int l, int r)
{
data_t tmp = datas[l];
int i = l;
int j = 2 * i + 1;
while (j <= r)
{
if (j + 1 <= r && datas[j] < datas[j + 1])
{
j++;
}
if (datas[i] > datas[j])
{
break;
}
else
{
swap(&datas[i], &datas[j]);
i = j;
j = 2 * i + 1;
}
}
}
void sort_heap(data_t* datas, int size)
{
for (int i = size / 2; i >= 0; i--)
{
heap_adjust(datas, i, size - 1);
}
for (int i = size - 1; i > 0; i--)
{
swap(&datas[0], &datas[i]);
heap_adjust(datas, 0, i - 1);
}
}
|
C
|
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include "total_function.h"
/*
WHICH BLOCK WOULD YOU LIKE TO SEARCH ? (A1 , A2 , B1 , B3)
PLEASE ENTER YOUR CHOICE : a1
STUDENT ID: TP049952 FIRST NAME: JARED GENDER: M BLOCK: A1 ROOM: 1 IDETIFICATION: 990423076521 PHONE: 0134020303 EMAIL: jaredchan0074@gmail.com
STUDENT ID: TP204357 FIRST NAME: ROBERT GENDER: M BLOCK: A1 ROOM: 96 IDETIFICATION: AK729302 PHONE: 0174338694 EMAIL: iron_man99@gmail.com
PRESS ANYTHING TO EXIT :
*/
/* THIS FUNCTION IS CALLED FOR LISTING ALL THE DEATILS OF STUDENTS BASED ON BLOCK */
/* VISUALS SHOWN ABOVE IS FOR BLOCK A1*/
/* FUNCTION IS CALLED IN check_room_available.c*/
void check_block_student() {
FILE *block;
char check_block[3],check_choice;
block = fopen("Student.txt", "r");
printf("\tWHICH BLOCK WOULD YOU LIKE TO SEARCH ? (A1 , A2 , B1 , B3)\n");
printf("\tPLEASE ENTER YOUR CHOICE : ");
scanf("%s",check_block);
if ((check_block[0] == 'A' || check_block[0] == 'a') && check_block[1] == '1') {
while (fscanf(block, "%s \t %s \t %s \t %s \t %s \t %d \t %s \t %s \t %s \t %d \t %d \t %d \t %d \t %d \t %d \t %d \n", strupr(check.studentID), check.firstName, check.lastName, check.gender, check.identification, &check.age, check.phone_num, check.email, check.block_area, &check.room_num, &check.laundry_service, &check.gym_service, &check.week_stay, &check.amount_due, &check.paid_amount, &check.bed_num) != EOF) {
if (check.block_area[0] == 'A' && check.block_area[1] == '1')
printf("\tSTUDENT ID: %s FIRST NAME: %s GENDER: %s BLOCK: %s ROOM: %d IDETIFICATION: %s PHONE: %s EMAIL: %s AMOUNT RECEIVABLE: %d\n", check.studentID, strupr(check.firstName), check.gender, check.block_area, check.room_num, check.identification, check.phone_num, check.email, check.amount_due);
}
}
else if ((check_block[0] == 'A' || check_block[0] == 'a') && check_block[1] == '2') {
while (fscanf(block, "%s \t %s \t %s \t %s \t %s \t %d \t %s \t %s \t %s \t %d \t %d \t %d \t %d \t %d \t %d \t %d \n", strupr(check.studentID), check.firstName, check.lastName, check.gender, check.identification, &check.age, check.phone_num, check.email, check.block_area, &check.room_num, &check.laundry_service, &check.gym_service, &check.week_stay, &check.amount_due, &check.paid_amount, &check.bed_num) != EOF) {
if (check.block_area[0] == 'A' && check.block_area[1] == '2')
printf("\tSTUDENT ID: %s FIRST NAME: %s GENDER: %s BLOCK: %s ROOM: %d IDETIFICATION: %s PHONE: %s EMAIL: %s AMOUNT RECEIVABLE: %d\n", check.studentID, strupr(check.firstName), check.gender, check.block_area, check.room_num, check.identification, check.phone_num, check.email, check.amount_due);
}
}
else if ((check_block[0] == 'B' || check_block[0] == 'b') && check_block[1] == '1') {
while (fscanf(block, "%s \t %s \t %s \t %s \t %s \t %d \t %s \t %s \t %s \t %d \t %d \t %d \t %d \t %d \t %d \t %d \n", strupr(check.studentID), check.firstName, check.lastName, check.gender, check.identification, &check.age, check.phone_num, check.email, check.block_area, &check.room_num, &check.laundry_service, &check.gym_service, &check.week_stay, &check.amount_due, &check.paid_amount, &check.bed_num) != EOF) {
if (check.block_area[0] == 'B' && check.block_area[1] == '1')
printf("\tSTUDENT ID: %s FIRST NAME: %s GENDER: %s BLOCK: %s ROOM: %d IDETIFICATION: %s PHONE: %s EMAIL: %s AMOUNT RECEIVABLE: %d\n", check.studentID, strupr(check.firstName), check.gender, check.block_area, check.room_num, check.identification, check.phone_num, check.email, check.amount_due);
}
}
else if ((check_block[0] == 'B' || check_block[0] == 'b') && check_block[1] == '3') {
while (fscanf(block, "%s \t %s \t %s \t %s \t %s \t %d \t %s \t %s \t %s \t %d \t %d \t %d \t %d \t %d \t %d \t %d \n", strupr(check.studentID), check.firstName, check.lastName, check.gender, check.identification, &check.age, check.phone_num, check.email, check.block_area, &check.room_num, &check.laundry_service, &check.gym_service, &check.week_stay, &check.amount_due, &check.paid_amount, &check.bed_num) != EOF) {
if (check.block_area[0] == 'B' && check.block_area[1] == '3')
printf("\tSTUDENT ID: %s FIRST NAME: %s GENDER: %s BLOCK: %s ROOM: %d IDETIFICATION: %s PHONE: %s EMAIL: %s AMOUNT RECEIVABLE: %d\n", check.studentID, strupr(check.firstName), check.gender, check.block_area, check.room_num, check.identification, check.phone_num, check.email, check.amount_due);
}
}
printf("\n\n\tPRESS ANYTHING TO EXIT : ");
scanf("%c", &check_choice);
fclose(block);
}
|
C
|
#include <stdio.h>
int findDigitalRoot(int number)
{
while(number >= 10)
{
number = number % 10 + findDigitalRoot(number / 10);
}
return number;
}
int main(int argc, char *argv[])
{
int digitalRoot = findDigitalRoot(atoi(argv[1]));
printf("Digital root: %d", digitalRoot);
return 0;
}
|
C
|
/**
* Hamlog
*
* Copyright (C) 2011, Jan Kaluza <hanzz.k@gmail.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02111-1301 USA
*/
#include "parser.h"
#include <stdlib.h>
#include <stdio.h>
#include <stddef.h>
#include <string.h>
#include <errno.h>
#include "list.h"
HAMParser *ham_parser_new() {
HAMParser *parser = malloc(sizeof(HAMParser));
if (parser == NULL)
return NULL;
ham_parser_reset(parser);
return parser;
}
static int isChar(int c) {
return c >= 0 && c <= 127;
}
static int isControl(int c) {
return (c >= 0 && c <= 31) || c == 127;
}
static int isSpecial(int c) {
switch (c) {
case '(':
case ')':
case '<':
case '>':
case '@':
case ',':
case ';':
case ':':
case '\\':
case '"':
case '/':
case '[':
case ']':
case '?':
case '=':
case '{':
case '}':
case ' ':
case '\t':
return 1;
default:
return 0;
}
}
static int isDigit(int c) {
return c >= '0' && c <= '9';
}
static int ham_parser_consume(HAMParser *parser, HAMReply *reply, char input) {
switch (parser->state) {
case http_version_h:
if (input == 'H') {
parser->state = http_version_t_1;
return 1;
}
/*HACK: FIX ME*/
else if (input == 10 || input == 13) {
return 1;
}
else {
return 0;
}
case http_version_t_1:
if (input == 'T') {
parser->state = http_version_t_2;
return 1;
}
else {
return 0;
}
case http_version_t_2:
if (input == 'T') {
parser->state = http_version_p;
return 1;
}
else {
return 0;
}
case http_version_p:
if (input == 'P') {
parser->state = http_version_slash;
return 1;
}
else {
return 0;
}
case http_version_slash:
if (input == '/') {
parser->state = http_version_major_start;
return 1;
}
else {
return 0;
}
case http_version_major_start:
if (isDigit(input)) {
parser->state = http_version_major;
return 1;
}
else {
return 0;
}
case http_version_major:
if (input == '.') {
parser->state = http_version_minor_start;
return 1;
}
else if (isDigit(input)) {
return 1;
}
else {
return 0;
}
case http_version_minor_start:
if (isDigit(input)) {
parser->state = http_version_minor;
return 1;
}
else {
return 0;
}
case http_version_minor:
if (input == ' ') {
parser->state = status_start;
return 1;
}
else if (isDigit(input)) {
return 1;
}
else {
return 0;
}
case status_start:
if (isDigit(input)) {
reply->status = 100 * (input - '0');
parser->state = status_1;
return 1;
}
else {
return 0;
}
case status_1:
if (isDigit(input)) {
reply->status += 10 * (input - '0');
parser->state = status_2;
return 1;
}
else {
return 0;
}
case status_2:
if (isDigit(input)) {
reply->status += input - '0';
parser->state = status_text;
return 1;
}
else {
return 0;
}
case status_text:
/* we skip this one */
if (isDigit(input)) {
return 0;
}
else if (input == '\r') {
parser->state = expecting_newline_1;
return 1;
}
else {
return 1;
}
case expecting_newline_1:
if (input == '\n') {
parser->state = header_line_start;
return 1;
}
else {
return 0;
}
case header_line_start:
if (input == '\r') {
parser->state = expecting_newline_3;
return 1;
}
else if (reply->headers_count == 0 && (input == ' ' || input == '\t')) {
parser->state = header_lws;
return 1;
}
else if (!isChar(input) || isControl(input) || isSpecial(input)) {
return 0;
}
else {
parser->state = header_name;
parser->ptr = parser->header_name;
*parser->ptr++ = input;
return 1;
}
case header_lws:
if (input == '\r') {
parser->state = expecting_newline_2;
return 1;
}
else if (input == ' ' || input == '\t') {
return 1;
}
else if (isControl(input)) {
return 0;
}
else {
parser->state = header_value;
*parser->ptr++ = input;
//response->m_headers.back().value.push_back(input);
return 1;
}
case header_name:
if (input == ':') {
parser->state = space_before_header_value;
return 1;
}
else if (!isChar(input) || isControl(input) || isSpecial(input)) {
return 0;
}
else {
*parser->ptr++ = input;
return 1;
}
case space_before_header_value:
if (input == ' ') {
parser->state = header_value;
*parser->ptr = 0;
parser->ptr = parser->header_value;
return 1;
}
else {
return 0;
}
case header_value:
if (input == '\r') {
parser->state = expecting_newline_2;
*parser->ptr = 0;
HAMReplyHeader *header = ham_reply_header_new(parser->header_name, parser->header_value);
ham_reply_add_header(reply, header);
return 1;
}
else if (isControl(input)) {
return 0;
}
else {
*parser->ptr++ = input;
return 1;
}
case content_start:
if (input == '\r') {
parser->state = expecting_newline_3;
return 1;
}
else {
parser->state = content;
parser->ptr = reply->content;
*parser->ptr++ = input;
return 1;
}
case content:
if (input == '\r') {
*parser->ptr = 0;
parser->state = expecting_newline_4;
return 1;
}
else {
*parser->ptr++ = input;
return 1;
}
case expecting_newline_2:
if (input == '\n') {
parser->state = header_line_start;
return 1;
}
else {
return 0;
}
case expecting_newline_3:
if (input == '\n') {
if (ham_reply_get_header(reply, "Content-Length") && strcmp(ham_reply_get_header(reply, "Content-Length"), "0") != 0) {
parser->state = content_start;
}
else {
*reply->content = 0;
reply->finished = 1;
ham_parser_reset(parser);
}
return 1;
}
return 0;
case expecting_newline_4:
if (input == '\n') {
reply->finished = 1;
ham_parser_reset(parser);
return 1;
}
return 0;
default:
return 0;
}
}
unsigned long ham_parser_parse(HAMParser *parser, HAMReply *response, const char *data, unsigned long size) {
unsigned long old_size = size;
for (;size > 0; size--) {
if (ham_parser_consume(parser, response, *data++) == 0) {
ham_parser_reset(parser);
return old_size - size;
}
if (response->finished) {
return old_size - size;
}
}
return old_size - size;
}
void ham_parser_reset(HAMParser *parser) {
parser->state = http_version_h;
parser->ptr = NULL;
}
void ham_parser_destroy(HAMParser *parser) {
if (parser == NULL)
return;
free(parser);
}
HAMList *ham_csv_parse(const char *str) {
HAMList *tokens = ham_list_new();
ham_list_set_free_func(tokens, (HAMListItemDataFree) ham_list_destroy);
unsigned int pos = 0;
int quotes = 0;
char field[65535];
char *ptr = field;
HAMList *line = ham_list_new();
ham_list_set_free_func(line, free);
while(pos < strlen(str) && str[pos] != 0) {
char c = str[pos];
if (!quotes && c == '"' ) {
quotes = 1;
}
else if (quotes && c== '"' ) {
if (pos + 1 < strlen(str) && str[pos+1]== '"' ) {
*ptr++ = c;
pos++;
}
else {
quotes = 0;
}
}
else if (!quotes && c == ';') {
*ptr++ = 0;
ham_list_insert_last(line, strdup(field));
ptr = field;
*ptr = 0;
}
else if (!quotes && ( c == '\n' || c == '\r' )) {
*ptr++ = 0;
ham_list_insert_last(line, strdup(field));
ptr = field;
*ptr = 0;
ham_list_insert_last(tokens, line);
line = ham_list_new();
ham_list_set_free_func(line, free);
}
else {
*ptr++ = c;
}
pos++;
}
if (strlen(field) != 0) {
ham_list_insert_last(line, strdup(field));
ham_list_insert_last(tokens, line);
}
else {
ham_list_destroy(line);
}
return tokens;
}
char *ham_csv_from_list(HAMList *parsed) {
unsigned long length = 0;
// Count the output size
HAMListItem *line = ham_list_get_first_item(parsed);
while (line) {
HAMListItem *field = ham_list_get_first_item(ham_list_item_get_data(line));
while (field) {
length += strlen(ham_list_item_get_data(field)) + 1; // ';'
field = ham_list_get_next_item(field);
}
length += 1; // '\n'
line = ham_list_get_next_item(line);
}
length += 1; // '\0'
// Generate the output string
char *res = malloc(sizeof(char) * length);
char *ptr = res;
line = ham_list_get_first_item(parsed);
while (line) {
HAMListItem *field = ham_list_get_first_item(ham_list_item_get_data(line));
while (field) {
strcpy(ptr, (char *) ham_list_item_get_data(field));
ptr += strlen(ham_list_item_get_data(field));
*ptr++ = ';';
field = ham_list_get_next_item(field);
}
*ptr++ = '\n';
line = ham_list_get_next_item(line);
}
*ptr++ = 0;
return res;
}
char *ham_csv_merge(const char *first, const char *second) {
// get the header line from "first"
HAMList *first_lines = ham_csv_parse(first);
HAMList *parsed = first_lines;
HAMListItem *first_line = ham_list_get_first_item(first_lines);
// get the header line from "second"
HAMList *second_lines = ham_csv_parse(second);
HAMListItem *second_line = ham_list_get_first_item(second_lines);
while(first_line && second_line) {
// add everything from "second" line to "first" line
HAMListItem *field = ham_list_get_first_item(ham_list_item_get_data(second_line));
while (field) {
ham_list_insert_last(ham_list_item_get_data(first_line), ham_list_item_get_data(field));
field = ham_list_get_next_item(field);
}
first_line = ham_list_get_next_item(first_line);
second_line = ham_list_get_next_item(second_line);
}
char *csv = ham_csv_from_list(parsed);
ham_list_destroy(parsed);
return csv;
}
|
C
|
/*
* procfs1.c
*/
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/proc_fs.h>
#include <linux/uaccess.h>
#define procfs_name "helloworld"
struct proc_dir_entry *Our_Proc_File;
ssize_t procfile_read(struct file *filePointer,char *buffer, size_t buffer_length, loff_t * offset)
{
int ret=0;
if(strlen(buffer) ==0) {
pr_info("procfile read %s\n",filePointer->f_path.dentry->d_name.name);
ret=copy_to_user(buffer,"HelloWorld!\n",sizeof("HelloWorld!\n"));
ret=sizeof("HelloWorld!\n");
}
return ret;
}
static const struct file_operations proc_file_fops = {
.owner = THIS_MODULE,
.read = procfile_read,
};
int init_module()
{
Our_Proc_File = proc_create(procfs_name,0644,NULL,&proc_file_fops);
if(NULL==Our_Proc_File) {
proc_remove(Our_Proc_File);
pr_alert("Error:Could not initialize /proc/%s\n",procfs_name);
return -ENOMEM;
}
pr_info("/proc/%s created\n", procfs_name);
return 0;
}
void cleanup_module()
{
proc_remove(Our_Proc_File);
pr_info("/proc/%s removed\n", procfs_name);
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* env.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: llim <llim@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/03/12 22:38:22 by llim #+# #+# */
/* Updated: 2021/04/20 12:26:41 by llim ### ########.fr */
/* */
/* ************************************************************************** */
#include "minishell.h"
void parse_env(char **envp, t_state *state)
{
int i;
int j;
char *key;
char *value;
i = 0;
while (envp[i])
{
j = 0;
while (envp[i][j])
{
if (envp[i][j] == '=')
{
key = ft_substr(envp[i], 0, j);
value = ft_substr(envp[i], j + 1, ft_strlen(envp[i]) - j - 1);
break ;
}
j++;
}
add_env_back(&(state->env_head), key, value, TRUE);
free(key);
free(value);
i++;
}
update_env(state->env_head, "OLDPWD", "", FALSE);
}
void add_env_back(t_env **head, char *key, char *value, int has_equal)
{
t_env *env;
if (*head == NULL)
*head = create_env(key, value, has_equal);
else
{
env = *head;
while (env->next)
env = env->next;
env->next = create_env(key, value, has_equal);
}
}
t_env *create_env(char *key, char *value, int has_equal)
{
t_env *env;
if (!ft_calloc(1, sizeof(t_env), (void *)&env))
exit(1);
env->key = ft_strdup(key);
env->has_equal = has_equal;
env->next = 0;
if (value)
env->value = ft_strdup(value);
else
env->value = ft_strdup("");
return (env);
}
void change_dollar_sign(int i)
{
int len;
char *key;
char *temp;
char *value;
char *input;
input = g_state.input2;
len = check_key_len(&input[i + 1], TRUE);
key = ft_substr(&input[i + 1], 0, len);
if (!ft_strcmp(key, "?"))
{
temp = ft_itoa(g_state.ret);
value = ft_strdup(temp);
free(temp);
}
else
value = ft_strdup(find_env_val(g_state.env_head, key));
free(key);
temp = changed_str(input, i, i + len, value);
free(g_state.input2);
g_state.input2 = ft_strdup(temp);
free(temp);
}
|
C
|
#include <stdio.h>
#include "WolframRTL.h"
#include "functions.m.h"
int main(int argc, char *arg[])
{
double num1 = 20.4;
double num2;
WolframLibraryData libData = WolframLibraryData_new(WolframLibraryVersion);
Initialize_functions(libData);
square(libData, num1, &num2);
printf("square %5.2f\n", num2);
cube(libData, num1, &num2);
printf("cube %5.2f\n", num2);
WolframLibraryData_free(libData);
return 0;
}
|
C
|
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
int main(){
int t,i=0,c=1,j=0;
float avg;
cin>>t;
while(t--)
{
char a;
while(c<3){
scanf("%c",&a);
if(a==' ')
j++;
else if(a=='\n')
c++;
else
i++;
}
avg=i/j;
if(avg>=8)
cout<<"High\n";
else if(avg>=4&&avg<8)
cout<<"Medium\n";
else
cout<<"Low\n";
}
return 0;
}
|
C
|
//#include <stdio.h>
//
//int N, M;
//int front, back=-1;
//int num;
//int cnt;
//int q[100000];
//int push(int num)
//{
// q[++back] = num;
//}
//int pop()
//{
// return q[front++];
//}
// int main()
//{
// scanf("%d %d", &N, &M);
//
// for (int i = 1; i <= N; i++)
// {
// push(i);
// }
// for (int i = 0; i < M; i++)
// {
// scanf("%d", &num);
// if (num - 1 - front < back - num+1)
// {
// while (front!=num-1) {
// push(pop());
// cnt++;
// }
// pop();
// }
// else
// {
// while (back-num !=-2) {
// q[(front+N-1)%N] = q[--back];
// cnt++;
// }
// pop();
// }
// }
// printf("%d", cnt);
//}
|
C
|
/*
* Makenna Kidd
* CSE 240
* Professor Chen
* T+TH 1:30pm - 2:45pm
* Due Jan 23th by 11:59pm
*
* This program hw01q2_2 was rewritten from the provided homework problem into a for loop format to contain
* break statements, fix syntax/semantic errors, change numbers to floating point, and allow user input to enter an operation.
*
*/
#include <stdio.h>
void main()
{
char ch = ' ';
double a = 10, b = 20;
double f;
int i = 0;
for (i = 0; i < 5; i++)
{
printf(" Enter a math operation: ");
ch = getchar(); // Reading char that user entered.
printf(" ch = %c \n", ch); //Printing char entered.
switch (ch)
{
// case statements below changed to floating numbers instead of decimals.
case '+': f = a + b; printf(" f = %g\n", f); break;
case '-': f = a - b; printf(" f = %g\n", f); break;
case '*': f = a * b; printf(" f = %g\n", f); break;
case '/': f = a / b; printf(" f = %g\n", f); break;
default: printf(" Invalid operator\n"); break;
}
ch = getchar();
}
ch = getchar(); // Restarting the loop to get another char and keeping the console window open.
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fast-aleck/fast-aleck.h>
struct fast_aleck_test_case {
int count;
int passes;
int fails;
char wrap_amps;
char wrap_caps;
char wrap_quotes;
char widont;
};
void fast_aleck_test(struct fast_aleck_test_case *a_test_case, char *a_input, char *a_expected_output);
int main(void)
{
struct fast_aleck_test_case test_case;
test_case.count = 0;
test_case.passes = 0;
test_case.fails = 0;
test_case.wrap_amps = 0;
test_case.wrap_caps = 0;
test_case.wrap_quotes = 0;
test_case.widont = 0;
fprintf(stdout, "1..%i\n", test_case.count);
fast_aleck_test(&test_case,
"I am a simple sentence.",
"I am a simple sentence.");
fast_aleck_test(&test_case,
"I am... a sentence with an ellipsis!",
"I am… a sentence with an ellipsis!");
fast_aleck_test(&test_case,
"I am a sentence--really---with two dashes!",
"I am a sentence—really—with two dashes!");
fast_aleck_test(&test_case,
"This sentence ends in two periods..",
"This sentence ends in two periods..");
fast_aleck_test(&test_case,
"This sentence ends in three periods...",
"This sentence ends in three periods…");
fast_aleck_test(&test_case,
"Weird! This sentence ends in a dash-",
"Weird! This sentence ends in a dash-");
fast_aleck_test(&test_case,
"Weird! This sentence ends in two dashes--",
"Weird! This sentence ends in two dashes—");
fast_aleck_test(&test_case,
"Weird! This sentence ends in three dashes---",
"Weird! This sentence ends in three dashes—");
fast_aleck_test(&test_case,
"My sister's book. My sisters' books.",
"My sister’s book. My sisters’ books.");
fast_aleck_test(&test_case,
"'Hello', she said. 'Hello,' she said. 'Huh...' she mumbled.",
"‘Hello’, she said. ‘Hello,’ she said. ‘Huh…’ she mumbled.");
fast_aleck_test(&test_case,
"\"Hello\", she said. \"Hello,\" she said. \"Huh...\" she mumbled.",
"“Hello”, she said. “Hello,” she said. “Huh…” she mumbled.");
fast_aleck_test(&test_case,
"'That's mine!', she said. \"That's mine!\", she said.",
"‘That’s mine!’, she said. “That’s mine!”, she said.");
fast_aleck_test(&test_case,
"(\"Amazing!\" she thought.) ('Amazing!' she thought.)",
"(“Amazing!” she thought.) (‘Amazing!’ she thought.)");
fast_aleck_test(&test_case,
"Before... yes. <img alt=\"During... no.\"> After... yes.",
"Before… yes. <img alt=\"During... no.\"> After… yes.");
fast_aleck_test(&test_case,
"Before... yes. <script>In script... no.</script> After... yes.",
"Before… yes. <script>In script... no.</script> After… yes.");
fast_aleck_test(&test_case,
"Before... yes. <pre>In pre... no.</pre> After... yes.",
"Before… yes. <pre>In pre... no.</pre> After… yes.");
fast_aleck_test(&test_case,
"Before... yes. <code>In code... no.</code> After... yes.",
"Before… yes. <code>In code... no.</code> After… yes.");
fast_aleck_test(&test_case,
"Before... yes. <kbd>In kbd... no.</kbd> After... yes.",
"Before… yes. <kbd>In kbd... no.</kbd> After… yes.");
fast_aleck_test(&test_case,
"Before... <samp>In samp... </samp> After...",
"Before… <samp>In samp... </samp> After…");
fast_aleck_test(&test_case,
"Before... <var>In var... </var> After...",
"Before… <var>In var... </var> After…");
fast_aleck_test(&test_case,
"Before... <math>In math... </math> After...",
"Before… <math>In math... </math> After…");
fast_aleck_test(&test_case,
"Before... <textarea>In textarea... </textarea> After...",
"Before… <textarea>In textarea... </textarea> After…");
fast_aleck_test(&test_case,
"Before... yes. <p>In something else (like p)... yes!</p> After... yes.",
"Before… yes. <p>In something else (like p)… yes!</p> After… yes.");
fast_aleck_test(&test_case,
"Before... <pre>In pre... <code>In code...</code> In pre...</pre> After...",
"Before… <pre>In pre... <code>In code...</code> In pre...</pre> After…");
fast_aleck_test(&test_case,
"Some <em>text</em> wrapped in <span class=\"meh\">elements</span>.",
"Some <em>text</em> wrapped in <span class=\"meh\">elements</span>.");
fast_aleck_test(&test_case,
"Before... <codezzz>during...</codezzz> after...",
"Before… <codezzz>during…</codezzz> after…");
fast_aleck_test(&test_case,
"Before... <kbdzzz>during...</kbdzzz> after...",
"Before… <kbdzzz>during…</kbdzzz> after…");
fast_aleck_test(&test_case,
"Before... <prezzz>during...</prezzz> after...",
"Before… <prezzz>during…</prezzz> after…");
fast_aleck_test(&test_case,
"Before... <scriptzzz>during...</scriptzzz> after...",
"Before… <scriptzzz>during…</scriptzzz> after…");
fast_aleck_test(&test_case,
"Before... <zzzcode>during...</zzzcode> after...",
"Before… <zzzcode>during…</zzzcode> after…");
fast_aleck_test(&test_case,
"Before... <zzzkbd>during...</zzzkbd> after...",
"Before… <zzzkbd>during…</zzzkbd> after…");
fast_aleck_test(&test_case,
"Before... <zzzpre>during...</zzzpre> after...",
"Before… <zzzpre>during…</zzzpre> after…");
fast_aleck_test(&test_case,
"Before... <zzzscript>during...</zzzscript> after...",
"Before… <zzzscript>during…</zzzscript> after…");
fast_aleck_test(&test_case,
"<script>",
"<script>");
fast_aleck_test(&test_case,
"</script>",
"</script>");
fast_aleck_test(&test_case,
"<script>a",
"<script>a");
fast_aleck_test(&test_case,
"\"<a href=\"#\">blah</a>\"",
"“<a href=\"#\">blah</a>”");
fast_aleck_test(&test_case,
"<a href=\"#\">\"blah\"</a>",
"<a href=\"#\">“blah”</a>");
fast_aleck_test(&test_case,
"\"blah <a href=\"#\">blah</a>\"",
"“blah <a href=\"#\">blah</a>”");
fast_aleck_test(&test_case,
"\"<div>blah</div>\"",
"“<div>blah</div>“");
fast_aleck_test(&test_case,
"<div>\"blah\"</div>",
"<div>“blah”</div>");
fast_aleck_test(&test_case,
"\"blah <div>blah</div>\"",
"“blah <div>blah</div>“");
// WRAP AMPS TESTS
test_case.wrap_amps = 1;
fast_aleck_test(&test_case,
"Four < Seventeen",
"Four < Seventeen");
fast_aleck_test(&test_case,
"Ampersands & More",
"Ampersands <span class=\"amp\">&</span> More");
fast_aleck_test(&test_case,
"A & B <title>C & D</title> E & F",
"A <span class=\"amp\">&</span> B <title>C & D</title> E <span class=\"amp\">&</span> F");
test_case.wrap_amps = 0;
// WRAP QUOTES TESTS
test_case.wrap_quotes = 1;
fast_aleck_test(&test_case,
"There's a hole in the sky.",
"There’s a hole in the sky.");
fast_aleck_test(&test_case,
"'There's a hole in the sky', he said. 'Don't be silly', she said.",
"<span class=\"quo\">‘</span>There’s a hole in the sky’, he said. ‘Don’t be silly’, she said.");
fast_aleck_test(&test_case,
"\"There's a hole in the sky\", he said. \"Don't be silly\", she said.",
"<span class=\"dquo\">“</span>There’s a hole in the sky”, he said. “Don’t be silly”, she said.");
fast_aleck_test(&test_case,
"\"Here.\"<p>\"Here.\" \"Not here.\"<p>\"Here.\"",
"<span class=\"dquo\">“</span>Here.”<p><span class=\"dquo\">“</span>Here.” “Not here.”<p><span class=\"dquo\">“</span>Here.”");
fast_aleck_test(&test_case,
"\"Here.\"<li>\"Here.\" \"Not here.\"<li>\"Here.\"",
"<span class=\"dquo\">“</span>Here.”<li><span class=\"dquo\">“</span>Here.” “Not here.”<li><span class=\"dquo\">“</span>Here.”");
fast_aleck_test(&test_case,
"\"Here.\"<div>\"Here.\" \"Not here.\"<div>\"Here.\"",
"<span class=\"dquo\">“</span>Here.”<div><span class=\"dquo\">“</span>Here.” “Not here.”<div><span class=\"dquo\">“</span>Here.”");
fast_aleck_test(&test_case,
"<title>'There's a hole in the sky'</title>",
"<title>‘There’s a hole in the sky’</title>");
// TODO h1, h2, ..., h6
test_case.wrap_quotes = 0;
// WIDONT TESTS
test_case.widont = 1;
fast_aleck_test(&test_case,
"<p>Foo bar baz.</p><p>Woof meow moo.</p>",
"<p>Foo bar baz.</p><p>Woof meow moo.</p>");
fast_aleck_test(&test_case,
"<li>Foo bar baz.</li><li>Woof meow moo.</li>",
"<li>Foo bar baz.</li><li>Woof meow moo.</li>");
fast_aleck_test(&test_case,
"<div>Foo bar baz.</div><div>Woof meow moo.</div>",
"<div>Foo bar baz.</div><div>Woof meow moo.</div>");
fast_aleck_test(&test_case,
"<h1>Foo bar baz.</h1><h1>Woof meow moo.</h1>",
"<h1>Foo bar baz.</h1><h1>Woof meow moo.</h1>");
fast_aleck_test(&test_case,
"<h2>Foo bar baz.</h2><h2>Woof meow moo.</h2>",
"<h2>Foo bar baz.</h2><h2>Woof meow moo.</h2>");
fast_aleck_test(&test_case,
"<h3>Foo bar baz.</h3><h3>Woof meow moo.</h3>",
"<h3>Foo bar baz.</h3><h3>Woof meow moo.</h3>");
fast_aleck_test(&test_case,
"<h4>Foo bar baz.</h4><h4>Woof meow moo.</h4>",
"<h4>Foo bar baz.</h4><h4>Woof meow moo.</h4>");
fast_aleck_test(&test_case,
"<h5>Foo bar baz.</h5><h5>Woof meow moo.</h5>",
"<h5>Foo bar baz.</h5><h5>Woof meow moo.</h5>");
fast_aleck_test(&test_case,
"<h6>Foo bar baz.</h6><h6>Woof meow moo.</h6>",
"<h6>Foo bar baz.</h6><h6>Woof meow moo.</h6>");
fast_aleck_test(&test_case,
"<blockquote>Foo bar baz.</blockquote><blockquote>Woof meow moo.</blockquote>",
"<blockquote>Foo bar baz.</blockquote><blockquote>Woof meow moo.</blockquote>");
fast_aleck_test(&test_case,
"<dd>Foo bar baz.</dd><dd>Woof meow moo.</dd>",
"<dd>Foo bar baz.</dd><dd>Woof meow moo.</dd>");
fast_aleck_test(&test_case,
"<dt>Foo bar baz.</dt><dt>Woof meow moo.</dt>",
"<dt>Foo bar baz.</dt><dt>Woof meow moo.</dt>");
fast_aleck_test(&test_case,
"<ol>\n<li>This is a list item</li>\n</ol>",
"<ol>\n<li>This is a list item</li>\n</ol>");
fast_aleck_test(&test_case,
"<section>\n<h1>Title!</h1>\n</section>",
"<section>\n<h1>Title!</h1>\n</section>");
fast_aleck_test(&test_case,
"<p>Paragraph one</p>\n<p>Paragraph two</p>",
"<p>Paragraph one</p>\n<p>Paragraph two</p>");
fast_aleck_test(&test_case,
"<dt>Foo bar baz.</dt>\n<dt>Woof meow moo.</dt>",
"<dt>Foo bar baz.</dt>\n<dt>Woof meow moo.</dt>");
fast_aleck_test(&test_case,
"<li><a href=\"../\"><span>Home</span></a></li>\n<li><a href=\"../blog/\"><span>Blog</span></a></li>",
"<li><a href=\"../\"><span>Home</span></a></li>\n<li><a href=\"../blog/\"><span>Blog</span></a></li>");
fast_aleck_test(&test_case,
"<li><span>line one</span></li>\n<li><span>line two</span></li>",
"<li><span>line one</span></li>\n<li><span>line two</span></li>");
fast_aleck_test(&test_case,
"<h1><a href='#'>why won't this widon't</a></h1>",
"<h1><a href='#'>why won’t this widon’t</a></h1>");
fast_aleck_test(&test_case,
"<p>foo bar<br>baz qux</p>",
"<p>foo bar<br>baz qux</p>");
fast_aleck_test(&test_case,
"<p>one<br>\ntwo</p>",
"<p>one<br>\ntwo</p>");
fast_aleck_test(&test_case,
"<p>foo bar\n<br>\nbaz</p>",
"<p>foo bar\n<br>\nbaz</p>");
fast_aleck_test(&test_case,
"<p>foo bar </p>",
"<p>foo bar </p>");
fast_aleck_test(&test_case,
"<p>foo bar</p>",
"<p>foo bar</p>");
fast_aleck_test(&test_case,
"<p> foo</p>",
"<p> foo</p>");
fast_aleck_test(&test_case,
"<p>foo &</p>",
"<p>foo &</p>");
fast_aleck_test(&test_case,
"<p>foo & bar</p>",
"<p>foo & bar</p>");
test_case.widont = 0;
fast_aleck_test(&test_case,
"<dt>We don't Widon't.</dt>",
"<dt>We don’t Widon’t.</dt>");
// WRAP CAPS TEST
test_case.wrap_caps = 1;
fast_aleck_test(&test_case,
"Hello, this is DENIS speaking!",
"Hello, this is <span class=\"caps\">DENIS</span> speaking!");
fast_aleck_test(&test_case,
"DENIS's pants.",
"<span class=\"caps\">DENIS</span>’s pants.");
fast_aleck_test(&test_case,
"I have 13 EC2 instances but no static AMIs.",
"I have 13 <span class=\"caps\">EC2</span> instances but no static <span class=\"caps\">AMI</span>s.");
fast_aleck_test(&test_case,
"<title>Hello, this is DENIS speaking!</title>",
"<title>Hello, this is DENIS speaking!</title>");
fast_aleck_test(&test_case,
"<p>MongoDB is better than PostgreSQL</p>",
"<p>Mongo<span class=\"caps\">DB</span> is better than Postgre<span class=\"caps\">SQL</span></p>");
fast_aleck_test(&test_case,
"<p>HTML entities! © © ↩</p>",
"<p><span class=\"caps\">HTML</span> entities! © © ↩</p>");
test_case.wrap_caps = 0;
fast_aleck_test(&test_case,
"Do NOT wrap caps if I don't ask to!",
"Do NOT wrap caps if I don’t ask to!");
return (test_case.fails > 0 ? 1 : 0);
}
static void _fa_puts_escaped(char *a_s)
{
for (char *s = a_s; *s; ++s)
{
if ('\n' == *s)
fputs("\\n", stdout);
else
fputc(*s, stdout);
}
fputc('\n', stdout);
}
void fast_aleck_test(struct fast_aleck_test_case *a_test_case, char *a_input, char *a_expected_output)
{
fast_aleck_config config;
fast_aleck_config_init(&config);
config.wrap_amps = a_test_case->wrap_amps;
config.wrap_caps = a_test_case->wrap_caps;
config.wrap_quotes = a_test_case->wrap_quotes;
config.widont = a_test_case->widont;
size_t out_len;
char *actual_output = fast_aleck(config, a_input, strlen(a_input), &out_len);
if (0 != strcmp(a_expected_output, actual_output))
{
++a_test_case->fails;
fprintf(stdout, "not ok %i ", a_test_case->count+1);
_fa_puts_escaped(a_input);
fprintf(stdout, " Expected: ");
_fa_puts_escaped(a_expected_output);
fprintf(stdout, " Actual: ");
_fa_puts_escaped(actual_output);
}
else if(strlen(actual_output) != out_len)
{
++a_test_case->fails;
fprintf(stdout, "not ok %i %s\n", a_test_case->count+1, a_input);
fprintf(stdout, " Length of returned string: %lu\n", strlen(actual_output));
fprintf(stdout, " Returned length of string: %lu\n", out_len);
}
else
{
++a_test_case->passes;
fprintf(stdout, "ok %i ", a_test_case->count+1);
_fa_puts_escaped(a_input);
}
++a_test_case->count;
free(actual_output);
}
|
C
|
#include <stdio.h>
int length(int x, int y){
if(x>=y) return x-y;
else return y-x;
}
int main(){
int a,b,c,d;
scanf("%d %d %d %d",&a,&b,&c,&d);
if(length(a,c) <= d) printf("Yes\n");
else if(length(a,b) <= d && length(b,c) <= d) printf("Yes\n");
else printf("No\n");
return 0;
}
|
C
|
/* Thomas Stoeckert
COP 3223H - Final Project
Verbs handles pretty much all user input. This file is used both by the "Player" and the "Editor"
As such, functions used exclusively by one will be called out in commments.
This file is mostly entered through handlePlayerVerb or handleEditorVerb, with those functions
then dealing out data and requests to the other verbs in the file. In some simple cases, such as
ending the game or quitting, it can be done without the other verbs files, but it's not common.
*/
#include "verbs.h"
#include "io.h"
#include "actions.h"
#include "wizards.h"
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
// Used by the Player mode.
// This function takes in a pointer to the game data, and then prompts the user for their commands
// The behavior after the user inputs their command varies from command to command, but it handles (safely)
// all logic regarding that, only stopping when the command has been fully fulfilled.
void handlePlayerVerb(struct world *gamedata){
char command;
int target, secondTarget; // target is used for pretty much any interactive verb. second is only used for combine.
struct doors currentRoomPaths; // When we're navigating rooms, we don't alter the doors. It's safer to use a copy.
struct items *currentRoomItems; // Items in a room will change, so we point back to the original.
printf("Enter a command: "); // This block right here is used quite a bit throughout the program.
scanf(" %c", &command); // Easy entry, easy formatting, then clearing the screen to help clean it all up.
command = tolower(command);
system("cls");
switch(command){
default:
// If the user has no idea what's going on, help them.
printf("Unknown Command: %c\n", command);
printPlayerHelp();
clearBuffer();
break;
case 'g':
// Go - the user is going somewhere. They point to the index of the door/path, then handleGoVerb attempts
// to traverse said path.
currentRoomPaths = getCurrentRoom(gamedata->worldRooms, gamedata->currentRoomId)->paths;
scanf("%d", &target);
target--; // Room & item indexes are 1-based when printed, but 0-based in code. Fixed here.
handleGoVerb(currentRoomPaths, gamedata->worldRooms, &gamedata->currentRoomId, target);
break;
case 'i':
// Inspect - the user is looking at something. They point to the index of an item in the room or world, then
// handleInspectVerb looks more into it.
currentRoomItems = &getCurrentRoom(gamedata->worldRooms, gamedata->currentRoomId)->inventory;
scanf("%d", &target);
target--;
handleInspectVerb((*currentRoomItems), gamedata->inventory, target);
break;
case 't':
// Take - the user attempts to take an item from the room and place it into their inventory. Handled by
// handleTakeVerb
currentRoomItems = &getCurrentRoom(gamedata->worldRooms, gamedata->currentRoomId)->inventory;
scanf("%d", &target);
target--;
handleTakeVerb(currentRoomItems, &gamedata->inventory, target);
break;
case 'u':
// Use - the user is attempting to use an item. Items have a few different behaviors, all laid out in
// actions.c. However, it is handleUserVerb's job to prepare everything for the action functions.
scanf("%d", &target);
target--;
clearBuffer();
handleUseVerb(gamedata, target);
break;
case 'c':
// Combine - the user is combining items together to make a new one. It's a simple crafting system, really.
// It's also the most powerful tool in the engine, story-wise. It lets you use one item on another,
// or make a puzzle solvable by putting parts together. It's done with both room and inventory items.
currentRoomItems = &getCurrentRoom(gamedata->worldRooms, gamedata->currentRoomId)->inventory;
scanf("%d %d", &target, &secondTarget);
target--;
secondTarget--;
handleCombineVerb(target, secondTarget, currentRoomItems, &gamedata->inventory, gamedata->recipes, gamedata->itemPrototypes);
break;
case 'q':
// Quit - very simple confirm/deny quit function.
clearBuffer();
handleQuitVerb(&gamedata->playing);
break;
}
}
// Simple function to organize all the printing for user help
void printPlayerHelp(void){
printf("------ Player Commands ------\n");
printf(" g <door index> - Go through the door you select\n");
printf(" i <item index> - inspect the item you select\n");
printf(" t <item index> - take an item from the world and put it in your inventory\n");
printf(" u <item index> - use an item from the world or your inventory\n");
printf(" c <item index> <item index> - combine two items into a result\n");
printf(" q - quits the game\n");
return;
}
// ---- Player function ---- //
// This function helps organize the logic regarding handling the go command
// This picks the path at the target, and updates the pointer to the value of the
// destination if it's a valid location
void handleGoVerb(struct doors paths, struct rooms worldRooms, int * currentIndex, int target){
struct ll_door *helper;
int destination;
if(paths.paths == NULL){
printf("No Paths found when goVerb was called.\n");
return;
}
helper = dFindDoorByIndex(paths.paths, target);
if(helper == NULL){
printf("Invalid Choice: %d\n", target);
return;
}
destination = helper->data.dest;
// This checks to see if the room destination is valid by checking to see if the room destination exists
if(rFindRoomByID(worldRooms.roomData, destination) == NULL){
printf("You attempt to go down this path, but it's blocked!\n");
return;
}
(*currentIndex) = destination;
return;
}
// ---- Player function ---- //
// This function finds the appropriate item from either the room or the bag and prints its
// description to the screen
void handleInspectVerb(struct items roomItems, struct items bagItems, int target){
struct item *targetItem;
int sumItems = roomItems.numItems + bagItems.numItems;
if(target >= sumItems || target < 0){
printf("Invalid Item Selection");
return;
}
if(target >= roomItems.numItems){
targetItem = &iFindItemByIndex(bagItems.itemData, target - roomItems.numItems)->data;
} else {
targetItem = &iFindItemByIndex(roomItems.itemData, target)->data;
}
printf("%s\n", targetItem->desc);
return;
}
// ---- Player function ---- //
// This function finds the appropriate item from the room, copies it to the user's inventory,
// and deletes the original. Basically cloning. Ethically iffy with living things.
void handleTakeVerb(struct items *roomItems, struct items *bagItems, int target){
struct item targetItem;
if(target >= roomItems->numItems || target < 0){
printf("Invalid Item Selection.\n");
return;
}
targetItem = iFindItemByIndex(roomItems->itemData, target)->data;
if(!targetItem.pickable) {
printf("You seem to be unable to pick up the %s.\n", targetItem.name);
return;
}
bagItems->itemData = iAppend(bagItems->itemData, targetItem);
bagItems->numItems++;
roomItems->itemData = iDeleteItemByIndex(roomItems->itemData, target);
roomItems->numItems--;
return;
}
// ---- Player function ---- //
// The 'Use' verb handles a ton of data related to using items. It's much simpler to pass it the game's data
// instead of a half dozen variables.
// What this function does is it attempts to 'use' an item the user selects from the world according to
// the defined action of the item
void handleUseVerb(struct world *gamedata, int target){
struct item *targetItem;
struct room *currentRoom = getCurrentRoom(gamedata->worldRooms, gamedata->currentRoomId);
int sumItems = currentRoom->inventory.numItems + gamedata->inventory.numItems;
if(target >= sumItems || target < 0){
printf("Invalid Item Selection.\n");
return;
}
if(target >= currentRoom->inventory.numItems){
targetItem = &iFindItemByIndex(gamedata->inventory.itemData, target - currentRoom->inventory.numItems)->data;
} else {
targetItem = &iFindItemByIndex(currentRoom->inventory.itemData, target)->data;
}
handleAction(targetItem, gamedata, target);
return;
}
// ---- Player function ---- //
// This function takes in two targets, all the items the user can interact with, and the combinations in the world
// These are then used to see if the user can make a combo with these two items (after validating their existence)
// and then the result is placed in the right location.
void handleCombineVerb(int target, int secondTarget, struct items *roomItems, struct items *bagItems, struct combos recipes, struct items protos){
int target1ID, target2ID, resultID;
int target1InBag, target2InBag;
int sumItems = roomItems->numItems + bagItems->numItems;
struct combo *foundCombo;
struct item resultItem;
// Checking to see if the user has made a valid combination choice
// Fist step of that - checking the item ranges
int firstInvalid = 0, secondInvalid = 0;
firstInvalid = (target > sumItems || target < 0);
secondInvalid = (secondTarget > sumItems || target < 0);
// Both items must be valid
if(firstInvalid || secondInvalid){
printf("Invalid items selection.\n");
return;
}
// Second step of validation - checking if the user tried to add it to itself
if(target == secondTarget){
printf("You can't combine an item with itself!\n");
return;
}
// Next part of combining an item is checking the origin of the two targets
// We want to intelligently remove and add items despite their source - this helps us do that
// Checking for the first item's location, and getting the ID of the item while we're at it
if(target >= roomItems->numItems){
// The first item is in the user's bag
target1InBag = 1;
target1ID = iFindItemByIndex(bagItems->itemData, target - roomItems->numItems)->data.id;
} else {
target1InBag = 0;
target1ID = iFindItemByIndex(roomItems->itemData, target)->data.id;
}
if(secondTarget >= roomItems->numItems){
target2InBag = 1;
target2ID = iFindItemByIndex(bagItems->itemData, secondTarget - roomItems->numItems)->data.id;
} else {
target2InBag = 0;
target2ID = iFindItemByIndex(roomItems->itemData, secondTarget)->data.id;
}
// Combinations store their data as IDs - we needed to convert our indexes to the item IDs before we passed it over
foundCombo = findCombo(recipes, target1ID, target2ID);
// findCombo returns null if there's no associated recipe
if(foundCombo == NULL){
printf("These two items don't seem to combine...\n");
return;
}
// Getting our result information
resultID = foundCombo->resultID;
resultItem = iFindItemByID(protos.itemData, resultID)->data;
// Informing the user...
printf("%s\n", foundCombo->desc);
// If both of the source items were in the user's bag, we put the result in the user's bag
if(target1InBag && target2InBag){
bagItems->itemData = iAppend(bagItems->itemData, resultItem);
bagItems->numItems++;
} else {
// Otherwise, the result goes in the room
roomItems->itemData = iAppend(roomItems->itemData, resultItem);
roomItems->numItems++;
}
//Now we need to remove the source items according to their sources
if(target1InBag){
bagItems->itemData = iDeleteItemByID(bagItems->itemData, target1ID);
bagItems->numItems--;
} else {
roomItems->itemData = iDeleteItemByID(roomItems->itemData, target1ID);
roomItems->numItems--;
}
if(target2InBag){
bagItems->itemData = iDeleteItemByID(bagItems->itemData, target2ID);
bagItems->numItems--;
} else {
roomItems->itemData = iDeleteItemByID(roomItems->itemData, target2ID);
roomItems->numItems--;
}
return;
}
// ---- Player & Editor function ---- //
// Very simple function. Just a double-check to see if the user is doing what they really want.
void handleQuitVerb(int *playing){
char choice;
printf("Are you sure you want to quit? (y/n) ");
scanf(" %c", &choice);
choice = tolower(choice);
clearBuffer();
if(choice == 'y'){
// ONLY end if the user is certain.
(*playing) = 0;
}
return;
}
// ---- Editor Function ---- //
// This function is the same as the player function, but it deals with multiple modes
// if the editor is in a different mode than the base mode, it shunts its responsibilities off
// to them instead.
void handleEditorVerb(struct world *gamedata){
char mode = gamedata->mode;
char *filename;
char *tempText;
char command, choice;
printf("Enter a command: "); // Well aren't you familiar
command = tolower(getchar());
system("cls");
// Again, if the user is in one of these modes we need to send their data to them instead
switch(mode){
case 'r':
handleRoomEditorVerb(command, gamedata);
return;
case 'd':
handleDoorEditorVerb(command, gamedata);
return;
case 'i':
handleItemEditorVerb(command, gamedata);
return;
case 'c':
handleComboEditorVerb(command, gamedata);
return;
}
// At this point, we know we're in the main menu. We can now parse verbs as normal
switch(command){
// Here through 'c' are just verbs to enter other modes
case 'r':
printf("Entering Room Mode...\n");
gamedata->mode = 'r';
clearBuffer();
return;
case 'd':
printf("Entering Door Mode...\n");
gamedata->mode = 'd';
clearBuffer();
return;
case 'i':
printf("Entering Item Mode...\n");
gamedata->mode = 'i';
clearBuffer();
return;
case 'c':
printf("Entering Combo mode...\n");
gamedata->mode = 'c';
clearBuffer();
return;
// Asks for filename, validates input, then saves it with io.h's saveWorldToFile
case 's':
clearBuffer();
printf("Saving file...\n");
// getValidatedUserString prompts the users with the string you pass, then loops until they agree with
// their selection. It's very serious and will not let up, ever. We always get a string back
filename = getValidatedUserString("What would you like the files name to be?\n");
FILE * ofp = fopen(filename, "w");
saveWorldToFile(ofp, (*gamedata));
// Release memory back into the wild
fclose(ofp);
free(filename);
printf("File saved.\n");
return;
// Alter the text of the world - basically just the intro text. We do validate it, but it's akin to a wizard
// as seen in wizards.h
// (this was a very last-minute add)
case 't':
// We're altering the intro text for the world file
clearBuffer();
system("cls");
printf("The current intro text is: \n\t%s\n", gamedata->introMessage);
printf("Enter new intro text to replace it:\n");
tempText = getLine(stdin);
if(tempText[0] == '\0'){
smartStringCopy(&tempText, gamedata->introMessage);
}
printf("\nYour new intro text is: \n\t%s\n", tempText);
printf("Do you want to keep it (y/n) ");
scanf(" %c", &choice);
choice = tolower(choice);
clearBuffer();
if(choice == 'y'){
smartStringCopy(&gamedata->introMessage, tempText);
}
return;
// Exactly the same as the playerVerb
case 'q':
clearBuffer();
handleQuitVerb(&gamedata->playing);
return;
// This one's at the bottom for some reason
default:
clearBuffer();
printEditorHelp(mode, command);
return;
}
}
// ---- Editor Function ---- //
// This function takes in the mode and command, then informs the user all possible
// commands used in the specific mode that they are in.
void printEditorHelp(char mode, char command){
printf("Unknown Command: %c\n", command);
printf("---------- Commands for mode %c --------\n", mode);
switch(mode){
case 'r':
// Room edit mode
printf(" c - create a new room\n");
printf(" e <room id> - edit an existing room\n");
printf(" d <room id> - delete an existing room\n");
printf(" j <room id> - jump to another room\n");
printf(" q - quit the current mode and go back to the main mode.\n");
break;
case 'd':
// Door Edit mode
printf(" c - create a new door\n");
printf(" e <door index> - edit an existing door\n");
printf(" d <door index> - delete an existing door\n");
printf(" q - quit the current mode and go back to the main mode.\n");
break;
case 'i':
// Item edit mode
printf(" c - create a new item\n");
printf(" e <item id> - edit an existing item\n");
printf(" d <item id> - delete an existing item\n");
printf(" p <item id> - place an item into the current room\n");
printf(" r <item id> - remove an item from the current room\n");
printf(" q - quit the current mode and go back to the main mode.\n");
break;
case 'c':
// Combo Edit mode
printf(" c - create new combo\n");
printf(" e <combo index> - edit an existing combo\n");
printf(" d <combo index> - delete existing combo\n");
printf(" q - quit the current mode and return to the main mode.\n");
break;
default:
// Main menu
printf(" r - enter room mode\n");
printf(" d - enter door mode\n");
printf(" i - enter item mode\n");
printf(" c - enter combination mode\n");
printf(" t - edit the welcome message\n");
printf(" s - save the current world\n");
printf(" q - quit the editor\n");
break;
}
}
// ---- Editor Function ---- //
// This function handles all the behavior of editing rooms. Most of the actual editing responsibilities
// lie upon wizards.h, but this is done to organize it and present it to the user.
void handleRoomEditorVerb(char command, struct world *gamedata){
struct ll_room *targetRoom;
struct room newRoom;
char confirm;
int target;
switch(command){
case 'c':
clearBuffer();
// User is creating a new room. Send them to the room wizard.
newRoom = createRoomWizard(gamedata->worldRooms.nextID);
if(newRoom.id == -1){
// User ultimately didn't create a room
return;
}
gamedata->worldRooms.roomData = rAppend(gamedata->worldRooms.roomData, newRoom);
gamedata->worldRooms.numRooms++;
gamedata->worldRooms.nextID++;
return;
case 'e':
// Edit the room with the target ID
scanf("%d", &target);
clearBuffer();
targetRoom = rFindRoomByID(gamedata->worldRooms.roomData, target);
if(targetRoom == NULL){
printf("Room with id %d not found.\n", target);
return;
}
editRoomWizard(&targetRoom->data);
return;
case 'd':
// Delete the room with the target ID
scanf("%d", &target);
clearBuffer();
if(gamedata->worldRooms.numRooms <= 1){
printf("You cannot delete the only room in the world.\n");
return;
}
targetRoom = rFindRoomByID(gamedata->worldRooms.roomData, target);
if(targetRoom == NULL){
printf("Room with id %d not found.\n", target);
return;
}
printf("You want to delete room %s with id %d. This cannot be undone.\n Are you sure (y/n)?\n", targetRoom->data.name, targetRoom->data.id);
confirm = tolower(getchar());
clearBuffer();
if(confirm == 'y'){
gamedata->worldRooms.roomData = rDeleteRoomByID(gamedata->worldRooms.roomData, target);
gamedata->worldRooms.numRooms--;
printf("The room was deleted.\n");
}
return;
case 'j':
// This is unique to the room edit mode, since we can now jump to rooms without doors
// User is jumping to another room
scanf("%d", &target);
clearBuffer();
targetRoom = rFindRoomByID(gamedata->worldRooms.roomData, target);
if(targetRoom == NULL){
printf("Room with id %d not found.\n", target);
return;
}
gamedata->currentRoomId = target;
printf("%d", gamedata->currentRoomId);
return;
case 'q':
// Quitting these modes is less important than the player or main editor mode, so we don't verify here
gamedata->mode = 'm';
clearBuffer();
return;
default:
clearBuffer();
printEditorHelp(gamedata->mode, command);
return;
}
}
// ---- Editor function ---- //
// Handles the commands related to door editing
void handleDoorEditorVerb(char command, struct world *gamedata){
struct ll_door *targetdoor;
struct room *currentRoom;
struct door newDoor;
int target;
char confirm;
currentRoom = getCurrentRoom(gamedata->worldRooms, gamedata->currentRoomId);
switch(command){
default:
clearBuffer();
printEditorHelp(gamedata->mode, command);
return;
case 'c':
clearBuffer();
// User is creating a new door/path
newDoor = createDoorWizard();
if(newDoor.dest == DOOR_INVALID_FLAG){
// User ultimately didn't want to make a door
return;
}
currentRoom->paths.paths = dAppend(currentRoom->paths.paths, newDoor);
currentRoom->paths.numDoors++;
return;
case 'e':
scanf("%d", &target);
clearBuffer();
// User is editing an existing door/path
targetdoor = dFindDoorByIndex(currentRoom->paths.paths, target);
if(targetdoor == NULL){
printf("Invalid door selection.\n");
return;
}
editDoorWizard(&targetdoor->data);
return;
case 'd':
// Establish the door we're looking for
scanf("%d", &target);
targetdoor = dFindDoorByIndex(currentRoom->paths.paths, target);
if(targetdoor == NULL){
printf("Invalid door selection.\n");
return;
}
printf("You want to delete the door to dest %d with path \"%s\". Are you certain? This cannot be undone. (y/n) \n", targetdoor->data.dest, targetdoor->data.path);
// For some reason the tolower(getchar()) pattern I've used on other editors didn't work here. This one did.
// Odd.
scanf(" %c", &confirm);
confirm = tolower(confirm);
clearBuffer();
if(confirm == 'y'){
currentRoom->paths.paths = dDeleteDoorByIndex(currentRoom->paths.paths, target);
currentRoom->paths.numDoors--;
printf("The path was deleted.\n");
} else {
printf("Confirm was not y");
}
return;
case 'q':
gamedata->mode = 'm';
clearBuffer();
return;
}
}
// ---- Editor function ---- //
// Pretty much the same thing but with ITEMS WOO
void handleItemEditorVerb(char command, struct world* gamedata){
struct ll_item *targetItem;
struct room *currentRoom;
struct item newItem;
int target;
char choice;
currentRoom = getCurrentRoom(gamedata->worldRooms, gamedata->currentRoomId);
switch(command){
default:
clearBuffer();
printEditorHelp(gamedata->mode, command);
return;
case 'c':
// User is creating a new item
clearBuffer();
newItem = createItemWizard(gamedata->itemPrototypes.nextID);
if(newItem.id == -1){
// User didn't want to keep the item they created. Discard it.
printf("User has discarded the item");
return;
}
gamedata->itemPrototypes.itemData = iAppend(gamedata->itemPrototypes.itemData, newItem);
gamedata->itemPrototypes.numItems++;
gamedata->itemPrototypes.nextID++;
return;
case 'e':
// User is editing an existing item prototype
scanf("%d", &target);
clearBuffer();
targetItem = iFindItemByID(gamedata->itemPrototypes.itemData, target);
if(targetItem == NULL){
printf("Invalid item ID\n");
return;
}
editItemWizard(&targetItem->data);
return;
case 'd':
// Delete an existing item prototype
scanf("%d", &target);
clearBuffer();
targetItem = iFindItemByID(gamedata->itemPrototypes.itemData, target);
if(targetItem == NULL){
printf("Invalid item ID\n");
return;
}
printf("You want to delete the item %s with id %d. Are you sure? Do note that the item prototypes placed already will not be deleted from the world until you save and load the file again. It may cause issues with combinations and other items actions. (y/n): ",
targetItem->data.name, targetItem->data.id);
scanf(" %c", &choice);
choice = tolower(choice);
if(choice == 'y'){
gamedata->itemPrototypes.itemData = iDeleteItemByID(gamedata->itemPrototypes.itemData, target);
gamedata->itemPrototypes.numItems--;
}
return;
case 'p':
// Place a copy of an item prototype into the current room
// NOTE: Changes made to an item prototype will not propagate to its clones until the file is saved and
// opened again. It's a bit odd, but it's a one-week game engine.
scanf("%d", &target);
clearBuffer();
targetItem = iFindItemByID(gamedata->itemPrototypes.itemData, target);
if(targetItem == NULL){
printf("Invalid item ID\n");
return;
}
currentRoom->inventory.itemData = iAppend(currentRoom->inventory.itemData, targetItem->data);
currentRoom->inventory.numItems++;
return;
case 'r':
// Remove a copy of an item from the current room
scanf("%d", &target);
clearBuffer();
targetItem = iFindItemByID(currentRoom->inventory.itemData, target);
if(targetItem == NULL){
printf("Invalid item ID\n");
return;
}
currentRoom->inventory.itemData = iDeleteItemByID(currentRoom->inventory.itemData, target);
currentRoom->inventory.numItems--;
return;
case 'q':
gamedata->mode = 'm';
clearBuffer();
return;
}
}
// ---- Editor function ---- //
// Simplest of all modes for editing
void handleComboEditorVerb(char command, struct world *gamedata){
struct ll_combo *targetCombo;
struct combo newCombo;
int target;
switch(command){
case 'c':
// User is creating a new combo
newCombo = createComboWizard();
if(newCombo.resultID == -1){
// User abandoned the combo. Do nothing
return;
}
gamedata->recipes.data = cAppend(gamedata->recipes.data, newCombo);
gamedata->recipes.numCombos++;
break;
case 'e':
// User is editing an existing combo
scanf("%d", &target);
clearBuffer();
targetCombo = cFindComboByIndex(gamedata->recipes.data, target);
if(targetCombo == NULL){
printf("Invalid combination index.\n");
return;
}
editComboWizard(&targetCombo->data);
break;;
case 'd':
// User is deleting an existing combo
scanf("%d", &target);
clearBuffer();
targetCombo = cFindComboByIndex(gamedata->recipes.data, target);
if(targetCombo == NULL){
printf("Invalid combination index.\n");
return;
}
gamedata->recipes.data = cDeleteComboByIndex(gamedata->recipes.data, target);
gamedata->recipes.numCombos--;
break;
case 'q':
gamedata->mode = 'm';
clearBuffer();
break;
}
}
|
C
|
#include <stdio.h>
int main()
{
char g; // m or f
int age;
float height;
float weight;
float BMI = 0;
printf("input your age\n");
scanf("%d", &age);
printf("what's your gender? m or M for Male, f or F for female\n");
scanf(" %c", &g);
printf("what's your weight in kg?\n");
scanf("%f", &weight);
printf("what's your height in cm?\n");
scanf("%f", &height);
if ((weight > 0) && (height > 0) && (age > 0))
{
if ((g == 'f') || (g == 'F'))
{
printf("you're %d years old, your gender is female, your weight is %.2fkg, and you're height is %.2fcm.", age, weight, height);
height = height / 100;
BMI = (weight / (height * height)) * 0.9 + 8.0;
printf("your BMI is %.2f", BMI);
}
else if (g == 'm' || g == 'M')
{
printf("you're %d years old, your gender is male, your weight is %.2fkg, and you're height is %.2fcm.", age, weight, height);
height = height / 100;
BMI = weight / (height * height);
printf("your BMI is %.2f", BMI);
}
else
{
printf("type the gender again");
}
}
else
{
printf("check the numbers and the gender again.");
}
return 0;
}
|
C
|
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <stddef.h>
#define ALPHAB 26
void print_words_alphabetically(char ***alphabetical_array)
{
int row, col;
/*for loop to print words from alphabetical_array*/
for (row = 0; row < ALPHAB; row++) {
col = 0;
/*using ASCII value of 'A' and value of row to print letters in ascending order*/
printf("'%c'\n", row + 'A');
/*printing each string in the row of the 3d array*/
while (alphabetical_array[row][col] != NULL) {
printf("%s\n", alphabetical_array[row][col]);
col++;
}
/*checking if there are no words associated with the respective letter*/
if (col == 0) {
printf("There are no words that begin with the letter '%c'\n", row + 'A');
}
printf("\n");
}
}
|
C
|
#include "common.h"
int main(int argc, char * argv[])
{
char *fname;
byte buf[MAX_RX_LINE];
byte ackBuf[RXTX_BUFFER_SIZE];
struct sockaddr_in sin;
int len, dataLen, receiverSeqnum, firstSeqnum;
int s, i;
struct timeval tv;
char seq_num = 1;
FILE *fp;
struct Packet ackPkt;
struct Packet rxPkt;
if (argc==2) {
fname = argv[1];
}
else {
fprintf(stderr, "usage: ./server_udp filename\n");
exit(1);
}
/* build address data structure */
bzero((char *)&sin, sizeof(sin));
sin.sin_family = AF_INET;
sin.sin_addr.s_addr = INADDR_ANY;
sin.sin_port = htons(SERVER_PORT);
/* setup passive open */
if ((s = socket(PF_INET, SOCK_DGRAM, 0)) < 0) {
perror(": socket");
exit(1);
}
if ((bind(s, (struct sockaddr *)&sin, sizeof(sin))) < 0) {
perror(": bind");
exit(1);
}
socklen_t sock_len = sizeof sin;
srandom(time(NULL));
fp = fopen(fname, "w");
if (fp==NULL){
printf("Can't open file\n");
exit(1);
}
printf("sizeof struct Packet: %d\\n\r",(int)sizeof(struct Packet));
memset((void*)&ackPkt,0,sizeof(struct Packet));
memset((void*)&rxPkt,0,sizeof(struct Packet));
printf("Server up and awaiting packets at ANY interface on port %d\r\n",SERVER_PORT);
firstSeqnum = TRUE;
/*
Receiver just blocks, waiting for input to arrive.
If rx:
if rx length is 1 and == 0x02:
treat as end of transmission, and exit comm loop
else:
-deserialize packet from rx message
-write packet data to file
-send ACK to sender
-go back to wait for input
*/
while(1){
len = recvfrom(s, buf, sizeof(buf), 0, (struct sockaddr *)&sin, &sock_len);
printf("rxed pkt of len=%d\r\n",len);
if(len == -1){
perror("PError");
}
else if(len == 1){
if (buf[0] == 0x02){
printf("Transmission Complete\n");
break;
}
else{
perror("Error: Short packet??\n");
}
}
else if(len > 1){
//for local debugging: randomly fail to acknowledge ~1/3 of packets to test client recovery from missing acks
if(DBG && !(random() % 3 == 0)){
printf("Server dropped packet...");
}
else{
//deserialize the received packet
deserializePacket(buf,&rxPkt);
//seqnum is part of the receiver's state, and must be initialized in alignment with the sender; this bootstraps it on the first received packet.
//Subsequent packets are aligned with this seqnum, rejecting dupes that are re-sent if the receiver ACK packet is dropped.
if(firstSeqnum){
firstSeqnum = FALSE;
//careful here: we write data to file based on a new seqnum; so don't initialize seqnum to rxPkt.seqnum, or the first line will not be written
receiverSeqnum = (bytesToLint(rxPkt.seqnum) + 1) % 2;
}
printf("Receiver RXED client packet, seqnum=%d: >%s<\r\n",bytesToLint(rxPkt.seqnum),rxPkt.data);
printPacket(&rxPkt);
//send ACK for every packet received
//remember even the ACK could be dropped; hence sender needs to implement a timeout while waiting for ACK
makePacket(bytesToLint(rxPkt.seqnum), ACK, 0, &ackPkt);
serializePacket(&ackPkt,ackBuf);
sendPacket(&ackPkt,s,&sin);
//if this is a new packet, copy the packet data to file (making sure to null terminate it)
if(receiverSeqnum != bytesToLint(rxPkt.seqnum)){
//receiverSeqnum = bytesToLint(rxPkt.seqnum);
dataLen = bytesToLint(rxPkt.dataLen);
dataLen = dataLen < PKT_DATA_MAX_LEN ? dataLen : (PKT_DATA_MAX_LEN - 1);
rxPkt.data[dataLen] = '\0';
printf("Receiver rx'ed data: %s\r\n",(char*)rxPkt.data);
if(fputs((char *)rxPkt.data, fp) < 1){
printf("fputs() error\n");
}
//update the seqnum; for the alternating bit protocol, the seqnum just alternates between 0 and 1
receiverSeqnum = (receiverSeqnum + 1) % 2;
}
else{
printf("Sender dupe received with pkt.seqnum==%d receiver.seqnum=%d\r\n",bytesToLint(rxPkt.seqnum),receiverSeqnum);
}
}
}
}
fclose(fp);
close(s);
}
|
C
|
#include <stdlib.h>
#include <stdio.h>
#include "queue.h"
int main(){
struct Queue* queue = new_queue();
add(queue,1);
add(queue,2);
add(queue,3);
while(!isEmpity(queue))
printf("%d\n",getFirst(queue));
return 0;
}
|
C
|
// Peter Christakos
// Andrew Morrison
#include <sys/syscall.h>
#include <sys/wait.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
struct ancestry {
pid_t ancestors[10];
pid_t siblings[100];
pid_t children[100];
};
#define __NR_cs3013_syscall2 378
int main() {
pid_t pid1, pid2, pid3; //process ID
int c = 0;
int s = 0;
int a = 0; // counter variables for each member in ancestry
struct ancestry *tree = malloc(sizeof(struct ancestry));
printf("~~~~~~~~~~KERNEL INTERCEPTION TEST~~~~~~~~~~\n");
if ((pid1 = fork()) < 0) //-1 == fork error
{
perror("~~~Fork Failed~~~\n");
}
else if (pid1 == 0) // sleep and exit if child
{
sleep(10);
exit(0);
}
else
{
printf("First PID: %d\n", (int) pid1);
if ((pid2 = fork()) < 0) //-1 == fork error
{
perror("~~~Fork Failed~~~\n");
}
else if (pid2 == 0)
{
sleep (10);
exit(0);
}
else
{
printf("Second PID %d\n", (int) pid2);
if ((pid3 = fork()) < 0) //-1 == fork error
{
perror("~~~Fork Failed~~~\n");
}
else if (pid3 == 0)
{
sleep (10);
exit(0);
}
else
{
printf("Third PID %d\n\n", (int) pid3);
int ref = syscall(__NR_cs3013_syscall2, &pid2, tree);
if (ref)
{
perror("SysCall Failed\n");
return -1;
}
else
{
printf("Target PID: %d\n\n", (int) pid2);
printf("~~~~~Children~~~~~\n");
while(1)
{
if (tree->children[c] < 1)
{
break;
}
else
{
printf("Child [%d] PID: %d\n", (c+1), (int) tree->children[c]);
c++;
}
}
printf("\n~~~~~Siblings~~~~~\n");
while(1)
{
if (tree->siblings[s] < 1) //if no pid
{
break;
}
else
{
printf("Sibling [%d] PID: %d\n", (s+1), (int) tree->siblings[s]);
s++;
}
}
printf("\n~~~~~Ancestors~~~~~\n");
while(1)
{
if (tree->ancestors[a] < 1) { // if no pid
break;
}
else
{
printf("Parent [%d] PID: %d\n", (a+1), (int) tree->ancestors[a]);
a++;
}
}
}
}
}
}
return 0;
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_treat_s_tools.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: kabourad <kabourad@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2020/02/02 13:06:28 by kabourad #+# #+# */
/* Updated: 2020/03/06 20:23:08 by kabourad ### ########.fr */
/* */
/* ************************************************************************** */
#include "ft_printf.h"
void check_flags_s(t_options *tab)
{
if ((*tab).flag_zero == 1 && (*tab).flag_left == 1)
(*tab).flag_zero = 0;
if ((*tab).width < 0)
{
(*tab).flag_left = 1;
(*tab).width = (*tab).width * -1;
}
}
void modify_pr_s(t_options *tab, char *c)
{
if ((*tab).precision > 0 && (*tab).precision < (int)ft_strlen(c))
(*tab).precision = (*tab).precision;
else if ((*tab).precision == 0)
(*tab).precision = 0;
else
(*tab).precision = ft_strlen(c);
}
void modify_wd_s(t_options *tab)
{
if ((*tab).width && (*tab).width > (*tab).precision)
(*tab).width = (*tab).width - (*tab).precision;
else
(*tab).width = 0;
}
int print_only_s(char *c, int b)
{
int y;
int i;
int count;
y = 0;
i = 0;
count = 0;
while (c[y] && i < b)
{
count += ft_putchar_ret(c[y]);
y++;
i++;
}
return (count);
}
|
C
|
void wait(){
cin.ignore();
cout<<"PRESIONE ENTER PARA CONTINUAR";
cin.get();
}
void longitudMaxima(int id,string titulo,int dato1,string dato2){
if(to_string(id).size()>lId){
lId=to_string(id).size();
}
if(titulo.size()>lTitulo){
lTitulo=titulo.size();
}
if(to_string(dato1).size()>lDato1){
lDato1=to_string(dato1).size();
}
if(dato2.size()>lDato2){
lDato2=dato2.size();
}
}
string mult(string caracter,int cant){
string linea="";
for(int i=0;i<cant;i++){
linea=linea+caracter;
}
return linea;
}
void formatoTabla1(string contenido[]){
int s1=(lId-(contenido[0].size()));
int s2=(lTitulo-(contenido[1].size()));
int s3=(lDato1-(contenido[2].size()));
int s4=(lDato2-(contenido[3].size()));
cout<<"█ "<<contenido[0]+mult(" ",s1)<<" ";
cout<<"█ "<<contenido[1]+mult(" ",s2)<<" ";
cout<<"█ "<<contenido[2]+mult(" ",s3)<<" ";
cout<<"█ "<<contenido[3]+mult(" ",s4)<<" █"<<endl;
}
|
C
|
//
// pellet.c
// swim_mill
//
// Created by Michael Handria on 10/29/16.
// Copyright © 2016 Michael Handria. All rights reserved.
//
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <string.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <unistd.h>
#include <signal.h>
#include <time.h>
#define Size 210
#define wait 0
#define go 1
const key_t key = 9456;
int shmid;
int sleeping;
char (*pool)[11][10];
void *child(int *location);
void killProcess();
void endProcess();
FILE *fp;
//pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
int main(int argc, char *argv[]){
//CONNECT SHARED MEMORY
////////////////////////////////////////////////////
//connencts the shared memory id
//the starting point will be mem# 9886
//the size will be 100 bytes
//will have read and write access for all three
//users
if((shmid = shmget(key, Size, 0666))< 0){
perror("shmget");
exit(1);
}
if((pool = (char(*)[11][10])shmat(shmid, NULL, 0)) == (char(*)[11][10]) -1){
perror("shmat");
exit(1);
}
///////////////////////////////////////////////////////////
//SET UP SIGNALS
///////////////////////////////////////////////////////////
signal(SIGINT, killProcess);
//user defined signal (can be for any user)
signal(SIGUSR1, endProcess);
///////////////////////////////////////////////////////////
//SET UP RANDOM GENERATOR
///////////////////////////////////////////////////////////
time_t t;
/* Intializes random number generator */
srand((unsigned) time(&t));
////////////////////////////////////////////////////////////
fp = fopen("./log.txt", "a");
pthread_t pellet[14];
//int uid = 3;
//for(int i = 0; i < 6; i++){
/*int xaxis[2] = {0, 0};
int x1 = rand()%8;
int x2 = rand()%8;
if(x1 > x2){
*(xaxis) = x2;
*(xaxis+1) = x1;
}
else{
*(xaxis) = x1;
*(xaxis+1) = x2;
}*/
for(int i = 0; i < 15; i++){
//int xaxis = rand()%8;
int position[2] = {rand()%5, rand()%10};
//printf("location: %d, %d", *position, *(position+1));
//*pool[10][uid+i] = 1;
pthread_create(&pellet[i], NULL, child, position);
sleeping = (rand()%3)+1;
sleep(sleeping);
}
for(int i = 0; i < 15; i++){
pthread_join(pellet[i], NULL);
}
//}
}
void *child(int *location){
int r = *location;
int col = *(location+1);
fprintf(fp, "\nPellet created @ col: %d row: %d\n", col, r);
printf("\nPellet created @ col: %d row: %d\n", col, r);
for(int row = r; row <= 9; row++){
if(*pool[row+1][col] == 'F' || *pool[row][col+1] == 'F' || *pool[row][col-1] == 'F'){
*pool[row][col] = '.';
*pool[row+1][col] = 'F';
fprintf(fp, "\nPellet %d was EATEN at column %d!\n", pthread_self(), col);
printf("\nPellet %d was EATEN at column %d!\n", pthread_self(), col);
pthread_exit(0);
break;
}
else{
if(row+1 == 10){
*pool[row][col] = '.';
fprintf(fp, "\nPellet %d LEFT at column %d!\n", pthread_self(), col);
printf("\nPellet %d LEFT at column %d!\n", pthread_self(), col);
}
else{
*pool[row][col] = '.';
*pool[row+1][col] = 'o';
}
}
sleep(1);
}
pthread_exit(0);
}
void killProcess(){
shmdt(pool);
printf("\nInterrupt signal recieved PID: %d pellet killed\n", getpid());
fclose(fp);
exit(0);
}
void endProcess(){
shmdt(pool);
printf("\nTime limit reached PID: %d pellet killed\n", getpid());
fclose(fp);
exit(0);
}
|
C
|
//-----------------------------------------------------------------------------
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_CSTRING 128
typedef char CString[MAX_CSTRING];
typedef struct {
CString FamilyName;
CString GivenName;
} PersonType;
#define PRETTY_PRINT(This) printf("\n----------------\n%s\n----------------\n",(This))
//-----------------------------------------------------------------------------
void SetNames(CString NewFamilyName,CString NewGivenName,PersonType *APerson) {
strcpy(APerson->FamilyName,NewFamilyName);
strcpy(APerson->GivenName,NewGivenName);
}
//-----------------------------------------------------------------------------
void GetFullName(PersonType APerson,CString FullName) {
strcpy(FullName,APerson.GivenName);
strcat(FullName," ");
strcat(FullName,APerson.FamilyName);
}
//-----------------------------------------------------------------------------
int main(void) {
PersonType MyPerson;
CString InputFamilyName;
CString InputGivenName;
CString FullName;
CString OutputLine;
printf("Please enter the given name and family name : ");
scanf(" %s %s",InputGivenName,InputFamilyName);
SetNames(InputFamilyName,InputGivenName,&MyPerson);
GetFullName(MyPerson,FullName);
sprintf(OutputLine,"The full name is %s",FullName);
PRETTY_PRINT(OutputLine);
return(EXIT_SUCCESS);
}
//-----------------------------------------------------------------------------
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.