language
large_stringclasses 1
value | text
stringlengths 9
2.95M
|
---|---|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* error.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: stvalett <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2017/02/27 16:59:27 by stvalett #+# #+# */
/* Updated: 2017/03/31 11:10:00 by stvalett ### ########.fr */
/* */
/* ************************************************************************** */
#include "../include/minishell.h"
static char *ft_error_dollar_bis(char *av, char **env_bis, int *index)
{
char *tmp;
int i;
int k;
if ((tmp = (char *)malloc(sizeof(char ) * ft_strlen(av) + 1)) == NULL)
return (NULL);
i = 0;
while (av[i] == '$' && av[i])
i++;
k = 0;
if (av[i] == '"')
{
free(tmp);
return (NULL);
}
while (av[i] != ' ' && av[i])
{
tmp[k] = av[i];
k++;
i++;
}
tmp[k] = '\0';
*index = ft_getenv(tmp, env_bis);
return (tmp);
}
void ft_error_dollar(char **av, char **env_bis)
{
char *tmp;
int i;
int index;
i = 0;
index = 0;
while (av[++i])
if ((ft_strchr(av[i], '$')) != NULL
&& ft_no_digit(av[i]) == 0 && ft_strlen(av[i]) > 1)
{
tmp = ft_error_dollar_bis(av[i], env_bis, &index);
if (tmp == NULL)
{
ft_putendl_fd("Illegal variable name.", 2);
break ;
}
if (index < 0)
{
ft_error_setenv(tmp, 3);
break ;
}
free(tmp);
}
}
int ft_error_bracket(int count, char **av, int flag)
{
if (count % 2 == 1 && ft_is_dollar_n_acco(av) == 0)
{
ft_putstr_fd("Unmatched ", 2);
if (flag == 1)
ft_putchar_fd('"', 2);
else
ft_putchar_fd('\'', 2);
ft_putchar_fd('.', 2);
ft_putchar_fd('\n', 2);
return (0);
}
else if (ft_is_dollar_n_acco(av) == 1)
{
ft_putendl_fd("Illegal variable name.", 2);
return (0);
}
return (1);
}
void ft_error_setenv(char *str, int flag)
{
if (flag == 1)
ft_putendl_fd("setenv: Variable name must begin with a letter", 2);
else if (flag == 2)
{
ft_putstr_fd("setenv: Variable name must contain", 2);
ft_putendl_fd(" alphanumeric characters", 2);
}
else if (flag == 3)
{
ft_putstr_fd(str, 2);
ft_putendl_fd(": Undefined variable", 2);
free(str);
}
}
void ft_error_env(char *av, int flag)
{
struct stat info;
stat(av, &info);
if (flag == 0)
{
ft_putstr_fd("env: ", 2);
ft_putstr_fd(av, 2);
ft_putendl_fd(": No such file or directory", 2);
}
else
{
if (S_IXUSR && S_ISDIR(info.st_mode))
{
ft_putstr_fd(av, 2);
ft_putendl_fd(": Permission denied", 2);
}
else
{
ft_putstr_fd("cd: No such file or directory: ", 2);
ft_putendl_fd(av, 2);
}
}
}
|
C
|
#include <stdio.h>
struct cust_st
{
int acc_no;
char cust_nm[30];
float bal;
};
struct tran_st
{
int acc_no;
char trantype;
float amt;
};
int main()
{
int choice=1;
while(choice!=4)
{
printf("\nSelect choice from menu\n\n 1. Accept customer details\n
2. Record withdrawl/Deposit transaction\n 3. Print low balance report\n
4. Exit\n\n Enter choice: ");
scanf("%d", &choice);
if(choice==1)
addcust();
else if(choice==2)
rectran();
else if(choice==3)
prnlowbal();
}
return 0;
}
addcust()
{
FILE *fp;
char flag='y';
struct cust_st custdata;
if((fp=fopen("customer", "a+")))==NULL
{
printf("\nError opening customer file");
return;
}
while(flag=='y')
{
printf("\n\nEnter account number: ");
scanf("%d", &custdata.acc_no);
printf("\nEnter customer name: ");
scanf("%s", custdata.cust_nm);
printf("\nEnter account balance: ");
scanf("%f", &custdata.bal);
fwrite(&custdata, sizeof(struct cust_st), 1, fp);
printf("\n\nAdd another? (y/n): ");
scanf("%c", &flag);
}
fclose(fp);
}
rectran()
{
FILE *fpl, *fp2;
char flag='y', found, var_flag;
struct cust_st custdata;
struct tran_st trandata;
int size = sizeof(struct cust_st);
if((fp;=fopen("customer", "r+w"))==NULL)
{
printf("\nError opening customer file");
return;
}
if((fp2=fpen("trans", "a+"))==NULL)
{
printf("\nError opening transaction file");
return;
}
while(flag=='y')
{
printf("\n\nEnter account number: ");
scanf("%d", &trandata.acc_no);
int accno = trandata.acc_no;
rewind(fpl);
while((fread(&custdata, sizeof(struct cust_st), 1, fpl))==1)
{
if(custdata.acc_no = accno)
{
found = 'y';
break;
//printf("\n%d\t%s.2f", custdata.acc_no, custdata.cust_nm, custdata.bal);
}
}
//found = 'n';
val_flag='n';
if(found=='y')
{
while(val_flag=='n')
{
printf("\Enter transaction (D/W): ");
scanf("%c", &trandata.trantype);
if(trandata.trantype!='D' && trandata.trantype!='d' &&
trandata.trantype!='W' && trandata!='w')
printf("\t\tInvalid transaction type, please reenter");
else
val_flag='y';
}
val_flag='n';
while(val_flag=='n')
{
printf("\nEnter amount: ");
scanf("%f", &trandata.amt);
if(trandata.trantype =='W' || trandata.trantype=='w')
{
if(trandata.amt > custdata.bal)
printf("\nAccount balance is %.2f. Please reenter withdrawal amount.", custdata.bal);
else
{
custdata.bal-=trandata.amt;
val_flag='y';
}
}
else
{
custdata.bal+=trandata.amt;
val_flag='y';
}
}
fwrite(&trandata, sizeof(struct tran_st), l, fp2);
fseek(fpl, (long)(-size), l);
fwrite(&custdata, size, l, fpl);
}
else
printf("\nThis account number does not exist");
printf("\nRecord another transaction? (y/n): ");
scanf("%c", &flag);
}
fclose(fp1);
fclose(fp2);
}
prnlowbal()
{
FILE *fp;
struct cust_st custdata;
char flag='n';
if((fp=fopen("customer", "r")))==NULL)
{
printf("\nError openning customer file");
return;
}
printf("\nReport on account balance below 250\n\n");
while((fread(&custdata, sizeof(struct cust_st), l, fp)))==l
{
if(custdata.bal < 250)
{
flag='y';
printf("\n%d\t%s\t%.2f", custdata.acc_no, custdata.cust_nm, custdata.bal);
}
}
if(flag=='n')
printf("\nNo account balance found below 250");
fclose(fp);
}
}
|
C
|
#include "../node.h"
static const char *mode_strings[] = { "lowpass", "highpass", "bandpass", "notch", "off", NULL };
enum { LOWPASS, HIGHPASS, BANDPASS, NOTCH, OFF };
typedef struct {
Node node;
int mode;
float d1, d2;
NodePort in, freq, q; /* inlets */
NodePort out; /* outlets */
} SvfNode;
static void process(Node *node) {
SvfNode *n = (SvfNode*) node;
const float passes = 3;
float max_freq = NODE_SAMPLERATE * 0.130 * passes;
float f1, q1, in, hp;
float bp = n->d1;
float lp = n->d2;
for (int i = 0; i < NODE_BUFFER_SIZE; i++) {
q1 = 1.0 / maxf(n->q.buf[i], 0.5);
f1 = minf(fabs(n->freq.buf[i]), max_freq) / passes;
f1 = 2 * 3.141592 * f1 * NODE_SAMPLETIME;
in = n->in.buf[i];
for (int i = 0; i < passes; i++) {
lp = lp + f1 * bp;
hp = in - lp - q1 * bp;
bp = f1 * hp + bp;
}
switch (n->mode) {
case LOWPASS : n->out.buf[i] = lp; break;
case HIGHPASS : n->out.buf[i] = hp; break;
case BANDPASS : n->out.buf[i] = bp; break;
case NOTCH : n->out.buf[i] = hp + lp; break;
case OFF : n->out.buf[i] = in; break;
}
}
n->d1 = bp;
n->d2 = lp;
/* send output */
node_process(node);
}
static int receive(Node *node, const char *msg, char *err) {
SvfNode *n = (SvfNode*) node;
char buf[16];
if (sscanf(msg, "mode %15s", buf)) {
int idx = string_to_enum(mode_strings, buf);
if (idx < 0) { sprintf(err, "bad mode '%s'", buf); return -1; }
n->mode = idx;
} else {
sprintf(err, "bad command"); return -1;
}
return 0;
}
Node* new_svf_node(void) {
SvfNode *node = calloc(1, sizeof(SvfNode));
static const char *inlets[] = { "in", "freq", "q", NULL };
static const char *outlets[] = { "out", NULL };
static NodeInfo info = {
.name = "svf",
.inlets = inlets,
.outlets = outlets,
};
static NodeVtable vtable = {
.process = process,
.receive = receive,
.free = node_free,
};
node_init(&node->node, &info, &vtable, &node->in, &node->out);
node_set(&node->node, "freq", 440.0);
node_set(&node->node, "q", 1.0);
return &node->node;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <error.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#define ERR_EXIT(m) \
do{ \
perror(m); \
exit(EXIT_FAILURE); \
}while(0)
/*
*set flag using fcntl function
*
*/
void set_flag(int fd,int flag)
{
int val=fcntl(fd,F_GETFL,0);
if(val==-1)
ERR_EXIT("get flag error");
val |=flag;
if(fcntl(fd,F_SETFL,val)==-1)
ERR_EXIT("set flag error");
printf("set flag success\n");
}
/*
*clear flag using file discripation
*/
void clr_flag(int fd,int flag)
{
int val=fcntl(fd,F_GETFL,0);
if(val == -1)
ERR_EXIT("get flag error");
val &=~flag;
if(fcntl(fd,F_SETFL,val)==-1)
ERR_EXIT("set flag perror");
printf("clear flag success\n");
}
int main(void)
{
char buf[1024]={0};
set_flag(0,O_NONBLOCK);
clr_flag(0,O_NONBLOCK);
int ret=read(0,buf,1024);
if(ret==-1)
ERR_EXIT("read error");
printf("buf=%s\n",buf);
return 0;
}
|
C
|
#include "compiler.h"
char *BOILERPLATE =
"#include <stdlib.h>\n"
"#include <stdio.h>\n"
"#include <stdbool.h>\n"
"\n"
"typedef char *str;" CC_NEWLINE
"typedef unsigned long long u64;" CC_NEWLINE
"typedef unsigned int u32;" CC_NEWLINE
"typedef unsigned short u16;" CC_NEWLINE
"typedef unsigned char u8;" CC_NEWLINE
"typedef long long s64;" CC_NEWLINE
"typedef int s32;" CC_NEWLINE
"typedef short s16;" CC_NEWLINE
"typedef char s8;" CC_NEWLINE
"typedef float f32;" CC_NEWLINE
"typedef double f64;" CC_NEWLINE
;
Compiler *createCompiler(Vector *sourceFiles) {
Compiler *self = safeMalloc(sizeof(*self));
self->abstractSyntaxTree = NULL;
self->currentNode = 0;
self->sourceFiles = sourceFiles;
self->functions = hashmap_new();
self->structures = hashmap_new();
return self;
}
void emitCode(Compiler *self, char *fmt, ...) {
va_list args;
va_start(args, fmt);
switch (self->writeState) {
case WRITE_SOURCE_STATE:
vfprintf(self->currentSourceFile->outputFile, fmt, args);
va_end(args);
break;
case WRITE_HEADER_STATE:
vfprintf(self->currentSourceFile->headerFile->outputFile, fmt, args);
va_end(args);
break;
}
}
void emitExpression(Compiler *self, Expression *expr) {
emitCode(self, "5"); // lol it'll do for now
}
void emitType(Compiler *self, Type *type) {
switch (type->type) {
case POINTER_TYPE_NODE:
emitCode(self, "*");
emitType(self, type->pointerType->type);
break;
case ARRAY_TYPE_NODE:
emitType(self, type->arrayType->type);
emitCode(self, "[");
emitExpression(self, type->arrayType->length);
emitCode(self, "]");
break;
case TYPE_NAME_NODE:
emitCode(self, "%s", type->typeName->name);
break;
}
}
void emitParameters(Compiler *self, Parameters *params) {
for (int i = 0; i < params->paramList->size; i++) {
ParameterSection *param = getVectorItem(params->paramList, i);
if (!param->mutable) {
emitCode(self, "const ");
}
emitType(self, param->type);
emitCode(self, " %s", param->name);
if (params->paramList->size > 1 && i != params->paramList->size - 1) {
emitCode(self, ", ");
}
}
}
void emitReceiver(Compiler *self, Receiver *rec) {
if (rec != NULL){
if (!rec->mutable) {
emitCode(self, "const ");
}
emitCode(self, rec->name);
emitCode(self, " ");
emitType(self, rec->type);
}
}
void emitFunctionSignature(Compiler *self, FunctionSignature *func) {
if (!func->mutable) {
emitCode(self, "const ");
}
emitType(self, func->type);
emitCode(self, " %s(", func->name);
emitReceiver(self, func->receiver);
// cleaner formatting, also avoids trailing comma
if (func->receiver && func->parameters->paramList->size > 1) { emitCode(self, ", "); }
emitParameters(self, func->parameters);
emitCode(self, ")");
}
void emitStructuredStatement(Compiler *self, StructuredStatement *stmt) {
switch (stmt->type) {
case BLOCK_NODE: emitBlock(self, stmt->block); break;
case FOR_STAT_NODE: emitForStat(self, stmt->forStmt); break;
case IF_STAT_NODE: emitIfStat(self, stmt->ifStmt); break;
case MATCH_STAT_NODE: emitMatchStat(self, stmt->matchStmt); break;
}
}
void emitUnstructuredStatement(Compiler *self, UnstructuredStatement *stmt) {
switch (stmt->type) {
case DECLARATION_NODE: emitDeclaration(self, stmt->decl); break;
}
}
void emitBlock(Compiler *self, Block *block) {
emitCode(self, " {" CC_NEWLINE);
emitStatementList(self, block->stmtList);
emitCode(self, "}" CC_NEWLINE);
}
void emitForStat(Compiler *self, ForStat *stmt) {
}
void emitIfStat(Compiler *self, IfStat *stmt) {
}
void emitMatchStat(Compiler *self, MatchStat *stmt) {
}
void emitStatementList(Compiler *self, StatementList *stmtList) {
for (int i = 0; i < stmtList->stmts->size; i++) {
Statement *stmt = getVectorItem(stmtList->stmts, i);
switch (stmt->type) {
case STRUCTURED_STMT: emitStructuredStatement(self, stmt->structured); break;
case UNSTRUCTURED_STMT: emitUnstructuredStatement(self, stmt->unstructured); break;
}
}
}
void emitFunctionDecl(Compiler *self, FunctionDecl *decl) {
self->writeState = WRITE_HEADER_STATE;
emitFunctionSignature(self, decl->signature);
emitCode(self, ";"); // semi colon at end of prototype
self->writeState = WRITE_SOURCE_STATE;
emitFunctionSignature(self, decl->signature);
emitBlock(self, decl->body);
}
void emitIdentifierList(Compiler *self, IdentifierList *list) {
for (int i = 0; i < list->values->size; i++) {
Token *tok = getVectorItem(list->values, i);
emitCode(self, tok->content);
if (i != list->values->size - 1 && list->values->size > 1) {
emitCode(self, ", ");
}
}
}
void emitFieldDeclList(Compiler *self, FieldDeclList *list) {
for (int i = 0; i < list->members->size; i++) {
FieldDecl *decl = getVectorItem(list->members, i);
if (!decl->mutable) {
emitCode(self, "const ");
}
emitType(self, decl->type);
emitIdentifierList(self, decl->idenList);
}
}
void emitStructDecl(Compiler *self, StructDecl *decl) {
self->writeState = WRITE_HEADER_STATE;
emitCode(self, "typedef struct {" CC_NEWLINE);
emitFieldDeclList(self, decl->fields);
emitCode(self, "} %s;" CC_NEWLINE, decl->name);
}
void emitDeclaration(Compiler *self, Declaration *decl) {
switch (decl->declType) {
case FUNC_DECL: emitFunctionDecl(self, decl->funcDecl); break;
case STRUCT_DECL: emitStructDecl(self, decl->structDecl); break;
case VAR_DECL: break;
}
}
void consumeAstNode(Compiler *self) {
self->currentNode += 1;
}
void consumeAstNodeBy(Compiler *self, int amount) {
self->currentNode += amount;
}
void startCompiler(Compiler *self) {
int i;
for (i = 0; i < self->sourceFiles->size; i++) {
SourceFile *sourceFile = getVectorItem(self->sourceFiles, i);
self->currentNode = 0;
self->currentSourceFile = sourceFile;
self->abstractSyntaxTree = self->currentSourceFile->ast;
writeFiles(self->currentSourceFile);
self->writeState = WRITE_SOURCE_STATE;
// _gen_name.h is the typical name for the headers and c files that are generated
emitCode(self, "#include \"_gen_%s.h\"\n", self->currentSourceFile->name);
// write to header
self->writeState = WRITE_HEADER_STATE;
emitCode(self, "#ifndef __%s_H\n", self->currentSourceFile->name);
emitCode(self, "#define __%s_H\n\n", self->currentSourceFile->name);
emitCode(self, BOILERPLATE);
// compile code
compileAST(self);
// write to header
self->writeState = WRITE_HEADER_STATE;
emitCode(self, "\n");
emitCode(self, "#endif // __%s_H\n", self->currentSourceFile->name);
// close files
closeFiles(self->currentSourceFile);
}
sds buildCommand = sdsempty();
// append the compiler to use etc
buildCommand = sdscat(buildCommand, COMPILER);
buildCommand = sdscat(buildCommand, " ");
buildCommand = sdscat(buildCommand, ADDITIONAL_COMPILER_ARGS);
buildCommand = sdscat(buildCommand, " -o ");
buildCommand = sdscat(buildCommand, OUTPUT_EXECUTABLE_NAME);
buildCommand = sdscat(buildCommand, " ");
// append the filename to the build string
for (i = 0; i < self->sourceFiles->size; i++) {
SourceFile *sourceFile = getVectorItem(self->sourceFiles, i);
buildCommand = sdscat(buildCommand, sourceFile->generatedSourceName);
if (i != self->sourceFiles->size - 1) // stop whitespace at the end!
buildCommand = sdscat(buildCommand, " ");
}
// just for debug purposes
debugMessage("running cl args: `%s`", buildCommand);
system(buildCommand);
sdsfree(buildCommand); // deallocate dat shit baby
}
void compileAST(Compiler *self) {
int i;
for (i = 0; i < self->abstractSyntaxTree->size; i++) {
Statement *currentStmt = getVectorItem(self->abstractSyntaxTree, i);
switch (currentStmt->type) {
case UNSTRUCTURED_STMT: emitUnstructuredStatement(self, currentStmt->unstructured); break;
case STRUCTURED_STMT: emitStructuredStatement(self, currentStmt->structured); break;
default:
printf("idk?\n");
break;
}
}
}
void destroyCompiler(Compiler *self) {
// now we can destroy stuff
int i;
for (i = 0; i < self->sourceFiles->size; i++) {
SourceFile *sourceFile = getVectorItem(self->sourceFiles, i);
// don't call destroyHeaderFile since it's called in this function!!!!
destroySourceFile(sourceFile);
debugMessage("Destroyed source files on %d iteration.", i);
}
hashmap_free(self->functions);
hashmap_free(self->structures);
free(self);
debugMessage("Destroyed compiler");
}
|
C
|
#include <stdio.h>
#include <math.h>
int main ()
{
float f(float x)
{
float y;
y= cos(x/2)-sin(2*x);
return y;
}
float fprima(float x)
{
float y;
y=-(sin(x/2)/2)-2*cos(2*x);
return y;
}
float newtonRaphson(float X0,int iter)
{
int i=0;
float xi, xim,erp;
xi=X0;
printf("i \t Xi \t\t Xi+1 \t\t Err\n");
do
{
xim= xi - f(xi)/fprima(xi);
erp= fabs((xim-xi)/xim)*100;
printf("%i \t %.8f \t %.8f \t %.8f \n",i,xi,xim,erp);
i++;
xi=xim;
}while(i<iter);
printf("\n EL APROXIMADO DE RAIZ ES = [%.6f]",xi);
return xim;
}
system ("COLOR B");
float X0=3.3;
int iter=5;
float raiz;
raiz=newtonRaphson(X0,iter);
printf("\n\n");
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "funciones2.0.h"
int buscarLibre(char vector[][20], int *index, int largo);
int inicializarVector (char vector[][20], int len);
int buscarNombre(char *pNombre,
char lista[][20],
int len,
int *pIndex)
{
int i;
int ret = -1;
for (i=0;i<len;i++)
{
if(strcmp(pNombre,lista[i]))
{
*pIndex = i;
ret = 0;
break;
}
}
return ret;
}
int borrarNombre (char vector[][20],int pIndex)
{
int ret;
if (vector!=NULL)
{
vector[pIndex][0] = '\0';
ret=0;
}
return ret;
}
int main()
{
/*int option = 1;
int index;
char buffer[40];
char lista [20][20];
while (option!=0)
{
utn_getNumber(&option,"ingrese una opcion: ","nomero no sirve",0,5,3);
switch (option)
{
case 1:
getString(buffer, "ingrese un nombre: ", "nombre no sirve", 1, 20,3);
inicializarVector(lista,20);
buscarLibre(lista,&index,20);
strncpy(lista[index],buffer,20);
break;
case 4:
getString(buffer,"ingresa el valor a borrar","valor invalido",1,20,1);
buscarNombre(buffer, lista,20,&index);
borrarNombre(lista,index);
break;
case 0:
break;
}
}*/
int n = 5;
int *p = n;
printf("%d",*p);
return 0;
}
int buscarLibre(char vector[][20], int *index, int largo)
{
int i;
int ret = -1;
for(i=0;i<largo;i++)
{
if (vector[i][0]== '\0')
{
*index = i;
ret =0;
break;
}
}
return ret;
}
int inicializarVector (char vector[][20], int len)
{
int i;
for (i=0; i<len;i++)
{
vector[i][0] = '\0';
}
return 0;
}
|
C
|
#include <stdio.h>
int main()
{
float x = 5;
float y = 3;
float ergebnis;
ergebnis = pow(x, 2) + y;
printf ("Ergebnis von x^2 + y : %f\n", ergebnis);
system ("PAUSE");
return 0;
}
|
C
|
#include <graphics.h>
#include <stdio.h>
struct line
{
float x1,y1;
float x2,y2;
};
struct line makeline()
{
struct line l;
//Manual entry
printf("Enter x1: ");
scanf("%f", &l.x1);
printf("Enter y1: ");
scanf("%f", &l.y1);
printf("Enter x2: ");
scanf("%f", &l.x2);
printf("Enter y2: ");
scanf("%f", &l.y2);
if(l.x1>l.x2)
{
float t1, t2;
t1 = l.x1;
t2 = l.y1;
l.x1 = l.x2;
l.y1 = l.y2;
l.x2 = t1;
l.y2 = t2;
}
//Autoset
/*
l.x1 = 120;
l.y1 = 120;
l.x2 = 300;
l.y2 = 400;
*/
return l;
}
struct line makebox()
{
struct line l;
//Manual entry
/*
printf("Enter x1: ");
scanf("%f", &l.x1);
printf("Enter y1: ");
scanf("%f", &l.y1);
printf("Enter x2: ");
scanf("%f", &l.x2);
printf("Enter y2: ");
scanf("%f", &l.y2);
*/
//Autoset
///*
l.x1 = 100;
l.y1 = 100;
l.x2 = 300;
l.y2 = 300;
//*/
return l;
}
void drawline(struct line l)
{
line(l.x1, l.y1, l.x2, l.y2);
}
void drawbox(struct line l)
{
line(l.x1, l.y1, l.x2, l.y1);
line(l.x1, l.y1, l.x1, l.y2);
line(l.x1, l.y2, l.x2, l.y2);
line(l.x2, l.y1, l.x2, l.y2);
}
int inbox(float x1, float y1, struct line b)
{
if(x1>=b.x1 && x1<=b.x2)
{
if(y1>=b.y1 && y1<=b.y2)
{
// if(x2>b.x1 && x2<b.x2)
// {
// if(y2>b.y1 && y2<b.y2)
// {
return 1;
// }
// }
}
}
return 0;
}
struct line clipline(struct line l, struct line b)
{
float m = (l.y2-l.y1)/(l.x2-l.x1);
float p1,q1,p2,q2;
float x,y;
printf("Clipping Line\n");
//check full line
if(inbox(l.x1, l.y1, b)==1 && inbox(l.x2, l.y2, b)==1)
{
// printf("Inside box\n");
return l;
}
y = ((b.x1-l.x1)/(l.x2-l.x1))*(l.y2-l.y1)+l.y1;
if((l.y1<=y&&y<=l.y2)||(l.y1>=y&&y>=l.y2))
{
if(b.x1>=l.x1 && b.x1<=l.x2)
{
l.x1 = b.x1;
l.y1 = y;
//printf("Test1\n");
}
}
y = ((b.x2-l.x1)/(l.x2-l.x1))*(l.y2-l.y1)+l.y1;
if((l.y1<=y&&y<=l.y2)||(l.y1>=y&&y>=l.y2))
{
if(b.x2>=l.x1 && b.x1<=l.x2)
{
l.x2 = b.x2;
l.y2 = y;
//printf("Test2\n");
}
}
x = ((b.y1 - l.y1)/(l.y2 - l.y1))*(l.x2 - l.x1) + l.x1;
if(l.x1 <= x && l.x2 >= x)
{
if((b.y1<=l.y1 && b.y1>=l.y2) || (b.y1>=l.y1 && b.y1<=l.y2))
{
if(l.y1 >= l.y2)
{
l.x2 = x;
l.y2 = b.y1;
//printf("Test3\n");
}
else
{
l.x1 = x;
l.y1 = b.y1;
//printf("Test4\n");
}
}
}
x = ((b.y2 - l.y1)/(l.y2 - l.y1))*(l.x2 - l.x1) + l.x1;
if(l.x1 <= x && l.x2 >= x)
{
if((b.y2<=l.y1 && b.y2>=l.y2) || (b.y2>=l.y1 && b.y2<=l.y2))
{
if(l.y1 >= l.y2)
{
l.x1 = x;
l.y1 = b.y2;
//printf("Test5\n");
}
else
{
l.x2 = x;
l.y2 = b.y2;
//printf("Test6\n");
}
}
}
// printf("The end\n");
if(inbox(l.x1, l.y1, b)==0 && inbox(l.x2,l.y2,b)==0)
{
l.x1=b.x1;
l.x2=b.x1;
l.y1=b.y1;
l.y2=b.y2;
}
return l;
}
int main()
{
struct line l;
struct line b;
l = makeline();
b = makebox();
int gd = DETECT,gm;
initgraph(&gd,&gm,NULL);
drawline(l);
delay(1000);
drawbox(b);
delay(1000);
cleardevice();
drawbox(b);
l = clipline(l, b);
drawline(l);
delay(5000);
closegraph();
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef char String[128];
typedef enum { false, true } bool;
typedef enum { bird, fish, insect, mammal } typeAnimal;
typedef struct {
typeAnimal type;
double size;
String name;
} Animal;
bool informAnimal (Animal* a);
typeAnimal typeFromString (String type);
char* stringFromType (typeAnimal type);
void makeRoom (Animal*** found, int* size);
void printAnimals (Animal** found, int size);
int main (void) {
int maxSize = 1, currentIndex = -1;
Animal** found = malloc(sizeof(Animal *));
while (true) {
Animal* a = malloc(sizeof(Animal));
if (++currentIndex >= maxSize) {
makeRoom(&found, &maxSize);
}
if (!informAnimal(a)) {
break;
} else {
*(found + currentIndex) = a;
}
}
printAnimals(found, currentIndex);
return 0;
}
// retrieves all data from the user
bool informAnimal (Animal* a) {
String type;
printf("Enter animal information (\"exit\" as name to exit)\n");
printf("What is the name: ");
scanf("%s", a->name);
if (!strcmp(a->name, "exit")) {
return false;
}
printf("What is the size: ");
scanf("%lf", &a->size);
printf("What is the type: ");
scanf("%s", type);
a->type = typeFromString(type);
return true;
}
// finds type from input
typeAnimal typeFromString (String type) {
if (!strcmp(type, "bird")) {
return bird;
} else if (!strcmp(type, "fish")) {
return fish;
} else if (!strcmp(type, "insect")) {
return insect;
} else if (!strcmp(type, "mammal")) {
return mammal;
} else {
perror("invalid animal type. exiting");
exit(-1);
}
}
// finds whichever string it is
char* stringFromType (typeAnimal type) {
switch (type) {
case bird: return "bird";
case fish: return "fish";
case insect: return "insect";
case mammal: return "mammal";
default: return "error";
}
}
// reallocates the space in the list multiplying by 2
void makeRoom (Animal*** found, int* size) {
*size *= 2;
*found = realloc(*found, *size *sizeof(Animal*));
if (*found == NULL) {
perror("memory could not be reallocated. exiting.");
exit(-1);
}
}
// prints out all the animal data
void printAnimals (Animal** found, int size) {
int i;
Animal* a;
printf("The following new species were found:\n");
for (i = 0; i < size; i++) {
a = *(found + i);
printf("%-25s has size %5.2f and is a %s\n", a->name, a->size, stringFromType(a->type));
}
}
|
C
|
//lab 04 - Ejercicio 12 - Programa para mostrar el mayor elemento que tiene la lista
#include <stdio.h>
#include <stdlib.h>
typedef struct Nodo{
int valor;
struct Nodo *sgte;
}nodo;
typedef struct Lista{
nodo *ini;
nodo *fin;
int tam;
}lista;
lista *crearLista(){
lista *newlista;
if (newlista=(lista*)malloc(sizeof(lista))){
newlista->ini=NULL;
newlista->fin=NULL;
newlista->tam=0;
}else{
printf("\nError, memoria no asignada");
}
return newlista;
free(newlista);
}
void agregarNodo(lista *listaA,int num){
nodo *newNodo;
if(newNodo=(nodo*)malloc(sizeof(nodo))){
newNodo->valor=num;
if (listaA->tam==0){
listaA->fin=newNodo;
newNodo->sgte=NULL;
}
newNodo->sgte=listaA->ini;
listaA->ini=newNodo;
listaA->tam++;
}
}
void listarLista(lista *listaO,nodo *ptrO){
if(ptrO==listaO->ini){
printf("\nLos elementos de la lista son");
}
if (ptrO!=NULL){
listarLista(listaO,ptrO->sgte);
printf("\n%d",ptrO->valor);
}
}
int calcularMaximo(lista *listaO,nodo *ptrO){
int mayor=0;
if (ptrO!=NULL){
mayor=calcularMaximo(listaO,ptrO->sgte);
if(mayor<ptrO->valor){
mayor=ptrO->valor;
}
return mayor;
}else{
return mayor;
}
}
int main(int argc, char const *argv[])
{
lista *listaMain;
listaMain=crearLista();
agregarNodo(listaMain,8);
agregarNodo(listaMain,5);
agregarNodo(listaMain,1);
agregarNodo(listaMain,7);
agregarNodo(listaMain,4);
nodo *ptr=listaMain->ini;
listarLista(listaMain,ptr);
ptr=listaMain->ini;
int mayor=calcularMaximo(listaMain,ptr);
printf("\nEl mayor elemento de la lista es: %d \n",mayor);
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <dirent.h>
#include <assert.h>
#include <stdint.h>
#define __STDC_FORMAT_MACROS
#include <inttypes.h>
#include <time.h>
#include "matrixOperations.h"
int file_select(const struct dirent *entry);
int main (int argc, char **argv) {
char databasePath[] = "..//test_images//";
char filenameFilePath[] = "filenamesDB.dat";
char projectedImagesFilePath[] = "testDB.dat";
char *path = (char *) malloc (200 * sizeof (char));
char header[4];
clock_t start, end;
uint64_t i;
uint64_t imgWidth, imgHeight, pixMaxSize;
uint64_t numImages, numPixels;
/* Get # of images and image names from directory */
struct dirent **imageList;
numImages = scandir(databasePath, &imageList, file_select, alphasort);
if (numImages <= 0) {
perror("scandir");
exit (1);
}
/* Get the size of the images */
sprintf (path, "%s%s", databasePath, imageList[0]->d_name);
FILE * sampleImage = fopen (path, "r");
fscanf (sampleImage, "%s %" PRIu64 " %" PRIu64 " %" PRIu64 "", header, &imgHeight, &imgWidth, &pixMaxSize);
fclose (sampleImage);
assert (strcmp (header, "P6") == 0 && pixMaxSize == 255);
/* Calculate number of pixels per image */
numPixels = imgWidth * imgHeight;
/* Allocate the Image array T */
matrix_t *T = m_initialize (UNDEFINED, numPixels,numImages);
// Load images into the matrix
unsigned char *pixels = (unsigned char *) malloc (3 * numPixels * sizeof (unsigned char));
if ( pixels == NULL) {
printf ("malloc error with pixels\n");
}
start = clock();
for (i = 0; i < numImages; i++) {
// Load image
sprintf (path, "%s%s", databasePath, imageList[i]->d_name);
loadPPMtoMatrixCol (path, T, i, pixels);
}
end = clock();
printf("time to load images, time=%g\n",
((double)(end-start))/CLOCKS_PER_SEC);
// Calculate the mean face
start = clock();
matrix_t *m = m_meanRows (T);
end = clock();
printf("time to calc mean face, time=%g\n",
((double)(end-start))/CLOCKS_PER_SEC);
/* Subtract the mean face from the regular images to produce normalized matrix A */
matrix_t *A = T; // To keep naming conventions
start = clock();
for (i = 0; i < numImages; i++) {
m_subtractColumn (A, i, m, 0); //NEED TO MAKE THIS FUNCTION
}
end = clock();
printf("time to calc A, time=%g\n",
((double)(end-start))/CLOCKS_PER_SEC);
/* Calculate the surrogate matrix L */
/* ----- L = (A')*A ----- */
start = clock();
//matrix_t *L = calcSurrogateMatrix (A);
matrix_t *invA = m_inverseMatrix(A);
matrix_t *L = m_matrix_multiply(A,invA,invA->numCols);
end = clock();
printf("time to calc surrogate matrix L, time=%g\n",
((double)(end-start))/CLOCKS_PER_SEC);
/* Calculate eigenvectors for L */
start = clock();
//matrix_t *L_eigenvectors = calcEigenvectorsSymmetric (L);
matrix_t *L_eigenvectors = m_eigenvalues_eigenvectors(L);
end = clock();
printf("time to calc eigenvectors, time=%g\n",
((double)(end-start))/CLOCKS_PER_SEC);
m_free (L);
/* Calculate Eigenfaces */
/* ----- Eigenfaces = A * L_eigenvectors ----- */
start = clock();
matrix_t *eigenfaces = m_matrix_multiply (A, L_eigenvectors, L_eigenvectors->numCols);
end = clock();
printf("time to calc eigenfaces, time=%g\n",
((double)(end-start))/CLOCKS_PER_SEC);
m_free (L_eigenvectors);
/* Transpose eigenfaces */
start = clock();
matrix_t *transposedEigenfaces = m_transpose (eigenfaces);
end = clock();
printf("time to transpose eigenfaces, time=%g\n",
((double)(end-start))/CLOCKS_PER_SEC);
m_free (eigenfaces);
eigenfaces = NULL;
/* Calculate Projected Images */
/* ----- ProjectedImages = eigenfaces' * A ----- */
start = clock();
matrix_t *projectedImages = m_matrix_multiply (transposedEigenfaces, A, A->numCols);
end = clock();
printf("time to calc projectedImages, time=%g\n",
((double)(end-start))/CLOCKS_PER_SEC);
m_free (A);
A = NULL;
// Print the Projected Image matrix and the mean image
FILE * out = fopen (projectedImagesFilePath, "w");
/*fprintMatrix (out, projectedImages);
fprintMatrix (out, eigenfaces);
fprintMatrix (out, m); */
m_fwrite (out, projectedImages);
m_fwrite (out, transposedEigenfaces);
m_fwrite (out, m);
// Write the filenames corresponding to each column
FILE *filenamesFile = fopen (filenameFilePath, "w");
for (i = 0; i < numImages; i++) {
fprintf (filenamesFile, "%s\n", imageList[i]->d_name);
free (imageList[i]);
}
free (imageList);
// Save the mean image -> this is more of for fun and to make sure
// -> the function I wrote worked
writePPMgrayscale("meanImage.ppm", m, 0, imgHeight, imgWidth);
/* COMMENT - could move these up to help memory */
m_free (projectedImages);
m_free (transposedEigenfaces);
m_free (m);
fclose (out);
fclose (filenamesFile);
free (path);
free (pixels);
return 0;
}
int file_select(const struct dirent *entry){
if (strstr(entry->d_name, ".ppm") != NULL) {
return 1;
} else {
return 0;
}
}
|
C
|
/**
* @file
*
* @version 1.0
*
* @section DESCRIPTION
*
* Implementation of the io_metadata API.
*/
#include <stdlib.h>
#include <stdio.h>
#include <stddef.h>
#include <string.h>
#include "io_metadata.h"
#include "jansson.h"
#include "logging.h"
/* Private API ****************************************************************/
/**
* Put a string into the stream but replace all instances of <LF>, aka '\n',
* with "\\n" and tabs from '\n' to "\\n"
*
* NOTE: This is a poor escaping method and shouldn't be used for anything that
* will be parsed. If parsability is needed use `fputjsonstr` or
* `fputjsonstrs`.
*
* @param s the string to put on the stream escaped
* @param stream the stream to put the string on
*/
static void escaping_fputs(const char *s, FILE *stream);
/**
* print a string array to the output as a json array
*
* @param count number of items in strs
* @param strs the array of strings to escape and print
* @param out the stream to write the json array to
*/
static void fputjsonstrs(int count, const char *strs[], FILE *out);
/* Public Impl ****************************************************************/
int io_metadata_put(const char *key, const char *value, FILE *stream)
{
return io_metadata_put_strs(key, value==NULL? 0 : 1, &value, NULL, stream);
}
int io_metadata_put_strs(const char *key, int count, const char *val[],
const char *delim, FILE *stream)
{
int i;
if (delim == NULL)
delim = " ";
fputc('#', stream);
escaping_fputs(key, stream);
if (count > 0)
{
fputs("\t", stream);
escaping_fputs(val[0], stream);
for (i = 1; i < count; i++)
{
escaping_fputs(delim, stream);
escaping_fputs(val[i], stream);
}
}
fputs("\n", stream);
return 0;
}
int io_metadata_put_json(const char *key, int count, const char *val[],
FILE *stream)
{
fputc('#', stream);
escaping_fputs(key, stream);
fputc('\t', stream);
fputjsonstrs(count, val, stream);
fputc('\n', stream);
return 0;
}
/* Private Impl ***************************************************************/
inline void escaping_fputs(const char *s, FILE *out)
{
size_t len;
size_t i;
char c;
for (i = 0, len = strlen(s); i < len; i++)
{
c = s[i];
switch (c)
{
case '\n': fputs("\\n", out); break;
case '\t': fputs("\\t", out); break;
default: fputc(c, out);
}
}
}
inline void fputjsonstrs(int count, const char *strs[], FILE *out)
{
json_t *array;
json_t *string;
int i;
array = json_array();
for (i = 0; i < count; i++)
{
if ((string = json_string(strs[i])) == NULL)
{
log_errorx("cannot print metadata: invalid utf-8 string '%s'",
strs[i]);
json_decref(array);
return;
}
/* *_new functions steal the reference count, so we don't need to call
* json_decref on string */
json_array_append_new(array, string);
}
json_dumpf(array, out, JSON_COMPACT);
json_decref(array);
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* line_not_close.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: mblet <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2016/05/16 00:47:55 by mblet #+# #+# */
/* Updated: 2016/05/20 17:04:47 by mblet ### ########.fr */
/* */
/* ************************************************************************** */
#include "readline.h"
static t_bool s_stack_is_clear(char **astack)
{
if (ft_strlen(*astack) > 0)
{
ft_bzero(sgt_readline()->prompt.buffer, 1024);
ft_sprintf(sgt_readline()->prompt.buffer, "unclosed %s > ",
*astack);
sgt_readline()->prompt.len = strlenprint(sgt_readline()->prompt.buffer);
ft_strdel(astack);
return (true);
}
ft_strdel(astack);
return (false);
}
static void s_check_common_char(char **astack, char c)
{
if (c == '{')
ft_straddchar(astack, c);
else if (c == '}' && ft_strlen(*astack) > 0
&& (*astack)[ft_strlen(*astack) - 1] == '{')
(*astack)[ft_strlen(*astack) - 1] = '\0';
else if (c == '(')
ft_straddchar(astack, c);
else if (c == ')' && ft_strlen(*astack) > 0
&& (*astack)[ft_strlen(*astack) - 1] == '(')
(*astack)[ft_strlen(*astack) - 1] = '\0';
else if (c == '`' && ft_strlen(*astack) > 0
&& (*astack)[ft_strlen(*astack) - 1] == '`')
(*astack)[ft_strlen(*astack) - 1] = '\0';
else if (c == '`')
ft_straddchar(astack, c);
}
static void s_inquote(char *line, size_t *i, char quote, char **astack)
{
ft_straddchar(astack, quote);
while (line[*i] != '\0' && line[*i] != quote)
{
if (quote == '\"' && line[*i] == '\\')
++(*i);
++(*i);
}
if (line[*i] == quote && ft_strlen(*astack) > 0
&& (*astack)[ft_strlen(*astack) - 1] == quote)
(*astack)[ft_strlen(*astack) - 1] = '\0';
}
t_bool readline_line_not_close(void)
{
size_t i;
char *line;
char *stack;
if ((line = sgt_readline()->concat_buffer) == NULL)
return (false);
i = 0;
stack = NULL;
while (line[i])
{
if (line[i] == '\\')
++i;
else if ((line[i] == '\'' || line[i] == '\"') && (i += 1))
s_inquote(line, &i, line[i - 1], &stack);
else
s_check_common_char(&stack, line[i]);
i = (line[i] != '\0') ? ++i : i;
}
return (s_stack_is_clear(&stack));
}
|
C
|
/*************************************************************************
* ---------> File Name: spawn.c
* ---------> Author: chengfeiZH
* ---------> Mail: [email protected]
* ---------> Time: 2015年07月28日 星期二 10时52分13秒
************************************************************************/
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <assert.h>
#include <string.h>
typedef struct config
{
char path[64];
char name[64];
char mem[16];
} Config;
/*
* prog : mini-os启动文件路径
* name : domain名字
* mem : domain内存大小
*/
void spawn(const Config conf)
{
pid_t pid = fork();
if (pid == 0) {
printf("child process!\n");
char confPath[1028];
strcpy(confPath, conf.path);
strcat(confPath, "temp.conf");
printf("path: %s\n", confPath);
FILE *stream = fopen(confPath, "w");
assert(stream);
char content[1024];
strcat(content, "kernel = \"mini-os.gz\"\n");
strcat(content, "name = \"");
strcat(content, conf.name);
strcat(content, "\"\nmemory = ");
strcat(content, conf.mem);
strcat(content, "\non_crash = \"destroy\"\n");
printf("%s\n", content);
assert(fwrite(content, strlen(content), 1, stream)); // 这里要使用strlen,不能使用sizeof
fclose(stream);
//system("ls -l");
} else if (pid < 0) {
perror("fork");
} else {
printf("parent process\n");
}
}
#define x 3
int main()
{
Config conf;
strcpy(conf.path, "/home/zhangchengfei/");
strcpy(conf.name, "mini-os001");
strcpy(conf.mem, "32");
spawn(conf);
return 0;
}
|
C
|
#include <stdio.h>
/*
* cat, reversing each line with a function
*/
#define MAXLINE 1000
int getLine(char s[], int lim);
void reverseStr(char s[]);
int main()
{
int len;
char line[MAXLINE];
while((len = getLine(line, MAXLINE)) > 0)
{
reverseStr(line);
printf("%s\n", line);
}
}
int getLine(char s[], int lim)
{
int c, i;
for(i = 0; i < lim-1 && (c = getchar()) != EOF && c != '\n'; ++i)
s[i] = c;
if(c == '\n')
{
s[i] = c;
++i;
}
s[i] = '\0';
return i;
}
void reverseStr(char s[])
{
int i, n;
char c;
i = 0;
while(s[i] != '\0')
++i;
--i;
for(n = 0; n < i; ++n, --i)
{
c = s[n];
s[n] = s[i];
s[i] = c;
}
}
|
C
|
#include "4.h"
// innentől kezdve a SOROK és az OSZLOPOK értéke 2
#define SOROK 2
#define OSZLOPOK 2
int main()
{
int matrix[SOROK][OSZLOPOK]; // 2*2 mátrix
get_matrix(SOROK, OSZLOPOK, matrix); // bekérjük a mátrix elemeit
print_matrix(SOROK, OSZLOPOK, matrix); // kiírjuk a mátrix elemeit
printf("\n");
fill_matrix(SOROK, OSZLOPOK, matrix); // random számokkal töltjük fel a mátrixot
print_matrix(SOROK, OSZLOPOK, matrix); // kiírjuk ismét a mátrix elemeit
return 0;
}
|
C
|
/*
* main.c
*
* Created on: 8 abr. 2021
* Author: eneko
*/
#include "punto.h"
#include "poligono.h"
#include <stdlib.h>
#include <stdio.h>
void imprimePuntosYDistancia(Punto p1, Punto p2);
float perimetro(Poligono poli);
int main(void) {
Punto p = { 1, 2 };
// printf("(%i, %i)\n", p.x, p.y);
//
// //1.1
Punto p1 = { 3, 4 };
Punto p2 = { 5, 6 };
Punto p3 = { 7, 8 };
//
// //1.3
// printf("-----EJERCICIO 1.3-----\n");
// imprimePuntosYDistancia(p1, p2);
// trasladarXY(&p1, &p2, 5, 6);
// printf("Despues de trasladar los puntos...\n");
// imprimePuntosYDistancia(p1, p2);
// //modificacion 1.3
// printf("-----EJERCICIO 1.3 Modificado-----\n");
// printf("Coordenada X del primer punto: \n");
// scanf("%i", &(p1.x));
// printf("Coordenada Y del primer punto: \n");
// scanf("%i", &(p1.y));
// printf("Coordenada X del segundo punto: \n");
// scanf("%i", &(p2.x));
// printf("Coordenada Y del segundo punto: \n");
// scanf("%i", &(p2.y));
// imprimePuntosYDistancia(p1, p2);
// trasladarXY(&p1, &p2, 5, 6);
// printf("Despues de trasladar los puntos...\n");
// imprimePuntosYDistancia(p1, p2);
//2.2
Poligono poli;
poli.numVertices = 4;
poli.vertices = malloc(sizeof(Punto) * poli.numVertices);
poli.vertices[0] = p;
poli.vertices[1] = p1;
poli.vertices[2] = p2;
poli.vertices[3] = p3;
imprimirPoligono(poli);
printf("%f\n", perimetro(poli));
}
void imprimePuntosYDistancia(Punto p1, Punto p2) {
printf("(%i, %i)\n", p1.x, p1.y);
printf("(%i, %i)\n", p2.x, p2.y);
printf("Distancia = %f\n", distancia(p1, p2));
}
//Esta funcion perimetro deberia ir en poligono.c, pero daba un error.
float perimetro(Poligono poli) {
int i;
float perimetro = 0;
for (i = 0; i < poli.numVertices - 1; ++i) {
perimetro += distancia(poli.vertices[i], poli.vertices[i + 1]);
}
perimetro += distancia(poli.vertices[poli.numVertices - 1], poli.vertices[0]);
return perimetro;
}
|
C
|
/*
** EPITECH PROJECT, 2017
** 42sh
** File description:
** 42sh
*/
#include "my.h"
static const builtin_t built_po[] = {
{"env", &the_printenv},
{"setenv", &the_setenv},
{"unsetenv", &the_unsetenv},
{"cd", &the_cd},
{"alias", &the_alias},
{"history", &the_history},
{"unalias", &the_unalias},
{"where", &the_where},
{"which", &the_which},
{"echo", &my_echo},
{NULL, NULL}
};
int is_builtin2(char **av, shell_t *shell)
{
int tempor = 0;
if (av[0][0] == '!') {
tempor = bttf_com(av, shell);
return (tempor);
}
if (strcmp(av[0], "exit") == 0) {
tempor = the_exit(av, shell);
return (tempor);
}
return (tempor);
}
int is_builtin(char **av, shell_t *shell)
{
int tempor = 0;
int i = 0;
shell->exit_status = 0;
if (!av || !av[0])
return (0);
if (av[0][0] == '!' || strcmp(av[0], "exit") == 0)
return (is_builtin2(av, shell));
for (; built_po[i].func != NULL && strcmp(av[0], built_po[i].name);
i++);
if (built_po[i].func == NULL)
return (27);
if (i == 4 || i == 6)
tempor = built_po[i].func(av, shell->aliases, shell);
else if (i == 5)
tempor = built_po[i].func(av, shell->history, shell);
else
tempor = built_po[i].func(av, shell->env, shell);
return (tempor);
}
|
C
|
#include "among3D.h"
void ft_scale(t_data *data, int x, int y, int color)
{
int a;
int b;
a = (x + 1) * RAD_SCALE;
b = (y + 1) * RAD_SCALE;
x = x * RAD_SCALE;
y = y * RAD_SCALE;
while (y < b)
{
while (x < a)
{
ft_my_pixel_put(data, x, y, color);
x++;
}
x = x - RAD_SCALE;
y++;
}
}
void ft_put_sprites(t_data *data)
{
t_spr *tmp;
int a;
int b;
int x;
int y;
tmp = data->spr;
while (tmp)
{
x = (tmp->x / SCALE - 0.5) + RAD_X * 2;
y = (tmp->y / SCALE - 0.5) + RAD_Y * 2;
a = (x + 1) * RAD_SCALE;
b = (y + 1) * RAD_SCALE;
x = x * RAD_SCALE;
y = y * RAD_SCALE;
while (y < b)
{
while (x < a)
ft_my_pixel_put(data, x++, y, 0xDC143C);
x = x - RAD_SCALE;
y++;
}
tmp = tmp->next;
}
}
int ft_put_wall(t_data *data, char **map)
{
int x;
int y;
x = 0;
y = 0;
while (map[y])
{
x = 0;
while ((map[y])[x])
{
if ((map[y])[x] == '1')
ft_scale(data, x + RAD_X, y + RAD_Y, 0x000000);
else if ((map[y])[x] != ' ')
ft_scale(data, x + RAD_X, y + RAD_Y, 0xFFFFFF);
x++;
}
y++;
}
return (0);
}
void ft_put_player(t_data *data)
{
t_plr plr;
plr = *data->plr;
plr.x = data->plr->x / SCALE;
plr.y = data->plr->y / SCALE;
while (ft_valid_point(data, plr.y, plr.x) &&
(data->map[(int)(plr.y)][(int)(plr.x)] != '1'))
{
plr.x += cos(plr.pov) / RAD_SCALE;
plr.y += sin(plr.pov) / RAD_SCALE;
ft_my_pixel_put(data, (plr.x + RAD_X) * RAD_SCALE,
(plr.y + RAD_Y) * RAD_SCALE, 0xB22222);
}
}
int ft_put_radar(t_data *data)
{
if (!((data->win->height < 500) || (data->win->width < 500)))
{
ft_put_wall(data, data->map);
ft_put_player(data);
}
return (0);
}
|
C
|
#include <stdio.h>
#include <stdbool.h>
#define MAX 7
/*
Al igual que Los anteriores Shell Sort permite el intercambio de numeros dentro de una matriz por mas que estos esten muy separados.
basicamente desplaza al elemento mayor al lugar del elemento menor si esta se encontrara en una posicion con un valor mas alto.
*/
int intArray[MAX] = {4,6,3,2,1,9,7}; // valores
void printline(int count) {
int i;
for(i = 0;i < count-1;i++) {
printf("=");
}
printf("=\n");
}
void display() {
int i;
printf("[");
// Recorrer los elementos del array
for(i = 0;i < MAX;i++) {
printf("%d ",intArray[i]);
}
printf("]\n");
}
void shellSort() {
int inner, outer;
int valueToInsert;
int interval = 1;
int elements = MAX;
int i = 0;
while(interval <= elements/3) {
interval = interval*3 +1;
}
while(interval > 0) {
printf(" iteration %d:",i);
display();
for(outer = interval; outer < elements; outer++) {
valueToInsert = intArray[outer];
inner = outer;
while(inner > interval -1 && intArray[inner - interval]
>= valueToInsert) {
intArray[inner] = intArray[inner - interval];
inner -=interval;
printf(" Numero movido es el: %d\n",intArray[inner]);
}
intArray[inner] = valueToInsert;
printf("El numero: %d fue insertado en la posicion: [%d]\n",valueToInsert,inner);
}
interval = (interval -1) /3;
i++;
}
}
int main() {
printf("Matriz de entrada: ");
display();
printline(50);
shellSort();
printf("Matriz de salida: ");
display();
printline(50);
return 1;
}
/*#include <stdio.h>
void shell_sort (int *a, int n) {
int h, i, j, t;
for (h = n; h /= 2;) {
for (i = h; i < n; i++) {
t = a[i];
for (j = i; j >= h && t < a[j - h]; j -= h) {
a[j] = a[j - h];
}
a[j] = t;
}
}
}
int a[] = {4, 65, 2, -31, 0, 99, 2, 83, 782, 1};
int main (int ac, char **av) {
int n = sizeof a / sizeof a[0];
int i;
for (i = 0; i < n; i++)
printf("%d%s", a[i], i == n - 1 ? "\n" : " ");
shell_sort(a, n);
for (i = 0; i < n; i++)
printf("%d%s", a[i], i == n - 1 ? "\n" : " ");
return 0;
}
*/
|
C
|
#include "shell.h"
#include <path.h>
#include <disk.h>
#include <readline/readline.h>
char *getPrompt()
{
if ( !is_mounted() )
return strdup("➜ ");
char *cwd = get_cwd();
char *prompt = malloc(strlen(cwd) + 4);
strcpy(prompt, cwd);
strcpy(prompt + strlen(cwd), "➜ ");
free(cwd);
return prompt;
}
int main(int argc, char** argv)
{
const char *diskPath = NULL;
const char *cmdPath = NULL;
if (argc > 1)
diskPath = argv[1];
init_mount();
bool exiting = false;
unsigned int i;
char *line = NULL;
while(! is_mounted() )
{
char *disk = readline("Target disk: ");
char tmp[512];
memset(tmp, 0, 512);
if (diskPath)
strcat(tmp, diskPath);
strcat(tmp, disk);
mount(tmp);
free(disk);
}
for(;;)
{
char *prompt = getPrompt();
line = readline(prompt);
free(prompt);
if (line == NULL || strlen(line) == 0)
{
free(line);
line = NULL;
continue;
}
unsigned int cmdOffset = 0;
for (i = 0; i < strlen(line); ++i)
{
if (line[i] == ' ')
++cmdOffset;
else
break;
}
unsigned int sub_argc = 1;
for (i = cmdOffset; i < strlen(line); ++i)
if (line[i] == ' ')
++sub_argc;
char ** sub_argv = malloc((sub_argc + 1) * sizeof(char*));
for (i = 0; i < sub_argc + 1; ++i)
sub_argv[i] = NULL;
char *pch = NULL;
pch = strtok(line + cmdOffset, " ");
char *cmd = strdup(pch);
if (cmd[strlen(cmd) - 1] == '\n') cmd[strlen(cmd) - 1] = '\0';
if (sub_argc > 1)
{
i = 1;
while (pch != NULL)
{
pch = strtok(NULL, " ");
if (pch == NULL)
break;
sub_argv[i] = strdup(pch);
++i;
}
char *last_arg = sub_argv[sub_argc - 1];
if (last_arg[strlen(last_arg) - 1] == '\n') last_arg[strlen(last_arg) - 1] = '\0';
}
if (strcmp(cmd, "exitShell") == 0)
exiting = true;
else
{
char tmp[512];
memset(tmp, 0, 512);
if (cmdPath)
strcat(tmp, cmdPath);
strcat(tmp, cmd);
sub_argv[0] = strdup(tmp);
int result = run(sub_argv);
if (result > 0)
fprintf(stderr, "Command '%s' failed\n", cmd);
}
free(cmd);
for (i = 0; i < sub_argc; ++i)
free(sub_argv[i]);
free(sub_argv);
if (exiting)
break;
free(line);
}
umount();
free(line);
return 0;
}
int run(char ** argv)
{
pid_t pid;
int status;
if (0 == (pid = fork()))
{
if (-1 == execve(argv[0], (char **)argv, NULL))
{
perror(NULL);
return -1;
}
}
while (0 == waitpid(pid, &status, WNOHANG))
usleep(100);
return status;
}
|
C
|
#include "lists.h"
/**
* insert_dnodeint_at_index - inserts a new node at a given position
* @h: head pointer to list
* @idx: position in list to insert node (starts at 0)
* @n: number to store in node
* Return: address of the new node | NULL if it failed
*/
dlistint_t *insert_dnodeint_at_index(dlistint_t **h, unsigned int idx, int n)
{
dlistint_t *new = malloc(sizeof(dlistint_t));
dlistint_t *ptr = *h;
/* Check if malloc failed OR if list doesn't exist and idx is not 0 */
if (new == NULL || (*h == NULL && idx))
return (NULL);
/* Create node */
new->n = n;
new->next = NULL;
new->prev = NULL;
/* If idx is 0, set new->next to head and head to new */
if (idx == 0)
{
if (*h)
{
new->next = *h;
(*h)->prev = new;
}
*h = new;
return (new);
}
/* Traverse to index OR end of list */
while (--idx && ptr->next)
ptr = ptr->next;
/* If at end of list, but not at index, insertion is impossible. */
if (idx)
{
free(new);
return (NULL);
}
/* if there's another node, have new point to it and have it point to new */
if (ptr->next)
{
new->next = ptr->next;
(ptr->next)->prev = new;
}
/* Set new->prev to current pointer and current pointer's next to new */
new->prev = ptr;
ptr->next = new;
return (new);
}
|
C
|
/*
* sample.c - deal with sample buffers
*
* Separated from signal.c January 2022
* Written September 2018 by Chuck McManis
*
* Copyright (c) 2018-2019, Chuck McManis, all rights reserved.
*
* I hereby grant permission for anyone to use this software for any
* purpose that they choose, I do not warrant the software to be
* functional or even correct. It was written as part of an educational
* exercise and is not "product grade" as far as the author is concerned.
*
* NO WARRANTY, EXPRESS OR IMPLIED ACCOMPANIES THIS SOFTWARE. USE IT AT
* YOUR OWN RISK.
*
*/
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
#include <math.h>
#include <complex.h>
#include <arpa/inet.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/unistd.h>
#include <dsp/sample.h>
#include <dsp/signal.h>
/*
* alloc_buf( ... )
*
* Allocate a sample buffer.
*/
sample_buf_t *
alloc_buf(int size, int sample_rate) {
sample_buf_t *res;
res = malloc(sizeof(sample_buf_t));
res->data = malloc(sizeof(sample_t) * size);
if (res->data == NULL) {
fprintf(stderr, "alloc_buf(): malloc fail\n");
res->n = 0;
return res;
} else {
res->n = size;
}
res->n = size;
res->r = sample_rate;
/*
* Initialize min/max to values that will always trigger
* an update on first signal.
*/
res->max_freq = 0;
res->min_freq = (double)(sample_rate);
res->type = SAMPLE_UNKNOWN;
res->nxt = NULL;
/* clear it to zeros */
reset_minmax(res);
clear_samples(res);
/* return, data and 'n' are initialized */
return res;
}
/*
* free_buf(...)
*
* Free a buffer allocated with alloc_buf(). If it has a chained
* buffer linked in, return that pointer.
*/
sample_buf_t *
free_buf(sample_buf_t *sb)
{
sample_buf_t *nxt = (sample_buf_t *) sb->nxt;
if (sb->data != NULL) {
free(sb->data);
}
sb->data = 0x0;
sb->n = 0;
sb->nxt = NULL;
free(sb);
return (nxt);
}
|
C
|
#include<stdio.h>
int main()
{
int a,i,c,d;
float cel , incInFahr ;
float fahrenheit;
scanf("%d",&a);
for(i=1;i<=a;i++)
{
scanf("%d %d",&c,&d);
fahrenheit = (((cel * 9)/5)+32 ) ;
fahrenheit +=incInFahr;
cel = (5/9*(fahrenheit - 32));
printf("Case %d: %.2f\n",i,cel);
}
return 0;
}
|
C
|
/** @file gmst.h
* @brief Implementation of gmst
*
* @author Victor Coman
* @date May 2021
*/
#include "sat_const.h"
#include "gmst.h"
double gmst(double Mjd_UT1)
{
double Secs = 86400.0;
double Mjd_0 = floor(Mjd_UT1);
double UT1 = Secs * (Mjd_UT1 - Mjd_0);
double T_0 = (Mjd_0 - MJD_J2000) / 36525.0;
double T = (Mjd_UT1 - MJD_J2000) / 36525.0;
double gmst = 24110.54841 + 8640184.812866 * T_0 + 1.002737909350795 * UT1 + (0.093104 - pow(6.2, -6) * T) * T * T;
return 2 * M_PI * (gmst / Secs);
}
|
C
|
#include <stdio.h>
int binary_search(int A[], int key, int imin, int imax)
{
if (imax < imin)
return -1;
else
{
int imid = (imin+imax)/2;
if (A[imid] > key)
return binary_search(A, key, imin, imid-1);
else if (A[imid] < key)
return binary_search(A, key, imid+1, imax);
else
return imid;
}
}
int main()
{
int r,c,i,j,found,q,f,p;
int arr[1000][1000];
scanf("%d%d",&r,&c);
for(i = 0; i < r; ++i)
for(j = 0; j < c; ++j)
scanf("%d",&arr[i][j]);
scanf("%d",&q);
for(j=0; j < q; ++j)
{
scanf("%d",&f);
found = 0;
for(i=0; i < r; ++i)
{
p = binary_search(arr[i], f, 0, c);
if ( p == -1)
continue;
else
{
found = 1;
printf("%d %d\n", i, p);
}
}
if ( !found )
printf("-1 -1\n");
}
return 0;
}
|
C
|
/*
COMPUTE UPC DIGIT.
*/
#include<stdio.h>
#include<ctype.h>
#include<string.h>
#define MAX_LEN 100
void read_string(FILE* in, char* word){
// inputs:
// FILE* in = file to read string from
// char* word = pointer to string entered by user
// Function reads the input file and
// transfers the alphanumeric string
// into the character array "word"
int c;
for (c= fgetc(in); isalnum(c); c = fgetc(in), word++)
*word = c;
*word = '\0';
ungetc(c, in);
return;
}
int upc_check_digit(char* word){
// inputs
// char* word = user's string
// outputs
// int check_dig = UPC check digit computed as per the following alg.
/*
Sum the digits at odd-numbered positions (1st, 3rd, 5th, ..., 11th). If you use 0-based indexing, this is the even-numbered positions (0th, 2nd, 4th, ... 10th).
Multiply the result from step 1 by 3.
Take the sum of digits at even-numbered positions (2nd, 4th, 6th, ..., 10th) in the original number, and add this sum to the result from step 2.
Find the result from step 3 modulo 10 (i.e. the remainder, when divided by 10) and call it M.
If M is 0, then the check digit is 0; otherwise the check digit is 10 - M.
*/
int checkdig, x, step1 = 0, step2, step3 =0, M;
char padded_word[12]; // because we are strcpy-ing the word (which has an additional '\0' character)
char* p = padded_word; // because we can't do padded_word++ (understand why!)
int num_missing_digs;
size_t len = strlen(word); // okay because word is NULL terminated
// check for size less than 11
if (len < 11){
num_missing_digs = 11 - len;
for (int i = 0; i < num_missing_digs; i++, p++){
*p = '0';
}
}
strcpy(p, word); // the p++ in the last loop earlier already took our pointer to the next location
printf("The user's padded word is %s\n", padded_word);
for (int i = 0; i<11; i+=2){
x = padded_word[i] - '0';
step1+= x;
}
step2 = 3*step1;
for (int i = 1; i<11; i+=2){
x = padded_word[i]-'0';
step3+= x;
}
step3+= step2;
M = step3%10;
checkdig = (M==0) ? 0 : 10-M;
return checkdig;
}
int main(int argc, char* argv[]){
char inputword[MAX_LEN];
read_string(stdin, inputword);
printf("The user's word is %s\n", inputword);
printf("The UPC check digit is %d\n", upc_check_digit(inputword));
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <errno.h>
#include <time.h>
#include "videojuego.h"
extern int32_t time_now_ms(void);
static void jugador_remover(struct videojuego *vj)
{
struct jugador jugadores_restantes[JUGADORES];
return;
pthread_mutex_lock(&vj->lock);
int l=1;
memcpy(&jugadores_restantes[0], &vj->jugadores[0], sizeof(jugadores_restantes[0]));
for(int k=1; k < vj->jugadores_len; k++){
if(time_now_ms() - vj->jugadores[k].ultimo_ping <= 3000){
continue;
}
fprintf(stderr, "wwwww\n" );
memcpy(&jugadores_restantes[l], &vj->jugadores[k], sizeof(jugadores_restantes[l]));
l++;
}
vj->jugadores_len=l;
memcpy(&vj->jugadores, &jugadores_restantes, sizeof(jugadores_restantes));
pthread_mutex_unlock(&vj->lock);
}
static void jugador_agregar(struct videojuego *vj, struct queue_message *qm)
{
int i;
pthread_mutex_lock(&vj->lock);
if (JUGADORES <= vj->jugadores_len)
return;
for (i = 0; i < vj->jugadores_len; i++) {
if (vj->jugadores[i].id != qm->mensaje.datos.jugador.id)
continue;
vj->jugadores[i].pelota.pos.x = qm->mensaje.datos.jugador.x;
vj->jugadores[i].pelota.pos.y = qm->mensaje.datos.jugador.y;
vj->jugadores[i].choques = qm->mensaje.datos.jugador.choques;
vj->jugadores[i].puntos = qm->mensaje.datos.jugador.puntos;
vj->jugadores[i].ultimo_ping = time_now_ms();
pthread_mutex_unlock(&vj->lock);
jugador_remover(vj);
return;
}
vj->jugadores[i].id = qm->mensaje.datos.jugador.id;
vj->jugadores[i].pelota.r = vj->jugadores[0].pelota.r;
vj->jugadores[i].pelota.pos.x = qm->mensaje.datos.jugador.x;
vj->jugadores[i].pelota.pos.y = qm->mensaje.datos.jugador.y;
vj->jugadores[i].choques = qm->mensaje.datos.jugador.choques;
vj->jugadores[i].puntos = qm->mensaje.datos.jugador.puntos;
vj->jugadores_len++;
fprintf(stderr, "Player %d added\n", vj->jugadores[i].id);
pthread_mutex_unlock(&vj->lock);
jugador_remover(vj);
return;
}
static void process_message(struct videojuego *vj, struct queue_message *qm)
{
switch (qm->mensaje.tipo) {
case MENSAJE_PING:
/* send pong */
break;
case MENSAJE_PONG:
/* update last ping */
break;
case MENSAJE_CONNECT:
/* add player (in connecting) */
break;
case MENSAJE_READY:
/* if player has connected, send all info */
break;
case MENSAJE_MAPAS:
break;
case MENSAJE_MONEDAS:
break;
case MENSAJE_POSICION:
jugador_agregar(vj, qm);
break;
/* queue_enqueue(vj->queue_fs, op); */
}
}
void* recv_thread(void *param)
{
struct videojuego *vj = param;
while (1) {
struct queue_message qm_alloc = {{0}};
struct queue_message *qm = &qm_alloc;
struct mensaje m_alloc = {0};
struct mensaje *m = &m_alloc;
char phost[46] = {0};
char shost[46] = {0};
int pport = 0;
int sport = 0;
int s;
s = socket_recvfrom(vj->sock, m, sizeof(*m), &vj->peer_addr);
if (-1 == s && EAGAIN == errno){
jugador_remover(vj);
continue;
}
if (s <= 0)
continue;
if (m->id == vj->id)
continue;
socket_addr_get_ipv4(&vj->peer_addr, phost, sizeof(phost));
socket_addr_get_ipv4(&vj->self_addr, shost, sizeof(shost));
socket_addr_get_port(&vj->peer_addr, &pport);
socket_addr_get_port(&vj->self_addr, &sport);
fprintf(stderr,
"RECV [%s:%d] <- [%s:%d] recv %d bytes "
"(0x%08x@%d)\n",
shost, sport, phost, pport, s,
m->tipo, m->tiempo);
memcpy(&qm->mensaje, m, sizeof(*m));
memcpy(&qm->addr, &vj->peer_addr, sizeof(vj->peer_addr));
process_message(vj, qm);
}
return NULL;
}
|
C
|
#include "gb.h"
#include <assert.h>
void GB_update_joyp(GB_gameboy_t *gb)
{
if (gb->model & GB_MODEL_NO_SFC_BIT) return;
uint8_t key_selection = 0;
uint8_t previous_state = 0;
/* Todo: add delay to key selection */
previous_state = gb->io_registers[GB_IO_JOYP] & 0xF;
key_selection = (gb->io_registers[GB_IO_JOYP] >> 4) & 3;
gb->io_registers[GB_IO_JOYP] &= 0xF0;
uint8_t current_player = gb->sgb? (gb->sgb->current_player & (gb->sgb->player_count - 1) & 3) : 0;
switch (key_selection) {
case 3:
if (gb->sgb && gb->sgb->player_count > 1) {
gb->io_registers[GB_IO_JOYP] |= 0xF - current_player;
}
else {
/* Nothing is wired, all up */
gb->io_registers[GB_IO_JOYP] |= 0x0F;
}
break;
case 2:
/* Direction keys */
for (uint8_t i = 0; i < 4; i++) {
gb->io_registers[GB_IO_JOYP] |= (!gb->keys[current_player][i]) << i;
}
/* Forbid pressing two opposing keys, this breaks a lot of games; even if it's somewhat possible. */
if (!(gb->io_registers[GB_IO_JOYP] & 1)) {
gb->io_registers[GB_IO_JOYP] |= 2;
}
if (!(gb->io_registers[GB_IO_JOYP] & 4)) {
gb->io_registers[GB_IO_JOYP] |= 8;
}
break;
case 1:
/* Other keys */
for (uint8_t i = 0; i < 4; i++) {
gb->io_registers[GB_IO_JOYP] |= (!gb->keys[current_player][i + 4]) << i;
}
break;
case 0:
for (uint8_t i = 0; i < 4; i++) {
gb->io_registers[GB_IO_JOYP] |= (!(gb->keys[current_player][i] || gb->keys[current_player][i + 4])) << i;
}
break;
default:
break;
}
/* Todo: This assumes the keys *always* bounce, which is incorrect when emulating an SGB */
if (previous_state != (gb->io_registers[GB_IO_JOYP] & 0xF)) {
/* The joypad interrupt DOES occur on CGB (Tested on CGB-E), unlike what some documents say. */
gb->io_registers[GB_IO_IF] |= 0x10;
}
gb->io_registers[GB_IO_JOYP] |= 0xC0;
}
void GB_icd_set_joyp(GB_gameboy_t *gb, uint8_t value)
{
uint8_t previous_state = gb->io_registers[GB_IO_JOYP] & 0xF;
gb->io_registers[GB_IO_JOYP] &= 0xF0;
gb->io_registers[GB_IO_JOYP] |= value & 0xF;
if (previous_state & ~(gb->io_registers[GB_IO_JOYP] & 0xF)) {
gb->io_registers[GB_IO_IF] |= 0x10;
}
gb->io_registers[GB_IO_JOYP] |= 0xC0;
}
void GB_set_key_state(GB_gameboy_t *gb, GB_key_t index, bool pressed)
{
assert(index >= 0 && index < GB_KEY_MAX);
gb->keys[0][index] = pressed;
GB_update_joyp(gb);
}
void GB_set_key_state_for_player(GB_gameboy_t *gb, GB_key_t index, unsigned player, bool pressed)
{
assert(index >= 0 && index < GB_KEY_MAX);
assert(player < 4);
gb->keys[player][index] = pressed;
GB_update_joyp(gb);
}
|
C
|
/*
* PLC firmware is available under the MIT License. See http://opensource.org/licenses/MIT for full text.
*
* Copyright (C) Dmitry Ognyannikov, 2011
* Created: 19.06.2011 22:26:59
*/
#include "os.h"
void InitPins(void)
{
// Registers: DDRA (mode, direction), PORTA (out data), PINA (input)
// set port A as input pins (ADC)
DDRA = 0;
// set port B output pins to low level (disable port pull-ups)
PORTA = 0;
// set port B output pins to low level (disable port pull-ups)
PORTB = 0;
// set port B as out pins (PWM)
DDRB = 0xFF;
// set port C output pins to low level (disable port pull-ups)
PORTC = 0;
// set port D output pins to low level (disable port pull-ups)
PORTD = 0;
InitPWMPins();
gpioInitPins();
}
void InitGPIOPins(void)
{
;
}
uint8_t readPin(uint8_t portNumber, uint8_t pinNumber)
{
uint8_t portValue = 0;
if (portNumber == PORTA_INDEX)
portValue = PINA;
else if (portNumber == PORTB_INDEX)
portValue = PINB;
else if (portNumber == PORTC_INDEX)
portValue = PINC;
else if (portNumber == PORTD_INDEX)
portValue = PIND;
else
ctrlReportErrorWithParameter(CTRLR_SOFTWARE_ILLEGAL_PIN_PORT_NUMER, portNumber);
return (portValue>>pinNumber) & 1;
}
void setPin(uint8_t portNumber, uint8_t pinNumber, uint8_t pinValue)
{
uint8_t portValue = 0;
if (portNumber == PORTA_INDEX)
portValue = PORTA;
else if (portNumber == PORTB_INDEX)
portValue = PORTB;
else if (portNumber == PORTC_INDEX)
portValue = PORTC;
else if (portNumber == PORTD_INDEX)
portValue = PORTD;
else
ctrlReportErrorWithParameter(CTRLR_SOFTWARE_ILLEGAL_PIN_PORT_NUMER, portNumber);
if (pinValue > 0)
portValue |= (1<<pinNumber);
else
portValue &= ~(1<<pinNumber);
if (portNumber == PORTA_INDEX)
PORTA = portValue;
else if (portNumber == PORTB_INDEX)
PORTB = portValue;
else if (portNumber == PORTC_INDEX)
PORTC = portValue;
else if (portNumber == PORTD_INDEX)
PORTD = portValue;
}
void setPinMode(uint8_t portNumber, uint8_t pinNumber, uint8_t mode)
{
uint8_t portValue = 0;
if (portNumber == 0)
portValue = DDRA;
else if (portNumber == 1)
portValue = DDRB;
else if (portNumber == 2)
portValue = DDRC;
else if (portNumber == 3)
portValue = DDRD;
else
ctrlReportErrorWithParameter(CTRLR_SOFTWARE_ILLEGAL_PIN_PORT_NUMER, portNumber);
if (mode > 0)
portValue |= (1<<pinNumber);
else
portValue &= ~(1<<pinNumber);
if (portNumber == 0)
DDRA = portValue;
else if (portNumber == 1)
DDRB = portValue;
else if (portNumber == 2)
DDRC = portValue;
else if (portNumber == 3)
DDRD = portValue;
}
|
C
|
#include "problem_st2.h"
// Grammar:
// logic ::= comp {&&, ||} logic | comp
// comp ::= expr {<,>,==, != etc.} expr | expr;
// expr ::= mult {+, -} expr | mult
// mult ::= term {*, /} mult | term
// term ::= ( logic ) | number
struct node_t *
build_syntax_tree(struct lexem_t** lex) {
//printf("\nBuilding syntax tree...\nTotal lexems: %d\n",lexarr.capacity - 1);
struct lexem_t* enter_point = *lex;
struct node_t* ret = parse_logic(lex);
*lex = enter_point;
*lex = *lex + 1;
if(!ret)
printf("Parse failed: there are some syntax mistakes!\n");
return ret;
}
struct node_t* parse_logic(struct lexem_t** lex){
struct node_t* left = parse_comparation(lex);
if(!left)
return NULL;
if(is_logic(**lex)){
enum operation_t opcode = (**lex).lex.op;
*lex = *lex - 1;
struct node_t* right = parse_logic(lex);
if(!right){
free_syntax_tree(left);
return NULL;
}
struct node_t* expr = create_operation_expression(opcode);
expr->left = right;
expr->right = left;
return expr;
}
else
return left;
}
struct node_t* parse_comparation(struct lexem_t** lex){
struct node_t* left = parse_expr(lex);
if(!left)
return NULL;
if(is_compare(**lex)){
enum operation_t opcode = (**lex).lex.op;
*lex = *lex - 1;
struct node_t* right = parse_expr(lex);
if(!right){
free_syntax_tree(left);
return NULL;
}
struct node_t* expr = create_operation_expression(opcode);
expr->left = right;
expr->right = left;
return expr;
}
else
return left;
}
struct node_t* parse_expr(struct lexem_t** lex){
struct node_t* left= parse_mult(lex);
if(!left)
return NULL;
if(is_plusminus(**lex)){
enum operation_t opcode = (**lex).lex.op;
*lex = *lex - 1;
struct node_t* right = parse_expr(lex);
if(!right){
free_syntax_tree(left);
return NULL;
}
struct node_t* expr = create_operation_expression(opcode);
expr->left = right;
expr->right = left;
return expr;
}
else
return left;
}
int is_logic(struct lexem_t lex){
return (lex.kind == OP && (lex.lex.op == LG_AND || lex.lex.op == LG_OR)) ? 1:0;
}
int is_compare(struct lexem_t lex){
return (lex.kind == OP && (lex.lex.op == EQUAL || lex.lex.op == NOT_EQUAL
|| lex.lex.op == MORE || lex.lex.op == LESS
|| lex.lex.op == EQ_OR_MORE || lex.lex.op == EQ_OR_LESS)) ? 1:0;
}
int is_plusminus(struct lexem_t lex){
return (lex.kind == OP && (lex.lex.op == ADD || lex.lex.op == SUB)) ? 1:0;
}
int is_muldiv(struct lexem_t lex){
return (lex.kind == OP && (lex.lex.op == MUL || lex.lex.op == DIV)) ? 1:0;
}
int is_brace(struct lexem_t lex){
return lex.kind == BRACE ? 1:0;
}
int is_num(struct lexem_t lex){
return lex.kind == NUM ? 1:0;
}
int is_assign(struct lexem_t lex){
return lex.kind == ASSIGN ? 1:0;
}
int is_var(struct lexem_t lex){
return lex.kind == VAR ? 1:0;
}
int is_end(struct lexem_t lex){
return lex.kind == END ? 1:0;
}
int is_semicolon(struct lexem_t lex){
return lex.kind == SEMICOLON ? 1:0;
}
struct node_t* create_operation_expression(enum operation_t opcode){
struct node_t* expr = (struct node_t*)calloc(1,sizeof(struct node_t));
expr->data.k = NODE_OP;
expr->data.u.op = opcode;
return expr;
}
struct node_t* parse_mult(struct lexem_t** lex){
struct node_t* left= parse_term(lex);
if(!left)
return NULL;
if(is_muldiv(**lex)){
enum operation_t opcode = (**lex).lex.op;
*lex = *lex - 1;
struct node_t* right = parse_mult(lex);
if(!right){
free_syntax_tree(left);
return NULL;
}
struct node_t* expr = create_operation_expression(opcode);
expr->left = right;
expr->right = left;
return expr;
}
else
return left;
}
struct node_t* parse_term(struct lexem_t** lex){
if(check_end(*lex)){ //checking if we unexpectly reach the end of expression (e.g. mistakes in lexems). In case when something goes wrong we safely stop building
printf("Unexpected reach of the end of expression!\n");
return NULL;
}
struct node_t* ret = (struct node_t*)calloc(1,sizeof(struct node_t));
switch((**lex).kind){
case BRACE:{
*lex = *lex - 1;
free(ret);
ret = parse_logic(lex);
if(!is_brace(**lex)){ //if expression didn't end with brace, stopping the tree building
free_syntax_tree(ret);
printf("Braces are not correct!\n");
return NULL;
}
*lex = *lex - 1;
return ret;
}
case NUM: {
ret->data.k = NODE_VAL;
ret->data.u.d = (**lex).lex.num;
*lex = *lex - 1;
return ret;
}
case VAR: {
ret->data.k = NODE_VAR;
ret->data.u.name = (char*)calloc(1, sizeof(char));
ret->data.u.name = strcpy(ret->data.u.name, (**lex).lex.name);
*lex = *lex - 1;
return ret;
}
default:{
free(ret);
printf("Unnamed error!\n");
return NULL;
}
}
}
int check_end(struct lexem_t* lex){
return (lex->kind == OP || lex->kind == NUM || lex->kind == VAR || lex->kind == BRACE) ? 0 : 1;
}
struct calc_data_t calculate(struct node_t *top, struct var_table_t table){
struct calc_data_t ret = {CALC_SUCCES, 0};
switch(top->data.k){
case NODE_VAL:{
ret.result = top->data.u.d;
return ret;
}
case NODE_OP:{
struct calc_data_t res1 = calculate(top->left, table);
struct calc_data_t res2 = calculate(top->right, table);
if(res1.stat == CALC_FAILED || res2.stat == CALC_FAILED){
ret.stat = CALC_FAILED;
return ret;
}
switch(top->data.u.op){
case ADD:{
ret.result = res1.result + res2.result;
return ret;
}
case SUB:{
ret.result = res1.result - res2.result;
return ret;
}
case MUL:{
ret.result = res1.result * res2.result;
return ret;
}
case DIV:{
if(res2.result == 0){
printf("Division by zero!\n");
ret.stat = CALC_FAILED;
return ret;
}
else{
ret.result = res1.result / res2.result;
return ret;
}
}
case EQUAL:{
ret.result = (res1.result == res2.result) ? 1:0;
return ret;
}
case NOT_EQUAL:{
ret.result = (res1.result != res2.result) ? 1:0;
return ret;
}
case MORE:{
ret.result = (res1.result > res2.result) ? 1:0;
return ret;
}
case LESS:{
ret.result = (res1.result < res2.result) ? 1:0;
return ret;
}
case EQ_OR_MORE:{
ret.result = (res1.result >= res2.result) ? 1:0;
return ret;
}
case EQ_OR_LESS:{
ret.result = (res1.result <= res2.result) ? 1:0;
return ret;
}
case LG_AND:{
ret.result = (res1.result && res2.result) ? 1:0;
return ret;
}
case LG_OR:{
ret.result = (res1.result || res2.result) ? 1:0;
return ret;
}
default:{
ret.stat = CALC_FAILED;
return ret;
}
}
}
case NODE_VAR:{
struct var_t var = get_var(table, top->data.u.name);
if(is_undef(var)){
throw_the_undef_var_exception(top->data.u.name);
ret.stat = CALC_FAILED;
return ret;
}
ret.result = var.value;
return ret;
}
default:{
ret.stat = CALC_FAILED;
return ret;
}
}
}
void free_syntax_tree(struct node_t * top) {
if(!top)
return;
free_syntax_tree(top->left);
free_syntax_tree(top->right);
if(top->data.k == NODE_VAR)
free(top->data.u.name);
free(top);
}
|
C
|
/*
* Copyright (C) 2015-2017 Alibaba Group Holding Limited
*/
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <fcntl.h>
#include <errno.h>
#include <unistd.h>
int trap_open(const char *path, int flags)
{
#ifdef WITH_LWIP
return -ENOSYS;
#else
int fd = open(path, flags);
if (fd < 0) {
fd = open(path, O_RDWR | O_CREAT, 0644);
}
return fd;
#endif
}
int trap_read(int fd, void *buf, int len)
{
return read(fd, buf, len);
}
int trap_write(int fd, const void *buf, int len)
{
return write(fd, buf, len);
}
int trap_close(int fd)
{
return close(fd);
}
int trap_fcntl(int fd, int cmd, int val)
{
return fcntl(fd, cmd, val);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include "tool.h"
#include <time.h>
#define length 10000
int main()
{
int arr1[length];
fillArray(arr1, length);
//Metod bulbashki//
clock_t Start = clock();
BubbleSort(arr1, length);
clock_t End = clock();
printArray(arr1, length);
printf("\nTime of bubble sorting: %f seconds\n", (double)(End - Start) / CLK_TCK);
printFail(arr1, length);
//Metod viboru//
/*
clock_t Start = clock();
ChoiceSort(arr1, length);
clock_t End = clock();
printArray(arr1, length);
printf("\nTime of choice sorting: %f seconds\n", (double)(End - Start) / CLK_TCK);
printFail(arr1, length);
*/
//Metod vstavki//
/*
clock_t Start = clock();
InsertSort(arr1, length);
clock_t End = clock();
printArray(arr1, length);
printf("\nTime of insert sorting: %f seconds\n", (double)(End - Start) / CLK_TCK);
printFail(arr1, length);
*/
system("PAUSE");
return 0;
}
|
C
|
/**
* \file /arch/x86/gdt.c
* \brief Contains functions for the GDT (Global Descriptors Table) management
*/
#include <types.h>
#include <x86/gdt.h>
/**
* \brief The kernel GDT
*/
static struct Gdt_entry kgdt[NBR_GDT_ENTRIES] __attribute__ ((__aligned__ (8)));
/**
* \brief The value to load in the GDT register.
*
* Contains the physical address and the size of the GDT
*/
static struct Gdt_reg gdtr = {
.limit = NBR_GDT_ENTRIES * sizeof(struct Gdt_entry) - 1,
.linear_base_addr = (uint32_t)&kgdt
};
/**
* \fn void set_gdt_entry(uint32_t n, uint32_t base, uint32_t limit, uint8_t flags1, uint8_t flags2)
* \brief Specifies a new entry in the GDT (which describes a segment).
*
* \param n The index of the entry in the GDT. (Must be lower than NBR_GDT_ENTRIES)
* \param base The base of the segment.
* \param limit The size of the segment.
* \param flags1 Flag related to segment type and the privilege level (DPL)
* \param flags2 Flag related to the operation size (16 or 32 bits) and the granularity.
*
*/
void set_gdt_entry(uint32_t n, vaddr_t base, uint32_t limit, uint8_t flags1, uint8_t flags2)
{
if ( n < NBR_GDT_ENTRIES)
{
kgdt[n].seg_limit_0_15 = (uint16_t)(limit & 0xFFFF);
kgdt[n].base_addr_0_15 = (uint16_t)(base & 0xFFFF);
kgdt[n].base_addr_16_23 = (uint8_t)((base >> 16) & 0xFF);
kgdt[n].flags1 = flags1;
kgdt[n].flags2 = flags2 | (uint8_t)((limit >> 16) & 0xFF);
kgdt[n].base_addr_24_31 = (uint8_t)((base >> 24) & 0xFF);
}
}
/**
* \fn void gdt_init(void)
* \brief Initialise the kernel GDT
*
* Defines the code and data segments for user and supervisor.
*/
void gdt_init(void)
{
//The first segment descriptor must not be used (cf. Intel documentation)
set_gdt_entry(0,0,0,0,0);
//Kernel/user code and data segments
//We use a flat-memory model
set_gdt_entry(GDT_KERNEL_CS_INDEX,
0,0xFFFFF,
GDT_CODE_SEGMENT + GDT_CODE_XR + GDT_PRESENT + GDT_DPL0,
GDT_32B + GDT_GRANULARITY_4KB
);
set_gdt_entry(GDT_KERNEL_DS_INDEX,
0,0xFFFFF,
GDT_DATA_SEGMENT + GDT_DATA_RW + GDT_PRESENT + GDT_DPL0,
GDT_32B + GDT_GRANULARITY_4KB
);
set_gdt_entry(GDT_USER_CS_INDEX,
0,0xFFFFF,
GDT_CODE_SEGMENT + GDT_CODE_XR + GDT_PRESENT + GDT_DPL3,
GDT_32B + GDT_GRANULARITY_4KB
);
set_gdt_entry(GDT_USER_DS_INDEX,
0,0xFFFFF,
GDT_DATA_SEGMENT + GDT_DATA_RW + GDT_PRESENT + GDT_DPL3,
GDT_32B + GDT_GRANULARITY_4KB
);
gdt_flush(&gdtr);
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* wchar_handler.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: aklimchu <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2016/12/28 19:12:42 by aklimchu #+# #+# */
/* Updated: 2017/01/10 15:22:17 by aklimchu ### ########.fr */
/* */
/* ************************************************************************** */
#include "ft_printf.h"
static int count_bytes(unsigned int wchar)
{
if (wchar > 0x0 && wchar <= 0x7F)
return (1);
else if (wchar >= 0x80 && wchar <= 0x7FF)
return (2);
else if (wchar >= 0x800 && wchar <= 0xFFFF)
return (3);
else if (wchar >= 0x10000 && wchar <= 0x1FFFFF)
return (4);
else
return (0);
}
static unsigned char *ascii_str(unsigned int wchar)
{
unsigned char *str;
str = (unsigned char*)ft_strnew(1);
str[0] = (unsigned char)wchar;
return (str);
}
unsigned char *get_wchar(unsigned int wchar)
{
short size;
short i;
unsigned char *str;
unsigned char *curr_byte;
unsigned char rem;
curr_byte = (unsigned char*)&wchar;
if ((size = count_bytes(wchar)) < 2)
return ((size) ? ascii_str(wchar) : (unsigned char*)ft_strnew(0));
str = (unsigned char*)ft_strnew(size);
str[size] = '\0';
i = 0;
rem = 0;
while (i < size)
{
str[size - i - 1] |= rem;
str[size - i - 1] |= (*curr_byte << (i * 2));
rem = (*curr_byte >> (8 - ++i * 2));
str[size - i] &= 63;
str[size - i] |= 128;
curr_byte++;
}
str[0] |= (240 << (4 - size));
return (str);
}
|
C
|
#ifndef __HW_MPU6050_H__
#define __HW_MPU6050_H__
#include <stdint.h>
#include <stdbool.h>
/*
*define struct used for Gyroscope
*if any one want to get Gyroscope data
*he must define this struct first
*/
struct mpu6050Gyroscope
{
int16_t gyroX;
int16_t gyroY;
int16_t gyroZ;
};
/*
*define struct used for Acceleration
*if any one want to get Acceleration data
*he must define this struct first
*/
struct mpu6050Acceleration
{
int16_t acceX;
int16_t acceY;
int16_t acceZ;
};
typedef struct mpu6050Gyroscope mseGyroscope_t;
typedef struct mpu6050Acceleration mseAcceleration_t;
/*init the mpu6050 config*/
bool hwMpu6050Init(void);
/*read mpu6050`s Gyroscope data*/
bool hwMpu6050GetGyroscope(mseGyroscope_t* gyroData);
/*read mpu6050`s Acceleration data*/
bool hwMpu6050GetAcceleration(mseAcceleration_t* acceData);
#endif /* __HW_MPU6050_H__ */
|
C
|
#include "bubble.h"
#include "heap.h"
#include "quick.h"
#include "set.h"
#include "shell.h"
#include "utilities.h"
#include <inttypes.h>
#include <math.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#define OPTIONS "absqhr:n:p:"
#define SEEDMAX 4294967295
#define MAX_COLLUMNS 5
//External variable for keeping track of
//compares and swaps.
extern uint64_t moves;
extern uint64_t compares;
//Sets the default seed, array length, and number
//of elements to print.
uint32_t seed = 7092016;
uint32_t array_size = 100;
uint32_t num_of_elements = 100;
//Function to fill the main array
void fill_array(uint32_t *A, uint32_t n) {
srand(seed);
//30 consecutive bits enabled.
uint32_t random_mask = 0x03FFFFFFF;
//Fills array with random elements.
for (uint32_t i = 0; i < n; i++) {
A[i] = (rand() & random_mask);
}
}
//Function to format and print the array correctly.
void print_array(uint32_t *A, uint32_t p, uint32_t n) {
printf("%d elements, %ld moves, %ld compares\n", n, moves, compares);
if (n < p) {
for (uint32_t i = 0; i < n; i++) {
if ((i > 0) && (i % 5 == 0)) {
printf("\n");
}
printf("%13" PRIu32, A[i]);
}
printf("\n");
}
else {
for (uint32_t i = 0; i < p; i++) {
if ((i > 0) && (i % MAX_COLLUMNS == 0)) {
printf("\n");
}
printf("%13" PRIu32, A[i]);
}
printf("\n");
}
}
//This will be called accordingly, for bad inputs and such.
void print_error() {
fprintf(stderr, "SYNOPSIS\n"
" A collection of comparison-based sorting algorithms.\n\n"
"USAGE\n"
" ./sorting [-absqh] [-n length] [-p elements] [-r seed]\n\n"
"OPTIONS\n"
" -a Enable all sorts.\n"
" -b Enable Bubble Sort.\n"
" -s Enable Shell Sort.\n"
" -q Enable Quick Sort.\n"
" -h Enable Heap Sort.\n"
" -n length Specify number of array elements.\n"
" -p elements Specify number of elements to print.\n"
" -r seed Specify random seed.\n");
}
int main(int argc, char **argv) {
//When 1 or less argument values are inputed an error has occcured.
if (argc < 2) {
fprintf(stderr, "Select at least one sort to perform\n");
print_error();
return 0;
}
//Set the list that will hold all the sorts to empty, or 0 since its a number.
Set sort_list = set_empty();
//Easier to identify sorts especially with labels attached.
typedef enum sorts { all = 0, bubble = 1, shell = 2, quick = 3, heap = 4 } sorts;
//Simply adds sorts to the set, while also modifying print and array options.
//If a is inputted then add all sorts to set.
int opt = 0;
while ((opt = getopt(argc, argv, OPTIONS)) != -1) {
switch (opt) {
case 'a':
for (sorts s = bubble; s <= heap; s++) {
sort_list = set_insert(sort_list, s);
}
break;
case 'b': sort_list = set_insert(sort_list, 1); break;
case 's': sort_list = set_insert(sort_list, 2); break;
case 'q': sort_list = set_insert(sort_list, 3); break;
case 'h': sort_list = set_insert(sort_list, 4); break;
case 'r':
seed = atoi(optarg);
seed = (uint32_t)(seed); //converting to unsigned int
break;
case 'n': array_size = atoi(optarg); break;
case 'p': num_of_elements = atoi(optarg); break;
default: print_error(); return 0;
}
}
//If the set is empty then nothing to do, end program.
if (sort_list == set_empty()) {
print_error();
return 0;
}
//Create the main array, and allocate enough memory for array_size elements
//Of unsigned 32 bits size each.
uint32_t *main_arr = (uint32_t *) calloc(array_size, sizeof(uint32_t));
//For each sort in the set, fill the array, sort the list with the
//right sort, display details, and set moves and compares to 0;
for (sorts s = bubble; s <= heap; s++) {
if (set_member(sort_list, s)) {
switch (s) {
case all: break;
case bubble:
fill_array(main_arr, array_size);
bubble_sort(main_arr, array_size);
printf("Bubble Sort\n");
print_array(main_arr, num_of_elements, array_size);
moves = 0;
compares = 0;
break;
case shell:
fill_array(main_arr, array_size);
shell_sort(main_arr, array_size);
printf("Shell Sort\n");
print_array(main_arr, num_of_elements, array_size);
moves = 0;
compares = 0;
break;
case quick:
fill_array(main_arr, array_size);
quick_sort(main_arr, array_size);
printf("Quick Sort\n");
print_array(main_arr, num_of_elements, array_size);
moves = 0;
compares = 0;
break;
case heap:
fill_array(main_arr, array_size);
heap_sort(main_arr, array_size);
printf("Heap Sort\n");
print_array(main_arr, num_of_elements, array_size);
moves = 0;
compares = 0;
break;
}
}
}
//Frees the space in memory allocated to the array.
free(main_arr);
main_arr = NULL;
return 0;
}
|
C
|
#include <stdio.h>
main(){
int numero;
numero=1;
for(numero = 1; numero < 57; numero++)
{
printf("%d\n", numero);
}
numero=1;
while( numero < 57)
{
printf("%d\n", numero);
numero++;
}
numero=1;
do
{
printf("%d\n", numero);
numero++;
}
while( numero < 57);
}
|
C
|
#include <stdio.h>
int main()
{
int a;
scanf("%d", &a);
puts(a & 1 ? "1" : "0");
return 0;
}
|
C
|
#ifndef __POSIX_SEMAPHORE_H__
#define __POSIX_SEMAPHORE_H__
/*==========================================================================
* FILE: semaphore.h
*
* SERVICES: POSIX semaphore API interface
*
* DESCRIPTION: POSIX semaphore API interface based upon POSIX 1003.1-2004
*
* Copyright (c) 2008-2009 QUALCOMM Technologies Incorporated.
* All Rights Reserved. QUALCOMM Proprietary and Confidential.
*==========================================================================
*
* EDIT HISTORY FOR MODULE
*
* This section contains comments describing changes made to the module.
* Notice that changes are listed in reverse chronological order.
*
* $Header: //source/qcom/qct/core/pkg/bootloaders/rel/1.2.2/boot_images/core/api/kernel/posix/semaphore.h#1 $
*
* when who what, where, why
* -------- --- -------------------------------------------------------
* 10/13/08 cz Initial version.
*==========================================================================*/
typedef unsigned int sem_t;
// constant definitions
#define SEM_FAILED ((sem_t*) 0)
// SUPPORTED API declarations
/* SUPPORTED API declarations */
/** \details
* POSIX standard comes with two kinds of semaphores: named and unnamed
* semaphores.
*
* This implementation of POSIX kernel API only provide unnamed semaphore.
*
* Named semaphore functions, including sem_open(), sem_close(), sem_unlink()
* are not supported.
*
* sem_timedwait() is not provided.
*/
/** \defgroup semaphore POSIX Semaphore API */
/** \ingroup semaphore */
/** @{ */
/** Initialize an unnamed semaphore.
* Please refer to POSIX standard for details.
* @param pshared [in] This implementation does not support non-zero value,
* i.e., semaphore cannot be shared between processes in this implementation.
*/
int sem_init(sem_t *sem, int pshared, unsigned int value);
/** Lock a semaphore.
* Please refer to POSIX standard for details.
*/
int sem_wait(sem_t *sem);
/** Lock a semaphore.
* Please refer to POSIX standard for details.
*/
int sem_trywait(sem_t *sem);
/** Unlock a semaphore.
* Please refer to POSIX standard for details.
*/
int sem_post(sem_t *sem);
/** Get the value of a semaphore.
* Please refer to POSIX standard for details.
*/
int sem_getvalue(sem_t *sem, int *value);
/** Destroy an unnamed semaphore.
* Please refer to POSIX standard for details.
*/
int sem_destroy(sem_t *sem);
/** @} */
#endif //__POSIX_SEMAPHORE_H__
|
C
|
//
// Created by q on 3/24/2020.
//
#include "bst.h"
void errMessage() {
perror(ERR_MEM_ALLOC);
exit(EXIT_FAILURE);
}
BSTNodeT * createNode(int key) {
// function that creates a new node
BSTNodeT * n = (BSTNodeT*)malloc(sizeof(BSTNodeT));
if(!n) {
errMessage();
}
else {
n->key = key;
// new node is initially added as a leaf
n->height = 1;
n->right = n->left = NULL;
}
return n;
}
void printBST(BSTNodeT * root, int level) {
// function that prints the BST, traversing it post order
if(root) {
for(int i=0; i <= level; i++) {
printf(" ");
}
printf("%d\n", root->key);
printBST(root->left, level + 1);
printBST(root->right, level + 1);
}
}
void freeBST(BSTNodeT * root) {
// function that recursively frees the memory allocated to the tree
if(root) {
freeBST(root->left);
freeBST(root->right);
BSTNodeT * temp = root;
free(temp);
}
}
BSTNodeT * getParent(BSTNodeT * root, int key) {
/*
* recursive function that returns the parent of the node given by its key
*/
if(root == NULL) {
return NULL;
}
if(root->key < key) {
return getParent(root->left,key);
}
else if (root->key > key) {
return getParent(root->right,key);
}
else if(hasChildren(root,key)) {
// check is this node has actually a child with given key
return root;
}
}
bool hasChildren(BSTNodeT * node, int key) {
// function that checks if the give node has a child with given key
if((node->left != NULL && node->left->key == key) || (node->right != NULL && node->right->key == key)) {
return true;
}
return false;
}
bool findNode(BSTNodeT * root, int key) {
// function that finds a node in the tree, given its key
// return true when found, otherwise false
if(root == NULL) {
return false;
}
if( root->key == key) {
return true;
}
else if(key < root->key) {
return findNode(root->left,key);
}
else if (key > root->key) {
return findNode(root->right,key);
}
}
void printFound(BSTNodeT * root, int key) {
/*
* function that calls the findNode function and evaluates its return value,
* displaying the corresponding message
*/
if(findNode(root, key)) {
printf("Element %d was found.\n",key);
}
else {
printf("Element %d was not found.\n",key);
}
}
int height(BSTNodeT * node) {
// function that returns tha height of a node or 0, if it's null
if(node == NULL) {
return 0;
}
return node->height;
}
int max(int A, int B) {
// function that returns the maximum of the two numbers
return (A>B) ? A : B;
}
|
C
|
#include <stdio.h>
#include <stdlib.h> /* à compléter pour malloc() et free */
#include <assert.h> /* à compléter pour assert() */
int main(){
int x=1;
int * y;
int ** z;
y = &x ; /* initialisation du pointeur y */
z = (int**) malloc(2*sizeof(int*));
assert(z != NULL);
z[0] = y;
x = 2;
z[1] = y;
printf("*z[0]=%d\t\t*z[1]=%d\n", *z[0], *z[1]);// même valeur car adresse mémoire similaire malgré évolution du contenu
free (z); // mémoire devient dispo
return 0;
}
|
C
|
/*chatroom server function
*想法一(服务端转发):服务端每接受一个客户端的连接就把它的sockfd和sockaddr记录(可用数组记录)下来。
* 当客户端发来消息时,服务端将消息转发给除了该客户端外的所有已连接客户端;
* 当有客户端退出,则把它的sockfd和sockaddr从数组中移除;
*必须包含的功能:可群聊,也可私聊(发送消息时以<IPaddr>或<port>或其<sockfd>开头) (port或者sockfd就会成匿名聊天了)
*考虑拓展的功能:服务端也可发送消息
* */
#include "server.h"
#include "chat_sem.h"
#include "chat_shm.h"
void error_delt(const char *err, int line)
{
fprintf(stderr, "line %d ", line);
perror(err);
exit(EXIT_FAILURE);
}
void sig_child (int signo)
{ /*等待子进程结束并处理善后工作 */
pid_t pid;
int stat;
if (signo == SIGINT)
/*WNOHANG项设置在有尚未终止的子进程在运行前不要堵塞 */
while ((pid = waitpid (-1, &stat, WNOHANG)) > 0)
{
/*do something */
}
return;
}
int servinit ()
{ /*完成服务器端套接字创建初始化、端口绑定及监听 */
int listenfd;
struct sockaddr_in servaddr;
listenfd = socket (AF_INET, SOCK_STREAM, 0);
bzero (&servaddr, sizeof (servaddr));
servaddr.sin_family = AF_INET;
servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
/* inet_pton(AF_INET, "192.168.8.1", &servaddr.sin_addr); */
servaddr.sin_port = htons (SERVER_PORT);
if (bind (listenfd, (struct sockaddr *) &servaddr, sizeof (servaddr)) == -1)
{
error_delt ("bind error", __LINE__);
}
if (listen (listenfd, MAX_LISTEN) == -1)
{
error_delt ("listen error", __LINE__);
}
return listenfd;
}
/* msg_explain
* 函数功能:解析消息
* 详细:判断群聊还好是私聊,如果为私聊则把消息头去掉
* 并返回要私聊的客户端sockfd
* */
int msg_explain (char *msg, int len, struct clientinfo *clients, int maxfd)
{ /*解析消息,判断是否是私聊 */
char ip[16] = {0}, port[8] = {0};
char buff[MAXLINE] = {0};
int index, i;
if (msg[0] != '<') /*没有<ip:port>,说明群聊 */
return -1;
for (index = 1; index <= 16 && index < len; index++)
{
if (msg[index] != ':') /*ip地址结束标记*/
ip[index - 1] = msg[index];
else
break;
}
if (msg[index] != ':')
return -1;
ip[index - 1] = '\0';
i = 0;
for (index = index + 1; index < len; index++)
{
if (msg[index] != '>')
port[i++] = msg[index];
else
break;
}
port[i] = '\0';
if (msg[index] != '>') /*只有"<"标志而没有">" */
return -1;
/*获取除去地址后的消息*/
i = 0;
for (index = index + 1; index < len; index++)
buff[i++] = msg[index];
buff[i] = '\0';
//i = sizeof(msg); /*避免产生警告*/
bzero(msg, sizeof(char)*MAXLINE);
strncpy (msg, buff, strlen (buff));
for (index = 0; index < FD_SETSIZE; index++) /*目标IP、port和已连接客户端对比,如果存在则返回其sockfd */
{
if (clients[index].isempty != 0 && strncmp(ip, clients[index].ip, strlen(ip)) == 0 && atoi(port) == clients[index].port)
return index;
if (index == maxfd)
break;
}
return -1;
}
/* childproc
* 函数功能:转发消息
* 详细:将消息群发或者发到特定的sockfd客户端中
* */
void childproc (int sockfd, int maxfd, struct clientinfo *clients, char *message, int msg_len)
{ /*对已连接的客户端的数据收发处理 */
char msg[MAXLINE] = { 0 };
int index;
int chatfd = 0;
if ((chatfd = msg_explain(message, msg_len, clients, maxfd)) == -1)
{
memset(msg, 0, sizeof(msg));
snprintf (msg, sizeof (msg), "<%s:%d>%s", clients[sockfd].ip, clients[sockfd].port, message);
for (index = 0; index <= maxfd ; index++)
{ /*把消息发送给所有客户端,除了sockfd客户端 */
if (clients[index].isempty == 0 || index == sockfd)
continue;
write (index, msg, strlen (msg));
}
}else
{ /*私聊 */
memset(msg, 0, sizeof(msg));
snprintf (msg, sizeof (msg), "<%s:%d>%s", clients[sockfd].ip, clients[sockfd].port, message);
write (chatfd, msg, strlen (msg));
}
}
|
C
|
///
/// @file frame.c
/// @headerfile frame.h "frame.h"
///
/// @authors
/// Allisson Barros 12/0055619\n
/// Daniel Luz 13/0007714\n
/// Luiz Fernando Vieira 13/0013757\n
/// Mariana Pannunzio 12/0018276\n
/// Mateus Denucci 12/0053080\n
///
/// @date 28/06/2017
///
/// @copyright Copyright © 2017 GrupoSB. All rights reserved.
///
/// @brief
/// Gerenciamento e alocação de memória das frames do programa executado.
///
#include "frame.h"
Decodificador dec[NUM_INSTRUCAO];
Frame* frameCorrente;
int32_t qtdArrays;
static StackFrame* topo = NULL;
///
/// Cria um frame e coloca ele na pilha de frames.
///
/// @param ClassFile* Ponteiro para a estrutura ClassFile.
/// @param CodeAttribute* Ponteiro para a estrutura CodeAttribute.
/// @return @c void
/// @see pushFrame
void criaFrame(ClassFile* classe, CodeAttribute* codeAttribute){
StackFrame* stackFrame = NULL;
stackFrame = (StackFrame*) calloc(sizeof(StackFrame),1);
if(stackFrame == NULL) {
printf("Problema na alocação do frame\n");
}
stackFrame->refFrame = (Frame*) calloc(sizeof(Frame),1);
pushFrame(classe, codeAttribute, stackFrame);
}
///
/// Coloca o frame passado por parametro na pilha de frames e atualiza o topo da pilha.
///
/// @param ClassFile* Ponteiro para a estrutura ClassFile.
/// @param CodeAttribute* Ponteiro para a estrutura CodeAttribute.
/// @param StackFrame* Ponteiro para a estrutura StackFrame
/// @return @c void
void pushFrame(ClassFile* classe, CodeAttribute* codeAttribute, StackFrame* stackFrame){
stackFrame->next = topo;
topo = stackFrame;
topo->refFrame->pc = 0;
topo->refFrame->classe = classe;
topo->refFrame->constantPool = classe->constantPool;
topo->refFrame->maxStack = 2 * codeAttribute->maxStack + 110;
topo->refFrame->maxLocals = codeAttribute->maxLocals;
topo->refFrame->codeLength = codeAttribute->codeLength;
topo->refFrame->code = codeAttribute->code;
topo->refFrame->fields = calloc(sizeof(uint32_t), topo->refFrame->maxLocals);
topo->refFrame->pilhaOp = calloc(1, sizeof(PilhaOp));
topo->refFrame->pilhaOp->operandos = calloc(topo->refFrame->maxStack, sizeof(uint32_t));
topo->refFrame->pilhaOp->depth = 0;
frameCorrente = topo->refFrame;
}
///
/// Retira um frame da pilha de frames e atualiza o topo da pilha.
///
/// @param Nao possui parametros
/// @return @c void
/// @see pushOp
void popFrame() {
StackFrame *anterior;
if (topo->next != NULL) {
frameCorrente = topo->next->refFrame;
if(flagRet == 1) {
pushOp(retorno);
} else if(flagRet == 2) {
pushOp(retAlta);
pushOp(retBaixa);
}
flagRet = 0;
} else {
frameCorrente = NULL;
}
anterior = topo->next;
free(topo->refFrame->pilhaOp->operandos);
free(topo->refFrame->pilhaOp);
free(topo->refFrame->fields);
free(topo->refFrame);
free(topo);
topo = anterior;
}
///
/// Empilha um valor na pilha de operandos.
///
/// @param int32_t Valor a ser inserido na pilha de operandos.
/// @return @c void
void pushOp(int32_t valor) {
if(checkaOverflowPilhaOp()){
printf("Overflow na pilha de operandos!\n");
exit(0);
}
frameCorrente->pilhaOp->operandos[frameCorrente->pilhaOp->depth] = valor;
frameCorrente->pilhaOp->depth += 1;
}
///
/// Desempilha um valor na pilha de operandos.
///
/// @param Nao possui parametros.
/// @return @c int32_t Retorna o valor desempilhado da pilha de operandos.
int32_t popOp() {
frameCorrente->pilhaOp->depth -= 1;
if (checkaUnderflowPilhaOp()) {
printf("profundidade da pilha de operandos negativa: %d\n", frameCorrente->pilhaOp->depth);
printf("pc: %u\n", frameCorrente->pc);
}
return frameCorrente->pilhaOp->operandos[frameCorrente->pilhaOp->depth];
}
///
/// Confere se o tamanho da pilha excedeu o
/// tamanho maximo (max stack)
///
/// @param Nao possui parametros.
/// @return @c int Resultado de uma comparacao (0 ou 1)
int checkaOverflowPilhaOp(){
return frameCorrente->pilhaOp->depth >= frameCorrente->maxStack;
}
///
/// Confere se a profundidade da pilha esta negativa.
///
/// @param Nao possui parametros.
/// @return @c int Resultado de uma comparacao (0 ou 1)
int checkaUnderflowPilhaOp(){
return frameCorrente->pilhaOp->depth < 0;
}
|
C
|
/*************************************************************************
> File Name: open.c
> Author: ggboypc12138
> Mail: [email protected]
> Created Time: 2020年08月22日 星期六 20时35分45秒
************************************************************************/
#include <stdio.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
//int open(const char *pathname, int flags);
//int open(const char *pathname, int flags, mode_t mode);
//返回值:成功返回新分配的文件描述符,出错返回-1并设置errno
int main()
{
//使用open()文件不存在不会自动创建
int fd1 = open("hello.txt", O_RDWR);
if(fd1 == -1)
perror("fd1 :");
//使用O_CREAT需要指定文件权限,若不指定权限位则创建一个无权限的文件
int fd2 = open("world.txt", O_RDWR | O_CREAT);
if(fd2 == -1)
perror("fd2 :");
//S_IWOTH 表示00002权限
//S_IRUSR 表示00200权限
int fd3 = open("linux.txt", O_RDWR | O_CREAT, S_IRWXG | S_IRWXO);
if(fd3 == -1)
perror("fd3 :");
return 0;
}
|
C
|
/* Simple udp server with stop and wait functionality */
#include"packet.h"
char buffer[100/PDR][PACKET_SIZE];
int totalpkts;
int main(void)
{
FILE* fp=fopen("output.txt","w");
fd_set rfds;
totalpkts = 0;
printf("SERVER TRACE\n\n");
printf("TYPE SEQ.NO SIZE CHANNEL\n\n");
struct sockaddr_in serverAddr, clientAddr1, clientAddr2;
int s, i, slen = sizeof(clientAddr1), recv_len;
struct timeval tv;
//char buf[PACKET_SIZE];
DATA_PKT rcv_pkt, ack_pkt;
//create a TCP socket
if ((s = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP)) == -1)
{
die("socket");
}
// zero out the structure
memset((char *)&serverAddr, 0, sizeof(serverAddr));
serverAddr.sin_family = AF_INET;
serverAddr.sin_port = htons(PORT);
serverAddr.sin_addr.s_addr = htonl(INADDR_ANY);
//bind socket to port
if (bind(s, (struct sockaddr *)&serverAddr, sizeof(serverAddr)) < 0)
{
die("socket");
}
int temp1 = listen(s, 5);
if (temp1 < 0)
{
printf("Error in listening");
exit(0);
}
//printf("Now Listening\n");
/*ACCEPTING CONNECTION*/
int clientLength = sizeof(clientAddr1);
int s1;
s1 = accept(s, (struct sockaddr *)&clientAddr1, &clientLength);
if (clientLength < 0)
{
printf("Error in client socket");
exit(0);
}
//printf("connection 2 address is %d\n",clientAddr1.sin_port);
int clientLength2 = sizeof(clientAddr2);
int s2 = accept(s, (struct sockaddr *)&clientAddr2, &clientLength2);
if (clientLength2 < 0)
{
printf("Error in client socket");
exit(0);
}
//printf("connection 2 address is %d\n",clientAddr2.sin_port);
int state = 0;
int sq_no = 0;
int maxval = max(s1, s2);
int handle;
int skip1=0;
int skip2=0;
int index=0;
for(int i=0;i<100/PDR+1;i++){
memset(buffer[i],0,PACKET_SIZE);
}
while (1)
{
FD_ZERO(&rfds);
FD_SET(s1, &rfds);
FD_SET(s2, &rfds);
fflush(stdout);
handle = select(maxval + 1, &rfds, NULL, NULL,NULL);
//printf("handle value is --------------%d\n",handle);
if (FD_ISSET(s1, &rfds))
{
//printf("Waiting for packet %d from sender...\n", sq_no);
//printf("Total packets is %d\n",totalpkts);
//try to receive some data, this is a blocking call
if (recv_len = recv(s1, &rcv_pkt, sizeof(rcv_pkt), 0) < 0)
{
if(index!=0){
for(int i=0;i<index;i++){
fputs(buffer[i],fp);
}
}
die("recv()");
}
totalpkts++;
if (totalpkts % (100 / PDR) == 0)
{
skip1=rcv_pkt.sq_no;
//printf("\n\nskipping as total packets is %d\n\n", totalpkts);
continue;
}
if(rcv_pkt.sq_no==skip1 && skip1!=0){
//strcpy(buffer[0],rcv_pkt.data);
skip1=0;
}
if(skip2 < rcv_pkt.sq_no && skip2!=0){
strcpy(buffer[rcv_pkt.sq_no-skip2-1],rcv_pkt.data);
//printf("Buffering S1 Packet received with seq. no. %d from line %d\n", rcv_pkt.sq_no, rcv_pkt.channelid);
//printf("Packet data is :\n %s\n",rcv_pkt.data);
//printf("skip2 is %d\n\n",skip2);
index++;
}
else{
//printf("S1 Packet received with seq. no. %d from line %d \n", rcv_pkt.sq_no, rcv_pkt.channelid);
//printf("Packet data is :\n %s\n",rcv_pkt.data);
fputs(rcv_pkt.data,fp);
}
if(skip1==0 && skip2==0){
for(int i=0;i<100/PDR;i++){
fputs(buffer[i],fp);
memset(buffer[i],0,PACKET_SIZE);
}
////printf("Stop Buffer bruh \n");
index=0;
}
ack_pkt.sq_no = rcv_pkt.sq_no;
ack_pkt.channelid=rcv_pkt.channelid;
sq_no = rcv_pkt.sq_no + 1;
if (send(s1, &ack_pkt, sizeof(ack_pkt), 0) < 0)
{
die("send()");
}
printf("SEND_ACK %2d NULL %d\n", ack_pkt.sq_no,ack_pkt.channelid);
}
if (FD_ISSET(s2, &rfds))
{
//printf("Waiting for packet %d from sender...\n", sq_no);
//printf("Total packets is %d\n",totalpkts);
//try to receive some data, this is a blocking call
if (recv_len = recv(s2, &rcv_pkt, sizeof(rcv_pkt), 0) < 0)
{
die("recv()");
}
printf("RECV_PKT %2d %ld %d\n", rcv_pkt.sq_no,sizeof(rcv_pkt.data),rcv_pkt.channelid);
totalpkts++;
if (totalpkts % (100 / PDR) == 0)
{
skip2=rcv_pkt.sq_no;
//printf("\n\nskipping as total packets is %d\n\n", totalpkts);
continue;
}
if(rcv_pkt.sq_no==skip2 && skip2!=0){
// strcpy(buffer[0],rcv_pkt.data);
skip2=0;
}
if(skip1 < rcv_pkt.sq_no && skip1!=0){
strcpy(buffer[rcv_pkt.sq_no-skip1-1],rcv_pkt.data);
//printf("Buffering S2 Packet received with seq. no. %d from line %d \n", rcv_pkt.sq_no, rcv_pkt.channelid);
//printf("Packet data is :\n %s\n",rcv_pkt.data);
//printf("skip1 is %d\n\n",skip1);
index++;
}
else{
//printf("S2 Packet received with seq. no. %d from line %d \n", rcv_pkt.sq_no, rcv_pkt.channelid);
//printf("Packet data is :\n %s\n",rcv_pkt.data);
fputs(rcv_pkt.data,fp);
}
if(skip1==0 && skip2==0){
for(int i=0;i<100/PDR;i++){
fputs(buffer[i],fp);
memset(buffer[i],0,PACKET_SIZE);
}
//printf("Stop Buffer bruh \n");
index=0;
}
ack_pkt.sq_no = rcv_pkt.sq_no;
ack_pkt.channelid=rcv_pkt.channelid;
sq_no = rcv_pkt.sq_no + 1;
if (send(s2, &ack_pkt, sizeof(ack_pkt), 0) < 0)
{
die("send()");
}
printf("SEND_ACK %2d NULL %d\n", ack_pkt.sq_no,ack_pkt.channelid);
}
continue;
}
fclose(fp);
close(s);
close(s2);
return 0;
}
int max(int i, int j)
{
if (i >= j)
{
return i;
}
else
{
return j;
}
}
|
C
|
#include <time.h>
#include <stdio.h>
#include <errno.h>
#include <stdarg.h>
#include <stdlib.h>
#include <string.h>
#include "logger.h"
#include "string_allocation.h"
#define RED_BOLD "\033[1;31m" /* 1 -> bold ; 31 -> red */
#define RED "\033[0;31m" /* 0 -> normal ; 31 -> red */
#define YELLOW "\033[1;33m" /* 0 -> normal ; 33 -> yellow */
#define CYAN "\033[0;36m" /* 0 -> normal ; 36 -> cyan */
#define GREEN "\033[0;32m" /* 4 -> underline ; 32 -> green */
#define BLUE "\033[9;34m" /* 9 -> strike ; 34 -> blue */
#define NO_COLOR "\033[0m" /* to flush the previous property */
int verbose = 0;
int color_enabled = 1;
\
void enable_verbose() {
verbose = 1;
LOG(DEBUG, "Verbose enabled!");
}
void disable_color_output() {
color_enabled = 0;
LOG(DEBUG, "Color output disabled!");
}
void die(const char *message) {
if (errno) {
// perror(message);
char *error_message = strerror(errno);
char* whole_message = print_to_string("%s: %s", message, error_message);
LOG(ERROR, whole_message);
}
else {
LOG(ERROR, message);
}
exit(1);
}
void LOG(int type, const char* message_format, ...) {
char* log_type;
char* color;
switch(type) {
case ERROR:
log_type = ERROR_STR;
color = RED_BOLD;
break;
case INFO:
log_type = INFO_STR;
color = CYAN;
break;
case WARN:
log_type = WARN_STR;
color = YELLOW;
break;
case DEBUG:
if (verbose == 0) {
/* ignore debug logging of not verbose */
return;
}
log_type = DEBUG_STR;
color = GREEN;
break;
default:
log_type = UNKNOWN_STR;
color = BLUE;
break;
}
char current_time[TIME_SIZE];
currentTime(current_time);
char* line;
if (color_enabled) {
line =
print_to_string("%s%s %s :: %s%s\n", color, current_time, log_type, message_format, NO_COLOR);
} else {
line = print_to_string("%s %s :: %s\n", current_time, log_type, message_format);
}
va_list argptr;
va_start(argptr, message_format);
if (type != ERROR) {
vfprintf(stdout, line, argptr);
}
else {
vfprintf(stderr, line, argptr);
}
va_end(argptr);
free(line);
}
void currentTime(char* current_time) {
time_t now;
struct tm *tm;
now = time(0);
if ((tm = localtime (&now)) == NULL) {
current_time=" (time_error) ";
return;
}
sprintf(current_time, "%04d-%02d-%02d %02d:%02d:%02d",
tm->tm_year+1900, tm->tm_mon+1, tm->tm_mday,
tm->tm_hour, tm->tm_min, tm->tm_sec);
}
|
C
|
#include <sys/wait.h>
#include <signal.h>
#include "print_wait_status.h" /* Declares printWaitStatus() */
#include "tlpi_hdr.h"
void printStatus(int code, int status) {
if (code == CLD_EXITED) {
printf("Child has exited with a status: %d\n", status);
} else if (code == CLD_KILLED) {
printf("Child was killed by the signal: %d (%s)\n", status, strsignal(status));
} else if (code == CLD_STOPPED) {
printf("Child was stopped by the signal: %d (%s)\n", status, strsignal(status));
} else if (code == CLD_CONTINUED) {
printf("Child continued. \n");
} else {
printf("Unexpected: Child has a status: (status=%x)\n", (unsigned int)status);
}
}
int main(int argc, char *argv[]) {
int status;
pid_t childPid;
if (argc > 1 && strcmp(argv[1], "--help") == 0)
usageErr("%s [exit-status]\n", argv[0]);
switch (fork()) {
case -1: printf("fork");
case 0: /* Child: either exits immediately with given
status or loops waiting for signals */
printf("Child started with PID = %ld\n", (long) getpid());
if (argc > 1) /* Status supplied on command line? */
exit(getInt(argv[1], 0, "exit-status"));
else /* Otherwise, wait for signals */
for (;;)
pause();
exit(EXIT_FAILURE); /* Not reached, but good practice */
default: /* Parent: repeatedly wait on child until it
either exits or is terminated by a signal */
for (;;) {
childPid = waitid(P_ALL, 0, &child, WEXITED | WSTOPPED | WCONTINUED);
if (childPid == -1)
printf("waitid");
printf("waitid() returned: PID=%ld; status=0x%04x (%d,%d)\n",
(long) child.si_pid, child.si_status,
(unsigned int) child.si_status, child.si_status >> 8);
printStatus(NULL, status);
}
}
}
|
C
|
// ======================================================================== //
// Copyright 2009-2015 Intel Corporation //
// //
// Licensed under the Apache License, Version 2.0 (the "License"); //
// you may not use this file except in compliance with the License. //
// You may obtain a copy of the License at //
// //
// http://www.apache.org/licenses/LICENSE-2.0 //
// //
// Unless required by applicable law or agreed to in writing, software //
// distributed under the License is distributed on an "AS IS" BASIS, //
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. //
// See the License for the specific language governing permissions and //
// limitations under the License. //
// ======================================================================== //
#pragma once
/*! \file shapesampler.isph Implements sampling functions for different
* geometric shapes. */
//inline float cos2sin(const float f) { return sqrt(max(0.f,1.f-f*f)); }
//inline float sin2cos(const float f) { return sqrt(max(0.f,1.f-f*f)); }
/*! Cosine weighted hemisphere sampling. Up direction is the z direction. */
inline Sample3f cosineSampleHemisphere(const float u, const float v) {
const float phi = 2.0f * (float(pi)) * u;
const float cosTheta = sqrtf(v);
const float sinTheta = sqrtf(1.0f - v);
return Sample3f(Vec3fa(cosf(phi) * sinTheta,
sinf(phi) * sinTheta,
cosTheta),
cosTheta*(1.f/(float(pi))));
}
/*! Cosine weighted hemisphere sampling. Up direction is provided as argument. */
inline Sample3f cosineSampleHemisphere(const float u, const float v, const Vec3fa& N)
{
Sample3f s = cosineSampleHemisphere(u,v);
return Sample3f(frame(N)*s.v,s.pdf);
}
/*! Samples hemisphere with power cosine distribution. Up direction
* is the z direction. */
inline Sample3f powerCosineSampleHemisphere(const float u, const float v, const float _exp)
{
const float phi = 2.0f * (float(pi)) * u;
const float cosTheta = powf(v,1.0f/(_exp+1.0f));
const float sinTheta = cos2sin(cosTheta);
return Sample3f(Vec3fa(cosf(phi) * sinTheta,
sinf(phi) * sinTheta,
cosTheta),
(_exp+1.0f)*powf(cosTheta,_exp)*0.5f/(float(pi)));
}
/*! Computes the probability density for the power cosine sampling of the hemisphere. */
inline float powerCosineSampleHemispherePDF(const Vec3fa& s, const float _exp) {
if (s.z < 0.f) return 0.f;
return (_exp+1.0f)*powf(s.z,_exp)*0.5f/float(pi);
}
/*! Samples hemisphere with power cosine distribution. Up direction
* is provided as argument. */
inline Sample3f powerCosineSampleHemisphere(const float u, const float v, const Vec3fa& N, const float _exp) {
Sample3f s = powerCosineSampleHemisphere(u,v,_exp);
return Sample3f(frame(N)*s.v,s.pdf);
}
////////////////////////////////////////////////////////////////////////////////
/// Sampling of Spherical Cone
////////////////////////////////////////////////////////////////////////////////
/*! Uniform sampling of spherical cone. Cone direction is the z
* direction. */
inline Sample3f UniformSampleCone(const float u, const float v, const float angle) {
const float phi = (float)(2.0f * float(pi)) * u;
const float cosTheta = 1.0f - v*(1.0f - cosf(angle));
const float sinTheta = cos2sin(cosTheta);
return Sample3f(Vec3fa(cosf(phi) * sinTheta, sinf(phi) * sinTheta, cosTheta), 1.0f/((float)(4.0f*float(pi))*sqr(sinf(0.5f*angle))));
}
/*! Computes the probability density of spherical cone sampling. */
inline float UniformSampleConePDF(const Vec3fa &s, const float angle) {
return select(s.z < cosf(angle), 0.0f, 1.0f/((float)(4.0f*float(pi))*sqr(sinf(0.5f*angle))));
}
/*! Uniform sampling of spherical cone. Cone direction is provided as argument. */
inline Sample3f UniformSampleCone(const float u, const float v, const float angle, const Vec3fa& N) {
Sample3f s = UniformSampleCone(u,v,angle);
return Sample3f(frame(N)*s.v,s.pdf);
}
/*! Computes the probability density of spherical cone sampling. */
inline float UniformSampleConePDF(const Vec3fa &s, const float angle, const Vec3fa &N) {
// return make_select(dot(s,N) < cosf(angle), 0.0f, 1.0f/((float)(4.0f*float(pi))*sqr(sinf(0.5f*angle))));
if (dot(s,N) < cosf(angle))
return 0.f;
else
return 1.0f/((float)(4.0f*float(pi))*sqr(sinf(0.5f*angle)));
}
////////////////////////////////////////////////////////////////////////////////
/// Sampling of Triangle
////////////////////////////////////////////////////////////////////////////////
/*! Uniform sampling of triangle. */
inline Vec3fa UniformSampleTriangle(const float u, const float v, const Vec3fa& A, const Vec3fa& B, const Vec3fa& C) {
const float su = sqrtf(u);
return C + (1.0f-su)*(A-C) + (v*su)*(B-C);
}
////////////////////////////////////////////////////////////////////////////////
/// Sampling of Disk
////////////////////////////////////////////////////////////////////////////////
/*! Uniform sampling of disk. */
inline Vec2f UniformSampleDisk(const Vec2f &sample, const float radius)
{
const float r = sqrtf(sample.x);
const float theta = (2.f*float(pi)) * sample.y;
return Vec2f(radius*r*cosf(theta), radius*r*sinf(theta));
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include "function.h"
int maxValue(Node *tree){
int left_max=0, right_max=0, max = tree->data;
if(tree->left) left_max = maxValue(tree->left);
if(tree->right) right_max = maxValue(tree->right);
if(left_max > max) max = left_max;
if(right_max > max) max = right_max;
return max;
}
|
C
|
#ifndef SQLIST_H_
#define SQLIST_H_
#include <stdio.h>
#include <malloc.h>
#include <stdlib.h>
#include <stdbool.h>
//״̬
#define true 1
#define false 0
#define OK 1
#define ERROR 0
//
typedef int Status;
typedef int ElemType;
//˳
typedef struct SqList{
ElemType* elem;
int length;
int listsize;
}Sq, *pSq;
#define LIST_INIT_SIZE 10
#define LIST_INCREMENT 2
//
void InitList(pSq list);
Status ListInsert(pSq list, ElemType elem, int pov);
Status ListTraverse(pSq list);
ListDelete();
#endif
|
C
|
/*
author : ryoma okuda
id : s1270174
*/
#include <stdio.h>
#include <stdlib.h>
#define A 48271L
#define M 2147483647L
#define Q (M / A)
#define R (M % A)
static int x = 1;
int data[100];
int next_rnd2(void)
{
x = A * (x % Q) - R * (x / Q);
if (x < 0)
x = x + M;
return x;
}
int main()
{
int getrand, i;
int count[30] = {0};
for (i = 0; i < 1000; i++)
{
getrand = next_rnd2();
count[getrand % 30]++;
}
for (i = 0; i < 30; i++)
{
printf("%.2d: (num) -> %d\n", i, count[i]);
}
printf("\n");
return 0;
}
|
C
|
#include "libmx.h"
static void printerr_line(int i);
static void empty_lines(char *strarr);
static void INVLD_LINE_ASCII(char **strarr);
static void INVLD_LINE_INPUT(char **strarr);
static void INVLD_LINE1_DIGIT(char *strarr);
static void INVLD_FILE(int c, char *v[]);
void mx_pf_errors(int c, char *v[]) {
INVLD_FILE(c, v); // chech file
char *str = mx_file_to_str(v[1]);
empty_lines(str);
char **strarr = mx_strsplit(str, '\n');
INVLD_LINE1_DIGIT(strarr[0]); // chech if line1 is digit
INVLD_LINE_INPUT(strarr); // chech if line is correct '-' ','
INVLD_LINE_ASCII(strarr); // chech if line is correct ascii
mx_strdel(&str); // clean all leaks
mx_del_strarr(&strarr);
}
static void empty_lines(char *str) { //заодно рахує кількість островів
int k = 0;
for (int i = 0; i < mx_strlen(str) - 1; i++) {
if (str[i] == '\n') {
k++;
if (str[i] == str[i + 1]) {
printerr_line(k);
exit(1);
}
}
}
if (str[mx_strlen(str) - 1] == '\n') {
printerr_line(k);
exit(1);
}
}
static void INVLD_FILE(int c, char *v[]) {
if (c != 2) { // chech for arguments = 2
mx_printerr("usage: ./pathfinder [filename]\n");
exit(1);
}
int file = open(v[1], O_RDONLY);
if (file < 0) { // chech if v[1] exists
mx_printerr("error: file ");
mx_printerr(v[1]);
mx_printerr(" does not exist\n");
exit(1);
}
char buf[1]; // chech if v[1] isn't empty
int n = read(file, buf, sizeof(buf));
if (n <= 0) {
mx_printerr("error: file ");
mx_printerr(v[1]);
mx_printerr(" is empty\n");
exit(1);
}
if (buf[0] == '\n') {
printerr_line(0);
exit(1);
}
close(file);
}
static void INVLD_LINE1_DIGIT(char *strarr) {
for (int i = 1; i < mx_strlen(strarr); i++) {
if (!mx_isdigit(strarr[i])) {
mx_printerr("error: line 1 is not valid\n");
exit(1);
}
}
}
static void INVLD_LINE_INPUT(char **strarr) {
for (int i = 1; strarr[i]; i++) {
int count_space = 0;
int count_comma = 0;
int get_char = 0;
for (int j = 0; strarr[i][j] && count_space < 2; j++) {
get_char = mx_get_char_index(&strarr[i][j], '-');
if (get_char != -1) {
count_space += 1;
j += get_char;
}
else break;
}
for (int j = 0; strarr[i][j] && count_comma < 2; j++) {
get_char = mx_get_char_index(&strarr[i][j], ',');
if (get_char != -1) {
count_comma += 1;
j += get_char;
}
else break;
}
if (count_comma != 1 || count_space != 1) {
printerr_line(i);
exit(1);
}
}
}
static void INVLD_LINE_ASCII(char **strarr) {
char **tmp = NULL;
for (int i = 1; strarr[i]; i++) {
tmp = mx_pf_split(strarr[i]);
if (tmp[0][0] == '\0' || tmp[1][0] == '\0' || tmp[2][0] == '\0')
printerr_line(i);
for (int j = 0; j < mx_strlen(tmp[0]); j++) {
if (!mx_isalpha(tmp[0][j])) {
printerr_line(i);
}
}
for (int j = 0; j < mx_strlen(tmp[1]); j++) {
if (!mx_isalpha(tmp[1][j])) {
printerr_line(i);
}
}
for (int j = 0; j < mx_strlen(tmp[2]); j++) {
if (!mx_isdigit(tmp[2][j])) {
printerr_line(i);
}
}
mx_del_strarr(&tmp);
}
}
static void printerr_line(int i) {
mx_printerr("error: line ");
mx_printerr(mx_itoa(i + 1));
mx_printerr(" is not valid\n");
exit(1);
}
|
C
|
#include <stdio.h>
#include <string.h>
#include <winsock.h>
#define MAXLINE 1024
int main(int argc, char** argv) {
WSADATA wsadata;
SOCKET sd;
struct sockaddr_in serv;
int i, n, serv_len = sizeof(serv);
char str[1024] = "How are you?";
// Is WSAStartup() U WinSock DLL ϥ
WSAStartup(0x101,(LPWSADATA) &wsadata);
sd=socket(AF_INET, SOCK_DGRAM, 0);
// su@dzơA]tg sockaddr_in c (serv) C
// eGserver IP }Aport number C
serv.sin_family = AF_INET;
serv.sin_addr.s_addr = inet_addr("127.0.0.1");
serv.sin_port = htons(5678);
// ǰehow are youecho server
for(i=0; i<MAXLINE; i++) {
sendto(sd, str, strlen(str)+1, 0, (LPSOCKADDR)&serv, serv_len);
printf("client: client->server: %s\n" ,str);
// echo server
n=recvfrom(sd, str, MAXLINE, 0, (LPSOCKADDR)&serv, &serv_len);
str[n]='\0';
printf("client: server->client: %s\n",str);
}
// TCP socket
closesocket(sd);
// WinSock DLL ϥ
WSACleanup();
return 0;
}
|
C
|
#ifndef __DEQUE_H__
#define __DEQUE_H__
#define TRUE 1
#define FALSE 0
typedef int Data;
typedef struct _node
{
Data data;
struct _node *prev;
struct _node *next;
} Node;
typedef struct _DLdeque
{
Node *head;
Node *tail;
} DLDeque;
typedef DLDeque Deque;
void DequeInit(Deque *pdeq);
int DQIsEmpty(Deque *pdep);
void DQAddFirst(Deque *pdeq, Data data);
void DQAddLast(Deque *pdeq, Data data);
Data DQRemoveFirst(Deque *pdeq);
Data DQRemoveLast(Deque *pdeq);
Data DQPeekFirst(Deque *pdeq);
Data DQPeekLast(Deque *pdeq);
#endif
|
C
|
#include "holberton.h"
#include <stdio.h>
#include <stdlib.h>
/**
* _strdup - hat returns a pointer to a newly allocated space in memory
* @str: string
* Return: Return NULL if str = 0
*/
char *_strdup(char *str)
{
int largo;
char *b;
char *c;
if (str == NULL)
return (NULL);
while (str[largo] != '\0')
{
largo++;
}
b = (char *)malloc(sizeof(char) * largo + 1);
if (b == NULL)
return (NULL);
c = b;
while (*str)
{
*c = *str;
c++;
str++;
}
*c = '\0';
return (b);
}
|
C
|
#include<stdio.h>
#include<stdlib.h>
int cmp(const void *a,const void *b)
{
return *(int*)a-*(int*)b;
}
int main() {
int t, n;
scanf("%d",&t);
while(t--){
int n,l[10002];
scanf("%d",&n);
for (int i = 0; i < n; i++)
scanf("%d",&l[i]);
qsort(l,n,sizeof(int),cmp);
int max = 0;
for (int k = 2; k < n; k++) {
if(max<l[k]-l[k-2])
max=l[k]-l[k-2];
}
printf("%d\n",max);
}
return 0;
}
|
C
|
#include<stdio.h>
int main(int argc, char const *argv[])
{
int i;
printf("number square cube\n");
for(i=0; i<=10; i++){
printf("%d %6d %6d\n", i, i*i, i*i*i);
}
return 0;
}
|
C
|
//
// Created by snorcros on 11/18/20.
//
#include "mpi_labs.h"
/**
* Реализуйте на основе технологии MPI
* многопоточную программу умножения
* длинных целых чисел методом Шёнхаге — Штрассена
* */
// Инициализация массива, представляющего собой число
void init_num(int *num, int len, int simple)
{
int i;
i = 0;
while (i < len)
{
num[i] = simple;
i++;
}
}
// Печать массива, представляющего собой число
void print_num(int *num, int len)
{
int i;
i = len;
while (i > 0)
{
i--;
printf("%d", num[i]);
}
printf("\n");
}
int *multiply(int *num1, int len_num1, int *num2, int len_num2, int ProcRank, int ProcNum, MPI_Comm comm)
{
int *result;
int len_res = len_num1 + len_num2;
result = (int *)malloc(sizeof(int) * len_res);
for (int i = 0; i < len_num1 + len_num2; i++)
result[i] = 0;
if (len_num2 == ProcNum)
{
int i = ProcRank;
int rest = 0;
for (int j = len_num1 - 1; j >= 0; j--)
{
int intTemp = num2[i] * num1[j] + rest;
if (intTemp < 10)
{
if (result[(i + j + 1)] + intTemp < 10)
result[(i + j + 1)] += intTemp;
else
{
div_t yetAnotherRest = div(result[(i + j + 1)] + intTemp, 10);
result[(i + j + 1)] = yetAnotherRest.rem;
result[(i + j)] += yetAnotherRest.quot;
}
}
else
{
if (result[(i + j + 1)] + (intTemp % 10) < 10)
{
result[(i + j + 1)] += intTemp % 10;
result[(i + j)] += div(intTemp, 10).quot;
}
else
{
div_t yetAnotherRest = div(result[(i + j + 1)] + (intTemp % 10), 10);
result[(i + j + 1)] = yetAnotherRest.rem;
result[(i + j)] += div(intTemp, 10).quot + yetAnotherRest.quot;
}
}
}
int *res_all_proc;
if (ProcRank == 0)
res_all_proc = (int *)malloc(sizeof(int) * len_res * ProcNum);
// отправляем результаты умножения главному процессу
MPI_Gather(result, (len_num1 + len_num2), MPI_INT, res_all_proc, len_res, MPI_INT,
0, comm);
printf("Proc%d send %d (first num in res)\n", ProcRank, result[len_res]);
fflush(0);
if (ProcRank == 0)
{
int tail;
for (int i = 0; i < (len_num1 + len_num2); i++)
result[i] = 0;
// объединяем результаты полученные от детей (делаем переносы через разряды)
for (int i = 0; i < (len_num1 + len_num2); i++)
{
tail = 0;
for (int j = 0; j < (len_num1 + len_num2) * ProcNum; j = j + (len_num1 + len_num2))
tail += res_all_proc[i + j];
if (tail < 10)
result[i] += tail;
else
{
div_t rest = div(tail, 10);
result[i] = rest.rem;
int k = i;
while (result[k - 1] + rest.quot >= 10)
{
k--;
rest = div(result[k] + rest.quot, 10);
result[k] = rest.rem;
}
result[k - 1] += rest.quot;
}
}
}
if (ProcRank == 0)
free(res_all_proc);
return result;
}
else
return NULL;
}
int lab6(int *num1, int *num2, int N, int ProcNum, int ProcRank, MPI_Comm comm)
{
int *res_mul;
res_mul = multiply(num1, N, num2, N, ProcRank, ProcNum, comm);
if (ProcRank == 0)
{
if (res_mul != NULL)
{
printf("\nResult:\n");
fflush(0);
print_num(res_mul, N * 2);
}
else
printf("The count of processes and digits in the second number must be the same!");
}
free(res_mul);
return (0);
}
// run with /usr/bin/mpiexec -np 4
int main(int argc, char* argv[])
{
if (argc != 2)
return (0);
int ProcNum, ProcRank;
// int N = atoi(argv[1]); // Длина целых чисел
int N = 4; // Длина целых чисел
int *num1 = (int *)malloc(sizeof(int) * N);
int *num2 = (int *)malloc(sizeof(int) * N);
init_num(num1, N, 4);
init_num(num2, N, 2);
MPI_Init(&argc, &argv);
MPI_Comm_size(MPI_COMM_WORLD, &ProcNum);
MPI_Comm_rank(MPI_COMM_WORLD, &ProcRank);
// <программный код с использованием MPI функций>
if (ProcRank == 0)
{
printf("Будем перемножать числа:\n");
fflush(0); // сброс буфера
print_num(num1, N);
print_num(num2, N);
}
MPI_Comm grid_comm;
int my_grid_rank;
int coordinates[2];
MPI_Comm old_comm;
int ndims, reorder, periods[2], dim_size[2];
old_comm = MPI_COMM_WORLD;
ndims = 2; /* 2D matrix/grid */
dim_size[0] = 2; /* rows */
dim_size[1] = 2; /* columns */
periods[0] = 1; /* row periodic (each column forms a ring) */
periods[1] = 0; /* columns non-periodic */
reorder = 1; /* allows processes reordered for efficiency */
// создаём декартову топологию
MPI_Cart_create(old_comm, ndims, dim_size, periods, reorder, &grid_comm);
// Получаем ранг процесса
MPI_Comm_rank(grid_comm, &my_grid_rank);
// Получаем координаты процесса
MPI_Cart_coords(grid_comm, my_grid_rank, 2, coordinates);
printf("Process rank %i has coordinates %i %i\n", my_grid_rank, coordinates[0], coordinates[1]);
fflush(0); // сброс буфера
lab6(num1, num2, N, ProcNum, my_grid_rank, grid_comm);
MPI_Finalize();
free(num1);
free(num2);
return (0);
}
|
C
|
#include "utils.h"
bool checkIfLabelStringIsValidInInstruction(char* input_word)
{
while (*input_word) {
if (!isdigit(*input_word) && !isalpha((*input_word)))
return false;
input_word++;
}
return true;
}
bool checkIfLabelStringIsValidInStart(char* input_word) {
int count = 0;
int check = strlen(input_word)-1;
if (input_word[strlen(input_word) - 1] == ':') {
if (!isalpha(*input_word))
return false;
while ((*input_word)) {
if ((*input_word) == ':' && count == check)
return true;
if (!isalpha((*input_word)) || isdigit((*input_word)))
return false;
count++;
input_word++;
}
}
return false;
}
bool checkIfImmediateInRange(char* input_word) {
int num;
num = strtol(input_word, NULL, 10);
return ((num > INT16_MIN) && (num < INT16_MAX));
}
bool checkIfStringIsRegister(char* input_word)
{
if (strlen(input_word) == 2) {
if (input_word[0] == '$' && isdigit(input_word[1]))
return true;
}
if (strlen(input_word) == 3) {
if (input_word[0] == '$' && isdigit(input_word[1]) && isdigit(input_word[2]))
return true;
}
return false;
}
bool checkIfStringIsImmediateNumber(char* input_word)
{
if (isdigit(*input_word) || (*input_word) == '+' || (*input_word) == '-') {
input_word++;
while (*input_word) {
if (!isdigit(*input_word))
return false;
input_word++;
}
return true;
}
else
return false;
}
bool checkIfStringIsGuideData(char* input_word)
{
return(*input_word == '.');
}
|
C
|
/*
** my_swap.c for my_swap in /home/rosey_c/rendu/Piscine-C-simple
**
** Made by rosey
** Login <[email protected]>
**
** Started on Fri Oct 18 16:31:29 2013 rosey
** Last update Fri Oct 18 17:21:20 2013 rosey
*/
int my_putchar(char c)
{
write(1, &c, 1);
}
int my_swap(int *a, int *b)
{
int ptr;
ptr = *a;
*a = *b;
*b = ptr;
}
int main()
{
int a;
int b;
a = 70;
b = 80;
my_swap(&a, &b);
my_putchar(a);
}
|
C
|
#include "tabrakan.h"
#include <stdlib.h>
void gambarHancur(titik p) {
//titik pe = {p.x,p.y};
int i = 0;
//titik pd = {p.x+10,p.y-10};
for (i=0;i<10;i++) {
usleep(50000-(i*5000));
warna c = {255, 10+20*i, 0, 255};
bufferDrawCircle(p, 10-1*i, c);
}
for (;i>=0;i--) {
usleep(100000-(i*10000));
warna c = {255, 200-15*i, 0, 255};
bufferDrawCircle(p, 20-2*i, c);
}
/* Use this one for bigger explosion
*
for (i=0;i<10;i++) {
usleep(50000-(i*5000));
warna c = {255, 10+20*i, 0, 255};
bufferDrawCircle(p, 20-2*i, c);
}
for (;i>=0;i--) {
usleep(100000-(i*10000));
warna c = {255, 200-15*i, 0, 255};
bufferDrawCircle(p, 40-4*i, c);
}
* */
}
void gambarObjek() {
int i_pesawat, i_peluru, i, j;
// Gambar pesawat
for(i_pesawat = 0; i_pesawat < 1; i_pesawat++) {
titik d = pesawat[i_pesawat].posisi;
titik e = {d.x + 20, d.y+10};
// Kepala pesawat
for (i=0; i<10; i++) {
warna c = {235+i*2, 235+i*2, 235+i*2, 255};
bufferDrawCircle(e, 10-1*i, c);
}
// Sayap kiri
for(i = 0; i < 15; i++) {
for(j = 0; j < 25; j++){
titik m = {d.x + i-5, d.y + j-10};
warna x = {255-4*abs(10-i), 255-4*abs(10-i), 255-4*abs(10-i), 255};
bufferDrawDot(m, x);
}
}
// Body
for(i = 0; i < 50; i++) {
for(j = 0; j < 21; j++){
titik m = {d.x + i-27, d.y + j};
warna x = {255-5*abs(11-j), 255-5*abs(11-j), 255-5*abs(11-j), 255};
bufferDrawDot(m, x);
}
}
// Sayap kanan
for(i = 0; i < 15; i++) {
for(j = 0; j < 25; j++){
titik m = {d.x + i-5, d.y + j+ 10};
warna x = {255-5*abs(10-i), 255-5*abs(10-i), 255-5*abs(10-i), 255};
bufferDrawDot(m, x);
}
}
// Ekor
for(i = 0; i < 10; i++) {
for(j = 0; j < 28; j++){
titik m = {d.x + i-35, d.y + j - 7};
warna x = {255-5*abs(17-j), 255-5*abs(17-j), 255-5*abs(17-j), 255};
bufferDrawDot(m, x);
}
}
}
// Gambar peluru
for(i_peluru = 0; i_peluru < 1; i_peluru++) {
titik d = peluru[i_peluru].posisi;
for (i=0; i<5; i++) {
warna c = {200, 150+20*i, 0, 255};
bufferDrawCircle(d, 5-1*i, c);
}
for (i=0; i<10; i++) {
for(j = 0; j < 20; j++){
titik e = {d.x + i-5, d.y + j+3};
warna x = {220, 200-10*abs(3-i), 0, 255};
bufferDrawDot(e, x);
}
}
}
}
|
C
|
#define NULL ((void*)0)
typedef unsigned long size_t; // Customize by platform.
typedef long intptr_t; typedef unsigned long uintptr_t;
typedef long scalar_t__; // Either arithmetic or pointer type.
/* By default, we understand bool (as a convenience). */
typedef int bool;
#define false 0
#define true 1
/* Forward declarations */
typedef struct TYPE_4__ TYPE_1__ ;
/* Type definitions */
struct TYPE_4__ {int read_pipe; int /*<<< orphan*/ * handle_err; int /*<<< orphan*/ * process; int /*<<< orphan*/ * handle; } ;
typedef TYPE_1__ os_process_pipe_t ;
typedef int /*<<< orphan*/ * HANDLE ;
/* Variables and functions */
int /*<<< orphan*/ CloseHandle (int /*<<< orphan*/ *) ;
int /*<<< orphan*/ HANDLE_FLAG_INHERIT ;
int /*<<< orphan*/ SetHandleInformation (int /*<<< orphan*/ *,int /*<<< orphan*/ ,int) ;
TYPE_1__* bmalloc (int) ;
int /*<<< orphan*/ create_pipe (int /*<<< orphan*/ **,int /*<<< orphan*/ **) ;
int create_process (char const*,int /*<<< orphan*/ *,int /*<<< orphan*/ *,int /*<<< orphan*/ *,int /*<<< orphan*/ **) ;
os_process_pipe_t *os_process_pipe_create(const char *cmd_line,
const char *type)
{
os_process_pipe_t *pp = NULL;
bool read_pipe;
HANDLE process;
HANDLE output;
HANDLE err_input, err_output;
HANDLE input;
bool success;
if (!cmd_line || !type) {
return NULL;
}
if (*type != 'r' && *type != 'w') {
return NULL;
}
if (!create_pipe(&input, &output)) {
return NULL;
}
if (!create_pipe(&err_input, &err_output)) {
return NULL;
}
read_pipe = *type == 'r';
success = !!SetHandleInformation(read_pipe ? input : output,
HANDLE_FLAG_INHERIT, false);
if (!success) {
goto error;
}
success = !!SetHandleInformation(err_input, HANDLE_FLAG_INHERIT, false);
if (!success) {
goto error;
}
success = create_process(cmd_line, read_pipe ? NULL : input,
read_pipe ? output : NULL, err_output,
&process);
if (!success) {
goto error;
}
pp = bmalloc(sizeof(*pp));
pp->handle = read_pipe ? input : output;
pp->read_pipe = read_pipe;
pp->process = process;
pp->handle_err = err_input;
CloseHandle(read_pipe ? output : input);
CloseHandle(err_output);
return pp;
error:
CloseHandle(output);
CloseHandle(input);
return NULL;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <netinet/in.h>
int main(){
int socked_id = 0;
int conexion = 0;
char msm[]="Mi primer socket exitoso";
//Estructura de conexion al server
struct sockaddr_in Server_Ramon ;
Server_Ramon.sin_family= AF_INET;//Familia de protocolos
Server_Ramon.sin_addr.s_addr = inet_addr("127.0.0.1");// Direccion Ip del server
Server_Ramon.sin_port = htons(12000); //El puerto(Direccion de memoria) que estoy utilizando para enviar la info.
// Creo mi socket
socked_id = socket(AF_INET, SOCK_STREAM, 0);
//Ahora estableceremos la conexion entre el socket y el server
conexion = connect(socked_id, (struct sockaddr*)&Server_Ramon, sizeof(Server_Ramon));
if(conexion < 0){
printf("Conexion fallida\n\r");
return(-1);
}
printf("Conexion Exitosa\n\r");
send(socked_id,msm,sizeof(msm),0);
close(socked_id);
return(0);
}
|
C
|
#include<stdio.h>
int main()
{
int i,n,rem;
printf("Enter Any Digits of No");
scanf("%d",&n);
for (i=0; i<=n; i++)
{
rem=n%10;
printf("%d",rem);
n=n/10;
}
return 0;
}
|
C
|
#define TT_TRACE_MODULE_NAME "single_list_entry_demo"
#define TT_TRACE_DEBUG 1
#include "ttlib.h"
#include "../color.h"
typedef struct __tt_demo_single_list_entry_t{
tt_single_list_entry_t entry;
tt_size_t user_data;
}tt_demo_single_list_entry_t, *tt_demo_single_list_entry_ref_t;
static tt_void_t tt_demo_entry_copy_t(tt_pointer_t litem, tt_pointer_t ritem)
{
tt_assert(litem && ritem);
/// copy data
((tt_demo_single_list_entry_ref_t)litem)->user_data = ((tt_demo_single_list_entry_ref_t)ritem)->user_data;
}
/// list
tt_single_list_entry_head_t g_list;
static tt_demo_single_list_entry_t node[10] = {
{ 0, 0 },
{ 0, 1 },
{ 0, 2 },
{ 0, 3 },
{ 0, 4 },
{ 0, 5 },
{ 0, 6 },
{ 0, 7 },
{ 0, 8 },
{ 0, 9 },
};
tt_void_t tt_demo_single_list_entry_main(tt_void_t)
{
// print title
tt_print_title("demo single list entry");
tt_single_list_entry_init(&g_list, tt_demo_single_list_entry_t, entry, tt_demo_entry_copy_t);
tt_size_t entry = 0;
tt_demo_single_list_entry_ref_t node_ref = tt_null;
tt_iterator_ref_t iterator = tt_single_list_entry_iterator(&g_list);
// tt_size_t head = tt_iterator_heaad
/// test single list entry interfaces
tt_single_list_entry_insert_tail(&g_list, &node[2].entry);
tt_single_list_entry_insert_tail(&g_list, &node[3].entry);
tt_single_list_entry_insert_tail(&g_list, &node[4].entry);
tt_single_list_entry_insert_head(&g_list, &node[1].entry);
tt_single_list_entry_insert_head(&g_list, &node[0].entry);
tt_trace_d("---------------");
/// walk list
for (entry = tt_iterator_head(iterator); entry != tt_iterator_tail(iterator); entry = tt_iterator_next(iterator, entry))
{
node_ref = (tt_demo_single_list_entry_ref_t)tt_iterator_item(iterator, entry);
tt_trace_d("node entry, %X, node data, %d", node_ref, node_ref->user_data);
}
tt_single_list_entry_replace_head(&g_list, &node[5].entry);
tt_trace_d("\n---------------");
/// walk list
for (entry = tt_iterator_head(iterator); entry != tt_iterator_tail(iterator); entry = tt_iterator_next(iterator, entry))
{
node_ref = (tt_demo_single_list_entry_ref_t)tt_iterator_item(iterator, entry);
tt_trace_d("node entry, %X, node data, %d", node_ref, node_ref->user_data);
}
tt_single_list_entry_remove_head(&g_list);
tt_trace_d("---------------");
/// walk list
for (entry = tt_iterator_head(iterator); entry != tt_iterator_tail(iterator); entry = tt_iterator_next(iterator, entry))
{
node_ref = (tt_demo_single_list_entry_ref_t)tt_iterator_item(iterator, entry);
tt_trace_d("node entry, %X, node data, %d", node_ref, node_ref->user_data);
}
/// size
tt_trace_d("size, %d", tt_single_list_entry_size(&g_list));
/// head
tt_single_list_entry_ref_t node_head = tt_single_list_entry_head(&g_list);
tt_trace_d("node_head, %X", node_head);
/// last
tt_single_list_entry_ref_t node_last = tt_single_list_entry_last(&g_list);
tt_trace_d("node_last, %X", node_last);
tt_trace_d("---------------iterator");
/// step
tt_trace_d("step, %d", tt_iterator_step(iterator));
/// mode
tt_trace_d("mode, %d", tt_iterator_mode(iterator));
/// size
tt_trace_d("size, %d", tt_iterator_size(iterator));
/// head
tt_trace_d("head, %X", tt_iterator_head(iterator));
/// last
tt_trace_d("last, %X", tt_iterator_last(iterator));
/// remove
// tt_iterator_remove(iterator, tt_iterator_last(iterator));
/// walk list
for (entry = tt_iterator_head(iterator); entry != tt_iterator_tail(iterator); entry = tt_iterator_next(iterator, entry))
{
node_ref = (tt_demo_single_list_entry_ref_t)tt_iterator_item(iterator, entry);
tt_trace_d("node entry, %X, node data, %d", node_ref, node_ref->user_data);
}
/// test tt_for with single_list_entry
tt_trace_d("---------------tt_for");
tt_for_all(tt_demo_single_list_entry_ref_t, item0, iterator)
{
tt_trace_d("%d", (tt_demo_single_list_entry_ref_t)item0->user_data);
}
tt_trace_d("---------------tt_for_if");
tt_for_all_if(tt_demo_single_list_entry_ref_t, item1, iterator, ((tt_demo_single_list_entry_ref_t)item1)->user_data == 2)
{
tt_trace_d("%d", (tt_demo_single_list_entry_ref_t)item1->user_data);
}
tt_single_list_entry_exit(&g_list);
}
|
C
|
/*!
* @file
*
* GL EmbeddedProCamp - Task#1
*
* Task: Create function to copy all \b digits
* from input string to output string
*/
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
//! Test, if char in range of ANSI-table digits(0x30~0x39 char code).
#define IS_ANSI_DIGIT(char) \
(((uint8_t)char >= 0x30) && ((uint8_t)char <= 0x39))
/*!
* Calculate number of digits (ANSI code 0x30~0x39) in 0-terminated string.
*
* @param[in] in_str_ptr Source string(0-terminated) pointer.
*
* @return Number of digits chars in in_str_ptr string.
*/
uint16_t digit_num(uint8_t *in_str_ptr)
{
uint16_t digits_num = 0;
for (int16_t i = strlen(in_str_ptr) - 1; i >= 0; i--) {
if (IS_ANSI_DIGIT(in_str_ptr[i])) {
digits_num++;
}
}
return digits_num;
}
/*!
* Copy chars that contain ANSI-digits(code 0x30-0x39)
* from in_str to out_str.
*
* @param[in] in_str_ptr Source string pointer.
* @param[out] out_str_ptr Target string pointer, where digits will be putted.
*
* @note in_str_ptr String must be 0-terminated.
*/
void digit_cpy(uint8_t *in_str_ptr, uint8_t *out_str_ptr)
{
size_t chars_num = strlen(in_str_ptr);
uint16_t j = 0;
for (uint16_t i = 0; i < chars_num; i++) {
if (IS_ANSI_DIGIT(in_str_ptr[i])) {
out_str_ptr[j] = in_str_ptr[i];
j++;
}
}
out_str_ptr[j] = '\0';
}
int main()
{
printf("Please enter some string with digits\n");
printf("! less than 50 chars, without spaces !\n\n");
uint8_t in_buff[50];
scanf("%50s", in_buff);
// target string memory allocating (unnecessary memory not allocated)
/// \todo memory allocation can be moved into digit_cpy()
uint8_t *digit_str_ptr = NULL;
digit_str_ptr = (uint8_t*)malloc(sizeof(uint8_t) * digit_num(in_buff) + 1);
if (digit_str_ptr == NULL) {
printf("Error: memory allocation error.");
return -1;
}
digit_cpy(in_buff, digit_str_ptr);
printf("Target string, non-digits filtered:\n%s",\
digit_str_ptr);
free(digit_str_ptr);
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main(void)
{
long a;
long b;
long buf;
if (scanf("%ld", &a) != 1 || scanf("%ld", &b) != 1)
return EXIT_FAILURE;
buf = a;
a = b;
b = buf;
printf("%ld %ld", a, b);
return EXIT_SUCCESS;
}
|
C
|
#include <stdio.h> // printf
#include <math.h> // round
#define LOWER -50
#define UPPER 300
#define STEP 40
void header(int); // Ex. 1-15
int conv(int, int);
int main () {
/* flags:
dir for 1-4
ord 1-5 */
int t, dir = 1, ord = 0;
header(dir);
for (t = (ord == 1 ? LOWER : UPPER); // Ex. 1-5 up or down
(t <= UPPER && ord == 1) || (t >= LOWER && ord != 1);
t += STEP * (ord == 1 ? 1 : -1)) {
printf("%3d\t%3d\n", t, conv(t, dir));
}
return 0;
}
void header(int dir) {
if (dir == 0) { // Ex. 1-3 and 1-4
printf("F\tC\n--------------\n"); // print a header
} else {
printf("C\tF\n--------------\n");
}
return;
}
int conv(int v, int d) {
return (int)round(d == 0 ? 5 * (v - 32) / 9 : 9 * v / 5 + 32);
}
|
C
|
#include <stdio.h>
int main()
{
float length, width, area;
length = 27.2;
width = 13.8;
area = length * width;
printf("The length of the rectangle is %f", length);
printf("\nThe width of the rectangle is %f", width);
printf("\nThe area of the rectangle is %f", area);
return 0;
}
|
C
|
# include <stdlib.h>
# include <stdio.h>
# include <math.h>
# include <time.h>
# include <string.h>
# include "triangle_svg.h"
int main ( );
void test01 ( );
/******************************************************************************/
int main ( )
/******************************************************************************/
/*
Purpose:
MAIN is the main program for TRIANGLE_SVG_PRB.
Discussion:
TRIANGLE_SVG_PRB tests the TRIANGLE_SVG library.
Licensing:
This code is distributed under the GNU LGPL license.
Modified:
21 April 2014
Author:
John Burkardt
*/
{
timestamp ( );
printf ( "\n" );
printf ( "TRIANGLE_SVG_PRB\n" );
printf ( " C version\n" );
printf ( " Test the TRIANGLE_SVG library.\n" );
test01 ( );
/*
Terminate.
*/
printf ( "\n" );
printf ( "TRIANGLE_SVG_PRB\n" );
printf ( " Normal end of execution.\n" );
printf ( "\n" );
timestamp ( );
return 0;
}
/******************************************************************************/
void test01 ( )
/******************************************************************************/
/*
Purpose:
TEST01 calls TRIANGLE_SVG to plot a triangle and some points.
Licensing:
This code is distributed under the GNU LGPL license.
Modified:
21 April 2014
Author:
John Burkardt
*/
{
double p[2*13] = {
0.333333333333333, 0.333333333333333,
0.479308067841923, 0.260345966079038,
0.260345966079038, 0.479308067841923,
0.260345966079038, 0.260345966079038,
0.869739794195568, 0.065130102902216,
0.065130102902216, 0.869739794195568,
0.065130102902216, 0.065130102902216,
0.638444188569809, 0.312865496004875,
0.638444188569809, 0.048690315425316,
0.312865496004875, 0.638444188569809,
0.312865496004875, 0.048690315425316,
0.048690315425316, 0.638444188569809,
0.048690315425316, 0.312865496004875 };
int p_num = 13;
char plot_filename[] = "test01.svg";
double t[2*3] = {
0.0, 0.0,
1.0, 0.0,
0.0, 1.0 };
triangle_svg ( plot_filename, t, p_num, p );
return;
}
|
C
|
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <stdbool.h>
#include <time.h>
#include "define.h"
void copyPosStruct( struct Position pos, struct Position* pos0 )
{
int i,x,y;
for( i=0; i<256; i++ )
{
pos0->board[i] = pos.board[i];
pos0->boardNum[i] = pos.boardNum[i];
pos0->boardCol_b[i]= pos.boardCol_b[i];
pos0->boardCol_w[i]= pos.boardCol_w[i];
}
for( i=0; i<8; i++ )
{
pos0->w_hand[i] = pos.w_hand[i];
pos0->b_hand[i] = pos.b_hand[i];
}
for( i=0; i<64; i++ )
{
pos0->piecePos[i] = pos.piecePos[i];
}
for( x=0; x<8; x++ )
{
for( y=0; y<32; y++ )
{
pos0->pieceStock[x][y] = pos.pieceStock[x][y];
}
}
pos0->Is2FU_b = pos.Is2FU_b;
pos0->Is2FU_w = pos.Is2FU_w;
pos0->color = pos.color;
}
void confPosStruct( struct Position pos, struct Position pos0 )
{
int i,x,y;
for( i=0; i<256; i++ )
{
if( pos0.board[i] != pos.board[i] ) printf("Error\n");
if( pos0.boardNum[i] != pos.boardNum[i] ) printf("Error\n");
if( pos0.boardCol_b[i] != pos.boardCol_b[i] ) printf("Error\n");
if( pos0.boardCol_w[i] != pos.boardCol_w[i] ) printf("Error\n");
}
for( i=0; i<8; i++ )
{
if( pos0.w_hand[i] != pos.w_hand[i] ) printf("Error\n");
if( pos0.b_hand[i] != pos.b_hand[i] ) printf("Error\n");
}
for( i=0; i<64; i++ )
{
if( pos0.piecePos[i] != pos.piecePos[i] ) printf("Error\n");
}
for( x=0; x<8; x++ )
{
for( y=0; y<32; y++ )
{
if( pos0.pieceStock[x][y] != pos.pieceStock[x][y] ) printf("Error\n");
}
}
if( pos0.Is2FU_b != pos.Is2FU_b ) printf("Error\n");
if( pos0.Is2FU_w != pos.Is2FU_w ) printf("Error\n");
if( pos0.color != pos.color ) printf("Error\n");
}
void d_setPos( struct Position pos )
{
int x,y,i;
Board sq;
//局面の色と駒が一致しているか
for( x=1; x<=9; x++ )
{
for( y=1; y<=9; y++ )
{
sq = SQ(x,y);
if( pos.board[sq] != EMP )
{
if( pos.board[sq] != pos.board[ pos.piecePos[ pos.boardNum[sq] ] ] )
{
printf( "Error-1( %d )\n", NSQ(sq) );
}
if(
( pos.boardCol_b[sq] && ( SFU<=pos.board[sq] && pos.board[sq]<=SRY ) )
|| ( pos.boardCol_w[sq] && ( EFU<=pos.board[sq] && pos.board[sq]<=ERY ) )
) { continue; }
else
{
printf( "Error-2( %d )\n", NSQ(sq) );
}
}
}
}
}
Move d_move( struct Position* pos )
{
int x,y,from,to,drop;
//入力をもらう
printf("drop?? (Yes=1:No=0)\n");
if( scanf( "%d", &drop ) == 1 ) printf("OK\n");
else printf("Error\n");
printf("From\n");
if( scanf( "%d", &from ) == 1 ) printf("OK\n");
else printf("Error\n");
Board From;
if( drop == 0 )
{
From = SQ( (10-from/10), from%10 );
printf("pos:%d\n",NSQ(From));
}
else
{
From = from;
}
printf("To\n");
if( scanf( "%d", &to ) == 1 ) printf("OK\n");
else printf("Error\n");
Board To = SQ( (10-to/10), to%10 );
printf("pos:%d\n",NSQ(To));
Move move[600];
move[0] = AddFrom(From) | AddTo(To);
if( drop==1 )
{
move[0]|=AddDrop(1);
}
printf( "move:%d\n", move[0] );
doMove( pos, &move[0] );
return move[0];
}
void debugSearch( struct Position *pos, int depth )
{
if( depth <= 0 ) return;
int n;
unsigned int move[768];
int move_num=0x00;
move_num += GenMoves( pos, &move[move_num] );
//printAllMoves( &move[0], move_num );
//scanf("%d",&n);
int i;
for( i=0; i<move_num; i++ )
{
doMove( pos, move[i] );
//PrintBoard( pos );
//scanf("%d",&n);
pos->color = 1 - pos->color;
debugSearch( pos, depth-1 );
pos->color = 1 - pos->color;
undoMove( pos, move[i] );
}
}
void debugRule( struct Position *pos, Move move )
{
int x,y;
int n;
Board sq;
Board From = GetFrom( move );
Board To = GetTo( move );
Board Pro = GetPro( move );
Piece Cap = GetCap( move );
for( y=1; y<=9; y++ )
{
for( x=1; x<=9; x++ )
{
sq=SQ(x,y);
if( SFU <= pos->board[sq] && pos->board[sq] <= SRY )
{
if( !pos->boardCol_b[sq] ) printf("Error 1\n");
if( pos->boardCol_w[sq] ) printf("Error 2\n");
}
else if( EFU <= pos->board[sq] && pos->board[sq] <= ERY )
{
if( pos->boardCol_b[sq] )
{
printf("Error 3 sq = %d\n",sq);
printf("Error\n");
printf("board[To] : %d ", pos->board[To] );
printf("Piece : %d ", pos->board[From] );
printf("From : %d ", NSQ(From) );
printf("To : %d ", NSQ(To) );
printf("Cap : %d\n", Cap );
PrintBoard(*pos);
//scanf("%d",&n);
}
if( !pos->boardCol_w[sq] ) printf("Error 4\n");
}
else if( !pos->board[sq] )
{
if( pos->boardCol_b[sq] )
{
printf("Error 5 sq = %d\n",sq);
printf("Error\n");
printf("board[To] : %d ", pos->board[To] );
printf("Piece : %d ", pos->board[From] );
printf("From : %d ", NSQ(From) );
printf("To : %d ", NSQ(To) );
printf("Cap : %d\n", Cap );
PrintBoard(*pos);
//scanf("%d",&n);
}
if( pos->boardCol_w[sq] ) printf("Error 6\n");
}
}
}
}
void debugHashMoves( struct Position *pos )
{
int n;
unsigned int move[768];
int move_num=0x00;
move_num += GenMoves( pos, &move[move_num] );
//printAllMoves( &move[0], move_num );
//scanf("%d",&n);
int i;
for( i=0; i<move_num; i++ )
{
PrintBoard( *pos );
doMove( pos, move[i] );
PrintBoard( *pos );
undoMove( pos, move[i] );
PrintBoard( *pos );
//scanf("%d",&n);
}
}
|
C
|
#include<stdio.h>
void main(){
char ch1,ch2,ans;
printf("Enter two character:\n");
scanf("%c %c",&ch1,&ch2);
printf("ch1 = %c\n",ch1);
printf("ch2 = %c\n",ch2);
printf("ch1 ascii = %d\n",ch1);
printf("ch2 ascii = %d\n",ch2);
// ans = ch1 + ch2;
// printf("Addition of ch1 and ch2 in characters = %c\n",ans);
// printf("Addition of ch1 and ch2 in integer= %d\n",ans);
}
|
C
|
#include <stdio.h>
main()
{
float celsius, fahr;
int lower, upper, step;
lower = -20;
upper = 150;
step = 10;
celsius = lower;
while (celsius < upper) {
fahr = celsius * (9.0 / 5.0) + 32.0;
printf("%3.0f\t%3.0f\n", celsius, fahr);
celsius = celsius + step;
}
}
|
C
|
#define _USE_MATH_DEFINES
#include "geo_sphere.h"
#include <GL/glew.h>
#include <GL/gl.h>
#include <math.h>
void drawTexturedSphere(float r, int segs) {
int i, j;
float x, y, z, z1, z2, R, R1, R2;
// Top cap
glBegin(GL_TRIANGLE_FAN);
glNormal3f(0,0,1);
glTexCoord2f(0.5f,1.0f); // This is an ugly (u,v)-mapping singularity
glVertex3f(0,0,r);
z = cos(M_PI/segs);
R = sin(M_PI/segs);
for(i = 0; i <= 2*segs; i++) {
x = R*cos(i*2.0*M_PI/(2*segs));
y = R*sin(i*2.0*M_PI/(2*segs));
glNormal3f(x, y, z);
glTexCoord2f((float)i/(2*segs), 1.0f-1.0f/segs);
glVertex3f(r*x, r*y, r*z);
}
glEnd();
// Height segments
for(j = 1; j < segs-1; j++) {
z1 = cos(j*M_PI/segs);
R1 = sin(j*M_PI/segs);
z2 = cos((j+1)*M_PI/segs);
R2 = sin((j+1)*M_PI/segs);
glBegin(GL_TRIANGLE_STRIP);
for(i = 0; i <= 2*segs; i++) {
x = R1*cos(i*2.0*M_PI/(2*segs));
y = R1*sin(i*2.0*M_PI/(2*segs));
glNormal3f(x, y, z1);
glTexCoord2f((float)i/(2*segs), 1.0f-(float)j/segs);
glVertex3f(r*x, r*y, r*z1);
x = R2*cos(i*2.0*M_PI/(2*segs));
y = R2*sin(i*2.0*M_PI/(2*segs));
glNormal3f(x, y, z2);
glTexCoord2f((float)i/(2*segs), 1.0f-(float)(j+1)/segs);
glVertex3f(r*x, r*y, r*z2);
}
glEnd();
}
// Bottom cap
glBegin(GL_TRIANGLE_FAN);
glNormal3f(0,0,-1);
glTexCoord2f(0.5f, 1.0f); // This is an ugly (u,v)-mapping singularity
glVertex3f(0,0,-r);
z = -cos(M_PI/segs);
R = sin(M_PI/segs);
for(i = 2*segs; i >= 0; i--) {
x = R*cos(i*2.0*M_PI/(2*segs));
y = R*sin(i*2.0*M_PI/(2*segs));
glNormal3f(x, y, z);
glTexCoord2f(1.0f-(float)i/(2*segs), 1.0f/segs);
glVertex3f(r*x, r*y, r*z);
}
glEnd();
}
|
C
|
#include "variadic_functions.h"
/**
* print_numbers - function that prints numbers, followed by a new line.
* @separator: const char
* @n: const unsigned int
* @...: any arguments
* Return: void
*/
void print_numbers(const char *separator, const unsigned int n, ...)
{
va_list list;
unsigned int surplus = n;
va_start(list, n);
if (!separator)
separator = "";
while (surplus--)
{
printf("%i", va_arg(list, int));
if (surplus)
printf("%s", separator);
}
printf("\n");
va_end(list);
}
|
C
|
/**************************************************************
* Brett Waugh
* 4 October 2017
* Checks to see if the Universal Product Code (UPC) is valid.
**************************************************************/
#include <stdio.h>
int main(void)
{
// Declarations.
int d, i1, i2, i3, i4, i5, j1, j2, j3, j4, j5,
first_sum, second_sum, total, check_digit, actual_digit;
// Input.
printf("Enter the first (single) digit: ");
scanf("%1d", &d);
printf("Enter first group of five digits: ");
scanf("%1d%1d%1d%1d%1d", &i1, &i2, &i3, &i4, &i5);
printf("Enter the second group of five digits: ");
scanf("%1d%1d%1d%1d%1d", &j1, &j2, &j3, &j4, &j5);
printf("Enter the final digit: ");
scanf("%1d", &actual_digit);
// Calculation.
first_sum = d + i2 + i4 + j1 + j3 + j5;
second_sum = i1 + i3 + i5 + j2 + j4;
total = 3 * first_sum + second_sum;
check_digit = 9-((total-1)%10);
// Output.
printf("Calculated check digit: %d\n", check_digit);
printf("Actual check digit: %d\n", actual_digit);
return 0;
}
|
C
|
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
int main(int s,char *str[])
{
int l,a,count;
char *str[]="Vinoth ravi";
a=a_to_i(str[]);
l=strlen(str);
for(count=0;count<1;count++)
{
if(str[count]=='a'&&'A'||str[count]=='e'&&'E'||str[count]=='i'&&'I'||str[count]=='o'&&'O'||str[count]=='u'&&'U';
{
printf("vowel at position[%d}:%c\n",count,str[count]);
}}
return 0;
}
|
C
|
#include<stdio.h>
int ft_putchar(char c)
{
write(1, &c, 1);
return 0;
}
void ft_print_numbers(void)
{
char num;
num = '0';
while (num <= '9')
{
ft_putchar(num);
num++;
}
}
int main(){
ft_print_numbers();
return 0;
}
|
C
|
int gcd(int u,int v)
{
if (v==0) return u;
else return gcd(v,u-u/v*v);
/*it's a comment*/
}
int main(void){
int x;
int y;
x=1;
y=1;
gcd(x,y);
}
|
C
|
/* This is a test program for cmpeq8 instruction. */
/* { dg-do run } */
/* { dg-options "-march=rv32gc_zpn -mabi=ilp32d -O2" } */
#include <rvp_intrinsic.h>
#include <stdlib.h>
#include <stdint.h>
static __attribute__ ((noinline))
uint32_t cmpeq8 (uint32_t ra, uint32_t rb)
{
return __rv_cmpeq8 (ra, rb);
}
static __attribute__ ((noinline))
uint8x4_t v_scmpeq8 (int8x4_t ra, int8x4_t rb)
{
return __rv_v_scmpeq8 (ra, rb);
}
static __attribute__ ((noinline))
uint8x4_t v_ucmpeq8 (uint8x4_t ra, uint8x4_t rb)
{
return __rv_v_ucmpeq8 (ra, rb);
}
int
main ()
{
uint32_t a = cmpeq8 (0xffff0000, 0xffff0101);
uint8x4_t v_sa = v_scmpeq8 ((int8x4_t) { 0x7f, 0x7f, 0x01, 0x01},
(int8x4_t) { 0x7f, 0x7f, 0x00, 0x00});
uint8x4_t v_ua = v_ucmpeq8 ((uint8x4_t) { 0x7f, 0x7f, 0x01, 0x01},
(uint8x4_t) { 0x7f, 0x7f, 0x00, 0x00});
if (a != 0xffff0000)
abort ();
else if (v_sa[0] != 0xff
|| v_sa[1] != 0xff
|| v_sa[2] != 0
|| v_sa[3] != 0)
abort ();
else if (v_ua[0] != 0xff
|| v_ua[1] != 0xff
|| v_ua[2] != 0
|| v_ua[3] != 0)
abort ();
else
exit (0);
}
|
C
|
#include<stdio.h>
int main()
{
int num;
int start;
printf("Enter a number to check prime:\n");
scanf("%d",&num);
for(start=2;start<num;start++)
if(num%start==0)
break;
if(num==start)
printf("given number is a prime number\n");
else
printf("given number is not a prime number\n");
return 0;
}
|
C
|
#include "sgr.h"
#include "stdio.h"
static uint8_t get_mode(uint32_t mode) {
switch(mode) {
case 0x80000:
return 1;
case 0x100000:
return 4;
case 0x40000:
return 5;
case 0x200000:
return 7;
default:
return 0;
}
}
void sgr_sequence(uint32_t attribute, buffer *buffer) {
unsigned i;
unsigned int d = 0;
uint32_t modes[4] = {0x80000, 0x100000, 0x40000, 0x200000};
uint16_t color, highbit;
buf_printf(buffer, "\033[");
if (attribute == 0) {
buf_printf(buffer, "0m");
return;
}
for (i = 0; i<sizeof(modes)/sizeof(uint32_t); ++i) {
if (attribute & modes[i]) {
buf_printf(buffer, d++? ";%d" : "%d", get_mode(modes[i]));
}
}
color = attribute & 0xFF;
highbit = attribute & 0x100;
printf("Color %d, high %d\n", color, highbit);
if (highbit) {
buf_printf(buffer, d++? ";38;5;%d" : "38;5;%d", color);
} else if ((color >= 30 && color < 38) || color == 39) {
buf_printf(buffer, d++? ";%d" : "%d", color);
}
color = (attribute >> 9) & 0xFF;
highbit = (attribute >> 9) & 0x100;
if (highbit) {
buf_printf(buffer, d++? ";48;5;%d" : "48;5;%d", color);
} else if ((color >= 40 && color < 48) || color == 49) {
buf_printf(buffer, d++? ";%d" : "%d", color);
}
buf_printf(buffer, "m");
}
|
C
|
#include <stdio.h>
//Takes numbers and tells you what grade they would receive.
//Greater than 89 is an A, less than 60 is an F, -1 breaks the scan loop.
int main()
{
int x;
while (printf("Please enter a grade:\n") && scanf("%d", &x) && x != -1) {
printf("%c\n", x<100?x>59?'J'-(x/10):'F':'A');
}
return 0;
}
|
C
|
/**
* Author : Atul Pundhir
* Description: Program for Change dispenser
*/
#include <stdio.h>
#include <cs50.h>
#include <math.h>
int main(void){
float n=0.0;
int k = 0;
//User input and validation
do{
printf("O hai! How much change is owed?\n");
n = GetFloat();
}while(n < 0);
int cents = round(n * 100);
if(cents >= 25 ){
k = cents / 25;
cents = cents % 25;
}
if(cents >= 10){
k = k + (cents / 10);
cents = cents % 10;
}
if(cents >= 5){
k = k + (cents / 5);
cents = cents % 5;
}
if(cents >= 1){
for(int i=1;i<=cents;i++){
k++;
}
}
printf("%i\n", k);
}
|
C
|
#include<stdio.h>
#include<stdlib.h>
int main(void){
int n,num;
int i,j,k,l;
int **store;
scanf("%d",&n);
int *output = (int*) malloc (sizeof(int)*n);
for(i=0;i<n;i++){
scanf("%d",&num);
store = (int**) malloc (sizeof(int*) * num);
for(k=0;k<num;k++)
store[k] = (int*) malloc(sizeof(int) * num);
for(j=0;j<num;j++){
for(l=0;l<=j;l++)
scanf("%d",&store[j][l]);
}
for(j=num-2;j>=0;j--){
for(l=0;l<=j;l++){
store[j][l] += (store[j+1][l] > store[j+1][l+1])?store[j+1][l]:store[j+1][l+1];
//printf("%d ",store[j][l]);
}
//printf("\n");
}
output[i] = store[0][0];
for (k = 0; k < num; k++)
free(store[k]);
free(store);
}
for(i=0;i<n;i++)
printf("%d\n",output[i]);
free(output);
return 0;
}
|
C
|
#include <stdlib.h>
#include "queen_attack.h"
#define BOARD_SIZE 8
uint8_t is_off_board(position_t p) {
return (p.row >= BOARD_SIZE || p.column >= BOARD_SIZE);
}
attack_status_t can_attack(position_t queen_1, position_t queen_2) {
if (is_off_board(queen_1) || is_off_board(queen_2)) {
return INVALID_POSITION;
}
uint8_t dr = abs(queen_1.row - queen_2.row);
uint8_t dc = abs(queen_1.column - queen_2.column);
if (dr == 0 && dc == 0) {
return INVALID_POSITION;
} else if (dr == 0 || dc == 0 || dr == dc) {
return CAN_ATTACK;
} else {
return CAN_NOT_ATTACK;
}
}
|
C
|
#include <stdlib.h>
#include <ctype.h>
#include <signal.h>
#include <event2/event.h>
#include "util.h"
void fprintf_bytes(FILE *fp, const void *b, size_t l)
{
const char *buf = b;
for(;l; l--, buf++) {
char c = *buf;
if(isprint(c))
fputc(c, fp);
else
fprintf(fp, "\\x%02x", (int)(c&0xff));
}
}
typedef struct {
struct event *int_, *term, *quit;
struct event_base *base;
} sigevents;
static
void sighandle(evutil_socket_t s, short evt, void *raw)
{
sigevents *events = raw;
fprintf(stderr, "Signal. Breaking\n");
event_base_loopexit(events->base, NULL);
}
void* setsighandle(struct event_base *base)
{
sigevents *handle = calloc(1, sizeof(*handle));
if(handle)
{
handle->base = base;
handle->int_ = evsignal_new(base, SIGINT, sighandle, handle);
handle->term = evsignal_new(base, SIGTERM, sighandle, handle);
handle->quit = evsignal_new(base, SIGQUIT, sighandle, handle);
if(!handle->int_||!handle->term||!handle->quit) {
fprintf(stderr, "Failed to create some signal handlers\n");
free(handle);
return NULL;
}
evsignal_add(handle->int_, NULL);
evsignal_add(handle->term, NULL);
evsignal_add(handle->quit, NULL);
}
return handle;
}
void cancelsighandle(void* raw)
{
sigevents *events = raw;
if(!raw) return;
event_free(events->int_);
event_free(events->term);
event_free(events->quit);
free(events);
}
|
C
|
#include "config.h"
#include <stdlib.h>
#include <stdio.h>
#include <inttypes.h>
#if defined(HAVE_FUNC_GETTIMEOFDAY) && defined(HAVE_SYS_TIME_H)
#include <sys/time.h>
#endif
#if defined(HAVE_FUNC_TIME) || defined(HAVE_FUNC_CLOCK_GETTIME)
#include <time.h>
#endif
#if defined(HAVE_FUNC_GSTAFT)
#include <windows.h>
#endif
#if defined(HAVE_MACH_MACH_H)
#include <mach/mach.h>
#include <mach/clock.h>
#endif
#define SECS 1000000000LL
#define USECS 1000LL
#define WINDOWS_EPOCH 116444736000000000LLU /* in hundreds of nanosecond */
void main() {
uint64_t value;
#if defined(HAVE_FUNC_GSTAFT)
{
/*
* We should be able to pass directly ((int64_t*)&value) to
* GetSystemTimeAsFileTime on any standard Windows.
* But what about Windows RT for ARM?
*/
FILETIME ft;
GetSystemTimeAsFileTime(&ft);
value = (((uint64_t)ft.dwHighDateTime << 32) + ft.dwLowDateTime - WINDOWS_EPOCH)*100;
printf("GetSystemTimePreciseAsFT %" PRId64 "\n",value);
}
#endif
#if defined(HAVE_FUNC_GSTPAFT)
{
/*
* We should be able to pass directly ((int64_t*)&value) to
* GetSystemTimeAsFileTime on any standard Windows.
* But what about Windows RT for ARM?
*/
FILETIME ft;
GetSystemTimeAsFileTime(&ft);
value = (((uint64_t)ft.dwHighDateTime << 32) + ft.dwLowDateTime - WINDOWS_EPOCH)*100;
printf("GetSystemTimeAsFT %" PRId64 "\n",value);
}
#endif
#if defined(HAVE_FUNC_CLOCK_GETTIME)
{
struct timespec ts;
clock_gettime(CLOCK_REALTIME, &ts);
value = ts.tv_sec* SECS + ts.tv_nsec;
printf("clock_gettime(RT) %" PRId64 "\n",value);
}
#endif
#if defined(HAVE_FUNC_GETTIMEOFDAY)
{
struct timeval tv;
gettimeofday(&tv,NULL);
value = tv.tv_sec* SECS + tv.tv_usec* USECS;
printf("gettimeofday %" PRId64 "\n",value);
}
#endif
#if defined(HAVE_FUNC_TIME)
{
value = time(NULL)*SECS;
printf("time %" PRId64 "\n",value);
}
#endif
#if defined(HAVE_FUNC_CLOCK_GET_TIME)
{
clock_serv_t host_clock;
kern_return_t kr = host_get_clock_service(mach_host_self(),
CALENDAR_CLOCK, &host_clock);
//assert(kr == KERNEL_SUCCESS);
mach_timespec_t ts;
clock_get_time(host_clock, &ts);
value = ts.tv_sec* SECS + ts.tv_nsec;
printf("clock_get_time(CALENDAR) %" PRId64 "\n",value);
}
#endif
}
|
C
|
#define _POSIX_C_SOURCE 200809L
#include <stdio.h>
#include <signal.h>
#include <unistd.h>
#include <sys/wait.h>
#include <sys/types.h>
#include <error.h>
#include <stdlib.h>
#include <assert.h>
void handler();
int main() {
struct sigaction action;
action.sa_handler = handler;
sigemptyset ( &action.sa_mask );
action.sa_flags = SA_RESTART;
assert( sigaction( SIGUSR1, &action, NULL ) == 0 );
assert( sigaction( SIGUSR2, &action, NULL ) == 0 );
assert( sigaction( SIGURG, &action, NULL ) == 0 );
pid_t fork_status = fork();
if( fork_status > 0) {
// Parent
assert( waitpid( -1, &fork_status, 0 ) >= 0 );
} else if( fork_status < 0 ) {
// Error
perror("fork error");
exit(-1);
} else {
// Child
assert( execl( "./child", "child", NULL ) != -1 );
}
return(0);
}
void handler( int signal_type ) {
if( signal_type == 10 ) {
// SIGUSR1
assert( printf( "Signal 10: SIGUSR1\n" ) != 0 );
} else if( signal_type == 12 ) {
// SIGUSR2
assert( printf( "Signal 12: SIGUSR2\n" ) != 0 );
} else if (signal_type == 23 ) {
// SIGURG
assert( printf( "Signal 23: SIGURG\n" ) != 0 );
}
}
|
C
|
#pragma once
typedef struct _linked_list LinkedList;
LinkedList* list_instanteate();
int list_add(LinkedList* list, void* elem);
int list_insert(LinkedList* list, int index, void* elem);
int list_add_first(LinkedList* list, void* elem);
int list_clear(LinkedList* list);
LinkedList* list_clone(LinkedList* list);
int list_contains(LinkedList* list, void* elem);
void* list_get(LinkedList* list, int index);
void* list_get_first(LinkedList* list);
void* list_get_last(LinkedList* list);
int list_index_of(LinkedList* list, void* elem);
int list_last_index_of(LinkedList* list, void* elem);
void list_push(LinkedList* list, void* elem);
void* list_remove_index(LinkedList* list, int index);
int list_remove_item(LinkedList* list, void* elem);
void* list_remove_first(LinkedList* list);
void* list_remove_last(LinkedList* list);
int list_size(LinkedList* list);
void list_print_int(LinkedList* list, char* (*to_string)(void*));
|
C
|
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <unistd.h>
#include <signal.h>
#include <stdio.h>
#include <fcntl.h>
#include <errno.h>
#include <sys/time.h>
#include <stdlib.h>
#include <memory.h>
#include <string.h>
#include <dirent.h>
#define MAXBUFSIZE 3000
int main (int argc, char * argv[] )
{
int sock;
char command[30], filename[30];
struct sockaddr_in sin, remote;
unsigned int remote_length;
int nbytes, writesize, readsize;
int bufflen;
char buffer[MAXBUFSIZE];
if (argc != 2)
{
printf ("USAGE: <port>\n");
exit(1);
}
bzero(&sin,sizeof(sin));
sin.sin_family = AF_INET;
sin.sin_port = htons(atoi(argv[1]));
sin.sin_addr.s_addr = INADDR_ANY;
//Causes the system to create a generic socket of type UDP (datagram)
if((sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP))==-1)
{
printf("unable to create socket");
}
if (bind(sock, (struct sockaddr *)&sin, sizeof(sin)) < 0)
{
printf("unable to bind socket\n");
}
printf("successfully socket created\n");
while(1)
{
remote_length = sizeof(remote);
bzero(command, 30);
if ((nbytes = recvfrom(sock, command, 30, 0, (struct sockaddr *)&remote, &remote_length)) == -1)
{
printf("error in recvfrom");
}
printf("The client says %s \n", command);
if(!strcmp(command, "put") || !strcmp(command, "get"))
{
bzero(filename, 30);
nbytes = recvfrom(sock, filename, 30, 0, (struct sockaddr *)&remote, &remote_length);
printf("file name received %s \n", filename);
}
if(!strcmp(command, "put"))
{
FILE *fp;
fp = fopen(filename, "w+");
bzero(buffer,sizeof(buffer));
nbytes = recvfrom(sock, buffer, sizeof(buffer) , 0, (struct sockaddr *)&remote, &remote_length);
printf("file recv size = %d",nbytes );
if(nbytes == -1) printf("Error in recvfrom");
printf("the recv size is %d\n", nbytes);
writesize = fwrite(buffer, sizeof(char), nbytes, fp);
fclose(fp);
}
if(!strcmp(command, "get"))
{
printf("command get \n");
int size;
FILE *fp2;
printf("opening file %s\n",filename);
fp2 = fopen(filename, "r");
fseek (fp2, 0, SEEK_END);
size=ftell(fp2);
fseek (fp2, 0, SEEK_SET);
readsize = fread(buffer,sizeof(char), size, fp2);
printf("file readsize = %d\n",readsize);
nbytes = sendto(sock, buffer, readsize, 0,(struct sockaddr *)&remote, sizeof(remote));
if(nbytes == -1) printf("Error in sendto");
printf("the sent size is %d\n", nbytes);
printf("file sent \n");
fclose(fp2);
}
if(!strcmp(command, "ls"))
{
DIR *d;
struct dirent *dirent;
d = opendir(".");
while ((dirent = readdir(d)) != NULL)
{
nbytes = sendto(sock, dirent->d_name,strlen(dirent->d_name), 0,(struct sockaddr *)&remote, remote_length);
if(nbytes == -1) printf("Error in sendto");
}
closedir(d);
char END[] = {"END"} ;
nbytes = sendto(sock, END,strlen(END), 0,(struct sockaddr *)&remote, remote_length);
if(nbytes == -1) printf("Error in sendto");
}
if(!strcmp(command, "exit"))
{
printf("server exits \n");
break;
}
}
close(sock);
}
|
C
|
/*
* This file is part of GreatFET
*/
#include <gpio.h>
#include <gpio_lpc.h>
#include <greatfet_core.h>
#include "one_wire.h"
static struct gpio_t dq = GPIO(5, 8);
/* In the future we'll use a timer for the delay
* but for now a delay of 100 us is delay(3000)
*/
uint8_t one_wire_init_target(void)
{
gpio_output(&dq);
// pull low
gpio_write(&dq, 0);
// wait 500 us
delay(15000);
// switch to input
gpio_input(&dq);
// wait ~60 us
delay(1800);
// read pin
// if low, device is present
if(!gpio_read(&dq)) {
// wait 500 us
delay(15000);
return 0;
}
// wait 500 us
delay(15000);
return 1;
}
uint8_t one_wire_read_bit(void) {
gpio_output(&dq);
// pull low
gpio_write(&dq, 0);
// wait 5 us
delay(150);
// switch to input
gpio_input(&dq);
// wait 5 us
delay(150);
if(gpio_read(&dq)) {
// wait 60 us
delay(3000);
return 1;
}
// wait 60 us
delay(3000);
return 0;
}
uint8_t one_wire_read(void)
{
uint8_t i, byte = 0x00;
for(i=0; i<8; i++) {
// byte <<= 1;
byte |= (one_wire_read_bit() & 0x01) << i;
}
// Reset state to idle
gpio_output(&dq);
gpio_write(&dq, 1);
return byte;
}
void one_wire_write_bit(uint8_t bit)
{
gpio_output(&dq);
// pull low
gpio_write(&dq, 0);
if(bit) {
// wait 5 us
delay(150);
} else {
// wait >60 us
delay(3000);
}
gpio_write(&dq, 1);
delay(1800);
}
void one_wire_write(uint8_t byte)
{
int i;
for(i=0; i<8; i++) {
one_wire_write_bit(byte & 0x01);
byte >>= 1;
}
// Reset state to idle
gpio_write(&dq, 1);
}
|
C
|
/*
Write a program that prints an n X n magic square (a square arragement of the numbers
1, 2, ...., n^2 in which the sum of the rows, colums, and diagonals are all the same.)
The user will specify the value of n:
This program creates a magic square of a specified size.
The size must be odd number between 1 and 99.
Enter a size of magic square: 5
17 24 1 8 15
23 5 7 14 16
4 6 13 20 22
10 12 19 21 3
11 18 25 2 9
Store the magic square in a two-dimensional array. Start by placing the number 1
in the middle of row 0. Place each of the remaining 2, 3, ...., n^2 by moving up
one row and over one column. Any attempt to go outside the bounds of the array
should "wrap-around" to the opposite sideof the array. For example, instead of storing
the next number in row - 1, we sould store in row n -1 (the last row). Instead of
storing the next number in column n, we should store in column 0. If a particular
array element is already occupied, put the number directly below the previously stored
number. If your compiler supports variable-length arrays, delcare the array to have n
rows and n columns. If not, declare the array to have 99 rows and 99 columns.
*/
#include <stdio.h>
int main(void)
{
int size = 0;
printf("This program creates a magic square of a specified size.\n");
printf("The size must be odd number between 1 and 99.\n");
printf("Enter a size of magic square: ");
scanf("%d",&size);
printf("\n");
int magicSquare[size][size];
// To init array to zeros
for (int row = 0; row < size; row++)
for (int col = 0; col < size; col++)
magicSquare[row][col] = 0;
int row = 0; int col = size/2; int limit = size - 1;
int dummyRow, dummyCol;
for (int i = 1; i <= size*size; i++)
{
magicSquare[row][col] = i; // Store value in array
dummyRow = row; // Holds previous value
dummyCol = col; // Hold previous value
// Row/Col conditions: Ternary operator condition?True:False
(row -1 < 0) ? row = limit:row--;
(col + 1 > limit) ? col = 0: col++;
// To prevent overwrite in same spot. If a store a previous number:
// magicsquare[row][col] == 1
if(magicSquare[row][col] != 0)
{
row = dummyRow + 1;
col = dummyCol;
}
}
// To print final array
for (int i = 0; i < size; i++)
{
for (int j = 0; j < size; j++)
printf("%3d ", magicSquare[i][j]);
printf("\n");
}
printf("\n");
return 0;
}
|
C
|
#include<stdio.h>
#include<stdlib.h>
typedef struct LNode{
int data;
struct LNode* next;
}LNode, *LinkList;
LinkList fun(LinkList L,int x){
if(L){
if(L->data==x){
LinkList p;
L->next=fun(L->next, x);
p=L; //注意内存泄露!!!
L=L->next;
free(p);
}else{
L->next=fun(L->next,x);
}
}
return L;
}
int main(){
////////////////////////////////////////////////////////////
////////////////////建立链表////////////////////////////////
LinkList L,s;
int x=0;
L=(LinkList)malloc(sizeof(LNode));
L->next=NULL;
scanf("%d",&x);
while(x!=9999){
s=(LinkList)malloc(sizeof(LNode));
s->data=x;
s->next=L->next;
L->next=s;
scanf("%d",&x);
}
//带头结点:
//s=L->next;
//不带头结点:
L=L->next;
s=L;
////////////////////////////////////////////////////////////
//函数调用:返回链表
scanf("%d",&x);
L=fun(L,x);
s=L;
//打印链表:
while(s){
printf("%d ",s->data);
s=s->next;
}
free(s);
free(L);
return 0;
}
|
C
|
#include<stdio.h>
#include<math.h>
#define pr 0.0000001
long double newtonRaphson(long double x,long double c){
long double h = (2*x*x*x+6*x*x+7*x-3*c)/(6*x*x+12*x+7);
while (fabs(h) >= pr)
{
h = (2*x*x*x+6*x*x+7*x-3*c)/(6*x*x+12*x+7);
x = x - h;
}
return x;
}
int main(){
int t;
scanf("%d",&t);
while(t>0){
long double n,k;
unsigned long long int h;
scanf("%Lf",&n);
k = newtonRaphson(3,n);
h = ceil(k);
printf("%llu\n",h);
t--;
}
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main()
{
srand(time(NULL));
int size;
printf("Give me a number: \n");
scanf("%d", &size);
char Array[size][size];
for (int i=0; i<=size-1;i++){
for (int j=0; j<=size-1;j++){
Array[i][j]='*';
}
}
for (int i=0; i<=size-1;i++){
for (int j=0; j<=i;j++){
printf("%c",Array[i][j]);
}
printf("\n");
}
return 0;
}
|
C
|
#include "maze.h"
/*
Add your implementation of the functions in "maze.h" here.
*/
struct maze* maze_create(struct location *init_valid_locations,
int valid_location_count,
struct location init_location_start,
struct location init_location_end)
{
if(!init_valid_locations||valid_location_count<1) return NULL;
//ALLOC
struct maze* new_maze = (struct maze*)malloc(sizeof(struct maze));
new_maze->valid_locations = init_valid_locations;
new_maze->valid_location_count = valid_location_count;
new_maze->location_start = init_location_start;
new_maze->location_end = init_location_end;
return new_maze;
}
void maze_destroy(struct maze *maze){
if(!maze||!maze->valid_locations||maze->valid_location_count<1) return; //eval left to right, shouldnt be a problem.
free(maze->valid_locations);
maze->valid_locations = NULL;
free(maze);
maze = NULL;
//free locations and afterwards the maze itself
/* SEF_FAULT. How can we follow maze.h instructions of destroying
every location on the maze on this function then?
for(int i=0;i<(maze->valid_location_count);i++){
loc_destroy((maze->valid_locations)+i);
}
*/
return;
}
struct location maze_get_start(struct maze maze){
return maze.location_start;
}
bool maze_is_valid(struct maze maze, struct location loc){
if(!maze.valid_locations||maze.valid_location_count<1) return false;
for(int i=0;i<(maze.valid_location_count);i++){
if(loc_isequal((maze.valid_locations[i]),loc)) return true;
}
return false;
}
bool maze_is_end(struct maze maze, struct location loc){
return loc_isequal(maze.location_end,loc);
}
|
C
|
/*
* mm_alloc.c
*
* Stub implementations of the mm_* routines. Remove this comment and provide
* a summary of your allocator's design here.
*/
#include "mm_alloc.h"
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/time.h>
#include <sys/resource.h>
/* Your final implementation should comment out this macro. */
#define MM_USE_STUBS
s_block_ptr first = {0,NULL,NULL,1,NULL};
s_block_ptr last = {0,NULL,NULL,1,NULL};
s_block_ptr extend_heap (s_block_ptr last,size_t s){
void *brk_ptr = sbrk(s+sizeof(s_block))
if(brk_ptr == (void*)-1){
perror("extend_heap sbrk: ");
return NULL;
}
if(last->ptr == NULL){
set_block_content(last,s,NULL,NULL,0,brk_ptr);
}
else{
set_block_content(last,s,NULL,(s_block_ptr)last->ptr,0,brk_ptr);
}
if(first->ptr == NULL){
set_block_content(first,s,NULL,NULL,0,brk_ptr);
}
else if(first->next == NULL){
set_block_content(first,s,(s_block_ptr)brk_ptr,NULL,0,first->ptr);
}
return (brk_ptr;
}
void* mm_malloc(size_t size)
{
#ifdef MM_USE_STUBS
struct rlimit rlim;
getrlimit(RLIMIT_DATA,&rlim);
printf("max: %u\n",rlim.rlim_max);
printf("cur: %u\n",rlim.rlim_cur);
return calloc(1, size);
#else
#endif
}
void* mm_realloc(void* ptr, size_t size)
{
#ifdef MM_USE_STUBS
return realloc(ptr, size);
#else
#error Not implemented.
#endif
}
void mm_free(void* ptr)
{
#ifdef MM_USE_STUBS
free(ptr);
#else
#error Not implemented.
#endif
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.