language
large_stringclasses 1
value | text
stringlengths 9
2.95M
|
|---|---|
C
|
#include "iic.h"
#if IIC_MODE
/*
: ʼIIC
Ӳ:
SCL---PB6
SDA---PB7
*/
void IIC_Init(void)
{
RCC->APB2ENR|=1<<3;
GPIOB->CRL&=0x00FFFFFF;
GPIOB->CRL|=0x33000000;
GPIOB->ODR|=0x3<<6;
}
/*
: ʼź
ʱΪߵƽʱɸߵƽΪ͵ƽĹ
*/
void IIC_SendStart(void)
{
IIC_OUTPUT_MODE(); //ģʽ
IIC_SCL=1;
IIC_SDA_OUT=1;
DelayUs(2);
IIC_SDA_OUT=0;
DelayUs(2);
IIC_SCL=0; //߿ʼʼд
}
/*
: ֹͣź
ʱΪߵƽʱɵ͵ƽΪߵƽĹ
*/
void IIC_SendStop(void)
{
IIC_OUTPUT_MODE(); //ģʽ
IIC_SCL=0;
IIC_SDA_OUT=0;
DelayUs(2);
IIC_SCL=1;
DelayUs(2);
IIC_SDA_OUT=1;
}
/*
: ȡӦź
ֵ: 0ʾȡӦ 1ʾûлȡӦ
*/
u8 IIC_GetAck(void)
{
u8 cnt;
IIC_INPUT_MODE();//ģʽ
IIC_SDA_OUT=1; //
IIC_SCL=0;
DelayUs(2);
IIC_SCL=1;
while(IIC_SDA_IN)
{
cnt++;
if(cnt>250)return 1; //ȡӦ
}
IIC_SCL=0;
return 0;
}
/*
: Ӧź
0ʾӦ 1ʾӦ
*/
void IIC_SendAck(u8 ack)
{
IIC_OUTPUT_MODE(); //ģʽ
IIC_SCL=0;
DelayUs(2);
if(ack)IIC_SDA_OUT=1; //ͷӦ
else IIC_SDA_OUT=0; //Ӧ
DelayUs(2);
IIC_SCL=1;
DelayUs(2);
IIC_SCL=0;
}
/*
: һֽ
*/
void IIC_SendOneByte(u8 data)
{
u8 i=0;
IIC_OUTPUT_MODE(); //ģʽ
for(i=0;i<8;i++)
{
IIC_SCL=0;
if(data&0x80)IIC_SDA_OUT=1;
else IIC_SDA_OUT=0;
DelayUs(2);
IIC_SCL=1;
DelayUs(2);
data<<=1;
}
IIC_SCL=0;
}
/*
: һֽ
*/
u8 IIC_RecvOneByte(void)
{
u8 i=0;
u8 data=0;
IIC_INPUT_MODE();
for(i=0;i<8;i++)
{
IIC_SCL=0;
DelayUs(2);
IIC_SCL=1;
data<<=1; //ʾĬյ0
if(IIC_SDA_IN)data|=0x01;
DelayUs(2);
}
IIC_SCL=0;
return data;
}
#else //Ӳʱ
/*
: ʼIIC
Ӳ:
SCL---PB6
SDA---PB7
*/
void IIC_Init(void)
{
/*1. ʱ*/
RCC->APB2ENR|=1<<3; //PB
/*2. GPIOģʽ*/
GPIOB->CRL&=0x00FFFFFF;
GPIOB->CRL|=0xFF000000; //ÿ©
GPIOB->ODR|=0x3<<6;
/*3. GPIOʱ(˳ܴ)*/
RCC->APB1ENR|=1<<21; //I2C1ʱ
RCC->APB1RSTR|=1<<21; //λʱ
RCC->APB1RSTR&=~(1<<21);//رոλʱ
/*4. IICĺļĴ*/
I2C1->CR2=0x24<<0; //ƵΪ36MHZ
I2C1->CCR|=0x2D<<0; //Ƶ400KHZ
I2C1->CR1|=1<<0; //IICģ
/*
CCR=ʱƵ/2/IICߵƵ
45=36MHZ/2/400KHZ ---0x2D
*/
}
/*
: ʼź
ʱΪߵƽʱɸߵƽΪ͵ƽĹ
*/
void IIC_SendStart(void)
{
I2C1->CR1|=1<<8; //ʼź
while(!(I2C1->SR1&1<<0)){} //ȴʼź
I2C1->SR1=0; //״̬λ
}
/*
: ֹͣź
ʱΪߵƽʱɵ͵ƽΪߵƽĹ
*/
void IIC_SendStop(void)
{
I2C1->CR1|=1<<9;
}
/*
: ͵ַ
*/
void IIC_SendAddr(u8 addr)
{
u32 s1,s2;
I2C1->DR=addr; //
while(1)
{
s1=I2C1->SR1;
s2=I2C1->SR2;
if(s1&1<<1) //жϵַûзͳɹ
{
break;
}
}
}
/*
:
*/
void IIC_SendOneByte(u8 addr)
{
u32 s1,s2;
I2C1->DR=addr; //
while(1)
{
s1=I2C1->SR1;
s2=I2C1->SR2;
if(s1&1<<2) //жûзͳɹ
{
break;
}
}
}
/*
: һֽ
*/
u8 IIC_RecvOneByte(void)
{
u8 data=0;
I2C1->CR1|=1<<10; //ʹӦ
while(!(I2C1->SR1&1<<6)){} //ȴ
data=I2C1->DR;
I2C1->CR1&=~(1<<10); //رӦʹ
return data;
}
#endif
|
C
|
#include <stdio.h>
#include <stdint.h>
uint8_t u8a, u8b;
uint16_t u16c, u16d;
uint32_t u32e, u32f;
int8_t s8;
int16_t s16;
int32_t s32;
int main(void){
u8a = sizeof(uint8_t);
u16c = sizeof(uint16_t);
u32e = sizeof(uint32_t);
printf("size of uint8_t: %d Byte.\n", u8a);
printf("size of uint16_t: %d Bytes.\n", u16c);
printf("size of uint32_t: %d Bytes.\n", u32e);
u8a = 0xa1U;
u16c = 0xc1c2U;
u32e = 0xe1e2e3e4U;
printf("\n##########################\n\n");
u8b = u8a;
u16d = u16c;
u32f = u32e;
printf("valor armazenado em uint8_t: %d \n", u8b);
printf("valor armazenado em uint16_t: %d \n", u16d);
printf("valor armazenado em uint32_t: %d \n", u32f);
return 0;
}
|
C
|
#include<stdio.h>
#pragma warning(disable:4996)
int main(void) {
double h, w, s_w;
printf("ü߰ Ű ԷϽÿ : ");
scanf("%lf %lf", &w, &h);
s_w = (h - 100) * 0.9;
if (w < s_w)
printf("ü Դϴ");
else if (w > s_w)
printf("ü Դϴ");
else
printf("ǥü Դϴ");
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
printf("Hello world!\n");
FILE *archivoALeer;
FILE *archivoAEscribir;
char caracterLeido;
int caracterASCII,contador=0,comparador=0,entroADecimal=0,entroAOctal=0,entroAHexa=0;
archivoALeer= fopen("DocALeer.txt","r+"); //abro el archivo
archivoAEscribir= fopen("docAescribir.txt","wb");
if (!archivoALeer) //me fijo si se pudo leer
{
printf("no se pudo abrir el archvio\n");
}
else
{
while (fread(&caracterLeido,sizeof(caracterLeido),1,archivoALeer)) // mientras pueda leer el archivo...
{
caracterASCII=caracterLeido;
if (caracterASCII>=49 && caracterASCII<=57) //me fijo si es decimal con numeros entre 1 y 9 en ascii
{
comparador=comparador+1;contador=contador+1;
entroADecimal=1;
while (fread(&caracterLeido,sizeof(caracterLeido),1,archivoALeer)&& caracterLeido!=',')
{
caracterASCII=caracterLeido;
comparador=comparador+1;
if (caracterASCII>=48 && caracterASCII<=57)
contador=contador+1;
}
} //salgo del if para los decimales cuando tengo una coma o se termina el archivo
else if (caracterASCII==48) //nada mas entro aca si no entre a decimal
{
if (fread(&caracterLeido,sizeof(caracterLeido),1,archivoALeer)&& caracterLeido!=',')
{
caracterASCII=caracterLeido;
if (caracterASCII>=48 && caracterASCII<=55) //si entra aca voy a estar hablando de un posible numero octal
{
comparador=comparador+1;contador=contador+1;
entroAOctal=1;
while (fread(&caracterLeido,sizeof(caracterLeido),1,archivoALeer)&& caracterLeido!=',')
{
caracterASCII=caracterLeido;
comparador=comparador+1;
if (caracterASCII>=48 && caracterASCII<=55)
contador=contador+1;
}
}
else if (caracterASCII==88 || caracterASCII==120)
{
comparador=comparador+1;contador=contador+1;
entroAHexa=1;
while (fread(&caracterLeido,sizeof(caracterLeido),1,archivoALeer)&& caracterLeido!=',')
{
caracterASCII=caracterLeido;
comparador=comparador+1;
if ((caracterASCII>=48 && caracterASCII<=57)|| (caracterASCII>=65 && caracterASCII<=70)|| (caracterASCII>=97 && caracterASCII<=102))
contador=contador+1;
}
}
}
}
if (contador==comparador && contador>=1)
{
if (entroADecimal==1)
fputs("Numero decimal,",archivoAEscribir);
else if (entroAOctal==1)
fputs("Numero octal,",archivoAEscribir);
else if (entroAHexa==1)
fputs("Numero hexa,",archivoAEscribir);
}
else
{
fputs("Palabra no reconocida,",archivoAEscribir);
if (caracterLeido!=',')
{
while (fread(&caracterLeido,sizeof(caracterLeido),1,archivoALeer)&& caracterLeido!=',')
{
}
}
}
contador=0;
comparador=0;
entroADecimal=0;
entroAHexa=0;
entroAOctal=0;
}
}
fclose(archivoALeer);
fclose(archivoAEscribir);
}
|
C
|
/*
** С
*/
#include "stdio.h"
#include "stdlib.h"
int main()
{
/*------*/
double sum = 100;
/*---ĸ߶---*/
double h = 100;
/*---ش---*/
int n = 0;
for (n = 2; n < 10; ++n)
{
sum += h * 2;
h /= 2;
}
printf("%f\n10ʱĸ߶Ϊ%f\n", sum, h);
system("pause");
return 0;
}
|
C
|
int main()
{
int a,b=3,c=5,d=7;
char n='n';
scanf("%d",&a);
if(a%3==0&&a%5==0&&a%7==0)
printf("%d %d %d",b,c,d);
if(a%3!=0&&a%5==0&&a%7==0)
printf("%d %d",c,d);
if(a%3==0&&a%5!=0&&a%7==0)
printf("%d %d",b,d);
if(a%3==0&&a%5==0&&a%7!=0)
printf("%d %d",b,c);
if(a%3!=0&&a%5!=0&&a%7==0)
printf("%d",d);
if(a%3!=0&&a%5==0&&a%7!=0)
printf("%d",c);
if(a%3==0&&a%5!=0&&a%7!=0)
printf("%d",b);
if(a%3!=0&&a%5!=0&&a%7!=0)
printf("%c",n);
return 0;
}
|
C
|
//Authors: Aaron Elliot, Justin Montes
//pa32
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>
#include <unistd.h>
#define KBLU "\x1B[34m"
#define KRED "\x1B[31m"
#define KRESET "\x1B[0m"
#define ERROR_OUT_OF_MEM 0x1
#define ERROR_DATA_INCON 0x2
#define ERROR_ALIGMENT 0x4
#define ERROR_NOT_FF 0x8
#define ALIGN 8
#define rdtsc(x) __asm__ __volatile__("rdtsc \n\t" : "=A" (*(x)))
/* Basic constants and macros */
#define WSIZE 4 /* Word and header/footer size (bytes) */
#define DSIZE 8 /* Doubleword size (bytes) */
#define CHUNKSIZE (1<<12) /* Extend heap by this amount (bytes) */
#define VHEAP
// Define baseptr and such
typedef char *addrs_t;
typedef void *any_t;
// Counters for heapcheck
int count_Vfree = 0;
int count_Vmalloc = 0;
int raw_bytes = 0;
int padded_bytes = 0;
int num_failures = 0;
int raw_free = 0;
int padded_free = 0;
// Part 1
// Linked list architecture for tracking
struct node{
// start of memory chunk
addrs_t start;
// end of memory chunk
addrs_t end;
// next node in linked list
struct node *next;
};
// (NC) node null constructor
void init_node_types_1(struct node* n){
n->start = NULL;
n->end = NULL;
n->next = NULL;
}
// (NC) node constructor for end of linked list
void init_node_types_2(struct node* n, addrs_t start, addrs_t end){
n->start = start;
n->end = end;
n->next = NULL;
}
// (NC) node constructor for middle of linked list
void init_node_types_3(struct node* n, addrs_t start, addrs_t end, struct node* nextNode){
n->start = start;
n->end = end;
n->next = nextNode;
}
// Init head of list
struct node * Head;
struct node * Tail;
size_t TOTALSIZE;
// Init func
void VInit (size_t size) { // heap alloc
addrs_t baseptr;
baseptr = (addrs_t) malloc (size);
Head = malloc(sizeof(struct node));
Tail = Head;
init_node_types_2(Head,baseptr, baseptr);
TOTALSIZE = size;
}
// VMalloc
addrs_t * VMalloc (size_t size) {
//get initial value before allignment
int initial_size = size;
size = (size+(0x8-size%0x8)%0x8);
if (TOTALSIZE+Head->end - Tail->end >= size){ // IF we reach the end of the linked list, THEN check if there is space
count_Vmalloc+= 1;
raw_bytes += size;
padded_bytes += initial_size;
struct node * new = malloc(sizeof(struct node));
init_node_types_2(new,Tail->end,Tail->end+size);
Tail->next = new;
Tail = new;
return &(new->start);
}
else{
printf("NoSpaceLeftError : no space left\n");
num_failures += 1;
return (NULL);
}
}
// VFree
void VFree (addrs_t *addr) {
struct node* current = Head;
struct node* temp = current->next;
while (temp!=NULL){
if (((char*)(&(temp->start))) == ((char*)(addr)) ){
count_Vfree++;
raw_free += (int)sizeof(temp)- (sizeof(temp->start)*2);
padded_free += (int)sizeof(temp);
current->next = temp->next;
if (temp->next==NULL){
Tail = current;
}
free(temp);
break;
}
current = temp;
temp = current->next;
}
temp = current->next;
while(temp != NULL){
size_t size = temp->end-temp->start;
memmove(current->end,temp->start,size);
temp -> start = current -> end;
temp -> end = temp->start + size;
current = temp;
temp = current->next;
}
num_failures++;
}
// VPut
addrs_t* VPut (any_t data, size_t size) {
addrs_t* rtnVal = VMalloc (size);
if (rtnVal!=NULL){
memmove(*rtnVal,data, size);
}
return rtnVal;
}
// VGet
void VGet (any_t return_data, addrs_t *addr, size_t size) {
memmove(return_data, *addr, size);
VFree(addr);
}
// Heap Checker
/*
Number of allocated blocks : XXXX
Number of free blocks : XXXX
Raw total number of bytes allocated : XXXX
Padded total number of bytes allocated : XXXX
Raw total number of bytes free : XXXX
Aligned total number of bytes free : XXXX (which is sizeof(M2) minus the padded total number of bytes allocated. You should account for meta-datastructures inside M2 also)
Total number of VMalloc requests : XXXX
Total number of VFree requests: XXXX
Total number of request failures: XXXX
Average clock cycles for a VMalloc request: XXXX
Average clock cycles for a VFree request: XXXX
Total clock cycles for all requests: XXXX
*/
// Heap Checker funtions based off testsuite
#ifdef VHEAP
#define TESTSUITE_STR "Virtualized Heap"
#define INIT(msize) VInit(msize)
#define MALLOC(msize) VMalloc(msize)
#define FREE(addr, size) VFree(addr)
#define PUT(data,size) VPut(data,size)
#define GET(rt,addr,size) VGet(rt,addr,size)
#define ADDRS addrs_t*
#define LOCATION_OF(addr) ((size_t)(*addr))
#define DATA_OF(addr) (*(*(addr)))
#else
#define TESTSUITE_STR "Heap"
#define INIT(msize) Init(msize)
#define MALLOC(msize) Malloc(msize)
#define FREE(addr,size) Free(addr)
#define PUT(data,size) Put(data,size)
#define GET(rt,addr,size) Get(rt,addr,size)
#define ADDRS addrs_t
#define LOCATION_OF(addr) ((size_t)addr)
#define DATA_OF(addr) (*(addr))
#endif
int test_stability(int numIterations, unsigned long* tot_alloc_time, unsigned long* tot_free_time){
int i, n, res = 0;
char s[80];
ADDRS addr1;
ADDRS addr2;
char data[80];
char data2[80];
unsigned long start, finish;
*tot_alloc_time = 0;
*tot_free_time = 0;
for (i = 0; i < numIterations; i++) {
rdtsc(&start);
addr1 = PUT(s, n+1);
rdtsc(&finish);
*tot_alloc_time += finish - start;
addr2 = PUT(s, n+1);
// Check for heap overflow
if (!addr1 || !addr2){
res |= ERROR_OUT_OF_MEM;
break;
}
// Check aligment
if (((uint64_t)addr1 & (ALIGN-1)) || ((uint64_t)addr2 & (ALIGN-1)))
res |= ERROR_ALIGMENT;
// Check for data consistency
rdtsc(&start);
GET((any_t)data2, addr2, n+1);
rdtsc(&finish);
*tot_free_time += finish - start;
if (!strcmp(data,data2))
res |= ERROR_DATA_INCON;
GET((any_t)data2, addr1, n+1);
if (!strcmp(data,data2))
res |= ERROR_DATA_INCON;
}
return res;
}
//main
int main (int argc, char **argv) {
int res;
unsigned long tot_alloc_time, tot_free_time;
int numIterations = 1000000;
unsigned mem_size = (1<<20); // Default
// Parse the arguments
if (argc > 2){
fprintf(stderr, "Usage: %s [buffer size in bytes]\n",argv[0]);
exit(1);
}else if (argc == 2){
mem_size = atoi(argv[1]);
}
// Initialize the heap
INIT(mem_size);
printf("Evaluating a %s of %d KBs...\n",TESTSUITE_STR,mem_size/1024);
test_stability(numIterations,&tot_alloc_time,&tot_free_time);
printf("Number of allocated blocks: %d\n",count_Vmalloc);
printf("Number of free blocks: %d\n",count_Vfree);
printf("Raw total number of bytes allocated: %d\n",raw_bytes);
printf("Padded total number of bytes allocated: %d\n",(padded_bytes));
printf("Raw total number of bytes free: %d\n",raw_free);
printf("Aligned total number of bytes free: %d\n",(mem_size-padded_bytes));
printf("Total number of Malloc requests :%d\n", count_Vmalloc);
printf("Total number of Free requests :%d\n", count_Vfree);
printf("Total number of request failures: %d\n",num_failures);
printf("Average clock cycles for a Malloc request: :%lu\n",tot_alloc_time/numIterations);
printf("Average clock cycles for a Free request: :%lu\n", tot_free_time/numIterations);
printf("Total clock cycles for all requests: %lu\n",(tot_alloc_time+tot_free_time));
printf("\n");
return 0;
}
|
C
|
#include <stdio.h>
int main()
{
char ak[1000][1000];
int a,y,x,count = 0,i = 0,j = 0;
while ((a = getchar()) != EOF){
if (a != '\n')
{ak[i][j] = a;
j++;
}
else
{
i++;
j = 0;
}
}
for (x = 0;x < i;x++)/*to enter each line*/
{ count = 0;
for (y = 0;ak[x][y] != '\0';y++) /* j is not given because it changes each line so to check every j, upto max should given*/
{
count++;
}
if(count > 10)
printf("%s\n",ak[x]);
}
}
|
C
|
#include<stdio.h>
void ssort(int a[],int n)
{ int i,j,position,temp;
for (i = 0; i < n-1; i++)
{ for ( j = i+1; j < n; j++)
{ position=i;
if(a[position]>a[j])
position=j;
temp=a[i];
a[i]=a[position];
a[position]=temp;
}
}
}
int main()
{ int a[100],n,i;
printf("ENTER SIZE OF AN ARRAY:");
scanf("%d",&n);
printf("ENTER ARREY ELEMENETS:");
for(i=0;i<n;i++)
{ printf("ENTER %d ELEMENT:",i);
scanf("\n%d",&a[i]);
}
ssort(a,n);
printf("SELECTION SORT ELEMENTS ARE:");
for(i=0;i<n;i++)
printf("%d\t",a[i]);
return 0;
}
|
C
|
#include<stdio.h>
#include<string.h>
#define M 10000007
int t,n,a[M],b[M],c[M],d[M],i,j;
int main()
{
scanf("%d",&t);
while(t--)
{
scanf("%d",&n);
b[0]=0;
for(i=1;i<=n;i++)
{
scanf("%d",&a[i]);
b[i]=b[i-1]+a[i];
b[i]=b[i]%n;
}
memset(c,0,sizeof(c));
memset(d,0,sizeof(d));
for(i=0;i<=n;i++)
{
if(c[b[i]]==0)
{
c[b[i]]=1;
d[b[i]]=i;
}
else
{
int x=d[b[i]];
printf("%d\n",i-x);
while(x+1<=i)
{
printf("%d",x+1);
if (x+1<i)
printf(" ");
x++;
}
printf("\n");
break;
}
}
}
return 0;
}
|
C
|
#include<stdio.h>
#include<stdlib.h>
void swap(int *x , int *y)
{
int temp=*x;
*x = *y;
*y = temp;
}
int partition(int a[] , int start , int end)
{
int pivot = a[start];
int i = start;
int j = end;
while(i < j)
{
while(a[i] <= pivot)
i++;
while(a[j] > pivot)
j--;
if(i < j)
swap(&a[i] , &a[j]);
}
swap(&a[start] , &a[j]);
return j;
}
/*
OTHER WAY OF PARTITIONING:
int partition(int a[] , int start , int end)
{
int pivot = a[end]; //selecting the pivot element
int pIndex = start; //initially partition-index will be at starting
for(int i=start ; i<end ; i++)
{
//if an element is lesser than pivot, swap it.
if(a[i] <= pivot)
{
swap(&a[i] , &a[pIndex]);
pIndex++; //incrementing pIndex for further swapping.
}
}
swap(&a[pIndex] , &a[end]); //lastly swapping or the correct position of pivot
return pIndex;
}
*/
void quick_sort(int a[] , int start , int end)
{
int pivot;
//we will not call quick_sort if there is only one element
if(start < end)
{
pivot = partition(a , start , end);
quick_sort(a , start , pivot-1);
quick_sort(a , pivot+1 , end);
}
}
int main()
{
int n,i,start,end;
printf("Enter number of elements of array : ");
scanf("%d" , &n);
int a[n];
printf("Enter elements of array :\n");
for(i=0 ; i<n ; i++)
scanf("%d" , &a[i]);
start = 0;
end = n-1;
quick_sort(a , start , end);
printf("\n\nSorted array is : \n");
for(i=0 ; i<n ; i++)
printf("%d " , a[i]);
return 0;
}
|
C
|
#include <string.h>
#include <stdlib.h>
#include "linkedList_users.h"
#include "linkedList_messages.h"
#include <stdio.h>
users_list_t *llu_init() {
//We allocate the momery required
users_list_t *list = (users_list_t *) malloc(sizeof(users_list_t));
if (list == NULL) {
return NULL;
}
//set the head as null and size 0 because is empty
list->head = NULL;
list->size = 0;
return list;
}
int llu_exist(users_list_t *list, char *username){
//First we check if there are elements in the list
if (list == NULL || list->head == NULL) {
return -1;
}
node_users_t *current = list->head;
//Then we iterate through the list until we find the username or we get to the end
while (strcmp(current->username, username) != 0) {
if (current->next == NULL) {
//If we get to this point the key we are looking for doesnt exists so it returns -1
return 0;
}
current = current->next;
}
//If we actually get to this point, the username is not in the list
return 1;
}
int llu_register(users_list_t *list, char *username){ /*Add new users at the end of the list*/
if (list->size == 0) {
node_users_t *head = (node_users_t *) malloc(sizeof(node_users_t));
if (head == NULL) {
return -1;
}
//Scenario list is empty
strcpy(head->username, username);
head->identifier=0;
messages_list_t* message_queue = llm_init();
head->pending_messages=message_queue;
head->next = NULL;
list->head = head;
list->size = 1;
return 0;
}
//we check if the username is already in the list
if (llu_exist(list, username) == 1) {
return -1;
}
node_users_t *current = list->head;
while (current->next != NULL) {
current = current->next;
}
/* now we can add a new variable */
current->next = (node_users_t *) malloc(sizeof(node_users_t));
strcpy(current->next->username, username);
current->next->identifier=0;
current->next->pending_messages=llm_init();
current->next->next = NULL;
list->size++;
return 0;
}
int llu_get_identifier(users_list_t *list, char *username, uint32_t *message_identifier){
//method that gets the identifier of a username
node_users_t *current = list->head;
while (strcmp(current->username, username) != 0) {
if (current->next == NULL) {
return -1;
}
current = current->next;
}
*message_identifier = current->identifier;
return 0;
}
int llu_set_identifier(users_list_t *list, char *username, uint32_t message_identifier){
//Function that modify the user's identifier
node_users_t *current = list->head;
while (strcmp(current->username, username) != 0) {
if (current->next == NULL) {
return -1;
}
current = current->next;
}
current->identifier=message_identifier;
return 0;
}
int llu_unregister(users_list_t *list, char *username) {
//This method deletes a user from a linked list
//we also need the previous node as it is the one
// that will be linked with the node after the one that will be deleted
node_users_t *previous = NULL;
node_users_t *current = list->head;
while (strcmp(current->username, username) != 0) {
if (current->next == NULL) {
return -1;
}
previous = current;
current = current->next;
}
node_users_t *temp_node = current->next;
if (previous == NULL) {
//If the previous is null, the node that will be deleted will be the header
//so the node after the header will be the new header
list->head = temp_node;
} else {
if (current->next == NULL) {
//Scenario node removed is the last one
previous->next = NULL;
} else {
//Else the rest of the cases
previous->next = temp_node;
}
}
free(current);
list->size--;
return 0;
}
messages_list_t * llu_get_message_queue(users_list_t *list, char * username){
//Function that returns a user's message queue
node_users_t *current = list->head;
while (strcmp(current->username, username) != 0) {
if (current->next == NULL) {
return NULL;
}
current = current->next;
}
return current->pending_messages;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <strings.h>
#define MOBDIR "lib/world/mob/"
#define OBJDIR "lib/world/obj/"
#define ZONDIR "lib/world/zon/"
#define WLDDIR "lib/world/wld/"
#define SHPDIR "lib/world/shp/"
int main(void)
{
FILE* index;
FILE* input;
FILE* output;
char filename[100];
char newfilename[100];
char buf[900];
char tmp;
strcpy(filename, MOBDIR);
strcat(filename, "index");
if ((index = fopen(filename, "r")) == NULL) {
printf("Could not open %s.", filename);
exit(1);
}
while ((fscanf(index, "%s", buf) != EOF) && buf[0] != '$') {
strcpy(filename, MOBDIR);
strcat(filename, buf);
input = fopen(filename, "r");
strcpy(newfilename, MOBDIR);
strcat(newfilename, buf);
strcat(newfilename, ".new");
output = fopen(newfilename, "w");
while (fscanf(input, "%c", &tmp) != EOF) {
if (tmp == '\r')
tmp = tmp;
else
fprintf(output, "%c", tmp);
}
fclose(output);
fclose(input);
strcpy(buf, "mv ");
strcat(buf, newfilename);
strcat(buf, " ");
strcat(buf, filename);
system(buf);
}
fclose(index);
strcpy(filename, OBJDIR);
strcat(filename, "index");
if ((index = fopen(filename, "r")) == NULL) {
printf("Could not open %s.", filename);
exit(1);
}
while ((fscanf(index, "%s", buf) != EOF) && buf[0] != '$') {
strcpy(filename, OBJDIR);
strcat(filename, buf);
input = fopen(filename, "r");
strcpy(newfilename, OBJDIR);
strcat(newfilename, buf);
strcat(newfilename, ".new");
output = fopen(newfilename, "w");
while (fscanf(input, "%c", &tmp) != EOF) {
if (tmp == '\r')
tmp = tmp;
else
fprintf(output, "%c", tmp);
}
fclose(input);
fclose(output);
strcpy(buf, "mv ");
strcat(buf, newfilename);
strcat(buf, " ");
strcat(buf, filename);
system(buf);
}
fclose(index);
strcpy(filename, WLDDIR);
strcat(filename, "index");
if ((index = fopen(filename, "r")) == NULL) {
printf("Could not open %s.", filename);
exit(1);
}
while ((fscanf(index, "%s", buf) != EOF) && buf[0] != '$') {
strcpy(filename, WLDDIR);
strcat(filename, buf);
input = fopen(filename, "r");
strcpy(newfilename, WLDDIR);
strcat(newfilename, buf);
strcat(newfilename, ".new");
output = fopen(newfilename, "w");
while (fscanf(input, "%c", &tmp) != EOF) {
if (tmp == '\r')
tmp = tmp;
else
fprintf(output, "%c", tmp);
}
fclose(input);
fclose(output);
strcpy(buf, "mv ");
strcat(buf, newfilename);
strcat(buf, " ");
strcat(buf, filename);
system(buf);
}
fclose(index);
strcpy(filename, ZONDIR);
strcat(filename, "index");
if ((index = fopen(filename, "r")) == NULL) {
printf("Could not open %s.", filename);
exit(1);
}
while ((fscanf(index, "%s", buf) != EOF) && buf[0] != '$') {
strcpy(filename, ZONDIR);
strcat(filename, buf);
input = fopen(filename, "r");
strcpy(newfilename, ZONDIR);
strcat(newfilename, buf);
strcat(newfilename, ".new");
output = fopen(newfilename, "w");
while (fscanf(input, "%c", &tmp) != EOF) {
if (tmp == '\r')
tmp = tmp;
else
fprintf(output, "%c", tmp);
}
fclose(input);
fclose(output);
strcpy(buf, "mv ");
strcat(buf, newfilename);
strcat(buf, " ");
strcat(buf, filename);
system(buf);
}
fclose(index);
strcpy(filename, SHPDIR);
strcat(filename, "index");
if ((index = fopen(filename, "r")) == NULL) {
printf("Could not open %s.", filename);
exit(1);
}
while ((fscanf(index, "%s", buf) != EOF) && buf[0] != '$') {
strcpy(filename, SHPDIR);
strcat(filename, buf);
input = fopen(filename, "r");
strcpy(newfilename, SHPDIR);
strcat(newfilename, buf);
strcat(newfilename, ".new");
output = fopen(newfilename, "w");
while (fscanf(input, "%c", &tmp) != EOF) {
if (tmp == '\r')
tmp = tmp;
else
fprintf(output, "%c", tmp);
}
fclose(input);
fclose(output);
strcpy(buf, "mv ");
strcat(buf, newfilename);
strcat(buf, " ");
strcat(buf, filename);
system(buf);
}
fclose(index);
return 0;
}
|
C
|
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#pragma warning(disable : 4996)
typedef struct book {
char name[30];
char semi_ISBN[5];
int page;
}Book;
int main() {
int cmd = 0;
int count = 0;
int check = 0;
int num = 0;
char search[30];
char temp[30];
Book arr[100];
for (int i = 0; i < 100; i++) {
strcpy(arr[i].name, " ");
strcpy(arr[i].semi_ISBN, " ");
arr[i].page = 0;
}
strcpy(arr[0].name, "Let's do it.");
strcpy(arr[0].semi_ISBN, "4456");
arr[0].page = 36;
count++;
do {
printf("--------- menu ---------\n");
printf("1. Display my book(s)\n");
printf("2. Add a book\n");
printf("3. Delete a book\n");
printf("4. Sort my books\n");
printf("5. Exit\n");
printf("-------------------------\n");
printf("Choose a number : ");
rewind(stdin);
scanf("%d", &cmd);
switch (cmd) {
case 1 :
printf("\nThere is %d book(s)", count);
printf("\n");
for (int i = 0; i < count; i++) {
printf("%s (ISBN: %s), %d pages\n", arr[i].name, arr[i].semi_ISBN, arr[i].page);
}
printf("\n");
break;
case 2 :
printf("\nPlease enter the name : ");
rewind(stdin);
fgets(temp, 30, stdin);
temp[strlen(temp) - 1] = '\0';
strcpy(arr[count].name, temp);
printf("semi_ISBN : ");
rewind(stdin);
fgets(temp, 30, stdin);
temp[strlen(temp) - 1] = '\0';
strcpy(arr[count].semi_ISBN, temp);
printf("The number of page : ");
rewind(stdin);
scanf("%d", &num);
arr[count].page = num;
count++;
printf("\n");
break;
case 3 :
printf("\nPlease enter the book name to be removed : ");
check = -1;
rewind(stdin);
fgets(search, 30, stdin);
search[strlen(search) - 1] = '\0';
for (int i = 0; i < count; i++) {
if (!strcmp(arr[i].name, search))
check = i;
}
if (check == -1) {
printf("\n%s is not in your bookshelf.\n\n",search);
}
else {
for (int i = check; i < count - 1; i++) {
arr[i] = arr[i + 1];
}
printf("\n%s is removed from your bookshelf.\n\n", search);
count--;
}
break;
case 4 :
for (int i = 0; temp[i]; i++) {
temp[i] = '0';
}
for (int i = 0; i < count; i++) {
for (int j = 0; j < count -1; j++) {
if (strcmp(arr[j].name, arr[j + 1].name) > 0) {
Book temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
printf("\nBookshelf is a alphabetically ordered.\n\n");
break;
}
} while (cmd != 5);
}
|
C
|
/*
* driver.c
* This file is part of lammps-ensembles
*
* Copyright (C) 2012 - Mladen Rasic & Luke Westby
*
* lammps-ensembles 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.
*
* lammps-ensembles 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 lammps-ensembles; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor,
* Boston, MA 02110-1301 USA
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include "mpi.h"
#include "library.h"
#include "replica.h"
int malloc2dchar(char ***array, int n, int m);
int free2dchar(char ***array);
int main(int argc, char **argv) {
/*----------------------------------------------------------------------------------
* setup MPI
*/
MPI_Init(&argc,&argv);
int this_global_proc, n_global_procs;
MPI_Comm_rank(MPI_COMM_WORLD, &this_global_proc);
MPI_Comm_size(MPI_COMM_WORLD, &n_global_procs);
/*----------------------------------------------------------------------------------
* Set flag defaults
*/
int log_flag = 0; // Turn on/off print out to log.# files
int omp_flag = 0; // Turn on/off OpenMP in LAMMPS/RAPTOR
int Nstates = 1; // Number of state partitions
int Nper = 1; // Number of procs per partition
int read_input_flag = 0; // Turn on/off reading LAMMPS input files from file
int i;
char input_filename[256]; // Name of input file to read
if (this_global_proc == 0) {
/*----------------------------------------------------------------------------------
* Print a header to acknowledge the authors
*/
printf("\n");
printf("--------- Multi-replica ensemble driver for LAMMPS v0.1 ---------\n");
printf(" Brought to you by: Luke Westby, Mladen Rasic, & Adrian W. Lange\n");
printf("-----------------------------------------------------------------\n\n");
/*----------------------------------------------------------------------------------
* Read the input arguments
*/
int error = 0;
int offset = 2;
// check commandline args for errors
if (argc <= 1) {
printf("FLAG ERROR\n");
printf("---> Not enough command arguments\n");
error = 1;
}
// check if user wants to use OpenMP command line for LAMMPS
if(strcmp(argv[offset], "-suffix") == 0) {
if(strcmp(argv[offset+1], "omp") == 0) {
omp_flag = 1;
printf("---> OpenMP flag detected.\n");
offset += 2;
}
}
// check if user wants log files printed out
if(strcmp(argv[offset], "-log") == 0) {
log_flag = 1;
printf("---> Log flag detected. Will print out to numbered log files.\n");
offset += 1;
}
// check if user wants to read LAMMPS input files from disk
if(strcmp(argv[offset], "-readinput") == 0) {
read_input_flag = 1;
// Get name of file to read input from
strcpy( input_filename, argv[offset+1]);
printf("---> Read input flag detected. Will read input options from file %s\n", input_filename);
offset += 2;
}
int tmp_n_comm = atoi(argv[1]);
if ((argc != tmp_n_comm + offset) && read_input_flag == 0) {
printf("FLAG ERROR\n");
printf("---> Input files do not match number of instances (%d %d)\n", argc, tmp_n_comm + offset);
error = 1;
}
if (error == 1) {
printf("---> Syntax: $ ./bin-name P [-suffix omp] [-log] in.file.1 in.file.2 ... in.file.P\n");
printf("---> P = number of instances/replicas\n");
printf("---> [-suffix omp] is for optional OpenMP command line argument for LAMMPS\n");
printf("---> [-log] is for optional printing out to numbered log files for each replica\n\n");
printf("---> Alternatively, you can read LAMMPS inputs from a file and use the following syntax:\n");
printf("---> Syntax: $ ./bin-name P [-suffix omp] [-log] -readinput [input filename]\n");
printf("---> The flag -readinput signals that we need to read the inputs from file [input filename]\n");
printf("\n\nExiting.\n\n");
exit(1);
}
printf("Number of processes = %d\n", n_global_procs);
}
// Broadcast optional flags and values
MPI_Bcast(&omp_flag, 1, MPI_INT, 0, MPI_COMM_WORLD);
MPI_Bcast(&log_flag, 1, MPI_INT, 0, MPI_COMM_WORLD);
MPI_Bcast(&Nstates, 1, MPI_INT, 0, MPI_COMM_WORLD);
MPI_Bcast(&Nper, 1, MPI_INT, 0, MPI_COMM_WORLD);
MPI_Bcast(&read_input_flag, 1, MPI_INT, 0, MPI_COMM_WORLD);
/*----------------------------------------------------------------------------------
* split MPI_COMM_WORLD into subcomms
*/
// set up subcomms and lammps pointers
MPI_Comm subcomm;
void *lmp;
// grab number of communicators
int n_comms = atoi(argv[1]);
MPI_Barrier(MPI_COMM_WORLD);
if (this_global_proc == 0)
printf("Number of subcomms = %d\n", n_comms);
MPI_Barrier(MPI_COMM_WORLD);
// create look-up table for split_key value
if (this_global_proc == 0)
printf("Generating table of instance IDs.\n\n");
int *gproc_lcomm = (int*)malloc(sizeof(int) * n_global_procs);
int *rk_array = (int*)malloc(sizeof(int) * 2*n_comms);
int do_rk = 0; // Do the r-k partitioning?
char **inputfiles;
if (read_input_flag) {
// Handle reading inputs from file
malloc2dchar(&inputfiles, n_comms, 256);
int *npartitions = (int*)malloc(sizeof(int) * n_comms);
int *nper_array = (int*)malloc(sizeof(int) * n_comms);
ReadInputFiles(gproc_lcomm, inputfiles, n_comms, this_global_proc, npartitions, nper_array, rk_array, input_filename);
Nstates = npartitions[gproc_lcomm[this_global_proc]];
Nper = nper_array[gproc_lcomm[this_global_proc]];
if (rk_array[2*gproc_lcomm[this_global_proc]] > 0) {
do_rk = 1;
}
// Check correct number of procs
if (this_global_proc == 0) {
int sum = 0;
for (i = 0; i < n_comms; i++) sum += nper_array[i] * npartitions[i];
if (sum != n_global_procs) {
printf("Error: The total number of processors in %s is %d.\n", input_filename, sum);
printf(" The number of processors in MPI_COMM_WORLD is %d\n", n_global_procs);
printf(" These numbers must match.\n");
exit(1);
}
}
free(npartitions);
free(nper_array);
} else {
// Distribute procs evenly out across partitions
for (i = 0; i < n_global_procs; i += 1) {
gproc_lcomm[i] = floor((double)((i * n_comms)/(n_global_procs)));
}
}
MPI_Barrier(MPI_COMM_WORLD);
// split
if (this_global_proc == 0)
printf("Splitting MPI_COMM_WORLD\n");
int split_key = gproc_lcomm[this_global_proc];
MPI_Comm_split(MPI_COMM_WORLD, split_key, 0, &subcomm);
// get local rank
int this_local_proc;
MPI_Comm_rank(subcomm, &this_local_proc);
MPI_Barrier(MPI_COMM_WORLD);
if (this_local_proc == 0)
printf("---> Report from proc 0 on subcomm %d: %d\n", gproc_lcomm[this_global_proc], this_global_proc);
/*----------------------------------------------------------------------------------
* locate input script filename on commandline and disable default logging and screen
*/
// argv index
int offset = 2;
if (omp_flag) offset += 2;
if (log_flag) offset += 1;
int my_file = gproc_lcomm[this_global_proc] + offset;
// If read inputs from above, modify
if (read_input_flag) {
my_file = gproc_lcomm[this_global_proc];
if (this_local_proc == 0) {
printf("---> Subcomm %d will use input script: %s\n", gproc_lcomm[this_global_proc], inputfiles[my_file]);
}
}
/*----------------------------------------------------------------------------------
* open file and find TEMPER, ANNEAL, COORDX, COLVARX, RELAMB, REUS initializer
*/
MPI_Barrier(MPI_COMM_WORLD);
if (this_global_proc == 0)
printf("Attempting to find multi-replica simulation initializer in input script\n\n");
int nsteps, nevery, sseed, bseed, rate; // total run, frequency of swap, randswap seed, metropolis seed, cooling rate
int temperflag = 0, annealflag = 0; // RE or SA
int coordxflag = 0; // Coordinate exchange
int colvarxflag = 0; // Colvar exchange
int relambdaflag = 0; // Lambda scaling exchange for RAPTOR
int reusflag = 0; // REUS flag for RAPTOR
int mreusflag = 0; // MREUS flag for RAPTOR
double temp, temp_hi, temp_lo; // RE temp, SA high and low temp
char fix[50], file[50]; // fix id, restart binary filename
char EVBfix[50]; // EVB fix id
char ThermoFix[50]; // Thermo fix id
char CVID[50]; // Collecvtive Variable ID
int replicaID = -1; // replica ID for coordx
int dump_swap = 0; // swap dump file names in temper
int group_swap = 0; // In REUS, shall we swap the group 2 coordinates in the Monte Carlo?
double lambda = 0.0; // scaling scalar
int nsteps_short = 0; // short run steps for asynchronous REUS
int coordtype = -1; // REUS coordinate type
int dump = 0; // REUS dump frequency
// doing everything on root of subcomms
if (this_local_proc == 0) {
FILE *infile;
if (read_input_flag) {
infile = fopen(inputfiles[my_file], "r");
} else {
infile = fopen(argv[my_file], "r");
}
// buffer and file position for scanning
char command[9];
fpos_t position;
// search for TEMPER or ANNEAL line by checking first 9 chars
int flag_sum = temperflag + annealflag + coordxflag
+ colvarxflag + relambdaflag + reusflag + mreusflag;
while( flag_sum == 0 && !feof(infile) ) {
fgetpos(infile, &position); // store position
fgets(command, 9, infile); // read in 9 chars
fscanf(infile, "\n"); // move to end of line
// check
if (strcmp(command, "#TEMPER:") == 0) temperflag = 1;
else if(strcmp(command, "#ANNEAL:") == 0) annealflag = 1;
else if(strcmp(command, "#COORDX:") == 0) coordxflag = 1;
else if(strcmp(command, "#COLVARX") == 0) colvarxflag = 1;
else if(strcmp(command, "#RELAMB:") == 0) relambdaflag = 1;
else if(strcmp(command, "#REUS: ") == 0) reusflag = 1;
else if(strcmp(command, "#MREUS: ") == 0) mreusflag = 1;
flag_sum = temperflag + annealflag + coordxflag
+ colvarxflag + relambdaflag + reusflag + mreusflag;
}
// come back to beginning of line
fsetpos(infile, &position);
// scan values from line and clip commas off char *'s
if(temperflag) {
int n = fscanf(infile, "#TEMPER: run %d, swap %d, temp %lf, fix %s seed %d, dumpswap %d",
&nsteps, &nevery, &temp, fix, &sseed, &dump_swap);
if (n != 6) {
printf("%d %d %lf %s %d %d\n", nsteps, nevery, temp, fix, sseed, dump_swap);
printf("Problem reading #TEMPER line. Please check that formatting strictly complies.\n");
exit(1);
}
int len = strlen(fix) - 1;
fix[len] = 0;
} else if(annealflag) {
fscanf(infile, "#ANNEAL: run %d, swap %d, rate %d, file %s fix %s seed %d, temp_hi %lf, temp_lo %lf\n",
&nsteps, &nevery, &rate, file, fix, &bseed, &temp_hi, &temp_lo);
int len_fix = strlen(fix) - 1;
int len_file = strlen(file) -1;
fix[len_fix] = 0;
file[len_file] = 0;
} else if(coordxflag) {
fscanf(infile, "#COORDX: fix %s seed %d", fix, &sseed);
int len_fix = strlen(fix) - 1;
fix[len_fix] = 0;
// search for replica line for replica id
while( coordxflag == 1 && !feof(infile) ) {
int tmp1, tmp3;
double tmp2;
fgetpos(infile, &position); // store position
fgets(command, 10, infile); // read in 10 chars
fscanf(infile, "\n"); // move to end of line
if ( strcmp(command, "#REPLICA:") == 0) {
// come back to beginning of line
fsetpos(infile, &position);
if ( fscanf(infile, "#REPLICA: id %d, ndim %d, temp %lf, tdim %d",
&replicaID, &tmp1, &tmp2, &tmp3) == 4) {
coordxflag = 2;
}
}
}
} else if(colvarxflag) {
fscanf(infile, "#COLVARX: fix %s seed %d", fix, &sseed);
int len_fix = strlen(fix) - 1;
fix[len_fix] = 0;
// search for replica line for replica id
while( colvarxflag == 1 && !feof(infile) ) {
int tmp1, tmp3;
double tmp2;
fgetpos(infile, &position); // store position
fgets(command, 10, infile); // read in 10 chars
fscanf(infile, "\n"); // move to end of line
if ( strcmp(command, "#REPLICA:") == 0) {
// come back to beginning of line
fsetpos(infile, &position);
if ( fscanf(infile, "#REPLICA: id %d, ndim %d, temp %lf, tdim %d",
&replicaID, &tmp1, &tmp2, &tmp3) == 4) {
colvarxflag = 2;
}
}
}
} else if(relambdaflag) {
int n = fscanf(infile, "#RELAMB: LID %s", CVID);
n += fscanf(infile, " run %d, swap %d, temp %lf, fix %s",
&nsteps, &nevery, &temp, EVBfix);
n += fscanf(infile, " seed %d, lambda %lf",
&sseed, &lambda);
if (n != 7) {
printf("Problem reading #RELAMB line on subcomm %d.\n", gproc_lcomm[this_global_proc]);
printf("Wrong number of input fields. Please check that formatting strictly complies.\n");
exit(1);
}
int len = strlen(EVBfix) - 1;
EVBfix[len] = 0;
len = strlen(CVID) - 1;
CVID[len] = 0;
bseed = 0; // not used by RELAMBDA, we only need one seed
} else if(reusflag) {
int n = fscanf(infile, "#REUS: CVID %s", CVID);
n += fscanf(infile, " run %d, swap %d, temp %lf, fix %s",
&nsteps, &nevery, &temp, fix);
n += fscanf(infile, " seed %d, coordtype %d, short %d, dump %d, dump_swap %d, group_swap %d",
&sseed, &coordtype, &nsteps_short, &dump, &dump_swap, &group_swap);
if (n != 11) {
printf("Problem reading #REUS line on subcomm %d.\n", gproc_lcomm[this_global_proc]);
printf("Wrong number of input fields. Please check that formatting strictly complies.\n");
exit(1);
}
int len = strlen(fix) - 1;
fix[len] = 0;
len = strlen(CVID) - 1;
CVID[len] = 0;
bseed = 0; // not used by REUS, we only need one seed
} else if(mreusflag) {
int n = fscanf(infile, "#MREUS: evb %s fix %s thermo %s seed %d, coordtype %d, short %d, dump %d, dump_swap %d, group_swap %d",
EVBfix, fix, ThermoFix, &sseed, &coordtype, &nsteps_short, &dump, &dump_swap, &group_swap);
int len_fix = strlen(fix) - 1;
fix[len_fix] = 0;
len_fix = strlen(EVBfix) - 1;
EVBfix[len_fix] = 0;
len_fix = strlen(ThermoFix) - 1;
ThermoFix[len_fix] = 0;
if (n != 9) {
printf("Problem reading #MREUS line on subcomm %d.\n", gproc_lcomm[this_global_proc]);
printf("Wrong number of input fields. Please check that formatting strictly complies.\n");
exit(1);
}
// search for replica line for replica id
while( mreusflag == 1 && !feof(infile) ) {
int tmp1;
double tmp2;
fgetpos(infile, &position); // store position
fgets(command, 10, infile); // read in 10 chars
fscanf(infile, "\n"); // move to end of line
if ( strcmp(command, "#REPLICA:") == 0) {
// come back to beginning of line
fsetpos(infile, &position);
if ( fscanf(infile, "#REPLICA: id %d, ndim %d, temp %lf",
&replicaID, &tmp1, &tmp2) == 3) {
mreusflag = 2;
}
}
}
}
fclose(infile);
}
// bcast flags and common values
MPI_Bcast(&temperflag, 1, MPI_INT, 0, MPI_COMM_WORLD);
MPI_Bcast(&annealflag, 1, MPI_INT, 0, MPI_COMM_WORLD);
MPI_Bcast(&coordxflag, 1, MPI_INT, 0, MPI_COMM_WORLD);
MPI_Bcast(&colvarxflag, 1, MPI_INT, 0, MPI_COMM_WORLD);
MPI_Bcast(&relambdaflag, 1, MPI_INT, 0, MPI_COMM_WORLD);
MPI_Bcast(&reusflag, 1, MPI_INT, 0, MPI_COMM_WORLD);
MPI_Bcast(&mreusflag, 1, MPI_INT, 0, MPI_COMM_WORLD);
MPI_Bcast(&nsteps, 1, MPI_INT, 0, subcomm);
MPI_Bcast(&nevery, 1, MPI_INT, 0, subcomm);
MPI_Bcast(&bseed, 1, MPI_INT, 0, subcomm);
MPI_Bcast(fix, 50, MPI_CHAR, 0, subcomm);
MPI_Bcast(EVBfix, 50, MPI_CHAR, 0, subcomm);
MPI_Bcast(ThermoFix, 50, MPI_CHAR, 0, subcomm);
MPI_Bcast(&dump_swap, 1, MPI_INT, 0, subcomm);
MPI_Bcast(&group_swap, 1, MPI_INT, 0, subcomm);
// print for error checking and bcast specific values
if(temperflag) {
MPI_Bcast(&sseed, 1, MPI_INT, 0, subcomm);
if(this_global_proc == 0) {
printf("Preparing to run replica exchange:\n");
printf("---> Run %d total timesteps\n", nsteps);
printf("---> Attempt exchange every %d timesteps\n", nevery);
printf("---> Using fix id %s\n", fix);
printf("---> Using random swap seed %d\n", sseed);
} if(this_local_proc == 0)
printf("---> Instance %d using temp %lf\n", split_key, temp);
MPI_Bcast(&temp, 1, MPI_DOUBLE, 0, subcomm);
} else if(annealflag) {
if(this_global_proc == 0) {
printf("Preparing to run simulated annealing:\n");
printf("---> Run %d total timesteps\n", nsteps);
printf("---> Attempt exchange every %d timesteps\n", nevery);
printf("---> Using metroplis seed %d + (global rank)\n", bseed);
printf("---> Decrease temperature every %d timesteps\n", rate);
printf("---> Using fix id %s\n", fix);
printf("---> Starting temp: %lf\n", temp_hi);
printf("---> Ending temp: %lf\n", temp_lo);
} if(this_local_proc == 0)
printf("---> Instance %d using restart binary filename %s\n", split_key, file);
MPI_Bcast(file, strlen(file), MPI_INT, 0, subcomm);
MPI_Bcast(&rate, 1, MPI_INT, 0, subcomm);
MPI_Bcast(&temp_hi, 1, MPI_DOUBLE, 0, subcomm);
MPI_Bcast(&temp_lo, 1, MPI_DOUBLE, 0, subcomm);
} else if(coordxflag) {
MPI_Bcast(&sseed, 1, MPI_INT, 0, subcomm);
if(this_global_proc == 0) {
printf("Preparing to run replica exchange with coordinate exchange:\n");
printf("---> Using fix id %s\n", fix);
printf("---> Using random swap seed %d\n", sseed);
}
MPI_Bcast(&replicaID, 1, MPI_INT, 0, subcomm);
} else if(colvarxflag) {
MPI_Bcast(&sseed, 1, MPI_INT, 0, subcomm);
if(this_global_proc == 0) {
printf("Preparing to run replica exchange with colvar exchange:\n");
printf("---> Using fix id %s\n", fix);
printf("---> Using random swap seed %d\n", sseed);
}
MPI_Bcast(&replicaID, 1, MPI_INT, 0, subcomm);
} else if(relambdaflag) {
MPI_Bcast(CVID, 50, MPI_CHAR, 0, subcomm);
MPI_Bcast(&sseed, 1, MPI_INT, 0, subcomm);
MPI_Bcast(&temp, 1, MPI_DOUBLE, 0, subcomm);
MPI_Bcast(&lambda, 1, MPI_DOUBLE, 0, subcomm);
if(this_global_proc == 0) {
printf("Preparing to run replica exchange lambda simulation:\n");
printf("---> Run %d total timesteps\n", nsteps);
printf("---> Attempt exchange every %d timesteps\n", nevery);
printf("---> Using EVB fix id %s\n", EVBfix);
printf("---> Using random seed %d\n", sseed);
}
if (this_local_proc == 0) {
printf("---> Subcomm %d will use %s as its LID\n", gproc_lcomm[this_global_proc], CVID);
}
} else if(reusflag) {
MPI_Bcast(CVID, 50, MPI_CHAR, 0, subcomm);
MPI_Bcast(&sseed, 1, MPI_INT, 0, subcomm);
MPI_Bcast(&temp, 1, MPI_DOUBLE, 0, subcomm);
MPI_Bcast(&coordtype, 1, MPI_INT, 0, subcomm);
MPI_Bcast(&nsteps_short, 1, MPI_INT, 0, subcomm);
MPI_Bcast(&dump, 1, MPI_INT, 0, subcomm);
if(this_global_proc == 0) {
printf("Preparing to run replica exchange umbrella sampling simulation:\n");
printf("---> Run %d total timesteps\n", nsteps);
printf("---> Attempt exchange every %d timesteps\n", nevery);
printf("---> Using fix id %s\n", fix);
printf("---> Using random seed %d\n", sseed);
printf("---> Using coordinate type %d\n", coordtype);
printf("---> Run %d short timesteps\n", nsteps_short);
printf("---> Dump COLVAR data every %d time steps\n", dump);
}
if (this_local_proc == 0) {
printf("---> Subcomm %d will use %s as its CVID\n", gproc_lcomm[this_global_proc], CVID);
}
} else if(mreusflag) {
MPI_Bcast(&sseed, 1, MPI_INT, 0, subcomm);
MPI_Bcast(&temp, 1, MPI_DOUBLE, 0, subcomm);
MPI_Bcast(&coordtype, 1, MPI_INT, 0, subcomm);
MPI_Bcast(&nsteps_short, 1, MPI_INT, 0, subcomm);
MPI_Bcast(&dump, 1, MPI_INT, 0, subcomm);
if(this_global_proc == 0) {
printf("Preparing to run multi-dimensional replica exchange umbrella sampling simulation:\n");
printf("---> Attempt exchange every %d timesteps\n", nevery);
printf("---> Using fix id %s\n", fix);
printf("---> Using EVB fix id %s\n", EVBfix);
printf("---> Using Thermo fix id %s\n", ThermoFix);
printf("---> Using random seed %d\n", sseed);
printf("---> Using coordinate type %d\n", coordtype);
printf("---> Run %d short timesteps\n", nsteps_short);
printf("---> Dump COLVAR data every %d time steps\n", dump);
}
MPI_Bcast(&replicaID, 1, MPI_INT, 0, subcomm);
} else {
// could not find tag
if(this_global_proc == 0) {
printf("No multi-replica simulation specificied in input script.\n");
printf("Please specifiy a simulation.\n");
printf("Valid options are (whitespace sensitive):\n");
printf("'#TEMPER: ', '#ANNEAL: ', '#COORDX: ', '#COLVARX: ', '#RELAMB: ', '#REUS: ', '#MREUS: ''\n");
printf("Exiting.\n\n");
exit(1);
}
}
/*----------------------------------------------------------------------------------
* Handle passing command line input options
*/
MPI_Barrier(MPI_COMM_WORLD);
if (this_global_proc == 0) {
printf("\n");
printf("Disabling default LAMMPS logging and screen output\n\n");
}
// AWGL : have to put in command line argument options here
// hardcode lammps args
char str1[] = "./ens_driver";
char strin[] = "-in";
char strfile[256];
if (read_input_flag) {
sprintf(strfile,"%s",inputfiles[my_file]);
} else {
sprintf(strfile,"%s",argv[my_file]);
}
char str2[] = "-log";
char str3_none[] = "none";
char str3_log[256];
if (reusflag) {
sprintf(str3_log,"log.cv.%s", CVID);
} else if (relambdaflag) {
sprintf(str3_log,"log.id.%s", CVID);
} else if (coordxflag || colvarxflag || mreusflag) {
sprintf(str3_log,"log.id.%d", replicaID);
} else {
// Default to split key labelling
sprintf(str3_log,"log.%d", split_key);
}
char str4[] = "-screen";
char str_suffix[] = "-suffix";
char str_omp[] = "omp";
char str_partition[] = "-partition";
char str_nstates_nper[256];
sprintf(str_nstates_nper,"%dx%d", Nstates, Nper);
// ** Build list ** //
char *arglist[13];
int n = 0;
// Standard commands
arglist[n++] = str1;
arglist[n++] = strin;
arglist[n++] = strfile;
arglist[n++] = str2;
if (log_flag) arglist[n++] = str3_log;
else arglist[n++] = str3_none;
arglist[n++] = str4;
arglist[n++] = str3_none;
// Optional commands
if (omp_flag) {
arglist[n++] = str_suffix;
arglist[n++] = str_omp;
}
if (read_input_flag && Nstates > 1 && do_rk == 0) {
// Only do the partitioning if more than one state requested
arglist[n++] = str_partition;
arglist[n++] = str_nstates_nper;
}
if (read_input_flag && do_rk) {
arglist[n++] = str_partition;
char str_tmp[256];
sprintf(str_tmp,"%d", Nstates);
arglist[n++] = str_tmp;
sprintf(str_tmp,"%d", rk_array[2*gproc_lcomm[this_global_proc]]);
arglist[n++] = str_tmp;
sprintf(str_tmp,"%d", rk_array[2*gproc_lcomm[this_global_proc]+1]);
arglist[n++] = str_tmp;
}
// create pointer
char** args = arglist;
/*----------------------------------------------------------------------------------
* open LAMMPS - assign LAMMPS pointer, read input script, run simulation
*/
MPI_Barrier(MPI_COMM_WORLD);
int num_args = 7;
if (omp_flag) num_args += 2;
if (read_input_flag && Nstates > 1 && do_rk == 0) num_args += 2;
if (read_input_flag && do_rk) num_args += 3;
if(this_local_proc == 0) {
printf("---> Opening LAMMPS on subcomm %d with command:", split_key);
int j;
for (j=0; j<num_args; j++)
printf("%s ", args[j]);
printf("\n");
}
// assign lmp to new LAMMPS instance
lammps_open(num_args, args, subcomm, &lmp);
MPI_Barrier(MPI_COMM_WORLD);
if (this_local_proc == 0) {
if (read_input_flag) {
printf("---> Opening LAMMPS script %s subcomm %d...\n", inputfiles[my_file], split_key);
} else {
printf("---> Opening LAMMPS script %s subcomm %d...\n", argv[my_file], split_key);
}
}
// open input script
if (read_input_flag) {
lammps_file(lmp, inputfiles[my_file]);
} else {
lammps_file(lmp, argv[my_file]);
}
MPI_Barrier(MPI_COMM_WORLD);
int skip_run = 0; // debugging
// run simulation
if(temperflag) {
if (this_global_proc == 0)
printf("---> Beginning replica exchange...\n\n");
if (!skip_run)
temper(lmp, subcomm, nsteps, nevery, n_comms, split_key, temp, fix, sseed, dump_swap);
}
else if(annealflag) {
if(this_global_proc == 0)
printf("---> Beginning simulated annealing...\n\n");
//anneal(lmp, subcomm, file, fix, bseed, split_key, n_comms, nsteps, nevery, rate, temp_hi, temp_lo);
}
else if(coordxflag || colvarxflag) {
// ** Set up the replica data structure here ** //
Replica this_replica;
if (read_input_flag) {
ReadReplica(&this_replica, subcomm, split_key, this_local_proc, inputfiles[my_file]);
} else {
ReadReplica(&this_replica, subcomm, split_key, this_local_proc, argv[my_file]);
}
if (this_global_proc == 0)
printf("---> Beginning replica exchange...\n\n");
if (!skip_run) {
if (coordxflag) coord_exchange(lmp, subcomm, n_comms, split_key, &this_replica, fix, sseed);
if (colvarxflag) colvar_exchange(lmp, subcomm, n_comms, split_key, &this_replica, fix, sseed);
}
// ** Free replica array ** //
free(this_replica.neighbors);
free(this_replica.dim_run);
free(this_replica.dim_nevery);
}
else if(mreusflag) {
// ** Set up the replica data structure here ** //
Replica this_replica;
if (read_input_flag) {
ReadReplicaMREUS(&this_replica, subcomm, split_key, this_local_proc, inputfiles[my_file]);
} else {
ReadReplicaMREUS(&this_replica, subcomm, split_key, this_local_proc, argv[my_file]);
}
if (this_global_proc == 0)
printf("---> Beginning MREUS...\n\n");
if (!skip_run) {
mreus(lmp, subcomm, n_comms, split_key, EVBfix, fix, ThermoFix, sseed, coordtype, nsteps_short, dump, dump_swap, group_swap, &this_replica);
}
// ** Free replica array ** //
free(this_replica.neighbors);
free(this_replica.dim_run);
free(this_replica.dim_nevery);
}
else if(relambdaflag) {
if (this_global_proc == 0)
printf("---> Beginning replica exchange lambda simulation at temperature %f \n", temp);
relambda(lmp, subcomm, CVID, nsteps, nevery, n_comms, split_key, temp, EVBfix, sseed, lambda);
}
else if(reusflag) {
if (this_global_proc == 0)
printf("---> Beginning replica exchange umbrella sampling simulation at temperature %f \n", temp);
reus(lmp, subcomm, CVID, nsteps, nevery, n_comms, split_key, temp, fix, sseed, coordtype, nsteps_short, dump, dump_swap, group_swap);
}
/*----------------------------------------------------------------------------------
* close LAMMPS and clean up
*/
MPI_Barrier(MPI_COMM_WORLD);
if (this_local_proc == 0)
printf("---> Closing LAMMPS on subcomm %d.\n", gproc_lcomm[this_global_proc]);
free(gproc_lcomm);
if (read_input_flag) {
free2dchar(&inputfiles);
}
free(rk_array);
lammps_close(lmp);
MPI_Barrier(MPI_COMM_WORLD);
/*----------------------------------------------------------------------------------
* Print a footer
*/
if (this_global_proc == 0) {
printf("\n");
printf("-----------------------------------------------------------------\n");
printf(" Finished! \n");
printf("-----------------------------------------------------------------\n\n");
}
MPI_Finalize();
return 0;
}
/*----------------------------------------------------------------------------------
* 2d array helper functions
*/
int malloc2dchar(char ***array, int n, int m) {
char *p = (char *)malloc(n*m*sizeof(char));
(*array) = (char **)malloc(n*sizeof(char*));
int i;
for (i=0; i<n; i+=1)
(*array)[i] = &(p[i*m]);
return 0;
}
int free2dchar(char ***array) {
free(&((*array)[0][0]));
free(*array);
return 0;
}
|
C
|
#include <stdio.h>
#include <string.h>
#include <dirent.h>
#include <sys/stat.h>
#include <signal.h>
#include <stdlib.h>
#include <unistd.h>
char *cat_options[4] = {"-n", "-E", "-nE", "-En"};
int cat_ops[] = {0, 0};
int check(char *source)
{
int i = 0;
while (i < strlen(source))
{
if (source[i] == '-')
{
++i;
while (i < strlen(source))
{
if (source[i] == 'n')
cat_ops[0] = 1;
else if (source[i] == 'E')
cat_ops[1] =1;
else
return i;
++i;
}
}
++i;
}
return -1;
}
int check_options_driver(char **argv, int argc)
{
int i = 0;
for ( ; i < argc ; ++i)
{
int p;
if ( (p = check(argv[i])) != -1)
{
fprintf(stderr, "%s%s\n", "Invalid argument: ", argv[i]);
return 0;
}
}
return 1;
}
int isDirectory(const char *path) {
struct stat statbuf;
if (stat(path, &statbuf) != 0)
return 0;
return S_ISDIR(statbuf.st_mode);
}
int parse_cat(char **argv, int argc)
{
int i = 1;
for ( ; i < argc ; ++i)
{
int j = 0;
int found = 0;
for ( ; j < 4 ; ++j)
{
if (strcmp(argv[i], cat_options[j]) == 0)
{
cat_ops[j] = 1;
found = 1;
}
}
if (!found)
{
return i;
}
}
return argc;
}
char *ush_readline()
{
ssize_t buffer_size = 0;
char *buffer = NULL;
getline(&buffer, &buffer_size, stdin);
char *pos;
if ((pos = strchr(buffer, '\n')) != NULL)
*pos = '\0';
return buffer;
}
int main(int argc, char **argv)
{
if (!check_options_driver(argv, argc))
return 0;
if (argc == 1)
{
while(1)
{
char *command = ush_readline();
printf("%s\n", command);
}
return 0;
}
if (!strcmp(argv[1], "*"))
{
struct dirent *de;
DIR *dr;
dr = opendir(".");
while ((de = readdir(dr)) != NULL)
{
if(de->d_name[0] != '.')
{
if (isDirectory(de->d_name))
printf("%s%s%s\n", "cat: ", de->d_name, " is a directory");
else
{
FILE *fp = fopen(de->d_name, "r");
char c = fgetc(fp);
while (c != EOF)
{
printf ("%c", c);
c = fgetc(fp);
}
}
}
}
return 0;
}
int index = parse_cat(argv, argc);
while (index < argc)
{
if (!strcmp(argv[index], "-n") || !strcmp(argv[index], "-E") || !strcmp(argv[index], "-nE") || !strcmp(argv[index], "-En"))
{
index++;
continue;
}
if (isDirectory(argv[index]))
{
fprintf(stderr, "%s%s%s\n", "cat: ", argv[index], " is a directory");
}
FILE *fp = fopen(argv[index], "r");
if (fp == NULL)
{
fprintf(stderr, "%s\n", "file does not exist");
return 0;
}
if (cat_ops[0] == 0 && cat_ops[1] == 0)
{
char c = fgetc(fp);
while (c != EOF)
{
printf ("%c", c);
c = fgetc(fp);
}
}
else if (cat_ops[0] == 1)
{
char line[1024];
int counter = 1;
while (fgets(line, 1024, fp) != NULL)
{
char *pos;
if ((pos = strchr(line, '\n')) != NULL)
*pos = '\0';
if (cat_ops[1] == 1)
{
printf("%d %s%s", counter++, line, "$");
}
else
{
printf("%d %s", counter++, line);
}
printf("\n");
}
}
else
{
char line[1024];
while (fgets(line, 1024, fp) != NULL)
{
char *pos;
if ((pos = strchr(line, '\n')) != NULL)
*pos = '\0';
printf("%s%s\n", line, "$");
}
}
fclose(fp);
index++;
}
return 0;
}
|
C
|
/*
** EPITECH PROJECT, 2019
** manage_mouse_click
** File description:
** manage_mouse_click
*/
int my_putstr(char const *str);
int my_put_nbr(int nb);
#include <SFML/Audio.h>
#include <SFML/Graphics.h>
#include <stdlib.h>
void manage_mouse_click(sfMouseButtonEvent event)
{
my_putstr("Mouse x=");
my_put_nbr(event.x);
my_putstr(" y=");
my_put_nbr(event.y);
my_putstr("\n");
}
|
C
|
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main(int argc, char *argv[])
{
// open file for reading
FILE *inputFile = fopen("Prob19.in.txt", "r");
int testCases;
// read number of test cases
fscanf(inputFile, "%d\n", &testCases);
char nextChar;
int currentValue;
// each number represents the amount to add to the input
// to get the output. each rotor is listed in position 0.
// index values must be adjusted to account for rotation.
int rotors[4][10] = {{1, 2, 4, 7, 1, 9, 2, 0, 1, 3},
{0, 2, 3, 9, 2, 4, 5, 7, 0, 8},
{5, 8, 9, 4, 9, 3, 4, 5, 6, 7},
{1, 5, 3, 9, 5, 5, 1, 7, 5, 9}};
int inverseRotors[4][10] = {{3, 9, 7, 8, 1, 9, 6, 0, 8, 9},
{0, 5, 1, 8, 3, 7, 8, 2, 0, 6},
{6, 1, 5, 1, 4, 5, 3, 6, 7, 2},
{5, 9, 1, 5, 3, 7, 5, 9, 1, 5}};
int reflector[10] = {3, 5, 6, 7, 1, 9, 5, 2, 4, 8};
int leftRotor, leftRotorStart, leftRotorPosition;
int middleRotor, middleRotorStart, middleRotorPosition;
int rightRotor, rightRotorStart, rightRotorPosition;
int rotorIndex;
// execute test cases
while(testCases > 0){
// read key settings
fscanf(inputFile, "%d %d\n", &leftRotor, &leftRotorStart);
fscanf(inputFile, "%d %d\n", &middleRotor, &middleRotorStart);
fscanf(inputFile, "%d %d\n", &rightRotor, &rightRotorStart);
// adjust for index
leftRotor = leftRotor - 1;
middleRotor = middleRotor - 1;
rightRotor = rightRotor - 1;
// set start positions
leftRotorPosition = leftRotorStart;
middleRotorPosition = middleRotorStart;
rightRotorPosition = rightRotorStart;
// read characters one at a time
fscanf(inputFile, "%c", &nextChar);
// until we hit a newline
while(nextChar != '\n'){
// convert from number - '0' == 48, '1' == 49
// so '0' - 48 = 0, etc.
currentValue = nextChar - 48;
// enter left rotor
// when in position 0, currentValue is the rotorIndex
// when the rotor is shifted, we have to adjust accordingly
rotorIndex = currentValue - leftRotorPosition;
if(rotorIndex < 0){
rotorIndex = rotorIndex + 10;
}
// add the rotor's value to the current value
currentValue = currentValue + rotors[leftRotor][rotorIndex];
if(currentValue >= 10){
currentValue = currentValue - 10;
}
// enter middle rotor
rotorIndex = currentValue - middleRotorPosition;
if(rotorIndex < 0){
rotorIndex = rotorIndex + 10;
}
currentValue = currentValue + rotors[middleRotor][rotorIndex];
if(currentValue >= 10){
currentValue = currentValue - 10;
}
// enter right rotor
rotorIndex = currentValue - rightRotorPosition;
if(rotorIndex < 0){
rotorIndex = rotorIndex + 10;
}
currentValue = currentValue + rotors[rightRotor][rotorIndex];
if(currentValue >= 10){
currentValue = currentValue - 10;
}
// enter reflector
// the reflector doesn't rotate
currentValue = currentValue + reflector[currentValue];
if(currentValue >= 10){
currentValue = currentValue - 10;
}
// re-enter right rotor
// same as above, but now we use the inverseRotor arrays
// for going "backwards" through the rotors
rotorIndex = currentValue - rightRotorPosition;
if(rotorIndex < 0){
rotorIndex = rotorIndex + 10;
}
currentValue = currentValue + inverseRotors[rightRotor][rotorIndex];
if(currentValue >= 10){
currentValue = currentValue - 10;
}
// re-enter middle rotor
rotorIndex = currentValue - middleRotorPosition;
if(rotorIndex < 0){
rotorIndex = rotorIndex + 10;
}
currentValue = currentValue + inverseRotors[middleRotor][rotorIndex];
if(currentValue >= 10){
currentValue = currentValue - 10;
}
// re-enter left rotor
rotorIndex = currentValue - leftRotorPosition;
if(rotorIndex < 0){
rotorIndex = rotorIndex + 10;
}
currentValue = currentValue + inverseRotors[leftRotor][rotorIndex];
if(currentValue >= 10){
currentValue = currentValue - 10;
}
// print the resulting value
printf("%d", currentValue);
// rotate rotors
rightRotorPosition = rightRotorPosition + 1;
if(rightRotorPosition == 10){
rightRotorPosition = 0;
}
// if right rotor has completed a full rotation,
if(rightRotorPosition == rightRotorStart){
// rotate the middle one
middleRotorPosition = middleRotorPosition + 1;
if(middleRotorPosition == 10){
middleRotorPosition = 0;
}
// if it's completed a full rotation,
if(middleRotorPosition == middleRotorStart){
// rotate the left one too
leftRotorPosition = leftRotorPosition + 1;
if(leftRotorPosition == 10){
leftRotorPosition = 0;
}
}
}
// get next character
fscanf(inputFile, "%c", &nextChar);
}
printf("\n");
testCases = testCases - 1;
}
// close the file
fclose(inputFile);
}
|
C
|
#include <stdio.h>
int main()
{
int n;
printf("input:");
scanf("%d", &n);
printf("output:%d\n", &n);//ʮ
printf("output:%o\n", &n);//˽
printf("output:%X\n", &n);//ʮ
return 0;
}
|
C
|
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
typedef char Elementtype; // ͣɸҪж
typedef struct TreeNode * Node; // Node൱struct treeNode *
// ڵṹ
typedef struct TreeNode
{
Elementtype Element;
Node left; // ڵӽڵ
Node right; // ڵӽڵ
}TREE, *PTREE;
//
void CreatTree(PTREE *); //
void PreOrderTree(PTREE); // ǰ
void InOrderTree(PTREE); //
void PostOrderTree(PTREE); // ĺ
void LeafOfTree(PTREE); // ӡҶӽڵ㺯
int Get_Leaf_Num(PTREE); // ȡҶӽڵ
int Get_Height(PTREE); // ȡĸ߶
int main() {
PTREE Root;
printf("Ľڵݣ ");
CreatTree(&Root);
printf("\nǰΪ");
PreOrderTree(Root);
printf("\nΪ");
InOrderTree(Root);
printf("\nΪ");
PostOrderTree(Root);
printf("\nӡҶӽڵΪ");
LeafOfTree(Root);
printf("\nҶӽڵΪ%d", Get_Leaf_Num(Root));
printf("\nĸ߶Ϊ%d", Get_Height(Root));
printf("\n");
return 0;
}
//
void CreatTree(PTREE *Root) {
char val = 0; //
val = getchar(); // ֵ
// ' 'ָΪ
if (val == ' ')
(*Root) = NULL;
else
{
(*Root) = (PTREE)malloc(sizeof(TREE)); // ڴռ
if ((*Root) == NULL) {
printf("ڵʧܣڴ...\n");
exit(-1);
}
else {
(*Root)->Element = val; // ڵֵ
CreatTree(&(*Root)->left);
CreatTree(&(*Root)->right);
}
}
}
// ǰ
void PreOrderTree(PTREE Root) {
if (Root == NULL)
return;
else {
putchar(Root->Element);
PreOrderTree(Root->left);
PreOrderTree(Root->right);
}
}
//
void InOrderTree(PTREE Root) {
if (Root == NULL)
return;
else {
InOrderTree(Root->left);
putchar(Root->Element);
InOrderTree(Root->right);
}
}
// ĺ
void PostOrderTree(PTREE Root) {
if (Root == NULL)
return;
else{
PostOrderTree(Root->left);
PostOrderTree(Root->right);
putchar(Root->Element);
}
}
// ӡҶӽڵ㺯
void LeafOfTree(PTREE Tree) {
if (Tree == NULL)
return;
else {
if (Tree->left == NULL&&Tree->right == NULL)
putchar(Tree->Element);
else {
LeafOfTree(Tree->left);
LeafOfTree(Tree->right);
}
}
}
// ȡҶӽڵ
int Get_Leaf_Num(PTREE Tree) {
if (Tree == NULL)
return 0;
if (Tree->left == NULL&&Tree->right == NULL)
return 1;
//ݹҶӽڵ = Ҷӽڵĸ + Ҷӽڵĸ
return Get_Leaf_Num(Tree->left) + Get_Leaf_Num(Tree->right);
}
// ȡߵĺ
int Get_Height(PTREE Tree) {
int Height = 0;
if (Tree == NULL)
return 0;
//ĸ߶ = max(ĸ߶ȣĸ߶) + 1
else
{
int L_Height = Get_Height(Tree->left);
int R_Height = Get_Height(Tree->right);
Height = L_Height >= R_Height ? L_Height + 1 : R_Height + 1;
}
return Height;
}
|
C
|
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <stdlib.h>
#include <memory.h>
int main() {
//for parent to child
int parentToChild[2];
//for child to parent
int childToParent[2];
//string data
char message1[] = "massage from child to parent\n";
char message2[] = "message from parent to child\n";
char readBuffer[120];
pipe(parentToChild);
pipe(childToParent);
int processId , bytes;
if((processId = fork())== -1){
printf("error while creating a child process");
}
if(processId == 0){
//child process here
//send message from child to parent
close(childToParent[0]);
write(childToParent[1] , message1 , strlen(message1)+1);
//recive message from parent
close(parentToChild[1]);
bytes = read(parentToChild[0] , readBuffer , sizeof(readBuffer));
printf("%s",readBuffer);
// exit(1);
}
if(processId !=0 ){
//parent process here
//send message from parent to child
close(parentToChild[0]);
write(parentToChild[1] , message2 , strlen(message2)+1);
//recieve message from child
close(childToParent[1]);
bytes = read(childToParent[0] , readBuffer , sizeof(readBuffer));
printf("%s", readBuffer);
// exit(1);
}
return 0;
}
|
C
|
/* $Id: stresstest.c 732 2008-03-10 15:55:53Z lsc $ */
/*
* Author: Lee-Shawn Chin
* Date : Feb 2008
* Copyright (c) 2008 STFC Rutherford Appleton Laboratory
*
* File : stresstest.c
*
*/
#include "stresstest.h"
/* define and initialise global vars */
int env_rank = 0;
int env_size = 1;
int main(int argc, char ** argv) {
int rc;
/* Set up the message board environment */
if (setup_env(&argc, &argv) != OK)
{
complain_then_quit("Could not set up libmoard environment");
}
/* ============================================================ */
rc = t_manyboards();
if (rc != OK)
{
PRINT(">> TEST FAILED\n");
PRINT(">> We might have run out of memory. Try setting a lower\n");
PRINT(" value for TP_MANYBOARD_COUNT\n");
shutdown_env();
exit(1);
}
/* ------------------------------------------------------------ */
rc = t_manymsgs();
if (rc != OK)
{
PRINT(">> TEST FAILED\n");
PRINT(">> We might have run out of memory. Try setting a lower\n");
PRINT(" value for TP_MANYMSG_COUNT\n");
shutdown_env();
exit(1);
}
/* ============================================================ */
/* clean up and quit */
if (shutdown_env() != OK) exit(1);
exit(0);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include "func_basica.h" /* Header que chamas funcoes nos arquivos externos (*.c) */
int main()
{
int a, b;
float resultado;
system("clear");
printf("\n\n\tProgarma MAIN que chama Funcoes Externas");
printf("\n\tAs Funcoes Externas executam as 4 Operacoes Basicas da Matematica");
printf("\n\tExiste uma Funcao Somar, Subtrair, Multiplicar e Dividir");
printf("\n\tAs Operacoes serao realizadas entre [a] e [b], onde estes devem ser Inteiros");
printf("\n\n\tEntre com Numero [a]: ");
scanf("%d", &a);
printf("\n\tEntre com Numero [b]: ");
scanf("%d", &b);
resultado = somar(a, b);
printf("\n\t\tResultado: a(%d) + b(%d) = (%4.2f)", a, b, resultado);
resultado = subtrair(a, b);
printf("\n\t\tResultado: a(%d) - b(%d) = (%4.2f)", a, b, resultado);
resultado = multiplicar(a, b);
printf("\n\t\tResultado: a(%d) * b(%d) = (%4.2f)", a, b, resultado);
resultado = dividir(a, b);
printf("\n\t\tResultado: a(%d) / b(%d) = (%4.2f)", a, b, resultado);
printf("\n\n");
return 0;
}
|
C
|
/******************************************************************************
Use of time.h library functions
*******************************************************************************/
//The C library function clock_t clock(void) returns the number of clock ticks
//elapsed since the program was launched.
//To get the number of seconds used by the CPU, you will need to divide by CLOCKS_PER_SEC.
//Syntax --
// clock(void);
//2. time_t time( time_t *second )
/*
The time() function is defined in time.h header file.
This function returns the time since 00:00:00 UTC, January 1, 1970 in seconds.
*/
#include <time.h>
#include <stdio.h>
void main()
{
clock_t start_time,end_time;
start_time=clock();
for(int i=0;i<2000000;i++)
{
}
end_time=clock();
double time_req=(double)(end_time - start_time);
printf("The number of clock ticks since the beginning of program is %f\n",time_req);
printf("Time required to run this program is %f sec\n",time_req/CLOCKS_PER_SEC);
time_t t;
time(&t);
// printf("Seconds since January 1, 1970 = %ld\n", time(NULL));
printf("Seconds since January 1, 1970 = %ld\n", time(&t));
printf("Today's date and time : %s",ctime(&t));
}
/*
OUTPUT:
The number of clock ticks since the beginning of program is 4052.000000
Time required to run this program is 0.004052 sec
Seconds since January 1, 1970 = 1612873201
Today's date and time : Tue Feb 9 12:20:01 2021
*/
|
C
|
#include <stdio.h>
#include <string.h>
int main(void)
{
char s1[20] = "Hello ";
char s2[] = " World ";
char s3[40] = "";
printf( "string1 = %s\nstring2 = %s\n", s1, s2);
printf("strcat(s1, s2) = %s\n", strcat(s1, s2));
printf( "strncat(s3, s2, 6) = %s\n", strncat( s3, s2, 6 ));
return 0;
}
|
C
|
#include <stdio.h>
int main() {
int bills[12] = {10000, 5000, 2000, 1000, 500, 200, 100, 50, 25, 10, 5, 1};
char *prefix;
int coinsStart = 6;
int total, i, changed;
double tIn;
int amountBill;
while (scanf("%lf", &tIn) == 1) {
total = (int)(tIn * 100);
i = 0;
printf("NOTAS:\n");
changed = 0;
prefix = "nota";
while (total > 0 || i < 12) {
amountBill = total/bills[i];
total -= bills[i]*amountBill;
if (!changed && i >= coinsStart) {
changed = 1;
printf("MOEDAS:\n");
prefix = "moeda";
}
printf("%d %s(s) de R$ %.2f\n", amountBill, prefix, bills[i++]/100.0);
}
}
return 0;
}
|
C
|
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include<ctype.h>
#include <stdlib.h>
#include <string.h>
#include <locale.h>
#include <Windows.h>
#include <malloc.h>
#include "Neighbor.h"
#include <time.h>
#define kMaxKeySize 1024
//-, - , , .
// , - , ?
//
enum
{
XOR = 1,
GET_LENGTH_AND_KEY,
EXIT,
};
typedef struct Keys_
{
char key[50];
struct Keys_ *next;
}KEY;
KEY *beg, *cur;
init()
{
beg = (KEY*)malloc(sizeof(KEY));
beg->key[0] = '\0';
beg->next = NULL;
cur = beg;
}
KEY * addElem(char *key_, int size)
{
KEY *p = (KEY*)malloc(sizeof(KEY));
cur->next = p;
for (int i = 0; i < size; i++)// ??
{
p->key[i] = key_[i];
}
p->key[size] = '\0';
p->next = NULL;
return p;
}
void deletelem()
{
cur = beg->next;
while (cur != NULL)
{
beg->next = cur->next;
free(cur);
cur = beg->next;
printf("edel\n\n\n");
}
cur = beg;
cur->next = NULL;
}
void search(int number)
{
cur = beg->next;
int count = 1;
while (cur != NULL && number != count)
{
count++;
cur = cur->next;
}
}
unsigned int keystat[kMaxKeySize][256];
unsigned char password[50];
unsigned char* shifr_text, *lolo;
unsigned char* tmp_shifr_text;
int kSize;
int count_for_Brut = 6;
void xor_cypher()
{
setlocale(0, "");
FILE* fin = fopen("input.txt", "rb"), *fout = fopen("output.txt", "wb");
long long i = 0;
if (fin == NULL)
{
printf("Cant read file!\n");
return;
}
printf(" : ");
getchar();
gets(password);
long long length = strlen(password);
int c = fgetc(fin);// ,
// , , .
while (c != EOF)
{
c ^= password[i % length];
i++;
fputc(c, fout);
c = fgetc(fin);
}
fseek(fin, 0, SEEK_SET);
fclose(fin);
fclose(fout);
}
int menu()
{
int num = 0;
printf("\n ?\n");
printf(" :\n");
printf("1. .\n");
printf("2. . .\n");
printf("3. .\n");
if (!scanf("%d", &num))
{
fflush(stdin);
printf("input error.\ntry again: ");
}
return (num);
}
float sum_matches(unsigned char split_str[], int size)
{
int i = 0, count_repit = 0;
float sum = 0.0;
//int sizeFor = size - 1;//
for (i = 0; i < size-1; i++)
{
if (split_str[i] == split_str[i + 1])
{
count_repit++;
}
else
{
sum += count_repit * (count_repit - 1) / (float)(size * (size - 1));//
count_repit = 0;
}
}
return sum;
}
//. , , .
void qsortt(int l, int r, unsigned char a[])
{
if (l < r)
{
int i = l, j = r, t;
int d = (l + r) / 2;
int x = a[d];
do
{
while (a[i] < x) i++;
while (a[j] > x) j--;
if (i <= j)
{
t = a[i];
a[i] = a[j];
a[j] = t;
i++;
j--;
}
} while (i <= j);
qsortt(l, j, a);
qsortt(i, r, a);
}
}
float split_text(int size_key, unsigned char shifr_text[], int size)
{
int a = size / size_key + 1;
unsigned char* split_str = (unsigned char*)malloc(a * sizeof(unsigned char));
int count = 0;
float sum = 0.0;
for (int start = 0; start < size_key; start++)//
{
for (int i = start; i < size; i += size_key, count++)
{
split_str[count] = shifr_text[i];
}
qsortt(0, count - 1, split_str);
sum += sum_matches(split_str, count - 1);
count = 0;
}
free(split_str);
return sum / (float)size_key;
}
int key_size(unsigned char shifr_text[], int size, float key_long[])
{
int count_key = 0;
float sum_index = 0.0;
for (int i = 2; i < size / 2 + 1; i++)//size/2 + 1
{
key_long[i] = (split_text(i, shifr_text, size));
sum_index += key_long[i];
}
float max_delta = 0.0;
int kSize = 0;
float avverage = sum_index / (float)(size / 2 - 1);
for (int i = 2; i < size / 2 + 1; i++)//
{
if ((key_long[i] - avverage) > max_delta)
{
kSize = i;
max_delta = key_long[i] - avverage;
}
}
return kSize;
}
unsigned char frequency[] = " etaoinshrdlcumwfgypbvkxjqz";
unsigned char alphabet[] = " etaoinshrdlcumwfgypbvkxjqzETAOINSHRDLCUMWFGYPBVKXJQZ1234567890!_;%:?*()-=+&^$#@";
//-. .
int is_it_char(char c)
{
if ((c >= '0' && c <= '?') || (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= 32 && c <= 47))
{
return 1;
}
else return 0;
}
//. , - 8 , , .
// .
// ,
int check(char c, const char* neig)
{
if (c != ' ')
{
for (int i = 0; i < strlen(neig); i++)// dlina = strlen
{
if (c == neig[i])
{
if (i < strlen(neig) / 2)
{
return 2;
break;
}
else
{
return 1;
break;
}
}
}
return -1;
}
else return 0;
}
//. -? case if-elseif, case.
//
int analysis_bin(unsigned char* tempkey, int sizetext)
{
//memset(tmp_shifr_text, 0, sizetext);
int needsize = need_size(100, sizetext), tmp_count_bin = 0;
for (int j = 0; j < needsize; j++)//
{
tmp_shifr_text[j] = shifr_text[j] ^ tempkey[j % kSize];
}
for (int j = 1; j < needsize - 1; j++)//
{
unsigned char tmp = tolower(tmp_shifr_text[j]);
switch (tmp)
{
case 'a':
tmp_count_bin += check(tolower(tmp_shifr_text[j - 1]), neigA_left);
tmp_count_bin += check(tolower(tmp_shifr_text[j + 1]), neigA_right);
break;
case 'b':
tmp_count_bin += check(tolower(tmp_shifr_text[j - 1]), neigB_left);
tmp_count_bin += check(tolower(tmp_shifr_text[j + 1]), neigB_right);
break;
case 'c':
tmp_count_bin += check(tolower(tmp_shifr_text[j - 1]), neigC_left);
tmp_count_bin += check(tolower(tmp_shifr_text[j + 1]), neigC_right);
break;
case 'd':
tmp_count_bin += check(tolower(tmp_shifr_text[j - 1]), neigD_left);
tmp_count_bin += check(tolower(tmp_shifr_text[j + 1]), neigD_right);
break;
case 'e':
tmp_count_bin += check(tolower(tmp_shifr_text[j - 1]), neigE_left);
tmp_count_bin += check(tolower(tmp_shifr_text[j + 1]), neigE_right);
break;
case 'f':
tmp_count_bin += check(tolower(tmp_shifr_text[j - 1]), neigF_left);
tmp_count_bin += check(tolower(tmp_shifr_text[j + 1]), neigF_right);
break;
case 'g':
tmp_count_bin += check(tolower(tmp_shifr_text[j - 1]), neigG_left);
tmp_count_bin += check(tolower(tmp_shifr_text[j + 1]), neigG_right);
break;
case 'h':
tmp_count_bin += check(tolower(tmp_shifr_text[j - 1]), neigH_left);
tmp_count_bin += check(tolower(tmp_shifr_text[j + 1]), neigH_right);
break;
case 'i':
tmp_count_bin += check(tolower(tmp_shifr_text[j - 1]), neigI_left);
tmp_count_bin += check(tolower(tmp_shifr_text[j + 1]), neigI_right);
break;
case 'j':
tmp_count_bin += check(tolower(tmp_shifr_text[j - 1]), neigJ_left);
tmp_count_bin += check(tolower(tmp_shifr_text[j + 1]), neigJ_right);
break;
case 'k':
tmp_count_bin += check(tolower(tmp_shifr_text[j - 1]), neigK_left);
tmp_count_bin += check(tolower(tmp_shifr_text[j + 1]), neigK_right);
break;
case 'l':
tmp_count_bin += check(tolower(tmp_shifr_text[j - 1]), neigL_left);
tmp_count_bin += check(tolower(tmp_shifr_text[j + 1]), neigL_right);
break;
case 'm':
tmp_count_bin += check(tolower(tmp_shifr_text[j - 1]), neigM_left);
tmp_count_bin += check(tolower(tmp_shifr_text[j + 1]), neigM_right);
break;
case 'n':
tmp_count_bin += check(tolower(tmp_shifr_text[j - 1]), neigN_left);
tmp_count_bin += check(tolower(tmp_shifr_text[j + 1]), neigN_right);
break;
case 'o':
tmp_count_bin += check(tolower(tmp_shifr_text[j - 1]), neigO_left);
tmp_count_bin += check(tolower(tmp_shifr_text[j + 1]), neigO_right);
break;
case 'p':
tmp_count_bin += check(tolower(tmp_shifr_text[j - 1]), neigP_left);
tmp_count_bin += check(tolower(tmp_shifr_text[j + 1]), neigP_right);
break;
case 'q':
tmp_count_bin += check(tolower(tmp_shifr_text[j - 1]), neigQ_left);
tmp_count_bin += check(tolower(tmp_shifr_text[j + 1]), neigQ_right);
break;
case 'r':
tmp_count_bin += check(tolower(tmp_shifr_text[j - 1]), neigR_left);
tmp_count_bin += check(tolower(tmp_shifr_text[j + 1]), neigR_right);
break;
case 's':
tmp_count_bin += check(tolower(tmp_shifr_text[j - 1]), neigS_left);
tmp_count_bin += check(tolower(tmp_shifr_text[j + 1]), neigS_right);
break;
case 't':
tmp_count_bin += check(tolower(tmp_shifr_text[j - 1]), neigT_left);
tmp_count_bin += check(tolower(tmp_shifr_text[j + 1]), neigT_right);
break;
case 'u':
tmp_count_bin += check(tolower(tmp_shifr_text[j - 1]), neigU_left);
tmp_count_bin += check(tolower(tmp_shifr_text[j + 1]), neigU_right);
break;
case 'v':
tmp_count_bin += check(tolower(tmp_shifr_text[j - 1]), neigV_left);
tmp_count_bin += check(tolower(tmp_shifr_text[j + 1]), neigV_right);
break;
case 'w':
tmp_count_bin += check(tolower(tmp_shifr_text[j - 1]), neigW_left);
tmp_count_bin += check(tolower(tmp_shifr_text[j + 1]), neigW_right);
break;
case 'x':
tmp_count_bin += check(tolower(tmp_shifr_text[j - 1]), neigX_left);
tmp_count_bin += check(tolower(tmp_shifr_text[j + 1]), neigX_right);
break;
case 'y':
tmp_count_bin += check(tolower(tmp_shifr_text[j - 1]), neigY_left);
tmp_count_bin += check(tolower(tmp_shifr_text[j + 1]), neigY_right);
break;
case 'z':
tmp_count_bin += check(tolower(tmp_shifr_text[j - 1]), neigZ_left);
tmp_count_bin += check(tolower(tmp_shifr_text[j + 1]), neigZ_right);
break;
default:
break;
}
}
return tmp_count_bin;
}
int Max = 0;
char* kk = "helloworld";
int countRecords = 0;
int need_size(int want, int sizetext)
{
if (sizetext < want)
{
return sizetext;
}
else return want;
}
void show_result(unsigned char *tmp_key, int want, int sizetext, int currentMax)
{
int needsize = need_size(want, sizetext);
countRecords++;
printf("%d. \" \" = %d \n", countRecords, currentMax);
printf(" : ");
for (int j = 0; j < kSize; j++)//
/* ? , temp_key kSize , ?
-, , .
.
-, , . -*/
// , \0
{
printf("%c", tmp_key[j]);
}
printf("\n");
printf(": \n");
cur = addElem(tmp_key, kSize);
for (int j = 0; j < needsize; j++)//
{
printf("%c", tmp_shifr_text[j]);
}
printf("\n...\n");
printf("\n");
}
void BruteForce(unsigned char* key, unsigned char* hu, int size, int number, int sizetext)
{
if (size == 0)
{
/* , , ,
, . , ,
.*/
/*
if (strcmp(hu, kk) == 0)
{
printf("YES");
}
*/
int currentMax = analysis_bin(hu, sizetext);
if (currentMax > Max)
{
deletelem();
system("cls");
countRecords = 0;
show_result(hu, 100, sizetext, currentMax);
Max = currentMax;
}
// 2?
// ,
else if (Max - currentMax <= 2)
{
show_result(hu, 100, sizetext, currentMax);
}
return;
}
else
{
//count_for_Brut
for (int i = 0; i < count_for_Brut; i++)
{
hu[number] = key[number] ^ frequency[i];
if (is_it_char(hu[number]))
{
BruteForce(key, hu, size - 1, number + 1, sizetext);
}
}
}
}
void get_key(unsigned char* text, unsigned int size, unsigned char* key, unsigned int ksize)
{
//int t = clock();
//-. memset, , .
memset(keystat, 0, sizeof(keystat));
unsigned int read = ksize;
for (unsigned int start = 0; start < size;)
{
// size-start .
if (read > (size - start))
read = (size - start);
// ?
for (unsigned int i = 0; i < read; i++)
{
keystat[i][text[start + i]]++;
}
start += ksize;
}
for (int i = 0; i < ksize; i++)
{
unsigned int prev_max = 0;
unsigned int max = 0;
for (unsigned int i = 0; i < ksize; i++)
{
unsigned int v = 0;
unsigned int max = 0;
for (int j = 0; j < 256; j++)//razveeeeeertka
{
if (keystat[i][j] > max)
{
max = keystat[i][j];
v = j;
}
}
key[i] = v;
//key[i] ^= ' ';
}
char temp_key[50] = { 0 };//zapolnit pobache
kSize = ksize;
BruteForce(key, temp_key, ksize, 0, size);
if (ksize)
break;
}
//printf("\n%d", clock()-t);
}
void print(unsigned char* key, int length)
{
FILE* fin = fopen("output.txt", "rb"), *fout = fopen("finish.txt", "wb");
long long i = 0;
if (fin == NULL)
{
printf("Cant read file!\n");
return;
}
//for (int i = 0; i < length; i++)
//printf("%d - %c", key[i], key[i]);
int c = fgetc(fin);
while (c != EOF)
{
/*-. , . 0 lengt - 1. 0 1 2 3 0 1 2 3 0 1 2 3
if ( < lenght) . , */
/* ( 13 ).
*/
c ^= key[i % length];
i++;
fputc(c, fout);
c = fgetc(fin);
}
fseek(fin, 0, SEEK_SET);
fclose(fin);
fclose(fout);
}
int correct(char *key, int sizeText)
{
printf(" ?(0 - , 1 - )\n");
int menu = -1;
while (menu < 0)
{
scanf("%d", &menu);
// ?
if (menu < 0)
{
char c = '\0';
while (c != '\n')
{
c = getc(stdin);
}
}
if (menu != 0 && menu != 1)
{
menu = -1;
}
}
if (menu == 0)
{
return 0;
}
printf(" , , :\n");
char c = '\0';
scanf("%c", &c);
scanf("%c", &c);
int count = 0;
system("cls");
while (tmp_shifr_text[count] != c && count < 101)//izmenit
{
count++;
}
if (count == 101)
{
printf(" \n");
return 1;
}
//-. ? - , - .
int number = count % kSize;
char sim = key[number];
for (char i = 0; i < 127; i++)//mozno razvernyt
{
if (is_it_char(i))
{
key[number] = i;
int check = analysis_bin(key, sizeText);
if (Max - check < 5)
{
printf(" \" \" = %d \n", check);
printf(" : ");
for (int j = 0; j < kSize; j++)
{
printf("%c", key[j]);
}
printf("\n");
for (int j = 0; j < 100; j++)
{
printf("%c", tmp_shifr_text[j]);
}
printf("\n");
if (Max < check)
{
Max = check;
}
printf(" ?(0 - , 1 - )\n");
int anser = 0;
scanf("%d", &anser);
if (anser)
{
return 1;
}
}
}
}
// . char sim = key[number];, , . ?
key[number] = sim;
printf(" \n");
return 1;
}
int main()
{
SetConsoleCP(1251);
SetConsoleOutputCP(1251);
init();
FILE* fin = fopen("output.txt", "rb");
if (fin == NULL)
{
printf("Can't read file!\n");
return 0;
}
fseek(fin, 0, SEEK_END);
int size = ftell(fin);
fseek(fin, 0, SEEK_SET);
//unsigned char* shifr_text = (unsigned char*)malloc(size * sizeof(unsigned char));
shifr_text = (unsigned char*)malloc(size * sizeof(unsigned char));
tmp_shifr_text = (unsigned char*)malloc(size * sizeof(unsigned char));
unsigned int c = fgetc(fin), i = 0;
while (c != EOF)
{
shifr_text[i] = c;
i++;
c = fgetc(fin);
}
fclose(fin);
int t = 0;
float* keys_long = (float*)calloc(size / 2 + 1, sizeof(float));
kSize = key_size(shifr_text, size, keys_long);
int maxKsize = 0;
if (keys_long[kSize] < 0.045)
{
maxKsize = 13;
}
if (size > 300)
{
count_for_Brut = 5;
}
unsigned char key[50] = { 0 };
int n = menu();
while (n != 4)
{
switch (n)
{
case XOR:
xor_cypher();
return 0;
case GET_LENGTH_AND_KEY:
if (maxKsize)
{
t = clock();
for (kSize = 2; kSize < maxKsize; kSize++)
{
if (kSize < 10)
count_for_Brut = 7;
// else-if ?
else
{
if (kSize == 10)
count_for_Brut = 6;
else
{
if (kSize <= 12)
count_for_Brut = 2;
else
count_for_Brut = 1;
}
}
get_key(shifr_text, size, key, kSize);
}
}
else
{
count_for_Brut = 2;
get_key(shifr_text, size, key, kSize);
}
printf("\nTime: %d\n", clock() - t);
printf(" :\n");
int number = 0;
scanf("%d", &number);
search(number);
kSize = strlen(cur->key);
for (i = 0; i < kSize; i++)
{
key[i] = cur->key[i];
}
for (int j = 0; j < 100; j++)//
{
tmp_shifr_text[j] = shifr_text[j] ^ key[j % kSize];
}
while (correct(key, size));
case EXIT:
system("pause");
exit(0);
}
n = menu();
}
free(shifr_text);
free(tmp_shifr_text);
//free(key);
return 0;
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_handle_err.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: jjaniec <jjaniec@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2018/04/09 20:18:44 by jjaniec #+# #+# */
/* Updated: 2018/04/17 13:11:22 by jjaniec ### ########.fr */
/* */
/* ************************************************************************** */
#include <minishell.h>
/*
** Prints command not found error message
*/
void ft_err_cmd_not_found(t_msh_command *cmd)
{
ft_putstr_fd("minishell: command not found: ", 2);
ft_putstr_fd(cmd->prog_name, 2);
ft_putchar_fd(2, '\n');
ft_putchar_fd(1, '\n');
}
/*
** Search in st_mode if passed program is a directory or non executable
*/
void ft_handle_err_code(int err, char *prog_name)
{
ft_putstr_fd("minishell: ", 2);
ft_putstr_fd(prog_name, 2);
if (err == 1)
ft_putstr_fd(": is a directory\n", 2);
else if (err == 2)
ft_putstr_fd(": permission denied\n", 2);
}
int ft_handle_err(t_msh_command *cmd)
{
int err;
err = 0;
if (cmd && cmd->prog_stats)
{
if (S_ISDIR(cmd->prog_stats->st_mode))
ft_handle_err_code((err = 1), cmd->prog_name);
else if (!(cmd->prog_stats->st_mode & S_IXUSR))
ft_handle_err_code((err = 2), cmd->prog_name);
}
return (err);
}
|
C
|
//
// Created by Nylander on 09-04-2021.
//
#ifndef YUKON_PLAYINGCARD_H
#define YUKON_PLAYINGCARD_H
#include <stdbool.h>
#define PLAYING_CARD_NUM_SUITS 4
#define PLAYING_CARD_NUM_CARDS_IN_SUIT 13
#define PLAYING_CARD_MAX_LENGTH_AS_STRING 3
/**
* Represents a standard playing card
* @author Rasmus Nylander, s205418
*/
typedef struct playingCard* PlayingCard;
/**
* Creates a new PlayingCard with the specified suit and
* number and returns a pointer to it or NULL if memory
* allocation fails.
* @param suit the suit of the playing card
* @param number the number of the playing card
* @return A pointer to a new PlayingCard or NULL if
* memory allocation fails
* @author Rasmus Nylander, s205418
*/
PlayingCard newCard(unsigned char suit, unsigned char number);
int getCardSize(PlayingCard card);
bool isDifferentSuit(PlayingCard cardA, PlayingCard cardB);
/**
* Returns a boolean indicating whether the specified card is face up
* @param card the PlayingCard to determine if face up or not
* @return true if the card if face up
* @author Rasmus Nylander, s205418
*/
bool isFaceUp(PlayingCard card);
/**
* Sets whether the card the specified card faces up
* @param card the PlayingCard to turn face up or down
* @param up whether the card should face up
* @return true if the card changed
* @author Rasmus Nylander, s205418
*/
bool setFaceUp(PlayingCard card, bool up);
/**
* Flips the specified card. I.e. if it is facing up, after
* applying this function it will be facing down and vice versa
* @param card the PlayingCard to turn
* @return true if the card changed
* @author Rasmus Nylander, s205418
*/
bool flipPlayingCard(PlayingCard card);
/**
* Returns a string representation of the specified PlayingCard.
* @param card the PlayingCard to be represented as a string
* @return A new string representing the card or null if memory can't be allocated
* @author Rasmus Nylander, s205418
*/
char* playingCardToString(PlayingCard card);
/**
* Returns a string representation of the specified PlayingCard's suit
* @param card the PlayingCard whose suit it to be represented as a string
* @return a char representing the card's suit or null if memory can't be allocated
* @author Rasmus Nylander, s205418
*/
char* playingCardSuitToString(PlayingCard card);
/**
* Returns a string representation of the specified PlayingCard's number
* @param card the PlayingCard whose number it to be represented as a string
* @return a new string representing the card's number or null if memory can't be allocated
* @author Rasmus Nylander, s205418
*/
char* playingCardNumberToString(PlayingCard card);
#endif //YUKON_PLAYINGCARD_H
|
C
|
#include "primitives.h"
//****************************************************
// brdf.h. get the color of a certain pixel with given lights
//****************************************************
//given a point on the unit sphere, return the normal vector
Vector getNormal(Point p){
return Vector(p.x, p.y, p.z).normalize();
}
//given normalized light and normal vectors, return normal reflection vector
Vector getReflection(Vector l, Vector n){
l = l.normalize();
n = n.normalize();
double dp = l.dotProduct(n);
Vector v = (n * 2 * dp) - l;
return v.normalize();
}
//given point on sphere and location of light, return normal direction vector to light
Vector getLight(Point p, Point l){
Vector v = l.subtract(p);
return v.normalize();
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
typedef int element;
typedef struct linked_list {
element data;
struct linked_list* link;
}list;
typedef struct linked_list_base_queue {
list* front;
list* rear;
}queue;
void QInit(queue*);
int QIsEmpty(queue* que);
int QIsFull(queue* que);
void enqueue(queue *que, element);
element dequeue(queue*);
element QPeek(queue*);
void main() {
queue que1;
QInit(&que1);
enqueue(&que1, 1);
enqueue(&que1, 3);
enqueue(&que1, 5);
enqueue(&que1, 7);
enqueue(&que1, 9);
while (!QIsEmpty(&que1)) {
printf("%d ",dequeue(&que1));
}
}
void QInit(queue* que) {
que->front = NULL;
que->rear = NULL;
}
int QIsEmpty(queue* que) {
if (que->front == NULL) {
return 1;
}
else {
return 0;
}
}
void enqueue(queue* que, element data) {
list *new = (list*)malloc(sizeof(list));
new->data = data;
new->link = NULL;
if (que->front == NULL) {
que->front = new;
que->rear = new;
}
else {
que->rear->link = new;
que->rear = que->rear->link;
}
}
element dequeue(queue* que) {
element tmp;
if (que->front == NULL) {
return -109;
}
else {
tmp = que->front->data;
que->front = que->front->link;
return tmp;
}
}
|
C
|
/*program for bonus*/
#include <stdio.h>
int main(){
int bonus = 2500, cy , yoj , year ;
printf ("Enter the current year :");
scanf ("%d",&cy);
printf("Enter the year of joining :");
scanf("%d",&yoj);
year = cy - yoj;
if (year > 3 ) //if difference between current year and year of joining is greather than 3
printf ("\nbonus = %d \n", bonus );
return 0;
}
|
C
|
#ifndef _LIST_HASH_H_
#define _LIST_HASH_H_
#define RETURN_NULL(a) if(!a) return -1;
#define RETURN_NNULL(a) if(!a) return NULL;
#define SET_LIST(l, v, n) l->value = v; l->next = n;
#define SET_HASH(h, k, v, n) h->key = k; h->value =v; h->next = n;
typedef struct list list;
typedef struct hashmap hashmap;
struct list {
void *value;
list *next;
};
struct hashmap {
void *key;
void *value;
void *next;
};
list* list_create();
int list_free(list *head);
int list_empty(list *head);
int list_is_empty(list *head);
int list_addtofront(list *head, void *value);
int list_addtoend(list *head, void *value);
int list_remove(list *head, void *value);
int list_length(list *head);
int list_contains(list *map, void *key);
int list_contains_fun(list *map, void *key, bool (*fun)(void *, void*));
int list_get_index_fun(list *map, void *key, bool (*fun)(void *, void*));
void *list_get_elem(list *head, int index);
void list_print_str(list *head);
void *list_get_last(list *head);
void *get_from_end(list *head, int index);
hashmap* hashmap_create();
int hashmap_free(hashmap *map);
int hashmap_add(hashmap *map, void *key, void *value);
int hashmap_remove(hashmap *map, void *key);
int hashmap_contains(hashmap *map, void *key);
void* hashmap_get(hashmap *map, void *key);
void hashmap_empty(hashmap *map);
void hashmap_print(hashmap *map);
int hashmap_is_empty(hashmap *map);
hashmap* hashmap_pop(hashmap *map);
hashmap* hashmap_pop_last(hashmap *map);
#endif
|
C
|
#pragma once
struct ParticleDirection {
float x;
float y;
float z;
float length;
ParticleDirection(float x = 0, float y = 0, float z = 0, bool norm=false)
{
_init(x, y, z, norm);
}
ParticleDirection(CParticleF& from, CParticleF& to, bool norm = false){
_init(to.m_X - from.m_X, to.m_Y - from.m_Y, to.m_Z - from.m_Z, norm);
}
private:
void _init(float x, float y, float z, bool norm)
{
this->x = x;
this->y = y;
this->z = z;
length = sqrt(x*x + y*y + z*z);
if (norm)
{
this->x /= length;
this->y /= length;
this->z /= length;
}
}
};
|
C
|
#include "shared.h"
#include <stdlib.h>
#include <string.h>
#include <pthread.h>
#include <netdb.h>
#include <stdarg.h>
// All the things that could go wrong
enum ExitCodes {
EXIT_ARGS = 1,
EXIT_OPEN_SINISTER_FILE = 2,
EXIT_SINISTER_FILE_CONTENTS = 3,
EXIT_OPEN_TEAM_FILE = 4,
EXIT_TEAM_FILE_CONTENTS = 5,
EXIT_INVALID_PORT = 6,
EXIT_CONNECT_CONTROLLER = 7,
EXIT_CONNECT_TEAM = 8,
EXIT_CONTROLLER_DISCO = 9,
EXIT_TEAM_DISCO = 10,
EXIT_BAD_MESSAGE = 19,
EXIT_SYSTEM = 20
};
// Messages that can be received from another team
typedef enum TeamMessages {
FIGHTMEIRL,
HAVEATYOU,
ISELECTYOU,
ATTACK,
END // Used for EOF
} TeamMsgs;
// Messages that can be received from the controller
typedef enum ControllerMessages {
SINISTER,
BATTLE,
GAMEOVERMAN,
WHERENOW
} ControllerMsgs;
/**
* Adds the given narrative to game's array of narratives. Thread-safe.
*/
void add_narrative(Game *game, char *narrative) {
sem_wait(&game->narrativeLock);
game->numNarratives++;
game->narratives = realloc(game->narratives, sizeof(char *) *
game->numNarratives);
game->narratives[game->numNarratives - 1] = narrative;
sem_post(&game->narrativeLock);
}
/**
* Appends the format string to the narrative, replacing underscores with
* spaces and increasing space for the narrative if necessary.
*/
void append_string(char **narrative, const char *format, ...) {
int n, bufferSize = 40;
char *segment = NULL;
va_list args;
// reallocate size for format string until args fit
while (true) {
segment = realloc(segment, sizeof(char) * bufferSize);
va_start(args, format);
n = vsnprintf(segment, bufferSize, format, args);
va_end(args);
if (n < bufferSize) {
break; // formatted string fit into memory. All is well.
}
bufferSize = n + 1;
}
// append to narrative, replacing underscores with spaces
for (int i = 0; i < strlen(segment); i++) {
if (segment[i] == '_') {
segment[i] = ' ';
}
}
*narrative = realloc(*narrative, sizeof(char) * (strlen(*narrative) +
strlen(segment) + 1));
strcat(*narrative, segment);
free(segment);
}
/**
* Returns the effectiveness of the attack against the opponent.
* Assumes attack and opponent are valid.
*/
enum Effectiveness get_effectiveness(Attack *attack, Agent *opponent) {
for (int i = 0; i < attack->type->numLower; i++) {
if (strcmp(attack->type->lower[i]->name, opponent->type->name) == 0) {
return LOW;
}
}
for (int i = 0; i < attack->type->numHigher; i++) {
if (strcmp(attack->type->higher[i]->name, opponent->type->name) == 0) {
return HIGH;
}
}
return NORMAL;
}
/**
* Send member's attack on opponent to the write stream, and add to narrative.
* Increments the member's attack
*/
void attack(char **narrative, Game *game, FILE *write, Member *member,
Member *opponent) {
// message opposing team
Attack *attack = member->nextAttack->attack;
fprintf(write, "attack %s %s\n", member->agent->name, attack->name);
fflush(write);
// get effectiveness and update narrative
int effectiveness = get_effectiveness(attack, opponent->agent);
opponent->health -= effectiveness;
append_string(narrative, "%s uses %s: %s", member->agent->name,
attack->name, attack->type->effectiveness[effectiveness - 1]);
if (opponent->health <= 0) {
append_string(narrative, " - %s was eliminated.",
opponent->agent->name);
}
append_string(narrative, "\n");
// increment attack
member->nextAttack = member->nextAttack->next;
}
/**
* Exits the program with the given status and its corresponding error message
*/
void exit_game(int status) {
char *message;
switch (status) {
case EXIT_ARGS:
message = "Usage: 2310team controllerport teamfile\n "
"or: 2310team wait teamfile sinisterfile\n "
"or: 2310team challenge teamfile sinisterfile targetport";
break;
case EXIT_OPEN_TEAM_FILE:
message = "Unable to access team file";
break;
case EXIT_TEAM_FILE_CONTENTS:
message = "Error reading team file";
break;
case EXIT_OPEN_SINISTER_FILE:
message = "Unable to access sinister file";
break;
case EXIT_SINISTER_FILE_CONTENTS:
message = "Error reading sinister file";
break;
case EXIT_INVALID_PORT:
message = "Invalid port number";
break;
case EXIT_CONNECT_CONTROLLER:
message = "Unable to connect to controller";
break;
case EXIT_CONNECT_TEAM:
message = "Unable to connect to team";
break;
case EXIT_CONTROLLER_DISCO:
message = "Unexpected loss of controller";
break;
case EXIT_TEAM_DISCO:
message = "Unexpected loss of team";
break;
case EXIT_BAD_MESSAGE:
message = "Protocol error";
break;
case EXIT_SYSTEM:
message = "System error";
break;
default:
message = "Well, this is awkward.";
}
fprintf(stderr, "%s\n", message);
exit(status);
}
/**
* Populates line with the next line read from file.
* length is line's initial size. line is reallocated space if needed.
* Exits with controller disconnected or protocol error if invalid message.
*/
ControllerMsgs read_controller_msg(char *line, int length, FILE *file) {
read_line(line, length, file);
if (strlen(line) == 0) {
exit_game(EXIT_CONTROLLER_DISCO);
}
char *type = get_token(line, ' ');
ControllerMsgs result = -1;
if (strcmp(type, "sinister") == 0) {
result = SINISTER;
} else if (strcmp(type, "battle") == 0) {
result = BATTLE;
} else if (strcmp(type, "gameoverman") == 0) {
result = GAMEOVERMAN;
} else if (strcmp(type, "wherenow?") == 0) {
result = WHERENOW;
} else {
exit_game(EXIT_BAD_MESSAGE);
}
free(type);
return result;
}
/**
* Populates line with the next line read from file, up to the given length.
* Exits with protocol error if invalid message.
* Calling thread exits if EOF is found (Sends "disco" to controller first if
* we're in simulation mode)
*/
TeamMsgs read_team_msg(char *line, int length, FILE *file, Game *game) {
read_line(line, length, file);
if (strlen(line) == 0) {
if (game->simulation) {
fprintf(game->write, "disco\n"); // team disconnected in sim mode
fflush(game->write);
pthread_exit(0);
} else {
exit_game(EXIT_TEAM_DISCO); // team disconnected in 1v1 mode
}
}
char *type = get_token(line, ' ');
TeamMsgs result = -1;
if (strcmp(type, "fightmeirl") == 0) {
result = FIGHTMEIRL;
} else if (strcmp(type, "haveatyou") == 0) {
result = HAVEATYOU;
} else if (strcmp(type, "iselectyou") == 0) {
result = ISELECTYOU;
} else if (strcmp(type, "attack") == 0) {
result = ATTACK;
} else {
exit_game(EXIT_BAD_MESSAGE);
}
free(type);
return result;
}
/**
* Returns a team member whose agent is specified in an "iselectyou" message
* read from opposing->read.
* Exits with protocol error if invalid message.
*/
Member *get_selected_opponent(Game *game, Team *opposing, char **narrative) {
Member *opponent = malloc(sizeof(Member));
opponent->health = MAX_HEALTH;
// read iselectyou message
char *message = malloc(sizeof(char) * BUFFER);
if (read_team_msg(message, BUFFER, opposing->read, game) != ISELECTYOU) {
exit_game(EXIT_BAD_MESSAGE); // not iselectyou
}
// get agent
char *agentName = get_token(&message[strlen("iselectyou ")], '\0');
free(message);
if ((opponent->agent = get_agent(game, agentName)) == NULL) {
exit_game(EXIT_BAD_MESSAGE);
}
free(agentName);
// add to narrative
append_string(narrative, "%s chooses %s\n", opposing->name,
opponent->agent->name);
return opponent;
}
/**
* Sends a message to opposition that this team member has been selected.
* Adds to narrative.
* Returns a copy of the given team member with full health.
*/
Member *select_member(char **narrative, FILE *opposition, char *teamName,
Member *member) {
Member *copy = malloc(sizeof(Member));
copy->agent = member->agent;
copy->health = MAX_HEALTH;
copy->nextAttack = member->firstAttack;
fprintf(opposition, "iselectyou %s\n", copy->agent->name);
fflush(opposition);
append_string(narrative, "%s chooses %s\n", teamName, member->agent->name);
return copy;
}
/**
* Reads and processes an attack from the opposing team.
* Exits with protocol error if invalid information received.
*/
void get_attacked(Game *game, char **narrative, Member *member,
Member *opponent, Team *opposing) {
char *message = malloc(sizeof(char) * BUFFER);
if (read_team_msg(message, BUFFER, opposing->read, game) != ATTACK) {
exit_game(EXIT_BAD_MESSAGE); // attack message not received
}
// figure out what attack is being used on us
char *agentName = get_token(&message[strlen("attack ")], ' ');
Attack *attack = get_attack(game, &message[strlen("attack ") +
strlen(opponent->agent->name)]);
if (attack == NULL || !legal_attack(opponent->agent, attack) ||
strcmp(agentName, opponent->agent->name) != 0) {
// invalid attack, invalid agent, or illegal attack for that agent
exit_game(EXIT_BAD_MESSAGE);
}
free(agentName);
// update our stats and add to narrative
int effectiveness = get_effectiveness(attack, member->agent);
member->health -= effectiveness;
append_string(narrative, "%s uses %s: %s", opponent->agent->name,
attack->name, attack->type->effectiveness[effectiveness - 1]);
if (member->health <= 0) {
append_string(narrative, " - %s was eliminated.", member->agent->name);
}
append_string(narrative, "\n");
free(message);
}
/**
* Battles game->team and opposing team. goFirst should be true when game->team
* is to attack first, false otherwise. Battle story added to narrative.
* Calling thread exits with protocol error if bad message found; or exits if
* opposing team disconnects (with status 0 in sim mode, 10 otherwise).
*/
void battle(char **narrative, Game *game, Team *opposing, bool goFirst) {
char *msg = malloc(sizeof(char) * BUFFER);
Team *loser = game->team;
Member *opponent;
if (!goFirst) {
opponent = get_selected_opponent(game, opposing, narrative);
}
// i is the index of our team's agent, j is index of opposing agent
for (int i = 0, j = 0; i < MAX_TEAM_PLAYERS && j < MAX_TEAM_PLAYERS; ++i) {
Member *member = select_member(narrative, opposing->write,
game->team->name, game->team->members[i]);
// first round only
if (i == 0) {
if (!goFirst) {
get_attacked(game, narrative, member, opponent, opposing);
} else {
opponent = get_selected_opponent(game, opposing, narrative);
}
}
// fight until our agent dies or whole opposing team dies
while (member->health > 0) {
attack(narrative, game, opposing->write, member, opponent);
if (opponent->health <= 0) {
if (++j == MAX_TEAM_PLAYERS) {
loser = opposing;
break;
}
free(opponent);
opponent = get_selected_opponent(game, opposing, narrative);
}
get_attacked(game, narrative, member, opponent, opposing);
}
free(member);
}
free(msg);
append_string(narrative, "Team %s was eliminated.\n", loser->name);
add_narrative(game, *narrative);
}
/**
* Goes through wait mode. Game narrative is added to game->narratives.
* Calling thread exits if a protocol error or team disconnected error occurs.
*/
void be_challenged(Game *game, Team *opposing) {
FILE *read = opposing->read;
char *msg = malloc(sizeof(char) * BUFFER);
char *narrative = malloc(sizeof(char));
narrative[0] = '\0';
// setup communication
if (read_team_msg(msg, BUFFER, read, game) != FIGHTMEIRL) {
exit_game(EXIT_BAD_MESSAGE);
}
opposing->name = get_token(&msg[strlen("fightmeirl ")], 0);
append_string(&narrative, "%s has a difference of opinion\n", opposing->name);
fprintf(opposing->write, "haveatyou %s\n", game->team->name);
fflush(opposing->write);
battle(&narrative, game, opposing, false);
}
/**
* For qsorting strings in lexicographical order
*/
int sort_strings(const void *a, const void *b) {
return strcmp(*(char **)a, *(char **)b);
}
/**
* Prints the game's narratives list in lexicographical order.
* Frees narratives and resets numNarratives to 0.
*/
void print_and_free_narratives(Game *game) {
qsort(game->narratives, game->numNarratives, sizeof(char *), sort_strings);
for (int i = 0; i < game->numNarratives; i++) {
printf("%s", game->narratives[i]);
free(game->narratives[i]);
}
fflush(stdout);
game->numNarratives = 0;
}
/**
* Challenges the opposing team and adds the narrative to game->narratives upon
* completion.
* Exits if a bad message is received or if opposing team disconnects.
*/
void challenge(Game *game, Team *opposing) {
char *narrative = malloc(sizeof(char));
narrative[0] = '\0';
char *message = malloc(sizeof(char) * BUFFER);
// set-up communication
fprintf(opposing->write, "fightmeirl %s\n", game->team->name);
fflush(opposing->write);
if (read_team_msg(message, BUFFER, opposing->read, game) != HAVEATYOU) {
exit_game(EXIT_BAD_MESSAGE);
}
opposing->name = get_token(&message[strlen("haveatyou ")], '\0');
append_string(&narrative, "%s has a difference of opinion\n",
opposing->name);
free(message);
battle(&narrative, game, opposing, true);
}
/**
* Runs wait mode, then either prints the resulting narrative or sends
* "donefighting" to the controller if in simulation mode.
* args should be a ThreadGame pointer.
* Calling thread exits with NULL on success.
* Exits if a bad message is received or if opposing team disconnects.
*/
void *wait_wrapper(void *args) {
ThreadGame *params = (ThreadGame *)args;
be_challenged(params->game, params->opposing);
if (params->game->simulation) {
fprintf(params->game->write, "donefighting\n");
fflush(params->game->write);
} else {
print_and_free_narratives(params->game);
}
pthread_exit(NULL);
}
/**
* Starts listening on a port, and prints port if necessary. Accepts one or
* multiple connections depending on if game is in simulation mode.
* Runs through a battle with each connected team.
* Exits if bad message received or if opposing team disconnects.
* args should be a Game *.
*/
void *enter_wait_mode(void *args) {
Game *game = (Game *)args;
// start listening, and print port if necessary
int fd = open_listen(&game->team->port);
if (fd < 0) {
exit_game(EXIT_SYSTEM);
}
if (!game->simulation) {
printf("%d\n", game->team->port);
fflush(stdout);
}
while (true) {
ThreadGame *params = malloc(sizeof(ThreadGame));
Team *opposing = malloc(sizeof(Team));
// accept a connection and spawn another thread to battle
if (accept_connection(fd, &opposing->read, &opposing->write) < 0) {
exit_game(EXIT_CONNECT_TEAM);
}
params->opposing = opposing;
params->game = game;
pthread_t waiter;
pthread_create(&waiter, NULL, wait_wrapper, (void *)params);
pthread_detach(waiter);
if (!game->simulation) {
pthread_exit(0); // stop this thread if we're doing one battle only
}
}
}
/**
* Connects to localhost on the given port. read and write will be set up to
* communicate over the resulting file descriptor.
* Returns non-zero on error.
*/
int connect_to_port(int port, FILE **read, FILE **write) {
struct sockaddr_in socketAddr;
struct addrinfo *addressInfo;
getaddrinfo("localhost", NULL, NULL, &addressInfo);
struct in_addr *ipAddress =
&(((struct sockaddr_in *)(addressInfo->ai_addr))->sin_addr);
int fd = socket(AF_INET, SOCK_STREAM, 0);
if (fd < 0) {
exit_game(EXIT_SYSTEM);
}
// attempt connection
socketAddr.sin_family = AF_INET;
socketAddr.sin_port = htons(port);
socketAddr.sin_addr.s_addr = ipAddress->s_addr;
if (connect(fd, (struct sockaddr *)&socketAddr, sizeof(socketAddr)) < 0) {
return -1;
}
*read = fdopen(fd, "r");
*write = fdopen(fd, "w");
return fd;
}
/**
* Starts a challenge on the given port.
* Can exit with protocol error, invalid port, or team disconnected on error.
*/
void enter_challenge_mode(Game *game, int port) {
// check port validity
if (!valid_port(port)) {
exit_game(EXIT_INVALID_PORT);
}
// set up connection to opposition
Team *opposing = malloc(sizeof(Team));
if (connect_to_port(port, &opposing->read, &opposing->write) < 0) {
exit_game(EXIT_CONNECT_TEAM);
}
challenge(game, opposing);
}
/**
* Starts a challenge thread on the specified port, then sends "donefighting"
* to the controller and exits the calling thread.
* args is a ThreadGame *.
* Can exit with protocol error, invalid port, or team disconnected on error.
*/
void *spawn_challenge_thread(void *args) {
ThreadGame *params = (ThreadGame *)args;
enter_challenge_mode(params->game, params->port);
fprintf(params->game->write, "donefighting\n");
fflush(params->game->write);
pthread_exit(0);
}
/**
* Populates member's attacks with attacks given in the line.
* Attacks should be space-separated with no leading or trailing space.
* Exits with invalid team file contents if attacks invalid.
*/
void read_team_attacks(char *line, Game *game, Member *member) {
int pos = 0;
if (pos >= strlen(line)) {
exit_game(EXIT_TEAM_FILE_CONTENTS); // no attacks
}
// read attacks until we have reached the end of the line
AttackNode *tail;
while (pos < strlen(line)) {
// get attack
char *attackName = get_token_update_pos(line, ' ', &pos);
Attack *attack = get_attack(game, attackName);
free(attackName);
if (attack == NULL) {
exit_game(EXIT_TEAM_FILE_CONTENTS); // invalid attack
} else if (!legal_attack(member->agent, attack)) {
exit_game(EXIT_TEAM_FILE_CONTENTS); // not legal attack
}
// Create attack node and add it to member's list
AttackNode *attackNode = malloc(sizeof(AttackNode));
attackNode->attack = attack;
if (member->firstAttack == NULL) {
member->firstAttack = attackNode;
} else {
tail->next = attackNode;
}
tail = attackNode;
}
// make members attacks circularly linked
tail->next = member->firstAttack;
member->nextAttack = member->firstAttack;
}
/**
* Reads the agents and their attacks from the given team file, and populates
* game struct with this information.
* Exits with invalid team file contents if bad format or inconsistent with
* sinister file.
*/
void read_agents(FILE *file, Game *game) {
for (int i = 0; i < MAX_TEAM_PLAYERS; i++) {
char *line = malloc(sizeof(char) * BUFFER);
read_line(line, BUFFER, file);
if (line == NULL || strlen(line) == 0) {
exit_game(EXIT_TEAM_FILE_CONTENTS); // empty line or EOF
}
// Set up agent
char *agentName = get_token(line, ' ');
Agent *agent = get_agent(game, agentName);
free(agentName);
if (agent == NULL) {
exit_game(EXIT_TEAM_FILE_CONTENTS); // invalid agent
}
// add member and their attacks to team members
Member *member = malloc(sizeof(Member));
game->team->members[i] = member;
member->agent = agent;
member->firstAttack = NULL;
int pos = strlen(agent->name) + 1;
read_team_attacks(&line[pos], game, member);
free(line);
}
}
/**
* Reads a line of directions from the given file, and adds these to team data.
* Exits with invalid team file contents if invalid characters or format.
*/
void read_directions(FILE *file, Team *team) {
int c;
Direction *tail;
while ((c = fgetc(file)) != EOF) {
// look for letter
if (c == 'N' || c == 'S' || c == 'E' || c == 'W') {
Direction *d = malloc(sizeof(Direction));
d->direction = c;
d->next = NULL;
if (team->nextMove == NULL) {
team->nextMove = d;
} else {
tail->next = d;
}
tail = d;
} else {
exit_game(EXIT_TEAM_FILE_CONTENTS); // invalid char
}
// look for space
c = fgetc(file);
if (c != ' ' && c != EOF && c != '\n') {
exit_game(EXIT_TEAM_FILE_CONTENTS); // unexpected char (not space)
}
}
// make directions circularly linked
tail->next = team->nextMove;
}
/**
* Populates the given game struct with team info.
*/
void read_team_file(Game *game, char *filename) {
FILE *file = fopen(filename, "r");
if (file == NULL) {
exit_game(EXIT_OPEN_TEAM_FILE); // cannot open file
}
// read teamname, agents, attacks
char *name = malloc(sizeof(char) * BUFFER);
read_line(name, BUFFER, file);
if (name == NULL || strlen(name) == 0) {
exit_game(EXIT_TEAM_FILE_CONTENTS);
}
game->team = new_team(name);
read_agents(file, game);
// get coords
char coords[BUFFER];
if (fgets(coords, BUFFER, file) == NULL) {
exit_game(EXIT_TEAM_FILE_CONTENTS); // unexpected EOF
}
int pos = 0;
game->team->pos = get_coords(coords, '\n', &pos);
if (game->team->pos->x < 0 || game->team->pos->y < 0) {
exit_game(EXIT_TEAM_FILE_CONTENTS); // invalid coords
}
// get directions
read_directions(file, game->team);
if (fgetc(file) != EOF) {
exit_game(EXIT_TEAM_FILE_CONTENTS); // too much file
}
}
/**
* Populates game with the data from the given sinister and team files.
* Exits with Sinister or Team file errors if invalid data found.
*/
void parse_game_files(Game *game, FILE *sinister, char *teamFilename) {
if (read_sinister_file(game, sinister) != 0) {
exit_game(EXIT_SINISTER_FILE_CONTENTS);
}
read_team_file(game, teamFilename);
}
/**
* Runs through set-up communication with the controller.
* Can exit with protocol error, sinister file contents error, team file
* errors, or controller disconnected error.
*/
void set_up_simulation(Game *game, char *teamFile) {
char *message = malloc(sizeof(char) * BUFFER);
// check for "sinister" message and read sinister file and team file
if (read_controller_msg(message, BUFFER, game->read) != SINISTER) {
exit_game(EXIT_BAD_MESSAGE);
}
free(message);
parse_game_files(game, game->read, teamFile);
game->team->port = 0;
// start waiting for connections
pthread_t waiter;
pthread_create(&waiter, NULL, enter_wait_mode, (void *)game);
pthread_detach(waiter);
// let controller know we're ready once we're accepting connections
while (game->team->port == 0) {
}
fprintf(game->write, "iwannaplay %d %d %s %d\n", game->team->pos->x,
game->team->pos->y, game->team->name, game->team->port);
fflush(game->write);
}
/**
* Runs through a simulation, communicating with the controller and other teams
* as necessary. Prints narratives at the end of each round.
* Exits normally if gameover received.
* Exits with bad message if invalid message from controller or team received.
* Exits with controller disconnected if unable to read from controller.
*/
void run_simulation(Game *game) {
char *message = malloc(sizeof(char) * BUFFER);
Team *team = game->team;
while (true) {
ControllerMsgs type = read_controller_msg(message, BUFFER, game->read);
if (type == BATTLE) {
int pos = strlen("battle ");
if (pos >= strlen(message)) {
exit_game(EXIT_BAD_MESSAGE);
}
// get and print our coords
free(team->pos);
team->pos = get_coords(message, ' ', &pos);
if (team->pos->x < 0 || team->pos->y < 0) {
exit_game(EXIT_BAD_MESSAGE);
}
printf("Team is in zone %d %d\n", team->pos->x, team->pos->y);
fflush(stdout);
// start a challenge mode thread for each port
while (pos < strlen(message)) {
char *portVal = get_token_update_pos(message, ' ', &pos);
ThreadGame *params = malloc(sizeof(ThreadGame));
params->port = number(portVal);
params->game = game;
free(portVal);
pthread_t challenger;
pthread_create(&challenger, NULL, spawn_challenge_thread,
(void *)params);
pthread_detach(challenger);
}
} else if (type == GAMEOVERMAN) {
print_and_free_narratives(game);
exit(0); // all good
} else if (type == WHERENOW) {
print_and_free_narratives(game);
fprintf(game->write, "travel %c\n", team->nextMove->direction);
fflush(game->write);
team->nextMove = team->nextMove->next;
continue;
} else {
exit(EXIT_BAD_MESSAGE);
}
}
}
int main(int argc, char **argv) {
// check num args and usage
if (argc < 3 || argc > 5) {
exit_game(EXIT_ARGS);
} else if (argc > 3 && !(strcmp(argv[1], "wait") == 0 ||
strcmp(argv[1], "challenge") == 0)) {
exit_game(EXIT_ARGS);
}
ignore_sigpipe();
Game *game = new_game();
char *teamFilename = argv[2];
if (argc == 3) {
// simulation mode
int port = number(argv[1]);
if (!valid_port(port)) {
exit_game(EXIT_INVALID_PORT);
}
if (connect_to_port(port, &game->read, &game->write) < 0) {
exit_game(EXIT_CONNECT_CONTROLLER);
}
game->simulation = true;
set_up_simulation(game, teamFilename);
run_simulation(game);
} else {
// parse sinister and team files
FILE *sinister = fopen(argv[3], "r");
if (sinister == NULL) {
exit_game(EXIT_OPEN_SINISTER_FILE);
}
parse_game_files(game, sinister, teamFilename);
if (fgetc(sinister) != -1) {
exit_game(EXIT_SINISTER_FILE_CONTENTS); // extra junk in sinister
}
game->simulation = false;
// enter wait or challenge mode
if (argc == 4) {
enter_wait_mode((void *)game);
} else if (argc == 5) {
enter_challenge_mode(game, number(argv[4]));
print_and_free_narratives(game);
}
}
pthread_exit(0);
}
|
C
|
#include<stdio.h>
int main()
{
int a1,b1,c1,d1;
int a2,b2,c2,d2;
int a3,b3,c3,d3;
int a4,b4,c4,d4;
int a5,b5,c5,d5;
int tot1,tot2,tot3,tot4,tot5;
scanf("%d %d %d %d",&a1,&b1,&c1,&d1);
tot1=a1+b1+c1+d1;
scanf("%d %d %d %d",&a2,&b2,&c2,&d2);
tot2=a2+b2+c2+d2;
scanf("%d %d %d %d",&a3,&b3,&c3,&d3);
tot3=a3+b3+c3+d3;
scanf("%d %d %d %d",&a4,&b4,&c4,&d4);
tot4=a4+b4+c4+d4;
scanf("%d %d %d %d",&a5,&b5,&c5,&d5);
tot5=a5+b5+c5+d5;
if(tot1>tot2 && tot1>tot3 && tot1>tot4 && tot1>tot5)
{
printf("1 %d",tot1);
}
else if(tot2>tot1 && tot2>tot3 && tot2>tot4 && tot2>tot5)
{
printf("2 %d",tot2);
}
else if(tot3>tot1 && tot3>tot2 && tot3>tot4 && tot3>tot5)
{
printf("3 %d", tot3);
}
else if(tot4>tot1 && tot4>tot2 && tot4>tot3 && tot4>tot5)
{
printf("4 %d", tot4);
}
else
{
printf("5 %d", tot5);
}
return 0;
}
|
C
|
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
void stringSwap(char *s1,char *s2){ //Function to swap two strings.
char t[10];
strcpy(t,s1);
strcpy(s1,s2);
strcpy(s2,t);
}
int main(void) {
char s[100][100];
int arrayLength=0;
while(scanf("%s",s[arrayLength++])>0); //string array input is obtained
for(int i=0;i<arrayLength;i++){
for(int j=i+1;j<arrayLength;j++){
if(s[i][0]=='-'&&s[j][0]=='-'){
if(strlen(s[i])<strlen(s[j])){
stringSwap(s[i],s[j]);
}
else if(strlen(s[i])==strlen(s[j])&&(strcmp(s[i],s[j])<strcmp(s[j],s[i]))){
stringSwap(s[i],s[j]);
}
}
else if(s[i][0]!='-'&&s[j][0]=='-'){
stringSwap(s[i],s[j]);
}
else if((strlen(s[i])>strlen(s[j]))&&s[i][0]!='-'&&s[j][0]!='-'){
stringSwap(s[i],s[j]);
}
else if(strlen(s[i])==strlen(s[j])){
if(strcmp(s[i],s[j])>strcmp(s[j],s[i])){
stringSwap(s[i],s[j]);
}
}
}
}
for(int i=0;i<arrayLength;i++){
printf("%s ",s[i]);
}
return 0;
}
|
C
|
/*****************************************************************************
* Licensed to Qualys, Inc. (QUALYS) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* QUALYS licenses this file to You 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.
****************************************************************************/
#ifndef _IA_EUDOXUS_BITS_H_
#define _IA_EUDOXUS_BITS_H_
/**
* @file
* @brief IronAutomata — Eudoxus Bit Manipulation
*
* @author Christopher Alfeld <calfeld@qualys.com>
*/
#include <stdbool.h>
#include <stdint.h>
/**
* @defgroup IronAutomataBits Bits
* @ingroup IronAutomata
*
* Bit manipulation routines.
*
* @{
*/
#ifdef __cplusplus
extern "C" {
#endif
/**
* Return @a i th bit of a uint8_t.
*
* @param[in] byte Byte to read bit of.
* @param[in] i Index of bit to read.
* @return true iff @a i th bit of @a byte is 1.
*/
static
inline
bool ia_bit8(uint8_t byte, int i)
{
return (byte & (1 << i)) != 0;
}
/**
* Return @a i th bit of a uint16_t.
*
* @param[in] word Word to read bit of.
* @param[in] i Index of bit to read.
* @return true iff @a i th bit of @a word is 1.
*/
static
inline
bool ia_bit16(uint16_t word, int i)
{
return (word & (1 << i)) != 0;
}
/**
* Return @a i th bit of a uint32_t.
*
* @param[in] word Word to read bit of.
* @param[in] i Index of bit to read.
* @return true iff @a i th bit of @a word is 1.
*/
static
inline
bool ia_bit32(uint32_t word, int i)
{
return (word & (1 << i)) != 0;
}
/**
* Return @a i th bit of a uint64_t.
*
* @param[in] word Word to read bit of.
* @param[in] i Index of bit to read.
* @return true iff @a i th bit of @a word is 1.
*/
static
inline
bool ia_bit64(uint64_t word, int i)
{
return (word & ((uint64_t)1 << i)) != 0;
}
/**
* Returns @a i th bit of a byte sequence.
*
* This function is for variable length byte sequences. For fixed multiple
* of two bytes, e.g., uint32_t, prefer other methods.
*
* @param[in] bytes Bytes to read from.
* @param[in] i Index of bit to read.
* @return true iff @a i th bit of @a bytes is 1.
*/
static
inline
bool ia_bitv(const uint8_t *bytes, int i)
{
return ia_bit8(bytes[i / 8], i % 8);
}
/**
* Returns @a i th bit of a 64 bit word sequence.
*
* @param[in] words Bytes to read from.
* @param[in] i Index of bit to read.
* @return true iff @a i th bit of @a bytes is 1.
*/
static
inline
bool ia_bitv64(const uint64_t *words, int i)
{
return ia_bit64(words[i / 64], i % 64);
}
/**
* Return @a byte with @a i th bit set to 1.
*
* @param[in] byte Byte to set bit of.
* @param[in] i Bit to set.
* @return @a byte with @a i th bit set to 1.
*/
static
inline
uint8_t ia_setbit8(uint8_t byte, int i)
{
return byte | (1 << i);
}
/**
* Return @a byte with @a i th bit set to 0.
*
* @param[in] byte Byte to unset bit of.
* @param[in] i Bit to unset.
* @return @a byte with @a i th bit set to 0.
*/
static
inline
uint8_t ia_unsetbit8(uint8_t byte, int i)
{
return byte & ~(1 << i);
}
/**
* Return @a word with @a i th bit set to 1.
*
* @param[in] word Word to set bit of.
* @param[in] i Bit to set.
* @return @a word with @a i th bit set to 1.
*/
static
inline
uint16_t ia_setbit16(uint16_t word, int i)
{
return word | (1 << i);
}
/**
* Return @a word with @a i th bit set to 0.
*
* @param[in] word Word to unset bit of.
* @param[in] i Bit to unset.
* @return @a word with @a i th bit set to 0.
*/
static
inline
uint16_t ia_unsetbit16(uint16_t word, int i)
{
return word & ~(1 << i);
}
/**
* Return @a word with @a i th bit set to 1.
*
* @param[in] word Word to set bit of.
* @param[in] i Bit to set.
* @return @a word with @a i th bit set to 1.
*/
static
inline
uint32_t ia_setbit32(uint32_t word, int i)
{
return word | (1 << i);
}
/**
* Return @a word with @a i th bit set to 0.
*
* @param[in] word Word to unset bit of.
* @param[in] i Bit to unset.
* @return @a word with @a i th bit set to 0.
*/
static
inline
uint32_t ia_unsetbit32(uint32_t word, int i)
{
return word & ~(1 << i);
}
/**
* Return @a word with @a i th bit set to 1.
*
* @param[in] word Word to set bit of.
* @param[in] i Bit to set.
* @return @a word with @a i th bit set to 1.
*/
static
inline
uint64_t ia_setbit64(uint64_t word, int i)
{
return word | ((uint64_t)1 << i);
}
/**
* Return @a word with @a i th bit set to 0.
*
* @param[in] word Word to unset bit of.
* @param[in] i Bit to unset.
* @return @a word with @a i th bit set to 0.
*/
static
inline
uint64_t ia_unsetbit64(uint64_t word, int i)
{
return word & ~((uint64_t)1 << i);
}
/**
* Change the @a i th bit of the the bytes at @a bytes to 1.
*
* @param[in] bytes Byte sequence to change.
* @param[in] i Bit to set.
*/
static
inline
void ia_setbitv(uint8_t *bytes, int i)
{
bytes[i / 8] = ia_setbit8(bytes[i / 8], i % 8);
}
/**
* Change the @a i th bit of the the bytes at @a bytes to 0.
*
* @param[in] bytes Byte sequence to change.
* @param[in] i Bit to unset.
*/
static
inline
void ia_unsetbitv(uint8_t *bytes, int i)
{
bytes[i / 8] = ia_unsetbit8(bytes[i / 8], i % 8);
}
/**
* Change the @a i th bit of the 64 bit words at @a words to 1.
*
* @param[in] words Pointer to uint64_ts.
* @param[in] i Bit to set.
*/
static
inline
void ia_setbitv64(uint64_t *words, int i)
{
words[i / 64] = ia_setbit64(words[i / 64], i % 64);
}
/**
* Change the @a i th bit of the 64 bit words at @a words to 0.
*
* @param[in] words Pointer to uint64_ts.
* @param[in] i Bit to set.
*/
static
inline
void ia_unsetbitv64(uint64_t *words, int i)
{
words[i / 64] = ia_unsetbit64(words[i / 64], i % 64);
}
/**
* Population count of a 64 bit word.
*
* @param[in] word Word to count 1s of.
* @return Number of 1s.
*/
static
inline
int ia_popcount64(uint64_t word)
{
#if __GNUC__ >= 4
return __builtin_popcountll(word);
#else
#error "__builtin_popcountll support required. Please report this to developers."
#endif
}
/**
* Population count of 64 bit words.
*
* @param[in] words Words to counts 1s of.
* @param[in] i Index of last bit to look at.
* @return Number of 1s.
*/
static
inline
int ia_popcountv64(const uint64_t *words, int i)
{
int acc = 0;
for (int j = 0; j < i / 64; ++j) {
acc += ia_popcount64(words[j]);
}
if ((i % 64) > 0) {
acc += ia_popcount64(
words[i / 64] & (~(uint64_t)0 >> (63 - (i % 64)))
);
}
return acc;
}
/**
* @} IronAutomataBits
*/
#ifdef __cplusplus
}
#endif
#endif /* _IA_EUDOXUS_BITS_H_ */
|
C
|
// 6.12
#include <stdio.h>
#define SIZE 8
int main( void )
{
int twopows[SIZE];
int i;
int value = 1; /* 2 to the 0 */
for (i = 0; i < SIZE; i++)
{
twopows[i] = value;
value *= 2;
}
i = 0;
do
{
printf("%d ", twopows[i]);
i++;
} while (i < SIZE);
printf("\n");
return 0;
}
|
C
|
#include <stdio.h>
#include <string.h>
int main() {
char str1[15];
char str2[15];
int resultado;
strcpy(str1, "victor");
strcpy(str2, "victor hugo");
resultado = strncmp(str1, str2, 6);
if(resultado < 0)
printf("str1 é menor que str2\n");
else if(resultado > 0)
printf("str1 é maior que str2\n");
else
printf("str1 é igual a str2\n");
printf("Resultado: %d\n", resultado);
return(0);
}
/*
DESCRIÇÃO:
A função int strncmp(const char *str1, const char *str2, size_t n) compara os n primeiros
caracteres das strings apontadas str1 e str2.
DECLARAÇÃO:
- Declaração da função strncmp().
int strncmp(const char *str1, const char *str2, size_t n);
PARAMETROS:
str1 -- Primeira string a ser comparada.
str2 -- Segunda string a ser comparada.
n -- O número máximo de caracteres a ser comparados.
RETORNO:
- Esta função retorna os seguintes valores:
Se o valor de retorno for menor que 0 então indica que str1 é menor que str2.
Se o valor de retorno for maior que 0 então indica que str1 é maior que str2.
Se o valor de retorno for igual a 0 então indica que str1 é igual a str2.
*/
|
C
|
#include <am.h>
#include <klib.h>
#include <klib-macros.h>
#if !defined(__ISA_NATIVE__) || defined(__NATIVE_USE_KLIB__)
static unsigned long int next = 1;
int rand(void) {
// RAND_MAX assumed to be 32767
next = next * 1103515245 + 12345;
return (unsigned int)(next/65536) % 32768;
}
void srand(unsigned int seed) {
next = seed;
}
int abs(int x) {
return (x < 0 ? -x : x);
}
// 太简单了
// 输入 "3 4 5",得到 345,这个合理吗?
int atoi(const char* nptr) {
int x = 0;
while (*nptr == ' ') { nptr ++; }
while (*nptr >= '0' && *nptr <= '9') {
x = x * 10 + *nptr - '0';
nptr ++;
}
return x;
}
/*
功能: int转换为零结尾的字符串
参数:
int value 要转换的32位整数
char * str 要写入的字符串缓冲区
返回值:
无
备注: 至多需要12个字节来产生32位整数的字符串形式
*/
void itoa(int value, char * str) {
// 32位整数,最大值是 2147483647,共10位,再加一个负号,一个零结束标志
char buf[12];
int n = 0; // buf的写入位置
int n1 = 0; // str的写入位置
bool neg = (value < 0); // 是否为负数
// 负数处理
if (neg) {
value = -value;
}
// 倒序存入
while (true) {
buf[n++] = (value % 10) + '0';
value = value / 10;
if (!value) {
break;
}
}
if (neg) {
buf[n++] = '-';
}
// 正序输出
for (; n > 0; n--) {
str[n1++] = buf[n - 1];
}
str[n1] = 0;
}
/*
功能: int转换为零结尾的无符号的Hex字符串
参数:
int value 要转换的32位整数
char * str 要写入的字符串缓冲区
返回值:
无
备注: 至多需要9个字节来产生32位整数的字符串形式
*/
void itox(int value, char * str) {
// 32位整数,最大值是 FFFFFFFF,共8位,再加一个零结束标志
char buf[9];
int n = 0; // buf的写入位置
int n1 = 0; // str的写入位置
uint32_t uval = (uint32_t)value;
// 倒序存入
int rem = 0;
char c = 0;
while (true) {
rem = uval % 16;
if (rem > 9) c = (rem - 10) + 'A';
else c = rem + '0';
buf[n++] = c;
uval = uval / 16;
if (!uval) {
break;
}
}
// 正序输出
for (; n > 0; n--) {
str[n1++] = buf[n - 1];
}
str[n1] = 0;
}
// 一个内存块
typedef struct {
char * pstart;
size_t size;
} memBlk;
// static char * s_pfree = 0; // 指向空闲区域
void *malloc(size_t size) {
size = (size + 0xf) & ~0xf; // aligned to 16 Byte
if (heap.end - heap.start >= size) {
//printf("malloc %x bytes at %x\n", size, heap.start);
char * pstart = heap.start;
heap.start += size;
return pstart;
} else {
panic_on(0, "Run out of memory!");
return NULL;
}
//panic("Not implemented");
}
void free(void *ptr) {
}
#endif
|
C
|
/**
* Copyright (c) 2018 Zachary Puls <zach@zachpuls.com>
*/
#include <string.h>
/**
* @brief Scans str1 for the first occurrence of any of the characters that are
* part of str2, returning the number of characters of str1 read before this
* first occurrence.
*
* @param str1 A pointer to the string to be scanned
* @param str2 A pointer to the string containing the characters to match
* @return size_t The length of the initial part of str1 not containing any
* of the characters that are part of str2, which is the
* length of str1 if none of the characters in str2 are found
* in str1.
*/
size_t strcspn(const char *str1, const char *str2) {
return strlen(str1);
}
|
C
|
/**************************************************
* file: queue.h
*
* header file containing implementation details
* for a queue based on a linked list
**************************************************/
#include "linked_list.h"
typedef struct Queue Queue;
struct Queue {
Node *head;
Node *tail;
}
Queue *initQueue() {
Queue *q = malloc(sizeof(Queue));
assert(q);
return q;
}
|
C
|
../leetcode/748-Largest Number At Least Twice of Others.c
|
C
|
#include "benchmark.h"
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "algorithm/lcs_blackler.h"
#include "thirdparty/lcs_hirschberg.h"
#include "thirdparty/lcs_neiljones.h"
#include "thirdparty/lcs_rogerzhang.h"
#include "thirdparty/lcs_soarpenguin.h"
#include "util/issubstring.h"
#include "util/timing.h"
// Information about each sample (individual benchmark run).
typedef struct Sample {
int methodNumber; // Index of the method.
size_t size; // Input data size in bytes.
long long measure; // Measure, either time duration or memory used.
size_t strlen; // Length of the LCS returned.
bool valid; // If the LCS was actually a substring of the inputs.
struct Sample *next; // Next sample for this method.
} Sample;
// Generate a random string of the specified size.
static char *randomString(size_t size) {
char *text = malloc(size + 1);
char *ptr = text;
while (size) {
*ptr++ = (char) (' ' + rand() % (256 - ' '));
size--;
}
*ptr = 0;
return text;
}
// Perform a sample of the specified |size|, and specified method specs.
static Sample *doSample(size_t size,
int methodNumber, char *(*method)(char const *, char const *),
const char *methodName, int units) {
// The input is seeded to ensure consistent data across the methods.
srand(size);
// Generate the two input strings.
const char *a = randomString(size);
const char *b = randomString(size);
// Allocate the sample structure on the heap.
Sample *sample = malloc(sizeof(Sample));
sample->methodNumber = methodNumber;
sample->size = size;
sample->next = NULL;
printf("%s (%lu) .. ", methodName, size); // Log to console.
#ifdef MEMORY_PROFILE
long long before = memoryCount; // Get memory before.
#else
long long before = getMicroseconds(); // Get time before.
#endif // MEMORY_PROFILE
char *result = method(a, b); // Perform the method.
#ifdef MEMORY_PROFILE
long long after = memoryCount; // Get memory afterwards.
#else
long long after = getMicroseconds(); // Get time afterwards.
#endif // MEMORY_PROFILE
// Record the timing/memory data.
// Check the result was valid.
if (result) {
sample->measure = after - before;
sample->valid = isSubstring(result, a) && isSubstring(result, b);
sample->strlen = strlen(result); // Record the length of the result.
free(result); // Free the memory.
} else {
sample->measure = 0;
sample->valid = 0;
sample->strlen = 0;
}
free(a);
free(b);
// Log to the console.
if (!sample->valid)
printf("*INVALID* ");
printf("%lld\n", sample->measure);
return sample;
}
// Perform a benchmark test of increasing data size on all LCS methods
// and output the results to a CSV file.
void benchmark() {
#ifdef MEMORY_PROFILE
int units = 1024 * 1024;
int maxMeasure = units * 200;
#else
int units = 1000000;
int maxMeasure = units * 5;
#endif // MEMORY_PROFILE
double growthMultiply = 1.18;
int growthAdd = 1;
// Data about the methods and names.
size_t numberMethods = 5;
const char *methodNames[] =
{"Blackler", "NeilJones", "SoarPenguin", "RogerZhang", "Hirschberg"};
char *(*methods[])(const char *, const char *) =
{LCS_Blackler, LCS_NeilJones, LCS_SoarPenguin, LCS_RogerZhang, LCS_Hirschberg};
// Tables of first samples for each method.
Sample **firstSample = calloc(sizeof(Sample *), numberMethods);
// Perform the first sample of every method to bootstrap the system.
for (int methodNumber = 0; methodNumber != numberMethods;
methodNumber++) {
// First sample is one single byte.
Sample *sample = doSample(0, methodNumber, methods[methodNumber],
methodNames[methodNumber], units);
// Record the data.
firstSample[methodNumber] = sample;
}
// Progressively sample methods; the method selected is the one that completed
// in the shortest time on the previous occasion it was run (whatever the
// sample size), or in the case of memory profile, least memory used. This
// gives faster feedback during experiments because heavy algorithms do not
// dominate the testing time.
while (true) {
// Find the method with the fastest/smallest most recent valid sample.
// O(n^2) time but has negligible impact on program running time.
Sample *smallestMostRecentSample = NULL;
for (int methodNumber = 0; methodNumber != numberMethods; methodNumber++) {
// Find most recent sample.
Sample *sample = firstSample[methodNumber];
while (sample->next)
sample = sample->next;
if (!smallestMostRecentSample ||
(sample->measure < smallestMostRecentSample->measure &&
sample->valid)) {
smallestMostRecentSample = sample;
}
}
// If the fastest method was over the cap time, stop.
if (smallestMostRecentSample->measure >= maxMeasure)
break;
// Make a new sample with a size of a percentage increase from the previous.
int previous = smallestMostRecentSample->size;
int targetNext = previous * growthMultiply + growthAdd;
// Round down to the largest-rounded milestone figure that won't take the
// figure below the previous result.
int roundUnit = 5; // Lowest milestone rounding is 5.
int nextMultiplier = 2;
int next = targetNext;
while (true) {
int prospect = (targetNext / roundUnit) * roundUnit; // Round down.
if (prospect > previous) // Not less than previous figure?
next = prospect; // Store as potential result.
else
break; // Break out and use the last potential result.
// Units go 5, 10, 50, 100, 500... etc.
roundUnit *= nextMultiplier;
if (nextMultiplier == 2)
nextMultiplier = 5;
else
nextMultiplier = 2;
}
Sample *sample =
doSample((size_t) (next),
smallestMostRecentSample->methodNumber,
methods[smallestMostRecentSample->methodNumber],
methodNames[smallestMostRecentSample->methodNumber], units);
// Link the new sample to the previous.
smallestMostRecentSample->next = sample;
}
// Write the results to a CSV file for import into a chart package.
FILE *outFile = fopen("lcs.csv", "w");
// Write the header (method names).
for (int methodNumber = 0; methodNumber != numberMethods; methodNumber++) {
fprintf(outFile, ",%s", methodNames[methodNumber]);
}
fprintf(outFile, "\n");
// Write the data (sorted in size order on the fly).
size_t minimum = 0;
while (true) {
// Find the smallest size not yet output.
Sample *smallest = NULL;
for (int methodNumber = 0; methodNumber != numberMethods; methodNumber++) {
Sample *sample = firstSample[methodNumber];
while (sample && sample->size <= minimum)
sample = sample->next;
if (!sample)
continue;
if (!smallest || sample->size < smallest->size)
smallest = sample;
}
if (!smallest)
break;
// Find the longest valid LCS for this sample size.
size_t bestLCS = 0;
for (int methodNumber = 0; methodNumber != numberMethods; methodNumber++) {
Sample *sample = firstSample[methodNumber];
while (sample && sample->size < smallest->size)
sample = sample->next;
if (sample && sample->size == smallest->size &&
sample->valid && sample->strlen > bestLCS)
bestLCS = sample->strlen;
}
// Write the size column.
fprintf(outFile, "%lu", smallest->size);
// Write the results for this row.
for (int methodNumber = 0; methodNumber != numberMethods; methodNumber++) {
Sample *sample = firstSample[methodNumber];
while (sample && sample->size < smallest->size)
sample = sample->next;
fprintf(outFile, ",");
if (sample && sample->size == smallest->size) {
// Write the results cell (including error cases if results were invalid
// or sub-optimal).
if (!sample->valid) // Test failed, not a subsequence.
fprintf(outFile, "NOT SS");
else if (sample->strlen < bestLCS)
fprintf(outFile, "NOT LCS"); // A better valid alternative is known.
else fprintf(outFile, "%f", (float) sample->measure / units);
}
}
fprintf(outFile, "\n"); // Complete the row.
minimum = smallest->size; // On to the next size.
}
fclose(outFile); // Write the file.
// Free the data.
for (int methodNumber = 0; methodNumber != numberMethods; methodNumber++) {
Sample *sample = firstSample[methodNumber];
while (sample) {
Sample *next = sample->next;
free(sample);
sample = next;
}
}
free(firstSample);
}
|
C
|
#include "tout.h"
void init_liste(t_liste * liste, void (*copier_elem)(void *, void *), void (*supprimer_elem)(void *)){
liste->drapeau = malloc(sizeof(t_element));
liste->drapeau->succ = liste->drapeau;
liste->drapeau->pred = liste->drapeau;
liste->copier_elem = copier_elem;
liste->supprimer_elem = supprimer_elem;
liste->ec = liste->drapeau;
liste->nb_elem = 0;
}
int liste_vide(t_liste * liste){
return(liste->drapeau->pred == liste->drapeau);
}
int hors_liste(t_liste * liste){
return( liste->ec == liste->drapeau);
}
void en_tete(t_liste * liste){
if(!liste_vide(liste)){
liste->ec = liste->drapeau->succ;
}
}
void en_queue(t_liste * liste){
if(!liste_vide(liste)){
liste->ec = liste->drapeau->pred;
}
}
void precedent(t_liste * liste){
if(!hors_liste(liste)){
liste->ec = liste->ec->pred;
}
}
void suivant(t_liste * liste){
if(!hors_liste(liste)){
liste->ec= liste->ec->succ;
}
}
void valeur_elt(t_liste * liste, void * v){
if(!hors_liste(liste)){
liste->copier_elem(liste->ec->p_val,v);
}
}
void modif_elt(t_liste * liste,void * v){
if(!hors_liste(liste)){
liste->supprimer_elem(liste->ec->p_val);
liste->ec->p_val = v;
}
}
void oter_elt(t_liste * liste){
t_element* elem;
if(!hors_liste(liste)){
elem = liste->ec;
liste->ec->succ->pred = liste->ec->pred;
liste->ec->pred->succ = liste->ec->succ;
liste->ec = liste->ec->pred;
liste->supprimer_elem(elem->p_val);
liste->nb_elem = liste->nb_elem - 1;
free(elem);
}
}
void ajout_droit(t_liste * liste, void * pt){
t_element* nouv;
if(liste_vide(liste) || !hors_liste(liste)){
nouv = malloc(sizeof(t_element));
nouv->succ = liste->ec->succ;
nouv->pred = liste->ec;
liste->ec->succ = nouv;
nouv->succ->pred = nouv;
nouv->p_val = pt;
liste->ec = nouv;
liste->nb_elem = liste->nb_elem + 1;
}
}
void ajout_gauche(t_liste * liste, void * pt){
t_element* nouv;
if(liste_vide(liste) || !hors_liste(liste)){
nouv = malloc(sizeof(t_element));
nouv->succ = liste->ec;
nouv->pred = liste->ec->pred;
liste->ec->pred = nouv;
nouv->pred->succ = nouv;
nouv->p_val = pt;
liste->ec = nouv;
liste->nb_elem = liste->nb_elem + 1;
}
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
int main(int argc, char *argv[]) {
int x, y, aux, vetAt[100];
for(x=0;x<100;x++){
printf("Insira o %d numero: ", x+1);
scanf("%d",&vetAt[x]);
}
for(x=0;x<100;x++){
for(y=x+1;y<100;y++){
if(vetAt[x]>vetAt[y]){
aux = vetAt[x];
vetAt[x] = vetAt[y];
vetAt[y] = aux;
}
}
}
printf("Em ordem crescente: \n");
for(x=0;x<100;x++){
printf("%d \n",vetAt[x]);
}
return 0;
}
|
C
|
#include <linux/types.h>
#include <linux/wireless.h>
#include <string.h>
#include <sys/ioctl.h>
#include <sys/socket.h>
#include <unistd.h>
enum {
SUCCESS,
ERROR_ARGS,
ERROR_SOCKET,
ERROR_IOCTL,
ERROR__COUNT
};
enum {
ARGS_EXEC,
ARGS_INTERFACE,
ARGS__COUNT
};
int main (int argc, char** argv) {
// Determine if all required arguments have been provided. Without
// the wireless interface, this program cannot set the interface
// name for the ioctl function call.
if (argc < ARGS__COUNT)
{
return ERROR_ARGS;
}
// There seems to be a race condition between this and iwd. This
// must execute after iwd has configured the wireless interface.
// This seems to give iwd enough time to complete.
sleep(2);
int fd = socket(AF_INET, SOCK_DGRAM, 0);
if (fd == -1)
{
return ERROR_SOCKET;
}
struct iwreq wrq = { 0 };
// assign interface name
strncpy(wrq.ifr_name, argv[ARGS_INTERFACE], IFNAMSIZ);
// assign power-savings
wrq.u.power.disabled = 1;
// Send an ioctl request to configure the wireless interface. If
// the interface name passed via the command-line arguments does
// not match a valid wireless interface, this will fail. This
// ioctl request also requires root privileges.
if (ioctl(fd, SIOCSIWPOWER, &wrq) == -1)
{
return ERROR_IOCTL;
}
close(fd);
return SUCCESS;
}
|
C
|
#include <stdio.h>
int main()
{
float a[8]={0,};
float b[8]={0,};
int i;
for(i=0;i<8;i++)
{
scanf("%f", &a[i]);
b[i]+=a[i];
printf("a[%d]=%.3f ",i,a[i]);
}
printf("\n");
for(i=0;i<8;i++)
{
b[i]+=a[i];
printf("b[%d]=%.3f ",i,b[i]);
if(b[i]>10)
{
}
}
return 0;
}
|
C
|
/**
* Video for Linux version 2 (V4L2) example 1 - print device capabilities
*
* Based on
* - https://gist.github.com/Circuitsoft/1126411
* - https://jayrambhia.com/blog/capture-v4l2
*
* Kyle M. Douglass, 2018
* kyle.m.douglass@gmail.com
*/
#include <errno.h>
#include <fcntl.h>
#include <linux/videodev2.h>
#include <stdio.h>
#include <sys/ioctl.h>
#include <unistd.h>
static const char DEVICE[] = "/dev/video0";
/**
* Prints the capabilities of the device.
*/
int print_capabilities(int fd) {
int ret;
struct v4l2_capability caps = {0};
ret = ioctl(fd, VIDIOC_QUERYCAP, &caps);
if (ret == -1) {
perror("Querying device capabilities");
return errno;
}
printf("Driver Caps:\n"
" Driver: \"%s\"\n"
" Card: \"%s\"\n"
" Bus: \"%s\"\n"
" Version: %u.%u.%u\n"
" Capabilities: %08x\n",
caps.driver,
caps.card,
caps.bus_info,
(caps.version >> 16) & 0xFF,
(caps.version >> 8) & 0xFF,
(caps.version ) & 0XFF,
caps.capabilities);
return 0;
}
int main(void) {
int fd;
// Open the device file
fd = open(DEVICE, O_RDWR);
if (fd < 0) {
perror(DEVICE);
return errno;
}
print_capabilities(fd);
close(fd);
return 0;
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* project.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: nmanzini <nmanzini@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2018/01/23 14:12:19 by nmanzini #+# #+# */
/* Updated: 2018/01/26 13:53:02 by nmanzini ### ########.fr */
/* */
/* ************************************************************************** */
#include "fdf.h"
void perspective_z(t_mlx_data *md, float *xp, float *yp, float *zp)
{
float tempx;
float tempy;
float tempz;
tempx = *xp;
tempy = *yp;
tempz = *zp - md->in->max_size * md->in->cam_d_f;
*xp = tempx / tempz * md->in->cam_d_f * md->in->max_size;
*yp = tempy / tempz * md->in->cam_d_f * md->in->max_size;
}
void project_pe(t_mlx_data *md)
{
int i;
int j;
float xp;
float yp;
float zp;
i = -1;
while (++i < md->in->n)
{
j = -1;
while (++j < md->in->m)
{
xp = i - md->in->n / 2;
yp = j - md->in->m / 2;
zp = md->in->matrix[j][i] * md->in->height;
rotate_z(md, &xp, &yp, &zp);
rotate_x(md, &xp, &yp, &zp);
rotate_y(md, &xp, &yp, &zp);
md->in->matrix_p[j][i][2] = (int)((zp + md->in->max_size) /
md->in->max_size * md->in->dots_size);
perspective_z(md, &xp, &yp, &zp);
md->in->matrix_p[j][i][0] = (int)(md->in->c_x - xp * md->in->scale);
md->in->matrix_p[j][i][1] = (int)(md->in->c_y - yp * md->in->scale);
}
}
}
void project_is(t_mlx_data *md)
{
int i;
int j;
float xp;
float yp;
float zp;
i = -1;
while (++i < md->in->n)
{
j = -1;
while (++j < md->in->m)
{
xp = i - md->in->n / 2;
yp = j - md->in->m / 2;
zp = md->in->matrix[j][i] * md->in->height;
rotate_z(md, &xp, &yp, &zp);
rotate_x(md, &xp, &yp, &zp);
rotate_y(md, &xp, &yp, &zp);
md->in->matrix_p[j][i][0] = (int)(md->in->c_x + xp * md->in->scale);
md->in->matrix_p[j][i][1] = (int)(md->in->c_y + yp * md->in->scale);
md->in->matrix_p[j][i][2] = (int)(md->in->dots_size);
}
}
}
|
C
|
#include <stdio.h>
int main() {
int inputNumber;
printf("give me a number");
scanf("%d",&inputNumber );
if(inputNumber>=18){
printf("you can get booze in hungary\n");
}
else{
printf("you are too young to drink bruv\n");
}
printf("Hello, World!\n");
return 0;
}
|
C
|
#include <stdio.h>
#include <omp.h>
#define N 4
int main(){
int i, j;
#pragma omp parallel for
for(i=0; i<N; i++){
for(j=0; j<N; j++){
printf("i:%d, j:%d\n", i, j);
}
}
return 0;
}
|
C
|
#include <string.h>
#include <time.h>
#include <stdio.h>
#include <stdlib.h>
#include <omp.h>
#include "mkl_vsl.h"
#define batchsize 100
int main(int argc, char **argv)
{
int niter = atoi(argv[1]);
/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
/* ~~~~~~~~~~~~~~~~~PARALLELIZE ME~~~~~~~~~~~~~~~~~~ */
/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
/* Random Number Generation via MKL Random Number Stream */
float * rand_buffer_x = (float*)malloc(batchsize*sizeof(float));
float * rand_buffer_y = (float*)malloc(batchsize*sizeof(float));
VSLStreamStatePtr stream;
int SEED = omp_get_thread_num() + time(NULL); /* RNG seed dependent on time of day and thread number*/
vslNewStream( &stream, VSL_BRNG_SFMT19937, SEED );
/* Loop over Randomly Generated Numbers */
int count = 0;
int i,j;
for(j = 0; j < niter; j+=batchsize)
{
vsRngUniform( VSL_RNG_METHOD_UNIFORM_STD, stream, batchsize, rand_buffer_x, 0.0, 1.0 );
vsRngUniform( VSL_RNG_METHOD_UNIFORM_STD, stream, batchsize, rand_buffer_y, 0.0, 1.0 );
for(i = 0; i < batchsize; i++)
{
float z = rand_buffer_y[i]*rand_buffer_y[i] + rand_buffer_x[i]*rand_buffer_x[i];
if (z<=1) count++;
}
}
/* Delete the stream and buffers*/
vslDeleteStream( &stream );
free(rand_buffer_x);
free(rand_buffer_y);
/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
/* ~~~~~~~~~~~~~~~~~PARALLELIZE ME~~~~~~~~~~~~~~~~~~ */
/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
double pi = (double) count / niter*4;
printf("num trials=%d, estimate of pi=%f\n", niter, pi);
return 0;
}
|
C
|
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode {
int val;
struct ListNode *next;
};
struct ListNode *detectCycle(struct ListNode *head) {
struct ListNode* fast = head;
struct ListNode* slow = head;
int flag = 0;
while(fast != NULL && fast->next != NULL){
fast = fast->next->next;
slow = slow->next;
if (fast == slow){
flag = 1;
break;
}
}
if (flag == 0){
return NULL;
}
while(head != slow){
head = head->next;
slow = slow->next;
}
return head;
}
|
C
|
//trapizoidal rule
#include<stdio.h>
#include<conio.h>
#include<math.h>
float f(float x)
{ return((4*x)-(3*(pow(x,2))));
}
void main()
{ float a,b,x[50],y[50],s=0.0,h;
int n,i;
clrscr();
printf("Lower Limit-");
scanf("%f",&a);
printf("\nUpper Limit-");
scanf("%f",&b);
printf("\nEnter no. of subintervals-");
scanf("%d",&n);
h=(b-a)/n;
x[0]=a;
x[n]=b;
y[0]=f(x[0]);
y[n]=f(x[n]);
for(i=1;i<n;i++)
{ x[i]=x[0]+(i*h);
y[i]=f(x[i]);
s=s+y[i];
}
s=(h/2)*(y[0]+y[n]+(2*s));
printf("\nI=%f",s);
getch();
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void rotate(char * r, char * q) {
for (int i = 0; i < 10; i++) {
for (int j = 0; j < 10; j++) {
*(q + 10 * j + 9 - i) = *(r + 10 * i + j);
}
}
for (int k = 0; k < 10; k++) {
for (int l = 0; l < 10; l++) {
fprintf(stdout, "%c", *(q + 10 * k + l));
}
fprintf(stdout, "\n");
}
}
int main(int argc, char ** argv) {
char array[10][10] = {{0}};
char store[10][10] = {{0}};
char * p = &store[0][0];
char * q = &array[0][0];
int c;
int n = 0;
if (argc != 2) {
fprintf(stderr, "Command line argument error\n");
return EXIT_FAILURE;
}
FILE * f = fopen(argv[1], "r");
if (f == NULL) {
fprintf(stderr, "f is NULL\n");
return EXIT_FAILURE;
}
while ((c = fgetc(f)) != EOF) {
n++;
if ((c > 127) || (c < -128)) {
fprintf(stderr, "Input not char\n");
return EXIT_FAILURE;
}
if ((n % 11 == 0) && (c != '\n')) {
fprintf(stderr, "Input error\n");
return EXIT_FAILURE;
}
if (n > 110) {
fprintf(stderr, "Input too long\n");
return EXIT_FAILURE;
}
if (c != '\n') {
*p = c;
p++;
}
}
if (n != 110) {
fprintf(stderr, "Input too short\n");
return EXIT_FAILURE;
}
char * r = &store[0][0];
rotate(r, q);
if (fclose(f) != 0) {
fprintf(stderr, "Failure to close the input file\n");
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <check.h>
#include <binary_tree_int.h>
#include "check_suites.h"
#define ROOT_ELEMENT (11)
#define NUM_ELEMENTS (10)
#define BUFFER_SIZE (64)
START_TEST(sprintf_test)
{
bt_node_int_t *tree;
bt_node_int_err_t ret;
char buf[BUFFER_SIZE];
tree = bt_int_create(ROOT_ELEMENT);
ck_assert_ptr_ne(NULL, tree);
ret = bt_int_snprintf(tree, BT_INT_PREORDER, buf, sizeof(buf));
ck_assert_int_eq(BT_INT_SUCCESS, ret);
ck_assert_str_eq("11 ", buf);
ret = bt_int_snprintf(tree, BT_INT_INORDER, buf, sizeof(buf));
ck_assert_int_eq(BT_INT_SUCCESS, ret);
ck_assert_str_eq("11 ", buf);
ret = bt_int_snprintf(tree, BT_INT_POSTORDER, buf, sizeof(buf));
ck_assert_int_eq(BT_INT_SUCCESS, ret);
ck_assert_str_eq("11 ", buf);
ret = bt_int_insert(tree, 5);
ck_assert_int_eq(BT_INT_SUCCESS, ret);
ret = bt_int_snprintf(tree, BT_INT_PREORDER, buf, sizeof(buf));
ck_assert_int_eq(BT_INT_SUCCESS, ret);
ck_assert_str_eq("11 5 ", buf);
ret = bt_int_snprintf(tree, BT_INT_INORDER, buf, sizeof(buf));
ck_assert_int_eq(BT_INT_SUCCESS, ret);
ck_assert_str_eq("5 11 ", buf);
ret = bt_int_snprintf(tree, BT_INT_POSTORDER, buf, sizeof(buf));
ck_assert_int_eq(BT_INT_SUCCESS, ret);
ck_assert_str_eq("5 11 ", buf);
ret = bt_int_insert(tree, 16);
ck_assert_int_eq(BT_INT_SUCCESS, ret);
ret = bt_int_snprintf(tree, BT_INT_PREORDER, buf, sizeof(buf));
ck_assert_int_eq(BT_INT_SUCCESS, ret);
ck_assert_str_eq("11 5 16 ", buf);
ret = bt_int_snprintf(tree, BT_INT_INORDER, buf, sizeof(buf));
ck_assert_int_eq(BT_INT_SUCCESS, ret);
ck_assert_str_eq("5 11 16 ", buf);
ret = bt_int_snprintf(tree, BT_INT_POSTORDER, buf, sizeof(buf));
ck_assert_int_eq(BT_INT_SUCCESS, ret);
ck_assert_str_eq("5 16 11 ", buf);
ret = bt_int_insert(tree, 19);
ck_assert_int_eq(BT_INT_SUCCESS, ret);
ret = bt_int_insert(tree, 3);
ck_assert_int_eq(BT_INT_SUCCESS, ret);
ret = bt_int_insert(tree, 8);
ck_assert_int_eq(BT_INT_SUCCESS, ret);
ret = bt_int_insert(tree, 7);
ck_assert_int_eq(BT_INT_SUCCESS, ret);
ret = bt_int_insert(tree, 10);
ck_assert_int_eq(BT_INT_SUCCESS, ret);
ret = bt_int_snprintf(tree, BT_INT_PREORDER, buf, sizeof(buf));
ck_assert_int_eq(BT_INT_SUCCESS, ret);
ck_assert_str_eq("11 5 3 8 7 10 16 19 ", buf);
ret = bt_int_snprintf(tree, BT_INT_INORDER, buf, sizeof(buf));
ck_assert_int_eq(BT_INT_SUCCESS, ret);
ck_assert_str_eq("3 5 7 8 10 11 16 19 ", buf);
ret = bt_int_snprintf(tree, BT_INT_POSTORDER, buf, sizeof(buf));
ck_assert_int_eq(BT_INT_SUCCESS, ret);
ck_assert_str_eq("3 7 10 8 5 19 16 11 ", buf);
ret = bt_int_destroy(tree);
ck_assert_int_eq(BT_INT_SUCCESS, ret);
tree = NULL;
ck_assert_ptr_eq(NULL, tree);
}
END_TEST
Suite *
sprintf_suite(void)
{
Suite *s;
TCase *tc;
s = suite_create("Sprintf Suite");
tc = tcase_create("Sprintf Test");
tcase_add_test(tc, sprintf_test);
suite_add_tcase(s, tc);
return s;
};
|
C
|
#include <stdio.h>
#include <string.h>
int main()
{
int a[100], b[100], i, p;
while(scanf("%d", &n)==1){
if(n==0) break;
memset(a, 0, sizeof a);
printf("Discarded cards: ");
for(i = 1, j = 1; i<=n; i++){
if(i==1) printf("%d");
else if(i%2==1) printf(", %d");
else {
a[j] = i;
j++;
}
}
if(n%2==0) a[j] = n;
if(n%2==0){
while{
p = z;
memset(b, 0, sizeof b);
for(i = 1; i<=p; i++){
}
}
}
}
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_inst_var.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: alac <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2019/03/04 13:23:32 by alac #+# #+# */
/* Updated: 2019/03/04 13:23:34 by alac ### ########.fr */
/* */
/* ************************************************************************** */
#include "includes/ft_push_swap.h"
void ft_lst_add(t_inst **alst, t_inst *news)
{
t_inst *current;
if (alst && news)
{
current = *alst;
while (current->next != NULL)
{
current = current->next;
}
current->next = news;
}
}
t_inst *ft_inst_new(char *content)
{
t_inst *tmp;
if (!(tmp = (t_inst *)malloc(sizeof(t_pile))))
return (NULL);
if (!content)
{
tmp->content = NULL;
tmp->next = NULL;
return (tmp);
}
else
{
tmp->content = ft_strdup(content);
tmp->next = NULL;
return (tmp);
}
}
t_inst *ft_to_inst(t_inst **inst, char *line)
{
t_inst *head;
if (!(*inst))
{
*inst = ft_inst_new(line);
head = *inst;
}
else
{
head = ft_inst_new(line);
ft_lst_add(inst, head);
}
return (*inst);
}
|
C
|
/*
** my_exec.c for my_exec in /home/nguye_z/rendu/PSU_2015_my_exec
**
** Made by nguyen kevin
** Login <nguye_z@nguye-z-pc>
**
** Started on Tue Jan 5 11:30:24 2016 nguyen kevin
** Last update Sat Apr 9 14:44:06 2016 nguyen kevin
*/
#include "header.h"
char esperluette_or_comma(char **tab)
{
int i;
int j;
i = 0;
while (tab[i] != NULL)
{
j = 0;
while (tab[i][j] != '\0')
{
if (tab[i][j] == '&' && tab[i][j + 1] == '&')
return (tab[i][j]);
else if (tab[i][j] == ';')
return (tab[i][j]);
j++;
}
i++;
}
return (0);
}
int check_esperluette(char **tab)
{
int i;
int j;
int count;
char c;
count = 0;
i = 0;
c = esperluette_or_comma(tab);
while (tab[i] != NULL)
{
j = 0;
while (tab[i][j] != '\0')
{
if (c == '&')
if (tab[i][j] == c && tab[i][j + 1] == c)
count++;
if (c == ';')
if (tab[i][j] == c)
count++;
j++;
}
i++;
}
return (count);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
char sym[3][3]={'1','2','3','4','5','6','7','8','9'};
char user='X';
bool check=true,check_winning=false;
int iteration=1;
void Display(char arr[3][3])
{
printf("\t\t T I C T A C T O E \n");
printf(" Player One is:- X\n");
printf(" Player Two is:- O\n");
printf("\n %c | %c | %c ",arr[0][0],arr[0][1],arr[0][2]);
printf("\n ----- | ----- | -----");
printf("\n %c | %c | %c ",arr[1][0],arr[1][1],arr[1][2]);
printf("\n ----- | ----- | -----");
printf("\n %c | %c | %c ",arr[2][0],arr[2][1],arr[2][2]);
if (check==false)
printf("\n Enter valid number");
check=true;
}
void turn()
{
if(user =='X')
{
user = 'O';
}
else
{
user ='X';
}
}
bool empty(char sym)
{
if(sym =='X'||sym =='O')
return false;
else
{
return true;
}
}
int insert()
{
int u_input;
printf("\n");
scanf("%d", &u_input);
switch (u_input)
{
case 1:
if(empty(sym[0][0]) == true)
{
sym [0][0] =user;
turn();
break;
}
else printf("The cell isn't empty");
iteration=0;
break;
case 2:
if(empty(sym[0][1])== true)
{
sym [0][1] =user;
turn();
break;
}
else printf("The cell isn't empty");
iteration=0;
break;
case 3:
if(empty(sym[0][2])== true)
{
sym [0][2] =user;
turn();
break;
}
else printf("The cell isn't empty");
iteration=0;
break;
case 4:
if(empty(sym[1][0])== true)
{
sym [1][0] =user;
turn();
break;
}
else printf("The cell isn't empty");
iteration=0;
break;
case 5:
if(empty(sym[1][1])== true)
{
sym [1][1] =user;
turn();
break;
}
else printf("The cell isn't empty");
iteration=0;
break;
case 6:
if(empty(sym[1][2])== true)
{
sym [1][2] =user;
turn();
break;
}
else printf("The cell isn't empty");
iteration=0;
break;
case 7:
if(empty(sym[2][0])== true)
{
sym [2][0] =user;
turn();
break;
}
else printf("The cell isn't empty");
iteration=0;
break;
case 8:
if(empty(sym[2][1])== true)
{
sym [2][1] =user;
turn();
break;
}
else printf("The cell isn't empty");
iteration=0;
break;
case 9:
if(empty(sym[2][2])== true)
{
sym [2][2] =user;
turn();
break;
}
else printf("The cell isn't empty");
iteration=0;
break;
default:{check=false;
iteration=0;
}
}
}
void is_winning()
{
for(int i=0;i<3; i++)
{
if(sym[i][0]== sym[i][1] &&
sym[i][0]== sym[i][2])
{
printf("\n %c wins",sym[i][0]);
check_winning=true;
}
}
for(int i=0; i<3; i++)
{
if(sym[0][i]==sym[1][i] &&
sym[0][i]==sym[2][i])
{
printf("\n %c wins",sym[0][i]);
check_winning=true;
}
}
if(sym[0][0]==sym[1][1] &&
sym[1][1]==sym[2][2])
{
printf("\n %c wins",sym[0][0]);
check_winning=true;
}
else if(sym[0][2]==sym [1][1] &&
sym[1][1]==sym[2][0])
{
printf("\n %c wins",sym[0][2]);
check_winning=true;
}
else
{
int tie = 0;
for(int i=0;i<3;i++)
{
for (int j=0;j<3;j++)
{
if(((sym[i][j]=='X')||(sym[i][j]=='O')))
{
tie ++;
}
}
}
if (tie==9)
{
printf("\n X & O Tied");
check_winning=true;
}
}
}
int main()
{
Display(sym);
do
{
insert();
system("cls");
Display(sym);
if (iteration==0)
{
iteration=1;
}
is_winning(sym);
if(check_winning==true)
{
break;
}
} while (iteration=1);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <time.h>
int main()
{
int fd = open("hw1_door",O_RDWR);
char buf[20]={0,};
if(fd <= 0)
{
perror("open");
return -1;
}
srand(22);
while(1)
{
int r = 1500000+rand()%1000000;
int f = read(fd,buf,15);
if(f == -1)
{
printf("Consumer : Stack is empty. Wait for production\n");
}
else
{
printf("Consumer : %d is popped from stack\n",f);
}
usleep(r);
}
close(fd);
return 0;
}
|
C
|
#include "unity.h"
#include "TokenAffix.h"
#include "Token.h"
#include "Tokenizer.h"
#include "Common.h"
#include <stdio.h>
#include <stdlib.h>
void setUp(void){}
void tearDown(void){}
/* Before encode
* Affix = PREFIX = 0x0002 0000
* TokenType = TOKEN_OPERATOR_TYPE = 0x0000 0004
*
* After encode
* TokenType = 0x0002 0004 = 131076 (decimals)
*/
void test_encodeAffix_given_minus_sign_expect_131076_after_encode(void){
Token *token = NULL;
Tokenizer *tokenizer = NULL;
tokenizer = createTokenizer("-");
// should get operator '-'
token = getToken(tokenizer);
encodeAffix(token,PREFIX);
TEST_ASSERT_EQUAL(131076,token->type);
}
/* FiRST ENCODE (Same result as previous test)
* Before
* TokenType = 0x0002 0004 = 131076 (decimals)
*
* After (getAffix)
* TokenType = 0x0002 0000 = 131072 (decimals)
*/
void test_getAffix_given_minus_sign_expect_PREFIX(void){
Affix affix;
Token *token = NULL;
Tokenizer *tokenizer = NULL;
tokenizer = createTokenizer("-");
// should get operator '-'
token = getToken(tokenizer);
encodeAffix(token,PREFIX);
affix = getAffix(token);
TEST_ASSERT_EQUAL(131076,token->type);
TEST_ASSERT_EQUAL(PREFIX,affix);
}
/* FiRST ENCODE (Same result as previous test)
* Before
* TokenType = 0x0002 0004 = 131076 (decimals)
*
* After (getTokenType)
* TokenType = 0x0000 0004 = 4 (decimals)
*/
void test_getTokenType_given_minus_sign_expect_TOKEN_OPERATOR_TYPE(void){
TokenType tokenType;
Token *token = NULL;
Tokenizer *tokenizer = NULL;
tokenizer = createTokenizer("-");
// should get operator '-'
token = getToken(tokenizer);
encodeAffix(token,PREFIX);
tokenType = getTokenType(token);
TEST_ASSERT_EQUAL(131076,token->type);
TEST_ASSERT_EQUAL(TOKEN_OPERATOR_TYPE,tokenType);
}
/* FIRST Cycle
* ------------
* encodeAffix
* TokenType = 0x0002 0004 = 131076 (decimals)
* getAffix
* TokenType = 0x0002 0000 = 131072 (decimals)
* getTokenType
* TokenType = 0x0000 0004 = 4 (decimals)
*
* SECOND Cycle
* ------------
* encodeAffix
* TokenType = 0x0001 0003 = 65539 (decimals)
* getAffix
* TokenType = 0x0001 0000 = 65536 (decimals)
* getTokenType
* TokenType = 0x0000 0003 = 3 (decimals)
*/
void test_TokenAffix_three_functions_encodeAffix_getAffix_getTokenType_given_minus_2_expect_minus_PREFIX_TOKEN_OPERATOR_TYPE_and_2_NO_AFFIX_and_TOKEN_INTEGER_TYPE(void){
Affix affix;
TokenType tokenType;
Token *token = NULL;
Tokenizer *tokenizer = NULL;
tokenizer = createTokenizer("-2");
// should get operator '-'
token = getToken(tokenizer);
encodeAffix(token,PREFIX);
affix = getAffix(token);
tokenType = getTokenType(token);
TEST_ASSERT_EQUAL(131076,token->type);
TEST_ASSERT_EQUAL(PREFIX,affix);
TEST_ASSERT_EQUAL(TOKEN_OPERATOR_TYPE,tokenType);
// should get operand '2'
token = getToken(tokenizer);
encodeAffix(token,NO_AFFIX);
affix = getAffix(token);
tokenType = getTokenType(token);
TEST_ASSERT_EQUAL(65539,token->type);
TEST_ASSERT_EQUAL(NO_AFFIX,affix);
TEST_ASSERT_EQUAL(TOKEN_INTEGER_TYPE,tokenType);
}
/* FIRST Cycle
* ------------
* encodeAffix
* TokenType = 0x0002 0004 = 131076 (decimals)
* getAffix
* TokenType = 0x0002 0000 = 131072 (decimals)
* getTokenType
* TokenType = 0x0000 0004 = 4 (decimals)
*
* SECOND Cycle
* ------------
* encodeAffix
* TokenType = 0x0001 0003 = 65539 (decimals)
* getAffix
* TokenType = 0x0001 0000 = 65536 (decimals)
* getTokenType
* TokenType = 0x0000 0003 = 3 (decimals)
*
* THIRD Cycle
* ------------
* encodeAffix
* TokenType = 0x0004 0004 = 262148 (decimals)
* getAffix
* TokenType = 0x0004 0000 = 262144 (decimals)
* getTokenType
* TokenType = 0x0000 0004 = 4 (decimals)
*
* FOURTH Cycle
* ------------
* encodeAffix
* TokenType = 0x0001 0003 = 65539 (decimals)
* getAffix
* TokenType = 0x0001 0000 = 65536 (decimals)
* getTokenType
* TokenType = 0x0000 0003 = 3 (decimals)
*/
void test_TokenAffix_three_functions_encodeAffix_getAffix_getTokenType_given_minus_2_plus_3_expect_minus_PREFIX_TOKEN_OPERATOR_TYPE_and_2_NO_AFFIX_and_TOKEN_INTEGER_TYPE_and_plus_POST_AFFIX_TOKEN_OPERATOR_TYPE_and_3_NO_AFFIX_and_TOKEN_INTEGER_TYPE(void){
Affix affix;
TokenType tokenType;
Token *token = NULL;
Tokenizer *tokenizer = NULL;
tokenizer = createTokenizer("-2+ 3");
// should get operator '-'
token = getToken(tokenizer);
encodeAffix(token,PREFIX);
affix = getAffix(token);
tokenType = getTokenType(token);
TEST_ASSERT_EQUAL(131076,token->type);
TEST_ASSERT_EQUAL(PREFIX,affix);
TEST_ASSERT_EQUAL(TOKEN_OPERATOR_TYPE,tokenType);
// should get operand '2'
token = getToken(tokenizer);
encodeAffix(token,NO_AFFIX);
affix = getAffix(token);
tokenType = getTokenType(token);
TEST_ASSERT_EQUAL(65539,token->type);
TEST_ASSERT_EQUAL(NO_AFFIX,affix);
TEST_ASSERT_EQUAL(TOKEN_INTEGER_TYPE,tokenType);
// should get operator '+'
token = getToken(tokenizer);
encodeAffix(token, SUFFIX);
affix = getAffix(token);
tokenType = getTokenType(token);
TEST_ASSERT_EQUAL(262148,token->type);
TEST_ASSERT_EQUAL(SUFFIX,affix);
TEST_ASSERT_EQUAL(TOKEN_OPERATOR_TYPE,tokenType);
// should get operand '3'
token = getToken(tokenizer);
encodeAffix(token,NO_AFFIX);
affix = getAffix(token);
tokenType = getTokenType(token);
TEST_ASSERT_EQUAL(65539,token->type);
TEST_ASSERT_EQUAL(NO_AFFIX,affix);
TEST_ASSERT_EQUAL(TOKEN_INTEGER_TYPE,tokenType);
}
|
C
|
#include "my_apue.h"
int main(int argc, char const *argv[]) {
if(argc == 1) {
printf("must has a file\n");
exit(1);
}
struct stat buf;
int i;
for(i = 1 ; i < argc; i++) {
if(lstat(argv[i], &buf) == -1) {
perror("lstat");
continue;
}
if(S_ISREG(buf.st_mode)) {
printf("regular file\n");
} else if(S_ISDIR(buf.st_mode)) {
printf("directory\n");
} else if(S_ISCHR(buf.st_mode)) {
printf("character device\n" );
} else if(S_ISBLK(buf.st_mode)) {
printf("block device\n" );
} else if(S_ISFIFO(buf.st_mode)) {
printf("fifo file\n" );
} else if(S_ISLNK(buf.st_mode)) {
printf("symbolic link file\n");
} else if(S_ISSOCK(buf.st_mode)) {
printf("socket\n" );
}
}
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
#include "libfat.h"
void print_file_info(Entry *entry);
void dif_fat(FILE * in, BootSector bs, bool show);
void blocos_livres(FILE * in, BootSector bs);
void blocos_deletados(FILE * in, BootSector bs);
void corrige_fat(FILE * in, int nr_fat);
void copia_fat(FILE * in, FILE * out,int fat_in, int fat_out);
//void seek_dir(FILE * in,
void ajuda();
FILE * init(const char * fileName, char * str);
BootSector ReadBootSector(FILE * in);
int main(int argc, char ** argv) {
if (argc >= 2) {
int copia_disabled = 0;
FILE * fp = init("disco", "r+b");
if (!fp) {
printf("Nao foi possivel abrir o disco virtual, verifique se existe ou crie-o:\n");
printf("dd if=/dev/zero of=disco bs=1M count=2\n");
printf("mkfs.vfat -F16 disco\n");
return -1;
}
FILE * fp2 = init("disco_2", "r+b");
if (!fp2) {
printf("Nao foi possivel abrir o segundo disco virtual, verifique se existe ou crie-o:\n");
printf("dd if=/dev/zero of=disco_2 bs=1M count=2\n");
printf("mkfs.vfat -F16 disco_2\n");
copia_disabled = 1;
}
BootSector bs = ReadBootSector(fp);
if (argv[1][0] == '-') {
char * argument = &argv[1][1];
if (strcmp(argument,"vf") == 0) {
printf("Verificar FATs:\n");
dif_fat(fp,bs,false);
} else if (strcmp(argument,"bl") == 0) {
printf("Imprimir lista de blocos livres\n");
blocos_livres(fp,bs);
} else if (strcmp(argument,"bd") == 0) {
printf("Imprimir lista de blocos livres com dados\n");
blocos_deletados(fp,bs);
} else if (strcmp(argument,"cf1") == 0) {
printf("Corrigir a primeira cópia da FAT\n");
corrige_fat(fp,2);
} else if (strcmp(argument,"cf2") == 0) {
printf("Corrigir a segunda cópia da FAT\n");
corrige_fat(fp,1);
} else if (strcmp(argument,"cdf1") == 0) {
/**
* Copia a fat1 do disco 2 para fat1 do disco 1 para gerar caso de testes
**/
if (!copia_disabled) {
printf("Fazendo caso de testes, copiando fat1 do disco 2 para fat1 do disco 1...\n");
copia_fat(fp2,fp,1,1);
}
} else if (strcmp(argument,"cdf2") == 0) {
/**
* Copia a fat1 do disco 2 para fat2 do disco 1 para gerar caso de testes
**/
if (!copia_disabled) {
copia_fat(fp2,fp,1,2);
}
} else {
printf("Argumento desconhecido!\n");
ajuda();
}
}
fclose(fp);
} else {
ajuda();
}
return 0;
}
void print_file_info(Entry *entry) {
switch(entry->filename[0]) {
case 0x00:
return; // unused entry
case 0xE5:
printf("Deleted file: [?%.7s.%.3s]\n", entry->filename+1, entry->ext);
return;
case 0x05:
printf("File starting with 0xE5: [%c%.7s.%.3s]\n", 0xE5, entry->filename+1, entry->ext);
break;
case 0x2E:
printf("Directory: [%.8s.%.3s]\n", entry->filename, entry->ext);
break;
default:
printf("File: [%.8s.%.3s][offset:0x%04X]\n", entry->filename, entry->ext,entry->starting_cluster);
}
printf(" Modified: %04d-%02d-%02d %02d:%02d.%02d Start: [%04X] Size: %d\n",
1980 + (entry->modify_date >> 9), (entry->modify_date >> 5) & 0xF, entry->modify_date & 0x1F,
(entry->modify_time >> 11), (entry->modify_time >> 5) & 0x3F, entry->modify_time & 0x1F,
entry->starting_cluster, entry->file_size);
}
void dif_fat(FILE * in, BootSector bs, bool show) {
int nr_fat_sectors = (bs.fat_size_sectors * bs.sector_size / 2) - 2;
u_int32_t start_fat1 = sizeof(BootSector) + (bs.reserved_sectors-1) * bs.sector_size;;
u_int32_t start_fat2 = sizeof(BootSector) + start_fat1 + (bs.fat_size_sectors - 1) * bs.sector_size;
u_int32_t root_start = sizeof(BootSector) + start_fat2 + (bs.fat_size_sectors - 1) * bs.sector_size;
u_short fat1[nr_fat_sectors];
u_short fat2[nr_fat_sectors];
//printf("Posicao inicial fat1: 0x%X\n", start_fat1);
fseek(in, start_fat1+4, SEEK_SET);
fread(&fat1, sizeof(fat1), 1, in);
//printf("Posicao final fat1: 0x%lX\n", ftell(in));
//printf("Posicao inicial fat2: 0x%X\n", start_fat2);
fseek(in, start_fat2+4, SEEK_SET);
fread(&fat2, sizeof(fat2), 1, in);
//printf("Posicao final fat2: 0x%lX\n root: 0x%X\n", ftell(in),root_start);
int i = 0;
int count = 0;
for (i = 0; i < nr_fat_sectors; i++) {
//printf("FAT %d: 0x%04X,0x%04X\n",i,fat1[i],fat2[i]);
if (fat1[i] != fat2[i]) {
count++;
printf("DIF %d: 0x%04X,0x%04X\n",i,fat1[i],fat2[i]);
}
if (i > 50)
break;
}
//if (count == 0)
// printf("nenhuma diferenca entre as FATs\n");
if (show) {
printf("FAT:\n");
for (i = 0; i < nr_fat_sectors; i++) {
printf("%d:%ud,%ud\n",i,fat1[i],fat2[i]);
}
}
}
void blocos_livres(FILE * in, BootSector bs) {
int nr_fat_sectors = (bs.fat_size_sectors * bs.sector_size / 2) - 2;
int i, j = 0;
u_int32_t start_fat1 = sizeof(BootSector) + (bs.reserved_sectors-1) * bs.sector_size;;
u_int32_t start_fat2 = sizeof(BootSector) + start_fat1 + (bs.fat_size_sectors - 1) * bs.sector_size;
u_int32_t root_start = start_fat1 + bs.fat_size_sectors * bs.number_of_fats * bs.sector_size;
u_int32_t data_start = root_start + (sizeof(Entry) * (bs.root_dir_entries));
u_int32_t cluster_size = bs.sectors_per_cluster * bs.sector_size;
u_int32_t cluster[bs.sector_size];
u_int32_t pos = 0;
fseek(in, data_start, SEEK_SET);
int count = 0;
int zero = 0;
printf("LIVRE: ", count);
while(!feof(in)) {
//inicia novo cluster
zero = 0;
fread(&cluster, cluster_size, 1, in);
pos++;
for(i = 0; i < bs.sector_size; i++) {
if (cluster[i] != 0)
zero = 1;
}
if (!zero) {
count++;
if (j != 0)
printf(", ");
j++;
printf("%d",pos);
}
}
printf("\n");
//printf("TOTAL LIVRE: %d\n", count);
}
void blocos_deletados(FILE * in, BootSector bs) {
int nr_fat_sectors = (bs.fat_size_sectors * bs.sector_size / 2) - 2;
int i, j;
u_int32_t start_fat1 = sizeof(BootSector) + (bs.reserved_sectors-1) * bs.sector_size;;
u_int32_t start_fat2 = sizeof(BootSector) + start_fat1 + (bs.fat_size_sectors - 1) * bs.sector_size;
u_int32_t root_start = start_fat1 + bs.fat_size_sectors * bs.number_of_fats * bs.sector_size;
u_int32_t data_start = root_start + (sizeof(Entry) * (bs.root_dir_entries));
u_short fat1[nr_fat_sectors];
u_int32_t cluster_size = bs.sectors_per_cluster * bs.sector_size;
u_int32_t cluster[bs.sector_size];
u_int32_t pos = 0;
fseek(in, data_start, SEEK_SET);
int count = 2;
while(!feof(in)) {
pos = data_start + (count - 2 ) * cluster_size;
fread(&cluster, cluster_size, 1, in);
//if (cluster[0] != 0)
// printf("Endereco Utilizadas: 0x%04X Pos: %d\n", pos, count);
count++;
}
//printf("Nr clusters: %d\n", count);
fseek(in, start_fat1, SEEK_SET);
fread(&fat1, sizeof(fat1), 1, in);
printf("REMOVIDOS ");
int c = 0;
int achou = 0;
for (i = 2; i < count; i++) {
fseek(in, data_start + (i - 2 ) * cluster_size, SEEK_SET);
fread(&cluster, cluster_size, 1, in);
if (cluster[0] != 0) {
achou = 0;
for (j = 0; j < nr_fat_sectors; j++) {
if (fat1[j] != 0 && fat1[j] != 0xFFFF) {
if ((fat1[j] - 2) == i) {
achou = 1;
}
}
}
if (!achou) {
if (c > 0)
printf(",");
printf("%d",i);
c++;
}
}
}
printf("\n");
}
void corrige_fat(FILE * in, int nr_fat) {
BootSector bs = ReadBootSector(in);
int nr_fat_sectors = (bs.fat_size_sectors * bs.sector_size / 2) - 2;
//printf("nr_fat_sectors: %d\n", nr_fat_sectors);
u_int32_t start_fat1 = sizeof(BootSector) + (bs.reserved_sectors-1) * bs.sector_size;
u_int32_t start_fat2 = sizeof(BootSector) + start_fat1 + (bs.fat_size_sectors - 1) * bs.sector_size;
u_short fat1[nr_fat_sectors];
u_short fat2[nr_fat_sectors];
int i;
if (nr_fat == 1) {
fseek(in, start_fat1 + 4, SEEK_SET);
fread(&fat1, sizeof(fat1), 1, in);
fseek(in, start_fat2 + 4, SEEK_SET);
fwrite (fat1 , sizeof(fat1), 1, in);
} else if (nr_fat == 2) {
fseek(in, start_fat2 + 4, SEEK_SET);
fread(&fat2, sizeof(fat2), 1, in);
fseek(in, start_fat1 + 4, SEEK_SET);
fwrite (fat2 , sizeof(fat2), 1, in);
}
}
void copia_fat(FILE * in, FILE * out,int nr_fat_in, int nr_fat_out) {
BootSector bs_in = ReadBootSector(in);
BootSector bs_out = ReadBootSector(out);
u_int32_t start_fat_in;
u_int32_t start_fat_out;
int nr_fat_sectors = (bs_in.fat_size_sectors * bs_in.sector_size / 2) - 2;
u_short fat_in[nr_fat_sectors];
if(nr_fat_in == 1) {
start_fat_in = sizeof(BootSector) + (bs_in.reserved_sectors-1) * bs_in.sector_size;
} else {
u_int32_t start_fat1 = sizeof(BootSector) + (bs_in.reserved_sectors-1) * bs_in.sector_size;
start_fat_in = sizeof(BootSector) + start_fat1 + (bs_in.fat_size_sectors - 1) * bs_in.sector_size;
}
//printf("start_fat_in: 0x%04X\n", start_fat_in);
fseek(in, start_fat_in + 4, SEEK_SET);
fread(&fat_in, sizeof(fat_in), 1, in);
u_short fat_out[nr_fat_sectors];
if(nr_fat_out == 1) {
start_fat_out = sizeof(BootSector) + (bs_out.reserved_sectors-1) * bs_out.sector_size;
} else {
u_int32_t start_fat1 = sizeof(BootSector) + (bs_out.reserved_sectors-1) * bs_out.sector_size;
start_fat_out = sizeof(BootSector) + start_fat1 + (bs_out.fat_size_sectors - 1) * bs_out.sector_size;
}
//printf("start_fat_out: 0x%04X\n", start_fat_out);
fseek(out, start_fat_out + 4, SEEK_SET);
fwrite (fat_in , sizeof(fat_in), 1, out);
}
void ajuda() {
printf("Ajuda: \n");
printf(" -vf: Verificar se as duas FATs são iguais – caso não sejam, imprime uma lista de diferenças no seguinte formato, com uma linha para cada diferença.\n");
printf(" -bl: Imprime os índices de todos os blocos que estão livres (ou seja, não são apontados pela FAT) em uma única linha.\n");
printf(" -bd: Imprime os índices de todos os blocos que estão livres e que tem conteúdo diferente de zeros, em uma única linha.\n");
printf(" -cf1: Copia o conteúdo da segunda cópida da FAT na primeira cópia.\n");
printf(" -cf2: Copia o conteúdo da primeira cópida da FAT na segunda cópia.\n");
printf(" -cdf1: copia a fat1 de outro disco (disco_2) para fat1 do disco principal.\n");
printf(" -cdf2: copia a fat1 de outro disco (disco_2) para fat2 do disco principal.\n");
}
FILE * init(const char * fileName, char * str) {
FILE * fp = fopen(fileName, str);
return fp;
}
BootSector ReadBootSector(FILE * in) {
BootSector retorno;
rewind(in);
fread(&retorno, sizeof(BootSector), 1, in);
return retorno;
}
|
C
|
// PR c++/94695
// { dg-do compile { target c++11 } }
// { dg-options "-Wrange-loop-construct" }
#include <initializer_list>
struct Small {
char arr[64];
};
struct Big_aggr {
char arr[65];
};
struct Big_triv_copy {
char arr[65];
Big_triv_copy() { }
};
struct Big {
char arr[65];
Big () = default;
Big(const Big&);
};
struct Foo { };
struct Bar {
char arr[100];
Bar(Foo);
Bar(int);
operator int();
};
template<typename T>
struct It {
T operator*();
It operator++();
bool operator!=(const It);
};
template<typename T>
struct Cont {
using I = It<T>;
I begin();
I end();
};
#define TEST \
void fn_macro() \
{ \
Cont<Bar &> cont_bar_ref; \
for (const Bar x : cont_bar_ref) { (void) x; } \
}
TEST
Cont<Bar &>& foo ();
Cont<Bar &> foo2 ();
void
fn1 ()
{
for (const auto x : foo () ) { (void) x; } // { dg-warning "creates a copy" }
for (const auto x : foo2 () ) { (void) x; } // { dg-warning "creates a copy" }
Small s{};
Small sa[5] = { };
for (const auto x : sa) { (void) x; }
for (const auto x : { s, s, s }) { (void) x; }
Big_aggr b{};
Big_aggr ba[5] = { };
for (const auto x : ba) { (void) x; } // { dg-warning "creates a copy" }
for (const auto x : { b, b, b }) { (void) x; } // { dg-warning "creates a copy" }
Big_triv_copy bt{};
Big_triv_copy bta[5];
for (const auto x : bta) { (void) x; } // { dg-warning "creates a copy" }
for (const auto x : { bt, bt, bt }) { (void) x; } // { dg-warning "creates a copy" }
Big b2;
Big ba2[5];
for (const auto x : ba2) { (void) x; } // { dg-warning "creates a copy" }
for (const auto x : { b2, b2, b2 }) { (void) x; } // { dg-warning "creates a copy" }
}
void
fn2 ()
{
Cont<int> cont_int;
for (const auto x : cont_int) { (void) x; }
for (const int x : cont_int) { (void) x; }
for (int x : cont_int) { (void) x; }
for (const auto &x : cont_int) { (void) x; }
for (double x : cont_int) { (void) x; }
for (const double x : cont_int) { (void) x; }
for (const Bar x : cont_int) { (void) x; }
for (Bar x : cont_int) { (void) x; }
}
void
fn3 ()
{
Cont<int &> cont_int_ref;
for (const int x : cont_int_ref) { (void) x; }
for (int x : cont_int_ref) { (void) x; }
for (const double x : cont_int_ref) { (void) x; }
for (double x : cont_int_ref) { (void) x; }
for (const Bar x : cont_int_ref) { (void) x; }
for (Bar x : cont_int_ref) { (void) x; }
}
void
fn4 ()
{
Cont<Bar> cont_bar;
for (const Bar x : cont_bar) { (void) x; }
for (Bar x : cont_bar) { (void) x; }
for (const int x : cont_bar) { (void) x; }
for (int x : cont_bar) { (void) x; }
}
void
fn5 ()
{
Cont<Bar&> cont_bar_ref;
for (const Bar x : cont_bar_ref) { (void) x; } // { dg-warning "creates a copy" }
for (Bar x : cont_bar_ref) { (void) x; }
for (const int x : cont_bar_ref) { (void) x; }
for (int x : cont_bar_ref) { (void) x; }
}
void
fn6 ()
{
Cont<Foo> cont_foo;
for (const Bar x : cont_foo) { (void) x; }
for (Bar x : cont_foo) { (void) x; }
}
void
fn7 ()
{
Cont<Foo &> cont_foo_ref;
for (const Bar x : cont_foo_ref) { (void) x; }
for (Bar x : cont_foo_ref) { (void) x; }
}
void
fn8 ()
{
double arr[2];
for (const double x : arr) { (void) x; }
for (double x : arr) { (void) x; }
for (const int x : arr) { (void) x; }
for (int x : arr) { (void) x; }
for (const Bar x : arr) { (void) x; }
for (Bar x : arr) { (void) x; }
}
void
fn9 ()
{
Foo foo[2];
for (const Foo x : foo) { (void) x; }
for (Foo x : foo) { (void) x; }
for (const Bar x : foo) { (void) x; }
for (Bar x : foo) { (void) x; }
}
void
fn10 ()
{
Bar bar[2] = { 1, 2 };
for (const Bar x : bar) { (void) x; } // { dg-warning "creates a copy" }
for (Bar x : bar) { (void) x; }
for (const int x : bar) { (void) x; }
for (int x : bar) { (void) x; }
}
template<typename T>
void
fn11 ()
{
Cont<Bar> cont_bar;
for (const Bar x : cont_bar) { (void) x; }
Cont<Bar&> cont_bar_ref;
for (const Bar x : cont_bar_ref) { (void) x; } // { dg-warning "creates a copy" }
Cont<T> cont_dep;
for (const T x : cont_dep) { (void) x; }
}
template<typename T>
void
fn12 ()
{
for (const auto x : { T{} }) { (void) x; } // { dg-warning "creates a copy" }
}
void
invoke ()
{
fn11<int> ();
fn12<Big> ();
}
|
C
|
/*
** EPITECH PROJECT, 2023
** game_of_life
** File description:
** Created by Anthony Anicotte,
*/
#include <stdlib.h>
#include "struct.h"
void free_tab(char **tab)
{
for (int i = 0; tab[i] != NULL; i++)
free(tab[i]);
free(tab);
}
void free_structure(game_of_life_t *gol_struct)
{
free_tab(gol_struct->map);
free(gol_struct);
}
|
C
|
#include <stdio.h>
const double e = 0.0000001;
double start(double x){
return ((1+x)/2);
}
double heron(double w, double x){
double temp = ((w+(x/w))/2);
if ((w-temp) < e)
return temp;
return heron(temp,x);
}
int main(void){
double x = 123.4;
printf("Heron: %f\n", heron(start(x),x));
return 0;
}
|
C
|
#ifndef __LONG_DATA_UART_PROTOCOL__
#define __LONG_DATA_UART_PROTOCOL__
#include <Arduino.h>
#define MAX_MESG_SIZE 14
/// Enum for the states of the finite state machine which implements the Long
/// Data UART Protocol.
enum LDProtocolState
{
GET_HEADER,
GET_DATA,
GET_CHECKSUM,
};
/**
* This struct is used to implement and track the state of the Long Data UART
* Protocol as described in the LongDataUARTProtocol.md document. An instance of
* this struct must be declared and initialized to use the protocol.
*
* To use the Long Data UART Protocol, the user must:
*
* 1. Create an instance of this struct and initialize all fields to zero either
* manually or using the init_ldprotocol() function.
*
* 2. Inform the protocol handle (this struct) of where the mailboxes for
* receiving data are located and how big these mailboxes are using the
* register_mailbox() function.
*
* 3. Finally, call the recieve_message() function in a loop.
*
* Note that serial initialization is NOT performed by the init_ldprotocol()
* function. The user is responsible for initializing serial to their desired
* preference.
*/
struct LDProtocol
{
char mailbox_addr; ///< Mailbox to which the next message should be commited
char state; ///< Current state of the protocol. Used for controlling the protocol's FSM.
char bytes_total; ///< Total number of bytes the current message contains.
char packets_total; ///< Total number of packets the current message contains. Includes checksum.
char packets_current; ///< Sequence number of the last packet received.
unsigned char mesg_buffer[18]; ///< Buffer to place the message into while still receiving data.
char mailbox_sizes[8]; ///< Size of each mailbox in bytes.
unsigned char* mailboxes[8]; ///< pointers to each mailbox.
};
/**
* Initializes the given protocol handle to zero in all fields. Should be called
* before attempting to register new mailboxes or receive_messages.
*
* @param proto_handle: pointer to an LDProtocol struct.
*/
void init_ldprotocol(struct LDProtocol* proto_handle);
/**
* Informs the protocol handle of the location and size of a mailbox for data.
* Must be called before the mailbox with address 'which' can be used.
*
* @param which: which mailbox to register. Must not be greater than 7.
* @param mailbox: pointer to the buffer associated with the mailbox.
* @param size: size of the buffer in bytes. messages recieved for this mailbox must be less than this.
* @param proto_handle: pointer to the protocol handle.
*/
void register_mailbox(char which, void* mailbox, char size, struct LDProtocol* proto_handle);
/**
* Calculates the number of packets in a message including checksum for a message
* which contains some number of bytes.
*
* @param bytes: number of bytes the message contains.
* @return Number of packets the message is composed of. Includes checksum.
*/
char bytes_to_packets(char bytes);
/**
* This function operates the finite state machine for implementing the Long
* Data UART Protocol. Once mailboxes have been registered, this function should
* be called in a loop.
*
* @param proto_handle: pointer to the protocol handle.
*/
void recieve_message(struct LDProtocol* proto_handle);
#endif
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* select.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: tsanzey <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2016/10/23 14:20:42 by tsanzey #+# #+# */
/* Updated: 2016/10/23 14:20:45 by tsanzey ### ########.fr */
/* */
/* ************************************************************************** */
#include "push_swap.h"
#include <stdio.h>
int string_is_valid(char *str)
{
int i;
int j;
i = 0;
j = 0;
if (ft_strcmp(str, "") == 0)
return (0);
while (str[i])
{
if (str[i] == ' ')
j++;
i++;
}
if (i == j)
return (0);
return (1);
}
void push_swap_suite(t_shell *head)
{
while (l_len(head->sb) > 0)
{
while (l_len(head->sb) > 1 &&
l_nb(head->sb) > head->sb->nb)
ft_rrb(head, 1);
ft_pa(head, 1);
if (l_len(head->sb) > 1 && l_len(head->sa) > 1 &&
head->sa->nb > head->sa->n->nb && head->sb->nb < head->sb->n->nb)
ft_ss(head, 1);
else
{
if (head->sa->nb > head->sa->n->nb)
ft_sa(head, 1);
if (l_len(head->sb) > 1 &&
head->sb->nb < head->sb->n->nb)
ft_sb(head, 1);
}
}
}
void small_swap(t_shell *h)
{
while (l_len(h->sa) > 1)
{
if (l_len(h->sb) > 1 && h->sa->nb > h->sa->n->nb &&
h->sb->nb < h->sb->n->nb)
ft_ss(h, 1);
else if (h->sa->nb > h->sa->n->nb)
ft_sa(h, 1);
else if (l_len(h->sb) > 1 && h->sb->nb < h->sb->n->nb)
ft_sb(h, 1);
if (h->max == h->sa->nb || (l_len(h->sb) > 2 &&
h->sa->nb > h->sa->n->nb && h->sa->nb > h->sa->n->n->nb))
ft_ra(h, 1);
while (l_len(h->sa) > 2 &&
l_nb(h->sa) < h->sa->nb && l_nb(h->sa) < h->sa->n->nb)
ft_rra(h, 1);
if (l_len(h->sb) > 1 && l_nb(h->sb) > h->sb->nb)
ft_rrb(h, 1);
if (ft_sorted(h->sa))
break ;
ft_pb(h, 1);
if (l_len(h->sb) > 2 && ((h->sb->nb < h->sb->n->nb
&& h->sb->nb < h->sb->n->n->nb) || l_nb(h->sb) > h->sb->nb))
ft_rb(h, 1);
}
push_swap_suite(h);
}
void which_swap(t_shell *head)
{
if (l_len(head->sa) >= 40)
push_swap(head, INT_MIN, 0, 0);
else
{
while (ft_sorted(head->sa) == 0)
small_swap(head);
}
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* check_text.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: aouloube <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2015/12/08 10:18:46 by aouloube #+# #+# */
/* Updated: 2015/12/14 14:00:43 by nlagache ### ########.fr */
/* */
/* ************************************************************************** */
#include "fillit.h"
char *read_one(int fd, int index)
{
char buf[20];
int i;
int len;
char *res;
len = read(fd, buf, 20);
i = 0;
if (len < 20)
exit_error(7);
res = (char *)malloc(17 * sizeof(*res));
while (i < len)
{
if (buf[i] != '\n' && buf[i] != '.' && buf[i] != '#')
exit_error(1);
if (buf[i] == '#')
res[i - (i / 5)] = index + 'A';
else if ((buf[i] == '\n') && ((i % 5) != 4))
exit_error(2);
else
res[i - (i / 5)] = '.';
i++;
}
res[i - (i / 5)] = '\0';
check_tetris(res);
return (res);
}
t_tetris *read_file(char *file, t_tetris *tab)
{
int i;
int fd;
char buf[1];
fd = open(file, O_RDONLY);
tab[0].form = read_one(fd, 0);
tab[0].last_try = -1;
i = 1;
while (read(fd, buf, 1))
{
if (*buf != '\n')
exit_error(10);
tab[i].form = read_one(fd, i);
tab[i].last_try = -1;
i++;
}
close(fd);
check_tetris(tab[0].form);
return (tab);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main ()
{
int iSecret, iGuess;
srand (time(NULL));
iSecret = rand() % 10 + 1;
if (primo(2)) {
printf("sim");
} else {
printf("nao");
}
return 0;
}
int primo (int n) {
if (n == 1) return 0;{}
for (int i = 2; i < n; i++)
if (n % i == 0) return 0;
return 1;
}
|
C
|
/*
Print the sum of the divisors of a given n. (Given by input through standar input).
Example: input -> 12
output -> 28
*/
#include <stdio.h>
static unsigned int SumDiv (unsigned int n)
{
unsigned int sum = 0;
size_t d = 1;
while (d * d < n) {
if (n % d == 0)
sum += (d + (n / d));
d++;
}
if (d * d == n)
sum += d;
return sum;
}
int main (void)
{
unsigned int n;
scanf("%u", &n);
printf("%u\n", SumDiv(n));
return 0;
}
|
C
|
#ifndef MACHINEH
#define MACHINEH
//-------------------------------- The Machine ------------------------------//
// I want you to be totally honest with me about how the machine makes you feel.
//
// Each frame represents an instructions and a scope in which
// that instruction should be carried out. Instructions, like slaves,
// come in chains:
//
// Current frame
// vvv vvv
// Another frame
// vvv vvv
// Da base frame
//
// Most instructions are simply oysters waiting to be evaluated as code.
// Some, though, are flagged as special instructions to the machine ---
// adding values to the scope-to-be, handling special arguments to functions,
// and so on.
struct machine {
void (*decref) (machine * x);
int ref;
frame *now;
frame *current_frame;
frame *base_frame;
oyster *accumulator;
stack_trace *trace;
int paused;
};
// Stuff everybody wants:
// Stuff some people want:
machine *machine_copy(machine * m);
void set_accumulator(machine * m, oyster * value);
void push_new_instruction(machine * m, oyster * instruction, int flag);
void push_instruction_list(machine * m,
oyster * ins,
table * scope, table * scope_below);
//m->current_frame
//m->base_frame
//m->copy_frame
//------------------------- Stack Traces -----------------------------//
struct stack_trace {
void (*decref) (stack_trace * t);
int ref;
oyster *function;
int count;
frame *remove_when;
stack_trace *below;
};
stack_trace *make_stack_trace(oyster *function, frame *remove_when, stack_trace *below);
void stack_trace_free(stack_trace *t);
void push_stack_trace(oyster *function, frame *remove_when, machine *m);
void stack_trace_update(machine *m);
#endif
|
C
|
int gcd(int a, int b){
for(;;){
if(a==b) return a;
else if(a>b) a = a-b;
else b = b-a;
}
}
int main(){
int a = 10, b = 75;
int c = gcd(a,b);
syscall_print_int(c);
syscall_print_newline();
}
|
C
|
#include "lists.h"
/**
* free_listint- Free
*@head: Head of the list
* Return: No.
*/
void free_listint(listint_t *head)
{
listint_t *tmp;
while (head != NULL)
{
tmp = head;
head = head->next;
free(tmp);
}
}
|
C
|
/*
* Date: 2016-04-26
*/
/*==================[inclusions]=============================================*/
#include "sapi.h" // <= sAPI header
#include "sapi_i2c.h" /* <= sAPI I2C header */
#include "sapi_adc.h" // sAPI ADC header
/*===========================================================================*/
#define GY906_ADDR 0x00 // Dirección del sensor de temperatura
#define TAMB_ADDR 0x06 // Dirección de la temperatura de ambiente
#define TOBJ1_ADDR 0x07 // Dirección de la temperatura del objeto
/*===========================================================================*/
DEBUG_PRINT_ENABLE; // Declara debugPrint
/*=========[Función para convertir punto flotante a string]==================*/
static void floatToString( float valor, char *dst, uint8_t pos );
/*=========[MAIN]============================================================*/
int main(void){
/* ------------- DECLARACIONES --------------- */
uint16_t t_amb=0;
uint16_t t_obj1=0;
float temp,tension;
uint8_t dato[3];
uint8_t dataToRead;
char buffout[64];
/* ------------- INICIALIZACIONES ------------- */
boardConfig(); // Inicializar la placa
debugPrintConfigUart( UART_USB, 115200 ); // Inicializa la comunicación seire
// Imprimo cartel de inicio
debugPrintString( "***********************************************************\n\r" );
debugPrintString( "* Proyecto - 6648 Sistemas Embebidos *\n\r" );
debugPrintString( "***********************************************************\n\r" );
i2cConfig( I2C0, 100000 ); // Inicializa la comunicación I2C
adcConfig( ADC_ENABLE ); // Inicializa el ADC
/* ------------- REPETIR POR SIEMPRE ------------- */
while(1) {
/* Prendo el led azul */
gpioWrite( LEDB, ON );
delay(500);
/* Apago el led azul */
gpioWrite( LEDB, OFF );
delay(500);
/* Leo temperatura de ambiente del sensor */
dataToRead = TAMB_ADDR;
i2cRead( I2C0,GY906_ADDR,&dataToRead,1,TRUE,&dato,3,TRUE );
debugPrintString( "Temperatura de ambiente: " );
t_amb = dato[0];
t_amb |= dato[1]<<8;
temp = 0.02 * t_amb - 273.15;
floatToString( temp, buffout, 0 );
debugPrintString( buffout );
debugPrintString( " / " );
/* Leo temperatura de objeto del sensor */
dataToRead = TOBJ1_ADDR;
i2cRead( I2C0,GY906_ADDR,&dataToRead,1,TRUE,&dato,3,TRUE );
debugPrintString( "Temperatura de objeto: " );
t_obj1 = dato[0];
t_obj1 |= dato[1]<<8;
temp = 0.02 * t_obj1 - 273.15;
floatToString( temp, buffout, 0 );
debugPrintString( buffout );
debugPrintEnter();
/* Leo la tensión de la entreda analógica */
tension = adcRead( CH1 ) * 3.30 / 1024 ;
debugPrintString( "Entrada analógica: " );
floatToString( tension, buffout, 0 );
debugPrintString( buffout );
debugPrintEnter();
}
return 0 ;
}
/*=========[Función para convertir punto flotante a string]==================*/
static void floatToString( float valor, char *dst, uint8_t pos ){
uint16_t val;
val = 100 * valor;
dst[pos] = (val / 1000) + '0';
pos++;
dst[pos] = (val % 1000) / 100 + '0';
pos++;
dst[pos] = '.';
pos++;
dst[pos] = (val % 100) / 10 + '0';
pos++;
dst[pos] = (val % 10) + '0';
pos++;
dst[pos] = '\0';
}
/*==================[end of file]============================================*/
|
C
|
// main.c
// dz3
//
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include "tool.h"
#include "sort.h"
unsigned const int size = 4;
int main()
{
float container = 0;
FILE *theFile = fopen("Database.json", "w+");
FigureList *theList = createFigureList( abs(size) );
addCircle(theList, 1, 2, 3);
addCircle(theList, 3, 23, 14);
addCircle(theList, 4, 23, 43);
addCircle(theList, 12, 2, 11);
addCircle(theList, 123, 2, 12);
// Circle *aCircle = &(theList->circles[1]);
// container = Square(aCircle);
// printf("\nSquare = %i\n", container);
printf("\n .........................Before Sorting.........................\n");
printFigureList(theList);
Bubble_Sort_List(theList);
// Selection_Sort_List(theList);
// Insertion_Sort_List(theList);
printf("\n .........................After Sorting.........................\n");
printFigureList(theList);
fileWrite(theFile, theList);
destroyFigureList( theList );
fflush(theFile);
fclose(theFile);
return 0;
}
|
C
|
#include <ctype.h>
#include "stdio.h"
int main(void)
{
char s;
int n,count;
scanf("%d%*c",&n);
while(n--)
{
count=0;
do{
s=getchar();
if(isdigit(s))
count++;
}while(s!='\n');
printf("%d\n",count);
}
return 0;
}
|
C
|
//implement DNS_client using udp
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
void main()
{
int sockid;
char dname[50],ip[50];
struct sockaddr_in addr1;
sockid = socket(AF_INET,SOCK_DGRAM,0);
memset(&addr1,0,sizeof(addr1));
addr1.sin_family = AF_INET;
addr1.sin_addr.s_addr = INADDR_ANY;
addr1.sin_port = htons(8080);
printf("\nSending Domain name to server!");
scanf("%s",dname);
sendto(sockid,dname,strlen(dname),0,(struct sockaddr*)&addr1,sizeof(addr1));
printf("\nReceiving Corresponding Ip from server!");
recvfrom(sockid,ip,50,0,(struct sockaddr*)&addr1,sizeof(addr1));
printf("\nIp Address : %s",ip);
close(sockid);
}
|
C
|
// input: NCBI SRA FASTQ format
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#define READ_LEN 1000
#define READ1 1
#define READ2 2
int main(int argc, char *argv[])
{
FILE *f;
char buf[10000];
int len = 0, num = 0;
char head[READ_LEN];
char name[READ_LEN];
char part[READ_LEN];
int type = 0;
char read_num = '\0';
strcpy(buf, "");
strcpy(head, "");
strcpy(name, "");
strcpy(part, "");
if( argc != 2 ) {
printf("fastq_head fastq_file\n");
return EXIT_FAILURE;
}
if(!(f = fopen(argv[1], "r"))) {
printf("no file %s exists\n", argv[1]);
return EXIT_FAILURE;
}
while(fgets(buf, 10000, f))
{
num++;
if( (num % 4) == 1 ) {
len = strlen(buf);
if( buf[len-1] == '\n' ) {
read_num = buf[len-2];
if( read_num == '1' ) {
type = READ1;
strcpy(head, buf);
head[len-3] = '\0';
}
else if( read_num == '2' ) {
type = READ2;
strcpy(head, buf);
head[len-3] = '\0';
}
else {
printf("head line in wrong format: %s\n", buf);
return EXIT_FAILURE;
}
}
else {
read_num = buf[len-1];
if( read_num == '1' ) {
type = READ1;
strcpy(head, buf);
head[len-2] = '\0';
}
else if( read_num == '2' ) {
type = READ2;
strcpy(head, buf);
head[len-2] = '\0';
}
else {
printf("head line in wrong format: %s\n", buf);
return EXIT_FAILURE;
}
}
if( read_num == '1' ) {
if( sscanf(head, "%[^#]#%s", name, part ) != 2 ) {
printf("head line in wrong format: %s\n", head);
return EXIT_FAILURE;
}
printf("%s 1:%s\n", name, part);
}
else if( read_num == '2' ) {
if( sscanf(head, "%[^#]#%s", name, part ) != 2 ) {
printf("head line in wrong format: %s\n", head);
return EXIT_FAILURE;
}
printf("%s 2:%s\n", name, part);
}
else {
printf("head line in wrong format: %s\n", buf);
return EXIT_FAILURE;
}
}
else {
printf("%s", buf);
}
}
fclose(f);
return EXIT_SUCCESS;
}
|
C
|
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
#include<ctype.h>
#define max 5
void input_dequeue();
void output_dequeue();
void insert_right(int);
void insert_left(int);
void delete_right();
void delete_left();
void display_dequeue();
int deque[max];
int left=-1,right=-1;
void main()
{
int ch;
printf("\n********Type Double ended queue*****\n");
printf("\n 1.input_restricted deque \n");
printf("2.output_restricted deque \n");
printf("\nenter your choice of Queue Type :");
scanf("%d",&ch);
switch(ch)
{
case 1:input_dequeue();break;
case 2:output_dequeue();break;
default:printf("\n invalid operation");
}
}
void input_dequeue()
{
int ch1,no;
char ch='y';
while(ch=='y')
{
printf("\n\t1.insert in right");
printf("\n\t2.delete from left");
printf("\n\t3.delete from right");
printf("\n\t4.display");
printf("\n\tenter your option :");
scanf("%d",&ch1);
switch(ch1)
{
case 1:printf("enter a number ");
scanf("%d",&no);
insert_right(no);break;
case 2:delete_left();break;
case 3:delete_right();break;
case 4:display_dequeue();break;
}
printf("\n\t do another operation(y/n)");
ch=getche();
}
}
void output_dequeue()
{
int ch1,no;
char ch='y';
while(ch=='y')
{
printf("\n\t1.insert in right");
printf("\n\t2.insert in left");
printf("\n\t3.delete from left");
printf("\n\t4.display");
printf("\n\tenter your option :");
scanf("%d",&ch1);
switch(ch1)
{
case 1:printf("enter a number ");
scanf("%d",&no);
insert_right(no);
break;
case 2:printf("enter a number ");
scanf("%d",&no);
insert_left(no);
break;
case 3:delete_left();break;
case 4:display_dequeue();break;
}
printf("\n\t do another operation(y/n)");
ch=getche();
}
}
void insert_right(int num)
{
if((left==0&&right==max-1)||(left==right+1))
{
printf("\n deque overflow :");
return;
}
if(left==-1)
{
left=0;
right=0;
}
else if(right==max-1)
right=0;
else
right=right+1;
deque[right]=num;
}
void insert_left(int num)
{
if((left==0&&right==max-1)||(left==right+1))
{
printf("\n deque overflow :");
return;
}
if(left==-1)
{
left=0;
right=0;
}
else if(left==0)
left=max-1;
else
left=left-1;
deque[left]=num;
}
void delete_left()
{
int no;
if(left==-1)
{
printf("\n\tunderflow");
return ;
}
no=deque[left];
if(left==right)
{
left=-1;
right=-1;
}
else if(left==max-1)
{
left=0;
}
else
{
left=left+1;
}
printf("\n\t%d deleted ",no);
}
void delete_right()
{
int no;
if(left==-1)
{
printf("\n\tunderflow");
return ;
}
no=deque[right];
if(left==right)
{
left=-1;
right=-1;
}
else if(right==0)
{
right=max-1;
}
else
{
right=right-1;
}
printf("\n\t%d deleted ",no);
}
void display_dequeue()
{
int i;
if(left<=right)
{
for(i=left;i<=right;i++)
printf("%d ",deque[i]);
}
else
{
for(i=left;i<max;i++)
printf("%d ",deque[i]);
for(i=0;i<=right;i++)
printf("%d ",deque[i]);
}
}
|
C
|
#include <stdio.h>
int main( int argc, char *argv[])
{
/*printf("Height: ");
int height= get_int("Height: ");
while( height < 0 || height < 1){
height = get_int("Height: ");
}*/
int height = (int) argv[1];
for(int i = 0 ; i <= height ;i++){
printf("#");
printf("\n");
}
return 0;
}
|
C
|
#include "cem.h"
#define STD_OBJ 1
#include "stdobj.h"
#include "symbol.h"
#include "type.h"
/*
* Type creation routines.
*/
/*
* We keep a cache of data objects rather than allowing malloc
* to inefficiently recycle them.
*/
static e_elt *e_elt_free;
static s_elt *s_elt_free;
static u_elt *u_elt_free;
static e_data *e_data_free;
static s_data *s_data_free;
static u_data *u_data_free;
static type *type_free;
/*
* Allocation routines.
*/
static type *
new_type()
{
register type *p;
if (type_free == NULL)
return talloc(type);
p = type_free;
type_free = p->t_subtype;
return p;
}
static void
free_e_elt(p)
e_elt *p;
{
p->e_next = e_elt_free;
e_elt_free = p;
}
static void
free_s_elt(p)
s_elt *p;
{
p->s_next = s_elt_free;
s_elt_free = p;
}
static void
free_u_elt(p)
u_elt *p;
{
p->u_next = u_elt_free;
u_elt_free = p;
}
static void
free_type(p)
type *p;
{
p->t_subtype = type_free;
type_free = p;
}
static void
free_e_data(p)
e_data *p;
{
p->e_u.e_n = e_data_free;
e_data_free = p;
}
static void
free_s_data(p)
s_data *p;
{
p->s_u.s_n = s_data_free;
s_data_free = p;
}
static void
free_u_data(p)
u_data *p;
{
p->u_u.u_n = u_data_free;
u_data_free = p;
}
static void
free_elist(p)
register e_elt *p;
{
register e_elt *q;
while (p != NULL)
{
q = p->e_next;
p->e_next = e_elt_free;
e_elt_free = p;
p = q;
}
}
static void
free_slist(p)
register s_elt *p;
{
register s_elt *q;
while (p != NULL)
{
q = p->s_next;
p->s_next = s_elt_free;
s_elt_free = p;
p = q;
}
}
static void
free_ulist(p)
register u_elt *p;
{
register u_elt *q;
while (p != NULL)
{
q = p->u_next;
p->u_next = u_elt_free;
u_elt_free = p;
p = q;
}
}
void
delete_type(p)
register type *p;
{
switch (p->t_type)
{
case t_enum:
free_elist(p->d.e->e_list);
p->d.e->e_u.e_n = e_data_free;
e_data_free = p->d.e;
break;
case t_structof:
free_slist(p->d.s->s_list);
p->d.s->s_u.s_n = s_data_free;
s_data_free = p->d.s;
break;
case t_unionof:
free_ulist(p->d.u->u_list);
p->d.u->u_u.u_n = u_data_free;
u_data_free = p->d.u;
}
p->t_subtype = type_free;
type_free = p;
}
/*
* Constructors.
*/
static type *
make_enum(n, f, l)
symbol *n;
symbol *f;
long l;
{
register type *p;
register e_data *e;
if (e_data_free == NULL)
e = talloc(e_data);
else
{
e = e_data_free;
e_data_free = e->e_u.e_n;
}
p = new_type();
p->t_type = t_enum;
p->d.e = e;
e->e_file = f;
e->e_line = l;
e->e_name = n;
e->e_list = NULL;
return p;
}
static type *
make_struct(n, f, l)
symbol *n;
symbol *f;
long l;
{
register type *p;
register s_data *s;
if (s_data_free == NULL)
s = talloc(s_data);
else
{
s = s_data_free;
s_data_free = s->s_u.s_n;
}
p = new_type();
p->t_type = t_structof;
p->d.s = s;
s->s_file = f;
s->s_line = l;
s->s_name = n;
s->s_list = NULL;
return p;
}
static type *
make_union(n, f, l)
symbol *n;
symbol *f;
long l;
{
register type *p;
register u_data *u;
if (u_data_free == NULL)
u = talloc(u_data);
else
{
u = u_data_free;
u_data_free = u->u_u.u_n;
}
p = new_type();
p->t_type = t_unionof;
p->d.u = u;
u->u_file = f;
u->u_line = l;
u->u_name = n;
u->u_list = NULL;
return p;
}
/*
* Elaborators.
*/
static void
elab_enum(p, f, l, m)
type *p;
symbol *f;
long l;
long m;
{
register e_data *e;
register e_elt **n;
register long l0;
e = p->d.e;
e->e_file = f;
e->e_line = l;
n = &e->e_list;
l0 = m;
do
{
if (e_elt_free == NULL)
*n = talloc(e_elt);
else
{
*n = e_elt_free;
e_elt_free = (*n)->e_next;
}
(*n)->e_name = str_trans[l0];
(*n)->e_value = getv();
n = &(*n)->e_next;
}
while ((l0 = getv()) != 0);
*n = NULL;
e->e_low = getu();
e->e_high = getu();
}
static void
elab_struct(p, f, l)
type *p;
symbol *f;
long l;
{
register s_data *s;
register s_elt **n;
register long l0;
s = p->d.s;
s->s_file = f;
s->s_line = l;
n = &s->s_list;
l0 = getv();
do
{
if (s_elt_free == NULL)
*n = talloc(s_elt);
else
{
*n = s_elt_free;
s_elt_free = (*n)->s_next;
}
(*n)->s_name = str_trans[l0];
(*n)->s_ptype.index = getv();
(*n)->s_offset = getv();
n = &(*n)->s_next;
}
while ((l0 = getv()) != 0);
*n = NULL;
s->s_size = getv();
}
static void
elab_union(p, f, l)
type *p;
symbol *f;
long l;
{
register u_data *u;
register u_elt **n;
register long l0;
u = p->d.u;
u->u_file = f;
u->u_line = l;
n = &u->u_list;
l0 = getv();
do
{
if (u_elt_free == NULL)
*n = talloc(u_elt);
else
{
*n = u_elt_free;
u_elt_free = (*n)->u_next;
}
(*n)->u_name = str_trans[l0];
(*n)->u_ptype.index = getv();
n = &(*n)->u_next;
}
while ((l0 = getv()) != 0);
*n = NULL;
u->u_size = getv();
}
/*
* Enter types from input file. Construct type translation table.
*/
void
enter_types(n)
register long n;
{
register int i;
register type *p;
register type **v;
v = (type **)salloc(n * sizeof (type *));
type_trans = v;
while (data_ptr < data_end)
{
register long l0;
register long l1;
register long l2;
i = getd();
switch (obj_item(i))
{
case i_data:
skip();
skip();
skip();
loop
{
i = getd();
switch (obj_item(i))
{
case d_addr:
skip4();
continue;
case d_bytes:
if (obj_id(i) == 0)
l0 = getv();
else
l0 = obj_id(i);
data_ptr += l0;
continue;
case d_end:
break;
case d_istring:
if (obj_id(i) == 0)
l0 = getv();
else
l0 = obj_id(i);
str_num++;
data_ptr += l0;
continue;
case d_irstring:
if (obj_id(i) == 0)
l0 = getv();
else
l0 = obj_id(i);
str_num++;
data_ptr += l0;
skip4();
continue;
case d_space:
if (obj_id(i) == 0)
skip();
continue;
case d_string:
skip();
continue;
case d_reloc:
case d_rstring:
skip();
skip4();
continue;
default:
fprintf(stderr, "%s: unknown data id %d\n", my_name, i);
exit(1);
}
break;
}
break;
case i_lib:
in_lib = 1;
src_file = str_trans[getv()];
break;
case i_src:
in_lib = 0;
src_file = str_trans[getv()];
break;
case i_string:
if (obj_id(i) == 0)
l0 = getv();
else
l0 = obj_id(i);
data_ptr += l0;
break;
case i_type:
switch (obj_id(i))
{
case t_arrayof:
p = talloc(type);
p->t_type = t_arrayof;
p->d.dim = getv();
p->t_subindex = getv();
v[type_index++] = p;
break;
case t_basetype:
p = talloc(type);
p->t_type = t_basetype;
p->d.mask = getd();
v[type_index++] = p;
break;
case t_bitfield:
p = talloc(type);
p->t_type = t_bitfield;
p->d.size = getv();
p->t_subindex = getv();
v[type_index++] = p;
break;
case t_dimless:
p = talloc(type);
p->t_type = t_dimless;
p->t_subindex = getv();
v[type_index++] = p;
break;
case t_elaboration:
l0 = getv();
l1 = getv();
l2 = getv();
switch (i = obj_id(getd()))
{
case t_enum:
elab_enum(v[l0], str_trans[l1], l2, getv());
break;
case t_structof:
elab_struct(v[l0], str_trans[l1], l2);
break;
case t_unionof:
elab_union(v[l0], str_trans[l1], l2);
break;
default:
fprintf(stderr, "%s: unknown elaboration id %d\n", my_name, i);
exit(1);
}
break;
case t_enum:
l0 = getv();
l1 = getv();
l2 = getv();
v[type_index] = make_enum(str_trans[l0], str_trans[l1], l2);
l0 = getv();
if (l0 != 0)
elab_enum(v[type_index], str_trans[l1], l2, l0);
type_index++;
break;
case t_ftnreturning:
p = talloc(type);
p->t_type = t_ftnreturning;
p->t_subindex = getv();
v[type_index++] = p;
break;
case t_ptrto:
p = talloc(type);
p->t_type = t_ptrto;
p->t_subindex = getv();
v[type_index++] = p;
break;
case t_structof:
l0 = getv();
l1 = getv();
l2 = getv();
v[type_index++] = make_struct(str_trans[l0], str_trans[l1], l2);
break;
case t_unionof:
l0 = getv();
l1 = getv();
l2 = getv();
v[type_index++] = make_union(str_trans[l0], str_trans[l1], l2);
break;
default:
fprintf(stderr, "%s: unknown type id %d\n", my_name, obj_id(i));
exit(1);
}
break;
case i_var:
switch (obj_id(i))
{
case v_arglist:
skip();
skip();
skip();
while (getv() != 0)
{
skip();
skip();
skip();
}
break;
case v_array_size:
skip();
skip();
break;
case v_call:
skip();
skip();
skip();
while (getv() != 0)
;
break;
case v_auto:
case v_block_static:
case v_global:
case v_implicit_function:
case v_static:
skip();
skip();
skip();
skip();
break;
case v_varargs:
skip();
skip();
break;
default:
fprintf(stderr, "%s: unknown var id %d\n", my_name, obj_id(i));
exit(1);
}
break;
default:
fprintf(stderr, "%s: unknown obj_item %d\n", my_name, obj_item(i));
exit(1);
}
}
fix_types(n);
}
|
C
|
/*
* problem01.c
*
* Created on: Feb 5, 2019
* Author: tcrokicki
* Description: [ADD DESCRIPTON]
*/
#include<stdio.h>
#include "myflush.h"
void execute_problem01() {
printf("START PROBLEM 1\n");
int position = 0, arr[10], element, count = 0;
printf("Enter 10 numbers: \n");
for (int i = 0; i < 10; i++) {
scanf("%d", &arr[i]);
clean_stdin();
}
printf("Enter element to be searched: \n");
scanf("%d", &element);
clean_stdin();
for (int i = 0; i < 10; i++) {
if (arr[i] == element) {
position = i + 1;
printf("Element %d found at position %d. \n", element, position);
count++;
}
}
if (count > 0) {
printf("Element %d occurs %d times. \n", element, count);
} else {
printf("Element %d not found. \n", element);
}
}
|
C
|
/*
* main.c
*
* Created on: 10 dic 2019
* Author: simone
*/
#include <stdio.h>
#include <stdlib.h>
// funzione per stamapre la sequenza di caratteri secondo la frequenza desiderata
void StampaNcarattteri( FILE* file_caratteri, int frequenza );
// funzione per contare il numero di presenza di un carattere tra quelli stampati
int ContaCarattereSelezionato( FILE* file_caratteri, int frequenza, char carattere_selezionato );
int main()
{
FILE* file_read;
file_read = fopen("file.txt","r");
if( file_read == NULL )
{
printf("ERRORE: file non aperto! \n");
}
else
{
int frequenza_caratteri_stampa;
char seleziona_carattere;
printf("Inserisci la frequenza di caratteri da stampare nel file \n");
scanf("%d" ,&frequenza_caratteri_stampa);
StampaNcarattteri(file_read, frequenza_caratteri_stampa);
// riporto testina all'inizio del file
rewind(file_read);
// svuoto buffer di input
fflush(stdin);
printf("\nInserisci il carattere di cui vuoi contare la frequenza tra i caratteri stampati \n");
scanf("%c" ,&seleziona_carattere);
int num_caratteri = ContaCarattereSelezionato( file_read, frequenza_caratteri_stampa, seleziona_carattere );
printf("La frequenza del carattere selezionato tra quelli stampati e' %d \n" ,num_caratteri);
}
system("pause");
return 0;
}
void StampaNcarattteri( FILE* file_caratteri, int frequenza )
{
int count = 1;
if( frequenza > 0 )
{
while( !feof(file_caratteri) )
{
char carattere_file = fgetc(file_caratteri);
if( count % frequenza == 0 )
{
printf(" %c " ,carattere_file);
}
count = count + 1;
}
}
}
int ContaCarattereSelezionato( FILE* file_caratteri, int frequenza, char carattere_selezionato )
{
int count = 1;
int count_caratteri = 0;
if( frequenza > 0 )
{
while( !feof(file_caratteri) )
{
char carattere_file = fgetc(file_caratteri);
if( count % frequenza == 0 && carattere_file == carattere_selezionato )
{
count_caratteri = count_caratteri + 1;
}
count = count + 1;
}
}
return count_caratteri;
}
|
C
|
#include <stdio.h>
#include <signal.h>
#include <unistd.h>
void sig_func(int signum)
{
printf("信号%d触发了\n",signum);
sleep(3);
printf("信号处理完毕\n");
}
int main()
{
struct sigaction act = {};
act.sa_handler = sig_func;
sigaddset(&act.sa_mask,SIGINT);
sigaction(SIGINT,&act,NULL);
for(;;)
{
printf("*\n");
sleep(1);
}
}
|
C
|
/*
** EPITECH PROJECT, 2019
** generator
** File description:
** check_error.c
*/
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
int check_nbr(char *str)
{
for (int i = 0; str[i]; i++)
if (isdigit(str[i]) == 0)
return (84);
return (0);
}
int check_error(int ac, char **av)
{
if (ac != 4 && ac != 3)
return (84);
if (check_nbr(av[1]) == 84 || check_nbr(av[2]) == 84)
return (84);
if (atoi(av[1]) <= 0 || atoi(av[2]) <= 0)
return (84);
if (ac == 4)
if (strcmp(av[3], "perfect") != 0)
return (84);
return (0);
}
|
C
|
#include <pthread.h>
#include <unistd.h>
pthread_mutex_t lock;
int main() {
if (pthread_mutex_init(&lock, NULL) != 0)
{
printf("\n First initialization of mutex failed\n");
return 1;
}
pthread_mutex_lock(&lock);
pthread_mutex_unlock(&lock);
}
|
C
|
//Write a C program to find HCF (GCD) of two numbers.
#include <stdio.h>
void main()
{int i,x,y,n;
printf("Enter 2 numbers:");
scanf("%d %d",&x,&y);
for(i=1;i<=x; i++)
if(x%i==0 && y%i==0)
n=i;
printf("\nHCF of %d and %d is:%d",x,y,n);
}
|
C
|
#include <stdio.h>
void printArr(int arr[], int length);
void josephArr(int arr[], int length){
int arr2[length];
int i = 0;
int j = 0;
for(i=0; i<length; i++){
if(i+1 % 3 == 0){
continue;
}
arr2[j] = arr[i];
j++;
}
printArr(arr2, length);
}
void printArr(int arr[], int length){
int i = 0;
printf("arr=[");
for(i=0; i<length; i++){
if(i==length-1){
printf("%d]", arr[i]);
}else{
printf("%d,", arr[i]);
}
}
printf("\n");
}
int main(void){
int arr[6] = {1,2,3,4,5,6};
int length = sizeof(arr) / sizeof(int);
int i = 0;
printArr(arr, length);
josephArr(arr, length);
return 0;
}
|
C
|
/****************************************************************************
**
** modmem.c ANU SQ Alice C Niemeyer
**
** Copyright 1994 Mathematics Research Section
** School of Mathematical Sciences
** Australian National University
*/
#include <stdio.h>
#include "pres.h"
#include "sq.h"
#include "pcparith.h"
extern Presentation *P;
extern GroupWord CollectGroupWord();
/* The Error Function */
void Error( str )
char *str;
{
fprintf( stderr, "%s\n", str );
exit(1);
}
/****************************************************************************
**
** Memory Allocation
**
** The following functions allocate memory for the various data objects.
*/
/*
** Allocate storage for a group word of length <nr>.
*/
GroupWord NewGroupWord( nr )
uint nr;
{
GroupWord w;
w = (GroupWord) Allocate( (nr+1)*sizeof(GroupGenerator) );
return w;
}
GroupWord GroupWordOne()
{
GroupWord w;
w = NewGroupWord(1);
w->gen = 1;
w->exp = 0;
return w;
}
GroupWord CopyGroupWord(w)
GroupWord w;
{
GroupWord v, r;
if ( w == (GroupWord) NULL ) return w;
if ( ISONEGG(w) ) return IdGrp;
r = v = NewGroupWord( LengthGroupWord(w) );
while( ISBOUNDGG(w) ) {
v->gen = w->gen;
v->exp = w->exp;
v++; w++;
}
return r;
}
/*
** The elements of the group ring are arrays of RingElements.
** Allocate storage for an array of length <nr>.
** Note that no storage is allocated for the group words.
*/
RingWord NewRingWord( nr )
uint nr;
{
RingWord w;
w = (RingWord) Allocate( (nr+1)*sizeof(struct RingElement) );
return w;
}
RingWord RingWordOne()
{
RingWord r;
r = NewRingWord(1);
r->mult = 1;
r->ring = IdGrp;
return r;
}
RingWord CopyRingWord(w)
RingWord w;
{
RingWord r, v;
if ( w == (RingWord) NULL ) return w;
if ( ISONERE(w) ) return RingWordOne();
r = NewRingWord( LengthRingWord(w) );
for ( v = r; ISBOUNDRE(w); v++, w++){
v->ring = CopyGroupWord( w->ring );
v->mult = w->mult;
}
return r;
}
/*
** Allocate storage for a vector of length <nr>.
*/
Vector NewVector( nr )
uint nr;
{
Vector v;
v = (Vector) Allocate( (nr+1)*sizeof(ModuleGenerator) );
return v;
}
Vector VectorOne()
{
Vector v;
v = NewVector(1);
v->gen = 1;
v->exp = NULL;
return v;
}
Vector NormalNewVector( l )
uint l;
{
Vector tv;
int i;
tv = NewVector (l);
for ( i = 0; i < l; i++ ) {
tv[i].gen = P->Nr_GroupGenerators + i + 1;
tv[i].exp = (RingWord) NULL;
}
return tv;
}
Vector CopyVector(v)
Vector v;
{
Vector w, x;
if ( v == (Vector) NULL) return v;
if ( ISONEMG(v) ) return VectorOne();
w = NewVector (LengthVector (v));
for ( x = w; ISBOUNDMG(v); v++, x++ ) {
x->gen = v->gen;
x->exp = CopyRingWord( v->exp );
}
return w;
}
ExtensionElement *CopyExtensionElement(ee)
ExtensionElement *ee;
{
ExtensionElement *res;
res = (ExtensionElement *) Allocate( sizeof(ExtensionElement) );
res->group = CopyGroupWord( ee->group );
res->vector = CopyVector( ee->vector );
return res;
}
Presentation *NewPresentation()
{
Presentation *P;
P = (Presentation*) Allocate( sizeof(Presentation) );
P->name = "SqPresentation";
return P;
}
/*
** Allocate storage for an ExtensionElement.
** Note that no storage is allocated for the struct entries.
*/
ExtensionElement *NewExtensionElement()
{
ExtensionElement *e;
e = (ExtensionElement *) Allocate( sizeof(struct _ExtensionElement) );
return e;
}
/****************************************************************************
**
** Free
**
** The following functions deal with freeing the data structures.
*/
void FreeGroupWord( w )
GroupWord w;
{
if ( w == (GroupWord) NULL || w == IdGrp ) return;
Free( (void *) w);
}
void FreeRingWord( w )
RingWord w;
{
RingWord v;
if ( w == (RingWord) NULL ) return;
for ( v = w; ISBOUNDRE(v); v++ )
FreeGroupWord(v->ring);
Free( (void *) w);
}
void FreeVector( v )
Vector v;
{
Vector w;
if ( v == (Vector) NULL ) return;
for ( w = v; ISBOUNDMG(w); w++ )
FreeRingWord(w->exp);
Free( (void *) v);
}
void FreeExtensionElement( e )
ExtensionElement *e;
{
FreeGroupWord( e->group );
FreeVector( e->vector );
Free( (void *) e );
}
/****************************************************************************
**
** Print
**
** The following functions print the data structures.
*/
PrintGeneratorVE( fpt, i )
FILE * fpt;
int i;
{
i -= 1;
while ( i >= 0) {
fputc( 'a' + i%26, fpt );
i /= 26;
i -= 1;
}
}
PrintGenerator( fpt, i )
FILE * fpt;
int i;
{
fprintf( fpt, "a.%d", i );
}
/*
** The following function prints a GroupWord. If the flag ve is non-zero,
** it is printed in the format used by the Vector Enumerator. This means in
** particular that the power a^2 is printed as a2. If ve is zero it is
** printed in GAP format.
*/
PrintGroupWord (g,f,ve)
GroupWord g;
FILE *f;
int ve;
{
char c;
if ( g == (GroupWord) NULL ) return;
if ( ISONEGG(g) ) {
fprintf( f, "1" );
return;
}
c = ' ';
if (ve)
for ( ; ISBOUNDGG(g); g++ ) {
fputc( c, f );
PrintGeneratorVE( f, g->gen );
if ( g->exp != 1 )
fprintf( f, "%d", g->exp );
c = '*';
}
else
for ( ; ISBOUNDGG(g); g++ ) {
if ( c != ' ' )
fputc( c, f );
PrintGenerator( f, g->gen );
if ( g->exp != 1 )
fprintf( f, "^%d", g->exp );
c = '*';
}
}
PrintRingWord ( w, f, ve )
RingWord w;
FILE *f;
int ve;
{
int printed;
GroupWord gw;
if ( w == (RingWord) NULL || (w->mult == 0 && w->ring == NULL)) {
fprintf( f, "0" );
return;
}
printed = 0;
for ( ; ISBOUNDRE(w); w++ ){
if ( w->mult != 0 ) {
if ( printed ) fprintf( f, " + " );
#ifdef COLLECT
gw = CollectGroupWord( w->ring );
#else
gw = w->ring;
#endif
if ( w-> mult != 1 ) fprintf( f, "%d * ", w->mult );
if( gw != NULL && ISBOUNDGG(gw) )
PrintGroupWord( gw, f, ve );
else
fprintf( f, "1" );
printed = 1;
#ifdef COLLECT
FreeGroupWord( gw );
#endif
}
}
if ( !printed )
fprintf( f, "0" );
}
PrintVector (v, f)
Vector v;
FILE *f;
{
char c;
if ( v == (Vector) NULL ) return;
if ( ISONEMG(v) ) {
fprintf( f, "1" );
return;
}
c = ' ';
for ( ; ISBOUNDMG(v); v++ ) {
if ( v->exp != (RingWord) NULL && (v->exp)->mult != 0 ) {
if ( c == '*' ) fputc( c, f );
fprintf( f, "t%d", v->gen-P->Nr_GroupGenerators);
c = '*';
if ( ISBOUNDRE(v->exp) && !ISONERE(v->exp) ){
fprintf( f, "^(" );
PrintRingWord( v->exp, f, 0 );
fprintf( f, ")" );
}
}
}
}
PrintExtensionElement (e,f)
ExtensionElement *e;
FILE *f;
{
int vecone, grpone;
vecone = grpone = 1;
if ( e == (ExtensionElement *) NULL ) return;
if ( e->vector != NULL && ISBOUNDMG(e->vector) && !ISONEMG(e->vector) )
vecone = 0;
if ( e->group != NULL && ISBOUNDGG(e->group) && !ISONEGG(e->group) )
grpone = 0;
if ( !grpone )
PrintGroupWord( e->group, f, 0 );
if ( !vecone || (grpone && vecone) ) {
if (!grpone) fprintf( f, "*" );
PrintVector( e->vector, f );
}
}
PrintExPresentation (f)
FILE *f;
{
register i, j;
if ( P->Nr_Generators == P->Nr_GroupGenerators ) {
fprintf( f, "a := FreeGroup( %d, \"a\" );\n", P->Nr_Generators );
}
fprintf(f,"%s := rec(\n", P->name );
fprintf(f," generators := [ ");
for ( i = 1; i < P->Nr_Generators; i++ ) {
if ( i <= P->Nr_GroupGenerators )
PrintGenerator( f, i );
else
fprintf( f, "t%d", i-P->Nr_GroupGenerators );
fprintf( f, ", ");
}
if ( P->Nr_GroupGenerators == P->Nr_Generators ) {
PrintGenerator( f, P->Nr_Generators );
fprintf( f, " ],\n" );
}
else
fprintf( f, "t%d ],\n", P->Nr_Generators-P->Nr_GroupGenerators );
/* fprintf(f," exponents := [");
for ( i = 1; i < P->Nr_Generators; i++ )
fprintf(f,"%d,", P->exponents[i] );
fprintf(f,"%d ],\n", P->exponents[P->Nr_Generators] );
*/
fprintf(f," relators := [\n");
/* Don't print the other relations, since they are not inserted!! */
for ( i = 1; i <= P->Nr_GroupGenerators; i++ ){
for ( j = 1; j <= i; j++ ){
if ( i != j ) {
PrintGenerator( f, i );
fprintf( f, "^" );
PrintGenerator( f, j );
}
else {
PrintGenerator( f, i );
fprintf( f, "^%d", P->exponents[i] );
}
if ( (P->relations[i][j]).group != (GroupWord) NULL )
if ( !ISONEEE(&P->relations[i][j]) &&
(P->relations[i][j].group->gen != 0 ||
(P->relations[i][j].vector != NULL &&
!ISONEMG(P->relations[i][j].vector))) ){
fprintf( f, "/(");
PrintExtensionElement( &P->relations[i][j],f );
fprintf( f, ")");
}
if ( j <= i ) fprintf( f, ", " );
}
fprintf(f, "\n");
}
fprintf( f, "]\n" );
fprintf( f, "# Definitions\n");
for ( i = 1; i <= P->Nr_Generators; i++ )
if ( !P->defepi[i] && P->definedby[i] != (int *) NULL ) {
if ( i > P->Nr_GroupGenerators )
fprintf( f, "# t%d <- ", i - P->Nr_GroupGenerators );
else {
fprintf( f, "# ");
PrintGenerator( f, i );
fprintf( f, " <- " );
}
if ( P->definedby[i][0] == P->definedby[i][1] ) {
/* defined as a $p$-th power */
if ( P->definedby[i][0] > P->Nr_GroupGenerators )
fprintf ( f, "t%d^%d\n",
P->definedby[i][0]-P->Nr_GroupGenerators,
P->exponents[P->definedby[i][0]-P->Nr_GroupGenerators] );
else {
PrintGenerator ( f, P->definedby[i][0] );
fprintf( f, "^%d\n", P->exponents[P->definedby[i][0]] );
}
}
else {
if ( P->definedby[i][1] > P->Nr_GroupGenerators ) {
fprintf ( f, "t%d^" );
PrintGenerator(f,P->definedby[i][1]-P->Nr_GroupGenerators);
}
else {
PrintGenerator( f, P->definedby[i][1] );
fprintf ( f, "^" );
}
if ( P->definedby[i][0] > P->Nr_GroupGenerators ) {
fprintf ( f, "t%d\n",
P->definedby[i][0]-P->Nr_GroupGenerators );
}
else {
PrintGenerator ( f, P->definedby[i][0] );
fprintf ( f, "\n" );
}
}
}
fprintf( f, "# Epimorphism : " );
for ( i = 1; i <= P->Nr_Orig; i++ ) {
fprintf( f, "phi(%d) ", i );
if ( IsDefEpi(i) ) fprintf( f, ":" );
fprintf( f, "= ");
PrintExtensionElement( &(P->Epimorphism[i]), f );
if ( i < P->Nr_Orig )
fprintf( f, ", " );
else
fprintf( f, " " );
}
fprintf( f, "\n)\n\n");
}
IsTrivialRingWord ( w )
RingWord w;
{
for ( ; ISBOUNDRE(w); w++ )
if (w->mult != 0) return 0;
return 1;
}
/*
** Print the module enumerator relations in packed format.
*/
int PrintMERelation( lhs, rhs, f )
ExtensionElement *lhs, *rhs;
FILE *f;
{
RingWord r;
Vector v1, v2;
uint i, printed;
v1 = lhs->vector;
v2 = rhs->vector;
printed = 0;
for ( i = 1; i <= P->Nr_Generators - P->Nr_GroupGenerators; i++ ) {
if ( v1 && ISBOUNDMG(v1) && (v1->gen == i+P->Nr_GroupGenerators) ) {
if ( (v2 == NULL) ||
(ISBOUNDMG(v2) && (v2->gen != i+P->Nr_GroupGenerators))){
if ( v1->exp != NULL && ISBOUNDRE(v1->exp) &&
!IsTrivialRingWord( v1->exp ) ) {
if ( printed ) fprintf( f, ", " );
else fprintf( f, "[" );
fprintf( f, "%d, ", i );
PrintRingWord( v1->exp, f, 1 );
printed = 1;
}
}
else {
r = SubRingWord( v1->exp, v2->exp );
if ( r != NULL && ISBOUNDRE(r) && !IsTrivialRingWord(r) ) {
if ( printed ) fprintf( f, ", " );
else fprintf( f, "[" );
fprintf( f, "%d, ", i );
PrintRingWord( r, f, 1 );
printed = 1;
}
FreeRingWord(r);
v2++;
}
v1++;
}
else if (v2 && ISBOUNDMG(v2) && (v2->gen == i+P->Nr_GroupGenerators)){
if ( v2->exp != NULL && ISBOUNDRE(v2->exp) ) {
if ( printed ) fprintf( f, ", " );
else fprintf( f, "[" );
fprintf( f, "%d, ", i );
r = SubRingWord( 0, v2->exp );
PrintRingWord( r, f, 1 );
printed = 1;
FreeRingWord(r);
}
v2++;
}
}
if( printed ) fprintf( f, "]" );
return printed;
}
|
C
|
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include "common.h"
#include "solvers.h"
#include "poissoncommon.h"
double alpha=0.1;
double exact(double x)
{
return x*(pow(x,5.0)-1.0);
}
double source(double x)
{
return -30*pow(x,4.0);
}
int GaussJacobiPoisson1D(Vector u, double tol, int maxit)
{
int it=0, i;
double rl;
double max = tol+1;
Vector b = createVector(u->len);
Vector e = createVector(u->len);
copyVector(b, u);
fillVector(u, 0.0);
rl = maxNorm(b);
while (max > tol*rl && ++it < maxit) {
copyVector(e, u);
copyVector(u, b);
#pragma omp parallel for schedule(static)
for (i=0;i<e->len;++i) {
if (i > 0)
u->data[i] += e->data[i-1];
if (i < e->len-1)
u->data[i] += e->data[i+1];
u->data[i] /= (2.0+alpha);
}
axpy(e, u, -1.0);
max = maxNorm(e);
}
freeVector(b);
freeVector(e);
return it;
}
int GaussSeidelPoisson1D(Vector u, double tol, int maxit)
{
int it=0, i, j;
double max = tol+1;
double rl = maxNorm(u);
Vector b = createVector(u->len);
Vector r = createVector(u->len);
Vector v = createVector(u->len);
copyVector(b, u);
fillVector(u, 0.0);
while (max > tol*rl && ++it < maxit) {
copyVector(v, u);
copyVector(u, b);
for (i=0;i<r->len;++i) {
if (i > 0)
u->data[i] += v->data[i-1];
if (i < r->len-1)
u->data[i] += v->data[i+1];
r->data[i] = u->data[i]-(2.0+alpha)*v->data[i];
u->data[i] /= (2.0+alpha);
v->data[i] = u->data[i];
}
max = maxNorm(r);
}
freeVector(b);
freeVector(r);
freeVector(v);
return it;
}
int GaussSeidelPoisson1Drb(Vector u, double tol, int maxit)
{
int it=0, i, j;
double max = tol+1;
double rl = maxNorm(u);
Vector b = createVector(u->len);
Vector r = createVector(u->len);
Vector v = createVector(u->len);
copyVector(b, u);
fillVector(u, 0.0);
while (max > tol && ++it < maxit) {
copyVector(v, u);
copyVector(u, b);
for (j=0;j<2;++j) {
#pragma omp parallel for schedule(static)
for (i=j;i<r->len;i+=2) {
if (i > 0)
u->data[i] += v->data[i-1];
if (i < r->len-1)
u->data[i] += v->data[i+1];
r->data[i] = u->data[i]-(2.0+alpha)*v->data[i];
u->data[i] /= (2.0+alpha);
v->data[i] = u->data[i];
}
}
max = maxNorm(r);
}
freeVector(b);
freeVector(r);
freeVector(v);
return it;
}
void DiagonalizationPoisson1D(Vector u, const Vector lambda, const Matrix Q)
{
Vector btilde = createVector(u->len);
int i;
MxV(btilde, Q, u, 1.0, 0.0, 'T');
for (i=0;i<btilde->len;++i)
btilde->data[i] /= lambda->data[i];
MxV(u, Q, btilde, 1.0, 0.0, 'N');
freeVector(btilde);
}
void DiagonalizationPoisson1Dfst(Vector u, const Vector lambda)
{
Vector btilde = createVector(u->len);
Vector buf = createVector(4*(u->len+1));
int i;
int N=u->len+1;
int NN=4*N;
copyVector(btilde, u);
fst(btilde->data, &N, buf->data, &NN);
for (i=0;i<btilde->len;++i)
btilde->data[i] /= (lambda->data[i]+alpha);
fstinv(btilde->data, &N, buf->data, &NN);
copyVector(u, btilde);
freeVector(btilde);
freeVector(buf);
}
void Poisson1D(Vector u, const Vector v)
{
int i;
#pragma omp parallel for schedule(static)
for (i=0;i<u->len;++i) {
u->data[i] = (2.0+alpha)*v->data[i];
if (i > 0)
u->data[i] -= v->data[i-1];
if (i < u->len-1)
u->data[i] -= v->data[i+1];
}
}
int main(int argc, char** argv)
{
int i, j, N, flag;
Matrix A=NULL, Q=NULL;
Vector b, grid, e, lambda=NULL;
double time, sum, h, tol=1e-4;
if (argc < 3) {
printf("need two parameters, N and flag [and tolerance]\n");
printf(" - N is the problem size (in each direction\n");
printf(" - flag = 1 -> Dense LU\n");
printf(" - flag = 2 -> Dense Cholesky\n");
printf(" - flag = 3 -> Full Gauss-Jacobi iterations\n");
printf(" - flag = 4 -> Full Gauss-Jacobi iterations using BLAS\n");
printf(" - flag = 5 -> Full Gauss-Seidel iterations\n");
printf(" - flag = 6 -> Full Gauss-Seidel iterations using BLAS\n");
printf(" - flag = 7 -> Full CG iterations\n");
printf(" - flag = 8 -> Matrix-less Gauss-Jacobi iterations\n");
printf(" - flag = 9 -> Matrix-less Gauss-Seidel iterations\n");
printf(" - flag = 10 -> Matrix-less Red-Black Gauss-Seidel iterations\n");
printf(" - flag = 11 -> Diagonalization\n");
printf(" - flag = 12 -> Diagonalization - FST\n");
printf(" - flag = 13 -> Matrix-less CG iterations\n");
return 1;
}
N=atoi(argv[1]);
flag=atoi(argv[2]);
if (argc > 3)
tol = atof(argv[3]);
if (N < 0) {
printf("invalid problem size given\n");
return 2;
}
if (flag < 0 || flag > 13) {
printf("invalid flag given\n");
return 3;
}
if (flag == 10 && (N-1)%2 != 0) {
printf("need an even size for red-black iterations\n");
return 4;
}
if (flag == 12 && (N & (N-1)) != 0) {
printf("need a power-of-two for fst-based diagonalization\n");
return 5;
}
h = 1.0/N;
grid = equidistantMesh(0.0, 1.0, N);
b = createVector(N-1);
e = createVector(N-1);
evalMeshInternal(b, grid, source);
evalMeshInternal(e, grid, exact);
scaleVector(b, pow(h, 2));
axpy(b, e, alpha);
if (flag < 8) {
A = createMatrix(N-1,N-1);
diag(A, -1, -1.0);
diag(A, 0, 2.0+alpha);
diag(A, 1, -1.0);
}
if (flag >= 11 && flag < 13)
lambda = generateEigenValuesP1D(N-1);
if (flag == 11)
Q = generateEigenMatrixP1D(N-1);
time = WallTime();
if (flag == 1) {
int* ipiv=NULL;
lusolve(A, b, &ipiv);
free(ipiv);
} else if (flag == 2)
llsolve(A,b,0);
else if (flag == 3)
printf("Gauss-Jacobi used %i iterations\n",
GaussJacobi(A, b, tol, 10000000));
else if (flag == 4)
printf("Gauss-Jacobi used %i iterations\n",
GaussJacobiBlas(A, b, tol, 10000000));
else if (flag == 5)
printf("Gauss-Seidel used %i iterations\n",
GaussSeidel(A, b, tol, 10000000));
else if (flag == 6)
printf("Gauss-Seidel used %i iterations\n",
GaussSeidelBlas(A, b, tol, 10000000));
else if (flag == 7)
printf("CG used %i iterations\n", cg(A, b, 1e-8));
else if (flag == 8)
printf("Gauss-Jacobi used %i iterations\n",
GaussJacobiPoisson1D(b, tol, 10000000));
else if (flag == 9)
printf("Gauss-Jacobi used %i iterations\n",
GaussSeidelPoisson1D(b, tol, 10000000));
else if (flag == 10)
printf("Gauss-Jacobi used %i iterations\n",
GaussSeidelPoisson1Drb(b, tol, 10000000));
else if (flag == 11)
DiagonalizationPoisson1D(b,lambda,Q);
else if (flag == 12)
DiagonalizationPoisson1Dfst(b,lambda);
else if (flag == 13)
printf("CG used %i iterations\n", cgMatrixFree(Poisson1D, b, tol));
printf("elapsed: %f\n", WallTime()-time);
evalMeshInternal(e, grid, exact);
axpy(b,e,-1.0);
printf("max error: %e\n", maxNorm(b));
if (A)
freeMatrix(A);
if (Q)
freeMatrix(Q);
freeVector(grid);
freeVector(b);
freeVector(e);
if (lambda)
freeVector(lambda);
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "asm.h"
#include "directive.h"
int directive_parse(struct ScanData *scanInfo,
struct Token *dirToken,
struct SymTab **curSyms,
struct ASMRecord **asmrec,
unsigned int *offset) {
char tokName[MAX_TOKLEN];
struct Token newToken;
unsigned int value;
/* architecture selection directive */
if ((strcmp(dirToken->token, ".arch") == 0)) {
/* next token should be an identifier to our architecture file */
if (get_token(&newToken, scanInfo) != TOK_IDENT) {
fprintf(stderr, "ERROR - Unexpected Token %s, line %d\n",
newToken.token, newToken.linenum);
return -1;
}
/* check that we have a valid pointer to write to */
if (asmrec != NULL) {
if (*asmrec != NULL) {
asmrec_free(*asmrec);
}
DEBUG(1) printf("Loading architecture %s\n", newToken.token);
*asmrec = asmrec_load(curSyms, newToken.token);
if (*asmrec == NULL) {
printf("Could not load architecture file for %s\n", newToken.token);
}
}
}
/* define directive */
else if ((strcmp(dirToken->token, ".define") == 0)) {
/* next token should be an string to define */
if (get_token(&newToken, scanInfo) != TOK_IDENT) {
fprintf(stderr, "ERROR - Unexpected Token %s, line %d\n",
newToken.token, newToken.linenum);
return -1;
}
strcpy(tokName, newToken.token);
/* check that we have a valid pointer to write to */
if (curSyms != NULL) {
/* next token(s) should be a numeric value/expression to set */
if (1) {
if (asmgen_parse_value(scanInfo, curSyms, &value) != 0) {
fprintf(stderr, "ERROR - Invalid Define, line %d\n",
newToken.linenum);
return -1;
}
symtab_record(curSyms, tokName, NULL, value);
}
else {
if (get_token(&newToken, scanInfo) != TOK_INT) {
fprintf(stderr, "ERROR - Unexpected Token %s, line %d\n",
newToken.token, newToken.linenum);
return -1;
}
symtab_record(curSyms, tokName, NULL, newToken.value);
}
}
}
/* output specifier define */
else if ((strcmp(dirToken->token, ".outfmt") == 0)) {
/* next token should be an string specifying output */
if (get_token(&newToken, scanInfo) != TOK_IDENT) {
fprintf(stderr, "ERROR - Unexpected Token %s, line %d\n",
newToken.token, newToken.linenum);
return -1;
}
/* check that we have a valid pointer to write to */
if (curSyms != NULL) {
symtab_record(curSyms, "$outfmt", newToken.token, -1);
}
}
/* output position define */
else if ((strcmp(dirToken->token, ".org") == 0)) {
/* next token should be an string specifying output */
if (get_token(&newToken, scanInfo) != TOK_INT) {
fprintf(stderr, "ERROR - Unexpected Token %s, line %d\n",
newToken.token, newToken.linenum);
return -1;
}
/* check that we have a valid pointer to write to */
if (offset != NULL) {
*offset = newToken.value;
}
}
/* output specifier define */
else if ((strcmp(dirToken->token, ".mifwords") == 0)) {
/* next token should be an integer specifying size */
if (get_token(&newToken, scanInfo) != TOK_INT) {
fprintf(stderr, "ERROR - Unexpected Token %s, line %d\n",
newToken.token, newToken.linenum);
return -1;
}
/* check that we have a valid pointer to write to */
if (curSyms != NULL) {
symtab_record(curSyms, "$mifwords", NULL, newToken.value);
}
}
/* output specifier define */
else if ((strcmp(dirToken->token, ".mifwidth") == 0)) {
/* next token should be an integer specifying size */
if (get_token(&newToken, scanInfo) != TOK_INT) {
fprintf(stderr, "ERROR - Unexpected Token %s, line %d\n",
newToken.token, newToken.linenum);
return -1;
}
/* check that we have a valid pointer to write to */
if (curSyms != NULL) {
symtab_record(curSyms, "$mifwidth", NULL, newToken.value);
}
}
/* unknown directive */
else {
printf("ERROR - Unknown directive %s\n", dirToken->token);
}
/* chew tokens until end of line */
while (get_token(&newToken, scanInfo) != TOK_ENDL) {
DEBUG(3) printf("-> ignoring token %s\n", newToken.token);
}
return 0;
}
|
C
|
#include <stdint.h>
#include <stdbool.h>
#include <string.h>
#include "debug.h"
static debug_context_t debug_context;
uint32_t debug_mode;
typedef struct {
debug_command_t *handler;
} help_command_t;
typedef struct {
uint32_t address;
uint32_t len;
uint8_t size;
} md_command_t;
static union {
md_command_t md;
help_command_t help;
} command_context;
int debug_md_handler(debug_context_t *pContext);
debug_context_t *get_dbg()
{
return &debug_context;
}
void debug_init(void)
{
debug_context.input.wr_index = 0;
debug_context.input.rd_index = 0;
debug_context.line.wr_index = 0;
debug_context.line.rd_index = 0;
debug_context.output.wr_index = 0;
debug_context.output.rd_index = 0;
debug_context.field_start = 0;
debug_context.field_next = 0;
debug_context.state = DEBUG_PROMPT;
debug_context.user_context = NULL;
}
void debug_set_user_context(void *user_context)
{
debug_context.user_context = user_context;
}
void debug_putc(uint8_t c)
{
debug_context_t *pContext = &debug_context;
pContext->output.data[pContext->output.wr_index] = c;
pContext->output.wr_index++;
if (pContext->output.wr_index == sizeof(pContext->output.data)) {
pContext->output.wr_index = 0;
}
}
int debug_tx_empty()
{
debug_context_t *pContext = &debug_context;
return pContext->output.wr_index == pContext->output.rd_index;
}
void debug_puts(char *s)
{
int len = strlen(s);
debug_context_t *pContext = &debug_context;
if (pContext->output.wr_index + len >= sizeof(pContext->output.data)) {
int first_size = sizeof(pContext->output.data)- pContext->output.wr_index;
memcpy(&pContext->output.data[pContext->output.wr_index],s,first_size);
len = len - first_size;
if (len > 0) {
if (len > pContext->output.wr_index) {
len = pContext->output.wr_index;
}
memcpy(pContext->output.data,&s[first_size],len);
pContext->output.wr_index = len;
}
} else {
memcpy(&pContext->output.data[pContext->output.wr_index],s,len);
pContext->output.wr_index += len;
}
}
int debug_next_field(void)
{
debug_context_t *pContext = &debug_context;
uint8_t field_start;
uint8_t field_end;
field_start = pContext->field_next;
while ((field_start < pContext->line.wr_index) &&
(pContext->line.data[field_start] == ' ')) {
field_start++;
}
if (field_start >= pContext->line.wr_index) {
return 0;
}
pContext->field_start = field_start;
field_end = field_start;
while ((field_end < pContext->line.wr_index) &&
(pContext->line.data[field_end] != ' ')) {
field_end++;
}
pContext->line.data[field_end] = '\0';
pContext->field_next = field_end + 1;
return 1;
}
void debug_process(void);
void debug_loop(void)
{
debug_context_t *pContext = &debug_context;
switch (pContext->state) {
case DEBUG_IDLE:
if (pContext->output.rd_index != pContext->output.wr_index) {
break;
}
pContext->output.wr_index = 0;
pContext->output.rd_index = 0;
if (pContext->input.rd_index != pContext->input.wr_index) {
uint8_t c;
c = pContext->input.data[pContext->input.rd_index];
pContext->input.rd_index++;
if (pContext->input.rd_index >= sizeof(pContext->input.data)) {
pContext->input.rd_index = 0;
}
if ((c == '\r') || (c == '\n')) {
if (pContext->line.wr_index != 0) {
debug_putc('\r');
debug_putc('\n');
pContext->field_start = 0;
debug_process();
}
pContext->line.wr_index = 0;
} else {
if ((c >= ' ') && (c != 0x7F)) {
// Keep room for \0
if (pContext->line.wr_index < DEBUG_LINE-2) {
pContext->line.data[pContext->line.wr_index++] = c;
debug_putc(c);
}
} else if (c == 0x08) {
if (pContext->line.wr_index != 0) {
pContext->line.wr_index--;
debug_putc('\b');
debug_putc(' ');
debug_putc('\b');
}
}
}
}
break;
case DEBUG_IN_PROGRESS:
if (pContext->output.rd_index == pContext->output.wr_index) {
pContext->output.wr_index = 0;
pContext->output.rd_index = 0;
pContext->handler(pContext);
}
break;
case DEBUG_PROMPT:
if (pContext->output.rd_index == pContext->output.wr_index) {
pContext->output.data[0] = '>';
pContext->output.wr_index = 1;
pContext->output.rd_index = 0;
pContext->handler = NULL;
memset(&command_context,0,sizeof(command_context));
pContext->state = DEBUG_FLUSHING;
}
break;
case DEBUG_FLUSHING:
if (pContext->output.rd_index == pContext->output.wr_index) {
pContext->output.wr_index = 0;
pContext->output.rd_index = 0;
pContext->state = DEBUG_IDLE;
}
break;
}
}
void debug_line_memory_display_8(uint32_t addr, int len)
{
int i;
int l;
uint8_t c;
uint8_t *pH;
uint8_t *pT;
debug_context_t *pContext = &debug_context;
l = pContext->output.wr_index;
fmt_hexa32(&pContext->output.data[l],addr);
pContext->output.data[l+8] = ' ';
pH = &pContext->output.data[l+9];
pT = &pContext->output.data[l+9+16*3];
*pT++ = ' ';
for (i = 0;i < len;i++) {
c = *(uint8_t *)(addr+i);
fmt_hexa8(pH,c);
pH += 2;
if ((c >= ' ') && (c <= 0x7e)) {
*pT = c;
} else {
*pT = '.';
}
pT++;
*pH++ = ' ';
}
while (i < 16) {
*pH++ = ' ';
*pH++ = ' ';
*pH++ = ' ';
*pT++ = ' ';
i++;
}
*pT++ = '\n';
*pT = '\0';
pContext->output.wr_index = pT - pContext->output.data;
}
void debug_line_memory_display_16(uint32_t addr, int len)
{
int i;
int l;
uint16_t v;
uint8_t *pH;
debug_context_t *pContext = &debug_context;
l = pContext->output.wr_index;
fmt_hexa32(&pContext->output.data[l],addr);
pContext->output.data[l+8] = ' ';
pH = &pContext->output.data[l+9];
for (i = 0;i < len;i+=2) {
v = *(uint16_t *)(addr+i);
fmt_hexa16(pH,v);
pH += 4;
*pH++ = ' ';
}
*pH++ = '\n';
*pH = '\0';
pContext->output.wr_index = pH - pContext->output.data;
}
void debug_line_memory_display_32(uint32_t addr, int len)
{
int i;
int l;
uint32_t v;
uint8_t *pH;
debug_context_t *pContext = &debug_context;
l = pContext->output.wr_index;
fmt_hexa32(&pContext->output.data[l],addr);
pContext->output.data[l+8] = ' ';
pH = &pContext->output.data[l+9];
for (i = 0;i < len;i+=4) {
v = *(uint32_t *)(addr+i);
fmt_hexa32(pH,v);
pH += 8;
*pH++ = ' ';
}
*pH++ = '\n';
*pH = '\0';
pContext->output.wr_index = pH - pContext->output.data;
}
void debug_context_memory_display(void)
{
int line;
int len = command_context.md.len;
if (len > 16) {
line = 16;
} else {
line = len;
}
if (command_context.md.size == 8) {
debug_line_memory_display_8(command_context.md.address, line);
} else if (command_context.md.size == 16) {
debug_line_memory_display_16(command_context.md.address, line);
} else if (command_context.md.size == 32) {
debug_line_memory_display_32(command_context.md.address, line);
}
command_context.md.len -= line;
command_context.md.address += line;
}
void debug_memory_display(uint32_t addr, uint32_t len, uint8_t size)
{
debug_context_t *pContext = &debug_context;
if (len != 0) {
pContext->state = DEBUG_IN_PROGRESS;
pContext->handler = debug_md_handler;
command_context.md.address = addr;
command_context.md.len = len;
command_context.md.size = size;
debug_context_memory_display();
}
}
static debug_command_t *first_handler;
static debug_command_t *last_handler;
void debug_add_command(debug_command_t *handler)
{
if (first_handler == NULL) {
first_handler = handler;
} else {
last_handler->next = handler;
}
last_handler = handler;
last_handler->next = NULL;
}
void debug_add_commands(debug_command_t *handlers, int n)
{
int i;
for (i = 0;i < n;i++) {
debug_add_command(&handlers[i]);
}
}
int debug_help_handler(debug_context_t *pContext);
int debug_help_handler(debug_context_t *pContext)
{
debug_command_t *handler;
int l;
int i;
if (command_context.help.handler == NULL) {
command_context.help.handler = first_handler;
pContext->state = DEBUG_IN_PROGRESS;
pContext->handler = debug_help_handler;
}
handler = command_context.help.handler;
l = pContext->output.wr_index;
i = 0;
while (handler->name[i]) {
pContext->output.data[l++] = handler->name[i++];
}
while (i < 16) {
pContext->output.data[l++] = ' ';
i++;
}
pContext->output.data[l++] = ':';
pContext->output.data[l++] = ' ';
i = 0;
while (handler->help[i]) {
pContext->output.data[l++] = handler->help[i++];
}
pContext->output.data[l++] = '\n';
pContext->output.wr_index = l;
command_context.help.handler = handler->next;
if (handler->next == NULL) {
pContext->state = DEBUG_PROMPT;
}
return 1;
}
int debug_md_handler(debug_context_t *pContext)
{
uint32_t addr;
uint32_t len = 0x100;
int size = 8;
char c;
if (pContext->state != DEBUG_IN_PROGRESS) {
c = pContext->line.data[pContext->field_start+2];
if ((c == '\0') || (c == 'b')) {
size = 8;
} else if (c == 'h') {
size = 16;
} else if (c == 'w') {
size = 32;
}
if (debug_next_field() == 0) {
return 0;
}
addr = ltoi((char *)&pContext->line.data[pContext->field_start],16);
if (debug_next_field()) {
len = ltoi((char *)&pContext->line.data[pContext->field_start],16);
}
pContext->state = DEBUG_IN_PROGRESS;
pContext->handler = debug_md_handler;
command_context.md.address = addr;
command_context.md.len = len;
command_context.md.size = size;
} else {
if (command_context.md.len == 0) {
pContext->state = DEBUG_PROMPT;
} else {
debug_context_memory_display();
}
}
return 1;
}
int debug_mode_handler(debug_context_t *pContext)
{
if (debug_next_field() == 0) {
int l;
l = pContext->output.wr_index;
fmt_hexa32(&pContext->output.data[l],debug_mode);
pContext->output.data[l+8] = '\n';
pContext->output.wr_index = l + 9;
return 1;
}
debug_mode = ltoi((char *)&pContext->line.data[pContext->field_start],16);
return 1;
}
int debug_mm_handler(debug_context_t *pContext)
{
uint32_t addr;
uint32_t value;
int size = 8;
char c;
c = pContext->line.data[pContext->field_start+2];
if ((c == '\0') || (c == 'b')) {
size = 8;
} else if (c == 'h') {
size = 16;
} else if (c == 'w') {
size = 32;
}
if (debug_next_field() == 0) {
return 0;
}
addr = ltoi((char *)&pContext->line.data[pContext->field_start],16);
if (debug_next_field() == 0) {
return 0;
}
value = ltoi((char *)&pContext->line.data[pContext->field_start],16);
if (size == 8) {
*(uint8_t *)addr = value;
} else if (size == 16) {
*(uint16_t *)addr = value;
} else if (size == 32) {
*(uint32_t *)addr = value;
}
return 1;
}
debug_command_t basics[] = {
{ .name = "help",
.help = "List available commands",
.handler = debug_help_handler,
.next = NULL},
{ .name = "mode",
.help = "mode [value], displays/sets debug mode",
.handler = debug_mode_handler,
.next = NULL},
{ .name = "md",
.help = "md addr [len], displays memory content as bytes",
.handler = debug_md_handler,
.next = NULL},
{ .name = "mdb",
.help = "mdb addr [len], displays memory content as bytes",
.handler = debug_md_handler,
.next = NULL},
{ .name = "mdh",
.help = "mdh addr [len], displays memory content as halfwords",
.handler = debug_md_handler,
.next = NULL},
{ .name = "mdw",
.help = "mdw addr [len], displays memory content as words",
.handler = debug_md_handler,
.next = NULL},
{ .name = "mm",
.help = "mm addr value, modifies memory content as byte",
.handler = debug_mm_handler,
.next = NULL},
{ .name = "mmb",
.help = "mmb addr value, modifies memory content as byte",
.handler = debug_mm_handler,
.next = NULL},
{ .name = "mmh",
.help = "mmh addr value, modifies memory content as haldword",
.handler = debug_mm_handler,
.next = NULL},
{ .name = "mmw",
.help = "mmw addr value, modifies memory content as word",
.handler = debug_mm_handler,
.next = NULL}
};
void debug_process(void)
{
debug_context_t *pContext = &debug_context;
uint8_t field_start;
pContext->field_next = 0;
if (debug_next_field()) {
debug_command_t *handler = first_handler;
field_start = pContext->field_start;
while (handler != NULL) {
if (strcmp((char *)&pContext->line.data[field_start],
handler->name) == 0) {
pContext->state = DEBUG_PROMPT;
(handler->handler)(pContext);
break;
}
handler = handler->next;
}
}
}
int debug_get_next_char(void)
{
debug_context_t *pContext = &debug_context;
if (pContext->output.wr_index != pContext->output.rd_index) {
int c = pContext->output.data[pContext->output.rd_index];
pContext->output.rd_index++;
if (pContext->output.rd_index == sizeof(pContext->output.data)) {
pContext->output.rd_index = 0;
}
return c;
}
return -1;
}
int debug_get_next_string(uint8_t **start, uint32_t *length)
{
debug_context_t *pContext = &debug_context;
if (pContext->output.wr_index != pContext->output.rd_index) {
*start = &pContext->output.data[pContext->output.rd_index];
if (pContext->output.wr_index > pContext->output.rd_index) {
*length = pContext->output.wr_index - pContext->output.rd_index;
} else {
*length = sizeof(pContext->output.data) - pContext->output.rd_index;
}
return 0;
}
return -1;
}
void debug_update_next_string(uint32_t length)
{
debug_context_t *pContext = &debug_context;
pContext->output.rd_index += length;
if (pContext->output.rd_index >= sizeof(pContext->output.data)) {
pContext->output.rd_index -= sizeof(pContext->output.data);
}
}
void debug_add_char(int c)
{
debug_context_t *pContext = &debug_context;
pContext->input.data[pContext->input.wr_index] = c;
pContext->input.wr_index++;
if (pContext->input.wr_index == sizeof(pContext->input.data)) {
pContext->input.wr_index = 0;
}
}
void debug_start(void)
{
debug_add_commands(basics,SIZEOF(basics));
debug_putc('=');
debug_putc('>');
}
|
C
|
/*Group 2 Program 2
Paul Maclean- mac7537@calu.edu
Mike Gorse- gor9632@calu.edu
Robert Breckenridge- bre6896@calu.edu
Chase Smith- smi8808@calu.edu
Rudolph Hanzes - han7739@calu.edu
CSC 460
Language Translations
*/
#include "file_util.h"
#include "scanner.h"
file_outcome init(int argc, char* argv[]) {
file_outcome fileCheck = openFiles(argc, argv);
if (fileCheck == cont)
{
}
return fileCheck;
}
void cleanup() {
//closes files
closeFiles();
}
int main(int argc, char* argv[]) {
if (init(argc, argv) == cont) {
initScanner(InpFile);
printf("Scanner initialized. Parsing...\n");
systemgoal();
printf("Parsing complete.\n");
cleanup();
}
else
{
printf("Init has failed. No scanner for you.");
}
return 0;
}
|
C
|
/* vector a column-major
* a = [ x
* y
* z
* 1 ]
* a^T = [ x y z 1 ]
* ^T means the transpotion of the matrix
* matrix definition
* M = [ r00 r01 r02 m03
* r10 r11 r12 m13
* r20 r21 r22 m23
* tx ty tz 1 ]
*
* M^T =[ r00 r10 r20 tx
* r01 r11 r21 ty
* r02 r12 r22 tx
* m03 m13 m23 1 ]
* we have two frame A and B, the base vector of two frame are represent as A and B, where A = ( v1, v2, v3 ), vi is a vector.
* we have a point P0, in frame A, P0 equeals a(a is a vector). and in frame B, P0 equals b
* and we have B = M.A . means dot , A and B means base vectors of two frames
* |
* \|/
* a = M^T.b
* b = ((M^T)^(-1)).a
* b = ((M^(-1))^T).a
*
* a = M1^T.M2^T.b
* a^T = b^T.M2.M1
*/
typedef struct __matrix{
union{
float m[16];
struct {
float r00, r01, r02, m03;
float r10, r11, r12, m13;
float r20, r21, r22, m23;
float tx, ty, tz, m33;
};
};
}matrix;
matrix * matrix_identity( matrix* a );
matrix * matrix_zero( matrix* a);
matrix * matrix_copy( matrix* a, matrix *b ); // a = b;
matrix * matrix_multiply( matrix *a, matrix *b, matrix *v ); // v = a * b;
matrix * matrix_left_mult( matrix *a, matrix *b ); // a = a*b;
matrix * matrix_right_mult( matrix *a, matrix *b); // a = b*a;
matrix * matrix_scale( matrix *a, float x, float y, float z );
matrix * matrix_rotate_x( matrix *a, float angle );
matrix * matrix_rotate_y( matrix *a, float angle );
matrix * matrix_rotate_z( matrix *a, float angle );
matrix * matrix_rotate_xyz( matrix *a, float x, float y, float z, float angle ); // !!!TODO
matrix * matrix_translate( matrix *a, float x, float y, float z );
|
C
|
#include "stdio.h"
#include "gpio_handler.h"
#include "string.h"
#include "driver/gpio.h"
#include "cJSON.h"
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "gpio_config_parser.h"
#include "iot2tangle.h"
#include "../mqtt_handler.h"
enum pinMode pinmode_of(char* str_mode){
if (strcmp(str_mode, "DO") == 0){
return DO;
}else if (strcmp(str_mode, "DI") == 0){
return DI;
}else if (strcmp(str_mode, "AO") == 0){
return AO;
}else if (strcmp(str_mode, "AI") == 0){
return AI;
}else{
printf("got nothing vaild\n");
return None;
}
return None;
}
char* str_of(enum pinMode mode){
switch(mode){
case DO:
return "DO";
break;
case DI:
return "DI";
break;
case AO:
return "AO";
break;
case AI:
return "AI";
break;
default:
return "NO_PIN_MODE";
}
}
void build_iot2tangle_msg(uint8_t cfgNr, uint8_t val, char* msg){
sprintf(msg, "{\"sensor\": \"%s\", \"data\":[{\"%s%d\":%d}]}", pins[cfgNr].id, str_of(pins[cfgNr].mode), pins[cfgNr].pin, val );
printf("IOT2Tangle MSG: %s\n", msg);
}
esp_err_t gpio_read_h(uint8_t cfgNr){
printf("in gpio read for cfgNr %d \n", cfgNr);
if(pins[cfgNr].mode ==DI){
printf("read val\n");
uint8_t val = gpio_get_level(pins[cfgNr].pin);
printf("build topic\n");
char topic[200];
strcpy(topic, macAdress);
strcat(topic, "/");
strcat(topic, pins[cfgNr].id);
//printf("build payload\n");
char payload[50];
sprintf(payload, "{\"value\":%d}", val);
mqtt_publish(topic, payload);
//build i2t_message
char i2tMsg[300];
build_iot2tangle_msg(cfgNr, val, i2tMsg);
send_to_gateway(i2tMsg);
//printf("send to gateway\n");
}
return 0;
}
esp_err_t gpio_write_h(uint8_t pin, enum pinMode mode, uint8_t value){
if(mode ==DO){
if(value !=0 && value != 1){
printf("Invalid Value for digital pin!\n");
return ESP_FAIL;
}
if(gpio_set_level(pin, value) != ESP_OK){
printf("Set GPIO Level failed\n");
return ESP_FAIL;
}
return ESP_OK;
}
return ESP_FAIL;
}
void gpio_event_handler(char* message){
cJSON *msg = cJSON_Parse(message);
uint8_t status = 1;
const cJSON *entry_b = NULL;
if (msg == NULL)
{
const char *error_ptr = cJSON_GetErrorPtr();
if (error_ptr != NULL)
{
printf("Error before: %s\n", error_ptr);
}
return 1;
}
cJSON *gpio_id = cJSON_GetObjectItemCaseSensitive(msg, "id");
cJSON *gpioWrite = cJSON_GetObjectItemCaseSensitive(msg, "write");
cJSON *read = cJSON_GetObjectItemCaseSensitive(msg, "read");
if(read != NULL){
}
if(gpioWrite != NULL){
//search for id
for(uint8_t i=0; i<pinCnt; i++){
printf("compare %s with %s\n",gpio_id->valuestring, pins[i].id );
if(strcmp(gpio_id->valuestring, pins[i].id)==0){
printf("set gpio %d to %d\n", pins[i].pin, gpioWrite->valueint);
if (gpio_write_h(pins[i].pin, pins[i].mode, gpioWrite->valueint) == ESP_OK){
char topic[200];
strcpy(topic, macAdress);
strcat(topic, "/");
strcat(topic, pins[i].id);
char payload[50];
sprintf(payload, "{\"value\":%d}", gpioWrite->valueint);
mqtt_publish(topic, payload);
}
}
}
}
}
void gpio_message_handler(char* topic, char* message){
char * token = strtok(topic, "/");
while( token != NULL ) {
printf( "Token: %s\n", token ); //printing each token
if(strcmp(token, "event")==0){
printf("In Event\n");
gpio_event_handler(message);
return;
}else if(strcmp(token, "config")==0){
printf("In config\n");
gpio_parse_config(message);
init_hw();
}
token = strtok(NULL, "/");
}
}
void init_hw(){
printf("GPIO INIT\n");
for (uint8_t i = 0; i<pinCnt; i++){
gpio_reset_pin(pins[i].pin);
if (pins[i].mode == DO){
if(gpio_set_direction(pins[i].pin, GPIO_MODE_OUTPUT) != ESP_OK){
printf("gpio initializing fialed!!!!!\n");
}
}else if (pins[i].mode == DI){
gpio_set_direction(pins[i].pin, GPIO_MODE_INPUT);
}else{
printf("This pinmode is not supported for now\n");
}
}
}
void gpio_loop(){
unsigned long currentMillis = xTaskGetTickCount() * portTICK_PERIOD_MS;
for(uint8_t i = 0; i<pinCnt; i++){
if (pins[i].mode == DI){
if(currentMillis >= lastTime[i]+pins[i].interval*1000){
printf("before gpio read\n");
gpio_read_h(i);
lastTime[i] = currentMillis;
printf("after gpio read\n");
}
}
}
}
|
C
|
/*
** my_strcapitalize.c for Pool Day06 in /home/laroch_f/Desktop/PiscineDay06/Piscine_C_J06/ex_10
**
** Made by Hugo Laroche
** Login <laroch_f@epitech.net>
**
** Started on Tue Mar 8 15:24:07 2016 Hugo Laroche
** Last update Tue Mar 8 21:57:51 2016 Hugo Laroche
*/
char *my_strcapitalize(char *str)
{
int cpt;
int mot;
mot = 1;
cpt = 0;
while (str[cpt])
{
if (mot == 1 && str[cpt] >= 'a' && str[cpt] <= 'z')
{
str[cpt] = str[cpt] - 32;
mot = 0;
}
else if (str[cpt] >= '0' && str[cpt] <= '9')
mot = 0;
else if (str[cpt] == '-' || str[cpt] == '+')
mot = 1;
else if (str[cpt] == ' ' || (str[cpt] >= 'A' && str[cpt] <= 'Z'))
mot = 1;
cpt = cpt + 1;
}
return (str);
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.