language
large_stringclasses 1
value | text
stringlengths 9
2.95M
|
|---|---|
C
|
/* Author: jburb003
* Partner(s) Name:
* Lab Section:
* Assignment: Lab # Exercise #
* Exercise Description: [optional - include for your own benefit]
*
* I acknowledge all content contained herein, excluding template or example
* code, is my own original work.
*/
#include <avr/io.h>
#ifdef _SIMULATE_
#include "simAVRHeader.h"
#endif
int main(void) {
/* Insert DDR and PORT initializations */
DDRA = 0x00; PORTA = 0xFF;
DDRC = 0xFF; PORTC = 0x00;
//unsigned char cnt = 0;
unsigned char tempA;
/* Insert your solution below */
while (1) {
tempA = PINA & 0xFF; //copies the number on PINA into a variable
if(tempA < 1){
PORTC = 64;
}
else if((tempA <= 2) && (tempA >= 1))
{
PORTC = 32 + 64;
}
else if((tempA >= 3) && (tempA <= 4)){
PORTC= 48 + 64;
}
else if((tempA >= 5) && (tempA <= 6))
{
PORTC = 56;
}
else if((tempA >= 7) && (tempA <= 9))
{
PORTC = 60;
}
else if((tempA >= 10) && (tempA <=12))
{
PORTC = 62;
//then 63
}
else
{
PORTC = 63;
}
}
return 1;
}
|
C
|
// server
#include <argp.h>
#include <netdb.h> // AF_INET, SOCK_STREAM, INADDR_ANY, sockaddr_in
#include <string.h> // bzero(), strlen()
#include <stdio.h> // perror(), printf
#include <stdlib.h> // exit()
#include <fcntl.h> // fcntl()
///////////////////////
///////////////////////
// server
///////////////////////
///////////////////////
/*Message read buffer size and clients arr size*/
static const int BUF_SIZE = 100;
/*The protocol family which will be used for communicatio*/
static const int PROTOCOL = 0;
/*The backlog argument defines the maximum length to which the queue ofpending
* connections for sockfd may grow*/
static const int BACKLOG = 10;
/*Setting the Timeout Value*/
static const int TIMEOUT = 10;
///////////////////////
///////////////////////
// argp
///////////////////////
///////////////////////
/* Program version */
const char* argp_program_version = "Echoserver 0.1";
/* Program bug address */
const char* argp_program_bug_address = "<.com>";
/* Program description. */
static const char argp_program_desc[] = "An Echoserver accepts connection requests from clients on some port. "
"After the connection has been established, the server simply echoes back "
"all the data arriving from the client, until the client disconnects.";
/* The options we understand. */
const static struct argp_option options[] = {
// name, key, argname, flags, doc, group
{ "port", 'p', "PORT", 0, "connection port" },
{ 0 }
};
/* Used by main to communicate with parse_opt. */
struct arguments {
int port;
};
/* Parse a single option. */
static error_t parse_option(int key, char* arg, struct argp_state* state)
{
if (state->argc == 1) {
argp_usage(state);
}
struct arguments* arguments = state->input;
switch (key) {
case 'p':
arguments->port = atoi(arg);
break;
default:
return ARGP_ERR_UNKNOWN;
}
return 0;
}
/* Our argp parser. */
static struct argp argp = { options, parse_option, 0, argp_program_desc };
///////////////////////
///////////////////////
// vector
///////////////////////
///////////////////////
static const int MAX_VECTOR_SIZE = 10000;
static int size = 0; // secret
static int* pVector; // secret
static void createVector()
{
pVector = (int*)malloc(MAX_VECTOR_SIZE * sizeof(int));
}
static int getSizeVector()
{
return size;
}
static int getElemAtVector(int pos)
{
if ((pos < 0) || (pos >= size)) {
perror("Error in getElemVector() \n");
}
return pVector[pos];
}
static void addElemAtVector(int val)
{
if (size == MAX_VECTOR_SIZE) {
perror("Error in addElemAtVector() \n");
}
pVector[size] = val;
size++;
}
static void setElemAtVector(int pos, int val)
{
if ((pos < 0) || (pos >= size)) {
perror("Error in setElemAtVector() \n");
}
pVector[pos] = val;
}
static void delElemAtVector(int pos)
{
if ((pos < 0) || (pos >= size)) {
perror("Error in delElemAtVector() \n");
}
int oldInd = 0;
int newInd = 0;
for (oldInd = 0; oldInd < size; oldInd++) {
if (oldInd != pos) {
pVector[newInd] = pVector[oldInd];
newInd++;
}
}
size--;
}
static int getMaxElemAtVector()
{
int max = 0;
if (size != 0) {
max = pVector[0];
}
else {
return 0;
//perror("Error in getMaxElemAtVector() \n");
}
int i = 0;
for (i = 0; i < size; ++i) {
if (pVector[i] > max) {
max = pVector[i];
}
}
return max;
}
static int _max(int a, int b) { return a > b ? a : b; }
///////////////////////
///////////////////////
int main(int argc, char* argv[])
{
struct arguments arguments;
int err = 0;
argp_parse(&argp, argc, argv, 0, 0, &arguments);
if (err != 0) {
perror("Error in argp_parse() \n");
exit(012);
}
printf("\n Current settings: \n");
printf("-> Input port: %d \n", arguments.port);
int listener = socket(AF_INET, SOCK_STREAM, PROTOCOL);
if (listener < 0) {
perror("Could not create socket \n");
exit(1);
}
else {
printf("-> domain: %d \n", AF_INET);
printf("-> type: %d \n", SOCK_STREAM);
printf("-> protocol: %d \n", PROTOCOL);
printf("-> listener: %d \n", listener);
}
err = fcntl(listener, F_SETFL, O_NONBLOCK);
if (err == -1) {
perror("Error in fcntl() \n");
close(listener);
exit(2345);
}
else {
printf("-> + Successful fcntl \n");
}
struct sockaddr_in addr;
addr.sin_family = AF_INET;
addr.sin_port = htons(arguments.port);
addr.sin_addr.s_addr = INADDR_ANY;
err = bind(listener, (struct sockaddr*)&addr, sizeof(addr));
if (err < 0) {
printf("-> - Port %d is bussy \n", arguments.port);
int port = 0;
int portFound = 0;
for(port = 50000; port <= 55000; port++){
addr.sin_port = htons(port);
err = bind(listener, (struct sockaddr*)&addr, sizeof(addr));
if (err >= 0) {
portFound = 1;
break;
}
}
if(portFound == 1){
arguments.port = port;
printf("-> Port: %d \n", arguments.port);
}
else {
perror("Not fount empty port \n");
close(listener);
exit(2345);
}
}
else {
printf("-> + Successful binding \n");
}
err = listen(listener, BACKLOG);
if (err < 0) {
perror("Could not listen on socket\n");
close(listener);
exit(345);
}
else {
printf("-> + Successful listening \n");
printf("-> backlog: %i \n", BACKLOG);
}
char buf[BUF_SIZE];
int bytes_read = 0;
createVector(MAX_VECTOR_SIZE);
while (1) {
//
fd_set readset;
FD_ZERO(&readset);
FD_SET(listener, &readset);
int ind = 0;
int sizeVec = getSizeVector();
for (ind = 0; ind < sizeVec; ind++) {
FD_SET(getElemAtVector(ind), &readset);
}
//
struct timeval timeout;
timeout.tv_sec = TIMEOUT;
timeout.tv_usec = 0;
//
int mx = _max(listener, getMaxElemAtVector());
/*=========== there is a wait for connection*/
puts("-> ? Waiting for connection");
int count = 0;
count = select(mx + 1, &readset, NULL, NULL, &timeout);
if (count == 0) {
printf("-> - Time out %d sec \n", TIMEOUT);
continue;
}
if (count < 0) {
perror("Error in select() \n");
close(listener);
exit(3);
}
/*=========== there is a detect type of event */
int sock = 0;
if (FD_ISSET(listener, &readset)) {
/*=========== if connection request */
printf("-> + Listener in set\n");
//
sock = accept(listener, NULL, NULL);
if (sock >= FD_SETSIZE) {
perror("fd big size. Err in select()\n");
close(sock);
continue;
}
if (sock < 0) {
perror("Could not establish new connection \n");
close(listener);
exit(3);
}
else {
printf("\n-> + Connected client (listener: %d) (client: %d)\n", listener, sock);
}
err = fcntl(sock, F_SETFL, O_NONBLOCK);
if (err == -1) {
perror("Error in fcntl() \n");
close(listener);
close(sock);
exit(2345);
}
else {
printf("-> + Successful fcntl \n");
}
addElemAtVector(sock);
}
sizeVec = getSizeVector();
for (ind = 0; ind < sizeVec; ind++) {
if (FD_ISSET(getElemAtVector(ind), &readset)) {
/*=========== if have data from the client */
bytes_read = recv(getElemAtVector(ind), buf, BUF_SIZE, 0);
if (bytes_read <= 0) {
/*=========== if disconect */
close(getElemAtVector(ind));
delElemAtVector(ind);
continue;
}
printf("-> (Source: %d / Bytes: %d) :%s \n", sock, bytes_read, buf);
/*=========== send answer */
err = send(getElemAtVector(ind), buf, bytes_read, 0);
if (err == -1){
perror("Error in send() \n");
close(getElemAtVector(ind));
close(listener);
exit(2345);
}
}
}
}
close(listener);
free(pVector);
return 0;
}
|
C
|
#include "shell.h"
/**
* exist - Verify if a file exist
* @pathname: path to the file
* Return: 0 if the file exist or -1 if not
*/
int exist(char *pathname)
{
int exist_stat;
exist_stat = (open(pathname, O_RDONLY));
if (exist_stat != -1)
{
close(exist_stat);
return (0);
}
else
return (-1);
}
|
C
|
/*
VC-1 Elementary Stream converter
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define TRUE 1
#define FALSE 0
#define I 0
#define P 1
#define B 2
#define BI 3
#define SKIPPED 4
#define CONVERT
#define BUFFER_SIZE 0x200000
unsigned int process_chunk(unsigned int length, unsigned int stuffing);
unsigned int stuff_chunk(unsigned int length);
unsigned int strip_chunk(unsigned int length);
void putbits(unsigned int bits, unsigned int *ptr);
unsigned int getbits(unsigned int bits, unsigned int *ptr);
unsigned char chunk_buffer[BUFFER_SIZE];
unsigned char strip_buffer[BUFFER_SIZE];
unsigned char process_buffer[BUFFER_SIZE];
unsigned char output_buffer[BUFFER_SIZE];
unsigned int getbitptr = 0;
unsigned int putbitptr = 0;
unsigned int coded_frames = 0;
typedef size_t (*StreamRead)(void* stream, void* buff, size_t length);
typedef size_t (*StreamWrite)(void* stream, void* buff, size_t length);
void TestLoad(void) {
}
size_t FileStreamRead(void* stream, void* buff, size_t length) {
if(feof((FILE*)stream)) {
return 0;
}
int ret = 0;
while(ret == 0) {
ret = fread(buff, 1, length, (FILE*)stream);
}
return ret;
}
size_t FileStreamWrite(void* stream, void* buff, size_t length) {
return fwrite(buff, 1, length, (FILE*)stream);
}
int VC1ConvRemovePulldownStreamStream(StreamRead inStreamRead, void* inStream, StreamWrite outStreamWrite, void* outStream);
int VC1ConvRemovePulldownFileFile(const char* inFile, const char* outFile) {
FILE *fp, *fpout;
/*--- open binary file (for parsing) ---*/
fp = fopen(inFile, "rb");
if (fp == 0) {
fprintf(stderr, "Cannot open bitstream file <%s>\n", inFile);
return 0;
}
/*--- open binary file (for parsing) ---*/
fpout = fopen(outFile, "wb");
if (fpout == 0) {
fprintf(stderr, "Cannot open bitstream file <%s>\n", outFile);
return 0;
}
int ret = VC1ConvRemovePulldownStreamStream(&FileStreamRead, fp, &FileStreamWrite, fpout);
fclose(fp);
fclose(fpout);
return ret;
}
int VC1ConvRemovePulldownFileStream(const char* inFile, StreamWrite outStreamWrite, void* outStream) {
FILE *fp;
/*--- open binary file (for parsing) ---*/
fp = fopen(inFile, "rb");
if (fp == 0) {
fprintf(stderr, "Cannot open bitstream file <%s>\n", inFile);
return 0;
}
int ret = VC1ConvRemovePulldownStreamStream(&FileStreamRead, fp, outStreamWrite, outStream);
fclose(fp);
return ret;
}
int VC1ConvRemovePulldownStreamFile(StreamRead inStreamRead, void* inStream, const char* outFile) {
FILE *fpout;
/*--- open binary file (for parsing) ---*/
fpout = fopen(outFile, "wb");
if (fpout == 0) {
fprintf(stderr, "Cannot open bitstream file <%s>\n", outFile);
return 0;
}
int ret = VC1ConvRemovePulldownStreamStream(inStreamRead, inStream, &FileStreamWrite, fpout);
fclose(fpout);
return ret;
}
int VC1ConvRemovePulldownStreamStream(StreamRead inStreamRead, void* inStream, StreamWrite outStreamWrite, void* outStream)
{
static unsigned char input_buffer[BUFFER_SIZE];
unsigned int parse = 0xffffffff;
unsigned int xfer = FALSE;
unsigned int i, length, index, strip_length, stuff_length, process_length;
unsigned int first_sequence_input = FALSE;
unsigned int temp_time, hours, minutes;
long double time;
getbitptr = 0;
putbitptr = 0;
coded_frames = 0;
printf("vc1conv VC-1 Elementary Stream Converter 0.4\n");
while((length = inStreamRead(inStream, &input_buffer[0], BUFFER_SIZE)) != 0) {
for(i = 0; i < length; i++) {
parse = (parse << 8) + input_buffer[i];
if (parse == 0x0000010f) {
first_sequence_input = TRUE;
if (xfer == FALSE) {
xfer = TRUE;
index = 0;
chunk_buffer[index++] = (parse >> 24) & 0xff;
chunk_buffer[index++] = (parse >> 16) & 0xff;
chunk_buffer[index++] = (parse >> 8) & 0xff;
}
else {
strip_length = strip_chunk(index - 3);
strip_buffer[strip_length] = 0;
process_length = process_chunk(strip_length, (index - 3 - strip_length));
stuff_length = stuff_chunk(strip_length);
outStreamWrite(outStream, &output_buffer[0], stuff_length);
index = 0;
chunk_buffer[index++] = (parse >> 24) & 0xff;
chunk_buffer[index++] = (parse >> 16) & 0xff;
chunk_buffer[index++] = (parse >> 8) & 0xff;
}
}
else if (parse == 0x0000010d) {
if (first_sequence_input == TRUE) {
if (xfer == FALSE) {
xfer = TRUE;
index = 0;
}
else {
strip_length = strip_chunk(index - 3);
strip_buffer[strip_length] = 0;
process_length = process_chunk(strip_length, (index - 3 - strip_length));
stuff_length = stuff_chunk(strip_length);
outStreamWrite(outStream, &output_buffer[0], stuff_length);
index = 0;
chunk_buffer[index++] = (parse >> 24) & 0xff;
chunk_buffer[index++] = (parse >> 16) & 0xff;
chunk_buffer[index++] = (parse >> 8) & 0xff;
}
}
}
else if (parse == 0x0000010e) {
if (first_sequence_input == TRUE) {
if (xfer == FALSE) {
xfer = TRUE;
index = 0;
}
else {
strip_length = strip_chunk(index - 3);
strip_buffer[strip_length] = 0;
process_length = process_chunk(strip_length, (index - 3 - strip_length));
stuff_length = stuff_chunk(strip_length);
outStreamWrite(outStream, &output_buffer[0], stuff_length);
index = 0;
chunk_buffer[index++] = (parse >> 24) & 0xff;
chunk_buffer[index++] = (parse >> 16) & 0xff;
chunk_buffer[index++] = (parse >> 8) & 0xff;
}
}
}
else if (parse == 0x0000010a) {
if (first_sequence_input == TRUE) {
if (xfer == FALSE) {
xfer = TRUE;
index = 0;
}
else {
strip_length = strip_chunk(index - 3);
strip_buffer[strip_length] = 0;
process_length = process_chunk(strip_length, (index - 3 - strip_length));
stuff_length = stuff_chunk(strip_length);
outStreamWrite(outStream, &output_buffer[0], stuff_length);
index = 0;
first_sequence_input = FALSE;
xfer = FALSE;
}
}
}
if (xfer == TRUE) {
chunk_buffer[index++] = parse & 0xff;
if (index > (BUFFER_SIZE)) {
fprintf(stderr, "Picture bigger than 2 megabytes\n");
exit(-1);
}
}
}
}
time = 1.001/24.0 * (long double)coded_frames;
temp_time = (long double)time;
hours = temp_time / 3600;
temp_time -= hours * 3600;
minutes = temp_time / 60;
temp_time -= minutes * 60;
time -= (long double)((minutes * 60) + (hours * 3600));
printf("\nframes = %d, running time = %d:%d:%f\n", coded_frames, hours, minutes, time);
return 0;
}
unsigned int getbits(unsigned int bits, unsigned int *ptr)
{
static unsigned int mask[33] = {0x0, 0x1, 0x3, 0x7, 0xf,
0x1f, 0x3f, 0x7f, 0xff,
0x1ff, 0x3ff, 0x7ff, 0xfff,
0x1fff, 0x3fff, 0x7fff, 0xffff,
0x1ffff, 0x3ffff, 0x7ffff, 0xfffff,
0x1fffff, 0x3fffff, 0x7fffff, 0xffffff,
0x1ffffff, 0x3ffffff, 0x7ffffff, 0xfffffff,
0x1fffffff, 0x3fffffff, 0x7fffffff, 0xffffffff};
unsigned int temp, index, offset;
if (bits == 0) {
bits = 8 - (getbitptr % 8);
if (bits == 8) {
bits = 0;
}
}
index = getbitptr / 8;
offset = getbitptr % 8;
if (bits > 24) {
temp = (strip_buffer[index++] << 24) & 0xff000000;
temp |= (strip_buffer[index++] << 16) & 0xff0000;
temp |= (strip_buffer[index++] << 8) & 0xff00;
temp |= strip_buffer[index++] & 0xff;
if (offset != 0) {
temp = temp << offset;
temp |= (strip_buffer[index++] >> (8 - offset)) & mask[offset];
}
temp = temp >> (32 - bits);
}
else if (bits > 16) {
temp = (strip_buffer[index++] << 16) & 0xff0000;
temp |= (strip_buffer[index++] << 8) & 0xff00;
temp |= strip_buffer[index++] & 0xff;
if (offset != 0) {
temp = temp << offset;
temp |= (strip_buffer[index++] >> (8 - offset)) & mask[offset];
}
temp = temp >> (24 - bits);
}
else if (bits > 8) {
temp = (strip_buffer[index++] << 8) & 0xff00;
temp |= strip_buffer[index++] & 0xff;
if (offset != 0) {
temp = temp << offset;
temp |= (strip_buffer[index++] >> (8 - offset)) & mask[offset];
}
temp = temp >> (16 - bits);
}
else if (bits > 0) {
temp = strip_buffer[index++] & 0xff;
if (offset != 0) {
temp = temp << offset;
temp |= (strip_buffer[index++] >> (8 - offset)) & mask[offset];
}
temp = temp >> (8 - bits);
}
temp = temp & mask[bits];
getbitptr = getbitptr + bits;
*ptr = temp;
return (bits);
}
void putbits(unsigned int bits, unsigned int *ptr)
{
static unsigned int mask[33] = {0x0, 0x1, 0x3, 0x7, 0xf,
0x1f, 0x3f, 0x7f, 0xff,
0x1ff, 0x3ff, 0x7ff, 0xfff,
0x1fff, 0x3fff, 0x7fff, 0xffff,
0x1ffff, 0x3ffff, 0x7ffff, 0xfffff,
0x1fffff, 0x3fffff, 0x7fffff, 0xffffff,
0x1ffffff, 0x3ffffff, 0x7ffffff, 0xfffffff,
0x1fffffff, 0x3fffffff, 0x7fffffff, 0xffffffff};
unsigned int temp, index, offset, prev, total_bits;
index = putbitptr / 8;
offset = putbitptr % 8;
total_bits = bits + offset;
if (bits > 24) {
if (offset != 0) {
prev = process_buffer[index];
if (total_bits > 32) {
temp = (*ptr << (40 - offset - bits)) | (prev << 32);
}
else {
temp = (*ptr << (32 - offset - bits)) | (prev << 24);
}
}
else {
temp = *ptr << (32 - bits);
}
if (total_bits > 24) {
process_buffer[index++] = (temp >> 32) & 0xff;
process_buffer[index++] = (temp >> 24) & 0xff;
process_buffer[index++] = (temp >> 16) & 0xff;
process_buffer[index++] = (temp >> 8) & 0xff;
process_buffer[index++] = temp & 0xff;
}
else {
process_buffer[index++] = (temp >> 24) & 0xff;
process_buffer[index++] = (temp >> 16) & 0xff;
process_buffer[index++] = (temp >> 8) & 0xff;
process_buffer[index++] = temp & 0xff;
}
}
else if (bits > 16) {
if (offset != 0) {
prev = process_buffer[index];
if (total_bits > 24) {
temp = (*ptr << (32 - offset - bits)) | (prev << 24);
}
else {
temp = (*ptr << (24 - offset - bits)) | (prev << 16);
}
}
else {
temp = *ptr << (24 - bits);
}
if (total_bits > 24) {
process_buffer[index++] = (temp >> 24) & 0xff;
process_buffer[index++] = (temp >> 16) & 0xff;
process_buffer[index++] = (temp >> 8) & 0xff;
process_buffer[index++] = temp & 0xff;
}
else {
process_buffer[index++] = (temp >> 16) & 0xff;
process_buffer[index++] = (temp >> 8) & 0xff;
process_buffer[index++] = temp & 0xff;
}
}
else if (bits > 8) {
if (offset != 0) {
prev = process_buffer[index];
if (total_bits > 16) {
temp = (*ptr << (24 - offset - bits)) | (prev << 16);
}
else {
temp = (*ptr << (16 - offset - bits)) | (prev << 8);
}
}
else {
temp = *ptr << (16 - bits);
}
if (total_bits > 16) {
process_buffer[index++] = (temp >> 16) & 0xff;
process_buffer[index++] = (temp >> 8) & 0xff;
process_buffer[index++] = temp & 0xff;
}
else {
process_buffer[index++] = (temp >> 8) & 0xff;
process_buffer[index++] = temp & 0xff;
}
}
else if (bits > 0) {
if (offset != 0) {
prev = process_buffer[index];
if (total_bits > 8) {
temp = (*ptr << (16 - offset - bits)) | (prev << 8);
}
else {
temp = (*ptr << (8 - offset - bits)) | prev;
}
}
else {
temp = *ptr << (8 - bits);
}
if (total_bits > 8) {
process_buffer[index++] = (temp >> 8) & 0xff;
process_buffer[index++] = temp & 0xff;
}
else {
process_buffer[index++] = temp;
}
}
putbitptr = putbitptr + bits;
}
unsigned int strip_chunk(unsigned int length)
{
unsigned int i, parse = 0xffffffff;
unsigned int bits;
unsigned int index = 0;
for (i = 0; i < length;) {
bits = chunk_buffer[i++];
parse = (parse << 8) + bits;
if ((parse & 0xffffff) == 0x000003) {
bits = chunk_buffer[i++];
parse = (parse << 8) + bits;
if (parse == 0x00000300 || parse == 0x00000301 || parse == 0x00000302 || parse == 0x00000303) {
strip_buffer[index++] = bits;
}
else {
strip_buffer[index++] = 0x3;
strip_buffer[index++] = bits;
}
}
else {
strip_buffer[index++] = bits;
}
}
return (index);
}
unsigned int stuff_chunk(unsigned int length)
{
unsigned int i, parse = 0xffffffff;
unsigned int bits;
unsigned int index = 0;
for (i = 0; i < length;) {
bits = process_buffer[i++];
parse = (parse << 8) + bits;
if ((parse & 0xffffff) == 0x000000) {
output_buffer[index++] = 0x3;
parse = 0xffffff00;
}
else if ((parse & 0xffffff) == 0x000001) {
if (i > 3) {
output_buffer[index++] = 0x3;
}
parse = 0xffffff01;
}
else if ((parse & 0xffffff) == 0x000002) {
output_buffer[index++] = 0x3;
parse = 0xffffff02;
}
else if ((parse & 0xffffff) == 0x000003) {
output_buffer[index++] = 0x3;
parse = 0xffffff03;
}
output_buffer[index++] = bits;
}
return (index);
}
unsigned int process_chunk(unsigned int length, unsigned int stuffing)
{
unsigned int i, j;
static unsigned int parse = 0;
static unsigned int first = TRUE;
static unsigned int first_sequence = FALSE;
static unsigned int first_sequence_dump = FALSE;
static unsigned long sequence_size = 0;
static unsigned long entry_size = 0;
static unsigned int interlace, psf;
static unsigned int tfcntrflag;
static unsigned int ptype;
static unsigned int picture_type;
static long double frame_rate = 1.0;
static long double frameratenr;
static long double frameratedr;
static unsigned int picture_count = 0;
static unsigned int running_average_start = 0;
static unsigned int running_average_count = 0;
static unsigned int running_average_frames = 0;
static unsigned int running_average_samples[1024];
static unsigned int running_average_fields[1024];
static unsigned int video_fields = 0;
static unsigned int running_average_bitrate = 0;
static unsigned int temp_flags;
long double temp_running_average;
long double temp_running_fields;
static unsigned int fcm;
static unsigned int bits, num;
static unsigned int profile, level, format, width, height, pulldown, display, horz, vert;
static unsigned int aspect, framerateind, frameratenr_int, frameratedr_int, framerateexp;
static unsigned int trash, header, panscan, quantizer, ps, zero = 0;
static unsigned int windows, rff, rptfrm, finter, pqindex, one = 1;
getbitptr = 0;
putbitptr = 0;
for (i = 0; i < length; i++) {
num = getbits(8, &bits);
if (first_sequence == TRUE) {
putbits(8, &bits);
}
parse = (parse << 8) + bits;
if (parse == 0x0000010d && i == 3) {
picture_count++;
if (first_sequence == TRUE) {
coded_frames++;
}
if (interlace == 1) {
/* FCM */
num = getbits(1, &fcm);
#ifdef CONVERT
/* delete */
#else
putbits(1, &fcm);
#endif
if (fcm) {
num = getbits(1, &fcm);
#ifdef CONVERT
/* delete */
#else
putbits(1, &fcm);
#endif
fcm = fcm | 0x2;
}
}
/* PTYPE */
num = getbits(1, &ptype);
putbits(1, &ptype);
if (ptype) {
num = getbits(1, &ptype);
putbits(1, &ptype);
if (ptype) {
num = getbits(1, &ptype);
putbits(1, &ptype);
if (ptype) {
num = getbits(1, &ptype);
putbits(1, &ptype);
if (ptype) {
picture_type = SKIPPED;
}
else {
picture_type = BI;
}
}
else {
picture_type = I;
}
}
else {
picture_type = B;
}
}
else {
picture_type = P;
}
if (tfcntrflag) {
/* TFCNTR */
num = getbits(8, &trash);
putbits(8, &trash);
}
#if 0
printf("picture_type = %d\n", picture_type);
#endif
if(pulldown == 1) {
/* RPTFRM, TFF, RFF */
num = getbits(2, &temp_flags);
#ifdef CONVERT
putbits(2, &zero);
#else
putbits(2, &temp_flags);
#endif
if (interlace == 0 || psf == 1) {
rptfrm = temp_flags;
}
else {
rff = temp_flags & 0x1;
}
}
if (panscan) {
/* PS_PRESENT */
num = getbits(1, &ps);
putbits(1, &ps);
if (ps) {
if (interlace == 1 && psf == 0) {
if (pulldown == 1) {
windows = 2 + rff;
}
else {
windows = 2;
}
}
else {
if (pulldown == 1) {
windows = 1 + rptfrm;
}
else {
windows = 1;
}
}
}
for (i = 0; i < windows; i++) {
/* PS_HOFFSET */
num = getbits(18, &trash);
putbits(18, &trash);
/* PS_VOFFSET */
num = getbits(18, &trash);
putbits(18, &trash);
/* PS_WIDTH */
num = getbits(14, &trash);
putbits(14, &trash);
/* PS_HEIGHT */
num = getbits(14, &trash);
putbits(14, &trash);
}
}
if (picture_type != SKIPPED) {
/* RNDCTRL */
num = getbits(1, &trash);
putbits(1, &trash);
if (interlace) {
/* UVSAMP */
num = getbits(1, &trash);
#ifdef CONVERT
/* delete */
#else
putbits(1, &trash);
#endif
}
if (finter) {
/* INTRPFRM */
num = getbits(1, &trash);
putbits(1, &trash);
}
if (picture_type == B) {
/* BFRACTION */
num = getbits(3, &trash);
putbits(3, &trash);
if (trash == 0x7) {
/* BFRACTION */
num = getbits(4, &trash);
putbits(4, &trash);
}
}
/* PQINDEX */
num = getbits(5, &pqindex);
putbits(5, &pqindex);
if (pqindex <= 8) {
/* HALFQP */
num = getbits(1, &trash);
putbits(1, &trash);
}
if (quantizer == 1) {
/* PQUANTIZER */
num = getbits(1, &trash);
putbits(1, &trash);
}
}
if(interlace == 1) {
if(temp_flags & 0x1) {
video_fields += 3;
running_average_fields[running_average_frames] = 3;
}
else {
video_fields += 2;
running_average_fields[running_average_frames] = 2;
}
}
else {
switch(temp_flags & 0x3) {
case 3:
video_fields += 4;
running_average_fields[running_average_frames] = 4;
break;
case 2:
video_fields += 3;
running_average_fields[running_average_frames] = 3;
break;
case 1:
video_fields += 2;
running_average_fields[running_average_frames] = 2;
break;
case 0:
video_fields += 1;
running_average_fields[running_average_frames] = 1;
break;
default:
video_fields += 0;
break;
}
}
if(first == TRUE) {
first = FALSE;
}
#if 0
printf("%8ld\n", (length + stuffing + sequence_size + entry_size) * 8);
#endif
running_average_samples[running_average_frames] = (length + stuffing + sequence_size + entry_size) * 8;
sequence_size = 0;
entry_size = 0;
running_average_frames = (running_average_frames + 1) & 1023;
running_average_count++;
if(running_average_count == 300) {
running_average_count = 299;
temp_running_average = 0;
temp_running_fields = 0.0;
for(j = 0; j < 300; j++) {
temp_running_average += running_average_samples[(running_average_start + j) & 1023];
temp_running_fields += running_average_fields[(running_average_start + j) & 1023];
}
running_average_start = (running_average_start + 1) & 1023;
if(interlace == 1) {
running_average_bitrate = (unsigned int)((temp_running_average / 300.0) * ((600.0 / temp_running_fields) * frame_rate));
}
else {
running_average_bitrate = (unsigned int)((temp_running_average / 300.0) * ((300.0 / temp_running_fields) * frame_rate));
}
printf("bitrate = %9d\r", running_average_bitrate);
}
}
else if (parse == 0x0000010f && i == 3) {
if (first_sequence_dump == FALSE) {
printf("Sequence Header found\n");
}
if (first_sequence == FALSE) {
printf("%d frames before first I-frame\n", picture_count);
header = (parse >> 24) & 0xff;
putbits(8, &header);
header = (parse >> 16) & 0xff;
putbits(8, &header);
header = (parse >> 8) & 0xff;
putbits(8, &header);
header = parse & 0xff;
putbits(8, &header);
first_sequence = TRUE;
}
/* PROFILE */
num = getbits(2, &profile);
putbits(2, &profile);
/* LEVEL */
num = getbits(3, &level);
putbits(3, &level);
/* COLORDIFF_FORMAT */
num = getbits(2, &format);
putbits(2, &format);
/* FRMRTQ_POSTPROC, BITRTQ_POSTPROC */
num = getbits(8, &trash);
putbits(8, &trash);
/* POSTPROCFLAG */
num = getbits(1, &trash);
putbits(1, &trash);
/* MAX_CODED_WIDTH */
num = getbits(12, &width);
putbits(12, &width);
/* MAX_CODED_HEIGHT */
num = getbits(12, &height);
putbits(12, &height);
/* PULLDOWN */
num = getbits(1, &pulldown);
putbits(1, &pulldown);
/* INTERLACE */
num = getbits(1, &interlace);
#ifdef CONVERT
putbits(1, &zero);
#else
putbits(1, &interlace);
#endif
/* TFCNTRFLAG */
num = getbits(1, &tfcntrflag);
putbits(1, &tfcntrflag);
/* FINTERFLAG */
num = getbits(1, &finter);
putbits(1, &finter);
/* RESERVED */
num = getbits(1, &trash);
putbits(1, &trash);
/* PSF */
num = getbits(1, &psf);
putbits(1, &psf);
/* DISPLAY_EXT */
num = getbits(1, &display);
putbits(1, &display);
if (display == 1) {
/* DISPLAY_HORIZ_SIZE */
num = getbits(14, &horz);
putbits(14, &horz);
/* DISPLAY_VERT_SIZE */
num = getbits(14, &vert);
putbits(14, &vert);
/* ASPECT_RATIO_FLAG */
num = getbits(1, &trash);
putbits(1, &trash);
if (trash == 1) {
/* ASPECT_RATIO */
num = getbits(4, &aspect);
putbits(4, &aspect);
if (aspect == 15) {
/* ASPECT_HORIZ_SIZE, ASPECT_VERT_SIZE */
num = getbits(16, &trash);
putbits(16, &trash);
}
}
else {
aspect = 0;
}
/* FRAMERATE_FLAG */
num = getbits(1, &trash);
putbits(1, &trash);
if (trash == 1) {
/* FRAMERATEIND */
num = getbits(1, &framerateind);
putbits(1, &framerateind);
if (framerateind == 0) {
/* FRAMERATENR */
num = getbits(8, &frameratenr_int);
#ifdef CONVERT
putbits(8, &one);
#else
putbits(8, &frameratenr_int);
#endif
/* FRAMERATEDR */
num = getbits(4, &frameratedr_int);
putbits(4, &frameratedr_int);
}
else {
/* FRAMERATEEXP */
num = getbits(16, &framerateexp);
putbits(16, &framerateexp);
}
}
}
if (first_sequence_dump == FALSE) {
if (profile == 3) {
printf("Advanced Profile\n");
}
else {
printf("Reserved Profile\n");
}
if (level > 4) {
printf("Level = Reserved\n");
}
else {
printf("Level = %d\n", level);
}
if (format == 1) {
printf("Chroma Format = 4:2:0\n");
}
else {
printf("Chroma Format = Reserved\n");
}
printf("Horizontal size = %d\n", ((width * 2) + 2));
printf("Vertical size = %d\n", ((height * 2) + 2));
printf("Pulldown = %d\n", pulldown);
printf("Interlace = %d\n", interlace);
if (display) {
printf("Display Horizontal size = %d\n", horz + 1);
printf("Display Vertical size = %d\n", vert + 1);
}
switch (aspect & 0xf) {
case 0:
printf("Aspect ratio = unspecified\n");
break;
case 1:
printf("Aspect ratio = 1:1 (square samples)\n");
break;
case 2:
printf("Aspect ratio = 12:11 (704x576 4:3)\n");
break;
case 3:
printf("Aspect ratio = 10:11 (704x480 4:3)\n");
break;
case 4:
printf("Aspect ratio = 16:11 (704x576 16:9)\n");
break;
case 5:
printf("Aspect ratio = 40:33 (704x480 16:9)\n");
break;
case 6:
printf("Aspect ratio = 24:11 (352x576 4:3)\n");
break;
case 7:
printf("Aspect ratio = 20:11 (352x480 4:3)\n");
break;
case 8:
printf("Aspect ratio = 32:11 (352x576 16:9)\n");
break;
case 9:
printf("Aspect ratio = 80:33 (352x480 16:9)\n");
break;
case 10:
printf("Aspect ratio = 18:11 (480x576 4:3)\n");
break;
case 11:
printf("Aspect ratio = 15:11 (480x480 4:3)\n");
break;
case 12:
printf("Aspect ratio = 64:33 (528x576 16:9)\n");
break;
case 13:
printf("Aspect ratio = 160:99 (528x480 16:9)\n");
break;
case 14:
printf("Aspect ratio = Reserved\n");
break;
case 15:
break;
}
if (framerateind == 0) {
switch (frameratenr_int) {
case 0:
printf("Forbidden Frame Rate!\n");
break;
case 1:
frameratenr = 24000.0;
break;
case 2:
frameratenr = 25000.0;
break;
case 3:
frameratenr = 30000.0;
break;
case 4:
frameratenr = 50000.0;
break;
case 5:
frameratenr = 60000.0;
break;
case 6:
frameratenr = 48000.0;
break;
case 7:
frameratenr = 72000.0;
break;
default:
printf("Reserved Frame Rate!\n");
break;
}
switch (frameratedr_int) {
case 0:
printf("Forbidden Frame Rate!\n");
break;
case 1:
frameratedr = 1000.0;
break;
case 2:
frameratedr = 1001.0;
break;
default:
printf("Reserved Frame Rate!\n");
break;
}
frame_rate = frameratenr / frameratedr;
printf("Frame Rate = %.3f\n", frame_rate);
}
else {
frame_rate = ((long double)(framerateexp + 1)) / 32.0;
printf("Frame Rate = %.3f\n", frame_rate);
}
first_sequence_dump = TRUE;
}
if (first == FALSE) {
sequence_size = length + stuffing;
}
}
else if (parse == 0x0000010e && i == 3) {
/* BROKEN LINK, CLOSED_ENTRY */
num = getbits(2, &trash);
putbits(2, &trash);
/* PANSCAN_FLAG */
num = getbits(1, &panscan);
putbits(1, &panscan);
/* REFDIST_FLAG, LOOPFILTER, FASTUVMC, EXTENDED_MV, DQUANT, VTRANSFORM, OVERLAP */
num = getbits(8, &trash);
putbits(8, &trash);
/* QUANTIZER */
num = getbits(2, &quantizer);
putbits(2, &quantizer);
if (first == FALSE) {
entry_size = length + stuffing;
}
}
}
num = getbits(0, &trash);
putbits(num, &trash);
return (0);
}
/*
int main() {
VC1ConvRemovePulldownFileFile("/home/john/Videos/Main_Movie_t01.vc1", "test.vc1");
return 0;
}
*/
|
C
|
/**
* @file
* Factory reset button monitor file
* Created on: 28-Nov-2018
* Author: einfochips
* Copyright(C) 2019 eInfochips All rights reserved.
*
*/
#include "factory-reset-monitor.h"
Button factory_reset = { .Button_status = BUTTON_IDLE , .Button_Hold_timeout = false};
/**
* Get current time in seconds
*
* @param None
* @return Seconds
*/
long current_time()
{
struct timespec spec;
clock_gettime(CLOCK_REALTIME, &spec);
return spec.tv_sec; //seconds
}
/**
* Grab and immediately ungrab the device.
*
* @param fd The file descriptor to the device.
* @return 0 if the grab was successful, or 1 otherwise.
*/
static int test_grab(int fd, int grab_flag)
{
int rc;
rc = ioctl(fd, EVIOCGRAB, (void*)1);
if (rc == 0 && !grab_flag)
ioctl(fd, EVIOCGRAB, (void*)0);
return rc;
}
/**
*
* Function to monitor button events
*
*/
static int monitor_events(int fd, struct mosquitto *mosq)
{
struct input_event ev[64];
int i, rd;
bool event_notify = false;
fd_set rdfs;
FD_ZERO(&rdfs);
FD_SET(fd, &rdfs);
while (!stop)
{
select(fd + 1, &rdfs, NULL, NULL, NULL);
if (stop)
break;
rd = read(fd, ev, sizeof(ev));
if (rd < (int) sizeof(struct input_event)) {
printf("expected %d bytes, got %d\n", (int) sizeof(struct input_event), rd);
perror("\nerror reading");
return 1;
}
for (i = 0; i < rd / sizeof(struct input_event); i++) {
unsigned int code, value;
unsigned long timeout;
code = ev[i].code;
value= ev[i].value;
if(code == FACTORY_RESET_BUTTON)
{
if(value == factory_reset.Button_status) {
timeout = current_time();
if( (timeout - factory_reset.Button_Hold_start_time) > TIMEOUT_SEC ) {
factory_reset.Button_Hold_timeout = true;
}
break;
}
switch(value) {
case BUTTON_RELEASED:
event_notify = false;
factory_reset.Button_status = BUTTON_RELEASED;
factory_reset.Button_Hold_timeout = false;
factory_reset.Button_Hold_start_time = 0;
break;
case BUTTON_PRESS:
factory_reset.Button_status = BUTTON_PRESS;
break;
case BUTTON_HOLD:
factory_reset.Button_status = BUTTON_HOLD;
factory_reset.Button_Hold_start_time = current_time();
break;
}
}
}
if(factory_reset.Button_Hold_timeout && !event_notify)
{
event_notify = true;
factory_reset.Button_Hold_start_time = 0;
factory_button_longPress_detected(mosq);
}
}
return 0;
}
/**
*
* Function to start monitor of button events
*
*/
int monitor_button(const char *device, int grab_flag, struct mosquitto *mosq)
{
int fd;
char *filename = NULL;
filename = strdup(device);
if (!filename)
return EXIT_FAILURE;
if ((fd = open(filename, O_RDONLY)) < 0) {
if (errno == EACCES && getuid() != 0)
fprintf(stderr, "You do not have access to %s. Try "
"running as root instead.\n",
filename);
goto error;
}
if (!isatty(fileno(stdout)))
setbuf(stdout, NULL);
logButtonInfo("Button Monitoring started");
if (test_grab(fd, grab_flag))
{
printf("***********************************************\n");
printf(" This device is grabbed by another process.\n");
printf(" No events are available to this applicaton while the\n"
" other grab is active.\n");
printf("***********************************************\n");
}
free(filename);
return monitor_events(fd, mosq);
error:
free(filename);
return EXIT_FAILURE;
}
/**
*
* Function to find event number for gpio events
*
*/
int find_event_num(char * name)
{
int i = 0 , ret = 0 , fd = -1;
char filename[MAX_STR_BUF_SIZE];
char value[MAX_STR_BUF_SIZE];
int bytes = 0;
int found_index = -1;
CLEAR(filename);
CLEAR(value);
/*
* Iterate over all /sys/class/input/eventX/device/name,
* get name of each device and match with "gpio_keys".
*
* If not matched, then module probe is failed due to some reason and
* device is not present.
*/
for(i = 0; ; i++) {
/* prepare file name */
sprintf(filename, "/sys/class/input/event%d/device/name", i);
fd = open(filename, O_RDONLY);
if (fd < 0) {
sprintf(value, "couldn't open %s", filename);
perror(value);
ret = fd;
break;
}
ret = read(fd, value, MAX_STR_BUF_SIZE);
if (ret < 0) {
sprintf(value, "couldn't read from %s", filename);
perror(value);
}
value[ret - 1] = '\0';
close(fd);
/* compare with device name */
if ( !strcmp(value, name) ) {
/* match found */
found_index = i;
break;
}
}
return found_index;
}
/**
*
* Thread function
*
*/
void* monitorFactoryReset(void *args)
{
logButtonInfo("Monitor Factory reset thread started\n");
int ret = 0;
char device[MAX_STR_BUF_SIZE];
struct mosquitto *mosq = (struct mosquitto *)args;
ret = find_event_num("gpio_keys");
if(ret < 0)
{
logButtonInfo("Error : gpio_keys event not found : %d.\n",ret);
return NULL;
}
sprintf(device, "/dev/input/event%d", ret);
ret = monitor_button(device, grab_flag, mosq);
if(ret < 0)
{
logButtonInfo("Error : Button monitor failed : %d.\n",ret);
}
return NULL;
}
|
C
|
/**
* Implement an iterator over a binary search tree (BST). Your iterator will be
* initialized with the root node of a BST. Calling next() will return the next
* smallest number in the BST.
*
* Note: next() and hasNext() should run in average O(1) time and uses O(h)
* memory, where h is the height of the tree.
*
* 要求实现一个二叉查找树迭代器,这个迭代器有两个方法:
* 1. hasNext(): 是否存在下一个最小的元素.
* 2. next(): 返回下一个最小的元素的值.
* 这两个方法的时间复杂度都是O(1),空间复杂度是O(h),其中h为树的高度.
* 如果空间复杂度没有限制,我们可以用一个数组来保存BST中序遍历的结果,迭代器内部用一个
* 指针指向该数组的头部即可.
*/
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
struct BSTIterator {
int *elem;
int curr;
int size;
};
#define BUFFSIZE 1024
void traversal(struct TreeNode *root, int **elem, int *size) {
if (!root)
return;
traversal(root->left, elem, size);
if (*size % BUFFSIZE == 0)
*elem = realloc(*elem, (*size + BUFFSIZE) * sizeof(int));
(*elem)[(*size)++] = root->val;
traversal(root->right, elem, size);
}
struct BSTIterator *bstIteratorCreate(struct TreeNode *root) {
struct BSTIterator *iter;
iter = malloc(sizeof(struct BSTIterator));
iter->elem = NULL;
iter->size = 0;
iter->curr = 0;
traversal(root, &iter->elem, &iter->size);
return iter;
}
/** @return whether we have a next smallest number */
bool bstIteratorHasNext(struct BSTIterator *iter) {
return iter->curr < iter->size;
}
/** @return the next smallest number */
int bstIteratorNext(struct BSTIterator *iter) {
return iter->elem[iter->curr++];
}
/** Deallocates memory previously allocated for the iterator */
void bstIteratorFree(struct BSTIterator *iter) {
if (iter) {
free(iter->elem);
free(iter);
}
}
/**
* Your BSTIterator will be called like this:
* struct BSTIterator *i = bstIteratorCreate(root);
* while (bstIteratorHasNext(i)) printf("%d\n", bstIteratorNext(i));
* bstIteratorFree(i);
*/
/**
* 上述做法用了O(n)的空间来保存BST中的每个元素.
* 其实这个问题本质上是对BST进行中序遍历,既然此题要求空间复杂度是O(h),那就只能
* 存储指针,如果借助threaded binary tree的思路,我们要保存每个叶子节点的指针,对
* 于一棵高度为h的二叉树而言,其叶子节点个数为2^(h-1),也不符合题目要求.
*
* 上面的解法在中序遍历时利用了递归,也就是借用了系统的栈,算法的空间复杂度是O(h).
* 我们也可以用一个大小为h的栈来解决问题,初始时栈中的元素为BST的最左路径上的节点
* 的指针,栈顶元素为BST中最小的元素.
* 1. 若栈非空,则hashNext()为真.
* 2. next()返回栈顶元素
* 在每个元素出栈时,判断其右孩子是否为空,若非空则找到右子树中最小的元素.
*/
typedef struct {
struct TreeNode **array;
int size;
int top;
} Stack;
Stack *
stackCreate(int size) {
Stack *s;
s = malloc(sizeof(Stack));
s->top = -1;
s->size = size;
s->array = malloc(size * sizeof(struct TreeNode *));
return s;
}
void
stackFree(Stack *s) {
if (s) {
free(s->array);
free(s);
}
}
bool
stackEmpty(Stack *s) {
return s->top == -1;
}
void
stackPush(Stack *s, struct TreeNode *node) {
if (s->top == s->size - 1) {
s->size <<= 1;
s->array = realloc(s->array, s->size * sizeof(struct TreeNode *));
}
s->array[++s->top] = node;
}
struct TreeNode *
stackPop(Stack *s) {
return s->array[s->top--];
}
struct BSTIterator {
Stack *s;
};
void
find_left(Stack *s, struct TreeNode *root) {
while (root) {
stackPush(s, root);
root = root->left;
}
}
struct BSTIterator *bstIteratorCreate(struct TreeNode *root) {
struct BSTIterator *iter;
struct TreeNode *node = root;
int height = 0;
iter = malloc(sizeof(struct BSTIterator));
iter->s = stackCreate(1024);
find_left(iter->s, root);
return iter;
}
/** @return whether we have a next smallest number */
bool bstIteratorHasNext(struct BSTIterator *iter) {
return !stackEmpty(iter->s);
}
/** @return the next smallest number */
int bstIteratorNext(struct BSTIterator *iter) {
struct TreeNode *node;
node = stackPop(iter->s);
/**
* next()方法调用了find_left寻找下一个最小元素,对于单次next()调用
* 时间复杂度不是O(1),但从整体上来看,每个节点在遍历的过程中只会访问
* 一次,故总体而言,平均时间复杂度是O(1).
*/
find_left(iter->s, node->right);
return node->val;
}
/** Deallocates memory previously allocated for the iterator */
void bstIteratorFree(struct BSTIterator *iter) {
if (iter) {
stackFree(iter->s);
free(iter);
}
}
|
C
|
#include <string.h>
/*
* coy char s2[max n] to end of s1[]
*/
char * Strncat(char *s1, const char *s2, size_t n) {
char *s;
for (s = s1; *s != '\0'; ++s)
;
for (; 0 < n && *s2 != '\0'; --n)
*s++ = *s2++;
*s = '\0';
return (s1);
}
|
C
|
#include "main.h"
#include "calcengine.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// ****************************************************************************
// Function that will load the weights from the data file for any specific day
// ****************************************************************************
int fnLoadWeights( void )
{
// Function Removed and no longer in use - left for backwards compatability
return TRUE;
}
int fnStockCompare( const void* p1, const void* p2 )
{
return strcmp( (char *)p1, (char *)p2 );
}
// *****************************************************************************
// Function to load the stock watch list into memory
// *****************************************************************************
int fnLoadStocks( void )
{
char szBuffer[LINE_BUFFER_SIZE];
char szListFile[BUFFER_SIZE];
char szStock[BUFFER_SIZE];
int iStockCount=0;
int iSkip=FALSE;
FILE *fpListFile;
int i;
//char szDate[BUFFER_SIZE];
//int iBufferSize=0;
//struct tm *tLocalTime;
//time_t tTime;
fnDebug( "Loading Stock List" );
// Get the list file from the config
pthread_mutex_lock( &config_mutex );
fnGetConfigSetting( szListFile, "STOCKLISTFILE", DEFAULT_STOCK_LIST );
pthread_mutex_unlock( &config_mutex );
fpListFile = fopen( szListFile, "r" );
if( fpListFile == NULL )
return 0;
while ( fgets(szBuffer, LINE_BUFFER_SIZE-2, fpListFile) != NULL)
{
bzero( szStock, sizeof(szStock) );
strcpy( szStock, szBuffer );
// Remove any trailing CR/LF and replace any . with a 0x00
if( szStock[strlen(szStock)-1] == 0x0A || szStock[strlen(szStock)-1] == 0x0D )
szStock[strlen(szStock)-1] = 0x00;
// Check if this stock has already been loaded
iSkip=FALSE;
for( i=0; i<iStockCount; i++ )
{
if( strcmp( szStock, gszStocks[i] ) == 0 )
{
iSkip=TRUE;
break;
}
}
if( iSkip )
{
// Duplicate stock found - don't add this
snprintf( szBuffer, sizeof(szBuffer), "Skipping duplicate %s", szStock );
fnDebug( szBuffer );
}
else
{
// New stock found - add to list
strcpy( gszStocks[iStockCount], szStock );
snprintf( szBuffer, sizeof(szBuffer), "%d Loaded stock %s", iStockCount, gszStocks[iStockCount] );
fnDebug( szBuffer );
iStockCount++;
if (iStockCount == MAXIMUM_STOCKS )
{
fnHandleError( "fnLoadStocks", "Maximum stocks reached" );
break;
}
}
}
fclose(fpListFile);
iStocksLoaded = iStockCount;
QQQQ = fnStockFilter( "QQQQ" );
if( QQQQ == STOCK_NOT_FOUND )
fnHandleError( "fnLoadStocks", "QQQQ Index tracking stock not found" );
else
{
snprintf( szBuffer, sizeof(szBuffer), "Found QQQQ Index tracking Stock %d", QQQQ );
fnDebug( szBuffer );
}
//qsort ( gszStocks, iStockCount, sizeof(gszStocks[0]), fnStockCompare );
snprintf( szBuffer, sizeof(szBuffer), "%i stocks loaded", iStockCount );
fnDebug( szBuffer );
return iStockCount;
}
// ****************************************************************************
// Function to load the divisor for the index calculation
// ****************************************************************************
double fnLoadDivisor( void )
{
// Function Removed and no longer in use - left for backwards compatability
return 0.00;
}
// ****************************************************************************
// Stock Filter: fnStockFilter( Stock Name )
// Return the index # of the located stock
// Return STOCK_NOT_FOUND ( -1 ) if no match is found
// ****************************************************************************
int fnStockFilter( char * szStock )
{
int i;
for( i=0; i<iStocksLoaded; i++ )
if( strcmp( szStock, gszStocks[i] ) == 0 )
return i;
return STOCK_NOT_FOUND;
}
// ****************************************************************************
// Function to recalcuation the NASDAQ 100 indexes - 3 indexes are kept up to date:
// The actual index, and the indexes based on the bid and ask prices
// The Bid/Ask index value was added to generate additional complexity
// ****************************************************************************
int fnCalculateIndex( void )
{
// Function Removed and no longer in use - left for backwards compatability
return TRUE;
}
// ****************************************************************************
// Function to recalcuation the NASDAQ 100 indexes - 3 indexes are kept up to date:
// The actual index, and the indexes based on the bid and ask prices
// The Bid/Ask index value was added to generate additional complexity
// ****************************************************************************
int fnCalculateBidAskIndex( void )
{
// Function Removed and no longer in use - left for backwards compatability
return TRUE;
}
//-----------------------------------------------------------------------------
// This function will recalculate all the FV's when there is a change
//-----------------------------------------------------------------------------
void fnCalculateFV( void )
{
// Function Removed and no longer in use - left for backwards compatability
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#define MAX 46340
int mySqrt(int x)
{
int mid;
int low;
int high;
low = 0;
high = x;
mid = (low+high)/2;
if(mid>=MAX)
{
high = MAX;
}
mid = (low+high)/2;
while(mid*mid!=x && low < high)
{
if(mid*mid>x)
{
high = mid - 1;
}
if(mid*mid<x)
{
low = mid + 1;
}
mid = (low+high)/2;
}
if(mid*mid==x)
{
return mid;
}
if(mid*mid>x)
{
mid = mid - 1;
}
return mid;
}
void main()
{
int x;
int result;
x = 4;
result = mySqrt(x);
printf("%d", result);
}
|
C
|
#include <stdio.h>
#pragma warning (disable:4996)
// Ʒ Global Scope struct Ÿ ÿ ϴ
// ϳ, ÿ ش DZ
// ȭ α ۼϴ Ģ 谡 Ƿ Ϲ ʴ.
struct point{
int xpos;
int ypos;
} pos1, pos2, pos3;
void main() {
// ü Ʒ Լ ο ϴ ϴ.
// Ϲ ʴ.
// ֳϸ ش Ÿ Լο ϰڴٴ ǵ̱ ̴.
// ش Ÿ ٸ Լ .
struct point{
int xpos;
int ypos;
};
// struct Ÿ Լ ο ִ.
// ٸ ܺ ̸ 쿡 ϰ
// ȴ.
struct point pos1;
pos1.xpos = 1;
pos2.ypos = 2;
printf("END\n");
}
|
C
|
#include "semantic.h"
#include "intercode.h"
char msg[100];
FieldList hashTable[HASH_SIZE];
object *getChild(object *root, int i) {
object *ret = root->child;
while (i--) ret = ret->next;
return ret;
}
int countChild(object *root) {
int count = 0;
object *foo = root->child;
for (; foo != NULL; foo = foo->next, count++);
return count;
}
unsigned int hashFunc(char *name) {
unsigned int val = 0, i;
for (; *name; ++name) {
val = (val << 2u) + *name;
if ((i = val & ~HASH_SIZE)) val = (val ^ (i >> 12u)) & HASH_SIZE;
}
return val;
}
void initHashTable() {
int i;
for (i = 0; i < HASH_SIZE; i++);
hashTable[i] = NULL;
Type returnReadType = malloc(sizeof(Type_));
returnReadType->kind = KBASIC;
returnReadType->basic_ = _INT;
Type readType = malloc(sizeof(Type_));
readType->kind = KFUNC;
readType->func_.funcType = returnReadType;
readType->func_.paramNum = 0;
readType->func_.params = NULL;
FieldList readField = malloc(sizeof(FieldList_));
readField->name = "read";
readField->type = readType;
readField->isArg = false;
insertSymbol(readField);
Type returnWriteType = malloc(sizeof(Type_));
returnWriteType->kind = KBASIC;
returnWriteType->basic_ = _INT;
Type writeParamType = malloc(sizeof(Type_));
writeParamType->kind = KBASIC;
writeParamType->basic_ = _INT;
FieldList writeParamField = malloc(sizeof(FieldList_));
writeParamField->name = "dest";
writeParamField->type = writeParamType;
writeParamField->isArg = true;
writeParamField->tail = NULL;
Type writeType = malloc(sizeof(Type_));
writeType->kind = KFUNC;
writeType->func_.funcType = returnWriteType;
writeType->func_.paramNum = 1;
writeType->func_.params = writeParamField;
FieldList writeField = malloc(sizeof(FieldList_));
writeField->name = "write";
writeField->type = writeType;
writeField->isArg = false;
insertSymbol(writeField);
}
bool insertSymbol(FieldList field) {
unsigned int key;
if (field == NULL) return 0;
if (field->name == NULL) return 0;
if (field->type->kind == KFUNC) {
char funcName[128];
funcName[0] = '0';
strcpy(funcName + 1, field->name);
key = hashFunc(funcName);
} else
key = hashFunc(field->name);
while (1) {
if (hashTable[key] == NULL) {
hashTable[key] = field;
return true;
}
key++;
key = key % HASH_SIZE;
}
}
FieldList findSymbol(char *name, bool isFunc) {
unsigned key;
if (name == NULL) return NULL;
if (isFunc) {
char funcName[128];
funcName[0] = '0';
strcpy(funcName + 1, name);
key = hashFunc(funcName);
} else {
key = hashFunc(name);
}
FieldList field = hashTable[key];
while (field != NULL) {
if (strcmp(name, field->name) == 0) {
if (isFunc && field->type->kind == KFUNC) return field;
if (!isFunc && field->type->kind != KFUNC) return field;
}
key++;
key = key % HASH_SIZE;
field = hashTable[key];
}
return NULL;
}
bool isTypeEqual(Type p1, Type p2) {
if (p1 == NULL || p2 == NULL) return false;
if (p1->kind != p2->kind) return false;
switch (p1->kind) {
case KBASIC: {
return (p1->basic_ == p2->basic_);
}
case KARRAY: {
return (isTypeEqual(p1->array_.type, p2->array_.type));
}
case KSTRUCT: {
FieldList f1 = p1->struct_, f2 = p2->struct_;
if (f1 != NULL && f2 != NULL) {
while (f1 != NULL && f2 != NULL) {
if (!isTypeEqual(f1->type, f2->type)) return false;
f1 = f1->tail;
f2 = f2->tail;
}
if (f1 == NULL && f2 == NULL) return true;
}
return false;
}
case KFUNC: {
if (p1->func_.paramNum != p2->func_.paramNum) return false;
FieldList param1 = p1->func_.params, param2 = p2->func_.params;
for (int i = 0; i < p1->func_.paramNum; i++) {
if (!isTypeEqual(param1->type, param2->type)) return false;
param1 = param1->tail;
param2 = param2->tail;
}
return true;
}
default: { return false; }
}
}
/*
VarDec : ID {_ac(1);}
| VarDec LB INT RB {_ac(4);}
;
*/
FieldList goVarDec(object *root, Type type) {
object *tmp = root;
int i = 0;
while (tmp->child->type != TID) {
tmp = tmp->child;
i++;
}
char *idName = tmp->child->vstr;
FieldList field = malloc(sizeof(FieldList_));
field->isArg = false;
field->name = idName;
switch (i) {
// e.g. a
case 0: {
field->type = type;
return field;
}
// e.g. a[1]
case 1: {
Type var = malloc(sizeof(Type_));
var->kind = KARRAY;
// var->array_.size = root->child->next->next->vint;
var->array_.size = getChild(root, 2)->vint;
var->array_.type = type;
field->type = var;
return field;
}
// e.g. a[1][2]
case 2: {
Type inner = malloc(sizeof(Type_)),
outer = malloc(sizeof(Type_));
inner->kind = KARRAY;
// inner->array_.size = root->child->next->next->vint;
inner->array_.size = getChild(root, 2)->vint;
inner->array_.type = type;
outer->kind = KARRAY;
// outer->array_.size = root->child->child->next->next->vint;
outer->array_.size = getChild(getChild(root, 0), 2)->vint;
outer->array_.type = inner;
field->type = outer;
return field;
}
default: {
printf("error in goVarDec case %d.\n", i);
return NULL;
}
}
}
/*
Specifier : TYPE {_ac(1);}
| StructSpecifier {_ac(1);}
;
StructSpecifier : STRUCT OptTag LC DefList RC {_ac(5);}
| STRUCT Tag {_ac(2);}
;
*/
Type goSpecifier(object *root) {
Type foo = malloc(sizeof(Type_));
// Specifier: TYPE
if (root->child->type == TTYPE) {
foo->kind = KBASIC;
if (!strcmp(root->child->vstr, "int"))
foo->basic_ = _INT;
else
foo->basic_ = _FLOAT;
return foo;
}
// Specifier: StructSpecifier
foo->kind = KSTRUCT;
object *structSpecifier = getChild(root, 0);
if (countChild(getChild(root, 0)) == 2) { // STRUCT Tag
char *idName = getChild(getChild(structSpecifier, 1), 0)->vstr;
FieldList field = findSymbol(idName, false);
if (field == NULL) { ;
sprintf(msg, "Undefined structure \"%s\".", idName);
sem_error(17, root->fl, msg);
foo->struct_ = NULL;
return foo;
} else if (field->type != NULL) {
return field->type;
} else {
foo->struct_ = NULL;
return foo;
}
} else { // StructSpecifier : STRUCT OptTag LC DefList RC
object *defList = getChild(structSpecifier, 3);
while (defList->type != TNUL) { // DefList : Def DefList
object *def = getChild(defList, 0); // Def : Specifier DecList SEMI
Type basicType = goSpecifier(getChild(def, 0));
object *decList = getChild(def, 1);
while (decList->type != TNUL) { // DecList: Dec COMMA DecList
// Dec : VarDec
FieldList field =
goVarDec(getChild(getChild(decList, 0), 0), basicType);
if (countChild(getChild(decList, 0)) != 1) { ;
sprintf(msg, "Variable %s in struct is initialized.", field->name);
sem_error(15, def->fl, msg);
}
if (findSymbol(field->name, false) != NULL) { ;
sprintf(msg, "Redefined variable \"%s\".", field->name);
sem_error(3, def->fl, msg);
} else {
insertSymbol(field);
field->tail = foo->struct_;
foo->struct_ = field;
}
if (countChild(decList) == 3)
decList = getChild(decList, 2);
else
break;
}
defList = getChild(defList, 1);
} // StructSpecifier : STRUCT OptTag LC DefList RC
if (getChild(structSpecifier, 1)->type != TNUL) {
// OptTag : ID | ;
FieldList field = malloc(sizeof(FieldList_));
field->isArg = false;
field->type = foo;
field->name = getChild(getChild(structSpecifier, 1), 0)->vstr;
if (findSymbol(field->name, false) != NULL) { ;
sprintf(msg, "Duplicated name \"%s\".", field->name);
sem_error(16, root->fl, msg);
} else {
insertSymbol(field);
}
}
return foo;
}
}
/*
ExtDefList : ExtDef ExtDefList | ;
ExtDef : Specifier ExtDecList SEMI
| Specifier SEMI
| Specifier FunDec CompSt
*/
void goExtDefList(object *root) {
object *extDefList = root;
while (countChild(extDefList) != 0) {
object *extDef = getChild(extDefList, 0);
Type basicType = goSpecifier(getChild(extDef, 0));
if (!strcmp(getChild(extDef, 1)->vstr, "ExtDecList")) {
// ExtDecList : VarDec
// | VarDec COMMA ExtDecList;
object *extDecList = getChild(extDefList, 1);
while (extDecList != NULL) {
FieldList field = goVarDec(getChild(extDecList, 0), basicType);
if (findSymbol(field->name, false) != NULL) {
sprintf(msg, "Redefined variable \"%s\".", field->name);
sem_error(3, extDef->fl, msg);
} else {
insertSymbol(field);
}
if (countChild(extDecList) == 3)
extDecList = getChild(extDecList, 2);
else
break;
}
} else if (!strcmp(getChild(extDef, 1)->vstr, "FunDec")) {
// FunDec : ID LP VarList RP
// | ID LP RP;
object *funDec = getChild(extDef, 1);
FieldList field = malloc(sizeof(FieldList_));
field->isArg = false;
field->name = getChild(funDec, 0)->vstr;
Type type = malloc(sizeof(Type_));
type->kind = KFUNC;
type->func_.funcType = basicType;
type->func_.paramNum = 0;
type->func_.params = NULL;
// insert code begin
Operand funcOperand = genOperandStr(oFunction, field->name);
InterCode funcInterCode = genInterCodeUnary(iFunction, funcOperand);
appendCode(funcInterCode);
// end
if (countChild(funDec) == 4) {
object *varList = getChild(funDec, 2);
// VarList : ParamDec COMMA VarList
// | ParamDec;
// ParamDec : Specifier VarDec;
while (varList != NULL) {
Type varType = goSpecifier(getChild(getChild(varList, 0), 0));
FieldList varField =
goVarDec(getChild(getChild(varList, 0), 1), varType);
if (findSymbol(varField->name, false) != NULL) {
sprintf(msg, "Redefined variable \"%s\".", varField->name);
sem_error(3, funDec->fl, msg);
} else {
varField->isArg = true;
insertSymbol(varField);
}
type->func_.paramNum++;
varField->tail = type->func_.params;
type->func_.params = varField;
// insert code begin
// Operand paramOperand = genOperandStr(oVariable, varType->func_.params->name);
Operand paramOperand = genOperandStr(oVariable, varField->name);
InterCode paramInterCode = genInterCodeUnary(iParam, paramOperand);
appendCode(paramInterCode);
//end
if (countChild(varList) == 3)
varList = getChild(varList, 2);
else
break;
}
}
field->type = type;
if (findSymbol(field->name, true) != NULL) { ;
sprintf(msg, "Redefined function \"%s\".", field->name);
sem_error(4, funDec->fl, msg);
} else {
field->isArg = false;
insertSymbol(field);
}
goCompSt(getChild(extDef, 2), basicType);
} else { // Specifier SEMI
}
if (getChild(extDefList, 1)->type == TNUL)
break;
else
extDefList = getChild(extDefList, 1);
}
}
// CompSt : LC DefList StmtList RC
void goCompSt(object *compSt, Type funcType) {
goDefList(getChild(compSt, 1));
object *stmtList = getChild(compSt, 2);
while (stmtList->type != TNUL) {
object *stmt = getChild(stmtList, 0);
goStmt(stmt, funcType);
stmtList = getChild(stmtList, 1);
}
}
// DefList : Def DefList | ;
// Def : Specifier DecList SEMI
void goDefList(object *defList) {
while (defList->type != TNUL) {
object *def = getChild(defList, 0);
Type basicType = goSpecifier(getChild(def, 0));
object *decList = getChild(def, 1);
// DecList : Dec {_ac(1);}
// | Dec COMMA DecList {_ac(3);}
while (decList->type != TNUL) {
// Dec : VarDec {_ac(1);}
// | VarDec ASSIGNOP Exp {_ac(3);}
object *dec = getChild(decList, 0);
FieldList field = goVarDec(getChild(dec, 0), basicType);
// insert code begin
if (field->type->kind == KARRAY) {
Operand operand = genOperandStr(oVariable, field->name);
InterCode interCode = genInterCodeDec(operand, getSize(field->type, false));
appendCode(interCode);
}
if (countChild(dec) == 3) {
Operand place = genEmptyOperand();
// if (getChild(getChild(dec, 2), 0)->type == TINT) {
// goExp(getChild(dec, 2), NULL);
// place->kind = oConstant;
// sprintf(place->un.value, "%d", getChild(getChild(dec, 2), 0)->vint);
// } else {
// place->kind = oTempVariable;
// goExp(getChild(dec, 2), place);
// }
goExp(getChild(dec, 2), place);
if (place->kind != oVariable || strcpy(place->un.value, field->name) != 0) {
Operand leftOperand = genOperandStr(oVariable, field->name);
InterCode addressInterCode = genInterCodeBinary(iAssign, leftOperand, place);
appendCode(addressInterCode);
}
}
// end
if (findSymbol(field->name, false) != NULL) { ;
sprintf(msg, "Redefined variable \"%s\".", field->name);
sem_error(3, decList->fl, msg);
} else {
insertSymbol(field);
}
if (countChild(decList) == 3)
decList = getChild(decList, 2);
else
break;
}
defList = getChild(defList, 1);
}
}
/*
Stmt : Exp SEMI
| CompSt
| RETURN Exp SEMI
| IF LP Exp RP Stmt
| IF LP Exp RP Stmt ELSE Stmt
| WHILE LP Exp RP Stmt
;
*/
void goStmt(object *stmt, Type funcType) {
if (!strcmp(getChild(stmt, 0)->vstr, "Exp")) {
goExp(getChild(stmt, 0), NULL);
} else if (!strcmp(getChild(stmt, 0)->vstr, "CompSt")) {
goCompSt(getChild(stmt, 0), funcType);
} else if (!strcmp(getChild(stmt, 0)->vstr, "RETURN")) {
Type type;
Operand operand;
// if (getChild(getChild(stmt, 1), 0)->type == TINT) {
// operand = genOperandInt(oConstant, getChild(getChild(stmt, 1), 0)->vint);
// type = goExp(getChild(stmt, 1), NULL);
// } else {
// operand = genEmptyOperand();
// type = goExp(getChild(stmt, 1), operand);
// }
operand = genEmptyOperand();
type = goExp(getChild(stmt, 1), operand);
if (!isTypeEqual(type, funcType))
sem_error(8, stmt->fl, "Type mismatched for return.");
InterCode interCode = genInterCodeUnary(iReturn, operand);
appendCode(interCode);
// end
} else if (!strcmp(getChild(stmt, 0)->vstr, "WHILE")) { // WHILE LP Exp RP Stmt
// insert code begin
/*
* label1
* if condition goto label2
* goto label3
* label2
* code
*/
// label1 condition label2 code goto label3
Operand firstLabelOperand = genLabelOperand(),
secondLabelOperand = genLabelOperand(),
thirdLabelOperand = genLabelOperand();
InterCode firstLabelInterCode = genLabelInterCode(firstLabelOperand),
secondLabelInterCode = genLabelInterCode(secondLabelOperand),
thirdLabelInterCode = genLabelInterCode(thirdLabelOperand);
// label1
appendCode(firstLabelInterCode);
// condition
Type conditionType = goCondition(getChild(stmt, 2), secondLabelOperand, thirdLabelOperand);
if (conditionType->kind != KBASIC || conditionType->basic_ != _INT)
sem_error(5, stmt->fl, "Only type INT could be used for judgement.");
// label2
appendCode(secondLabelInterCode);
// code
goStmt(getChild(stmt, 4), funcType);
//goto label1
InterCode gotoLabelInterCode = genGotoLabelInterCode(firstLabelOperand);
appendCode(gotoLabelInterCode);
// label3
appendCode(thirdLabelInterCode);
} else {
Operand firstLabelOperand = genLabelOperand(),
secondLabelOperand = genLabelOperand();
// if condition goto label1 goto label2
Type conditionType = goCondition(getChild(stmt, 2), firstLabelOperand, secondLabelOperand);
if (conditionType->kind != KBASIC || conditionType->basic_ != _INT)
sem_error(5, stmt->fl, "Only type INT could be used for judgement.");
// label1
InterCode firstLabelInterCode = genLabelInterCode(firstLabelOperand);
appendCode(firstLabelInterCode);
// code
goStmt(getChild(stmt, 4), funcType);
if (countChild(stmt) == 4) {
// label2
InterCode secondLabelInterCode = genLabelInterCode(secondLabelOperand);
appendCode(secondLabelInterCode);
} else {
// goto label3
Operand thirdLabelOperand = genLabelOperand();
InterCode gotoThirdLabelInterCode = genGotoLabelInterCode(thirdLabelOperand);
appendCode(gotoThirdLabelInterCode);
// label2
InterCode secondLabelInterCode = genLabelInterCode(secondLabelOperand);
appendCode(secondLabelInterCode);
// else code
goStmt(getChild(stmt, 6), funcType);
// label3
InterCode thirdLabelInterCode = genLabelInterCode(thirdLabelOperand);
appendCode(thirdLabelInterCode);
}
}
}
/*
Exp : Exp ASSIGNOP Exp
| Exp AND Exp
| Exp OR Exp
| Exp RELOP Exp
| Exp PLUS Exp
| Exp MINUS Exp
| Exp STAR Exp
| Exp DIV Exp
| LP Exp RP
| MINUS Exp
| NOT Exp
| ID LP Args RP
| ID LP RP
| Exp LB Exp RB
| Exp DOT ID
| ID
| INT
| FLOAT
;
*/
Type goExp(object *exp, Operand upshot) {
if (exp == NULL || exp->type == TNUL) return NULL;
char *firstStr = getChild(exp, 0)->vstr;
char *secondStr = (countChild(exp) > 1) ? getChild(exp, 1)->vstr : NULL;
if (getChild(exp, 0)->type == TID && countChild(exp) == 1) {
FieldList field = findSymbol(firstStr, false);
if (field == NULL) {
sprintf(msg, "Undefined variable \"%s\".", firstStr);
sem_error(1, exp->fl, msg);
return NULL;
}
if (upshot != NULL) {
upshot->kind = oVariable;
strcpy(upshot->un.value, getChild(exp, 0)->vstr);
}
return field->type;
} else if (getChild(exp, 0)->type == TINT) {
Type foo = malloc(sizeof(Type_));
foo->kind = KBASIC;
foo->basic_ = _INT;
// if (upshot != NULL) {
// Operand operand = genOperandInt(oConstant, getChild(exp, 0)->vint);
// setOperandTemp(upshot);
// InterCode interCode = genInterCodeBinary(iAssign, upshot, operand);
// appendCode(interCode);
// }
if (upshot != NULL) {
upshot->kind = oConstant;
sprintf(upshot->un.value, "%d", getChild(exp, 0)->vint);
}
return foo;
// } else if (!strcmp(firstStr, "FLOAT")) {
} else if (getChild(exp, 0)->type == TFLOAT) {
Type foo = malloc(sizeof(Type_));
foo->kind = KBASIC;
foo->basic_ = _FLOAT;
return foo;
} else if (!strcmp(firstStr, "LP")) {
return goExp(getChild(exp, 1), upshot);
} else if (!strcmp(firstStr, "MINUS")) {
object *second = getChild(exp, 1);
Type foo;
if (getChild(second, 0)->type == TINT && upshot != NULL && getChild(second, 0)->vint >= 0) {
foo = goExp(second, NULL);
upshot->kind = oConstant;
sprintf(upshot->un.value, "-%d", getChild(second, 0)->vint);
return foo;
} else {
Operand rightOperand = genEmptyOperand();
foo = goExp(second, rightOperand);
if (foo == NULL) return NULL;
if (upshot != NULL) {
Operand zeroOperand = genOperandStr(oConstant, "0");
setOperandTemp(upshot);
InterCode interCode = genInterCodeTernary(iMinus, upshot, zeroOperand, rightOperand);
appendCode(interCode);
}
return foo;
}
} else if (!strcmp(firstStr, "NOT")) {
if (upshot != NULL) {
// upshot = 1
Operand zeroOperand = genOperandStr(oConstant, "0");
InterCode initPosInterCode = genInterCodeBinary(iAssign, upshot, zeroOperand);
appendCode(initPosInterCode);
Operand firstLabelOperand = genLabelOperand(), secondLabelOperand = genLabelOperand();
Type foo = goCondition(exp, firstLabelOperand, secondLabelOperand);
// first label
InterCode firstLabelInterCode = genLabelInterCode(firstLabelOperand);
appendCode(firstLabelInterCode);
// upshot = 1;
Operand oneOperand = genOperandStr(oConstant, "1");
InterCode setPosInterCode = genInterCodeBinary(iAssign, upshot, oneOperand);
appendCode(setPosInterCode);
// second label
InterCode secondLabelInterCode = genLabelInterCode(secondLabelOperand);
appendCode(secondLabelInterCode);
return foo;
} else {
return goExp(getChild(exp, 1), NULL);
}
} /* Exp AND Exp
| Exp OR Exp
| Exp RELOP Exp
| Exp PLUS Exp
| Exp MINUS Exp
| Exp STAR Exp
| Exp DIV Exp*/
else if (!strcmp(secondStr, "PLUS") || !strcmp(secondStr, "MINUS") ||
!strcmp(secondStr, "STAR") || !strcmp(secondStr, "DIV")) {
Type leftType, rightType;
Operand leftOperand, rightOperand;
// if (getChild(getChild(exp, 0), 0)->type == TINT) {
// leftOperand = genOperandInt(oConstant, getChild(getChild(exp, 0), 0)->vint);
// leftType = goExp(getChild(exp, 0), NULL);
// } else {
// leftOperand = genOperand(oTempVariable);
// leftType = goExp(getChild(exp, 0), leftOperand);
// }
// if (getChild(getChild(exp, 2), 0)->type == TINT) {
// rightOperand = genOperandInt(oConstant, getChild(getChild(exp, 2), 0)->vint);
// rightType = goExp(getChild(exp, 0), NULL);
// } else {
// rightOperand = genOperand(oTempVariable);
// rightType = goExp(getChild(exp, 2), rightOperand);
// }
leftOperand = genEmptyOperand();
rightOperand = genEmptyOperand();
leftType = goExp(getChild(exp, 0), leftOperand);
rightType = goExp(getChild(exp, 2), rightOperand);
if (!isTypeEqual(leftType, rightType)) {
sem_error(7, exp->fl, "Type mismatched for operands.");
return leftType;
}
if (leftOperand->kind == oTempAddress) {
Operand tempOperand = genTempOperand();
appendCode(genInterCodeBinary(iAssign, tempOperand, leftOperand));
leftOperand = tempOperand;
}
if (rightOperand->kind == oTempAddress) {
Operand tempOperand = genTempOperand();
appendCode(genInterCodeBinary(iAssign, tempOperand, rightOperand));
rightOperand = tempOperand;
}
InterCode interCode;
if (!strcmp(getChild(exp, 1)->vstr, "PLUS"))
interCode = genInterCode(iPlus);
else if (!strcmp(getChild(exp, 1)->vstr, "MINUS"))
interCode = genInterCode(iMinus);
else if (!strcmp(getChild(exp, 1)->vstr, "STAR"))
interCode = genInterCode(iStar);
else // DIV
interCode = genInterCode(iDiv);
if (upshot != NULL) {
setOperandTemp(upshot);
if (leftOperand->kind == oConstant && rightOperand->kind == oConstant) {
int result, leftNum = getChild(getChild(exp, 0), 0)->vint,
rightNum = getChild(getChild(exp, 2), 0)->vint;
switch (interCode->kind) {
case iPlus:result = leftNum + rightNum;
break;
case iMinus:result = leftNum - rightNum;
break;
case iStar:result = leftNum * rightNum;
break;
case iDiv:result = leftNum / rightNum;
break;
default: result = 0;
break;
}
free(interCode);
free(leftOperand);
free(rightOperand);
rightOperand = genOperandInt(oConstant, result);
interCode = genInterCodeBinary(iAssign, upshot, rightOperand);
} else if (leftOperand->kind == oConstant) {
interCode->ternary.left = rightOperand;
interCode->ternary.right = leftOperand;
interCode->ternary.res = upshot;
} else {
interCode->ternary.left = leftOperand;
interCode->ternary.right = rightOperand;
interCode->ternary.res = upshot;
}
appendCode(interCode);
}
return leftType;
} else if (!strcmp(secondStr, "AND") || !strcmp(secondStr, "OR") ||
getChild(exp, 1)->type == TREL) {
if (upshot == NULL) {
Operand labelOperand = genLabelOperand();
Type varType = goCondition(exp, labelOperand, labelOperand);
appendCode(genLabelInterCode(labelOperand)); // end label
return varType;
} else {
Operand firstLabelOperand = genLabelOperand(), secondLabelOperand = genLabelOperand();
Operand zeroOperand = genOperandStr(oConstant, "0");
InterCode setZeroInterCode = genInterCodeBinary(iAssign, upshot, zeroOperand);
appendCode(setZeroInterCode); // set 0
Type varType = goCondition(exp, firstLabelOperand, secondLabelOperand);
InterCode firstLabelInterCode = genLabelInterCode(firstLabelOperand);
appendCode(firstLabelInterCode); // first label
Operand oneOperand = genOperandStr(oConstant, "1");
InterCode setOneInterCode = genInterCodeBinary(iAssign, upshot, oneOperand);
appendCode(setOneInterCode);
InterCode secondLabelInterCode = genLabelInterCode(secondLabelOperand);
appendCode(secondLabelInterCode);
return varType;
}
} else if (!strcmp(secondStr, "ASSIGNOP")) {
object *dest = getChild(exp, 0), *src = getChild(exp, 2);
Operand leftOperand = genOperand(oTempVariable);
Type foo = goExp(getChild(exp, 0), leftOperand), bar;
Operand rightOperand;
// if (getChild(getChild(exp, 2), 0)->type == TINT) {
// bar = goExp(getChild(exp, 2), NULL);
// rightOperand = genOperandInt(oConstant, getChild(getChild(exp, 2), 0)->vint);
// } else {
// rightOperand = genOperand(oTempVariable);
// bar = goExp(getChild(exp, 2), rightOperand);
// }
rightOperand = genOperand(oTempVariable);
bar = goExp(src, rightOperand);
if ((countChild(dest) == 1 && getChild(dest, 0)->type == TID) ||
(countChild(dest) == 3 && !strcmp(getChild(dest, 0)->vstr, "Exp") &&
!strcmp(getChild(dest, 1)->vstr, "DOT") &&
getChild(dest, 2)->type == TID) ||
(countChild(dest) == 4 && !strcmp(getChild(dest, 0)->vstr, "Exp") &&
// !strcmp(getChild(dest, 1)->vstr, "LB") &&
// !strcmp(getChild(dest, 3)->vstr, "RB") &&
!strcmp(getChild(dest, 2)->vstr, "Exp"))) {
if (isTypeEqual(foo, bar)) {
if (leftOperand->kind == oTempAddress &&
(rightOperand->kind == oTempAddress ||
(countChild(src) > 2 &&
!strcmp(getChild(src, 0)->vstr, "Exp") &&
!strcmp(getChild(src, 2)->vstr, "Exp")
)
)
) {
Operand midOperand = genTempOperand();
appendCode(genInterCodeBinary(iAssign, midOperand, rightOperand));
appendCode(genInterCodeBinary(iAssign, leftOperand, midOperand));
} else {
InterCode assignInterCode = genInterCodeBinary(iAssign, leftOperand, rightOperand);
appendCode(assignInterCode);
}
if (upshot != NULL) {
InterCode upInterCode = genInterCodeBinary(iAssign, upshot, rightOperand);
appendCode(upInterCode);
}
} else {
sem_error(5, exp->fl, "Type mismatched for assignment.");
}
} else {
sem_error(6, exp->fl,
"The left-hand side of an assignment must be a variable.");
}
return foo;
} /*
| ID LP Args RP
| ID LP RP
*/
else if (getChild(exp, 0)->type == TID) {
FieldList foo = findSymbol(getChild(exp, 0)->vstr, true);
if (foo == NULL) {
FieldList bar = findSymbol(getChild(exp, 0)->vstr, false);
if (bar != NULL) {
sprintf(msg, "\"%s\" is not a function.", getChild(exp, 0)->vstr);
sem_error(11, exp->fl, msg);
} else {
sprintf(msg, "Undefined function \"%s\".", getChild(exp, 0)->vstr);
sem_error(2, exp->fl, msg);
}
return NULL;
}
Type definedType, type = malloc(sizeof(Type_));
definedType = foo->type;
type->kind = KFUNC;
type->func_.paramNum = 0;
type->func_.params = NULL;
if (countChild(exp) == 3) {
if (!strcmp(getChild(exp, 0)->vstr, "read")) {
if (upshot != NULL) {
setOperandTemp(upshot);
InterCode readInterCode = genInterCodeUnary(iRead, upshot);
appendCode(readInterCode);
}
} else {
Operand funcOperand = genOperandStr(oFunction, getChild(exp, 0)->vstr);
if (upshot == NULL)
upshot = genEmptyOperand();
setOperandTemp(upshot);
InterCode interCode = genInterCodeBinary(iCall, upshot, funcOperand);
appendCode(interCode);
}
} else if (!strcmp(getChild(exp, 0)->vstr, "write")) {
Type varType;
Operand argOperand;
object *argExp = getChild(getChild(exp, 2), 0);
/*if (getChild(exp, 0)->type == TINT) {
varType = goExp(argExp, 0);
argOperand = genOperandStr(oConstant, getChild(exp, 0)->vstr);
} else {
argOperand = genOperand(oTempVariable);
varType = goExp(argExp, argOperand);
}
*/
argOperand = genEmptyOperand();
varType = goExp(argExp, argOperand);
FieldList tmpField = malloc(sizeof(FieldList_));
tmpField->isArg = false;
tmpField->type = varType;
type->func_.paramNum++;
tmpField->tail = type->func_.params;
type->func_.params = tmpField;
InterCode interCode = genInterCodeUnary(iWrite, argOperand);
appendCode(interCode);
} else {
// Args : Exp COMMA Args | Exp;
object *args = getChild(exp, 2);
// InterCode headArgInterCode = NULL;
InterCode headArgInterCode = genInterCode(iArg);
headArgInterCode->next = headArgInterCode;
headArgInterCode->prev = headArgInterCode;
while (args->type != TNUL) {
Type varType;
Operand argOperand;
// if (getChild(getChild(args, 0), 0) == TINT) {
// argOperand = genOperandInt(oConstant, getChild(getChild(args, 0), 0)->vint);
// varType = goExp(getChild(args, 0), NULL);
// } else {
// argOperand = genOperand(oTempVariable);
argOperand = genEmptyOperand();
varType = goExp(getChild(args, 0), argOperand);
if (varType->kind == KARRAY && argOperand->kind == oVariable) {
char tmp[128];
sprintf(tmp, "&%s", argOperand->un.value);
strcpy(argOperand->un.value, tmp);
}
// }
InterCode argInterCode = genInterCodeUnary(iArg, argOperand);
// argInterCode->next = headArgInterCode;
// headArgInterCode = argInterCode;
insertInterCodeBefore(headArgInterCode->next, argInterCode);
// appendCode(argInterCode);
FieldList tmpField = malloc(sizeof(FieldList_));
tmpField->isArg = false;
tmpField->type = varType;
type->func_.paramNum++;
tmpField->tail = type->func_.params;
type->func_.params = tmpField;
if (countChild(args) == 3)
args = getChild(args, 2);
else
break;
}
if (headArgInterCode->next != headArgInterCode)
insertListBeforeHead(headArgInterCode->next, headArgInterCode->prev);
Operand funcOperand = genOperandStr(oFunction, getChild(exp, 0)->vstr);
if (upshot == NULL)
upshot = genEmptyOperand();
setOperandTemp(upshot);
InterCode funcInterCode = genInterCodeBinary(iCall, upshot, funcOperand);
appendCode(funcInterCode);
}
if (!isTypeEqual(type, definedType)) {
sprintf(msg, "Params wrong in function \"%s\".", getChild(exp, 0)->vstr);
sem_error(9, exp->fl, msg);
}
// return NULL;
// } else {
return definedType->func_.funcType;
} else if (!strcmp(secondStr, "DOT")) { // Exp DOT ID
Type foo = goExp(getChild(exp, 0), NULL);
if (foo->kind != KSTRUCT) { // not a struct
object *var = getChild(exp, 0);
char *idName = "1";
switch (countChild(var)) {
case 1: {
if (getChild(var, 0)->type == TID) idName = getChild(var, 0)->vstr;
break;
}
case 3: {
if (getChild(var, 2)->type == TID) idName = getChild(var, 0)->vstr;
break;
}
case 4: {
if (!strcmp(getChild(var, 0)->vstr, "Exp") &&
getChild(getChild(var, 0), 0)->type == TID)
idName = getChild(getChild(var, 0), 0)->vstr;
break;
}
default:break;
}
if (findSymbol(idName, false) != NULL)
sem_error(13, exp->fl, "Illegal use of \".\".");
return foo;
}
char *idName = getChild(exp, 2)->vstr;
FieldList field = foo->struct_;
while (field != NULL) {
if (!strcmp(field->name, idName)) return field->type;
field = field->tail;
}
sprintf(msg, "Non-existed field \"%s\".", getChild(exp, 2)->vstr);
sem_error(14, exp->fl, msg);
return foo;
} else if (!strcmp(getChild(exp, 1)->vstr, "LB")) { // Exp LB Exp RB
Operand baseOperand = genEmptyOperand(), subOperand, offsetOperand;
Type foo = goExp(getChild(exp, 0), baseOperand);
if (foo->kind != KARRAY) { // not an array
object *var = getChild(exp, 0);
char *idName = "1";
switch (countChild(var)) {
case 1: {
if (getChild(var, 0)->type == TID) idName = getChild(var, 0)->vstr;
break;
}
case 3: {
if (getChild(var, 2)->type == TID) idName = getChild(var, 0)->vstr;
break;
}
case 4: {
if (!strcmp(getChild(var, 0)->vstr, "Exp") &&
getChild(getChild(var, 0), 0)->type == TID)
idName = getChild(getChild(var, 0), 0)->vstr;
break;
}
default:break;
}
if (findSymbol(idName, false) != NULL) {
sprintf(msg, "\"%s\" is not an array.", idName);
sem_error(10, exp->fl, msg);
}
return foo;
}
Type bar;
// if (getChild(getChild(exp, 2), 0)->type == TINT) {
// subOperand = genOperandInt(oConstant, getChild(getChild(exp, 2), 0)->vint);
// bar = goExp(getChild(exp, 2), NULL);
// } else {
// subOperand = genEmptyOperand();
// bar = goExp(getChild(exp, 2), subOperand);
// }
subOperand = genEmptyOperand();
bar = goExp(getChild(exp, 2), subOperand);
// if (!strcmp(subOperand->un.value, "0")) {
if (bar->kind != KBASIC || bar->basic_ == _FLOAT)
sem_error(12, exp->fl, "There is not a integer between \"[\" and \"]\".");
// if (getChild(getChild(exp, 2), 0)->type == TINT && getChild(getChild(exp, 2), 0)->vint == 0) {
// free(subOperand);
// offsetOperand = genOperandStr(oConstant, "0");
// } else {
Operand widthOperand = genOperandInt(oConstant, getSize(foo, true));
offsetOperand = genTempOperand();
InterCode offsetInterCode = genInterCodeTernary(iStar, offsetOperand, subOperand, widthOperand);
appendCode(offsetInterCode);
// }
// InterCode baseInterCode = genInterCodeTernary(iPlus, upshot, baseOperand, offsetOperand);
// appendCode(baseInterCode);
// }
InterCode baseInterCode = genInterCodeTernary(iPlus, NULL, baseOperand, offsetOperand);
if (foo->array_.type->kind == KBASIC) {
Operand addrOperand = genTempOperand();
baseInterCode->ternary.res = addrOperand;
upshot->kind = oTempAddress;
upshot->un.dest = addrOperand;
} else {
baseInterCode->ternary.res = upshot;
setOperandTemp(upshot);
}
// if (getChild(getChild(exp, 0), 0)->type == TID) {
// FieldList fieldList = findSymbol(baseOperand->un.value, false);
// if (fieldList->isArg)
// baseInterCode->kind = iPlus;
// } else {
// baseInterCode->kind = iPlus;
// }
appendCode(baseInterCode);
return foo->array_.type;
} else {
sem_error(0, exp->fl, "ERROR");
return NULL;
}
}
Type goCondition(object *exp, Operand trueLabelOperand, Operand falseLabelOperand) {
// if left relop right trueLabel
// goto falseLabel
if (strcmp(getChild(exp, 0)->vstr, "Exp") == 0) {
object *operator = getChild(exp, 1);
if (operator->type == TREL) {
Operand fooOperand, barOperand;
Type leftType, rightType;
// left
// if (getChild(getChild(exp, 0), 0)->type == TINT) {
// leftType = goExp(getChild(exp, 0), NULL);
// fooOperand = genOperandInt(oConstant, getChild(getChild(exp, 0), 0)->vint);
// } else {
// fooOperand = genOperand(oTempVariable);
// leftType = goExp(getChild(exp, 0), fooOperand);
// }
// right
// if (getChild(getChild(exp, 2), 0)->type == TINT) {
// rightType = goExp(getChild(exp, 2), NULL);
// barOperand = genOperandInt(oConstant, getChild(getChild(exp, 2), 0)->vint);
// } else {
// barOperand = genOperand(oTempVariable);
// rightType = goExp(getChild(exp, 2), barOperand);
// }
fooOperand = genEmptyOperand();
leftType = goExp(getChild(exp, 0), fooOperand);
barOperand = genEmptyOperand();
rightType = goExp(getChild(exp, 2), barOperand);
if (leftType == NULL || rightType == NULL)
return NULL;
// goto trueLabel
InterCode ifGotoInterCode = genInterCodeIfGoto(trueLabelOperand, fooOperand, barOperand, getChild(exp, 1)->vstr);
appendCode(ifGotoInterCode);
// goto falseLabel
InterCode gotoInterCode = genGotoLabelInterCode(falseLabelOperand);
appendCode(gotoInterCode);
return rightType;
} else if (strcmp(getChild(exp, 1)->vstr, "AND") == 0 ||
strcmp(getChild(exp, 1)->vstr, "OR") == 0) {
// split into double condition
Operand operand = genLabelOperand();
Type leftType;
// first condition
if (strcmp(getChild(exp, 1)->vstr, "AND") == 0)
leftType = goCondition(getChild(exp, 0), operand, falseLabelOperand);
else
leftType = goCondition(getChild(exp, 0), trueLabelOperand, operand);
// transfer label
InterCode interCode = genLabelInterCode(operand);
appendCode(interCode);
// second condition
goCondition(getChild(exp, 2), trueLabelOperand, falseLabelOperand);
return leftType;
}
} else if (strcmp(getChild(exp, 0)->vstr, "NOT") == 0) {
// reverse
return goCondition(getChild(exp, 1), falseLabelOperand, trueLabelOperand);
} else {
Operand operand = genEmptyOperand();
Type type;
// if (getChild(exp, 0)->type == TINT) {
// type = goExp(exp, NULL);
// operand->kind = oConstant;
// sprintf(operand->un.value, "%d", getChild(exp, 0)->vint);
// } else {
// operand->kind = oTempVariable;
type = goExp(exp, operand);
// }
// turn `if condition` to `if condition != 0`, goto trueLabel
Operand zeroOperand = genOperandStr(oConstant, "0");
InterCode ifGotoInterCode = genInterCodeIfGoto(trueLabelOperand, operand, zeroOperand, "!=");
appendCode(ifGotoInterCode);
// goto falseLabel
InterCode gotoInterCode = genGotoLabelInterCode(falseLabelOperand);
appendCode(gotoInterCode);
return type;
}
return NULL;
}
void traverseTree(object *root) {
if (root == NULL) {
} else if (root->type == TDEF && !strcmp(root->vstr, "ExtDefList")) {
goExtDefList(root);
} else if (countChild(root) != 0) {
for (object *foo = root->child; foo != NULL; foo = foo->next) {
traverseTree(foo);
}
}
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
int partition(int a[],int low,int high)
{
int pivot=a[high];
int i=low-1;
int j,temp;
for(j=low;j<high;j++)
{
if(a[j]<=pivot)
{
i++;
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
}
i=i+1;
temp=pivot;
a[high]=a[i];
a[i]=temp;
return (i);
}
void quicksort(int a[],int l,int h)
{
if(l<=h){
int i=partition(a,l,h);
quicksort(a,l,i-1);
quicksort(a,i+1,h);
}
}
int main()
{
int n,a[100],i;
printf("Enter number of elements\n");
scanf("%d",&n);
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
quicksort(a,0,n-1);
for(i=0;i<n;i++)
{
printf("%d ",a[i]);
}
return 0;
}
|
C
|
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
// So, every time when program is called fork, process are dublicated, so number of proccess equal to 2^n, where n is number of calling fork
int main(){
for (int i = 0; i < 3; i++) {
fork();
}
sleep(5);
return 0;
}
|
C
|
#ifndef __C_LINKED_LIST_H__
#define __C_LINKED_LIST_H__
#define TRUE 1
#define FALSE 0
typedef int Item;
typedef struct _node{
Item item;
struct _node *next;
}Node;
typedef struct _CLL{
Node *tail;
Node *cur;
Node *before;
int numOfData;
}CList;
typedef CList List;
void ListInit(List *plist);
void Insert(List *plist, Item item);
void InsertFront(List *plist, Item item);
int First(List *plist, Item *pitem);
int Next(List *plist, Item *pitem);
Item Remove(List *plist);
int Count(List *plist);
#endif
|
C
|
#include "BinarySearchTree.h"
//Malloc a new BinarySearchTreeImp and return it's address.
BinarySearchTree newBinarySearchTree(){
BinarySearchTree tree = (BinarySearchTree)malloc(sizeof(BinarySearchTreeImp));
tree->root = NULL;
return tree;
}
//Free the BinarySearchTree and any nodes that still exist in the tree. I recommend creating another "helper" function to recursively free all the nodes in the tree using a postorder traversal as discussed in class.
void freeBinarySearchTree(BinarySearchTree tree){
free_BST_Node(tree->root);
free(tree);
}
//Allocate a new node and store "value" as the Element in the node. Return the address of the node.
NodeT *allocateNode(Element value){
NodeT* n = (NodeT*)malloc(sizeof(NodeT));
n->element = value;
n->left = NULL;
n->right = NULL;
return n;
}
//Given a BinarySearchTree and a searchValue, return a pointer to the node in the tree that contains searchValue if you find it or return NULL if it does not exist. I recommend writing a secondary function to recursively search the tree.
NodeT *search(BinarySearchTree tree, int searchValue){
if(tree->root == NULL){
return;
}
return searching(tree->root, searchValue);
}
//Create a node to store the given Element and add it as a leaf in the BinarySearchTree. Do not worry about balancing the tree for this project.
//Return true if the insert worked successfully, and return false if the node already existed in the tree.
int insert(BinarySearchTree tree, Element value){
NodeT* node = allocateNode(value);
NodeT* temp_node;
if(tree->root == NULL){
tree->root = node;
return TRUE;
}
else{
temp_node = tree->root;
while(temp_node != NULL){
if(temp_node->element.accountNumber == value.accountNumber)
return FALSE;
else if(value.accountNumber < temp_node->element.accountNumber){
if(temp_node->left == NULL){
temp_node->left = node;
return TRUE;
}
else
temp_node = temp_node->left;
}
else{
if(temp_node->right == NULL){
temp_node->right = node;
return TRUE;
}
else
temp_node = temp_node->right;
}
}
}
//
return FALSE;
}
//Print the key values of all nodes in the subtree rooted at p in increasing order. I recommend writing a secondary function to recursively traverse the nodes.
void printInOrder(BinarySearchTree tree){
printInOrderr(tree->root);
}
void printPreOrder(BinarySearchTree tree){
printPreOrderr(tree->root);
}
//Recursivly print the key values of all nodes in the subtree rooted at p according to a preorder traversal.
void printInOrderr(NodeT *p)
{
if(p == NULL )
return;
printInOrderr(p->left);
printf("%d %.2f \n", p->element.accountNumber, p->element.accountBalance);
printInOrderr(p->right);
}
void printPreOrderr(NodeT *p)
{
if(p == NULL )
return;
printf("%d %.2f \n", p->element.accountNumber, p->element.accountBalance);
printPreOrderr(p->left);
printPreOrderr(p->right);
}
///_______________________________///////////////////
// Teacher sugestion:
void free_BST_Node(NodeT* n){
if (n == NULL){
return;
}
free_BST_Node(n->left);
free_BST_Node(n->right);
free(n);
}
NodeT *searching(NodeT *ptr, int searchValue){
if(ptr == NULL)
return ;
else if( searchValue == ptr->element.accountNumber ){
return ;
}
else if(searchValue < ptr->element.accountNumber){
return searching(ptr->left, searchValue);
}
else if ((searchValue > ptr->element.accountNumber)){
return searching(ptr->right, searchValue);
}
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main(int argc, char **argv)
{
int i;
unsigned char *buff;
buff = (char *)malloc(sizeof(char) * 1024);
printf("my pid is: %d\n", getpid());
for ( i = 0; i < 60; i++ )
{
sleep(60);
}
return 0;
}
|
C
|
//
// main.c
// gradeInTheShade
//
// Created by edwardtoday on 12/23/14.
// Copyright (c) 2014 edwardtoday. All rights reserved.
//
#include <stdio.h>
#include <stdlib.h> // malloc(), free()
float averageFloats(float *data, int dataCount) {
float sum = 0.0;
for (int i = 0; i < dataCount; i++) {
sum = sum + data[i];
}
return sum / dataCount;
}
int main(int argc, const char *argv[]) {
// Create an array of floats
float *gradeBook = malloc(3 * sizeof(float));
gradeBook[0] = 60.2;
gradeBook[1] = 94.5;
gradeBook[2] = 81.1;
// Calculate the average
float average = averageFloats(gradeBook, 3);
// Free the array
free(gradeBook);
gradeBook = NULL;
printf("Average = %.2f\n", average);
float gradeBookLiteral[] = {60.2, 94.5, 81.1};
average = averageFloats(gradeBookLiteral, 3);
printf("Average = %.2f\n", average);
return 0;
}
|
C
|
#define _BSD_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <string.h>
#include <time.h>
#include <math.h>
#include <sys/types.h>
#include <sys/stat.h>
#include "list.h"
#include "create.h"
#include "mytar.h"
typedef struct
{
int flag;
int index;
int value;
} ModeChar;
static ModeChar MODECHRS[] = {
{S_IRUSR, 1, 'r'}, {S_IWUSR, 2, 'w'}, {S_IXUSR, 3, 'x'},
{S_IRGRP, 4, 'r'}, {S_IWGRP, 5, 'w'}, {S_IXGRP, 6, 'x'},
{S_IROTH, 7, 'r'}, {S_IWOTH, 8, 'w'}, {S_IXOTH, 9, 'x'},
{S_ISUID, 3, 's'}, {S_ISGID, 6, 's'}, {S_IFDIR, 0, 'd'},
{0, 0, 0}
};
int given_names(char *name, int argc, char **argv)
{
int i;
int found = 0;
for (i = 3; i < argc; i++)
{
if (strcmp(name, argv[i]) == 0)
{
found = 1;
break;
}
else if ((argv[i][strlen(argv[i]) - 1] == '/') && (strstr(name, argv[i]) != NULL))
{
found = 1;
break;
}
}
return found;
}
void list(Tar *tar, char **argv, int argc)
{
Header header;
ModeChar *mode_chr;
int tar_fd, file_size, size, i, mode, file_shift, boo = 0;
char *end;
char mode_str[11];
char time_str[20];
char name_str[H_NAME + H_PREFIX + 1];
time_t mtime;
tar_fd = open(tar->tar_file, O_RDONLY);
if (tar_fd < 0)
fprintf(stderr, "Cannnot open tar file: %s\n", tar->tar_file);
/*read in block by block*/
while ((size = read(tar_fd, &header, BUF_SIZE)) != 0)
{
/*reset the stuff*/
boo = 0;
memset(name_str, '\0', H_NAME + H_PREFIX + 1);
/*validate the tar header*/
if (header.name[0] == '\0')
break;
header.magic[H_MAGIC - 1] = '\0';
if (strcmp(MAGIC_NUM, header.magic) !=0)
{
fprintf(stderr, "Header Error invalid magic: '%s'\n", header.magic);
return;
}
/*concat prefix and name if there is a prefix*/
if (strlen(header.prefix) != 0)
{
strncpy(name_str, header.prefix, 155);
if (name_str[strlen(name_str - 1)] != '/')
strcat(name_str, "/");
strcat(name_str, header.name);
}
else
strncpy(name_str, header.name, 100);
/*if listed files given, read each header to see if need to list*/
if (argc > 3)
{
if (given_names(name_str, argc, argv) == 1)
boo = 1;
}
else
boo = 1; /*otherwise list all*/
/*move file pointer to next header*/
file_size = strtol(header.size, &end, 8);
file_shift = (int)ceil((double)file_size/BUF_SIZE);
lseek(tar_fd, file_shift * BUF_SIZE, SEEK_CUR);
/*if need to print, begin doing so*/
if (boo)
{
/*if verbose option selscted*/
if (tar->options[V_FLAG])
{
mode = strtol(header.mode, &end, 8);
for (i = 0; i < 10; i++)
mode_str[i] = '-';
mode_str[i] = 0;
for (mode_chr = MODECHRS; mode_chr->flag; mode_chr++)
{
if (mode & mode_chr->flag)
mode_str[mode_chr->index] = mode_chr->value;
}
if (header.typeflag[0] == '5')
mode_str[0] = 'd';
else if (header.typeflag[0] == '2')
mode_str[0] = 'l';
mtime = strtol(header.mtime, &end, 8);
strftime(time_str, 19, "%Y-%m-%d %H:%M", localtime(&mtime));
time_str[strlen(time_str) ] = '\0';
printf("%s %s/%s %14u %s ", mode_str, header.uname, header.gname, file_size, time_str);
}
/*else just print file name*/
if (strlen(name_str) > 100 && strlen(name_str) < 110)
name_str[H_NAME] = '\0';
printf("%s\n", name_str);
}
}
}
|
C
|
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <sys/stat.h>
#include <fcntl.h>
const int m_size = 3000;
int main(int argc, char const *argv[])
{
int fdwrite ,fdread,fdstate; // file descriptors
char *pipeName = "story_teller";
char *pipeName2 = "reader_response_msg";
char *state_pipe = "state_description";
char *like_pipe = "like_state_pipe";
umask(0); //set file mode creation mask--setting the file creation permission mode
mknod(pipeName,S_IFIFO|0666, 0); // creating the named pipe and setting up the permissions
umask(0); //set file mode creation mask--setting the file creation permission mode
mknod(pipeName2,S_IFIFO|0666, 0); // creating the named pipe and setting up the permissions
umask(0); //set file mode creation mask--setting the file creation permission mode
mknod(state_pipe,S_IFIFO|0666, 0); // creating the named pipe and setting up the permissions
umask(0); //set file mode creation mask--setting the file creation permission mode
mknod(like_pipe,S_IFIFO|0666, 0); // creating the named pipe and setting up the permissions
//declaring varibles
char story[m_size]; // story buff size
char reader_response[m_size];
char ready_state_msg[m_size];
char ready_state_msg_down[m_size];
sprintf(story,"I am writer Process. id %d.\nI would like tell you a story. I will continue if you like it.",getpid());
int like_count = 0;
int dislike_count = 0;
printf("How many reader do we have\n");
int num,initial = 1,i;
scanf("%d",&num);
printf("write your story\n");
getchar();
char my_story[m_size];
scanf("%[^\n]%*c",my_story);
sprintf(story,"%s\n%s",story,my_story);
for(i = 1;i <= num;i++)
{
fdwrite = open(pipeName,O_WRONLY);
write(fdwrite, story, m_size);
close(fdwrite);
fdread = open(pipeName2,O_RDONLY);
read(fdread, reader_response, m_size);
close(fdread);
printf("%s\n",reader_response);
}
return 0;
}
|
C
|
#include <stdio.h>
#include <string.h>
void allow_access(){
printf ("\n Root privileges given to the user \n");
}
void deny_access(){
printf ("\nIncorrect Password\n");
}
void login(pass){
char buff[10];
printf("\n Enter the password : \n");
gets(buff);
if(strcmp(buff, pass))
{
deny_access();
}
else
{
allow_access();
}
}
int main(void)
{
int pass = 0;
login("password");
return 0;
}
|
C
|
/* Write a program to print following pattern
AAAAA
BBBB
CCC
DD
E
*/
#include<stdio.h>
void main()
{
int i,j;
for(i=0;i<5;i++)
{
for(j=5;j>i;j--)
{
printf("%c",i+65);
}
printf("\n");
}
}
|
C
|
int fact(int n){
int i=1;
int fact=1;
if(n==0)
return fact;
else{
while(i<=n){
fact*=i;
i++;
}
}
return fact;
}
|
C
|
#include <stdio.h>
#include <pthread.h>
#define PRODUCER_NUM 100
#define MAXITEMS 1000000
int buff[MAXITEMS];
struct {
pthread_mutex_t mutex;
int nput;/*next index to store*/
int nvalue;/*next value to store*/
} put = {
PTHREAD_MUTEX_INITIALIZER,
0,0
};
struct {
pthread_mutex_t mutex;
pthread_cond_t cond;
int nready;
}nready={
PTHREAD_MUTEX_INITIALIZER,
PTHREAD_COND_INITIALIZER,
0
};
void *produce(void *arg)
{
while(1)
{
pthread_mutex_lock(&put.mutex);
if(put.nput >= MAXITEMS) /*have produced MAXITEMS product, done*/
{
pthread_mutex_unlock(&put.mutex);
return NULL;
}
buff[put.nput] = put.nvalue;
++put.nput;
++put.nvalue;
pthread_mutex_unlock(&put.mutex);
pthread_mutex_lock(&nready.mutex);
++nready.nready;
if(nready.nready == 1)
pthread_cond_signal(&nready.cond);
pthread_mutex_unlock(&nready.mutex);
*((int*)arg) += 1;
}
return NULL;
}
void *consume(void *arg)
{
for(int i=0; i<MAXITEMS; ++i)
{
pthread_mutex_lock(&nready.mutex);
while(nready.nready == 0)
pthread_cond_wait(&nready.cond, &nready.mutex);
--nready.nready;
pthread_mutex_unlock(&nready.mutex);
if(buff[i] != i)
printf("buff[%d] = %d\n", i, buff[i]);
}
return NULL;
}
int main(int argc, char *argv[])
{
int count[PRODUCER_NUM];
pthread_t tid_producer[PRODUCER_NUM], tid_consumer;
for(int i=0; i<PRODUCER_NUM; ++i)
{
count[i] = 0;
pthread_create(&tid_producer[i], NULL, produce, &count[i]);
}
pthread_create(&tid_consumer, NULL, consume, NULL);
/*wait for all producers and the consumer*/
for(int i=0; i<PRODUCER_NUM; ++i)
{
pthread_join(tid_producer[i], NULL);
printf("count[%d] = %d\n", i, count[i]);
}
pthread_join(tid_consumer, NULL);
return 0;
}
|
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 i = 0;
char pole[10];
int pocet = 0;
char c;
printf("Zadaj znaky a ja ich vypisem odzadu\n");
while( pocet < 10){
// c = getchar();
pole[i] = getchar();
// scanf("%c", &pole[i]);
pocet++;
i++;
}
for(i=9;i>=0;i--)
printf("%c", pole[i]);
//putchar(pole[i]);
return 0;
}
|
C
|
/*
* main.cpp
*
* This is the maze runner program for the Homebrew Robotics Club
* Maze Challenge.
*
* This code is designed to run on a Pololu 3pi robot.
*
* Bryant Pong
* 8/28/16
*
* Last Updated: 9/16/16
*/
// 3rd Party Libraries:
#include <pololu/3pi.h> // 3 pi library
#include <avr/pgmspace.h> // For accessing values in FLASH
// Custom Libraries:
#include "list.h" // Custom Linked List class
//#include <queue>
/***** CONSTANTS/GLOBALS/ENUMERATIONS *****/
/*
* Strings for displaying information to user. These are stored
* in flash to avoid taking up space in RAM.
*/
const char intro_line1[] PROGMEM = "Maze";
const char intro_line2[] PROGMEM = "Solver";
const char calib_line1[] PROGMEM = "Calib.";
const char calib_line2[] PROGMEM = "Sensors";
/*
* Sounds for debugging.
*/
const char beep[] PROGMEM = ">g32>>c32";
/*
* The type of junction that the robot has encountered.
* From the HBRC rules, these are as follows:
*
* 1) Maze's End
* 2) Plus (+)
* 3) Tee ( T )
* 4) Left 90 Degree Turn
* 5) Right 90 Degree Turn
* 6) Straight Line
*/
enum JUNCTION_TYPES
{
MAZE_END=0,
PLUS,
TEE,
LEFT_TURN,
RIGHT_TURN,
STRAIGHT
};
/***** END SECTION CONSTANTS *****/
/***** FUNCTION PROTOTYPES *****/
void Display2Lines( const char *line1, const char *line2 );
void OnForXMSecs( const int leftPower, const int rightPower, const int millisecs );
void InitializeRobot();
void CalibrateLineSensors();
void PerformMappingRun();
void PerformActualRun();
enum JUNCTION_TYPES DetermineJunctionType();
/***** END SECTION FUNCTION PROTOTYPES *****/
/*
* This helper function displays two lines of text
* for 1 second before clearing the screen.
*/
void Display2Lines( const char *line1, const char *line2 )
{
print_from_program_space( line1 );
lcd_goto_xy( 0, 1 );
print_from_program_space( line2 );
play_from_program_space( beep );
delay( 1000 );
clear();
}
/*
* This function sets the motors to run at their specified
* speeds for the given number of milliseconds.
*/
void OnForXMSecs( const int leftPower, const int rightPower,
const int millisecs )
{
set_motors( leftPower, rightPower );
delay_ms( millisecs );
set_motors( 0, 0 );
}
/*
* This helper function spins the robot in place
* by 45 degrees so the line sensors can calibrate.
*/
void CalibrateLineSensors()
{
// Display a message for beginning calibration:
Display2Lines( calib_line1, calib_line2 );
// Wait for the user to press the B Button before moving:
while( !button_is_pressed( BUTTON_B ) )
{
clear();
print( "Press B" );
delay_ms( 100 );
}
// Wait for the user to release the B Button before spinning to calibrate:
wait_for_button_release( BUTTON_B );
delay( 1000 );
clear();
// The amount to spin:
const int SPIN_SPEED = 30;
set_motors( SPIN_SPEED, -1 * SPIN_SPEED );
}
/*
* This function initializes the 3pi. This includes
* displaying the welcome message, initializing the sensors
* etc.
*/
void InitializeRobot()
{
// Initialize the 3pi sensors:
pololu_3pi_init( 2000 );
// Display the "Maze Solver" message:
Display2Lines( intro_line1, intro_line2 );
/*
* Check that the battery levels are acceptable. The
* 3pi uses 4 AAA batteries (at 1.5 Volts a piece).
*
*/
// Finally, spin in place and calibrate the line sensors:
CalibrateLineSensors();
}
// Main function:
int main()
{
// Initialize the 3pi
InitializeRobot();
return 0;
}
|
C
|
/*
// Created by hn on 6/18/20.
*/
#include <stdlib.h>
#include "cpp2c_defs_poly.h"
extern funPtr MultiplierVTable[2];
void doPrePostFixer()
{
PrePostFixer angleBrackets;
printf("\n--- start doPrePostFixer() ---\n\n");
PrePostFixer_CTOR_kcpkcp(&angleBrackets, "<<< ", " >>>");
PrePostFixer_print_kcp(&angleBrackets, "Hello World!");
PrePostFixer_print_lc(&angleBrackets, -777, '\0');
PrePostFixer_print_lc(&angleBrackets, 350, '#');
PrePostFixer_print_lc(&angleBrackets, (long int)3.14, '\0');
printf("\n--- end doPrePostFixer() ---\n\n");
angleBrackets.defaultTextFormatter.textFormatter._vptr[0](&angleBrackets);
}
void doPrePostDollarFixer()
{
PrePostDollarFixer asterisks;
printf("\n--- start doPrePostDollarFixer() ---\n\n");
PrePostDollarFixer_CTOR_kcpkcp(&asterisks, "***** ", " *****");
PrePostDollarFixer_print_ic(&asterisks, -777, '$');
PrePostDollarFixer_print_ic(&asterisks, 350, '#');
PrePostDollarFixer_print_dc(&asterisks, 3.14f, '$');
printf("\n--- end doPrePostDollarFixer() ---\n\n");
PrePostDollarFixer_DTOR(&asterisks);
}
void doPrePostChecker()
{
PrePostChecker check;
printf("\n--- start doPrePostChecker() ---\n\n");
PrePostChecker_CTOR(&check);
PrePostChecker_printThisSymbolUsingFunc(&check);
PrePostChecker_printThisSymbolDirectly(&check);
PrePostChecker_printDollarSymbolByCastDirectly(&check);
PrePostChecker_printDollarSymbolByScopeDirectly(&check);
PrePostChecker_printDollarSymbolByCastUsingFunc(&check);
PrePostChecker_printDollarSymbolByScopeUsingFunc(&check);
printf("\n--- end doPrePostChecker() ---\n\n");
PrePostChecker_DTOR(&check);
}
void doPrePostFloatDollarFixer()
{
PrePostFloatDollarFixer hashes;
PrePostDollarFixer hashes2;
printf("\n--- start doPrePostFloatDollarFixer() ---\n\n");
PrePostFloatDollarFixer_CTOR_kcpkcp(&hashes, "### ", " ###");
PrePostFloatDollarFixer_print_f(&hashes, -777);
PrePostFloatDollarFixer_print_fc(&hashes, 350, '#');
PrePostFloatDollarFixer_print_f(&hashes, 3.14f);
PrePostDollarFixer_CTOR_kPrePostDollarFixerp(&hashes2, (PrePostDollarFixer*)&hashes);
PrePostDollarFixer_print_dc(&hashes2, 7.5, '$');
PrePostDollarFixer_print_ic(&hashes2, 100, '$');
printf("\n--- start doPrePostFloatDollarFixer() ---\n\n");
PrePostDollarFixer_DTOR(&hashes2);
PrePostFloatDollarFixer_DTOR(&hashes);
}
void runAsPrePostFixerRef(const PrePostFixer* pp){
printf("\n--- start runAsPrePostFixerRef() ---\n\n");
pp -> defaultTextFormatter.textFormatter._vptr[2](pp, 123, '\0');
printf("\n--- end runAsPrePostFixerRef() ---\n\n");
}
void runAsPrePostDollarFixerRef(const PrePostDollarFixer* pp){
printf("\n--- start runAsPrePostDollarFixerRef() ---\n\n");
PrePostDollarFixer_print_ic((PrePostDollarFixer*)pp, 123, '$');
printf("\n--- end runAsPrePostDollarFixerRef() ---\n\n");
}
void runAsPrePostDollarFixerObj(const PrePostDollarFixer pp)
{
printf("\n--- start runAsPrePostDollarFixerObj() ---\n\n");
PrePostDollarFixer_print_ic(&pp, 123, '$');
printf("\n--- end runAsPrePostDollarFixerObj() ---\n\n");
}
void runAsPrePostHashFixerRef(const PrePostHashFixer* pp){
printf("\n--- start runAsPrePostHashFixerRef() ---\n\n");
PrePostHashFixer_print_ic(pp, 123, '#');
printf("\n--- end runAsPrePostHashFixerRef() ---\n\n");
}
void doMultiplier() {
Multiplier m1, m2, m3, m4;
printf("\n--- start doMultiplier() ---\n\n");
DefaultTextFormatter_CTOR((DefaultTextFormatter*)&m1);
m1.DefaultTextFormatter.textFormatter._vptr = MultiplierVTable;
m1.times = 3;
printf("--- Multiplier CTOR: times = %d\n", 3);
DefaultTextFormatter_CTOR((DefaultTextFormatter*)&m2);
m2.DefaultTextFormatter.textFormatter._vptr = MultiplierVTable;
m2.times = 5;
printf("--- Multiplier CTOR: times = %d\n", 5);
DefaultTextFormatter_CTOR_kDefaultTextFormatter((DefaultTextFormatter*)&m3, (DefaultTextFormatter*)&m1);
m3.DefaultTextFormatter.textFormatter._vptr = m1.DefaultTextFormatter.textFormatter._vptr;
m3.times = m1.times;
DefaultTextFormatter_CTOR_kDefaultTextFormatter((DefaultTextFormatter*)&m4, (DefaultTextFormatter*)&m2);
m4.DefaultTextFormatter.textFormatter._vptr = m2.DefaultTextFormatter.textFormatter._vptr;
m4.times = m2.times;
Multiplier_print_kcp(&m1, "abc ");
Multiplier_print_kcp(&m2, "abc ");
Multiplier_print_kcp(&m3, "abc ");
Multiplier_print_kcp(&m4, "abc ");
printf("\n--- start doMultiplier() ---\n\n");
Multiplier_Dtor(&m4);
Multiplier_Dtor(&m3);
Multiplier_Dtor(&m2);
Multiplier_Dtor(&m1);
}
void doFormatterArray(){
PrePostDollarFixer prePostDollarFixer;
Multiplier multiplier;
PrePostChecker prePostChecker;
DefaultTextFormatter formatters[3];
int i;
printf("\n--- start doFormatterArray() ---\n\n");
PrePostDollarFixer_CTOR_kcpkcp(&prePostDollarFixer, "!!! ", " !!!");
DefaultTextFormatter_CTOR_kDefaultTextFormatter(&formatters[0], (DefaultTextFormatter*)&prePostDollarFixer);
PrePostDollarFixer_DTOR(&prePostDollarFixer);
DefaultTextFormatter_CTOR((DefaultTextFormatter*)&multiplier);
multiplier.DefaultTextFormatter.textFormatter._vptr = MultiplierVTable;
multiplier.times = 4;
printf("--- Multiplier CTOR: times = %d\n", 4);
DefaultTextFormatter_CTOR_kDefaultTextFormatter(&formatters[1], (DefaultTextFormatter*)&multiplier);
Multiplier_Dtor(&multiplier);
PrePostChecker_CTOR(&prePostChecker);
DefaultTextFormatter_CTOR_kDefaultTextFormatter(&formatters[2], (DefaultTextFormatter*)&prePostChecker);
PrePostChecker_DTOR(&prePostChecker);
for (i = 0; i < 3; ++i)
DefaultTextFormatter_print_kcp(&formatters[i], "Hello World!");
printf("\n--- end doFormatterArray() ---\n\n");
for (i = 2; i >= 0; --i) {
DefaultTextFormatter_DTOR(&formatters[i]);
}
}
void doFormatterPtrs()
{
DefaultTextFormatter* pfmt[3];
int i;
printf("\n--- start doFormatterPtrs() ---\n\n");
pfmt[0] = malloc(sizeof(PrePostDollarFixer));
PrePostDollarFixer_CTOR_kcpkcp((PrePostDollarFixer*)pfmt[0], "!!! ", " !!!");
pfmt[1] = malloc(sizeof(Multiplier));
DefaultTextFormatter_CTOR((DefaultTextFormatter*)pfmt[1]);
((Multiplier*)pfmt[1])->DefaultTextFormatter.textFormatter._vptr = MultiplierVTable;
((Multiplier*)pfmt[1])->times = 4;
printf("--- Multiplier CTOR: times = %d\n", 4);
pfmt[2] = malloc(sizeof(PrePostChecker));
PrePostChecker_CTOR((PrePostChecker*)pfmt[2]);
for (i = 0; i < 3; ++i)
pfmt[i]->textFormatter._vptr[1](pfmt[i], "Hello World!");
for (i = 2; i >= 0; --i) {
pfmt[i]->textFormatter._vptr[0](pfmt[i]);
free(pfmt[i]);
}
printf("\n--- end doFormatterPtrs() ---\n\n");
}
void doFormatterDynamicArray()
{
DefaultTextFormatter* formatters;
int i;
printf("\n--- start doFormatterDynamicArray() ---\n\n");
formatters = generateFormatterArray();
for (i = 0; i < 3; ++i)
formatters[i].textFormatter._vptr[1](&formatters[i], "Hello World!");
for (i = 2; i >= 0; --i)
formatters[i].textFormatter._vptr[0](&formatters[i]);
free(formatters);
printf("\n--- start doFormatterDynamicArray() ---\n\n");
}
int main()
{
PrePostHashFixer hfix;
PrePostDollarFixer tmp;
printf("\n--- Start main() ---\n\n");
doPrePostFixer();
doPrePostDollarFixer();
doPrePostFloatDollarFixer();
doPrePostChecker();
PrePostHashFixer_CTOR_i(&hfix, 4);
runAsPrePostFixerRef((PrePostFixer*)&hfix);
runAsPrePostDollarFixerRef((PrePostDollarFixer*)&hfix);
PrePostDollarFixer_CTOR_kPrePostDollarFixerp(&tmp, (PrePostDollarFixer*)&hfix);
runAsPrePostDollarFixerObj(tmp);
PrePostDollarFixer_DTOR(&tmp);
runAsPrePostHashFixerRef(&hfix);
doMultiplier();
doFormatterArray();
doFormatterPtrs();
doFormatterDynamicArray();
printf("\n--- End main() ---\n\n");
PrePostHashFixer_DTOR(&hfix);
return 0;
}
|
C
|
/*
** try_separator.c for in /home/hugo/PSU_2016_42sh
**
** Made by Hugo
** Login <hugo.tallineau@epitech.eu>
**
** Started on Sun May 21 21:58:07 2017 Hugo
** Last update Sun May 21 22:04:13 2017 Hugo
*/
#include <string.h>
#include <stdlib.h>
#include "proto.h"
t_graph *set_default_graph(void)
{
t_graph *new;
if ((new = malloc(sizeof(t_graph))) == NULL)
exit(84);
new->cmd = NULL;
new->left = NULL;
new->right = NULL;
new->type = SYMBOLE;
return (new);
}
void free_left_right(t_graph *left, t_graph *right)
{
free(left);
free(right);
}
t_graph *try(char *cmd, size_t i, char *separator, t_graph *graph)
{
t_graph *left;
t_graph *right;
left = set_default_graph();
right = set_default_graph();
if (strncmp(&cmd[i], separator, strlen(separator)) == 0)
{
graph->cmd = strndup(&cmd[i], strlen(separator));
cmd[i] = '\0';
(i > 0) ? cmd[i - 1] = '\0' : 0;
graph->left = parse(&cmd[0], left);
if (cmd[i + strlen(separator)] == '\0')
{
cmd[i + 1] = '\0';
graph->right = parse(&cmd[i + strlen(separator)], right);
}
else
{
cmd[i + 1] = '\0';
graph->right = parse(&cmd[i + strlen(separator) + 1], right);
}
}
else
free_left_right(left, right);
return (graph);
}
|
C
|
#include<stdio.h>
#define TRUE 1
#define FALSE 0
#define HEAP_LEN 100
typedef char DATATYPE;
typedef struct Heap {
int NumofData;
DATATYPE arr[HEAP_LEN];
} Heap;
void HeapInit(Heap *THeap);
int IsEmpty(Heap *THeap);
void HeapInsert(Heap *THeap, DATATYPE Data);
DATATYPE HeapDelete(Heap *THeap);
int RetIndexParent(int index);
int RetIndexLeftChild(int index);
int RetIndexRightChild(int index);
int RetIndexHigherPriorityOfChilds(Heap *THeap, int index);
void PrintAll(Heap *THeap);
void HeapInit(Heap *THeap) {
THeap->NumofData=0;
}
int IsEmpty(Heap *THeap) {
if (THeap->NumofData==0) {
return TRUE;
}
else {
return FALSE;
}
}
void HeapInsert(Heap *THeap, DATATYPE Data) {
int index=THeap->NumofData+1;
while (index!=1) {
if ((Data-THeap->arr[RetIndexParent(index)]) > 0) {
THeap->arr[index]=THeap->arr[RetIndexParent(index)];
index=RetIndexParent(index);
}
else {
break;
}
}
THeap->arr[index]=Data;
THeap->NumofData+=1;
}
DATATYPE HeapDelete(Heap *THeap) {
DATATYPE Data=THeap->arr[1];
DATATYPE last=THeap->arr[THeap->NumofData];
int ParentIndex=1;
int ChildIndex;
while (ChildIndex=RetIndexHigherPriorityOfChilds(THeap, ParentIndex)) {
if ((last-THeap->arr[ChildIndex])>=0) {
break;
}
THeap->arr[ParentIndex]=THeap->arr[ChildIndex];
ParentIndex=ChildIndex;
}
THeap->arr[ParentIndex]=last;
THeap->NumofData-=1;
return Data;
}
int RetIndexParent(int index) {
return index/2;
}
int RetIndexLeftChild(int index) {
return index*2;
}
int RetIndexRightChild(int index) {
return RetIndexLeftChild(index)+1;
}
int RetIndexHigherPriorityOfChilds(Heap *THeap, int index) {
if (RetIndexLeftChild(index) > THeap->NumofData) {
return 0;
}
else if (RetIndexLeftChild(index) == THeap->NumofData) {
return RetIndexLeftChild(index);
}
else {
if ((THeap->arr[RetIndexRightChild(index)]-THeap->arr[RetIndexLeftChild(index)])>0) {
return RetIndexRightChild(index);
}
else {
return RetIndexLeftChild(index);
}
}
}
void PrintAll(Heap *THeap) {
for (int i=1;i<THeap->NumofData+1;i++) {
printf("%d : %c\n", i, THeap->arr[i]);
}
}
int main(int argc, char*argv[]) {
Heap heap;
HeapInit(&heap);
HeapInsert(&heap, 'T');
HeapInsert(&heap, 'H');
HeapInsert(&heap, 'I');
HeapInsert(&heap, 'S');
HeapInsert(&heap, 'I');
HeapInsert(&heap, 'S');
HeapInsert(&heap, 'H');
HeapInsert(&heap, 'E');
HeapInsert(&heap, 'A');
HeapInsert(&heap, 'P');
PrintAll(&heap);
printf("\n");
printf("%c\n", HeapDelete(&heap));
printf("\n");
PrintAll(&heap);
printf("\n");
while (!IsEmpty(&heap)) {
printf("%c\n", HeapDelete(&heap));
}
return 0;
}
|
C
|
//READ A SIGNLE CHARECTER INTO FILE AND DISPLAY IT:
#include<stdio.h>
#include<conio.h>
void main(){
FILE *fp;
char c;
fp=fopen("a.txt","r");
while((c=fgetc(fp))!=EOF){
printf("%c",c);
}
fclose(fp);
getch();
}
/*output:
HELLO STUDENTS
*/
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int Out[5000][5000]={0};
void Output(int n,int num)
//nǼλ numpow(2,n)
{
if(n==1) //num=2
{
Out[0][0]=0;
Out[1][0]=1;
return;
}
int i=0,j=0;
for(i=0;i<num/2;i++)
{
Out[i][n-1]=0;
Out[num-i-1][n-1]=1;
}//ݹ ĩλ0 1
Output(n-1,num/2);
for(i=num/2;i<num;i++)
for(j=0;j<n-1;j++)//ǰһ
Out[i][j]=Out[num-i-1][j];
}
int main()
{
FILE *In,*Ou;
int n;
if((In=fopen("D:\\input.txt","r"))!=NULL)
{
fscanf(In,"%d",&n);
fclose(In);
int i=1;
Output(n,pow(2,n));//
}
else
{
printf("ļʧܣ\n");
}
if((Ou=fopen("D:\\output.txt","w"))!=NULL)
{
int i=0,j=0;
for(i=0;i<pow(2,n);i++)
{
for(j=0;j<n;j++)
fprintf(Ou,"%d",Out[i][j]);
fprintf(Ou,"\n");
}
fclose(Ou);
}
else
{
printf("ļʧ\n");
}
return 0;
}
|
C
|
/*
* Queue operation implementation
*
*/
#include "queue.h"
queue_t* q_init() {
queue_t *nq = malloc(sizeof(*nq));
nq->list = malloc(sizeof(*nq->list));
nq->flags = 0;
nq->last_op = 0;
return nq;
}
void q_enqueue(queue_t *q, struct generic_data data) {
if(q_size(q)==QUEUE_MAX_CAPACITY) {
mds_error(E_FULL_QUEUE, "Queue is full");
return;
}
ll_insert_end(q->list, data);
}
struct generic_data q_dequeue(queue_t *q) {
if(q_isEmpty(q)) {
mds_error(E_EMPTY_QUEUE, "Queue is empty");
return;
}
return ll_remove(q->list, q_size(q));
}
struct generic_data q_front(queue_t *q) {
if(q_isEmpty(q)) {
mds_error(E_EMPTY_QUEUE, "Queue is empty");
return;
}
return ll_get(q->list, q_size(q));
}
size_t q_size(queue_t *q) {
return q->list->total;
}
uchar_t q_isEmpty(queue_t *q) {
return (q_size(q)==0);
}
void q_print(queue_t *q) {
printf("Queue elements (front first):\n");
ll_walk(q->list, ll_print_elem);
}
/* Example usage (old)
* Round robin scheduler
* Each generic_data element could be considered as describing a process:
* the key is the name of the process, the value is the PID */
void round_robin_scheduler(struct generic_data *processes, size_t total) {
int i, total_time, temp;
queue_t queue = q_init();
for(i=0;i<total;i++)
q_queue(processes[i]);
for(total_time=0;total_time<3600;total_time++) {
for(i=0;i<total;i++) {
struct generic_data temp = q_dequeue();
f_process(temp);
q_enqueue(temp);
}
}
}
void f_process(struct generic_data process) {
process.value = (process.value++)%1000;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
int factorial(int n)
{
printf("Entra en la funcion factorial, n vale: %d \t", n);
if(n > 1)
{
//si n es mayor que 1, entonces se vuelve a llamar la funcion multiplicar a n ** (n-1
printf("La funcion se llama a si mismo otrea vez. \n\n");
return n * factorial(n-1);
}
else
{
//si n es igual 1, ya nos se llama la funcion a si misma para terminar la recursividad.
printf("n es igual a 1, termina la recursividad. \n");
return 1;
}
}
int main()
{
printf("Recursividad - Factorial.\n\n\n");
int res = factorial(10);
printf("\nEl resultado es: %d \n\n", res);
return 0;
}
|
C
|
#ifndef __LOG_H__
#define __LOG_H__
#include <stdio.h>
#include <sys/time.h>
// Log levels
#define LEVEL_NONE 0
#define LEVEL_ERROR 1
#define LEVEL_WARN 2
#define LEVEL_INFO 3
#define LEVEL_DEBUG 4
#define LEVEL_TRACE 5
#define LOG_ERROR(...) logger_write(LEVEL_ERROR,__FILE__,__LINE__,NULL,__VA_ARGS__);
#define LOG_WARN(...) logger_write(LEVEL_WARN, __FILE__,__LINE__,NULL,__VA_ARGS__);
#define LOG_INFO(...) logger_write(LEVEL_INFO, __FILE__,__LINE__,NULL,__VA_ARGS__);
#define LOG_DEBUG(...) logger_write(LEVEL_DEBUG,__FILE__,__LINE__,NULL,__VA_ARGS__);
#define LOG_TRACE(...) logger_write(LEVEL_TRACE,__FILE__,__LINE__,NULL,__VA_ARGS__);
#define LOG_INFO_TIME(time,...) logger_write(LEVEL_INFO, __FILE__,__LINE__,time,__VA_ARGS__);
#define LOG_DEBUG_TIME(time,...) logger_write(LEVEL_DEBUG,__FILE__,__LINE__,time,__VA_ARGS__);
#define LOG_TRACE_TIME(time,...) logger_write(LEVEL_TRACE,__FILE__,__LINE__,time,__VA_ARGS__);
int logger_init(int level, FILE* out);
int logger_set_thread_name(const char* name);
int logger_write(int level, const char* file, int line, struct timeval * time, const char* format, ...);
int logger_destroy();
#endif
|
C
|
#include<stdio.h>
#include<locale.h>
int main(){
setlocale(LC_ALL,"Portuguese");
float notaA,notaB,notaC,media;
printf("\nPor favor digite as notas dos alunos A,B e C:\n");
scanf("%f",¬aA);
scanf("%f",¬aB);
scanf("%f",¬aC);
if(notaA && notaB && notaC <= 10.0){
media = (((notaA*2)+(notaB*3)+(notaC*5))/10);
printf("\nA mdia :\n%f\n",media);
}
else
printf("\n As notas devem conter valores de 0.0 a 10.0!\n");
return 0;
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_strcspn.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: aponomar <aponomar@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2019/12/03 19:29:36 by aponomar #+# #+# */
/* Updated: 2019/12/17 19:30:53 by aponomar ### ########.fr */
/* */
/* ************************************************************************** */
#include <stdio.h>
#include <string.h>
#include <time.h>
size_t ft_strcspn(const char *s, const char *reject)
{
size_t size;
size_t i;
size_t min_size;
i = 0;
min_size = 0;
if (reject[i] == '\0')
{
while (s[i] != '\0')
i++;
return (i);
}
while (reject[i])
{
size = 0;
while (s[size])
{
if (s[size] == reject[i])
{
if (size == 0)
return (size);
else if (min_size > size)
min_size = size;
else if (size > min_size && min_size == 0)
min_size = size;
}
size++;
}
reject++;
}
if (min_size == 0)
while (s[min_size])
min_size++;
return (min_size);
}
int main(void)
{
// Calculate the time taken by fun()
clock_t t;
t = clock();
// int size;
int ft_size;
// initializing strings
char *str1 = "11111111123112312312313123123123123123123123123123123123123123123123123123123123123123123123123123111111111231123123123131231231231231231231231231231231231231231231231231231231231231231231231231231111111112311231231231312312312312312312312312312312312312312312312312312312312312312312312312312311111111123112312312313123123123123123123123123123123123123123123123123123123123123123123123123123111111111231123123123131231231231231231231231231231231231231231231231231231231231231231231231231231111111112311231231231312312312312312312312312312312312312312312312312312312312312312312312312312311111111123112312312313123123123123123123123123123123123123123123123123123123123123123123123123123111111111231123123123131231231231231231231231231231231231231823123123123123123123123123123123123123";
char *str2 = "0909090909090909090909090900dfgdsfgsdfgsdfg9898098-88-888887987878788798797897897987";
// using strcspn() to calculate initial chars
// before 1st matching chars 'f'.
// returns 24
// size = strcspn(str1, str2);
ft_size = ft_strcspn(str1, str2);
// printf("The unmatched characters before first matched character (strcspn):\t%d\n", size);
printf("The unmatched characters before first matched character (ft_strcspn):\t%d\n", ft_size);
t = clock() - t;
double time_taken = ((double)t)/CLOCKS_PER_SEC; // in seconds
// printf("strcspn took %f seconds to execute \n", time_taken);
printf("ft_strcspn took %f seconds to execute \n", time_taken);
return (0);
}
|
C
|
#include <stdio.h>
int main(void) {
float x, y;
char sign = '+';
while (sign != '0') {
printf("Input the sign: ");
scanf("%c%*c", &sign);
if (sign == '0') { break; }
if (sign == '+' || sign == '-' || sign == '*' || sign == '/') {
printf("x=");
scanf("%f%*c", &x);
printf("y=");
scanf("%f%*c", &y);
switch (sign) {
case '+':
printf("%.2f\n", x + y);
break;
case '-':
printf("%.2f\n", x - y);
break;
case '*':
printf("%.2f\n", x*y);
break;
case '/':
if (y != 0) printf("%.2f\n", x / y);
else printf("Must not! \n");
}
}
else printf("Write a sign \n");
}
return 0;
}
|
C
|
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef APACHE_HTRACE_UTIL_STRING_H
#define APACHE_HTRACE_UTIL_STRING_H
/**
* @file string.h
*
* Functions for manipulating strings.
*
* This is an internal header, not intended for external use.
*/
struct htrace_log;
/**
* Print to a buffer and move the pointer forward by the number of bytes
* written.
*
* @param buf (inout) The buffer to write to. We will advance this
* buffer by the number of bytes written.
* If this buffer is NULL, nothing will be written.
* @param rem (inout) The maximum number of bytes to write to the
* buffer. If bytes are written to the buffer, this
* number will be decremented by that amount.
* @param fmt Printf-style format string.
*
* @return The number of bytes that would have been used if bytes
* had been written
*/
int fwdprintf(char **buf, int* rem, const char *fmt, ...)
__attribute__((format(printf, 3, 4)));
/**
* Validate that a string could appear in a JSON expression without causing
* problems. We don't accept control characters, double quotes, backslashes,
* tabs, newlines, or carriage returns.
*
* @param lg The log to print messages about invalid strings to.
* @param str The string.
*
* @return 0 if the string is problematic; 1 if it's safe.
*/
int validate_json_string(struct htrace_log *lg, const char *str);
/**
* Parse an endpoint string.
*
* We support a few different formats:
* Hostname/port:
* my.hostname:9075
* ipv4/port:
* 127.0.0.1:9075
* ipv6/port:
* [2001:db8:85a3:8d3:1319:8a2e:370:7348]:9075
*
* @param lg The htrace log object.
* @param endpoint The endpoint string.
* @param default_port The default port to use if no port is given.
* @param remote (out param) The remote name. Malloced.
* @param port (out param) The port.
*
* @return 0 on failure; 1 on success.
*/
int parse_endpoint(struct htrace_log *lg, const char *endpoint,
int default_port, char **remote, int *port);
#endif
// vim: ts=4:sw=4:et
|
C
|
#include <stdio.h>
#include <stdlib.h>
#define WEBSITES 100
#define TRIALS 40
int get_index(int web, int trial){
return (web-1)*TRIALS+trial-1;
}
void parse_onefile(double** matrix, char* infname){
int webx,weby,trialx,trialy,lengthx,lengthy;
double dis;
char cruft;
int line = 0;
FILE* fin;
if((fin = fopen(infname, "r")) == NULL){
printf("cannot open %s for reading\n", infname);
exit(1);
}
while(fscanf(fin, "%d;%d;%d;%d;%d;%d;%lf%c", &webx,&trialx,&weby,&trialy,&lengthx,&lengthy,&dis,&cruft) == 8){
matrix[get_index(webx,trialx)][get_index(weby,trialy)] = dis;
line ++;
}
printf("parsing %s finished, lines = %d\n",infname,line);
fclose(fin);
}
void writetofile(double** matrix, char* outfname){
int dim = WEBSITES*TRIALS;
int i, j;
FILE* fout;
if((fout = fopen(outfname, "w")) == NULL){
printf("cannot open %s for writing\n", outfname);
exit(1);
}
for(i = 0; i < dim; i++){
for(j = 0; j < dim; j++){
fprintf(fout, "%lf ", matrix[i][j]);
}
fprintf(fout, "\n");
}
}
int main(int argc, char** argv){
int i,j;
int dim = WEBSITES*TRIALS;
char* outfname = argv[1];
double** matrix = (double**)malloc(sizeof(double*) * dim);
for(i = 0; i < dim; i++){
matrix[i] = (double*)malloc(sizeof(double)* dim);
}
for(i = 0; i < dim; i++)
matrix[i][i] = 0.0f;
for(i = 2; i < argc; i++){
parse_onefile(matrix, argv[i]);
}
printf("start writing to file ...\n");
writetofile(matrix, outfname);
printf("finished\n");
return 0;
}
|
C
|
#include "holberton.h"
#include <stdlib.h>
/**
*malloc_checked -should cause normal process termination with a status value.
* @b: is a number.
*
* Return: Nothing.
*/
void *malloc_checked(unsigned int b)
{
int *a;
a = malloc(b);
if (a == NULL)
exit(98);
return (a);
}
|
C
|
/*
** EPITECH PROJECT, 2021
** mylib
** File description:
** mylib
*/
#include "../../includes/client.h"
static int thread_create(connect_t *con)
{
if (con->status != THREAD_CREATED)
return 0;
char *uuid = cjson_get_by_key(con->res, "uuid");
char *title = cjson_get_by_key(con->res, "title");
char *body = cjson_get_by_key(con->res, "body");
char *timestamp = cjson_get_by_key(con->res, "timestamp");
char *user_uuid = cjson_get_by_key(con->res, "user_uuid");
client_print_thread_created(uuid, user_uuid, atoi(timestamp), title, body);
client_event_thread_created(uuid, user_uuid, atoi(timestamp), title, body);
free(uuid);
free(title);
free(body);
free(timestamp);
free(user_uuid);
return 1;
}
static int channel_create(connect_t *con)
{
if (con->status != CHANNEL_CREATED)
return 0;
char *uuid = cjson_get_by_key(con->res, "uuid");
char *name = cjson_get_by_key(con->res, "name");
char *description = cjson_get_by_key(con->res, "description");
client_print_channel_created(uuid, name, description);
client_event_channel_created(uuid, name, description);
free(uuid);
free(name);
free(description);
return 1;
}
static int team_create(connect_t *con)
{
if (con->status != TEAM_CREATED)
return 0;
char *uuid = cjson_get_by_key(con->res, "uuid");
char *name = cjson_get_by_key(con->res, "name");
char *description = cjson_get_by_key(con->res, "description");
client_print_team_created(uuid, name, description);
client_event_team_created(uuid, name, description);
free(uuid);
free(name);
free(description);
return 1;
}
static int reply_create(connect_t * con)
{
if (con->status != REPLY_CREATED)
return 0;
char *uuid = cjson_get_by_key(con->res, "uuid");
char *body = cjson_get_by_key(con->res, "body");
char *timestamp = cjson_get_by_key(con->res, "timestamp");
char *user_uuid = cjson_get_by_key(con->res, "user_uuid");
char *team_uuid = cjson_get_by_key(con->res, "team_uuid");
client_print_reply_created(uuid, user_uuid, atoi(timestamp), body);
client_event_thread_reply_received(team_uuid, uuid, user_uuid, body);
free(uuid);
free(body);
free(timestamp);
free(user_uuid);
free(team_uuid);
return 1;
}
int create(connect_t *con)
{
int tot = 0;
tot += team_create(con);
tot += channel_create(con);
tot += thread_create(con);
tot += reply_create(con);
return tot;
}
|
C
|
/*
* rtc.c
*
* Created: 1/4/2020 8:04:14 PM
* Author: runne
*/
#include "i2cmaster.h"
#include "rtc.h"
#include <stdbool.h>
uint8_t rtc_read(unsigned char reg)
{
uint8_t data;
i2c_start(DS3231_SLAVE_ADDRESS+I2C_WRITE);
i2c_write(reg);
i2c_stop();
i2c_start(DS3231_SLAVE_ADDRESS+I2C_READ);
data = i2c_readNak();
i2c_stop();
return data;
}
void rtc_write(unsigned char reg, unsigned char value)
{
i2c_start(DS3231_SLAVE_ADDRESS+I2C_WRITE);
i2c_write(reg);
i2c_write(value);
i2c_stop();
}
uint8_t toSeconds(uint8_t i2c_seconds_register_read_data)
{
return (i2c_seconds_register_read_data&0x0F) // ones, 0b0000 1111
+ (((i2c_seconds_register_read_data&0x70)>>4)*10); // tens, 0b0111 0000 >> 4 * 10
}
uint8_t toMinutes(uint8_t i2c_minutes_register_read_data)
{
return (i2c_minutes_register_read_data&0x0F) // ones, 0b0000 1111
+ (((i2c_minutes_register_read_data&0x70)>>4)*10); // tens, 0b0111 0000 >> 4 * 10
}
uint8_t toHours(uint8_t i2c_hours_register_read_data)
{
return (i2c_hours_register_read_data&0x0F) // ones, mask 0b0000 1111
+ (((i2c_hours_register_read_data&0x30)>>4)*10); // tens, 0b0011 0000 >> 4 * 10 // 24 hour clock
}
// extras below
// problem with this is that there could be stuff IN FRONT OF the 10s sec/min/hrs place
// so still better to be exact like above in my opinion.
uint8_t toRegisterValue(uint8_t decimal)
{
// getting the first digit in the tens position by dividing by 10 ( xxXx base 10 )
// that bit pattern represents # 10s needed, so shift by 4 to 2nd nibble so it is right
// section of the register to represent the #10s.
// %10 or 0x0F to get 1s and leave them be cause they are already in right position.
return ((decimal/10)<<4) + (decimal%10); // gets 10s place, shift, add remainder
}
uint8_t fromRegisterValue(uint8_t hex)
{
// getting the first bit in 2nd nibble ( xxxX xxxx base 2) by dividing by 16
// that bit pattern represents # 10s of sec/min/hr, so multiply by 10
// %16 or &0x0F to get 1s of seconds represented by first nibble
return ((hex>>4) * 10) + (hex % 16);
}
// these from exploreembedded library, give me some ideas.
uint8_t dec2bcd(char num)
{
return ((num/10 * 16) + (num % 10));
}
uint8_t bcd2dec(char num)
{
return ((num/16 * 10) + (num % 16)); // first 4 bits never represent more than 9. Also, same as & 0x0F
// modulus 16 basically kills off anything past first nibble.
}
|
C
|
#ifndef LIST_H_
#define LIST_H_
#include <stdint.h>
typedef intptr_t val_t;
typedef struct __LIST_T {
val_t data;
struct node *next;
} list_t;
list_t *list_mid(list_t *list);
int list_add(list_t *list, val_t val);
void list_print(list_t *list);
int list_size(list_t *list)
#endif
|
C
|
#include<omp.h>
#include<stdio.h>
#include<time.h>
static long num_steps=100000;
#define NUM_THREADS 2
void main()
{
int i;
double x,pi=0,sum;
double step=1.0/num_steps;
struct timespec start, end;
clock_gettime(CLOCK_MONOTONIC, &start);
omp_set_num_threads(NUM_THREADS);
#pragma omp parallel private(i,x,sum)
{
int id=omp_get_thread_num();
for(i=id,sum=0;i<num_steps;i=i+NUM_THREADS)
{
x=(i+0.5)*step;
sum+=4.0/(1.0+x*x);
}
#pragma omp critical
pi+=sum*step;
}
clock_gettime(CLOCK_MONOTONIC, &end);
printf("PI :%lf\nTime: %lfs\n",pi, (end.tv_sec-start.tv_sec) + (end.tv_nsec - start.tv_nsec)/1000000000.0);
}
|
C
|
#include<stdio.h>
typedef long long int ll;
void swap (ll* a , ll* b)
{
ll temp = *a;
*a = *b;
*b = temp;
}
heap_insert(ll a[], ll n)
{
ll i;
for(i=1;i<(n+1);i++)
{
ll k;
scanf("%lld",&k);
a[i]=k;
ll j=i;
while( j > 1 && a[j]>a[j/2])
{
swap(a+j,a+j/2);
j=j/2;
}
}
ll b[n];
for(i=0;i<n;i++)
{
b[i]=a[i+1];
a[i]=b[i];
}
}
ll max(ll a[])
{
return a[0];
}
ll heap_delete_top(ll a[],ll n)
{
ll temp = a[0];
a[0]=a[n-1];
a[n-1]=a[0];
n=n-1;
ll i=0;
while(a[i]<=a[2*i+1] || a[i] <= a[2*i+2])
{
if(2*i+1>n)
break;
if(2*i+2>n)
break;
if(a[2*i+2]>a[2*i+1])
{
swap(a+i,a+2*i+2);
i=2*i+2;
}
else
{
swap(a+i,a+2*i+1);
i=i*2+1;
}
}
return n;
}
void printer(ll a[], ll n)
{
ll i;
for(i=0;i<n;i++)
printf("%lld ",a[i]);
printf("\n");
return;
}
void sort(ll a[], ll n)
{
ll b[n];
ll len=n;
ll i=0;
while(n>0)
{
b[i]=max(a);
n=heap_delete_top(a,n);
i=i+1;
}
for(i=0;i<len;i++)
a[i]=b[i];
}
int main()
{
ll a[100],n,i;
scanf("%lld",&n);
heap_insert(a,n);
printer(a,n);
sort(a,n);
printer(a,n);
return 0;
}
|
C
|
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
int main() {
while(1) {
int* ptr = (int*)malloc(1024*1024*10);
memset(ptr,0,1024*1024*10);
sleep(1);
}
return 0;
}
|
C
|
#include <stdio.h>
#include <string.h>
#include <SDL2/SDL.h>
#include <SDL2/SDL_image.h>
#include <SDL2/SDL_ttf.h>
#include "error.h"
#include "graphics.h"
#include "input.h"
// Blit a button on the main screen surface
int blit_button(struct s_context *cxt, const char *path, SDL_Rect pos, const char * text, const char *fpath)
{
int t = strlen(text);
SDL_Colour c;
SDL_Rect txtpos;
SDL_Surface *tmp;
SDL_Surface *b = IMG_Load(path);
TTF_Font *f = TTF_OpenFont(fpath, 36); // 16x16 pixels by character
if(b == NULL)
{
log_error("Could not create button surface", "blit_button", IMG_GetError(), 0);
return -1;
}
// Set text to fully opaque black (0x00A0A0)
c.r = 0x00;
c.g = 0x00;
c.b = 0x00;
c.a = 0xFF;
tmp = TTF_RenderText_Blended(f, text, c);
if(tmp == NULL)
{
log_error("Could not put text on button surface", "blit_button", TTF_GetError(), 0);
return -1;
}
// The text must be less than 13 characters long
// centralizes the string 'text' in the button
txtpos.x = 105 - ((t * 16) / 2);
txtpos.y = 30;
SDL_BlitSurface(tmp, NULL, b, &txtpos);
SDL_BlitSurface(b, NULL, cxt->screen, &pos);
// Clean up the mess
SDL_FreeSurface(tmp);
SDL_FreeSurface(b);
TTF_CloseFont(f);
return 0;
}
int close_app(struct s_context *ctx)
{
SDL_FreeSurface(ctx->screen);
SDL_DestroyWindow(ctx->win);
SDL_DestroyRenderer(ctx->ren);
IMG_Quit();
TTF_Quit();
SDL_Quit();
return 0;
}
int create_context(struct s_context *cxt, const char *title, const int sizex, const int sizey)
{
if(SDL_Init(SDL_INIT_EVERYTHING))
{
log_error("Could not initialize SDL", "create_context", SDL_GetError(), 1);
close_app(cxt);
}
if(IMG_Init(IMG_INIT_PNG) != IMG_INIT_PNG)
{
log_error("Could not initialize SDL_image", "create_context", IMG_GetError(), 1);
close_app(cxt);
}
if(TTF_Init())
{
log_error("Could not initialize SDL_ttf", "create_context", TTF_GetError(), 1);
close_app(cxt);
}
cxt->win = SDL_CreateWindow(title, SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, sizex, sizey, SDL_WINDOW_SHOWN);
cxt->ren = SDL_CreateRenderer(cxt->win, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC);
if(cxt->win == NULL || cxt->ren == NULL)
{
log_error("Can't create window and/or renderer", "create_context", SDL_GetError(), 1);
close_app(cxt);
}
// Set background as grey (0xD3D3D3)
cxt->screen = SDL_GetWindowSurface(cxt->win);
SDL_FillRect(cxt->screen, NULL, SDL_MapRGB(cxt->screen->format, 0xD3, 0xD3, 0xD3));
return 0;
}
int show(struct s_context cxt)
{
SDL_Texture *tmp = SDL_CreateTextureFromSurface(cxt.ren, cxt.screen);
SDL_RenderCopy(cxt.ren, tmp, NULL, NULL);
SDL_RenderPresent(cxt.ren);
SDL_DestroyTexture(tmp);
return 0;
}
int blit_text(struct s_context * cxt, const int size, const char *text, const char *fpath, SDL_Rect pos)
{
SDL_Surface *tmp;
SDL_Colour c;
TTF_Font *f = NULL;
f = TTF_OpenFont(fpath, size);
// fully opaque black (0x000000)
c.r = 0x00;
c.g = 0x00;
c.b = 0x00;
c.a = 0xFF;
// in case there's nothing to blit here
if(strlen(text) == 0)
return -1;
tmp = TTF_RenderText_Blended(f, text, c);
if(tmp == NULL)
{
log_error("Could not put text on temporary surface", "blit_text", TTF_GetError(), 0);
return -3; // Coudn't render
}
SDL_BlitSurface(tmp, NULL, cxt->screen, &pos);
SDL_FreeSurface(tmp);
TTF_CloseFont(f);
return 0;
}
int clear_screen(struct s_context * cxt)
{
// Clean main surface
cxt->screen = SDL_GetWindowSurface(cxt->win);
SDL_FillRect(cxt->screen, NULL, SDL_MapRGB(cxt->screen->format, 0xD3, 0xD3, 0xD3));
return 0;
}
int blit_element(struct s_context * cxt, const char * path, SDL_Rect pos)
{
SDL_Surface *element = IMG_Load(path);
if(element == NULL)
{
log_error("Coudn't load image file as surface", "blit_element", IMG_GetError(), 0);
return -2; // Coudn't load resource
}
SDL_BlitSurface(element, NULL, cxt->screen, &pos);
SDL_FreeSurface(element);
return 0;
}
|
C
|
#include "rubyfmt.h"
extern void init_logger();
extern void format_sexp_tree_to_stdout(ruby_string_pointer buf, VALUE tree);
extern void format_sexp_tree_to_file(
ruby_string_pointer filename,
ruby_string_pointer buf,
VALUE tree
);
VALUE rubyfmt_rb_module_rubyfmt = Qnil;
ruby_string_pointer ruby_string_pointer_from_value(VALUE string) {
ruby_string_pointer ret = {StringValuePtr(string), RSTRING_LEN(string)};
return ret;
}
VALUE rubyfmt_rb_format_to_stdout(VALUE _mod, VALUE file_buffer, VALUE tree) {
ruby_string_pointer file = ruby_string_pointer_from_value(file_buffer);
format_sexp_tree_to_stdout(file, tree);
return Qnil;
}
VALUE rubyfmt_rb_format_to_file(VALUE _mod, VALUE filename, VALUE file_buffer, VALUE tree) {
ruby_string_pointer fn_p = ruby_string_pointer_from_value(filename);
ruby_string_pointer buf = ruby_string_pointer_from_value(file_buffer);
format_sexp_tree_to_file(fn_p, buf, tree);
return Qnil;
}
char *rubyfmt_rstring_ptr(VALUE s) {
return RSTRING_PTR(s);
}
long rubyfmt_rstring_len(VALUE s) {
return RSTRING_LEN(s);
}
enum ruby_value_type rubyfmt_rb_type(VALUE v) {
return rb_type(v);
}
long long rubyfmt_rb_num2ll(VALUE v) {
return RB_NUM2LL(v);
}
long rubyfmt_rb_ary_len(VALUE v) {
return rb_array_len(v);
}
int rubyfmt_rb_nil_p(VALUE v) {
return RB_NIL_P(v);
}
void Init_rubyfmt() {
rubyfmt_rb_module_rubyfmt = rb_define_module("Rubyfmt");
init_logger();
rb_define_module_function(
rubyfmt_rb_module_rubyfmt,
"format_to_stdout",
rubyfmt_rb_format_to_stdout,
2
);
rb_define_module_function(
rubyfmt_rb_module_rubyfmt,
"format_to_file",
rubyfmt_rb_format_to_file,
3
);
}
void Init_rubyfmt_debug() {
Init_rubyfmt();
}
void Init_rubyfmt_release() {
Init_rubyfmt();
}
|
C
|
#include <stdio.h>
#include <cs50.h>
#include <ctype.h>
#include <string.h>
#include<stdbool.h>
/**
* vigenere cipher crypto program
*
*/
int k = 0;
bool KeyAlphaChars(string s);
char Encrypt(char a);
int GetK(char ki);
int main(int argc, string argv[])
{
if (argc == 1 || argc > 2 || (KeyAlphaChars(argv[1]) == false))
{
printf("Please use one key without any non-alphabetical characters\n");
return 1;
}
// get the phrase from user
string phrase = GetString();
//encrypt user input
int l = 0;
for (int i = 0, n = strlen(phrase); i < n; i++)
{
// calculate the k key
int keyLenght = strlen(argv[1]);
char keyChar;
keyChar= argv[1][(i - l) % keyLenght];
if (isalpha(phrase[i]))
{
GetK(keyChar);
Encrypt(phrase[i]);
printf("%c", Encrypt(phrase[i]));
}
else
{
printf("%c", phrase[i]);
l = l + 1;
}
}
printf("\n");
return 0;
}
// Checks if user input uses only alphabetical char
bool KeyAlphaChars(string s)
{
bool answer;
for (int i = 0, n = strlen(s); i < n; i++)
{
if ( isalpha( s[i] ) )
{
answer = true;
}
else answer = false;
}
return answer;
}
//mod26 function to calculate the key
int GetK(char ki)
{
k = 0;
if (islower(ki))
{
char a = 'a';
while(a < ki)
{
a++;
k++;
}
}
if (isupper(ki))
{
char a = 'A';
while (a < ki)
{
a++;
k++;
}
}
return k;
}
//Encrypt a character
char Encrypt(char a)
{
if (isalpha(a) != 0)
{
int j;
j = (int) a;
//encrypt a lower character
if (islower(a) != 0)
{
j = j - 97;
j = (j + k) % 26;
j = j + 97;
}
else
//encrypt a uppper character
if (isupper(a) != 0)
{
j = j - 65;
j = (j + k) % 26;
j = j + 65;
}
a = (char) j;
}
return a;
}
|
C
|
#ifndef __SORT_H__
#define __SORT_H__
/**
* @brief insert sort implement, (suitable for small sets of data)
*
* @param data : array of elements in data
* @param size : the number of elements in data
* @param esize : the size of each element
* @param compare : function pointer compare between elements
*
* @return 0:succes, -1:fail
*/
int insert_sort(void *data, int size, int esize, int (*compare)(const void *key1, const void *key2));
/**
* @brief quic sort
*
* @param data : array of elements in data
* @param esize : the size of each element
* @param start : current partition start position
* @param end : current partition end position
* @param compare : compare function
*
* @return 0:succes, -1:fail
*/
int quick_sort(void *data, int esize, int start, int end, int(*compare)(const void *key1, const void *key2));
#endif /* end of include guard */
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#define DNS_FILE "9_dns.txt"
#define LEN_128 128
int main ( int argc, char *argv[] )
{
FILE *fp;
if((fp=fopen(DNS_FILE,"r")) == NULL)
{
printf("Open file %s failed: %s\n",DNS_FILE,strerror(errno));
exit(-1);
}
char buf[LEN_128] = {0};
char *p = NULL;
while(fgets(buf,LEN_128,fp)){
#if 0
if(p = strstr(buf,"nameserver")){
printf("%s\n",buf+strlen("nameserver")+1);
}
//末尾多一个 \n
#endif
sscanf(buf,"nameserver %s\n",buf);
printf("%s\n",buf);
}
return 0;
}
|
C
|
/* Esercizio 6.21 */
#include<stdio.h>
#include<string.h>
#include<ctype.h>
#include<stdlib.h>
#include<assert.h>
int pal(char *);
int word_count(char *);
int word_len(char *, int);
int single_word_len(char *);
int pal_evo(char *, int);
char up_to_low(char);
int wspace = 0;
/************ MAIN ***********/
int main(int argc, char *argv[]){
FILE *pToFile = fopen(argv[1], "r");
char single;
char w[10000];
char *s; /*area di lavoro*/
int i = 0;
int j = 0;
static int z = 0;
while((single = fgetc(pToFile)) != EOF){
w[i++] = up_to_low(single);
wspace += isspace(w[i]);
}
*(w + i + 1) = '\0';
int input_len = strlen(w);
printf("Nel file abbiamo = %s", &w[0]);
printf("ovvero %d parole. In totale sono %d caratteri\n", word_count(w), input_len);
printf("\nSe togliamo gli spazi otteniamo:\n\n");
s = malloc((input_len - wspace) * sizeof(char));/* alloca spazio di lavoro per stringa */
assert(s != NULL); /* verifica allocamento */
while(*(w + j)){ /* trasferisci parola in area di lavoro*/
if(isspace(*(w + j))){
++j;
wspace += 1;
}
else{
*(s + z) = *(w + j);
++j; ++z;
}
}
*(s + z) = '\0';
printf("%s, di lunghezza %d\n ", s, (int)(strlen(s)));
printf("\ngli spazi bianchi erano %d.\n", wspace);
printf("La parola risultante%s palindroma.\n\n", pal(s)? " è": " non è");
free(s);
return 0;
}
/************ AUX ***********/
int pal(char *a){ /*Controlla se stringa è palindroma*/
int min = 0;
int max = strlen(a) - 1;
while(max > min){
if(a[min++] != a[max--])
return 0;
else
return 1;
}
}
int pal_evo(char *a, int max){ /* Controlla se palindroma, adattata a dimensione */
int min = 0; /* spaizo di lavoro */
while(max > min){
if(a[min++] != a[max--])
return 0;
else
return 1;
}
}
int word_count(char *s){ /* Conta singole parole in input */
int count = 0;
while(*s != '\0'){
while(isspace(*s))
++s;
if(*s != '\0'){
count++;
while(!isspace(*s) && *s != '\0'){
++s;
}
}
}
return count;
}
int word_len(char *s, int dim){ /* Riporta lunghezza parola di qualsiasi stringa */
if(*s != '\0'){
while(isspace(*s))
++s;
if(*s != '\0'){
while(!isspace(*s) && *s != '\0'){
++s; ++dim;
}
return dim;
}
word_len(s, 0);
}
else
return 0;
}
int single_word_len(char *s){ /* Lunghezza singola parola all'interno di una stringa */
int dim = 0;
while(*s != ' ' && *s != '\0'){
while(isspace(*s))
++s;
if(*s != '\0'){
if(!isspace(*s) && *s != ' '){
++s; dim++;
}
}
}
return dim;
}
char up_to_low(char c){ /*Converte maiuscole in minuscole */
if(c >= 65 && c <= 97)
return c += 32;
else
return c;
}
|
C
|
/*
* UDP client
*/
#include <stdio.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <errno.h>
/*
* クライアントの接続先サーバ情報
*/
struct client_info {
unsigned short sv_port;
char *sv_ipaddr;
char *msg;
};
typedef struct client_info cl_info_t;
/*!
* @brief UDP接続してメッセージを送る
* @param[in] sd ソケットディスクリプタ
* @param[in] sv_addr 接続先サーバ情報
* @param[in] msg 送信するメッセージ
* @param[out] errmsg エラーメッセージ格納先
* @return 成功ならば0、失敗ならば-1を返す。
*/
static int
udp_send_msg(int sd, struct sockaddr_in *sv_addr, char *msg,
char *errmsg)
{
int rc = 0;
int msg_len = strlen(msg) + 1;
/* メッセージの送信 */
rc = sendto(sd, msg, msg_len, 0, (struct sockaddr *)sv_addr,
sizeof(*sv_addr));
if(rc != msg_len){
sprintf(errmsg, "(line:%d) %s", __LINE__, strerror(errno));
return(-1);
}
return(0);
}
/*!
* @brief UDPクライアント実行
* @param[in] info クライアント接続情報
* @param[out] errmsg エラーメッセージ格納先
* @return 成功ならば0、失敗ならば-1を返す。
*/
static int
udp_client(cl_info_t *info, char *errmsg)
{
struct sockaddr_in sv_addr = {0};
int sd = 0;
int rc = 0;
/* ソケットの生成 : UDPを指定する */
sd = socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP);
if(sd < 0){
sprintf(errmsg, "(line:%d) %s", __LINE__, strerror(errno));
return(-1);
}
/* サーバのアドレス構造体を作成する */
memset(&sv_addr, 0, sizeof(sv_addr));
sv_addr.sin_family = AF_INET;
sv_addr.sin_addr.s_addr = inet_addr(info->sv_ipaddr);
sv_addr.sin_port = htons(info->sv_port);
/* 文字列を送信する */
rc = udp_send_msg(sd, &sv_addr, info->msg, errmsg);
/* ソケットの破棄 */
if(sd != 0) close(sd);
return( rc );
}
/*!
* @brief 初期化処理。IPアドレスとポート番号を設定する。
* @param[in] argc コマンドライン引数の数
* @param[in] argv コマンドライン引数
* @param[out] info クライアント接続情報
* @param[out] errmsg エラーメッセージ格納先
* @return 成功ならば0、失敗ならば-1を返す。
*/
static int
initialize(int argc, char *argv[], cl_info_t *info, char *errmsg)
{
if(argc != 4){
sprintf(errmsg, "Usage: %s <ip-addr> <port> <msg>", argv[0]);
return(-1);
}
memset(info, 0, sizeof(cl_info_t));
info->sv_ipaddr = argv[1];
info->sv_port = atoi(argv[2]);
info->msg = argv[3];
return(0);
}
/*!
* @brief main routine
* @return 成功ならば0、失敗ならば-1を返す。
*/
int
main(int argc, char *argv[])
{
int rc = 0;
cl_info_t info = {0};
char errmsg[256];
rc = initialize(argc, argv, &info, errmsg);
if(rc != 0){
fprintf(stderr, "Error: %s\n", errmsg);
return(-1);
}
rc = udp_client(&info, errmsg);
if(rc != 0){
fprintf(stderr, "Error: %s\n", errmsg);
return(-1);
}
return(0);
}
|
C
|
#include "libft.h"
#include <stdio.h>
#if SYSTEM == macos
# include <string.h>
#else
# include <bsd/string.h>
#endif
static void display_result(char *expected, char *result, int success)
{
printf("--------------\n");
(success) ? printf("\033[0;32mOK!\n") : printf("\033[0;31mKO!\n");
printf("Expected = \"%s\"\n", expected);
printf("Result = \"%s\"\n", result);
printf("\033[0m");
}
static int check_ft_strnstr(char *expected, char *got, size_t len)
{
if ((!expected && !got) || (!*expected && !*got))
return (1);
if (ft_strncmp(expected, got, len) == 0)
return (1);
return (0);
}
static void test_ft_strnstr(char *haystack, char *needle, size_t len, int *success, int *failure)
{
char *got;
char *expected;
got = ft_strnstr(haystack, needle, len);
expected = strnstr(haystack, needle, len);
if (check_ft_strnstr(expected, got, len))
{
(*success)++;
//display_result(expected, got, 1);
}
else
{
(*failure)++;
display_result(expected, got, 0);
}
}
void specs_ft_strnstr(void)
{
printf("\nTests for %s\n", &__func__[6]);
int success;
int failure;
success = 0;
failure = 0;
char *haystack = "bonjojour";
char *needle = "on ";
char *needle2 = "jour";
char *needle3 = "\0";
char *needle4 = "uri";
char *needle5 = "bon";
char *needle7 = "Bon";
char *needle6 = "ro";
char *needle8 = "joj";
char *needle9 = "bonjour";
char *str12 = "Hello wwworld";
char *o_find1 = "wworld";
char *str21 = "FooBarBaz";
char *o_find2 = "Baz";
char *testn = "tetehelllotetahelloteshellotstetstesthello";
char *needletestn = "test";
char needleweird[2];
needleweird[0] = -1;
needleweird[1] = 0;
char tofindweird[2];
tofindweird[0] = 43;
tofindweird[1] = 0;
char *big = "123456789";
char *little = "9";
test_ft_strnstr(needleweird, tofindweird, 15, &success, &failure);
test_ft_strnstr(haystack, needle, 15, &success, &failure);
test_ft_strnstr(str12, o_find1, 15, &success, &failure);
test_ft_strnstr(str21, o_find2, 15, &success, &failure);
test_ft_strnstr(haystack, needle, 15, &success, &failure);
test_ft_strnstr(haystack, needle2, 15, &success, &failure);
test_ft_strnstr(haystack, needle3, 15, &success, &failure);
test_ft_strnstr(haystack, needle4, 15, &success, &failure);
test_ft_strnstr(haystack, needle5, 15, &success, &failure);
test_ft_strnstr(haystack, needle6, 15, &success, &failure);
test_ft_strnstr(haystack, needle7, 15, &success, &failure);
test_ft_strnstr(haystack, needle8, 15, &success, &failure);
test_ft_strnstr(haystack, needle9, 10, &success, &failure);
test_ft_strnstr(needle3, needle4, 15, &success, &failure);
test_ft_strnstr(needle3, needle3, 15, &success, &failure);
test_ft_strnstr(testn, needletestn, 15, &success, &failure);
test_ft_strnstr(haystack, haystack, 15, &success, &failure);
test_ft_strnstr(haystack, "", 0, &success, &failure);
test_ft_strnstr(haystack, "j", 0, &success, &failure);
test_ft_strnstr(haystack, "j", 1, &success, &failure);
test_ft_strnstr(haystack, "j", 2, &success, &failure);
test_ft_strnstr(haystack, "j", 3, &success, &failure);
test_ft_strnstr(big, little, 8, &success, &failure);
test_ft_strnstr(haystack, needle5, 2, &success, &failure);
printf("\t%d success out of %d tests\n", success, (success + failure));
}
|
C
|
#include <asf.h>
#include <avr/delay.h>
#include <stdio.h>
#include <inttypes.h>
#include <math.h>
#include "uv_sensor.h"
#define START 0x08
#define RESTART 0x10
#define SL_ACK 0x18
#define MT_DATA_ACK 0x28
#define MR_SLA_ACK 0x40
//Si1145 Default Slave Address is 0x60
#define SI_SLA_W 0xc0
#define SI_SLA_R 0xc1
uint8_t SI_readI2Cbyte(uint8_t whichReg);
uint8_t SI_writeI2Cbyte(uint8_t whichReg, uint8_t data);
uint16_t SI_readI2Cword(uint8_t whichReg);
uint8_t SI_readI2Cbyte(uint8_t whichReg) {
uint8_t retValue;
TWCR = (1<<TWINT)|(1<<TWSTA)|(1<<TWEN); // send Start
while ( !(TWCR & (1<<TWINT) ) ); // Wait for Start to be transmitted
if ( (TWSR & 0xf8) != START) {
TWCR = (1<<TWINT) | (1<<TWEN) | (1<<TWSTO); // Send a Stop
return 0xaa;
}
TWDR = SI_SLA_W; // Send the slave module address + write bit
TWCR = (1<<TWINT) | (1<<TWEN); // Transmit the address and wait
while (!(TWCR & (1<<TWINT)));
if ( (TWSR & 0xf8) != SL_ACK) { // Look for slave ACK
TWCR = (1<<TWINT) | (1<<TWEN) | (1<<TWSTO); // Send a Stop
return 0xab;
}
TWDR = whichReg; // Load and send address of SI ID register 0x0 which should contain teh PART_ID
TWCR = (1<<TWINT) | (1<<TWEN );
while (!(TWCR & (1<<TWINT)));
if ( (TWSR & 0xf8) != MT_DATA_ACK) { // Look for slave ACK
TWCR = (1<<TWINT) | (1<<TWEN) | (1<<TWSTO); // Send a Stop
return 0xac;
}
TWCR = (1<<TWINT) | (1<<TWSTA) | (1<<TWEN); // send Repeated Start and wait...
while (!(TWCR & (1<<TWINT)));
TWDR = SI_SLA_R; // Send the slave module address + read bit and wait
TWCR = (1<<TWINT) | (0<<TWSTA) | (0<<TWSTO) | (1<<TWEA) | (1<<TWEN);
while (!(TWCR & (1<<TWINT)));
if ( (TWSR & 0xf8) != MR_SLA_ACK) { // Look for slave ACK
TWCR = (1<<TWINT) | (1<<TWEN) | (1<<TWSTO); // Send a Stop
return 0xae;
}
TWCR = (0<<TWSTA) | (0<<TWSTO) | (1<<TWINT) | (0<<TWEA) | (1<<TWEN); // send a RESTART and return a NACK
while (!(TWCR & (1<<TWINT))); // Wait for slave to return a byte
retValue = TWDR;
TWCR = (1<<TWINT) | (1<<TWEN) | (1<<TWSTO); // Send a Stop
return retValue;
}
uint8_t SI_writeI2Cbyte(uint8_t whichReg, uint8_t data) {
uint8_t retValue;
TWCR = (1<<TWINT)|(1<<TWSTA)|(1<<TWEN); // send Start
while ( !(TWCR & (1<<TWINT) ) ); // Wait for Start to be transmitted
if ( (TWSR & 0xf8) != START) {
TWCR = (1<<TWINT) | (1<<TWEN) | (1<<TWSTO); // Send a Stop
return 0xaa;
}
TWDR = SI_SLA_W; // Send the slave module address + write bit
TWCR = (1<<TWINT) | (1<<TWEN); // Transmit the address and wait
while (!(TWCR & (1<<TWINT)));
if ( (TWSR & 0xf8) != SL_ACK) { // Look for slave ACK
TWCR = (1<<TWINT) | (1<<TWEN) | (1<<TWSTO); // Send a Stop
return 0xab;
}
TWDR = whichReg; // Load and send address of SI ID register 0x0 which should contain teh PART_ID
TWCR = (1<<TWINT) | (1<<TWEN );
while (!(TWCR & (1<<TWINT)));
if ( (TWSR & 0xf8) != MT_DATA_ACK) { // Look for slave ACK
TWCR = (1<<TWINT) | (1<<TWEN) | (1<<TWSTO); // Send a Stop
return 0xac;
}
TWDR = data; // Load and send address of SI ID register 0x0 which should contain teh PART_ID
TWCR = (1<<TWINT) | (1<<TWEN );
while (!(TWCR & (1<<TWINT)));
if ( (TWSR & 0xf8) != MT_DATA_ACK) { // Look for slave ACK
TWCR = (1<<TWINT) | (1<<TWEN) | (1<<TWSTO); // Send a Stop
return 0xad;
}
TWCR = (1<<TWINT) | (1<<TWEN) | (1<<TWSTO); // Send a Stop
_delay_ms(30);
// Verify that the data got written
TWCR = (1<<TWINT)|(1<<TWSTA)|(1<<TWEN); // send Start
while ( !(TWCR & (1<<TWINT) ) ); // Wait for Start to be transmitted
if ( (TWSR & 0xf8) != START) {
TWCR = (1<<TWINT) | (1<<TWEN) | (1<<TWSTO); // Send a Stop
return 0xaa;
}
TWDR = SI_SLA_W; // Send the slave module address + read bit and wait
TWCR = (1<<TWINT) | (0<<TWSTA) | (0<<TWSTO) | (1<<TWEA) | (1<<TWEN);
while (!(TWCR & (1<<TWINT)));
if ( (TWSR & 0xf8) != SL_ACK) { // Look for slave ACK
TWCR = (1<<TWINT) | (1<<TWEN) | (1<<TWSTO); // Send a Stop
return 0xaf;
}
TWDR = whichReg; // Load and send address of SI ID register 0x0 which should contain teh PART_ID
TWCR = (1<<TWINT) | (1<<TWEN );
while (!(TWCR & (1<<TWINT)));
if ( (TWSR & 0xf8) != MT_DATA_ACK) { // Look for slave ACK
TWCR = (1<<TWINT) | (1<<TWEN) | (1<<TWSTO); // Send a Stop
return 0xaf;
}
TWCR = (1<<TWINT) | (1<<TWSTA) | (1<<TWEN); // send Repeated Start and wait...
while (!(TWCR & (1<<TWINT)));
TWDR = SI_SLA_R; // Send the slave module address + write bit
TWCR = (1<<TWINT) | (1<<TWEN); // Transmit the address and wait
while (!(TWCR & (1<<TWINT)));
if ( (TWSR & 0xf8) != MR_SLA_ACK) { // Look for slave ACK
TWCR = (1<<TWINT) | (1<<TWEN) | (1<<TWSTO); // Send a Stop
return 0xac;
}
TWCR = (0<<TWSTA) | (0<<TWSTO) | (1<<TWINT) | (0<<TWEA) | (1<<TWEN); // send a RESTART and return a NACK
while (!(TWCR & (1<<TWINT))); // Wait for slave to return a byte
retValue = TWDR;
TWCR = (1<<TWINT) | (1<<TWEN) | (1<<TWSTO); // Send a Stop
return retValue;
}
uint16_t SI_readI2Cword(uint8_t whichReg) {
uint16_t retWord, MSB, LSB;
TWCR = (1<<TWINT)|(1<<TWSTA)|(1<<TWEN); // send Start
while ( !(TWCR & (1<<TWINT) ) ); // Wait for Start to be transmitted
TWDR = SI_SLA_W; // Send the slave module address + write bit
TWCR = (1<<TWINT) | (1<<TWEN); // Transmit the address
while (!(TWCR & (1<<TWINT)));
if ( (TWSR & 0xf8) != SL_ACK) { // Look for slave ACK
TWCR = (1<<TWINT) | (1<<TWEN) | (1<<TWSTO); // Send a Stop
return 0xaa;
}
TWDR = whichReg; // Send the address of the AD MSB
TWCR = (1<<TWINT) | (1<<TWEN );
while (!(TWCR & (1<<TWINT)));
if ( (TWSR & 0xf8) != MT_DATA_ACK) { // Look for slave ACK
TWCR = (1<<TWINT) | (1<<TWEN) | (1<<TWSTO); // Send a Stop
return 0xab;
}
TWCR = (1<<TWINT) | (1<<TWSTA) | (1<<TWEN); // send Repeated Start and wait...
while (!(TWCR & (1<<TWINT)));
TWDR = SI_SLA_R; // Send the slave module address + read bit
TWCR = (1<<TWINT) | (0<<TWSTA) | (0<<TWSTO) | (1<<TWEA) | (1<<TWEN);
while (!(TWCR & (1<<TWINT)));
if ( (TWSR & 0xf8) != MR_SLA_ACK) { // Look for slave ACK
TWCR = (1<<TWINT) | (1<<TWEN) | (1<<TWSTO); // Send a Stop
return 0xac;
}
TWCR = (0<<TWSTA) | (0<<TWSTO) | (1<<TWINT) | (1<<TWEA) | (1<<TWEN); // Send a RESTART and an ACK after MSB is received
while (!(TWCR & (1<<TWINT)));
LSB = TWDR;
TWCR = (0<<TWSTA) | (0<<TWSTO) | (1<<TWINT) | (0<<TWEA) | (1<<TWEN); // Send a RESTART and a NACK after LSB is received
while (!(TWCR & (1<<TWINT)));
MSB = TWDR;
TWCR = (1<<TWINT) | (1<<TWEN) | (1<<TWSTO); // Send a Stop
retWord = (MSB << 8) | LSB;
return retWord;
}
|
C
|
#ifdef __EMX__
#include <stdlib.h>
#endif
#ifndef WIN32
#include <sys/time.h>
#include <sys/types.h>
#include <unistd.h>
#else
#include <time.h>
#endif
#include <string.h>
#ifdef HAVE_SYS_SELECT_H
#include <sys/select.h>
#endif
#include "cfg.h"
/* gets current time in microseconds */
unsigned long_long get_time(void)
{
#ifndef WIN32
struct timeval tv;
struct timezone tz;
memset(&tz,0,sizeof(tz));
gettimeofday(&tv,&tz);
return ((unsigned long_long)tv.tv_sec)*1000000+(unsigned long_long)tv.tv_usec;
#else
return ((unsigned long_long)GetTickCount())*1000UL;
#endif
}
/* waits until time t passes */
void sleep_until(unsigned long_long t)
{
unsigned long_long u=get_time();
if (u>=t) return;
t-=u;
#if defined(WIN32)
Sleep(t/1000);
#elif defined(__EMX__)
_sleep2(t/1000);
#else
{
struct timeval tv;
tv.tv_sec=0;
tv.tv_usec=t;
select(0,NULL,NULL,NULL,&tv);
}
#endif
}
/* waits time t microseconds */
void my_sleep(unsigned long_long t)
{
#if defined(WIN32)
Sleep(t/1000);
#elif defined(__EMX__)
_sleep2(t/1000);
#else
{
struct timeval tv;
tv.tv_sec=0;
tv.tv_usec=t;
select(0,NULL,NULL,NULL,&tv);
}
#endif
}
|
C
|
#include<stdio.h>
int main()
{
int arr[] = {1,2,1,2,1,3,1,3,1,3,4,2,4,1};
int size = (sizeof(arr)/4) - 1;
int *ptr_arr =(int *)( &arr + 1 ) -1;
int *ptr1_arr = ptr_arr - 1;
//printf("%d %d %d\n",*ptr_arr,*ptr1_arr,size);
int i,j,count = 0,k;
for(i=0;i<size;i++)
printf("%d\t",arr[i]);
printf("\n\n");
for(i = 0 ; i <= size; i++)
{
// printf("%d firtand\n",arr[i]);
for(j=i+1 ; j <= size ; ){
// printf("%d firtand %d\n",arr[i],arr[j]);
if(arr[i] == arr[j])
{
// printf("%d and %d\n",arr[i],arr[j]);
for(k=j ; k <= size ;k++)
{
if(arr[i] == arr[k+1]){
count++;
printf("____%d and %d\t",arr[k+1],count);
printf("\n\n");
continue;
}
else{
printf("__%d\t",count);
arr[k] = arr[k+count];
size -= count;
count = 0;
}
}
size -= 1;
}
else
j++;
}
}
for(i=0;i<=size+2;i++)
printf("%d\n",arr[i]);
}
|
C
|
#include <stdio.h>
#include "bitmap.h"
int bitmap_get(void* bm, int ii) {
return ((char*)bm)[ii / 8] >> (ii % 8) & 1;
}
// puts a value at the specified bit in the bitmap
void bitmap_put(void* bm, int ii, int vv) {
//bitmap_print(bm, ii);
int bit = (vv) ? 1 : 0;
char* bitmap = (char*)bm;
int actual = bitmap_get(bm, ii);
//printf("\nbit val : %d \nstate of the %d th bit : %d\n",bit,ii,actual);
if ( actual == bit) {
//printf("returning from bitmamp put \n");
return;
}
else {
bitmap[(ii / 8)] ^= 1 << ii % 8;
}
//bitmap_print(bm, ii);
}
// debug statement
void bitmap_print(void* bm, int size) {
for (int ii = 0; ii < size * 4; ++ii) {
printf("%d", bitmap_get(bm, ii));
}
//printf("\n");
}
|
C
|
#include<stdio.h>
#include<stdlib.h>
#include<math.h>
#include<string.h>
#include "structure.h"
#include "listeSommet.h"
#include "listeArc.h"
#include "listeSommetP.h"
#include "listeArcP.h"
ListeSommet ajout_ville(ListeSommet tabu,Sommet* villes, int N )
{
Sommet q; ListeSommet p=creer_listeSommet();
q.num=(villes[N]).num;
q.x=(villes[N]).x;
q.y=(villes[N]).y;
q.ListeVoisin=(villes[N]).ListeVoisin;
q.nom=(villes[N]).nom;
p=ajout_teteSommet(q,tabu);
return(p);
}
//n est le nombre total de ville (=nbVille dans le main)
/* renvoie 1 si la fourmi est passe par la ville de numro N, 0 si elle est passe
par toutes les villes et 2 si elle nest pas encore passe*/
int ville_parcourue(ListeSommetP tabu, int N,int n) //ok
{
int i=0; int j=0; ListeSommetP p=NULL;
if (est_videSommetP(tabu))
return(2);
p=tabu;
while (!est_videSommetP(p))
{
i=i+1;
if(p->val->num==N) j=1;
p=p->suiv;
}
if (i==n) return (0);
if (j==1) return (1);
return (2);
}
//memo : n = nbVille
ListeSommet depart(Sommet* villes, int n)//ok
{
int i=0;
ListeSommet p=creer_listeSommet();
i =rand() %(n);
printf("%d\n",i);
p=ajout_ville(p,villes,i);
return (p);
}
void afficheListeSommet(ListeSommet tabu)
{
ListeSommet p=tabu;
while (!est_videSommet(p))
{
printf("\t tabu %d \n",(p->val).num);
p=p->suiv;
}
}
double* initialisation(int n)
{
double* t; int i=0;
t=calloc(n, sizeof(*t)); /*on cre le tableau et on linitialise -1*/
if (t==NULL) return (NULL);
for (i=0; i<n; i++)
t[i]=-1;
return(t);
}
void affichedouble(double* t,int n)
{
int i=0;
for(i=0;i<n;i++)
printf("\t %lf \n",t[i]);
}
double* probatabu(double* t,ListeSommetP tabu)
{
ListeSommetP p=NULL;
p=tabu;
while (!est_videSommetP(p)) /*si la ville est dans tabu proba=0*/
{
t[(p->val->num)]=0;
p=p->suiv;
}
return(t);
}
double* repartition(Sommet s, ListeSommetP tabu, Sommet* villes, int n, double ALPHA, double BETA)
{
double* t;int i=0;
ListeArc q=creer_listeArc();
double somme=0; double cumul=0;
t=initialisation(n); /*on cre le tableau et on linitialise -1*/
i=ville_parcourue( tabu,s.num,n) ;
if(i==0) return (t); /*si toutes les villes sont parcourues renvoit t initialis -1*/
i=0;
t=probatabu(t,tabu); /*si la ville est dans tabu proba =0*/
/*si elle est dans les arcs voisins et*/
/*pas dans tabu on place la
pondration correspondante et on fait la somme terme a terme*/
q=s.ListeVoisin;
if(est_videArc(q))
{
printf("Pas de voisins! Le voyage est fini :/ \n");
somme=1;
}
while (!est_videArc(q))
{
if(t[ (q->val).sarr]<0)
{
t[ (q->val).sarr]= pow((q->val).to,ALPHA)/pow( (q->val).d ,BETA);
somme=somme+t[ (q->val).sarr];
}
q=q->suiv;
}
i=0;
for(i=0;i<n;i++)
{
if(t[i]<=0) /*pour les villes non voisines et non parcourrues
p=0 aussi*/
t[i]=0;
else
{cumul=cumul+t[i];
t[i]=cumul;
}
t[i]=t[i]/somme; /* enfin on divise tout par la somme des pondrations*/
}
return(t);
}
ListeArcP parcours_fourmi(Fourmi f, ListeSommetP tabu)
{
ListeArc q=creer_listeArc(); int Narr=0;
if (est_videSommetP(tabu)) return(f.solution);
if (est_videSommetP (tabu->suiv))return(f.solution);
Narr=tabu->val->num;
q=((tabu->suiv)->val->ListeVoisin);
while(!est_videArc(q))
{
if(q->val.sarr==Narr)
{
f.solution=ajout_teteArcP(&(q->val),f.solution);
}
q=q->suiv;
}
f.solution=parcours_fourmi(f,tabu->suiv);
return(f.solution);
}
double Lchemin(ListeArcP tabuArc)//test numriquement 28/04
{
if(est_videArcP(tabuArc)) return 1000000000000000000; //utile au dbut quand cheminMin est vide
ListeArcP iL=NULL; double somme=0;
iL=tabuArc;
while(!est_videArcP(iL))
{
somme= somme +(iL->val)->d;
iL=iL->suiv;
}
return somme;
}
void evapPheromone(Sommet* tabVille, int nbVille,double RHO) //teste numriquement le 28/02
{
int i=0; ListeArc iL=NULL;
for(i=0;i<nbVille;i++)
{iL=tabVille[i].ListeVoisin;
while(!est_videArc(iL))
{iL->val.to*=RHO;
iL=iL->suiv;
}
}
}
void depotPheromone(Fourmi* tabFourmi, int nbFourmi, double Q)
{
int i=0;
ListeArcP iL=NULL;
for(i=0;i<nbFourmi;i++)
{
double dTo = Q/Lchemin((tabFourmi[i]).solution);
for(iL=tabFourmi[i].solution;iL!=NULL;iL=iL->suiv)
{
iL->val->to += dTo;
}
}
}
void depotPheromone_Fourmis_intelligentes(Fourmi* tabFourmi, int nbFourmi, int x, double Q)
{if (x>nbFourmi)
{
depotPheromone(tabFourmi, nbFourmi,Q);
}
else
{int i=0;
ListeArcP iL=NULL;
for(i=0;i<x;i++)
{
double dTo = Q/Lchemin((tabFourmi[i]).solution);
for(iL=tabFourmi[i].solution;iL!=NULL;iL=iL->suiv)
{
iL->val->to += dTo;
}
}
}
}
triFourmi(Fourmi* tabFourmi, int nbFourmi , double* Ltab)
{ int i=0; Fourmi f; double L;
if(nbFourmi>1)
{
for(i=0;i<nbFourmi-1;i++)
{if(Ltab[i]>Ltab[i+1] )
{L=Ltab[i]; Ltab[i]=Ltab[i+1]; Ltab[i+1]=L;
f.iVilleCour=tabFourmi[i].iVilleCour;
f.iVilleDep=tabFourmi[i].iVilleDep;
f.solution=tabFourmi[i].solution;
tabFourmi[i].iVilleCour=tabFourmi[i+1].iVilleCour;
tabFourmi[i].iVilleDep=tabFourmi[i+1].iVilleDep;
tabFourmi[i].solution=tabFourmi[i+1].solution;
tabFourmi[i+1].iVilleCour=f.iVilleCour;
tabFourmi[i+1].iVilleDep=f.iVilleDep;
tabFourmi[i+1].solution=f.solution;
}
}
triFourmi(tabFourmi,nbFourmi-1,Ltab);
}
}
int ville_next(ListeSommetP tabu,int n, Sommet s, Sommet* villes, double ALPHA,double BETA, int iVilleDep)
{
double* t;int i=0;
ListeArc q=creer_listeArc(); int ville_nonnulle=0;
double somme=0; double cumul=0;
int N=0; double a=rand(); double tirage=a/RAND_MAX; double diff=1;
i=ville_parcourue( tabu,s.num,n) ;
if(i==0)
{return (iVilleDep);/*si toutes les villes sont parcourues renvoit la ville de dpart*/
}
t=initialisation(n); /*on cre le tableau et on linitialise -1*/
if (t==NULL) return (-1);
t=probatabu(t,tabu); /*si la ville est dans tabu proba =0*/
/*si elle est dans les arcs voisins et*/
/*pas dans tabu on place la
pondration correspondante et on fait la somme terme a terme*/
q=s.ListeVoisin;
if(est_videArc(q))
{
printf("Pas de voisins! Le voyage est fini :/ \n");
somme=1;
}
while (!est_videArc(q))
{
if(t[ (q->val).sarr]<0)
{
t[ (q->val).sarr]= pow((q->val).to,ALPHA)/pow( (q->val).d ,BETA);
somme=somme+t[ (q->val).sarr];
}
q=q->suiv;
}
if (somme==0){free(t);return(-42);}//s'il manque des villes mais toutes les villes voisins du sommet actuel sont parcourrues on ne prend pas en copte le parcours
i=0;
for(i=0;i<n;i++)
{
if(t[i]<=0) /*pour les villes non voisines et non parcourrues
p=0 aussi*/
t[i]=0;
else
{cumul=cumul+t[i];
t[i]=cumul;
}
t[i]=t[i]/somme; /* enfin on divise tout par la somme des pondrations*/
if(tirage==1 && t[i]==1) {free(t);return(i);}
if(t[i]>tirage) {free(t); return(i);}
}
free(t);
return(N);
}
|
C
|
#include<stdio.h>
void rotate(int arr[],int d,int n)
{
int new[n],i,pos=0;
for(i=d;i<n;i++)
{
new[pos]=arr[i];
pos++;
}
for(i=0;i<d;i++)
{
new[pos]=arr[i];
pos++;
}
printf("Array after rotate %d place ",d);
for(i=0;i<n;i++)
{
printf("%d\t",new[i]);
}
}
void main()
{
int arr[10],n,d,i;
printf("Enter size of array : ");
scanf("%d",&n);
printf("Enter d : ");
scanf("%d",&d);
printf("Eneter array data :");
for(i=0;i<n;i++)
{
scanf("%d",&arr[i]);
}
rotate(arr,d,n);
}
|
C
|
// Item.h ... interface to Items
// Written by John Shepherd, May 2013
#ifndef ITEM_H
#define ITEM_H
#include <string.h>
typedef char *Key;
typedef Key Item; // item is just a key
#define key(it) (it)
#define cmp(k1,k2) (strcmp((k1),(k2)))
#define less(k1,k2) (cmp(k1,k2) < 0)
#define eq(k1,k2) (cmp(k1,k2) == 0)
#define copyItem(it) strdup((it))
#define dropItem(it) free((it))
#define showItem(it) printf("%5.4s",(it))
#endif
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* get_flags.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: iiliuk <iiliuk@student.42.us.org> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2017/02/01 17:28:25 by iiliuk #+# #+# */
/* Updated: 2017/02/27 14:53:09 by iiliuk ### ########.fr */
/* */
/* ************************************************************************** */
#include "ft_printf.h"
static void get_width_precision(char *fmt, t_flags *got_flags)
{
int i;
i = 0;
got_flags->width = 1;
got_flags->precision = 1;
got_flags->got_precis = 0;
got_flags->got_width = 0;
while (fmt[i] != '\0')
{
if (fmt[i] != '.' && fmt[i] != '0' && ft_isdigit(fmt[i]))
{
got_flags->got_width = 1;
got_flags->width = ft_atoi(fmt + i);
while (fmt[i] && ft_isdigit(fmt[i]))
i++;
}
if (fmt[i] == '.' && fmt[i + 1] != '*')
{
got_flags->got_precis = 1;
got_flags->precision = ft_atoi(fmt + i + 1);
while (fmt[i] && ft_isdigit(fmt[i + 1]))
i++;
}
i++;
}
}
static void get_star(char *fmt, t_flags *got_flags, va_list *args)
{
int i;
int arg;
i = -1;
while (fmt[++i] != '\0')
{
if (fmt[i] == '*' && !ft_isdigit(fmt[i + 1]))
{
arg = va_arg(*args, int);
if (fmt[i - 1] == '.')
{
got_flags->got_precis = (arg >= 0) ? 1 : 0;
got_flags->precision = (arg >= 0) ? arg : 0;
}
else
{
got_flags->left_justify = (got_flags->left_justify ||
arg < 0) ? 1 : 0;
got_flags->got_width = 1;
got_flags->width = ft_abs(arg);
}
}
else if (fmt[i] == '*')
arg = va_arg(*args, int);
}
}
static void get_len_mod(char *fmt, t_flags *got_flags)
{
int i;
i = -1;
while (fmt[++i] != '\0')
{
if (fmt[i] == 'h')
got_flags->len_mod = (fmt[++i] == 'h') ? hh : h;
else if (fmt[i] == 'l')
{
if (fmt[++i] == 'l')
got_flags->len_mod = ll;
else
got_flags->len_mod = l;
}
else if (fmt[i] == 'j')
got_flags->len_mod = j;
else if (fmt[i] == 'z')
got_flags->len_mod = z;
else if (fmt[i] == 't')
got_flags->len_mod = t;
i++;
}
}
static int process_conv(t_flags *got_flags, va_list *args)
{
if (got_flags->conv_spec == 's' || got_flags->conv_spec == 'S' ||
got_flags->conv_spec == 'c' || got_flags->conv_spec == 'C')
return (process_c_s(got_flags, args));
else if (got_flags->conv_spec == 'd' || got_flags->conv_spec == 'D' ||
got_flags->conv_spec == 'i' || got_flags->conv_spec == 'o' ||
got_flags->conv_spec == 'O' || got_flags->conv_spec == 'u' ||
got_flags->conv_spec == 'U' || got_flags->conv_spec == 'x' ||
got_flags->conv_spec == 'X')
return (process_digit(got_flags, args));
else if (got_flags->conv_spec == 'p')
return (process_ptr(got_flags, args));
else if (got_flags->conv_spec == '%')
return (process_percent(got_flags, args));
else
return (process_non_valid(got_flags));
}
int get_flags(char *fmt, va_list *args)
{
int i;
t_flags *got_flags;
i = 0;
got_flags = (t_flags *)ft_memalloc(sizeof(t_flags));
got_flags->conv_spec = fmt[ft_strlen(fmt) - 1];
while (fmt[i] != '\0')
{
got_flags->pound = (fmt[i] == '#') ? 1 : got_flags->pound;
got_flags->sign = (fmt[i] == '+') ? 1 : got_flags->sign;
if (fmt[i] == '0' && fmt[i - 1] != '.' && !ft_isdigit(fmt[i - 1]))
got_flags->pad_zero = 1;
if (fmt[i] == '-')
got_flags->left_justify = 1;
if (fmt[i] == ' ')
got_flags->space = 1;
i++;
}
get_width_precision(fmt, got_flags);
get_star(fmt, got_flags, args);
get_len_mod(fmt, got_flags);
i = process_conv(got_flags, args);
free(got_flags);
return (i);
}
|
C
|
#include <main.h>
#include "..\library\delay.h"
unsigned char KeyPress()
{
unsigned char key = 0;
Col1 = 0;
if(Cow1==0) key = 1;
if(Cow2==0) key = 2;
if(Cow3==0) key = 3;
if(Cow4==0) key = 4;
Col1 = 1;
Col2 = 0;
if(Cow1==0) key = 5;
if(Cow2==0) key = 6;
if(Cow3==0) key = 7;
if(Cow4==0) key = 8;
Col2 = 1;
Col3 = 0;
if(Cow1==0) key = 9;
if(Cow2==0) key = 10;
if(Cow3==0) key = 11;
if(Cow4==0) key = 12;
Col3 = 1;
Col4 = 0;
if(Cow1==0) key = 13;
if(Cow2==0) key = 14;
if(Cow3==0) key = 15;
if(Cow4==0) key = 16;
Col4 = 1;
return key;
}
void LCD_cmd(unsigned char cmd) //khoi tao LCD
{
LCD_RS = 0;
LCD_DATA = cmd;
LCD_EN = 0;
LCD_EN = 1;
if(cmd <= 0x02) delay(2);
else delay(1);
}
void LCD_chr_cp(char c) // ham gui 1 ki tu
{
LCD_RS = 1;
LCD_DATA = c;
LCD_EN = 0;
LCD_EN = 1;
delay(1);
}
void LCD_out_cp(char *str)
{
unsigned char i = 0;
while(str[i]!=0)
{
LCD_chr_cp(str[i]);
i++;
}
}
void LCD_Init()
{
LCD_cmd(0x30);
delay(5);
LCD_cmd(0x30);
delay(1);
LCD_cmd(0x30);
LCD_cmd(0x38);
LCD_cmd(0x01);
LCD_cmd(0x0C);
}
void Key_in()
{
unsigned char tmp;
delay(20);
switch(KeyPress())
{
case 1: LCD_cmd(0x01);
break;
case 2: tmp = '1';
break;
case 3: tmp = '4';
break;
case 4: tmp = '7';
break;
case 5: tmp = '0';
break;
case 6: tmp = '2';
break;
case 7: tmp = '5';
break;
case 8: tmp = '8';
break;
case 9: tmp = '=';
break;
case 10: tmp = '3';
break;
case 11: tmp = '6';
break;
case 12: tmp = '9';
break;
case 13: tmp = '/';
break;
case 14: tmp = 'x';
break;
case 15: tmp = '-';
break;
case 16: tmp = '+';
break;
default: break;
}
while(KeyPress()!=0)
{
LCD_chr_cp(tmp);
while(KeyPress()!=0);
}
}
void main()
{
LCD_Init();
while(1)
{
Key_in();
}
}
|
C
|
#include "test_http.h"
static void test_reason( void )
{
test_req_t req[] = {
//
// line-terminated by CRLF
//
// HTTP/1.0
{
HTTP_SUCCESS,
HTTP_OK | HTTP_V10,
0,
"HTTP/1.0 200 OK\r\n\r\n"
},
{
HTTP_SUCCESS,
HTTP_OK | HTTP_V10,
0,
"HTTP/1.0 200 \r\n\r\n"
},
// invalid status code
{
HTTP_EREASON,
HTTP_OK | HTTP_V10,
0,
"HTTP/1.0 200 OK\r\t"
},
//
// line-terminated by LF
//
// HTTP/1.0
{
HTTP_SUCCESS,
HTTP_OK | HTTP_V10,
0,
"HTTP/1.0 200 OK\n\n"
},
{
HTTP_SUCCESS,
HTTP_OK | HTTP_V10,
0,
"HTTP/1.0 200 \n\n"
},
// end of request
{ 0, 0, 0, "" }
};
test_req_t *ptr = req;
http_t *r = http_alloc(0);
int rc;
while( ptr->protocol )
{
rc = http_parse_response( r, ptr->entity, strlen( ptr->entity ),
INT16_MAX );
assert( rc == ptr->rc );
if( rc == HTTP_SUCCESS ){
assert( r->protocol == ptr->protocol );
}
ptr++;
http_init( r );
}
http_free( r );
}
#ifdef TESTS
int main(void)
{
test_reason();
return 0;
}
#endif
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_utf8.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: kperreau <kperreau@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2015/01/13 23:10:16 by kperreau #+# #+# */
/* Updated: 2015/01/15 00:24:26 by kperreau ### ########.fr */
/* */
/* ************************************************************************** */
#include "printf.h"
int ft_utfclen(wint_t c)
{
int len;
len = ft_binlen(c);
if (len <= 7)
return (1);
else if (len <= 11)
return (2);
else if (len <= 16)
return (3);
else if (len <= 21)
return (4);
return (-1);
}
int ft_utfnlen(wchar_t *s, int n)
{
int len;
int temp;
int mem;
len = 0;
mem = 0;
while (*s && len <= n)
{
mem = len;
temp = ft_utfclen(*s++);
len += temp;
}
return ((len != n) ? mem : n);
}
int ft_utflen(wchar_t *s)
{
int len;
int temp;
len = 0;
while (*s)
{
temp = ft_utfclen(*s++);
if (temp < 0)
return (-1);
len += temp;
}
return (len);
}
int ft_to_utf8(wint_t c, int bytes, unsigned char *mask)
{
int i;
int ft_or[3];
int value;
if (bytes < 2)
{
mask[0] = (unsigned char)c;
return (0);
}
ft_or[0] = 0xC0;
ft_or[1] = 0xE0;
ft_or[2] = 0xF0;
i = -1;
while (++i < bytes)
{
value = 0;
value = (c >> (8 * (bytes - (i + 1)) - 2 * (bytes - (i + 1))));
mask[i] = (i) ? (value & 0x3F) | 0x80 : value | ft_or[bytes - 2];
}
return (0);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include "listadpl.h"
int main(){
TipoListaDpl* lista;
char *nome = {"Pedro"};
lista = NULL;
TipoItem *buffer = InicializaTipoItem("Pedro", 123, "Rua do Coqueiro");
lista = Insere(buffer, lista);
buffer = InicializaTipoItem("Lenke", 456, "Que eu nao sei");
lista = Insere(buffer, lista);
buffer = InicializaTipoItem("Ryan", 789, "Alguma Rua");
lista = Insere(buffer, lista);
buffer = InicializaTipoItem("Rogerio", 179, "Perto da Ufes");
lista = Insere(buffer, lista);
buffer = InicializaTipoItem("Raphael", 248, "Burgues q mora praia");
lista = Insere(buffer, lista);
Imprime(lista);
lista = Retira(lista, nome);
printf("\n\nRETIRADO: %s\n", nome);
Imprime(lista);
lista = libera(lista);
if(lista == NULL){
printf("\n\nLISTA NULL");
}
return 0;
}
|
C
|
#include "list.h"
#include <assert.h>
#include <stdlib.h>
#include <stdio.h>
struct Node {
void* data;
struct Node* next;
};
struct List {
struct Node* head;
struct Node* tail;
Display display;
Copy copy;
Free free;
};
struct Node* new_node(void* elem) {
struct Node* node = malloc(sizeof *node);
node->data = elem;
node->next = NULL;
return node;
}
struct List* new_list(Display display_elem, Copy copy_elem, Free free_elem) {
struct List* list = malloc(sizeof *list);
list->head = NULL;
list->tail = NULL;
list->display = display_elem;
list->copy = copy_elem;
list->free = free_elem;
return list;
}
struct List* copy_list(struct List* self) {
struct List* self_copy = new_list(self->display, self->copy, self->free);
struct Node* cur_self = self->head;
self_copy->head = new_node(self->copy(cur_self->data));
struct Node* cur_copy = self_copy->head;
while (cur_self != self->tail) {
cur_self = cur_self->next;
cur_copy->next = new_node(self->copy(cur_self->data));
cur_copy = cur_copy->next;
}
self_copy->tail = cur_copy;
return self_copy;
}
void free_list(struct List* self) {
struct Node* cur = self->head;
struct Node* next;
while (cur) {
next = cur->next;
self->free(cur->data);
free(cur);
cur = next;
}
free(self);
}
void display_list(struct List* self) {
struct Node* cur = self->head;
if (!cur) {
puts("[]");
return;
}
printf("[");
while (cur->next) {
self->display(cur->data);
printf(", ");
cur = cur->next;
}
self->display(cur->data);
puts("]");
}
void append_front(struct List* self, void* elem) {
struct Node* elem_node = new_node(elem);
if (!self->head) {
self->head = elem_node;
self->tail = elem_node;
} else {
elem_node->next = self->head;
self->head = elem_node;
}
}
void append_back(struct List* self, void* elem) {
struct Node* elem_node = new_node(elem);
if (!self->head) {
self->head = elem_node;
self->tail = elem_node;
} else {
self->tail->next = elem_node;
self->tail = elem_node;
}
}
void remove_at(struct List* self, int index) {
struct Node* cur = self->head;
if (!index) {
self->head = cur->next;
} else {
for (int i = 0; i < index-1; ++i) {
cur = cur->next;
}
struct Node* prev = cur;
cur = cur->next;
prev->next = cur->next;
}
self->free(cur->data);
free(cur);
}
|
C
|
#include "mpi.h"
#include <stdio.h>
#include <stdlib.h>
void srandom (unsigned seed);
double dboard (int darts);
#define DARTS 50000
#define ROUNDS 100
#define MASTER 0
int main (int argc, char *argv[])
{
double homepi,
pisum,
pi,
avepi;
int taskid,
numtasks,
rc,
i;
MPI_Status status;
MPI_Init(&argc,&argv);
MPI_Comm_size(MPI_COMM_WORLD,&numtasks);
MPI_Comm_rank(MPI_COMM_WORLD,&taskid);
printf ("MPI task %d began...\n", taskid);
srandom (taskid);
avepi = 0;
for (i = 0; i < ROUNDS; i++) {
homepi = dboard(DARTS);
rc = MPI_Reduce(&homepi, &pisum, 1, MPI_DOUBLE, MPI_SUM,
MASTER, MPI_COMM_WORLD);
if (taskid == MASTER) {
pi = pisum/numtasks;
avepi = ((avepi * i) + pi)/(i + 1);
printf(" After %8d throws, average value of pi = %10.8f\n",
(DARTS * (i + 1)),avepi);
}
}
if (taskid == MASTER)
printf ("\nPI= 3.14 \n");
MPI_Finalize();
return 0;
}
double dboard(int darts)
{
long random(void);
double x_coord, y_coord, pi, r;
int score, n;
unsigned int cconst;
if (sizeof(cconst) != 4) {
printf("You have inputed the wrong data size for cconst variable in dboard routine!\n");
printf("See comments in source file. Quitting.\n");
exit(1);
}
cconst = 2 << (31 - 1);
score = 0;
for (n = 1; n <= darts; n++) {
r = (double)random()/cconst;
x_coord = (2.0 * r) - 1.0;
r = (double)random()/cconst;
y_coord = (2.0 * r) - 1.0;
if ((sqr(x_coord) + sqr(y_coord)) <= 1.0)
score++;
}
pi = 4.0 * (double)score/(double)darts;
return(pi);
}
|
C
|
#include <stdio.h>
int main(){
float produto = 2*3;
printf("O valor de 2x3 eh %f \n",produto);
return 0;
}
|
C
|
#include<stdio.h>
#include<stdlib.h>
#include<stdbool.h>
#include<math.h>
#include<time.h>
int main(){
int array[100],n;
srand(time(0));
printf("ixtiyoriy sonni kiriting n : ");
scanf("%d",&n);
for (int i=0;i<=n;i++){
array[i]=rand()%50;
}
printf("\n");
for (int i=0;i<=n;i+=2){
printf("\n array[%d]= %d",i,array[i]);
}
printf("\n\n");
return 0;
}
|
C
|
#include <unistd.h>
#include <stdlib.h>
/*
* Write "hello", on a fail, write "fail
*/
int main(){
int fildes = 1; // STDOUT
char * msg = "hello\n"; // text to write
size_t nbytes = 6; // length of msg
if((write(fildes, msg, nbytes)) != nbytes) {
int fildes = 2; // STDERR
char * msg = "fail\n"; // text to write
size_t nbytes = 5; // length of msg
write(fildes, msg, nbytes);
}
exit(0);
}
|
C
|
#include <stdio.h>
#include <math.h>
#include <utils.h>
#include <utl_stats.h>
/***************************************************************************/
double fit( double *x, double *y, int n,
double *a, double *b, double *corr ) {
/***************************************************************************
* Least square linear regresssion of y with respect to x
***************************************************************************/
double sumx,sumy;
double sx,sy,sxy;
int i;
sumx = sumy= 0.;
sumxx = sumxy= 0.;
sumyy = 0.;
for( i=0; i<n; i++ ) {
sumx += x[i];
sumy += y[i];
sx += x[i]*x[i];
sxy += x[i]*y[i];
sy += y[i]*y[i];
}
sumx/=(double)n;
sumy/=(double)n;
sxy/=(double)n;
sx/=(double)n;
sy/=(double)n;
sxy -= sumx*sumy;
sx = sqrt(fabs(sx-sumx*sumx));
sy = sqrt(fabs(sy-sumy*sumy));
if(sx > MIN_NUM_RESOLUTION) {
*a = sxy / (sx*sx);
*b = sumy - (*a)*sumx;
if(sy<MIN_NUM_RESOLUTION) *corr=1.;
else *corr = sxy / (sx*sy);
} else {
*a = 0.;
*b = sumy;
*corr = 1.;
}
return sy*sy-a[0]*a[0]*sx*sx;
} // end of fit
/***************************************************************************/
double fit_best(double *x, double *y, int n, int hmin,
double **repx, double **repy, int *N) {
/***************************************************************************/
double *histoc,*rep1,*repe2;
double mm1[2];
double norm;
double m2,me2,var2,vare2,regr;
double histac,rep1ac,repe2ac;
int ix,ip,ip0;
*N = n;
if( (histoc = (double*)calloc(n,sizeof(double))) == NULL ||
(rep1 = (double*)calloc(n,sizeof(double))) == NULL ||
(repe2 = (double*)calloc(n,sizeof(double))) == NULL )
return ERROR; // note that regr cannot be <0
mm1[0] = mm1[1] = x[0];
for( ix=0; ix<n; ix++ ) {
mm1[0] = fMin(mm1[0],x[ix]);
mm1[1] = fMax(mm1[1],x[ix]);
}
mm1[1] -= mm1[0];
m2 = var2 = 0.;
for( ix=0; ix<n; ix++ ) {
ip = (int) (((double)*N)*(x[ix]-mm1[0])/mm1[1]);
if(ip >= *N) ip = *N - 1;
histoc[ip] += 1.;
rep1[ip] += x[ix];
repe2[ip] += y[ix];
m2 += y[ix];
var2 += y[ix]*y[ix];
}
m2 /= (double)n;
var2 = var2/((double)n) - m2*m2;
histac = 0.;
rep1ac = repe2ac = 0.;
ip0 = 0;
for( ip=0; ip<*N; ip++ ) {
if(histac < hmin) {
histac += histoc[ip];
rep1ac += rep1[ip];
repe2ac += repe2[ip];
} else {
histoc[ip0] = histac;
rep1[ip0] = rep1ac;
repe2[ip0] = repe2ac;
histac = histoc[ip];
rep1ac = rep1[ip];
repe2ac = repe2[ip];
ip0 ++;
}
}
histoc[ip0] = histac;
rep1[ip0] = rep1ac;
repe2[ip0] = repe2ac;
*N = ip0 + 1;
for( ip=0; ip<*N; ip++ )
{
rep1[ip] /= histoc[ip];
repe2[ip] /= histoc[ip];
}
me2 = vare2 = norm = 0.;
for( ip=0; ip<*N; ip++ ) {
norm += histoc[ip];
me2 += repe2[ip] * histoc[ip];
vare2 += repe2[ip] * repe2[ip] * histoc[ip];
}
me2 /= norm;
vare2 = vare2/norm - me2*me2;
if(var2 > 1e-30) regr = vare2 / var2;
else regr = 1.;
if( (*repx=(double*)calloc(*N,sizeof(double))) == NULL ||
(*repy=(double*) calloc(*N,sizeof(double))) == NULL)
return ERROR;
for( ip=0; ip<*N; ip++ ) {
repx[0][ip] = rep1[ip];
repy[0][ip] = repe2[ip];
}
free(histoc);
free(rep1);
free(repe2);
return(regr);
} // end of fit_best
/***************************************************************************/
int fit_line( double *yValues, double *xValues, int dimx, double *slope ) {
/***************************************************************************
* Fit a signal with a straight line by regression, i.e. it computes the
* slope a of the line y=ax+b that best fits the data [xValues,yValues].
*
* Parameters:
* - xValues : the list of indexes of the signal,
* - yValues : the values of the signal to fit,
* - dimx : lenght of the signal,
* - slope : slope a of the approximation line, what we want
* Returns the number of scales used in the approximation
*
* Note: in LastWave toolbox, this operation is mainly realized by the
* function:
* LineFitSig
* in file signal_function.c (package package_signal), except that we
* consider only signals with regular time intervals.
***************************************************************************/
int i;
double t,sxoss,sx=0.,sy=0.,st2=0.;
double a = 0.;
/* a : the equation line is y = a*x+b */
double x, y;
int ss=0;
for( i=0; i<dimx; i++ ) {
sx += xValues[i];
sy += yValues[i];
ss++;
}
sxoss = sx/(double)ss;
for( i=0; i<dimx; i++ ) {
t = xValues[i] - sxoss;
st2 += t*t;
a += t*yValues[i];
}
a /= st2;
*slope = a;
return ss;
} // end of fit_line
/***************************************************************************/
int dimensiona( int dim) {
/***************************************************************************/
int out;
out=1;
while(out<dim) out=2*out;
return(out);
} // end of dimensiona
/***************************************************************************/
int adimensiona( int size) {
/***************************************************************************/
int out,s0;
for(out=0,s0=size;s0>1;s0=s0/2) out++;
return(out);
} // end of adimensiona
/***************************************************************************/
int adimensiona_pos( int size ) { /* strictement positif */
/***************************************************************************/
int out,s0;
for( out=0,s0=size; s0>0; s0=s0/2 ) out++;
return out;
} // end of adimensiona_pos
/***************************************************************************/
double fMax(double a,double b) {
/***************************************************************************/
if(a > b) return a; else return b;
} // end of fMax
/***************************************************************************/
double fMin(double a,double b) {
/***************************************************************************/
if(a<b) return a; else return b;
} // end of fMin
/***************************************************************************/
int Max(int a,int b) {
/***************************************************************************/
if(a>b) return a; else return b;
} // end of Max
/***************************************************************************/
int Min(int a,int b) {
/***************************************************************************/
if(a<b) return a; else return b;
} // end of Min
/***************************************************************************/
int Mod(int a, int b) {
/***************************************************************************/
int output = a/b;
output = a - output*b;
if(output < 0) output += b;
return output;
} // end of Mod
/***************************************************************************/
int Round( double a) {
/***************************************************************************/
int out = (int)(a+0.5);
if(a < -0.5) out--;
return out;
} // end of Round
/***************************************************************************/
void C_mult( double a1, double b1, double a2, double b2,
double *a, double *b ) {
/***************************************************************************/
*a = a1*a2 - b1*b2;
*b = a1*b2 + a2*b1;
} // end of C_mult
/***************************************************************************/
void C_sqrt( double a0, double b0, double *a, double *b) {
/***************************************************************************/
double mod = sqrt(a0*a0+b0*b0);
*a = sqrt(0.5*(mod+a0));
if(b0<0) *b = -sqrt(0.5*(mod-a0));
else *b = sqrt(0.5*(mod-a0));
} // end of C_sqrt
/***************************************************************************/
double angulo( double dx, double dy) {
/***************************************************************************/
/* Computes the orientation of any vector */
/***************************************************************************/
double salida;
if(fabs(dx)>1e-30) {
salida=atan(dy/dx);
if(dx<0) salida+=M_PI;
if(salida<0) salida+=2*M_PI;
if(salida>2*M_PI) salida-=2*M_PI;
}
else if(dy>0) salida=M_PI/2;
else salida=3*M_PI/2;
return(salida);
} // end of angulo
/************************************************************************/
int resolution( int winsize, int limit ) {
/************************************************************************/
/* Defining the resolution parameter taking into account the size of the
* window.
* In our application limit=NBLIMIT=6 */
/************************************************************************/
int res;
res = (int)(2.*log(2.*winsize+1.)/log(2.)) - 1.;
/* limiting the resolution anyway to limit bits */
if(limit > 0) res = Min( res, limit );
res = Max( res, 0 );
res = (int) pow(2.,(double)res);
return res;
} // end of resolution
/************************************************************************/
int vecindex( int *vecii, int i, int wsize, int dim, int per ) {
/************************************************************************/
int d, count=0;
IF(per) {
/* Version image periodisee: hypothese de cyclite des bords */
for( d=0; d<2*wsize+1; d++ ) vecii[d] = /*(i+d-winsize) % dim;*/
Mod( i+d-wsize, dim );
count = dim;
} ELSE {
/* Version image non periodisee */
for( d=0; d<2*wsize+1; d++ )
if( i-wsize+d<0 || i-wsize+d>=dim) vecii[d] = -1;
else {
vecii[d] = i+d-wsize;
count ++;
}
}
return count; /* Nombre de pixels qui vont entrer dans le calcul */
} // end of vecindex
|
C
|
/* ************************************************************************** */
/* LE - / */
/* / */
/* line_tracer.c .:: .:/ . .:: */
/* +:+:+ +: +: +:+:+ */
/* By: ebourgeo <ebourgeo@student.le-101.fr> +:+ +: +: +:+ */
/* #+# #+ #+ #+# */
/* Created: 2019/06/27 16:43:00 by ebourgeo #+# ## ## #+# */
/* Updated: 2019/06/27 16:43:00 by ebourgeo ### #+. /#+ ###.fr */
/* / */
/* / */
/* ************************************************************************** */
#include "../includes/fdf.h"
void linewriter1(t_line *line, t_seg *seg, t_env *env)
{
int i;
t_writer writer;
i = 0;
writer.px1 = line->px;
writer.py1 = line->py;
writer.img_str = mlx_get_data_addr(env->img_pptr,
&(writer.bpp), &(writer.sl), &(writer.endian));
setup_colors(env);
get_gradient(env, writer.px1, seg);
while (i <= writer.px1)
{
fill_pixel(writer.img_str, seg, env);
i++;
seg->x1 += line->x_incr;
line->px -= line->dy;
if (line->px < 0)
{
seg->y1 += line->y_incr;
line->px += line->dx;
}
}
}
void linewriter2(t_line *line, t_seg *seg, t_env *env)
{
int i;
t_writer writer;
i = 0;
writer.px1 = line->px;
writer.py1 = line->py;
writer.img_str = mlx_get_data_addr(env->img_pptr,
&(writer.bpp), &(writer.sl), &(writer.endian));
setup_colors(env);
get_gradient(env, writer.py1, seg);
while (i <= writer.py1)
{
fill_pixel(writer.img_str, seg, env);
i++;
seg->y1 += line->y_incr;
line->py -= line->dx;
if (line->py < 0)
{
seg->x1 += line->x_incr;
line->py += line->dy;
}
}
return ;
}
void line_tracer(t_seg *seg, t_env *env)
{
t_line line;
line.px = abs(seg->x2 - seg->x1);
line.py = abs(seg->y2 - seg->y1);
line.x_incr = 1;
line.y_incr = 1;
if (seg->x1 > seg->x2)
line.x_incr = -1;
if (seg->y1 > seg->y2)
line.y_incr = -1;
line.dx = 2 * line.px;
line.dy = 2 * line.py;
if (line.dx >= line.dy)
linewriter1(&line, seg, env);
else if (line.dx < line.dy)
linewriter2(&line, seg, env);
return ;
}
|
C
|
#include "monty.h"
/**
* len - length of stack
* @stack: pointer that point to stack
* Return: unsigned int
**/
unsigned int len(stack_t **stack)
{
stack_t *current;
unsigned int l = 0;
current = *stack;
while (current)
{
current = current->next;
l++;
}
return (l);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char **argv)
{
float tC = 0.0,tF = 0.0;
printf("Donner la valeur de la températeur en Fahrenheit\n");
scanf("%f",&tF);
tC = (5/9)*(tF-32);
printf("La température en Celsis est : %f\n",tC);
return 0;
}
|
C
|
/**************************************************************
* Class: CSC-415-02
* Name: Lilian Gouzeot/Jennifer Finaldi(DreamTeam)
* Student ID:
* Project: File System Project
*
* File: b_io.h
*
* Description: Header for readwrite.c struct definition for
* a structure that stores information about an
* open file.
*
**************************************************************/
#ifndef _B_IO_H
#define _B_IO_H
#include "mfs.h"
typedef int b_io_fd;
typedef struct fd_struct
{
int Fd;
int isAllocate;
int flag; //stores read/write permissions
_Bool flaggedForClose; //true when file is about to close
//dirEntry variable clones
unsigned long locationLBA;
unsigned long childLBA;
short entryIndex;
unsigned long dataLocation;
char name[256];
uint64_t sizeOfFile;
unsigned long numBlocks;
time_t dateCreated;
time_t dateModified;
time_t dateAccessed;
unsigned long locationMetadata;
unsigned long extents;
unsigned short numExtents;
unsigned short numExtentBlocks;
unsigned char type;
//buffer and tracking variables
unsigned long filePointer; //file pointer tracks the current byte in the file
unsigned long blockPointer;
char *buffer; // For b_read
char *writeBuffer; // for b_write
short bufIndex; //tracks where in the buffer we are. used in b_read
short buflen; //tracks how much of buffer is being used, used in b_read
int lenBuffer; //used in b_write
unsigned long LBAInDataLocation; //LBA block in file blob. Will need to be adjusted
//to utilize extents
short offsetInDataLocation;//tracks bytes read in an LBA block
int extentArrayPtrRead; //tracks the logical index in extents array for read
int extentArrayPtrWrite; //tracks the logical index in extents array for write
} fd_struct;
extern fd_struct *fileOpen;
int b_open(char *filename, int flags);
int b_read(int fd, char *buffer, int count);
int b_write(int fd, char *buffer, int count);
int b_seek(int fd, off_t offset, int whence);
void b_close(int fd);
#endif
|
C
|
#include <stdio.h>
#include <string.h>
void zamienNapis(char napis[])
{
int l = strlen(napis);
for(int i = 0; i<l; i++)
{
if((napis[i] >= 97) && (napis[i] <= 122))
{
napis[i] -= 32;
}
else if((napis[i] >= 65) && (napis[i] <= 90))
{
napis[i] += 32;
}
}
}
int main()
{
char wyraz[31] = "";
gets(wyraz);
zamienNapis(wyraz);
printf("%s", wyraz);
return 0;
}
|
C
|
/*
** init_image.c for raytracer in /home/leprov_a//depot/rt/src
**
** Made by alexis leprovost
** Login <leprov_a@epitech.net>
**
** Started on Tue May 1 20:47:29 2012 alexis leprovost
** Last update Sun Jun 3 18:55:43 2012 ronan guiho
*/
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include "image.h"
#include "mlx.h"
#include "my.h"
#include "determ_img_type.h"
#include "import_jpg.h"
#include "import_bmp.h"
char *my_puterror_n_ret_null(char *str)
{
int len;
if (str != NULL)
{
len = write(2, str, strlen(str));
if (len != my_strlen(str))
exit(-1);
}
return (NULL);
}
t_image *empty_image(t_image *image, int x, int y, void *mlx_ptr)
{
image->ptr = mlx_new_image(mlx_ptr, x, y);
image->data = mlx_get_data_addr(image->ptr, &image->bpp,
&image->sizeline, &image->endian);
image->size[0] = x;
image->size[1] = y;
image->type = B_NONE;
image->cut_texture = NULL;
image->type_texture = 0;
image->relief = 0.0F;
image->freq = 1.0F;
return (image);
}
int create_default_img(t_image *image, void *mlx_ptr)
{
empty_image(image, 100, 100, mlx_ptr);
return (-1);
}
t_image *init_image(void *mlx_ptr, char *path, int x, int y)
{
t_image *image;
int img_type;
if (mlx_ptr == NULL)
return (NULL);
if ((image = malloc(sizeof(*image))) == NULL)
return (NULL);
if (path == NULL && x == 0 && y == 0)
return (NULL);
if (path == NULL)
return (empty_image(image, x, y, mlx_ptr));
img_type = determ_img_type(path);
if (img_type == JPG && import_jpg(path, image, mlx_ptr) == -1)
return (NULL);
if (img_type == XPM &&
((image->ptr = mlx_xpm_file_to_image \
(mlx_ptr, path, &image->size[WIDTH], &image->size[HEIGHT])) == NULL ||
(image->data = mlx_get_data_addr \
(image->ptr, &image->bpp, &image->sizeline, &image->endian)) != NULL))
img_type = IMG_ERROR;
if (img_type == IMG_ERROR && create_default_img(image, mlx_ptr) == -1)
my_puterror_n_ret_null("[*] Raytracer: Could not create image.\n");
return (img_type == BMP ? NULL :
img_type == IMG_ERROR ? NULL : image);
}
|
C
|
#include "common/an_zorder.h"
/*
* See https://graphics.stanford.edu/~seander/bithacks.html#InterleaveBMN for more info
*/
uint32_t
an_zorder(uint16_t x, uint16_t y)
{
uint64_t key = x;
key |= ((uint64_t)y << 32);
key = (key | (key << 8)) & 0x00FF00FF00FF00FFULL;
key = (key | (key << 4)) & 0x0F0F0F0F0F0F0F0FULL;
key = (key | (key << 2)) & 0x3333333333333333ULL;
key = (key | (key << 1)) & 0x5555555555555555ULL;
return (uint32_t)(key | key >> 31);
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_dtoa.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: armoulin <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2019/04/06 15:13:42 by armoulin #+# #+# */
/* Updated: 2019/04/08 14:24:14 by armoulin ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
static char *ft_round(char *str)
{
size_t i;
i = ft_strlen(str) - 1;
while (i && (str[i] == '9' || str[i] == '.'))
{
if (str[i] != '.')
str[i] = '0';
i--;
}
if (i == 0 && str[i] == '9')
{
str[i] = '0';
str = ft_str_addi_front('1', str, 1);
}
else
str[i]++;
return (str);
}
char *ft_dtoa(double nb, size_t preci)
{
char *res;
double dec_nb;
long long int_nb;
int_nb = (long long)nb;
dec_nb = nb - (double)int_nb;
res = ft_str_addi_back('.', ft_ntoa_base(int_nb, 0), 1);
while (preci--)
{
dec_nb *= 10;
int_nb = (long long)dec_nb;
dec_nb -= int_nb;
res = ft_str_addi_back('0' + int_nb, res, 1);
}
if ((dec_nb * 10) > 5.0)
res = ft_round(res);
return (res);
}
|
C
|
#define NPARRAYSIZE 20
#define CMDARRAYSIZE 20
#define STATARRAYSIZE 20
#define FINDSIZE 16
#define CORNER 0
#define STRAIGHT 1
#define MAXSPACES 5
typedef struct np_ {
int id;
int type; /* Corner or Straight */
int rot; /* Orientation */
int col; /* Center block of piece */
} np;
#define SLIDE 0
#define ROTATE 1
#define LEFT 0
#define RIGHT 1
#define CLK 1
#define CNTRCLK 0
typedef struct cmd_ * cmdPtr;
typedef struct cmd_ {
int cmd; /* Slide or Rotate */
int id; /* ID of piece */
int dir;
cmdPtr next;
} cmd;
#define CLEAR 0
#define TD 1
typedef struct stat_ {
int type; /* CLEAR or TD */
int sbm0; /* 16 bit integers lol */
int sbm1;
int sbm2;
int sbm3;
int sbm4;
int sbm5;
} stat;
/* Single Space States are
* 0 0 0 0 0 0 0 X 0 X 0 0 |X or X| 0 0
* X 0 X 0 X 0 X X 0 X 0 0 |X X| 0 0
* 1A 1AB 1B 1C 1D
* Priority
* Low Low Low High Med
* (strait (strait
* only) only)
* X = full space
* 0 = empty space
* | = wall
* |X = wall/full
*/
#define A1 0
#define B1 1
#define C1 3
#define D1 4
/* Double Space States are
* 0 0 0 0 |X or X| 0 0
* 1A 2B
* Preferred
*/
#define A2 5
#define B2 6
/* Triple Space States are
* 0 0 0 0 |X or X| 0 0
* 3A 3B
* Preferred
*/
#define A3 7
#define B3 8
typedef struct space_j {
int state; /* State of the space */
int row; /* Row of space */
int col; /* Location of space */
int rot; /* Same as in new piece */
int cost; /* Cost of space */
cmdPtr commands;
int priority; /* Priority */
} space_t; /* Could include a linked list of cmd */
/* Single space rotation costs
* Corner Piece States are (for reference):
* X X XX XX
* XX XX X X
* 0 1 2 4
* Transitions are # -> State
* 0 -> A RR
* 1 -> A L
* 2 -> A N
* 3 -> A R
*
* 0 -> B R
* 1 -> B RR
* 2 -> B L
* 3 -> B N
*
* R = rotate Right
* RR = rotate Right twice
* L = rotate Left
* N = No action taken
* If two actions must be taken, it will always be RR
*/
|
C
|
#define NULL ((void*)0)
typedef unsigned long size_t; // Customize by platform.
typedef long intptr_t; typedef unsigned long uintptr_t;
typedef long scalar_t__; // Either arithmetic or pointer type.
/* By default, we understand bool (as a convenience). */
typedef int bool;
#define false 0
#define true 1
/* Forward declarations */
/* Type definitions */
typedef scalar_t__ u_int ;
struct window_mode_entry {struct window_copy_mode_data* data; } ;
struct screen {int dummy; } ;
struct window_copy_mode_data {scalar_t__ cy; scalar_t__ oy; int /*<<< orphan*/ backing; struct screen screen; } ;
/* Variables and functions */
scalar_t__ screen_hsize (int /*<<< orphan*/ ) ;
scalar_t__ screen_size_y (struct screen*) ;
scalar_t__ window_copy_find_length (struct window_mode_entry*,scalar_t__) ;
int /*<<< orphan*/ window_copy_scroll_to (struct window_mode_entry*,scalar_t__,scalar_t__) ;
__attribute__((used)) static void
window_copy_next_paragraph(struct window_mode_entry *wme)
{
struct window_copy_mode_data *data = wme->data;
struct screen *s = &data->screen;
u_int maxy, ox, oy;
oy = screen_hsize(data->backing) + data->cy - data->oy;
maxy = screen_hsize(data->backing) + screen_size_y(s) - 1;
while (oy < maxy && window_copy_find_length(wme, oy) == 0)
oy++;
while (oy < maxy && window_copy_find_length(wme, oy) > 0)
oy++;
ox = window_copy_find_length(wme, oy);
window_copy_scroll_to(wme, ox, oy);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#define SIZE 10
int main(void)
{
int record[SIZE];
int times = 0;
srand(time(NULL));
int randomNumber = rand()%21;
int guess;
puts("Enter the number that you guess:");
do
{
scanf("%d", &guess);
if (guess < randomNumber)
{
printf("The number you guess is less than the number! try again: \n");
}
if (guess > randomNumber)
{
printf("THe number you guess is more than the random number! try again: \n");
}
record[times++] = guess;
} while (guess!=randomNumber && times<SIZE);
if (guess == randomNumber)
printf("Congulation! you use %d times chances to guess the number! \n", times);
else
{
printf("Sorry! the game is over! \n");
}
puts("The detail of the game:");
for (int i=0; i<times; i++)
{
printf("%d\n", record[i]);
}
return 0;
}
|
C
|
#include<stdlib.h>
#include<stdio.h>
#include<string.h>
/* Function to print an array */
void printArray(int arr[], int size) {
int i;
for (i=0; i < size; i++) {
printf("%d ", arr[i]);
}//for
}//printArray
void swap(int* x, int* y){
int t = *x;
*x = *y;
*y = t;
}
//Uses last element as pivot, places it at correct place in sorted array
//Then, puts all <= elements to the left of pivot, all > elements to right
int partition (int* arr, int low, int high) {
int pivot = arr[high];//pivot is last element
int i = low - 1;//index of smaller element
int j;
for (j = low; j < high; j++) {
if (arr[j]<=pivot) {
i++;//increment smaller element's index
swap(&arr[i], &arr[j]);
}
}//for
swap(&arr[i + 1], &arr[high]);
return (i+1);//
}
void quickSort(int* someArr, int low, int high){
if (low<high) {
//ptn is partitioning index, someArr[ptn] at right place
int ptn = partition(someArr, low, high);
//sort elements before and after partition
quickSort(someArr, low, ptn-1);
quickSort(someArr, ptn+1, high);
}
}//quickSort
int main() {
int i, arrLength;
if (scanf("%d", &arrLength) == 1 && arrLength > 0) {
int testArr[arrLength];
for (i = 0; i < arrLength; i++) {
scanf("%d", &testArr[i]);
}//for
quickSort(testArr, 0, arrLength-1);
printArray(testArr, arrLength);
exit(0);
} else {
exit(1);
}//if
/*int x[4] = {1,4,3,2};
printf("%d\n", sizeof(x));
return 0;*/
}
|
C
|
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include "move.h"
#include "disc.h"
static const int reversi_size = 8;
static const int top_left_corner = 0;
static const int top_right_corner = reversi_size - 1;
static const int bottom_left_corner = reversi_size * (reversi_size - 1);
static const int bottom_right_corner = (reversi_size * reversi_size) - 1;
/**************************************************************************/
typedef struct reversi {
char *array;
int n_moves;
} reversi_t;
/**************************************************************************/
static int position(int x, int y)
{
return reversi_size * y + x;
}
static int is_corner(int p)
{
return p % reversi_size == 0;
}
static int end_left(int p)
{
return p % reversi_size == 0;
}
static int end_right(int p)
{
return p % reversi_size == reversi_size - 1;
}
static int end_up(int p)
{
return p / reversi_size == 0;
}
static int end_down(int p)
{
return p / reversi_size == reversi_size - 1;
}
/**************************************************************************/
void reversi_init(reversi_t **r)
{
*r = malloc(sizeof(reversi_t));
(*r)->array = malloc(sizeof(char) * reversi_size * reversi_size);
(*r)->n_moves = reversi_size * reversi_size - 4;
int pos = position(reversi_size / 2 - 1, reversi_size / 2 - 1);
(*r)->array[pos] = WHITE;
(*r)->array[pos + 1] = BLACK;
(*r)->array[pos + reversi_size] = BLACK;
(*r)->array[pos + reversi_size + 1] = WHITE;
}
void reversi_free(reversi_t *r)
{
free(r->array);
free(r);
}
/**************************************************************************/
static void reversi_draw_line(void)
{
printf("\n +");
for (int i = 1; i < reversi_size; ++i)
printf("---+");
printf("---+\n");
}
static void reversi_draw_char(void)
{
printf(" ");
for (int i = 0; i < reversi_size; ++i)
printf(" %c ", i + 'A');
}
void reversi_display(reversi_t *r)
{
unsigned int i, j, k = 0;
printf("\n");
reversi_draw_char();
reversi_draw_line();
for (j = 1; j <= reversi_size; ++j) {
printf(" %d |", j);
for (i = 1; i <= reversi_size; ++i, ++k)
printf(" %c |", r->array[k]? r->array[k] : ' ');
printf(" %d", j);
reversi_draw_line();
}
reversi_draw_char();
printf("\n\n");
}
/**************************************************************************/
int reversi_is_possible(reversi_t *r, disc_t d, move_t *m)
{
int i;
/*constant move*/
const int cpos = position(m->x, m->y);
/*opponent*/
disc_t op = d == WHITE? BLACK : WHITE;
if (m->x == -1 && m->y == -1) return 0;
if (r->array[cpos] != 0) return 0;
/*horizontale 1*/
if (!end_left(cpos) && r->array[i = cpos - 1] == op) {
for (; !end_left(i) && r->array[i] == op; --i);
if (r->array[i] == d) return 1;
}
/*horizontale 2*/
if (!end_right(cpos) && r->array[i = cpos + 1] == op) {
for (; !end_right(i) && r->array[i] == op; ++i);
if (r->array[i] == d) return 1;
}
/*vertical 1*/
if (!end_up(cpos) && r->array[i = cpos - reversi_size] == op) {
for (; !end_up(i) && r->array[i] == op; i -= reversi_size);
if (r->array[i] == d) return 1;
}
/*vertical 2*/
if (!end_down(cpos) && r->array[i = cpos + reversi_size] == op) {
for (; !end_down(i) && r->array[i] == op; i += reversi_size);
if (r->array[i] == d) return 1;
}
/*diagonal 1*/
if (!end_left(cpos) && !end_up(cpos) && r->array[i = cpos - reversi_size - 1] == op) {
for (; !end_left(i) && !end_up(i) && r->array[i] == op; i -= reversi_size + 1);
if (r->array[i] == d) return 1;
}
/*diagonal 2*/
if (!end_right(cpos) && !end_down(cpos) && r->array[i = cpos + reversi_size + 1] == op) {
for (; !end_right(i) && !end_down(i) && r->array[i] == op; i += reversi_size + 1);
if (r->array[i] == d) return 1;
}
/*diagonal 3*/
if (!end_left(cpos) && !end_down(cpos) && r->array[i = cpos + reversi_size - 1] == op) {
for (; !end_left(i) && !end_down(i) && r->array[i] == op; i += reversi_size - 1);
if (r->array[i] == d) return 1;
}
/*diagonal 1*/
if (!end_right(cpos) && !end_up(cpos) && r->array[i = cpos - reversi_size + 1] == op) {
for (; !end_right(i) && !end_up(i) && r->array[i] == op; i -= reversi_size - 1);
if (r->array[i] == d) return 1;
}
return 0;
}
int reversi_exist_moves(reversi_t *r, disc_t d)
{
move_t m;
if (r->n_moves == 0) return 0;
for (m.x = 0; m.x < reversi_size; ++m.x)
for (m.y = 0; m.y < reversi_size; ++m.y)
if (reversi_is_possible(r, d, &m))
return 1;
return 0;
}
void reversi_put(reversi_t *r, disc_t d, move_t *m)
{
const int cpos = position(m->x, m->y);
int i;
disc_t op = d == WHITE? BLACK : WHITE;
r->array[cpos] = d;
/*horizontal1*/
if (!end_left(cpos)) {
for (i = cpos - 1; !end_left(i) && r->array[i] == op; --i);
if (r->array[i] == d)
for (; i < cpos; r->array[++i] = d);
}
/*horizontal2*/
if (!end_right(cpos)) {
for (i = cpos + 1; !end_right(i) && r->array[i] == op; ++i);
if (r->array[i] == d)
for (; i > cpos; r->array[--i] = d);
}
/*vertical1*/
if (!end_up(cpos)) {
for (i = cpos - reversi_size; !end_up(i) && r->array[i] == op; i -= reversi_size);
if (r->array[i] == d)
for (; i < cpos; r->array[i += reversi_size] = d);
}
/*vertical2*/
if (!end_down(cpos)) {
for (i = cpos + reversi_size; !end_down(i) && r->array[i] == op; i += reversi_size);
if (r->array[i] == d)
for (; i > cpos; r->array[i -= reversi_size] = d);
}
/*diagonal1*/
if (!end_left(cpos) && !end_up(cpos)) {
for (i = cpos - reversi_size - 1; !end_left(i) && !end_up(i) &&
r->array[i] == op; i -= reversi_size + 1);
if (r->array[i] == d)
for (; i < cpos; r->array[i += reversi_size + 1] = d);
}
/*diagonal2*/
if (!end_right(cpos) && !end_down(cpos)) {
for (i = cpos + reversi_size + 1; !end_right(i) && !end_down(i) &&
r->array[i] == op; i += reversi_size + 1);
if (r->array[i] == d)
for (; i > cpos; r->array[i -= reversi_size + 1] = d);
}
/*diagonal3*/
if (!end_left(cpos) && !end_down(cpos)) {
for (i = cpos + reversi_size - 1; !end_left(i) && !end_down(i) &&
r->array[i] == op; i += reversi_size - 1);
if (r->array[i] == d)
for (; i > cpos; r->array[i -= reversi_size - 1] = d);
}
/*diagonal4*/
if (!end_right(cpos) && !end_up(cpos)) {
for (i = cpos - reversi_size + 1; !end_right(i) && !end_up(i) &&
r->array[i] == op; i -= reversi_size - 1);
if (r->array[i] == d)
for (; i < cpos; r->array[i += reversi_size - 1] = d);
}
}
|
C
|
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <racr/racr.h>
#include "event.h"
#include "worker.h"
static Worker* workers = NULL;
static int worker_count;
void worker_kill(void) {
if (workers) {
free(workers);
workers = NULL;
}
worker_count = 0;
}
int worker_init(void) {
worker_kill();
FILE* f = fopen("config.txt", "r");
if (!f) return -1;
double time = timestamp();
char line[256];
char addr[256];
char type[256];
int id;
int parent_id;
while (fgets(line, sizeof(line), f)) {
if (line[0] == '#') continue;
if (strlen(line) == strspn(line, " \t\n")) continue;
char* endl = strchr(line, '\n');
if (*endl) *endl = '\0';
if (sscanf(line, "worker %d %d %s %s",
&id, &parent_id, addr, type) == 4) {
worker_count++;
workers = realloc(workers, sizeof(Worker) * worker_count);
Worker* w = &workers[worker_count - 1];
inet_pton(AF_INET, addr, &w->addr);
w->is_switch = 0;
w->id = id;
w->parent_id = parent_id;
w->port = 0;
w->socket_fd = -1;
w->state = WORKER_OFF;
w->timestamp = time;
int t;
for (t = 0; t < DEVICE_MAX; t++) {
if (strcmp(type, worker_device_string(t)) == 0) {
w->device_type = t;
break;
}
}
if (t == DEVICE_MAX) {
fclose(f);
return -2;
}
racr_call_str("add-worker-to-ast", "iisd", id, parent_id, type, time);
}
else if (sscanf(line, "switch %d %d", &id, &parent_id) == 2) {
worker_count++;
workers = realloc(workers, sizeof(Worker) * worker_count);
Worker* w = &workers[worker_count - 1];
memset(w, 0, sizeof(Worker));
w->is_switch = 1;
w->id = id;
w->parent_id = parent_id;
w->state = WORKER_OFF;
w->timestamp = time;
racr_call_str("add-switch-to-ast", "iid", id, parent_id, time);
}
else {
fclose(f);
return -3;
}
}
fclose(f);
return 0;
}
Worker* worker_next(Worker* w) {
if (!w) return workers;
if (w == workers + worker_count - 1) return NULL;
return w + 1;
}
Worker* worker_find_by_address(struct in_addr a, unsigned short p) {
int i;
for (i = 0; i < worker_count; i++) {
Worker* w = &workers[i];
if (w->is_switch) continue;
if (w->addr.s_addr == a.s_addr
&& (w->port == 0 || w->port == p)) return w;
}
return NULL;
}
Worker* worker_find_by_socket(int s) {
int i;
for (i = 0; i < worker_count; i++) {
Worker* w = &workers[i];
if (w->is_switch) continue;
if (w->socket_fd == s) return w;
}
return NULL;
}
Worker* worker_find_by_id(int id) {
int i;
for (i = 0; i < worker_count; i++) {
Worker* w = &workers[i];
if (w->id == id) return w;
}
return NULL;
}
ssize_t worker_send(Worker* w, const char* format, ...) {
char line[256];
va_list args;
va_start(args, format);
vsnprintf(line, sizeof(line), format, args);
va_end(args);
return send(w->socket_fd, line, strlen(line) + 1, 0);
}
|
C
|
#define F_CPU 1000000UL
#include <avr/io.h>
#include <util/delay.h>
void UART_init(void){
int UBRR_Value = 25; // 2400 baud rate
UBRRH = (unsigned char) (UBRR_Value >> 8);
UBRRL = (unsigned char) UBRR_Value;
UCSRB = (1 << RXEN);
UCSRC = (1 << USBS) | (3 << UCSZ0);
//UCSRC = 0b10001110;
}
unsigned char UART_receive(void){
// Wait until RXC flag is set to logic 1
while ((UCSRA & (1<<RXC)) == 0x00);
return UDR; // Read the received character from UDR
}
int main(void)
{
DDRD = 0b11111110;//PORTD pin0 as INPUT
DDRC = 0xFF;//PORTB as OUTPUT
//unsigned char receiveData;
// while ((UCSRA & (1 << RXC)) == 0x00);
//receiveData = UDR;
UART_init();
while (1)
{
PORTD = 0b11111100;
char ch = UART_receive();
if(ch == '0'){
PORTC = 0x00;
PORTC |= (1<<PC1);
_delay_ms(200);
}
else if(ch == '1'){
PORTC = 0x00;
PORTC |= (1<<PC2);
_delay_ms(100);
}
else if(ch == '2'){
PORTC = 0x00;
PORTC |= (1<<PC3);
_delay_ms(200);
}
else if(ch == '3'){
PORTC = 0x00;
PORTC |= (1<<PC4);
_delay_ms(200);
}
else if(ch == '4'){
PORTC = 0x00;
PORTC |= (1<<PC5);
_delay_ms(200);
}
else if(ch == '5'){
PORTC = 0x00;
PORTC |= (1<<PC6);
_delay_ms(200);
}
else if(ch == '6'){
PORTC = 0x00;
PORTC |= (1<<PC7);
_delay_ms(200);
}
else if(ch == '7'){
PORTC = 0x00;
PORTC |= (1<<PC0);
_delay_ms(200);
}
}
}
|
C
|
#include <stdio.h>
void function()
{
int a;
block#1
{
block#2
{
}
block#3
{
}
}
}
void functionA()
{
int b;
block#1
{
}
block#2
{
}
}
void main()
{
printf("Hello Sample");
}
|
C
|
#ifndef SPI_HEADER_THOMAS_CHEVALIER
#define SPI_HEADER_THOMAS_CHEVALIER
#include <avr/io.h>
#define LSBFIRST 0
#define MSBFIRST 1
#define SPI_CLOCK_DIV4 0x00
#define SPI_CLOCK_DIV16 0x01
#define SPI_CLOCK_DIV64 0x02
#define SPI_CLOCK_DIV128 0x03
#define SPI_CLOCK_DIV2 0x04
#define SPI_CLOCK_DIV8 0x05
#define SPI_CLOCK_DIV32 0x06
#define SPI_MASTER 0x10
#define SPI_ENABLE 0x40
#define SPI_MODE0 0x00
#define SPI_MODE1 0x04
#define SPI_MODE2 0x08
#define SPI_MODE3 0x0C
#define SPI_MODE_MASK 0x0C // CPOL = bit 3, CPHA = bit 2 on SPCR
#define SPI_CLOCK_MASK 0x03 // SPR1 = bit 1, SPR0 = bit 0 on SPCR
#define SPI_2XCLOCK_MASK 0x01 // SPI2X = bit 0 on SPSR
/**
* @brief Setup register for SPI.
*/
void spi_init (void);
/**
* @brief Send a byte via the spi port and read one.
*
* @param data The byte to send.
* @return The byte that the slave send.
*/
uint8_t spi_transfer_8 (uint8_t data);
/**
* @brief Shift full array to target device without receiving any byte.
*
* @param dataout The array of bytes to send.
* @param len The lenght of the array.
*/
void spi_send (uint8_t * dataout, uint8_t len);
/**
* @brief Write one byte on the bus without receiving anything.
*
* @param data The byte to send.
*/
void spi_send_8 (uint8_t data);
/**
* @brief Read an array of byte from spi bus.
*
* @param buffer The array that contains the content read.
* @param size How many bytes to read.
*/
void spi_read (uint8_t* buffer, uint8_t size);
/**
* @brief Read one byte from the bus.
* @details Send a dummy byte (0x00). Same as spi_transfer_8(0x00).
* @return The byte that the slave send.
*/
uint8_t spi_read_8 (void);
/**
* @brief Send several times a byte on the spi bus.
*
* @param val The byte to send several times.
* @param num How many times the byte must be sent.
*/
void spi_set (uint8_t val, uint8_t num);
#endif // SPI_HEADER_THOMAS_CHEVALIER
|
C
|
int foo(int a, int b, int c, int d, int e, int f) {
printf("%d\n", a + b + c + d + e + f);
}
|
C
|
#include "stdlib.h"
#include "stdio.h"
#include "file.h"
void catmain() {
char src[20];
char w;
int f_src, my_ds;
asm mov ax, ss
asm mov my_ds, ax
src[0] = 0;
getParameter(my_ds, src);
f_src = fopen(src, "r");
if (f_src >= 0) {
} else
if (f_src == -1) {
puts("error: file not found");
exit(0);
} else
if (f_src == -2) {
puts("error: file is being occupied");
exit(0);
} else
if (f_src == -3) {
puts("error: no enough space");
exit(0);
} else
if (f_src == -4) {
puts("error: unknown open method");
exit(0);
} else {
puts("error: unknown error");
exit(0);
}
while ((w = fgetc(f_src)) != -1) {
putchar(w);
}
puts("");
fclose(f_src);
exit(0);
}
|
C
|
#include "perf_poll.h"
#include <sys/ioctl.h>
#include <assert.h>
#include <errno.h>
#include <stdio.h>
#include <string.h>
#include "syscallers.h"
int perf_poll_init(size_t count, const struct perf_event_attr *counters) {
assert(counters);
int fd = -1;
for(unsigned idx = 0; idx < count; ++idx) {
int tfd = perf_event_open(counters + idx, 0, -1, fd, 0);
if(tfd == -1) {
int terrno = errno;
char desc[] = "Initializing perf counter \0\0";
sprintf(strchr(desc, '\0'), "%u", idx);
errno = terrno;
puts(desc);
return tfd;
}
if(fd == -1)
fd = tfd;
}
return fd;
}
bool perf_poll_start(int fd) {
assert(fd > fileno(stderr));
return ioctl(fd, PERF_EVENT_IOC_ENABLE) >= 0;
}
bool perf_poll_stop(int fd) {
assert(fd > fileno(stderr));
return ioctl(fd, PERF_EVENT_IOC_DISABLE) >= 0;
}
|
C
|
#include <metodo/metodo.h>
#include <system.h>
void stop_dump_stack(void);
#define STOP_MSG "A problem has been detected and Dux has been shut down to prevent damage\nto your computer.\n\n"
#define va_start(v,l) __builtin_va_start(v,l)
#define va_arg(v,l) __builtin_va_arg(v,l)
#define va_end(v) __builtin_va_end(v)
#define va_copy(d,s) __builtin_va_copy(d,s)
//typedef __builtin_va_list va_list;
struct stack_frame {
struct stack_frame *next;
void *addr;
};
unsigned int stack;
void stack_dump(void);
void register_dump(void);
char *stop_table[7] = {
(char*)0x01, "ASSERTION_FAILED",
(char*)0x02, "NO_MULTIBOOT",
(char*)0x10, "USER_INITIALIZED",
(char*)0x0
};
int in_panic = 0;
void panic(char *text)
{
if (in_panic) {
/* Something is causing a recursive panic, so
* just kill the machine. */
asm volatile("cli");
asm volatile("hlt");
}
in_panic = 1;
HalInitDisplay();
HalDisplaySetAttr(0x4f);
HalDisplayClear();
printf("\nDux quacked!\n%s\n\n", text);
stack_dump();
asm("cli");
asm("hlt");
}
void panic_dump_hex(unsigned int *stack)
{
unsigned int orig_stack = (unsigned int) stack;
printf("\nStack Contents\n");
while ((unsigned int) stack < ((orig_stack+0x1000) & ~(0x1000-1))) {
printf("0x%x: 0x%x\n", stack, *stack);
// TODO: Check if this is the proper method
if ( *stack == 0x0 )
break;
stack++;
}
}
char *stop_getmsg(int error)
{
int i;
int index;
/* Loop through the table, stopping at every other entry to see if it
* matches. If so, record it. */
for (i = 0; stop_table[i] != 0x0; i+=2) {
if ((int)stop_table[i] == error) {
index = i;
break;
}
}
return stop_table[index+1];
}
void stop(int error, int argc, ...)
{
va_list ap;
int i;
int arg;
if (in_panic) {
/* Something is causing a recursive stop, so
* just kill the machine. */
asm volatile("cli");
asm volatile("hlt");
}
in_panic = 1;
HalInitDisplay();
HalDisplaySetAttr(0x4f);
HalDisplayClear();
printf(STOP_MSG);
printf("%s\n\n", stop_getmsg(error));
printf("STOP: 0x%x (", error);
/* Print all the arguments. */
va_start(ap, argc);
for (i = 0; i < argc; i++) {
arg = va_arg(ap, unsigned int);
printf("0x%x, ", arg);
}
/* \x08 is backspace, so it doesn't have an extra ", " at the end. */
if (argc != 0)
printf("\x08\x08)\n\n");
else
printf(")\n\n");
va_end(ap);
printf("Stack Dump:\n\n");
stop_dump_stack();
asm volatile("cli");
asm volatile("hlt");
}
void assert_dowork(char *file, int line)
{
printf("Asserton failed in %s:%d", file, line);
stop(0x01, 0x2, file, line);
}
void stop_dump_stack(void)
{
struct stack_frame *frame;
asm volatile ("movl %%ebp, %0" : "=rm" (frame));
while ((unsigned int)frame < stack) {
printf("addr: 0x%x, frame: 0x%x\n", frame->addr, frame);
frame = frame->next;
}
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct node* nptr;
typedef struct node{
int data;
nptr link;
}NODE;
void Insert(nptr*, int);
void PrintAll(nptr head);
int main(void){
int A[10] = {3, 9, 8, 2, 5, 10, 7, 1, 4, 6};
nptr head = NULL;
int i;
for(i = 0; i<10; i++){
Insert(&head, A[i]);
PrintAll(head);
}
printf("%d\n", head->data);
return 0;
}
void Insert(nptr* head, int n){
NODE*end = *head;
NODE*new = (NODE*)malloc(sizeof(NODE));
new->data = n;
new->link = NULL;
if(*head == NULL){
*head = new;
}
else{
while(1){
if(end->link == NULL){
end->link = new;
break;
}
else end = end->link;
}
}
return;
}
void PrintAll(nptr head){
NODE *end = head;
while(1){
printf("%d ", end->data);
end = end->link;
if(end == NULL) break;
}
printf("\n");
return;
}
|
C
|
#include "../common/chatroom.h"
#include "../common/tcp_client.h"
#include "../common/common.h"
#include "../common/color.h"
char *conf = "./client.conf";
int sockfd;
void *logout(int signalnum) {
close(sockfd);
exit(1);
printf("recv a signal");
}
int main() {
system("clear");
int port;
struct Msg msg;
char ip[20] = {0};
port = atoi(get_value(conf, "SERVER_PORT"));
strcpy(ip, get_value(conf, "SERVER_IP"));
printf("ip = %s , port = %d\n", ip, port);
if ((sockfd = socket_connect(ip, port)) < 0) {
perror("socket_connect");
return 1;
}
strcpy(msg.from, get_value(conf, "MY_NAME"));
printf("%s\n", msg.from);
msg.flag = 2;
if (chat_send(msg, sockfd) < 0) {
return 2;
}
struct RecvMsg rmsg = chat_recv(sockfd);
if (rmsg.retval < 0) {
fprintf(stderr, "Error!\n");
return 1;
}
printf(GREEN"Server "NONE": %s\n", rmsg.msg.message);
if (rmsg.msg.flag == 3) {
close(sockfd);
return 1;
}
pid_t pid;
int x;
for (int i = 0; i < 2; i++) {
if ((pid = fork()) < 0){
perror("fork");
}
if (pid == 0) {
x = i;
break;
}
}
if (pid == 0 && x == 0) {
signal(SIGINT, logout);
while (1) {
char tmp[533];
scanf("%[^\n]s", tmp);
getchar();
int len = 0;
if (tmp[0] == '@') {
msg.flag = 1;
while (tmp[len] != ' ' && len < strlen(tmp)) {
len++;
}
strncpy(msg.to, tmp + 1, len - 1);
msg.to[len - 1] = '\0';
}
else {
msg.flag = 0;
}
strcpy(msg.message, tmp + len);
chat_send(msg, sockfd);
memset(msg.message, 0, sizeof(msg.message));
}
}
else if (pid == 0 && x == 1) {
while(1) {
rmsg = chat_recv(sockfd);
FILE *fp;
fp=fopen("./Log_File","a");//参数a表示追加写入
fprintf(fp, BLUE"[%s]"NONE, rmsg.msg.from);
if (rmsg.msg.flag == 1) {
fprintf(fp, "私聊 %s :%s\n", rmsg.msg.to, rmsg.msg.message);
}
else {
fprintf(fp, "公聊:%s\n", rmsg.msg.message);
}
fclose(fp);
system("clear");
system("tail -10 ./Log_File");
printf(L_PINK"Please Input Message:"NONE"\n");
}
}
else{
wait(NULL);
close(sockfd);
}
return 0;
}
|
C
|
/*
* zero_skew_adjust.c
*
* Created on: Nov 19, 2018
* Author: wei100
*/
#include "zst.h"
void recalc_total_cap(node* curr) {
if(curr->leaf_node_label != -1) {
return;
}
else {
double left_cap = 0.0;
double right_cap = 0.0;
if(curr->left->node_num != -1 && curr->left->num_node_inv == 0){
//If the left child is not an inverter nor an internal node with an inverter
left_cap = curr->left->total_cap;
}
else {
//If the left child is an inverter or an internal node with an inverter
left_cap = curr->left->num_node_inv * inv_cin;
}
if(curr->right != NULL) {
//If the node has a right child
if(curr->right->node_num != -1 && curr->right->num_node_inv == 0){
//If the right child is not an inverter or an internal node with an inverter
right_cap = curr->right->total_cap;
}
else {
//If the right child is an inverter or an internal node with an inverter
right_cap = curr->right->num_node_inv * inv_cin;
}
}
if(curr->right != NULL) {
curr->total_cap = inv_cout * curr->num_node_inv + left_cap + right_cap + c * (curr->left_wire_len + curr->right_wire_len);
}
else {
curr->total_cap = inv_cout * curr->num_node_inv + left_cap + c * curr->left_wire_len;
}
}
}
void zero_skew_adjust(node* curr) {
recalc_total_cap(curr);
if(curr->leaf_node_label != -1) {
curr->delay = 0.0;
return;
}
double wire_delay_l = 0.0;
double wire_delay_r = 0.0;
if(curr->left->node_num != -1 && curr->left->num_node_inv == 0) {
wire_delay_l = r * curr->left_wire_len * (curr->left->total_cap + c * curr->left_wire_len / 2);
}
else {
wire_delay_l = r * curr->left_wire_len * (curr->left->num_node_inv * inv_cin + c * curr->left_wire_len / 2);
}
if(curr->node_num == -1) {
double propagation_delay = SKEW_CONST * inv_rout * 1 / curr->num_node_inv * curr->total_cap;
curr->delay = curr->left->delay + wire_delay_l + propagation_delay;
return;
}
if(curr->right != NULL) {
if(curr->right->node_num != -1 && curr->right->num_node_inv == 0) {
wire_delay_r = r * curr->right_wire_len * (curr->right->total_cap + c * curr->right_wire_len / 2);
}
else {
wire_delay_r = r * curr->right_wire_len * (curr->right->num_node_inv * inv_cin + c * curr->right_wire_len / 2);
}
}
double left_time = curr->left->delay + wire_delay_l;
double right_time;
if(curr->right != NULL) {
right_time = curr->right->delay + wire_delay_r;
} else {
curr->delay = left_time;
return;
}
curr->delay = left_time;
if(!almost_equal_relative(left_time, right_time)) {
if(left_time < right_time) {
double a, b, c_new;
//Right branch arrival too late, make the left wire longer
if(curr->left->node_num != -1 && curr->left->num_node_inv == 0) {
a = r * c / 2;
b = r * curr->left->total_cap;
if(curr->right->node_num != -1 && curr->right->num_node_inv == 0) {
c_new = curr->left->delay - curr->right->delay - r * curr->right->total_cap * curr->right_wire_len - 0.5 * r * c * pow(curr->right_wire_len, 2);
}
else {
c_new = curr->left->delay - curr->right->delay - r * curr->right->num_node_inv * inv_cin * curr->right_wire_len - 0.5 * r * c * pow(curr->right_wire_len, 2);
}
curr->left_wire_len = (-b + sqrt(pow(b, 2) - 4 * a * c_new)) / (2 * a);
wire_delay_l = r * curr->left_wire_len * (curr->left->total_cap + c * curr->left_wire_len / 2);
}
else {
a = r * c / 2;
b = r * curr->left->num_node_inv * inv_cin;
if(curr->right->node_num != -1 && curr->right->num_node_inv == 0) {
c_new = curr->left->delay - curr->right->delay - r * curr->right->total_cap * curr->right_wire_len - 0.5 * r * c * pow(curr->right_wire_len, 2);
}
else {
c_new = curr->left->delay - curr->right->delay - r * curr->right->num_node_inv * inv_cin * curr->right_wire_len - 0.5 * r * c * pow(curr->right_wire_len, 2);
}
curr->left_wire_len = (-b + sqrt(pow(b, 2) - 4 * a * c_new)) / (2 * a);
wire_delay_l = r * curr->left_wire_len * (curr->left->num_node_inv * inv_cin + c * curr->left_wire_len / 2);
}
curr->delay = curr->left->delay + wire_delay_l;
}
else {
double a, b, c_new;
//Left branch arrival too late, make the right wire longer
if(curr->right->node_num != -1 && curr->right->num_node_inv == 0) {
a = r * c / 2;
b = r * curr->right->total_cap;
if(curr->left->node_num != -1 && curr->left->num_node_inv == 0) {
c_new = curr->right->delay - curr->left->delay - r * curr->left->total_cap * curr->left_wire_len - 0.5 * r * c * pow(curr->left_wire_len, 2);
}
else {
c_new = curr->right->delay - curr->left->delay - r * curr->left->num_node_inv * inv_cin * curr->left_wire_len - 0.5 * r * c * pow(curr->left_wire_len, 2);
}
curr->right_wire_len = (-b + sqrt(pow(b, 2) - 4 * a * c_new)) / (2 * a);
wire_delay_r = r * curr->right_wire_len * (curr->right->total_cap + c * curr->right_wire_len / 2);
}
else {
a = r * c / 2;
b = r * curr->right->num_node_inv * inv_cin;
if(curr->left->node_num != -1 && curr->left->num_node_inv == 0) {
c_new = curr->right->delay - curr->left->delay - r * curr->left->total_cap * curr->left_wire_len - 0.5 * r * c * pow(curr->left_wire_len, 2);
}
else {
c_new = curr->right->delay - curr->left->delay - r * curr->left->num_node_inv * inv_cin * curr->left_wire_len - 0.5 * r * c * pow(curr->left_wire_len, 2);
}
curr->right_wire_len = (-b + sqrt(pow(b, 2) - 4 * a * c_new)) / (2 * a);
wire_delay_r = r * curr->right_wire_len * (curr->right->num_node_inv * inv_cin + c * curr->right_wire_len / 2);
}
curr->delay = curr->right->delay + wire_delay_r;
}
}
double propagation_delay_node = 0.0;
recalc_total_cap(curr);
if(curr->num_node_inv > 0) {
propagation_delay_node = SKEW_CONST * inv_rout * 1 / curr->num_node_inv * curr->total_cap;
}
curr->delay += propagation_delay_node;
}
|
C
|
# inclui < stdio.h >
# inclui < string.h >
int main ( void ) {
char msg [ 20 ];
// Inicializa uma msg como uma string vazia
msg [ 0 ] = ' \ 0 ' ;
char dado;
faça {
// Ler uma letra do teclado
dado = getchar ();
printf ( " Digitado: % c \ n " , dado);
// Tudo que for digitado que não for enter (\ n) vai para dentro da variavel msg
if (dado! = ' \ n ' ) {
sprintf (msg, " % s% c " , msg, dado);
}
printf ( " Valor de msg: % s \ n " , msg);
} enquanto (dado! = ' q ' );
printf ( " FIM DIGITACAO! \ n " );
printf ( " % s \ n " , msg);
// Verifica uma mensagem recebida
if ( strcmp (msg, " olaq " ) == 0 ) {
printf ( " Msg valida! \ n " );
} else {
printf ( " Msg invalida recebida! \ n " );
}
return 0 ;
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* pushing_qsort_addition.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: amichak <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2018/01/18 16:36:00 by amichak #+# #+# */
/* Updated: 2018/01/18 16:36:01 by amichak ### ########.fr */
/* */
/* ************************************************************************** */
#include "push_swap.h"
t_stack *buble_sort_st(t_stack *st, int q)
{
int i;
int y;
t_stack *head;
i = 0;
head = st;
while (i < q - 1)
{
y = 0;
while (y < q - i - 1)
{
if (st && st->next && st->cont > st->next->cont)
ft_swap(&st->cont, &st->next->cont);
y++;
if (st && st->next)
st = st->next;
}
i++;
st = head;
}
return (st);
}
t_stack *stcpy(t_stack *st)
{
t_stack *newst;
if (st)
newst = stcpy(st->next);
else
return (NULL);
add_node(&newst, st->cont);
return (newst);
}
int find_av_val(t_stack *st, int qel, int a)
{
int i;
t_stack *newst;
t_stack *tmp;
int res;
i = 0;
newst = buble_sort_st(stcpy(st), qel);
tmp = newst;
if (qel % 2 == 1 || a)
while (i < qel / 2)
{
tmp = tmp->next;
i++;
}
else
while (i < qel / 2 - 1)
{
tmp = tmp->next;
i++;
}
res = tmp->cont;
delete_stack(&newst);
return (res);
}
int find_quant_to_move(t_stack *st, int av_val, char s_cmp)
{
int res;
res = 0;
if (s_cmp == '<')
{
while (st)
{
if (st->cont <= av_val)
res++;
st = st->next;
}
}
else if (s_cmp == '>')
{
while (st)
{
if (st->cont > av_val)
res++;
st = st->next;
}
}
return (res);
}
|
C
|
#include<stdio.h>
main()
{
double a1,b1,c1,a2,b2,c2,R,x,y;
printf("a1=");
scanf("%lf",&a1);
printf("b1=");
scanf("%lf",&b1);
printf("c1=");
scanf("%lf",&c1);
printf("a2 b2 c2\n");
scanf("%lf%lf%lf",&a2,&b2,&c2);
R=a1*b2-a2*b1;
if(R==0)
printf("error");
x=(c1*b2-c2*b1)/R;
y=(a1*c2-a2*c1)/R;
printf("x=%lf\n y=%lf",x,y);
return 0;
}
|
C
|
#include<stdio.h>
int main()
{
int max=0,i,n,sum=0;
scanf("%d",&n);
int num[n];
for(i=0; i<n; i++)
{
scanf("%d",&num[i]);
if(max<num[i])
{
max=num[i];
sum=i+1;
}
}
printf("%d %d",sum,max);
return 0;
}
|
C
|
#include<fcntl.h>
#include<stdio.h>
main()
{
char *fname = "test.txt";
int fd;
fd = creat(fname,0777);
if(fd<0)
perror("creat()");
else{
printf("Sucess!\n Filename : %s, fd :%d\n",fname,fd);
close(fd);
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.