language
large_stringclasses 1
value | text
stringlengths 9
2.95M
|
|---|---|
C
|
/*
Image Processing
Bilateral Filtering Images
Ivan Alexander Rulik Cote
10/10/2021
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <malloc/malloc.h>
#include <memory.h>
#define max(x, y) ((x>y) ? (x):(y))
#define min(x, y) ((x<y) ? (x):(y))
int xdim;
int ydim;
int maxraw;
unsigned char *image;
unsigned char *imageOut;
unsigned char *imageOutBF;
unsigned char *imageOutG;
/*
New variables defined for the project
*/
float t; // escale factor modified by the user IDEA: make it the 4th argument for an easier use
float s; // spatial extent of the kernel, size of the considered neighborhood.
float r; // “minimum” amplitude of an edge
int n; // size of the filter window
int mode; // user input for mode
void ReadPGM(FILE*);
void WritePGM(FILE*);
/* This new fuction will take a given file and apply Bilinear Interpolation to it */
// void BilinearInterpolation(FILE*, float t);
void BilateralFiltering(FILE*, float r, float s, int n);
void GaussianFiltering(FILE*, float s, int n);
int main(int argc, char **argv)
{
int i, j;
FILE *fp;
if (argc != 7){
printf("Usage: MyProgram <input_ppm> <output_ppm> \n");
printf(" <input_ppm>: PGM file \n");
printf(" <output_ppm>: PGM file \n");
exit(0);
}
/* This code reads the escaling factor as an argument and changes its type from char*
to float using the function atof(), then it prints the value to give feedback */
mode = atof(argv[3]);
if(mode == 0){
printf("Mode = Gaussian Filering \n");
}
else if(mode == 1){
printf("Mode = Bilateral Filering \n");
}
else{
printf("Bad input, taking Mode = Gaussian Filering \n");
}
n = atof(argv[4]);
s = atof(argv[5]);
r = atof(argv[6]);
printf("Window Size = %d by %d\n",n,n);
n = (n-1)/2;
printf("Space Factor = %3.2f \n",s);
printf("Range Factor = %3.2f \n",r);
/* begin reading PGM.... */
printf("begin reading PGM.... \n");
if ((fp=fopen(argv[1], "rb"))==NULL){
printf("read error...\n");
exit(0);
}
ReadPGM(fp);
// your application here
// As an example, let's just make an inversion of the input image.
// for (j=0; j<ydim; j++)
// for (i=0; i<xdim; i++) {
// image[j*xdim+i] = 255 - image[j*xdim+i];
// }
/* Begin writing PGM.... */
printf("Begin writing PGM.... \n");
if ((fp=fopen(argv[2], "wb")) == NULL){
printf("write pgm error....\n");
exit(0);
}
/* Calculate the new dimension of the output image by multiplying the
scale factor and then rounding it to the closest integer */
// xdimOut = round(t*xdim);
// ydimOut = round(t*ydim);
// printf("Out Width=%d, Out Height=%d \n",xdimOut,ydimOut);
// BilateralFiltering(fp,s,r,n);
if(mode == 0){
GaussianFiltering(fp,s,n);;
}
else if(mode == 1){
BilateralFiltering(fp,s,r,n);;
}
else{
GaussianFiltering(fp,s,n);;
}
WritePGM(fp);
free(image);
free(imageOut);
return (1);
}
void ReadPGM(FILE* fp)
{
int c;
int i,j;
int val;
unsigned char *line;
char buf[1024];
while ((c=fgetc(fp)) == '#')
fgets(buf, 1024, fp);
ungetc(c, fp);
if (fscanf(fp, "P%d\n", &c) != 1) {
printf ("read error ....");
exit(0);
}
if (c != 5 && c != 2) {
printf ("read error ....");
exit(0);
}
if (c==5) {
while ((c=fgetc(fp)) == '#')
fgets(buf, 1024, fp);
ungetc(c, fp);
if (fscanf(fp, "%d%d%d",&xdim, &ydim, &maxraw) != 3) {
printf("failed to read width/height/max\n");
exit(0);
}
printf("Width=%d, Height=%d \nMaximum=%d\n",xdim,ydim,maxraw);
image = (unsigned char*)malloc(sizeof(unsigned char)*xdim*ydim);
getc(fp);
line = (unsigned char *)malloc(sizeof(unsigned char)*xdim);
for (j=0; j<ydim; j++) {
fread(line, 1, xdim, fp);
for (i=0; i<xdim; i++) {
image[j*xdim+i] = line[i];
}
}
free(line);
}
else if (c==2) {
while ((c=fgetc(fp)) == '#')
fgets(buf, 1024, fp);
ungetc(c, fp);
if (fscanf(fp, "%d%d%d", &xdim, &ydim, &maxraw) != 3) {
printf("failed to read width/height/max\n");
exit(0);
}
printf("Width=%d, Height=%d \nMaximum=%d,\n",xdim,ydim,maxraw);
image = (unsigned char*)malloc(sizeof(unsigned char)*xdim*ydim);
getc(fp);
for (j=0; j<ydim; j++)
for (i=0; i<xdim; i++) {
fscanf(fp, "%d", &val);
image[j*xdim+i] = val;
}
}
fclose(fp);
}
// void WritePGM(FILE* fp)
// {
// int i,j;
// fprintf(fp, "P5\n%d %d\n%d\n", xdim, ydim, 255);
// for (j=0; j<ydim; j++)
// for (i=0; i<xdim; i++) {
// fputc(image[j*xdim+i], fp);
// }
// fclose(fp);
// }
void WritePGM(FILE* fp)
{
int i,j;
fprintf(fp, "P5\n%d %d\n%d\n", xdim, ydim, 255);
for (j=0; j<ydim; j++)
for (i=0; i<xdim; i++) {
fputc(imageOut[j*xdim+i], fp);
}
fclose(fp);
}
// void BilinearInterpolation(FILE* fp, float t)
// {
// int i,j;
// int T1, T2;
// int A[2],B[2],C[2],D[2];
// float x,y;
// float distX, distY;
// imageOutBF = (unsigned char*)malloc(sizeof(unsigned char)*xdimOut*ydimOut);
// for (j=0; j<ydimOut; j++)
// for (i=0; i<xdimOut; i++) {
// /* Visual representation of the loop to sample the
// new pixel intensities based on the original image
// A##########B
// |##########|
// -####ij####-
// T1#########|
// |#########T2
// C##########D
// */
// x=i/t; // current position of the sampled image mapped to the orginal on the x axis
// y=j/t; // current position of the sampled image mapped to the orginal on the y axis
// A[0]=floor(x); // left top corner neighbor x
// A[1]=floor(y)+1; // left top corner neighbor y
// B[0]=floor(x)+1; // right top corner neighbor x
// B[1]=floor(y)+1; // right top corner neighbor y
// C[0]=floor(x); // left botton corner neighbor x
// C[1]=floor(y); // left botton corner neighbor y
// D[0]=floor(x) + 1; // right bottom corner neighbor x
// D[1]=floor(y); // right bottom corner neighbor y
// distX=x-floor(x); // x distance from current pixel to bottom left corner
// distY=y-floor(y); // y distance from current pixel to bottom left corner
// T1 = distY*image[(A[1]*xdim)+A[0]] + (1-distY)*image[(C[1]*xdim)+C[0]]; // y distance of the (i,j) pixel to the left lower edge corner and theleft top neighbor
// T2 = distY*image[(B[1]*xdim)+B[0]] + (1-distY)*image[(D[1]*xdim)+D[0]]; // x distance of the (i,j) pixel to the left lower edge corner
// imageOut[j*xdimOut+i] = distX*T2 + (1-distX)*T1;
// }
// }
void BilateralFiltering(FILE* fp, float s, float r, int n)
{
int x,y;
int i,j;
int wx,wy;
float g,h;
float hp, w;
imageOut = (unsigned char*)malloc(sizeof(unsigned char)*xdim*ydim);
for (y=0;y<ydim;y++)
{
for(x=0;x<xdim;x++)
{
g=0;
h=0;
hp=0;
w=0;
// start window loops
for(j=-n;j<n;j++)
{
for(i=-n;i<n;i++)
{
// keep indexes within bounds
wx=i+x;
wy=j+y;
if(wx<0){wx=0;}
if(wy<0){wy=0;}
if(wx>xdim-1){wx=xdim-1;}
if(wy>ydim-1){wy=ydim-1;}
// Gaussian Filter weight
g =exp(-(pow((wx-x),2)/(2*pow(s,2))+pow((wy-y),2)/(2*pow(s,2))));
// bilateral weight
h=g*exp(-(pow((image[wy*xdim+wx]-image[y*xdim+x]),2)/(2*pow(r,2))));
hp += h*image[wy*xdim+wx];
w += h;
}
}
// apply filtered window into output pixel
imageOut[y*xdim+x] = round(hp/w);
printf("intensity= In %d vs Out %d \n",image[y*xdim+x], imageOut[y*xdim+x]);
}
}
}
void GaussianFiltering(FILE* fp, float s, int n)
{
int x,y;
int i,j;
int wx,wy;
double g;
float gp, w;
imageOut = (unsigned char*)malloc(sizeof(unsigned char)*xdim*ydim);
for (y=0;y<ydim;y++)
{
for(x=0;x<xdim;x++)
{
g=0;
gp=0;
w=0;
// start window loops
for(j=-n;j<n;j++)
{
for(i=-n;i<n;i++)
{
// keep indexes within bounds
wx=i+x;
wy=j+y;
if(wx<0){wx = 0;}
if(wy<0){wy=0;}
if(wx>xdim-1){wx=xdim-1;}
if(wy>ydim-1){wy=ydim-1;}
// Gaussian Filter weight
g =exp(-(pow((wx-x),2)/(2*pow(s,2))+pow((wy-y),2)/(2*pow(s,2))));
gp += g*image[wy*xdim+wx];
w += g;
}
}
// apply filtered window into output pixel
imageOut[y*xdim+x] = round(gp/w);
printf("intensity= In %d vs Out %d \n",image[y*xdim+x], imageOut[y*xdim+x]);
}
}
}
|
C
|
#include <stdio.h>
int main() {
float BaseMaior, BaseMenor, Altura, Area;
//Recebe os valores da base maior, menor e altura
printf("Digite o valor da Base Maior do trapézio: cm ");
scanf("%f", &BaseMaior);
printf("Digite o valor da Base Menor do trapézio: cm ");
scanf("%f", &BaseMenor);
printf("Digite o valor da Altura: cm ");
scanf("%f", &Altura);
//Calcula o valor da area
Area = ((BaseMenor + BaseMaior) * Altura) / 2;
//Mostra o valor obtido
printf("A área do trapézio vale: %.2f %s",Area,"cm²");
return 0;
}
|
C
|
#include <stdio.h>
#include <ctype.h>
#include <assert.h>
#include <string.h>
#define MAXSTRING 100
int edit_dist(char *x, char *y);
int stringlen(char *x);
int change(char *x, char *y);
void tests(void);
int main() {
char string1[MAXSTRING], string2[MAXSTRING];
int i;
printf("enter 2, 4 letter words:\n");
scanf("%s", string1);
scanf("\n%s", string2);
printf("\n");
tests();
while (edit_dist(string1, string2) != 0) {
printf("%s\n",string1);
change(string1, string2);
}
return 0;
}
int edit_dist(char *x, char *y){
int i,count = 0;
char letter1, letter2;
if(stringlen(x) == 4 && stringlen(y) == 4){
for (i = 0; i < 4; i++) {
if (isalpha(*x) && isalpha(*y)) {
letter1 = tolower(*x);
letter2 = tolower(*y);
if (letter1 != letter2) {
count++;
}
x++;
y++;
}
else {
//point x and y back to position x[0][0]
return -1;
}
}
}
else{
return -1;
}
return count;
}
int stringlen(char *x){
int count = 0;
while (*x != '\0') {
count++;
x++;
}
return count;
}
int change(char *x, char *y){
int i;
for (i = 0; i < 4; i++) {
if (x[i] != y[i]) {
x[i] = y[i];
printf("%s\n", x);
}
}
}
void tests(void){
/*edit_dist testing*/
assert(edit_dist("chap", "ball") == 4);
assert(edit_dist("chap", "chat") == 1);
assert(edit_dist("shoe", "shop") == 1);
assert(edit_dist("sho^", "shop") == -1);
assert(edit_dist("shoes", "shoes") == -1);
assert(edit_dist("shoe", "shoe") == 0);
/*stringlen testing*/
assert(stringlen("shoe") == 4);
assert(stringlen("") == 0);
assert(stringlen(" ") == 2);
assert(stringlen("shoes") == 5);
assert(stringlen("ghfdjsgd") == 8);
}
|
C
|
//
// Created by shadowiterator on 18-10-27.
//
#include "global.h"
#include "msghandler.h"
#include "server.h"
#include "sistring.h"
typedef struct
{
int filefd;
ConnectArg* cargs;
}FileArgs;
int countParam(char* cmd)
{
int p = 0;
while(cmd[p] && cmd[p] != ' ')
++p;
if(cmd[p] && cmd[p] == ' ')
++p;
if(!cmd[p])
return 0;
else
return 1;
}
int file_exists(char* path)
{
return access(path, F_OK) == 0;
}
int getIP(char* cmd, int len, unsigned int* ip)
{
int data[6];
int p = 0;
int t;
int port;
char tt;
for(int i = 0; i < 6; ++i)
{
for(t = 0; p < len && (tt = cmd[p]) != ','; ++p)
{
if(tt < '0' || tt > '9')
return -1;
t = t * 10 + tt - '0';
}
if(t & 0xffffff00)
return -1;
data[i] = t;
++p;
}
if(p <= len)
return -1;
port = (data[4] << 8 ) + data[5];
if((port) & 0xffff0000)
return -1;
*ip = (unsigned int)(data[3] << 24) + (data[2] << 16) + (data[1] << 8) + data[0];
return port;
}
int getParam(char* cmd, int k)
{
int p = 0;
for(int i = 0; i < k; ++i)
{
while(cmd[p] && cmd[p] != ' ')
++p;
if(cmd[p] && cmd[p] == ' ')
++p;
if(!cmd[p])
return -1;
}
// *len = p;
// while(cmd[p] && cmd[p] != ' ') ++p;
// p -= (*len);
// (*len)^=p^=(*len)^=p;
return p;
}
int checkParamterN(char* cmd, int n)
{
return countParam(cmd) == n;
}
void decodePathName(char *pathname, int n)
{
for(int i = 0; i < n; ++i)
if(pathname[i] == 0x00)
pathname[i] = 0x0A;
}
int getFullPathName(ConnectArg* args, char* ecdpathName, char* buffer)
{
if(ecdpathName[0] == '/')
sprintf(buffer, "%s%s", SERVERDIR, ecdpathName);
else
sprintf(buffer, "%s%s/%s", SERVERDIR, args->dir, ecdpathName);
return 0;
}
int getUserPathName(ConnectArg* args, char* ecdpathName, char* buffer)
{
if(ecdpathName[0] == '/')
sprintf(buffer, "%s", ecdpathName);
else
sprintf(buffer, "%s/%s", args->dir, ecdpathName);
return 0;
}
//int getNextDir(char* path, int p, int n)
//{
// for(; p < n && path[p] !='/'; ++p);
// return p + 1;
//}
//
//int getPrevDir(char* path, int p, int n)
//{
// for(; p >= 0 && path[p] != '/'; --p);
// for(--p; p >= 0 && path[p] != '/'; --p);
// ++p;
// return p;
//}
int getDirEd(char* path, int p, int n)
{
while(p < n && path[p] == '/') ++p;
for(; p < n && path[p] != '/'; ++p);
// if(p != n)
// --p;
return p;
}
int getDirSt(char* path, int p, int n)
{
while(p >=0 && path[p] == '/') --p;
for(; p >= 0 && path[p] != '/'; --p);
return p;
}
int reducePath(char* path, int n)
{
int p = 0;
int q = 0;
int eq;
if(path[q] != '/')
return -1;
if(n == 1)
{
path[0] = '\0';
return 0;
}
while(q < n)
{
eq = getDirEd(path, q, n);
if(sistrcmp("/..", &path[q], 0, 0, MAX(eq - q, 3)) == 0)
{
if(p == 0)
return -1;
else
{
p = getDirSt(path, p, n);
}
}
else if(sistrcmp("/.", &path[q], 0, 0, MAX(eq - q, 2)) == 0)
{
// do nothing
}
else
{
for(;q < eq;)
{
path[p++] = path[q++];
}
}
q = eq;
}
path[p] = '\0';
return 0;
}
void wait_for_connection(ConnectArg* args)
{
// printf("wait for connect\n");
int datafd;
while(1)
{
if(args->psvlistenfd < 0)
break;
if ((datafd = accept(args->psvlistenfd, NULL, NULL)) == -1)
{
// printf("Error accept(): %s(%d)\n", strerror(errno), errno);
if(errno == EAGAIN || errno == EWOULDBLOCK)
continue;
// sendFmtMsg(&args->connfd, args, "accept failed", 0, 530);
// puts("accept failed");
printf("accept failed %d\n", args->connfd);
return ;
}
else
break;
}
if(args->psvlistenfd < 0)
{
sendFmtMsg(&args->connfd, args, "listenfd closed", 0, 530);
if(args->psvlistenfd != -1)
{
close(-args->psvlistenfd);
puts("close listen");
}
return ;
}
printf("data connection from %d\n", datafd);
args->datafd = datafd;
// sendFmtMsg(&args->connfd, args, "data connection established", 0, 230);
}
int send_file(FileArgs* cargs)
{
#define RETRFBUFFSIZE 1024
int fd = cargs->filefd;
ConnectArg* args = cargs->cargs;
char *fbuffer = malloc(RETRFBUFFSIZE * sizeof(char));
int filelen;
int msgRet = 1;
while((filelen = read(fd, fbuffer, RETRFBUFFSIZE)))
{
usleep(100000);
// sleep(1);
if(filelen < 0)
{
sendFmtMsg(&args->connfd, args, "unable to open file", 0, 551);
goto send_file_end;
}
else
{
msgRet = sendMsg(&args->datafd, args, fbuffer, filelen);
if(msgRet < 0)
{
sendFmtMsg(&args->connfd, args, "connection broken", 0, 426);
goto send_file_end;
}
}
}
sendFmtMsg(&args->connfd, args, "transfer success", 0, 226);
send_file_end:
cargs->cargs->sp = 0;
free(fbuffer);
free(cargs);
close(fd);
if(args->datafd != -1)
{
close(args->datafd > 0? args->datafd : -args->datafd);
puts("close datafd");
args->datafd = -1;
}
if(args->psvlistenfd != -1)
{
close(args->psvlistenfd > 0? args->psvlistenfd : -args->psvlistenfd);
puts("close listen");
args->psvlistenfd = -1;
}
return 0;
}
int recv_file(FileArgs* cargs)
{
#define STORFBUFFSIZE 1024
char* buffer = malloc(STORFBUFFSIZE * sizeof(char));
int fd = cargs->filefd;
ConnectArg* args = cargs->cargs;
int flen = 0;
while((flen = readMsg(&args->datafd, args, buffer, STORFBUFFSIZE)))
{
if(flen < 0)
{
sendFmtMsg(&args->connfd, args, "connection broken", 0, 426);
goto recv_file_end;
}
if(write(fd, buffer, flen) < 0)
{
printf("Error: %s(%d)\n", strerror(errno), errno);
sendFmtMsg(&args->connfd, args, "failed to write file", 0, 452);
goto recv_file_end;
}
}
sendFmtMsg(&args->connfd, args, "STOR success", 0, 226);
recv_file_end:
close(fd);
free(buffer);
free(cargs);
if(args->datafd != -1)
{
close(args->datafd > 0? args->datafd : -args->datafd);
puts("close datafd");
args->datafd = -1;
}
if(args->psvlistenfd != -1)
{
close(args->psvlistenfd > 0? args->psvlistenfd : -args->psvlistenfd);
puts("close listen");
args->psvlistenfd = -1;
}
return 0;
}
int user_handler(ConnectArg* args, char* cmd, int cmdn)
{
int len = 0;
int p;
char* msg;
int code;
if(countParam(cmd) == 0)
{
msg = " expected exact 1 parameter";
code = 530;
p = -1;
}
else
{
p = getParam(cmd, 1);
len = cmdn - p;
printf("user len = %d cmdn = %d\n", len, cmdn);
if(sistrcmp("anonymous", cmd, 0, p, MAX(len, strlen("anonymous"))) != 0)
{
msg = " only support anonymous";
code = 530;
p = -1;
}
}
if(p == -1)
sendFmtMsg(&args->connfd, args, msg, 0, code);
else
{
set_cmd_status_all(args, CMD_DISABLE);
set_cmd_status(args, PASS, CMD_ENABLE);
set_cmd_status(args, QUIT, CMD_ENABLE);
sendFmtMsg(&args->connfd, args, " password?", 0, 331);
}
return 0;
}
int pass_handler(ConnectArg* args, char* cmd, int cmdn)
{
// int len = 0;
// int p;
// char* msg;
// int code;
if(countParam(cmd) == 0)
{
// msg = "expected exact 1 parameter";
// code = 530;
// p = -1;
sendFmtMsg(&args->connfd, args, "expected exact 1 parameter", 0, 530);
return 0;
}
else
{
// p = getParam(cmd, 1, &len);
// valid!
set_cmd_status_all(args, CMD_ENABLE);
set_cmd_status(args, USER, CMD_DISABLE);
set_cmd_status(args, PASS, CMD_DISABLE);
// set_cmd_status(args, LIST, CMD_DISABLE);
// set_cmd_status(args, STOR, CMD_DISABLE);
// set_cmd_status(args, RETR, CMD_DISABLE);
sendFmtMsg(&args->connfd, args, "login!", 0, 230);
// sendFmtMsg(&args->connfd, args, " welcome", 0, 230);
}
return 0;
}
int list_handler(ConnectArg* args, char* cmd, int cmdn)
{
decodePathName(cmd, cmdn);
if(args->datafd < 0)
{
sendFmtMsg(&args->connfd, args, "no connection established", 0, 425);
return 0;
}
int p;
char dpath[1024];
if(countParam(cmd) == 1)
{
p = getParam(cmd, 1);
getFullPathName(args, &cmd[p], dpath);
}
else
getFullPathName(args, "", dpath);
// int p = countParam(cmd);
// if(p > 1)
// {
// sendFmtMsg(&args->connfd, args, " too many args", 0, 530);
// return 0;
// }
char si_cmd[2048];
// sprintf(si_cmd, "cd %s", dpath);
// system(si_cmd);
sprintf(si_cmd, "ls -a -l %s", dpath);
FILE *fpread = popen(si_cmd, "r");
char res[2048];
int si_len;
// char tt = fgetc(fpread);
// fscanf(fpread, "%[^\n]%c", res);
while(fgetc(fpread) != '\n');
// tt = fgetc(fpread);
while((si_len = fread(res, 1, 2047, fpread))>0)
{
res[si_len] = '\0';
// printf("%s", res);
if(sendMsg(&args->datafd, args, res, si_len) < 0)
break;
// printf("%s", res);
}
//
// DIR *dir;
// struct dirent *ptr;
// struct stat finfo;
// char path[1024];
// char msg[1024];
// dir = opendir(dpath);
// ptr = readdir(dir);
// while(ptr)
// {
// sprintf(path, "%s%s", dpath, ptr->d_name);
// stat(path, &finfo);
// sprintf(msg, " %s %d", ptr->d_name, S_ISDIR(finfo.st_mode));
// sendFmtMsg(&args->datafd, args, msg, 0, 230);
// ptr = readdir(dir);
// }
if(args->datafd != -1)
{
close(args->datafd > 0? args->datafd : -args->datafd);
puts("close datafd");
args->datafd = -1;
}
if(args->psvlistenfd != -1)
{
close(args->psvlistenfd > 0? args->psvlistenfd : -args->psvlistenfd);
puts("close listen");
args->psvlistenfd = -1;
}
return 0;
}
int syst_handler(ConnectArg* args, char* cmd, int cmdn)
{
sendFmtMsg(&args->connfd, args, "UNIX Type: L8", 0, 215);
return 0;
}
int type_handler(ConnectArg* args, char* cmd, int cmdn)
{
if(countParam(cmd) != 1)
{
sendFmtMsg(&args->connfd, args, " expected 1 parameter", 0, 530);
return 0;
}
int p;
// int len;
p = getParam(cmd, 1);
// len = cmdn - p;
if(sistrcmp("I", cmd, 0, p, 1) != 0)
{
sendFmtMsg(&args->connfd, args, "expected I as parameter", 0, 530);
return 0;
}
else
{
sendFmtMsg(&args->connfd, args, "Type set to I.", 0, 200);
return 0;
}
}
int port_handler(ConnectArg* args, char* cmd, int cmdn)
{
if(countParam(cmd)!=1)
{
sendFmtMsg(&args->connfd, args, " expected 1 parameter", 0, 530);
return 0;
}
int p;
int len;
p = getParam(cmd, 1);
len = cmdn - p;
unsigned int ip;
int port;
port = getIP(&cmd[p], len, &ip);
if(port == -1)
{
sendFmtMsg(&args->connfd, args, " invalid ip address", 0, 530);
return 0;
}
//-----------------------------------------------
//--------set socket-----------------------------
if(args->datafd != -1)
{
close(args->datafd > 0? args->datafd : -args->datafd);
puts("close datafd");
args->datafd = -1;
}
if(args->psvlistenfd != -1)
{
close(args->psvlistenfd > 0? args->psvlistenfd : -args->psvlistenfd);
puts("close listen");
args->psvlistenfd = -1;
}
int sockfd;
struct sockaddr_in addr;
//创建socket
if ((sockfd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) == -1) {
printf("Error socket(): %s(%d)\n", strerror(errno), errno);
return 0;
}
printf("Xdata connection: %d\n", sockfd);
//设置目标主机的ip和port
memset(&addr, 0, sizeof(addr));
addr.sin_family = AF_INET;
addr.sin_port = htons(port);
memcpy(&addr.sin_addr, &ip, sizeof(unsigned int));
// addr.sin_addr = ip;
// if (inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr) <= 0) { //转换ip地址:点分十进制-->二进制
// printf("Error inet_pton(): %s(%d)\n", strerror(errno), errno);
// return 1;
// }
int i = 3;
//连接上目标主机(将socket和目标主机连接)-- 阻塞函数
for (i = 3; i && (connect(sockfd, (struct sockaddr*)&addr, sizeof(addr)) < 0); --i) {
sleep(1);
}
if(!i)
{
printf("Error connect(): %s(%d)\n", strerror(errno), errno);
sendFmtMsg(&args->connfd, args, " connect fail", 0, 530);
return 0;
}
puts("socket connection established");
args->datafd = sockfd;
sendFmtMsg(&args->connfd, args, "data connection established", 0, 200);
printf("data connection: %d\n", sockfd);
set_cmd_status(args, LIST, CMD_ENABLE);
set_cmd_status(args, STOR, CMD_ENABLE);
set_cmd_status(args, RETR, CMD_ENABLE);
return 0;
}
int pasv_handler(ConnectArg* args, char* cmd, int cmdn)
{
int listenfd;
struct sockaddr_in addr;
if(args->datafd != -1)
{
close(args->datafd > 0? args->datafd : -args->datafd);
puts("close datafd");
args->datafd = -1;
}
if(args->psvlistenfd != -1)
{
close(args->psvlistenfd > 0? args->psvlistenfd : -args->psvlistenfd);
puts("close listen");
args->psvlistenfd = -1;
}
//创建socket
if ((listenfd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) == -1) {
printf("Error socket(): %s(%d)\n", strerror(errno), errno);
return 1;
}
int rport;
int k;
for(k = 20000; k; --k)
{
rport = (rand() % (45536)) + 20000;
//设置本机的ip和port
memset(&addr, 0, sizeof(addr));
addr.sin_family = AF_INET;
addr.sin_port = htons(rport);
addr.sin_addr.s_addr = htonl(INADDR_ANY); //监听"0.0.0.0"
//将本机的ip和port与socket绑定
if (bind(listenfd, (struct sockaddr*)&addr, sizeof(addr)) == -1) {
printf("Error bind(): %s(%d)\n", strerror(errno), errno);
// return 1;
continue;
}
else
break;
}
if(!k)
{
sendFmtMsg(&args->connfd, args, "unable to find a port", 0, 530);
return 0;
}
// printf("port = %d\n", rport);
//开始监听socket
if (listen(listenfd, 1) == -1) {
printf("Error listen(): %s(%d)\n", strerror(errno), errno);
// return 1;
sendFmtMsg(&args->connfd, args, "listen failed", 0, 530);
return 0;
}
// set non blocking
int flags = fcntl(listenfd, F_GETFL, 0);
fcntl(listenfd, F_SETFL, flags | O_NONBLOCK);
args->psvlistenfd = listenfd;
pthread_t pid;
int pret = pthread_create(&pid, NULL, (void*)wait_for_connection, (void*)args);
if(pret)
{
sendFmtMsg(&args->connfd, args, "create thread failed", 0, 530);
return 0;
}
pthread_detach(pid);
char retMsg[100];
sprintf(retMsg, "=%s,%d,%d", "127,0,0,1", (rport >> 8) & 0xff, rport & 0xff);
sendFmtMsg(&args->connfd, args, retMsg, 0, 227);
return 0;
}
int rest_handler(ConnectArg* args, char* cmd, int cmdn)
{
if(countParam(cmd) != 1)
{
sendFmtMsg(&args->connfd, args, "no path specified", 0, 530);
return 0;
}
int p = getParam(cmd, 1);
// int plen = cmdn - p;
char* ptr = NULL;
int nsp = (int)(strtol(&cmd[p], &ptr, 10));
if (errno != 0 && nsp == 0)
{
sendFmtMsg(&args->connfd, args, "invalid parameter", 0, 550);
return 0;
}
args->sp = nsp;
sendFmtMsg(&args->connfd, args, "successfully set starting point", 0, 350);
return 0;
}
int retr_handler(ConnectArg* args, char* cmd, int cmdn)
{
int p;
decodePathName(cmd, cmdn);
sendFmtMsg(&args->connfd, args, "get RETR request", 0, 150);
char path[1024];
if(countParam(cmd) != 1)
{
sendFmtMsg(&args->connfd, args, "no path specified", 0, 530);
return 0;
}
if(args->datafd < 0)
{
sendFmtMsg(&args->connfd, args, "no connection established", 0, 425);
return 0;
}
p = getParam(cmd, 1);
// len = cmdn - p;
// decodePathName(&cmd[p], len);
// sprintf(path, "%s%s%s", SERVERDIR, args->dir, &cmd[p]);
getFullPathName(args, &cmd[p], path);
printf("trying to open %s with sp = %d\n", path, args->sp);
FileArgs* cargs = malloc(sizeof(FileArgs));
cargs->filefd = open(path, O_RDONLY);
cargs->cargs = args;
if(lseek(cargs->filefd, args->sp, SEEK_SET) < 0 )
{
printf("Error: %s(%d)\n", strerror(errno), errno);
sendFmtMsg(&args->connfd, args, "filed in lseek, try to set starting point first", 0, 452);
lseek(cargs->filefd, 0, SEEK_END);
}
pthread_t pid;
int pret = pthread_create(&pid, NULL, (void*)send_file, (void*)cargs);
if(pret)
{
sendFmtMsg(&args->connfd, args, "create thread failed", 0, 530);
return 0;
}
pthread_detach(pid);
return 0;
}
int cwd_handler(ConnectArg* args, char* cmd, int cmdn)
{
decodePathName(cmd, cmdn);
if(countParam(cmd) != 1)
{
sendFmtMsg(&args->connfd, args, "a parameter is required", 0, 550);
return 0;
}
int p = getParam(cmd, 1);
// int len = cmdn - p;
char pathName[1040];
char fullPathName[1040];
getUserPathName(args, &cmd[p], pathName);
getFullPathName(args, &cmd[p], fullPathName);
if(reducePath(pathName, strlen(pathName)) < 0)
{
sendFmtMsg(&args->connfd, args, "invalid directory", 0, 550);
return 0;
}
DIR* dir = opendir(fullPathName);
if(dir == NULL)
{
sendFmtMsg(&args->connfd, args, "no such directory", 0, 550);
return 0;
}
strcpy(args->dir, pathName);
sendFmtMsg(&args->connfd, args, "Okey", 0, 250);
return 0;
}
int pwd_handler(ConnectArg* args, char* cmd, int cmdn)
{
char msg[1040];
sprintf(msg, "\"%s\"", args->dir);
sendFmtMsg(&args->connfd, args, msg, 0, 257);
return 0;
}
int quit_handler(ConnectArg* args, char* cmd, int cmdn)
{
sendFmtMsg(&args->connfd, args, "Bye", 0, 221);
close(args->connfd);
args->connfd = -1;
return 0;
}
int stor_handler(ConnectArg* args, char* cmd, int cmdn)
{
decodePathName(cmd, cmdn);
sendFmtMsg(&args->connfd, args, "get STOR request", 0, 150);
if(countParam(cmd) != 1)
{
sendFmtMsg(&args->connfd, args, "a parameter expected", 0, 550);
return 0;
}
if(args->datafd < 0)
{
sendFmtMsg(&args->connfd, args, "no connection established", 0, 425);
return 0;
}
int p = getParam(cmd, 1);
char path[1040];
getFullPathName(args, &cmd[p], path);
printf("stor : %s\n", path);
FileArgs* cargs = malloc(sizeof(FileArgs));
cargs->filefd = open(path, O_WRONLY | O_CREAT);
cargs->cargs = args;
pthread_t pid;
int pret = pthread_create(&pid, NULL, (void*)recv_file, (void*)cargs);
if(pret)
{
sendFmtMsg(&args->connfd, args, "create thread failed", 0, 530);
return 0;
}
pthread_detach(pid);
return 0;
}
int appe_handler(ConnectArg* args, char* cmd, int cmdn)
{
decodePathName(cmd, cmdn);
sendFmtMsg(&args->connfd, args, "get APPE request", 0, 150);
if(countParam(cmd) != 1)
{
sendFmtMsg(&args->connfd, args, "a parameter expected", 0, 550);
return 0;
}
if(args->datafd < 0)
{
sendFmtMsg(&args->connfd, args, "no connection established", 0, 425);
return 0;
}
int p = getParam(cmd, 1);
char path[1040];
getFullPathName(args, &cmd[p], path);
printf("stor : %s\n", path);
FileArgs* cargs = malloc(sizeof(FileArgs));
cargs->filefd = open(path, O_WRONLY | O_CREAT | O_APPEND);
cargs->cargs = args;
pthread_t pid;
int pret = pthread_create(&pid, NULL, (void*)recv_file, (void*)cargs);
if(pret)
{
sendFmtMsg(&args->connfd, args, "create thread failed", 0, 530);
return 0;
}
pthread_detach(pid);
return 0;
}
int mkd_handler(ConnectArg* args, char* cmd ,int cmdn)
{
decodePathName(cmd, cmdn);
if(countParam(cmd) != 1)
{
sendFmtMsg(&args->connfd, args, "a parameter is expected", 0, 530);
return 0;
}
int p = getParam(cmd, 1);
char pathname[1040];
getFullPathName(args, &cmd[p], pathname);
int tres = mkdir(pathname, S_IRWXU);
if(tres < 0)
{
sendFmtMsg(&args->connfd, args, "create dir failed", 0, 550);
return 0;
}
char msg[1080];
sprintf(msg, "\"%s\"", args->dir);
sendFmtMsg(&args->connfd, args, msg, 0, 250);
return 0;
/*
* /a/b
* MKD a/d/e
* /a/b
*/
}
int rmd_handler(ConnectArg* args, char* cmd, int cmdn)
{
decodePathName(cmd, cmdn);
if(countParam(cmd) != 1)
{
sendFmtMsg(&args->connfd, args, "a parameter is expected", 0, 530);
return 0;
}
int p = getParam(cmd, 1);
char pathname[1040];
getFullPathName(args, &cmd[p], pathname);
int tres = rmdir(pathname);
if(tres < 0)
{
sendFmtMsg(&args->connfd, args, "remove dir failed", 0, 550);
return 0;
}
// char msg[1080];
// sprintf(msg, "\"%s\"", args->dir);
sendFmtMsg(&args->connfd, args, "rm okey", 0, 250);
return 0;
}
int rnfr_handler(ConnectArg* args, char* cmd, int cmdn)
{
decodePathName(cmd, cmdn);
if(countParam(cmd) != 1)
{
sendFmtMsg(&args->connfd, args, "a parameter is required", 0, 530);
return 0;
}
char pathName[1080];
int p = getParam(cmd, 1);
getFullPathName(args, &cmd[p], pathName);
if(!file_exists(pathName))
{
sendFmtMsg(&args->connfd, args, "file do not exist", 0, 450);
return 0;
}
sendFmtMsg(&args->connfd, args, "RNFR OK", 0, 350);
int nlen = readMsg(&args->connfd, args, args->readbuffer, BUFFSIZE);
if(nlen < 0)
return 0;
int hid = seek_handler(args, args->readbuffer);
if(hid != RNTO)
processMsg(args, args->readbuffer, nlen);
else
rnto_handler_accept(args, pathName, args->readbuffer, nlen);
return 0;
}
int rnto_handler_accept(ConnectArg* args, char* oldpath, char* cmd, int cmdn)
{
decodePathName(cmd, cmdn);
if(countParam(cmd) != 1)
{
sendFmtMsg(&args->connfd, args, "a parameter is required", 0, 550);
return 0;
}
char newpath[1080];
int p = getParam(cmd, 1);
getFullPathName(args, &cmd[p], newpath);
int tret = rename(oldpath, newpath);
if(tret < 0)
{
sendFmtMsg(&args->connfd, args, "rename failed", 0, 553);
return 0;
}
sendFmtMsg(&args->connfd, args, "rename ok", 0, 250);
return 0;
}
int rnto_handler_refuse(ConnectArg* args, char* cmd, int cmdn)
{
sendFmtMsg(&args->connfd, args, "RNTO must comes after RNFR", 0, 503);
return 0;
}
|
C
|
/*
* intToStr.c
*
* Created on: 2018311
* Author: xubov
*/
int intlen(int m);
char itoa(int n);
// int תΪӦַ
int intToStr(char a[],int m){
int length = intlen(m);
int i;
for(i = 1; i <= length ; i++){
a[length - i] = itoa(m % 10);
m /= 10;
}
return length;
}
// αij
int intlen(int m){
int length = 0;
while (m != 0) {
length++;
m /= 10;
}
return length;
}
// һ0 - 9 תΪӦ ַ'0' - '9'
char itoa(int n){
if(n >= 0 && n <= 9)
{
return (n + '0');
}else
{
return -1;
}
}
|
C
|
//
// Created by djvas on 16/11/2017.
//
#include "stack_int_array.h"
void testClient_StackIntArray() {
struct StackIntArray stk;
init_StackIntArray(&stk, 6);
push_StackIntArray(&stk, 4);
push_StackIntArray(&stk, 8);
push_StackIntArray(&stk, 16);
pop_StackIntArray(&stk);
print_StackIntArray(&stk);
}
void init_StackIntArray(struct StackIntArray *st, int capacity) {
st->s = (int *) malloc(capacity * sizeof(int));
st->capacity = capacity;
st->N = 0;
}
void push_StackIntArray(struct StackIntArray *st, int v) {
st->s[st->N] = v;
st->N++;
}
int pop_StackIntArray(struct StackIntArray *st) {
int item;
st->N--;
item = st->s[st->N];
return item;
}
void print_StackIntArray(struct StackIntArray *st) {
int i;
printf("Stack: ");
for (i = 0; i < st->N; i++) {
printf("%d ", st->s[i]);
}
printf("\n");
}
|
C
|
#include "binary_trees.h"
#include <limits.h>
/**
* count_nodes - counts the number of nodes inside the tree.
* @tree: binary tree node.
* Return: number of nodes in the tree.
*/
int count_nodes(const binary_tree_t *tree)
{
if (!tree)
return (0);
return (1 + count_nodes(tree->left) + count_nodes(tree->right));
}
/**
* is_complete - function that checks if tree is complete.
* @tree: binary tree node.
* @index: index of the tree.
* @n: number of nodes.
* Return: 1 on success 0 on failure.
*/
int is_complete(const binary_tree_t *tree, int index, int n)
{
if (!tree)
return (1);
if (index >= n)
return (0);
return (is_complete(tree->left, (2 * index) + 1, n) &&
is_complete(tree->right, (2 * index) + 2, n));
}
/**
* binary_tree_is_complete - checks if binary tree is complete.
* @tree: binary tree node.
* Return: 1 on success 0 on failure.
*/
int binary_tree_is_complete(const binary_tree_t *tree)
{
if (!tree)
return (0);
return (is_complete(tree, 0, count_nodes(tree)));
}
/**
* is_heap - check if tree is max heap
* @tree: binary tree
* @min: min value
* @max: max value
* Return: 1 if it is a bst otherwise 0
*/
int is_heap(const b_t_t *tree, int min, int max)
{
if (!tree)
return (1);
if (tree->n > max)
return (0);
return (is_heap(tree->left, min, tree->n) &&
is_heap(tree->right, tree->n, max));
}
/**
* binary_tree_is_heap - is binary tree a max heap
* @tree: binary tree
* Return: 1 on success 0 on failure
*/
int binary_tree_is_heap(const binary_tree_t *tree)
{
if (!tree)
return (0);
if (!binary_tree_is_complete(tree))
return (0);
return (is_heap(tree, INT_MIN, INT_MAX));
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_abs.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: jboissy <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2017/11/08 00:01:15 by jboissy #+# #+# */
/* Updated: 2018/05/04 19:13:33 by jboissy ### ########.fr */
/* */
/* ************************************************************************** */
#include "template.h"
#define MUSIC_TIME 3500
#define MUSIC_DELAY 500
static int check_skip(void)
{
SDL_Event event;
if (SDL_PollEvent(&event) == 1)
{
if (event.type == SDL_KEYDOWN && event.key.keysym.sym == SDLK_SPACE)
{
Mix_HaltChannel(1);
return (1);
}
}
SDL_PumpEvents();
SDL_FlushEvent(SDL_KEYDOWN);
SDL_FlushEvent(SDL_MOUSEMOTION);
return (0);
}
static int play_channel(int channel, Mix_Chunk *intro)
{
int i;
i = 0;
Mix_PlayChannel(channel, intro, -1);
if (Mix_Playing(channel) == 1)
{
while (i < MUSIC_TIME + MUSIC_DELAY)
{
if (i == MUSIC_TIME)
Mix_FadeOutChannel(channel, MUSIC_DELAY);
if (check_skip() == 1)
return (4);
i++;
SDL_Delay(1);
}
}
return (1);
}
int play_sound(int channel, char *path)
{
Mix_Chunk *intro;
int i;
intro = Mix_LoadWAV(path);
if (intro != NULL)
return (play_channel(channel, intro));
i = 0;
while (i < MUSIC_DELAY)
{
if (check_skip() == 1)
return (4);
i++;
SDL_Delay(1);
}
return (1);
}
|
C
|
/*File name: token.h ------------------------------------------------*
|Project: Implementace překladače imperativního jazyka IFJ20 |
|Team: 124, varianta II |
|Authors: Ondřej Sloup (xsloup02) |
| Viktor Rucký (xrucky01) |
| |
| _ _ _ __ __ _ _ |
| | | (_) | | /_/ /_/ | | | | |
| | | _ __| | ___ _ _ __ ___ _| |_ __ _| |__ _ _ |
| | | | |/ _` |/ _ \ | | | | \ \ / / | | | __/ _` | '_ \| | | | |
| | |____| | (_| | __/ | |_| | \ V /| |_| | || (_| | | | | |_| | |
| |______|_|\__,_|\___| \__,_| \_/ \__, |\__\__,_|_| |_|\__,_| |
| __/ | |
| |___/ |
*-------------------------------------------------------------------*/
#ifndef TOKEN_H
#define TOKEN_H
#include <stdint.h>
#include "str.h"
#include "data_type.h"
/**
* @enum ScannerState
* @brief Describes all tokens which scanner can send.
*
*/
typedef enum {
/* Definition of Tokens */
/* Strings */
TokenStringLiteral, /** Read string literal (value is in the attribute 's') */
/* Conditions */
TokenNotEqual, /** Read '!=' */
TokenIsEqual, /** Read '=' */
TokenIsGreaterThan, /** Read '>' */
TokenIsGreaterEqual, /** Read '>=' */
TokenIsLessThan, /** Read '<' */
TokenIsLessEqual, /** Read '>=' */
/* Feature UNARY */
TokenAddEqual, /** Read '+=' */
TokenSubtractEqual, /** Read '-=' */
TokenMultiplyEqual, /** Read '*=' */
TokenDivideEqual, /** Read '/=' */
/* Operation */
TokenAssignment, /** Read '=' */
TokenVarDefine, /** Read ':=' */
TokenAdd, /** Read '+' */
TokenSubtract, /** Read '-' */
TokenMultiply, /** Read '*' */
TokenDivide, /** Read '/' */
/* Numbers */
TokenWholeNbr, /** Read whole number (value is in the attribute 'i') */
TokenDecimalNbr, /** Read decimal number (value is in the attribute 'd') */
/* Symbols */
TokenLeftCurlyBracket, /** Read '{' */
TokenRightCurlyBracket, /** Read '}' */
TokenLeftBracket, /** Read '(' */
TokenRightBracket, /** Read ')' */
TokenComma, /** Read ',' */
TokenSemicolon, /** Read ';' */
TokenIdentifier, /** Read string identifier (value is in the attribute 's') */
TokenEOL, /** Read End of Line – '\n' */
TokenEOF, /** Read EOL – End of file */
/* Keywords */
TokenFor, /** Read keyword 'for' */
TokenReturn, /** Read keyword 'return' */
TokenElse, /** Read keyword 'else' */
TokenFunc, /** Read keyword 'func' */
TokenIf, /** Read keyword 'if' */
TokenPackage, /** Read keyword 'package' */
TokenDataType, /** Read keyword 'float64', 'string' or 'int'. The exact datatype is described in attribute 't' */
TokenUndefined /** Undefined token – Error state */
} _TokenType;
/** @struct Attribute
* @brief This structure is used to identify which value has the token.
*/
typedef union {
int64_t i; /** Value of token if it is 'TokenWholeNbr' */
double d; /** Value of token if it is 'TokenDecimalNbr' */
string s; /** Value of token if it is 'TokenStringLiteral' or 'TokenIdentifier' */
DataType t; /** Value of token if it is 'TokenDataType' */
} Attribute;
/** @struct Token
* @brief This structure describes the token. It consists of the token type and optional attribute.
*/
typedef struct {
_TokenType type; /** Identify token type */
Attribute attribute; /** Attribute for token value */
} Token;
#endif
|
C
|
#include<stdio.h>
#include<stdlib.h>
struct node{
int data;
struct node* next;
}*temp;
void reverse(struct node**head_ref){
printf("\n reverse function called");
struct node *next=NULL,*prev=NULL,*curr=*head_ref;
printf("%d",curr->data);
int i=0;
while(curr!=NULL){
printf("lulz");
next=curr->next;
curr->next=prev;
prev=curr;
curr=next;
}
*head_ref=prev;
printf("%d",prev->data);
printf("\n reverse function ended");
}
void printx(struct node** head_ref){
printf("\n printing");
struct node *temp;
temp=*head_ref;
while(temp!=NULL){
printf(" %d ",temp->data);
temp=temp->next;
}
}
void make(struct node **head_ref,int data){
struct node* newnode;
newnode=(struct node*)malloc(sizeof(struct node));
newnode->data=data;
newnode->next=(*head_ref);
*head_ref=newnode;
}
void main(){
int n;
struct node *head = NULL;
scanf("%d",&n);
int i,data;
for(i=0;i<n;i++){
scanf("%d",&data);
make(&head,data);
}
printx(&head);
reverse(&head);
printx(&head);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <arpa/inet.h>
#include <string.h>
#include <pthread.h>
#include <string.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <dirent.h>
#define PATH_MEDIA "/home/jiesse/upload/MediaFile"
#define PATH_PIC "/home/jiesse/upload/PicFile"
#define PATH_TEXT "/home/jiesse/upload/TextFile"
#define PATH_OTHER "/home/jiesse/upload/OtherFile"
int main(int argc, char* argv[])
{
char buf[100] = {0};
int ret;
//directory
DIR *dp;
struct dirent *filename;
printf("Content-Type: text/html\n\n");
printf("\
<meta http-equiv=\"Content-Type\" content=\"text/html;charset=utf-8\">\
\n") ;
printf("\
<form action=\"../cgi-bin/delete\" method=\"post\">\
\n") ;
ret = fread(buf, 1, sizeof(buf), stdin);
if(ret == 9)
{
dp = opendir(PATH_MEDIA);
printf("\
<font color=\"0xff0000\"><font size=5> MediaFile </font></font>\
\n") ;
printf("<br>\n");
while(filename=readdir(dp))
{
if(filename->d_type == DT_DIR ) //DT_DIR == 4
{
continue;
}
printf("\
<input type=\"checkbox\" value=\"%s\" name=\"check\" />\
\n",filename->d_name) ;
printf("%s\n",filename->d_name) ;
printf("<br>\n");
}
closedir(dp);
printf("\
<input type=\"submit\" value=\"delete\" name=\"log1\" style=\" font-size: 50px; background: #CCCCFF\">\
\n") ;
}
if(ret == 11)
{
dp = opendir(PATH_PIC);
printf("\
<font color=\"0xff0000\"><font size=5> PicFile </font></font>\
\n") ;
printf("<br>\n");
while(filename=readdir(dp))
{
if(filename->d_type == DT_DIR ) //DT_DIR == 4
{
continue;
}
printf("\
<input type=\"checkbox\" value=\"%s\" name=\"check\" />\
\n",filename->d_name) ;
printf("%s\n",filename->d_name) ;
printf("<br>\n");
}
closedir(dp);
printf("\
<input type=\"submit\" value=\"delete\" name=\"log2\" style=\" font-size: 50px; background: #CCCCFF\">\
\n") ;
}
if(ret == 8)
{
dp = opendir(PATH_TEXT);
printf("\
<font color=\"0xff0000\"><font size=5> TextFile </font></font>\
\n") ;
printf("<br>\n");
while(filename=readdir(dp))
{
if(filename->d_type == DT_DIR ) //DT_DIR == 4
{
continue;
}
printf("\
<input type=\"checkbox\" value=\"%s\" name=\"check\" />\
\n",filename->d_name) ;
printf("%s\n",filename->d_name) ;
printf("<br>\n");
}
closedir(dp);
printf("\
<input type=\"submit\" value=\"delete\" name=\"log3\" style=\" font-size: 50px; background: #CCCCFF\">\
\n") ;
}
if(ret == 10)
{
dp = opendir(PATH_OTHER);
printf("\
<font color=\"0xff0000\"><font size=5> OtherFile </font></font>\
\n") ;
printf("<br>\n");
while(filename=readdir(dp))
{
if(filename->d_type == DT_DIR ) //DT_DIR == 4
{
continue;
}
printf("\
<input type=\"checkbox\" value=\"%s\" name=\"check\" />\
\n",filename->d_name) ;
printf("%s\n",filename->d_name) ;
printf("<br>\n");
}
closedir(dp);
printf("\
<input type=\"submit\" value=\"delete\" name=\"log4\" style=\" font-size: 50px; background: #CCCCFF\">\
\n") ;
}
return 0;
}
|
C
|
#include "eps.h"
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
Figure *start_figure(double width, double height)
{
Figure *fig = (Figure *)malloc(sizeof(Figure));
fig->urx = width / 2;
fig->ury = height / 2;
fig->llx = -width / 2;
fig->lly = -height / 2;
return fig;
}
void set_thickness_resolution(Figure *fig, double resolution, double thickness)
{
fig->resolution = resolution;
fig->thickness = thickness;
}
void set_color(Figure *fig, Color col)
{
fig->color.blue = col.blue;
fig->color.red = col.red;
fig->color.green = col.green;
}
void point_insert(Point2D *point, double x, double y, int FLAG)
{
point->x = x;
point->y = y;
point->flag = FLAG;
}
void draw_fx(Figure *fig, double f(double x), double start_x, double end_x, double step_size)
{
Point2D *point = (Point2D *)malloc(sizeof(Point2D));
point->x = start_x;
point->y = f(start_x);
point->flag = 1; // flag 'move to'
point->next = NULL;
Point2D *temp = (Point2D *)malloc(sizeof(Point2D));
temp = point;
double i = 0;
for (i = start_x + 1 / fig->resolution; i <= end_x; i += 1 / fig->resolution) // adding all the points between start_x and end_x (increasing in multiplies of resolution)
{
temp->next = (Point2D *)malloc(sizeof(Point2D));
temp = temp->next;
point_insert(temp, i, f(i), 0);
temp->next = NULL;
}
temp->next = (Point2D *)malloc(sizeof(Point2D)); // adding the last point
temp = temp->next;
point_insert(temp, end_x, f(end_x), 0);
temp->next = NULL;
if (fig->point != NULL) // if figure has already points, we must go to the last addres of these points
{
Point2D *showpo = (Point2D *)malloc(sizeof(Point2D));
showpo = fig->point;
while (showpo->next != NULL)
showpo = showpo->next;
showpo->next = (Point2D *)malloc(sizeof(Point2D));
showpo->next = point; // when we arrive, merging the points that was created with the function to the figure->point's last addres.
}
else
{
fig->point = point;
}
}
void append_figures(Figure *fig, Figure *fig2) // this function merges points of the figure on the right to the figure on the left
{
if (fig->point == NULL)
{
Point2D *pointfig2 = (Point2D *)malloc(sizeof(Point2D));
pointfig2 = fig2->point;
fig->point = pointfig2;
fig->point->flag = 1;
return;
}
Point2D *pointfig1 = (Point2D *)malloc(sizeof(Point2D));
Point2D *pointfig2 = (Point2D *)malloc(sizeof(Point2D));
pointfig2 = fig2->point;
pointfig1 = fig->point;
while (pointfig1->next != NULL)
{
pointfig1 = pointfig1->next;
}
pointfig1->next = (Point2D *)malloc(sizeof(Point2D));
pointfig1->next = pointfig2;
pointfig1->next->flag = 1;
}
void draw_ellipse(Figure *fig, Point2D *centre, Point2D *width_height)
{
Figure *fig2 = (Figure *)malloc(sizeof(Figure));
fig2->text = NULL;
fig2->color = fig->color;
fig2->llx = fig->llx;
fig2->lly = fig->lly;
fig2->urx = fig->urx;
fig2->ury = fig->ury;
fig2->resolution = fig->resolution;
fig2->thickness = fig->thickness; // fig1 copied to fig2 to merge later.
fig2->point = NULL;
double width = width_height->x;
double height = width_height->y;
double start_x, end_x;
start_x = -width_height->x; // center is assumed (0,0), will be shifted if necessary
end_x = width_height->x; // center is assumed (0,0), will be shifted if necessary
double pos_ellipse(double x) { return sqrt((1 - ((x * x) / (width * width))) * (height * height)); }
double neg_ellipse(double x) { return -sqrt((1 - ((x * x) / (width * width))) * (height * height)); }
draw_fx(fig, pos_ellipse, start_x, end_x, 0);
draw_fx(fig2, neg_ellipse, start_x, end_x, 0);
append_figures(fig, fig2);
Point2D *point = (Point2D *)malloc(sizeof(Point2D));
if (centre->x != 0 && centre->y != 0) // if the center is not (0,0), coordinates must be shifted. ->>
{
point = fig->point;
while (point != NULL)
{
point->x += centre->x;
point->y += centre->y;
point = point->next;
}
}
point = fig->point;
while(point->next != NULL) point = point->next;
point->next == NULL;
}
void text(Figure *fig, Text *text2)
{
Text *texto = (Text *)malloc(sizeof(Text));
texto = fig->text;
if(texto==NULL)
{
texto=text2;
return;
}
while (texto->next != NULL)
{
texto = texto->next;
}
texto->next = text2;
}
void end_point_instert(Figure *fig, double x, double y, int flag)
{
Point2D *pointt = (Point2D*)malloc(sizeof(Point2D));
pointt = fig->point;
while (pointt->next!=NULL) pointt = pointt->next;
Point2D *new = (Point2D*)malloc(sizeof(Point2D));
new->x = x;
new->y = y;
new->flag = flag;
pointt->next = new;
}
void draw_binary_tree(Figure *fig, Tree *tree, double center_x, double center_y)
{
if (tree == NULL)
return;
int radius = 10; // optional choosing, can be changed
Point2D *center = (Point2D *)malloc(sizeof(Point2D));
center->x = center_x;
center->y = center_y;
Point2D *width_height = (Point2D *)malloc(sizeof(Point2D));
width_height->x = radius;
width_height->y = radius;
Figure *fig2 = (Figure *)malloc(sizeof(Figure));
fig2->color = fig->color;
fig2->llx = fig->llx;
fig2->lly = fig->lly;
fig2->urx = fig->urx;
fig2->ury = fig->ury;
fig2->resolution = fig->resolution;
fig2->thickness = fig->thickness; // fig1 copied to fig2 to merge later.
fig2->point = NULL;
fig2->text = NULL;
Text *texto = (Text *)malloc(sizeof(Text));
texto->number = tree->number;
texto->x = center_x - radius / 3;
texto->y = center_y;
texto->next = NULL;
if (fig->text == NULL)
fig->text = texto;
else text(fig, texto);
draw_ellipse(fig2, center, width_height);
append_figures(fig, fig2);
if (tree->branch1 != NULL)
{
end_point_instert(fig,center_x,center_y-radius,1); // drawing arms
end_point_instert(fig,center_x - radius * 3,(center_y - radius * 3)+radius,0); // drawing arms
draw_binary_tree(fig, tree->branch1, center_x - radius * 3, center_y - radius * 3); // go to left branch ->
}
if (tree->branch2 != NULL)
{
end_point_instert(fig,center_x,center_y-radius,1); // drawing arms
end_point_instert(fig,center_x + radius * 3,(center_y - radius * 3)+radius,0); // drawing arms
draw_binary_tree(fig, tree->branch2, center_x + radius * 3, center_y - radius * 3); // go to left branch ->
}
}
void draw_polygon(Figure *fig, Point2D *poly_line) // merges the last point to the first point, and merges this point struct to fig->point
{
Point2D *temp1 = (Point2D *)malloc(sizeof(Point2D));
Point2D *temp2 = (Point2D *)malloc(sizeof(Point2D));
temp1 = poly_line;
temp2 = poly_line;
temp1 = temp2;
while (temp1->next != NULL)
{
temp1 = temp1->next;
}
temp1->next = (Point2D *)malloc(sizeof(Point2D));
temp1 = temp1->next;
temp1->x = temp2->x;
temp1->y = temp2->y;
temp1->flag = temp2->flag;
fig->point = temp2;
}
void draw_polyline(Figure *fig, Point2D *point, int n)
{
Point2D *temp = (Point2D *)malloc(sizeof(Point2D));
temp->x = point[0].x;
temp->y = point[0].y;
temp->flag = 0;
temp->next = NULL;
Point2D *p = (Point2D *)malloc(sizeof(Point2D));
p = temp;
temp->next = (Point2D *)malloc(sizeof(Point2D));
temp = temp->next;
int i = 1;
while (i < n)
{
temp->x = point[i].x;
temp->y = point[i].y;
temp->flag = 0;
temp->next = NULL;
if (i == (n - 1))
break;
temp->next = (Point2D *)malloc(sizeof(Point2D));
temp = temp->next;
i++;
}
fig->point = p;
}
void export_eps(Figure *fig, char *filename)
{
FILE *file;
file = fopen(filename, "wt");
fprintf(file, "%%!PS-Adobe-3.0 EPSF-3.0");
fprintf(file, "\n%%%%BoundingBox: %d %d %d %d", (int)fig->llx, (int)fig->lly, (int)fig->urx, (int)fig->ury);
fprintf(file, "\n%d setlinewidth", (int)fig->thickness);
fprintf(file, "\n%.1f %.1f %.1f setrgbcolor", fig->color.red, fig->color.green, fig->color.blue);
if (fig->text != NULL)
{
fprintf(file, "\n/Calibri findfont\n5 scalefont\nsetfont");
while (fig->text != NULL)
{
fprintf(file, "\n%d %d moveto", (int)fig->text->x, (int)fig->text->y);
fprintf(file, "\n(%d) show", fig->text->number);
fig->text = fig->text->next;
}
}
fprintf(file, "\n%.1f %.1f moveto", fig->point->x, fig->point->y); // move to starting point
Point2D *point = (Point2D *)malloc(sizeof(Point2D));
point = fig->point->next;
while (point != NULL)
{
fprintf(file, "\n%.1f %.1f ", point->x, point->y);
if (point->flag == 1)
fprintf(file, "moveto");
else
fprintf(file, "lineto");
point = point->next;
}
fprintf(file, "\nstroke\n");
fclose(file);
}
void scale_figure(Figure *fig, double scale_x, double scale_y)
{
Point2D *point = (Point2D *)malloc(sizeof(Point2D));
point = fig->point;
while (point != NULL)
{
point->x *= scale_x;
point->y *= scale_y;
point = point->next;
}
}
void resize_figure(Figure *fig, Point2D *start_roi, Point2D *end_roi)
{
fig->llx = start_roi->x;
fig->lly = start_roi->y;
fig->urx = end_roi->x;
fig->ury = end_roi->y;
}
|
C
|
#include<stdio.h>
#include<stdlib.h>
#include<math.h>
#include<ctype.h>
#include<string.h>
#define NEXT(a) ((a)->next)
// #define DEBUG
typedef struct range_node Range_node, *Range;
typedef struct source_node Source_node, *Source;
typedef struct {
int year;
int month;
int day;
} Date;
struct source_node {
char name[100];
Range times;
Range last;
Source next;
};
struct range_node {
char start[100];
char stop[100];
Range next;
};
/*
* Enumerate valid months and their non-leap year number of days.
*/
struct Month {
char *name;
int imonth;
int nday;
};
static struct Month months[12] = {
{"Jan", 1, 31},
{"Feb", 2, 28},
{"Mar", 3, 31},
{"Apr", 4, 30},
{"May", 5, 31},
{"Jun", 6, 30},
{"Jul", 7, 31},
{"Aug", 8, 31},
{"Sep", 9, 30},
{"Oct", 10,31},
{"Nov", 11,30},
{"Dec", 12,31},
};
static int compdate(Date date1, Date date2, Date *result);
static int parsedate(char *fdate, Date *date);
static int getsdate(char *sdate, Date *date);
Range installSource(Source* list, char* name, char* starttime, char* stoptime);
Range new_Range(char* name);
Range append_Range(Range* list, char* starttime, char* stoptime);
Source new_Source(char* name);
Source append_Source(Source *list, char* name);
Source find_Source(Source *list, char* name);
int emptySourceList(Source list);
int emptyRangeList(Range list);
void free_Source(Source *list);
void free_Range(Range *list);
extern int coprocess(char *exe, char **argv, FILE **rfp, FILE **wfp);
int main(int argc, char *argv[])
{
FILE *pipe;
char command[300];
char buf[200], tmpbuf[200];
Source list=NULL,tmp,tmpsource;
Source currsource=NULL;
Range currrange=NULL,tmp2;
char *time=NULL,*date=NULL,*sdate=NULL,lastsource[100],source[100],
timestring[100], starttime[100], stoptime[100];
FILE *rfp, *wfp;
int nsource = 0;
char *junk[]={NULL},*localhost=NULL;
int dofull=0,pending=0;
bool startLine=false;
int i;
int islinux=1;
Date datetmp = {0}; /* A container for reading new dates. */
Date current = {0}; /* The highest of the current date stamp from the
file name or from a Date line in the logfile */
static char srccheck[]="track";
static char schstartcheck[]=" Starting schedule:";
static char schstopcheck[]=" Exiting schedule:";
char *startcheck=NULL, *stopcheck=NULL;
int sort=1;
int counter=0;
bool doSrc=true;
typedef enum { /* Enumerate the different hosts we know about */
HOST_SPT,
HOST_CROSS,
HOST_NONLOCAL
} Host;
Host host=HOST_NONLOCAL;
bool test=false;
lastsource[0] = '\0';
datetmp.year = current.year = 0;
datetmp.month = current.month = 0;
datetmp.day = current.day = 0;
if(argc < 4) {
fprintf(stderr,"Usage: src|sch list|sort filename1 filename2 ... (regexp)\n");
fprintf(stderr,"Note: If you use regexp characters, you must enclose the\n expression in single quotes (\')\n");
return 0;
}
/*
* Check what host we're on.
*/
if((localhost=getenv("HOST"))==NULL)
host = HOST_NONLOCAL;
else if(strstr(localhost,"spt")!=NULL)
host = HOST_SPT;
else if(strstr(localhost,"cross")!=NULL)
host = HOST_CROSS;
/*
* Now check whether we are searching for sources or schedules.
*/
if(strcmp(argv[1], "src")==0) {
startcheck = srccheck;
doSrc = true;
}
else if(strcmp(argv[1], "sch")==0) {
startcheck = schstartcheck;
stopcheck = schstopcheck;
doSrc = false;
}
/*
* A kludge to look in the testcrate directory
*/
else if(strcmp(argv[1], "srctest")==0) {
startcheck = srccheck;
test = true;
}
else if(strcmp(argv[1], "schtest")==0) {
startcheck = schstartcheck;
stopcheck = schstopcheck;
test = true;
}
else {
fprintf(stderr,"Unrecognized parameter: %s\n",argv[1]);
return 1;
}
/*
* Now check what output was requested.
*/
if(strcmp(argv[2],"sort")==0)
sort = 1;
else if(strcmp(argv[2],"list")==0)
sort = 0;
else {
fprintf(stderr,"Unrecognized output format: %s\n",argv[2]);
return 1;
}
/*
* Main loop -- for each argument, grep out relevant lines
*/
for(i=3;i < argc;i++) {
if(host != HOST_NONLOCAL) {
if(host==HOST_SPT || host==HOST_CROSS)
strcpy(command,"egrep --with-filename --binary-files=text \"[0-9] track|Starting schedule:|Exiting schedule:|Date:\" ");
else
strcpy(command,"egrep --binary-files=text \"[0-9] track|Starting schedule:|Exiting schedule:|Date:\" ");
}
else
strcpy(command,"egrep --with-filename --binary-files=text \"[0-9] track|Starting schedule:|Exiting schedule:|Date:\" ");
/*
* Do we need to parse a regexp string?
*/
if(strchr(argv[i],'*') || strchr(argv[i],'['))
dofull = 1;
else
dofull = 0;
/*
* First argument should be the directory in which the logfiles are to
* be found.
*/
switch (host) {
case HOST_SPT:
case HOST_CROSS:
strcat(command, "/data/sptdaq/log/");
break;
default: /* Default to parker */
strcat(command, "/data/sptdaq/log/");
break;
};
/*
* Next, tack on the name of the file(s) to search.
*/
strcat(command,argv[i]);
if(host==HOST_NONLOCAL)
strcat(command,"\'");
/*
* Now execute the command.
*/
pipe = popen(command,"r");
/*
* If this was a single file, read the date stamp out of it directly
* from the file name.
*/
if(!dofull) {
/*
* Read the day stamp out of the filename -- this will be the first
* string of every line.
*/
date = strtok(argv[i], "_");
while(!isdigit((int)(*date))) ++date;
parsedate(date, ¤t);
}
/*
* Now loop over all matching lines. These can be either track lines, or
* Date lines.
*/
while(fgets(buf, sizeof(buf),pipe) != NULL) {
strcpy(tmpbuf, buf);
/*
* If this is not a single file, we need to read the date from
* the file name at the head of the line.
*
*
* Read the day stamp out of the filename -- this will be the first
* string of every line.
*/
/*
* Ignore emacs droppings
*/
if(strstr(buf, ".log~"))
continue;
if(!islinux)
dofull = strstr(buf, ".log:")!=NULL;
if(dofull) {
date = strstr(buf, ".log:");
date -= 15;
date = strtok(date, "_");
parsedate(date, &datetmp);
strtok(NULL, ":");
}
/*
* And read the timestamp from this line.
*/
time = strtok(dofull ? NULL : buf, " ");
/*
* If this file was created after the time format was changed,
* read the next line.
*/
if(strstr(time,":")==NULL)
time = strtok(NULL," ");
/*
* And if this was a Date line, read the new date.
*/
if(strstr(tmpbuf,"Date")) {
strtok(strstr(buf,"Date")," ");
sdate = strtok(NULL," ");
getsdate(sdate, ¤t);
}
/*
* Store the most recent of the file date stamp and the date stamp
* from the last Date line.
*/
compdate(current, datetmp, ¤t);
/*
* And construct the date string out of the date and time.
*/
sprintf(timestring, "%02d-%s-%04d:%s",
current.day, months[current.month].name, current.year, time);
/*
* Furthermore, if the line contained a src or sch specifier, extract
* the name.
*/
if(strstr(tmpbuf,startcheck) || (stopcheck && strstr(tmpbuf,stopcheck))) {
#if 0
if(strstr(tmpbuf, "blank_sky.sch") != 0)
fprintf(stdout, "Hello\n");
#endif
// If this was a start line
if(strstr(tmpbuf,startcheck)) {
// Now extract the source/sch name
strtok(strstr(tmpbuf,startcheck)," ");
if(startcheck==schstartcheck)
strtok(NULL," ");
strcpy(source,strtok(NULL,"\n"));
//------------------------------------------------------------
// List the source
//------------------------------------------------------------
/*
* If the new source doesn't match the last, we encountered two
* start lines with no intervening exit lines.
*/
if(!sort) {
if(startcheck==schstartcheck) {
/*
* If we are waiting for an exit line from the previous
* schedule, but have instead encountered a new start line,
* terminate the old listing without an end time (regardless
* of whether the two schedules match.
*/
if(pending)
fprintf(stdout, " %s\n", lastsource);
/*
* And start the new listing.
*/
fprintf(stdout,"%s, ",timestring);
if(startcheck==schstartcheck)
pending = 1;
}
// Else this is a source listing -- don't check for exit
// lines.
else
fprintf(stdout,"%s %s\n",timestring,source);
}
//------------------------------------------------------------
// Now add the source to the list of known sources
//------------------------------------------------------------
if(doSrc) {
// Case 1: this is the first source encountered: install
// it as the current source and keep the start time
if(lastsource[0] == '\0') {
strcpy(lastsource, source);
strcpy(starttime, timestring);
}
// Case 2: this is not the first source encountered, and it
// is the same as the last source. Do nothing -- we will
// elide consecutive source listings into a single range
// Case 3: this is not the first source encountered, and
// it is different from the last source. Close off the
// range with the stop time, and add it to the list. Install it as the
// current source, and store the new start time.
else if(strcmp(lastsource, source) != 0) {
strcpy(stoptime, timestring);
installSource(&list, lastsource, starttime, stoptime);
strcpy(lastsource, source);
strcpy(starttime, timestring);
}
} else {
// Case 1: this is the first schedule encountered: install
// it as the current source and keep the start time
if(lastsource[0] == '\0') {
strcpy(lastsource, source);
strcpy(starttime, timestring);
}
// Case 2: This is not the first schedule encountered, and
// we are done with the previous schedule listing: Install
// it as the current source, and store the start time.
else if(!pending) {
strcpy(lastsource, source);
strcpy(starttime, timestring);
}
// Case 2: This is not the first schedule encountered, and
// we are waiting for an exit line from the previous
// schedule listing: Close off the range with no time
// stamp, and add it to the list. Install it as the
// current source and store the new start time.
else {
installSource(&list, lastsource, starttime, 0);
strcpy(lastsource, source);
strcpy(starttime, timestring);
}
}
// Set the pending flag to true
pending = true;
}
/*
* Else if this was an exit line for a schedule
*/
else {
if(startcheck==schstartcheck) {
strtok(strstr(tmpbuf,stopcheck)," ");
strtok(NULL," ");
strcpy(source,strtok(NULL,"\n"));
}
if(!sort) {
/*
* If the schedule exiting is not the same one that started last,
* then a new schedule was started with no record of it in the log
* file
*/
if(strcmp(lastsource, source) != 0) {
/*
* If we were waiting for an exit line for the previous schedule,
* and we instead encountered an exit line for a different
* schedule, terminate the current schedule listing with no end
* time.
*/
if(pending)
fprintf(stdout, " %s\n", lastsource);
/*
* And write an entry for the schedule we just encountered, with
* no start time.
*/
fprintf(stdout, " , %s %s\n", timestring,
source);
}
else if(pending)
fprintf(stdout, "%s %s\n", timestring, lastsource);
pending = 0;
}
//------------------------------------------------------------
// Store the schedule
//------------------------------------------------------------
// Case 1: we are waiting for an exit line, and the schedule
// matches the current one: close off the range, and add it
// to the list.
if(pending) {
if(strcmp(lastsource, source)==0) {
strcpy(stoptime, timestring);
installSource(&list, lastsource, starttime, stoptime);
} else {
// Case 2: we are waiting for an exit line, and the schedule
// doesn't match the current one: close off the current
// range with no end time, and add it to the list. Add a
// range for the new schedule with no start time.
installSource(&list, lastsource, starttime, 0);
strcpy(stoptime, timestring);
installSource(&list, source, 0, stoptime);
}
} else {
// Case 3: we are not waiting for an exit line. Add a range
// for the new schedule with no start time.
strcpy(stoptime, timestring);
installSource(&list, source, 0, stoptime);
}
// And set the pending flag to false
pending = false;
}
}
/*
* If not, skip the rest of the loop.
*/
else
continue;
}
pclose(pipe);
}
// If we were waiting for an exit line when the read ended, close
// out the terminal range with no stop time
if(!doSrc && pending) {
installSource(&list, lastsource, starttime, 0);
// And if not sorting, print the final entry
if(!sort)
fprintf(stdout, " %s\n", lastsource);
}
/*
* If sorted output was requested, pipe the list to sort.
*/
if(sort) {
if(coprocess("sort", junk, &rfp, &wfp))
exit(1);
for(tmp=list;tmp != NULL;tmp = tmp->next)
fprintf(wfp, "%s\n", tmp->name);
fclose(wfp);
while(fgets(source, sizeof(source), rfp)) {
char *cptr = strchr(source, '\n');
if(cptr) *cptr = '\0';
for(tmp=list;tmp != NULL;tmp = tmp->next)
if(strcmp(tmp->name,source)==0) {
printf("\n%s:\n\n",source);
for(tmp2=tmp->times;tmp2 != NULL;tmp2=tmp2->next) {
printf("\t%s, ",tmp2->start);
if(tmp2->stop[0] == '\0')
printf("%s"," \n");
else
printf("%s\n",tmp2->stop);
}
}
}
}
fprintf(stdout,"\n");
free_Source(&list);
return 1;
}
Range installSource(Source* list, char* name, char* starttime, char* stoptime)
{
Source src = find_Source(list, name);
src->last = append_Range(&src->times, starttime, stoptime);
return src->last;
}
Range new_Range(char* starttime, char* stoptime)
{
Range newRange = (Range) malloc(sizeof(Range_node));
if(newRange == NULL)
return 0;
NEXT(newRange) = NULL;
sprintf(newRange->start, "%20s", "");
sprintf(newRange->stop, "%20s", "");
if(starttime)
strcpy(newRange->start, starttime);
if(stoptime)
strcpy(newRange->stop, stoptime);
return newRange;
}
Range append_Range(Range* list, char* starttime, char* stoptime)
{
Range newRange = new_Range(starttime, stoptime);
Range tmp;
if(newRange == NULL)
return 0;
if(emptyRangeList(*list))
*list = newRange;
else {
for(tmp = *list; NEXT(tmp) != NULL;tmp = NEXT(tmp));
NEXT(tmp) = newRange;
}
return newRange;
}
Source new_Source(char* name)
{
Source src = (Source) malloc(sizeof(Source_node));
if(src == NULL)
return 0;
src->times = 0x0;
src->last = 0x0;
NEXT(src) = NULL;
strcpy(src->name, name);
return src;
}
Source find_Source(Source* list, char* name)
{
Source tmp=0;
if(emptySourceList(*list))
return append_Source(list, name);
else {
for(tmp = *list; tmp != NULL;tmp = NEXT(tmp))
if(strcmp(tmp->name, name)==0)
return tmp;
}
return append_Source(list, name);
}
Source append_Source(Source *list, char* name)
{
Source src = new_Source(name);
Source tmp=0;
if(emptySourceList(*list))
*list = src;
else {
for(tmp = *list; NEXT(tmp) != NULL;tmp = NEXT(tmp));
NEXT(tmp) = src;
}
return src;
}
int emptySourceList(Source list)
{
return (list == NULL) ? 1 : 0;
}
int emptyRangeList(Range list)
{
return (list == NULL) ? 1 : 0;
}
void free_Source(Source *list)
{
Source temp,nxt;
if(*list)
for(temp = *list;NEXT(temp) != NULL;temp = nxt) {
nxt = NEXT(temp);
free_Range(&temp->times);
free(temp);
}
}
void free_Range(Range *list)
{
Range temp,nxt;
if(*list)
for(temp = *list;NEXT(temp) != NULL;temp = nxt) {
nxt = NEXT(temp);
free(temp);
}
}
/*.......................................................................
* Compare two dates, and return the more recent of the two.
*/
static int compdate(Date date1, Date date2, Date *result)
{
int dayno, iy, i;
double jul1, jul2;
/*
* Check for leap years
*/
if(date1.year % 4 == 0)
if((date1.year % 100 != 0) || (date1.year % 400 == 0))
months[1].nday = 29;
/*
* Now convert the first date's month and day into a day number.
*/
dayno = 0;
for(i=0;i < date1.month;i++)
dayno += months[i].nday;
dayno += date1.day;
iy = date1.year-1;
jul1 = iy*365 + (iy/4) - (iy/100) + (iy/400);
jul1 += dayno;
/*
* Check for leap years
*/
if(date2.year % 4 == 0)
if((date2.year % 100 != 0) || (date2.year % 400 == 0))
months[1].nday = 29;
/*
* Now convert the first date's month and day into a day number.
*/
dayno = 0;
for(i=0;i < date2.month;i++)
dayno += months[i].nday;
dayno += date2.day;
iy = date2.year-1;
jul2 = iy*365 + (iy/4) - (iy/100) + (iy/400);
jul2 += dayno;
/*
* Now store whichever is the larger of the two dates.
*/
result->year = jul1 > jul2 ? date1.year : date2.year;
result->month = jul1 > jul2 ? date1.month : date2.month;
result->day = jul1 > jul2 ? date1.day : date2.day;
return 0;
}
/*.......................................................................
* Parse a date string into a date structure.
*/
static int parsedate(char *fdate, Date *date)
{
char num[5];
int i;
for(i=0;i < 4;i++)
num[i] = *fdate++;
num[i] = '\0';
date->year = atoi(num);
for(i=0;i < 2;i++)
num[i] = *fdate++;
num[i] = '\0';
date->month = atoi(num)-1;
for(i=0;i < 2;i++)
num[i] = *fdate++;
num[i] = '\0';
date->day = atoi(num);
return 0;
}
/*.......................................................................
* Parse a date string into a date structure.
*/
static int getsdate(char *sdate, Date *date)
{
char *month=NULL;
int day, year;
int i;
day = atoi(strtok(sdate,"-"));
month = strtok(NULL,"-");
year = atoi(strtok(NULL," "));
for(i=0;i < 12;i++)
if(strcasecmp(month, months[i].name)==0)
break;
date->day = day;
date->year = year;
date->month = i;
return 0;
}
|
C
|
/*****************************
hw05: quick sort排序
姓名: stu012
學號:
******************************/
#include <stdio.h>
#include <string.h>
void showdata(int*);
void quick(int*, int, int);
int main(void)
{
int data[18]={10,12,31,89,2013,13,42,88,76,45,21,17,75,8,5,2,1,100}; //原始資料
quick(data,0,17);
showdata(data);
return 0;
}
void showdata (int data[])
{
{
printf("Quick sort:");
printf("\n");
}
int i;
for(i=0; i<18; i++)
{
if(i==17)
{
printf("%d",data[i]);
printf("\n");
}
else
{
printf("%d,",data[i]);
}
}
printf("\n");
}
void quick(int d[], int lf,int rg)
{
int i,j,tmp;
int lf_idx;
int rg_idx;
int t;
//第一筆鍵值為d[lf]
if(lf<rg)
{
lf_idx=lf+1;
rg_idx=rg;
search_step:
for(t=0;t<18;t++)
for(i=lf+1;i<=rg;i++) //由左向右找出一個鍵值大於d[lf]者
{
if(d[i]>=d[lf])
{
lf_idx=i;
break;
}
lf_idx++;
}
for(j=rg;j>=lf+1;j--) //由右向左找出一個鍵值小於d[lf]者
{
if(d[j]<=d[lf])
{
rg_idx=j;
break;
}
rg_idx--;
}
if(lf_idx < rg_idx) //如果lf_idx <rg_idx 則d[lf_idx]和 [rg_idx]互換
{
tmp=d[lf_idx];
d[lf_idx]=d[rg_idx];
d[rg_idx]=tmp;
goto search_step; //繼續執行步驟
}
if(lf_idx >=rg_idx); //如果lf_idx 大於等於 rg_idx 則將d[lf]跟 d[rg]互換
{
tmp=d[lf];
d[lf]= d[rg_idx];
d[rg_idx]=tmp; //並以rg_idx為基準點 分成左右兩半
quick(d,lf,rg_idx-1); //以遞迴方式分別為左右兩半進行排序
quick(d,rg_idx+1,rg); //直到排序完成
}
}
}
|
C
|
#include <linux/completion.h>
#include <linux/spinlock.h>
/**
* complete: - signals a single thread waiting on this completion
* @x: holds the state of this particular completion
*
* This will wake up a single thread waiting on this completion. Threads will be
* awakened in the same order in which they were queued.
*
* It may be assumed that this function implies a write memory barrier before
* changing the task state if and only if any tasks are woken up.
*/
void complete(struct completion *x)
{
ithEnterCritical();
x->done++;
ithExitCritical();
sem_post(&x->wait);
}
/**
* wait_for_completion_timeout: - waits for completion of a task (w/timeout)
* @x: holds the state of this particular completion
* @timeout: timeout value in jiffies
*
* This waits for either a completion of a specific task to be signaled or for a
* specified timeout to expire. The timeout is in jiffies. It is not
* interruptible.
*
* The return value is 0 if timed out, and positive (at least 1, or number of
* jiffies left till timeout) if completed.
*/
unsigned long
wait_for_completion_timeout(struct completion *x, unsigned long timeout)
{
unsigned long ret;
/* itpSemWaitTimeout() return -1 when timeout */
ret = itpSemWaitTimeout(&x->wait, timeout);
return ret ? 0 : 1;
}
|
C
|
/*
W3C Sample Code Library libwww Timer Class
!
The Timer Class
!
*/
/*
** (c) COPYRIGHT MIT 1995.
** Please first read the full copyright statement in the file COPYRIGH.
*/
/*
The Timer class handles timers for libwww and the application. This works
exactly as in X where you create a timer object with a callback function
and a timeout. The callback will be called every time the timer expires.
There are several timeouts that can be set in libwww:
o
The time we keep an idle persistent connection open. Here there are in fact
two mechanisms depending on whether you use blocking or non-blocking sockets.
The default is 60 secs. The timers can be accessed using the functions defined
in the HTHost object
o
The idle time we want to wait when receiving a response from a server, that
is, if it doesn't send anything in a number of secs. The default here is
no timeout. It can be accessed in the
HTHost object as well.
o
The timeout before we flush pending requests in a pipeline, the default here
is 30 ms. It is also accessed in the HTHost
object
o
The timeout before we start sending the body of a PUT or
POST request. Normally we send the Expect: 100-continue
header field but if the server doesn't send back a 100 Continue
code then we upload the body anyway. The default is 2 secs and can be accessed
in the HTTP module.
*/
#ifndef HTTIMER_H
#define HTTIMER_H
#include "wwwsys.h"
#include "HTReq.h"
typedef struct _HTTimer HTTimer;
typedef int HTTimerCallback (HTTimer *, void *, HTEventType type);
/*
.
Create and Delete Timers
.
The callback function is the function that is to be called when timer expires.
*/
extern HTTimer * HTTimer_new (HTTimer *, HTTimerCallback *,
void *, ms_t millis,
BOOL relative, BOOL repetitive);
extern BOOL HTTimer_delete (HTTimer * timer);
extern BOOL HTTimer_deleteAll (void);
extern BOOL HTTimer_expireAll (void);
/*
.
Dispatch Timer
.
Just do it
*/
extern int HTTimer_dispatch (HTTimer * timer);
/*
(
Get the next timer in line
)
Dispatches all expired timers and optionally returns the time till the next
one.
*/
extern int HTTimer_next (ms_t * pSoonest);
/*
(
Reset an already existing Repetitive Timer
)
*/
extern BOOL HTTimer_refresh(HTTimer * timer, ms_t now);
/*
.
Get Information about a Timer Object
.
(
Absolute Time when This Timer Expires
)
Absolute time in millies when this timer will expire
*/
extern ms_t HTTimer_expiresAbsolute (HTTimer * timer);
/*
(
Relative Time this Timer is running
)
Gived the relative time in millies that this timer was registered with. For
example, a relative timer set to expire in 20ms will return 20.
*/
#define HTTimer_getTime(t) HTTimer_expiresRelative(t)
extern ms_t HTTimer_expiresRelative (HTTimer * timer);
/*
(
Has this Timer Expired?
)
If so then it's time to call the dispatcher!
*/
extern BOOL HTTimer_hasTimerExpired (HTTimer * timer);
/*
(
What callback is this Timer Registered with?
)
*/
extern HTTimerCallback * HTTimer_callback (HTTimer * timer);
/*
(
Is this Time relative or Absolute?
)
*/
extern BOOL HTTimer_isRelative (HTTimer * timer);
/*
.
Platform Specific Timers
.
On some platform, timers are supported via events or other OS specific
mechanisms. You can make libwww can support these by registering a platform
specific timer add and timer delete method.
*/
typedef BOOL HTTimerSetCallback (HTTimer * timer);
extern BOOL HTTimer_registerSetTimerCallback (HTTimerSetCallback * cbf);
extern BOOL HTTimer_registerDeleteTimerCallback (HTTimerSetCallback * cbf);
/*
*/
#endif /* HTTIMER_H */
/*
@(#) $Id: HTTimer.html,v 2.12 2005-11-11 14:03:16 vbancrof Exp $
*/
|
C
|
/******************************************************
* 排序算法:
* - 冒泡排序:
* - 插入排序
* - 希尔排序
* - 堆排序
* - 归并排序
* - 快速排序
* - 表排序
* - 桶排序
* - 基数排序
*
* 各个算法的时间复杂度、额外空间复杂度和稳定性见PPT10.4
*
* 定义同一接口:void XSort(ElementType a[], int n);
* 统一为从小到大排序
* (只讨论内部排序)
******************************************************/
#ifndef SORT_H
#define SORT_H
#include <stdbool.h>
typedef int ElementType;
void BubbleSort(ElementType a[], int n);
void InsertSort(ElementType a[], int n);
void ShellSort(ElementType a[], int n);
void HeapSort(ElementType a[], int n);
void MergeSort_R(ElementType a[], int n);
void MergeSort(ElementType a[], int n);
void QuickSort(ElementType a[], int n);
int* CreateTable(ElementType a[], int n);
void TableSort(ElementType a[], int table[], int n);
void BucketSort(ElementType a[], int n); //没写
void LSDRadixSort(ElementType a[], int n);
void MSDRadixSort(ElementType a[], int n);
#endif
|
C
|
/**
* VUT FIT IMP project - heart rate measurement.
*
* original
*
* @brief LED display interface.
* @author Dominik Harmim (xharmi00) <xharmi00@stud.fit.vutbr.cz>
* @date 30.12.2018
*/
#ifndef DISPLAY_H
#define DISPLAY_H
#include <stdint.h>
/**
* Display refresh period in us.
* Frequency 60 Hz, 1 / 60 = 0.0166666 s = 16666 us,
* for 4 digits = 16666 / 4 = 4166.
*/
static const uint64_t DISPLAY_REFRESH_IN_USEC = 4166;
/**
* Displays next number on the LED display.
*/
void display_display_next_number(void);
/**
* Sets number to be displayed on the LED display.
*
* @param number Number to be displayed on the LED display.
*/
void display_set_number(const unsigned int number);
#endif //DISPLAY_H
|
C
|
#include<stdio.h>
int bsearch(int*,int,int);
int main()
{
int i,n,a[50],k,r;
printf("Enter the number of elements : ");
scanf("%d",&n);
printf("Enter the array : ");
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
printf("Enter no. to be searched : ");
scanf("%d",&k);
r=bsearch(a,n,k);
if(r==-1)
printf("Search unsuccessful");
else
printf("The element at found in %d index",r);
return 0;
}
int bsearch(int a[],int n,int k)
{
int l,u,mid;
l=0;
u=n-1;
while(l!=u)
{
mid=(l+u)/2;
if(k>a[mid])
l=mid+1;
else if(k<a[mid])
u=mid-1;
else
return mid;
}
return -1;
}
|
C
|
#pragma poroto memory input_mem int 16984
#pragma poroto memory output_mem int 16984
#pragma poroto stream::roccc_bram_in threshold::input_image(input_mem, N*N, ROCCC_uint8)
#pragma poroto stream::roccc_bram_out threshold::output_image(output_mem, N*N, ROCCC_uint8)
typedef unsigned int ROCCC_uint8;
void threshold(int N, ROCCC_uint8 **input_image, ROCCC_uint8 threshold_v, ROCCC_uint8 **output_image)
{
int c;
int r;
ROCCC_uint8 aux;
for (r = 0; r < N; r++) {
for (c = 0; c < N; c++) {
if (input_image[r][c] < threshold_v) {
aux = 0;
} else {
aux = 255;
}
output_image[r][c]= aux;
}
}
}
|
C
|
/*
* file: mkfamesmr.c
* description: initialize fake SMR drive or image
*/
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <getopt.h>
#include "stl_fakesmr.h"
#define SECTOR_SIZE 4096
#define BANDS_PER_SECTOR (SECTOR_SIZE/sizeof(int))
int band_size = 128 * 1024 * 1024; /* 128MB */
struct option opts[] = {
{.name = "bandsize", required_argument, 0, 'b'},
{.name = "read", no_argument, 0, 'r'},
{0, 0, 0, 0}
};
off_t parseint(char *s)
{
off_t val = strtol(s, &s, 0);
if (toupper(*s) == 'G')
val *= (1024*1024*1024);
if (toupper(*s) == 'M')
val *= (1024*1024);
if (toupper(*s) == 'K')
val *= 1024;
return val;
}
int main(int argc, char **argv)
{
int c, opt_index, do_read = 0;
while ((c = getopt_long_only(argc, argv, "", opts, &opt_index)) != -1) {
switch (opts[opt_index].val) {
case 'b':
band_size = parseint(optarg);
break;
case 'r':
do_read = 1;
break;
}
}
if (optind != argc-1) {
fprintf(stderr, "usage: %s <device>\n", argv[0]);
exit(1);
}
char *name = argv[optind];
if (do_read) {
struct smr *dev;
if ((dev = smr_open(name)) == NULL)
fprintf(stderr, "can't open %s\n", name);
else {
int i, n = smr_n_bands(dev);
int s = smr_band_size(dev);
printf("%d bands of %.1f MB\n", n, s / 256.0);
for (i = 0; i < n; i++) {
int m = smr_write_pointer(dev, i);
if (m != 0)
printf("%d: %d\n", i, m);
}
}
}
else {
int n = smr_init(name, band_size / 4096);
printf("successfully initialized with %d bands\n", n);
}
return 0;
}
|
C
|
/**********************************************************
*
* File : client1_main.c
* Author : Cédric HUMBERT & Kilian CONTAMAIN
*
* Description :
* Ce fichier contient le code du programe principal coté
* Client du systeme TOMM
*
* Projet : PSE ISMIN 2A
*
* Date : 19/ 11/ 2014
*
*************************************************************/
#include "include/pse.h"
#include "head_Cli.h"
int main(int argc, char *argv[]){
// Déclaration des variables :
int sock, arret = VRAI;
char init_EN[TAILLE_NOM], init_REC[TAILLE_NOM];
Utilisateur *Cur_User = NULL;
//Cur_User = (Utilisateur *) malloc(sizeof(Utilisateur));
Message_TOMM *Mes; // Outils pour decrire les fichiers envoyés
// Initialisation :
//MesL = malloc(sizeof(Message_TOMM));
strcpy(init_EN, "ENVOI");
strcpy(init_REC, "RECPT");
// création de la socket
sock = Create_Sock(argc, argv);
// Connection au serveur
Connection_TOMM(sock, argc, argv);
while(arret){
// Authetification :
Mes = Interpret_Cli();
// Demande au Seveur :
ecrireLigne(sock, init_EN); // On se place en Envoi
write_Message_TOMM(Mes, "Temp/echange"); // Ecrit le message dans le fichier
envoyerFichier(sock, "Temp/echange"); // Envoi le fichier au serveur
rm_File("Temp/echange");
// Confirmation Je sais pas si il faudra encore ecrire une ligne pour qu'il nous envoi sa reponse
RecevoirFich(sock, "Temp/conf"); // Reception de l'authetifiction
read_Message_TOMM(Mes, "Temp/conf"); // Lecture du fichier recut
// Renvoi l'utilisateur qui a été envoyé par le serveur
//if (Mes->)
Authentification_Locale(Mes, Cur_User);
//Affiche_Utilisateur(Cur_User);
while(!(Mes->descript == 7) /*&& !(Mes->descript == 15)*/){ // Test Authentification reussi si MesL != 15
Mes = Interpret_Cli();
printf("Mes->descript = %d\n", Mes->descript);
if (Mes->descript != 7){
// Envoi de Requete
write_Message_TOMM(Mes, "Temp/Requete"); // Ecriture du fichier correspondant au Message
ecrireLigne(sock, init_EN); // On se place en Envoi
envoyerFichier(sock, "Temp/Requete"); // Envoi le fichier au serveur
rm_File("Temp/Requete");
// Reception
RecevoirFich(sock, "Temp/Answer"); // Recoit le fichier envoyé par le serveur
Traitement_Answer("Temp/Answer"); // Traitement Affichage et rm fichier
}
}
if(Mes->descript == 7){ // Cas de fin
printf("Commande End demandee\n");
printf("Le client TOMM va s'arreter...\n");
arret = FAUX;}
if(Mes->descript == 15){ // Cas d'erreur authetification
printf("Vous n'etes pas authentifié \n");
}
}
if (close(sock) == -1) {erreur_IO("close canal");}
exit(EXIT_SUCCESS);
}
|
C
|
#define max(X, Y) (((X) < (Y)) ? (X) : (Y))
extern int yylineno;
struct expr_type{
int tip;
// int: 0
// char: 1
// bool: 2
// float: 3
float val;
};
struct expr_type* create_expr(float n){
struct expr_type *res = (struct expr_type*) malloc(sizeof(struct expr_type));
res->tip = 3;
res->val = n;
return res;
}
struct expr_type* create_expr(int n){
struct expr_type *res = (struct expr_type*) malloc(sizeof(struct expr_type));
res->tip = 0;
res->val = (float)n;
return res;
}
struct expr_type* create_expr(char c){
struct expr_type *res = (struct expr_type*) malloc(sizeof(struct expr_type));
res->tip = 1;
res->val = (float)c;
return res;
}
struct expr_type* create_expr(int b, int smth){
struct expr_type *res = (struct expr_type*) malloc(sizeof(struct expr_type));
res->tip = 2;
res->val = (float)b;
return res;
}
struct expr_type* logical_operations(struct expr_type *left, struct expr_type *right, char *op){
struct expr_type *res = (struct expr_type*) malloc(sizeof(struct expr_type));
res->tip = 2;
if(strcmp(op, "==") == 0)
res->val = (float)(left->val == right->val);
else if(strcmp(op, "<") == 0)
res->val = (float)(left->val < right->val);
else if(strcmp(op, "<=") == 0)
res->val = (float)(left->val <= right->val);
else if(strcmp(op, ">") == 0)
res->val = (float)(left->val > right->val);
else if(strcmp(op, ">=") == 0)
res->val = (float)(left->val >= right->val);
return res;
}
struct expr_type* expr_aritm(struct expr_type *a, struct expr_type *b, char op){
struct expr_type* res = (struct expr_type*) malloc(sizeof(struct expr_type));
res->tip = max(a->tip, b->tip);
switch(op){
case '+':
res->val = a->val + b->val;
break;
case '-':
res->val = a->val - b->val;
break;
case '*':
res->val = a->val * b->val;
break;
case '/':
res->val = a->val / b->val;
}
return res;
}
|
C
|
#include <stdio.h>
/* Assume name shorter than 20 chars. */
int main() {
char name[20];
puts("Enter name: ");
scanf("%19s", name);
printf("Hello, %s.\n\n\tNice to see you.\n", name);
puts("Enter name: ");
scanf("%19s", name);
printf("Hello, %s.\n\n\tNice to see you.\n", name);
char name1[] = "Anna";
char a_letter = name1[0];
name1[0] = name1[3];
name1[3] = a_letter;
puts(name1);
}
|
C
|
#include <stdio.h>
#include <mpi.h>
int main(int argc, char *argv[]) {
int n = 10 ;
int a[10];
int b[2];
int i;
int rank;
int size;
MPI_Init(&argc,&argv);
MPI_Comm_rank(MPI_COMM_WORLD,&rank);
MPI_Comm_size(MPI_COMM_WORLD,&size);
b[0]=b[1]=rank;
for (i=0; i< n; i++) a[i] = 0;
printf("Process of rank %d has array a=[%d,%d,%d,%d,%d,%d,%d,%d,%d,%d] and b[]=[%d,%d] \n", rank, a[0],a[1],a[2],a[3],a[4],a[5],a[6],a[7],a[8],a[9],b[0],b[1]);
MPI_Allgather(b, 2, MPI_INT, a, 2, MPI_INT, MPI_COMM_WORLD);
printf("Process of rank %d has array a=[%d,%d,%d,%d,%d,%d,%d,%d,%d,%d] and b[]=[%d,%d] \n", rank, a[0],a[1],a[2],a[3],a[4],a[5],a[6],a[7],a[8],a[9],b[0],b[1]);
MPI_Finalize();
return 0;
}
|
C
|
#include<stdio.h>
int main()
{
printf("int:%d\nchar:%d\nDouble:%d\nFloat:%d\n", sizeof(int), sizeof(char), sizeof(double), sizeof(float));
return 0;
}
|
C
|
#include<stdio.h>
int sum(int,int);
int sub(int,int);
int mul(int,int);
int div(int,int);
int mod(int,int);
void main()
{
int a=5,b=2,s1,s2,m,d,m1;
s1=sum(a,b);
s2=sub(a,b);
m=mul(a,b);
d=div(a,b);
m1=mod(a,b);
printf(" %d %d %d %d %d \n", s1,s2,m,d,m1);
}
int sum(int a, int b)
{
int s1=a+b;
return s1;
}
int sub(int a, int b)
{
int s2=a-b;
return s2;
}
int mul(int a, int b)
{
int m=a*b;
return m;
}
int div(int a, int b)
{
int d=a/b;
return d;
}
int mod(int a, int b)
{
int m1=a%b;
return m1;
}
|
C
|
/**
*
* Hodaya Koslowsky
* Comments are in the header files
*
*/
#include "jobList.h"
#include <stdio.h>
#include <memory.h>
#include <malloc.h>
Head *CreateHead() {
Head *head = (Head *) malloc(sizeof(Head));
if (head == NULL) { return NULL; }
head->first = NULL;
head->last = NULL;
head->numberOfNodes = 0;
return head;
}
Job *CreateJob(pid_t pid, char **args, int numArgs) {
static int jobId = 1;
Job *job = (Job *) malloc(sizeof(Job));
job->numArgs = numArgs;
job->pid = pid;
job->jobId = jobId++;
// copy the args to the new job
if (strcmp(args[numArgs - 1], "&") == 0) {
job->state = bg;
//free(args[numArgs - 1]);
job->numArgs--;
} else {
job->state = fg;
}
char **jobArgs = (char **) malloc(job->numArgs * sizeof(char *));
int i;
for(i = 0; i < job->numArgs; i++){
jobArgs[i] = (char *) malloc(strlen(args[i]) + 1);
strcpy(jobArgs[i], args[i]);
}
job->args = jobArgs;
return job;
}
void AddJob(Head *head, Job *newJob) {
if (newJob == NULL || head == NULL) { return; }
if (head->last == NULL || head->first == NULL) {
Node *newNode = (Node *) malloc(sizeof(Node));
if (newNode == NULL) { return; }
newNode->job = newJob;
newNode->next = NULL;
head->first = newNode;
head->last = newNode;
head->numberOfNodes = 1;
return;
}
Node *currentLast = head->last;
Node *newNode = (Node *) malloc(sizeof(Node));
if (newNode == NULL) { return; }
newNode->job = newJob;
newNode->next = NULL;
currentLast->next = newNode;
head->last = newNode;
head->numberOfNodes++;
}
void FreeJob(Job *job) {
if (job == NULL) { return; }
if (job->args == NULL) {
free(job);
return;
}
FreeArgsWithNum(job->args, job->numArgs);
free(job);
}
void FreeNode(Node *node) {
if (node == NULL) { return; }
FreeJob(node->job);
free(node);
}
void RemoveJobId(Head *head, pid_t pid) {
if (head == NULL || head->numberOfNodes < 1 || head->first == NULL) { return; }
if (head->numberOfNodes == 1) {
FreeNode(head->first);
head->first = NULL;
head->last = NULL;
head->numberOfNodes = 0;
return;
}
Node *currentNode = head->first;
Node *previousNode = NULL;
while (currentNode != NULL) {
if (currentNode->job->pid == pid) { break; }
previousNode = currentNode;
currentNode = currentNode->next;
}
if (currentNode == NULL) { return; } // there is no job with that id
if (previousNode == NULL) { //the job to delete is the first one
head->first = currentNode->next;
} else if (head->last == currentNode) { // the job to delete is the last one
head->last = previousNode;
previousNode->next = NULL;
} else { //the job is in the middle
previousNode->next = currentNode->next;
}
FreeNode(currentNode);
head->numberOfNodes--;
}
void RemoveJob(Head *head, Job *job) {
if (head == NULL || job == NULL || head->numberOfNodes < 1) { return; }
RemoveJobId(head, job->pid);
}
void RemoveNode(Head *head, Node *node) {
if (head == NULL || node == NULL) { return; }
RemoveJobId(head, node->job->pid);
}
void FreeArgsWithNum(char **args, int numArgs){
int i = 0;
if (args == NULL) { return; }
for(i = 0; i < numArgs; i++){
if(args[i] != NULL){
free(args[i]);
}
}
free(args);
}
void FreeMemory(Head *head) {
Node *current = head->first;
Node *previous = NULL;
while (current != NULL) {
previous = current;
current = current->next;
RemoveNode(head, previous);
}
free(head);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
struct Node {
int operations;
struct Node* left;
struct Node* down;
struct Node* right;
};
typedef struct Node Node;
Node* init(int value) {
Node* root = (Node*)malloc(sizeof(Node));
root->left = root->down = root->right = NULL;
root->operations = value;
return root;
}
int* buffer;
int size;
int is_present(int value) {
int i;
for(i = 0; i < size; i++) {
if(buffer[i] == value) return 1;
}
return 0;
}
void fill(Node* root, Node* node, int capacity, int* m) {
if(node->operations > capacity || node->operations == 0 || *m == capacity) return;
if(*m < node->operations) *m = node->operations;
Node* right, *left, *down;
int a, b, c;
a = 3 * node->operations;
b = 2 * node->operations;
c = node->operations / 5;
if(!is_present(a)) {
buffer[++size] = a;
left = (Node*)malloc(sizeof(Node));
left->operations = a;
left->right = left->down = left->left = NULL;
node->left = left;
if(*m < left->operations && left->operations <= capacity) *m = left->operations;
fill(root, left, capacity, m);
}
if(!is_present(b)) {
buffer[++size] = b;
down = (Node*)malloc(sizeof(Node));
down->operations = b;
down->right = down->down = down->left = NULL;
if(*m < down->operations && down->operations <= capacity) *m = down->operations;
node->down = down;
fill(root, down, capacity, m);
}
if(!is_present(c)) {
buffer[++size] = c;
right = (Node*)malloc(sizeof(Node));
right->operations = c;
right->left = right->down = right->right = NULL;
if(*m < right->operations && right->operations <= capacity) *m = right->operations;
node->right = right;
fill(root, right, capacity, m);
}
}
// void max(Node* node, int capacity, int* m) {
// if(node->operations > *m && node->operations <= capacity) *m = node->operations;
// if(node->left) {
// max(node->left, capacity, m);
// }
// if(node->down) {
// max(node->down, capacity, m);
// }
// if(node->right) {
// max(node->right, capacity, m);
// }
// }
int main(int argc, const char** argv) {
int capacity, begin, m = 0xFFFFFFFF;
Node* root;
scanf("%d", &capacity);
scanf("%d", &begin);
size = 1;
buffer = malloc(size * sizeof(int));
buffer[0] = begin;
root = init(begin);
fill(root, root, capacity, &m);
printf("%d\r\n", m);
return EXIT_SUCCESS;
}
|
C
|
#include<stdio.h>
void push();
void pop();
void peep();
void update();
int main()
{
int n,a[100],top=0;
void push()
{
printf("\nenter the value to insert");
scanf("%d",&n);
top=top+1;
a[top]=n;
}
void pop()
{
if(top==0)
{
printf("\nstack is empty");
}
else
{
int item;
item=a[top];
top=top-1;
printf("\npoped item is %d ",item);
}
}
void peep()
{
int i;
printf("\nenter the element position to view from top");
scanf("%d",&i);
if(top-i+1<0)
{
printf("\nunderflow condition");
}
else
{
int x;
x=a[top-i+1];
printf("\nthe %dth element from top is %d",i,x);
}
}
void update()
{
int i,n;
printf("\nenter the position to update");
scanf("%d",&i);
printf("\nenter the item to insert");
scanf("%d",&n);
if(top-i+1<0)
{
printf("\nunderflow condition");
}
else
{
a[top-i+1]=n;
}
}
int x;
while(1)
{
printf("\n1.push");
printf("\n2.pop");
printf("\n3.peep");
printf("\n4.update");
printf("\nenter your choice");
scanf("%d",&x);
switch(x)
{
case 1:
push();
break;
case 2:
pop();
break;
case 3:
peep();
break;
case 4:
update();
break;
default:
printf("\ninvalid choice");
}
}
return(0);
}
|
C
|
#ifndef __LOGIC_H__
#define __LOGIC_H__
/**
* @file
* Schnittstelle des Logik-Moduls.
* Das Modul kapselt die Programmlogik.
*
* @author Christopher Blöcker
* @author Julius Beckmann
*/
#include "types.h"
#include "object.h"
/** Umschaltbare Informationen */
typedef enum {
LOGIC_SWITCHABLE_LIGHT0
, LOGIC_SWITCHABLE_LIGHT1
, LOGIC_SWITCHABLE_CHEAT
, LOGIC_SWITCHABLE_PAUSE
, LOGIC_SWITCHABLE_CUBEROTATION
, LOGIC_SWITCHABLE_RACKETUP
, LOGIC_SWITCHABLE_RACKETDOWN
, LOGIC_SWITCHABLE_RACKETLEFT
, LOGIC_SWITCHABLE_RACKETRIGHT
, LOGIC_SWITCHABLE_CAMUP
, LOGIC_SWITCHABLE_CAMLEFT
, LOGIC_SWITCHABLE_CAMDOWN
, LOGIC_SWITCHABLE_CAMRIGHT
, LOGIC_SWITCHABLE_CAMFORWARD
, LOGIC_SWITCHABLE_CAMBACKWARD
, LOGIC_SWITCHABLE_LIGHTFORWARD
, LOGIC_SWITCHABLE_LIGHTBACKWARD
, LOGIC_SWITCHABLE_LIGHTUP
, LOGIC_SWITCHABLE_LIGHTDOWN
, LOGIC_SWITCHABLE_LIGHTLEFT
, LOGIC_SWITCHABLE_LIGHTRIGHT
, LOGIC_SWITCHABLE_SHADOWS
, LOGIC_SWITCHABLE_SHADOWVOLUMES
, LOGIC_SWITCHABLE_DUMMY
} LogicSwitchable;
/** Vektoren */
typedef enum {
LOGIC_VECTOR_CENTER
, LOGIC_VECTOR_EYE
, LOGIC_VECTOR_CAM
, LOGIC_VECTOR_N
, LOGIC_VECTOR_DUMMY
} LogicVector;
/** Integers */
typedef enum {
LOGIC_INT_LIFES
, LOGIC_INT_POINTS
, LOGIC_INT_DUMMY
} LogicInt;
/** Objekte */
typedef enum {
LOGIC_OBJECT_BALL
, LOGIC_OBJECT_WALLLEFT
, LOGIC_OBJECT_WALLRIGHT
, LOGIC_OBJECT_WALLCENTER
, LOGIC_OBJECT_WALLFRONT
, LOGIC_OBJECT_GROUND
, LOGIC_OBJECT_LIGHT
, LOGIC_OBJECT_RACKET
, LOGIC_OBJECT_CUBE0
, LOGIC_OBJECT_CUBE1
, LOGIC_OBJECT_DUMMY
} LogicObject;
/** Objektsammlungen */
typedef enum {
LOGIC_OBJECTS_LEVEL
, LOGIC_OBJECTS_SHADOWABLEBYLIGHT
, LOGIC_OBJECTS_SHADOWABLEBYBALL
, LOGIC_OBJECTS_DUMMY
} LogicObjects;
/**
* Initialisiert das Spiel und sagt "1".
*
* @return 1.
*/
extern int logicInit(void);
/**
* Berechnet die Szene neu.
*
* @param[in] interval Zeit, die seit dem letzten Aufruf vergangen ist.
*/
extern void logicCalcScene(double interval);
/**
* Gibt die zum Objekttypen t zugeordnete Zeichenfunktion zurück.
*
* @param[in] t Zu zeichnender Objekttyp.
*
* @return zu t gehörende Zeichenfunktion.
*/
extern DrawFunction logicGetDrawFunction(DrawFunctionType t);
/**
* Schaltet s um.
*
* @param[in] s Gibt an, was umgeschaltet werden soll.
*/
extern void logicSwitch(LogicSwitchable s);
/**
* Gibt den Wert von s zurück.
*
* @param[in] s
*
* @return Wert von s.
*/
extern Boolean logicGetSwitchable(LogicSwitchable s);
/**
* Gibt den Vektor v zurück.
*
* @param[in] v
*
* @return Wert von v.
*/
extern Vector3d logicGetVector(LogicVector v);
/**
* Gibt den Wert von i zurück.
*
* @param[in] i
*
* @return Wert von i.
*/
extern int logicGetInt(LogicInt i);
/**
* Gibt einen Zeiger auf das Objekt o zurück.
*
* @param[in] o
*
* @return Zeiger auf o.
*/
extern Object * logicGetObject(LogicObject o);
/**
* Gibt einen Zeiger auf die Objekte os zurück.
*
* @param[in] os
*
* @return Zeiger auf os.
*/
extern Objects * logicGetObjects(LogicObjects os);
#endif
|
C
|
#include "structHeader.h"
/**
* This tests that the element gets correctly matched to the parameter if traced through a call.
* It does this by having two struct elements each accessed in foo and find, where the
* element are in opposite order in the argument list in each one. Each has one
* null-terminated and one non-null-terminated struct element.
**/
void print(char *string) {}
int find(struct foo *f) {
print(f->nonString);
for (int i = 0;; i++) {
if (f->nonString[i] != '\0') {
print("About to break from loop");
break;
}
}
for (int i = 0;; i++) {
if (f->string[i] == '\0') {
print("About to break from loop");
break;
}
}
return 1;
}
int foo(struct foo *f) {
print(f->nonString);
for (int i = 0;; i++) {
if (f->nonString[i] != '\0') {
print("About to break from loop");
break;
}
}
return find(f);
}
|
C
|
/* Escribe un programa con un menú que defina las siguientes funciones y emita los resultados, la
dimensión del vector será de 10 (elementos):
a) Cargar m elementos de un vector por teclado. Deberá considerar que no podrá superar el
máximo de elementos de vector: void cargar(int vect[], int unNum);
b) Leer elementos de un vector hasta encontrar el número entero a. Deberá retornar el
número de elementos que ha leído sin contar el entero a. int leerMarca(int
vect[]);
c) Dado un elemento y dado un vector de enteros, desarrolle una función que devuelva el
número de apariciones del elemento en el vector. int veces(int valor, int
vect[], int unNum);
d) Invertir los elementos del vector sin utilizar otro vector. Por ejemplo, el vector formado por
los enteros: 1 2 3, debe quedar 3 2 1. void invertirOrden(int vect[], int
unNum);
*/
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#define DIM 10
void store(int numbers[]);
int find(int numbers[], int* searchFor);
int countOccurrences(int numbers[], int* match);
void reverse(int numbers[], int right);
int main() {
int numbers[DIM] = {0};
int occurrence = 0;
int searchFor = 0;
int matches = 0;
int match = 0;
char option = '0';
printf(" Welcome.\n");
do {
system("cls");
printf("\n Please, select an option:");
printf("\n 1. Enter numbers into the 'numbers' array");
printf("\n 2. Find the first ocurrence of a number inside the 'numbers' array");
printf("\n 3. Find the number of occurrences of a number inside the 'numbers' array");
printf("\n 4. Reverse all numbers inside of 'numbers' array");
printf("\n 5. Exit\n ");
scanf("%c", &option);
fflush(stdin);
switch (option) {
case '1':
system("cls");
store(&numbers); //-------------------STORE NUMBERS---------------
printf("\n The stored array 'numbers' looks like this:\n");
printf(" [");
for (int i = 0; i < DIM; i++){
printf("%d", numbers[i]);
if(i<DIM-1){
printf(", ");
}
};
printf("]\n\n\n\n");
system("pause");
break;
case '2':
system("cls");
occurrence = find(numbers, &searchFor);//------------------FIND NUMBER----------------
if(occurrence > -1){
printf("\n The first ocurrence of %d appears after %d numbers at numbers[%d]\n\n", searchFor, occurrence, occurrence);
} else {
printf("\n There are no coincidences for %d inside of 'numbers' array.\n\n", searchFor);
};
system("pause");
break;
case '3':
system("cls");
matches = countOccurrences(&numbers, &match);//------------------OCCURRENCE OF NUMBER----------------
if(matches > 0){
printf("\n The number %d appears %d times inside of 'numbers' array.\n\n", match, matches);
} else {
printf("\n There are no coincidences for %d inside of 'numbers' array.\n\n", match);
};
system("pause");
break;
case '4':
system("cls");
reverse(&numbers, DIM-1);//---------------REVERSE NUMBERS-------------------
printf("\n The rearranged array 'numbers' looks like this now:\n");
for (int i =0; i < DIM; i++){
printf("%d\n", numbers[i]);
};
printf("\n\n\n\n");
system("pause");
break;
case '5': //Exit
break;
default:
system("cls");
printf("\n Invalid option.\n\n\n\n");
system("pause");
break;
};
} while (option != '5');
system("pause");
return 0;
};
void store(int numbers[]) {
printf("\n Please, enter the numbers:\n ");
for (int i =0; i < DIM; i++){
scanf("%d", &numbers[i]);
fflush(stdin);
};
};
int find(int numbers[], int *searchFor){
printf("\n Please, enter a number to search for its first ocurrence of.\n ");
scanf("%d", searchFor);
fflush(stdin);
for (int i =0; i < DIM; i++){
if (numbers[i] == (*searchFor)){
return i;
};
};
return -1;
};
int countOccurrences(int numbers[], int* match){
int matches = 0;
printf("\n Please, enter a number to search for all the instances of its ocurrence within numbers array.\n ");
scanf("%d", match);
fflush(stdin);
for (int i =0; i < DIM; i++){
if (numbers[i] == (*match)){
matches++;
};
};
return matches;
};
void reverse(int numbers[], int right) {
int left = 0;
while (left < right){
int temp = numbers[left];
numbers[left] = numbers[right];
left++;
numbers[right] = temp;
right--;
};
};
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>
int main(){
int N;
int A, B;
int jogadorA, jogadorB;
while(1){
scanf("%d", &N);
if(N == 0)
break;
jogadorA = 0;
jogadorB = 0;
while(N>0){
scanf("%d", &A);
scanf("%d", &B);
if(A > B)
jogadorA++;
else if(B > A)
jogadorB++;
N--;
}
printf("%d %d\n", jogadorA, jogadorB);
}
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
void main()
{
int num1, num2, soma;
printf("Informe o primeiro numero\n");
scanf("%d", &num1);
printf("Informe o segundo numero\n");
scanf("%d", &num2);
soma=num1+num2;
if (soma>10)
{
printf("A soma dos valores e: %d",soma);
}
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include<string.h>>
int main(int argc, char *argv[])
{
char a[300],b[300];
int ans=0,s=0,j,l,i,k=0,z;
gets (a);
l=strlen(a);
if (a[1]=='}')
{
printf("0");
ans=1;
}
if (ans==0)
{
ans=1;
b[0]=a[1];
s=1;
for (i=4;i<l;i=i+3)
{
b[s]=a[i];
s++;
for (j=0;j<s-1;j++)
{
if (a[i]==b[j])
{
z=0;
break;
}
else
{
z=1;
}
}
if (z==1)
ans++;
}
}
printf("%d",ans);
return 0;
}
|
C
|
#include "thread.h"
void init_pthread_pool(THREAD_POOL *ts,unsigned int workers,unsigned int maxTaskNum, void *handler){
ts->compartments = Calloc(maxTaskNum,sizeof(void *));
ts->maxTaskNum = maxTaskNum;
ts->front = ts->rear = 0;
ts->workers = workers;
#ifdef __APPLE__
ts->mutex = sem_open("mutex",O_CREAT, S_IRUSR | S_IWUSR, 1);
ts->slots = sem_open("slots",O_CREAT, S_IRUSR | S_IWUSR, maxTaskNum);
ts->tasks = sem_open("items",O_CREAT, S_IRUSR | S_IWUSR, 0);
#else
ts->mutex = (sem_t*)malloc(sizeof(sem_t));
Sem_init(ts->mutex, 0, 1);
ts->slots = (sem_t*)malloc(sizeof(sem_t));
Sem_init(ts->slots, 0, maxTaskNum);
ts->tasks = (sem_t*)malloc(sizeof(sem_t));
Sem_init(ts->tasks, 0, 0);
#endif
pthread_t tid[workers];
for(int i = 0;i < workers ;i++){
int *pid = (int *)malloc(sizeof(int));
*pid = i;
Pthread_create(&tid[i], NULL, handler, (void *)pid);
}
}
void put_pthread_item(THREAD_POOL *ts,void *task){
P(ts->slots);
P(ts->mutex);
int index = (++ts->rear)%(ts->maxTaskNum);
ts->compartments[index] = task;
V(ts->mutex);
V(ts->tasks);
}
void *get_pthread_item(THREAD_POOL *ts){
void *item;
P(ts->tasks);
P(ts->mutex);
int index = (++ts->front)%(ts->maxTaskNum);
item = ts->compartments[index];
V(ts->mutex);
V(ts->slots);
return item;
}
void destroy_pthoread_pool(THREAD_POOL *ts){
Free(ts->compartments);
Free(ts);
}
|
C
|
/*
** builtin_prompt.c for in /home/munoz_d/Bureau/PSU_2015_42sh/src/builtins
**
** Made by David Munoz
** Login <munoz_d@epitech.net>
**
** Started on Wed May 11 02:27:30 2016 David Munoz
** Last update Mon May 23 16:13:44 2016 Lucas
*/
#include "shell.h"
/*
** Custom prompt with the logname and number of lines
*/
void prompt_custom(t_shell *shell, int i)
{
if ((shell->logname = get_logname(shell, "USER")) != NULL)
{
my_putstr(shell->logname);
my_putstr(" - ");
my_put_nbr(i);
my_putstr(" - $> ");
}
else
{
my_putstr("- ");
my_put_nbr(i);
my_putstr(" - $> ");
}
}
|
C
|
#include <stdio.h>
int main() {
int obstacles, removes, speed;
scanf("%d%d%d", &obstacles, &removes, &speed);
/*
* (1200 / speed) * (obstacles / removes + 1) + 2 * removes * (obstacles / removes) * (obstacles / removes + 1) / 2
* (1200 / speed) * (obstacles / removes + 1) + obstacles * (obstacles / removes + 1)
* (1200 / speed + obstacles) * (obstacles / removes + 1)
*/
printf("%d\n", (1200 / speed + obstacles) * (obstacles / removes + 1));
}
|
C
|
/*
* File: ms5803-14ba.c
* Author: Markus Backes
*
* Created on 8. August 2012
*
*/
#include "ms5803-14ba.h"
void calculateTemperature(CalibrationData CB_DATA, MeasurementData MM_DATA, CalculatedValues *values) {
values->dT = MM_DATA.D2 - CB_DATA.C5 * pow(2, 8);
values->TEMP = 2000 + ((values->dT * CB_DATA.C6) / pow(2, 23));
}
void doSecondOrderTemperatureCompensation(CalculatedValues *values) {
int32_t T2;
int64_t OFF2;
int64_t SENS2;
if (values->TEMP < 2000) {
//LOW TEMP
T2 = 3 * pow(values->dT, 2) / pow(2, 33);
OFF2 = 3 * pow((values->TEMP - 2000), 2) / pow(2, 1);
SENS2 = 5 * pow((values->TEMP - 2000), 2) / pow(2, 3);
if (values->TEMP < -1500) {
//VERY LOW TEMP
OFF2 = OFF2 + (7 * pow((values->TEMP + 1500), 2));
SENS2 = SENS2 + (4 * pow((values->TEMP + 1500), 2));
}
} else {
//HIGH TEMP
T2 = 7 * pow(values->dT, 2) / pow(2, 37);
OFF2 = 1 * pow((values->TEMP - 2000), 2) / pow(2, 4);
SENS2 = 0;
}
values->TEMP = values->TEMP - T2;
values->OFF = values->OFF - OFF2;
values->SENS = values->SENS - SENS2;
}
void calculateTemperatureCompensatedPressure(CalibrationData CB_DATA, MeasurementData MM_DATA, CalculatedValues *values) {
values->OFF = (CB_DATA.C2 * pow(2, 16)) + ((CB_DATA.C4 * values->dT) / pow(2, 7));
values->SENS = (CB_DATA.C1 * pow(2, 15)) + ((CB_DATA.C3 * values->dT) / pow(2, 8));
values->P = ((MM_DATA.D1 * values->SENS / pow(2, 21)) - values->OFF) / pow(2, 15);
}
|
C
|
#define NULL ((void*)0)
typedef unsigned long size_t; // Customize by platform.
typedef long intptr_t; typedef unsigned long uintptr_t;
typedef long scalar_t__; // Either arithmetic or pointer type.
/* By default, we understand bool (as a convenience). */
typedef int bool;
#define false 0
#define true 1
/* Forward declarations */
/* Type definitions */
/* Variables and functions */
double INT_MAX ;
double INT_MIN ;
double floor (double) ;
scalar_t__ isnan (double) ;
int jsV_numbertointeger(double n)
{
if (n == 0) return 0;
if (isnan(n)) return 0;
n = (n < 0) ? -floor(-n) : floor(n);
if (n < INT_MIN) return INT_MIN;
if (n > INT_MAX) return INT_MAX;
return (int)n;
}
|
C
|
/****************************/
/**Ryan Evenstad Homework 1**/
/****************************/
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
int main()
{
float r=.25, B=2000.0, P, interest, total_interest=0.0, prev_interest;
int n=1;
printf("Enter monthly payment: ");
scanf("%f", &P);
while(B >= 0)
{
if (n == 1)
{
interest=(r/12)*B;
printf("%d %.2f %.2f\n", n, interest, B);
total_interest=total_interest+interest;
}
else
{
prev_interest=interest;
interest=(r/12)*(B-P+interest);
B=B-P+prev_interest;
printf("%d %.2f %.2f\n", n, interest, B);
if (interest>0)
{
total_interest=total_interest+interest;
}
}
n++;
}
printf("\nTotal Interest Paid: %.2f\n", total_interest);
return 0;
}
|
C
|
#include <stdio.h>
#include <conio.h>
#include <ctype.h>
void main(void)
{
char ch;
printf("Entre com algum texto (digite um ponto para sair).\n");
do {
ch = getch();
if(islower(ch)) ch = toupper(ch);
else ch = tolower(ch);
putchar(ch);
} while (ch!='.');
}
|
C
|
#include <stdlib.h>
#include "../CPU.h"
#include "minunit.h"
CPU cpu;
Memory* mem;
/* tests the reset functionality of the CPU */
MU_TEST(reset){
/* act */
CPU_reset(&cpu);
/* assert */
mu_assert_int_eq(0, cpu.AF);
mu_assert_int_eq(0, cpu.A);
mu_assert_int_eq(0, cpu.z);
mu_assert_int_eq(0, cpu.n);
mu_assert_int_eq(0, cpu.h);
mu_assert_int_eq(0, cpu.cy);
mu_assert_int_eq(0, cpu.F);
mu_assert_int_eq(0, cpu.BC);
mu_assert_int_eq(0, cpu.B);
mu_assert_int_eq(0, cpu.C);
mu_assert_int_eq(0, cpu.DE);
mu_assert_int_eq(0, cpu.D);
mu_assert_int_eq(0, cpu.E);
mu_assert_int_eq(0, cpu.HL);
mu_assert_int_eq(0, cpu.H);
mu_assert_int_eq(0, cpu.L);
mu_assert_int_eq(0x100, cpu.PC);
mu_assert_int_eq(0xFFFE, cpu.SP);
}
/* tests if the struct/union c layout works as intended */
MU_TEST(unionification){
/* act */
CPU_reset(&cpu);
cpu.AF = 0xA952;
/* assert */
mu_assert_int_eq(0xA952, cpu.AF);
mu_assert_int_eq(0x52, cpu.F);
mu_assert_int_eq(0xA9, cpu.A);
mu_assert_int_eq(0, cpu.z);
mu_assert_int_eq(1, cpu.n);
mu_assert_int_eq(0, cpu.h);
mu_assert_int_eq(1, cpu.cy);
}
MU_TEST(instructions_ld_immediate_to_register){
/* act */
CPU_reset(&cpu);
mem->ROM_bank_0[0x100] = 0x06; /* LD B, n */
mem->ROM_bank_0[0x101] = 0x24; /* immediate value */
CPU_process_instruction(&cpu, mem);
/* assert */
mu_assert_int_eq(0x24, cpu.B);
}
MU_TEST(instructions_ld_register_to_register){
/* act */
CPU_reset(&cpu);
cpu.BC = 0xA952;
mem->ROM_bank_0[0x100] = 0x51; /* LD D, C */
mem->ROM_bank_0[0x101] = 0x48; /* LD C, B */
CPU_process_instruction(&cpu, mem);
CPU_process_instruction(&cpu, mem);
/* assert */
mu_assert_int_eq(0xA9, cpu.C);
mu_assert_int_eq(0xA9, cpu.B);
mu_assert_int_eq(0x52, cpu.D);
}
MU_TEST(instructions_ld_register_to_hl_ram){
/* act */
CPU_reset(&cpu);
cpu.B = 0x3C;
cpu.HL = 0xAC5;
mem->ROM_bank_0[0x100] = 0x70; /* LD (HL), B */
CPU_process_instruction(&cpu, mem);
/* assert */
mu_assert_int_eq(0x3C, mem->ROM_bank_0[0xAC5]);
}
MU_TEST(instructions_push){
/* act */
CPU_reset(&cpu);
cpu.SP = 0xFFE;
cpu.BC = 0xABCD;
mem->ROM_bank_0[0x100] = 0xC5; /* PUSH BC */
CPU_process_instruction(&cpu, mem);
/* assert */
mu_assert_int_eq(0xCD, mem->ROM_bank_0[0xFFD]);
mu_assert_int_eq(0xAB, mem->ROM_bank_0[0xFFC]);
}
MU_TEST(instructions_pop){
/* act */
CPU_reset(&cpu);
cpu.SP = 0xFFFC;
mem->ROM_bank_0[0x100] = 0xC1; /* POP BC */
CPU_op_push(&cpu, mem, 0xABCD);
CPU_process_instruction(&cpu, mem);
/* assert */
mu_assert_int_eq(0xABCD, cpu.BC);
}
MU_TEST(instructions_add){
/* act */
CPU_reset(&cpu);
cpu.A = 0x3A;
cpu.B = 0xC6;
mem->ROM_bank_0[0x100] = 0x80; /* ADD A, B */
CPU_process_instruction(&cpu, mem);
/* assert */
mu_assert_int_eq(0x00, cpu.A);
mu_assert_int_eq(1, cpu.z);
mu_assert_int_eq(1, cpu.h);
mu_assert_int_eq(0, cpu.n);
mu_assert_int_eq(1, cpu.cy);
/* act */
CPU_reset(&cpu);
cpu.A = 0x3A;
cpu.B = 0xC5;
mem->ROM_bank_0[0x100] = 0x80; /* ADD A, B */
CPU_process_instruction(&cpu, mem);
/* assert */
mu_assert_int_eq(0xFF, cpu.A);
mu_assert_int_eq(0, cpu.z);
mu_assert_int_eq(0, cpu.h);
mu_assert_int_eq(0, cpu.n);
mu_assert_int_eq(0, cpu.cy);
}
MU_TEST(instructions_sub){
/* act */
CPU_reset(&cpu);
cpu.A = 0x3E;
cpu.E = 0x3E;
cpu.HL = 0x40;
mem->ROM_bank_0[0x100] = 0x93; /* SUB A, E */
CPU_process_instruction(&cpu, mem);
/* assert */
mu_assert_int_eq(0x00, cpu.A);
mu_assert_int_eq(1, cpu.z);
mu_assert_int_eq(0, cpu.h);
mu_assert_int_eq(1, cpu.n);
mu_assert_int_eq(0, cpu.cy);
/* act */
CPU_reset(&cpu);
cpu.A = 0x3E;
cpu.E = 0x3E;
cpu.HL = 0x40;
mem->ROM_bank_0[0x100] = 0xD6; /* sub A, n */
mem->ROM_bank_0[0x101] = 0x0F; /* sub A, n */
CPU_process_instruction(&cpu, mem);
/* assert */
mu_assert_int_eq(0x2F, cpu.A);
mu_assert_int_eq(0, cpu.z);
mu_assert_int_eq(1, cpu.h);
mu_assert_int_eq(1, cpu.n);
mu_assert_int_eq(0, cpu.cy);
/* act */
CPU_reset(&cpu);
cpu.A = 0x3E;
cpu.E = 0x3E;
cpu.HL = 0x1000;
mem->ROM_bank_0[0x100] = 0x96; /* sub A, (HL) */
mem->ROM_bank_0[0x1000] = 0x40;
CPU_process_instruction(&cpu, mem);
/* assert */
mu_assert_int_eq(0xFE, cpu.A);
mu_assert_int_eq(0, cpu.z);
mu_assert_int_eq(0, cpu.h);
mu_assert_int_eq(1, cpu.n);
mu_assert_int_eq(1, cpu.cy);
}
MU_TEST(instructions_and){
/* act */
CPU_reset(&cpu);
cpu.A = 0x5A;
cpu.L = 0x3F;
mem->ROM_bank_0[0x100] = 0xA5; /* AND L */
mem->ROM_bank_0[cpu.HL] = 0x00;
CPU_process_instruction(&cpu, mem);
/* assert */
mu_assert_int_eq(0x1A, cpu.A);
mu_assert_int_eq(0, cpu.z);
mu_assert_int_eq(1, cpu.h);
mu_assert_int_eq(0, cpu.n);
mu_assert_int_eq(0, cpu.cy);
/* act */
CPU_reset(&cpu);
cpu.A = 0x5A;
cpu.L = 0x3F;
mem->ROM_bank_0[0x100] = 0xE6; /* AND n */
mem->ROM_bank_0[0x101] = 0x38; /* immediate value */
mem->ROM_bank_0[cpu.HL] = 0x00;
CPU_process_instruction(&cpu, mem);
/* assert */
mu_assert_int_eq(0x18, cpu.A);
mu_assert_int_eq(0, cpu.z);
mu_assert_int_eq(1, cpu.h);
mu_assert_int_eq(0, cpu.n);
mu_assert_int_eq(0, cpu.cy);
/* act */
CPU_reset(&cpu);
cpu.A = 0x5A;
cpu.L = 0x3F;
mem->ROM_bank_0[0x100] = 0xA6; /* AND (HL) */
mem->ROM_bank_0[cpu.HL] = 0x00;
CPU_process_instruction(&cpu, mem);
/* assert */
mu_assert_int_eq(0x00, cpu.A);
mu_assert_int_eq(1, cpu.z);
mu_assert_int_eq(1, cpu.h);
mu_assert_int_eq(0, cpu.n);
mu_assert_int_eq(0, cpu.cy);
}
MU_TEST(instructions_or){
/* act */
CPU_reset(&cpu);
cpu.A = 0x5A;
mem->ROM_bank_0[0x100] = 0xB7; /* OR L */
mem->ROM_bank_0[cpu.HL] = 0x0F;
CPU_process_instruction(&cpu, mem);
/* assert */
mu_assert_int_eq(0x5A, cpu.A);
mu_assert_int_eq(0, cpu.z);
/* act */
CPU_reset(&cpu);
cpu.A = 0x5A;
mem->ROM_bank_0[0x100] = 0xF6;
mem->ROM_bank_0[0x101] = 0x03; /* immediate value */
mem->ROM_bank_0[cpu.HL] = 0x0F;
CPU_process_instruction(&cpu, mem);
/* assert */
mu_assert_int_eq(0x5B, cpu.A);
mu_assert_int_eq(0, cpu.z);
/* act */
CPU_reset(&cpu);
cpu.A = 0x5A;
mem->ROM_bank_0[0x100] = 0xB6; /* OR (HL) */
mem->ROM_bank_0[cpu.HL] = 0x0F;
CPU_process_instruction(&cpu, mem);
/* assert */
mu_assert_int_eq(0x5F, cpu.A);
mu_assert_int_eq(0, cpu.z);
}
MU_TEST(instructions_xor){
/* act */
CPU_reset(&cpu);
cpu.A = 0xFF;
mem->ROM_bank_0[0x100] = 0xAF; /* XOR A */
mem->ROM_bank_0[cpu.HL] = 0x8A;
CPU_process_instruction(&cpu, mem);
/* assert */
mu_assert_int_eq(0x00, cpu.A);
mu_assert_int_eq(1, cpu.z);
/* act */
CPU_reset(&cpu);
cpu.A = 0xFF;
mem->ROM_bank_0[0x100] = 0xEE; /* XOR n */
mem->ROM_bank_0[0x101] = 0x0F; /* immediate value */
mem->ROM_bank_0[cpu.HL] = 0x8A;
CPU_process_instruction(&cpu, mem);
/* assert */
mu_assert_int_eq(0xF0, cpu.A);
mu_assert_int_eq(0, cpu.z);
/* act */
CPU_reset(&cpu);
cpu.A = 0xFF;
mem->ROM_bank_0[0x100] = 0xAE; /* XOR (HL) */
mem->ROM_bank_0[cpu.HL] = 0x8A;
CPU_process_instruction(&cpu, mem);
/* assert */
mu_assert_int_eq(0x75, cpu.A);
mu_assert_int_eq(0, cpu.z);
}
MU_TEST(instructions_cp){
/* act */
CPU_reset(&cpu);
cpu.A = 0x3C;
cpu.B = 0x2F;
mem->ROM_bank_0[0x100] = 0xB8; /* CP B */
mem->ROM_bank_0[cpu.HL] = 0x40;
CPU_process_instruction(&cpu, mem);
/* assert */
mu_assert_int_eq(0, cpu.z);
mu_assert_int_eq(1, cpu.h);
mu_assert_int_eq(1, cpu.n);
mu_assert_int_eq(0, cpu.cy);
/* act */
CPU_reset(&cpu);
cpu.A = 0x3C;
cpu.B = 0x2F;
mem->ROM_bank_0[0x100] = 0xFE; /* CP n */
mem->ROM_bank_0[0x101] = 0x3C; /* immediate value */
mem->ROM_bank_0[cpu.HL] = 0x40;
CPU_process_instruction(&cpu, mem);
/* assert */
mu_assert_int_eq(1, cpu.z);
mu_assert_int_eq(0, cpu.h);
mu_assert_int_eq(1, cpu.n);
mu_assert_int_eq(0, cpu.cy);
/* act */
CPU_reset(&cpu);
cpu.A = 0x3C;
cpu.B = 0x2F;
mem->ROM_bank_0[0x100] = 0xBE; /* CP B */
mem->ROM_bank_0[cpu.HL] = 0x40;
CPU_process_instruction(&cpu, mem);
/* assert */
mu_assert_int_eq(0, cpu.z);
mu_assert_int_eq(0, cpu.h);
mu_assert_int_eq(1, cpu.n);
mu_assert_int_eq(1, cpu.cy);
}
MU_TEST(instructions_inc){
/* act */
CPU_reset(&cpu);
cpu.A = 0xFF;
mem->ROM_bank_0[0x100] = 0x3C; /* INC A */
CPU_process_instruction(&cpu, mem);
/* assert */
mu_assert_int_eq(0, cpu.A);
mu_assert_int_eq(1, cpu.z);
mu_assert_int_eq(1, cpu.h);
mu_assert_int_eq(0, cpu.n);
/* act */
CPU_reset(&cpu);
cpu.A = 0xFF;
mem->ROM_bank_0[0x100] = 0x34; /* INC (HL) */
mem->ROM_bank_0[cpu.HL] = 0x50;
CPU_process_instruction(&cpu, mem);
/* assert */
mu_assert_int_eq(0x51, mem->ROM_bank_0[cpu.HL]);
mu_assert_int_eq(0, cpu.z);
mu_assert_int_eq(0, cpu.h);
mu_assert_int_eq(0, cpu.n);
}
MU_TEST(instructions_dec){
/* act */
CPU_reset(&cpu);
cpu.L = 0x01;
mem->ROM_bank_0[0x100] = 0x2D; /* DEC L */
CPU_process_instruction(&cpu, mem);
/* assert */
mu_assert_int_eq(0x00, cpu.L);
mu_assert_int_eq(1, cpu.z);
mu_assert_int_eq(0, cpu.h);
mu_assert_int_eq(1, cpu.n);
/* act */
CPU_reset(&cpu);
mem->ROM_bank_0[0x100] = 0x35; /* DEC (HL) */
mem->ROM_bank_0[cpu.HL] = 0x00;
CPU_process_instruction(&cpu, mem);
/* assert */
mu_assert_int_eq(0xFF, mem->ROM_bank_0[cpu.HL]);
mu_assert_int_eq(0, cpu.z);
mu_assert_int_eq(1, cpu.h);
mu_assert_int_eq(1, cpu.n);
}
MU_TEST(instructions_add_16){
/* act */
CPU_reset(&cpu);
cpu.HL = 0x8A23;
cpu.BC = 0x0605;
mem->ROM_bank_0[0x100] = 0x09; /* ADD HL BC */
CPU_process_instruction(&cpu, mem);
/* assert */
mu_assert_int_eq(0x9028, cpu.HL);
mu_assert_int_eq(1, cpu.h);
mu_assert_int_eq(0, cpu.n);
mu_assert_int_eq(0, cpu.cy);
/* act */
CPU_reset(&cpu);
cpu.HL = 0x8A23;
cpu.BC = 0x0605;
mem->ROM_bank_0[0x100] = 0x29; /* ADD HL BC */
CPU_process_instruction(&cpu, mem);
/* assert */
mu_assert_int_eq(0x1446, cpu.HL);
mu_assert_int_eq(1, cpu.h);
mu_assert_int_eq(0, cpu.n);
mu_assert_int_eq(1, cpu.cy);
}
MU_TEST(instructions_inc_16){
/* act */
CPU_reset(&cpu);
cpu.DE = 0x235F;
mem->ROM_bank_0[0x100] = 0x13; /* INC DE */
CPU_process_instruction(&cpu, mem);
/* assert */
mu_assert_int_eq(0x2360, cpu.DE);
}
MU_TEST(instructions_dec_16){
/* act */
CPU_reset(&cpu);
cpu.DE = 0x235F;
mem->ROM_bank_0[0x100] = 0x1B; /* DEC DE */
CPU_process_instruction(&cpu, mem);
/* assert */
mu_assert_int_eq(0x235E, cpu.DE);
}
MU_TEST(instructions_rla){
/* act */
CPU_reset(&cpu);
cpu.A = 0x85;
mem->ROM_bank_0[0x100] = 0x07; /* RLCA */
CPU_process_instruction(&cpu, mem);
/* assert */
mu_assert_int_eq(0x0A, cpu.A);
mu_assert_int_eq(0, cpu.z);
mu_assert_int_eq(0, cpu.h);
mu_assert_int_eq(0, cpu.n);
mu_assert_int_eq(1, cpu.cy);
/* act */
CPU_reset(&cpu);
cpu.A = 0x95;
cpu.cy = 1;
mem->ROM_bank_0[0x100] = 0x17; /* RLA */
CPU_process_instruction(&cpu, mem);
/* assert */
mu_assert_int_eq(0x2B, cpu.A);
mu_assert_int_eq(0, cpu.z);
mu_assert_int_eq(0, cpu.h);
mu_assert_int_eq(0, cpu.n);
mu_assert_int_eq(1, cpu.cy);
}
MU_TEST(instructions_rra){
/* act */
CPU_reset(&cpu);
cpu.A = 0x3B;
mem->ROM_bank_0[0x100] = 0x0F; /* RRCA */
CPU_process_instruction(&cpu, mem);
/* assert */
mu_assert_int_eq(0x9D, cpu.A);
mu_assert_int_eq(0, cpu.z);
mu_assert_int_eq(0, cpu.h);
mu_assert_int_eq(0, cpu.n);
mu_assert_int_eq(1, cpu.cy);
/* act */
CPU_reset(&cpu);
cpu.A = 0x81;
mem->ROM_bank_0[0x100] = 0x1F; /* RRA */
CPU_process_instruction(&cpu, mem);
/* assert */
mu_assert_int_eq(0x40, cpu.A);
mu_assert_int_eq(0, cpu.z);
mu_assert_int_eq(0, cpu.h);
mu_assert_int_eq(0, cpu.n);
mu_assert_int_eq(1, cpu.cy);
}
MU_TEST(instructions_jp){
/* act */
CPU_reset(&cpu);
mem->ROM_bank_0[0x100] = 0xC3; /* JP nn */
mem->ROM_bank_0[0x101] = 0x00;
mem->ROM_bank_0[0x102] = 0xFF;
CPU_process_instruction(&cpu, mem);
/* assert */
mu_assert_int_eq(0xFF00, cpu.PC);
/* act */
CPU_reset(&cpu);
mem->ROM_bank_0[0x100] = 0xC3; /* JP nn */
mem->ROM_bank_0[0x101] = 0x00;
mem->ROM_bank_0[0x102] = 0xFF;
CPU_process_instruction(&cpu, mem);
/* assert */
mu_assert_int_eq(0xFF00, cpu.PC);
}
MU_TEST(instructions_jr){
/* act */
CPU_reset(&cpu);
cpu.A = 0x81;
mem->ROM_bank_0[0x100] = 0x18; /* JR n */
mem->ROM_bank_0[0x101] = 0x7F;
CPU_process_instruction(&cpu, mem);
/* assert */
mu_assert_int_eq(385, cpu.PC);
/* act */
CPU_reset(&cpu);
cpu.A = 0x81;
mem->ROM_bank_0[0x100] = 0x18; /* JR n */
mem->ROM_bank_0[0x101] = 0x00;
CPU_process_instruction(&cpu, mem);
/* assert */
mu_assert_int_eq(0x102, cpu.PC);
}
MU_TEST_SUITE(cpu_suite){
mem = Memory_create();
mem->ROM_bank_0 = (uint8_t*) malloc(sizeof(uint8_t) * 0x10000);
MU_RUN_TEST(reset);
MU_RUN_TEST(unionification);
MU_RUN_TEST(instructions_ld_register_to_register);
MU_RUN_TEST(instructions_ld_immediate_to_register);
MU_RUN_TEST(instructions_ld_register_to_hl_ram);
MU_RUN_TEST(instructions_push);
MU_RUN_TEST(instructions_pop);
MU_RUN_TEST(instructions_add);
MU_RUN_TEST(instructions_sub);
MU_RUN_TEST(instructions_and);
MU_RUN_TEST(instructions_or);
MU_RUN_TEST(instructions_xor);
MU_RUN_TEST(instructions_cp);
MU_RUN_TEST(instructions_inc);
MU_RUN_TEST(instructions_dec);
MU_RUN_TEST(instructions_add_16);
MU_RUN_TEST(instructions_inc_16);
MU_RUN_TEST(instructions_dec_16);
MU_RUN_TEST(instructions_rla);
MU_RUN_TEST(instructions_rra);
MU_RUN_TEST(instructions_jp);
MU_RUN_TEST(instructions_jr);
}
int main(int argc, char *argv[]) {
MU_RUN_SUITE(cpu_suite);
MU_REPORT();
return minunit_fail;
}
|
C
|
#include "Stats.h"
/**********************************************************************************/
void Sats_Init(PATRICIA_Stats *S){
S->measure_words = 0 ;
S->measure_memory = 0 ;
S->measure_comparisons_search = 0 ;
S->measure_comparisons_insert.Compare_insert_char = 0 ;
S->measure_comparisons_insert.Compare_insert_index = 0;
S->measure_comparisons_insert.Compare_insert_internal_node = 0 ;
S->measure_comparisons_insert.Compare_insert_external_node = 0 ;
S->measure_time.time_insertion = 0.0 ;
S->measure_time.time_insertion = 0.0;
}
/***************************************************************************************************************************************/
void Stats_Print_Mount(PATRICIA_Stats S){
printf("Number of words in this tree: %d\n", S.measure_words);
}
/****************************************************************************************************************************************/
void Stats_Print_Memory_Consumption(PATRICIA_Stats S){
printf("Total of memory consumption: %ld kilobytes\n", S.measure_memory);
}
/****************************************************************************************************************************************/
void Stats_Print_Comparisons_Search(PATRICIA_Stats S){
printf("Total of comparison in the search: %ld \n", S.measure_comparisons_search);
}
/*****************************************************************************************************************************************/
void Stats_Print_Comparisons_Insert(PATRICIA_Stats S){
printf("Total of char comparison in the insertion: %ld \n", S.measure_comparisons_insert.Compare_insert_char);
printf("Total of index's comparison in the insertion: %ld \n", S.measure_comparisons_insert.Compare_insert_index);
printf("Total of internal's node comparison in the insertion: %ld \n", S.measure_comparisons_insert.Compare_insert_internal_node);
printf("Total of external's node comparison in the insertion: %ld \n", S.measure_comparisons_insert.Compare_insert_external_node);
}
|
C
|
//Calculate Sum
# include <stdio.h>
int prime_Factor(int);
int main()
{
int num , result;
printf("Enter Num : ");
scanf("%d",&num);
result = prime_Factor(num);
printf("%d",result);
return 0;
}
int prime_Factor(int num){
int ii;
if(num == 1 )return 1;
for(int i = 2 ; i <= num ; i++){
if(num%i == 0){
printf(" %d x ",prime_Factor(num /= i));
ii = i;
break;
}
}
return ii;
}
|
C
|
/*
* An introduction to arrays
* Reverse 10 numbers entered by the user
*/
#include <stdio.h>
int main () {
// array declaration, 10 integers which are collectively
// referred by the variable n
int n[10];
// the indexes start from 0 and till (size-1)
for (int i = 0; i < 10; i ++) {
scanf("%d", &n[i]);
}
for (int i = 9; i >= 0; i --) {
printf("%d ", n[i]);
}
return 0;
}
|
C
|
#include<stdio.h>
#include<conio.h>
int main()
{
int num;
printf("enter an integer number:");
scanf("%d",&num);
if(is power of 2(num))
printf("%d is a number that is the power of 2,"num);
else
printf("%d is not the power of 2",num);
retrun 0;
}
|
C
|
#include "../../includes/math_functions_float.h"
#include "../../includes/verify.h"
#include "float_exp.h"
int main() {
/* REQ-BL-0832
* The exp and expf procedures shall return 1 if the argument x is +-0.
*/
float x = 0.0f;
__VERIFIER_precond_reach();
float res = __ieee754_expf(x);
// x is +0, result shall be 1.
if (res != 1.0f) {
__VERIFIER_error();
return 1;
}
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <allegro.h>
#define ESPACO_QUADRADO 10
int clicouEmQuadrado(int x, int y, int COORDQuadrado[9],int coordMouse[2],int espacoEntreQuadrados)
{
int i = 0,p = 0;
int achou = 0; //comea como falso
while(achou == 0 && p != 8)
{
if(x > COORDQuadrado[p] && x < COORDQuadrado[p+1]-espacoEntreQuadrados) //se o x est entre as coordenadas x de um quadrado
{
while(achou == 0 && i != 8) //s entra aqui se achou o i j
{
if(y > COORDQuadrado[i] && y < COORDQuadrado[i+1]-espacoEntreQuadrados)
{
achou = 1;
coordMouse[0] = i; // 0 = y
coordMouse[1] = p; //1 = x
}
i++;
}
}
p++;
}
return achou;
}
|
C
|
#include<stdio.h>
void func() {
const int a = 10;
printf("a = %d\n",a);
}
int main() {
func();
func();
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
int main (void)
{
int fd;
int ret;
// fd = open ("./truncate_basic.txt", O_WRONLY | O_CREAT | O_TRUNC);
fd = creat ("./truncate_basic.txt", S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP);
if (fd == -1) {
perror ("open");
return (EXIT_FAILURE);
}
write (fd, "Edward Teach was a notorious English pirate.\n", 45);
write (fd, "He was nicknamed Blackbard.\n", 28);
if (close (fd) == -1) {
perror ("close");
return (EXIT_FAILURE);
}
ret = truncate ("./truncate_basic.txt", 45);
if (ret == -1) {
perror ("truncate");
return (EXIT_FAILURE);
}
return (EXIT_SUCCESS);
}
|
C
|
#include <stdlib.h>
#include <stdio.h>
#include <stdbool.h>
#include <stdint.h>
/********************************************/
/* Tables for initial and final permutation */
/********************************************/
// initial permutation
char IP[64] = {
58, 50, 42, 34, 26, 18, 10, 2,
60, 52, 44, 36, 28, 20, 12, 4,
62, 54, 46, 38, 30, 22, 14, 6,
64, 56, 48, 40, 32, 24, 16, 8,
57, 49, 41, 33, 25, 17, 9, 1,
59, 51, 43, 35, 27, 19, 11, 3,
61, 53, 45, 37, 29, 21, 13, 5,
63, 55, 47, 39, 31, 23, 15, 7
};
// final permutation
char FP[64] = {
40, 8, 48, 16, 56, 24, 64, 32,
39, 7, 47, 15, 55, 23, 63, 31,
38, 6, 46, 14, 54, 22, 62, 30,
37, 5, 45, 13, 53, 21, 61, 29,
36, 4, 44, 12, 52, 20, 60, 28,
35, 3, 43, 11, 51, 19, 59, 27,
34, 2, 42, 10, 50, 18, 58, 26,
33, 1, 41, 9, 49, 17, 57, 25
};
/*******************************/
/* Tables for the key schedule */
/*******************************/
// PC-1 table (initial key permutation)
int PC1[56] = {
57, 49, 41, 33, 25, 17, 9,
1, 58, 50, 42, 34, 26, 18,
10, 2, 59, 51, 43, 35, 27,
19, 11, 3, 60, 52, 44, 36,
63, 55, 47, 39, 31, 23, 15,
7, 62, 54, 46, 38, 30, 22,
14, 6, 61, 53, 45, 37, 29,
21, 13, 5, 28, 20, 12, 4
};
// PC-2 table (permutation for generating each subkey)
int PC2[48] = {
14, 17, 11, 24, 1, 5, 3, 28,
15, 6, 21, 10, 23, 19, 12, 4,
26, 8, 16, 7, 27, 20, 13, 2,
41, 52, 31, 37, 47, 55, 30, 40,
51, 45, 33, 48, 44, 49, 39, 56,
34, 53, 46, 42, 50, 36, 29, 32
};
/*********************************/
/* Tables for the round function */
/*********************************/
// expansion box
char E[48] = {
32, 1, 2, 3, 4, 5,
4, 5, 6, 7, 8, 9,
8, 9, 10, 11, 12, 13,
12, 13, 14, 15, 16, 17,
16, 17, 18, 19, 20, 21,
20, 21, 22, 23, 24, 25,
24, 25, 26, 27, 28, 29,
28, 29, 30, 31, 32, 1
};
// substitution boxes
// addressable using xxyyyy where xx are the first and last bits, and yyyy are the middle 4 bits
/*
* changed from original form to make traversal easier with coordinates
*/
const int SBox[8][4][16] = {
{
{14, 4, 13, 1, 2, 15, 11, 8, 3, 10, 6, 12, 5, 9, 0, 7},
{ 0, 15, 7, 4, 14, 2, 13, 1, 10, 6, 12, 11, 9, 5, 3, 8},
{ 4, 1, 14, 8, 13, 6, 2, 11, 15, 12, 9, 7, 3, 10, 5, 0},
{15, 12, 8, 2, 4, 9, 1, 7, 5, 11, 3, 14, 10, 0, 6, 13},
},
{
{15, 1, 8, 14, 6, 11, 3, 4, 9, 7, 2, 13, 12, 0, 5, 10},
{ 3, 13, 4, 7, 15, 2, 8, 14, 12, 0, 1, 10, 6, 9, 11, 5},
{ 0, 14, 7, 11, 10, 4, 13, 1, 5, 8, 12, 6, 9, 3, 2, 15},
{13, 8, 10, 1, 3, 15, 4, 2, 11, 6, 7, 12, 0, 5, 14, 9},
},
{
{10, 0, 9, 14, 6, 3, 15, 5, 1, 13, 12, 7, 11, 4, 2, 8},
{13, 7, 0, 9, 3, 4, 6, 10, 2, 8, 5, 14, 12, 11, 15, 1},
{13, 6, 4, 9, 8, 15, 3, 0, 11, 1, 2, 12, 5, 10, 14, 7},
{ 1, 10, 13, 0, 6, 9, 8, 7, 4, 15, 14, 3, 11, 5, 2, 12},
},
{
{ 7, 13, 14, 3, 0, 6, 9, 10, 1, 2, 8, 5, 11, 12, 4, 15},
{13, 8, 11, 5, 6, 15, 0, 3, 4, 7, 2, 12, 1, 10, 14, 9},
{10, 6, 9, 0, 12, 11, 7, 13, 15, 1, 3, 14, 5, 2, 8, 4},
{ 3, 15, 0, 6, 10, 1, 13, 8, 9, 4, 5, 11, 12, 7, 2, 14},
},
{
{ 2, 12, 4, 1, 7, 10, 11, 6, 8, 5, 3, 15, 13, 0, 14, 9},
{14, 11, 2, 12, 4, 7, 13, 1, 5, 0, 15, 10, 3, 9, 8, 6},
{ 4, 2, 1, 11, 10, 13, 7, 8, 15, 9, 12, 5, 6, 3, 0, 14},
{11, 8, 12, 7, 1, 14, 2, 13, 6, 15, 0, 9, 10, 4, 5, 3},
},
{
{12, 1, 10, 15, 9, 2, 6, 8, 0, 13, 3, 4, 14, 7, 5, 11},
{10, 15, 4, 2, 7, 12, 9, 5, 6, 1, 13, 14, 0, 11, 3, 8},
{ 9, 14, 15, 5, 2, 8, 12, 3, 7, 0, 4, 10, 1, 13, 11, 6},
{ 4, 3, 2, 12, 9, 5, 15, 10, 11, 14, 1, 7, 6, 0, 8, 13},
},
{
{ 4, 11, 2, 14, 15, 0, 8, 13, 3, 12, 9, 7, 5, 10, 6, 1},
{13, 0, 11, 7, 4, 9, 1, 10, 14, 3, 5, 12, 2, 15, 8, 6},
{ 1, 4, 11, 13, 12, 3, 7, 14, 10, 15, 6, 8, 0, 5, 9, 2},
{ 6, 11, 13, 8, 1, 4, 10, 7, 9, 5, 0, 15, 14, 2, 3, 12},
},
{
{13, 2, 8, 4, 6, 15, 11, 1, 10, 9, 3, 14, 5, 0, 12, 7},
{ 1, 15, 13, 8, 10, 3, 7, 4, 12, 5, 6, 11, 0, 14, 9, 2},
{ 7, 11, 4, 1, 9, 12, 14, 2, 0, 6, 10, 13, 15, 3, 5, 8},
{ 2, 1, 14, 7, 4, 10, 8, 13, 15, 12, 9, 0, 3, 5, 6, 11},
},
};
/**************************** start added code*********************************/
/*
* IP(x) = L0R0
* Li=Ri-1
* Ri=Li-1 XOR f(Ri-1,Ki)
* y=IP^-1R16L16
*
* key generation
* Ci=Si(Ci-1)
* Di=Si(Di-1)
* Ki=PC2(CiDi)
*
* S=Left shift (shift 1 position if i=1,2,9,or 16, else shift 2 positions)
* x<<y (left shift) takes 2 numbers, shifts the bits of x by y places to the left
* x>>y (right shift) takes 2 numbers, shifts the bits of x by y places to the right
* & is bitwise AND
* */
uint64_t initBit=0x8000000000000000; //1000
int shiftBy[16]=
{
1,1,2,2,2,2,2,2,1,2,2,2,2,2,2,1
};
int P[32]=
{
16, 7, 20, 21,
29, 12, 28, 17,
1, 15, 23, 26,
5, 18, 31, 10,
2, 8, 24, 14,
32, 27, 3, 9,
19, 13, 30, 6,
22, 11, 4, 25
};
/*
* simple function because I keep forgetting which character is used for XOR
*/
uint64_t XOR(uint64_t a, uint64_t b)
{
return (a^b);
}
/*
* from https://stackoverflow.com/questions/4068033/add-two-integers-using-only-bitwise-operators
* As long as the bit that you're looking at isn't the initial bit (which is just 0, but in hex),
* then the 64bit block=itself+the value of 0 shifted by the number of places indicated by the final position wanted.
*/
void bitwiseAddition(uint64_t init, uint64_t * block, int initPosition, int finPosition)
{
if (((init<<initPosition)&initBit)!=0)
{
*block+=(initBit>>finPosition);
}
}
/*
* if this is the first permutation, then use the IP block
* otherwise, use the FP block
* block used to shift current 64bit block the indicated number of placed
*/
void permuteBlock(uint64_t * block, bool isInitialPermutation)
{
uint64_t temp;
int i;
temp=0;
for (i=0; i<64; i++)
{
if (isInitialPermutation==0)
{
bitwiseAddition(*block, &temp, IP[i]-1, i);
}
else
{
bitwiseAddition(*block, &temp, FP[i]-1, i);
}
}
*block=temp;
}
/*
* depending on the round number,
*/
void keyScheduler(uint64_t * initKey, uint64_t * nextKey, int roundNum)
{
uint64_t leftKey;
uint64_t tempLeftKey;
uint64_t rightKey;
uint64_t tempRightKey;
int i;
leftKey=0;
tempLeftKey=0;
rightKey=0;
tempRightKey=0;
(* nextKey)=0;
if (roundNum==0)
{
for (i=0; i<56; i++)
{
/*if the current position is in the first half of the 56 bit key,
* then if the current key shifted to the left by the number of place indicated by PC1 (for the first round) or just i
* (for the following 15 rounds) is not equal to 0x8000000000000000, the left key will be shifted to the right by i positions
* Otherwise, if the current position is not in the first half (i.e. in the second half),
* this same algorithm is followed, except if the current key shifted to the left by the number
* of place indicated by PC1 is not equal to 0x8000000000000000, the right key will be shifted
* to the right by i%28 positions (i.e. starting over from 1, just in the second half, so 29 = 1)
*/
if (i<28)
{
bitwiseAddition(* initKey, &leftKey, PC1[i]-1, i);
}
else
{
bitwiseAddition(* initKey, &rightKey, PC1[i]-1, i%28);
}
}
}
else
{
for (i=0; i<56; i++)
{
if (i<28)
{
bitwiseAddition(* initKey, &leftKey, i, i);
}
else
{
bitwiseAddition(* initKey, &rightKey, i, i%28);
}
}
}
//depending on whether the round indicates the key should shift by 1 or 2 bits, set the placeholder for the left/right key = the corresponding number of bits
if (shiftBy[roundNum]==1)
{
tempLeftKey=initBit;//aka 1
tempRightKey=initBit;
}
else
{
tempLeftKey=0xC000000000000000; //11 aka 2
tempRightKey=0xC000000000000000;
}
//the left/right placeholder key is now equal to the bitwise AND of the left/right key and 1 or 2 shifted to the right by either 27 or 26
tempLeftKey=(leftKey&tempLeftKey)>>(28-shiftBy[roundNum]);
tempRightKey=(rightKey&tempRightKey)>>(28-shiftBy[roundNum]);
//placeholder key equals itself added to the actual key shifted to the left by 1 or 2 bits
tempLeftKey+=(leftKey<<shiftBy[roundNum]);
tempRightKey+=(rightKey<<shiftBy[roundNum]);
//same as beginning, except with new key ordering
for (i=0; i<56; i++)
{
if (i<28)
{
bitwiseAddition(tempLeftKey, nextKey, i, i);
}
else
{
bitwiseAddition(tempRightKey, nextKey, i%28, i);
}
}
//resets initkey
(* initKey)=0;
/*as long as *nextKey shifted to the left by the number of place indicated by PC2 is not equal to 0x8000000000000000,
* the new initkey (0) is shifted to the right i places
*/
for (i=0; i<48; i++)
{
bitwiseAddition(*nextKey, initKey, PC2[i]-1, i);
}
};
/*
* dummy function
*/
uint64_t singleRoundDES2(uint64_t * leftBlock, uint64_t key)
{
return key;
}
/*
* runs a single round of DES
*/
void singleRoundDES(uint64_t * leftBlock, uint64_t key)
{
uint64_t rightBlock;
uint64_t tempRightBlock;
uint64_t subBlock;
int i;
int j;
int x;
int y;
rightBlock=0;
tempRightBlock=0;
/*
* Let E be such that the 48 bits of its output, written as 8 blocks of 6 bits each, are obtained by selecting the bits in its inputs in order
* E[i]+31-->32 bits
* 6*i
*/
for (i=0; i<48; i++)
{
bitwiseAddition(* leftBlock, &rightBlock, (E[i]+31), i);
}
rightBlock=XOR(rightBlock,key);
for (i=0; i<8; i++)
{
if ((((rightBlock<<6*i)&initBit))==initBit)
{
x=2;
}
else
{
x=0;
}
y=0;
if (((rightBlock<<(6*i+5))&initBit)==initBit)
{
x++;
}
for (j=1; j<5; j++)
{
if (((rightBlock<<(6*i+j))&initBit)==initBit)
{
//basically just shifts the y coordinate to the left or right by 1 place
y+=(2^(4-j));
}
}
/*
* gets specific substitution at coordinate
*/
subBlock=SBox[i][x][y];
subBlock=(subBlock<<(4-(4*i)));
tempRightBlock+=subBlock;
}
rightBlock=tempRightBlock;
tempRightBlock=0;
for (i=0; i<32; i++)
{
bitwiseAddition(rightBlock, &tempRightBlock, P[i]-1, i);
}
rightBlock=tempRightBlock;
rightBlock=XOR(rightBlock,* leftBlock);
(* leftBlock)=((* leftBlock)<<32)+(rightBlock>>32);
};
|
C
|
#include <stdio.h>
#include <time.h>
int main()
{
time_t rawtime;
struct tm* timeinfo;
char buf[80];
time(&rawtime);
printf("%d\n",(int)rawtime);
timeinfo = localtime(&rawtime);
//%p is for A.M. or P.M.
//%T is ISO 8601 time format(HH:MM:SS)
strftime(buf, 80, "%T\n",timeinfo);
puts (buf);
return 0;
}
|
C
|
//// ӡ 100-200 ֮
//
//
//
////#include<stdio.h>
////#include<stdlib.h>
////
////int main()
////{
//// int i = 0;
//// int j = 0;
//// int count = 0; //
////
//// for (i = 100; i <= 200; i++){
//// for (j = 2; j <= i; j++){
//// if (i % j == 0) {
//// break;
//// }
//// }
////
//// // j == i ʱ˵С i ܱ i i
//// if (j == i) {
//// printf("%d ", i); // ӡ
//// count++; // ͳ 100-200 ֮ĸ
//// }
//// }
//// printf("\ncount = %d\n", count);
//// system("pause");
//// return 0;
////}
//
////ӡ100~200֮Ҽ
////dz1ܱ
////һ100200֮ÿһֳ2䱾
////ǰһ֣˹г
////ûΪ
////#include<stdio.h>
////int main()
////{
//// int i = 0;
//// int count = 0;
//// for(i = 100; i <= 200; i++)
//// {
//// int j = 0;
//// for(j = 2; j <= i; j++)
//// {
//// if (i%j == 0)
//// {
//// break;
//// }
//// }
//// if (i == j)
//// {
//// count++;
//// printf("%d ", i);
//// }
//// }
//// printf("\ncount = %d\n", count);
//// system("pause");
//// return 0;
////}
////ʹsqrtԷһŻsqrtƽд
////1a*bʽab֮һСڵab֮Ŀƽ
////#include<stdio.h>
////#include<math.h>
////int main()
////{
//// int i = 0;
//// int count = 0;
//// for (i = 100; i <= 200; i++)
//// {
//// int j = 0;
//// for (j = 2; j <= sqrt(i); j++)
//// {
//// if (i % j == 0)
//// {
//// break;
//// }
//// }
//// if (j > sqrt(i))
//// {
//// count++;
//// printf("%d ", i);
//// }
//// }
//// printf("\ncount = %d\n", count);
//// system("pause");
//// return 0;
////}
////
////#include<stdio.h>
////#include<math.h>
////int main()
////{
//// int i = 0;
//// int count = 0;
//// for(i = 101; i <= 200; i += 2)
//// {
//// int j = 0;
//// for (j = 2; j <= sqrt(i); j++)
//// {
//// if (i % j == 0)
//// {
//// break;
//// }
//// }
//// if (j > sqrt(i))
//// {
//// count++;
//// printf("%d ", i);
//// }
//// }
//// printf("\ncount = %d\n", count);
//// system("pause");
//// return 0;
////}
//
//
////ģʵ
//
//
//#include<stdio.h>
//#include<stdlib.h>
//
//// 庯
//int is_prime(int n)
//{
// int j = 0;
// for (j = 2; j < n; j++) {
// if (n % j == 0) {
// return 0;
// }
// if(j == n){
// return 1;
// }
// }
//}
//
//int main()
//{
// int count = 0;
// int i = 0;
// for (i = 100; i <= 200; i++) {
//
// //
// // is_primt(i) ʾ i
// if (is_prime(i)) {
// printf("%d ", i);
// count++;
// }
// }
// printf("\ncount = %d\n", count);
// system("pause");
// return 0;
//}
|
C
|
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[]) {
int x;
double vet1[10], vet2[10], vet3[10];
for (x = 0; x < 10; x++ ){
printf("\n Vetor 1 na posicao %i = ", x + 1);
scanf("%d", &vet1[x]);
}
for (x = 0; x < 10; x++ ){
printf("\n Vetor 2 na posicao %i = ", x + 1);
scanf("%d", &vet2[x]);
}
for (x = 0; x < 10; x++){
vet3[x] = vet2[x] + vet1[x];
printf("\n Posicao %i = Vet1 %d Vet2 %d Vet3 %d ", x + 1, vet1[x], vet2[x], vet3[x]);
}
return 0;
}
|
C
|
#include <stdbool.h>
#include <stdlib.h>
#include <string.h>
char* itoa(int value, char* str, uint8_t base)
{
int idx_str = 0;
int rem;
bool isNegative = false;
/* Handle 0 explicitely, otherwise empty string is printed for 0 */
if (value == 0)
{
str[idx_str++] = '0';
str[idx_str] = '\0';
return str;
}
// In standard itoa(), negative numbers are handled only with
// base 10. Otherwise numbers are considered unsigned.
if (value < 0 && base == 10)
{
isNegative = true;
value = -value;
}
// Process individual digits
while (value != 0)
{
rem = value % base;
str[idx_str++] = (rem > 9)? (rem-10) + 'A' : rem + '0';
value = value/base;
}
// If number is negative, append '-'
if (isNegative)
str[idx_str++] = '-';
str[idx_str] = '\0'; // Append string terminator
// Reverse the string
strrev(str);
return str;
}
|
C
|
#include <stdio.h>
int main()
{
int T;
scanf("%d", &T);
for(int i = 0; i < T; i++)
{
char question[80];
int sum = 0, score = 1;
scanf("%s", question);
for(int j = 0; question[j] != 0; j++)
{
if(question[j] == 'O')
{
sum += score;
score++;
}
else
score = 1;
}
printf("%d\n", sum);
}
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
void main()
{
int A[25]; //
int R[25]; //
srand(time(NULL));
for (int i = 0; i < 25; i++)
{
//scanf("%d", &A[i]);
A[i] = (rand() % 10) + 10;
R[i] = 1;
}
for (int i = 0; i < 25; i++) {
for (int j = 0; j < 25; j++) {
if (i == j)continue;
if (A[i] < A[j])R[i]++;
}
}
for (int i = 0; i < 25; i++) {
printf("%d 븮 : %d [%d]\n", i, A[i], R[i]);
}
}
|
C
|
#include <stdio.h>
int mul(int a, int b);
int main(void){
int x, y, z;
x = 10; y = 20;
z = mul(x, y); /* 1 */
printf("%d", mul(x,y)); /* 2 */
mul(x, y); /* 3 */
return 0;
}
int mul(int a, int b){
return a*b;
}
|
C
|
/*string de caracteres em linguagem c elas nao existem, por isso é uma convenção entre os
programadores. É um grupo de bytes terminado em um byte de valor 0(zero)*/
#include <stdio.h>
int main(void)
{
char str[] = "lol";
str[0] = 'p';
/*char *str;
str = "lol";
/*str[0] = 'p'; /*Segmentation fault (core dumped)
/*char c;
c = 0; /* ou escreve-se \0 char 0 (zero) com valor 0 zero */
printf("%c %s\n", *str, str);
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <math.h>
int freq[26];
char inp[250];
int main()
{
#ifndef ONLINE_JUDGE
freopen("11577.inp", "r", stdin);
#endif
int n, i, m;
char c;
scanf("%d", &n);
while(n--)
{
scanf(" %[^\n]", inp);
memset(freq, 0, sizeof(freq));
for(i = m = 0; c = *(inp + i); ++i)
{
if(isalpha(c))
{
c = tolower(c) - 'a';
if(++freq[c] > m)
m = *(freq + c);
}
}
for(i=0; i<26; ++i)
if(freq[i]==m)
putchar(i+'a');
putchar('\n');
}
return 0;
}
|
C
|
#include "holberton.h"
/**
* _strpbrk - searches a string for any set of bytes
* @s: string to be searched
* @accept: string to search for
* Return: pointer to search
*/
char *_strpbrk(char *s, char *accept)
{
char *t = s, *acc2 = accept;
int alen = 0;
if (!s || !accept)
return (0);
while (*t)
{
while (*acc2)
{
if (*acc2 == *t)
return (t);
acc2++;
alen++;
}
acc2 = acc2 - alen;
alen = 0;
t++;
}
return (0);
}
|
C
|
#include "include/robot/test/arm.h"
Stepper armStepper(200, ARM_STEPPER_1, ARM_STEPPER_2, ARM_STEPPER_3, ARM_STEPPER_4);
Servo primaryServo, secondaryServo, grabberServo;
bool primary_enabled = true, secondary_enabled = false, grabber_enabled = false;
void setup() {
Serial.begin(9600);
armStepper.setSpeed(50);
primaryServo.attach(SERVO_PRIMARY);
secondaryServo.attach(SERVO_SECONDARY);
grabberServo.attach(SERVO_GRABBER);
primaryServo.write(90);
secondaryServo.write(50);
grabberServo.write(90);
robot::wait_for_connection();
rlogf("Setup complete");
rlogf("Use `T angle` to rotate stepper");
rlogf("Use `P|S|G angle` to set servo angle (primary, secondary, grabber)");
rlogf("Use `D angle` to set stepper angle");
rlogf("Use `R 0-3` to get state of servos");
rlogf("Use `K 1-3` to toggle which servos are active");
}
void loop() {
robot::update_message_buffer();
if (robot::peek_next_opcode() == 'K' || robot::peek_next_opcode() == 'k') {
Message *message = robot::read_message_buffer();
switch (message->payload) {
case 1: primary_enabled = !primary_enabled; break;
case 2: secondary_enabled = !secondary_enabled; break;
case 3: grabber_enabled = !grabber_enabled; break;
}
rlog(primary_enabled ? "Primary enabled" : "Primary NOT enabled");
rlog(secondary_enabled ? "Secondary enabled" : "Secondary NOT enabled");
rlog(grabber_enabled ? "Grabber enabled" : "Grabber NOT enabled");
}
if (robot::peek_next_opcode() == 'P' || robot::peek_next_opcode() == 'p') {
Message *message = robot::read_message_buffer();
rlogf("Moving primary servo");
primaryServo.write(message->payload);
}
if (robot::peek_next_opcode() == 'S' || robot::peek_next_opcode() == 's') {
Message *message = robot::read_message_buffer();
rlogf("Moving secondary servo");
secondaryServo.write(message->payload);
}
if (robot::peek_next_opcode() == 'G' || robot::peek_next_opcode() == 'g') {
Message *message = robot::read_message_buffer();
rlogf("Moving grabber");
grabberServo.write(message->payload);
}
if (robot::peek_next_opcode() == 'T' || robot::peek_next_opcode() == 't') {
Message *message = robot::read_message_buffer();
rlogf("Turning stepper for arm");
rlogi(message->payload);
armStepper.step(message->payload);
}
if (robot::peek_next_opcode() == 'D' || robot::peek_next_opcode() == 'd') {
Message *message = robot::read_message_buffer();
if (primary_enabled) { rlogf("Turning primary"); primaryServo.write(message->payload); }
if (secondary_enabled) { rlogf("Turning secondary"); secondaryServo.write(message->payload); }
if (grabber_enabled) { rlogf("Turning grabber"); grabberServo.write(message->payload); }
}
if (robot::peek_next_opcode() == 'R' || robot::peek_next_opcode() == 'r') {
Message *message = robot::read_message_buffer();
switch (message->payload) {
case 0:
rlog(primary_enabled ? "Primary enabled" : "Primary NOT enabled");
rlog(secondary_enabled ? "Secondary enabled" : "Secondary NOT enabled");
rlog(grabber_enabled ? "Grabber enabled" : "Grabber NOT enabled");
break;
case 1:
rlogi(primaryServo.read());
break;
case 2:
rlogi(secondaryServo.read());
break;
case 3:
rlogi(grabberServo.read());
break;
}
}
if (robot::peek_next_opcode()) {
Message *message = robot::read_message_buffer();
rlogf("Unknown command");
}
delay(100);
}
|
C
|
#include<stdio.h>
#include<stdbool.h>
#include<math.h>
typedef long long int ll;
ll totient[1000001];
ll val[1000001];
void sieve()
{
int i,j;
ll x;
for(i=0;i<=1000000;i++)totient[i]=i;
for(i=2;i<=1000000;i++)
{
if(totient[i]==i)
{
for(j=2*i;j<=1000000;j+=i)
{
totient[j]-=totient[j]/i;
}
}
}
for(i=2;i<=1000000;i++)
{
if(totient[i]==i)totient[i]-=1;
}
for(i=1;i<=1000000;i++)
{
x=i*totient[i];
for(j=i;j<=1000000;j+=i)
{
val[j]+=x;
}
}
}
int main()
{
int t,n,i,sroot;
ll q;
sieve();
scanf("%d",&t);
while(t--)
{
scanf("%d",&n);
q=(1+val[n])*n/2;
printf("%lld\n",q);
}
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include "mylib.h"
#include "bst.h"
void print_key(char *s){
printf("%s\n", s);
}
int main(void){
bst b = bst_new();
char word[256];
while (1==scanf("%255s", word)){
b = bst_insert(b, word);
printf("%d %s\n", bst_search(b, word),word);
}
printf("Preorder\n");
bst_preorder(b, print_key);
printf("Delete\n");
b = bst_delete(b, "This");
printf("Inorder\n");
bst_inorder(b, print_key);
bst_free(b);
return EXIT_SUCCESS;
}
|
C
|
#include"AppController.h"
#include<time.h>
#include<stdio.h>
#define MIN_TEST_SIZE 1000
#define NUMBER_OF_TESTS 5
#define INTERVAL_SIZE 1000
struct _AppController {
int* _testData;
};
AppController* AppController_new(void) {
AppController* _this = NewObject(AppController);
return _this;
}
void AppController_run(AppController* _this)
{
AppView_out(MSG_StartPerformanceMeasuring);
int numberOfTests = NUMBER_OF_TESTS;
int intervalSize = INTERVAL_SIZE;
int maxTestSize = MIN_TEST_SIZE + INTERVAL_SIZE * (NUMBER_OF_TESTS - 1);
_this->_testData = NewVector(int, maxTestSize); // : , ̰ Ҹų ġ?
AppController_generateTestDataByRandomNumbers(_this);
AppView_out(MSG_TitleForUnsortedLinkedList);
int testSize = MIN_TEST_SIZE;
for (int i = 0; i < numberOfTests; i++) {
UnsortedLinkedList* listForTest = UnsortedLinkedList_new();
double timeForAdd = AppController_timeForUnsortedLinkedList_add(_this, listForTest, testSize);
double timeForRemoveMax = AppController_timeForUnsortedLinkedList_removeMax(_this, listForTest, testSize);
double timeForMin = AppController_timeForUnsortedLinkedList_min(_this, listForTest, testSize);
AppController_showResults(_this, testSize, timeForAdd, timeForMin,timeForRemoveMax);
UnsortedLinkedList_delete(listForTest);
testSize += intervalSize;
}
AppView_out(MSG_EndPerformanceMeasuring);
}
void AppController_generateTestDataByRandomNumbers(AppController* _this) {
int maxTestSize = MIN_TEST_SIZE + INTERVAL_SIZE * (NUMBER_OF_TESTS - 1);
srand((unsigned)time(NULL));
for (int i = 0; i < maxTestSize; i++) {
_this->_testData[i] = rand();
}
}
double AppController_timeForUnsortedLinkedList_add(AppController* _this, UnsortedLinkedList* aList, int aTestSize) {
Timer* timer = Timer_new();
double duration = 0;
for (int i = 0; i < aTestSize; i++) {
Timer_start(timer);
if (!UnsortedLinkedList_isFull(aList)) {
UnsortedLinkedList_add(aList, _this->_testData[i]);
}
Timer_stop(timer);
duration += Timer_duration(timer);
}
Timer_delete(timer);
return duration;
}
double AppController_timeForUnsortedLinkedList_removeMax(AppController* _this, UnsortedLinkedList* aList, int aTestSize) {
Element max;
double duration = 0;
Timer* timer = Timer_new();
for (int i = 0; i < aTestSize; i++) {
Timer_start(timer);
if (!UnsortedLinkedList_isEmpty(aList)) {
max = UnsortedLinkedList_removeMax(aList);
}
Timer_stop(timer);
duration += Timer_duration(timer);
}
Timer_delete(timer);
return duration;
}
double AppController_timeForUnsortedLinkedList_min(AppController* _this, UnsortedLinkedList* aList, int aTestSize) {
Element min;
double duration = 0;
Timer* timer = Timer_new();
for (int i = 0; i < aTestSize; i++) {
Timer_start(timer);
if (!UnsortedLinkedList_isEmpty(aList)) {
min = UnsortedLinkedList_min(aList);
}
Timer_stop(timer);
duration += Timer_duration(timer);
}
Timer_delete(timer);
return duration;
}
void AppController_showResults(AppController* _this, int aTestSize, double aTimeForAdd,double aTimeFormin,double aTimeForRemoveMax)
{
char results[255];
sprintf_s(results, sizeof(results), "ũ: %4d, : %6ld, ּڰ:%7ld ִ밪: %7ld\n", aTestSize, (long)aTimeForAdd, (long)aTimeFormin,(long)aTimeForRemoveMax);
AppView_out(results);
}
void AppController_delete(AppController* _this) {
free(_this->_testData);
free(_this);
}
|
C
|
/**
* Given a 2D binary matrix filled with 0's and 1's, find the largest rectangle containing only 1's and return its area.
*/
int largestRectangleArea(char* heights, int heightsSize) {
if (heightsSize == 0) return 0;
int area, maxarea = 0;
int* stack = (int*)malloc(sizeof(int) * (heightsSize + 1));
stack[0] = -1; // important
int top = 0;
for (int i = 0; i < heightsSize; ++i) {
while (top > 0 && heights[i] < heights[stack[top]]) {
area = heights[stack[top]] * (i - stack[top - 1] - 1); // starts with stack[top-1]+1, ends with i-1
if (maxarea < area) maxarea = area;
--top;
}
stack[++top] = i;
}
while (top > 0) {
area = heights[stack[top]] * (heightsSize - stack[top - 1] - 1);
if (maxarea < area) maxarea = area;
--top;
}
free(stack);
return maxarea;
}
int maximalRectangle(char** matrix, int matrixSize, int* matrixColSize) {
int rows = matrixSize;
if (rows == 0) return 0;
int cols = matrixColSize[0];
for (int i = 0; i < cols; ++i) {
if (matrix[0][i] == '1')
matrix[0][i] = 1;
else
matrix[0][i] = 0;
}
int max = largestRectangleArea(matrix[0], cols);
for (int i = 1; i < rows; ++i) {
for (int j = 0; j < cols; ++j) {
if (matrix[i][j] == '1')
matrix[i][j] = 1 + matrix[i - 1][j];
else
matrix[i][j] = 0;
}
int curr = largestRectangleArea(matrix[i], cols);
if (curr > max) max = curr;
}
return max;
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* process.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: tdefresn <tdefresn@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2016/04/06 14:13:27 by tdefresn #+# #+# */
/* Updated: 2016/04/10 17:16:52 by tdefresn ### ########.fr */
/* */
/* ************************************************************************** */
#include "minishell.h"
static char *look_in_path(char *program_name, char **path, int amode)
{
char *full_path;
char *tmp;
int i;
i = 0;
while (path[i])
{
tmp = ft_strjoin(path[i], "/");
full_path = ft_strjoin(tmp, program_name);
ft_strdel(&tmp);
if (access(full_path, amode) >= 0)
return (full_path);
ft_strdel(&full_path);
i++;
}
return (NULL);
}
static void run_process(char *path, char **argv, char **environ)
{
pid_t fork_id;
int pid;
fork_id = fork();
if (fork_id == 0)
{
if (execve(path, argv, environ) < 0)
{
ft_printf("%s: exec format error: %s\n", PROGRAM_NAME, path);
ft_strdel(&path);
exit(1);
}
}
else
wait(&pid);
}
static void clear(char **split)
{
int i;
i = 0;
while (split[i])
ft_strdel(&split[i++]);
ft_memdel((void **)&split);
}
int run_exec(char **argv, t_sh_datas *sh_datas, char **exec_env)
{
char **path;
char *program_name;
char *full_path;
path = get_environ(sh_datas->environ, "PATH=");
program_name = ft_strdup((argv[0][0] != '=') ? &argv[0][0] : &argv[0][1]);
full_path = (path) ? look_in_path(program_name, path, F_OK | X_OK) : NULL;
clear(path);
if (!full_path && access(program_name, F_OK | X_OK) < 0)
{
ft_printf("%s: %s: command not found\n", PROGRAM_NAME, program_name);
ft_strdel(&program_name);
return (-1);
}
if (!exec_env)
exec_env = sh_datas->environ;
run_process((full_path) ? full_path : program_name, argv, exec_env);
if (full_path)
ft_strdel(&full_path);
ft_strdel(&program_name);
return (0);
}
|
C
|
#include <stdio.h>
#include <string.h>
int main() {
char * strings[32];
int index = 0;
//char string[] = "Geia sas. Me lene Petro kai thelw na me paroun stin Microsoft!";
char string[] = "Γειά σας. Με λένε Πέτρο και θέλω να δουλέψω στην Microsoft!";
char * stringp = strtok(string," ");
while(stringp) {
strings[index] = stringp;
index++;
stringp = strtok(NULL," ");
}
int i;
for(i = index -1; i >= 0; i--) {
printf("%s ", strings[i]);
}
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
int main()
{
int a;
a=89;
printf("%d\n",a%2);
return 0;
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_strtrim.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: tisabel <tisabel@student.21-school.ru> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2020/05/19 19:51:41 by tisabel #+# #+# */
/* Updated: 2020/10/18 20:49:22 by tisabel ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
static int ft_set_checker(const char c, char const *set)
{
unsigned int trueth;
unsigned int i;
trueth = 0;
i = 0;
while (set[i] != '\0')
{
if (c == set[i])
trueth = 1;
i++;
}
return (trueth);
}
static int ft_trim_size_counter(char const *s1, char const *set, int end)
{
int i;
unsigned int len;
len = 0;
if (end == 1)
{
i = 0;
while (s1[i] != '\0' && ft_set_checker(s1[i], set) == 1)
{
len++;
i++;
}
}
else
{
i = ft_strlen(s1) - 1;
while (i >= 0 && ft_set_checker(s1[i], set) == 1)
{
len++;
i--;
}
}
return (len);
}
char *ft_strtrim(char const *s1, char const *set)
{
char *trim_str;
unsigned int i;
unsigned int cut;
unsigned int len;
i = 0;
if (!set || !s1)
return (NULL);
cut = ft_trim_size_counter(s1, set, 1);
if (cut == ft_strlen(s1))
len = 0;
else
len = ft_strlen(s1) - (cut + ft_trim_size_counter(s1, set, 2));
trim_str = (char*)malloc(sizeof(char) * (len + 1));
if (!trim_str)
return (NULL);
while (i < len)
{
trim_str[i] = s1[i + cut];
i++;
}
trim_str[i] = '\0';
free((char*)s1);
return (trim_str);
}
|
C
|
/*************************************************************************
> File Name: src/2035.c
> Author: Js
> Created Time: 2016年03月22日 星期二 19时09分16秒
************************************************************************/
#include<stdio.h>
int main()
{
int a, b;
while (scanf("%d%d", &a, &b) != EOF && a && b){
int s = 1;
for (int i = 0; i < b; i++){
s = s * a;
s = s % 1000;
}
printf("%d\n", s);
}
return 0;
}
|
C
|
/*
** EPITECH PROJECT, 2018
** MUL_my_rpg_2018
** File description:
** sword_dir.c
*/
#include "lib.h"
#include "monster.h"
#include "link.h"
#include "zone.h"
int dir_in_angle_range(int ID_dir, double angle, float dir_x)
{
switch (ID_dir) {
case 0: if (angle > 0)
return (1);
break;
case 1: if (angle < 0)
return (1);
break;
case 2: if (dir_x < 0)
return (1);
break;
case 3: if (dir_x > 0)
return (1);
break;
default:
break;
}
return (0);
}
int sword_dir(link_t *link, sfVector2f dir)
{
double rad = cos(-dir.x) / sin(-dir.y);
return (dir_in_angle_range(link->previous_anim - 4, rad, dir.x));
}
void check_monster_attack(link_t *link, monster_t *monst)
{
if (main_time - (float)monst->last_hit > monst->hit_rate &&
link->status == L_ALIVE) {
monst->last_hit = main_time;
link->status = L_DAMAGE;
}
}
void check_monst_link_attack(link_t *link, monster_t *monst,
sfVector3f dist_dir)
{
if (link->event == 1 &&
sword_dir(link, (sfVector2f){dist_dir.y, dist_dir.z}) == 1) {
monst->health -= 1;
monst->pos.x += (dist_dir.y * 20);
monst->pos.y += (dist_dir.z * 20);
}
if (dist_dir.x < 100) {
check_monster_attack(link, monst);
}
}
|
C
|
#include<stdio.h>
int main(){
char x[10];
int i=0,c,s=0;
scanf("%s",&x);
while(x[i]!='\0'){
i++;
}
int findVal(int c){
return 91-c;
}
for(int j=0;j<i;j++){
s=s+(pow(26,i-j-1)*findVal(x[j]));
}
printf("%d",s);
return 0;}
|
C
|
/**
* @file PWM.C
* @brief Funções relacionadas ao PWM
* @author Ricardo Estefano Rosa (restefano)
* @date 09/08/14
* <p>(C) Copyright <b> WEG CRITICAL POWER </b> - Todos os direitos reservados.</p>
* @see http://www.weg.net
*/
#include <plib/pwm.h>
#include <plib/timers.h>
#include "PWM.h"
#include "PINAGEM.h"
extern bit _inibePWM;
void Configura_PWM(){
/**@brief Habilita a geração de PWM em 25kHz.<br>
* A base do PWM1 é TMR2. A base do PWM2 é TMR4.<br>
* Habilita o PWM1, aguarda TMR2 avançar 180 graus e habilita o PWM2.
* @date 15/08/15
* @param Nenhum.
* @return Nada.
* @warning Desabilita as interrupções para garantir a temporização.
* @author Ricardo Estefano Rosa (restefano)
*/
unsigned char Timer2Config; ///< PWM clock source A
unsigned char Timer4Config; ///<PWM clock source B
union PWMDC DCycle;
unsigned char dutycycle = 0;
INTCONbits.GIE = 0;
CCPTMRS = 0b00000010;
Timer2Config = T2_PS_1_4 || TIMER_INT_OFF; //prescale 4
OpenTimer2(Timer2Config);
T2CONbits.TMR2ON = 0; // STOP TIMER2 registers to POR state
PR2 = 159; // Set period
TMR2 = 0;
T2CONbits.TMR2ON = 1; // Turn on PWM1
// Save the dutycycle value in the union
DCycle.lpwm = dutycycle << 6;
// Write the high byte into CCPR1L
CCPR1L = DCycle.bpwm[1];
// Write the low byte into CCP1CON5:4
CCP1CON = (CCP1CON & 0xCF) | ((DCycle.bpwm[0] >> 2) & 0x30);
CCP1CON |= 0b00001100; //ccpxm3:ccpxm0 11xx=pwm mode
while (TMR2 < 73) //73, confirmado para 1/2T de 25kHz
{
}
NOP();
NOP();
NOP();
Timer4Config = T4_PS_1_4 || TIMER_INT_OFF; //prescale 4
OpenTimer4(Timer4Config);
T4CONbits.TMR4ON = 0; // STOP TIMER2 registers to POR state
PR4 = 159; // Set period
T4CONbits.TMR4ON = 1; // Turn on PWM1
// Save the dutycycle value in the union
DCycle.lpwm = dutycycle << 6;
// Write the high byte into CCPR1L
CCPR2L = DCycle.bpwm[1];
// Write the low byte into CCP1CON5:4
CCP2CON = (CCP2CON & 0xCF) | ((DCycle.bpwm[0] >> 2) & 0x30);
CCP2CON |= 0b00001100; //ccpxm3:ccpxm0 11xx=pwm mode
INTCONbits.GIE = 1;
}
void Altera_PWM(unsigned int dutycycle, unsigned char na_int){
/**@brief Altera a largura de pulso do PWM, caso não esteja inibido.
* @date 26/08/15
* @param dutycycle Razão cíclica desejada (x62,5ns). Máx:320, Mín:0.
* @param na_int 1 = está na interrupção, 0 = está fora dela.
* @return Nada.
* @author Ricardo Estefano Rosa (restefano)
*/
if (!na_int) GIE = 0;
union PWMDC DCycle;
unsigned char temp;
if (_inibePWM) { dutycycle = 0; } // Se sobrecorrente, largura = nula
// Save the dutycycle value in the union
DCycle.lpwm = dutycycle << 6;
// Write the high byte into CCPR1L
CCPR1L = DCycle.bpwm[1];
CCPR2L = DCycle.bpwm[1];
temp = ((DCycle.bpwm[0] >> 2) & 0x30);
// Write the low byte into CCP1CON5:4
CCP1CON = (CCP1CON & 0xCF) | temp;
// Write the low byte into CCP1CON5:4
CCP2CON = (CCP2CON & 0xCF) | temp;
if (!na_int) GIE = 1;
}
|
C
|
#include <stdio.h>
int main (void){
int secondi=0;
//SCANSIONE INPUT
scanf("%d", &secondi);
//CHECK INPUT
if (secondi<0){
printf("invalid input\n");
return 0;
}
//CALCOLO & STAMPA ORE, MINUTI E SECONDI
printf("%d h ", secondi/3600);
secondi-= 3600*(secondi/3600);
printf("%d min ", secondi/60);
secondi-= 60*(secondi/60);
printf("%d s\n", secondi);
}
|
C
|
/* Set a real-time scheduling policy, then drop privileges and exec a program.
* This is intended to be a setuid binary. To minimise the attack surface, it
* does not take any command-line arguments, and is hard-coded to set the
* policy to SCHED_RR with priority 1.
*/
#include <unistd.h>
#include <sys/types.h>
#include <stdio.h>
#include <sched.h>
int main(int argc, char * const *argv)
{
int result;
struct sched_param param = {};
if (argc < 2)
{
fputs("Usage: schedrr program [args]\n", stderr);
return 2;
}
param.sched_priority = 1;
result = sched_setscheduler(0, SCHED_RR, ¶m);
if (result != 0)
{
perror("sched_setscheduler failed");
return 1;
}
/* Drop privileges */
result = seteuid(getuid());
if (result != 0)
{
perror("seteuid failed");
return 1;
}
execvp(argv[1], argv + 1);
/* If execvp returns, it definitely failed */
perror("execvp failed");
return 1;
}
|
C
|
#include <stdio.h>
#include "LPC17xx.H" /* LPC17xx definitions */
#include "Serial.h"
/* 1. Store the Question, correct answer and wrong answer all as individual arrays
e.g. uint8_t questions[] = "......" */
/* 2. write a void putstring() function to send a string to UART0 by calling the function of int SER_PutChar (int c)
void putstring(.....){
} */
/*----------------------------------------------------------------------------
Main Program
*----------------------------------------------------------------------------*/
int main (void) {
uint8_t choice;
SER_Init();
while(1)
{
/* 3. - Send question array string to UART0, to print the question
- Store the input option(answer) in choice variable declared above
- If Input option is 'c' or 'C', Send correctanswer array string to UART0,
to print the correctanswer, else send wronganswer array string to UART0
*/
}
return 0;
}
|
C
|
/*
** utils.c
**
** This holds some utilities to allocate memory, and other stuff.
**
*/
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
#include <errno.h>
#include "utils.h"
#include "R.h"
/* Required for Microsoft? */
#include <stddef.h>
extern void dsort_ (double *vector, long *length, long *flag);
#ifdef USE_R_ALLOC
extern char *R_alloc();
void do_nothing();
#define calloc R_alloc
#define free do_nothing
#endif
#ifdef CALL_FROM_R
#define Slong int
#else
#define Slong long
#endif
#define TRUE 1
#define FALSE 0
/*============================ count_lines ===========================*/
int count_lines (FILE *in_file, long starting_point, unsigned long *line_count)
{
/*
** This counts how many lines there are in a file, starting at "starting_
** point, by reading all the way through it and counting new-line characters.
** How handy.
*/
char in_buffer[100]; /* We read up to 100 characters at a time. */
int i; /* Indexes in_buffer */
long char_count; /* How many did we get? */
long pointer_at_input; /* Where were we at the start? */
*line_count = 0L;
char_count = 1; /* set this so as to enter the loop the first time */
/* Save the point where the file pointer is now. */
pointer_at_input = ftell (in_file);
/* Now position to "starting_point." */
fseek (in_file, starting_point, 0);
/* Loop: read up to 100 characters, count new lines, resume if not EOF */
while (char_count > 0)
{
char_count = fread (in_buffer, 1, 100, in_file);
for (i = 0; i < char_count; i++)
if (in_buffer[i] == '\n')
(*line_count)++;
}
/* Reset the file, as a courtesy. */
fseek (in_file, pointer_at_input, 0);
return (0);
}
/*====================== alloc_some_double_pointers =====================*/
int alloc_some_double_pointers (double ***my_array, unsigned long how_many)
{
/* Allocate "how_many" double pointers in memory. */
if ( (*my_array = (double **) calloc (how_many, sizeof (double *))) == NULL)
{
Rprintf ("Unable to alloc %lu pointers-to-double\n", how_many);
return (-1);
}
return (0);
}
/*========================= alloc_some_doubles =====================*/
int alloc_some_doubles (double **my_array, unsigned long how_many)
{
/* Allocate "how_many" doubles in memory. */
if ( (*my_array = (double *) calloc (how_many, sizeof (double))) == NULL)
{
Rprintf ("Unable to alloc %lu doubles, error %i\n", how_many, errno);
return (-1);
}
return (0);
}
/*========================= alloc_some_floats =====================*/
int alloc_some_floats (float **my_array, unsigned long how_many)
{
/* Allocate "how_many" floats in memory. */
if ( (*my_array = (float *) calloc (how_many, sizeof (float))) == NULL)
{
Rprintf ("Unable to alloc %lu floats\n", how_many);
return (-1);
}
return (0);
}
/*========================= alloc_some_long_ptrs =====================*/
int alloc_some_long_ptrs (long ***my_array, unsigned long how_many)
{
/* Allocate "how_many" long ptrs in memory. */
if ( (*my_array = (long **) calloc
(how_many, sizeof (long *))) == NULL)
{
Rprintf ("Unable to alloc %li long ptrs\n", how_many);
return (-1);
}
return (0);
}
/*========================= alloc_some_longs =====================*/
int alloc_some_longs (long **my_array, unsigned long how_many)
{
/* Microsoft */
/* size_t my_size = (size_t) how_many * sizeof (long); */
/* Allocate "how_many" longs in memory. */
if ( (*my_array = (long *) calloc (how_many, sizeof (long))) == NULL)
/* (how_many, (unsigned) sizeof (long))) == NULL) */
{
Rprintf ("Unable to alloc %lu longs\n", how_many);
return (-1);
}
return (0);
}
/*========================= alloc_some_Slongs =====================*/
int alloc_some_Slongs (Slong **my_array, unsigned long how_many)
{
/* Microsoft */
/* size_t my_size = (size_t) how_many * sizeof (long); */
/* Allocate "how_many" longs in memory. */
if ( (*my_array = (Slong *) calloc (how_many, sizeof (Slong))) == NULL)
/* (how_many, (unsigned) sizeof (Slong))) == NULL) */
{
Rprintf ("Unable to alloc %lu Slongs\n", how_many);
return (-1);
}
return (0);
}
/*========================= alloc_some_u_longs =====================*/
int alloc_some_u_longs (unsigned long **my_array, unsigned long how_many)
{
/* Allocate "how_many" unsigned longs in memory. */
if ( (*my_array = (unsigned long *) calloc
(how_many, sizeof (unsigned long))) == NULL)
{
Rprintf ("Unable to alloc %lu u_longs\n", how_many);
return (-1);
}
return (0);
}
/*========================= alloc_some_ints ========================*/
int alloc_some_ints (int **my_array, unsigned long how_many)
{
/* Allocate "how_many" ints in memory. */
if ( (*my_array = (int *) calloc (how_many, sizeof (int))) == NULL)
{
Rprintf ("Unable to alloc %lu ints\n", how_many);
return (-1);
}
return (0);
}
/*========================= alloc_some_char_ptrs ========================*/
int alloc_some_char_ptrs (char ***my_array, unsigned long how_many)
{
/* Allocate "how_many" char ptrs in memory. */
if ( (*my_array = (char **) calloc (how_many, sizeof (char *))) == NULL)
{
Rprintf ("Unable to alloc %lu char_ptrs\n", how_many);
return (-1);
}
return (0);
}
/*========================= alloc_some_chars ========================*/
int alloc_some_chars (char **my_array, unsigned long how_many)
{
/* Allocate "how_many" char in memory. */
if ( (*my_array = (char *) calloc (how_many, sizeof (char))) == NULL)
{
Rprintf ("Unable to alloc %lu chars\n", how_many);
return (-1);
}
return (0);
}
/*========================= provisional_means ===========================*/
int provisional_means (double *new_vector, long vector_length, long status,
double *mean, double *var)
{
/*
** In this function, we compute component-wise means and variances of sets
** of vectors by the method of provisional means. The first time through,
** and indeed every time, "vector_length" should hold the number of elements
** in the vector. The calling function also supplies pointers to vectors
** of results. This may be keeping track of several "groups" of vectors at
** once (since the only information it needs to keep is the number of vectors
** supplied). "Status" can be QUIT (meaning both quit and be prepared to
** initialize next time through), END_GROUP (meaning compute the results for
** this group), INCREMENT (meaning all groups are though, so increment the
** count) or none of these (process one vector for one group).
*/
static int initialized = FALSE;
static long number_count = 0L; /* How many vectors are there? */
double previous_prov_mean; /* Don't you love long variable names? */
long i;
/*
** If it's quitting time, return the provisional mean. Since prov_var
** holds the numerator, divide by (n-1). Print. If there are no numbers,
** set mean =0, var = 0.
*/
if (!initialized)
{
initialized = TRUE;
if (vector_length < 1)
return (ILLEGAL_LENGTH);
number_count = 1L;
for (i = 0L; i < vector_length; i ++)
{
mean[i] = 0.0;
if (var != (double *) NULL)
var[i] = 0.0;
}
if (status != INCREMENT)
status = DONT_QUIT;
}
if (status == QUIT || status == END_GROUP)
{
if (var != (double *) NULL)
for (i = 0L; i < vector_length; i++)
{
/*
** Each time through, number_count is incremented at the bottom of the loop. That means
** when it's finally time to quit it's one too big. We subtract one to get the correct
** number_count, and one more to get the inbiased estimate.
*/
var[i] /= (number_count - 2);
}
if (status == QUIT)
{
number_count = 1L;
initialized = FALSE;
}
return (0);
}
/*
** Add 1 to the count if necessary; compute new provisional mean and variance.
*/
for (i = 0L; i < vector_length; i++)
{
previous_prov_mean = mean[i];
mean[i] += (new_vector[i] - mean[i]) / number_count;
if (var != (double *) NULL)
var[i] += (new_vector[i] - previous_prov_mean)
* (new_vector[i] - mean[i]);
}
if (status == INCREMENT)
number_count++;
return (0);
} /* end "provisional_means" */
/*========================= compute_mad ===========================*/
double compute_mad (double *in_vector, long vector_length, long *status)
{
/*
** Compute the median absolute deviation of in_vector in several steps. First sort
** and compute the median; then compute the absolute deviations from the median, sort
** again, and compute the median of those deviations. We don't know in advance whether
** vector_length will be odd or even, so we take the mean of the two central elements
** (which will be the same if vector_length is odd).
*/
double *sorted_data, median, mad;
long i;
long sort_ascending = 1L;
int center_index_1, center_index_2;
*status = 0L;
center_index_1 = (int) floor ( ((double) vector_length + 1.0)/ 2.0) - 1;
center_index_2 = (int) ceil ( ((double) vector_length + 1.0)/ 2.0) - 1;
if (alloc_some_doubles (&sorted_data, (unsigned) vector_length))
{
*status = -1L;
return (0.0);
}
/*
** Load the data into "sorted_data"
*/
for (i = 0; i < vector_length; i++)
sorted_data[i] = in_vector[i];
/* Sort once in preparation for finding the median. */
dsort_ (sorted_data, &vector_length, &sort_ascending);
median = (sorted_data[center_index_1] + sorted_data[center_index_2]) / 2.0;
for (i = 0; i < vector_length; i++)
sorted_data[i] = fabs (sorted_data[i] - median);
/* Sort a second time. The median of these is the MAD */
dsort_ (sorted_data, &vector_length, &sort_ascending);
mad = (sorted_data[center_index_1] + sorted_data[center_index_2]) / 2.0;
free (sorted_data);
return (mad);
} /* end "compute_mad" */
#ifdef USE_R_ALLOC
void do_nothing (void *ptr)
{
}
#endif
|
C
|
#include "holberton.h"
#include <stdio.h>
#include <stdlib.h>
/**
* main - program that prints its name, followed by a new line
*
* @argc: argument count for main
* @argv: vector to the arguments
*
* Return: void
*/
int main(int argc, char **argv)
{
if (argc >= 1)
printf("%s\n", argv[0]);
return (0);
}
|
C
|
#include "timeds.h"
#include "p24FJ64GA002.h"
#include "tick.h"
/******************************************************************
ʱѾADתˣתõݽһһУٽд
÷ֻҪADgetDataͿˡ
******************************************************************/
#include "common.h"
BYTE Second;
BYTE Minute;
BYTE Hour;
BYTE Day;
BYTE Month;
BYTE Year;
extern DWORD mSeconds;
TICK StartmSeconds;
RTIME ServerTime;
RTIME CurrentSysTime;
/********************ʱʼֹ*************************/
void CurSysTimeInit(void)
{
CurrentSysTime.year = 0xff;
CurrentSysTime.month = 0x07;
CurrentSysTime.day = 0x07;
CurrentSysTime.hour = 0x12;
CurrentSysTime.minute = 0x01;
CurrentSysTime.second = 0x01;
}
/****************㵱ǰʱ******************************/
void CalCurSysTime(DWORD time_sys , RTIME *p)//ǰϵͳʱ
{
WORD hour,minute,second;
time_sys /= 100; //뻻
hour = (WORD)(time_sys / 3600);//Сʱ
minute = (WORD)(time_sys / 60);//
minute = minute % 60;//ʾķȥСʱ
second = (WORD)(time_sys % 60); //ʾ
p->day = ServerTime.day;
p->hour = ServerTime.hour + (BYTE)hour;
p->minute = ServerTime.minute + (BYTE)minute;
p->second = ServerTime.second + (BYTE)second;
if(p->second >= 60)
{
p->second %= 60;
p->minute += 1;
}
if (p->minute >= 60)
{
p->minute %= 60;
p->hour += 1;
}
if(p->hour >= 24)
{
p->hour %= 24;
p->day += 1;
}
}
/********************ϵͳʵʱ**************************/
void SysRealTime(void)
{
if(CurrentSysTime.year!=0xFF)
{
CalCurSysTime((mSeconds-StartmSeconds) , &CurrentSysTime);
}
}
TICK GetmSecinds(void)
{
return mSeconds;
}
|
C
|
/* ************************************************************************** */
/* */
/* :::::::: */
/* ft_read_connections.c :+: :+: */
/* +:+ */
/* By: ayundina <marvin@codam.nl> +#+ */
/* +#+ */
/* Created: 2019/09/15 13:38:12 by ayundina #+# #+# */
/* Updated: 2019/09/15 13:38:16 by ayundina ######## odam.nl */
/* */
/* ************************************************************************** */
#include "lem_in.h"
/*
** ft_insert_new_edge() function adds a room (connection) to an array of edges
** (connections). It first checks if the given room (connection) is already
** present in the array.
**
** Param 1: t_room ***edges is a pointer to array of edges (connections) where
** a new room (connection) have to be added.
**
** Param 2: t_room *room_to_connect is a new room (connection) that have to be
** added to the array of edges.
**
** Returns: none.
*/
static void ft_insert_new_edge(t_room ***edges, t_room *room_to_connect)
{
int i;
i = 0;
while (i < N_CONNECTIONS)
{
if ((*edges)[i] == room_to_connect)
return ;
if ((*edges)[i] == NULL)
{
(*edges)[i] = room_to_connect;
return ;
}
i++;
}
}
/*
** ft_malloc_n_copy_connection() function allocates an array of edges
** (connections) for each room if it wasn't allocated before (the check if
** an array needs to be allocated happens in ft_malloc_arr_of_rooms() function)
** Then each room gets a copy of a room it connected to.
**
** Param 1: t_lem *lem is a struct that holds all the necessary data
** about the given map with ants, rooms, connections and later generated
** possible paths for the execution.
**
** Param 2: unsigned int room_one is an index of the first room in given edge
** in the array of all given rooms.
**
** Param 3: unsigned int room_two is an index of the first room in given edge
** in the array of all given rooms.
**
** Returns: none.
*/
static void ft_malloc_n_copy_connection(t_lem *lem, unsigned room_one, \
unsigned room_two)
{
ft_malloc_arr_of_rooms(&lem->map->room_arr[room_one]->edges, \
N_CONNECTIONS, 1);
ft_malloc_arr_of_rooms(&lem->map->room_arr[room_two]->edges, \
N_CONNECTIONS, 1);
ft_insert_new_edge(&lem->map->room_arr[room_one]->edges, \
lem->map->room_arr[room_two]);
ft_insert_new_edge(&lem->map->room_arr[room_two]->edges, \
lem->map->room_arr[room_one]);
}
/*
** ft_copy_connections() function receives a line as "room_1-room_2" that
** means that "room_1" is connected to "room_2". Both names of rooms are sent
** to get their hashed index, that is index in the array of rooms.
** In ft_malloc_n_copy_connection() function for each room, array of
** connections is allocated if it doesn't exist yet. And "room_1" is copied
** into "room_2" array of edges and "room_2" is copied into "room_1" array
** of edges.
**
** Param 1: char *line is a pointer to a string to save a line from
** the given file.
**
** Param 2: t_lem *lem is a struct that holds all the necessary data
** about the given map with ants, rooms, connections and later generated
** possible paths for the execution.
**
** Returns: none or error message and exits if an error occurred.
*/
static void ft_copy_connections(char *line, t_lem *lem)
{
char **edge;
unsigned room_one;
unsigned room_two;
edge = ft_strsplit(line, '-');
if (edge[1] == NULL)
exit(ft_printf("lem-in ERROR: invalid connection: %s\n", line));
room_one = ft_hash(edge[0], NULL);
room_two = ft_hash(edge[1], NULL);
if (lem->map->room_arr[room_one] == NULL \
|| lem->map->room_arr[room_two] == NULL)
exit(ft_printf("lem-in ERROR: invalid connection: %s\n", line));
ft_malloc_n_copy_connection(lem, room_one, room_two);
ft_strdel(&edge[0]);
ft_strdel(&edge[1]);
free(edge);
edge = NULL;
}
/*
** ft_read_connections() function checks if previosly parsed rooms has start
** and end rooms. The first encountered connection passed to
** ft_read_connections() with "*line" variable.
** Each room node has "**edges", which is array of rooms, array that holds
** pointers to rooms. All the rooms saved only once in a linked list.
** Other references to rooms are containing adresses of the rooms.
** In ft_copy_connections() function line with connection is parsed and
** both rooms get a new edge in their array of edges
** (edge is same as connection).
** Check at the end of ft_read_connections() is if start and end room
** are having connections.
**
** Param 1: char *line is a pointer to a string to save a line from
** the given file.
**
** Param 2: t_lem *lem is a struct that holds all the necessary data
** about the given map with ants, rooms, connections and later generated
** possible paths for the execution.
**
** Returns: none or error message and exits if an error occurred.
*/
void ft_read_connections(char *line, t_lem *lem)
{
ft_printf("%s\n", line);
if ((lem->map->start_room_ind == 0 \
&& lem->map->room_arr[lem->map->start_room_ind] == NULL) \
|| (lem->map->end_room_ind == 0 \
&& lem->map->room_arr[lem->map->end_room_ind] == NULL))
exit(ft_printf("lem-in ERROR: invalid map - no start or end room\n"));
ft_copy_connections(line, lem);
ft_strdel(&line);
while (get_next_line(lem->fd_read, &line) == 1)
{
if (!line)
exit(ft_printf("lem-in ERROR: get_next_line failed\n"));
ft_printf("%s\n", line);
if (ft_strchr(line, '-'))
ft_copy_connections(line, lem);
ft_strdel(&line);
}
if (lem->map->room_arr[lem->map->start_room_ind]->edges == NULL \
|| lem->map->room_arr[lem->map->end_room_ind]->edges == NULL)
exit(ft_printf("lem-in ERROR: invalid map - start or end \
is not connected\n"));
ft_delete_dead_ends(lem->map, lem->map->arr_size, 0, 0);
}
|
C
|
#include <stdio.h>
#include <stdlib.h> //para exit(1)
#include <conio.h> //para funcion getche()
#define ARCH ".\\bin.dat"
#define ESC 27
/*LECTURA-ESCRITURA DE ARCHIVOS BINARIOS que tiene datos*/
/*wb = lecto/escritura. Si no existe->Crea. Si Existe->Pisa
rb = lectura. Posicin al comienzo.
ab = Si no existe->Crea. Si Existe->Agrega al final
*/
struct a {
char nombre[31];
int edad;
};
int main(void) {
FILE *bin;
struct a pers, pers1;
int cant;
/*Para crear un archivo por primera vez se debe usar el modo w,
pero primero nos debemos asegurar que el archivo no exista,
ya que en ese caso el contenido del archivo se pisa.*/
if ((bin = fopen(ARCH, "rb+")) == NULL) {
if ((bin = fopen(ARCH, "wb+")) == NULL) {
printf("No se pudo abrir el archivo");
exit(1);
}
}
/*cargo la estructura y escribo el archivo*/
do {
printf("\nIngrese el nombre: ");
gets(pers.nombre);
printf("Ingrese la edad: ");
scanf("%d", &pers.edad);
fflush(stdin);
/*int fseek (FILE* fichero, long desplazamiento, int desde);
Desplaza la posicin actual de lectura/escritura del fichero
a otro punto. El desplazamiento puede ser positivo (avanzar),
cero o negativo (retroceder).
La posicin de origen se puede indicar con la ayuda de tres
constantes:
SEEK_SET (0, comienzo),
SEEK_CUR (1, actual),
SEEK_END (2, final)*/
fseek(bin, 0L, SEEK_END);
fwrite(&pers, sizeof(pers), 1, bin);
printf("\nPresione ESC para terminar");
} while ((getche()) != ESC);
//se lleva el indicador de posicin al principio para comenzar a leer
rewind(bin);
while (!feof(bin)) {
cant = fread(&pers1, sizeof(pers1), 1, bin);
if (cant != 1) {
if (feof(bin)) {
break;
} else {
printf("No leyo el ultimo registro");
break;
}
}
printf("\n%s\t%d", pers1.nombre, pers1.edad);
}
fclose(bin);
getch();
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#define MAX 3
int main(){
float salario[MAX], soma_salario, soma_filhos, maiorSalario, mediaSalario, mediaNfilhos, porcentagemacima1000;
int i, n_filhos[MAX], cont1000;
maiorSalario=0; //Vou arbritar um valor inicial para fazer comparacao
i=1;
cont1000=0;
soma_salario=0;
soma_filhos=0;
printf("------Serao 10 perguntas------ \n");
printf("\n");
do{
printf("------Programa Estatistico------ \n");
///
printf("pergunta no: %d \n", i);
printf("Digite o valor do salario: \n");
scanf("%f", &salario[i]);
if(salario[i]<0){
break;
}
if(salario[i]>1000){ //verificando aqueles que ganham acima de 1000
cont1000=cont1000+1;
}
printf("Digite o numero de filhos: \n");
scanf("%d", &n_filhos[i]);
soma_salario=soma_salario+salario[i];
soma_filhos=soma_filhos+n_filhos[i];
//
if(maiorSalario<salario[i]){ //verificando o maior salario
maiorSalario=salario[i];
}
//
//printf("indice: %d \n", i);
i++;
}while(i<=MAX);
i=i-1;
printf("+++++++++++++++++++++++++++ \n");
mediaSalario=soma_salario/i; //media do total dos salarios
mediaNfilhos=soma_filhos/i; //media do total do numero de filhos
porcentagemacima1000=((cont1000*1.0)/i)*100; //porcentagem dos que ganham acima de R$ 1000.00
printf("Foram %d entrevistados \n", i);
printf("A media dos salarios e: %.2f \n", mediaSalario);
printf("A media do numero de filhos e: %.2f \n", mediaNfilhos);
printf("O maior salario e: %.2f \n", maiorSalario);
printf("A quantidade de salarios acima de R$ 1000.00 e: %d \n", cont1000);
printf("A porcentagem dos que ganham acima de R$1000.00 e: %.1f%% \n", porcentagemacima1000);
printf("+++++++++++++++++++++++++++ \n");
}
|
C
|
#include "syscall.h"
static inline unsigned
strlen(const char * s)
{
unsigned i;
for (i = 0; s[i] != '\0'; i++);
return i;
}
int
main()
{
char * filename = "A.txt";
char * filecontent = "Hola Mundo";
Create(filename);
OpenFileId o = Open(filename);
Write(filecontent, strlen(filecontent), o);
Close(o);
}
|
C
|
#include<stdio.h>
#include<math.h>
int main(){
float a, b, c, d, t, tich, tbc;
printf("Nhap so thuc thu nhat: ");
scanf("%f", &a);
printf("Nhap so thuc thu hai: ");
scanf("%f", &b);
printf("Nhap so thuc thu ba: ");
scanf("%f", &c);
printf("Nhap so thuc thu bon: ");
scanf("%f", &d);
t = a + b + c + d;
tich = a * b * c * d;
tbc = t / 4;
printf("\nTong cua bon so nguyen la: %f", t);
printf("\nTich cua bon so nguyen la: %f", tich);
printf("\nTrung binh cong cua bon so nguyen la: %f", tbc);
return 0;
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* main.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: groussel <groussel@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2018/04/07 16:43:56 by groussel #+# #+# */
/* Updated: 2018/04/22 11:46:18 by groussel ### ########.fr */
/* */
/* ************************************************************************** */
#include "fillit.h"
#include "libft.h"
void ft_print(char **map)
{
int r;
int i;
r = 0;
i = 0;
while (map[r])
{
while (map[r][i])
{
ft_putchar(map[r][i]);
i++;
}
ft_putchar('\n');
i = 0;
r++;
}
}
void ft_strerror(t_shapes *shapes, char *square, int fd, int code)
{
if (code == 1)
ft_putendl("usage: ./fillit source_file");
else
ft_putendl("error");
free(shapes);
free(square);
close(fd);
exit(EXIT_FAILURE);
}
int check_empty_or_bad_ending(int fd, t_shapes *shapes)
{
char str[2];
char *result;
int firstime;
firstime = 0;
while (read(fd, str, 1) > 0)
{
str[1] = '\0';
if (!firstime)
result = ft_strdup(str);
if (!(result = ft_strjoin(result, str)))
return (0);
firstime++;
}
if (firstime == 0)
ft_strerror(shapes, result, fd, 2);
firstime = ft_strlen(result);
if (firstime < 20)
ft_strerror(shapes, result, fd, 2);
if (result[firstime - 1] == '\n' && result[firstime - 2] == '\n')
ft_strerror(shapes, result, fd, 2);
return (1);
}
int main(int ac, char **av)
{
t_shapes *shapes;
char *square;
int fd;
if (!(shapes = (t_shapes *)malloc(sizeof(*shapes) * 27)))
return (EXIT_FAILURE);
if (!(square = ft_strnew(20)))
return (EXIT_FAILURE);
if (ac != 2)
ft_strerror(shapes, square, 0, 1);
if ((fd = open(av[1], O_RDONLY)) < 0)
ft_strerror(shapes, square, fd, 2);
if (!check_empty_or_bad_ending(fd, shapes))
return (0);
close(fd);
if ((fd = open(av[1], O_RDONLY)) < 0)
ft_strerror(shapes, square, fd, 2);
if (!checkfile(shapes, &square, fd))
ft_strerror(shapes, square, fd, 2);
start(shapes);
close(fd);
return (EXIT_SUCCESS);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#define SIZE 1024
int main(int argc,char * argv[])
{
char buff[SIZE];
int len,ret,c;
/*
while((c = fgetc(stdin)) != EOF){
if((c = fputc(c,stdout)) == EOF){
perror("fputc");
}
}
exit(0);
*/
while((len = read(STDIN_FILENO,buff,SIZE)) > 0){
if((ret = write(STDOUT_FILENO,buff,len))!=len){
perror("write");
}
}
exit(0);
}
|
C
|
/*
** my_strncmp.c for my_strncmp in /Users/Abrahxas/ETNA/Piscine-C/day4/quegui_v/my_strncmp
**
** Made by QUEGUINER Vincent
** Login <quegui_v@etna-alternance.net>
**
** Started on Fri Mar 28 17:06:31 2014 QUEGUINER Vincent
** Last update Sat Mar 29 09:44:53 2014 QUEGUINER Vincent
*/
int my_strncmp(char *s1, char *s2, int n)
{
int i;
for (i = 0; i != '\0' && i != '\0'; i++)
{
if (i < n)
{
if (s1[i] != s2[i])
return (s1[i] - s2[i]);
}
}
return (0);
}
|
C
|
/*
** get_next_line.c for get_next_line in /home/heurta_s/rendu/after_pool/B2/prepare/dante
**
** Made by Stanislav HEURTAULT
** Login <heurta_s@epitech.net>
**
** Started on Tue May 10 13:56:10 2016 Stanislav HEURTAULT
** Last update Wed Jun 8 10:55:22 2016 mathis rousselot
*/
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
#include "my_sh.h"
int check_rest(char *rest)
{
size_t nb;
if (rest == NULL)
return (0);
nb = 0;
while (rest[nb] != '\0')
{
if (rest[nb] == '\n')
return (1);
nb++;
}
return (0);
}
char *add_to_rest(char reader[READ_SIZE + 1], char *rest, int r)
{
char *tmp;
size_t nb;
size_t len;
(1 ? nb = 0, len = 0 : 0);
if (rest == NULL)
{
if ((tmp = malloc(sizeof(char) * (r + 1))) == NULL)
fatal_error_exit(MALLOC);
while (reader[nb] != '\0')
(1 ? tmp[nb] = reader[nb], nb++ : 0);
tmp[nb] = '\0';
return (tmp);
}
while (rest[len] != '\0')
len++;
if ((tmp = malloc(sizeof(char) * (len + r + 1))) == NULL)
fatal_error_exit(MALLOC);
len = 0;
while (rest[len] != '\0')
(1 ? tmp[len] = rest[len], len++ : 0);
while (reader[nb] != '\0')
(1 ? tmp[len + nb] = reader[nb], nb++ : 0);
(1 ? tmp[len + nb] = '\0', free(rest) : 0);
return (tmp);
}
char *returned(char *rest)
{
char *tmp;
size_t nb;
if (rest == NULL)
return (NULL);
nb = 0;
while (rest[nb] != '\n' && rest[nb] != '\0')
nb++;
if ((tmp = malloc(sizeof(char) * (nb + 1))) == NULL)
fatal_error_exit(MALLOC);
nb = 0;
while (rest[nb] != '\n' && rest[nb] != '\0')
{
tmp[nb] = rest[nb];
nb++;
}
tmp[nb] = '\0';
return (tmp);
}
char *truncate_rest(char *rest)
{
char *tmp;
size_t nb;
size_t len;
(1 ? len = 0, nb = 0 : 0);
while (rest[nb] != '\n' && rest[nb] != '\0')
nb++;
len = nb;
while (rest[len] != '\0')
len++;
if (len == nb)
{
free(rest);
return (NULL);
}
if ((tmp = malloc(sizeof(char) * (len - nb))) == NULL)
fatal_error_exit(MALLOC);
(1 ? nb++, len = 0 : 0);
while (rest[len + nb] != '\0')
(1 ? tmp[len] = rest[len + nb], len++ : 0);
(1 ? tmp[len] = '\0', free(rest) : 0);
return (tmp);
}
char *get_next_line(const int fd)
{
static char *rest;
char reader[READ_SIZE + 1];
char *ret;
size_t r;
r = READ_SIZE;
while (r == READ_SIZE && check_rest(rest) == 0)
{
r = read(fd, reader, READ_SIZE);
reader[r] = '\0';
if (r > 0)
rest = add_to_rest(reader, rest, r);
}
if (r == 0)
return (NULL);
ret = returned(rest);
rest = truncate_rest(rest);
return (ret);
}
|
C
|
#include<stdio.h>
int main()
{
int *p,*q,a,b;
printf("Two numbers: ");
scanf("%d%d",&a,&b);
p=&a;
q=&b;
printf("Sum= %d",*p+*q);
return 0;
}
|
C
|
Find the kth largest factor of a number N.
Eg: input: 36(N) 2(k)
output: 18
explaination:
factors of 36: 1, 2, 3, 4, 6, 9,12, 18, 36
2nd largest factor is : 18
//method 1
#include<stdio.h>
int main()
{
int n,count=0,factor,k,total;
scanf("%d,%d",&n,&k);
for(factor=n;facotr>=1;factor--)
{
if(n%factor==0){
count++;
if(count==k)
{
printf("%d",factor);
break;
}
}
}
if(k>count)
printf("1");
return 0;
}
method 2
#include<stdio.h>
int main()
{
int n,factor,setA[100],setB[100];
scanf("%d,%d",&n,&k);
int acount=0,bcount=0;
for(factor=1;factor<=sqrt(n);factor++)
{
int b;
if(n%factor==0)
{
setA[acount]=factor;
b=n/setA[acount];
if(setA[acount]!=b){
setB[bcount]=b;
acount++;
}
bcount++;
}
}
total=acount+bcount;
if(k>total)
{
if(k<=bcount)
printf("%d",setB[k-1]);
else{
k=k-bcount;
printf("%d",setA[acount-k]);
}
}
else
printf("1");
}
|
C
|
#include <stdio.h>
#ifndef COLLATZ
void collatz(int n) {
if((n % 2) == 0) {
#ifndef PRINTNUMBER
printf("%d -> ", n);
#endif
collatz(n / 2);
} else if (n != 1) {
#ifndef PRINTNUMBER
printf("%d -> ", n);
#endif
collatz(n * 3 + 1);
} else {
#ifndef PRINTNUMBER
printf("1");
#endif
}
}
#endif
int main( ) {
int n = 3;
int sequencia[2] = {1, 1000};
printf("Arquivo de teste 03.\n");
printf("=> ");
#ifndef SIZE
collatz(n);
#ifdef SIZE
maiorSequencia(sequencia);
#endif
#endif
return 0;
}
|
C
|
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <assert.h>
#define N_THREADS 5
void *printMessage(void *arg) {
int i;
for (i = 0; i < 100; i += 1) {
printf("This is a message from thread %ld\n", (long)arg);
}
printf("Thread %ld finished\n", (long)arg);
pthread_exit((void *)0);
}
int main(void) {
pthread_t thread[N_THREADS];
int rc;
long i;
for (i = 0; i < N_THREADS; i += 1) {
rc = pthread_create(&thread[i], NULL, printMessage, (void *)i);
assert(rc == 0);
}
for (i = 0; i < N_THREADS; i += 1) {
rc = pthread_join(thread[i], NULL);
assert(rc == 0);
}
printf("Finished\n");
exit(0);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX 128
typedef struct {
char* nome;
float notas[4], media;
} Aluno;
int load(char fileName[], Aluno* alunos[], int* qAlunos);
int fRelat(char fileName[], Aluno* alunos[], int qAlunos, int relatType);
int calc(Aluno* alunos[], int qAlunos);
int libera(Aluno* alunos[], int qAlunos);
int ordFis(Aluno* alunos[], int qAlunos);
Aluno* read(FILE* f, Aluno* aluno);
Aluno* write1(FILE* fw, Aluno* aluno);
Aluno* write2(FILE* fw, Aluno* aluno);
Aluno* write3(FILE* fw, Aluno* aluno);
int main(int argc, char const *argv[]) {
Aluno* alunos[MAX];
int qAlunos;
if(!(load("Alunos.txt", alunos, &qAlunos))) {
fRelat("relat.txt", alunos, qAlunos, 1);
calc(alunos, qAlunos);
fRelat("relat2.txt", alunos, qAlunos, 2);
//fRelat("relat3.txt", alunos, qAlunos, 3);
//ordFis(alunos, qAlunos);
//fRelat("ord.txt", alunos, qAlunos, 3);
libera(alunos, qAlunos);
}
return 0;
}
int libera(Aluno* alunos[], int qAlunos) {
int i;
for (i = 0; i < qAlunos; ++i) {
free(alunos[i]);
}
}
int calc(Aluno* alunos[], int qAlunos) {
int i, j;
float soma;
for (i = 0; i < qAlunos; ++i) {
soma = 0;
for (j = 0; j < 4; ++j) {
soma += alunos[i]->notas[j];
}
alunos[i]->media = soma/4;
}
return 0;
}
int ordFis(Aluno* alunos[], int qAlunos) {
}
int load(char fileName[], Aluno* alunos[], int* qAlunos) {
FILE* fr;
int i;
if(!(fr = fopen(fileName, "r"))) return 1;
for (i = 0; !feof(fr); ++i) {
alunos[i] = read(fr, alunos[i]);
}
*qAlunos = i;
fclose(fr);
return 0;
}
Aluno* read(FILE* fr, Aluno* aluno) {
int i;
aluno = malloc(sizeof(Aluno));
aluno->nome = malloc(MAX);
fscanf(fr, "%[^\n]%*c", aluno->nome);
aluno->nome = realloc(aluno->nome, strlen(aluno->nome));
for (i = 0; i < 4; ++i) {
fscanf(fr, "%f%*c", &aluno->notas[i]);
}
return aluno;
}
int fRelat(char fileName[], Aluno* alunos[], int qAlunos, int relatType) {
int i;
FILE* fw;
if(!(fw = fopen(fileName, "w"))) return 1;
for (i = 0; i < qAlunos; ++i) {
switch(relatType) {
case 1:
write1(fw, alunos[i]);
break;
case 2:
write2(fw, alunos[i]);
break;
case 3:
write3(fw, alunos[i]);
break;
default:
break;
}
}
fclose(fw);
return 0;
}
Aluno* write1(FILE* fw, Aluno* aluno) {
int i;
fprintf(fw, "%s\n", aluno->nome);
for (i = 0; i < 4; ++i) {
fprintf(fw, "%.1f ", aluno->notas[i]);
}
fprintf(fw, "\n");
return aluno;
}
Aluno* write2(FILE* fw, Aluno* aluno) {
int i;
fprintf(fw, "%-40s ", aluno->nome);
for (i = 0; i < 4; ++i) {
fprintf(fw, "%.1f ", aluno->notas[i]);
}
fprintf(fw, "%.1f", aluno->media);
fprintf(fw, "\n");
return aluno;
}
Aluno* write3(FILE* fw, Aluno* aluno) {
int i;
fprintf(fw, "%-40s ", aluno->nome);
for (i = 0; i < 4; ++i) {
fprintf(fw, "%.1f ", aluno->notas[i]);
}
fprintf(fw, "%.1f \n", aluno->media);
return aluno;
}
|
C
|
#include <linux/init.h>
#include <linux/printk.h>
#include <linux/module.h>
#include <linux/device.h>
#include <linux/fs.h>
#include <linux/cdev.h>
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Ramy Lerner");
MODULE_DESCRIPTION("My own null/dev");
MODULE_VERSION("0.1.2");
const int MINOR_COUNT = 1;
static dev_t first_dev;
static struct class* my_class;
static struct device* my_device;
static struct cdev my_cdev;
static int open_myNull( struct inode *inode, struct file *file){
pr_info("at open\n");
return 0;
}
static ssize_t write_myNull(struct file *file, const char __user *buf, size_t count,
loff_t *ppos)
{
pr_info("at read!\n");
return count;
}
static int release_myNull( struct inode *inode, struct file *file){
pr_info("at release\n");
return 0;
}
static const struct file_operations myNull_fops = {
.owner = THIS_MODULE,
.open = open_myNull,
.write = write_myNull,
.release = release_myNull,
};
static int __init init_myNULL(void){
int err =0 ;
pr_info("at init_myNull()\n");
err = alloc_chrdev_region(&first_dev, 0, MINOR_COUNT, "myNull");
if (err) {
pr_err("cannot alloc_chrdev_region\n");
goto err_final;
}
my_class = class_create(THIS_MODULE, THIS_MODULE->name);
if (IS_ERR(my_class)) {
pr_err("failed in class_create\n");
err = PTR_ERR(my_class);
goto err_dealloc;
}
pr_info("created the class\n");
my_device = device_create(my_class,
/*parent*/ NULL,
/*dev_t major+minor*/ first_dev,
NULL, "%s",
THIS_MODULE->name);
if (IS_ERR(my_device)) {
pr_err("failed in device_create\n");
err = PTR_ERR(my_device);
goto err_class;
}
pr_info("created the device\n");
cdev_init(&my_cdev, &myNull_fops);
err = cdev_add(&my_cdev, first_dev, MINOR_COUNT);
if (err) {
pr_err("cannot cdev_add\n");
goto err_device;
}
pr_info("finished loading device driver\n");
return 0;
err_device:
device_destroy(my_class, first_dev);
err_class:
class_destroy(my_class);
err_dealloc:
unregister_chrdev_region(first_dev, MINOR_COUNT);
err_final:
return err;
}
static void __exit exit_myNull(void){
device_destroy(my_class, first_dev);
class_destroy(my_class);
cdev_del(&my_cdev);
unregister_chrdev_region(first_dev, MINOR_COUNT);
pr_info("exit completed\n");
}
module_init(init_myNULL);
module_exit(exit_myNull);
|
C
|
#include <stdio.h>
#include <string.h>
void func(char *str) {
char buffer[24];
int *ret;
strcpy(buffer,str);
}
int main(int argc, char **argv) {
int x;
x = 0;
func(argv[1]);
x = 1;
printf("x is 1\n");
printf("x is 0\n");
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <float.h>
#include <math.h>
unsigned long long debug_count = 0;
typedef struct
{
double x;
double y;
} point;
double distance(point a, point b)
{
double dx = a.x-b.x;
double dy = a.y-b.y;
return sqrt(dx*dx+dy*dy);
}
double route_distance(point*p, int n)
{
double sum = 0;
for(int i=0;i<n-1;i++)
{
sum += distance(p[i],p[i+1]);
}
sum += distance(p[n-1],p[0]);
return sum;
}
double* distance_matrix(point*p, int n)
{
double*dm = malloc(sizeof(double)*n*n);
for(int i=0;i<n;i++)
for(int j=0;j<n;j++)
{
dm[i*n+j] = distance(p[i],p[j]);
}
return dm;
}
double route_distance_matrix(double*dm, point*p, int n)
{
double sum = 0;
for(int i=0;i<n-1;i++)
{
sum += dm[n*i + i+1];
}
sum += dm[n*(n-1) + 0];
return sum;
}
void copy_point(point x, point*y)
{
y->x = x.x;
y->y = x.y;
}
void copy_path(point*x, point*y, int n)
{
for(int i=0;i<n;i++)
{
copy_point(x[i],&y[i]);
}
}
void swap_points(point*p, int a, int b)
{
point t;
copy_point(p[a],&t);
copy_point(p[b],&p[a]);
copy_point(t,&p[b]);
}
int swap_points_opt(double*d, point*p, int a, int b, int n)
{
//1 on success
debug_count++;
double new;
swap_points(p,a,b);
new = route_distance(p,n);
if((*d) <= new){swap_points(p,a,b); return 0;}
*d = new;
return 1;
}
int swap_all_pairs(double*d, point*p, int n)
{
//1 on success
for(int i=0;i<n;i++)
for(int j=i+1;j<n;j++)
{
if(swap_points_opt(d,p,i,j,n)){return 1;}
}
return 0;
}
int swap_all_pairs_depth(int depth, double*d, point*p, int n)
{
if(depth == 1)
{
return swap_all_pairs(d,p,n);
}
for(int i=0;i<n;i++)
{
for(int j=i;j<n;j++)
{
swap_points(p,i,j);
if(swap_all_pairs_depth(depth-1,d,p,n)){return 1;}
swap_points(p,i,j);
}
}
return 0;
}
int main(int argc, char *argv[])
{
//./exe input output
if((argc != 2) && (argc != 3))
{
printf("Incorrect number of arguments\n");
exit(1);
}
//Open file
FILE*fp;
fp = fopen(argv[1],"r");
if(fp == 0)
{
printf("Cannot open file\n");
exit(2);
}
//Read file into buffer
fseek(fp,0,SEEK_END);
int n = ftell(fp);
fseek(fp,0,SEEK_SET);
char*buf = malloc(sizeof(char)*n);
int r = fread(buf,1,n,fp);
if(r != n)
{
printf("Read error\n");
exit(3);
}
fclose(fp);
//Extract points
n /= 2;
point*p=malloc(sizeof(point)*n);
for(int i=0;i<n;i++)
{
p[i].x = buf[2*i];
p[i].y = buf[2*i+1];
}
//Get the distance matrix
double d = route_distance(p,n);
//Find a new path
int depth = 3;
int changed = 1;
while(changed)
{
changed = swap_all_pairs_depth(depth,&d,p,n);
printf("Update = %f, Count = %llu\n",d,debug_count);
}
//Show some useful info
printf("Distance = %f\n",route_distance(p,n));
//Dump results
if (argc == 3)
{
//Generate results
char*result=malloc(2*n);
for(int i=0;i<n;i++)
{
result[2*i] = p[i].x;
result[2*i+1] = p[i].y;
}
//Write results
fp = fopen(argv[2],"w");
fwrite(result,1,2*n,fp);
fclose(fp);
}
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include "funcoes.h"
int main()
{
int num;
do
{
printf("Que tabuada deseja ver\n");
scanf("%d",&num);
printf("\n");
}while((num < 1) ||(num > 10));
tabuada(num);
return 0;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.