language
large_stringclasses 1
value | text
stringlengths 9
2.95M
|
|---|---|
C
|
#include <stdio.h>
#include <math.h>
int main(){
double a=0, b=0, c=0, D=0;
printf("Enter a, b, c: ");
scanf("%lf%lf%lf", &a, &b, &c);
if (a==0 && b==0 && c==0) printf ("There is an infinite set of solutions");
else if (a==0 && b==0) printf ("No solution");
else if (a==0) printf("x=%lf", -c/b);
else{
D=b*b-4*a*c;
if (D<0) printf("Complex roots");
else if (D==0) printf ("x=%lf", -b/(2*a));
else{
printf("x1=%f\nx2=%f", (-b+sqrt(D))/(2*a), (-b-sqrt(D))/(2*a));
}
}
return 0;
}
|
C
|
#include "stm32f10x.h"
#include "hardware_conf.h"
#include "sccb.h"
// #include "define.h"
void DelaySCCB(unsigned int i)
{
while( i--)
{
}
}
/*****************************************************
SCCB_GPIO_Config
ܣSCCB߶˿
룺
ֵ
*****************************************************/
void SCCB_GPIO_Config(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
/* Enable GPIOE clock */
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOC, ENABLE);
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_8 | GPIO_Pin_9;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP;
GPIO_InitStructure.GPIO_Speed =GPIO_Speed_50MHz;
GPIO_Init(GPIOC, &GPIO_InitStructure);
}
void SCCB_SID_GPIO_OUTPUT(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
/* Enable GPIOE clock */
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOC, ENABLE);
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_9;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(GPIOC, &GPIO_InitStructure);
}
void SCCB_SID_GPIO_INPUT(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
/* Enable GPIOE clock */
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOC, ENABLE);
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_9;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING;
// GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(GPIOC, &GPIO_InitStructure);
}
/*
-----------------------------------------------
: start,SCCBʼź
:
ֵ:
-----------------------------------------------
*/
void startSCCB(void)
{
SCCB_SID =1; //߸ߵƽ
DelaySCCB(300);
SCCB_SIC =1; //ʱ߸ߵʱɸ
DelaySCCB(300);
SCCB_SID =0;
DelaySCCB(300);
SCCB_SIC =0; //ָ͵ƽҪ
DelaySCCB(300);
}
/*
-----------------------------------------------
: stop,SCCBֹͣź
:
ֵ:
-----------------------------------------------
*/
void stopSCCB(void)
{
SCCB_SID =0;
DelaySCCB(500);
SCCB_SIC =1;
DelaySCCB(500);
SCCB_SID =1;
DelaySCCB(500);
}
/*
-----------------------------------------------
: noAck,ȡеһ
:
ֵ:
-----------------------------------------------
*/
void noAck(void)
{
SCCB_SID =1;
DelaySCCB(500);
SCCB_SIC =1;
DelaySCCB(500);
SCCB_SIC =0;
DelaySCCB(500);
SCCB_SID =0;
DelaySCCB(500);
}
/*
-----------------------------------------------
: дһֽڵݵSCCB
: д
ֵ: ͳɹ1ʧܷ0
-----------------------------------------------
*/
unsigned char SCCBwriteByte(unsigned char m_data)
{
unsigned char j,tem;
for(j=0;j<8;j++) //ѭ8η
{
if((m_data<<j)&0x80)
{
SCCB_SID =1;
}
else
{
SCCB_SID =0;
}
DelaySCCB(500);
SCCB_SIC =1;
DelaySCCB(500);
SCCB_SIC =0;
DelaySCCB(500);
}
DelaySCCB(100);
SCCB_SID_IN;/*SDAΪ*/
DelaySCCB(500);
SCCB_SIC =1;
DelaySCCB(100);
if(SCCB_SID_STATE) {tem=0;} //SDA=1ʧܣ0}
else {tem=1;} //SDA=0ͳɹ1
SCCB_SIC =0;
DelaySCCB(500);
SCCB_SID_OUT;/*SDAΪ*/
return (tem);
}
/*
-----------------------------------------------
: һֽݶȡҷ
:
ֵ: ȡ
-----------------------------------------------
*/
unsigned char SCCBreadByte(void)
{
unsigned char read,j;
read=0x00;
SCCB_SID_IN; /*SDAΪ*/
DelaySCCB(500);
for(j=8;j>0;j--) //ѭ8ν
{
DelaySCCB(500);
SCCB_SIC =1;
DelaySCCB(500);
read=read<<1;
if(SCCB_SID_STATE)
{
read=read+1;
}
SCCB_SIC =0;
DelaySCCB(500);
}
/**/
SCCB_SID_OUT;/*SDAΪ*/
return(read);
}
|
C
|
// C program to demonstrate that size_t or
// any unsigned int type should be used
// carefully when used in a loop.
#include<stdio.h>
#define N 10
int main()
{
int a[N],size_t,n;
// This is fine.
for (n = 0; n < N; ++n) {
a[n] = n;
}
// But reverse cycles are tricky for unsigned
// types as they can lead to infinite loops.
for (n = N-1; n >= 0; --n)
printf("%d ", a[n]);
}
|
C
|
// gcc hdlc.c hdlc_test.c && ./a.out
#include "hdlc.h"
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[]) {
uint8_t bufxmit[800];
uint8_t bufrecv[801]; // need 1 extra for closing flag
for (int i = 0; i < 800; ++i) {
bufxmit[i] = lrand48();
}
bufrecv[0] = 0;
uint8_t *txp = bufxmit;
uint8_t *rxp = bufrecv;
for (;;) {
uint8_t val = hdlc_encode(&txp, bufxmit + 800);
int flag = hdlc_decode(&rxp, bufrecv + 801, val);
if (flag != 0) {
break;
}
}
int err = 0;
for (int i = 0; i < 800; ++i) {
// unflip escaped values
switch (bufrecv[i]) {
case HDLC_ESC:
case HDLC_FLAG:
case HDLC_ABORT:
bufxmit[i] ^= 0x20;
}
if (bufxmit[i] != bufrecv[i]) {
printf("difference at %d: %x %x\n", i, bufxmit[i], bufrecv[i]);
++err;
}
}
if (err == 0) {
printf("ok.");
}
return 0;
}
|
C
|
#include <stdio.h>
int main()
{
int i,j,k,n,f=0;
int a[100];
printf("How many values: ");
scanf("%d",&n);
for(i=0;i<n;i++){
scanf("%d",&a[i]);
}
for(i=0;i<n;i++){
for(j=0;j<n;j++){
if(a[j]>a[j+1]){
k=a[j];
a[j]=a[j+1];
a[j+1]=k;
f++;
}
}
}
printf("Sort(A to Z) : ");
for(i=0;i<n;i++){
printf("%d ",a[i]);
}
printf("\n\tTotal Swap happened: %d times\n",f);
return 0;
}
|
C
|
#include <stdio.h>
#define NAME_LEN 64
typedef struct {
char name[NAME_LEN];
int height;
float weight;
long int scholarship;
} student;
int main(void){
student p1;
printf("enter the data\n");
printf("enter the name\t");
scanf("%s",p1.name);
printf("enter the height\t");
scanf("%d",&p1.height);
printf("enter the weight\t");
scanf("%f",&p1.weight);
printf("enter the scholarship\t");
scanf("%d",&p1.scholarship);
printf("check the data");
printf("name:\t%s\n",p1.name);
printf("height:\t%d\n",p1.height);
printf("weight:\t%f\n",p1.weight);
printf("scholarship:\t%d\n",p1.scholarship);
return 0;
}
|
C
|
/* C Program to Calculate Square root of a Number */
#include<stdio.h>
#include<math.h>
int main()
{
int number, result;
printf(" \n Please Enter any Number to find Square root : ");
scanf("%d", &number);
result = pow(number, 0.5);
printf("\n Square Root a given number %d = %d", number, result);
return 0;
}
//not able to understand how to use while loop here
|
C
|
#ifndef STANDARD_H
#define STANDARD_H
/* include files **************************************************************/
#include <stdint.h>
#ifdef __cplusplus
extern "C" {
#endif
/* MACRO Definition ***********************************************************/
#define BYTE_SIZE (8) /*!< One byte composite w/ 8 bits */
#define SMAX(type) ((type)((1 << ((BYTE_SIZE * sizeof(type)) - 1)) - (1)))
#define SMIN(type) ((type) (1 << ((BYTE_SIZE * sizeof(type)) - 1)))
#define UMAX(type) ((type)(~((type)(0))))
#define S8_MAX SMAX(T_S8) /*!< Maximum "signed" "8 bit" value (127) */
#define S8_MIN SMIN(T_S8) /*!< Minimum "signed" "8 bit" value (-128) */
#define U8_MAX UMAX(T_U8) /*!< Maximum "unsigned" "8 bit" value (256) */
#define S16_MAX SMAX(T_S16) /*!< Maximum "signed" "16 bit" value (32767) */
#define S16_MIN SMIN(T_S16) /*!< Maximum "signed" "16 bit" value (-32768)*/
#define U16_MAX UMAX(T_U16) /*!< Maximum "unsigned" "16 bit" value (65535) */
#define S32_MAX SMAX(T_S32) /*!< Maximum "signed" "16 bit" value (2147483647) */
#define S32_MIN SMIN(T_S32) /*!< Maximum "signed" "16 bit" value (-2147483648)*/
#define U32_MAX UMAX(T_U32) /*!< Maximum "unsigned" "16 bit" value (4294967295) */
#define S64_MAX SMAX(T_S64)
#define S64_MIN SMIN(T_S64)
#define U64_MAX UMAX(T_U64)
#ifndef NULL
#define NULL ((void*)(0)) /* NULL or NIL pointer */
#endif
#define UNUSED(x) (void)(x)
#define RETURN_SUCCESS (0)
#define RETURN_ERR_GENERAL (-1)
#define RETURN_ERR_BADPARA (-2)
#define RETURN_ERR_BADSTATUS (-3)
#define RETURN_ERR_OUTOFRES (-4)
typedef int8_t T_SChar; /*!< 1 Byte -127 .. 128 */
typedef int8_t T_S8; /*!< 1 Byte -127 .. 128 */
typedef int16_t T_S16; /*!< 2 Byte -32768 .. 32767 */
typedef int32_t T_S32; /*!< 4 Byte -2147483648 .. 2147483647 */
typedef int64_t T_S64; /*!< 8 Byte */
typedef uint8_t T_UChar; /*!< 1 Byte 0 .. 255 */
typedef uint8_t T_U8; /*!< 1 Byte 0 .. 255 */
typedef uint16_t T_U16; /*!< 2 Byte 0 .. 65'535 */
typedef uint32_t T_U32; /*!< 4 Byte 0 .. 4'294'967'295 */
typedef uint64_t T_U64; /*!< 8 Byte */
#ifdef __cplusplus
}
#endif
#endif /* STANDARD_H */
|
C
|
/****************************
* 2011.1 Miao Yu Implement Vis hypervisor on x86 and x86_64(not finished).
Create this file
*
*****************************/
#include <stdarg.h>
#include <vis/spinlock.h>
#include <vis/print_infos.h>
#define snprintf _snprintf
PVOID g_debugWindowAddrVA = 0;
ULONG32 appendIndex = 0;// The index the next string should append.
ULONG32 bufferLength = 0;//Total Buffer Length, used in buffer overflow check.
static spinlock_t g_PrintSpinLock;
/**
* Effects: Write info with format.
**/
NTSTATUS NTAPI WriteDbgInfo (PUCHAR fmt,...)
{
va_list args;
UCHAR str[1024] = { 0 };
ULONG32 length ;
va_start (args, fmt);
//length = snprintf (str,sizeof(str),fmt,args);
length = vsnprintf (str, sizeof (str), (PUCHAR) fmt, args);
return _WriteInfo(str,length);
}
void NTAPI WriteInfoInit()
{
spin_lock_init (&g_PrintSpinLock);
}
void NTAPI WriteInfoDispose()
{
if(g_debugWindowAddrVA)
{
ExFreePoolWithTag(g_debugWindowAddrVA, DEBUG_WINDOW_TAG);
}
}
static NTSTATUS _CreateDebugWindow(ULONG32 numContinuousPages)
{
PHYSICAL_ADDRESS l1, l2, l3;
l1.QuadPart = 0;
l2.QuadPart = -1;
l3.QuadPart = 0x200000;
//g_debugWindowAddrVA = MmAllocateContiguousMemorySpecifyCache (numContinuousPages * PAGE_SIZE, l1, l2, l3, MmCached);
g_debugWindowAddrVA = ExAllocatePoolWithTag (NonPagedPool, numContinuousPages * PAGE_SIZE, DEBUG_WINDOW_TAG);
RtlZeroMemory (g_debugWindowAddrVA, numContinuousPages * PAGE_SIZE);
if(!g_debugWindowAddrVA)
{
bufferLength = 0;
return STATUS_UNSUCCESSFUL;
}
bufferLength = numContinuousPages * PAGE_SIZE;
return STATUS_SUCCESS;
}
static VOID _AppendStringToAddress(PUCHAR str,ULONG32 strLength)
{
//Step 1.Overflow Check
if(appendIndex+strLength+2>=bufferLength)
{
return;
}
//Step 1.Append <str> at the end of the debug window.
memcpy(&((PUCHAR)g_debugWindowAddrVA)[appendIndex],(PVOID)str,strLength);
//Step 2.Append a '\0' at the end of this str.
appendIndex += (strLength+2);
((PUCHAR)g_debugWindowAddrVA)[appendIndex-2] = '\r';
((PUCHAR)g_debugWindowAddrVA)[appendIndex-1] = '\n';
}
/**
* Effects: Append the string <str> into the end of the debug window
* If the debug window not exists, then it will be created at first.
**/
static NTSTATUS NTAPI _WriteInfo(PUCHAR str,ULONG32 strLength)
{
spin_lock_acquire (&g_PrintSpinLock);
//Step 1. Check if the debug window exists.
if(!g_debugWindowAddrVA)
{
if(!NT_SUCCESS(_CreateDebugWindow(NUM_DEBUG_PAGES)))
{
//Continous Memory Allocate Failed!
return STATUS_UNSUCCESSFUL;
}
}
//Step 2.Append the <str> at the end of the debug window.
_AppendStringToAddress(str,strLength);
spin_lock_release (&g_PrintSpinLock);
return STATUS_SUCCESS;
}
|
C
|
// example to illustrate C structure and typedef
#include <stdio.h>
typedef struct customer {
char name[10];
int age;
int intern_id;
} customer_t;
main()
{
customer_t joe;
joe.name[0] = 'j';
joe.name[1] = 'o';
joe.name[2] = 'e';
joe.name[3] = '\0';
joe.age = 19;
joe.intern_id = 1200;
printf("%s\n",joe.name);
printf("%d\n",joe.age);
printf("%d\n",joe.intern_id);
}
|
C
|
#include <stdlib.h>
#include <unistd.h>
void ft_putint(int i);
void ft_putchar(char a);
void ft_putstr(char *str);
void ft_print_board(int r1, int r2, int r3, int r4);
int ft_strlen(char *str);
int is_begin_possible(int *results, int begin);
int is_end_possible(int *results, int end);
int is_poss(int soll[4], int begin, int end);
int ft_checkvertical_last_two(int *inputt, int counters[4]);
int ft_checkvertical(int *inputt, int counters[4]);
int g_array[4][4] = {{0}};
int g_poss[24][4] = {
{1, 2, 3, 4},
{1, 2, 4, 3},
{1, 3, 2, 4},
{1, 3, 4, 2},
{1, 4, 2, 3},
{1, 4, 3, 2},
{2, 1, 3, 4},
{2, 1, 4, 3},
{2, 3, 4, 1},
{2, 3, 1, 4},
{2, 4, 1, 3},
{2, 4, 3, 1},
{3, 1, 2, 4},
{3, 1, 4, 2},
{3, 2, 1, 4},
{3, 2, 4, 1},
{3, 4, 1, 2},
{3, 4, 2, 1},
{4, 1, 2, 3},
{4, 1, 3, 2},
{4, 2, 1, 3},
{4, 2, 3, 1},
{4, 3, 1, 2},
{4, 3, 2, 1}
};
int ft_backtracking(int *inputt)
{
const int count = 24;
int counters[4]; // rows
int i;
int j;
int k;
int l;
i = 0;
while (i < count)
{
if (is_poss(g_poss[i], inputt[8], inputt[12]) == 1)
{
j = 0;
while (j < count)
{
if (is_poss(g_poss[j], inputt[9], inputt[13]) == 1)
{
k = 0;
while (k < count)
{
if (is_poss(g_poss[k], inputt[10], inputt[14]) == 1)
{
l = 0;
while (l < count)
{
if (is_poss(g_poss[l], inputt[11], inputt[15]) \
== 1)
{
counters[0] = i; //rows
counters[1] = j;
counters[2] = k;
counters[3] = l;
if (ft_checkvertical(inputt, counters) == 1)
{
ft_print_board(i, j, k, l);
return (1);// give row1 row 2 row 3 and row 4
}
}
l++;
}
}
k++;
}
}
j++;
}
}
i++;
}
return(0);
}
int *ft_convert_argv(char *argv)
{
int *tab;
int j;
int k;
tab = malloc (sizeof (int) * 16);
k = 0;
j = 0;
while (argv[j])
{
if (argv[j] >= '1' && argv[j] < '5')
{
tab[k] = argv[j] - '0';
k++;
}
j++;
}
return (tab); //without spaces
}
int ft_check_argv(char *argv)
{
int i;
int j;
int len;
i = 0;
j = 0;
len = ft_strlen(argv);
if (len != 31)
{
ft_putstr("Error\n");
return (0);
}
while (i < len)
{
if (j % 2 == 0 && (argv[i] < '0' || argv[i] > '5'))
{
ft_putstr("Error\n");
return (0);
}
if (j % 2 == 1 && argv[i] != ' ')
{
ft_putstr("Error\n");
return (0);
}
j = j + 1;
i++;
}
return (1);
}
int main(int argc, char **argv)
{
int valid;
int *inputt;
int count;
int i;
int k;
count = 16;
if (argc == 2)
{
inputt = ft_convert_argv(argv[1]);
valid = ft_check_argv(argv[1]);
if (valid == 0)
{
return (0);
}
ft_backtracking(inputt);
if(ft_backtracking(inputt) == 0)
ft_putstr("Error");
return (0);
}
else
ft_putstr("Error\n");
}
|
C
|
//
// Created by diego on 15/11/2019.
//
#include <stdio.h>
#include "Funciones.h"
int main()
{
char n[] = {"7364678393525325392035295"};
char n2[] = {"1674033096929473859689548"};
int x,x2,i;
x = (int)sizeof(n) - 1;x2 = (int)sizeof(n2) - 1;
char n3[x];
char *nn1,*nn2,*nn3;
nn1 = n;nn2 = n2;nn3 = n3;
for(i=0;i <= x;i++)
{
nn3[x-i] = sumar(nn1+x-i,nn2+x2-i);
}
for(i=0;i<x;i++)
{
printf("%c ",nn1[i]);
}
printf("\n\n");
for(i=0;i < x2;i++)
{
printf("%c ",nn2[i]);
}
printf("\n\n");
for(i=0;i<x;i++)
{
printf("%c ",nn3[i]);
}
}
|
C
|
#ifndef SPI_H
#define SPI_H
#include <xs1.h>
#ifdef __spi_conf_h_exists__
#include "spi_conf.h"
#endif
#ifndef SPI_CLK_MHZ
#define SPI_CLK_MHZ 25
#endif
#ifdef __XC__
/** Struct containing ports and clocks used to access a flash device. */
typedef struct fl_spi_ports {
buffered in port:8 spiMISO; /**< Master input, slave output (MISO) port. */
out port spiSS; /**< Slave select (SS) port. */
buffered out port:32 spiCLK; /**< Serial clock (SCLK) port. */
buffered out port:8 spiMOSI; /**< Master output, slave input (MOSI) port. */
clock spiClkblk; /**< Clock block for use with SPI ports. */
} fl_spi_ports;
interface spi_interface {
/** This function issues a single command without parameters to the SPI,
* and reads up to 4 bytes status value from the device.
*
* \param cmd command value - listed above
*
* \param returnBytes The number of bytes that are to be read from the
* device after the command is issued. 0 means no bytes
* will be read.
*
* \returns the read bytes, or zero if no bytes were requested. If multiple
* bytes are requested, then the last byte read is in the least-significant
* byte of the return value.
*/
int command_status(int cmd, unsigned returnBytes);
/** This function issues a single command with a 3-byte address parameter
* and an optional data-set to be output to or input form the device.
*
* \param cmd command value - listed above
*
* \param address the address to send to the SPI device. Only the least
* significant 24 bits are used.
*
* \param data an array of data that contains either data to be written to
* the device, or which is used to store that that is
* read from the device.
*
* \param returnBytes If positive, then this is the number of bytes that
* are to be read from the device, into ``data``. If
* negative, then this is (minus) the number of bytes to
* be written to the device from ``data``. 0 means no
* bytes will be read or written.
*
*/
void command_address_status(int cmd, unsigned int address, unsigned char data[], int returnBytes);
};
/** Task that implements a SPI interface to serial flash, typically the boot flash.
*
* Can be combined or distributed into other tasks.
*
* \param i_spi server interface of type ``spi_interface``
* \param spi_ports reference to a ``fl_spi_ports`` structure containing the SPI flash ports and clockblock
*/
[[distributable]]
void spi_task(server interface spi_interface i_spi, fl_spi_ports &spi_ports);
#endif
#endif
|
C
|
#include <stdio.h>
#include <conio.h>
long c(int n) /* khai bao c la tong giai thua */
{
if (n == 0)
return 1;
else
return(n * c(n - 1));
}
int main() /* a la 1 so bat ky */
/* b la giai thua */
{
int a;
long b;
printf("Enter number : ");
scanf("%d", &a);
b = c(a);
printf("Giai thua cua %d la: %ld", a, b);
getch();
}
/* long la ham khai bao giai thua */
/* ham main de tinh giai thua */
|
C
|
#include"chat.h"
pthread_t thread;
void *sendmessage(void *arg);
char data[MAXMSG];
int main()
{
int cfd;
int recbytes;
int sin_size;
char buffer[MAXMSG];
struct sockaddr_in s_add;
unsigned short portnum=0x8888;
cfd = socket(AF_INET, SOCK_STREAM, 0);
if(-1 == cfd)
{
printf("socket fail ! \r\n");
return -1;
}
printf("socket ok !\r\n");
bzero(&s_add,sizeof(struct sockaddr_in));
s_add.sin_family=AF_INET;
s_add.sin_addr.s_addr= inet_addr("127.0.0.1");
s_add.sin_port=htons(portnum);
printf("s_addr = %#x ,port : %#x\r\n",s_add.sin_addr.s_addr,s_add.sin_port);
if(-1 == connect(cfd,(struct sockaddr *)(&s_add), sizeof(struct sockaddr)))
{
printf("connect fail !\r\n");
return -1;
}
printf("connect ok !\r\n");
pthread_create(&thread,NULL,sendmessage,(void *)cfd);
while(1)
{
bzero(buffer,sizeof(buffer));
recbytes = read(cfd,buffer,MAXMSG);
if(-1 == recbytes)
{
printf("read data fail !\r\n");
return -1;
}else if(0 == recbytes){
printf("the server has terminal the chat!\n");
return 0;
}
else
printf("REC:%s\n",buffer);
bzero(data,sizeof(data));
// if((scanf("%s",data)) > 0)
// {
// write(cfd,data,strlen(data));
// }
}
getchar();
close(cfd);
return 0;
}
void *sendmessage(void *arg)
{
int fd = (int)arg;
bzero(data,sizeof(data));
while((scanf("%s",data)) != EOF)
{
write(fd,data,strlen(data));
}
}
|
C
|
#include<stdio.h>
void main()
{
int n,i=1,m;
printf("\nEnter a number :");
scanf("%d",&n);
printf("\nMultiplication table of %d :",n);
do{
m=n*i;
printf("\n%d",m);
i++;
}while(i<=10);
}
|
C
|
//http://www.geeksforgeeks.org/inorder-predecessor-successor-given-key-bst/
/*
*
Inorder Successor
=================
There are two cases for the node.
1) if the node has right child. Then the successor would be the leftmost node (or mininum) of its right subtree.
2) if the node has no right child. Then the successor would be the lowest node whose left subtree contains the node.
*
*/
#include <stdio.h>
#include <stdlib.h>
typedef struct node
{
int key;
struct node *left, *right ;
}Node;
// A utility function to create a new BST node
Node *newNode(int item)
{
Node *temp = malloc(sizeof (Node));
temp->key = item;
temp->left = temp->right = NULL;
return temp;
}
/* A utility function to insert a new node with given key in BST */
Node* insert(Node* node, int key)
{
if (node == NULL) return newNode(key);
if (key < node->key)
node->left = insert(node->left, key);
else
node->right = insert(node->right, key);
return node;
}
Node *find(Node *root, int key)
{
if(!root) return NULL;
if(root->key == key) return root;
else if(key < root->key) find(root->left, key);
else find(root->right, key);
}
Node *find_min(Node *root)
{
Node *curr = root;
if(!root) return NULL;
while(curr->left)
{
curr=curr->left;
}
return curr;
}
Node *find_max(Node *root)
{
Node *curr = root;
if(!root) return NULL;
while(curr->right)
{
curr=curr->right;
}
return curr;
}
Node * successor(Node *root, int key)
{
Node *curr = find(root,key);
if(!curr) return NULL; // ie., no node with given key.
if (curr->right)
{
return find_min(curr->right);
}
//Handle the case, there is no right subtree to given search key
//start at root
{
Node * ancestor = root;
Node * successor = NULL;
while(curr != ancestor)
{
if (curr->key < ancestor->key)
{
successor = ancestor;
ancestor = ancestor->left;
}
else
{
ancestor = ancestor->right;
}
}
return successor;
}
}
Node * predecessor(Node *root, int key)
{
Node *curr = find(root,key);
if(!curr) return NULL; // ie., no node with given key.
if (curr->left)
{
return find_max(curr->left);
}
//Handle the case, there is no left subtree to given search key
//start at root
{
Node * ancestor = root;
Node * predecessor = NULL;
while(curr != ancestor)
{
if (curr->key > ancestor->key)
{
predecessor = ancestor;
ancestor = ancestor->right;
}
else
{
ancestor = ancestor->left;
}
}
return predecessor;
}
}
// Driver program to test above function
int main()
{
//int key = 30; //Key to be searched in BST
int key = 70; //Key to be searched in BST
//int key = 50; //Key to be searched in BST
//int key = 65; //Key to be searched in BST
/* Let us create following BST
50
/ \
30 70
/ \ / \
20 40 60 80 */
/* Let us create following BST
50
/ \
30 70
/ \
20 80 */
Node *root = NULL;
Node* pre = NULL, *suc = NULL;
root = insert(root, 50);
insert(root, 30);
insert(root, 20);
//insert(root, 40);
insert(root, 70);
//insert(root, 60);
insert(root, 80);
suc = successor(root, key);
if (suc)
printf("Successor is %d\n", suc->key);
else
printf("NO Successor\n");
pre = predecessor(root, key);
if (pre)
printf("Predecessor is %d\n", pre->key);
else
printf("NO Predecessor\n");
return 0;
}
|
C
|
#include<stdio.h>
int main()
{
int num,sum=0,rem,temp;
printf("\nEnter a number: ");
scanf("%d",&num);
temp = num;
while (num != 0)
{
rem = num % 10;
sum = sum + (rem*rem*rem);
num = num / 10;
}
if(temp == sum)
printf("%d is an Armstrong Number",temp);
else
printf("\n%d is not an Armstrong Number",temp);
return(0);
}
|
C
|
/********************************************************************************
* Copyright (c) 2020 AVL List GmbH and others
*
* This program and the accompanying materials are made available under the
* terms of the Apache Software License 2.0 which is available at
* https://www.apache.org/licenses/LICENSE-2.0.
*
* SPDX-License-Identifier: Apache-2.0
********************************************************************************/
#include <stdarg.h>
#include <stdio.h>
#include <string.h>
#include "common/memory.h"
#include "util/string.h"
#ifdef __cplusplus
extern "C" {
#endif /* __cplusplus */
char * mcx_string_dup(const char * s) {
char * ret = NULL;
if (s) {
ret = (char*)mcx_calloc(strlen(s)+1, 1);
if (ret) {
strcpy(ret, s);
}
}
return ret;
}
static int mcx_string_contains_char(const char * str, char c) {
size_t i = 0;
size_t len = strlen(str);
for (i = 0; i < len; i++) {
if (str[i] == c) {
return 1;
}
}
return 0;
}
char * mcx_string_encode(const char * str, char _escape_char, const char _chars_to_escape[]) {
size_t len = strlen(str);
size_t num = 0;
size_t i = 0, j = 0;
/* allocate maximal length (if all chars need to be escaped) */
char * buffer = (char *) mcx_calloc(len * 3 + 1, sizeof(char));
if (!buffer) {
return NULL;
}
for (i = 0; i < len; i++) {
if (mcx_string_contains_char(_chars_to_escape, str[i])) {
buffer[j++] = _escape_char;
sprintf(buffer + j, "%2x", str[i]);
j += 2;
} else {
buffer[j++] = str[i];
}
}
/* shrink to real size */
buffer = (char *) mcx_realloc(buffer, (strlen(buffer) + 1) * sizeof(char));
if (!buffer) {
return NULL;
}
return buffer;
}
char * mcx_string_encode_filename(const char * str) {
return mcx_string_encode(str, '%', "\\\"<>|!#$&'()*+,/:;=?@[]%");
}
int mcx_string_ends_with(const char * str, const char * suffix) {
if ( *str ) {
char * pos = strstr(str, suffix);
if ( pos && pos + strlen(suffix) == str + strlen(str) ) {
return 1;
}
}
return 0;
}
int mcx_string_starts_with(const char * str, const char * prefix) {
if ( *str ) {
char * pos = strstr(str, prefix);
if ( pos && pos == str ) {
return 1;
}
}
return 0;
}
char * mcx_string_copy(const char * src) {
size_t len = 0;
char * dst = NULL;
if (!src) {
/* the copy of a NULL string is a NULL string */
return NULL;
}
len = strlen(src) + 1;
dst = (char *) mcx_calloc(len, sizeof(char));
if (!dst) {
return NULL;
}
return strncpy(dst, src, len);
}
char * mcx_string_merge(size_t numStrings, ...) {
va_list listPointer;
va_start(listPointer, numStrings);
size_t i = 0;
size_t idx = 0;
const char * * strList = NULL;
char * mergedString = NULL;
size_t mergedStringLen = 0;
if (numStrings == 0) {
return NULL;
}
strList = (const char * *) mcx_calloc(numStrings, sizeof(const char *));
if (!strList) {
return NULL;
}
for (i = 0; i < numStrings; i++) {
const char * str = va_arg(listPointer, const char *);
strList[i] = str;
mergedStringLen += strlen(str);
}
mergedString = (char *) mcx_calloc(mergedStringLen + 1, sizeof(char));
if (mergedString) {
for (i = 0; i < numStrings; i++) {
strcpy(mergedString + idx, strList[i]);
idx += strlen(strList[i]);
}
mergedString[idx] = '\0';
}
mcx_free((void *)strList);
return mergedString;
}
char * mcx_string_merge_array_with_spaces(char * strs[]) {
char * str = NULL;
char ** cur = &strs[0];
size_t len = 0;
while (*cur) {
len += strlen(*cur) + 1; // (+ 1) for space/null termination
++cur;
}
str = mcx_calloc(len, sizeof(char));
if (!str) {
return NULL;
}
cur = &strs[0];
len = 0;
if (*cur) {
len += sprintf(str + len, "%s", *cur);
++cur;
}
while (*cur) {
len += sprintf(str + len, " %s", *cur);
++cur;
}
return str;
}
char * mcx_string_merge_quoted_array_with_spaces(char * strs[]) {
char * str = NULL;
char ** cur = &strs[0];
size_t len = 0;
while (*cur) {
// (+ 1) for space/null termination
// (+ 2) for quotation marks
len += strlen(*cur) + 1 + 2;
++cur;
}
str = mcx_calloc(len, sizeof(char));
if (!str) {
return NULL;
}
cur = &strs[0];
len = 0;
if (*cur) {
len += sprintf(str + len, "\"%s\"", *cur);
++cur;
}
while (*cur) {
len += sprintf(str + len, " \"%s\"", *cur);
++cur;
}
return str;
}
//implements the description from http://man7.org/linux/man-pages/man3/strsep.3.html
char* mcx_string_sep(char** stringp, const char* delim)
{
char* start = NULL;
char* p = NULL;
if (NULL != stringp) {
start = *stringp;
if (NULL != start) {
p = strpbrk(start, delim);
if (p == NULL)
{
*stringp = NULL;
}
else
{
*p = '\0';
*stringp = p + 1;
}
}
}
return start;
}
#ifdef __cplusplus
} /* closing brace for extern "C" */
#endif /* __cplusplus */
|
C
|
/*
* I - PushTo Telescope
* ICPC 2012 Greater NY Regional
* Solution by Fred Pickel
* Problem by Fred Pickel
*/
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <ctype.h>
#include <string.h>
#undef TEST
#define EPS .01
#define MAX_STARS 100
#define MAX_SUBPROBS 10
#define PI (3.141592653589793238462643383279)
double rotRate = (2.0 * PI * 1.0027379093)/86400.0;
double mat[3][6];
double matA[3][3];
typedef struct _star_data_
{
double azimuth;
double elevation;
} STAR_DATA;
STAR_DATA stars[MAX_STARS+1];
double v0[3], v1[3], v2[3];
double star1base[3], star1meas[3], star2base[3], star2meas[3], star3base[3], star3meas[3];
double star2baseA[3], star2measA[3], star3baseA[3], star3measA[3];
// we use a coordinate system that rotates with the earth and aligns with
// geocentric equatorial coordinates when the telescpoe is turned on (at time = 0)
// in this coordinate system the declination of a start is the same but the right ascension is
// ra - t*rotRate where ra is right ascension in geocentric equatorial coordinates
// and rot rate is the earths rotaion rate in radians per second
//
// in SetStar1 below we get a vector in this coordinate system to the first star
// the corresponding vector in telescope coordinates is determined by the measured azimuth and elevation
// in SetStar2 below we get a vector in this coordinate system to the second star
// and a vector in telescope coordinates
// then get a third independnet vector in each coordinate system by taking the cross product
// of the two vectors we already have
// what we want is a matrix that transforms the rotating start coordinates to telsescope coordinates
// if the columns of A are the vectors in star coordinates and the vectors in B are the corresponding
// telescope coordinates, we want B*A^(-1) the solution to X*A = B or Atrans * Xtrans = Btrans (trans = transpose
// solvestars uses gausian elimination to solve for Xtrans (int mat[0-2][3-5]
// this is then used to find telescope coordinates for subsequent stars
int solvestars()
{
int i, j, k, pivind;
double pivot, temp;
for(i = 0; i < 3; i++) {
mat[0][i] = star1base[i];
mat[1][i] = star2base[i];
mat[2][i] = star3base[i];
mat[0][3+i] = star1meas[i];
mat[1][3+i] = star2meas[i];
mat[2][3+i] = star3meas[i];
}
// gauss elim
for( i = 0; i < 3 ; i++) {
// find largest abs size elt in col i row >= i
pivot = mat[i][i];
pivind = i;
for(j = i+1 ; j < 3; j++) {
if(fabs(mat[j][i]) > fabs(pivot)) {
pivot = mat[j][i];
pivind = j;
}
}
if(pivind != i) {
// swap rows
for(j = i; j < 6; j++) {
temp = mat[i][j];
mat[i][j] = mat[pivind][j];
mat[pivind][j] = temp;
}
}
if(fabs(pivot) < EPS) {
return -1;
}
pivot = 1.0/pivot;
// normalize pivot row
for(j = i; j < 6 ; j++) {
mat[i][j] *= pivot;
}
// eliminate from remaining rows
for(j = 0; j < 3; j++) {
if(j == i) {
continue;
}
pivot = mat[j][i];
for(k = i ;k < 6; k++) {
mat[j][k] -= pivot * mat[i][k];
}
}
}
#ifdef TEST
for(i = 0; i < 3; i++) {
v0[i] = v1[i] = v2[i] = 0;
}
for(i = 0; i < 3; i++) {
for(j = 0; j < 3; j++) {
v0[i] += mat[j][3+i]*star1base[j];
v1[i] += mat[j][3+i]*star2base[j];
v2[i] += mat[j][3+i]*star3base[j];
}
}
fprintf(stderr, "%.4f %.4f %.4f %.4f %.4f %.4f\n",
v0[0], v0[1], v0[2], star1meas[0], star1meas[1], star1meas[2]);
fprintf(stderr, "%.4f %.4f %.4f %.4f %.4f %.4f\n",
v1[0], v1[1], v1[2], star2meas[0], star2meas[1], star2meas[2]);
fprintf(stderr, "%.4f %.4f %.4f %.4f %.4f %.4f\n",
v2[0], v2[1], v2[2], star3meas[0], star3meas[1], star3meas[2]);
#endif
return 0;
}
int SetStar1(int secs, int ind, double measaz, double measelev)
{
STAR_DATA *pBase = &(stars[ind]);
star1base[2] = sin(pBase->elevation);
star1base[0] = cos(pBase->elevation) * cos(pBase->azimuth - ((double)secs)*rotRate);
star1base[1] = cos(pBase->elevation) * sin(pBase->azimuth - ((double)secs)*rotRate);
star1meas[2] = sin(measelev);
star1meas[0] = cos(measelev) * cos(measaz);
star1meas[1] = cos(measelev) * sin(measaz);
return 0;
}
int SetStar2(int secs, int ind, double measaz, double measelev)
{
STAR_DATA *pBase = &(stars[ind]);
star2base[2] = sin(pBase->elevation);
star2base[0] = cos(pBase->elevation) * cos(pBase->azimuth - ((double)secs)*rotRate);
star2base[1] = cos(pBase->elevation) * sin(pBase->azimuth - ((double)secs)*rotRate);
star2meas[2] = sin(measelev);
star2meas[0] = cos(measelev) * cos(measaz);
star2meas[1] = cos(measelev) * sin(measaz);
// star3 dir is cross prod
star3base[0] = star1base[1] * star2base[2] - star1base[2] * star2base[1];
star3base[1] = star1base[2] * star2base[0] - star1base[0] * star2base[2];
star3base[2] = star1base[0] * star2base[1] - star1base[1] * star2base[0];
star3meas[0] = star1meas[1] * star2meas[2] - star1meas[2] * star2meas[1];
star3meas[1] = star1meas[2] * star2meas[0] - star1meas[0] * star2meas[2];
star3meas[2] = star1meas[0] * star2meas[1] - star1meas[1] * star2meas[0];
return solvestars();
}
// alternate version
// we make star2baseA and star2measA orthogonal to star1base and star1meas resp
// then make them unit vectors
// then compute star3... as befor by cross product
// the resulting matrix of columns A = [star1base star2baseA star3baseA] is orthognal so A^-1 = Atrans
// so the matrix we need is B*Atrans which we compute directly
// NOTE: these two methods do not ingeneral compute exactly the same star directions
// the first method computes a matrix which takes the base star directions to the measured star directions
// the second method computes and orthogonal (rotation) matrix which takes the first star base direction
// to the first star measured direction and the plane of the two star base diections to the plane of the
// two measured star directions
// In the second case assunes that the angle between the base star directions and the angle between
// the measured star directions is exactly the same (rotations preserve angles)
// If this is not true, due for instance to errors in pointing at the base stars, the two methods
// will not give the same answer
// It is beyond the scope of this problem to correct for those errors
// for instance by adjusting the two measured star directions by the smallest amount that gives
// the same angle for the adjusted measured directions as the base directions
int SetStar2A(int secs, int ind, double measaz, double measelev)
{
STAR_DATA *pBase = &(stars[ind]);
double dbase, dmeas, magbase, magmeas;
int i, j;
star2baseA[2] = sin(pBase->elevation);
star2baseA[0] = cos(pBase->elevation) * cos(pBase->azimuth - ((double)secs)*rotRate);
star2baseA[1] = cos(pBase->elevation) * sin(pBase->azimuth - ((double)secs)*rotRate);
star2measA[2] = sin(measelev);
star2measA[0] = cos(measelev) * cos(measaz);
star2measA[1] = cos(measelev) * sin(measaz);
// find dot product
dbase = dmeas = 0.0;
magbase = magmeas = 0.0;
for(i= 0; i < 3; i++) {
dbase += star1base[i]*star2baseA[i];
dmeas += star1meas[i]*star2measA[i];
magbase += star1base[i] * star1base[i];
magmeas += star1meas[i] * star1meas[i];
}
// make star2 perp to star1 and compute magnitudes
magbase = magmeas = 0.0;
for(i= 0; i < 3; i++) {
star2baseA[i] -= dbase * star1base[i];
star2measA[i] -= dmeas * star1meas[i];
magbase += star2baseA[i] * star2baseA[i];
magmeas += star2measA[i] * star2measA[i];
}
if((magbase < EPS) || (magmeas < EPS)) {
return -5;
}
magbase = 1.0/sqrt(magbase);
magmeas = 1.0/sqrt(magmeas);
// normalize
dbase = dmeas = 0.0;
for(i= 0; i < 3; i++) {
star2baseA[i] *= magbase;
star2measA[i] *= magmeas;
dbase += star1base[i]*star2baseA[i];
dmeas += star1meas[i]*star2measA[i];
}
// star3 dir is cross prod
star3baseA[0] = star1base[1] * star2baseA[2] - star1base[2] * star2baseA[1];
star3baseA[1] = star1base[2] * star2baseA[0] - star1base[0] * star2baseA[2];
star3baseA[2] = star1base[0] * star2baseA[1] - star1base[1] * star2baseA[0];
star3measA[0] = star1meas[1] * star2measA[2] - star1meas[2] * star2measA[1];
star3measA[1] = star1meas[2] * star2measA[0] - star1meas[0] * star2measA[2];
star3measA[2] = star1meas[0] * star2measA[1] - star1meas[1] * star2measA[0];
dbase = dmeas = 0.0;
magbase = magmeas = 0.0;
for(i= 0; i < 3; i++) {
dbase += star1base[i]*star3baseA[i];
dmeas += star1meas[i]*star3measA[i];
magbase += star2baseA[i] * star3baseA[i];
magmeas += star2measA[i] * star3measA[i];
}
for(i = 0; i < 3; i++) {
for(j = 0; j < 3; j++) {
matA[i][j] = star1base[j] * star1meas[i] + star2baseA[j] * star2measA[i] + star3baseA[j] * star3measA[i];
}
}
#ifdef TEST
for(i = 0; i < 3; i++) {
v0[i] = v1[i] = v2[i] = 0;
}
for(i = 0; i < 3; i++) {
for(j = 0; j < 3; j++) {
v0[i] += matA[i][j]*star1base[j];
v1[i] += matA[i][j]*star2base[j];
v2[i] += matA[i][j]*star3base[j];
}
}
fprintf(stderr, "%.4f %.4f %.4f %.4f %.4f %.4f\n",
v0[0], v0[1], v0[2], star1meas[0], star1meas[1], star1meas[2]);
fprintf(stderr, "%.4f %.4f %.4f %.4f %.4f %.4f\n",
v1[0], v1[1], v1[2], star2meas[0], star2meas[1], star2meas[2]);
fprintf(stderr, "%.4f %.4f %.4f %.4f %.4f %.4f\n",
v2[0], v2[1], v2[2], star3meas[0], star3meas[1], star3meas[2]);
#endif
return 0;
}
int FindStarA(int secs, int ind, double *paz, double *pelev)
{
double x, y, z, r, base[3], az;
STAR_DATA *pBase = &(stars[ind]);
base[2] = sin(pBase->elevation);
base[0] = cos(pBase->elevation) * cos(pBase->azimuth - ((double)secs)*rotRate);
base[1] = cos(pBase->elevation) * sin(pBase->azimuth - ((double)secs)*rotRate);
x = base[0] * matA[0][0] + base[1] * matA[0][1] + base[2] * matA[0][2];
y = base[0] * matA[1][0] + base[1] * matA[1][1] + base[2] * matA[1][2];
z = base[0] * matA[2][0] + base[1] * matA[2][1] + base[2] * matA[2][2];
r = sqrt(x*x + y*y);
*pelev = atan2(z, r) * 180.0/PI;
az = atan2(y, x) * 180.0/PI;
if(az < 0.0) az += 180.0;
*paz = az;
return 0;
}
int FindStar(int secs, int ind, double *paz, double *pelev)
{
double x, y, z, r, base[3], az;
STAR_DATA *pBase = &(stars[ind]);
base[2] = sin(pBase->elevation);
base[0] = cos(pBase->elevation) * cos(pBase->azimuth - ((double)secs)*rotRate);
base[1] = cos(pBase->elevation) * sin(pBase->azimuth - ((double)secs)*rotRate);
x = base[0] * mat[0][3] + base[1] * mat[1][3] + base[2] * mat[2][3];
y = base[0] * mat[0][4] + base[1] * mat[1][4] + base[2] * mat[2][4];
z = base[0] * mat[0][5] + base[1] * mat[1][5] + base[2] * mat[2][5];
r = sqrt(x*x + y*y);
*pelev = atan2(z, r) * 180.0/PI;
az = atan2(y, x) * 180.0/PI;
if(az < 0.0) az += 180.0;
*paz = az;
return 0;
}
char inbuf[256];
int main()
{
int nprob, nstars, curprob, index, subprobs, starInd, secs, subprob;
double elev, az;
if(fgets(&(inbuf[0]), 255, stdin) == NULL)
{
fprintf(stderr, "Read failed on problem and star count\n");
return -1;
}
if(sscanf(&(inbuf[0]), "%d %d", &nstars, &nprob) != 2)
{
fprintf(stderr, "Scan failed on problem and star count\n");
return -2;
}
if((nstars < 5) || (nstars > MAX_STARS))
{
fprintf(stderr, "star count must be in range 5 to %d\n", MAX_STARS);
return -21;
}
for(starInd = 1; starInd <= nstars ; starInd++)
{
if(fgets(&(inbuf[0]), 255, stdin) == NULL)
{
fprintf(stderr, "Read failed on star %d data\n", starInd);
return -23;
}
if(sscanf(&(inbuf[0]), "%d %lf %lf", &index, &az, &elev) != 3)
{
fprintf(stderr, "scan failed on star %d data\n", starInd);
return -26;
}
if(starInd != index) {
fprintf(stderr, "star index %d not = expected star %d\n",
index, starInd);
return -27;
}
stars[index].azimuth = (az * PI)/180.0;
stars[index].elevation = (elev * PI)/180.0;
}
for(curprob = 1; curprob <= nprob ; curprob++)
{
if(fgets(&(inbuf[0]), 255, stdin) == NULL)
{
fprintf(stderr, "Read failed on problem header problem index %d \n", curprob);
return -3;
}
// get prob num and subprob count
if(sscanf(&(inbuf[0]), "%d %d", &index, &subprobs) != 2)
{
fprintf(stderr, "scan failed on problem header problem index %d\n",
curprob);
return -6;
}
if(curprob != index) {
fprintf(stderr, "problem index %d not = expected %d\n",
index, curprob);
return -7;
}
if((subprobs < 1) || (subprobs > MAX_SUBPROBS)) {
fprintf(stderr, "number of subproblems %d not in range 1 to %d problem %d\n",
subprobs, MAX_SUBPROBS, curprob);
return -8;
}
// get first alignment star
if(fgets(&(inbuf[0]), 255, stdin) == NULL)
{
fprintf(stderr, "Read failed on first alignment star problem %d \n", curprob);
return -10;
}
if(sscanf(&(inbuf[0]), "%d %d %lf %lf", &secs, &starInd, &az, &elev) != 4)
{
fprintf(stderr, "scan failed on on first alignment star problem %d\n",
curprob);
return -11;
}
if((starInd < 1) || (starInd > MAX_STARS)) {
fprintf(stderr, "first alignment star index %d not in range 1 to %d problem %d\n",
starInd, MAX_STARS, curprob);
return -51;
}
SetStar1(secs, starInd, (PI*az)/180.0, (PI*elev)/180.0);
// get second alignment star
if(fgets(&(inbuf[0]), 255, stdin) == NULL)
{
fprintf(stderr, "Read failed on second alignment star problem %d \n", curprob);
return -12;
}
if(sscanf(&(inbuf[0]), "%d %d %lf %lf", &secs, &starInd, &az, &elev) != 4)
{
fprintf(stderr, "scan failed on on second alignment star problem %d\n",
curprob);
return -13;
}
if((starInd < 1) || (starInd > MAX_STARS)) {
fprintf(stderr, "second alignment star index %d not in range 1 to %d problem %d\n",
starInd, MAX_STARS, curprob);
return -52;
}
#ifdef USE_ORIG
if(SetStar2(secs, starInd, (PI*az)/180.0, (PI*elev)/180.0) != 0) {
fprintf(stderr, "bad alignment stars problem %d\n",
curprob);
return -14;
}
#else
if(SetStar2A(secs, starInd, (PI*az)/180.0, (PI*elev)/180.0) != 0) {
fprintf(stderr, "bad alignmentA stars problem %d\n",
curprob);
return -24;
}
#endif
printf("%d %d\n", curprob, subprobs);
for(subprob = 1 ; subprob <= subprobs ; subprob++) {
if(fgets(&(inbuf[0]), 255, stdin) == NULL)
{
fprintf(stderr, "Read failed on sub problem %d problem %d \n", subprob, curprob);
return -15;
}
if(sscanf(&(inbuf[0]), "%d %d %d", &index, &secs, &starInd) != 3)
{
fprintf(stderr, "scan failed on on sub problem %d problem %d\n",
subprob, curprob);
return -16;
}
if(index != subprob) {
fprintf(stderr, "subproblem index %d not = expected %d problem %d\n",
index, subprob, curprob);
return -17;
}
if((starInd < 1) || (starInd > MAX_STARS)) {
fprintf(stderr, "sub problem %d star index %d not in range 1 to %d problem %d\n",
subprob, starInd, MAX_STARS, curprob);
return -53;
}
#ifdef USE_ORIG
FindStar(secs, starInd, &az, &elev);
#else
FindStarA(secs, starInd, &az, &elev);
#endif
if(elev < 0.0) {
printf("%d NOT VISIBLE\n", subprob);
} else {
printf("%d %.1lf %.1lf\n", subprob, az, elev);
}
}
}
return 0;
}
|
C
|
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
int main(int argc, char *argv[])
{
if (argc != 2) {
printf("usage: %s file\n", argv[0]);
return 0;
}
if (access(argv[1], R_OK) == -1)
perror("access R_OK test failed");
else
printf("access R_OK test passed\n");
if (open(argv[1], O_RDONLY) < 0)
perror("open with O_RDONLY failed");
else
printf("open with O_RDONLY passed\n");
}
|
C
|
/* Header for Thermometer module
Computerarchitektur 3
Hochschule Esslingen
Author: M.Brandel, J.Ruess, 04.01.2018
Modified: -
*/
#include "ad.h"
extern int ad_value;
static int temp_value;
static char sign = ' ';
static int upperLimit = 70;
static int lowerLimit = -30;
static int maxResolution = 1023;
static int minResolution = 0;
void updateThermo(int ad_val)
{
ad_value = ad_val;
temp_value = (int)(ad_value/10) + lowerLimit;//= (long)((ad_value * (upperLimit-lowerLimit)) / (maxResolution-minResolution) + lowerLimit);
//temp_value = (int)temp_val;
if (temp_value < 0){
temp_value *= -1 ;
sign = '-';
} else {
sign = '+';
}
}
char getTempChar()
{
return sign;
}
int getTempValue()
{
return (char)temp_value;
}
|
C
|
/*
* mmap( MAP_SHARED ) test program
*
* Copyright (C) 2014 KO Myung-Hun <komh@chollian.net>
*
* This program is free software. It comes without any warranty, to
* the extent permitted by applicable law. You can redistribute it
* and/or modify it under the terms of the Do What The Fuck You Want
* To Public License, Version 2, as published by Sam Hocevar. See
* http://www.wtfpl.net/ for more details.
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <io.h>
#include <fcntl.h>
#include <process.h>
#include "mmap.h"
#include "mmap-2.h"
#define EXIT(c) do { rc = ( c ); goto exit_close; } while( 0 )
int main( void )
{
const char *name = MMAP_FILENAME;
const char *msg = MMAP_MSG;
const char *child = "mmap-2-child.exe";
const int pagesize = getpagesize();
int fd;
char *p;
int len = strlen( msg ) + 1;
int rc = 0;
fd = open( name, O_RDWR | O_CREAT | O_SIZE | O_BINARY, S_IREAD | S_IWRITE,
pagesize * 3 );
if( fd == -1 )
{
fprintf( stderr, "open() failed!!!\n");
return 1;
}
p = mmap( NULL, pagesize * 2, PROT_READ, MAP_SHARED, fd, 0 );
if( p == MAP_FAILED )
{
fprintf( stderr, "mmap() failed\n");
EXIT( 1 );
}
printf("Spawning a child...\n");
if( spawnlp( P_WAIT, child, child, NULL ) != 0 )
{
fprintf( stderr, "spawnlp() failed\n");
munmap( p, len );
EXIT( 1 );
}
printf("Comparing a mmaped memory... ");
if( memcmp( msg, p + pagesize, len ))
printf("FAILED\n");
else
printf("PASSED\n");
if( munmap( p, pagesize * 2 ) == -1 )
{
fprintf( stderr, "munmap() failed\n");
EXIT( 1 );
}
printf("Reading from a file...\n");
p = calloc( 1, len );
lseek( fd, pagesize, SEEK_SET );
read( fd, p, len );
printf("Comparing contents... ");
if( !memcmp( msg, p, len ))
printf("PASSED\n");
else
printf("FAILED\n");
free( p );
exit_close:
close( fd );
remove( name );
return rc;
}
|
C
|
// SPDX-License-Identifier: GPL-2.0+
#ifndef __LINUX_BITMAP_H
#define __LINUX_BITMAP_H
#include <asm/types.h>
#include <linux/types.h>
#include <linux/bitops.h>
#define small_const_nbits(nbits) \
(__builtin_constant_p(nbits) && (nbits) <= BITS_PER_LONG)
static inline void bitmap_zero(unsigned long *dst, int nbits)
{
if (small_const_nbits(nbits)) {
*dst = 0UL;
} else {
int len = BITS_TO_LONGS(nbits) * sizeof(unsigned long);
memset(dst, 0, len);
}
}
static inline unsigned long
find_next_bit(const unsigned long *addr, unsigned long size,
unsigned long offset)
{
const unsigned long *p = addr + BIT_WORD(offset);
unsigned long result = offset & ~(BITS_PER_LONG - 1);
unsigned long tmp;
if (offset >= size)
return size;
size -= result;
offset %= BITS_PER_LONG;
if (offset) {
tmp = *(p++);
tmp &= (~0UL << offset);
if (size < BITS_PER_LONG)
goto found_first;
if (tmp)
goto found_middle;
size -= BITS_PER_LONG;
result += BITS_PER_LONG;
}
while (size & ~(BITS_PER_LONG - 1)) {
tmp = *(p++);
if ((tmp))
goto found_middle;
result += BITS_PER_LONG;
size -= BITS_PER_LONG;
}
if (!size)
return result;
tmp = *p;
found_first:
tmp &= (~0UL >> (BITS_PER_LONG - size));
if (tmp == 0UL) /* Are any bits set? */
return result + size; /* Nope. */
found_middle:
return result + __ffs(tmp);
}
/*
* Find the first set bit in a memory region.
*/
static inline unsigned long find_first_bit(const unsigned long *addr, unsigned long size)
{
unsigned long idx;
for (idx = 0; idx * BITS_PER_LONG < size; idx++) {
if (addr[idx])
return min(idx * BITS_PER_LONG + __ffs(addr[idx]), size);
}
return size;
}
#define for_each_set_bit(bit, addr, size) \
for ((bit) = find_first_bit((addr), (size)); \
(bit) < (size); \
(bit) = find_next_bit((addr), (size), (bit) + 1))
#endif /* __LINUX_BITMAP_H */
|
C
|
#include "commandthread.h"
#include "utils.h"
#include <unistd.h>
#include <stdlib.h>
command_thread_desc_struct *cmDesc = NULL;
void *command_thread_func(void *arg) {
cmDesc->s_socket_desc = socket(AF_INET , SOCK_STREAM , 0);
if (cmDesc->s_socket_desc == -1) {
cmDesc->thread_state = TERMINATED;
printf("Error: Could not create socket");
}
cmDesc->s_addr.sin_family = AF_INET;
cmDesc->s_addr.sin_addr.s_addr = INADDR_ANY;
cmDesc->s_addr.sin_port = htons(3150);
if (bind(cmDesc->s_socket_desc, (struct sockaddr *)&cmDesc->s_addr, sizeof(cmDesc->s_addr)) < 0) {
perror("Error: Socket BIND failed");
return 1;
}
listen(cmDesc->s_socket_desc, 1);
printf("Waiting for incoming connections...");
while (is_alive()) {
int addr_len = sizeof(struct sockaddr_in);
cmDesc->c_socket_desc = accept(cmDesc->s_socket_desc, (struct sockaddr *)&cmDesc->c_addr, (socklen_t*)&addr_len);
printf("Connection accepted!\n");
while (is_alive()) {
char *msg = "Hello!";
write(cmDesc->c_socket_desc, msg, strlen(msg));
usleep(1000000);
}
}
pthread_exit(0);
}
int command_thread_create() {
if (cmDesc == NULL) {
return -2;
}
cmDesc = malloc(sizeof(command_thread_desc_struct));
zero_memory(cmDesc, sizeof(command_thread_desc_struct));
printf("Staring CommandThread...");
cmDesc->thread_state = STARTED;
if (pthread_create(&cmDesc->thread, NULL, command_thread_func, NULL) != 0) {
printf("FAILED\n");
command_thread_cleanup();
return -1;
}
printf("OK\n");
return 0;
}
void command_thread_free() {
if (!is_alive()) {
return;
}
cmDesc->thread_state = TERMINATED;
command_thread_cleanup();
}
void command_thread_join() {
if (!is_alive()) {
return;
}
pthread_join(cmDesc->thread, NULL);
}
void command_thread_cleanup() {
if (cmDesc != NULL) {
cmDesc->thread = 0;
cmDesc->thread_state = NOT_INITIALIZED;
}
}
int is_alive() {
return (cmDesc != NULL && cmDesc->thread != 0 && cmDesc->thread_state == STARTED);
}
|
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 A, B;
printf("\n what is your salary? " );
scanf("%d", &A);
printf("\n how old are you? " );
scanf("%d", &B);
printf("\n i earn %d", A);
printf("\n i am %d", B );
return 0;
}
|
C
|
#include<stdio.h>
int main(){
char c1='A',c2='B',c3='c';
char *p1,*p2,*p3;
p3=&c3;
p2=&c2;
p1=&c1;
printf("%c , %c , %c \n ",*p1,*p2,*p3);
}
|
C
|
#include "TextureManager.h"
#include <string.h>
TextureManager * newTextureManager()
{
TextureManager *t = malloc(sizeof(TextureManager));
t->key = NULL;
t->left = NULL;
t->right = NULL;
t->texture = NULL;
return t;
}
SDL_Texture * getTexture(TextureManager *tm, char * name)
{
int r = 0;
if (tm == NULL)
return NULL;
if (tm->key == NULL)
return NULL;
r = strcmp(tm->key, name);
if (r < 0)
return getTexture(tm->left, name);
else if (r > 0)
return getTexture(tm->right, name);
else
return tm->texture;
}
Drawable getResizedDrawable(TextureManager *tm, SDL_Renderer *ren, char * name, int x, int y, int w, int h)
{
Drawable d;
d.dst.x = x;
d.dst.y = y;
d.dst.h = h;
d.dst.w = w;
d.ren = ren;
d.tex = getTexture(tm, name);
if (d.tex == NULL)
d.tex = loadTexture(tm, ren, name);
return d;
}
Drawable getDrawable(TextureManager *tm, SDL_Renderer *ren, char * name, int x, int y)
{
return getResizedDrawable(tm, ren, name, x, y, -1, -1);
}
int insertTexture(SDL_Texture *texture,TextureManager ** tm, char * name)
{
int r = 0;
if (*tm == NULL)
{
*tm = newTextureManager();
(*tm)->key = name;
(*tm)->texture = texture;
return 1;
}
else if ((*tm)->key == NULL)
{
(*tm)->key = name;
(*tm)->texture = texture;
return 1;
}
r = strcmp((*tm)->key, name);
if (r < 0)
return insertTexture(texture, &(*tm)->left, name);
else if (r > 0)
return insertTexture(texture, &(*tm)->right, name);
else
return 0;
}
SDL_Texture * loadTexture(TextureManager *tm, SDL_Renderer * ren, char * name)
{
SDL_Texture *texture = IMG_LoadTexture(ren, name);
insertTexture(texture, &tm, name);
return texture;
}
void deleteTextureManager(TextureManager *tm)
{
if (tm != NULL)
{
deleteTextureManager(tm->left);
deleteTextureManager(tm->right);
SDL_DestroyTexture(tm->texture);
free(tm);
}
}
|
C
|
/***********************************************************
* Author: Eric Magers
* Lab Number: CST 211 Lab 2
* Filename: Insertion.cpp
* Date Created: 4/15/2014
* Modifications:
*
************************************************************/
#include "Insertion.h"
void InsertionSort(int m_array[], int m_length)
{
for (int i = 1; i < m_length; i++)
{
int temp = m_array[i];
int j;
for (j = i; (j > 0) && temp < m_array[j - 1]; j--)
{
m_array[j] = m_array[j - 1];
}
m_array[j] = temp;
}
}
void InsertionSort(Array<int> & m_array)
{
int m_length = m_array.getLength();
for (int i = 1; i < m_length; i++)
{
int temp = m_array[i];
int j;
for (j = i; (j > 0) && temp < m_array[j - 1]; j--)
{
m_array[j] = m_array[j - 1];
}
m_array[j] = temp;
}
}
void InsertionSort(vector<int> & m_array)
{
int m_length = m_array.size();
for (int i = 1; i < m_length; i++)
{
int temp = m_array[i];
int j;
for (j = i; (j > 0) && temp < m_array[j - 1]; j--)
{
m_array[j] = m_array[j - 1];
}
m_array[j] = temp;
}
}
|
C
|
#include <stdio.h>
#include <poll.h>
#include <time.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
int main(int argc,char *argv[]){
int numpipes,numwrites,i,nwrite,ret;
int (*pipefdp)[2];
struct pollfd *fds;
if(argc < 2 || strcmp(argv[1],"--help") == 0){
fprintf(stderr,"%s num-pipes [num-writes]\n",argv[0]);
exit(EXIT_FAILURE);
}
numpipes = atoi(argv[1]);
numwrites = argc > 2 ? atoi(argv[2]) : 1;
pipefdp = calloc(numpipes,sizeof(int [2]));
fds = calloc(numpipes,sizeof(struct pollfd));
for(i = 0; i < numpipes; i++){
if(pipe(pipefdp[i]) == -1){
fprintf(stderr,"pipe\n");
exit(EXIT_FAILURE);
}
}
srand(time(NULL));
for(i = 0; i < numwrites; i++){
nwrite = rand() % numpipes;
printf("write to the %d pipe\n",nwrite);
if(write(pipefdp[nwrite][1],"a",1) != 1){
fprintf(stderr,"write\n");
exit(EXIT_FAILURE);
}
}
for(i = 0; i < numpipes; i++){
fds[i].fd = pipefdp[i][0];
fds[i].events = POLLIN;
}
ret = poll(fds,numpipes,-1);
if(ret < 0){
fprintf(stderr,"poll\n");
exit(EXIT_FAILURE);
}
printf("return %d\n",ret);
for(i = 0; i < numpipes; i++){
if(fds[i].revents & POLLIN){
printf("raeadable : %d\n",i);
}
}
return 0;
}
|
C
|
#include <stdio.h>
#include <tcp_client.h>
#include <error.h>
#include <errno.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#define MAXLINE 1024
int main(int argc, char *argv[])
{
if (argc != 3)
error(1,0,"usage:tcpclient<IPaddress> <Port>");
int port = atoi(argv[2]);
int socket_fd = tcp_client(argv[1],port);
fd_set readmask,allreads;
FD_ZERO(&allreads);
FD_SET(0,&allreads);
FD_SET(socket_fd,&allreads);
int n;
char recv_line[MAXLINE],send_line[MAXLINE];
for(;;) {
readmask = allreads;
int s = select(socket_fd+1,&readmask,NULL,NULL,NULL);
if (s <= 0) {
error(1,errno,"slect failed");
}
if (FD_ISSET(socket_fd,&readmask)) {
n = read(socket_fd,recv_line,MAXLINE);
if (n < 0) {
error(1,errno,"read error");
} else if (n == 0){
printf("server!! closed");
break;
}
recv_line[n] = 0;
printf("get %d byte\n",n);
fputs(recv_line,stdout);
fputs("\n",stdout);
}
if (FD_ISSET(STDIN_FILENO,&readmask)){
if (fgets(send_line,MAXLINE,stdin) != NULL) {
int i = strlen(send_line);
// if (send_line[i - 1] == '\n') {
// send_line[i - 1] = '\0'; // 空 = NULL?
// }
if (strncmp(send_line,"quit",strlen(send_line)) == 0) {
//shutdown??
printf("shutdown\n");
if(shutdown(socket_fd,1)) {
error(1,errno,"shutdown failed");
}
}
size_t rt = write(socket_fd,send_line,strlen(send_line));
printf("send: %d bytes\n",rt);
fputs(send_line,stdout);
fputs("\n",stdout);
if(rt < 0) {
error(1,errno,"write failed");
}
}
}
}
exit(0);
}
|
C
|
/* $Id: test_sm_contains.c 1871 2009-06-12 13:58:18Z lsc $ */
/*
* Copyright (c) 2009 STFC Rutherford Appleton Laboratory
* Author: Lee-Shawn Chin
* Date : June 2009
*
*/
#include "header_string_map.h"
void test_sm_contains(void) {
int i, rc;
MBIt_stringmap *sm;
const char *str[10] = { "value 1",
"value 2",
"value 3",
"value 4",
"value 5",
"The quick brown fox jumps over the lazy dog!",
"The quick brown fox jumps over the lazy dog!!",
" ", /* a single space */
" ", /* three spaces */
"(*^$£$&"
};
/* query from a null map */
sm = NULL;
rc = MBI_stringmap_Contains(sm, "qwerty");
CU_ASSERT_EQUAL(rc, MB_ERR_INVALID);
/* create a map */
sm = MBI_stringmap_Create();
CU_ASSERT_PTR_NOT_NULL(sm);
if (sm != NULL) CU_ASSERT_PTR_NOT_NULL(sm->map);
/* Add a strings */
for (i = 0; i < 10; i++)
{
rc = MBI_stringmap_AddString(sm, str[i]);
if (rc != MB_SUCCESS)
{
CU_FAIL("Failed to add string");
break;
}
}
/* query null string */
rc = MBI_stringmap_Contains(sm, NULL);
CU_ASSERT_EQUAL(rc, MB_ERR_INVALID);
/* query unknown strings */
rc = MBI_stringmap_Contains(sm, "value 8");
CU_ASSERT_EQUAL(rc, MB_FALSE);
rc = MBI_stringmap_Contains(sm, " "); /* four spaces */
CU_ASSERT_EQUAL(rc, MB_FALSE);
rc = MBI_stringmap_Contains(sm, "The quick brown fox jumps over the lazy dog!!!");
CU_ASSERT_EQUAL(rc, MB_FALSE);
rc = MBI_stringmap_Contains(sm, "The quick brown fox jumps over the lazy dog");
CU_ASSERT_EQUAL(rc, MB_FALSE);
/* query known strings */
for (i = 0; i < 10; i++)
{
rc = MBI_stringmap_Contains(sm, str[i]);
if (rc != MB_TRUE)
{
CU_FAIL("Failed to retrieve valid string");
break;
}
}
/* delete the map */
rc = MBI_stringmap_Delete(&sm);
CU_ASSERT_EQUAL(rc, MB_SUCCESS);
CU_ASSERT_PTR_NULL(sm);
}
|
C
|
#pragma once
#include <stdint.h>
#include <stddef.h>
/* A coloured pixel. */
typedef struct {
uint8_t red;
uint8_t green;
uint8_t blue;
} pixel_t;
/* A picture. */
typedef struct {
pixel_t *pixels;
size_t width;
size_t height;
} bitmap_t;
/* Given "bitmap", this returns the pixel of bitmap at the point
("x", "y"). */
pixel_t * pixel_at (bitmap_t * bitmap, int x, int y);
/* Sets a pixel at x,y of bitmap to RGB values of pixel */
void set_pixel(bitmap_t* bitmap, const int x, const int y, const pixel_t* pixel);
|
C
|
/**
* URL - https://www.urionlinejudge.com.br/judge/pt/problems/view/1180
*
* Enunciado - Faça um programa que leia um valor N. Este N será o
* tamanho de um vetor X[N]. A seguir, leia cada um dos
* valores de X, encontre o menor elemento deste vetor
* e a sua posição dentro do vetor, mostrando esta informação.
*
* Entrada - A primeira linha de entrada contem um único inteiro N (1 < N < 1000),
* indicando o número de elementos que deverão ser lidos em seguida para
* o vetor X[N] de inteiros. A segunda linha contém cada um dos N valores,
* separados por um espaço.
*
* Saída - A primeira linha apresenta a mensagem “Menor valor:” seguida de um espaço
* e do menor valor lido na entrada. A segunda linha apresenta a mensagem “Posicao:”
* seguido de um espaço e da posição do vetor na qual se encontra o menor valor lido,
* lembrando que o vetor inicia na posição zero.
*/
#include <stdio.h>
// Versão de teste para VScode
int main()
{
int N = 10,
X[10] = {1, 2, 3, 4, -5, 6, 7, 8, 9, 10},
menor,
posicao;
for (int i = 0; i < N; i++)
{
if (X[i] < menor)
{
/**
* por não ter sido pré-definido,
* menor é um número aleatório muito grande
*/
menor = X[i];
posicao = i;
}
}
printf("Menor valor: %d\nPosicao: %d", menor, posicao);
return 0;
}
// Versão submetida ao URI
int mainURI()
{
int N;
scanf("%d\n", &N);
int X[N], menor, posicao;
for (int i = 0; i < N; i++)
{
scanf("%d ", &X[i]);
if (X[i] < menor)
{
menor = X[i];
posicao = i;
}
}
printf("Menor valor: %d\nPosicao: %d", menor, posicao);
return 0;
}
|
C
|
/*
아래에서 보이는 main 함수에서 물음표 ???을 대신할 수 있는 포인터 변수를 선언해보자.
int main(void)
{
int * arr1[5];
int * arr2[3][5];
??? = arr1;
??? = arr2;
}
*/
|
C
|
#include <stm32f4xx.h>
#include "Spi.h"
#define NULL 0
static volatile uint8_t spi_running = 0;
static volatile uint8_t spi_txe = 1;
static volatile uint8_t spi_last_byte = 0;
static uint8_t* spi_transmit_buffer = NULL;
static uint8_t* spi_receive_buffer = NULL;
static uint16_t spi_data_buffersize = 0;
static volatile uint16_t spi_data_rx_counter = 0;
static volatile uint16_t spi_data_tx_counter = 0;
static void (*spi_external_handler)(void);
// A function to allow bypassing of the here used SPI2_IRQHandler.
// Call spi_overwrite_interrupt_hanlder(your_handler) and it will feel as if
// your handler was the SPI2_IRQHandler.
// To reset call with a value of 0.
void spi_overwrite_interrupt_handler(void (*handler)(void))
{
spi_external_handler = handler;
}
// Initialize SPI hardware
uint8_t spi_initialize(void)
{
// Enable clock for SPI hardware and GPIO port B
RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOB, ENABLE);
RCC_APB1PeriphClockCmd(RCC_APB1Periph_SPI2, ENABLE);
// SPI (SCK PB13, MISO PB14, MOSI PB15)
GPIO_Init(GPIOB, &(GPIO_InitTypeDef){
.GPIO_Pin = GPIO_Pin_13 | GPIO_Pin_14 | GPIO_Pin_15,
.GPIO_Mode = GPIO_Mode_AF,
.GPIO_Speed = GPIO_Speed_50MHz,
});
// Configure pins to be used by the SPI hardware (alternate function)
GPIO_PinAFConfig(GPIOB, GPIO_PinSource13, GPIO_AF_SPI2);
GPIO_PinAFConfig(GPIOB, GPIO_PinSource14, GPIO_AF_SPI2);
GPIO_PinAFConfig(GPIOB, GPIO_PinSource15, GPIO_AF_SPI2);
// Init SPI
SPI_Init(SPI2, &(SPI_InitTypeDef){
.SPI_BaudRatePrescaler = SPI_BaudRatePrescaler_64, // Configure Data speed
.SPI_CPHA = SPI_CPHA_1Edge, // Sample data on rising edge
.SPI_CPOL = SPI_CPOL_Low, // Clock is default low
.SPI_CRCPolynomial = 1, // Don't use CRC
.SPI_DataSize = SPI_DataSize_8b, // Send 16 bit words at a time
.SPI_Direction = SPI_Direction_2Lines_FullDuplex, // Only enable sending (transmission/TX)
.SPI_FirstBit = SPI_FirstBit_MSB, // Most Significant Bit first
.SPI_Mode = SPI_Mode_Master, // STM32 is the master
.SPI_NSS = SPI_NSS_Soft, // Don't use automatic chip select
});
// Enable SPI interrupt
NVIC_Init(&(NVIC_InitTypeDef){
.NVIC_IRQChannel = SPI2_IRQn,
.NVIC_IRQChannelPreemptionPriority = 0,
.NVIC_IRQChannelSubPriority = 0,
.NVIC_IRQChannelCmd = ENABLE,
});
// Enable SPI hardware
SPI_Cmd(SPI2, ENABLE);
}
// Return wheter the SPI is done completely
uint8_t spi_is_running(void)
{
return spi_running;
}
// Return wheter the SPI transmit buffer is empty, and can take more data
uint8_t spi_is_txe(void)
{
return spi_txe;
}
// Wait for spi_is_running == false
void spi_wait_running(void)
{
while (spi_running);
}
// Wait for spi_is_running == true
void spi_wait_txe(void)
{
while (!spi_txe);
}
// Put a byte into the transmit buffer
void spi_send_byte(uint8_t data)
{
spi_wait_txe();
spi_transmit_buffer = NULL;
spi_receive_buffer = NULL;
spi_txe = 0;
spi_running = 1;
SPI_I2S_SendData(SPI2, data);
SPI_I2S_ITConfig(SPI2, SPI_I2S_IT_RXNE, ENABLE);
}
// Same as spi_send_byte(0) - for receive-only applications
void spi_receive_byte(void)
{
spi_send_byte(0);
}
// Get the last received byte
uint8_t spi_get_last_byte(void)
{
return spi_last_byte;
}
// Send/receive count bytes of data. Any of the buffers may be NULL. Then
// there will be sent bytes of value 0 / received bytes won't be saved.
void spi_send_buffer(uint8_t* send_buffer, uint8_t* receive_buffer, uint16_t count)
{
spi_wait_running();
spi_transmit_buffer = send_buffer;
spi_receive_buffer = receive_buffer;
spi_data_buffersize = count;
spi_data_tx_counter = 0;
spi_data_rx_counter = 0;
spi_txe = 0;
spi_running = 1;
SPI_I2S_ITConfig(SPI2, SPI_I2S_IT_TXE, ENABLE);
SPI_I2S_ITConfig(SPI2, SPI_I2S_IT_RXNE, ENABLE);
}
void SPI2_IRQHandler(void){
// If the external interrupt handler is set, call it
if (spi_external_handler)
{
spi_external_handler();
return;
}
// Check for interrupt cause
if(SPI_I2S_GetFlagStatus(SPI2, SPI_I2S_FLAG_RXNE) == SET)
{
spi_last_byte = SPI_I2S_ReceiveData(SPI2);
if (spi_receive_buffer)
{
// buffered mode
spi_receive_buffer[spi_data_rx_counter++] = spi_last_byte;
if (spi_data_rx_counter >= spi_data_buffersize)
{
spi_receive_buffer = NULL;
spi_running = 0;
SPI_I2S_ITConfig(SPI2, SPI_I2S_IT_RXNE, DISABLE);
}
} else {
// non buffered mode
spi_running = 0;
SPI_I2S_ITConfig(SPI2, SPI_I2S_IT_RXNE, DISABLE);
}
}
else if(SPI_I2S_GetFlagStatus(SPI2, SPI_I2S_FLAG_TXE) == SET)
{
// only buffered mode
if (spi_data_tx_counter >= spi_data_buffersize)
{
SPI_I2S_ITConfig(SPI2, SPI_I2S_IT_TXE, DISABLE);
spi_transmit_buffer = NULL;
spi_txe = 1;
} else {
SPI_I2S_SendData(SPI2, spi_transmit_buffer ? spi_transmit_buffer[spi_data_tx_counter] : 0);
spi_data_tx_counter++;
}
}
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <semaphore.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/shm.h>
#include "common.h"
sem_t *sem_send;
sem_t *sem_recive;
int main()
{
// init
char msg[512];
char msgBuf[512];
strcpy(msg,"");
int shmid = shmget(key, sizeof(message), 0666 | IPC_CREAT);
check_error(shmid);
void* shmp = shmat(shmid, NULL, 0);
sem_send = sem_open(name, O_CREAT, 0666, 1);
sem_recive = sem_open(name, O_CREAT, 0666, 1);
//这段代码的目的是防止之前使用Ctrl+C强行终止进程导致重新允许时初始化信号量时,信号量sem_send的值为之前运行的0
int i;//see the value of sem_send
if(sem_getvalue(sem_send,&i)==0){
while(i>2)
sem_wait(sem_send);
if(i==0)
sem_post(sem_send);
}
while(1){
sem_wait(sem_send);
printf("input:");
gets(msg);
if(strlen(((message*)shmp)->text)+strlen(msg)>=MAX_SIZE){//当共享内存满的情况
printf("buffer is full! please wait!\n");
int len=MAX_SIZE-strlen(((message*)shmp)->text);//目前共享内存可用容量len,可能取值:0-512
if(strlen(msg)>MAX_SIZE){//目的是为了分段发送消息
int count=((strlen(msg)-len)/MAX_SIZE)+1+1;//该字段是为了计算要分段发送几次数据,两次+1的其中一个是为了取上整数,另一个是因为减去了len(一次len占用一次发送)。
//eg:假设目前共享内存用了500,则len=12,而用户输入了长度为520的数据,此时count=3;则第一次要发送len=12的数据,
//第二次发送512长度数据,第三次发送8长度数据。
int index=0;//循环变量
printf("该条消息将分%d段发送!\n",count);
while(index<count){
len=MAX_SIZE-strlen(((message*)shmp)->text);//这里重新计算是因为发送了一次数据被接收后,共享内存可用容量会变化
printf("发送第%d条消息\n",index+1);
strncat(((message*)shmp)->text,msg,len);
strncpy(msg,msg+len,512);//把msg前len的数据截取弃用掉,因为发送一次后要发送的数据长度会变短len。
index++;
if(index<count){//最后一次发送之后已经不需要再阻塞自己了
sem_wait(sem_send);
}else sleep(1);
}
}else{
strncat(((message*)shmp)->text,msg,len);
sem_wait(sem_send);
}
}else{
strcat(((message*)shmp)->text,msg);
strcat(((message*)shmp)->text," ");
printf("msg:%s,len:%d\n",((message*)shmp)->text,strlen(((message*)shmp)->text));
}
strcpy(msg, ((message*)shmp)->text);
if(strcmp(msg,"over")==0){
printf("sender receive:over\n");
sem_close(sem_send);
break;
}
sem_post(sem_send);
}
sem_unlink(name);
shmctl(shmid, IPC_RMID, shmp);
printf("sender end\n");
return 0;
}
|
C
|
#include "csf.h"
#include "csfimpl.h"
/* read attribute control block (LIBRARY_INTERNAL)
*/
void CsfReadAttrBlock(
MAP *m, /* map handle */
CSF_FADDR32 pos, /* file position of block to be read */
ATTR_CNTRL_BLOCK *b) /* write-only. attribute control block read */
{
int i;
if (csf_fseek(m->fp, pos, SEEK_SET) != 0 )
return;
for(i=0; i < NR_ATTR_IN_BLOCK; i++)
{
m->read((void *)&(b->attrs[i].attrId), sizeof(UINT2),(size_t)1,m->fp);
m->read((void *)&(b->attrs[i].attrOffset), sizeof(CSF_FADDR32),(size_t)1,m->fp);
m->read((void *)&(b->attrs[i].attrSize), sizeof(UINT4),(size_t)1,m->fp);
}
m->read((void *)&(b->next), sizeof(CSF_FADDR32),(size_t)1,m->fp);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int modo = 0;
//FUNCION QUE CUENTA EL NUMERO DE ENTRADAS DE LA TABLA DE SINDROMES
int cuentaentradas(char *nombrearch) {
char actual;
int leialgo = 0;
int lineas = 0;
FILE* entrada;
entrada = fopen(nombrearch,"r");
if (entrada == NULL) {
printf("TBLSIND: ERROR: Imposible abrir fichero %s\n", nombrearch);
exit(1);
}
while ((actual = fgetc(entrada)) != EOF) {
if (actual == '0' || actual == '1' || actual == ',') leialgo = 1;
if ((actual == '\n') && (leialgo != 0)) {
lineas++;
leialgo = 0;
}
}
if (leialgo != 0) lineas++;
fclose(entrada);
return lineas;
}
//FUNCION QUE CARGA LA TABLA DE SINDROMES EN MEMORIA
void cargatabla(char **tabla, char *archivo, int numentradas, int longentrada) {
FILE *entrada;
int i, j;
char actual;
entrada = fopen(archivo, "rt");
if (entrada == NULL) {
printf("TBLSIND: ERROR: Imposible abrir fichero %s\n", archivo);
exit(-1);
}
for (i = 0; i < numentradas; i++) {
for (j = 0; j < longentrada; j++) {
actual = fgetc(entrada);
if (actual != '0' && actual != '1' && actual != ',') {
printf("TBLSIND: ERROR: Imposible abrir fichero %s\n", archivo);
exit(-1);
}
tabla[i][j] = actual;
}
actual = fgetc(entrada);
while (actual != EOF && actual != '\n') actual = fgetc(entrada);
if (actual == EOF) break;
}
fclose(entrada);
}
//CALCULO DEL FACTORIAL DE UN NUMERO
int factorial(int numero) {
int i, contador;
contador = 1;
for (i = 1; i <= numero; i++) contador *= i;
return contador;
}
//CALCULO DE UN NUMERO SOBRE OTRO
int sobre(int m, int n) {
return ((factorial(m))/(factorial(n) * factorial(m-n)));
}
//CALCULO DE L A PARTIR DE LA DISTANCIA MINIMA
int calculal(int distancia) {
if (distancia % 2 == 0) {
//ES DE LA FORMA d = 2l+2
return ((distancia - 2)/2);
}
else {
//ES DE LA FORMA d = 2l+1
return ((distancia - 1)/2);
}
}
//CALCULO DEL NUMERO DE ENTRADAS DE LA TABLA DE SINDROMES
int calculaentradas (int longitud, int l) {
int i, contador;
//SE TIENE EN CUENTA EL ERROR DE ORDEN 0: LA PALABRA CODIGO
contador = 1;
for (i = 1; i <= l; i++) contador += sobre(longitud, i);
return contador;
}
//FUNCION QUE HALLA EL SINDROME DE UN VECTOR
void calculasindrome(char **h, char *vector, char *sindrome, int longitud, int dimension) {
int i, j, contador;
for (i = 0; i < dimension; i++) {
contador = 0;
for (j = 0; j < longitud; j++) {
if (vector[j] == '1' && h[i][j] == '1') contador++;
}
if (contador % 2 == 0) sindrome[i] = '0';
else sindrome[i] = '1';
}
}
//FUNCION QUE CALCULA EL NUMERO DE UNOS DE UN VECTOR
int numunos(char* vector, int longitud) {
int i, contador;
contador = 0;
for (i = 0; i < longitud; i++) if (vector[i] == '1') contador++;
return contador;
}
//FUNCION QUE DADO UN VECTOR CALCULA EL SIGUIENTE EN ORDEN LEXICOGRAFICO
//Nota: el siguiente del vector todo unos es el vector todo ceros
void siguiente(char *vector, int longitud) {
int i, j;
if (numunos(vector, longitud) == longitud) {
for (j = 0; j < longitud; j++) vector[j] = '0';
}
else {
i = longitud - 1;
while (vector[i] != '0') {
i--;
}
vector[i] = '1';
for (j = i + 1; j < longitud; j++)if (vector[j] == '1') vector[j] = '0';
}
}
//FUNCION QUE ELABORA LA TABLA DE SINDROMES INCOMPLETA
void construyetabla(char *tabla, char **h, char *vector, char* sindrome,
int l, int longitud, int dimension) {
FILE *salida;
int i, j;
salida = fopen(tabla, "w");
if (salida == NULL) {
printf("TBLSIND: ERROR: Imposible abrir fichero %s\n", tabla);
exit(-1);
}
j = 0;
do {
if (numunos(vector, longitud) <= l) {
calculasindrome(h, vector, sindrome, longitud, dimension);
for (i = 0; i < longitud; i++) {
fputc(vector[i], salida);
if (modo != 0) printf("%c", vector[i]);
}
fputc(',', salida);
if (modo != 0) printf(",");
for (i = 0; i < dimension; i++) {
fputc(sindrome[i], salida);
if (modo != 0) printf("%c", sindrome[i]);
}
fputc('\n', salida);
if (modo != 0) printf("\n");
j++;
}
siguiente(vector, longitud);
} while (numunos(vector, longitud) != 0);
fclose(salida);
}
//LECTURA DE LA LONGITUD, LA DIMENSION Y LA DISTANCIA MINIMA
void lectura1(char *archivo, int *dimension, int *longitud, int *distancia) {
FILE *entrada;
char actual;
int linea, columna, numero;
entrada = fopen(archivo,"rt");
if (entrada == NULL) {
printf("TBLSIND: ERROR: Codigo incorrecto\n");
exit(-1);
}
linea = 1;
do {
numero = 0;
if (feof(entrada)) {
printf("TBLSIND: ERROR: Codigo incorrecto\n");
exit(-1);
}
do {
actual = fgetc(entrada);
if (feof(entrada)) {
printf("TBLSIND: ERROR: Codigo incorrecto\n");
exit(-1);
}
if ((actual < '0' || actual > '9') && (actual != '\n')) {
do {
if (feof(entrada) || ((actual != '\n') && (actual != ' ')
&& (actual != '\t'))) {
printf("TBLSIND: ERROR: Codigo incorrecto\n");
exit(-1);
}
actual = fgetc(entrada);
} while (actual != '\n');
}
else {
if (actual != '\n') {
numero *= 10;
numero += actual - '0';
}
}
} while (actual != '\n');
if ((numero == 0) || ((linea == 3) && (numero > 99))) {
printf("TBLSIND: ERROR: Codigo incorrecto\n");
exit(-1);
}
if (linea == 1) *longitud = numero;
if (linea == 2) *dimension = numero;
if (linea == 3) *distancia = numero;
linea++;
} while (linea < 4);
fclose(entrada);
}
//LECTURA DE LA MATRIZ GENERADORA DEL CODIGO
char** lectura2(char *archivo, int dimension, int longitud) {
FILE *entrada;
char actual;
int contador, linea, columna, numero;
char **matriz;
entrada = fopen(archivo,"r");
if (entrada == NULL) {
printf("TBLSIND: ERROR: Codigo incorrecto\n");
exit(-1);
}
contador = 0;
while (contador < 3) {
actual = fgetc(entrada);
if (actual == '\n') contador++;
}
columna = 0;
matriz = (char**) malloc(dimension * sizeof(char*));
if (matriz == NULL) {
printf("TBLSIND: ERROR: Falta memoria\n");
exit(-1);
}
for (linea = 0; linea < dimension; linea++) {
matriz[linea] = (char*) malloc(longitud * sizeof(char));
if (matriz[linea] == NULL) {
printf("TBLSIND: ERROR: Falta memoria\n");
exit(-1);
}
}
for (linea = 0; linea < dimension; linea++) {
for (columna = 0; columna < longitud; columna++) {
if (feof(entrada)) {
printf("TBLSIND: ERROR: Codigo incorrecto\n");
exit(-1);
}
actual = fgetc(entrada);
if (actual != '0' && actual != '1') {
printf("TBLSIND: ERROR: Codigo incorrecto\n");
exit(-1);
}
matriz[linea][columna] = actual;
}
if (linea < dimension - 1) {
while (actual != '\n') {
if (feof(entrada)) {
printf("TBLSIND: ERROR: Codigo incorrecto\n");
exit(-1);
}
actual = fgetc(entrada);
if (actual != '\n' && actual != ' ' && actual != '\t') {
printf("TBLSIND: ERROR: Codigo incorrecto\n");
exit(-1);
}
}
}
else {
while (!feof(entrada)) {
actual = fgetc(entrada);
if (!feof(entrada) && actual != '\n' && actual != ' '
&& actual != '\t') {
printf("TBLSIND: ERROR: Codigo incorrecto\n");
exit(-1);
}
}
}
}
fclose(entrada);
return matriz;
}
//FUNCION QUE DIBUJA UNA MATRIZ
void dibug(char **matriz, int dimension, int longitud) {
int linea, columna;
for (linea = 0; linea < dimension; linea++) {
for (columna = 0; columna < longitud; columna++) {
printf("%c ", matriz[linea][columna]);
}
printf("\n");
}
}
//FUNCION QUE CREA UNA MATRIZ COPIA DE OTRA RESERVANDOLE MEMORIA
char **copiag(char **matriz, int dimension, int longitud){
char **copia;
int i, j;
copia = (char**) malloc(dimension * sizeof(char*));
if (copia == NULL) {
printf("TBLSIND: ERROR: Falta memoria\n");
exit(-1);
}
for (i = 0; i < dimension; i++) {
copia[i] = (char*) malloc(longitud * sizeof(char));
if (copia[i] == NULL) {
printf("TBLSIND: ERROR: Falta memoria\n");
exit(-1);
}
}
for (i = 0; i < dimension; i++) {
for (j = 0; j < longitud; j++) {
copia[i][j] = matriz[i][j];
}
}
return copia;
}
//FUNCION QUE LE RESERVA MEMORIA A UNA MATRIZ DE CARACTERES
char** creamatriz(int dimension, int longitud){
int i;
char **h;
h = (char**) malloc(dimension * sizeof(char*));
if (h == NULL){
printf("TBLSIND: ERROR: Falta memoria\n");
exit(-1);
}
for (i = 0; i < dimension; i++) {
h[i] = (char*) malloc(longitud * sizeof(char));
if (h[i] == NULL) {
printf("TBLSIND: ERROR: Falta memoria\n");
exit(-1);
}
}
return h;
}
//FUNCION QUE INTERCAMBIA DOS FILAS
void cambiafilas(char **matriz, int fila1, int fila2, int longitud){
char actual;
int i;
for (i = 0; i < longitud; i++) {
actual = matriz[fila1][i];
matriz[fila1][i] = matriz[fila2][i];
matriz[fila2][i] = actual;
}
}
//FUNCION QUE INTERCAMBIA DOS COLUMNAS
void cambiacolumnas(char **matriz, int col1, int col2, int dimension){
char actual;
int i;
for (i = 0; i < dimension; i++) {
actual = matriz[i][col1];
matriz[i][col1] = matriz[i][col2];
matriz[i][col2] = actual;
}
}
//FUNCION QUE BUSCA LA FILA DONDE ESTARA EL PIVOTE
int buscapivote(char **matriz, int dimension, int orden) {
int i;
for (i = orden; i < dimension; i++) {
if (matriz[i][orden] == '1') return i;
}
return -1;
}
//FUNCION QUE HACE CEROS POR ENCIMA Y POR DEBAJO DEL PIVOTE
void hacerceros(char **matriz, int dimension, int longitud, int orden){
int i, j;
for (i = 0; i < orden; i++) {
for (j = longitud - 1; j >= orden; j--) {
if (matriz[i][orden] == '1') {
if (matriz[orden][j] == '1') {
if (matriz[i][j] == '1') matriz[i][j] = '0';
else matriz[i][j] = '1';
}
}
}
}
for (i = orden + 1; i < dimension; i++) {
for (j = longitud - 1; j >= orden; j--) {
if (matriz[i][orden] == '1') {
if (matriz[orden][j] == '1') {
if (matriz[i][j] == '1') matriz[i][j] = '0';
else matriz[i][j] = '1';
}
}
}
}
}
//FUNCION QUE HACE GAUSS A UNA MATRIZ
int gausear(char **matriz, int dimension, int longitud, int *cambios) {
int i, pivote, reserva, numero;
reserva = dimension;
numero = 0;
i = 0;
while (i < dimension) {
pivote = buscapivote(matriz, dimension, i);
if (pivote == -1) {
if (reserva >= longitud) {
printf("TBLSIND: ERROR: Imposible gauss\n");
exit(-1);
}
else {
cambiacolumnas(matriz, i, reserva, dimension);
cambios[numero] = i;
cambios[numero + 1] = reserva;
numero += 2;
reserva++;
continue;
}
}
cambiafilas(matriz, i, pivote, longitud);
hacerceros(matriz, dimension, longitud, i);
i++;
}
return (numero - 1);
}
//FUNCION QUE CREA H' A PARTIR DE G'
void llenah(char **h, char **matriz, int dimension, int longitud) {
int i, j, k;
k = longitud - dimension;
for (i = 0; i < k; i++) {
for (j = 0; j < dimension; j++) {
h[i][j] = matriz[j][dimension + i];
}
}
for (j = dimension; j < longitud; j++) {
for (i = 0; i < k; i++) {
if (i == j - dimension) h[i][j] = '1';
else h[i][j] = '0';
}
}
}
//FUNCION QUE TRANSFORMA H' EN H DESHACIENDO CAMBIOS EN COLUMNAS
void reformah(char **h, int dimension, int numcambios, int *cambios) {
int i;
for (i = numcambios; i >= 0; i-=2)
cambiacolumnas(h, cambios[i], cambios[i-1], dimension);
}
//FUNCION QUE COMPRUEBA SI [G] * [H]tr = 0
int comprobacion(char **g, char **h, int dimension, int longitud) {
int i, j, cont, k, estasuma;
k = longitud - dimension;
for (i = 0; i < dimension; i++) {
for (j = 0; j < k; j++) {
estasuma = 0;
for (cont = 0; cont < longitud; cont++) {
if (g[i][cont] == 1 && h[j][cont] == 1) estasuma++;
}
if ((estasuma % 2) != 0) return -1;
}
}
return 0;
}
char** calcularH(char *entrada, int dimension, int longitud, int distancia) {
int i, k, numcambios;
char **matriz, **g, **h;
int *cambios;
//LEEMOS LOS DETALLES DEL CODIGO DEL PRIMER ARCHIVO
matriz = lectura2(entrada, dimension, longitud);
k = longitud - dimension;
if (k <= 0) {
printf("TBLSIND: ERROR: Imposible encontrar matriz de paridad\n");
exit(-1);
}
//ESCRIBIMOS LOS DETALLES DEL CODIGO POR PANTALLA
if (modo == 1 || modo == 2) {
printf("Dimension del codigo: %d\n", dimension);
printf("Longitud del codigo: %d\n", longitud);
printf("Distancia minima del codigo: %d\n", distancia);
printf("La matriz generadora G es:\n");
dibug(matriz, dimension, longitud);
}
//RESERVAMOS MEMORIA PARA EL VECTOR DE CAMBIOS EN COLUMNAS
cambios = (int*) malloc(2 * k * sizeof(int));
if (cambios == NULL) {
printf("TBLSIND: ERROR: FALTA MEMORIA\n");
exit(-1);
}
//SE CREA UNA COPIA PARA OPERAR SOBRE ELLA
g = copiag(matriz, dimension, longitud);
numcambios = gausear(g, dimension, longitud, cambios);
if (modo == 1) {
printf("La matriz G' sistematica equivalente a G es:\n");
dibug(g, dimension, longitud);
}
//SE PINTAN LOS CAMBIOS REALIZADOS EN COLUMNAS
if (modo == 1) {
printf("Cambios realizados en columnas:\n");
if (numcambios == -1) printf("No hubo cambios en columnas\n");
else {
for (i = 0; i <= numcambios; i+=2) {
printf("%d <-> %d; ", cambios[i], cambios[i+1]);
}
printf("\n");
}
}
//SE RESERVA MEMORIA PARA LA MATRIZ H
h = creamatriz(k, longitud);
//SE CONSTRUYE LA MATRIZ H'
llenah(h, g, dimension, longitud);
if (modo == 1) {
printf("Obtenemos asi la siguiente matriz H'\n");
dibug(h, k, longitud);
}
//SE CONSTRUYE LA MATRIZ H
reformah(h, k, numcambios, cambios);
if (modo == 1)
printf("Ahora deshacemos los cambios en columnas para obtener H\n");
if (modo == 1 || modo == 2) {
printf("\nLa matriz control de paridad H es:\n");
dibug(h, k, longitud);
}
//COMPROBAMOS SI G*[H]tr = 0
if (comprobacion(matriz, h, dimension, longitud) == 0) {
if (modo == 1 || modo == 2) printf("[G] * [H]tr = 0\n");
}
else printf("TBLSIND: ERROR: [G] * [H]tr <> 0\n");
//SE LIBERA LA MEMORIA Y SE SALE
free(matriz);
free(g);
free(cambios);
return h;
}
void calcularT(char *entrada, char *salida){
int i, j, k, l, dimension, longitud, distancia, numentradas, longtabla;
char **h, **tabla;
char *vector, *sindrome;
//LEEMOS LOS DETALLES FUNDAMENTALES DEL CODIGO
lectura1(entrada, &dimension, &longitud, &distancia);
k = longitud - dimension;
//CALCULAMOS LA MATRIZ DE PARIDAD H
h = calcularH(entrada, dimension, longitud, distancia);
//SE CALCULA EL VALOR DE l
l = calculal(distancia);
//SE PREPARA EL VECTOR QUE CALCULARA LOS SINDROMES
vector = (char*)malloc(longitud * sizeof(char));
if (vector == NULL) {
printf("TBLSIND: ERROR: Falta memoria\n");
exit(-1);
}
for (i = 0; i < longitud; i++) vector[i] = '0';
//SE PREPARA EL ARRAY DONDE SE GUARDARA EL SINDROME
sindrome = (char*)malloc(k * sizeof(char));
if (sindrome == NULL) {
printf("TBLSIND: ERROR: Falta memoria\n");
exit(-1);
}
for (i = 0; i < k; i++) sindrome[i] = '0';
//SE CONSTRUYE LA TABLA DE SINDROMES
construyetabla(salida, h, vector, sindrome, l, longitud, k);
/* ACTIVAR ESTE CODIGO SI SE QUIERE CARGAR LA TABLA EN MEMORIA
//SE CALCULA EL NUMERO DE ENTRADAS QUE TENDRA LA TABLA
numentradas = cuentaentradas(salida);
if (modo == 1 || modo == 2)
printf("\nNumero de entradas en la tabla de sindromes: %d\n", numentradas);
//SE RESERVA MEMORIA PARA LA TABLA Y SE LLENA
longtabla = longitud + k + 1;
tabla = creamatriz(numentradas, longtabla);
cargatabla(tabla, salida, numentradas, longtabla);
//SE IMPRIME LA TABLA COMO COMPROBACION
if (modo == 2) {
printf("\n");
for (i = 0; i < numentradas; i++) {
for (j = 0; j < longtabla; j++) printf("%c", tabla[i][j]);
printf("\n");
}
printf("\nNumero de entradas en la tabla de sindromes: %d\n", numentradas);
}
FIN DE CODIGO DE CARGA DE TABLA EN MEMORIA*/
//SE LIBERA LA MEMORIA Y SE SALE
free(h);
free(tabla);
}
int main (int argc, char * argv []) {
if (argc != 3) {
printf("TBLSIND: ERROR: Numero de argumentos incorrecto\n");
exit(-1);
}
if (!strcmp(argv[1],argv[2])) {
printf("TBLSIND: ERROR: Intento de modificacion de archivo de entrada %s\n", argv[2]);
exit(-1);
}
calcularT(argv[1], argv[2]);
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
struct Node
{
struct Node *left;
struct Node *right;
struct Node *parent;
int d;
int f;
char c;
char code;
};
int suma3;
int ile(struct Node *huff[])
{
int i;
int p=0;
for(i = 0; i < 100; i++)
{
if(huff[i]->f > 0)
p++;
}
return p;
}
void dodaj(struct Node *huff[], struct Node *e, int jest)
{
int i;
if(jest==0)
{
for(i = 0; i <= 26; i++)
{
if(huff[i]->f == -1)
{
huff[i] = e;
return;
}
else if(huff[i]->c == e->c)
{
huff[i]->f++;
return;
}
}
}
else
{
for(i=27;i<100;i++)
{
if(huff[i]->f == -1)
{
huff[i]=e;
return;
}
}
}
}
void nowy(struct Node *huff[])
{
FILE *f = fopen("test.txt", "r");
char temp;
int i;
for(i=0;i<100;i++)
{
huff[i] = malloc(sizeof(struct Node));
huff[i]->c = '1';
huff[i]->f = -1;
}
do
{
temp = fgetc(f);
if(temp>32)
{
struct Node *e = malloc(sizeof(struct Node));
e->c = temp;
e->f = 1;
e->d = 0;
e->left = e->right = e->parent = NULL;
dodaj(huff, e, 0);
}
}while(temp != EOF);
}
struct Node *min(struct Node *huff[])
{
int i;
int p;
int min = INT_MAX;
for(i=0;i<100;i++)
{
if(huff[i]->d == 0)
{
if(huff[i]->f != -1)
{
if(huff[i]->f < min)
{
min=huff[i]->f;
p=i;
}
}
}
}
if(min == INT_MAX)
return huff[0];
else
{
huff[p]->d = 1;
return huff[p];
}
}
void druk(struct Node *huff[])
{
int i;
for(i=0;i<100;i++)
if(huff[i]->f > 0)
printf("%d. %c: %d\n", i, huff[i]->c, huff[i]->f);
}
struct Node *huffman(struct Node *huff[])
{
int i;
struct Node *x;
struct Node *y;
int ko = ile(huff);
for(i=27;i<27+ko-1;i++)
{
x = min(huff);
//printf("x->f = %d\t\t\t", x->f);
y = min(huff);
//printf("y->f = %d \n", y->f);
struct Node *z = malloc(sizeof(struct Node));
x->code = '0';
y->code = '1';
z->left = x;
x->parent = z;
z->right = y;
y->parent = z;
z->f = x->f + y->f;
z->c = 'z';
//printf("\t\tz->f = %d \n", z->f);
dodaj(huff,z,1);
}
return min(huff);
}
void drukD(struct Node *n, char c[], int lenc)
{
if(!(n->left))
{
printf("Kod %c: ", n->c);
int i;
int suma2=0;
for(i=0;i<lenc;i++)
{
suma2++;
printf("%c", c[i]);
}
suma2=suma2*n->f;
suma3=suma3+suma2;
printf("\n");
}
else
{
c[lenc] = '0';
drukD(n->left, c, lenc + 1);
c[lenc] = '1';
drukD(n->right, c, lenc + 1);
}
}
void zlicz(struct Node *h[])
{
int i;
int suma=0;
for(i=0;i<27;i++)
if(h[i]->f != -1)
suma = suma + h[i]->f;
suma=suma*8; //8 bitow na znak
printf("Przed: %d\nPo: %d \n", suma, suma3);
}
int main()
{
struct Node *huff[100], *tmp;
char tab[100];
suma3=0;
nowy(huff);
tmp=huffman(huff);
druk(huff);
printf("\n");
drukD(tmp, tab, 0); //koncowe
printf("\n");
zlicz(huff);
return 0;
}
|
C
|
#define NULL ((void*)0)
typedef unsigned long size_t; // Customize by platform.
typedef long intptr_t; typedef unsigned long uintptr_t;
typedef long scalar_t__; // Either arithmetic or pointer type.
/* By default, we understand bool (as a convenience). */
typedef int bool;
#define false 0
#define true 1
/* Forward declarations */
typedef struct TYPE_12__ TYPE_1__ ;
/* Type definitions */
typedef int mp_size ;
typedef scalar_t__ mp_sign ;
typedef int /*<<< orphan*/ mp_result ;
typedef TYPE_1__* mp_int ;
typedef scalar_t__ mp_digit ;
struct TYPE_12__ {int used; scalar_t__ sign; scalar_t__* digits; } ;
/* Variables and functions */
int /*<<< orphan*/ CLAMP (TYPE_1__*) ;
int MAX (int,int) ;
int /*<<< orphan*/ MP_DIGITS (TYPE_1__*) ;
int /*<<< orphan*/ MP_MEMORY ;
scalar_t__ MP_NEG ;
int /*<<< orphan*/ MP_OK ;
scalar_t__ MP_SIGN (TYPE_1__*) ;
int MP_USED (TYPE_1__*) ;
scalar_t__ MP_ZPOS ;
int /*<<< orphan*/ assert (int) ;
int /*<<< orphan*/ s_pad (TYPE_1__*,int) ;
scalar_t__ s_uadd (int /*<<< orphan*/ ,int /*<<< orphan*/ ,int /*<<< orphan*/ ,int,int) ;
int s_ucmp (TYPE_1__*,TYPE_1__*) ;
int /*<<< orphan*/ s_usub (int /*<<< orphan*/ ,int /*<<< orphan*/ ,int /*<<< orphan*/ ,int,int) ;
mp_result
mp_int_sub(mp_int a, mp_int b, mp_int c)
{
assert(a != NULL && b != NULL && c != NULL);
mp_size ua = MP_USED(a);
mp_size ub = MP_USED(b);
mp_size max = MAX(ua, ub);
if (MP_SIGN(a) != MP_SIGN(b))
{
/* Different signs -- add magnitudes and keep sign of a */
if (!s_pad(c, max))
return MP_MEMORY;
mp_digit carry = s_uadd(MP_DIGITS(a), MP_DIGITS(b), MP_DIGITS(c), ua, ub);
mp_size uc = max;
if (carry)
{
if (!s_pad(c, max + 1))
return MP_MEMORY;
c->digits[max] = carry;
++uc;
}
c->used = uc;
c->sign = a->sign;
}
else
{
/* Same signs -- subtract magnitudes */
if (!s_pad(c, max))
return MP_MEMORY;
mp_int x,
y;
mp_sign osign;
int cmp = s_ucmp(a, b);
if (cmp >= 0)
{
x = a;
y = b;
osign = MP_ZPOS;
}
else
{
x = b;
y = a;
osign = MP_NEG;
}
if (MP_SIGN(a) == MP_NEG && cmp != 0)
osign = 1 - osign;
s_usub(MP_DIGITS(x), MP_DIGITS(y), MP_DIGITS(c), MP_USED(x), MP_USED(y));
c->used = x->used;
CLAMP(c);
c->sign = osign;
}
return MP_OK;
}
|
C
|
/**
* Test that bit-sliced signature implementation works as expected.
*
* Calls all functions in bit-sliced signature API
*
* Author: Gati Aher
*/
#include "test_bitslicedsig_main.h"
extern int errno;
extern char *optarg;
extern int opterr, optind;
int main(int argc, char *argv[])
{
int opt;
char *def_prefix_path_to_corpus = "bitslicedsig/test/corpus/doc";
char *def_path_to_query = "bitslicedsig/test/query.txt";
options_t options = {0, def_prefix_path_to_corpus, NULL, 60, 3, 3};
// Initialize opterr to 0 to disable getopt from emiting a ?.
opterr = 0;
while ((opt = getopt(argc, argv, OPTSTR)) != EOF)
switch (opt)
{
case 'a':
options.prefix_path_of_corpus_to_add = optarg;
break;
case 'c':
{
if (!(options.fquery = fopen(optarg, "r")))
{
perror(ERR_FOPEN_CHECK_IN_BITSLICEDSIG);
exit(EXIT_FAILURE);
/* NOTREACHED */
}
break;
}
case 'm':
options.m = atoi(optarg);
break;
case 'k':
options.k = atoi(optarg);
break;
case 'd':
options.d = atoi(optarg);
break;
case 'v':
options.verbose = 1;
break;
case 'h':
default:
usage(basename(argv[0]));
/* NOTREACHED */
break;
}
/* default query file */
if (options.fquery == NULL)
{
if (!(options.fquery = fopen(def_path_to_query, "r")))
{
perror(ERR_FOPEN_CHECK_IN_BITSLICEDSIG);
exit(EXIT_FAILURE);
/* NOTREACHED */
}
}
if (options.verbose)
printf("Program: %s\n", DEFAULT_PROGNAME);
if (test_bitslicedsig(&options) != EXIT_SUCCESS)
{
perror(ERR_RUN_BITSLICEDSIG);
exit(EXIT_FAILURE);
/* NOTREACHED */
}
fclose(options.fquery);
return EXIT_SUCCESS;
}
void usage(char *progname)
{
fprintf(stderr, USAGE_FMT, progname ? progname : DEFAULT_PROGNAME);
exit(EXIT_FAILURE);
/* NOTREACHED */
}
|
C
|
//
// Created by Axel LE BOT on 11/12/17.
//
#include "harmonique.h"
double harmonique(int n) {
int i;
int result = 1;
for (i = 1; i <= n; i++) {
result = result + (1 / i);
}
return result;
}
double harmoniqueRecursif(int n) {
int result;
if (n == 1) result = 1;
else result = harmoniqueRecursif(n - 1) + (1 / n);
return result;
}
|
C
|
/**********************************************************/
//公司名称:
//创建时间:2012-10-16
//作者:ke
//文件名:datafifo.c
//功能描述:该文件提供一个先进先出的缓冲区
/**********************************************************/
#include "main.h"
#include "datafifo.h"
#include <stdio.h>
#ifdef SUPDYMEM
#include "malloc.h"
/*******************************************************************
函数原形: u8 init_data_fifo (DATAFIFO* pdatafifo, u32 set_size)
功能: 初始化数据fifo相关参数;
参数: set_size要申请的fifo大小
*******************************************************************/
DATAFIFO* init_data_fifo (u32 set_size)
{
DATAFIFO* pdfifo;
if ((set_size < 1) || (set_size > 4096))
{
printf ("Datafifo set_size error!!\r\n");
return NULL;
}
pdfifo = (DATAFIFO*)mymalloc(SRAMIN,sizeof(DATAFIFO));
if (pdfifo == NULL)
{
printf ("Datafifo memory error!!\r\n");
return NULL;
}
pdfifo->size = set_size;
pdfifo->front = 0;
pdfifo->rear = 0;
pdfifo->elem = (u8*)mymalloc(SRAMIN,pdfifo->size);
if (pdfifo->elem == NULL)
{
printf ("Datafifo elem memory error!!\r\n");
return NULL;
}
return pdfifo;
}
#else
/*******************************************************************
函数原形: void init_data_fifo (DATAFIFO* pdatafifo)
功能: 初始化数据fifo相关参数;
参数:
*******************************************************************/
void init_data_fifo (DATAFIFO* pdatafifo)
{
pdatafifo->size = 32;
pdatafifo->front = 0;
pdatafifo->rear = 0;
}
#endif
/*******************************************************************
函数原形: u8 insert_data_fifo (DATAFIFO* pdfifo, u8 elem)
功能: 数据fifo字节插入;
参数: pdfifo要操作fifo的地址,elem要插入的数据
返回:1表示fifo满
*******************************************************************/
u8 insert_data_fifo (DATAFIFO* pdfifo, u8 elem)
{
u32 j = 0;
j = (pdfifo->rear +1 )%pdfifo->size;
if ( pdfifo->front == j) return 1;
pdfifo->elem[pdfifo->rear] = elem;
pdfifo->rear = j; //插入
return 0;
}
/*******************************************************************
函数原形: u8 delete_data_fifo(DATAFIFO* pdfifo, u8 *pelem)
功能: 数据fifo包删除;
参数: pdfifo要操作fifo的地址,pelem从fifo中移除数据转存地址
返回:1表示fifo里面无数据
*******************************************************************/
u8 delete_data_fifo(DATAFIFO* pdfifo, u8 *pelem)
{
if ( pdfifo->front == pdfifo->rear)return 1; //数据fifo空返回错误1
*pelem = pdfifo->elem[pdfifo->front];
pdfifo->front = (pdfifo->front +1)%pdfifo->size;
return 0;
}
|
C
|
// Reveni (c) 2020 Baltasar MIT License <baltasarq@gmail.com>
#include "ctrl.h"
#include "player.h"
#include "locs.h"
#include <stddef.h>
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
void draw_presentation()
{
byte pic_data[] = {
DCMD_Circle, 50, 10, 10,
DCMD_Fill, 50, 10,
DCMD_Circle, 100, 15, 25,
DCMD_EOD
};
draw_pic( pic_data );
}
void play_intro()
{
cls();
set_default_colors();
draw_presentation();
zx_movecursorto( SCR_FIRST_LINE_TEXT, 0 );
println( "Reveni v1.0 20200411 "
"(c) 2020 Baltasar <baltasarq@gmail.com>" );
lf();
println( "La nave espacial mercante Aristarco vuelve desde "
"Proxima Centauri con un cargamento minero, "
"navegando cercana a Neptuno. "
"En la soledad del espacio, el aislado tripulante "
"duerme en el interior de su vaina de crio-letargo." );
lf();
set_highlighted_colors();
println( "De repente, un meteorito impacta en el carguero, "
"y la nave te despierta a ti, Daesder, el piloto." );
lf();
set_default_colors();
println( "No hay tiempo. Tu vaina se acopla a otra mayor y sale "
"despedida por babor, rumbo a Ceres." );
lf();
wait_for_key();
}
int main()
{
Player player;
const Order * order;
play_intro();
// Main loop
cls();
set_default_colors();
init_game( &player );
do_loc_desc( &player );
show_hud( &player );
do {
// Proc1
proc1( &player );
order = input_cmd( &player );
if ( order->cmd != NULL ) {
zx_movecursorto( SCR_FIRST_LINE_ANSWER, 0 );
set_highlighted_colors();
resp( &player, order );
// Proc2
if ( order->cmd != cmdNop ) {
player.num_turns += 1;
proc2( &player );
}
set_default_colors();
}
} while( order->cmd->cmdId != CmdEnd );
return EXIT_SUCCESS;
}
|
C
|
//#include "quantum.h"
void qubit(int param, int num);
void X(int q);
void Z(int q);
void Y(int q);
void H(int q);
void Rk(int param, int q);
void CNOT(int q1, int q2);
void CRk(int param, int q1, int q2);
void Measure(int q);
void GetQuantumMeasurementReg(int a);
void Toffoli(int q0, int q1, int q2);
void negI(int q);
int x0=0, x1=1, x2=2, ax=3;
int a=4;
int main()
{
int i = 0;
int k = 4;
// initialize X
qubit(0,x0);
qubit(0,x1);
qubit(0,x2);
// initialize ancilla for Uf
qubit(0,ax);
// initialize a
qubit(0,a);
// perform H on X
H(x0);
H(x1);
H(x2);
for(i=0; i<k; i++)
{
//Apply G
G();
}
// Measure X
Measure(x0);
Measure(x1);
Measure(x2);
int meas;
GetQuantumMeasurementReg(meas);
meas = meas && 0x07;
}
void G()
{
// Apply -HZ0HZf
// Apply -I on X
negI(x0);
negI(x1);
negI(x2);
// perform H on X
H(x0);
H(x1);
H(x2);
// Apply Z0
Z0();
// perform H on X
H(x0);
H(x1);
H(x2);
// Apply Zf
Zf();
}
void Z0()
{
// invert X
X(x0);
X(x1);
X(x2);
// apply Uf
Uf();
// invert X
X(x0);
X(x1);
X(x2);
}
void Zf()
{
// perform H on X
H(x0);
H(x1);
H(x2);
// invert a
X(a);
// apply Uf
Uf();
// perform H on X
H(x0);
H(x1);
H(x2);
// invert a
X(a);
}
void Uf()
{
Toffoli(x0,x1,ax);
Toffoli(x2,ax,a);
Toffoli(x0,x1,ax);
}
void Toffoli(int q0, int q1, int q2)
{
CRk(1,q2,q1);
H(q2);
Rk(-3,q2);
CNOT(q2,q0);
Rk(3,q2);
CNOT(q2,q1);
Rk(-3,q2);
CNOT(q2,q0);
Rk(3,q2);
H(q2);
CRk(2,q1,q0);
}
void negI(int q)
{
Z(q); X(q); Z(q); X(q);
}
void qubit(int param, int num)
{
asm("qr %0, %1" :: "r" (param), "r" (num));
asm("nop"); asm("nop"); asm("nop"); asm("nop");
}
void X(int q)
{
asm("Xr %0" :: "r" (q));
asm("nop"); asm("nop"); asm("nop"); asm("nop");
}
void Z(int q)
{
asm("Zr %0" :: "r" (q));
asm("nop"); asm("nop"); asm("nop"); asm("nop");
}
void Y(int q)
{
asm("Yr %0" :: "r" (q));
asm("nop"); asm("nop"); asm("nop"); asm("nop");
}
void H(int q)
{
asm("Hr %0" :: "r" (q));
asm("nop"); asm("nop"); asm("nop"); asm("nop");
}
void Rk(int param, int q)
{
asm("Rkr %0, %1" :: "r" (param), "r" (q));
asm("nop"); asm("nop"); asm("nop"); asm("nop");
}
void CNOT(int q1, int q2)
{
asm("CNOTr %0, %1" :: "r" (q1), "r" (q2));
asm("nop"); asm("nop"); asm("nop"); asm("nop");
}
void CRk(int param, int q1, int q2)
{
asm("CRkr %0, %1, %2" :: "r" (param), "r" (q1), "r" (q2));
asm("nop"); asm("nop"); asm("nop"); asm("nop");
}
void Measure(int q)
{
asm("MEASUREr %0" :: "r" (q));
asm("nop"); asm("nop"); asm("nop"); asm("nop");
}
void GetQuantumMeasurementReg(int a)
{
asm("lqmeas %0" : "=r" (a));
asm("nop"); asm("nop"); asm("nop"); asm("nop");
}
|
C
|
#include "triangle.h"
/*
* высчитываем периметр триугольникa
*/
Dtype triangle_perimeter(triangle t) {
segment a = {t.b, t.c};
segment b = {t.a, t.c};
segment c = {t.a, t.b};
Dtype a_length = segment_length(a);
Dtype b_length = segment_length(b);
Dtype c_length = segment_length(c);
return (a_length + b_length + c_length);
}
/*ищем вектор-нормали (векторное произведение двух векторов плоскости треугольника)*/
vector triangle_n_vector(triangle t) {
vector v1 = {t.b.x - t.a.x, t.b.y - t.a.y, t.b.z - t.a.z};
vector v2 = {t.c.x - t.a.x, t.c.y - t.a.y, t.c.z - t.a.z};
return v_mult(v1, v2);
}
/*
* высчитываем площадь триугольникa
* так как для вычисления вектора нормали нами использовалось векторное произвeдение двух сторон треугольника,
* мы можем использовать его длину для определения площади
*/
Dtype triangle_area(triangle t) {
return vector_length(triangle_n_vector(t))/2;
}
/*
* задаем плоскость,в которой находится триугольник
*/
plane triangle_plane(triangle t) {
vector n = triangle_n_vector(t);
vector d = {t.a.x, t.a.y, t.a.z};
plane res = {n.x, n.y, n.z, -v_multS(n, d)};
return res;
}
|
C
|
/* 4. Insert a value X (Take input X from user) in the array at Kth (take input K from user) index and shift all other value to right.
Name: Sanower Hossain Rabbi
ID: 1915002510
*/
#include<stdio.h>
int main()
{
int a[100] = {36,19,3,15,5,6,18,8,10,20}, max_size = 100, size = 10, i, X,K;
printf("Enter the value of X :\n");
scanf("%d",&X);
printf("Enter the value of K :\n");
scanf("%d",&K);
if(K<0 || K>=max_size)
{
printf("Array is above the limit.\n");
}
else if(K>size)
{
printf("Array is above the limit.");
}
else
{
printf("Before Operation :\n");
for(i=0;i<size;i++)
{
printf("%d ",a[i]);
}
printf("\n");
for(i=size-1;i>=K;i--)
{
a[i+1] = a[i];
}
a[K] = X;
size++;
printf("After Operation :\n");
for(i=0;i<size;i++)
{
printf("%d ",a[i]);
}
}
return 0;
}
|
C
|
/*
** EPITECH PROJECT, 2020
** concat param
** File description:
** cat param like ch star star to ch star
*/
#include <stdio.h>
#include "my.h"
#include <stdlib.h>
char *concat_params(int ac, char **av)
{
int len = 0;
char *param;
for (int i = 0; i < ac; i++)
len = len + my_strlen(av[i]);
param = malloc(sizeof(char) * (len + 1));
param = my_strcpy(param, av[0]);
for (int j = 1; j < ac; j++) {
my_strcat(param, av[j]);
}
return (param);
}
|
C
|
#include <stdlib.h>
#include <stdio.h>
#include "hashtable.h"
void hashtable_init()
{
inode_table = NULL;
attributes = NULL;
}
void hashtable_add_entry(char *link, int inode_value)
{
hashable *new_item = (hashable *)malloc(sizeof(hashable));
strcpy(new_item->key, link);
new_item->inode_value = inode_value;
HASH_ADD_STR(inode_table, key, new_item);
}
int hashable_get_entry(char *link)
{
hashable *h = (hashable *)malloc(sizeof(hashable));
HASH_FIND_STR(inode_table, link, h);
int value = -1;
if (h)
{
value = h->inode_value;
}
return value;
}
int hashtable_remove_entry(char *link)
{
hashable *h = (hashable *)malloc(sizeof(hashable));
HASH_FIND_STR(inode_table, link, h);
int value = h->inode_value;
HASH_DEL(inode_table, h);
free(h);
return value;
}
void hashtable_string_to_table(char *links) // link\nvalue\nlink\nvalue\n\0
{
char cur = '\r';
int index = 0;
char cur_word[1024];
int cur_word_size = 0;
int is_link = 1;
char *link = NULL;
while (cur != '\0')
{
cur = links[index];
if (cur == '\n')
{
if (is_link)
{
link = (char *)malloc(cur_word_size + 1);
memcpy(link, cur_word, cur_word_size);
link[cur_word_size] = '\0';
memset(cur_word, 0, cur_word_size + 1);
cur_word_size = 0;
is_link = 0;
}
else
{
cur_word[cur_word_size] = '\0';
int value = atoi(cur_word);
memset(cur_word, 0, cur_word_size + 1);
cur_word_size = 0;
is_link = 1;
hashtable_add_entry(link, value);
free(link);
}
}
else
{
cur_word[cur_word_size] = cur;
cur_word_size += 1;
}
index += 1;
}
}
unsigned long hashtable_get_attribute(char *attr_name)
{
hashable_attr *h = (hashable_attr *)malloc(sizeof(hashable_attr));
HASH_FIND_STR(attributes, attr_name, h);
unsigned long value = 0;
if (h)
{
value = h->value;
}
return value;
}
void hashtable_construct_attributes(char *attribute_data) // assumes data : a\n0\nb\n1\n
{
char *token = strtok(attribute_data, "\n");
char *name = token;
int is_token_key = 0;
while (token != NULL)
{
token = strtok(NULL, "\n");
if (is_token_key)
{
name = token;
is_token_key = 0;
}
else
{
char *value = token;
hashable_attr *new_item = (hashable_attr *)malloc(sizeof(hashable_attr));
char *key = strdup(name);
strcpy(new_item->key, key);
unsigned long value_long = strtoul(value, NULL, 10);
new_item->value = value_long;
HASH_ADD_STR(attributes, key, new_item);
is_token_key = 1;
}
}
}
void hashtable_free_attributes()
{
attributes = NULL;
}
int hashtable_count()
{
return HASH_COUNT(inode_table);
}
void hashtable_free()
{
struct hashable *current, *tmp;
HASH_ITER(hh, inode_table, current, tmp)
{
HASH_DEL(inode_table, current);
free(current);
}
}
|
C
|
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define STACKSIZE 5
#define STACKINCREMENT 10
#define OK 1
#define ERROR 0
#define OPSETSIZE 7
struct IntStack{
int *base;
int *top;
int stacksize;
};//ջûõ
int IntInitStack(IntStack &S){
S.base=(int *)malloc(STACKSIZE*sizeof(int));
if(!S.base) exit(1);
S.top=S.base;
S.stacksize=STACKSIZE;
return OK;
} //ʼջ
int IntPush(IntStack &S,int e)
{
if(S.top-S.base>=S.stacksize)
{
S.base=(int*)realloc(S.base,
(S.stacksize+STACKINCREMENT)*sizeof(int));
if(!S.base) return ERROR;
else
{
S.top=S.base+S.stacksize;
S.stacksize+=STACKINCREMENT;
}
}
*S.top++=e;
return OK;
}
int IntPop(IntStack &S,int &e)
{
if(S.top==S.base) return ERROR;
else e = * (--S.top);
return OK;
}
float IntGetTop(IntStack &S,int &e)
{
if(S.top==S.base) return ERROR;
else e=*(S.top-1);
return OK;
}
int IntStackEmpty(IntStack &S)
{
if(S.top==S.base) return OK;
else return ERROR;
return OK;
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_numbers.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: sdincbud <sdincbud@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2019/01/14 15:44:34 by sdincbud #+# #+# */
/* Updated: 2019/06/24 10:34:30 by sdincbud ### ########.fr */
/* */
/* ************************************************************************** */
#include "ft_printf.h"
int pf_atoi(const char *str)
{
int pos;
long long res;
char *nstr;
pos = 1;
res = 0;
nstr = (char*)str;
if (*nstr == '-' || *nstr == '+')
pos = (*nstr++ == '+');
while (*nstr <= '9' && *nstr >= '0')
res = res * 10 + *nstr++ - '0';
return (pos ? res : (-res));
}
void pf_putnbr(t_params *p)
{
long long int n;
(p->f & PF_ADD) ? p->f &= ~PF_SPACE : 0;
(p->f & PF_MINUS) ? p->f &= ~PF_ZERO : 0;
if (p->f & PF_LONG || p->f & PF_LONG2)
n = (p->f & PF_LONG2) ? (long long int)(va_arg(p->ap, long long))
: (long long int)(va_arg(p->ap, long));
else if (p->f & PF_SHORT || p->f & PF_SHORT2)
n = (p->f & PF_SHORT2) ? (char)(va_arg(p->ap, int))
: (short)(va_arg(p->ap, int));
else if (p->f & PF_SSIZE_T)
n = (ssize_t)va_arg(p->ap, long long int);
else if (p->f & PF_INTMAX)
n = (long long int)va_arg(p->ap, long long int);
else
n = (long long int)va_arg(p->ap, int);
(p->f & PF_ZERO && !(p->f & PF_PREC)) ? p->prec = p->minw : 0;
(p->f & PF_PREC) ? p->f &= ~PF_ZERO : 0;
pf_itoa(n, p, 0);
}
void pf_putnbr_base(t_params *p, int base)
{
unsigned long long int n;
(p->f & PF_ADD) ? p->f &= ~PF_SPACE : 0;
(p->f & PF_MINUS) ? p->f &= ~PF_ZERO : 0;
if (p->f & PF_LONG || p->f & PF_LONG2)
n = (p->f & PF_LONG2) ? va_arg(p->ap, unsigned long long int)
: (unsigned long)(va_arg(p->ap, unsigned long long int));
else if (p->f & PF_SHORT || p->f & PF_SHORT2)
n = (p->f & PF_SHORT2) ? (unsigned char)(va_arg(
p->ap, unsigned long long int))
: (unsigned short)(va_arg(p->ap, unsigned long long int));
else if (p->f & PF_SSIZE_T)
n = (size_t)va_arg(p->ap, unsigned long long int);
else if (p->f & PF_INTMAX)
n = (unsigned long long int)va_arg(p->ap, unsigned long long int);
else
n = (unsigned int)(va_arg(p->ap, unsigned long long int));
pf_itoa_base(n, p, base);
}
void pf_print_adress(t_params *p)
{
void *pointer;
pointer = va_arg(p->ap, void *);
(p->f & PF_ZERO || !pointer) ? p->minw -= 2 : 0;
p->f |= PF_POINTER;
p->f |= PF_SHARP;
pf_itoa_base((unsigned long long int)pointer, p, 16);
}
|
C
|
#pragma once
#include "vector.h"
/* Works only for C strings, uses vector.
* Strings must be allocated in heap or seg fault will occur.
*/
typedef struct {
vector storage;
} simple_map;
void simple_map_new(simple_map* m);
void simple_map_put(simple_map* m, char* key, char* value);
char* simple_map_get(simple_map* m, char* key);
void simple_map_dispose(simple_map* m);
int simple_map_size(simple_map* m);
|
C
|
#include <stdio.h>
#include <stdlib.h>
/*
ϵ
> >= < <= != ==
ж==жϲ!=
*/
/*
&&
||
int main()
{
int a=0;
int b=5;
int c=a&&b;
int d=a||b;
printf("%d\n",c);
printf("%d\n",d);
int i=0;int x=1;int y=2;int z=3;
i=x++ && ++y && z++; //Ϊ߾Ͳ
//i=x++ || ++y || z++; //룬Ϊٺ߾Ͳ
printf("x=%d\n y=%d\n z=%d\n",x,y,z);
return 0;
}
*/
/*
Ŀ
ʽ1 ? ʽ2 : ʽ3
ʽ1Ϊ棬ʽ2ΪʽӵĽ
ʽ1Ϊ٣ʽ3ΪʽӵĽ
int main()
{
int a=10;
int b=20;
int max=0;
//if(a>b)
// max=a;
//else
// max=b;
max=(a>b ? a : b);
return 0;
}
*/
/*
űʽ
ʽ1ʽ2ʽ3ʽ4
űʽöŸĶʽ
űʽִУʽĽһʽĽ
int main()
{
//α
a=get_val();
count_val(a);
while(a>0)
{
//ҵ
a=get_val();
count_val(a);
}
//дɶűʽ
while(a=get_val(),count_val(a),a>0)
{
//ҵ
}
return 0;
}
*/
//±áúͽṹԱ
/*
1.[]±ò
һ+һֵ
int main()
{
int a[10]={0};
a[4]=10; //[]a4
return 0;
}
*/
/*
2.()ò
һ߶һǺʣIJǴݸIJ
int get_max(int x,int y)
{
return x>y?x:y;
}
int main()
{
int a=10;
int b=20;
//úʱ()Ǻò
int max=get_max(a,b);//get_max,a,b
return 0;
}
*/
/*
3.һṹijԱ
. ṹ.Ա
-> ṹָ->Ա
*/
//ѧ
//һṹ
struct Stu
{
char name[20];
int age;
char id[20];
};
int main()
{
int a=10;
//ýṹʹһѧs1ʼ
struct Stu s1={"",20,"001"};
printf("%s\n",s1.name);
printf("%d\n",s1.age);
printf("%s\n",s1.id);
struct Stu* ps=&s1;
printf("%s\n",(*ps).name);
printf("%d\n",(*ps).age);
printf("%s\n",(*ps).id);
printf("%s\n",ps->name);
printf("%d\n",ps->age);
printf("%s\n",ps->id);
//ṹ.Ա
return 0;
}
|
C
|
#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
#include<string.h>
//ʹָӡ
//void Print_arr(int *str,int sz)
//{
// int *start = str;
// while (start<=(str+sz-1))
// {
// printf("%d ", *start);
// start++;
// }
//}
//int main()
//{
// int arr[10] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 };
// int sz = sizeof(arr) / sizeof(arr[0]);
// Print_arr(arr,sz);
// return 0;
//}
//дһһַݡ
//void reverse_arr(char *str,int len)
//{
// char* left = str;
// char* right = str+len - 1;
// while (left < right)
// {
// char tmp = *left;
// *left = *right;
// *right = tmp;
// left++;
// right--;
// }
//}
//int main()
//{
// char arr[30] = {0};
// gets(arr);
// int len = strlen(arr);
// reverse_arr(arr,len);
// puts(arr);
// return 0;
//}
//Sn = a + aa + aaa + aaaa + aaaaaǰ5֮ͣaһ֣
//磺2 + 22 + 222 + 2222 + 22222
//int Add(int a,int n)
//{
// int i = 0;
// int num = 0;
// int tmp = 0;//洢õÿλ
// for (i = 0; i < n; i++)
// {
// tmp = tmp * 10 + a;
// num = num + tmp;
// }
// return num;
//}
//int main()
//{
// int a = 0;
// int n = 0;
// scanf("%d%d", &a,&n);
// int num=Add(a,n);
// printf("%d\n", num);
// return 0;
//}
//
////ӡˮɻ
//#include<math.h>
//int main()
//{
// int i = 0;
// for (i = 0; i <= 100000; i++)
// {
// int count = 1;
// int tmp = i;
// int sum = 0;
// //λ
// while (tmp / 10)
// {
// count++;
// tmp /= 10;
// }
// //ÿλη
// tmp = i;
// while (tmp)
// {
// sum += pow(tmp % 10, count);
// tmp /= 10;
// }
// //ж
// if (sum == i)
// printf("%d ", i);
// }
// return 0;
//}
//ӡ
//void Print_diamond()
//{
// int i = 0;
// int line = 0;
// scanf("%d", &line);
// for (i = 0; i < line; i++)
// {
// int j = 0;
// for (j = 0; j < line - 1 - i; j++)
// {
// printf(" ");
// }
// for (j = 0; j < 2 * i + 1; j++)
// {
// printf("*");
// }
// printf("\n");
// }
// for (i = 0; i < line-1; i++)
// {
// int j = 0;
// for (j = 0; j < 1 + i; j++)
// {
// printf(" ");
// }
// for (j = 0; j < 2 * (line-1-i)-1; j++)
// {
// printf("*");
// }
// printf("\n");
// }
//}
//int main()
//{
// Print_diamond();
// return 0;
//}
int Add(int a)
{
int i = 0;
int num = 0;
for (i = 0; i < 5; i++)
{
num = num + a;
a = a * 10 + a;
}
return num;
}
int main()
{
int a = 0;
scanf("%d", &a);
int num = Add(a);
printf("%d\n", num);
return 0;
}
|
C
|
#include <assert.h>
#include <SDL/SDL.h>
#include <esic/elcd/lcd.h>
#include "emulator_system.h"
#include <Winbase.h>
extern int assign_drives(void);
static const vtable_Object s_object_vtable = {
EmulatorSystem_destructor,
NULL,
NULL,
NULL
};
static const vtable_AbstractSystem s_abstract_system_vtable = {
EmulatorSystem_waitEvent,
EmulatorSystem_pollEvent,
EmulatorSystem_update,
EmulatorSystem_delay,
EmulatorSystem_getTicks,
EmulatorSystem_getFrameBuffer
};
/* Private functions */
static void _createEvent(PPEvent event, const SDL_Event* psdl_event);
static void _initFileSystem(PAbstractSystem self);
PEmulatorSystem EmulatorSystem_constructor(PEmulatorSystem self) {
int error;
/* Calling parent constructor */
self->abstract_system.object.vtable = &s_object_vtable;
self->abstract_system.vtable = &s_abstract_system_vtable;
self->abstract_system.object.size = sizeof(EmulatorSystem);
error = SDL_Init(SDL_INIT_VIDEO);
self->screen = SDL_SetVideoMode(480, 272, 16, SDL_HWSURFACE);
/* Ensure screen's been created */
assert(self->screen != NULL);
/* Init file system? */
_initFileSystem(&self->abstract_system);
return self;
}
static void _initFileSystem(PAbstractSystem self) {
PEmulatorSystem real_self = (PEmulatorSystem)self;
FRESULT ret = FR_OK;
DSTATUS status;
FIL file;
/* Specific to Windows layer: drives assignment */
assign_drives();
/* Enforce initialization */
status = disk_initialize(1);
/* Mount the volume */
ret = f_mount(1, &real_self->fat);
/* Change current drive */
ret = f_chdrive(1);
}
void EmulatorSystem_destructor(PObject self) {
}
void EmulatorSystem_waitEvent(PAstractSystem self, PPEvent systemEvent) {
SDL_Event sdl_event;
SDL_WaitEvent(&sdl_event);
_createEvent(systemEvent, &sdl_event);
}
BOOL EmulatorSystem_pollEvent(PAstractSystem self, PPEvent systemEvent) {
SDL_Event sdl_event;
BOOL ret = FALSE;
if(SDL_PollEvent(&sdl_event)) {
_createEvent(systemEvent, &sdl_event);
if(*systemEvent != NULL) {
ret = TRUE;
}
}
return ret;
}
void EmulatorSystem_update(PAstractSystem self) {
PEmulatorSystem real_self = (PEmulatorSystem)self;
SDL_Flip(real_self->screen);
}
static void _createEvent(PPEvent systemEvent, const SDL_Event* psdl_event) {
switch(psdl_event->type) {
case SDL_KEYDOWN:
break;
case SDL_QUIT:
*systemEvent = NEW(*systemEvent, Event);
(*systemEvent)->type = EVENT_QUIT;
break;
}
}
void EmulatorSystem_delay(PAstractSystem self, DWORD milliseconds) {
SDL_Delay(milliseconds);
}
DWORD EmulatorSystem_getTicks(PAstractSystem self) {
return SDL_GetTicks();
}
void* EmulatorSystem_getFrameBuffer(PAbstractSystem self) {
return ((PEmulatorSystem)self)->screen->pixels;
}
/*---------------------------------------------------------*/
/* User Provided RTC Function for FatFs module */
/*---------------------------------------------------------*/
/* This is a real time clock service to be called from */
/* FatFs module. Any valid time must be returned even if */
/* the system does not support an RTC. */
/* This function is not required in read-only cfg. */
DWORD get_fattime (void)
{
SYSTEMTIME tm;
/* Get local time */
GetLocalTime(&tm);
/* Pack date and time into a DWORD variable */
return ((DWORD)(tm.wYear - 1980) << 25)
| ((DWORD)tm.wMonth << 21)
| ((DWORD)tm.wDay << 16)
| (WORD)(tm.wHour << 11)
| (WORD)(tm.wMinute << 5)
| (WORD)(tm.wSecond >> 1);
}
|
C
|
/**
* @file filev6.c
* @brief Implement some methods to work with filev6
*
* @author Théo Nikles & Sacha Kozma
* @date 22 mars 2017
*
*/
#include <stdio.h>
#include <inttypes.h>
#include "inode.h"
#include "sector.h"
#include "filev6.h"
#include "error.h"
#include "bmblock.h"
#include "string.h"
int filev6_writesector(struct unix_filesystem *u, struct filev6 *fv6, const char *buf, int len);
int to_indirect_sectors(struct unix_filesystem *u, struct filev6 *fv6);
int big_file_add_sector(struct unix_filesystem *u, struct filev6 *fv6, int32_t i_size, int32_t last_used_addr_index);
int filev6_open(const struct unix_filesystem *u, uint16_t inr, struct filev6 *fv6) {
M_REQUIRE_NON_NULL(u);
M_REQUIRE_NON_NULL(u->f);
M_REQUIRE_NON_NULL(fv6);
if (inr >= u->s.s_isize * INODES_PER_SECTOR) {
return ERR_BAD_PARAMETER;
}
struct inode inode;
int error = inode_read(u, inr, &inode);
M_RETURN_IF_NEGATIVE(error);
fv6->u = u;
fv6->i_number = inr;
fv6->i_node = inode;
fv6->offset = 0;
return 0;
}
int filev6_readblock(struct filev6 *fv6, void *buf) {
M_REQUIRE_NON_NULL(fv6);
M_REQUIRE_NON_NULL(buf);
M_REQUIRE_NON_NULL(fv6->u);
M_REQUIRE_NON_NULL(fv6->u->f);
if (fv6->offset >= inode_getsize(&(fv6->i_node)) || fv6->offset < 0) {
return 0;
}
int sector = inode_findsector(fv6->u, &(fv6->i_node), fv6->offset / SECTOR_SIZE);
M_RETURN_IF_NEGATIVE(sector);
int error = sector_read(fv6->u->f, (uint32_t) sector, buf);
M_RETURN_IF_NEGATIVE(error);
int byteRead = 0;
int remainingByte = inode_getsize(&(fv6->i_node)) - fv6->offset;
byteRead = remainingByte > SECTOR_SIZE ? SECTOR_SIZE : remainingByte;
fv6->offset += byteRead;
return byteRead;
}
int filev6_lseek(struct filev6 *fv6, int32_t offset) {
M_REQUIRE_NON_NULL(fv6);
if (offset < 0 || offset >= inode_getsize(&fv6->i_node)) {
return ERR_OFFSET_OUT_OF_RANGE;
}
fv6->offset = offset;
return 0;
}
int filev6_create(struct unix_filesystem *u, uint16_t mode, struct filev6 *fv6) {
M_REQUIRE_NON_NULL(u);
M_REQUIRE_NON_NULL(fv6);
memset(&fv6->i_node, 0, sizeof(struct inode));
fv6->i_node.i_mode = mode;
fv6->offset = 0;
fv6->u = u;
int error = inode_write(u, fv6->i_number, &fv6->i_node);
M_RETURN_IF_NEGATIVE(error);
return 0;
}
int filev6_writebytes(struct unix_filesystem *u, struct filev6 *fv6, const void *buf, int len) {
M_REQUIRE_NON_NULL(u);
M_REQUIRE_NON_NULL(fv6);
M_REQUIRE_NON_NULL(buf);
fv6->offset = 0;
int byte_read = 0;
const char *byte_buf = buf;
while (len > 0) {
byte_read = filev6_writesector(u, fv6, &byte_buf[fv6->offset], len);
M_RETURN_IF_NEGATIVE(byte_read);
fv6->offset += byte_read;
len -= byte_read;
}
int error = inode_write(u, fv6->i_number, &fv6->i_node);
M_RETURN_IF_NEGATIVE(error);
return 0;
}
int filev6_writesector(struct unix_filesystem *u, struct filev6 *fv6, const char *buf, int len) {
M_REQUIRE_NON_NULL(u);
M_REQUIRE_NON_NULL(fv6);
M_REQUIRE_NON_NULL(buf);
int32_t i_size = inode_getsize(&fv6->i_node);
int error = 0;
if (0 >= len) {
return 0;
} else if (i_size + len > MAX_BIG_FILE_SIZE) {
return ERR_FILE_TOO_LARGE;
} else if (i_size == ADDR_SMALL_LENGTH * SECTOR_SIZE) {
error = to_indirect_sectors(u, fv6);
M_RETURN_IF_NEGATIVE(error);
}
int is_big_file = i_size >= MAX_SMALL_FILE_SIZE ? 1 : 0;
int32_t index = i_size / SECTOR_SIZE;
uint16_t last_addr = fv6->i_node.i_addr[index];
if (is_big_file) {
index = i_size / (SECTOR_SIZE * ADDRESSES_PER_SECTOR);
uint16_t sector[ADDRESSES_PER_SECTOR];
memset(sector, 0, sizeof(sector));
error = sector_read(u->f, fv6->i_node.i_addr[index], sector);
M_RETURN_IF_NEGATIVE(error);
}
char byte[SECTOR_SIZE];
memset(byte, 0, SECTOR_SIZE);
int byte_written;
int next;
if (i_size % SECTOR_SIZE == 0) {
if (is_big_file) {
next = big_file_add_sector(u, fv6, i_size, index);
M_RETURN_IF_NEGATIVE(error);
} else {
next = bm_find_next(u->fbm);
M_RETURN_IF_NEGATIVE(error);
bm_set(u->fbm, (uint64_t) next);
fv6->i_node.i_addr[index] = (uint16_t) next;
}
byte_written = len > SECTOR_SIZE ? SECTOR_SIZE : len;
memcpy(byte, buf, (size_t) len > SECTOR_SIZE ? SECTOR_SIZE : (size_t) len);
} else {
sector_read(u->f, last_addr, byte);
int remaining_byte = SECTOR_SIZE - (i_size % SECTOR_SIZE);
remaining_byte = remaining_byte < len ? remaining_byte : len;
memcpy(&byte[i_size % SECTOR_SIZE], buf, (size_t) remaining_byte);
byte_written = remaining_byte;
next = last_addr;
}
error = sector_write(u->f, (uint32_t) next, byte);
M_RETURN_IF_NEGATIVE(error);
return (error = inode_setsize(&fv6->i_node, i_size + byte_written)) ? error : byte_written;
}
int to_indirect_sectors(struct unix_filesystem *u, struct filev6 *fv6) {
M_REQUIRE_NON_NULL(u);
M_REQUIRE_NON_NULL(fv6);
// each cell take two bytes thus we divide the size by two
uint16_t buf[ADDRESSES_PER_SECTOR];
memset(buf, 0, SECTOR_SIZE);
for (int i = 0; i < ADDR_SMALL_LENGTH; ++i) {
buf[i] = fv6->i_node.i_addr[i];
}
int next = bm_find_next(u->fbm);
M_RETURN_IF_NEGATIVE(next);
int error = sector_write(u->f, (uint32_t) next, buf);
M_RETURN_IF_NEGATIVE(error);
memset(fv6->i_node.i_addr, 0, sizeof(fv6->i_node.i_addr));
fv6->i_node.i_addr[0] = (uint16_t) next;
error = inode_write(u, fv6->i_number, &fv6->i_node);
M_RETURN_IF_NEGATIVE(error);
bm_set(u->fbm, (uint64_t) next);
return 0;
}
int big_file_add_sector(struct unix_filesystem *u, struct filev6 *fv6, int32_t i_size, int32_t last_used_addr_index) {
M_REQUIRE_NON_NULL(u);
M_REQUIRE_NON_NULL(fv6);
int error = 0;
int sector_addr = bm_find_next(u->fbm);
M_RETURN_IF_NEGATIVE(sector_addr);
bm_set(u->fbm, (uint64_t) sector_addr);
uint16_t buf[ADDRESSES_PER_SECTOR];
memset(buf, 0, sizeof(buf));
int sector_offset = i_size / SECTOR_SIZE % ADDRESSES_PER_SECTOR;
if (i_size % (ADDRESSES_PER_SECTOR * SECTOR_SIZE) == 0) {
int data_sector = bm_find_next(u->fbm);
if (data_sector < 0) {
bm_clear(u->fbm, (uint64_t) sector_addr);
return data_sector;
}
buf[0] = (uint16_t) data_sector;
fv6->i_node.i_addr[last_used_addr_index] = (uint16_t) sector_addr;
error = inode_write(u, fv6->i_number, &fv6->i_node);
if (error < 0) {
bm_clear(u->fbm, (uint64_t) sector_addr);
return error;
}
error = sector_write(u->f, (uint32_t) sector_addr, buf);
if (error < 0) {
bm_clear(u->fbm, (uint64_t) sector_addr);
return error;
}
bm_set(u->fbm, (uint64_t) data_sector);
return data_sector;
} else {
error = sector_read(u->f, fv6->i_node.i_addr[last_used_addr_index], buf);
M_RETURN_IF_NEGATIVE(error);
buf[sector_offset] = (uint16_t) sector_addr;
error = sector_write(u->f, fv6->i_node.i_addr[last_used_addr_index], buf);
M_RETURN_IF_NEGATIVE(error);
return sector_addr;
}
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_stack.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: kdaou <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2019/07/21 11:07:57 by kdaou #+# #+# */
/* Updated: 2019/11/07 19:28:21 by kdaou ### ########.fr */
/* */
/* ************************************************************************** */
#include "checker.h"
t_stack *ft_new_stack(int n)
{
t_stack *l;
if (!(l = (t_stack *)malloc(sizeof(t_stack))))
return (NULL);
l->stack = n;
l->next = NULL;
l->prev = NULL;
return (l);
}
void ft_stackadd(t_stack **stack, t_stack *new)
{
t_stack *tmp;
tmp = *stack;
if (*stack == NULL)
*stack = new;
else
{
while (tmp->next)
tmp = tmp->next;
tmp->next = new;
new->prev = tmp;
}
}
void ft_stackdel(t_stack **stack)
{
t_stack *tmp;
tmp = *stack;
while (tmp)
{
tmp = tmp->next;
free(*stack);
*stack = tmp;
}
}
t_stack *ft_stack_copy(t_stack *stack)
{
t_stack *new;
t_stack *head;
new = NULL;
head = stack;
while (head)
{
ft_stackadd(&new, ft_new_stack(head->stack));
head = head->next;
}
return (new);
}
size_t ft_stack_len(t_stack *stack)
{
size_t len;
t_stack *tmp;
tmp = stack;
len = 0;
while (tmp)
{
len++;
tmp = tmp->next;
}
return (len);
}
|
C
|
#include "string.h"
extern void serial_putc(unsigned char c);
extern unsigned char serial_getc(void);
extern void serial_puts(char *s);
char * get_string(char *s)
{
char ch;
char *buf = s;
while( (ch = serial_getc()) != '\r' ) {
if(ch == '\b') {
if(buf > s) { // the num of backspaces should not be exceeded the buffer size
buf--; // delete the character of backspace from the buffer
*buf = '\0'; // set the last pos be NULL('\0')
serial_putc('\b'); // backspace
serial_putc(' '); // clear the char to empty will move the cursor to the next position
serial_putc('\b'); // so, we need to backspace again
}
}else {
*buf++ = ch;
serial_putc(ch);
}
}
*buf = '\0';
serial_puts("\r\n");
return s;
}
int put_string(const char *s)
{
char ch;
const char *buf = s;
while( (ch = *buf++) != '\0') {
if(ch == '\n')
serial_putc('\r');
serial_putc(ch);
}
return buf - s;
}
void puthex(unsigned char ch)
{
static char hex[17] = "0123456789abcdef";
serial_putc(hex[ch]);
}
void putcharx(unsigned char ch)
{
unsigned char c0, c1;
c0 = ch & 0x0F;
c1 = (ch & 0xF0) >> 4;
puthex(c1);
puthex(c0);
}
void putx(unsigned long value)
{
unsigned char c0, c1, c2, c3;
c0 = value & 0xFF;
c1 = (value & 0xFF00) >> 8;
c2 = (value & 0xFF0000) >> 16;
c3 = (value & 0xFF000000) >> 24;
putcharx(c3);
putcharx(c2);
putcharx(c1);
putcharx(c0);
}
void put_int(int num, int base) {
char temp, buf[100];
int div = num, cnt = 0, pos, len;
static char hex[17] = "0123456789ABCDEF";
// converting int to array
do {
pos = div % base;
div = div / base;
buf[cnt++] = hex[pos];
}while(div);
buf[cnt] = '\0';
// swap
len = strlen(buf);
for(cnt = 0; cnt < len/2; ++cnt) {
temp = buf[cnt];
buf[cnt] = buf[len-cnt-1];
buf[len-cnt-1] = temp;
}
put_string(buf);
}
int atoi(char *s)
{
int i;
int c_value;
int value = 0;
char ch;
// deal with base 16
if(s[0] == '0' && (s[1] == 'x' || s[1] == 'X')) {
i = 2;
while( (ch = s[i++]) != '\0' ) {
c_value = (ch >= '0' && ch <= '9' ? ch - '0' : ch - 'a' + 10);
value = value * 16 + c_value;
}
return value;
}
// deal with base 10
i = 0;
while( (ch = s[i++]) != '\0' ) {
c_value = ch - '0';
value = value * 10 + c_value;
}
return value;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
typedef int Data;
typedef struct node
{
struct node *left;
struct node *right;
Data data;
}node;
node *create_node(Data key)
{
node *temp=(node *)malloc(sizeof(node));
temp->data=key;
temp->left=NULL;
temp->right=NULL;
return temp;
}
int searchindex(Data inorder[],Data search,Data size,Data low)
{
int i=low;
for(;i<=size;++i)
{
if(inorder[i]==search)
{
return i;
}
}
return 0;
}
node *buildtree(int l,int h,int inorder[],int postorder[],int *postindex)
{
//printf("no error");
if(l>h)
{
return NULL;
}
//printf("no error");
int search=postorder[--(*postindex)];
node *element=create_node(search);
int index=searchindex(inorder,search,h,l);
//printf("%d ",index);
element->right=buildtree(index+1,h,inorder,postorder,postindex);
element->left=buildtree(l,index-1,inorder,postorder,postindex);
return element;
}
void printinorder(node *root)
{
if(root==NULL)
return;
printinorder(root->left);
printf("%d ",root->data);
printinorder(root->right);
}
node *constructtree(Data inorder[],Data postorder[],int size)
{
//printf("no error");
return buildtree(0,7,inorder,postorder,&size);
}
int main()
{
//printf("No error");
Data inorder[8]={4,2,1,7,5,8,3,6};
Data postorder[8]={4,2,7,8,5,6,3,1};
//printf("no error");
node *root=constructtree(inorder,postorder,8);
printinorder(root);
return 0;
}
|
C
|
/* math.h -- Definitions for the math floating point package. */
#ifndef _MATH_H_
#define _MATH_H_
#define HUGE_VAL (float)3.40282346638528860e+38
/*
* set X_TLOSS = pi*2**52
*/
#define X_TLOSS 1.41484755040568800000e+16
struct complex
{
float x;
float y;
};
#define cabsf(z) (hypot ((z).x, (z).y))
/* Reentrant ANSI C functions. */
extern double atan(double);
extern double cos(double);
extern double sin(double);
extern double tan(double);
extern double tanh(double);
extern double frexp(double, int *);
extern double modf(double, double *);
extern double ceil(double);
extern double fabs(double);
extern double floor(double);
/* Non reentrant ANSI C functions. */
extern double acos(double);
extern double asin(double);
extern double atan2(double, double);
extern double cosh(double);
extern double sinh(double);
extern double exp(double);
extern double ldexp(double, int);
extern double log(double);
extern double log10(double);
extern double pow(double, double);
extern double sqrt(double);
extern double fmod(double, double);
/* Non ANSI double precision functions. */
extern double infinity(void);
extern double nan(void);
extern int isnan(double);
extern int isinf(double);
extern int finite(double);
extern double copysign(double, double);
extern int ilogb(double);
extern double asinh(double);
extern double cbrt(double);
extern double nextafter(double, double);
extern double rint(double);
extern double scalbn(double, int);
extern double log1p(double);
extern double expm1(double);
extern double acosh(double);
extern double atanh(double);
extern double remainder(double, double);
extern double gamma(double);
extern double gamma_r(double, int *);
extern double lgamma(double);
extern double lgamma_r(double, int *);
extern double erf(double);
extern double erfc(double);
extern double y0(double);
extern double y1(double);
extern double yn(int, double);
extern double j0(double);
extern double j1(double);
extern double jn(int, double);
extern double poly(double x,int n,double c[]);
#define log2(x) (log (x) / M_LOG2_E)
extern double hypot(double, double);
//extern double cabs(struct complex z);
extern double drem(double, double);
/* Single precision versions of ANSI functions. */
extern float atanf(float);
extern float cosf(float);
extern float sinf(float);
extern float tanf(float);
extern float tanhf(float);
extern float frexpf(float, int *);
extern float modff(float, float *);
extern float ceilf(float);
extern float fabsf(float);
extern float floorf(float);
extern float acosf(float);
extern float asinf(float);
extern float atan2f(float, float);
extern float coshf(float);
extern float sinhf(float);
extern float expf(float);
extern float ldexpf(float, int);
extern float logf(float);
extern float log10f(float);
extern float powf(float, float);
extern float sqrtf(float);
extern float fmodf(float, float);
/* Other single precision functions. */
extern float infinityf(void);
extern float nanf(void);
extern int isnanf(float);
extern int isinff(float);
extern int finitef(float);
extern float copysignf(float, float);
extern int ilogbf(float);
extern float asinhf(float);
extern float cbrtf(float);
extern float nextafterf(float, float);
extern float rintf(float);
extern float scalbnf(float, int);
extern float log1pf(float);
extern float expm1f(float);
extern float acoshf(float);
extern float atanhf(float);
extern float remainderf(float, float);
extern float gammaf(float);
extern float gammaf_r(float, int *);
extern float lgammaf(float);
extern float lgammaf_r(float, int *);
extern float erff(float);
extern float erfcf(float);
extern float y0f(float);
extern float y1f(float);
extern float ynf(int, float);
extern float j0f(float);
extern float j1f(float);
extern float jnf(int, float);
extern float polyf(float x,int n,float c[]);
#define log2f(x) (logf (x) / (float) M_LOG2_E)
extern float hypotf(float, float);
//extern float cabsf(struct complex z);
extern float dremf(float, float);
/* The gamma functions use a global variable, signgam. */
extern int signgam;
/* The exception structure passed to the matherr routine. */
#ifdef __cplusplus
struct __exception
#else
struct exception
#endif
{
int type;
char *name;
double arg1;
double arg2;
double retval;
int err;
};
#ifdef __cplusplus
extern int matherr(struct __exception *e);
#else
extern int matherr(struct exception *e);
#endif
/* Values for the type field of struct exception. */
#define DOMAIN 1
#define SING 2
#define OVERFLOW 3
#define UNDERFLOW 4
#define TLOSS 5
#define PLOSS 6
/* Useful constants. */
#define M_E 2.7182818284590452354
#define M_LOG2E 1.4426950408889634074
#define M_LOG10E 0.43429448190325182765
#define M_LN2 0.69314718055994530942
#define M_LN10 2.30258509299404568402
#define M_PI 3.14159265358979323846
#define M_TWOPI (M_PI * 2.0)
#define M_PI_2 1.57079632679489661923
#define M_PI_4 0.78539816339744830962
#define M_3PI_4 2.3561944901923448370E0
#define M_SQRTPI 1.77245385090551602792981
#define M_1_PI 0.31830988618379067154
#define M_2_PI 0.63661977236758134308
#define M_2_SQRTPI 1.12837916709551257390
#define M_SQRT2 1.41421356237309504880
#define M_SQRT1_2 0.70710678118654752440
#define M_LN2LO 1.9082149292705877000E-10
#define M_LN2HI 6.9314718036912381649E-1
#define M_SQRT3 1.73205080756887719000
#define M_IVLN10 0.43429448190325182765 /* 1 / log(10) */
#define M_LOG2_E 0.693147180559945309417
#define M_INVLN2 1.4426950408889633870E0 /* 1 / log(2) */
/* CYGNUS LOCAL: Default to XOPEN_MODE. */
#define _XOPEN_MODE
#define HUGE ((float)3.40282346638528860e+38)
/*
* set X_TLOSS = pi*2**52, which is possibly defined in <values.h>
* (one may replace the following line by "#include <values.h>")
*/
#define X_TLOSS 1.41484755040568800000e+16
/* Functions that are not documented, and are not in <math.h>. */
extern double logb(double);
#ifdef _SCALB_INT
extern double scalb(double, int);
#else
extern double scalb(double, double);
#endif
extern double significand(double);
/* ieee style elementary functions */
extern double __ieee754_sqrt(double);
extern double __ieee754_acos(double);
extern double __ieee754_acosh(double);
extern double __ieee754_log(double);
extern double __ieee754_atanh(double);
extern double __ieee754_asin(double);
extern double __ieee754_atan2(double,double);
extern double __ieee754_exp(double);
extern double __ieee754_cosh(double);
extern double __ieee754_fmod(double,double);
extern double __ieee754_pow(double,double);
extern double __ieee754_lgamma_r(double,int *);
extern double __ieee754_gamma_r(double,int *);
extern double __ieee754_log10(double);
extern double __ieee754_sinh(double);
extern double __ieee754_hypot(double,double);
extern double __ieee754_j0(double);
extern double __ieee754_j1(double);
extern double __ieee754_y0(double);
extern double __ieee754_y1(double);
extern double __ieee754_jn(int,double);
extern double __ieee754_yn(int,double);
extern double __ieee754_remainder(double,double);
extern long __ieee754_rem_pio2(double,double*);
#ifdef _SCALB_INT
extern double __ieee754_scalb(double,int);
#else
extern double __ieee754_scalb(double,double);
#endif
/* fdlibm kernel function */
extern double __kernel_standard(double,double,int);
extern double __kernel_sin(double,double,int);
extern double __kernel_cos(double,double);
extern double __kernel_tan(double,double,int);
//extern int __kernel_rem_pio2 __P((double*,double*,int,int,int,const __int32_t*));
extern int __kernel_rem_pio2(double*,double*,int,int,int,const int*);
/* Undocumented float functions. */
extern float logbf(float);
#ifdef _SCALB_INT
extern float scalbf(float, int);
#else
extern float scalbf(float, float);
#endif
extern float significandf(float);
/* ieee style elementary float functions */
extern float __ieee754_sqrtf(float);
extern float __ieee754_acosf(float);
extern float __ieee754_acoshf(float);
extern float __ieee754_logf(float);
extern float __ieee754_atanhf(float);
extern float __ieee754_asinf(float);
extern float __ieee754_atan2f(float,float);
extern float __ieee754_expf(float);
extern float __ieee754_coshf(float);
extern float __ieee754_fmodf(float,float);
extern float __ieee754_powf(float,float);
extern float __ieee754_lgammaf_r(float,int *);
extern float __ieee754_gammaf_r(float,int *);
extern float __ieee754_log10f(float);
extern float __ieee754_sinhf(float);
extern float __ieee754_hypotf(float,float);
extern float __ieee754_j0f(float);
extern float __ieee754_j1f(float);
extern float __ieee754_y0f(float);
extern float __ieee754_y1f(float);
extern float __ieee754_jnf(int,float);
extern float __ieee754_ynf(int,float);
extern float __ieee754_remainderf(float,float);
extern long __ieee754_rem_pio2f(float,float*);
#ifdef _SCALB_INT
extern float __ieee754_scalbf(float,int);
#else
extern float __ieee754_scalbf(float,float);
#endif
/* float versions of fdlibm kernel functions */
extern float __kernel_sinf(float,float,int);
extern float __kernel_cosf(float,float);
extern float __kernel_tanf(float,float,int);
//extern int __kernel_rem_pio2f(float*,float*,int,int,int,const __int32_t*);
extern int __kernel_rem_pio2f(float*,float*,int,int,int,const int*);
/* A union which permits us to convert between a float and a 32 bit
int. */
typedef union
{
float value;
long word;
} ieee_float_shape_type;
/* Get a 32 bit int from a float. */
#define GET_FLOAT_WORD(i,d) \
do { \
ieee_float_shape_type gf_u; \
gf_u.value = (d); \
(i) = gf_u.word; \
} while (0)
/* Set a float from a 32 bit int. */
#define SET_FLOAT_WORD(d,i) \
do { \
ieee_float_shape_type sf_u; \
sf_u.word = (i); \
(d) = sf_u.value; \
} while (0)
#endif /* _MATH_H_ */
|
C
|
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
void main(){
// char * fifo1 = "/mnt/z/DAM2/Inicio/FIFO";
mkfifo("/mnt/z/DAM2/Inicio/FIFO", 0666);
int fp;
char buffer[100];
char cadena[100];
while(1){
fp = open("FIFO1", O_RDONLY);
//wait(NULL);
//fgets(buffer,100,stdin);
read (fp, buffer, sizeof(buffer));
if(strcmp(buffer, cadena)){
printf("Mensaje recibido: %s\n", buffer);
strcpy(cadena, buffer);
}
close(fp);
}
}
|
C
|
//display leaf nodes in a level
#include<stdio.h>
#include<stdlib.h>
typedef struct Node
{
struct Node* left;
int info;
struct Node *right;
}node;
node* insert(node*,int);
void Display(node*);
void DisplayKthlevelLeaf(node*,int,int);
int Height(node *root);
void Level(node *,int );
void main()
{
printf("Enter number of elements:");
int n;
node *root=NULL;
scanf("%d",&n);
root=insert(root,n);
Display(root);
printf("Enter Kth Height:");
int value,level=Height(root);
scanf("%d",&value);
printf("\nPrint Kth Leaf:\n");
DisplayKthlevelLeaf(root,value,level);
}
node* insert(node* root,int n)
{
node *curr,*p,*q;
int i,item;
for(i=0;i<n;i++)
{
curr=(node*)malloc(sizeof(node));
if(curr==NULL)
{
printf(" MAF");
return;
}
else
{
printf(" Enter number: ");
scanf("%d",&item);
curr->info=item;
curr->left=NULL;
curr->right=NULL;
if(root==NULL)
root=curr;
else
{
p=root;
while(p!=NULL && p->info!=item)
{
q=p;
if(p->info > item)
p=p->left;
else
p=p->right;
}
if(p!=NULL)
printf(" Avoid duplicates \n ");
else
{
if(q->info > item)
q->left=curr;
else
q->right=curr;
}
}
}
}
return root;
}
void Display(node *root)
{
if(root==NULL) return ;
Display(root->left);
printf("%d ",root->info);
Display(root->right);
}
void DisplayKthlevelLeaf(node *root,int value,int level)
{
if(value<=level)
Level(root,value);
}
void Level(node *root,int level)
{
if(root==NULL)
return;
else if(level==1 && root->left==NULL && root->right==NULL)
printf("%d ",root->info);
else
Level(root->left,level-1);
Level(root->right,level-1);
}
int Height(node *root)
{
int left,right;
if(root==NULL)
return 0;
else
{
left=Height(root->left);
right=Height(root->right);
}
if(left>right) return left+1;
else return right+1;
}
|
C
|
#include <assert.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include "../src/chip8.h"
static uint16_t get_instruction_at(chip8_t* ch8, uint16_t addr) {
return (ch8->mem[addr] << 8) | ch8->mem[addr + 1];
}
static void set_instruction_at(chip8_t* ch8, uint16_t addr, uint16_t instr) {
ch8->mem[addr] = (instr >> 8);
ch8->mem[addr + 1] = instr & 0xFF;
}
static void test_loading_rom() {
chip8_t ch8;
chip8_init(&ch8);
assert(chip8_load_rom(&ch8, "./rocket.ch8"));
assert(get_instruction_at(&ch8, 0x0200) == 0x6100);
assert(get_instruction_at(&ch8, 0x0202) == 0x6200);
assert(get_instruction_at(&ch8, 0x027E) == 0x7CD6);
assert(get_instruction_at(&ch8, 0x0280) == 0x7C00);
assert(get_instruction_at(&ch8, 0x0282) == 0x0000);
}
static void test_run_instruction() {
chip8_t ch8;
// 1MMM - Go to MMM
chip8_init(&ch8);
set_instruction_at(&ch8, 0x0200, 0x1124);
chip8_run_instruction(&ch8);
assert(ch8.ip == 0x0124);
// BMMM - Go to MMM + V0
chip8_init(&ch8);
set_instruction_at(&ch8, 0x0200, 0xB124);
ch8.reg_v[0] = 6;
chip8_run_instruction(&ch8);
assert(ch8.ip == 0x012A);
// 2MMM - Do subroutine at 0MMM (must end with 00EE)
chip8_init(&ch8);
set_instruction_at(&ch8, 0x0200, 0x2124);
chip8_run_instruction(&ch8);
assert(ch8.stack[0] == 0x0202);
assert(ch8.sp == 1);
assert(ch8.ip == 0x0124);
// 00EE - Return from subroutine
chip8_init(&ch8);
set_instruction_at(&ch8, 0x0200, 0x00EE);
ch8.stack[0] = 0x0124;
ch8.sp = 1;
chip8_run_instruction(&ch8);
assert(ch8.ip == 0x0124);
// 3XKK - Skip next instruction if VX == KK
chip8_init(&ch8);
set_instruction_at(&ch8, 0x0200, 0x3524);
ch8.reg_v[5] = 0x24;
chip8_run_instruction(&ch8);
assert(ch8.ip == 0x0204);
chip8_init(&ch8);
set_instruction_at(&ch8, 0x0200, 0x3524);
ch8.reg_v[5] = 0x25;
chip8_run_instruction(&ch8);
assert(ch8.ip == 0x0202);
// 4XKK - Skip next instruction if VX != KK
chip8_init(&ch8);
set_instruction_at(&ch8, 0x0200, 0x4524);
ch8.reg_v[5] = 0x25;
chip8_run_instruction(&ch8);
assert(ch8.ip == 0x0204);
chip8_init(&ch8);
set_instruction_at(&ch8, 0x0200, 0x4524);
ch8.reg_v[5] = 0x24;
chip8_run_instruction(&ch8);
assert(ch8.ip == 0x0202);
// 5XY0 - Skip next instruction if VX == VY
chip8_init(&ch8);
set_instruction_at(&ch8, 0x0200, 0x5240);
ch8.reg_v[2] = 0x42;
ch8.reg_v[4] = 0x42;
chip8_run_instruction(&ch8);
assert(ch8.ip == 0x0204);
chip8_init(&ch8);
set_instruction_at(&ch8, 0x0200, 0x5240);
ch8.reg_v[2] = 0x42;
ch8.reg_v[4] = 0x24;
chip8_run_instruction(&ch8);
assert(ch8.ip == 0x0202);
// 9XY0 - Skip next instruction if VX != VY
chip8_init(&ch8);
set_instruction_at(&ch8, 0x0200, 0x9240);
ch8.reg_v[2] = 0x42;
ch8.reg_v[4] = 0x24;
chip8_run_instruction(&ch8);
assert(ch8.ip == 0x0204);
chip8_init(&ch8);
set_instruction_at(&ch8, 0x0200, 0x9240);
ch8.reg_v[2] = 0x42;
ch8.reg_v[4] = 0x42;
chip8_run_instruction(&ch8);
assert(ch8.ip == 0x0202);
// EX9E - Skip next instruction if VX == hexadecimal key (LSD)
chip8_init(&ch8);
set_instruction_at(&ch8, 0x0200, 0xE19E);
ch8.reg_v[1] = 4;
ch8.keypress = 4;
chip8_run_instruction(&ch8);
assert(ch8.ip == 0x0204);
chip8_init(&ch8);
set_instruction_at(&ch8, 0x0200, 0xE19E);
ch8.reg_v[1] = 0;
ch8.keypress = 1;
chip8_run_instruction(&ch8);
assert(ch8.ip == 0x0202);
chip8_init(&ch8);
set_instruction_at(&ch8, 0x0200, 0xE19E);
ch8.reg_v[1] = 0;
ch8.keypress = CHIP8_NO_KEY_PRESSED;
chip8_run_instruction(&ch8);
assert(ch8.ip == 0x0202);
// EXA1 - Skip next instruction if VX != hexadecimal key (LSD)
chip8_init(&ch8);
set_instruction_at(&ch8, 0x0200, 0xE1A1);
ch8.reg_v[1] = 4;
ch8.keypress = 4;
chip8_run_instruction(&ch8);
assert(ch8.ip == 0x0202);
chip8_init(&ch8);
set_instruction_at(&ch8, 0x0200, 0xE1A1);
ch8.reg_v[1] = 0;
ch8.keypress = 1;
chip8_run_instruction(&ch8);
assert(ch8.ip == 0x0204);
chip8_init(&ch8);
set_instruction_at(&ch8, 0x0200, 0xE1A1);
ch8.reg_v[1] = 0;
ch8.keypress = CHIP8_NO_KEY_PRESSED;
chip8_run_instruction(&ch8);
assert(ch8.ip == 0x0204);
// 6XKK - Let VX = KK
chip8_init(&ch8);
set_instruction_at(&ch8, 0x0200, 0x6A05);
chip8_run_instruction(&ch8);
assert(ch8.reg_v[10] == 0x05);
assert(ch8.ip == 0x0202);
// CXKK - Let VX = random byte (KK = mask)
chip8_init(&ch8);
set_instruction_at(&ch8, 0x0200, 0xCA1A);
chip8_run_instruction(&ch8);
assert(ch8.reg_v[10] == 0x02);
assert(ch8.ip == 0x0202);
// 7XKK - Let VX = VX + KK
chip8_init(&ch8);
set_instruction_at(&ch8, 0x0200, 0x7BCD);
ch8.reg_v[11] = 0x02;
chip8_run_instruction(&ch8);
assert(ch8.reg_v[11] == 0xCF);
assert(ch8.ip == 0x0202);
// 8XY0 - Let VX = VY
chip8_init(&ch8);
set_instruction_at(&ch8, 0x0200, 0x8120);
ch8.reg_v[1] = 0x01;
ch8.reg_v[2] = 0x02;
chip8_run_instruction(&ch8);
assert(ch8.reg_v[1] == 0x02);
assert(ch8.reg_v[2] == 0x02);
assert(ch8.ip == 0x0202);
// 8XY1 - Let VX = VX/VY (VF changed)
chip8_init(&ch8);
set_instruction_at(&ch8, 0x0200, 0x8121);
ch8.reg_v[1] = 0x04;
ch8.reg_v[2] = 0x02;
chip8_run_instruction(&ch8);
assert(ch8.reg_v[1] == 0x02);
assert(ch8.reg_v[2] == 0x02);
assert(ch8.ip == 0x0202);
chip8_init(&ch8);
set_instruction_at(&ch8, 0x0200, 0x8121);
ch8.reg_v[1] = 0x01;
ch8.reg_v[2] = 0x03;
chip8_run_instruction(&ch8);
assert(ch8.reg_v[1] == 0x00);
assert(ch8.reg_v[2] == 0x03);
assert(ch8.ip == 0x0202);
// 8XY2 - Let VX = VX & VY (VF changed)
chip8_init(&ch8);
set_instruction_at(&ch8, 0x0200, 0x8122);
ch8.reg_v[1] = 0x07;
ch8.reg_v[2] = 0x0C;
chip8_run_instruction(&ch8);
assert(ch8.reg_v[1] == 0x04);
assert(ch8.reg_v[2] == 0x0C);
assert(ch8.ip == 0x0202);
// 8XY4 - Let VX = VX + VY (VF = 0 if VX + VY <= FF,
// VF == 01 if VX + VY > FF)
chip8_init(&ch8);
set_instruction_at(&ch8, 0x0200, 0x8124);
ch8.reg_v[1] = 0x07;
ch8.reg_v[2] = 0x0C;
chip8_run_instruction(&ch8);
assert(ch8.reg_v[1] == 0x13);
assert(ch8.reg_v[2] == 0x0C);
assert(ch8.reg_v[15] == 0x00);
assert(ch8.ip == 0x0202);
chip8_init(&ch8);
set_instruction_at(&ch8, 0x0200, 0x8124);
ch8.reg_v[1] = 0xFE;
ch8.reg_v[2] = 0x01;
chip8_run_instruction(&ch8);
assert(ch8.reg_v[1] == 0xFF);
assert(ch8.reg_v[15] == 0x00);
assert(ch8.ip == 0x0202);
chip8_init(&ch8);
set_instruction_at(&ch8, 0x0200, 0x8124);
ch8.reg_v[1] = 0xFE;
ch8.reg_v[2] = 0x02;
chip8_run_instruction(&ch8);
assert(ch8.reg_v[1] == 0x00);
assert(ch8.reg_v[15] == 0x01);
assert(ch8.ip == 0x0202);
// 8XY5 - Let VX = VX - VY (VF = 00 if VX < VY,
// VF == 01 if VX >= VY)
chip8_init(&ch8);
set_instruction_at(&ch8, 0x0200, 0x8125);
ch8.reg_v[1] = 0x07;
ch8.reg_v[2] = 0x0C;
chip8_run_instruction(&ch8);
assert(ch8.reg_v[1] == 0xFB);
assert(ch8.reg_v[15] == 0x00);
assert(ch8.ip == 0x0202);
chip8_init(&ch8);
set_instruction_at(&ch8, 0x0200, 0x8125);
ch8.reg_v[1] = 0x07;
ch8.reg_v[2] = 0x07;
chip8_run_instruction(&ch8);
assert(ch8.reg_v[1] == 0x00);
assert(ch8.reg_v[15] == 0x01);
assert(ch8.ip == 0x0202);
chip8_init(&ch8);
set_instruction_at(&ch8, 0x0200, 0x8125);
ch8.reg_v[1] = 0x02;
ch8.reg_v[2] = 0x01;
chip8_run_instruction(&ch8);
assert(ch8.reg_v[1] == 0x01);
assert(ch8.reg_v[15] == 0x01);
assert(ch8.ip == 0x0202);
// FX07 - Let VX = current timer value
chip8_init(&ch8);
set_instruction_at(&ch8, 0x0200, 0xF107);
ch8.reg_v[1] = 0x12;
ch8.timer = 0x0C;
chip8_run_instruction(&ch8);
// assert(ch8.reg_v[1] == 0x0C); // TODO depends on clock speed
assert(ch8.ip == 0x0202);
// FX0A - Let VX = hexadecimal key digit (waits for key press)
chip8_init(&ch8);
set_instruction_at(&ch8, 0x0200, 0xF10A);
ch8.reg_v[1] = 0x11;
ch8.keypress = CHIP8_NO_KEY_PRESSED;
chip8_run_instruction(&ch8);
assert(ch8.reg_v[1] == 0x11);
assert(ch8.ip == 0x0200);
chip8_init(&ch8);
set_instruction_at(&ch8, 0x0200, 0xF10A);
ch8.reg_v[1] = 0x11;
ch8.keypress = 7;
chip8_run_instruction(&ch8);
assert(ch8.reg_v[1] == 0x07);
assert(ch8.ip == 0x0202);
// FX15 - Set timer = VX (01 = 1/60 second)
chip8_init(&ch8);
set_instruction_at(&ch8, 0x0200, 0xF115);
ch8.reg_v[1] = 0xF0;
chip8_run_instruction(&ch8);
assert(ch8.timer == 0xF0);
assert(ch8.ip == 0x0202);
// FX18 - Set tone duration = VX (01 = 1/60 second)
chip8_init(&ch8);
set_instruction_at(&ch8, 0x0200, 0xF118);
ch8.reg_v[1] = 0xF0;
chip8_run_instruction(&ch8);
assert(ch8.tone_clock == 0xF0);
assert(ch8.ip == 0x0202);
// AMMM - Set I = 0MMM
chip8_init(&ch8);
set_instruction_at(&ch8, 0x0200, 0xA123);
chip8_run_instruction(&ch8);
assert(ch8.reg_i == 0x0123);
assert(ch8.ip == 0x0202);
// FX1E - Let I = I + VX
chip8_init(&ch8);
set_instruction_at(&ch8, 0x0200, 0xF21E);
ch8.reg_i = 0x0422;
ch8.reg_v[2] = 0x0A;
chip8_run_instruction(&ch8);
assert(ch8.reg_i == 0x042C);
assert(ch8.ip == 0x0202);
// FX29 - Let I = 5 byte display pattern for LSD of VX
chip8_init(&ch8);
set_instruction_at(&ch8, 0x0200, 0xFA29);
ch8.reg_v[10] = 0xD2;
chip8_run_instruction(&ch8);
assert(ch8.reg_i == CHIP8_DIGITS_START_ADDRESS + (2 * 5));
assert(ch8.ip == 0x0202);
// FX33 - Let MI = 3 decimal digit equivalent of VX (I unchanged)
chip8_init(&ch8);
set_instruction_at(&ch8, 0x0200, 0xF933);
ch8.reg_i = 0x0422;
ch8.reg_v[9] = 0xA7;
chip8_run_instruction(&ch8);
assert(ch8.mem[0x0422] == 0x01);
assert(ch8.mem[0x0423] == 0x06);
assert(ch8.mem[0x0424] == 0x07);
assert(ch8.ip == 0x0202);
// FX55 - Let MI = V0 : VX (I = I + X + 1)
chip8_init(&ch8);
set_instruction_at(&ch8, 0x0200, 0xF255);
ch8.reg_i = 0x0422;
ch8.reg_v[0] = 0x01;
ch8.reg_v[1] = 0x06;
ch8.reg_v[2] = 0x07;
ch8.reg_v[3] = 0xDF;
chip8_run_instruction(&ch8);
assert(ch8.mem[0x0422] == 0x01);
assert(ch8.mem[0x0423] == 0x06);
assert(ch8.mem[0x0424] == 0x07);
assert(ch8.mem[0x0425] == 0x00);
assert(ch8.reg_i == 0x0425);
assert(ch8.ip == 0x0202);
// FX65 - Let V0 : VX = MI (I = I + X + 1)
chip8_init(&ch8);
set_instruction_at(&ch8, 0x0200, 0xF265);
ch8.reg_i = 0x0422;
ch8.mem[0x0422] = 0x01;
ch8.mem[0x0423] = 0x06;
ch8.mem[0x0424] = 0x07;
chip8_run_instruction(&ch8);
assert(ch8.reg_v[0] == 0x01);
assert(ch8.reg_v[1] == 0x06);
assert(ch8.reg_v[2] == 0x07);
assert(ch8.reg_i == 0x0425);
assert(ch8.ip == 0x0202);
// 00E0 - Erase display (all 0s)
chip8_init(&ch8);
set_instruction_at(&ch8, 0x0200, 0x00E0);
ch8.framebuffer[0x42] = 0xFF;
chip8_run_instruction(&ch8);
assert(ch8.framebuffer[0x42] == 0);
assert(ch8.ip == 0x0202);
// DXYN - Show n byte MI pattern at VX - VY coordinates.
// I unchanged. MI pattern is combined with existing display via exclusive-OR
// function. VF = 01 if a 1 in MI pattern matches 1 in existing display.
chip8_init(&ch8);
set_instruction_at(&ch8, 0x0200, 0xD121);
ch8.reg_v[1] = 0x00;
ch8.reg_v[2] = 0x00;
ch8.reg_i = 0x0300;
ch8.mem[0x300] = 0x33;
chip8_run_instruction(&ch8);
assert(ch8.framebuffer[0] == 0x33);
for (int i = 1; i < CHIP8_FRAMEBUFFER_SIZE; i++)
assert(ch8.framebuffer[i] == 0);
assert(ch8.reg_v[15] == 0);
assert(ch8.ip == 0x0202);
chip8_init(&ch8);
set_instruction_at(&ch8, 0x0200, 0xD121);
ch8.reg_v[1] = 0x01;
ch8.reg_v[2] = 0x00;
ch8.reg_i = 0x0300;
ch8.mem[0x300] = 0xA3;
chip8_run_instruction(&ch8);
assert(ch8.framebuffer[0] == 0x51);
assert(ch8.framebuffer[1] == 0x80);
for (int i = 2; i < CHIP8_FRAMEBUFFER_SIZE; i++)
assert(ch8.framebuffer[i] == 0);
assert(ch8.reg_v[15] == 0);
assert(ch8.ip == 0x0202);
chip8_init(&ch8);
set_instruction_at(&ch8, 0x0200, 0xD121);
ch8.reg_v[1] = 0x01;
ch8.reg_v[2] = 0x00;
ch8.reg_i = 0x0300;
ch8.mem[0x300] = 0xA3;
ch8.framebuffer[1] = 0x80;
chip8_run_instruction(&ch8);
assert(ch8.framebuffer[0] == 0x51);
assert(ch8.framebuffer[1] == 0x00);
for (int i = 2; i < CHIP8_FRAMEBUFFER_SIZE; i++)
assert(ch8.framebuffer[i] == 0);
assert(ch8.reg_v[15] == 1);
assert(ch8.ip == 0x0202);
chip8_init(&ch8);
set_instruction_at(&ch8, 0x0200, 0xD122);
ch8.reg_v[1] = 0x01;
ch8.reg_v[2] = 0x02;
ch8.reg_i = 0x0300;
ch8.mem[0x300] = 0x01;
ch8.mem[0x301] = 0x24;
ch8.mem[0x302] = 0xFF;
ch8.framebuffer[24] = 0x10;
chip8_run_instruction(&ch8);
assert(ch8.framebuffer[16] == 0x00);
assert(ch8.framebuffer[17] == 0x80);
assert(ch8.framebuffer[24] == 0x02);
assert(ch8.framebuffer[25] == 0x00);
assert(ch8.reg_v[15] == 1);
assert(ch8.ip == 0x0202);
// 0MMM - Do machine language subroutine at 0MMM (subroutine must end with D4
// byte)
chip8_init(&ch8);
set_instruction_at(&ch8, 0x0200, 0x00D4);
chip8_run_instruction(&ch8);
assert(ch8.stack[0] == 0x0202);
assert(ch8.sp == 1);
assert(ch8.ip == 0x00D4);
}
int main() {
test_loading_rom();
test_run_instruction();
printf("\33[1;32m🎉 Tests passed! 🎉\33[m\n");
}
|
C
|
#include <math.h>
#include <SDL2/SDL.h>
#include "../entities/entity.h"
#include "../blit/blit.h"
#define PI 3.14159265358979323846
// Move this much pixels every frame a move is detected:
#define PLAYER_MAX_SPEED 6.0f
// AFTER a movement-key is released, reduce the movement speed for
// every consecutive frame by (1.0 - this amount):
#define PLAYER_DECELERATION 0.9f
#define BULLET_LIFESPAN 300
#define MUZZLE_VEL 20
//static SDL_Window *window = NULL;
//static SDL_Renderer *renderer = NULL;
float get_angle(int x1, int y1, int x2, int y2)
{
float radius_schouder = 310.0;
return (float)(360 + atan2(y2 - y1, x2 - x1) * (180.0 / PI) - (float)asin((radius_schouder / sqrt(pow(x1 - x2, 2) + pow(y1 - y2, 2)))*PI/180) * PI*180);
}
void process_keugel(player *player, keugel *keugel, float angle, mouse *mouse, flash *flash)
{
int radius = 140;
if (player->shooting)
{
keugel->life = BULLET_LIFESPAN;
keugel->speed_x = MUZZLE_VEL*(float)(cos(angle*PI/180));
keugel->speed_y = MUZZLE_VEL*(float)(sin(angle*PI/180));
angle += 23;
keugel->x = (int)(player->x + radius * cos(angle*PI/180));
keugel->y = (int)(player->y + radius * sin(angle*PI/180));
keugel->angle = (float)(360 + atan2(mouse->y - keugel->y, mouse->x - keugel->x) * (180/PI)); //blorp is magic, blorp can shoot tha bullets backwards
if (player->state == IDLE)
{
player->state = SHOOTING;
}
if (player->state == WALKING)
{
player->state = SHOOTING_WHILE_WALKING;
}
printf("graden: %.2f \n", keugel->angle);
flash->x = keugel->x;
flash->y = keugel->y;
flash->angle = keugel->angle;
flash->a = 255;
}
if (keugel->life)
{
keugel->x += (int)keugel->speed_x;
keugel->y += (int)keugel->speed_y;
}
if (keugel->life == 0)
{
player->state = IDLE;
}
//printf("keugel bevindt zich op \n x: %d \n y: %d \n De snelheid is: \n x: %.2f \n y: %.2f \n", keugel->x, keugel->y, keugel->speed_x, keugel->speed_y);
}
void update_player(player *tha_playa, mouse *tha_mouse, keugel *keugel, flash *flash)
{
if (tha_playa->up)
{
tha_playa->y -= (int)PLAYER_MAX_SPEED;
if (keugel->life >= (BULLET_LIFESPAN - 3))
{
flash->y -= (int)PLAYER_MAX_SPEED;
}
//keugel->y += (int)PLAYER_MAX_SPEED;
}
if (tha_playa->down)
{
tha_playa->y += (int)PLAYER_MAX_SPEED;
if (keugel->life >= (BULLET_LIFESPAN - 3))
{
flash->y += (int)PLAYER_MAX_SPEED;
}
//keugel->y -= (int)PLAYER_MAX_SPEED;
}
if (tha_playa->left)
{
tha_playa->x -= (int)PLAYER_MAX_SPEED;
if (keugel->life >= (BULLET_LIFESPAN - 3))
{
flash->x -= (int)PLAYER_MAX_SPEED;
}
//keugel->x += (int)PLAYER_MAX_SPEED;
}
if (tha_playa->right)
{
tha_playa->x += (int)PLAYER_MAX_SPEED;
if (keugel->life >= (BULLET_LIFESPAN - 3))
{
flash->x += (int)PLAYER_MAX_SPEED;
}
//keugel->x -= (int)PLAYER_MAX_SPEED;
}
tha_playa->angle = get_angle(tha_playa->x, tha_playa->y,
tha_mouse->x, tha_mouse->y);
process_keugel(tha_playa, keugel, tha_playa->angle, tha_mouse, flash);
}
void draw_flash(flash *flash, SDL_Renderer *renderer)
{
SDL_SetRenderDrawBlendMode(renderer, SDL_BLENDMODE_ADD);
SDL_SetTextureBlendMode(flash->txtr_flash, SDL_BLENDMODE_ADD);
SDL_SetTextureColorMod(flash->txtr_flash, flash->r, flash->g, flash->b);
SDL_SetTextureAlphaMod(flash->txtr_flash, flash->a);
blit_angled(flash->txtr_flash, flash->x, flash->y, flash->angle, -5, renderer);
SDL_SetRenderDrawBlendMode(renderer, SDL_BLENDMODE_NONE);
}
void get_angle_enemy(player *player, enemy *enemy)
{
enemy->angle = (float)(360 + atan2(player->y - enemy->y, player->x - enemy->x) * (180.0 / PI));
}
|
C
|
#include "network.h"
/********************************* TCP socket function ***************************************************/
int createTCP_server(char *addrstr, char *port)
{
int sockfd, len; // listen on sock_fd, new connection on new_fd
struct addrinfo hints, *servinfo, *p;
struct sockaddr_in local;
void *ptr;
char hostname[1024];
int rv, yes = 1;
hostname[1023] = '\0';
gethostname(hostname, 1023);
memset(&hints, 0, sizeof hints);
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
hints.ai_flags = AI_PASSIVE; // use my IP
if ((rv = getaddrinfo(hostname, NULL, &hints, &servinfo)) != 0)
{
fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(rv));
return 0;
}
// loop through all the results and bind to the first we can
for (p = servinfo; p != NULL; p = p->ai_next)
{
if ((sockfd = socket(p->ai_family, p->ai_socktype, p->ai_protocol))
== -1)
{
perror("server: socket");
continue;
}
if (setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(int))
== -1)
{
perror("setsockopt: reuse address");
continue;
}
if (bind(sockfd, p->ai_addr, p->ai_addrlen) == -1)
{
close(sockfd);
perror("server: bind");
continue;
}
break;
}
if (p == NULL)
{
fprintf(stderr, "server: failed to bind\n");
return 0;
}
/*get ip address and port*/
//get ip
switch (p->ai_family)
{
case AF_INET:
ptr = &((struct sockaddr_in *) p->ai_addr)->sin_addr;
break;
case AF_INET6:
ptr = &((struct sockaddr_in6 *) p->ai_addr)->sin6_addr;
break;
}
inet_ntop(p->ai_family, ptr, addrstr, 100);
// get port number
len = sizeof(local);
getsockname(sockfd, (struct sockaddr *) &local, &len);
sprintf(port, "%d", htons(local.sin_port));
/* done get ip and port */
freeaddrinfo(servinfo); // all done with this structure
if (listen(sockfd, 10) == -1)
{
perror("listen");
return 0;
}
return sockfd;
}
int connectTCP_server(char *Server_ip, char *port)
{
int sockfd, status;
struct addrinfo hints, *servinfo, *p;
memset(&hints, 0, sizeof hints);
hints.ai_family = AF_INET;
hints.ai_socktype = SOCK_STREAM;
if ((status = getaddrinfo(Server_ip, port, &hints, &servinfo)) != 0)
{
fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(status));
return 0;
}
// loop through all the results and connect to the first we can
for (p = servinfo; p != NULL; p = p->ai_next)
{
if ((sockfd = socket(p->ai_family, p->ai_socktype, p->ai_protocol))
== -1)
{
perror("client: socket");
continue;
}
if (connect(sockfd, p->ai_addr, p->ai_addrlen) == -1)
{
close(sockfd);
perror("TCP client: connect");
continue;
}
else
{
printf("Connecting.... Master... ");
}
break;
}
if (p == NULL)
{
fprintf(stderr, "client: failed to connect\n");
return 0;
}
freeaddrinfo(servinfo); // all done with this structure
return sockfd;
}
void *get_in_addr(struct sockaddr *sa)
{
if (sa->sa_family == AF_INET)
{
return &(((struct sockaddr_in*) sa)->sin_addr);
}
return &(((struct sockaddr_in6*) sa)->sin6_addr);
}
/********************************* END TCP socket function ************************************************/
|
C
|
#include <stdio.h>
#include "counter.h"
#include "defaults.h"
#include "llist.h"
typedef struct __myargs_t {
int loops;
counter_t *counter;
int mytid;
llist_t *list;
int key;
} myargs_t;
void *build_list(void *arg) {
myargs_t *a = (myargs_t *) arg;
// do some work
int i, key;
for (i = 0; i < a->loops; i++) {
key = counter_inc_and_get(a->counter);
ll_insert(a->list, key);
}
return NULL;
}
void *search_list(void *arg) {
myargs_t *a = (myargs_t *) arg;
int rc;
double total;
struct timeval start, end;
rc = gettimeofday(&start, NULL); // set timer
if (rc != 0) {
fprintf(stderr, "gettimeofday error\n");
return (void *) EXIT_FAILURE;
}
int index = ll_indexof(a->list, a->key); // find the key
rc = gettimeofday(&end, NULL); // end timer
if (rc != 0) {
fprintf(stderr, "gettimeofday error\n");
return (void *) EXIT_FAILURE;
}
total = (end.tv_sec - start.tv_sec) * MILLION + (end.tv_usec - start.tv_usec);
printf("%d was found at index %d by thread #%d in %f seconds\n",
a->key, index, a->mytid, total / MILLION);
return NULL;
}
int main(int argc, char *argv[])
{
if (argc <= 2) {
fprintf(stderr, "Usage: ./main <int: loops> <int: threads>\n");
return 1;
}
int loops, num_threads;
loops = strtol(argv[1], NULL, BASE_10);
num_threads = strtol(argv[2], NULL, BASE_10);
if (!loops || !num_threads) {
fprintf(stderr, "Usage: ./main <int: loops> <int: threads>\n");
return 1;
}
if (num_threads > MAX_THREADS) {
fprintf(stderr, "Let's not go crazy. Choose %d or less threads.\n", MAX_THREADS);
return 1;
}
pthread_t threads[num_threads];
int i;
counter_t counter;
counter_init(&counter);
llist_t list;
ll_init(&list);
myargs_t args[num_threads];
// build the list
for (i = 0; i < num_threads; i++) {
args[i].mytid = i; // thread ID
args[i].loops = loops;
args[i].counter = &counter;
args[i].list = &list;
Pthread_create(&threads[i], NULL, build_list, &args[i]);
}
for (i = 0; i < num_threads; i++) {
Pthread_join(threads[i], NULL);
}
// Send the threads to find keys in the list
for (i = 0; i < num_threads; i++) {
args[i].key = (num_threads * loops) / (num_threads - i);
Pthread_create(&threads[i], NULL, search_list, &args[i]);
}
for (--i; i >= 0; i--) {
Pthread_join(threads[i], NULL);
}
int exp = num_threads * loops;
printf("Summary\n\tExpected nodes:\t%d\n\tActual nodes:\t%d\n\n",
exp, ll_length(&list));
printf("\nThe counter got to %d (expected %d)\n",
counter_get(&counter), exp);
printf("The index of %d is %d (expected -1)\n\n",
exp + 1, ll_indexof(&list, exp + 1));
return 0;
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* int_convertion.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: aminadzh <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2018/02/18 14:44:52 by aminadzh #+# #+# */
/* Updated: 2018/02/18 14:44:54 by aminadzh ### ########.fr */
/* */
/* ************************************************************************** */
#include "ft_printf.h"
static intmax_t get_i_argument(s_pecs specs, va_list args)
{
intmax_t nbr;
nbr = va_arg(args, intmax_t);
if (specs.e_size == hh)
nbr = (char)nbr;
else if (specs.e_size == h)
nbr = (short int)nbr;
else if (specs.e_size == l)
nbr = (long int)nbr;
else if (specs.e_size == ll)
nbr = (long long int)nbr;
else if (specs.e_size == j)
nbr = (intmax_t)nbr;
else if (specs.e_size == z)
nbr = (size_t)nbr;
else
nbr = (int)nbr;
return (nbr);
}
ssize_t int_left_conversion(char *val, s_pecs specs, size_t len, intmax_t nbr)
{
ssize_t ret;
ret = 0;
if (specs.spbar && !specs.sign)
ret += write(1, " ", 1);
if (specs.sign)
ret += write(1, &specs.sign, 1);
if (MIN_INT(nbr))
{
ret += write(1, val, 1);
val++;
}
while (specs.prec > 0)
{
ret += write(1, "0", 1);
specs.prec--;
}
ret += write(1, val, (int)len);
specs.width -= ret;
if (specs.sign && !specs.zero)
specs.width += 1;
while (specs.width > 0)
{
ret += write(1, " ", 1);
specs.width--;
}
return (ret);
}
ssize_t int_right_conversion(char *val, s_pecs specs, size_t len, intmax_t nbr)
{
ssize_t ret;
ret = 0;
if (specs.spbar && !specs.sign)
ret += write(1, " ", 1);
if (specs.sign && specs.zero)
ret += write(1, &specs.sign, 1);
if (val && *val == '-')
{
ret += write(1, val, 1);
val++;
}
specs.width -= ret;
while (specs.width > 0)
{
if (specs.zero)
ret += write(1, "0", 1);
else
ret += write(1, " ", 1);
specs.width--;
}
if (specs.sign && !specs.zero)
ret += write(1, &specs.sign, 1);
while (specs.prec > 0)
{
ret += write(1, "0", 1);
specs.prec--;
}
ret += write(1, val, (int)len);
return (ret);
}
ssize_t int_conversion(s_pecs specs, va_list args)
{
char *val;
intmax_t nbr;
ssize_t ret;
size_t len;
nbr = get_i_argument(specs, args);
if (nbr < 0 && !(MIN_INT(nbr)))
{
specs.sign = 45;
nbr *= -1;
}
val = ft_intmaxtoa(nbr);
if (nbr == 0 && (specs.dot && specs.prec == 0))
ft_strdel(&val);
len = ft_strlen(val);
if (MIN_INT(nbr))
len -= 1;
if (specs.sign && !specs.zero)
specs.width -= 1;
if ((specs.prec - (int)len) >= 0 )
specs.prec -= (int)len;
else
specs.prec = 0;
if (!specs.minus)
specs.width = specs.width - specs.prec - len;
if (specs.minus)
ret = int_left_conversion(val, specs, len, nbr);
else
ret = int_right_conversion(val, specs, len, nbr);
if (nbr != 0)
free(val);
return (ret);
}
|
C
|
#include <stdio.h>
// Estruturas de Repetição for, while, do while;
int main(){
int x = 0, soma = 0;
printf("\n");
for(int i = 0;i<=10; i++){ //mais usado quando se sabe o numero de repeticoes Ex: Vetores e Matrizes
printf("Digite o %d numero\n", i);
scanf("%d", &x);
soma += x;
}
printf("O valor de x eh %d\n", x);
printf("A soma de todos os valores eh %d\n\n", soma);
x = 0;
while(x != 10){ //mais usado quando o numero de repeticoes eh incerto
x++;
printf("O valor atual de x eh %d\n", x);
}
printf("\n");
x = 0;
int tentativas = 0;
do{
printf("Adivinhe o numero entre 1 e 10!\n");
scanf("%d", &x);
tentativas++;
if(x == 5){
printf("5! Voce achou o numero :]\n");
printf("seu numero de tentativas foi %d\n", tentativas);
}
}while(x != 5);
return 0;
}
|
C
|
#include <bicpl.h>
int main(
int argc,
char *argv[] )
{
FILE *file;
STRING filename1, filename2, output_filename;
int i, n, n_objects1, n_objects2, n_normals1, n_normals2;
Vector *normals1, *normals2;
Point p1, p2;
Real dist;
File_formats format;
object_struct **object_list1, **object_list2;
initialize_argument_processing( argc, argv );
if( !get_string_argument( "", &filename1 ) ||
!get_string_argument( "", &filename2 ) ||
!get_string_argument( "", &output_filename ) )
{
print_error( "Usage: %s input1.obj input2.obj output.txt\n",
argv[0] );
return( 1 );
}
if( input_graphics_file( filename1, &format, &n_objects1, &object_list1 )
!= OK )
return( 1 );
if( input_graphics_file( filename2, &format, &n_objects2, &object_list2 )
!= OK )
return( 1 );
if( n_objects1 != n_objects2 )
{
print_error( "Number of objects do not match.\n" );
return( 1 );
}
if( open_file( output_filename, WRITE_FILE, ASCII_FORMAT, &file ) != OK )
return( 1 );
n_normals1 = get_object_normals( object_list1[0], &normals1 );
n_normals2 = get_object_normals( object_list2[0], &normals2 );
if( n_normals1 != n_normals2 )
{
print_error( "Number of normals do not match.\n" );
return( 1 );
}
for_less( n, 0, n_normals1 )
{
dist = distance_between_points( (Point*)&normals1[n], (Point*)&normals2[n] );
(void) output_real( file, dist );
(void) output_newline( file );
}
(void) close_file( file );
delete_object_list( n_objects1, object_list1 );
delete_object_list( n_objects2, object_list2 );
return( 0 );
}
|
C
|
#include <stdio.h>
/* month_name: return name of n-th month */
char *month_name(int n)
{
static char *name[] =
{
"Illegal month",
"January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December"
};
return (n < 1 || n > 12) ? name[0] : name[n];
/* The characters of each string are placed 'somewhere', each string is assigned
* a corresponding position in the array.
* The pointer is all that matters here, stored in name[i].
*
* Since the size of the array is not specified, the compiler counts the initializers
* and fills in the correct number.
*/
}
int main()
{
char *res;
res = month_name(13);
printf("res = >%s<\n\n", res);
res = month_name(1);
printf("res = >%s<\n\n", res);
res = month_name(9);
printf("res = >%s<\n\n", res);
return 0;
}
|
C
|
// Various utility functions for finding the shortest path.
// Copyright 2009-2010 David Lawrence Miller
#include <math.h>
#include <stdlib.h>
#include <stdio.h>
#include "utils.h"
#include "wood.h"
extern double eps;
int do_int(double p1[2], double p2[2], double p3[2], double p4[2], double ip[2]){
double s,t, s1_x, s1_y, s2_x, s2_y, denom;
s1_x = p2[0] - p1[0];
s1_y = p2[1] - p1[1];
s2_x = p4[0] - p3[0];
s2_y = p4[1] - p3[1];
denom= (-s2_x*s1_y + s1_x*s2_y);
if(fabs(denom)<eps){
return 0;
}
s = (-s1_y * (p1[0] - p3[0]) + s1_x * (p1[1] - p3[1])) /denom;
t = ( s2_x * (p1[1] - p3[1]) - s2_y * (p1[0] - p3[0])) /denom;
if (s >= 0 && s <= 1 && t >= 0 && t <= 1){
// Collision detected
ip[0] = p1[0] + (t * s1_x);
ip[1] = p1[1] + (t * s1_y);
return 1;
}
return 0; // No collision
}
void do_intersect(double p1[], double p2[], int nbnd, double **bnd,int *bndint){
int i;
double p3[2],p4[2],ip[2];
// iterate over sides (ie vertex pairs)
// NB the last vertex should be the first
for(i=0;i<(nbnd-1);i++){
bndint[i]=0;
p3[0]=bnd[i][0];
p4[0]=bnd[i+1][0];
p3[1]=bnd[i][1];
p4[1]=bnd[i+1][1];
// are the lines identical?
if(( (fabs(p1[0]-p3[0]) < eps) &
(fabs(p2[0]-p4[0]) < eps) &
(fabs(p1[1]-p3[1]) < eps) &
(fabs(p2[1]-p4[1]) < eps) ) |
( (fabs(p2[0]-p3[0]) < eps) &
(fabs(p1[0]-p4[0]) < eps) &
(fabs(p2[1]-p3[1]) < eps) &
(fabs(p1[1]-p4[1]) < eps) )) bndint[i]=1;
if(bndint[i]==0){
bndint[i]=do_int(p1,p2,p3,p4,ip);
}
} // end bnd loop
}
void sp_do_intersect(double p1[], double p2[], int nbnd, double **bnd,int *bndint)
{
/*
* p1,p2 points we wish to test
* nbnd length of boundary
* bnd boundary
* bndint boundary intersections (length nbnd-1)
*/
int i;
double p3[2], p4[2];
double ip[2];
// iterate over sides (ie vertex pairs)
// NB the last vertex should be the first
for(i=0;i<(nbnd-1);i++){
// set true to begin with
bndint[i]=1;
p3[0]=bnd[i][0];
p4[0]=bnd[i+1][0];
p3[1]=bnd[i][1];
p4[1]=bnd[i+1][1];
// are they just the same line?
if(( (fabs(p1[0]-p3[0]) < eps) &
(fabs(p2[0]-p4[0]) < eps) &
(fabs(p1[1]-p3[1]) < eps) &
(fabs(p2[1]-p4[1]) < eps) ) |
( (fabs(p2[0]-p3[0]) < eps) &
(fabs(p1[0]-p4[0]) < eps) &
(fabs(p2[1]-p3[1]) < eps) &
(fabs(p1[1]-p4[1]) < eps) )) bndint[i]=0;
if(bndint[i]==1){
bndint[i]=do_int(p1,p2,p3,p4,ip);
}
if(bndint[i]==1){
// is the intersection point just one of the ends?
if(( (fabs(ip[0]-p1[0]) <eps) & (fabs(ip[1]-p1[1]) <eps) ) |
( (fabs(ip[0]-p2[0]) <eps) & (fabs(ip[1]-p2[1]) <eps) )){
bndint[i]=0;
}
if(( (fabs(ip[0]-p3[0]) <eps) & (fabs(ip[1]-p3[1]) <eps) ) |
( (fabs(ip[0]-p4[0]) <eps) & (fabs(ip[1]-p4[1]) <eps) )){
bndint[i]=0;
}
}
}
}
/* determine whether the line between two points is facing inside or outside */
int facing(double p1[], double p2[] , int nbnd, double **bnd){
/*
Args:
p1, p2 the points
nbnd length of the boundary
bnd the boundary
Return:
1 if facing inside, 0 otherwise
*/
int ret=0;
int in[2]={0,0};
int i, err, intind[2], tmpinout;
double ip1[2],ip2[2], xmp[2], ymp[2];
double *bx, *by, xmin, ymin, mina[2], break_code;
err=first_ips(p1, p2, nbnd, bnd, ip1, ip2, intind);
// if there are no errors, go ahead
if(err==0){
// are the midpoints inside?
// call the in_out routine from soap.
//void in_out(double *bx, double *by, double *break_code, double *x,double *y,int *in, int *nb, int *n)
bx=(double*)malloc(sizeof(double)*nbnd);
by=(double*)malloc(sizeof(double)*nbnd);
for(i=0; i<nbnd; i++){
bx[i]=bx[0]+i;
by[i]=by[0]+i;
bx[i]=bnd[i][0];
by[i]=bnd[i][1];
}
// find the "midpoints" between p1, p2 their first intersections
// store in x and y blocks
xmp[0]=(ip1[0]+eps*p1[0])/(1+eps);
xmp[1]=(ip2[0]+eps*p2[0])/(1+eps);
ymp[0]=(ip1[1]+eps*p1[1])/(1+eps);
ymp[1]=(ip2[1]+eps*p2[1])/(1+eps);
// to handle holes, multiple boundaries
// ignore this at the moment
xmin=minarr(nbnd,bx);
ymin=minarr(nbnd,by);
mina[0] = xmin; mina[1]=ymin;
break_code=minarr(2,mina)-1;
tmpinout=2;
in_out(bx, by, &break_code, xmp, ymp, in, &nbnd, &tmpinout);
// if they are both inside, return true (ie they face inside)
// or if one is on boundary and the other is inside...
if((in[0] && in[1])){
ret=1;
}
// free some memory
free(bx);free(by);
}
return ret;
}
int intpoint(double p1[], double p2[],double edge[][2], double ip[]){
double p3[2],p4[2];
int ret;
double arr[2];
p3[0]=edge[0][0];
p3[1]=edge[0][1];
p4[0]=edge[1][0];
p4[1]=edge[1][1];
// if they overlap
if(( (fabs(p1[0]-p3[0]) < eps) &
(fabs(p2[0]-p4[0]) < eps) &
(fabs(p1[1]-p3[1]) < eps) &
(fabs(p2[1]-p4[1]) < eps) ) |
( (fabs(p2[0]-p3[0]) < eps) &
(fabs(p1[0]-p4[0]) < eps) &
(fabs(p2[1]-p3[1]) < eps) &
(fabs(p1[1]-p4[1]) < eps) )){
arr[0]=p1[0];
arr[1]=p2[0];
ip[0]=minarr(2,arr);
arr[0]=p1[1];
arr[1]=p2[1];
ip[1]=minarr(2,arr);
return 0;
}
// ends
if(online(p1,edge)){
ip[0]=p1[0];
ip[1]=p1[1];
return 0;
}
if(online(p2,edge)){
ip[0]=p2[0];
ip[1]=p2[1];
return 0;
}
//// HACK
double pedge[2][2];
pedge[0][0]=p1[0];
pedge[0][1]=p1[1];
pedge[1][0]=p2[0];
pedge[1][1]=p2[1];
if(online(p3,pedge)){
ip[0]=p3[0];
ip[1]=p3[1];
return 0;
}
if(online(p4,pedge)){
ip[0]=p4[0];
ip[1]=p4[1];
return 0;
}
ret = do_int(p1,p2,p3,p4,ip);
return !ret;
}
int online(double p1[],double thisline[][2]){
double m,c;
double xarr[2], yarr[2];
// check this first before messing around with arrays
// is p1 an endpoint of thisline?
if( ((fabs(p1[0]-thisline[0][0])<eps) & (fabs(p1[1]-thisline[0][1])<eps)) |
((fabs(p1[0]-thisline[1][0])<eps) & (fabs(p1[1]-thisline[1][1])<eps))){
return 1;
}
// now create the bounding box
xarr[0]=thisline[0][0];
xarr[1]=thisline[1][0];
yarr[0]=thisline[0][1];
yarr[1]=thisline[1][1];
twosort(xarr);
twosort(yarr); // make xarr, yarr small->large
// check p1 is inside the bounding box
if( ((p1[0]>xarr[1]) | (p1[0]<xarr[0])) |
((p1[1]>yarr[1]) | (p1[1]<yarr[0])) ){
return 0;
}
// calculate gradient of the line
/* first handle if it's a vertical/horizontal line */
if(fabs(thisline[1][0]-thisline[0][0])<eps){
/* vertical line */
if((fabs(thisline[1][0]-p1[0])<eps) &&
((p1[1]<yarr[1])&&(p1[1]>yarr[0]))){
return 1;
}else{
return 0;
}
}else if(fabs(thisline[1][1]-thisline[0][1])<eps){
/* horizontal line */
if((fabs(thisline[1][1]-p1[1])<eps) &&
((p1[0]<xarr[1])&&(p1[0]>xarr[0]))){
return 1;
}else{
return 0;
}
}else{
m = (thisline[1][1]-thisline[0][1])/(thisline[1][0]-thisline[0][0]);
}
// calculate intercept
c = thisline[1][1]-m*thisline[1][0];
// is p1 a solution?
if(fabs(p1[1]-(m*p1[0]+c))<eps){
return 1;
}else{
return 0;
}
}
// calculate the length of the hull by iterating over
// the list object
double hull_length(node** hull) {
double hullen=0;
node* current = *hull;
if(current ==NULL){
return(1e10);
}
while (current->next != NULL) {
hullen=hullen+hypot((current->next->data[0] - current->data[0]),
(current->next->data[1] - current->data[1]));
current = current->next;
}
return(hullen);
}
// find the first intersection points of p1 and p2
// with bnd
int first_ips(double p1[], double p2[], int nbnd, double **bnd,
double ip1[], double ip2[],int intind[]){
/* Args:
* p1, p2 the points
* nbnd length of boundary
* bnd the boundary
* ip1, ip2 intersection points (returned)
* intbnd boundary intersection indices (index of bnd where
* the intersections occur.)
*
* Return:
* error code, 0=okay
* Uses:
* crapfind, qsort
*/
int i, firstel, lastel, *retint, *bbindex;
int lbbindex=0;
double thisedge[2][2], **ips, *dists, *sortdists;
double ip[2];
int j=0;
// error code 0= okay
int err=0;
// setup retint
retint=(int*)malloc(sizeof(int)*(nbnd-1));
for(i=0; i<(nbnd-1); i++){
retint[i]=retint[0]+i;
}
// do_intersect returns a string of T/F values
// find intersections
// this is what is used in the R code.
do_intersect(p1,p2,nbnd,bnd,retint);
double *bx, *by, break_code,xmin,ymin,mina[2],xmp[1],ymp[1];
int in[1], tmpinout;
bx=(double*)malloc(sizeof(double)*nbnd);
by=(double*)malloc(sizeof(double)*nbnd);
for(i=0; i<nbnd; i++){
bx[i]=bx[0]+i;
by[i]=by[0]+i;
bx[i]=bnd[i][0];
by[i]=bnd[i][1];
}
// to handle holes, multiple boundaries
// ignore this at the moment
xmin=minarr(nbnd,bx);
ymin=minarr(nbnd,by);
mina[0] = xmin; mina[1]=ymin;
break_code=minarr(2,mina)-1;
tmpinout=1;
// this loop handles when the intersection point is a vertex, in this
// case we need to make sure that the intersection is the first
// between p1 and p2. So if p1 starts on a vertex but then the line p1p2
// cuts the line again to go outside then ignore it. If p1 is a vertex
// and immediately after we are outside, keep it.
for(i=0;i<(nbnd-1);i++){
if( (fabs(p1[0]-bnd[i][0])<eps) && (fabs(p1[1]-bnd[i][1])<eps)){
xmp[0]=(p1[0]+eps*p2[0])/(1+eps);
ymp[0]=(p1[1]+eps*p2[1])/(1+eps);
in_out(bx, by, &break_code, xmp, ymp, in, &nbnd, &tmpinout);
retint[i]=!in[0];
if(i==0){
retint[nbnd-2]=!in[0];
}else{
retint[i-1]=!in[0];
}
}
if( (fabs(p2[0]-bnd[i][0])<eps) && (fabs(p2[1]-bnd[i][1])<eps)){
xmp[0]=(eps*p1[0]+p2[0])/(1+eps);
ymp[0]=(eps*p1[1]+p2[1])/(1+eps);
in_out(bx, by, &break_code, xmp, ymp, in, &nbnd, &tmpinout);
retint[i]=!in[0];
if(i==0){
retint[nbnd-2]=!in[0];
}else{
retint[i-1]=!in[0];
}
}
}
// length of the bounding box index
lbbindex=iarrsum((nbnd-1),retint);
// if lbbindex < 2 increment err
if(lbbindex>1){
// setup bbindex, dists, sortdists
bbindex=(int*)malloc(sizeof(int)*lbbindex);
dists=(double*)malloc(sizeof(double)*lbbindex);
sortdists=(double*)malloc(sizeof(double)*lbbindex);
for(i=0; i<lbbindex; i++){
bbindex[i]=bbindex[0]+i;
dists[i]=dists[0]+i;
sortdists[i]=sortdists[0]+i;
}
// find intersections & sort by distance
// populate bbindex
for(i=0;i<(nbnd-1);i++){
if(retint[i]){
bbindex[j]=i;
j++;
}
}
// hold distances and intersection points temporarily
ips=(double**)malloc(sizeof(double*)*lbbindex);
ips[0]=(double*)malloc(sizeof(double)*lbbindex*2);
for(i=0; i<lbbindex; i++){
ips[i]=ips[0]+i*2;
}
for(i=0;i<lbbindex;i++){
// get current index
j=bbindex[i];
thisedge[0][0]=bnd[j][0];
thisedge[1][0]=bnd[j+1][0];
thisedge[0][1]=bnd[j][1];
thisedge[1][1]=bnd[j+1][1];
// calculate and save the intersection
err=intpoint(p1,p2,thisedge,ip);
ips[i][0]=ip[0];
ips[i][1]=ip[1];
// find the distance and save
dists[i]=hypot(p1[0]-ip[0],p1[1]-ip[1]);
// also copy for sorting
sortdists[i]=dists[i];
}
// prototype from stdlib.h
// void qsort (void *array, size_t count, size_t size, comparison_fn_t compare)
// The qsort function sorts the array array.
// The array contains count elements, each of which is of size size.
// The compare function is used to perform the comparison on the array elements.
qsort(sortdists,lbbindex,sizeof(double),compare_doubles);
// find first intersection between p1 and bnd
// p1.int<-pe(ips,order(dists)[1])
firstel = crapfind(lbbindex,dists,sortdists[0]);
ip1[0]=ips[firstel][0];
ip1[1]=ips[firstel][1];
// find first intersection between p2 and bnd
// p2.int<-pe(ips,order(dists,decreasing=TRUE)[1])
lastel = crapfind(lbbindex,dists,sortdists[(lbbindex-1)]);
ip2[0]=ips[lastel][0];
ip2[1]=ips[lastel][1];
// calculate intind
intind[0]=bbindex[firstel];
intind[1]=bbindex[lastel];
free(ips[0]);
free(ips);
free(bbindex);
free(dists);
free(sortdists);
}else{
// let the Robot warn us...
//printf("### DANGER, WILL ROBINSON! lbbindex=%d (< 2)\n",lbbindex);
err++;
} // end of lbbindex<2 check
free(retint);
free(bx);
free(by);
return(err);
}
int find_end(double *p1, double xdel, double ydel, double xstart, double ystart, int ngrid, int *refio){
int i,j, iret=-1, jret=-1;
double dist=1e10,xg,yg;
// find the index for nearest bottom left corner
// of the grid to p1
i=abs((int)floor((p1[0]-xstart)/xdel));
j=abs((int)floor((p1[1]-ystart)/ydel));
// and the location of that point
xg=xdel*i;
yg=ydel*j;
// distance from p1 to that corner
// are any of the other corners closer?
if((refio[j*ngrid+i]==1) & (hypot(p1[0]-xg,p1[1]-yg)<dist)){
iret=i;jret=j;
dist=hypot(p1[0]-xg,p1[1]-yg);
}
if((refio[j*ngrid+i+1]==1) & (hypot(p1[0]-xg-xdel,p1[1]-yg)<dist)){
iret=i+1;
dist=hypot(p1[0]-xg-xdel,p1[1]-yg);
}
if((refio[(j+1)*ngrid+i]==1) & (hypot(p1[0]-xg,p1[1]-yg-ydel)<dist)){
jret=j+1;
dist=hypot(p1[0]-xg,p1[1]-yg-ydel);
}
if((refio[(j+1)*ngrid+i+1]==1) & (hypot(p1[0]-xg-xdel,p1[1]-yg-ydel)<dist)){
iret=i+1; j=jret+1;
dist=hypot(p1[0]-xg-xdel,p1[1]-yg-ydel);
}
// if at least one of the above has been activated
if((iret!=-1) && (jret!=-1)){
return(jret*ngrid+iret);
}else{
return(-1);
}
}
// check to see if any of the ends can be used as a start path
void append_check(double p1[2], double p2[2], double xstart, double ystart, double xdel, double ydel, int ngrid, int *refio, int nbnd, double **bnd, int app[2]){
/*
* Args:
* paths array of paths
* nref grid size
* point point to investigate
* app[2] entry 0: match_ends output
* entry 1: path number
*
*/
int end1,end2;
// find the indices of the grid points nearest to p1 and p2
end1=find_end(p1, xdel, ydel, xstart, ystart, ngrid, refio);
end2=find_end(p2, xdel, ydel, xstart, ystart, ngrid, refio);
// check for errors then return the index
if( (end1==-1) | (end2==-1)){
app[0]=0;
}else if(end2<end1){
app[0]=2;
app[1]=1/2*(end1-1)+end2;
}else{
app[0]=1;
app[1]=1/2*(end2-1)+end1;
}
}
// create a reference grid
void create_refpaths(double *xref, double *yref, int nref, double xdel, double ydel, double xstart,double ystart, int *refio, int ngrid, int nbnd, node*** savedpaths, double **bnd){
double p1[2],p2[2],*pl;
int i,j,k,m,err,npl,p,q,savesize;
// we know what's inside, find only those paths that are
// non-Euclidean within the domain, check that first...
npl=(nref*(nref-1))/2;
pl=(double*)malloc(sizeof(double)*(npl));
for(i=0; i<npl; i++){
pl[i]=pl[0]+i;
}
get_euc_path(xref,yref,nbnd,bnd,nref,pl,0);
// malloc the memory for the saved paths
//savesize=ngrid*ngrid;
savesize=ngrid*ngrid*(ngrid*ngrid/2-1);
*savedpaths=(node**)malloc(sizeof(node*)*savesize);
for(i=0; i<savesize; i++){
(*savedpaths)[i]=(*savedpaths[0])+i*sizeof(node*);
(*savedpaths)[i]=NULL;
}
k=0;
// calculate some paths
// first loop over all the grid points
for(i=0;i<nref;i++){
for(j=(i+1);j<nref;j++){
// are the points inside ?
p=abs((int)floor((xref[i]-xstart)/xdel))+
abs((int)floor((yref[i]-ystart)/ydel))*ngrid;
q=abs((int)floor((xref[j]-xstart)/xdel))+
abs((int)floor((yref[j]-ystart)/ydel))*ngrid;
if(pl[k]==-1){
p1[0]=xref[i]; p1[1]=yref[i]; // set p1
p2[0]=xref[j]; p2[1]=yref[j]; // set p2
// find the index to put the path in
if(p<q){
m=1/2*(p-1)*p +q;
}else{
m=1/2*(q-1)*q +p;
}
err=make_bnd_path(p1,p2,nbnd,bnd,&((*savedpaths)[m]),0);
err=iter_path(&((*savedpaths)[m]),nbnd,bnd);
k++;
}
}
}
free(pl);
}
/*
* Linked list code here
* mostly modified from http://cslibrary.stanford.edu/
*/
/*
* Takes a list and a data value.
* Creates a new link with the given data and pushes
* it onto the front of the list.
* The list is not passed in by its head pointer.
* Instead the list is passed in as a "reference" pointer
* to the head pointer -- this allows us
* to modify the caller's memory.
*/
// free a linked list's memory
void FreeList(node** headRef) {
node* current = *headRef;// deref headRef to get the real head
node* next=NULL;
while (current != NULL) {
next = current->next; // note the next pointer
free(current); // delete the node
current = next; // advance to the next node
}
*headRef = NULL; // Again, deref headRef to affect the real head back
// in the caller.
}
// Push something to the start of a list
void Push(node** headRef, double data[]) {
node* newNode = malloc(sizeof(node));
newNode->data[0] = data[0];
newNode->data[1] = data[1];
// next element of the new node will be the head
newNode->next = *headRef; // The '*' to dereferences back
// to the real head
if(newNode->next !=NULL){
newNode->next->prev = newNode;
}
// previous element of new node will be NULL
newNode->prev = NULL;
*headRef = newNode;
}
// Append something to the end of a list
// AppendNode with Push()
void AppendNode(node** headRef, double data[]) {
node* current = *headRef;
// special case for the empty list
if (current == NULL) {
Push(headRef, data);
}else{
// Locate the last node
while (current->next != NULL) {
current = current->next;
}
// Build the node after the last node
Push(&(current->next), data);
current->next->prev=current;
}
}
// Variant of CopyList() that uses Push()
// copy from head to newList
void CopyList(node* head, node** newList)
{
node* current = head; // used to iterate over the original list
// Re-write of this code with AppendNode.
while (current != NULL) {
AppendNode(newList, current->data);
current = current->next;
}
}
/*
* Given a linked list head pointer, compute
* and return the number of nodes in the list.
*/
int Length(node** head) {
node* current = *head;
int count = 0;
while (current != NULL) {
count++;
current = current->next;
}
return count;
}
/*
* Debug printer for paths
*/
void PrintPath(node** mypath) {
node* current=*mypath;
printf("plot(bnd,type=\"l\",asp=1)\n");
printf("path<-list(x=c(),y=c())\n");
while(current!=NULL){
printf("path$x<-c(path$x,%f)\n",current->data[0]);
printf("path$y<-c(path$y,%f)\n",current->data[1]);
current=current->next;
}
printf("lines(path,lwd=2,col=\"red\")\n");
printf("scan()\n");
printf("#******* END ********** \n");
}
// Delete the first and last entries of a list
void DelTopBot(node** head){
node* current = *head; // used to iterate over the original list
node* top = NULL;
// miss out the first node
current=current->next;
free(current->prev);
current->prev=NULL;
top=current;
// skip to the end
while (current->next->next != NULL) {
current = current->next;
}
free(current->next);
current->next=NULL;
*head=top;
}
void ReverseList(node** head){
node* current=*head;
node* revlist = NULL;
while(current!=NULL){
Push(&revlist,current->data);
current=current->next;
}
FreeList(head);
*head=revlist;
}
////////////////////////////
/*
* Real utility stuff below here!
*/
void twosort(double *twovec){
// sort two vectors small->large
double tmp;
if(twovec[1]<twovec[0]){
tmp=twovec[0];
twovec[0]=twovec[1];
twovec[1]=tmp;
}
}
// integer version of the above
void itwosort(int *twovec){
// see if two vectors are small->large
int tmp;
if(twovec[1]<twovec[0]){
tmp=twovec[0];
twovec[0]=twovec[1];
twovec[1]=tmp;
}
}
// find the maximum in an array
double maxarr(int narr, double *arr)
{
int i;
double maxval=arr[0];
for(i=1;i<narr;i++){
if(arr[i]>maxval){
maxval=arr[i];
}
}
return maxval;
}
// find the minimum in an array
double minarr(int narr, double *arr)
{
int i;
double minval=arr[0];
for(i=1;i<narr;i++){
if(arr[i]<minval){
minval=arr[i];
}
}
return minval;
}
// sum an array of integers
int iarrsum(int narr, int *arr){
int i;
int val=0;
for(i=0;i<narr;i++){
val=val+arr[i];
}
return val;
}
/* for use with qsort from stdlib.h
* see:
* http://www.gnu.org/software/libc/manual/html_mono/libc.html#Search_002fSort-Example
*/
int compare_doubles (const void *a, const void *b){
const double *da = (const double *) a;
const double *db = (const double *) b;
return (*da > *db) - (*da < *db);
}
// my very own, very poor find
// returns the first element of the array to match the value
int crapfind(int narr, double *arr, double val){
int i, index=-1;
for(i=0;i<narr;i++){
if(arr[i]==val){
index=i;
break;
}
}
return index;
}
// routine to set the global eps value
void set_epsilon(int n, double *x, double *y){
// x and y should be the boundary points
// since all points are inside there...
double machEps = 1e-10;
double maxx,minx,maxy,miny, dxy[2];
// first find the max and min of x and y
maxx=maxarr(n,x);
maxy=maxarr(n,y);
minx=minarr(n,x);
miny=minarr(n,y);
// determine the machine epsilon
// from http://en.wikipedia.org/wiki/Machine_epsilon#Approximation_using_C
do{
machEps /= 2.0;
// If next epsilon yields 1, then break, because current
// epsilon is the machine epsilon.
}while ((double)(1.0 + (machEps/2.0)) != 1.0);
dxy[0]=(maxx-minx)*machEps;
dxy[1]=(maxy-miny)*machEps;
// now calculate our epsilon
eps=maxarr(2,dxy)*10;
// printf("eps=%.30f\n",eps);
}
|
C
|
/* https://leetcode.com/problems/insert-into-a-binary-search-tree/ */
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
struct TreeNode* Newnode(int key)
{
struct TreeNode* newnode = (struct TreeNode*)malloc(sizeof(struct TreeNode));
newnode->left = newnode->right = NULL;
newnode->val = key;
return newnode;
}
struct TreeNode* insertIntoBST(struct TreeNode* root, int val)
{
if(!root) return Newnode(val);
struct TreeNode* current = root;
while(current)
{
if(val > current->val)
{
if(current->right) current = current->right;
else
{
current->right = Newnode(val);
break;
}
}
else
{
if(current->left) current = current->left;
else
{
current->left = Newnode(val);
break;
}
}
}
return root;
}
|
C
|
/* 2014, Copyright Intel & Jose Bollo <jose.bollo@open.eurogiciel.org>, license MIT */
/*
* A smack_coda is a smack code of access and it is an integer data.
*/
typedef int smack_coda;
/*
* Constants used for smack_coda
*/
enum {
smack_coda_lock = 1, /* lock permission bit */
smack_coda_transmute = 2, /* transmute permission bit */
smack_coda_append = 4, /* append permission bit */
smack_coda_execute = 8, /* execute permission bit */
smack_coda_write = 16, /* write permission bit */
smack_coda_read = 32, /* read permission bit */
smack_coda_bits_count = 6, /* count of bits for permissions */
smack_coda_bits_mask = 0x3f /* mask of the permissions bits */
};
/*
* Is 'text' a valid string for coda?
*
* Requires: text != NULL
*
* Returns: 1 if yes, the access is valid, 0 otherwise.
*/
int smack_coda_string_is_valid(const char *text);
/*
* Is 'coda' valid?
*
* Returns: 1 if yes, the access is valid, 0 otherwise.
*/
int smack_coda_is_valid(smack_coda coda);
/*
* Returns the normalized coda value for the string 'text'.
*
* Requires: text != NULL
* && smack_coda_string_is_valid(text)
*/
smack_coda smack_coda_from_string(const char *text);
/*
* Returns the length (excluding the terminating null) of the
* string representation of 'coda'.
*
* Requires: smack_coda_is_valid(coda)
*/
int smack_coda_string_length(smack_coda coda);
/*
* Put the string representation of 'coda' in 'text' without the terminating
* null. The available 'length' of 'text' must be enough to handle the string
* representation.
*
* CAUTION: NOT NUL IS APPENED
*
* Requires: smack_coda_is_valid(coda)
* && text != NULL
* && length >= smack_coda_string_length(coda)
*
* Returns the count of characters written to 'text'.
*/
int smack_coda_to_string(smack_coda coda, char *text, int length);
/*
* Returns the complement of 'coda'.
*
* Requires: smack_coda_is_valid(coda)
*/
smack_coda smack_coda_complement(smack_coda coda);
/*
* Returns 'coda' modified such that the lock permission
* is added if 'coda' has the write permission.
*
* Requires: smack_coda_is_valid(coda)
*
* Returns the normalized coda.
*/
smack_coda smack_coda_normalize(smack_coda coda);
/*
* Check if the 'coda' is normalized what means that the write
* implies the lock permission.
*
* Requires: smack_coda_is_valid(coda)
*
* Returns 1 if 'coda' is normal or 0 otherwise.
*/
int smack_coda_is_normal(smack_coda coda);
|
C
|
#include<stdio.h>
main ()
{
int a[]={1,1,2,2,4};
int i=0;
a[i++]=a[++i]+i;
printf("%d %d %d %d %d\n",a[0],a[1],a[2],a[3],a[4]);
}
|
C
|
#include<stdio.h>
int main(){
int soma=0;
int n;
do{
printf("Digite um numero (menor que 0 para parar):");
scanf("%d",&n);
if(n>0)soma=soma+n;
}while(n>0);
printf("Total: %d", soma);
return 0;
}
|
C
|
/* Min Su Kim, mskim3494 */
/* CMSC 152, Winter 2015 */
/* HOMEWORK 5 */
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include <string.h>
#include "ss.h"
#include "htbl.h"
#include "sll.h"
#include "matrix.h"
void evidence_ss()
{
printf(" === testing squeezed strings ===\n");
char test_s[]="hello world";
printf(" --- testing capitalize/normalize --- \n");
printf("expecting H, %c\n", capitalize('h'));
printf("expecting 8, %d\n", normalize('h'));
squeezed_string* test_ss= squeeze(test_s);
printf(" --- testing ss_read ---\n");
show_ss(test_ss);
printf("expecting H, %c\n", ss_read(test_ss,0));
printf("expecting E, %c\n", ss_read(test_ss,5));
printf("expecting ' ', '%c'\n",ss_read(test_ss,6));
char* test=unsqueeze(test_ss);
printf("expecting HELLO WORLD, %s\n", test);
char garbage[]="@$%%&hi my friend$#%";
squeezed_string* test_garbage= squeeze(garbage);
char* unsqueezed_garbage= unsqueeze(test_garbage);
printf("expecting no garbage -> %s\n\n", unsqueezed_garbage);
free_squeezed_string(test_ss);
free_squeezed_string(test_garbage);
free(test);
free(unsqueezed_garbage);
}
void evidence_resize()
{
printf(" === testing is_prime===\n");
printf("expecting 1, %d\n", is_prime(7));
printf("expecting 0, %d\n", is_prime(224));
printf("expecting 1, %d\n\n", is_prime(223));
printf(" === testing ht_resize ===\n");
int i;
htbl* t=ht_new((&good_hash), 3);
sll* tmp=malloc(sizeof(sll));
tmp->s="i'm hungry";
tmp->next=NULL;
char* s[]= {"hi","I","love","bannanas","so","much","I","am","so","hungry"};
for(i=0;i<10;i++){
tmp=sll_cons(s[i],tmp);
} ht_ins_list(tmp, t);
ht_show(t);
printf("original load factor %f\n", ht_load_factor(t));
printf("original number of buckets %d\n\n", t->n_buckets);
printf("resize\n");
ht_resize(&t);
printf("new load factor %f\n", ht_load_factor(t));
printf("new number of buckets %d\n", t->n_buckets);
ht_show(t);
ht_free(t);
printf("\n");
}
void evidence_matrix()
{
printf(" === testing matrix ===\n");
matrix* test1= matrix_zero(2,2);
matrix* test2= matrix_zero(2,2);
printf("expecting 0.0, %f\n",test1->entries[1][1]);
matrix_write(test1, 0,0, 1);
matrix_write(test1, 0,1, 3);
matrix_write(test1, 1,0, 5);
matrix_write(test1, 1,1, 1.5);
printf("expecting 1.5, %f\n",test1->entries[1][1]);
matrix_write(test2,0,0,2);
matrix_write(test2,0,1,4.0);
matrix_write(test2,1,0,2.0);
matrix_write(test2,1,1,2.0);
printf("expecting 4, %f\n",test2->entries[0][1]);
matrix* test3= matrix_add(test1,test2);
printf("testing add, expecting 3 7 7 3.5\n");
matrix_show(test3);
matrix* test4= matrix_mult(test1, test2);
printf("testing mult, expecting 8 10 13 23\n");
matrix_show(test4);
matrix_free(test1);
matrix_free(test2);
matrix_free(test3);
matrix_free(test4);
}
int main()
{
evidence_resize();
evidence_matrix();
evidence_ss();
return 0;
}
|
C
|
#define NULL ((void*)0)
typedef unsigned long size_t; // Customize by platform.
typedef long intptr_t; typedef unsigned long uintptr_t;
typedef long scalar_t__; // Either arithmetic or pointer type.
/* By default, we understand bool (as a convenience). */
typedef int bool;
#define false 0
#define true 1
/* Forward declarations */
typedef struct TYPE_6__ TYPE_1__ ;
/* Type definitions */
struct TYPE_6__ {float y; float x; float z; } ;
typedef TYPE_1__ vertex_t ;
typedef int GLfloat ;
/* Variables and functions */
int /*<<< orphan*/ CrossProduct (TYPE_1__,TYPE_1__,TYPE_1__,TYPE_1__*) ;
scalar_t__ DRAW_BALL_SHADOW ;
int /*<<< orphan*/ GL_POLYGON ;
float RADIUS ;
int STEP_LATITUDE ;
int /*<<< orphan*/ STEP_LONGITUDE ;
scalar_t__ cos_deg (int) ;
scalar_t__ drawBallHow ;
int /*<<< orphan*/ glBegin (int /*<<< orphan*/ ) ;
int /*<<< orphan*/ glColor3f (float,float,float) ;
int /*<<< orphan*/ glEnd () ;
int /*<<< orphan*/ glNormal3f (float,float,float) ;
int /*<<< orphan*/ glVertex3f (float,float,float) ;
int /*<<< orphan*/ printf (char*,...) ;
scalar_t__ sin_deg (int) ;
void DrawBoingBallBand( GLfloat long_lo,
GLfloat long_hi )
{
vertex_t vert_ne; /* "ne" means south-east, so on */
vertex_t vert_nw;
vertex_t vert_sw;
vertex_t vert_se;
vertex_t vert_norm;
GLfloat lat_deg;
static int colorToggle = 0;
/*
* Iterate through the points of a latitude circle.
* A latitude circle is a 2D set of X,Z points.
*/
for ( lat_deg = 0;
lat_deg <= (360 - STEP_LATITUDE);
lat_deg += STEP_LATITUDE )
{
/*
* Color this polygon with red or white.
*/
if ( colorToggle )
glColor3f( 0.8f, 0.1f, 0.1f );
else
glColor3f( 0.95f, 0.95f, 0.95f );
#if 0
if ( lat_deg >= 180 )
if ( colorToggle )
glColor3f( 0.1f, 0.8f, 0.1f );
else
glColor3f( 0.5f, 0.5f, 0.95f );
#endif
colorToggle = ! colorToggle;
/*
* Change color if drawing shadow.
*/
if ( drawBallHow == DRAW_BALL_SHADOW )
glColor3f( 0.35f, 0.35f, 0.35f );
/*
* Assign each Y.
*/
vert_ne.y = vert_nw.y = (float) cos_deg(long_hi) * RADIUS;
vert_sw.y = vert_se.y = (float) cos_deg(long_lo) * RADIUS;
/*
* Assign each X,Z with sin,cos values scaled by latitude radius indexed by longitude.
* Eg, long=0 and long=180 are at the poles, so zero scale is sin(longitude),
* while long=90 (sin(90)=1) is at equator.
*/
vert_ne.x = (float) cos_deg( lat_deg ) * (RADIUS * (float) sin_deg( long_lo + STEP_LONGITUDE ));
vert_se.x = (float) cos_deg( lat_deg ) * (RADIUS * (float) sin_deg( long_lo ));
vert_nw.x = (float) cos_deg( lat_deg + STEP_LATITUDE ) * (RADIUS * (float) sin_deg( long_lo + STEP_LONGITUDE ));
vert_sw.x = (float) cos_deg( lat_deg + STEP_LATITUDE ) * (RADIUS * (float) sin_deg( long_lo ));
vert_ne.z = (float) sin_deg( lat_deg ) * (RADIUS * (float) sin_deg( long_lo + STEP_LONGITUDE ));
vert_se.z = (float) sin_deg( lat_deg ) * (RADIUS * (float) sin_deg( long_lo ));
vert_nw.z = (float) sin_deg( lat_deg + STEP_LATITUDE ) * (RADIUS * (float) sin_deg( long_lo + STEP_LONGITUDE ));
vert_sw.z = (float) sin_deg( lat_deg + STEP_LATITUDE ) * (RADIUS * (float) sin_deg( long_lo ));
/*
* Draw the facet.
*/
glBegin( GL_POLYGON );
CrossProduct( vert_ne, vert_nw, vert_sw, &vert_norm );
glNormal3f( vert_norm.x, vert_norm.y, vert_norm.z );
glVertex3f( vert_ne.x, vert_ne.y, vert_ne.z );
glVertex3f( vert_nw.x, vert_nw.y, vert_nw.z );
glVertex3f( vert_sw.x, vert_sw.y, vert_sw.z );
glVertex3f( vert_se.x, vert_se.y, vert_se.z );
glEnd();
#if BOING_DEBUG
printf( "----------------------------------------------------------- \n" );
printf( "lat = %f long_lo = %f long_hi = %f \n", lat_deg, long_lo, long_hi );
printf( "vert_ne x = %.8f y = %.8f z = %.8f \n", vert_ne.x, vert_ne.y, vert_ne.z );
printf( "vert_nw x = %.8f y = %.8f z = %.8f \n", vert_nw.x, vert_nw.y, vert_nw.z );
printf( "vert_se x = %.8f y = %.8f z = %.8f \n", vert_se.x, vert_se.y, vert_se.z );
printf( "vert_sw x = %.8f y = %.8f z = %.8f \n", vert_sw.x, vert_sw.y, vert_sw.z );
#endif
}
/*
* Toggle color so that next band will opposite red/white colors than this one.
*/
colorToggle = ! colorToggle;
/*
* This circular band is done.
*/
return;
}
|
C
|
#include<stdio.h>
main()
{
int a;
printf("enter a number");
scanf("%d",&a);
if(a>0)
printf("it is positive");
else if(a==0)
printf("it is zero ");
else
printf("it is negative n.0");
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int n = 1;
double potega(double x, int n) {
int i;
double wynik = 1;
for (i = 0; i < n; i++)
{
wynik = (double)wynik * x;
}
return wynik;
}
double sumowanie_od_przodu(int koniec, double x) {
double suma = 0;
for (n; n <= koniec; n++) {
suma = suma + (potega(-1, n + 1) / n) * potega(x, n);
}
return suma;
}
double sumowanie_od_tylu(int koniec, double x) {
double suma = 0;
for (n = koniec; n > 0; n--) {
suma = suma + (potega(-1, n + 1) / n) * potega(x, n);
}
return suma;
}
double nastepny_wyraz_przod(int koniec, double x) {
double suma = x;
double q = 1;
for (n ; n < koniec; n++) {
q = ((potega(x, n + 1) / (n + 1)) * (n / potega(x, n)));
if (n % 2 != 0) q = q * (-1);
double wyraz = (potega(x, n) / n);
suma = suma += wyraz * q;
}
return suma;
}
double nastepny_wyraz_tyl(int koniec, double x) {
double suma = x;
double q = 1;
for (n = koniec; n > 0; n--) {
q = ((potega(x, n + 1) / (n + 1)) * (n / potega(x, n)));
if (n % 2 != 0) q = q * (-1);
double wyraz = (potega(x, n) / n);
suma = suma += wyraz * q;
}
return suma;
}
double mod(double number) {
if (number < 0)
return number * (-1);
else return number;
}
//Wartossc beedu bezwzglednego niewiele mwi, gdy nic nie wiemy o
//rzedzie wielkosci wartosci dokadnej.
double blad_bezwzgledny(double x, double x0) {
return mod(x - x0);
}
double blad_wzgledny(double x, double x0) {
return blad_bezwzgledny(x, x0) / x * 100;
}
int main() {
int koniec = 100;
double x = -0.999998;
FILE *fpw = fopen("wyniki_.csv", "w");
FILE *fpwbw = fopen("wyniki_bezw.csv", "w");
FILE *fpww = fopen("wyniki_wzg.csv", "w");
fprintf(fpw, "x;funkcja biblioteczna;sumowanie szeregu od przodu; sumowanie szeregu od tylu; sumowanie ciagu od przodu; sumowanie ciagu od tylu\n");
fprintf(fpwbw, "x;funkcja biblioteczna; blad bezwzgledny od przodu;blad bezwzgledny od tylu;blad bezwzgledny ciagu p.;blad bezwzgledny ciagu t.\n");
fprintf(fpww, "x;funkcja biblioteczna; blad wzgledny od przodu;blad wzgledny od tylu;blad wzgledny c. przod;blad wzgledny c. tyl\n");
for (x; x < 1; x = x + 0.02) {
fprintf(fpw, "%.6f;%.16lf;%.16lf;%.16lf;%.16lf;%.16lf;\n", x, log(1 + x), sumowanie_od_przodu(koniec, x), sumowanie_od_tylu(koniec, x), nastepny_wyraz_przod(koniec, x), nastepny_wyraz_tyl(koniec, x));
fprintf(fpwbw, "%.6f;%.16lf;%.16lf;%.16lf;%.16lf;%.16lf;\n", x, log(1 + x), blad_bezwzgledny(log(1 + x), sumowanie_od_przodu(koniec, x)), blad_bezwzgledny(log(1 + x), sumowanie_od_tylu( koniec, x)), blad_bezwzgledny(log(1 + x), nastepny_wyraz_przod(koniec, x)), blad_bezwzgledny(log(1 + x), nastepny_wyraz_tyl(koniec, x)));
fprintf(fpww, "%.6f;%.16lf;%.16lf;%.16lf;%.16lf;%.16lf;\n", x, log(1 + x), blad_wzgledny(log(1 + x), sumowanie_od_przodu(koniec, x)), blad_wzgledny(log(1 + x), sumowanie_od_tylu(koniec, x)), blad_wzgledny(log(1 + x), nastepny_wyraz_przod(koniec, x)), blad_wzgledny(log(1 + x), nastepny_wyraz_tyl(koniec, x)));
}
fclose(fpw);
fclose(fpwbw);
fclose(fpww);
return 0;
}
|
C
|
#include <stdio.h>
#include <unistd.h>
#include <signal.h>
#include <string.h>
static void func_init()
{
puts("SIGINT");
}
int main(void)
{
struct sigaction act;
sigset_t set, oldset;
sigemptyset(&set);
sigaddset(&set, SIGINT);
if (sigprocmask(SIG_BLOCK, &set, &oldset) < 0) {
perror("sigprocmask");
return 1;
}
memset(&act, 0, sizeof act);
act.sa_handler = func_init;
if (sigaction(SIGINT, &act, NULL)) {
perror("sigaction");
return 1;
}
puts("Calling suspend");
sigsuspend(&oldset);
puts("suspend return");
return 0;
}
|
C
|
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <modbus.h>
modbus_t *initModbus_RTU(char *pdevpath, uint32_t sec, uint32_t usec)
{
modbus_t *mb = NULL;
//1-打开端口
if(NULL == (mb=modbus_new_rtu(pdevpath, 9600,'N',8, 1)))
{
printf("modbus-RTU serial open failed\r\n");
return NULL;
}
//2-设置从地址
modbus_set_slave(mb, 1);
//3-建立连接
modbus_connect(mb);
//4-设置应答延时
modbus_set_response_timeout(mb, sec, usec);
return mb;
}
void releaseModbus_RTU(modbus_t *mb)
{
if(mb == NULL)
return ;
//7-关闭modbus端口
modbus_close(mb);
//8-释放modbus资源
modbus_free(mb);
}
void modbus_Poll(void)
{
}
int main(int argc, char *argv[])
{
modbus_t *mb = NULL;
char *pdevpath = NULL;
uint16_t tab_reg[2] = {0};
if(argc < 2)
{
printf("please input the file of device \r\n");
return 0;
}
//设备文件路径
pdevpath = argv[1];
//初始化modbus-RTU
mb = initModbus_RTU(pdevpath, 0, 1000000); //1000ms
//5-循环读
int num = 0;
while(1)
{
memset(tab_reg, 0, 2);
//6-读寄存器设置:寄存器地址、数量、数据缓冲
int regs = modbus_read_registers(mb, 0, 2, tab_reg);
printf("-------------------------------------------\n");
printf("[%4d][read num = %d]", num, regs);
num++;
for(int i=0; i<2; i++)
{
//printf("<%d>",tab_reg[i]);
printf("<%#x>",tab_reg[i]);
}
printf("\n");
printf("-------------------------------------------\n");
sleep(1);
}
releaseModbus_RTU(mb);
return 0;
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* cd.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: lumenthi <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2018/03/13 11:51:16 by lumenthi #+# #+# */
/* Updated: 2018/03/13 12:04:39 by lumenthi ### ########.fr */
/* */
/* ************************************************************************** */
#include "../../../includes/minishell.h"
static void cd_error(char *path)
{
ft_putstr(RED);
ft_putstr("cd");
ft_putstr(BLANK);
if (ft_strcmp(path, "$HOME") == 0)
ft_putendl(": no $HOME variable");
else if (ft_strcmp(path, "$OLDPWD") == 0)
ft_putendl(": no $OLDPWD variable");
else
{
ft_putstr(": no such file or directory: ");
ft_putendl(path);
}
}
void cd_var(char **arg, char ***environ, char **abs_path)
{
char *tmp;
if (!(tmp = var_conv(arg[1], *environ)))
ft_print_error("cd", VAR_FOUND, arg[1]);
else if (chdir(tmp) == -1)
cd_error(tmp);
else
{
set_var(environ, "OLDPWD=", *abs_path);
*abs_path = getcwd(*abs_path, 99);
set_var(environ, "PWD=", *abs_path);
}
}
void cd_old(char ***environ, char **ap, char *op)
{
if (chdir(op) == -1)
cd_error("$OLDPWD");
else
{
set_var(environ, "OLDPWD=", *ap);
*ap = getcwd(*ap, 99);
set_var(environ, "PWD=", *ap);
ft_putendl(*ap);
}
}
void cd_home(char ***environ, char **abs_path)
{
if (!get_var(*environ, "HOME="))
ft_print_error("cd", VAR_FOUND, "$HOME");
else if (chdir(get_var(*environ, "HOME=")) == -1)
cd_error(get_var(*environ, "HOME="));
else
{
set_var(environ, "OLDPWD=", *abs_path);
*abs_path = getcwd(*abs_path, 99);
set_var(environ, "PWD=", *abs_path);
}
}
void cd_path(char **arg, char ***environ, char **abs_path)
{
if (chdir(arg[1]) == -1)
cd_error(arg[1]);
else
{
set_var(environ, "OLDPWD=", *abs_path);
*abs_path = getcwd(*abs_path, 99);
set_var(environ, "PWD=", *abs_path);
}
}
|
C
|
/* ************************************************************************** */
/* */
/* :::::::: */
/* draw_frame.c :+: :+: */
/* +:+ */
/* By: osamara <osamara@student.codam.nl> +#+ */
/* +#+ */
/* Created: 2021/02/08 23:23:11 by osamara #+# #+# */
/* Updated: 2021/03/12 22:51:19 by osamara ######## odam.nl */
/* */
/* ************************************************************************** */
#include "draw_frame.h"
#include "utils.h"
#include "sample_skybox.h"
#include "draw_utils.h"
#include "mlx.h"
void draw_vertical_line(t_game_engine_state *state,
t_intersection_result *result, int x, double ray_angle)
{
int wall_top;
int wall_bottom;
char *dst;
int y;
wall_top = state->style->resolution.y / 2 - (int)result->wall_height / 2;
wall_bottom = state->style->resolution.y / 2 + (int)result->wall_height / 2;
dst = state->window->addr + x * (state->window->bits_per_pixel / 8);
y = 0;
while (y < state->style->resolution.y)
{
if (y < wall_top)
*(unsigned int *)dst = draw_ceiling(state, y, ray_angle);
else if (y >= wall_top && y < wall_bottom)
{
result->tex_y = ((double)y - wall_top) / (wall_bottom - wall_top);
*(unsigned int *)dst = sample_texture(result->current_tex,
result->tex_x, result->tex_y);
}
else
*(unsigned int *)dst = state->style->floor_rgb;
y++;
dst += state->window->line_length;
}
}
unsigned int draw_ceiling(t_game_engine_state *state, int y, double angle)
{
unsigned int color;
if (BONUS && state->style->textures[TEXTURE_SKYBOX] != NULL)
color = sample_skybox(state, y, angle);
else
color = state->style->ceiling_rgb;
return (color);
}
unsigned int sample_texture(t_texture_info *tex, double tex_x, double tex_y)
{
char *tex_color;
int x;
int y;
x = tex_x * tex->img_width;
y = tex_y * tex->img_height;
if (x < 0)
x = 0;
else if (x >= tex->img_width)
x = tex->img_width - 1;
if (y < 0)
y = 0;
else if (y >= tex->img_height)
y = tex->img_height - 1;
tex_color = tex->addr + y * tex->line_length + x * (tex->bpp / 8);
return (*(unsigned int *)tex_color);
}
/*
** It would be more readable to assign the address like in wall draw:
** dst = state->window->addr + x * (state->window->bits_per_pixel / 8)
** + y * state->window->line_length;
** and then to assign color to dst
** but because of 25 I have to write an ugly solution
**
** t_sprite *sp stands for *sprite - also 25 lines :(
*/
void draw_sprites_vertical_line(t_game_engine_state *state, int x,
double dist_to_wall)
{
int i;
int y;
unsigned int color;
t_sprite *sp;
i = 0;
while (i < state->map->sprites_num)
{
sp = &state->sprites[i];
if (sp->dist_to_sprite < dist_to_wall && sp->dist_to_sprite > 0.0
&& x >= sp->draw_min_x && x <= sp->draw_max_x)
{
y = max(sp->draw_min_y, 0);
while (y <= min(sp->draw_max_y, state->style->resolution.y - 1))
{
color = sample_sprites_vertical_line(state, x, y, i);
if (color != 0x00000000)
*(unsigned int *)(state->window->addr
+ x * (state->window->bits_per_pixel / 8)
+ y * state->window->line_length) = color;
y++;
}
}
i++;
}
}
unsigned int sample_sprites_vertical_line(t_game_engine_state *state,
int x, int y, int i)
{
double sprite_tex_x;
double sprite_tex_y;
unsigned int color;
sprite_tex_x = ((double)x - (state->sprites[i].draw_min_x))
/ (state->sprites[i].draw_max_x - state->sprites[i].draw_min_x);
sprite_tex_y = ((double)y - (state->sprites[i].draw_min_y))
/ state->sprites[i].projected_height;
color = sample_texture(&state->tex_info[TEXTURE_SPRITE],
sprite_tex_x, sprite_tex_y);
return (color);
}
|
C
|
/*
* Copyright (c) 2011 Ignasi Barrera
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
/*
* Read welcome.c, oper.c and binding.c exampes first.
*
* This example shows generic callback features to handle error
* responses and to define global message handlers.
*/
#define _POSIX_C_SOURCE 200112L /* Use snprintf */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "utils.h" /* Utility functions and macros */
#include "irc.h" /* IRC protocol functions */
#define CONF_NICK "circus-bot" /* The nick to be used by the bot */
#define CONF_CHAN "#circus-bot" /* The channel to join */
/* Disconnect if the nick is in use */
void on_nick_in_use(ErrorEvent* event) {
printf("Nick %s is already in use\n", event->params[1]);
irc_quit("Bye");
irc_disconnect();
exit(EXIT_FAILURE);
}
/* Print the error message */
void on_error(ErrorEvent* event) {
printf("Incoming error message: [%s] %s\n", event->code, event->message);
}
/* Welcome a user when joining */
void on_join(JoinEvent* event) {
char msg[30];
if (s_ne(event->user.nick, CONF_NICK)) { /* String not-equal macro from utils.h */
snprintf(msg, 30, "Welcome %s", event->user.nick); /* Build the message to send */
irc_message(event->channel, msg); /* Send message to channel */
}
}
/* Print the incoming message */
void on_message(GenericEvent* event) {
printf("Incoming message: [%s] %s\n", event->code, event->message);
}
int main(int argc, char **argv) {
char* server, *port;
if (argc != 3) {
printf("Usage: %s <server> <port>\n", argv[0]);
exit(EXIT_FAILURE);
}
server = argv[1]; /* The IRC server */
port = argv[2]; /* The IRC server port */
/* Bind IRC event to custom functions.
* All bindable events are defined in codes.h */
irc_bind_event(ERR_NICKNAMEINUSE, (Callback) on_nick_in_use);
irc_bind_event(ERROR, (Callback) on_error);
irc_bind_event(JOIN, (Callback) on_join);
irc_bind_event(ALL, (Callback) on_message);
/* Connect, login and join the configured channel */
irc_connect(server, port);
irc_login(CONF_NICK, "Circus", "Circus IRC bot");
irc_join(CONF_CHAN);
/* Start listening to events.
* This method blocks until a quit signal is received */
irc_listen();
/* Send quit message and close connection */
irc_quit("Bye");
irc_disconnect();
return 0;
}
|
C
|
#include <stdio.h>
int main()
{
int n, ld = 1;
int a, b, c, d, e, f, g, h, i, j;
a = b = c = d = e = f = g = h = i = j = 0;
scanf("%d", &n);
while (ld > 0)
{
ld = n % 10;
n /= 10;
switch (ld)
{
case 1:
a++;
break;
case 2:
b++;
break;
case 3:
c++;
break;
case 4:
d++;
break;
case 5:
e++;
break;
case 6:
f++;
break;
case 7:
g++;
break;
case 8:
h++;
break;
case 9:
i++;
break;
default:
break;
}
}
printf("0 %d\n", j);
printf("1 %d\n", a);
printf("2 %d\n", b);
printf("3 %d\n", c);
printf("4 %d\n", d);
printf("5 %d\n", e);
printf("6 %d\n", f);
printf("7 %d\n", g);
printf("8 %d\n", h);
printf("9 %d\n", i);
}
|
C
|
/*
** EPITECH PROJECT, 2018
** minishell1_2017
** File description:
** minishell1_2017 made by Sanchez Lucas
*/
#include "42sh.h"
void exec_cd_minus(env_t *env, int *ret_value, char *old_pwd, char *cur_dir)
{
if (old_pwd == NULL || chdir(old_pwd) == -1) {
old_pwd != NULL ? my_putstr(old_pwd) : 0;
my_printf(": No such file or directory.\n");
*ret_value = 1;
free(cur_dir);
return;
}
old_pwd = my_strdup(cur_dir);
change_pwd(env);
}
void exec_cd(env_t *env, char **str, int *ret_value)
{
char *cur_dir = malloc(sizeof(char) * 4096);
static char *old_pwd = NULL;
getcwd(cur_dir, 4096);
if (my_strcmp(str[1], "-") == 0)
exec_cd_minus(env, ret_value, old_pwd, cur_dir);
else if (chdir(str[1]) == -1) {
if (access(str[1], F_OK) == -1 || strlen(str[1]) > NAME_MAX) {
strlen(str[1]) > N_MAX ? printf(FILE_TOO_LONG, str[1])
: printf("%s: No such file or directory.\n", str[1]);
} else
my_printf("%s: Not a directory.\n", str[1]);
*ret_value = 1;
} else {
old_pwd = my_strdup(cur_dir);
change_pwd(env);
}
free(cur_dir);
}
void cd_func(char **str, shell_t shell, int *ret_value)
{
char *home = get_env(shell.env, "HOME");
if (str[1] == NULL) {
if (home == NULL) {
my_printf("cd: No home directory\n");
*ret_value = 1;
return;
}
chdir(home);
change_pwd(shell.env);
} else if (str[2] != NULL) {
my_printf("cd: Too many arguments.\n");
*ret_value = 1;
} else
exec_cd(shell.env, str, ret_value);
}
|
C
|
/* Exercise 1-1. Create the "hello, world" program */
#include <stdio.h>
main()
{
printf("hello, ");
printf("world");
printf("\n");
}
|
C
|
// TODO: Include the correct file so you can use the methods you wrote in the puppies file
#include "puppies.c"
int main() {
Puppy puppy1 = create_new_puppy("Sparkie", 2);
printf("Welcome our new puppy, %s, who is %d years old!\n", puppy1.name, puppy1.age);
Puppy puppy2 = create_new_puppy("Bailey", 3);
printf("Welcome our new puppy, %s, who is %d years old!\n", puppy2.name, puppy2.age);
make_friends(puppy1, puppy2);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include "listaCirc.h"
void troca_conteudo(Node **Origem, Node **Destino);
int main(){
int Input, i, Deslocamentos;
Node *Anel, *Aux;
Anel = cria_node();
scanf("%d", &Input);
for(i=1; Input != -1; i++ , scanf("%d", &Input)){
if(i==1)
insere_inicio(Input, &Anel);
else
insere_final(Input, &Anel);
}
//exibe(Anel);
while(Anel->Conteudo != 1){
for(Aux = Anel; Aux->Proximo != Anel; Aux = Aux->Proximo) ;
}
return 0;
}
void troca_conteudo(Node **Origem, Node **Destino){
int Hold;
Hold = (*Origem)->Conteudo;
(*Origem)->Conteudo = (*Destino)->Conteudo;
(*Destino)->Conteudo = Hold;
return;
}
|
C
|
#pragma once
typedef unsigned long CRC32_t;
void CRC32_Init( CRC32_t* pulCRC );
void CRC32_ProcessBuffer( CRC32_t* pulCRC, const void* p, int len );
void CRC32_Final( CRC32_t* pulCRC );
CRC32_t CRC32_GetTableEntry( unsigned int slot );
inline CRC32_t CRC32_ProcessSingleBuffer( const void* p, int len )
{
CRC32_t crc;
CRC32_Init( &crc );
CRC32_ProcessBuffer( &crc, p, len );
CRC32_Final( &crc );
return crc;
}
|
C
|
#include "holberton.h"
/**
* print_line - a function that draws a staight line in the terminal
* @n: takes an integer value that determines # of times '_' is printed
* Return: a straight line of length n followed by a new
* line or just a new line
*/
void print_line(int n)
{
int i;
if (n > 0)
{
for (i = 0; i < n; i++)
_putchar('_');
_putchar('\n');
}
else
_putchar('\n');
}
|
C
|
#include <stdio.h>
#include <string.h>
int main(void) {
char texto[50];
printf("\nInforme seu nome completo: ");
fgets(texto, 50, stdin);
int cont = strlen(texto);
printf("\nO tamanho da string: %i\n", cont);
for (int i = 0; i < cont; i++) printf("%d ", texto[i]);
texto[cont - 1] = '\0';
cont = strlen(texto);
printf("\nO tamanho da string: %i\n", cont);
}
//https://pt.stackoverflow.com/q/157168/101
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <pthread.h>
#define N 100
#define RANDOM_RANGE 100000
#define NTHREAD 10
#define VECTOR_LENGTH_PER_THREAD (N/NTHREAD)
static int matrice_a[N][N];
static int matrice_b[N][N];
static int matrice_c[N][N];
static pthread_mutex_t mutex_matrice_mul;
static void init(void)
{
int i, j;
for (i = 0; i < N; i++) {
for (j = 0; j < N; j++) {
matrice_a[i][j] = matrice_b[i][j] = random() % RANDOM_RANGE;
}
}
}
static void *process(void *arg)
{
uintptr_t offset;
long i, start, end, k, j;
long sum;
offset = (uintptr_t) arg;
start = offset * VECTOR_LENGTH_PER_THREAD;
end = start + VECTOR_LENGTH_PER_THREAD;
for (i = start; i < end; i++) {
for (j = 0; j < N; j++) {
sum = 0;
for (k = 0; k < N; k++) {
sum += matrice_a[i][k] * matrice_b[k][j];
}
pthread_mutex_lock(&mutex_matrice_mul);
matrice_c[i][j] = sum;
pthread_mutex_unlock(&mutex_matrice_mul);
}
}
pthread_exit(NULL);
}
static void print_matrice(void)
{
int i, j;
for (i = 0; i < N; i++) {
for (j = 0; j < N; j++) {
printf("%d ", matrice_c[i][j]);
}
printf("\n");
}
}
int main(void)
{
uintptr_t i;
pthread_t threads[NTHREAD];
init();
pthread_mutex_init(&mutex_matrice_mul, NULL);
for (i = 0; i < NTHREAD; i++)
pthread_create(&threads[i], NULL, process, (void *) i);
for (i = 0; i < NTHREAD; i++)
pthread_join(threads[i], NULL);
print_matrice();
pthread_mutex_destroy(&mutex_matrice_mul);
exit(EXIT_SUCCESS);
}
|
C
|
/* vim: set et ts=4 sts=4 sw=4 : */
/********************************************************************\
* This program is free software; you can redistribute it and/or *
* modify it under the terms of the GNU General Public License as *
* published by the Free Software Foundation; either version 2 of *
* the License, or (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License*
* along with this program; if not, contact: *
* *
* Free Software Foundation Voice: +1-617-542-5942 *
* 59 Temple Place - Suite 330 Fax: +1-617-542-2652 *
* Boston, MA 02111-1307, USA gnu@gnu.org *
* *
\********************************************************************/
/**
@file safe.c
@brief Safe versions of stdlib/string functions that error out and exit if memory allocation fails
@author Copyright (C) 2005 Mina Naguib <mina@ilesansfil.org>
*/
/* Enable vasprintf */
#define _GNU_SOURCE
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <syslog.h>
#include "safe.h"
#include "debug.h"
/** @brief Clean up all the registered fds. */
static void cleanup_fds(void);
/** List of fd's to close on fork. */
typedef int fd_list_t;
static fd_list_t fd_list[MAX_FD_CLEANUP];
/** Clean up all the registered fds. Frees the list as it goes.
* XXX This should only be run by CHILD processes.
*/
static void
cleanup_fds(void)
{
unsigned int i;
for (i = 0; i < sizeof(fd_list) / sizeof(int); i++) {
if (fd_list[i]) {
close(fd_list[i]);
fd_list[i] = 0;
}
}
}
/** Register an fd for auto-cleanup on fork()
* @param fd A file descriptor.
*/
void
register_fd_cleanup_on_fork(const int fd)
{
unsigned int i;
for (i = 0; i < sizeof(fd_list) / sizeof(int); i++) {
if (!fd_list[i]) {
break;
}
}
if (MAX_FD_CLEANUP == i) {
debug(LOG_CRIT, "Trying to register more than %d fds for cleanup on fork",
MAX_FD_CLEANUP);
exit(1);
}
fd_list[i] = fd;
}
/** Allocate zero-filled ram or die.
* @param size Number of bytes to allocate
* @return void * pointer to the zero'd bytes.
*/
void *
safe_malloc(size_t size)
{
void *retval = NULL;
retval = malloc(size);
if (!retval) {
debug(LOG_CRIT, "Failed to malloc %d bytes of memory: %s. Bailing out", size, strerror(errno));
exit(1);
}
memset(retval, 0, size);
return (retval);
}
/** Re-allocates memory to a new larger allocation.
* DOES NOT ZERO the added RAM
* Original pointer is INVALID after call
* Dies on allocation failures.
* @param ptr A pointer to a current allocation from safe_malloc()
* @param newsize What size it should now be in bytes
* @return pointer to newly allocation ram
*/
void *
safe_realloc(void *ptr, size_t newsize)
{
void *retval = NULL;
retval = realloc(ptr, newsize);
if (NULL == retval) {
debug(LOG_CRIT, "Failed to realloc buffer to %d bytes of memory: %s. Bailing out", newsize, strerror(errno));
exit(1);
}
return retval;
}
/** Duplicates a string or die if memory cannot be allocated
* @param s String to duplicate
* @return A string in a newly allocated chunk of heap.
*/
char *
safe_strdup(const char *s)
{
char *retval = NULL;
if (!s) {
debug(LOG_CRIT, "safe_strdup called with NULL which would have crashed strdup. Bailing out");
exit(1);
}
retval = strdup(s);
if (!retval) {
debug(LOG_CRIT, "Failed to duplicate a string: %s. Bailing out", strerror(errno));
exit(1);
}
return (retval);
}
/** Sprintf into a newly allocated buffer
* Memory MUST be freed. Dies if memory cannot be allocated.
* @param strp Pointer to a pointer that will be set to the newly allocated string
* @param fmt Format string like sprintf
* @param ... Variable number of arguments for format string
* @return int Size of allocated string.
*/
int
safe_asprintf(char **strp, const char *fmt, ...)
{
va_list ap;
int retval;
va_start(ap, fmt);
retval = safe_vasprintf(strp, fmt, ap);
va_end(ap);
return (retval);
}
/** Sprintf into a newly allocated buffer
* Memory MUST be freed. Dies if memory cannot be allocted.
* @param strp Pointer to a pointer that will be set to the newly allocated string
* @param fmt Format string like sprintf
* @param ap pre-digested va_list of arguments.
* @return int Size of allocated string.
*/
int
safe_vasprintf(char **strp, const char *fmt, va_list ap)
{
int retval;
retval = vasprintf(strp, fmt, ap);
if (retval == -1) {
debug(LOG_CRIT, "Failed to vasprintf: %s. Bailing out", strerror(errno));
exit(1);
}
return (retval);
}
/** Fork and then close any registered fille descriptors.
* If fork() fails, we die.
* @return pid_t 0 for child, pid of child for parent
*/
pid_t
safe_fork(void)
{
pid_t result;
result = fork();
if (result == -1) {
debug(LOG_CRIT, "Failed to fork: %s. Bailing out", strerror(errno));
exit(1);
} else if (result == 0) {
/* I'm the child - do some cleanup */
cleanup_fds();
}
return result;
}
|
C
|
extern int _subtract_bignums(bignum*, bignum*);
extern int _add_bignums(bignum*, bignum*);
extern int _multiply_bignums(bignum*, bignum*, bignum*);
void resize_numbers(bignum* bn1, bignum* bn2);
void add_wrapper();
void add_carry(bignum* bn);
void sub_borrow(bignum* bn);
int compare_bignum(bignum* bn1, bignum* bn2);
int div_comparer(bignum * bn1,bignum * bn2);
int subtract_bignums(bignum* bn1, bignum* bn2);
void div_algorithm(bignum *bn1, bignum *bn2, bignum * divFactor);
int bn_is_zero(bignum* bn1);
bignum* divQuotiant;
bignum* divRemainder;
void add_carry(bignum* bn) {
link* addedLink = (link*) malloc(sizeof(link));
addedLink->num = 1;
bn->head->prev = addedLink;
addedLink->next = bn->head;
bn->number_of_digits++;
bn->head = addedLink;
}
bignum* init_mul_ptr(long length){
long new_length = length*2;
bignum* result= (bignum*) malloc(sizeof(bignum));
result->number_of_digits = new_length;
result->head = (link*) malloc(sizeof(link));
result->last = result->head;
result->last->num = 0;
for(int i=0; i<new_length;i++){
link* newLink = (link*) malloc(sizeof(link));
newLink->num = 0;
newLink->prev = result->last;
result->last->next = newLink;
result->last = newLink;
}
return result;
}
void resize_numbers(bignum* bn1, bignum* bn2) {
while(bn1->number_of_digits > bn2->number_of_digits) {
// Add zero before the actual number.
link* addedLink = (link*) malloc(sizeof(link));
addedLink->num = 0;
bn2->head->prev = addedLink;
addedLink->next = bn2->head;
bn2->number_of_digits++;
bn2->head = addedLink;
}
while(bn1->number_of_digits < bn2->number_of_digits) {
// Add zero before the actual number.
link* addedLink = (link*) malloc(sizeof(link));
addedLink->num = 0;
addedLink->prev = NULL;
bn1->head->prev = addedLink;
addedLink->next = bn1->head;
bn1->head = addedLink;
bn1->number_of_digits++;
}
}
void sub_borrow(bignum* bn){
link* oldLink = bn->head;
bn->head = bn->head->next;
free(oldLink);
bn->number_of_digits --;
}
/**
* Compare bignum values (ignore sign).
* @param bn1
* @param bn2
* @return
* - 0 on same value.
* - positive value if bn1 is bigger.
* - negative value if bn2 is bigger.
*/
int compare_bignum(bignum* bn1, bignum* bn2){
int result = (int) (bn1->number_of_digits - bn2->number_of_digits);
resize_numbers(bn1, bn2);
if (result != 0) {
return result;
}
link* bn_iterator_1 = bn1->head;
link* bn_iterator_2 = bn2->head;
while (bn_iterator_1 != 0 &&
bn_iterator_1->num == bn_iterator_2->num)
{
bn_iterator_1 = bn_iterator_1->next;
bn_iterator_2 = bn_iterator_2->next;
}
if (bn_iterator_1 == NULL) {
return 0;
}
return bn_iterator_1->num - bn_iterator_2->num;
}
/**
* Subtracts bn1 from bn2.
* @param bn1
* @param bn2
* @return 1/2 number of the bignum to free.
*/
int subtract_bignums(bignum* bn1, bignum* bn2) {
int comp = compare_bignum(bn1, bn2);
if (comp > 0 &&
(bn1->sign + bn2->sign == 0 || bn1->sign + bn2->sign == 2)
) {
// Bn1 is larger, but numbers are both positive or both negative.
_subtract_bignums(bn1, bn2);
return 2;
}
else if (comp < 0 &&
(bn1->sign + bn2->sign == 0 || bn1->sign + bn2->sign == 2)
) {
// Bn2 is larger, but numbers are both positive or both negative.
_subtract_bignums(bn2, bn1);
// Switch sign are for bn2 (since we're subtracting a bigger number).
bn2->sign = 1 - bn2->sign;
return 1;
}
else if (bn1->sign ^ bn2->sign) {
// Only one of the numbers is negative and the other is positive.
_add_bignums(bn1, bn2);
return 2;
}
else if(comp == 0) {
// Numbers are equal.
_subtract_bignums(bn1, bn2);
bn1->sign = 0;
return 2;
}
// Error.
return -1;
}
// Adds two numbers, pushes the result, and frees the unused variable.
void add_wrapper() {
stack_item * si2 = numstack_pop();
stack_item * si1 = numstack_pop();
bignum* bn2 = si2->value;
bignum* bn1 = si1->value;
// Resize variables.
resize_numbers(bn1, bn2);
// Compare bignums.
int comp = compare_bignum(bn1, bn2);
int which_to_free = 0;
if (bn1->sign == 0) {
// BN1 is positive.
if (bn2->sign == 0) {
// BN2 is positive.
// Just add.
_add_bignums(bn1, bn2);
which_to_free = 2;
}
else {
// BN2 is negative.
// Subtract BN2 from BN1.
bn2->sign = 0;
_subtract_bignums(bn1, bn2);
if (comp < 0) {
// BN2 is bigger, so the sign should be negative.
bn1->sign = 1;
}
which_to_free = 2;
}
}
else if (bn1->sign == 1) {
// BN1 is negative
if (bn2->sign == 0) {
// BN2 is positive.
// Subtract BN1 from BN2.
bn1->sign = 0;
_subtract_bignums(bn1, bn2);
if (comp > 0) {
// BN1 is bigger than BN2. We should return a negative number.
bn1->sign = 1;
}
which_to_free = 2;
}
else {
// Both numbers are negative.
// Just add.
_add_bignums(bn1, bn2);
which_to_free = 2;
}
}
else {
// Error.
printf("Error with sign in bn1.\n");
return;
}
after_operation_cleanup(which_to_free, si1, si2);
}
void multiply_wrapper() {
stack_item * si2 = numstack_pop();
stack_item * si1 = numstack_pop();
bignum* bn2 = si2->value;
bignum* bn1 = si1->value;
bignum* result = create_result_container_wrapper(bn1, bn2);
resize_numbers(bn1,bn1);
_multiply_bignums(bn1, bn2, result);
// Fix sign.
result->sign = (bn1->sign == bn2->sign) ? 0 : 1;
numstack_push_bignum(result);
// Set them bytes free!!!!11
clear_stack_item(si1);
clear_stack_item(si2);
}
/**
* Integer-divides the first two bignums in the stack.
* (bn1/bn2).
*/
void divide_wrapper() {
stack_item * si2 = numstack_pop();
stack_item * si1 = numstack_pop();
bignum* bn2 = si2->value;
bignum* bn1 = si1->value;
resize_numbers(bn1, bn2);
divQuotiant = create_result_container(bn1->number_of_digits);
divRemainder = create_result_container(bn1->number_of_digits);
bignum* divFactor = create_result_container(bn1->number_of_digits);
// Start factor at 1.
divFactor->last->num = 1;
if(bn_is_zero(bn2)) {
printf("Error: divide by zero.\n");
numstack_push(si2);
}
else if(div_comparer(bn1, bn2) < 0) {
// Bn2 is bigger - push 0.
numstack_push_bignum(divQuotiant);
// Clean up.
clear_bn(divFactor);
}
else if (div_comparer(bn1, bn2) == 0) {
// Bignums are equal - push 1.
numstack_push_bignum(divFactor);
// Clean up.
clear_bn(divQuotiant);
}
else {
// Start division algorithm (see explanation below).
div_algorithm(bn1, bn2, divFactor);
bignum * result = clone_bignum(divQuotiant);
if(bn1->sign ^ bn2->sign && !bn_is_zero(result)) {
result->sign = 1;
}
numstack_push_bignum(result);
// Cleanup.
clear_bn(divFactor);
}
}
int bn_is_zero(bignum* bn1) {
link* iterator = bn1->head;
while(iterator != NULL) {
if (iterator->num != 0) {
// Not zero...
return 0;
}
iterator = iterator->next;
}
// Yes it is a zero.
return 1;
}
/** USING MAYER's algorithm
* Idea behind the algorithm:
* Recusively (incrementing x) find if dividing bn1 by 2^x
* reduces it below bn2.
* if so, add 2^(x -1) to a "divisor list" that's added together.
* remove the part that can be divided from bn1 for future calculations.
* EXAMPLE: format - (bn1, bn2, result, factor)
; 2000 / 15 : (2000, 15, 0, 1)
; -> (2000, 30, 0, 2) -> (2000, 60, 0, 4) -> (2000, 120, 0, 8)
; -> (2000, 240, 0 , 16) -> (2000, 480, 0 , 32) -> (2000, 960, 0, 64)
; -> (2000, 1920, 0, 128) -> (2000, 3840, 0, 256) --- FOUND
; (2000 - 1920 = 80, 3840, 0 + (256 / 2), 256) = (80, 3840, 128, 256)
; (bn1 < bn2 - keep going back in divisors until bn1 > bn2).
; -> .... -> (80, 60, 128, 8) FOUND!
; -> (80-60, 60, 128+(8/2), 8) = (20, 60, 132, 8)
; (bn1 < bn2 - keep going back in divisors until bn1 > bn2).
; -> ... -> (20 - 15, 15, 132 + (1 /2), 1) = (5, 15, 132.5, 1)
; (there's a remainder... if we continue we should get 133+1/3)
*/
void div_algorithm(bignum *bn1, bignum *bn2, bignum * divFactor) {
if(div_comparer(bn1, bn2) < 0){
divRemainder = bn1;
divQuotiant = create_result_container(bn1->number_of_digits);
}
else {
bignum * second = clone_bignum(bn2);
bignum * factor = clone_bignum(divFactor);
_add_bignums(factor, divFactor);
_add_bignums(second, bn2);
div_algorithm(bn1, second, factor);
if(div_comparer(divRemainder, bn2) >= 0 ) {
_add_bignums(divQuotiant, divFactor);
_subtract_bignums(divRemainder, bn2);
}
}
}
int div_comparer(bignum * bn1, bignum * bn2) {
resize_numbers(bn1, bn2);
link* bn1_link = bn1->head;
link* bn2_link = bn2->head;
while (bn1_link != 0 && bn1_link->num == bn2_link->num) {
bn1_link = bn1_link->next;
bn2_link = bn2_link->next;
}
if (bn1_link == NULL) {
return 0;
}
return bn1_link->num - bn2_link->num;
}
|
C
|
// -*- tab-width:4 ; indent-tabs-mode:nil -*-
#include <hre/config.h>
#include <stdlib.h>
#include <string.h>
#include <zlib.h>
#include <hre-io/stream_object.h>
#include <hre-io/user.h>
struct stream_s {
struct stream_obj procs;
stream_t s;
int bufsize;
int compress;
z_stream wr;
void *wr_buf;
uint64_t orig_size;
z_stream rd;
void *rd_buf;
};
static void gzip_close_z(stream_t *stream,uint64_t orig_size){
int res;
if ((*stream)->wr_buf) {
do {
if ((*stream)->compress) {
res=deflate(&(*stream)->wr,Z_FINISH);
} else {
res=inflate(&(*stream)->wr,Z_FINISH);
}
if(res!=Z_OK && res!=Z_STREAM_END){
Abort("compression error %d %s",res,zError(res));
}
int len=((*stream)->bufsize) - ((*stream)->wr.avail_out);
if (len>0) {
stream_write((*stream)->s,(*stream)->wr_buf,len);
(*stream)->wr.next_out=(*stream)->wr_buf;
(*stream)->wr.avail_out=(*stream)->bufsize;
}
} while (res!=Z_STREAM_END);
if ((*stream)->compress) {
res=deflateEnd(&(*stream)->wr);
} else {
res=inflateEnd(&(*stream)->wr);
}
switch(res){
case Z_OK: break;
default:
Abort("cleanup failed");
}
RTfree((*stream)->wr_buf);
}
if ((*stream)->rd_buf) {
if ((*stream)->compress) {
res=inflateEnd(&(*stream)->rd);
} else {
res=deflateEnd(&(*stream)->rd);
}
switch(res){
case Z_OK: break;
default:
Abort("cleanup failed");
}
RTfree((*stream)->rd_buf);
}
if (stream_writable(*stream)) {
stream_close_z(&(*stream)->s,orig_size);
} else {
stream_close(&(*stream)->s);
}
RTfree (*stream);
*stream=NULL;
}
static void gzip_close(stream_t *stream){
gzip_close_z(stream,(*stream)->orig_size);
}
static size_t gzip_read_max(stream_t stream,void*buf,size_t count){
stream->rd.next_out=buf;
stream->rd.avail_out=count;
int res;
do {
if (stream->rd.avail_in==0){
stream->rd.next_in=stream->rd_buf;
stream->rd.avail_in=stream_read_max(stream->s,stream->rd_buf,stream->bufsize);
}
if (stream->compress){
res=inflate(&stream->rd, Z_NO_FLUSH);
} else {
res=deflate(&stream->rd, Z_NO_FLUSH);
}
if(res!=Z_OK && res!=Z_STREAM_END){
Abort("compression error %d %s",res,zError(res));
}
} while(stream->rd.avail_out && res!=Z_STREAM_END);
return (count-stream->rd.avail_out);
}
static void gzip_read(stream_t stream,void*buf,size_t count){
size_t res=gzip_read_max(stream,buf,count);
if (res<count) Abort("short read %zu instead of %zu",res,count);
}
static void gzip_write(stream_t stream,void*buf,size_t count){
stream->wr.next_in=buf;
stream->wr.avail_in=count;
stream->orig_size+=count;
while(stream->wr.avail_in){
int res;
if (stream->compress){
res=deflate(&stream->wr,Z_NO_FLUSH);
} else {
res=inflate(&stream->wr,Z_NO_FLUSH);
}
if(res != Z_OK && res!=Z_STREAM_END) {
Abort("compression error %d: %s.",res,zError(res));
}
if (stream->wr.avail_out==0){
stream_write(stream->s,stream->wr_buf,stream->bufsize);
stream->wr.next_out=stream->wr_buf;
stream->wr.avail_out=stream->bufsize;
}
}
stream->wr.next_in=Z_NULL;
}
static stream_t stream_zip(stream_t parent,int compress,int level,int bufsize){
stream_t s=(stream_t)RTmallocZero(sizeof(struct stream_s));
stream_init(s);
s->bufsize=bufsize;
s->s=parent;
s->compress=compress;
if(stream_writable(parent)){
s->procs.write=gzip_write;
//s->procs.flush= TO DO
s->wr.zalloc = Z_NULL;
s->wr.zfree = Z_NULL;
s->wr.opaque = Z_NULL;
s->wr_buf=(char*)RTmalloc(bufsize);
s->wr.next_in=Z_NULL;
s->wr.avail_in=0;
s->wr.next_out=s->wr_buf;
s->wr.avail_out=bufsize;
if (compress) {
if (deflateInit(&s->wr, level)!= Z_OK) {
Abort("gzip init failed");
}
} else {
if (inflateInit(&s->wr)!= Z_OK) {
Abort("gzip init failed");
}
}
} else {
s->wr_buf=NULL;
}
if(stream_readable(parent)){
s->procs.read_max=gzip_read_max;
s->procs.read=gzip_read;
//s->procs.empty= TO DO
s->rd.zalloc = Z_NULL;
s->rd.zfree = Z_NULL;
s->rd.opaque = Z_NULL;
s->rd.next_in=Z_NULL;
s->rd.avail_in=0;
s->rd.next_out=Z_NULL;
s->rd.avail_out=0;
s->rd_buf=(char*)RTmalloc(bufsize);
if (compress) {
if (inflateInit(&s->rd)!= Z_OK) {
Abort("gzip init failed");
}
} else {
if (deflateInit(&s->rd, level)!= Z_OK) {
Abort("gzip init failed");
}
}
} else {
s->rd_buf=NULL;
}
s->procs.close=gzip_close;
s->procs.close_z=gzip_close_z;
return stream_buffer(s,4096);
}
stream_t stream_gzip(stream_t compressed,int level,int bufsize){
return stream_zip(compressed,1,level,bufsize);
}
stream_t stream_gunzip(stream_t expanded,int level,int bufsize){
return stream_zip(expanded,0,level,bufsize);
}
|
C
|
/*!
@file spi.c
@brief This is the source file for the Serial Protocol Interface driver for Kinetis K64.
i.e.,this is the application programming interface(API).
@authors: César Villarreal Hernández, ie707560
José Luis Rodríguez Gutierrez,ie705694
@date 24/03/2019
@TODO: Implement the functions defined below, and write proper comments
to each function.
*/
#include "spi.h"
/*!
@brief This function enables the clock module of the SPI by modifying
the MDIS bits.
@param[in] spi_channel_t
@return static void
*/
static void SPI_enable(spi_channel_t channel)
{
switch(channel)
{
case SPI_0:
/*Enable the module clocks for the SPIO0*/
SPI0->MCR &= ~(SPI_MCR_MDIS_MASK);
break;
case SPI_1:
/*Enable the module clocks for the SPIO1*/
SPI1->MCR &= ~(SPI_MCR_MDIS_MASK);
break;
case SPI_2:
/*Enable the module clocks for the SPIO2*/
SPI2->MCR &= ~(SPI_MCR_MDIS_MASK);
break;
default:
break;
}
}
/*!
@brief This function activates the clock gating for the SPI.
@param[in] spi_channel_t
@return static void
*/
static void SPI_clk(spi_channel_t channel)
{
switch(channel)
{
case SPI_0:
/*Activating clock gate to the SPI0 module*/
SIM->SCGC6 |= SIM_SCGC6_SPI0_MASK;
break;
case SPI_1:
/*Activating clock gate to the SPI1 module*/
SIM->SCGC6 |= SIM_SCGC6_SPI1_MASK;
break;
case SPI_2:
/*Activating clock gate to the SPI2 module*/
SIM->SCGC3 |= SIM_SCGC3_SPI2_MASK;
break;
default:
break;
}
}
/*!
@brief This function configures the SPI as a master or slave depending
on the value of masterOrslave.
@param[in] spi_channel_t
@param[in] spi_master_t
@return static void
*/
static void SPI_set_master(spi_channel_t channel, spi_master_t masterOrSlave)
{
switch (channel)
{
case SPI_0:
if(SPI_SLAVE == masterOrSlave)
SPI0->MCR &= ~(SPI_MCR_MSTR_MASK);
else if(SPI_MASTER == masterOrSlave)
SPI0->MCR |= (SPI_MCR_MSTR_MASK);
break;
case SPI_1:
if (SPI_SLAVE == masterOrSlave)
SPI1->MCR &= ~(SPI_MCR_MSTR_MASK);
else if(SPI_MASTER == masterOrSlave)
SPI1->MCR |= (SPI_MCR_MSTR_MASK);
break;
case SPI_2:
if (SPI_SLAVE == masterOrSlave)
SPI2->MCR &= ~(SPI_MCR_MSTR_MASK);
else if(SPI_MASTER == masterOrSlave)
SPI2->MCR |= (SPI_MCR_MSTR_MASK);
break;
default:
break;
}
}
/*!
@brief This function activates the TX and RX FIFOs of the SPI depending
on the value of enableOrdisable.
@param[in] spi_channel_t
@param[in] spi_enable_fifo_t
@return static void
*/
static void SPI_fifo(spi_channel_t channel, spi_enable_fifo_t enableOrDisable)
{
switch (channel)
{
case SPI_0:
if(SPI_DISABLE_FIFO == enableOrDisable)
{
SPI0->MCR |= (SPI_MCR_DIS_RXF_MASK);
SPI0->MCR |= (SPI_MCR_DIS_TXF_MASK);
}
else if(SPI_ENABLE_FIFO == enableOrDisable)
{
SPI0->MCR &= ~(SPI_MCR_DIS_RXF_MASK);
SPI0->MCR &= ~(SPI_MCR_DIS_TXF_MASK);
}
break;
case SPI_1:
if (SPI_DISABLE_FIFO == enableOrDisable) {
SPI1->MCR |= (SPI_MCR_DIS_RXF_MASK);
SPI1->MCR |= (SPI_MCR_DIS_TXF_MASK);
} else if (SPI_ENABLE_FIFO == enableOrDisable) {
SPI1->MCR &= ~(SPI_MCR_DIS_RXF_MASK);
SPI1->MCR &= ~(SPI_MCR_DIS_TXF_MASK);
}
break;
case SPI_2:
if (SPI_DISABLE_FIFO == enableOrDisable) {
SPI2->MCR |= (SPI_MCR_DIS_RXF_MASK);
SPI2->MCR |= (SPI_MCR_DIS_TXF_MASK);
} else if (SPI_ENABLE_FIFO == enableOrDisable) {
SPI2->MCR &= ~(SPI_MCR_DIS_RXF_MASK);
SPI2->MCR &= ~(SPI_MCR_DIS_TXF_MASK);
}
break;
default:
break;
}
}
/*!
@brief This function selects the clock polarity depending on the
value of cpol.
@param[in] spi_channel_t
@param[in] spi_polarity_t
@return static void
*/
/*!
@brief This function selects the clock polarity depending on the value of cpol; selects the inactive state
of the Serial Communications Clock (SCK).
@note For successful communication between serial devices, the devices must have identical clock polarities.
@param[in] spi_channel_t
@param[in] spi_polarity_t
@return static void
*/
static void SPI_clock_polarity(spi_channel_t channel, spi_polarity_t cpol)
{
switch(channel)
{
case SPI_0:
if (SPI_HIGH_POLARITY == cpol)
{
/** The inactive state value of SCK is high **/
SPI0->CTAR[0] |= (SPI_CTAR_CPOL_MASK);
}
else
{
/** The inactive state value of SCK is low **/
SPI0->CTAR[0] &= ~(SPI_CTAR_CPOL_MASK);
}
break;
case SPI_1:
if (SPI_HIGH_POLARITY == cpol)
{
SPI1->CTAR[0] |= (SPI_CTAR_CPOL_MASK);
}
else
{
SPI1->CTAR[0] &= ~(SPI_CTAR_CPOL_MASK);
}
break;
case SPI_2:
if (SPI_HIGH_POLARITY == cpol)
{
SPI2->CTAR[0] |= (SPI_CTAR_CPOL_MASK);
}
else
{
SPI2->CTAR[0] &= ~(SPI_CTAR_CPOL_MASK);
}
break;
default:
break;
}
}
/*!
@brief This function selects the frame size depending on the value of
frameSize and the macros that are defined above.
@param[in] spi_channel_t
@param[in] uint32_t
@return static void
*/
static void SPI_frame_size(spi_channel_t channel, uint32_t frameSize)
{
/*FMSZ 16bits*/
switch(channel)
{
case SPI_0:
SPI0->CTAR[0] &= ~(SPI_CTAR_FMSZ_MASK);
SPI0->CTAR[0] |= frameSize;
break;
case SPI_1:
SPI1->CTAR[0] &= ~(SPI_CTAR_FMSZ_MASK);
SPI1->CTAR[0] |= frameSize;
break;
case SPI_2:
SPI2->CTAR[0] &= ~(SPI_CTAR_FMSZ_MASK);
SPI2->CTAR[0] |= frameSize;
break;
default:
break;
}
}
/*!
@brief This function selects the clock phase depending on the value of
cpha.
@param[in] spi_channel_t
@param[in] spi_phase_t
@return static void
*/
static void SPI_clock_phase(spi_channel_t channel, spi_phase_t cpha)
{
switch (channel)
{
case SPI_0:
if (SPI_LOW_PHASE == cpha)
SPI0->CTAR[0] &= ~(SPI_CTAR_CPHA_MASK);
else if (SPI_HIGH_PHASE == cpha)
SPI0->CTAR[0] |= (SPI_CTAR_CPHA_MASK);
break;
case SPI_1:
if (SPI_LOW_PHASE == cpha)
SPI1->CTAR[0] &= ~(SPI_CTAR_CPHA_MASK);
else if (SPI_HIGH_PHASE == cpha)
SPI1->CTAR[0] |= (SPI_CTAR_CPHA_MASK);
break;
case SPI_2:
if (SPI_LOW_PHASE == cpha)
SPI2->CTAR[0] &= ~(SPI_CTAR_CPHA_MASK);
else if (SPI_HIGH_PHASE == cpha)
SPI2->CTAR[0] |= (SPI_CTAR_CPHA_MASK);
break;
default:
break;
}
}
/*!
@brief This function selects the baud rate depending on the value of
baudRate and the macros that are defined above.
@param[in] spi_channel_t
@param[in] uint32_t
@return static void
*/
static void SPI_baud_rate(spi_channel_t channel, uint32_t baudRate)
{
switch(channel)
{
case SPI_0:
SPI0->CTAR[0] &= ~(SPI_CTAR_BR_MASK);
SPI0->CTAR[0] |= baudRate;
break;
case SPI_1:
SPI1->CTAR[0] &= ~(SPI_CTAR_BR_MASK);
SPI1->CTAR[0] |= baudRate;
break;
case SPI_2:
SPI2->CTAR[0] &= ~(SPI_CTAR_BR_MASK);
SPI2->CTAR[0] |= baudRate;
break;
}
}
/*!
@brief This function selects if MSB or LSM bits is first transmitted.
@param[in] spi_channel_t
@param[in] uint32_t
@return static void
*/
static void SPI_msb_first(spi_channel_t channel, spi_lsb_or_msb_t msb)
{
switch(channel)
{
case SPI_0:
if(SPI_MSB == msb)
SPI0->CTAR[0] &= ~(SPI_CTAR_LSBFE_MASK);
else if(SPI_LSM == msb)
SPI0->CTAR[0] |= (SPI_CTAR_LSBFE_MASK);
break;
case SPI_1:
if(SPI_MSB == msb)
SPI1->CTAR[0] &= ~(SPI_CTAR_LSBFE_MASK);
else if(SPI_LSM == msb)
SPI1->CTAR[0] |= (SPI_CTAR_LSBFE_MASK);
break;
case SPI_2:
if(SPI_MSB == msb)
SPI2->CTAR[0] &= ~(SPI_CTAR_LSBFE_MASK);
else if(SPI_LSM == msb)
SPI2->CTAR[0] |= (SPI_CTAR_LSBFE_MASK);
break;
}
}
/*!
@brief This function starts the SPI transmission by modifying
the value of HALT bit.
@param[in] spi_channel_t
@return void
*/
void SPI_start_tranference(spi_channel_t channel)
{
switch(channel)
{
case SPI_0:
SPI0->MCR &= ~(SPI_MCR_HALT_MASK);
break;
case SPI_1:
SPI1->MCR &= ~(SPI_MCR_HALT_MASK);
break;
case SPI_2:
SPI2->MCR &= ~(SPI_MCR_HALT_MASK);
break;
}
}
/*!
@brief This function stops the SPI transmission by modifying
the value of HALT bit.
@param[in] spi_channel_t
@return void
*/
void SPI_stop_tranference(spi_channel_t channel)
{
switch (channel) {
case SPI_0:
SPI0->MCR |= (SPI_MCR_HALT_MASK);
break;
case SPI_1:
SPI1->MCR |= (SPI_MCR_HALT_MASK);
break;
case SPI_2:
SPI2->MCR |= (SPI_MCR_HALT_MASK);
break;
}
}
/*!
@brief This function transmits the information contained in data.
@param[in] uint8_t
@return void
*/
void SPI_send_one_byte(uint8_t Data)
{
SPI0->PUSHR = Data;
while(0 == (SPI0->SR & SPI_SR_TCF_MASK));
/*Con esta mascara se escribe un 1 en el SR para limpiar*/
SPI0->SR |= SPI_SR_TCF_MASK;
}
/*!
@brief This function configures the SPI for transmission.
@param[in] pointer to constant (const spi_config_t*)
@return void
*/
void SPI_init(const spi_config_t* SPI_Config)
{
/** Activate clock gating for the SPI **/
SPI_clk(SPI_Config->spi_channel);
/** Activate clock gating for the GPIO **/
GPIO_clock_gating(SPI_Config->spi_gpio_port.gpio_port_name);
GPIO_pin_control_register(SPI_Config->spi_gpio_port.gpio_port_name, SPI_Config->spi_gpio_port.spi_clk, &(SPI_Config->pin_config));
GPIO_pin_control_register(SPI_Config->spi_gpio_port.gpio_port_name, SPI_Config->spi_gpio_port.spi_sout, &(SPI_Config->pin_config));
/** Configure the SPI as master **/
SPI_set_master(SPI_Config->spi_channel,SPI_Config->spi_master);
SPI_fifo(SPI_Config->spi_channel,SPI_Config->spi_enable_fifo);
/** Enable the clock modules of the SPI **/
SPI_enable(SPI_Config->spi_channel);
/* selects the clock polarity depending on the value of cpol.*/
SPI_clock_polarity(SPI_Config->spi_channel, SPI_Config->spi_polarity);
SPI_frame_size(SPI_Config->spi_channel, SPI_Config->spi_frame_size);
SPI_clock_phase(SPI_Config->spi_channel, SPI_Config->spi_phase);
SPI_baud_rate(SPI_Config->spi_channel, SPI_Config->spi_baudrate);
SPI_msb_first(SPI_Config->spi_channel, SPI_Config->spi_lsb_or_msb);
}
|
C
|
#include <stddef.h>
void * memset(void *s, int c, size_t size) {
char * p = s;
while (size--)
*p++ = c;
return s;
}
|
C
|
/* Copyright 2011; All Rights Reserved
* Please see http://www.coactionos.com/license.html for
* licensing information.
*/
/*! \addtogroup MEM Memory (RAM/Flash)
* @{
*
* \ingroup PERIPHIO
*
* \details The flash memory software module allows the user code to read memory
* in the flash program space. Reading the flash is portable across all supported MCU's. However,
* writing the flash is dependent on the MCU page size.
*/
/*! \file
* \brief Flash Memory Header File
*
*/
#ifndef DEV_MEM_H_
#define DEV_MEM_H_
#include <stdint.h>
#include "ioctl.h"
#include "hwpl/arch.h"
#ifdef __cplusplus
extern "C" {
#endif
#define MEM_IOC_IDENT_CHAR 'M'
#ifndef MEM_MIN_FLASH_WRITE_SIZE
/*! \brief This defines the MCU specific value for the
* minimum write size. This is also the minimum step
* and alignment size for writing the flash.
* \hideinitializer
*/
#define MEM_MIN_FLASH_WRITE_SIZE 256
#endif
#ifndef MEM_MAX_FLASH_WRITE_SIZE
/*! \brief This defines the MCU specific value for the
* maximum write size for a flash operation.
* \hideinitializer
*/
#define MEM_MAX_FLASH_WRITE_SIZE 1024
#endif
/*! \brief Holds the devices attributes.
* \details This defines the attributes of the memory.
*
* It is used with \ref I_MEM_GETATTR. The attributes
* are read-only so I_MEM_SETATTR has no effect.
*
*/
typedef struct HWPL_PACK {
uint32_t flash_pages /*! \brief The total number of flash pages */;
uint32_t flash_size /*! \brief The total size of the flash memory */;
uint32_t ram_pages /*! \brief The total number of RAM pages */;
uint32_t ram_size /*! \brief The total size of the RAM */;
} mem_attr_t;
/*! \details This lists each type of page.
*
*/
enum {
MEM_PAGEINFO_TYPE_QUERY /*! Query the page type */,
MEM_PAGEINFO_TYPE_RAM /*! RAM */,
MEM_PAGEINFO_TYPE_FLASH /*! Flash */,
MEM_PAGEINFO_TYPE_TOTAL
};
/*! \brief Holds the characteristics of a page.
* \details This structure contains the details
* for a page of memory.
*/
typedef struct HWPL_PACK {
int32_t num /*! \brief the page number */;
uint8_t type /*! \brief RAM or FLASH (page numbers are not unique between types) */;
uint32_t addr /*! \brief the address of the page */;
uint32_t size /*! \brief the size of the page */;
} mem_pageinfo_t;
typedef struct HWPL_PACK {
uint32_t addr /*! The address to write to */;
uint32_t nbyte /*! The number of bytes to write */;
uint8_t buf[FLASH_MAX_WRITE_SIZE] /*! \brief A buffer for writing to the flash */;
} mem_writepage_t;
/*! \brief This request gets the memory attributes.
* \hideinitializer
*/
#define I_MEM_GETATTR _IOCTLR(MEM_IOC_IDENT_CHAR, I_GLOBAL_GETATTR, mem_attr_t)
#define I_MEM_SETATTR _IOCTLW(MEM_IOC_IDENT_CHAR, I_GLOBAL_SETATTR, mem_attr_t)
#define I_MEM_SETACTION _IOCTLW(MEM_IOC_IDENT_CHAR, I_GLOBAL_SETACTION, mem_attr_t)
/*! \brief See details below.
* \details This request erases the page number specified by the ctl argument.
*
* Example:
* \code
* ioctl(mem_fd, I_MEM_ERASEPAGE, 3); //erase page 3
* \endcode
* \hideinitializer
*
* This function has no effect for pages that are not flash pages.
*
* \hideinitializer
*/
#define I_MEM_ERASEPAGE _IOCTL(MEM_IOC_IDENT_CHAR, I_GLOBAL_TOTAL)
#define I_MEM_ERASE_PAGE I_MEM_ERASEPAGE
/*! \brief See details below.
* \details This request gets the page number for the specified
* address. The ctl argument is the address and the return
* value is the page.
*
* Example:
* \code
* mem_pageinfo_t pageinfo;
* pageinfo.type = MEM_PAGEINO_TYPE_FLASH;
* paginfo.num = 0;
* //This will get the size and address of flash page 0
* ioctl(mem_fd, I_MEM_GET_PAGEINFO, &pageinfo );
* \endcode
*
* Or to lookup based on the address:
*
* \code
* mem_pageinfo_t pageinfo;
* pageinfo.type = MEM_PAGEINFO_TYPE_QUERY;
* paginfo.addr = 0x00001000;
* //This will get the size and address of flash page 0
* ioctl(mem_fd, I_MEM_GETPAGEINFO, &pageinfo );
* \endcode
*
* The \a type, \a num, and \a size parameters will then be populated.
*
* \hideinitializer
*/
#define I_MEM_GETPAGEINFO _IOCTLRW(MEM_IOC_IDENT_CHAR, I_GLOBAL_TOTAL + 1, mem_pageinfo_t)
#define I_MEM_GET_PAGEINFO I_MEM_GETPAGEINFO
/*! \brief See details below
* \details This request writes a page to flash memory.
*
*/
#define I_MEM_WRITEPAGE _IOCTLW(MEM_IOC_IDENT_CHAR, I_GLOBAL_TOTAL + 2, mem_writepage_t)
#define I_MEM_TOTAL 3
#ifdef __cplusplus
}
#endif
#endif // DEV_MEM_H_
/*! @} */
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.