language
large_stringclasses 1
value | text
stringlengths 9
2.95M
|
---|---|
C
|
/* *
* File: valen /players/valen/area/catacombs/rooms/dungeonc2.c *
* Function: room *
* Author(s): valen@Nirvana *
* Copyright: Copyright (c) 2009 valen *
* All Rights Reserved. *
* Source: 08/09/09 *
* Notes: dungeon room c 2 *
* *
* *
* Change History: *
*/
#include "/sys/lib.h"
#include <ansi.h>
inherit "room/room";
reset(arg)
{
::reset(arg);
if(arg) return;
set_light(1);
short_desc = HIBLK+"Catacombs of the Magi"+NORM;
long_desc =
HIBLK+" This part of the catacomb is much smaller than the\n\
atrium. Even the pillars here are much smaller. There are\n\
some torches hanging on the pillars. The ceiling is now\n\
visible with roots dangling from it. A flowing fountain is\n\
sculpted into the stone wall."+NORM+"\n";
items =
({
"torch",
"The torch is secured to the wall and cannot be removed",
"dust",
"The dust fills the air and covers the floor",
"pebbles",
"Pebbles are scattered everywhere on the floor",
"floor",
"The floor is covered with pebbles and dust",
"stones",
"The bricked stones are old looking",
"wall",
"The wall is made from stoned bricks",
"fountain",
"The fountain is running with water still. The water is\n"+
"looks clean to drink from. At the spout of water the water\n"+
"is coming from is a well engraved shape of a lion's head.\n"+
"The water is coming from the lion's"+RED+" mouth"+NORM+"\n",
"mouth",
"A button is hidden in the spout",
});
dest_dir =
({
"/players/valen/area/catacombs/rooms/dungeonb2.c", "west",
"/players/valen/area/catacombs/rooms/dungeonc1.c", "north",
"/players/valen/area/catacombs/rooms/dungeond2.c", "enter path",
"/players/valen/area/catacombs/rooms/dungeonc3.c", "south",
});
}
|
C
|
#include <stdio.h>
int x;
int sqr(int x){
int res = x * x;
return res;
}
int main(){
x = 10;
printf("%d\n", sqr(x));
return 0;
}
|
C
|
#include<stdio.h>
void main(){
int a[10]={23,43,1,6,2,44,3445,23,54,6};
int i,j;
int x;
for(i=1;i<10;i++){
j=i-1;
x=a[i];
while(j>=0 && a[j]>x){
a[j+1]=a[j];
j=j-1;
a[j+1]=x;
}
}
for(i=0;i<10;i++){
printf("%d\n",a[i]);
}
}
|
C
|
#include "q1.h"
#include <errno.h> /* Errors */
#include <stdio.h> /* Input/Output */
#include <stdlib.h> /* General Utilities */
#include <fcntl.h>
#include <string.h>
//#include <unistd.h> /* Symbolic Constants */
//#include <sys/types.h> /* Primitive System Data Types */
//#include <sys/wait.h> /* Wait for Process Termination */
//#include <termios.h>
#define BUFSIZE 32
/* for question 1/2, use O_RDONLY */
/* for question 1/3, use O_RDWR */
#define RW_PERM /*O_RDONLY */ O_RDWR
/* read /home/mrv/mrv with RO permissions */
int func1()
{
int fd;
char buf[BUFSIZE] = {0};
int read_len=-1;
int length=0;
printf("func1() read with RO permissions:\n");
printf("=================================\n");
if ( (fd = open("/home/mrv/mrv", O_RDONLY | O_CREAT, 0666)) < 0 )
{
perror("failed to open /home/mrv/mrv");
exit(errno);
}
/* Read up to max size of buf. */
length=BUFSIZE;
read_len = read (fd, buf, length);
if (read_len < 0)
{
/* reading file failed. Print an error message and exit. */
perror("error reading file");
exit(-2);
}
printf("%d bytes have been read from file \n",read_len);
/* make sure buf is ended with '\0' */
if (read_len == BUFSIZE) buf[BUFSIZE-1] = '\0';
printf("file content = %s", buf);
close(fd);
return 0;
}
/* trying to write with O_RDONLY permissions
trying to write with O_RDONLY permissions but with another file descriptor
trying to write with O_RDWR permissions */
int func2()
{
int fd /*,fd1*/;
char buf[BUFSIZE] = "1234567890";
int write_len=-1;
int read_len=-1;
int length=0;
printf("func2() write with RO permissions:\n");
printf("==================================\n");
if ( (fd = open("/home/mrv/q.txt", RW_PERM | O_CREAT, 0666)) < 0 )
{
perror("failed to open /home/mrv/mrv");
exit(errno);
}
/* Read up to max size of buf. */
write_len = write(fd, buf, strlen(buf));
if (write_len < 0)
{
/* writing to file failed. Print an error message and exit. */
perror("error writing file");
exit(errno);
}
printf("%d bytes have been written to file \n",write_len);
/* !!!!!! check by read !!!!!!!!!!!!! */
/* Rewind to the beginning of the file. */
lseek (fd, 0, SEEK_SET);
/* Read up to max size of buf. */
length=strlen(buf);
read_len = read (fd, buf, length);
if (read_len < 0)
{
/* reading file failed. Print an error message and exit. */
perror("error reading file");
exit(errno);
}
printf("%d bytes have been read from file \n",read_len);
/* make sure buf is ended with '\0' */
if (read_len == BUFSIZE) buf[BUFSIZE-1] = '\0';
printf("file content = %s", buf);
printf("\n");
close(fd);
return 0;
}
/* cp /home/mrv/mrv to a new file a.txt */
int func3(char *path)
{
int fd, fd1;
char *buf;
int read_len=-1;
int write_len=-1;
int length=0;
if (!path)
{
printf("file path is NULL\n\r");
return -1;
}
printf("func3() cp a file %s to ~/a.txt:\n", path);
printf("===========================================\n");
if ( (fd = open(path, O_RDONLY | O_CREAT, 0666)) < 0 )
{
perror("failed to open user file");
exit(errno);
}
/*Upon successful completion, lseek() returns the resulting offset location as measured in bytes from the beginning of the file.
On error, the value (off_t) -1 is returned and errno is set to indicate the error. */
if ((length = lseek(fd, 0, SEEK_END)) < 0 )
{
perror("failed to lseek user file");
exit(errno);
}
printf("lseek returned the file length in bytes: %d\n",length);
/* Allocate a buffer and read the data. */
buf = (char*) malloc (length);
if (buf == NULL)
{
perror("error allocating Memory");
exit(errno);
}
printf("Allocated buffer address is %p \n",buf);
/* Read up to max size of buf. */
/* Rewind to the beginning of the file. */
lseek (fd, 0, SEEK_SET);
read_len = read (fd, buf, length);
if (read_len < 0)
{
/* reading file failed. Print an error message and exit. */
perror("error reading file");
exit(errno);
}
printf("%d bytes have been read from file \n",read_len);
if ( (fd1 = open("/home/mrv/a.txt", O_RDWR | O_CREAT | O_TRUNC, 0666)) < 0 )
{
perror("failed to open /home/mrv/a.txt");
exit(errno);
}
write_len = write (fd1, buf, length);
if (write_len < 0)
{
/* writing the file failed. Print an error message and exit. */
perror("error writing file");
exit(errno);
}
printf("%d bytes have been written to file \n",write_len);
free(buf);
close(fd);
close(fd1);
return 0;
}
int func4()
{
int fd;
char buf[BUFSIZE] = {0};
int read_len=-1;
int length=0;
printf("func4() reads /dev/zero:\n");
printf("=================================\n");
if ( (fd = open("/dev/zero", O_RDONLY, 0666)) < 0 )
{
perror("failed to open /dev/zero");
exit(errno);
}
/* Read up to max size of buf. */
length=BUFSIZE;
read_len = read (fd, buf, length);
if (read_len < 0)
{
/* reading file failed. Print an error message and exit. */
perror("error reading file");
exit(-2);
}
printf("%d bytes have been read from /dev/zero \n",read_len);
/* make sure buf is ended with '\0' */
if (read_len == BUFSIZE) buf[BUFSIZE-1] = '\0';
printf("file content = %s", buf);
int i;
for (i = 0; i < read_len; i++)
{
printf("char in buf[%d] = %d\n\r", i, buf[i]);
}
close(fd);
return 0;
}
int func5()
{
int fd;
char buf[BUFSIZE] = {0};
int write_len =-1;
printf("func5() is trying to write /dev/full:\n");
printf("========================================\n");
if ( (fd = open("/dev/full", O_RDWR, 0666)) < 0 )
{
perror("failed to open /dev/full");
exit(errno);
}
write_len = write (fd, buf, BUFSIZE);
if (write_len < 0)
{
/* writing the file failed. Print an error message and exit. */
perror("error writing file");
exit(errno);
}
printf("%d bytes have been written to file /dev/full \n",write_len);
close(fd);
return 0;
}
extern char **environ;
int func6()
{
int fd;
int write_len =-1;
char **var;
char *file = strcat(getenv("HOME"), "/environment");
printf("func6() is writing all ENV variables into %s:\n", file);
printf("====================================================\n");
if ( (fd = open(file/*"/home/$USER/envrionment"*/, O_RDWR | O_CREAT | O_TRUNC, 0666)) < 0 )
{
perror("failed to open /home/mrv/envrionment");
exit(errno);
}
for(var=environ; *var!=NULL; ++var)
{
//printf("%s\n",*var);
write_len = write (fd, *var, strlen(*var));
if (write_len < 0)
{
/* writing the file failed. Print an error message and exit. */
perror("error writing file");
exit(errno);
}
write(fd, "\n", 1);
}
return 0;
}
|
C
|
#include <ESP8266WiFi.h>
#include "secret.h"
WiFiClient client;
int joinAP(int retry){
char ipaddr[20];
IPAddress ip;
logline(0, 1, "Connecting");
WiFi.mode(WIFI_STA);
WiFi.begin(MYSSID, MYPASSWD);
while ( ( WiFi.status() != WL_CONNECTED ) && ((retry--) > 0) )
{
delay(500);
Serial.print(".");
}
Serial.println();
if ( WiFi.status() != WL_CONNECTED ) {
logline(0, 1, "Can't connect to AP");
return 1;
}
ip=WiFi.localIP();
sprintf(ipaddr, "%d.%d.%d.%d", ip[0], ip[1], ip[2], ip[3]);
logline(0, 2, "<T1> Connected as ", ipaddr);
return 0;
}
void disconnectAP(){
WiFi.disconnect();
while (WiFi.status() == WL_CONNECTED) delay(1000);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
struct array_stack{
int top,capacity;
int *arr;
};
struct array_stack* create_stack(int cap){
struct array_stack *stack;
stack=(struct array_stack*)malloc(sizeof(struct array_stack));
stack->capacity=cap;
stack->top=-1;
stack->arr=(int*)malloc(sizeof(int)*cap);
return stack;
}
int isfull(struct array_stack *stack){
if(stack->top==stack->capacity-1)
return 1;
else
{
return 0;
}
}
int isempty(struct array_stack *stack){
if(stack->top==-1)
return 1;
else
return 0;
}
void PUSH(struct array_stack *stack,int item){
if(!isfull(stack)){
stack->top++;
stack->arr[stack->top]=item;
}
}
int POP(struct array_stack *stack){
int item;
if(!isempty(stack)){
item=stack->arr[stack->top];
stack->top--;
return item;
}
else
return -1;
}
int main(void){
int item,choice,size;
struct array_stack *stack;
printf("INPUT THE SIZE OF ARRAY YOU WANT :\n");
scanf("%d",&size);
stack=create_stack(size);
while(1){
printf("INPUT YOUR CHOICE :\n");
printf("INPUT 1 FOR PUSH.\n");
printf("INPUT 2 FOR POP.\n");
printf("INPUT 3 FOR EXIT\n");
scanf("%d",&choice);
switch(choice){
case 1:
printf("Input the value to be pushed !\n");
scanf("%d",&item);
PUSH(stack,item);
break;
case 2:
item=POP(stack);
if(item==-1)
printf("The stack is already empty!\n");
else
printf("The popped item is : %d\n",item);
break;
case 3:
free(stack);
exit(0);
break;
}
}
return 0;
}
|
C
|
#include <stdio.h>
/**
* main- Aprogram that prints the alphabet
*in lowercase, followed by a new line.
* Return: 0
**/
int main(void)
{
int i = 97;
for (i = 97; i <= 122; ++i)
{
if (i != 101 && i != 113)
{
putchar(i);
}
}
putchar('\n');
return (0);
}
|
C
|
#include<stdio.h>
void inverte_string(char *v);
int main(){
char v[100];
printf("Digite uma string: ");
scanf("%[^\n]", v);
printf("Inversa da string: ");
inverte_string(v);
return 0;
}
void inverte_string(char *v){
if(*v){
inverte_string(v+1);
}
else {
return;
}
printf("%c", *v);
}
|
C
|
#include"apue.h"
#include<dirent.h>
#include<limits.h>
typedef int Myfunc(const char*, const struct stat*, int);
static Myfunc myfunc;
static int myftw(char*, Myfunc*);
static int dopath(Myfunc*);
static long nreg, ndir, nblk, nchr, nfifo, nslink, nsock, ntot;
int
main(int argc, char* argv[])
{
int ret;
if (argc != 2)
err_quit("usage: ftw <starting-pathname>");
ret = myftw(argv[1], myfunc);
ntot = nreg + nblk + nchr + nfifo + nslink + nsock + ntot;
if (ntot == 0)
ntot = 1;
printf("regular files = %7ld, %5.2f %%\n", nreg, nreg * 100.0 / ntot);
printf("directories = %7ld, %5.2f %%\n", ndir, ndir * 100.0 / ntot);
printf("block special = %7ld, %5.2f %%\n", nblk, nblk * 100.0 / ntot);
printf("character special = %7ld, %5.2f %%\n", nchr, nchr * 100.0 / ntot);
printf("FIFO = %7ld, %5.2f %%\n", nfifo, nfifo * 100.0 /ntot);
printf("symbolic links = %7ld, %5.2f %%\n", nslink, nslink * 100.0 / ntot);
printf("sockets = %7ld, %5.2f %%\n", nsock, nsock * 100.0 % ntot);
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "LinkedList.h"
#include "Employee.h"
/** \brief Parsea los datos los datos de los empleados desde el archivo data.csv (modo texto).
*
* \param path char*
* \param pArrayListEmployee LinkedList*
* \return int
*
*/
int parser_EmployeeFromText(FILE* pFile , LinkedList* pArrayListEmployee)
{
Employee* pAuxEmployee;
char idStr[50],nombre[128],horasTrabajadasStr[50],sueldoStr[50];
int id;
int horasTrabajadas;
int sueldo;
int idMax=0;
if(pFile !=NULL){
do{
if(fscanf(pFile,"%[^,],%[^,],%[^,],%[^\n]\n",idStr,nombre,horasTrabajadasStr,sueldoStr)==4){
id=atoi(idStr);
horasTrabajadas=atoi(horasTrabajadasStr);
sueldo=atoi(sueldoStr);
if(id>idMax){
idMax=id;
}
}else{
break;
}
pAuxEmployee=employee_newParametros(id,nombre,horasTrabajadas,sueldo);
if(pAuxEmployee!=NULL){
ll_add(pArrayListEmployee, pAuxEmployee);
}
}while(!feof(pFile));
return idMax;
}
return -1;
}
/** \brief Parsea los datos los datos de los empleados desde el archivo data.csv (modo binario).
*
* \param path char*
* \param pArrayListEmployee LinkedList*
* \return int
*
*/
int parser_EmployeeFromBinary(FILE* pFile , LinkedList* pArrayListEmployee)
{
Employee* pAuxEmployee;
int idMax=0;
if(pFile !=NULL){
do{
pAuxEmployee=employee_new();
if(fread(pAuxEmployee,sizeof(Employee),1,pFile)==1){
ll_add(pArrayListEmployee, pAuxEmployee);
if(pAuxEmployee->id>idMax){
idMax=pAuxEmployee->id;
}
}else{
employee_delete(pAuxEmployee);
}
}while(!feof(pFile));
return idMax;
}
return -1;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <sys/types.h>
#include <mqueue.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <unistd.h>
#include <signal.h>
#include <string.h>
#include <time.h>
#include "chat.h"
mqd_t serverQueue;
int lastClientIndex = 0;
mqd_t clientsQueues[MAX_CLIENTS];
int lastFriendIndex = -1;
int friends[MAX_CLIENTS];
char clientPath[20];
Message waitForMessage(mqd_t queueID);
void sendMessage(mqd_t queueID, long type, char* text, long clientID, int textLen);
void handleMessage(Message message);
void handleINIT(Message message);
void handleECHO(Message message);
void handleTOONE(Message message);
void handleLIST(Message message);
void handleADD(Message message);
void handleTOALL(Message message);
void handleFRIENDS(Message message);
void handleTOFRIENDS(Message message);
void handleDEL(Message message);
void handleSTOP(Message message);
char* connectTime(Message* message);
char* connectClientTime(Message* message);
void handleExit();
void handleSIGINT();
int main() {
atexit(handleExit);
signal(SIGINT, handleSIGINT);
struct mq_attr attr;
attr.mq_maxmsg = MAX_MESSAGES;
attr.mq_msgsize = MAX_MESSAGE_SIZE;
for(int i = 0; i<MAX_CLIENTS; i++){
friends[i] = -1;
}
if ((serverQueue = mq_open("/server", O_RDONLY | O_CREAT | O_EXCL, 0666, &attr)) == -1) {
fprintf(stderr, "Wystąpił problem z tworzeniem kolejki dla serwera");
exit(1);
} else {
printf("SERVER ID %d\n", serverQueue);
while(1) {
Message Message = waitForMessage(serverQueue);
printf("Got message: \n\tType: %s \n\tClient: %ld\n\tText: %s\n", getTypeName(Message.mType), Message.clientID, Message.text);
handleMessage(Message);
}
}
}
Message waitForMessage(mqd_t queueID) {
Message message;
if(mq_receive(queueID, (char*)&message, MAX_MESSAGE_SIZE, NULL) == -1) {
fprintf(stderr, "Failed to get message from server %s", strerror(errno));
exit(1);
}
return message;
}
void sendMessage(mqd_t queueID, long type, char* text, long clientID, int textLen) {
Message message;
message.mType = type;
message.clientID = clientID;
message.textLength = textLen;
if(textLen > MAX_MESSAGE_LENGTH) {
fprintf(stderr, "Too long message");
exit(1);
}
memset(message.text, 0, 99);
memcpy(message.text, text, textLen);
printf("Send Message: \n\tType: %s \n\tClient: %ld\n\tText: %s\n", getTypeName(message.mType), message.clientID, message.text);
if (mq_send(queueID, (char*)&message, MAX_MESSAGE_SIZE, (unsigned int)type) == -1){
fprintf(stderr, "Failed to send a message\n");
exit(1);
}
}
void handleMessage(Message message) {
switch (message.mType) {
case ECHO:
handleECHO(message);
break;
case LIST:
handleLIST(message);
break;
case FRIENDS:
handleFRIENDS(message);
break;
case TOALL:
handleTOALL(message);
break;
case TOFRIENDS:
handleTOFRIENDS(message);
break;
case TOONE:
handleTOONE(message);
break;
case STOP:
handleSTOP(message);
break;
case INIT:
handleINIT(message);
break;
case ADD:
handleADD(message);
break;
case DEL:
handleDEL(message);
break;
}
}
void handleECHO(Message message) {
char* text = connectTime(&message);
sendMessage(clientsQueues[message.clientID], ECHO, text, 0, message.textLength);
free(text);
}
void handleLIST(Message message) {
char* result = calloc((lastClientIndex) * 15, sizeof(char));
for(int i=0; i<lastClientIndex; ++i) {
char part[10];
sprintf(part, "Clnt:%d | ", i);
strcat(result, part);
}
sendMessage(clientsQueues[message.clientID], ECHO, result, 0, (lastClientIndex) * 10);
}
void handleFRIENDS(Message message) {
lastFriendIndex = -1;
for(int i = 0; i<MAX_CLIENTS; i++) {
friends[i] = -1;
}
handleADD(message);
}
void handleADD(Message message) {
char* friendsList = calloc(message.textLength, sizeof(char));
memcpy(friendsList, message.text, message.textLength);
char *friend = strtok(friendsList, " ");
while(friend != NULL) {
int friendID = atoi(friend);
lastFriendIndex++;
for(int i = 0; i<lastFriendIndex; i++) {
if(friends[i] == friendID) {
fprintf(stderr, "You can't add two same friends");
exit(1);
}
}
friends[lastFriendIndex] = friendID;
friend = strtok(NULL, " ");
}
free(friendsList);
}
void handleDEL(Message message) {
char* friendsList = calloc(message.textLength, sizeof(char));
memcpy(friendsList, message.text, message.textLength);
char *friend = strtok(friendsList, " ");
while(friend != NULL) {
int friendID = atoi(friend);
for(int i=0; i<=lastFriendIndex; ++i) {
if(friends[i] == friendID) {
for(int j=i; j<lastFriendIndex; ++j) {
friends[j] = friends[j+1];
}
lastFriendIndex--;
}
}
friend = strtok(NULL, " ");
}
free(friendsList);
}
void handleTOONE(Message message) {
char* index = malloc(1);
memcpy(index, message.text, 1);
char* text = connectClientTime(&message);
sendMessage(clientsQueues[atoi(index)], ECHO, text+2, 0, message.textLength);
free(text);
}
void handleTOALL(Message message) {
char* text = connectClientTime(&message);
for(int i=0; i<=lastClientIndex; ++i) {
if(clientsQueues[i] != 0) {
sendMessage(clientsQueues[i], ECHO, text, 0, message.textLength);
}
}
free(text);
}
void handleTOFRIENDS(Message message) {
char* text = connectClientTime(&message);
for(int i=0; i<=lastFriendIndex; ++i) {
if(clientsQueues[i] != 0) {
sendMessage(clientsQueues[friends[i]], ECHO, text, 0, message.textLength);
}
}
free(text);
}
void handleINIT(Message message) {
if(lastClientIndex >= MAX_CLIENTS) {
fprintf(stderr, "Too many clients");
exit(1);
}
sprintf(clientPath, "/%ld", message.clientID);
if ((clientsQueues[lastClientIndex] = mq_open(clientPath, O_WRONLY)) == -1) {
fprintf(stderr, "Couldn't find client queue");
exit(1);
} else {
sendMessage(clientsQueues[lastClientIndex], INIT, "Server response", lastClientIndex, 0);
}
lastClientIndex++;
}
char* connectTime(Message* message) {
time_t now;
time(&now);
char* result = calloc(MAX_MESSAGE_LENGTH + 100, sizeof(char));
sprintf(result, "%s\n\tTime: %s", message->text, ctime(&now));
message->textLength = strlen(result);
return result;
}
char* connectClientTime(Message* message) {
time_t now;
time(&now);
char* result = calloc(MAX_MESSAGE_LENGTH + 100, sizeof(char));
sprintf(result, "%s\n\tClient: %ld\n\tTime: %s", message->text, message->clientID, ctime(&now));
message->textLength = strlen(result);
return result;
}
void handleSTOP(Message message) {
clientsQueues[message.clientID] = 0;
for(int i=0; i<=lastClientIndex; ++i) {
if(clientsQueues[i] == 0) {
for(int j=i; j<lastClientIndex; ++j) {
clientsQueues[j] = clientsQueues[j+1];
}
lastClientIndex--;
}
}
}
void handleExit() {
for (int i = 0; i<=lastClientIndex; ++i) {
if (clientsQueues[i] != 0) {
char* text = "STOP";
sendMessage(clientsQueues[i], STOP, text, 0, strlen(text));
waitForMessage(serverQueue);
mq_close(clientsQueues[i]);
}
}
mq_close(serverQueue);
mq_unlink("/server");
}
void handleSIGINT(int signum) {
printf("\nServer end after SIGINT\n");
exit(0);
}
|
C
|
#pragma once
#include "Utils.h"
struct Timer
{
LARGE_INTEGER freq;
LARGE_INTEGER startTicks;
Timer()
{
QueryPerformanceFrequency(&freq);
}
void start()
{
QueryPerformanceCounter(&startTicks);
}
int64 getElapsedTime()
{
LARGE_INTEGER stopTicks;
QueryPerformanceCounter(&stopTicks);
LARGE_INTEGER elapsedTicks;
elapsedTicks.QuadPart= stopTicks.QuadPart - startTicks.QuadPart;
elapsedTicks.QuadPart *= 1000;
elapsedTicks.QuadPart /= freq.QuadPart;
return elapsedTicks.QuadPart;
}
};
|
C
|
//
// Created by Daria Miklashevskaya on 31/10/2018.
//
#include <stdio.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
#include <unistd.h>
#include <stdlib.h>
int main(){
char * addr;
int fd; //file descriptor
off_t size;
struct stat s;
fd = open("ex1.txt", O_RDWR); //open the file for reading and writing
fstat(fd,&s);
size = s.st_size;
addr = mmap(NULL, size,PROT_READ|PROT_WRITE,MAP_SHARED, fd,0);
char str [] = "This is a nice day";
ftruncate(fd, strlen(str)*sizeof(char));
strcpy(addr,str);
munmap(addr, size);
close(fd);
}
|
C
|
#include<stdio.h>
#include<assert.h>
#define MAX(a,b) (a>b ? a : b)
#define MIN(a,b) (a>b ? b :a)
float median(int *arr, int size){
if(size & 0x01) return arr[size>>1];
return (arr[size>>1]+arr[(size>>1)-1])/2.0f;
}
float find_median(int *arr1, int *arr2, int size){
if(size <= 0) return -1;
if(size == 1) return (arr1[0]+arr2[0])/2;
// if(size==2)printf("MAX : %d \t Min %d \n",MAX(arr1[0], arr2[0]),MIN(arr1[1], arr2[1]) );
if(size == 2) return (MAX(arr1[0], arr2[0]) + MIN(arr1[1], arr2[1]))/2.0f;
float m1 = median(arr1, size);
float m2 = median(arr2, size);
// printf("Median 1 : %.2f, median 2 : %.2f , size: %d\n", m1, m2, size);
if (m1 == m2) return m1;
if (m1 < m2)
{ if(size %2 == 0)return find_median(arr1 +size/2-1, arr2 , size/2+1);
return find_median(arr1 + size/2, arr2, size-size/2);
}
if (size %2 == 0) return find_median(arr2 +size/2-1, arr1, size/2+1);
return find_median(arr2 +size/2, arr1, size-size/2);
}
int main () {
int arr1[]={1, 3, 7,10,15,17}, arr2[]= {2,5,9,16,20,24}, size;
size = sizeof(arr1)/sizeof(int);
// printf("Median %f", median(arr1,4));
printf("Median %.2f", find_median(arr1, arr2, size));
}
|
C
|
#pragma once
#include "Public.h"
void Partition(int arr[], int start, int end) {
if(start < end) {
int l = start, r = end;
int pivot = arr[l+(r-l)/2];
while(l <= r) {
while(l <= r && arr[r] > pivot) {
r--;
}
while(l <= r && arr[r] < pivot) {
l++;
}
if(l <= r) {
Swap(arr[l++], arr[r--]);
}
}
Partition(arr, start, r);
Partition(arr, l, end);
}
}
void QuickSort(int arr[], int n) {
Partition(arr, 0, n);
}
|
C
|
#ifndef NODE_H
#define NODE_H
#include <stdio.h>
#include <stdlib.h>
#include "node.h"
typedef enum types {TYPE_STRING, TYPE_INT} l_type;
typedef struct lNode {
int value;
struct lNode * next;
struct lNode * prev;
} l_node;
l_node * newListNode(int value);
l_node * addListNode(char * value, l_node * first);
void printList(l_node * first);
l_node * removeFromList(char * value, l_node * first);
void printBackwards(l_node * first);
#endif
|
C
|
#include<stdio.h>
int main()
{
int marks,count,i;
int d[15]={58,65,89,78,56,54,52,58,69,96,78,96,67,58,51};
for(marks=50;marks<=100;marks++){
count=0;
for(i=0;i<15;i++){
if(d[i]==marks)
count++;}
printf("Marks:%d\t count:%d\n",marks,count);}
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
struct Node
{
int data;
struct Node *next;
}*first, *last, *secound;
void create(int arr[], int n)
{
struct Node *temp, *last;
int i = 0;
first = (struct Node*)malloc(sizeof(struct Node));
first->data = arr[i];
first->next = NULL;
last = first;
for (i = 1; i < n; i++)
{
temp = (struct Node*)malloc(sizeof(struct Node));
temp->data = arr[i];
temp->next = NULL;
last->next = temp;
last = temp;
}
}
void RlistPrint(struct Node* p)
{
if(p)
{
printf("%d ", p->data);
RlistPrint(p->next);
}
if(p == 0)
printf("\n");
}
void reverseRlistPrint(struct Node* p)
{
if(p)
{
reverseRlistPrint(p->next);
printf("%d ", p->data);
}
if(p == first)
printf("\n");
}
void listPrint(struct Node* p)
{
while(p)
{
printf("%d ", p->data);
p = p->next;
}
printf("\n");
}
int countNode(struct Node *p)
{
int count = 0;
while(p)
{
count++;
p = p->next;
}
return count;
}
int RcountNode(struct Node *p)
{
if(p == NULL)
return 0;
return RcountNode(p->next)+1;
}
int sumNode(struct Node *p)
{
int count = 0;
while(p)
{
count += p->data;
p = p->next;
}
return count;
}
int RsumNode(struct Node *p)
{
if(p == NULL)
return 0;
return RsumNode(p->next)+p->data;
}
int listMax(struct Node *p)
{
int max = INT_MIN;
while(p)
{
if(p->data > max)
max = p->data;
p = p->next;
}
return max;
}
int RlistMax(struct Node *p)
{
if (p == 0)
return INT_MIN;
int x = RlistMax(p->next);
if(x > p->data)
return x;
else
return p->data;
}
int listMin(struct Node *p)
{
int min = INT_MAX;
while(p)
{
if(p->data < min)
min = p->data;
p = p->next;
}
return min;
}
int RlistMin(struct Node *p)
{
if(p == 0)
return INT_MAX;
int x = RlistMin(p->next);
if (x < p->data)
return x;
else
return p->data;
}
struct Node* listSearch(struct Node *p, int x)
{
// struct Node *q = NULL;
while(p)
{
if(p->data == x)
{
/*
// Move to first
if(q != NULL)
{
q->next = p->next;
p->next = first;
first = p;
}
*/
return p;
}
// q = p;
p = p->next;
}
return NULL;
}
struct Node* RlistSearch(struct Node *p, int x)
{
if(p->data == x)
return p;
else if(p->next == 0)
return NULL;
RlistSearch(p->next, x);
}
struct Node* moveToFrontRlistSearch(struct Node *p, struct Node *q, int x)
{
if(p->data == x)
{
// Move to first
if(q != NULL)
{
q->next = p->next;
p->next = first;
first = p;
}
return p;
}
else if(p->next == 0)
return NULL;
moveToFrontRlistSearch(p->next, p, x);
}
void insert(int pos, int item)
{
if (pos < 0)
return;
struct Node *temp = (struct Node*)malloc(sizeof(struct Node));
temp->data = item;
if(pos == 0)
{
temp->next = first;
first = temp;
}
else
{
struct Node *prev = first;
for (int i = 1; i < pos && prev; i++)
prev = prev->next;
if(prev)
{
temp->next = prev->next;
prev->next = temp;
}
}
}
void append(int item)
{
struct Node *temp = (struct Node *)malloc(sizeof(struct Node));
temp->data = item;
temp->next = NULL;
if(first == NULL)
first=last=temp;
else
{
last->next = temp;
last = temp;
}
}
void sortInsert(int item)
{
struct Node *p = first, *q = NULL, *temp;
temp = (struct Node *)malloc(sizeof(struct Node));
temp->data = item;
while(p && p->data < item)
{
q = p;
p = p->next;
}
if(q == NULL)
{
temp->next = first;
first = temp;
}
else
{
temp->next = q->next;
q->next = temp;
}
}
int deleteNode(int index)
{
int ele = -1;
struct Node *p = first, *q = NULL;
if(index == 1)
{
p = first;
first = first->next;
ele = p->data;
free(p);
}
else
{
for (int i = 1; i < index && p; i++)
{
q = p;
p = p->next;
}
q->next = p->next;
ele = p->data;
free(p);
}
return ele;
}
int isSorted(struct Node *p)
{
int x = INT_MIN;
while(p)
{
if(x > p->data)
return 0;
x = p->data;
p = p->next;
}
return 1;
}
void romoveDuplicateNode(struct Node *p)
{
struct Node *q = p->next;
while(q)
{
if(p->data != q->data)
{
p = q;
q = q->next;
}
else
{
p->next = q->next;
free(q);
q = p->next;
}
}
}
void reverseLinkList(struct Node *p)
{
struct Node *q = NULL, *r = NULL;
while(p)
{
r = q;
q = p;
p = p->next;
q->next = r;
}
first = q;
}
void RreverseLinkList(struct Node *p, struct Node *q)
{
if(p == NULL)
{
first = q;
return;
}
RreverseLinkList(p->next, p);
p->next = q;
}
void concatanate(struct Node *p, struct Node *q)
{
while(p->next)
p = p->next;
p->next = q;
}
struct Node* marge(struct Node *p, struct Node *q)
{
struct Node *third, *last;
if(p->data < q->data)
{
third = last = p;
p = p->next;
last->next = NULL;
}
else
{
third = last = q;
q = q->next;
last->next = NULL;
}
while(p && q)
{
if(p->data < q->data)
{
last->next = p;
last = p;
p = p->next;
last->next = NULL;
}
else
{
last->next = q;
last = q;
q = q->next;
last->next = NULL;
}
}
if(p) last->next = p;
if(q) last->next = q;
return third;
}
int isLoop(struct Node *f)
{
struct Node *p, *q;
p = q = f;
do
{
p = p->next;
q = q->next;
q = q ? q->next : q;
} while(p && q && p != q);
if(p==q)
return 1;
else
return 0;
}
struct Node* moveToMiddel(struct Node *p)
{
struct Node *q = p;
while(p)
{
p = p->next;
if(p) p = p->next;
if(p) q = q->next;
}
return q;
}
struct Node* intersectingPoint(struct Node *p, struct Node *q)
{
struct Node *ps[10], *qs[10];
int i, j;
for (i = 0; p; i++)
{
ps[i] = p;
p = p->next;
}
for (j = 0; q; j++)
{
qs[j] = q;
q = q->next;
}
i--; j--;
for ( ; ps[i] == qs[j]; i--, j--)
{
p = ps[i];
}
return p;
}
int main()
{
int list2[] = {10, 20};
create(list2, sizeof(list2)/sizeof(int));
secound = first;
int list1[] = {1, 2, 3, 30, 40, 50};
create(list1, sizeof(list1)/sizeof(int));
secound->next->next = first->next->next->next;
listPrint(first);
listPrint(secound);
struct Node *in = intersectingPoint(first, secound);
printf("%d\n", in->data);
return 0;
}
|
C
|
#include "tracking.h"
u8 trackStatus=0;
void tracking_init(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
//PG4 PG8 PG6
GPIO_InitStructure.GPIO_Mode=GPIO_Mode_IN_FLOATING;
GPIO_InitStructure.GPIO_Pin=GPIO_Pin_4|GPIO_Pin_8|GPIO_Pin_6;
GPIO_InitStructure.GPIO_Speed=GPIO_Speed_50MHz;
GPIO_Init(GPIOG,&GPIO_InitStructure);
}
void trackingSearch(void) //ȡѭ״̬
{
if(TRACKING_LEFT==BLACK && TRACKING_MIDDLE==BLACK && TRACKING_RIGHT==BLACK){
trackStatus = ONLINE;
}else if(TRACKING_LEFT!=BLACK && TRACKING_MIDDLE==BLACK && TRACKING_RIGHT!=BLACK){
trackStatus = ONLINE;
}else if(TRACKING_LEFT==BLACK || (TRACKING_LEFT==BLACK && TRACKING_MIDDLE==BLACK)) {
trackStatus = ONRIGHT;
}else if(TRACKING_RIGHT==BLACK || (TRACKING_RIGHT==BLACK && TRACKING_MIDDLE==BLACK)){
trackStatus = ONLEFT;
}else{
trackStatus = 0;
}
}
|
C
|
#ifndef M2_REAL_H
#define M2_REAL_H
//---------------------------------------------------------------------------
#include "math2d.h"
#include <float.h>
#define m2Pi 3.1415926535897932f
#define m2HalfPi 1.5707963267948966f
#define m2TwoPi 6.2831853071795865f
#define m2RealMax FLT_MAX
#define m2RealMin FLT_MIN
#define m2RadToDeg 57.295779513082321f
#define m2DegToRad 0.0174532925199433f
typedef float m2Real;
//---------------------------------------------------------------------------
inline m2Real m2Clamp(m2Real &r, m2Real min, m2Real max)
{
if (r < min) return min;
else if (r > max) return max;
else return r;
}
//---------------------------------------------------------------------------
inline m2Real m2Min(m2Real r1, m2Real r2)
{
if (r1 <= r2) return r1;
else return r2;
}
//---------------------------------------------------------------------------
inline m2Real m2Max(m2Real r1, m2Real r2)
{
if (r1 >= r2) return r1;
else return r2;
}
//---------------------------------------------------------------------------
inline m2Real m2Abs(m2Real r)
{
if (r < 0.0f) return -r;
else return r;
}
//---------------------------------------------------------------------------
inline m2Real m2Random(m2Real min, m2Real max)
{
return min + ((m2Real)rand() / RAND_MAX) * (max - min);
}
//---------------------------------------------------------------------------
inline m2Real m2Acos(m2Real r)
{
// result is between 0 and pi
if (r < -1.0f) r = -1.0f;
if (r > 1.0f) r = 1.0f;
return acos(r);
}
#endif
|
C
|
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
typedef struct contagem
{
char c;
int count;
} Item;
void intercala(Item *vetor, int l, int meio, int r)
{
Item *aux = malloc(sizeof(Item) * (r - l + 1));
int a = l, b = meio + 1, c = 0;
while (a <= meio && b <= r)
{
if (vetor[a].count <= vetor[b].count)
{
aux[c++] = vetor[a++];
}
else
{
aux[c++] = vetor[b++];
}
}
while (a <= meio)
{
aux[c++] = vetor[a++];
}
while (b <= r)
{
aux[c++] = vetor[b++];
}
for (int i = l, j = 0; i <= r; i++, j++)
{
vetor[i] = aux[j];
}
free(aux);
}
void mergeSort(Item *vetor, int l, int r)
{
if (l >= r)
return;
int meio = (l + r) / 2;
mergeSort(vetor, l, meio);
mergeSort(vetor, meio + 1, r);
intercala(vetor, l, meio, r);
}
int main()
{
Item th[128];
memset(th, 0, sizeof(Item) * 128);
char b;
while (scanf("%c", &b) == 1 && b != '\n')
{
th[b].c = b;
th[b].count++;
};
mergeSort(th, 0, 127);
for (int i = 0; i < 128; i++)
{
if (th[i].count != 0)
{
printf("%d %d\n", th[i].c, th[i].count);
}
}
}
|
C
|
#include "reverse.h"
int main(int argc, const char** argv){
if(argc != 2){
fprintf(stderr, "Usage: reverse <string>\n");
return 1;
}
int len = strlen_hs(argv[1]);
char str[len+1];
memset(str, 0, len+1);
memcpy(str, argv[1], len);
reverse_string(str);
printf("[%s]\n", str);
return 0;
}
|
C
|
#include<stdio.h>
#define dim 20
#define len 200
#include<string.h>
typedef struct magasin {
char nome[dim];
int quantita;
int anno;
}reg;
main(){
reg registro1[len];
int data[len];
reg scaduti[len];
int i=0;
int b,d,c=0;
int oggi;
char ris[dim],ris1[dim], ris3[dim];
do {
printf("\n prodotti da clasificare:\t\nscrivi(si) per si o(no) per no ");
scanf("%s", ris);
if (strcmp(ris, "si") == 0) {
printf("\ninserisci il numero di prodotto da classificare:\t ");
scanf("%d", &b);
while (i < b) {
printf("\n inserire il nome del %d prodotto:\t", i + 1);
scanf("%s", registro1[i].nome);
printf("\ninserisci il numero di prodotto:\t ");
scanf("%d", ®istro1[i].quantita);
printf("\ninserisci la data di scandenza:\t ");
scanf("%d", ®istro1[i].anno);
i++;
}
printf("\nvuoi visualizzare la data base:\nrispondi con (si) o (no):\t");
scanf("%s", ris1);
if (strcmp(ris, "si") == 0) {
printf("\nla tua data base e':\n");
for (i = 0; i < b; i++)
printf("\n prodotto nome:\t%s\nprodotto quantita:\t%d\nanno scandenza:\t%d", registro1[i].nome, registro1[i].quantita, registro1[i].anno);
}
else
printf("\nGrazie\n");
/*printf("\ninserisci le date di scandenza dei prodotti in modo elecato:\n");
for (i = 0; i < b; i++) {
printf("\ndata scadenza %d prodotto:\t", i + 1);
scanf("%d", &data[i]);
}
for (i = 0; i < b; i++) {
if (registro1[i].anno == data[i] || registro1[i].anno >= data[i]) {
scaduti[c].anno = registro1[i].anno;
strcpy(scaduti[c].nome, registro1[i].nome);
scaduti[c].quantita = registro1[i].quantita;
d = c++;
}*/
printf("\ninserici anno di oggi :\t");
scanf("%d", &oggi);
for (i = 0; i < b; i++) {
if (registro1[i].anno == oggi || registro1[i].anno <= oggi) {
scaduti[c].anno = registro1[i].anno;
strcpy(scaduti[c].nome, registro1[i].nome);
scaduti[c].quantita = registro1[i].quantita;
d = c++;
}
else {
scaduti[c].anno = registro1[i].anno;
strcpy(scaduti[c].nome, registro1[i].nome);
scaduti[c].quantita = registro1[i].quantita;
printf("\n non e scaduto :\nprodotto nome : \t%s\nprodotto quantita : \t%d\nanno scandenza : \t%d", scaduti[c].nome, scaduti[c].quantita, scaduti[c].anno);
}
printf("\n");
}
for (c = 0; c < d; c++)
printf("\n prodotto nome : \t%s\nprodotto quantita : \t%d\nanno scandenza : \t%d", scaduti[c].nome, scaduti[c].quantita, scaduti[c].anno);
} else {
printf("\nGrazie\n");
}
printf("\nscrivi (fine) per chuidere il programma o scrivi (si) per continuare:\t");
scanf("%s", ris);
} while (strcmp(ris, "fine") != 0);
}
|
C
|
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
#include <time.h>
void automorphicNumbers(void);
void randCustom(void);
void maxThree(void);
void avrPositive(void);
void existsOdd(void);
void divide(void);
void fromSquareToCube(void);
void checkmate(void);
void exchange(void);
//int main(int argc, const char * argv[])
//{
// srand((int)time(NULL));
//
// automorphicNumbers();
// randCustom();
// maxThree();
// avrPositive();
// existsOdd();
// divide();
// fromSquareToCube();
// checkmate();
// exchange();
//
// return 0;
//}
void exchange()
{
printf("\nTask 3b: exchange of values without temp var\n");
int a = 42;
int b = 11;
printf("a = %i, b = %i\n", a, b);
a = a - b;
b = a + b;
a = b - a;
printf("a = %i, b = %i\n", a, b);
}
void checkmate()
{
printf("\nTask 7: check and mats\n");
int x1;
int y1;
int x2;
int y2;
printf("Input x1: ");
scanf("%i", &x1);
printf("Input y1: ");
scanf("%i", &y1);
printf("Input x2: ");
scanf("%i", &x2);
printf("Input y2: ");
scanf("%i", &y2);
int isOneColor = (((abs(x1 - x2)) % 2) > 0) == (((abs(y1 - y2)) % 2) > 0);
printf("One color? – %s\n", isOneColor ? "Yeap!" : "Nope!");
}
void fromSquareToCube()
{
printf("\nTask 8: square and cube\n");
int from;
int to;
int i;
printf("Input from: ");
scanf("%i", &from);
printf("Input to: ");
scanf("%i", &to);
for (i = from; i <= to; i++) {
printf("Result: %i, %i, %i\n", i, i * i, i * i * i);
}
}
void divide()
{
printf("\nTask 9: divide\n");
int dividend;
int divider;
int quotient = 0;
printf("Input dividend: ");
scanf("%i", ÷nd);
printf("Input divider: ");
scanf("%i", ÷r);
for (dividend; dividend >= divider; dividend -= divider) {
quotient++;
}
printf("Quotient: %i\n", quotient);
printf("Memainder: %i\n", dividend);
}
void existsOdd()
{
printf("\nTask 10: exists odd numbers\n");
int number;
int part;
printf("Input number: ");
scanf("%i", &number);
for (part = number; part != 0; part /= 10) {
if (part % 2 != 0) {
printf("True\n");
return;
}
}
printf("False\n");
}
void avrPositive()
{
printf("\nTask 11: average of positive with 8\n");
int count = 0;
double avr = 0;
int number;
do {
printf("Input number (0 to end): ");
scanf("%i", &number);
if (number > 0 && number % 10 == 8) {
avr += number;
count++;
printf("– check!\n");
}
} while(number != 0);
printf("Avr: %f\n", avr / count);
}
void maxThree()
{
printf("\nTask 12: max number\n");
int size = 3;
int i;
int max;
int arrayNumbers[size];
printf("Array: ");
for (i = 0; i < size; i++) {
arrayNumbers[i] = (int)rand() % 100;
printf("%i ", arrayNumbers[i]);
}
max = arrayNumbers[0];
for (i = 1; i < size; i++) {
if (arrayNumbers[i] > max) {
max = arrayNumbers[i];
}
}
printf("Max: %i\n", max);
}
void randCustom()
{
printf("\nTask 13: rand\n");
int from = 1;
int to = 100;
int randNum = rand() % to + from;
printf("Rand stdlib: %i\n", randNum);
int a = 494;
int b = 2230;
// В нормальном генераторе я бы запоминал последнее сгенерированное
// число и подставлял бы его в расчёты, но тут возьму из randNum.
randNum = (a * randNum + b) % to + from;
printf("Rand custom: %d\n", randNum);
}
void automorphicNumbers()
{
printf("Task 14: automorphic numbers\n");
int number;
int divider;
printf("Input number: ");
scanf("%i", &number);
for (int i = 0; i <= number; i++) {
// Проверка на ноль – костыль, для оптимизации может быть уместно
// вынести вывод 0 перед цеиклом (вручную), и вырезать проверку.
divider = pow(10, (int)(log10(i == 0 ? 1 : i) + 1));
if ((i * i) % divider == i) {
printf("%d ", i);
}
}
}
|
C
|
#include "holberton.h"
/**
* print_line - function that draws a straight line in the terminal
* Description: Function that draws a straight line in the terminal
* @n: number of times the character _ us printed
* Return: void (successful)
*/
void print_line(int n)
{
int i;
for (i = n; i > 0; i--)
{
_putchar(95);
if (i == 0 && i < 0)
{
_putchar('\n');
}
}
_putchar('\n');
}
|
C
|
#pragma once
#include <stdbool.h>
typedef void* thread_t;
typedef void ( *thread_fnc_t )( void* );
typedef void* mutex_t;
thread_t thread_create( thread_fnc_t callback, void* argument );
bool thread_join( thread_t thr );
mutex_t mutex_create();
void mutex_lock( mutex_t m );
void mutex_unlock( mutex_t m );
bool mutex_try_lock( mutex_t m );
void mutex_destroy( mutex_t m );
|
C
|
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <pthread.h>
#include <unistd.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include "list.h"
#include "listFd.h"
int current_fd;
int main(int argc, char **argv) {
//Variables for the arguments and for the execution
int portNum = -1;
int mySocket;
char *token = NULL;
char *clientIP = NULL;
int clientPortNum = 0;
int flag = 0;
int bytes = -1;
int numOfClients = 0;
int fd ;
//strings for messages process
char *tuple = NULL;
char *getClientsMessage = NULL;
char *message = NULL;
char readBuffer[1000];
char writeBuffer[1000];
char *userOnMessage = malloc(50 * sizeof(char));
char delim[4] = " ,";
ListID *listID = NULL;
//Structs for socket communication
struct sockaddr_in server,client;
struct sockaddr *serverPtr = (struct sockaddr *)&server;
struct sockaddr *clientPtr = (struct sockaddr *)&client;
struct in_addr clientAddr;
socklen_t socklen = sizeof(client);
// Arguments processing
if (argc != 3) {
printf("<Wrong number of arguments!>");
return -1;
}
for (int i = 1; i < argc; i += 2) {
if (!strcmp(argv[i], "-p")) portNum = atoi(argv[i+1]);
else {
printf("<Wrong arguments!>");
return -1;
}
}
mySocket = socket(AF_INET,SOCK_STREAM,0);
if (mySocket == -1) {
perror("<Socket creation failed!>");
return -1;
}
int option = 1;
// kill "Address already in use" error message || Reuse the same port
if (setsockopt(mySocket, SOL_SOCKET, SO_REUSEADDR, &option, sizeof(int)) == -1) {
perror("setsockopt");
return -1;
}
server.sin_family = AF_INET;
server.sin_addr.s_addr = htonl(INADDR_ANY);
server.sin_port = htons(portNum);
//Binding
if (bind(mySocket,serverPtr, sizeof(server)) < 0) {
perror("<Socket binding failed!>");
return -1;
}
//Listening
if (listen(mySocket,3) < 0) {
perror("<Socket listening failed!>");
return -1;
}
printf("Server is listening in port %d!\n", portNum);
//List of file descriptors
fileDes *fdList = NULL;
fileDes *newList = NULL;
while (1) {
// Accept continuously new connections
fd = accept(mySocket, clientPtr, &socklen);
if (fd < 0) {
perror("<Accept failed!>");
exit(-1);
}
if ((bytes = read(fd, readBuffer, 1000)) > 0) {
printf("MESSAGE RECEIVED: %s\n", readBuffer);
token = strtok(readBuffer, " ,");
// Processing "LOG_ON" request
if (!strcmp(token, "LOG_ON")) {
numOfClients++;
while (token != NULL) {
if (flag == 1) clientIP = strdup(token);
else if (flag == 2) clientPortNum = atoi(token);
token = strtok(NULL, ",");
flag++;
}
flag = 0;
struct in_addr tempAddress;
tempAddress.s_addr = atoi(clientIP);
char *temp_addr = inet_ntoa(tempAddress);
// append the tuple <IP, portNum> to servers list
listID = append(clientPortNum, numOfClients, clientIP, listID);
tuple = getList (listID,clientPortNum,clientIP);
// Create "USER_ON" message
sprintf(userOnMessage,"%s %s %d", "USER_ON", clientIP, clientPortNum);
fileDes *temp = fdList;
// Broadcast "USER_ON" message to other clients
while (temp != NULL) {
memset(writeBuffer, '\0', 1000);
strcpy(writeBuffer,userOnMessage);
write(temp->fd, writeBuffer, strlen(writeBuffer));
temp = temp->next;
}
fdList = appendFd(fd, fdList);
//if clients are more than one connected to dropboxServer
if (tuple != NULL) {
// Creating "CLIENT_LIST" message
getClientsMessage = strdup("CLIENT_LIST");
message = malloc(strlen(getClientsMessage) + strlen(tuple) + sizeof(int)) ;
sprintf(message, "%s %d %s", getClientsMessage, numOfClients - 1, tuple);
memset(writeBuffer, '\0', 1000);
strcpy(writeBuffer, message);
write(fd, writeBuffer, sizeof(writeBuffer));
free(message);
free(getClientsMessage);
}
//If there is only one client in the system
else {
getClientsMessage = strdup("CLIENTS_LIST 0");
memset(writeBuffer, '\0', 1000);
strcpy(writeBuffer, getClientsMessage);
write(fd, writeBuffer, sizeof(writeBuffer));
free(getClientsMessage);
}
}
else if (strcmp(token, "LOG_OFF") == 0){
token = strtok(NULL, delim);
char *ip_to_del = strdup(token);
token = strtok(NULL, delim);
int portNum_to_del = atoi(token);
if (search(portNum_to_del, ip_to_del, listID)){
delete(portNum_to_del, ip_to_del, &listID);
fileDes *t = fdList;
char *mess = calloc(100, sizeof(char));
sprintf(mess, "%s %s %d", "USER_OFF", ip_to_del, portNum_to_del);
// Broadcast "USER_ON" message to other clients
while (t != NULL) {
memset(writeBuffer, '\0', 1000);
strcpy(writeBuffer,mess);
write(t->fd, writeBuffer, strlen(writeBuffer));
t= t->next;
}
deleteNodeFd(&newList,fd);
}
else {
printf("ERROR_IP_PORT_NOT_FOUND_IN_LIST\n");
}
}
memset(writeBuffer, '\0', 1000);
memset(readBuffer, '\0', 1000);
}
}
}
|
C
|
/*
** alias.c for 42sh in C:\Users\gambin_l\42SH\sources\builtins
**
** Made by Gambini Lucas
** Login <Lucas [email protected]>
**
** Started on Sun Jun 05 14:04:29 2016 Gambini Lucas
** Last update Mon Jun 6 19:40:28 2016 boris saint-bonnet
*/
# include "42.h"
char *just_concate(char *base, char *add)
{
char *ret;
int i;
int j;
if (base == NULL || add == NULL)
return (NULL);
if ((ret = malloc(sizeof(char)
* (strlen(base) + strlen(add) + 2))) == NULL)
return (NULL);
i = -1;
while (base[++i] != '\0')
ret[i] = base[i];
ret[i++] = ' ';
j = 0;
while (add[j] != '\0')
ret[i++] = add[j++];
ret[i] = '\0';
return (ret);
}
int check_line(char **cmd)
{
int i;
i = -1;
if (!cmd || !cmd[1])
return (FAILURE);
while (cmd[1][++i])
{
if (cmd[1][i] == '=' || cmd[1][i] == '\"')
return (FAILURE);
}
return (SUCCESS);
}
char *get_data_rc(char **cmd)
{
int i;
char *ret;
i = 1;
ret = NULL;
while (cmd[++i])
{
if (!ret)
ret = strdup(cmd[i]);
else
ret = just_concate(ret, cmd[i]);
}
return (ret);
}
int builtin_alias(t_list *list, char **cmd)
{
(void)list;
if (check_line(cmd) == FAILURE)
return (SUCCESS);
list->myRc = push_bash(list->myRc, get_data_rc(cmd), cmd[1]);
return (SUCCESS);
}
|
C
|
/*
** EPITECH PROJECT, 2021
** zappy
** File description:
** main
*/
static void try_move(world_t *world, player_t *player, int *x, int *y)
{
switch (player->_o) {
case (UP):
*x = player->_x;
*y = (0 < (player->_y - 1)) ? world->_y - 1 : player->_y - 1;
case (DOWN):
*x = player->_x;
*y = (world->_y <= (player->_y + 1)) ? 0 : player->_y + 1;
case (RIGHT):
*x = (world->_x <= (player->_x + 1)) ? 0 : player->_x + 1;
*y = player->_y;
case (LEFT):
*x = (0 < (player->_x - 1)) ? world->_x - 1 : player->_x - 1;
*y = player->_y;
}
}
int forward(client_t *clt, world_t *world)
{
player_t *player = find_player(clt->_id, world->_players);
int x = 0;
int y = 0;
if (!player) {
print("forward error no player found.\n");
return (84);
}
try_move(world, player, &x, &y);
player->_x = x;
player->_y = y;
print("forward ok.\n");
return (0);
}
|
C
|
#include <stdio.h>
/*
[description]
C(1≤C≤50)
정사각형의 수 n (1≤n≤100)
가로에 블럭이 하나의 그룹으로 되어야 한다
print result % 10,000,000
*/
#define FOR(i,j) for(i=0; i<(j); ++i)
#define FORP(i,j) for(i=1; i<=(j); ++i)
#define MAX_BLOCKS (100)
#define DIVIDER (10000000)
#define debugf
// polyomino_count[UP_COUNT][CURRENT_ROW_COUNT]
int polyomino_count[MAX_BLOCKS+1][MAX_BLOCKS+1];
int total_count;
int memo[MAX_BLOCKS+1][MAX_BLOCKS+1];
void init_board(int size_of_block)
{
int i;
int j;
FORP(i, size_of_block)
{
FORP(j, size_of_block)
{
polyomino_count[i][j] = j - 1 + i;
memo[i][j] = -1;
}
polyomino_count[0][i] = 1;
polyomino_count[i][0] = 1;
memo[0][i] = -1;
memo[i][0] = -1;
}
total_count = 0;
}
int get_answer(int up_count, int size_of_block)
{
debugf("[%d][%d]\n", up_count, size_of_block);
if (size_of_block == 0)
{
debugf("size_of_block 0\n");
return polyomino_count[up_count][0];
}
if (memo[up_count][size_of_block] != -1)
{
debugf("memo[%d][%d] %d\n", up_count, size_of_block, memo[up_count][size_of_block]);
return memo[up_count][size_of_block];
}
int i;
int count = 0;
FORP(i, size_of_block)
{
count += polyomino_count[up_count][i] * get_answer(i, size_of_block - i);
count = count % DIVIDER;
}
memo[up_count][size_of_block] = count;
debugf("[%d][%d] %d\n", up_count, size_of_block, count);
return count;
}
int main()
{
int test_case = 0;
int i = 0;
int size_of_block = 0;
scanf("%d", &test_case);
FOR(i, test_case)
{
scanf("%d", &size_of_block);
init_board(size_of_block);
printf("%d\n", get_answer(0, size_of_block));
}
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
main()
{
char a = '1' ;
char a1 = "1" ;
int i ;
i = atoi(a1) ;
printf( "kkkkkkkkkkk : %s ",a1 ) ;
printf( "kkkkkkkkkkk : %d ",i ) ;
}
|
C
|
#include<stdio.h>
struct dist
{
int km;
int m;
}d1,d2,d3;
struct dist add(struct dist a,struct dist b)
{
struct dist temp;
temp.km=a.km+b.km;
temp.m=a.m+b.m;
while(temp.m>=1000)
{
temp.km++;
ttemp.m-=1000;
}
return temp;
}
int main()
{
scanf("\n%d%d",&d1.km,&d1.m);
scanf("\n%d%d",&d2.km,&d2.m);
d3=add(d1,d2);
printf("\n%d km\t%d m",d3.km,d3.m);
return 0;
}
|
C
|
/*
** get_port.c for epitech in /home/chapuis_s/rendu/
**
** Made by chapui_s
** Login <[email protected]>
**
** Started on Mon Apr 6 04:15:57 2015 chapui_s
** Last update Thu Apr 16 00:04:03 2015 chapui_s
*/
#include "server.h"
int get_port(t_server *server, int argc, char **argv)
{
int port;
port = DEFAULT_PORT;
if (argc > 1)
{
port = atoi(argv[1]);
}
if (port <= 0 || port >= 0xFFFF)
{
fprintf(stderr, "%s: %s\n", argv[0], "Wrong port number");
return (-1);
}
else
{
server->port = port;
return (0);
}
}
|
C
|
#include<stdio.h>
#include<conio.h>
void main()
{
int num1,num2,temp;
printf("Enter first number");
scanf("%d",&num1);
printf("Enter second number");
scanf("%d",&num2);
if(num1>num2)
{
temp=num1;
num1=num2;
num2=temp;
}
if((num2%num1)==0)
{
printf("Multiplied\n");
}
else
{
printf("Not Multiplied");
}
getch();
}
|
C
|
#include <stdio.h>
int a[100001];
int main(void)
{
int n, i;
while(1)
{
ReadNewInput: scanf("%d", &n);
if(n)
{
for(i = 1; i <= n; i++)
scanf("%d", a + i);
for(i = 1; i <= n; i++)
if(i != *(a + *(a + i)))
{
printf("not ambiguous\n");
goto ReadNewInput;
}
printf("ambiguous\n");
}
else
return 0;
}
}
|
C
|
#include "test_helpers.h"
#include "interface.h"
#include <string.h>
#include <stdlib.h>
void initGameState(int players, struct gameState* state)
{
memset(state, 0, sizeof(struct gameState));
state->numPlayers = players;
state->numActions = 1;
state->numBuys = 1;
state->whoseTurn = 0;
state->phase = 0;
}
void addCards(int player, int* hand, int* deck, int* discard, struct gameState* state)
{
for (int i = 0; hand[i] != -1; ++i) {
state->hand[player][i] = hand[i];
state->handCount[player]++;
}
for (int i = 0; discard[i] != -1; ++i) {
state->discard[player][i] = discard[i];
state->discardCount[player]++;
}
for (int i = 0; deck[i] != -1; ++i) {
state->deck[player][i] = deck[i];
state->deckCount[player]++;
}
}
void fillDeck(int player, struct gameState* state, int max)
{
state->deckCount[player] = max;
for (int i = 0; i < MAX_DECK; ++i)
state->deck[player][i] = -1;
for (int i = 0; i < max; ++i)
{
state->deck[player][i] = rand() % (LAST_CARD + 1);
}
}
void fillHand(int player, struct gameState* state, int max)
{
state->handCount[player] = max;
for (int i = 0; i < MAX_HAND; ++i)
state->hand[player][i] = -1;
for (int i = 0; i < max; ++i)
state->hand[player][i] = rand() % (LAST_CARD + 1);
}
void fillDiscard(int player, struct gameState* state, int max)
{
state->discardCount[player] = max;
for (int i = 0; i < MAX_DECK; ++i)
state->discard[player][i] = -1;
for (int i = 0; i < max; ++i)
state->discard[player][i] = rand() % (LAST_CARD);
}
void debugGameState(int player, struct gameState* state)
{
printf("numPlayers: %d\n", state->numPlayers);
printf("whoseTurn: %d\n", state->whoseTurn);
printf("numActions: %d\n", state->numActions);
char phase[20];
phaseNumToName(state->phase, phase);
printf("phase: %s\n", phase);
printf("playedCardCount: %d\n", state->playedCardCount);
printf("playedCards: ");
for (int i = 0; i < state->playedCardCount; ++i) {
char name[20];
cardNumToName(state->playedCards[i], name);
printf("%s ", name);
}
printf("\n\n");
if (player > -1) {
printf("handCount: %d\n", state->handCount[player]);
printf("Hand: ");
for (int i = 0; i < state->handCount[player]; ++i) {
char name[20];
cardNumToName(state->hand[player][i], name);
printf("%s ", name);
}
printf("\n");
printf("deckCount: %d\n", state->deckCount[player]);
printf("Deck: ");
for (int i = 0; i < state->deckCount[player]; ++i) {
char name[20];
cardNumToName(state->deck[player][i], name);
printf("%s ", name);
}
printf("\n");
printf("discardCount: %d\n", state->discardCount[player]);
printf("Discard: ");
for (int i = 0; i < state->discardCount[player]; ++i) {
char name[20];
cardNumToName(state->deck[player][i], name);
printf("%s ", name);
}
printf("\n");
}
printf("\n");
}
int countCards(int card, int* pile, int size)
{
int count = 0;
for (int i = 0; i < size && i != -1; ++i)
{
if (pile[i] == card)
{
++count;
}
}
return count;
}
|
C
|
#include "oled.h"
#include "hardi2c1.h"
#include "oledfont.h"
#include <stdio.h>
/*
128*64
128
64Уÿֽڿһе8УܹҪ8ֽ
Ŀǰֻ֧16壨ĸ8*1616*16ʽ
Ϊ߶16Ļֻʾ4
һʾӢַ16
ֻʾ8
2020-04-05
*/
static uint8_t OLED_GRAM[8][128]; //8*8*128
int8_t OLED_WR_data(u8 *dat,uint16_t len,u8 mode)
{
return i2c1_write_data(SLAVER_ADDR_OLED,mode,dat,len);
// return 0;
}
//Դ浽OLED
void OLED_Refresh(void)
{
OLED_WR_data(OLED_GRAM[0],sizeof OLED_GRAM,OLED_DATA);
// OLED_WR_data(OLED_GRAM[0],32,OLED_DATA);
}
//
void OLED_Clear(void)
{
u8 i=0,n;
for(i=0;i<8;i++)
{
for(n=0;n<128;n++)
{
OLED_GRAM[i][n] = 1<<i;//
}
}
OLED_Refresh();//ʾ
}
////
////x:0~127
////y:0~63
//void OLED_DrawPoint(u8 x,u8 y)
//{
// u8 i,m,n;
// i = y>>3;
// m = y&7;
// n = 1<<m;
//
// OLED_GRAM[x][i]|=n;
//}
////һ
////x:0~127
////y:0~63
//void OLED_ClearPoint(u8 x,u8 y)
//{
// OLED_GRAM[x][y>>3] &=~(1<<(y&7));
//}
//ָλʾһַ,ַ
//y:0~127
//x:0~63
//size:ѡ 12/16/24
//ȡģʽ ʽ
void OLED_ShowChar(u8 x,u8 y,u8 chr,u8 size1)
{
u8 i,chr1;
u8 *temp;
y /= 8;
chr1 = chr - ' '; //ƫƺֵ
temp = (void*)asc2_1608;
size1 = 16;
// if(size1==12) //1206
// {
// temp = (void*)asc2_1206;
// }
// else if(size1==16)//1608
// {
// temp = (void*)asc2_1608;
// }
// else if(size1==24)//2412
// {
// temp = (void*)asc2_2412;
// }
// else
// return;
for(i=0;i<size1;i++)
{
OLED_GRAM[y+(i>>3)][x+(i&7)] = temp[chr1*size1+i];
}
}
//ʾַ
//x,y:
//size1:С
//*chr:ַʼַ
void OLED_ShowString(u8 x,u8 y,u8 *chr,u8 size1)
{
while((*chr>=' ')&&(*chr<='~'))//жDzǷǷַ!
{
OLED_ShowChar(x,y,*chr,size1);
x += size1/2;
if(x > 128-size1/2) //
{
x=0;
y+=16;
}
chr++;
}
OLED_Refresh();//ʾ
}
//ʾ
//x,y:
//num:ֶӦ
//ȡģʽ ʽ
static void OLED_ShowChinese(u8 x,u8 y,u8* str,u8 size1)
{
uint8_t* temp ;
uint8_t i,j;
y /= 8;
// if(num*2 > sizeof Hzk1 / (sizeof Hzk1[0]))
// {
// return ;
// }
temp = (void*)str;
for(j=0;j<2;j++)
for(i=0;i<size1;i++)
{
OLED_GRAM[y+(i>>4)+j][x+(i&0xf)] = temp[i+j*size1];
}
}
/*
x xʼλ
y yʼλã00Ͻǣ
chr ַַ
len ʾʾֵĸ
size1 ʾС
*/
void OLED_Chinese(u8 x,u8 y,void* chr,uint8_t len,u8 size1)
{
uint8_t i;
for(i=0;i<len;i++)
{
OLED_ShowChinese(x+size1*i,y,(uint8_t*)chr+2*size1*i,size1);
}
}
////ʾ2
////x,y :
////len :ֵλ
////size:С
void OLED_ShowNum(u8 x,u8 y,u32 num,u8 size1)
{
u8 t=0;
u8 arr[16] = {0};
t = 15;
while(num)
{
arr[--t] = num%10+'0';
num /= 10;
}
OLED_ShowString(x,y,arr+t,size1);
}
void Oled_init(void)
{
const uint8_t cmd[] = {0xAE,0x00,0x10,0x40,0x81,0xCF,0xA1,0xC8,
0xA6,0xA8,0x3f,0xD3,0x00,0xd5,0x80,0xD9,
0xF1,0xDA,0x12,0xDB,0x40,0x20,0x00,0x8D,
0x14,0xA4,0xA6,0xAF};
i2c1_init(); //i2cӿڳʼ
OLED_WR_data((void*)cmd,sizeof cmd,OLED_CMD);
// OLED_WR_Byte(0xAE,OLED_CMD);//--turn off oled panel
// OLED_WR_Byte(0x00,OLED_CMD);//---set low column address
// OLED_WR_Byte(0x10,OLED_CMD);//---set high column address
// OLED_WR_Byte(0x40,OLED_CMD);//--set start line address Set Mapping RAM Display Start Line (0x00~0x3F)
// OLED_WR_Byte(0x81,OLED_CMD);//--set contrast control register
// OLED_WR_Byte(0xCF,OLED_CMD);// Set SEG Output Current Brightness
// OLED_WR_Byte(0xA1,OLED_CMD);//--Set SEG/Column Mapping 0xa0ҷ 0xa1
// OLED_WR_Byte(0xC8,OLED_CMD);//Set COM/Row Scan Direction 0xc0· 0xc8
// OLED_WR_Byte(0xA6,OLED_CMD);//--set normal display
// OLED_WR_Byte(0xA8,OLED_CMD);//--set multiplex ratio(1 to 64)
// OLED_WR_Byte(0x3f,OLED_CMD);//--1/64 duty
// OLED_WR_Byte(0xD3,OLED_CMD);//-set display offset Shift Mapping RAM Counter (0x00~0x3F)
// OLED_WR_Byte(0x00,OLED_CMD);//-not offset
// OLED_WR_Byte(0xd5,OLED_CMD);//--set display clock divide ratio/oscillator frequency
// OLED_WR_Byte(0x80,OLED_CMD);//--set divide ratio, Set Clock as 100 Frames/Sec
// OLED_WR_Byte(0xD9,OLED_CMD);//--set pre-charge period
// OLED_WR_Byte(0xF1,OLED_CMD);//Set Pre-Charge as 15 Clocks & Discharge as 1 Clock
// OLED_WR_Byte(0xDA,OLED_CMD);//--set com pins hardware configuration
// OLED_WR_Byte(0x12,OLED_CMD);
// OLED_WR_Byte(0xDB,OLED_CMD);//--set vcomh
// OLED_WR_Byte(0x40,OLED_CMD);//Set VCOM Deselect Level
// OLED_WR_Byte(0x20,OLED_CMD);//-Set Page Addressing Mode (0x00/0x01/0x02)
// OLED_WR_Byte(0x02,OLED_CMD);//
// OLED_WR_Byte(0x8D,OLED_CMD);//--set Charge Pump enable/disable
// OLED_WR_Byte(0x14,OLED_CMD);//--set(0x10) disable
// OLED_WR_Byte(0xA4,OLED_CMD);// Disable Entire Display On (0xa4/0xa5)
// OLED_WR_Byte(0xA6,OLED_CMD);// Disable Inverse Display On (0xa6/a7)
// OLED_WR_Byte(0xAF,OLED_CMD);
OLED_Clear();
}
|
C
|
#include <iot/threadpool.h>
#include <iot/iot.h>
#include <CUnit.h>
#include "scheduler.h"
static atomic_uint_fast32_t sum_test;
static atomic_uint_fast32_t infinity_test;
static atomic_uint_fast32_t sum_work1, sum_work2, sum_work3;
static atomic_uint_fast32_t counter;
static iot_logger_t *logger = NULL;
static void reset_counters (void)
{
atomic_store (&sum_test, 0);
atomic_store (&infinity_test, 0);
atomic_store (&sum_work1, 0);
atomic_store (&sum_work2, 0);
atomic_store (&sum_work3, 0);
atomic_store (&counter, 0);
}
static void do_work1 (void *in)
{
for (uint32_t i = 0; i < 10; ++i)
{
atomic_fetch_add (&sum_work1, 1u);
}
}
static void do_work2 (void *in)
{
for (uint32_t i = 0; i < 20; ++i)
{
atomic_fetch_add (&sum_work2, i);
}
}
static void do_work3 (void *in)
{
for (int i = 0; i < 30; ++i)
{
atomic_fetch_add (&sum_work3, i);
}
}
static void do_work4 (void *in)
{
atomic_fetch_add (&sum_test, 1u);
}
static void do_work5 (void *in)
{
atomic_fetch_add (&infinity_test, 1u);
}
static void do_count (void *in)
{
atomic_fetch_add (&counter, 1u);
}
static int suite_init (void)
{
logger = iot_logger_alloc ("Test", IOT_LOG_WARN);
iot_logger_start (logger);
return 0;
}
static int suite_clean (void)
{
iot_logger_free (logger);
return 0;
}
static void cunit_scheduler_start (void)
{
iot_threadpool_t *pool = iot_threadpool_alloc (4, 0, NULL, logger);
iot_scheduler_t *scheduler = iot_scheduler_alloc (pool, logger);
reset_counters ();
CU_ASSERT (iot_threadpool_start (pool))
CU_ASSERT (iot_scheduler_start (scheduler))
iot_schedule_t *sched1 = iot_schedule_create (scheduler, do_work1, NULL, IOT_MS_TO_NS (500), 0, 0, NULL);
CU_ASSERT (sched1 != NULL)
iot_schedule_t *sched2 = iot_schedule_create (scheduler, do_work2, NULL, IOT_SEC_TO_NS (1), 0, 0, NULL);
CU_ASSERT (sched2 != NULL)
iot_schedule_t *sched3 = iot_schedule_create (scheduler, do_work3, NULL, IOT_SEC_TO_NS (1), 0, 0, NULL);
CU_ASSERT (sched3 != NULL)
CU_ASSERT (iot_schedule_add (scheduler, sched1))
CU_ASSERT (iot_schedule_add (scheduler, sched2))
sleep (2);
CU_ASSERT (atomic_load (&sum_work1) > 0u)
CU_ASSERT (atomic_load (&sum_work2) > 0u)
CU_ASSERT (atomic_load (&sum_work3) == 0u)
iot_threadpool_free (pool);
iot_scheduler_free (scheduler);
}
static void cunit_scheduler_stop (void)
{
iot_threadpool_t *pool = iot_threadpool_alloc (4, 0, NULL, logger);
iot_scheduler_t *scheduler = iot_scheduler_alloc (pool, logger);
reset_counters ();
CU_ASSERT (iot_threadpool_start (pool))
CU_ASSERT (iot_scheduler_start (scheduler))
sum_test = 0;
iot_schedule_t *sched1 = iot_schedule_create (scheduler, do_work4, NULL, IOT_MS_TO_NS (1), 0, 1, NULL);
CU_ASSERT (sched1 != NULL)
CU_ASSERT (iot_schedule_add (scheduler, sched1))
sleep (2);
iot_scheduler_stop (scheduler);
CU_ASSERT (atomic_load (&sum_test) == 1u)
iot_threadpool_free (pool);
iot_scheduler_free (scheduler);
}
static void cunit_scheduler_create (void)
{
iot_threadpool_t *pool = iot_threadpool_alloc (4, 0, NULL, logger);
iot_scheduler_t *scheduler = iot_scheduler_alloc (pool, logger);
CU_ASSERT (iot_threadpool_start (pool))
CU_ASSERT (iot_scheduler_start (scheduler))
reset_counters ();
iot_schedule_t *sched1 = iot_schedule_create (scheduler, do_work4, NULL, IOT_MS_TO_NS (250), 0, 1, NULL);
iot_schedule_t *sched2 = iot_schedule_create (scheduler, do_work5, NULL, IOT_MS_TO_NS (1), 0, 0, NULL);
CU_ASSERT (sched1 != NULL)
CU_ASSERT (sched2 != NULL)
CU_ASSERT (iot_schedule_add (scheduler, sched1))
CU_ASSERT (iot_schedule_add (scheduler, sched2))
iot_scheduler_start (scheduler);
sleep (2);
iot_scheduler_stop (scheduler);
CU_ASSERT (atomic_load (&sum_test) == 1u)
CU_ASSERT (atomic_load (&infinity_test) > 5u)
iot_threadpool_free (pool);
iot_scheduler_free (scheduler);
}
static void cunit_scheduler_remove (void)
{
iot_threadpool_t *pool = iot_threadpool_alloc (4, 0, NULL, logger);
iot_scheduler_t *scheduler = iot_scheduler_alloc (pool, logger);
CU_ASSERT (iot_threadpool_start (pool))
CU_ASSERT (iot_scheduler_start (scheduler))
reset_counters ();
iot_schedule_t *sched1 = iot_schedule_create (scheduler, do_work4, NULL, IOT_MS_TO_NS (1), 0, 1, NULL);
iot_schedule_t *sched2 = iot_schedule_create (scheduler, do_work5, NULL, IOT_MS_TO_NS (1), 0, 0, NULL);
iot_schedule_t *sched3 = iot_schedule_create (scheduler, do_work5, NULL, IOT_MS_TO_NS (1), 0, 0, NULL);
iot_schedule_t *sched4 = iot_schedule_create (scheduler, do_work3, NULL, IOT_MS_TO_NS (1), 0, 0, NULL);
iot_schedule_t *sched5 = iot_schedule_create (scheduler, do_work3, NULL, IOT_MS_TO_NS (1), 0, 0, NULL);
iot_schedule_t *sched6 = iot_schedule_create (scheduler, do_work3, NULL, IOT_MS_TO_NS (1), 0, 0, NULL);
CU_ASSERT (sched1 != NULL)
CU_ASSERT (sched2 != NULL)
CU_ASSERT (sched3 != NULL)
CU_ASSERT (sched4 != NULL)
CU_ASSERT (sched5 != NULL)
CU_ASSERT (sched6 != NULL)
CU_ASSERT (iot_schedule_add (scheduler, sched1))
CU_ASSERT (iot_schedule_add (scheduler, sched2))
CU_ASSERT (iot_schedule_add (scheduler, sched3))
CU_ASSERT (iot_schedule_add (scheduler, sched4))
CU_ASSERT (iot_schedule_add (scheduler, sched5))
CU_ASSERT (iot_schedule_add (scheduler, sched6))
sleep (1);
iot_schedule_remove (scheduler, sched2);
iot_schedule_remove (scheduler, sched3);
CU_ASSERT (atomic_load (&sum_test) == 1u)
CU_ASSERT (atomic_load (&infinity_test) > 20u)
uint32_t temp = atomic_load (&infinity_test);
sleep (1);
CU_ASSERT (temp <= (atomic_load (&infinity_test) + 2u))
iot_schedule_delete (scheduler, sched3);
iot_threadpool_free (pool);
iot_scheduler_free (scheduler);
}
static void cunit_scheduler_delete (void)
{
iot_threadpool_t *pool = iot_threadpool_alloc (4, 0, NULL, logger);
iot_scheduler_t *scheduler = iot_scheduler_alloc (pool, logger);
CU_ASSERT (iot_threadpool_start (pool))
reset_counters ();
iot_schedule_t *sched1 = iot_schedule_create (scheduler, do_work3, NULL, IOT_MS_TO_NS (1), 0, 1, NULL);
iot_schedule_t *sched2 = iot_schedule_create (scheduler, do_work4, NULL, IOT_MS_TO_NS (1), 0, 1, NULL);
iot_schedule_t *sched3 = iot_schedule_create (scheduler, do_work5, NULL, IOT_MS_TO_NS (1), 0, 0, NULL);
iot_schedule_t *sched4 = iot_schedule_create (scheduler, do_work3, NULL, IOT_MS_TO_NS (1), 0, 0, NULL);
iot_schedule_t *sched5 = iot_schedule_create (scheduler, do_work3, NULL, IOT_MS_TO_NS (1), 0, 0, NULL);
iot_schedule_t *sched6 = iot_schedule_create (scheduler, do_work3, NULL, IOT_MS_TO_NS (1), 0, 0, NULL);
CU_ASSERT (sched1 != NULL)
CU_ASSERT (sched2 != NULL)
CU_ASSERT (sched3 != NULL)
CU_ASSERT (sched4 != NULL)
CU_ASSERT (sched5 != NULL)
CU_ASSERT (sched6 != NULL)
CU_ASSERT (iot_schedule_add (scheduler, sched1))
CU_ASSERT (iot_schedule_add (scheduler, sched2))
CU_ASSERT (iot_schedule_add (scheduler, sched3))
CU_ASSERT (iot_schedule_add (scheduler, sched4))
CU_ASSERT (iot_schedule_add (scheduler, sched5))
CU_ASSERT (iot_schedule_add (scheduler, sched6))
iot_scheduler_start (scheduler);
sleep (1);
iot_schedule_delete (scheduler, sched3);
iot_scheduler_stop (scheduler);
CU_ASSERT (atomic_load (&sum_test) == 1u)
CU_ASSERT (atomic_load (&infinity_test) > 20u)
uint32_t temp = atomic_load (&infinity_test);
iot_scheduler_start (scheduler);
sleep (1);
CU_ASSERT (temp == atomic_load (&infinity_test))
iot_threadpool_free (pool);
iot_scheduler_free (scheduler);
}
static void cunit_scheduler_refcount (void)
{
iot_threadpool_t *pool = iot_threadpool_alloc (4, 0, NULL, logger);
iot_scheduler_t *scheduler = iot_scheduler_alloc (pool, logger);
iot_scheduler_add_ref (scheduler);
iot_scheduler_free (scheduler);
iot_scheduler_free (scheduler);
iot_scheduler_free (NULL);
iot_threadpool_free (pool);
}
static void cunit_scheduler_iot_scheduler_thread_pool (void)
{
iot_threadpool_t *pool = iot_threadpool_alloc (4, 0, NULL, logger);
iot_scheduler_t *scheduler = iot_scheduler_alloc (pool, logger);
assert (pool == iot_scheduler_thread_pool (scheduler));
iot_scheduler_free (scheduler);
iot_threadpool_free (pool);
}
static void cunit_scheduler_nrepeat (void)
{
iot_threadpool_t *pool = iot_threadpool_alloc (2, 0, NULL, logger);
iot_scheduler_t *scheduler = iot_scheduler_alloc (pool, logger);
CU_ASSERT (scheduler != NULL)
reset_counters ();
iot_schedule_t *sched1 = iot_schedule_create (scheduler, do_count, NULL, IOT_MS_TO_NS (100), 0, 5, NULL);
CU_ASSERT (iot_schedule_add (scheduler, sched1))
CU_ASSERT (iot_threadpool_start (pool))
CU_ASSERT (iot_scheduler_start (scheduler))
sleep (2);
iot_scheduler_stop (scheduler);
CU_ASSERT (atomic_load (&counter) == 5u)
iot_threadpool_free (pool);
iot_scheduler_free (scheduler);
}
static void cunit_scheduler_starttime (void)
{
iot_threadpool_t *pool = iot_threadpool_alloc (2, 0, NULL, logger);
iot_scheduler_t *scheduler = iot_scheduler_alloc (pool, logger);
CU_ASSERT (scheduler != NULL)
reset_counters ();
iot_schedule_t *sched1 = iot_schedule_create (scheduler, do_work4, NULL, IOT_MS_TO_NS (100), IOT_MS_TO_NS (100), 1, NULL);
CU_ASSERT (iot_schedule_add (scheduler, sched1))
CU_ASSERT (iot_threadpool_start (pool))
CU_ASSERT (iot_scheduler_start (scheduler))
sleep (2);
iot_scheduler_stop (scheduler);
CU_ASSERT (atomic_load (&sum_test) == 1)
iot_threadpool_free (pool);
iot_scheduler_free (scheduler);
}
static void cunit_scheduler_setpriority (void)
{
int prio_max = sched_get_priority_max (SCHED_FIFO);
int prio_min = sched_get_priority_min (SCHED_FIFO);
iot_threadpool_t *pool = iot_threadpool_alloc (2, 0, NULL, logger);
iot_scheduler_t *scheduler = iot_scheduler_alloc (pool, logger);
CU_ASSERT (scheduler != NULL)
reset_counters ();
iot_schedule_t *sched1 = iot_schedule_create (scheduler, do_count, NULL, IOT_MS_TO_NS (10), 0, 100, &prio_max);
CU_ASSERT (iot_schedule_add (scheduler, sched1))
iot_schedule_t *sched2 = iot_schedule_create (scheduler, do_work4, NULL, IOT_MS_TO_NS (1000), IOT_MS_TO_NS (1000), 5, &prio_min);
CU_ASSERT (iot_schedule_add (scheduler, sched2))
CU_ASSERT (iot_threadpool_start (pool))
CU_ASSERT (iot_scheduler_start (scheduler))
sleep (2);
iot_scheduler_stop (scheduler);
CU_ASSERT (atomic_load (&counter) == 100u)
CU_ASSERT (atomic_load (&sum_test) >= 1u)
iot_threadpool_free (pool);
iot_scheduler_free (scheduler);
}
extern void cunit_scheduler_test_init ()
{
CU_pSuite suite = CU_add_suite ("scheduler", suite_init, suite_clean);
CU_add_test (suite, "scheduler_start", cunit_scheduler_start);
CU_add_test (suite, "scheduler_stop", cunit_scheduler_stop);
CU_add_test (suite, "scheduler_create", cunit_scheduler_create);
CU_add_test (suite, "scheduler_remove", cunit_scheduler_remove);
CU_add_test (suite, "scheduler_delete", cunit_scheduler_delete);
CU_add_test (suite, "scheduler_refcount", cunit_scheduler_refcount);
CU_add_test (suite, "scheduler_nrepeat", cunit_scheduler_nrepeat);
CU_add_test (suite, "scheduler_starttime", cunit_scheduler_starttime);
CU_add_test (suite, "scheduler_setpriority", cunit_scheduler_setpriority);
CU_add_test (suite, "scheduler_iot_scheduler_thread_pool", cunit_scheduler_iot_scheduler_thread_pool);
}
|
C
|
/**
* Assignment 1 hy345 c shell
*
* @author csd3319
* @version 0.1 02/03/2018
*/
#include "funcs.h"
int main() {
pid_t bg[10];
pid_t pid;
pid_t tpid;
int status;
char** array;
char* command;
char* arg1;
char* arg2;
char* out;
char* in;
char* ena;
char* dyo;
char* tria;
char* tessera;
char* pente;
int flag1 = 0;
int metritis = 0;
int back = 0;
//ctrl_sq();
while(1) {
print_prompt();
command = parse();
char* temp = strdup(command);
char* temp_command = strdup(command);
arg2 = strchr(temp, '|');
out = strchr(temp, '>');
in = strchr(temp, '<');
while(temp_command) {
char* temp2 = strdup(temp_command);
char* dimitris;
dimitris = strtok( temp2, " ");
if (strcmp(dimitris, "exit\n") == 0)
{
return 1;
}else if (strcmp(dimitris, "cd") == 0) {
char* dir = strtok(NULL, "\n");
strcat(dir,"/");
int ret;
ret = chdir(dir);
break;
}else if (strcmp(dimitris, "fg\n") == 0) {
//printf("NAI MPIKA TEEE\n");
//tcsetpgrp(0,bg[0]);
kill(bg[0], SIGCONT);
temp_command = '\0';
}else{
}
dyo = strchr(temp_command, '>');
if (ena = strchr(temp_command, '|')){
//printf("*** has pipe ***\n");
int pipefd[2];
pid_t pid;
int count = 0;
char bin[100];
char** array;
char* lvalue = strsep(&temp_command, "|");
array = tokenize(lvalue);
strcpy(bin, array[0]); /* first command that the child must execute */
//printf("bin is -%s- \n", bin);
/* kalitera na balw strdup */
array[0] = bin;
while (array[count] != NULL) {
count++;
}
array[count] = (char*) NULL;
if (pipe(pipefd)==-1){
fprintf(stderr, "Pipe Failed" );
return 1;
}
pid = fork();
if (pid == -1){
perror("fork");
exit(EXIT_FAILURE);
}else if (pid == 0) {
/* child */
/* do redirections and close the wrong side of the pipe */
close(pipefd[0]); /* the other side of the pipe */
dup2(pipefd[1],1); /* automatically closes previous fd 1 */
close(pipefd[1]); /* cleanup */
execvp(bin,array);
/* return value from execl() can be ignored because if execl returns
* at all, the return value must have been -1, meaning error; and the
* reason for the error is stashed in errno */
perror("error on child execv in pipe state");
exit(1);
}else {
/* parent */
/*
* It is important that the last command in the pipeline is execd
* by the parent, because that is the process we want the shell to
* wait on. That is, the shell should not loop and print the next
* prompt, etc, until the LAST process in the pipeline terminates.
* Normally this will mean that the other ones have terminated as
* well, because otherwise their sides of the pipes won't be closed
* so the later-on processes will be waiting for more input still.
*/
/* do redirections and close the wrong side of the pipe */
pid = fork();
if(pid == 0) {
close(pipefd[1]); /* the other side of the pipe */
dup2(pipefd[0], 0); /* automatically closes previous fd 0 */
close(pipefd[0]); /* cleanup */
char* temp;
char* check = strchr(ena+2, '>');
if (check != NULL )
{
/***************************************************************************************** */
ena = ena + 2;
temp = strdup(strsep(&ena, ">"));
char** array = tokenize(temp);
char bin[100];
strcpy(bin,array[0]);
array[0] = strdup(bin);
int count = 0;
while (array[count] != NULL) {
count++;
}
array[count] = NULL;
strsep(&ena, " ");
char* rvalue = strdup(strsep(&ena, "\n"));
/*printf("ENA rvalue (%s)\n", rvalue);*/
int file = open(rvalue, O_CREAT | O_WRONLY);
if(file < 0) return 1;
/*Now we redirect standard output to the file using dup2 */
if(dup2(file,1) < 0) return 1;
execvp(bin,array);
/*fclose(fp); */
close(file);
exit(1);
}else{
/* paizei kata 99.9999% na min xreiazete xd :P*/
}
/*aplo pipe implementation*/
char** array = tokenize(ena+2);
char bin[100];
strcpy(bin,array[0]);
array[0] = strdup(bin);
int count = 0;
while (array[count] != NULL) {
/*printf("array = -%s-\n", array[count]);*/
count++;
}
array[count] = NULL;
execvp(bin,array);
exit(1);
}else{
close(pipefd[0]);
close(pipefd[1]);
waitpid(pid, &status, 0);
temp_command = '\0';
}
}
}else if(tria = strchr(temp_command, '<')){
//printf("*** has < ***\n");
if ((pid = fork()) == -1){
exit(EXIT_FAILURE);
perror("fork error");
}else if (pid == 0) {
int in, out;
int count = 0;
char param1[100];
char** array;
char* lvalue;
char* rvalue;
char temp[100];
char tempp[100];
const char s[3] = ">";
const char ss[3] = " ";
char* a = strdup(temp_command);
char b[100];
lvalue = strdup(strsep(&temp_command, "<"));
strcpy(temp,strtok(a+1, s));
strcpy(temp,strtok(a,"\n"));
strcpy(temp, strtok(temp+6, "\n"));
strcpy(temp, strtok(temp, " "));
if (strchr(temp_command, '>'))
{
strsep(&temp_command, ">");
flag1 = 1;
temp_command += 1;
temp_command = strsep(&temp_command, "\n");
}else{
flag1 = 0;
temp_command += 1;
rvalue = strdup(strsep(&temp_command, "\n"));
}
array = tokenize(lvalue);
//strcpy(param1,"/bin/");
strcpy(param1,array[0]);
array[0] = param1;
/*array = realloc(array, sizeof(char*)); */
while (array[count] != NULL) {
count++;
}
array[count] = NULL;
/* open input and output files */
in = open(temp, O_RDONLY);
if(in < 0) perror("ERROR open input file");
/* replace standard input with input file */
dup2(in, STDIN_FILENO);
if (flag1 == 1){
out = open(temp_command, O_WRONLY | O_TRUNC | O_CREAT, S_IRUSR | S_IRGRP | S_IWGRP | S_IWUSR);
if(out < 0) perror("ERROR open output file");
/*replace standard output with output file */
dup2(out, STDOUT_FILENO);
}
/*
FILE *fp;
fp = freopen(rvalue, "r", stdin);
execlp(param1, array[0], (char*)NULL
*/
execvp(param1, array);
close(in);
close(out);
/* fclose(fp); */
}else{
/* This is run by the parent. Wait for the child
to terminate. */
waitpid(pid, &status, 0);
temp_command = '\0';
}
}else if(dyo && dyo[1] != '>'){
//printf("*** has > ***\n");
if ((pid = fork()) == -1){
exit(EXIT_FAILURE);
perror("fork error");
}else if (pid == 0) {
int count = 0;
char param1[100];
char** array;
char* lvalue;
char* rvalue;
lvalue = strdup(strsep(&temp_command, ">"));
temp_command += 1; /* skipare to space meta to > */
rvalue = strdup(strsep(&temp_command, "\n"));
array = tokenize(lvalue);
//strcpy(param1,"/bin/");
strcpy(param1,array[0]);
array[0] = param1;
while (array[count] != NULL) {
count++;
}
array[count] = NULL;
count = 0;
/*
First, we're going to open a file
int file = open(rvalue, O_CREAT | O_WRONLY);
if(file < 0) return 1;
//Now we redirect standard output to the file using dup2
if(dup2(file,1) < 0) return 1;
*/
FILE *fp;
fp = freopen(rvalue, "w+", stdout);
execvp(param1, array);
perror("Return not expected. Must be an execv error.n");
fclose(fp);
}else{
/* This is run by the parent. Wait for the child
to terminate. */
temp_command = '\0';
waitpid(pid, &status, 0);
}
}else if(tessera = strchr(temp_command, '>')) {
//printf("*** has >> ***\n");
if ((pid = fork()) == -1){
exit(EXIT_FAILURE);
perror("fork error");
}else if (pid == 0) {
int count = 0;
char param1[100];
char** array;
char* lvalue;
char* rvalue;
lvalue = strdup(strsep(&temp_command, ">"));
temp_command +=2; /* skip ">space" */
rvalue = strdup(strsep(&temp_command, "\n"));
array = tokenize(lvalue);
strcpy(param1,"/bin/");
strcat(param1,array[0]);
array[0] = param1;
/* array = realloc(array, sizeof(char*)); */
while (array[count] != NULL) {
count++;
}
array[count] = NULL;
/*First, we're going to open a file */
FILE *fp;
fp = freopen(rvalue, "a+", stdout);
/*
int file = open(rvalue, O_APPEND| O_CREAT | O_WRONLY);
if(file < 0) return 1;
//Now we redirect standard output to the file using dup2
if(dup2(file,1) < 0) return 1;*/
execv(param1, array);
perror("Return not expected. Must be an execv error.n");
fclose(fp);
}else{
/* This is run by the parent. Wait for the child
to terminate. */
temp_command = '\0';
waitpid(pid, &status, 0);
}
}/*else if (pente = strchr(temp_command, '&')){
printf("*** has & ***\n");
}*/else {
char buff[200];
/*exw mia opoiadipote apli entoli me h xwris tis parametrous tis kai tin ektelw */
if (strchr(temp_command, '&') != NULL )
{
back = 1;
strcpy(buff, strtok(temp_command, "&"));
printf("BUFF without & -%s-\n", buff);
}else {
}//if &
char* param1 = strtok(buff, "\n");
/*printf("param1 (%s)", param1);
printf("temp_command (%s)", temp_command);*/
array = tokenize(temp_command);
if ((pid = fork()) == -1){
exit(EXIT_FAILURE);
perror("fork error");
}else if (pid == 0) {
int count = 0;
while (array[count] != NULL) {
count++;
}
//printf("1PGID %d\n", getpgrp());
setpgid(0,0); //puts the child in a new process group whose group ID is identical to the child’s PID
//setsid();
//printf("2PGID %d\n", getpgrp());
if (back == 1)
{
execvp(array[0], array);
perror("Return not expected. Must be an execvp error.n");
//exit(0);
}else{
execvp(array[0], array);
perror("Return not expected. Must be an execvp error.n");
}
}else{
/* This is run by the parent. Wait for the child
to terminate. */
if (back == 1)
{
//sleep(1);
bg[0] = pid;
/*The default action for SIGTSTP is to place a process in the stopped state,
where it remains until it is awakened by the receipt of a SIGCONT signal. */
kill(pid, SIGTSTP); //
//signal(SIGCHLD, SIG_IGN); /* ignore child */
back = 0;
temp_command = '\0';
//waitpid(pid, &status, WNOHANG);
}else{
temp_command = '\0';
waitpid(pid, &status, 0);
}
}
}
}/*end of while(temp_command)*/
}/*end of while*/
return 0;
}
|
C
|
/*
Given a string s, return the longest palindromic substring in s.
Time: O(n^2)
Space: O(1)
*/
char* longestPalindrome(char * s){
int pos=0;
int lenmax=1;
for (int i=0; s[i]!='\0'; i++){
int g=i, d=i;
while (g>=0 && s[d]!='\0' && s[g]==s[d]){
g-=1;
d+=1;
}
d--;
g++;
if (d-g>=lenmax){
lenmax=d-g+1;
pos=g;
}
g=i,d=i+1;
while (g>=0 && s[d]!='\0' && s[g]==s[d]){
g-=1;
d+=1;
}
d--;
g++;
if (d-g>=lenmax){
lenmax=d-g+1;
pos=g;
}
}
char* new_s = (char*)malloc(sizeof(char)*(lenmax+1));
new_s[lenmax]='\0';
for (int i=0; i<lenmax; i++){
new_s[i]=s[i+pos];
}
return new_s;
}
|
C
|
// Elabore uma função recursiva que calcule a sequência:
// 1 + 1/2 + 1/3 + 1/4 + ... + 1/n
// Pablo Cecilio 172050108
#include <stdio.h>
float FATORIAL(float s);
float SOMA(int n);
int main(void) {
float n;
printf("N= ");
scanf("%f", &n);
printf("Soma: %.2f\n", SOMA(n));
}
float FATORIAL(float s) {
if (s<=2) return s;
else return s*FATORIAL(s-1);
}
float SOMA(int n) {
float s=0;
if (n==1) return 1;
else {
s+=(SOMA(n-1) + (1.0/FATORIAL(n)));
return s;
}
}
|
C
|
#include<stdio.h>
#include<string.h>
int main()
{
int dia=0;
char mesNasci[25];
//Entrada de Dados
printf("Enter dia de nascinento: ");
scanf("%d", &dia);
printf("Enter the Mes Nascimento: ");
scanf("%s", &mesNasci);
//Teste e condição
if(mesNasci == "setembro")
{
printf("Primavera");
}
else if(mesNasci == "dezebro")
{
printf("Verão");
}
else if (mesNasci == "março")
{
printf("Outono");
}
else if(mesNasci == "junho")
{
printf("Inverno");
}
return 0;
}
|
C
|
/* ************************************************************************** */
/* LE - / */
/* / */
/* ai.c .:: .:/ . .:: */
/* +:+:+ +: +: +:+:+ */
/* By: angauber <[email protected]> +:+ +: +: +:+ */
/* #+# #+ #+ #+# */
/* Created: 2018/12/01 14:07:17 by angauber #+# ## ## #+# */
/* Updated: 2018/12/02 21:45:09 by angauber ### #+. /#+ ###.fr */
/* / */
/* / */
/* ************************************************************************** */
#include "../include/puissance4.h"
int call_check(char **str, int y, int x)
{
int pos;
pos = check_threat_line(str, y, x);
if (pos != -1)
{
put_coin(str, pos, y, 'X');
return (1);
}
pos = check_threat_column(str, y, x);
if (pos != -1)
{
put_coin(str, pos, y, 'X');
return (1);
}
pos = check_threat_diagonal(str, y, x);
if (pos != -1)
{
put_coin(str, pos, y, 'X');
return (1);
}
return (0);
}
int check_threat(char **str, int y, int x)
{
int pos;
int i;
int j;
i = -1;
while (++i < y)
{
j = -1;
while (++j < x)
{
if (str[i][j] != '.')
if (call_check(str, y, x) == 1)
return (1);
}
}
pos = check_strat(str, y, 0);
if (pos != -1)
{
put_coin(str, pos, y, 'X');
return (1);
}
return (0);
}
void solve(char **str, int x, int y, int ctr)
{
int pos;
pos = check_threat(str, y, x);
if (!pos)
{
if (ft_strchr(str[0], 'X') == NULL)
pos = x / 2;
else
{
pos = check_threat_line_trap(str, y);
if (pos == -1)
pos = rand() % x;
}
while (check_input(str, pos + 1, y) == 0 && give_win(str, pos, y) == 1)
{
pos = rand() % x;
ctr++;
if (ctr > 15)
break ;
}
if (ctr == 16)
while (check_input(str, pos + 1, y) == 0)
pos = rand() % x;
put_coin(str, pos, y, 'X');
}
}
|
C
|
/**
* @file memmanager.c
*
* @brief Memory Allocation for C
*
* @note Mentioned in Memory Allocation in C in Embedded Systems Programming, Aug. 89.
* https://www.embedded.com/memory-allocation-in-c/
*
* @note Original produced by Programming ARTS (8/18/88)
* Programmers: Les Aldridge, Travis I. Seay
*
* @note Updated to C89/C99
* Added doxygen documentation
* Name changed
* free -> MemFree
* malloc -> MemAlloc
* i_alloc -> MemInit
* All static variables are now initialized
* Add regions for allocation
*
* @note Header could be smaller for used blocks because the next pointer is only
* used for free blocks.
*
* @author Les Aldridge, Travis I. Seay (original version)
*
* @author Hans Schneebeli (updated version)
*/
#include <stdint.h>
#include "memmanager.h"
/**
* @brief NULL Pointer
*
* @note To avoid use of additional headers. This will be used on embedded systems
*/
///@{
#ifndef NULL
#define NULL (0)
#endif
///@}
/// Include stdio.h only for testing or debugging
#if defined(DEBUG) || defined(TEST)
#include <stdio.h>
#endif
/**
* @brief header structure for each block
*
* @note next points to the next free block, otherwise it is NULL
*
* @note Using bit fields. It will later be used in an embedded system
*
* @note Assumed unsigned it is 32 bits long
*/
typedef struct header {
union {
uint32_t word;
struct {
uint32_t used:1; ///< 1 bit for used/free flag
uint32_t region:2; ///< 2 bits for region
uint32_t size:29; ///< 29 bits for size (=512 MBytes)
};
};
union {
struct header *next; ///< Next free block
uint32_t area[1]; ///< Place marker
};
} HEADER;
/**
* @brief Region definition
*
* @note Definition of a heap area
*/
typedef struct region {
HEADER *start; ///< Start address of this heap
HEADER *end; ///< End address of this heap
HEADER *free; ///< Pointer to first free block (Free list)
int32_t memleft; ///< Free area in sizeof(HEADER) units
} REGION;
/**
* @brief Region definition
*
* @note Heap information loaded by MemInit
*
* @note To change the number of regions, the region field in HEADER must be changed too
*/
static REGION Regions[4] = {
{ .start = 0, .end = 0 },
{ .start = 0, .end = 0 },
{ .start = 0, .end = 0 },
{ .start = 0, .end = 0 }
};
/**
* @brief Add a region to the pool
*
* @note Area must be aligned to an uint32_t
*/
void
MemAddRegion( uint32_t region, void *area, uint32_t size) {
REGION *r;
r = &Regions[region];
// If already initialized, do nothing
if( r->start )
return;
r->start = area;
r->end = (HEADER *)((char *) area + size);
r->free = area;
r->free->next = NULL;
r->free->size = size/sizeof(HEADER)-1;
r->free->used = 0;
r->memleft = r->free->size;
}
/**
* @brief MemInit
*
* @note Initializes heap info
*
* @note There are two versions. A version without parameters, that uses
* symbols defined by the linker. Another one, with explicit parameters.
* The preprocessor symbol MEM_LINKERINIT chooses one
*/
#ifdef MEM_LINKERINIT
void MemInit(void) {
uint32_t size = (char *) &_heapend - char *) &_heapstart;
MemAddRegion( 0, &_heapstart, size);
}
#else
void MemInit(void *area, uint32_t size) {
MemAddRegion( 0, area, size);
}
#endif
/**
* @brief MemFree
*
* @note Return memory to free list.
* Where possible, make contiguous blocks of free memory.
* Assumes that 0 is not a valid address for allocation. Also,
* MemInit() must be called prior to using either MemFree() or MemAlloc();
*
* @note The Free List is kept in crescent order of address
*
* @note There are 4 case to consider:
*
* Previous | Next | Action
* ---------|--------|--------------------------
* Busy | Busy | Just add this block to free list
* Free | Busy | Add size to the previous block
* Busy | Free | Add size of the next block, add this block to list
* Free | Free | Add size of the next block and combine both to previous one
*
* Attention: Do not forget the remove the combined blocks from free list
*
* There are the limit cases to consider, start and end of area
*/
void MemFree(void *p) {
HEADER *block, *prev, *f, *old, *nxt;
REGION *r;
if( !p )
return;
f = (HEADER *)p - 1; /* Point to header of block being returned. */
#ifdef DEBUG
printf("Freeing element at %p with %d elements and area at %p\n",f,f->size,p);
#endif
// Already free
if( !f->used )
return;
// Get region used for allocation
r = &Regions[f->region];
r->memleft += f->size;
/*
* The Free list in kept in crescent order of address.
*
* Free-space head is higher up in memory than returnee. The returnee will
* be the new head
*/
if (f < r->free ) {
old = r->free; /* Old head */
r->free = f; /* New head */
/* The only possibility is that the old head points to a contiguos block*/
nxt = f + f->size; /* Right after new head */
if (nxt == old) { /* Old and new are contiguous. */
f->size += old->size; /* Combine them */
f->next = old->next; /* forming one block. */
} else {
f->next = old;
}
f->used = 0;
return;
}
/*
* Otherwise, current free-space head is lower in memory. Walk down
* free-space list looking for the block being returned. If the next pointer
* points past the block, make a new entry and link it. If next pointer plus
* its size points to the block, form one contiguous block.
*/
block = r->free;
prev = NULL;
while ( block && f > block ) {
if (block+block->size == f) {
block->size += f->size; /* They're contiguous. */
f = block + block->size; /* Form one block. */
if (f==block->next) {
/*
* The new, larger block is contiguous to the next free block,
* so form a larger block. There's no need to continue this checking
* since if the block following this free one
* were free, the two would already have been combined.
*/
block->size += f->size;
block->next = f->next;
block->used = 0;
}
return;
}
prev=block;
block=block->next;
}
/*
* The address of the block being returned is greater than one in
* the free queue (block) or the end of the queue was reached.
* If at end, just link to the end of the queue.
* Therefore, block is null or points to a block higher up in memory
* than the one being returned.
*/
prev->next = f; /* link to queue */
prev = f + f->size; /* right after space to free */
if (prev == block) { /* 'f' and 'block' are contiguous. */
f->size += block->size;
f->next = block->next; /* Form a larger, contiguous block. */
} else {
f->next = block;
}
f->used = 0;
return;
}
/**
* @brief MemAlloc
*
* @note Returns a pointer to an allocate memory block if found.
* Otherwise, returns NULL
*
* @note It uses a first fit algorithm
*
* @note Allocate the space requested plus space for the header of the block.
* Search the free-space queue for a block that's large enough.
* If block is larger than needed, break into two pieces
* and allocate the portion higher up in memory.
* Otherwise, just allocate the entire block.
*
*/
void *MemAlloc(uint32_t nb, uint32_t region) {
HEADER *block, *prev;
REGION *r;
uint32_t nelems;
/* Round to a multiple of sizeof(HEADER) */
nelems = (nb+sizeof(HEADER)-1)/sizeof(HEADER) + 1;
#ifdef DEBUG
printf("Allocating %u bytes (=%u elements)\n",nb,nelems);
#endif
r = &Regions[region];
for (prev=NULL,block=r->free; block!=NULL; block = block->next) {
/* First fit */
if ( nelems <= block->size ) { /* Big enough */
if ( nelems < block->size ) {
block->size -= nelems; /* Allocate tell end. */
block->used = 0;
block->next = NULL; /* Mark as occupied */
block += block->size;
block->size = nelems; /* block now == pointer to be alloc'd. */
block->used = 1;
} else {
if (prev==NULL) {
r->free = block->next;
} else {
prev->next = block->next;
}
}
r->memleft -= nelems;
/*
* Return a pointer past the header to the actual space requested.
*/
return((void *)(block+1));
}
}
/* Area not found */
return NULL;
}
/**
* @brief MemStats
*
* @note Delivers allocation information
*/
void MemStats( MEMSTATS *stats, uint32_t region ) {
REGION *r;
HEADER *p;
const uint32_t MAXBYTES = 1000000; /* to avoid the inclusion of other headers */
r = &Regions[region];
stats->memleft = r->memleft;
stats->freeblocks = 0;
stats->freebytes = 0;
stats->usedblocks = 0;
stats->usedbytes = 0;
stats->largestused = 0;
stats->smallestused= MAXBYTES;
stats->largestfree = 0;
stats->smallestfree= MAXBYTES;
if( !r->free )
return;
for(p=r->free;p;p=p->next) {
stats->freeblocks++;
stats->freebytes += p->size;
if( p->size > stats->largestfree )
stats->largestfree = p->size;
if( p->size < stats->smallestfree )
stats->smallestfree = p->size;
}
for(p=r->start;(p < r->end)&&(p->size>0);p=p+p->size) {
if( p->used ) {
stats->usedblocks++;
stats->usedbytes += p->size;
if( p->size > stats->largestused )
stats->largestused = p->size;
if( p->size < stats->smallestused )
stats->smallestused = p->size;
}
}
// To avoid "strange" numbers on output
if( stats->smallestfree == MAXBYTES )
stats->smallestfree = 0;
if( stats->smallestused == MAXBYTES )
stats->smallestused = 0;
// To report sizes in bytes
stats->freebytes *= sizeof(HEADER);
stats->usedbytes *= sizeof(HEADER);
stats->largestfree *= sizeof(HEADER);
stats->largestused *= sizeof(HEADER);
stats->smallestfree *= sizeof(HEADER);
stats->smallestused *= sizeof(HEADER);
stats->memleft *= sizeof(HEADER);
}
#if defined(DEBUG) || defined(TEST)
/**
* @brief Memory List
*
* @note List all memory blocks, including size and status
*
*/
void MemList(uint32_t region) {
uint32_t i;
HEADER *p;
REGION *r;
r = &Regions[region];
for(i=0,p=r->start;(p<r->end)&&(p->size>0);i++,p=p+p->size) {
printf("B%02u (%c): %u @%p (next=%p)\n",i,p->used?'U':'F',
(uint32_t) (p->size*sizeof(HEADER)),p,p->next);
}
putchar('\n');
}
#endif
//////////////////////// TEST ///////////////////////////////////////////////////////////////////
#ifdef TEST
#include <stdio.h>
void PrintStats(char *msg, MEMSTATS *stats ) {
puts(msg);
printf("Free blocks = %u\n",stats->freeblocks);
printf("Free bytes = %u\n",stats->freebytes);
printf("Smallest free = %u\n",stats->smallestfree);
printf("Largest free = %u\n",stats->largestfree);
printf("Used blocks = %u\n",stats->usedblocks);
printf("Used bytes = %u\n",stats->usedbytes);
printf("Smallest used = %u\n",stats->smallestused);
printf("Largest used = %u\n",stats->largestused);
printf("Memory left = %u\n",stats->memleft);
}
#define BUFFERSIZE 160
static uint32_t buffer[(BUFFERSIZE+sizeof(uint32_t)-1)/sizeof(uint32_t)];
int main(void) {
char *p1,*p2,*p3;
MEMSTATS stats;
printf("Size of block HEADER = %u\n",(uint32_t) sizeof(HEADER));
printf("Size of heap area = %u\n",(uint32_t) BUFFERSIZE);
MemInit(buffer,BUFFERSIZE);
MemStats(&stats,0);
PrintStats("Inicialized",&stats);
MemList(0);
p1 = MemAlloc(10,0);
MemStats(&stats,0);
PrintStats("Allocation #1",&stats);
MemList(0);
p2 = MemAlloc(10,0);
MemStats(&stats,0);
PrintStats("Allocation #2",&stats);
MemList(0);
p3 = MemAlloc(10,0);
MemStats(&stats,0);
PrintStats("Allocation #3",&stats);
MemList(0);
MemFree(p2);
MemStats(&stats,0);
PrintStats("Free #2",&stats);
MemList(0);
MemFree(p3);
MemStats(&stats,0);
PrintStats("Free #3",&stats);
MemList(0);
MemFree(p1);
MemStats(&stats,0);
PrintStats("Free #3",&stats);
MemList(0);
}
#endif
|
C
|
#include<stdio.h>
void main()
{
int num1;
printf("Check whether a number is negative, positive or zero.\n");
scanf("%d", &num1, printf("\nEnter a number: "));
if(num1 > 0)
{
printf("\n%d is positive number.\n", num1);
}
else if(num1 < 0)
{
printf("\n%d is negative number.\n", num1);
}
else if(num1 == 0)
{
printf("\nZero Detected!\n");
}
else
{
printf("Invalid Input!");
}
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <math.h>
#include <assert.h>
#define MIN(a,b) ((a)<(b)?(a):(b))
#include "jazlib/common.h"
#include "jazlib/gen_hash_reset.h"
#define GH_DEBUG
#define GEN_HASH_HASH_FUNC hash_djb2
#define GEN_HASH_KEY_CMP strcmp
// #define GEN_HASH_KEY_COPY
// #define GEN_HASH_KEY_FREE
#define GEN_HASH_VALUE_CMP strcmp
// #define GEN_HASH_VALUE_COPY
// #define GEN_HASH_VALUE_FREE
#include "jazlib/gen_hash.h"
GEN_HASH(hash, const char *, const char *);
typedef struct hash_test {
char key[16];
char value[16];
int in_table;
} hash_test_t;
#define COUNT 480000
#define PASSES 200
hash_test_t table[COUNT];
void random_string(char *target, int suffix) {
int len = (rand() % 8) + 1;
while (len--) *(target++) = (rand() % 26) + 'a';
sprintf(target, "%d", suffix);
}
void check(hash_t *hsh) {
unsigned long sz = 0;
int i;
for (i = 0; i < COUNT; i++) {
if (table[i].in_table) sz++;
const char *value;
int found = hash_read(hsh, table[i].key, &value);
if (found != table[i].in_table) {
printf("error (in_table=%d, ix=%d k=%s)\n", table[i].in_table, i, table[i].key);
} else if (found && (strcmp(value, table[i].value) != 0)) {
printf("cmp error\n");
}
}
if (sz != hsh->size) {
printf("size error (exp=%lu,rep=%lu)\n", sz, (unsigned long)hsh->size);
}
}
int main(int argc, char *argv[]) {
srand(time(NULL));
int i;
for (i = 0; i < COUNT; i++) {
random_string(table[i].key, i);
random_string(table[i].value, i);
table[i].in_table = 0;
if (((i+1)%50000) == 0) {
printf("%d random pairs generated\n", i+1);
}
}
hash_t hsh;
hash_init(&hsh);
unsigned long ops = 0;
int j;
for (j = 0; j < PASSES; j++) {
int ins = (j % 4 == 0) ? 0 : 1;
int range = (rand() % 30000) + 1;
ops += range;
int min = rand() % COUNT;
int max = MIN(COUNT, min + range);
printf("Pass %d/%d %s (%d) %d-%d\n", j+1, PASSES, ins ? "insert" : "delete", range, min, max);
GH_DEBUG_PRINT(&hsh);
if (ins) {
for (i = min; i < max; i++) {
gh_hash_t sz = hsh.size;
if (hash_put(&hsh, table[i].key, table[i].value)) {
if (!table[i].in_table) {
assert(sz + 1 == hsh.size);
} else if (sz != hsh.size) {
printf("expected=%lu actual=%lu\n", (unsigned long)sz, (unsigned long)hsh.size);
assert(0);
}
table[i].in_table = 1;
} else {
printf("put error\n");
exit(1);
}
}
} else {
for (i = min; i < max; i++) {
gh_hash_t sz = hsh.size;
if (hash_delete(&hsh, table[i].key)) {
assert(sz - 1 == hsh.size);
table[i].in_table = 0;
} else if (table[i].in_table) {
printf("delete error\n");
exit(1);
}
}
}
check(&hsh);
}
printf("ops: %lu\n", ops);
return 0;
}
|
C
|
#include "holberton.h"
#include <stdio.h>
#include <stdlib.h>
/**
* str_concat - function to concatenated 2 string
* @s1: string 1
* @s2: string 2
* Return: string concatenated
**/
char *str_concat(char *s1, char *s2)
{
unsigned int a, b, c, d;
char *conc;
if (s1 == NULL)
{
s1 = "";
}
if (s2 == NULL)
{
s2 = "";
}
for (a = 0; s1[a] != '\0'; a++)
;
for (b = 0; s2[b] != '\0'; b++)
;
conc = malloc((a + 1) + (b));
if (conc == NULL)
{
return (NULL);
}
for (c = 0; s1[c] != '\0'; c++)
{
conc[c] = s1[c];
}
for (d = 0; s2[d] != '\0'; d++)
{
conc[c + d] = s2[d];
}
return (conc);
}
|
C
|
#include <func.h>
int main(int argc,char* argv[])
{
printf("真实用户ID:%d\n真实组ID:%d\n有效用户ID:%d\n有效组ID:%d\n", \
getuid(),getgid(),geteuid(),getegid());
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
#include <unistd.h>
#include <sys/stat.h>
char memFrobByte (const char current)
{
return (current ^ 42);
}
int frobcmp (char const* first, char const* second)
{
while (1)
{
//Null bytes need to be skipped but are accepted as valid
while (*first == '\0')
first++;
while (*second == '\0')
second++;
if (*first == ' ' && *second == ' ')
// Both words ended, must be equal hence return 0
return 0;
if (*first == ' ' || memFrobByte(*first) < memFrobByte (*second))
return -1;
if (*second == ' ' || memFrobByte(*first) > memFrobByte(*second))
return 1;
first++; second++;
}
}
int universalfrobcmp(const void* wordA, const void* wordB)
{
//Typecast pointers for the qsort function
const char* word1 = *(const char**)wordA;
const char* word2 = *(const char**)wordB;
return frobcmp(word1, word2);
}
int main (int argc, char** argv)
{
//Default is set to 0
int flag_optf = 0;
if (argc > 2)
{
fprintf(stderr, "Too many options");
exit(1);
}
//Pointer to the first element of a string
char* currentWord = NULL;
//Pointer to multiple string pointers like the one above
char** text = NULL;
const char* options = argv[1];
const char* option_f = "-f";
if (argc == 2 && strcmp (options, option_f) != 0)
{
fprintf(stderr, "Only option -f allowed");
exit(1);
}
else if (argc == 2 && strcmp(options, option_f) == 0)
{
flag_optf = 1;
}
struct stat data;
if (fstat(0, &data) < 0)
{
fprintf(stderr, "Error in fstat.");
exit(1);
}
char* buffer;
int counter = 0;
int maxSize = 0;
if (S_ISREG(data.st_mode))
{
buffer = (char*)malloc(data.st_size * sizeof(char));
if (buffer == NULL)
{
fprintf(stderr, "Memory allocation error");
exit(1);
}
if (read(0, buffer, data.st_size) < 0)
{
fprintf(stderr, "Read error");
exit(1);
}
maxSize = data.st_size;
}
int numChars = 0;
int numWords = 0;
currentWord = (char*) malloc (sizeof(char));
if (currentWord == NULL)
{
//Memory not allocated successfully hence program must exit indicating
//this error
fprintf(stderr, "memory allocation unsuccessful. exiting \n");
exit (1);
}
currentWord[numChars] = getchar();
if (ferror(stdin))
{
}
ssize_t IOStatus;
if (counter >= maxSize)
{
IOStatus = read(0, (currentWord), 1);
if (IOStatus < 0)
{
//Exit program
fprintf(stderr, "I/O error. exiting \n");
free(currentWord);
exit(1);
}
}
else
{
currentWord[numChars] = buffer[counter++];
IOStatus = 1;
}
while (IOStatus > 0)
{
//next character
char nextChar;
if (counter >= maxSize)
{
IOStatus = read(0, &(nextChar), 1);
if (IOStatus < 0)
{
//Exit program
fprintf(stderr, "I/O error. exiting \n");
free(currentWord);
for (int i = 0; i < numWords; i++)
free(text[i]);
free(text);
exit(1);
}
}
else
{
nextChar = buffer[counter++];
}
if (currentWord[numChars] == ' ') //New word starting
{
//Allocate memory for numWords + 1 for the new word
char** temp_ptr = realloc (text, (numWords + 1) * sizeof(char*));
if (temp_ptr == NULL)
{
//Memory allocation unsuccesful
//Exit program
fprintf(stderr,"memory allocation unsuccessful. exiting \n");
free(currentWord);
for (int i = 0; i < numWords; i++)
free(text[i]);
free(text);
exit(1);
}
text = temp_ptr;
text[numWords] = currentWord;
numWords++;
numChars = -1; //So that later ++ makes it 0 again
currentWord = (char*) malloc (sizeof(char));
if (IOStatus == 0)
//Execution completed, break out of loop and exit normally
break;
while (nextChar == ' ')
{
if (counter >= maxSize)
{
IOStatus = read(0, &(nextChar), 1);
if (IOStatus < 0)
{
//Exit program
fprintf(stderr, "I/O error. exiting \n");
free(currentWord);
for (int i = 0; i < numWords; i++)
free(text[i]);
free(text);
exit(1);
}
}
else
{
nextChar = buffer[counter++];
}
}
}
else if (IOStatus == 0)
{
nextChar = ' ';
IOStatus = 1;
}
numChars++;
char* temp_str_ptr = realloc (currentWord, (numChars + 1) * sizeof(char));
if (temp_str_ptr == NULL)
{
//Memory allocation unsuccesful
//Exit program
fprintf(stderr,"memory allocation unsuccessful. exiting \n");
free(currentWord);
for (int i = 0; i < numWords; i++)
free(text[i]);
free(text);
exit(1);
}
currentWord = temp_str_ptr;
currentWord[numChars] = nextChar;
}
qsort(text, numWords, sizeof(char*), universalfrobcmp);
//Print sorted list
for (size_t i = 0; i < numWords; i++)
{
for (size_t j = 0; text[i][j] != ' '; j++)
write(1, &text[i][j], 1);
write(1, " ", 1);
}
//Free all memory
for (size_t i = 0; i < numWords; i++)
free(text[i]);
free(text);
free(currentWord);
return 0;
}
|
C
|
#include <unistd.h>
#include "42sh.h"
void pipe_exit(t_tree *tree, t_param *param)
{
static int exit_value = 1;
exit_value = exit_value ? g_last_exit : 0;
if (param == tree->param->prev)
{
g_last_exit = exit_value;
exit_value = 1;
}
}
int start_pipe(int pipe_fd[2][2], int *k, t_data *data)
{
*k = 1;
data->pipe = 1;
if (pipe(pipe_fd[0]) == -1
|| dup2(pipe_fd[0][1], 1) == -1)
return (ft_error("fail pipe / dup2"));
return (1);
}
int end_pipe(int pipe_fd[2][2], int *k, t_data *data)
{
data->pipe = 0;
if (*k == 1)
{
if (dup2(pipe_fd[0][0], 0) == -1)
return (ft_error("fail dup2"));
close(pipe_fd[0][1]);
if (pipe_fd[1][0] != -1)
close(pipe_fd[1][0]);
}
else
{
if (dup2(pipe_fd[1][0], 0) == -1)
return (ft_error("fail dup2"));
close(pipe_fd[1][1]);
close(pipe_fd[0][0]);
}
*k *= -1;
return (1);
}
int mid_pipe(int pipe_fd[2][2], int *k, t_data *data)
{
data->pipe = 1;
if (*k == 1)
{
if (pipe_fd[1][0] != -1)
close(pipe_fd[1][0]);
if (pipe(pipe_fd[1]) == -1
|| dup2(pipe_fd[1][1], 1) == -1
|| dup2(pipe_fd[0][0], 0) == -1)
return (ft_error("fail pipe / dup"));
close(pipe_fd[0][1]);
}
else
{
close(pipe_fd[0][0]);
if (pipe(pipe_fd[0]) == -1
|| dup2(pipe_fd[0][1], 1) == -1
|| dup2(pipe_fd[1][0], 0) == -1)
return (ft_error("fail pipe / dup"));
close(pipe_fd[1][1]);
}
*k *= -1;
return (1);
}
|
C
|
#include <stdio.h>
int main(int argc, char const *argv[]) {
double data[4] = {5.0,-2.0,2.0,0.0};
data[1] *= 2.0;
printf("%lf\n", --data[1]);
typedef struct matrix {
size_t m;
size_t n;
double **A;
} matrix_t;
matrix_t mat_arr[10];
(mat_arr+1)->m = 4;
for (size_t i = 0; i < 10; i++) {
printf("%lu\n", (mat_arr+i)->m);
}
return 0;
}
|
C
|
#include "dog.h"
#include <stdio.h>
#include <stdlib.h>
int _strlen(char *s);
char *_strcpy(char *dest, char *src);
/**
* new_dog - function that creates a new dog.
* @name: name of the dog
* @age: age of the dog
* @owner: owner of the dog
* Return: pointer to the new dog
*/
dog_t *new_dog(char *name, float age, char *owner)
{
char *store_name, *store_owner;
dog_t *new_dog;
store_name = malloc(sizeof(char) * (_strlen(name) + 1));/*safe memory space for name*/
if (store_name == NULL)
return (NULL);
store_owner = malloc(sizeof(char) * (_strlen(owner) + 1));/*safe memory space for owner*/
if (store_owner == NULL)
{
free(store_name);/* free space of name because it has been already asigned*/
return (NULL);
}
new_dog = malloc(sizeof(dog_t));/*safe memory for the whole structure*/
if (new_dog == NULL)/* if there is not space for the structure we free name and owner storage*/
{
free(store_name);
free(store_owner);
return (NULL);
}
_strcpy(store_name, name);
_strcpy(store_owner, owner);
new_dog->name = store_name;
new_dog->owner = store_owner;
new_dog->age = age;
return (new_dog);
}
/**
* _strlen - returns the length of a string.
* @s: pointer parameter
* Return: length of a string.
*/
int _strlen(char *s)
{
int i = 0;
while (*(s + i) != '\0')
{
i++;
}
return (i);
}
/**
* _strcpy - copies string from a pointer to a array of chars.
* @dest: Array destination
* @src: string parameter
* Return: cahr
*/
char *_strcpy(char *dest, char *src)
{
int i = 0;
while (*(src + i) != '\0')
{
*(dest + i) = *(src + i);
i++;
}
if (*(src + i) == '\0')
{
*(dest + i) = *(src + i);
}
return (dest);
}
|
C
|
#include <stdio.h>
int main(){
int i = 10,j=0;
while(i>0){
j+=i;
i--;
}
printf("the sum of first 10 natural numbers is : %d", j);
return 0;
}
|
C
|
/*
** SCCS ID: @(#)cio.h 2.2 3/10/20
**
** File: cio.h
**
** Author: K. Reek
**
** Contributor:
**
** Based on: c_io.c 1.13 (Ken Reek, Jon Coles, Warren R. Carithers)
**
** Description: Declarations and descriptions of console I/O routines
**
** These routines provide a rudimentary capability for printing to
** the screen and reading from the keyboard.
**
** Screen output:
** There are two families of functions. The first provides a window
** that behaves in the usual manner: writes extending beyond the right
** edge of the window wrap around to the next line, the top line
** scrolls off the window to make room for new lines at the bottom.
** However, you may choose what part of the screen contains this
** scrolling window. This allows you to print some text at fixed
** locations on the screen while the rest of the screen scrolls.
**
** The second family allows for printing at fixed locations on the
** screen. No scrolling or line wrapping are done for these functions.
** It is not intended that these functions be used to write in the
** scrolling area of the screen.
**
** In both sets of functions, the (x,y) coordinates are interpreted
** as (column,row), with the upper left corner of the screen being
** (0,0) and the lower right corner being (79,24).
**
** The printf provided in both sets of functions has the same
** conversion capabilities. Format codes are of the form:
**
** %-0WC
**
** where "-", "0", and "W" are all optional:
** "-" is the left-adjust flag (default is right-adjust)
** "0" is the zero-fill flag (default is space-fill)
** "W" is a number specifying the minimum field width (default: 1 )
** and "C" is the conversion type, which must be one of these:
** "c" print a single character
** "s" print a null-terminated string
** "d" print an integer as a decimal value
** "x" print an integer as a hexadecimal value
** "o" print an integer as a octal value
**
** Keyboard input:
** Two functions are provided: getting a single character and getting
** a newline-terminated line. A third function returns a count of
** the number of characters available for immediate reading.
** No conversions are provided (yet).
*/
#ifndef _CIO_H_
#define _CIO_H_
// EOT indicator (control-D)
#define EOT '\04'
/*
** Name: __cio_init
**
** Description: Initializes the I/O routines. This is called by the
** standalone loader so you need not call it.
** Argument: pointer to an input notification function, or NULL
*/
void __cio_init( void (*notify)(int) );
/*****************************************************************************
**
** SCROLLING OUTPUT ROUTINES
**
** Each operation begins at the current cursor position and advances
** it. If a newline is output, the reminder of that line is cleared.
** Output extending past the end of the line is wrapped. If the
** cursor is moved below the scrolling region's bottom edge, scrolling
** is delayed until the next output is produced.
*/
/*
** Name: __cio_setscroll
**
** Description: This sets the scrolling region to be the area defined by
** the arguments. The remainder of the screen does not scroll
** and may be used to display data you do not want to move.
** By default, the scrolling region is the entire screen .
** Arguments: coordinates of upper-left and lower-right corners of region
*/
void __cio_setscroll( unsigned int min_x, unsigned int min_y,
unsigned int max_x, unsigned int max_y );
/*
** Name: __cio_moveto
**
** Description: Moves the cursor to the specified position. (0,0) indicates
** the upper left corner of the scrolling region. Subsequent
** output will begin at the cursor position.
** Arguments: desired cursor position
*/
void __cio_moveto( unsigned int x, unsigned int y );
/*
** Name: __cio_putchar
**
** Description: Prints a single character.
** Arguments: the character to be printed
*/
void __cio_putchar( unsigned int c );
/*
** Name: __cio_puts
**
** Description: Prints the characters in the string up to but not including
** the terminating null byte.
** Arguments: pointer to a null-terminated string
*/
void __cio_puts( char *str );
/*
** Name: __cio_write
**
** Description: Prints "length" characters from the buffer.
** Arguments: Pointer to a character buffer, and the size of the buffer
*/
void __cio_write( const char *buf, int length );
/*
** Name: __cio_printf
**
** Description: Limited form of printf (see the beginning of this file for
** a list of what is implemented).
** Arguments: printf-style format and optional values
*/
void __cio_printf( char *fmt, ... );
/*
** Name: __cio_scroll
**
** Description: Scroll the scrolling region up by the given number of lines.
** The output routines scroll automatically so normally you
** do not need to call this routine yourself.
** Arguments: number of lines
*/
void __cio_scroll( unsigned int lines );
/*
** Name: __cio_clearscroll
**
** Description: Clears the entire scrolling region to blank spaces, and
** moves the cursor to (0,0).
*/
void __cio_clearscroll( void );
/*****************************************************************************
**
** NON-SCROLLING OUTPUT ROUTINES
**
** Coordinates are relative to the entire screen: (0,0) is the upper
** left corner. There is no line wrap or scrolling.
*/
/*
** Name: __cio_putchar_at
**
** Description: Prints the given character. If a newline is printed,
** the rest of the line is cleared. If this happens to the
** left of the scrolling region, the clearing stops when the
** region is reached. If this happens inside the scrolling
** region, the clearing stops when the edge of the region
** is reached.
** Arguments: coordinates, the character to be printed
*/
void __cio_putchar_at( unsigned int x, unsigned int y, unsigned int c );
/*
** Name: __cio_puts_at
**
** Description: Prints the given string. __cio_putchar_at is used to print
** the individual characters; see that description for details.
** Arguments: coordinates, null-terminated string to be printed
*/
void __cio_puts_at( unsigned int x, unsigned int y, char *str );
/*
** Name: __cio_printf_at
**
** Description: Limited form of printf (see the beginning of this file for
** a list of what is implemented).
** Arguments: coordinates, printf-style format, optional values
*/
void __cio_printf_at( unsigned int x, unsigned int y, char *fmt, ... );
/*
** Name: __cio_clearscreen
**
** Description: This function clears the entire screen, including the
** scrolling region.
*/
void __cio_clearscreen( void );
/*****************************************************************************
**
** INPUT ROUTINES
**
** When interrupts are enabled, a keyboard ISR collects keystrokes
** and saves them until the program calls for them. If the input
** queue fills, additional characters are silently discarded.
** When interrupts are not enabled, keystrokes made when no input
** routines have been ** called are lost. This can cause errors in
** the input translation because the states of the Shift and Ctrl keys
** may not be tracked accurately. If interrupts are disabled, the user
** is advised to refrain from typing anything except when the program is
** waiting for input.
*/
/*
** Name: __cio_getchar
**
** Description: If the character is not immediately available, the function
** waits until the character arrives.
** Returns: The next character typed on the keyboard.
*/
int __cio_getchar( void );
/*
** Name: __cio_gets
**
** Description: This function reads a newline-terminated line from the
** keyboard. __cio_getchar is used to obtain the characters;
** see that description for more details. The function
** returns when:
** a newline is entered (this is stored in the buffer)
** ctrl-D is entered (not stored in the buffer)
** the buffer becomes full.
** The buffer is null-terminated in all cases.
** Arguments: pointer to input buffer, size of buffer
** Returns: count of the number of characters read
*/
int __cio_gets( char *buffer, unsigned int size );
/*
** Name: __cio_input_queue
**
** Description: This function lets the program determine whether there
** is input available. This determines whether or not a call
** to __cio_getchar would block.
** Returns: number of characters in the input queue
*/
int __cio_input_queue( void );
#endif
|
C
|
/* 二叉搜索树 */
/* 1、二叉搜索树的查找操作Find(尾递归法) */
Position Find(ElementType X,BinTree BST){
if(!BST){
return NULL; //查找失败
}
if(X>BST->Data){
return Find(X,BST->Right); //在右子树中继续查找
}
else if(X<BST->Data){
return Find(X,BST->Left); //在左子树中继续查找
else //X == BST->Data
return BST; //查找成功,返回结点的找到结点的地址
}
}
/*2、二叉搜索树的查找操作ItemFind(迭代法) */
/* 非递归函数的执行效率高,查找效率取决于树的高度 */
Position itemFind(ElementType X,BinTree BST){
while(BST){
if(X>BST->Data){
BST = BST->Right; //向右子树中移动,继续查找
}
else if(X<BST->Data){
BST = BST->Left; //向左子树移动,继续查找
}
else{ //X == BST->Data
return BST; //查找成功,返回结点的找到结点的地址
}
return NULL; //查找失败
}
}
/* 3、查找最大元素和最小元素 */
Position FindMax(BinTree BST){
if(BST){
while(BST->Right){
BST = BST->Right; //沿右分支继续查找,直到最右叶节点
}
return BST;
}
}
Position FindMin(BinTree BST){
if(BST){
while(BST->Left){
BST = BST->Left; //沿左分支继续查找,直到最左叶节点
}
return BST;
}
}
/* 插入 */
BinTree Insert( BinTree BST, ElementType X )
{
if( !BST ){ /* 若原树为空,生成并返回一个结点的二叉搜索树 */
BST = (BinTree)malloc(sizeof(struct TNode));
BST->Data = X;
BST->Left = BST->Right = NULL;
}
else { /* 开始找要插入元素的位置 */
if( X < BST->Data )
BST->Left = Insert( BST->Left, X ); /*递归插入左子树*/
else if( X > BST->Data )
BST->Right = Insert( BST->Right, X ); /*递归插入右子树*/
/* else X已经存在,什么都不做 */
}
return BST;
}
/* 删除 */
BinTree Delete( BinTree BST, ElementType X )
{
Position Tmp;
if( !BST )
printf("要删除的元素未找到");
else {
if( X < BST->Data )
BST->Left = Delete( BST->Left, X ); /* 从左子树递归删除 */
else if( X > BST->Data )
BST->Right = Delete( BST->Right, X ); /* 从右子树递归删除 */
else { /* BST就是要删除的结点 */
/* 如果被删除结点有左右两个子结点 */
if( BST->Left && BST->Right ) {
/* 从右子树中找最小的元素填充删除结点 */
Tmp = FindMin( BST->Right );
BST->Data = Tmp->Data;
/* 从右子树中删除最小元素 */
BST->Right = Delete( BST->Right, BST->Data );
}
else { /* 被删除结点有一个或无子结点 */
Tmp = BST;
if( !BST->Left ) /* 只有右孩子或无子结点 */
BST = BST->Right;
else /* 只有左孩子 */
BST = BST->Left;
free( Tmp );
}
}
}
return BST;
}
|
C
|
/** \brief mostrar menu
*
* \param [] char recibe un mensaje
* \return int retorna una opcion
*
*/
int menu(char []);
/** \brief pide el ingreso de un dato.
*
* \param [] char recibe un mensaje para mostrar
* \param [] char recibe un dato para guardar
* \return void sin nada a retornar
*
*/
void getString(char [], char []);
/** \brief pide ingresar un dato alfabetico y lo valida
*
* \param [] char recibe un mensaje
* \param [] char recibe un dato para guardar
* \return void sin nada a retornar
*
*/
void getSoloLetras(char [], char []);
/** \brief pide un numero entero y lo valida
*
* \param [] char recibe un mensaje
* \return int retorna un numero ingresado y lo convierte en un entero
*
*/
int getSoloEnteros(char []);
/** \brief pide al usuario el ingreso de un numero flotante (sin signo), realizando la validacion correspondiente
*
* \param [] char recibe el mensaje a mostrar.
* \return float retorna un numero ingresado y lo convierte en un flotante
*
*/
float getSoloFlotantes(char []);
|
C
|
// 17 june 2014
#include "simplesale.h"
#include <sqlite3.h>
#include "dbschema.h"
// files:
// - accounts: [ { "name": name, "password": [ bytes ] }, ... ]
// - items: name\nprice\nname\nprice\n...
// - orders: concatenation of { "time": unixtime, "customer": customerName, "amountPaid": price, "items": items }
#define DBFILE "db.sqlite3"
static sqlite3 *db;
#define ACCOUNTSNAME "accounts"
#define ITEMSNAME "items"
#define ORDERSNAME "orders"
#define SQLERR (sqlite3_errmsg(db))
void initDB(void)
{
int err;
int i;
err = sqlite3_open_v2(DBFILE, &db, SQLITE_OPEN_READWRITE, NULL);
if (err != SQLITE_OK) { // may not exist; try creating
int i;
err = sqlite3_open_v2(DBFILE, &db, SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, NULL);
if (err != SQLITE_OK) // real error
g_error("error opening database: %s", SQLERR);
// needs creation
for (i = 0; i < NVER; i++) {
const char *p;
const char *nextp;
p = schemas[i];
nextp = p;
while (nextp != NULL && *nextp != '\0') {
sqlite3_stmt *s;
p = nextp;
err = sqlite3_prepare(db, p, -1, &s, &nextp);
if (err != SQLITE_OK)
g_error("error preparing database initialization statement: %s", SQLERR);
err = sqlite3_step(s);
if (err != SQLITE_DONE)
g_error("error executing database initialization statement: %s", SQLERR);
err = sqlite3_finalize(s);
if (err != SQLITE_OK)
g_error("error finalizing database initialization statement: %s", SQLERR);
}
}
}
for (i = 0; stmts[i].query != NULL; i++) {
err = sqlite3_prepare(db, stmts[i].query, -1, &stmts[i].stmt, NULL);
if (err != SQLITE_OK)
g_error("error preparing %s statement: %s", stmts[i].query, SQLERR);
}
}
void endDB(void)
{
int err;
int i;
for (i = 0; stmts[i].query != NULL; i++) {
err = sqlite3_finalize(stmts[i].stmt);
if (err != SQLITE_OK)
g_error("error finalizing %s statement: %s", stmts[i].query, SQLERR);
}
err = sqlite3_close(db);
if (err != SQLITE_OK)
g_error("error closing database: %s\n", SQLERR);
}
// TRUE if a row is present, FALSE if not (that is, query done)
static gboolean run(int i)
{
int err;
err = sqlite3_step(stmts[i].stmt);
if (err == SQLITE_ROW)
return TRUE;
if (err != SQLITE_DONE)
g_error("error executing %s statement: %s", stmts[i].query, SQLERR);
return FALSE;
}
static void reset(int i)
{
int err;
err = sqlite3_reset(stmts[i].stmt);
if (err != SQLITE_OK)
g_error("error resetting %s statement for next execution: %s", stmts[i].query, SQLERR);
}
static void bindBlob(int i, int arg, const void *blob, int n, void (*f)(void *))
{
int err;
err = sqlite3_bind_blob(stmts[i].stmt, arg, blob, n, f);
if (err != SQLITE_OK)
g_error("error binding blob argument %d of %s statement: %s", arg, stmts[i].query, SQLERR);
}
static void bindInt(int i, int arg, int n)
{
int err;
err = sqlite3_bind_int(stmts[i].stmt, arg, n);
if (err != SQLITE_OK)
g_error("error binding int argument %d of %s statement: %s", arg, stmts[i].query, SQLERR);
}
static void bindText(int i, int arg, const char *s, void (*f)(void *))
{
int err;
err = sqlite3_bind_text(stmts[i].stmt, arg, s, -1, f);
if (err != SQLITE_OK)
g_error("error binding text argument %d of %s statement: %s", arg, stmts[i].query, SQLERR);
}
static const void *blob(int i, int col)
{
return sqlite3_column_blob(stmts[i].stmt, col);
}
static int blobsize(int i, int col)
{
return sqlite3_column_bytes(stmts[i].stmt, col);
}
static int sqlint(int i, int col)
{
return sqlite3_column_int(stmts[i].stmt, col);
}
void *dbGetSetting(const char *setting, int *len)
{
void *out;
int size;
run(qBegin);
reset(qBegin);
bindText(qGetSetting, 1, setting, SQLITE_TRANSIENT);
run(qGetSetting);
size = blobsize(qGetSetting, 0);
out = g_malloc0(size);
memcpy(out, blob(qGetSetting, 0), size);
if (len != NULL)
*len = size;
reset(qGetSetting);
run(qCommit);
reset(qCommit);
return out;
}
void dbSetSetting(const char *setting, void *in, int size)
{
run(qBegin);
reset(qBegin);
bindText(qSetSetting, 1, setting, SQLITE_TRANSIENT);
bindBlob(qSetSetting, 2, in, size, SQLITE_TRANSIENT);
run(qSetSetting);
reset(qSetSetting);
run(qCommit);
reset(qCommit);
}
struct dbIn {
};
static dbIn *newdbIn(void)
{
return (dbIn *) g_malloc0(sizeof (dbIn));
}
dbIn *dbInOpenItems(void)
{
run(qBegin);
reset(qBegin);
return newdbIn();
}
dbIn *dbInOpenAccounts(void)
{
run(qBegin);
reset(qBegin);
return newdbIn();
}
gboolean dbInReadItem(dbIn *i, char **name, Price *price)
{
USED(i);
int n;
uint8_t pricebytes[8];
if (run(qGetItems) == FALSE) {
reset(qGetItems);
return FALSE;
}
n = blobsize(qGetItems, 0);
*name = (char *) g_malloc0((n + 1) * sizeof (char));
memcpy(*name, blob(qGetItems, 0), n);
memcpy(pricebytes, blob(qGetItems, 1), 8);
*price = priceFromBytes(pricebytes);
return TRUE;
}
gboolean dbInReadAccount(dbIn *i, char **name, char **password)
{
USED(i);
int n;
if (run(qGetAccounts) == FALSE) {
reset(qGetAccounts);
return FALSE;
}
n = blobsize(qGetAccounts, 0);
*name = (char *) g_malloc0((n + 1) * sizeof (char));
memcpy(*name, blob(qGetAccounts, 0), n);
n = blobsize(qGetAccounts, 1);
*password = (char *) g_malloc0((n + 1) * sizeof (char));
memcpy(*password, blob(qGetAccounts, 1), n);
return TRUE;
}
void dbInCommitAndFree(dbIn *i)
{
run(qCommit);
reset(qCommit);
g_free(i);
}
struct dbOut {
int append;
int count;
int cur;
};
static dbOut *newdbOut(void)
{
return (dbOut *) g_malloc0(sizeof (dbOut));
}
dbOut *dbOutOpenAndResetItems(void)
{
dbOut *o;
run(qBegin);
reset(qBegin);
run(qClearItems);
reset(qClearItems);
o = newdbOut();
o->append = qAppendItem;
return o;
}
dbOut *dbOutOpenForWritingAccounts(void)
{
dbOut *o;
run(qBegin);
reset(qBegin);
o = newdbOut();
run(qGetAccountCount);
o->count = sqlint(qGetAccountCount, 0);
reset(qGetAccountCount);
o->cur = 0;
return o;
}
static gboolean writeItem(GtkTreeModel *model, GtkTreePath *path, GtkTreeIter *iter, gpointer data)
{
USED(path);
dbOut *o = (dbOut *) data;
char *name;
Price price;
uint8_t pricebytes[8];
gtk_tree_model_get(model, iter, 0, &name, 1, &price, -1);
bindBlob(o->append, 1, name, strlen(name), g_free);
// the above calls g_free() already
priceToBytes(price, pricebytes);
bindBlob(o->append, 2, pricebytes, 8, SQLITE_TRANSIENT);
run(o->append);
reset(o->append);
return FALSE;
}
// for both items and orders
void dbOutWriteItemModel(GtkTreeModel *model, dbOut *o)
{
gtk_tree_model_foreach(model, writeItem, o);
}
static gboolean writeAccount(GtkTreeModel *model, GtkTreePath *path, GtkTreeIter *iter, gpointer data)
{
USED(path);
dbOut *o = (dbOut *) data;
char *name, *password;
gtk_tree_model_get(model, iter, 0, &name, 1, &password, -1);
if (o->cur < o->count) {
bindBlob(qChangeAccountInfo, 1, name, strlen(name), SQLITE_TRANSIENT);
bindBlob(qChangeAccountInfo, 2, password, strlen(password), SQLITE_TRANSIENT);
bindInt(qChangeAccountInfo, 3, o->cur + 1); // rowid starts with 1
run(qChangeAccountInfo);
reset(qChangeAccountInfo);
} else {
bindBlob(qAddAccount, 1, name, strlen(name), SQLITE_TRANSIENT);
bindBlob(qAddAccount, 2, password, strlen(password), SQLITE_TRANSIENT);
run(qAddAccount);
reset(qAddAccount);
}
o->cur++;
return FALSE;
}
void dbOutWriteAccountsModel(GtkTreeModel *model, dbOut *o)
{
gtk_tree_model_foreach(model, writeAccount, o);
}
void dbOutCommitAndFree(dbOut *o)
{
run(qCommit);
reset(qCommit);
g_free(o);
}
|
C
|
/******************************************************************************
* Project: hpsdr
*
* File: buffer.h
*
* Description: implement a simple buffer pool manager to avoid allocs/deallocs
* during operations. Alos used to minimize blocking IO time for USB
*
* Date: Mon 25 Feb 2013
*
* $Revision:$
*
* $Header:$
*
* Copyright (C) 2013 Kipp A. Aldrich <[email protected]>
******************************************************************************
*
* $Log:$
*
******************************************************************************
*/
#ifndef _OZYBUFIO_H
#define _OZYBUFIO_H
// stole the kernel's linked lists
#include <stddef.h> // size_t
#include <pthread.h>
#include "list.h"
#define OZY_BUFFER_SIZE 512
#define OZY_NUM_BUFS 32 // 1024 samples/OZY_BUFFER_SIZE (minimum samples/buffers to send to hpsdr at a time)
typedef struct usbBuf
{
// stolen kernel linked list for elegance and familiarity
struct list_head list; // available buffers
struct list_head inflight; // in flight buffers
void *buf;
int id;
size_t size;
struct libusb_transfer *xfr;
} usbBuf_t;
typedef struct usbBufPool
{
pthread_mutex_t lock;
usbBuf_t *ob;
const char *name;
} usbBufPool_t;
extern void buf_destroy_buffer_pool(usbBufPool_t *list);
extern usbBufPool_t *buf_create_pool(int num_bufs, size_t size, const char *name);
extern int buf_init_buffer_pools(void);
extern usbBuf_t *buf_create_buffer(size_t size);
extern usbBuf_t *buf_get_buffer(usbBufPool_t *pool);
extern void buf_put_buffer(usbBufPool_t *pool, usbBuf_t *entry);
extern int buf_count_buffers(usbBufPool_t *pool);
extern int buf_count_inflight(usbBufPool_t *pool);
extern void buf_cancel_inflight(usbBufPool_t *pool);
#endif /* _OZYBUFIO_H */
|
C
|
// converts RGB file to GIF (prints it to stdout)
//
#include <stdio.h>
#include <stdlib.h>
#include <gif_lib.h>
static
void rgb_to_gif(const char *filename, int width, int height)
{
FILE *in = fopen(filename, "r");
if (!in) {
fprintf(stderr, "Error: could not open %s\n", filename);
exit(1);
}
GifByteType *mem = malloc(sizeof(GifByteType)*width*height*3);
if (!mem) {
fprintf(stderr, "malloc failed");
exit(1);
}
GifByteType *red_buf = mem;
GifByteType *green_buf = mem + width*height;
GifByteType *blue_buf = mem + width*height*2;
GifByteType *buf = malloc(sizeof(GifByteType)*width*3);
if (!buf) {
fprintf(stderr, "malloc failed");
exit(1);
}
int i, j;
GifByteType *bufp, *rp=red_buf, *gp=green_buf, *bp=blue_buf;
for (i = 0; i < height; i++) {
if (fread(buf, width*3, 1, in) != 1) {
fprintf(stderr, "fread failed");
exit(1);
}
for (j = 0, bufp = buf; j < width; j++) {
*rp++ = *bufp++;
*gp++ = *bufp++;
*bp++ = *bufp++;
}
}
fclose(in);
free(buf);
int color_map_size = 256;
ColorMapObject *output_color_map = MakeMapObject(256, NULL);
if (!output_color_map) {
fprintf(stderr, "MakeMapObject failed");
exit(1);
}
GifByteType *output_buf = malloc(sizeof(GifByteType)*width*height);
if (!output_buf) {
fprintf(stderr, "malloc failed");
exit(1);
}
if (QuantizeBuffer(width, height, &color_map_size,
red_buf, green_buf, blue_buf,
output_buf, output_color_map->Colors) == GIF_ERROR)
{
fprintf(stderr, "QuantizeBuffer failed");
exit(1);
}
free(mem);
// output gif to stdout
GifFileType *gif_file = EGifOpenFileHandle(1);
if (!gif_file) {
fprintf(stderr, "EGifOpenFileHandle failed");
exit(1);
}
EGifSetGifVersion("89a");
if (EGifPutScreenDesc(gif_file, width, height, color_map_size, 0, output_color_map)
== GIF_ERROR)
{
fprintf(stderr, "EGifPutScreenDesc failed");
exit(1);
}
/*
char moo[] = {
1, // enable transparency
0, 0, // no time delay,
0xFF // transparency color index
};
EGifPutExtension(gif_file, GRAPHICS_EXT_FUNC_CODE, 4, moo);
*/
if (EGifPutImageDesc(gif_file, 0, 0, width, height, FALSE, NULL) == GIF_ERROR)
{
fprintf(stderr, "EGifPutImageDesc failed");
exit(1);
}
GifByteType *output_bufp = output_buf;
for (i = 0; i < height; i++) {
if (EGifPutLine(gif_file, output_bufp, width) == GIF_ERROR) {
fprintf(stderr, "EGifPutLine failed");
exit(1);
}
output_bufp += width;
}
free(output_buf);
FreeMapObject(output_color_map);
EGifCloseFile(gif_file);
}
int
main(int argc, char **argv)
{
if (argc != 4) {
fprintf(stderr, "Usage: rgb2gif <rgb file> <width> <height>\n");
exit(1);
}
char *filename = argv[1];
int width = atoi(argv[2]);
int height = atoi(argv[3]);
printf("Converting %s (%dx%d) from RGB to GIF.\n", filename, width, height);
rgb_to_gif(filename, width, height);
}
|
C
|
#ifndef VideoModule_h
#define VideoModule_h
#include <stdint.h>
#include "ClockFont.h"
typedef struct {
uint8_t Red;
uint8_t Green;
uint8_t Blue;
} Colour;
/*Given an array containing a certain time and a colour(using the colour structure), it shows on screen a digital real time clock,
by using calls to constanly refresh and print the time, until the quit hotckey is pressed. It uses the drawPixel() function and a list of pre set fonts for the numbers, containing ordered pixels*/
void drawTime(char * time, Colour colour);
/*Given a position on the grid that makes the shell, and a colour(using the colour structure), it prints a pixel of that colour in said position */
void drawPixel(int x, int y, Colour colour);
#endif
|
C
|
#include "S32K144.h" /* include peripheral declarations S32K144 */
void delay (void)
{
unsigned long i=1000000;
do{}while (--i);
}
int main(void)
{
//Activate clock PCC register description PCC_PORTD Chapter 29 page 633
PCC->PCCn[PCC_PORTD_INDEX]=0x40000000;
//Select port (
// Mux) PORT_PCR Chapter 12 PORT_PCRn page 198
PORTD->PCR[0]=0x00000100;
PORTD->PCR[15]=0x00000100;
PORTD->PCR[16]=0x00000100;
//Port Data direction PDDR Activar GPIO Chapter 13 page 218
//Activamos los pines de los puertos elegidos
//16 green
//15 red
//0 blue
PTD->PDDR=0x00018001;
for(;;) {
//Port Data direction PDOR Chapter 13 page 218
//PTD->PDOR=0x00018000;
//verde, rojo, azul
PTD->PDOR=(1<<16);
delay();
PTD->PDOR=(1<<15);
delay();
PTD->PDOR=1;
delay();
}
return 0;
}
|
C
|
#include<stdio.h>
void main(){
int arr[10],n,position,value;
printf("enter the no. of elements of the array: ");
scanf("%d",&n);
for (int i = 0; i < n; i++)
{
printf("\nenter the %d element of array\n",i+1);
scanf("%d",&arr[i]);
}
printf("enter the value and position of element to be inserted\n");
scanf("%d %d",&value,&position);
for (int i = n-1; i >= position; i--)
{
arr[i+1]=arr[i];
}
arr[position]=value;
printf("resulting array:\n");
for (int i = 0; i < n+1; i++)
{
printf("%d",arr[i]);
}
}
|
C
|
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include "UDPCookie.h"
#define ERRLEN 128
int isNotEqual(int x, int y) {
return !!(x^y);
}
int main(int argc, char *argv[]) {
int msgLen = 0;
if (argc != 2) // Test for correct number of arguments
dieWithError("Parameter(s): <Server Port #>");
char *service = argv[1]; // First arg: local port/service
// Construct the server address structure
struct addrinfo addrCriteria; // Criteria for address
memset(&addrCriteria, 0, sizeof(addrCriteria)); // Zero out structure
addrCriteria.ai_family = AF_INET; // We want IPv4 only
addrCriteria.ai_flags = AI_PASSIVE; // Accept on any address/port
addrCriteria.ai_socktype = SOCK_DGRAM; // Only datagram socket
addrCriteria.ai_protocol = IPPROTO_UDP; // UDP socket
struct addrinfo *servAddr; // List of server addresses
int rtnVal = getaddrinfo(NULL, service, &addrCriteria, &servAddr);
if (rtnVal != 0) {
char error[ERRLEN];
if (snprintf(error,ERRLEN,"getaddrinfo() failed: %s",
gai_strerror(rtnVal)) < 0) // recursive?!
dieWithSystemError("snprintf() failed");
dieWithError(error);
}
// Create socket for incoming connections
int sock = socket(servAddr->ai_family, servAddr->ai_socktype,
servAddr->ai_protocol);
if (sock < 0)
dieWithSystemError("socket() failed");
// Bind to the local address/port
if (bind(sock, servAddr->ai_addr, servAddr->ai_addrlen) < 0)
dieWithSystemError("bind() failed");
// Free address list allocated by getaddrinfo()
freeaddrinfo(servAddr);
for (;;) { // Run forever
struct sockaddr_storage clntAddr; // Client address
// Set Length of client address structure (in-out parameter)
socklen_t clntAddrLen = sizeof(clntAddr);
// Block until receive message from a client
char buffer[MAXMSGLEN]; // I/O buffer
// Size of received message
ssize_t numBytesRcvd = recvfrom(sock, buffer, MAXMSGLEN, 0,
(struct sockaddr *) &clntAddr, &clntAddrLen);
if (numBytesRcvd < 0)
dieWithSystemError("recvfrom() failed");
/* YOUR CODE HERE: parse & display incoming request message */
header_t* msg = (header_t*) buffer;
msgLen = msg->length;
char text[MAXMSGLEN];
int text_length = msgLen - 12;
memcpy(text, buffer + 12, text_length);
text[text_length] = '\0';
printf("message received from the client\n");
printf("magic=%d \n",ntohs(msg->magic));
printf("length= %d\n", ntohs(msg->length));
printf("xid=%x %x %x %x\n", msg->xactionid >> 24, (msg->xactionid >> 16)&0xff, (msg->xactionid >> 8)&0xff, msg->xactionid & 0xff);
printf("version=%d\n", msg->flags >> 4);
printf("flags=0x%x \n", msg->flags & 0xf);
printf("port=%d \n", ntohs(msg->port));
printf("result=%d \n",msg->result);
printf("variable part=%s\n", text);
/* YOUR CODE HERE: construct Response message in buffer, display it */
char msgBuf[MAXMSGLEN];
header_t* a = (header_t*)msgBuf;
a->magic = ntohs(msg->magic);
a->xactionid = msg->xactionid;
a->flags = msg->flags;
a->port = ntohs(msg->port);
a->result = msg->result;
// adding cookie to the character array msgBuff to send back to the client
char* cookie;
if (a->flags == 0x22) {
if (a->magic != 270) {
a->flags = 0x21;
cookie = "error";
a->length = sizeof(header_t) + strlen(cookie);
memcpy(msgBuf + 12, cookie, strlen(cookie));
}
else if (a->port != 0) {
a->flags = 0x21;
cookie = "error";
a->length = sizeof(header_t) + strlen(cookie);
memcpy(msgBuf + 12, cookie, strlen(cookie));
}
else if (ntohs(msg->length) != (12 + strlen(text))) {
cookie = "error";
a->flags = 0x21;
a->length = sizeof(header_t) + strlen(cookie);
memcpy(msgBuf + 12, cookie, strlen(cookie));
}
else if (ntohs(msg->length) == 12 + sizeof(text)) {
//a->result -= 1; // Terminating null included in length
a->flags = 0x21;
cookie = "error";
a->length = sizeof(header_t) + strlen(cookie);
memcpy(msgBuf + 12, cookie, strlen(cookie));
}
else {
char hoststr[NI_MAXHOST];
char portstr[NI_MAXSERV];
int rc = getnameinfo((struct sockaddr*)&clntAddr, clntAddrLen, hoststr, sizeof(hoststr), portstr, sizeof(portstr), NI_NUMERICHOST
| NI_NUMERICSERV);
if (rc == 0) printf("new connection from %s %s\n", hoststr, portstr);
else dieWithError("getnameinfo() fail!\n");
cookie = portstr;
memcpy(cookie + strlen(cookie), hoststr, strlen(hoststr));
a->length = 12 + strlen(cookie);
memcpy(msgBuf + 12, cookie, strlen(cookie));
}
}
else if (a->flags == 0x2a) {
if (a->magic != 270) {
a->flags = 0x29;
//cookie = "bad magic!";
//memcpy(&cookie[0], "bad magic!", sizeof("bad magic!"));
cookie = "error";
a->length = sizeof(header_t) + strlen(cookie);
memcpy(msgBuf + 12, cookie, strlen(cookie));
}
else if (a->port != 0) {
cookie = "error";
a->flags = 0x29;
a->length = sizeof(header_t) + strlen(cookie);
memcpy(msgBuf + 12, cookie, strlen(cookie));
}
else if (ntohs(msg->length) != (12 + strlen(text))) {
cookie = "error";
a->flags = 0x29;
a->length = sizeof(header_t) + strlen(cookie);
memcpy(msgBuf + 12, cookie, strlen(cookie));
}
else if (ntohs(msg->length) == 12 + sizeof(text)) {
//a->result -= 1; // Terminating null included in length
a->flags = 0x29;
cookie = "error";
a->length = sizeof(header_t) + strlen(cookie);
memcpy(msgBuf + 12, cookie, strlen(cookie));
}
else {
cookie = text;
a->length = sizeof(header_t) + strlen(cookie);
memcpy(msgBuf + 12, cookie, strlen(cookie));
}
}
a->magic = htons(a->magic);
a->port = htons(a->port);
numBytesRcvd = a->length;
a->length = htons(a->length);
printf("message sent to the client\n");
printf("magic=%d \n",ntohs(a->magic));
printf("length= %d\n", ntohs(a->length));
printf("xid=%x %x %x %x\n", msg->xactionid >> 24, (msg->xactionid >> 16)&0xff, (msg->xactionid >> 8)&0xff, msg->xactionid & 0xff);
//printf("version=%d\n", (a->flags) >> 4);
//printf("flags=0x%x \n", (a->flags)& 0xf);
printf("version=%d\n", a->flags >> 4);
printf("flags=0x%x \n", a->flags & 0xf);
printf("port=%d \n", ntohs(a->port));
printf("result=%d \n", a->result);
printf("variable part=%s\n", cookie);
ssize_t numBytesSent = sendto(sock, msgBuf, numBytesRcvd, 0, (struct sockaddr *) &clntAddr, sizeof(clntAddr));
if (numBytesSent < 0)
dieWithSystemError("sendto() failed)");
}
// NOT REACHED
}
|
C
|
#define GL_SILENCE_DEPRECATION
#include <GLUT/glut.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
static const GLint windowWidth = 640;
static const GLint windowHeight = 640;
static const GLfloat windowRatio = (float)windowWidth / windowHeight;
static const GLint leftCorner = -windowWidth / 2;
static const GLint rightCorner = windowWidth / 2;
static const GLint topCorner = windowHeight / 2;
static const GLint bottomCorner = -windowHeight / 2;
void exit_fatal(char * str) {
write(2, str, strlen(str));
exit(1);
}
GLfloat randFloat() {
return (float)(rand()) / (float)(RAND_MAX);
}
void init(void) {
glClearColor(0.33f,0.33f,0.33f,0.0);
glClear(GL_COLOR_BUFFER_BIT);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluOrtho2D(leftCorner, rightCorner, bottomCorner, topCorner);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
}
void reshape(GLsizei W, GLsizei H) {
if(windowRatio>W/H) glViewport(0,0,W,W/windowRatio);
else glViewport(0,0,H*windowRatio,H);
}
void triangle(GLfloat r, GLfloat g, GLfloat b) {
glColor3f(r, g, b);
glBegin(GL_TRIANGLES);
glVertex2f(0.f, 0.f);
glVertex2f(1.f, 0.f);
glVertex2f(0.5f, 0.86602540378f);
glEnd();
}
void line() {
glColor3b(0, 0, 0);
glBegin(GL_LINES);
glVertex2d(0,0);
glVertex2d(1,0);
glEnd();
}
void drawTunnel(GLint count, GLfloat scale, GLfloat * colors, GLint max) {
if (count == 0)
return;
glScalef(scale, scale, 0.f);
triangle(colors[(max - count) * 3], colors[(max - count) * 3 + 1], colors[(max - count) * 3 + 2]);
glRotatef(60.f, 0.f, 0.f, 1.f);
glTranslatef(1.f, 0.f, 0.f);
glRotatef(180.f, 0.f, 0.f, 1.f);
glScalef(1.f / scale, 1.f / scale, 0.f);
drawTunnel(count - 1, scale * 0.9f, colors, max);
}
void drawTriangles(GLint count, GLfloat scale, GLfloat * colors, GLint max) {
if (count == 0)
return;
GLfloat r = colors[(max - count) * 3];
GLfloat g = colors[(max - count) * 3 + 1];
GLfloat b = colors[(max - count) * 3 + 2];
// left triangle
glPushMatrix();
glScalef(scale / 2.f, scale / 2.f, 1.f);
triangle(r, g, b);
glPopMatrix();
glPushMatrix();
drawTriangles(count - 1, scale / 2.f, colors, max);
glPopMatrix();
// top triangle
glPushMatrix();
glScalef(scale / 2.f, scale / 2.f, 1.f);
glRotatef(60.f, 0.f, 0.f, 1.f);
glTranslatef(1.f, 0.f, 0.f);
glRotatef(-60.f, 0.f, 0.f, 1.f);
triangle(r, g, b);
glScalef(2.f / scale, 2.f / scale, 1.f);
drawTriangles(count - 1, scale / 2.f, colors, max);
glPopMatrix();
// right triangle
glPushMatrix();
glScalef(scale / 2.f, scale / 2.f, 0.f);
glTranslatef(1.f, 0.f, 0.f);
triangle(r, g, b);
glScalef(2.f / scale, 2.f / scale, 0.f);
drawTriangles(count - 1, scale / 2.f, colors, max);
glPopMatrix();
// mid triangle
// glPushMatrix();
// glScalef(scale / 2.f, scale / 2.f, 0.f);
// glTranslatef(1.f, 0.f, 0.f);
// glRotatef(60.f, 0.f, 0.f, 1.f);
// triangle(r, g, b);
// glScalef(2.f / scale, 2.f / scale, 0.f);
// drawTriangles(count - 1, scale / 2.f, colors, max);
// glPopMatrix();
}
GLfloat * reinitColors(GLfloat * colors, GLint count) {
if (colors)
free(colors);
colors = malloc(sizeof(GLfloat) * count * 3);
if (!colors)
exit_fatal("malloc fails");
for (int i = 0; i < count * 3; ++i) {
colors[i] = randFloat();
}
return colors;
}
static GLfloat angle;
static GLfloat dAngle = .5f;
void display() {
static GLint trianglesToDisplay;
static GLint maxTrianglesToDisplay = 7;
static GLfloat * colors;
if (!colors)
colors = reinitColors(colors, maxTrianglesToDisplay);
glClear(GL_COLOR_BUFFER_BIT);
for (int i = 0; i < 3; ++i) {
glPushMatrix();
glRotatef(angle + i * 120.f, 0.f, 0.f, 1.f);
drawTriangles(trianglesToDisplay + 1, windowHeight * 0.4f, colors, trianglesToDisplay + 1);
glPopMatrix();
}
angle += dAngle;
if (angle >= 360.f) {
angle = 0.f;
}
if ( (int)(angle * 2) % 36 == 0)
++trianglesToDisplay;
if (trianglesToDisplay == maxTrianglesToDisplay) {
trianglesToDisplay = 1;
colors = reinitColors(colors, maxTrianglesToDisplay);
}
glFlush();
glutSwapBuffers();
}
int main(int argc, char **argv) {
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB);
glutInitWindowSize(windowWidth, windowHeight);
glutInitWindowPosition(20, 20);
glutCreateWindow("MY SUPER PROGRAM!");
glutReshapeFunc(reshape);
glutDisplayFunc(display);
glutIdleFunc(display);
init();
glutMainLoop();
}
|
C
|
#include <stdio.h>
int in_word(int n);
int main(){
int n;
scanf("%d",&n);
in_word(n);
return 0;
}
int in_word(int n)
{
int rem,quo;
rem=n%10;
quo=n/10;
if(n==0)
return 0;
in_word(quo);
switch (rem)
{
case 1:
printf(" one ");
break;
case 2:
printf(" two ");
break;
case 3:
printf(" three ");
break;
case 4:
printf(" four ");
break;
case 5:
printf("five");
break;
case 6:
printf(" six ");
break;
case 7:
printf("seven");
break;
case 8:
printf(" eight ");
break;
case 9:
printf(" nine ");
break;
case 0:
printf(" zero ");
break;
}
}
|
C
|
/*
** EPITECH PROJECT, 2018
** attacks_arrow
** File description:
** arrow attacks
*/
#include "rpg.h"
void punch_arrow(window_t *win, game_t game, menus_t **menus)
{
size_t inc = 0;
timef_t time = init_time();
game.charac2.rect.top = 113;
game.charac2.rect.left = 910;
game.charac2.rect.width += 30;
game.charac2.pos = arrow_jump(win, game, menus);
game.charac2.pos.x += 70;
game.charac2.pos.y += 20;
while (sfRenderWindow_isOpen(win->window) && inc < 3) {
while (sfRenderWindow_pollEvent(win->window, &win->event)) {
anal_events_attack(win, game, menus);
}
sfSprite_setTextureRect(game.charac2.sprite, game.charac2.rect);
draw_game(game, win);
sfRenderWindow_display(win->window);
time.time_el = sfClock_getElapsedTime(time.clock);
time.seconds = time.time_el.microseconds / 10000;
if (time.seconds > 13) {
game.charac2.rect.left -= 130;
sfClock_restart(time.clock);
inc++;
}
}
game.charac2.rect.top = 0;
game.charac2.rect.left = 950;
game.charac2.rect.width = 100;
game.charac2.rect.height = 100;
game.charac2.pos.x = 1000;
game.charac2.pos.y = 685;
sfSprite_setTextureRect(game.charac2.sprite, game.charac2.rect);
game.charac.pv -= 15;
return;
}
void kick_arrow(window_t *win, game_t game, menus_t **menus)
{
size_t inc = 0;
timef_t time = init_time();
game.charac2.rect.top = 113;
game.charac2.rect.left = 130;
game.charac2.rect.width += 30;
game.charac2.pos = arrow_jump(win, game, menus);
game.charac2.pos.x += 40;
game.charac2.pos.y += 15;
while (sfRenderWindow_isOpen(win->window) && inc < 2) {
while (sfRenderWindow_pollEvent(win->window, &win->event)) {
anal_events_attack(win, game, menus);
}
sfSprite_setTextureRect(game.charac2.sprite, game.charac2.rect);
draw_game(game, win);
sfRenderWindow_display(win->window);
time.time_el = sfClock_getElapsedTime(time.clock);
time.seconds = time.time_el.microseconds / 10000;
if (time.seconds > 16) {
game.charac2.rect.left -= 130;
sfClock_restart(time.clock);
inc++;
}
}
game.charac2.rect.top = 0;
game.charac2.rect.left = 950;
game.charac2.rect.width = 100;
game.charac2.rect.height = 100;
game.charac2.pos.x = 1000;
game.charac2.pos.y = 685;
sfSprite_setTextureRect(game.charac2.sprite, game.charac2.rect);
game.charac.pv -= 30;
return;
}
void arrow_arrow(window_t *win, game_t game, menus_t **menus)
{
size_t inc = 0;
timef_t time = init_time();
game.charac2.rect.top = 330;
game.charac2.rect.left = 910;
game.charac2.rect.width += 30;
game.charac2.pos.y += 0;
while (sfRenderWindow_isOpen(win->window) && inc < 4) {
while (sfRenderWindow_pollEvent(win->window, &win->event)) {
anal_events_attack(win, game, menus);
}
sfSprite_setTextureRect(game.charac2.sprite, game.charac2.rect);
draw_game(game, win);
sfRenderWindow_display(win->window);
time.time_el = sfClock_getElapsedTime(time.clock);
time.seconds = time.time_el.microseconds / 10000;
if (time.seconds > 16) {
game.charac2.rect.left -= 130;
sfClock_restart(time.clock);
inc++;
}
}
arrow_in_air(win, game, menus);
game.charac2.rect.top = 0;
game.charac2.rect.left = 950;
game.charac2.rect.width = 100;
game.charac2.rect.height = 100;
game.charac2.pos.x = 1000;
game.charac2.pos.y = 685;
sfSprite_setTextureRect(game.charac2.sprite, game.charac2.rect);
game.charac.pv -= 40;
return;
}
|
C
|
#include <stdio.h>
int main(){
int array[100], maximum, size, c;
printf("Enter the number of elements in array: ");
scanf("%d", &size);
printf("Enter %d integers:\n", size);
for (c = 0; c < size; c++){
scanf("%d", &array[c]);
}
maximum = array[0];
for (c = 1; c < size; c++){
if (array[c] > maximum){
maximum = array[c];
}
}
printf("Largest element in the list is: %d\n", maximum);
return 0;
}
|
C
|
#include <stdio.h>
#include <sys/mman.h>
#include <seccomp.h>
int get_file_size(FILE *fp) {
fseek(fp, 0L, SEEK_END);
int sz = ftell(fp);
fseek(fp, 0L, SEEK_SET);
return sz;
}
void init_syscall_filter() {
// allow only four syscalls: open, read, write and exit
// the process is killed on execution of any other syscall
scmp_filter_ctx ctx = seccomp_init(SCMP_ACT_KILL);
seccomp_rule_add(ctx, SCMP_ACT_ALLOW, SCMP_SYS(open), 0);
seccomp_rule_add(ctx, SCMP_ACT_ALLOW, SCMP_SYS(read), 0);
seccomp_rule_add(ctx, SCMP_ACT_ALLOW, SCMP_SYS(write), 0);
seccomp_rule_add(ctx, SCMP_ACT_ALLOW, SCMP_SYS(exit), 0);
seccomp_load(ctx);
}
int main(int argc, char **argv) {
if (argc != 2) {
puts("./shellcode_executor <file>");
return 1;
}
char *shellcode_file = argv[1];
FILE *fp = fopen(shellcode_file, "r");
if (fp == NULL) {
puts("File not found");
return 1;
}
unsigned int file_size = get_file_size(fp);
void *shellcode_ptr = mmap(NULL, 0x1000, PROT_READ|PROT_WRITE, MAP_ANON|MAP_PRIVATE, -1, 0);
fread(shellcode_ptr, file_size + 1, 1, fp);
mprotect(shellcode_ptr, 0x1000, PROT_READ | PROT_EXEC);
init_syscall_filter();
void (*shellcode)() = (void(*)())shellcode_ptr;
shellcode();
return 0;
}
|
C
|
void main(){
int i;
for(i=0;i<5;i+=1){
print i;
}
}
|
C
|
#include <stdlib.h>
#include <stdio.h>
int main()
{
char data = "01/06/2015";
int iDia;
int iMes;
int iAno;
char sDia[3];
char sMes[3];
char sAno[5];
int i;
for (i = 0; data[i] != '/'; i++){
sDia[i] = data[i];
if (i > 1) return 0; //NO MAXIMO 2 NUMEROS ANTES DE '/'
if (procura_char(sDia[i]) == 1) return 0; //
}
sDia[i] = '\0';
i++;
if (strlen(sDia) == 0) return 0; // VERIFICA SE IGUAL A 0
iDia = atoi(sDia); //CONVERTE STRING EM INTEIRO
//MES
int j;
int cont_Mes = 0;
for (j = i; data[j] != '/'; j++, cont_Mes++){
sMes[cont_Mes] = data[j];
if (cont_Mes > 1) return 0;
if (procura_char(sMes[cont_Mes]) == 1) return 0;
}
sMes[j] = '\0';
j++;
if (strlen(sMes) == 0) return 0;
iMes = atoi(sMes);
// ANO
int cont_Ano = 0;
for (i = j; i < strlen(data); i++, cont_Ano++){
sAno[cont_Ano] = data[i];
if (procura_char(data[i]) == 1) return 0;
}
if (cont_Ano != 2 && cont_Ano != 4) return 0; //S ACEITA SE O ANO SE TIVER 2 OU 4 DIGITOS
sAno[cont_Ano] = '\0';
iAno = atoi(sAno);
//validar
int retorno = valida_data_numeros(iDia, iMes, iAno);
return retorno;
}
int valida_data_numeros(int dia, int mes, int ano){
if ((dia < 1 || dia > 31) || (mes < 1 || mes > 12) || (ano < 1 || ano > 2020))
return 0;
if (dia > 30 && (mes == 4 || mes == 6 || mes == 9 || mes == 11) )
return 0;
//FEVEREIRO
if (dia > 29 && (mes == 2 && ano % 4 == 0 || ano % 400 == 0 && ano % 100 != 0) ) // ANO BISSEXTO
return 0;
if (dia > 28 && (mes == 2 && ano % 4 != 0 || ano % 400 != 0 && ano % 100 == 0) )
return 0;
return 1;
}
int procura_char(char c){
if (c < 48 || c > 57)
return 1;
else
return 0;
}
}
|
C
|
/* *****************************************************************************
* freqmeasure.c
* See atmegaclib2.h header for the copyrights...
* *****************************************************************************
*/
#ifndef F_CPU
#define F_CPU 16000000UL //required by Atmel Studio 6
#endif
#include <avr/io.h>
#include <stdio.h>
#include <avr/interrupt.h>
#include "atmegaclib2.h"
#define FREQMEASURE_BUFFER_LEN 12
volatile uint32_t buffer_value[FREQMEASURE_BUFFER_LEN];
volatile uint8_t buffer_head;
volatile uint8_t buffer_tail;
uint16_t capture_msw;
uint32_t capture_previous;
void FreqMeasure_begin(void) {
capture_init();
capture_msw = 0;
capture_previous = 0;
buffer_head = 0;
buffer_tail = 0;
capture_start();
}
uint8_t FreqMeasure_available(void) {
uint8_t head, tail;
head = buffer_head;
tail = buffer_tail;
if (head >= tail)
return head - tail;
return FREQMEASURE_BUFFER_LEN + head - tail;
}
uint32_t FreqMeasure_read(void) {
uint8_t head, tail;
uint32_t value;
head = buffer_head;
tail = buffer_tail;
if (head == tail)
return 0xFFFFFFFF;
tail = tail + 1;
if (tail >= FREQMEASURE_BUFFER_LEN)
tail = 0;
value = buffer_value[tail];
buffer_tail = tail;
return value;
}
void FreqMeasure_end(void) {
capture_shutdown();
}
ISR(TIMER_OVERFLOW_VECTOR) {
capture_msw++;
}
ISR(TIMER_CAPTURE_VECTOR) {
uint16_t capture_lsw;
uint32_t capture, period;
uint8_t i;
// get the timer capture
capture_lsw = capture_read();
// Handle the case where but capture and overflow interrupts were pending
// (eg, interrupts were disabled for a while), or where the overflow occurred
// while this ISR was starting up. However, if we read a 16 bit number that
// is very close to overflow, then ignore any overflow since it probably
// just happened.
if (capture_overflow() && capture_lsw < 0xFF00) {
capture_overflow_reset();
capture_msw++;
}
// compute the waveform period
capture = ((uint32_t) capture_msw << 16) | capture_lsw;
period = capture - capture_previous;
capture_previous = capture;
// store it into the buffer
i = buffer_head + 1;
if (i >= FREQMEASURE_BUFFER_LEN)
i = 0;
if (i != buffer_tail) {
buffer_value[i] = period;
buffer_head = i;
}
}
|
C
|
#ifndef STACK_H_INCLUDED
#define STACK_H_INCLUDED
#define STACK_SIZE 100
int TOP=-1;
int STACK[STACK_SIZE];
int PUSH(int element)
{
if(TOP==STACK_SIZE-1)
{
printf("OVERFLOW");
return -1;
}
else{
STACK[++TOP]= element;
return 1;
}
}
int PEEK()
{
return STACK[TOP];
}
int POP()
{
if(TOP==-1)
{
printf("UNDERFLOW");
return -1;
}
else{
int ele=STACK[TOP];
TOP--;
return ele;
}
}
#endif // STACK_H_INCLUDED
|
C
|
#pragma once
#include "Lights/Light.h"
struct PointLight : public Light {
Vector position;
Color Lout;
PointLight() : position(Vector(0.0f, 0.0f, 0.0f)), Lout(Color(0.0f, 0.0f, 0.0f)){};
virtual ~PointLight(){};
PointLight(Vector position_init, Color Lout_init) : position(position_init), Lout(Lout_init){};
Color getIntensity(Vector &targetPoint) {
return Lout * (1 / npow(position.getDistance(targetPoint), 1.4f));
}
Vector getDirection(Vector &targetPoint) { return position - targetPoint; }
Number getDistance(Vector &targetPoint) { return (position - targetPoint).length(); }
};
|
C
|
# include <stdio.h>
int main()
{
int a,b,quatient,remainder;
printf("Finding quatient and remainder");
scanf("%d %d", &a,&b);
quatient = a / b;
remainder = a % b;
printf("%d %d\n", quatient,remainder);
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
int i;
char s[2];
s[0] = '$';
s[1] = '3';
i = atoi(s);
printf("%d\n", i);
return (0);
}
|
C
|
//分三步走,1.复制next节点放在原链表后面2.复制随机节点,按照原链表的顺序3.把两个链表分开
RandomListNode* Clone(RandomListNode* pHead)
{
//1
RandomListNode* currentNode = pHead;
while(currentNode)
{
RandomListNode *node = new RandomListNode(currentNode->label);
node->next = currentNode->next;
currentNode->next = node;
currentNode = node->next;
}
//2
currentNode = pHead;
while(currentNode->random)
{
currentNode->next->random=currentNode->random->next;
currentNode = currentNode->next->next;
}
//3
RandomListNode* copyHead = pHead->next;
currentNode = pHead;
RandomListNode *tmp;
while(currentNode->next){
tmp = currentNode ->next;
currentNode->next = tmp->next;
currentNode = tmp;
}
return copyHead;
}
|
C
|
#include<stdio.h>
#include<conio.h>
void main()
{
int i;
char c[6] = "hello\0" ;
clrscr();
printf("%s\n",c);
/* method 1*/
for(i=0; i<=5; i++)
{
printf("%c",c[i]);
}
/*method 2 */
for(i=0; i<=5; i++)
{
printf("%c",i[c]);
}
/*method 3*/
for(i=0; i<=5; i++)
{
printf("%c",*(c+i));
}
/*method 4*/
for(i=0; i<=5; i++)
{
printf("%c",*(i+c));
}
getch();
}
|
C
|
#include <stdio.h>
#include <unistd.h>
__attribute__((constructor))
void setup(void) {
setbuf(stdin, NULL);
setbuf(stdout, NULL);
}
int main() {
char buf[0x20];
read(0, buf, 0x100);
puts("Bye!");
return 0;
}
|
C
|
// 程序填空,不要改变与输入输出有关的语句。
// 输入一个正整数 repeat (0<repeat<10),做 repeat 次下列运算:
// 将一笔零钱(大于8分,小于1元, 精确到分)换成5分、2分和1分的硬币。
// 输入金额,问有几种换法?针对每一种换法,每种硬币至少有一枚,请输出各种面额硬币的数量和硬币的总数量。
// 要求:硬币面值按5分、2分、1分顺序,各类硬币数量依次从大到小的顺序,输出各种换法。
// 输出使用语句:printf("fen5:%d,fen2:%d,fen1:%d,total:%d\n",fen5, fen2, fen1, fen5+fen2+fen1);
// 输入输出示例:括号内为说明
// 输入:
// 2 (repeat=2)
// 10 (money=10分)
// 13 (money=13分)
// 输出:
// fen5:1,fen2:2,fen1:1,total:4
// fen5:1,fen2:1,fen1:3,total:5
// count = 2 (10分有2种换法)
// fen5:2,fen2:1,fen1:1,total:4
// fen5:1,fen2:3,fen1:2,total:6
// fen5:1,fen2:2,fen1:4,total:7
// fen5:1,fen2:1,fen1:6,total:8
// count = 4 (13分有4种换法)
#include "stdio.h"
int main(void)
{
int count, fen1, fen2, fen5, money;
int repeat, ri;
scanf("%d", &repeat);
for(ri = 1; ri <= repeat; ri++){
scanf("%d", &money);
count = 0;
for (fen5 = money/5; fen5 >= 1; fen5--) {
for (fen2 = (money-fen5*5)/2; fen2>=1; fen2--) {
fen1 = money - fen5*5 - fen2*2;
if (fen1) {
printf("fen5:%d,fen2:%d,fen1:%d,total:%d\n", fen5, fen2, fen1, fen5+fen2+fen1);
count++;
}
}
}
printf("count = %d\n", count);
}
}
|
C
|
#include <limits.h>
#include <stdio.h>
void bit_print(int);
int main(void){
bit_print(45692);
printf("\n");
return 0;
}
void bit_print(int a){
int i;
int n = sizeof(int) * CHAR_BIT;
int mask = 1 << (n - 1);
for (i = 1; i <= n; ++i){
putchar(((a & mask) == 0) ? '0' : '1');
a <<= 1;
if (i % CHAR_BIT == 0 && i < n)
putchar(' ');
}
}
|
C
|
#include <stdio.h>
#define M 10
void main()
{
static int a[M] = {-9, -5, -3, 0, 1, 5, 7, 14, 20, 43};
int n, min, mid, max, found;
min = 0;
max = M - 1;
printf("Please enter your search number: \n");
scanf("%d", &n);
while (1)
{
mid = (min + max) / 2;
if (min > max)
{
printf("您输入的数不在数组中!");
break;
}
if (a[mid] > n)
{
max = mid - 1;
continue;
}
else if (a[mid] < n)
{
min = mid + 1;
continue;
}
else
{
found = mid;
printf("找到了: 下标found = %d\n", found);
break;
}
}
}
|
C
|
#include "multiq.h"
MultiQ* createMQ(int num){
MultiQ* mq = (MultiQ*)malloc(sizeof(MultiQ));
mq->q = (Queue*)malloc(sizeof(Queue)*num);
for (int i=0; i<num; i++){
mq->q[i] = newQ();
}
mq->size = num;
return mq;
}
MultiQ* addMQ(MultiQ* mq, Task* t){
if(t->pr > mq->size){
return mq;
}
Element* node = (Element*)malloc(sizeof(Element));
node->key = t->tid;
mq->q[t->pr - 1] = addQ(mq->q[t->pr - 1], node);
return mq;
}
Task* nextMQ(MultiQ* mq){
int i=0;
while (mq->q[i].len == 0 && i < mq->size){
i++;
}
if(i == mq->size){
return NULL;
}
Element* node = mq->q[i].head;
Task* t = (Task*)malloc(sizeof(Task));
t->tid = node->key;
t->pr = i + 1;
return t;
}
MultiQ* delNextMQ(MultiQ* mq){
int i = 0;
while(mq->q[i].len == 0 && i < mq->size){
i++;
}
if(i == mq->size){
return mq;
}
mq->q[i] = delQ(mq->q[i]);
return mq;
}
boolean isEmptyMQ(MultiQ* mq){
int i = 0;
while (mq->q[i].len == 0 && i<mq->size){
i++;
}
if(i == mq->size){
return TRUE;
}
return FALSE;
}
int sizeMQ(MultiQ* mq){
int s = 0;
for (int i=0; i<mq->size; i++){
s = s + mq->q[i].len;
}
return s;
}
int sizeMQbyPriority(MultiQ* mq, Priority* p){
int prty = p->pr;
if(prty > mq->size){
return 0;
}
int s = mq->q[prty - 1].len;
return s;
}
Queue getQueueFromMQ(MultiQ* mq, Priority* p){
int prty = p->pr;
if(prty > mq->size){
return mq->q[0];
}
return mq->q[prty - 1];
}
|
C
|
//
// prog2.c
// prog2
//
// Created by ENZE XU on 2021/9/25.
//
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <signal.h>
#include <time.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <pwd.h>
#define MAXN 10000
void quitHandler(int);
char * getMainPath(void);
char * getUserName(void);
void printArgv(char *argv[]) { // test print function
int i = 0;
while(argv[i] != NULL) {
printf("argv[%d] %s (length = %ld)\n", i, argv[i], strlen(argv[i]));
i ++;
}
printf("argv[%d] NULL\n", i);
}
void commandExecute(char *line) {
char commandPathBin[MAXN] = "/bin/";
char commandPathUsrBin[MAXN] = "/usr/bin/";
char commandFullBin[MAXN];
char commandFullUsrBin[MAXN];
char commandFull[MAXN];
//char pathUser[MAXN] = "/home/csuser/";
int argc = 0;
char *argv[MAXN];
char *token;
token = strtok(line, " ");
while(token != NULL){
argv[argc] = token;
token = strtok(NULL, " ");
argc++;
}
//printArgv(argv);
//printf("argc = %d\n, %d", argc, argv[0]);
if (strlen(argv[argc - 1]) == 1 && argv[argc - 1][0] == 10) argc -= 1;
else if (argv[argc - 1][strlen(argv[argc - 1]) - 1] == 10) argv[argc - 1][strlen(argv[argc - 1]) - 1] = '\0';
// printf("argc = %d\n", argc);
if (argc == 0) return; // empty command, do nothing, just print the prompt again
int flagBackgroundExecution = 0;
if (argv[argc - 1][strlen(argv[argc - 1]) - 1] == '&') {
flagBackgroundExecution = 1;
printf("\033[32m[Enze Shell] background execution\033[0m\n");
if (strlen(argv[argc - 1]) == 1) {
argv[argc - 1] = NULL;
argc --;
}
else {
argv[argc - 1][strlen(argv[argc - 1]) - 1] = '\0';
argv[argc] = NULL;
}
}
else argv[argc] = NULL;
if (argc == 0) return; // empty command, do nothing, just print the prompt again
// deal with cd command
char pathUser[MAXN] = "";
if(strcmp(argv[0], "cd") == 0) {
if (argv[1] == NULL) return;
if (argv[1][0] == '~') {
argv[1][0] = '/';
char tmpPath[MAXN];
char pathHead[MAXN] = "/home/";
char pathTail[MAXN] = "/";
strcat(pathUser, pathHead);
strcat(pathUser, getUserName());
strcat(pathUser, pathTail);
// printf("pathUser: %s\n", pathUser);
strcpy(tmpPath, pathUser);
strcat(tmpPath, argv[1]);
strcpy(argv[1], tmpPath);
// printf("newpath: %s\n", argv[1]);
}
int chdir_return = chdir(argv[1]);
if (chdir_return == -1) perror("cd");
return;
}
// check if the command is available
strcpy(commandFullBin, commandPathBin);
strcat(commandFullBin, argv[0]);
strcpy(commandFullUsrBin, commandPathUsrBin);
strcat(commandFullUsrBin, argv[0]);
if (access(commandFullBin, F_OK) == 0) {
// strcpy(commandFull, commandFullBin);
}
else if (access(commandFullUsrBin, F_OK) == 0) {
// strcpy(commandFull, commandFullUsrBin);
}
else if (access(argv[0], F_OK) == 0) {
// strcpy(commandFull, commandFullUsrBin);
}
else {
printf("\033[32m[Enze Shell] %s: command not found\033[0m\n", argv[0]);
return;
}
// fork
pid_t pid, wait_pid;
int status;
pid = fork();
if (pid == 0) {
// printf("command = %s\n", commandFull);
int execvp_return = execvp(argv[0], argv);
if (execvp_return < 0) {
perror("\033[32m[Enze Shell] child failed\033[0m");
printf("\033[0m");
exit(EXIT_FAILURE);
}
}
if (flagBackgroundExecution == 1) { // iff receive an '&', skip waitpid
printf("\033[32m[Enze Shell] child pid = %d\033[0m\n", pid);
return ;
}
wait_pid = waitpid(pid, &status, 0);
// printf("waitpid return %d\n", wait_pid);
if (wait_pid == -1) {
printf("\033[32m[Enze Shell] parent process cannot wait any more, return\033[0m\n");
}
}
char mainPath[MAXN];
char * getMainPath(void) {
getcwd(mainPath, sizeof(mainPath));
return mainPath;
}
char * getUserName(void) { // mine is "/home/csuser/" but if Professor try other user...emmm...anyway, let me figure it out
struct passwd *pwd = getpwuid(getuid());
return pwd->pw_name;
}
int main(){
signal(SIGINT, quitHandler); // signal handler used to ignore Ctrl-C
time_t t;
time(&t);
printf("\033[32m[Enze Shell] version: v1.0\033[0m\n", ctime(&t));
printf("\033[32m[Enze Shell] pid = %d\033[0m\n", getpid()); // if execute lab2 in lab2, can help to identify
printf("\033[32m[Enze Shell] start at (GMT) %s\033[0m", ctime(&t)); // GMT time
while(1) {
char line[MAXN];
printf("\033[34m%s\033[37m %% ", getMainPath());
if (!fgets(line, MAXN, stdin)) {
printf("\n\033[32m[Enze Shell] OK close shop and go home (type: \"Ctrl-D\", pid: %d)\033[0m\n", getpid());
break;
}
if (strcmp(line, "exit\n") == 0) {
printf("\033[32m[Enze Shell] please use exit() or Ctrl-D to exit\033[0m\n");
continue;
}
if (strcmp(line, "exit()\n") == 0) {
printf("\033[32m[Enze Shell] OK close shop and go home (type: \"exit()\", pid: %d)\033[0m\n", getpid());
break;
}
commandExecute(line);
}
return 0;
}
void quitHandler(int theInt) { // signal handler used to ignore Ctrl-C
//fflush(stdin);
//printf("\n[Enze Shell] Not QUITTING (SIGINT = %d)\n", theInt);
//printf("\n%s %% ", getMainPath());
//fflush(stdout);
return;
}
|
C
|
#ifndef PLAYER_H
#define PLAYER_H
#include <stdarg.h>
#include "gl_kyl.h"
/*
* sprite struct containing ALL information about a sprite, like location, velocity, whether it is jumping
* or grounded, whether it is shielding and for how long, whether the character is knockbacked and for
* how long, whether the sprite is punching, information about the projectile the character fires, hitboxes,
* and sprite number for different sprites..
*/
typedef struct sprite {
int x;
int y;
volatile int vel_x;
volatile int vel_y;
int height;
int is_jumping;
int is_grounded;
int is_shielding;
int is_stunned;
int shield_timer;
int is_punching;
int knockback_timer;
int proj_sprite_num;
int hit;
int is_firing;
int direction;
int proj_cooldown;
int color;
int base_color;
int sprite_num; //Ball == 1, box == 2, fire == 3
int hit_x_left;
int hit_x_right;
int hit_y_top;
int hit_y_bottom;
int hit_points;
struct sprite* owner;
}sprite;
/*
* Sprite nums enum for redrawing. Based on which sprite number the player's sprite has, the GPU will redraw
* the sprite shape.
*/
typedef enum {
BOX = 1,
BALL = 2,
FIRE = 3,
} sprite_nums;
/*
* Enums for directions the sprite is facing. Affects punch direction and shot direction.
*/
typedef enum {
LEFT = -1,
RIGHT = 1,
NONE = 0,
} directions;
/*
* This function draws the initial player sprites to the doubleBuffered framebuffer.
*
* PARAMETERS
* n - The number of players in the game.
* ... - A variadic number of sprite pointers, where each sprite is the sprite of a player.
*/
void player_init(int n, ...);
/*
* Function that moves each player simultaneously based on vel_x and vel_y. It also moves any projectiles fired,
* checking for collisions.
*
* PARAMETERS
* sprites[30] - array in gameplay implementation that contains information about each sprite
* (WITH A MAX OF 30 SPRITES)
*/
void player_move(sprite sprites[30]);
/*
* Function takes a pointer to a sprite and makes that sprite jump by changing its vel_y and updating
* its is grounded and is_jumping variables.
*
* PARAMETERS
* _sprite - The sprite you want to jump.
*/
void player_jump(sprite* _sprite);
/*
* Function that erases sprite on the hidden buffer.
*
* PARAMETERS
* _sprite - Sprite you want to erase
*/
void player_erase_sprites(sprite* _sprite);
/*
* Helper function that updates the hitbox of _sprite.
*
* PARAMETERS
* _sprite - sprite that contains hitbox you want to update
*/
void update_hit_box(sprite* _sprite);
/*
* Make p_sprite shoot projectile
*
* PARAMETERS
* p_sprite - player_sprite: The sprite of player that you want to shoot.
* projectile - The sprite you want to treat as the projectile.
*/
void player_projectile(sprite* p_sprite, sprite* projectile);
/*
* Check whether projectile hit target by comparing hitboxes.
*
* PARAMETERS
* target - pointer to target sprite
* projectile - pointer to projectile sprite that you want to check for collision
*/
int projectile_hit(sprite* target, sprite* projectile);
/*
* Check if p_sprite hit target_sprite, drawing a fist to represent a punch.
*
* PARAMETERS
* p_sprite - player_sprite: The sprite of player you want punching
* target_sprite - The sprite of player you want to check for getting punched.
*/
int player_punch(sprite* p_sprite, sprite* target_sprite);
/*
* Helper function that registers whether p_sprite hit target_sprite by checking hitboxes.
*
* PARAMETERS
* p_sprite - player_sprite: The sprite of player you want punching
* target_sprite - The sprite of player you want to check for getting punched.
*/
int punch_hit(sprite* p_sprite, sprite* target_sprite);
/*
* Helper function that redrew each player's healthbars.
*
* PARAMETERS
* x - x_pos of health_bar for p1
* y - y_pos of health_bar for p1
* x2 - x_pos of health_bar for p2
* y2 - y_pos of health_bar for p2
* _sprite - sprite that was hit
*/
void player_redraw_health_bar(int x, int y, int x2, int y2, sprite _sprite);
#endif
|
C
|
/*
* Modify the problem written previously, so that the function returns the address
* of the character string containing the propery day to be displayed
*
*/
#include <stdio.h>
int
GetDay(char **days, int x);
int
main()
{
int input = 0;
char *days[7] = { "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", };
printf("Enter in day number: ");
scanf("%d", &input);
int address = GetDay(days, input);
printf("%s", (char *)address);
return 0;
}
int
GetDay(char **days, int x)
{
int result = (int)&(**(days + (x - 1)));
return result;
}
|
C
|
#include "MPU9250_header.h"
#include "mpu9250_methoden.c"
float sum = 0;
uint32_t sumCount = 0;
char buffer[14];
int main(){
printf("main startet...\n\r");
int data;
// Read the WHO_AM_I register, this is a good test of communication
int status = i2c_readByte(0, MPU9250_ADDRESS, WHO_AM_I_MPU9250, &data); // Read WHO_AM_I register for MPU-9250
if (data == 0x71){ // WHO_AM_I should always be 0x75
//printf("in if-schleife\n\r");
resetMPU9250(); // Reset registers to default in preparation for device calibration
//printf("MPU9250 reseted...\n\r");
// führt zu plausiblen Ausgaben
//MPU9250SelfTest(SelfTest); // Start by performing self test and reporting values
//printf("x-axis self test: acceleration trim within : %f of factory value\n\r", SelfTest[0]);
//printf("y-axis self test: acceleration trim within : %f of factory value\n\r", SelfTest[1]);
//printf("z-axis self test: acceleration trim within : %f of factory value\n\r", SelfTest[2]);
//printf("x-axis self test: gyration trim within : %f of factory value\n\r", SelfTest[3]);
//printf("y-axis self test: gyration trim within : %f of factory value\n\r", SelfTest[4]);
//printf("z-axis self test: gyration trim within : %f of factory value\n\r", SelfTest[5]);
//calibrateMPU9250(gyroBias, accelBias); // Calibrate gyro and accelerometers, load biases in bias registers
//printf("x gyro bias = %f\n\r", gyroBias[0]);
//printf("y gyro bias = %f\n\r", gyroBias[1]);
//printf("z gyro bias = %f\n\r", gyroBias[2]);
//printf("x accel bias = %f\n\r", accelBias[0]);
//printf("y accel bias = %f\n\r", accelBias[1]);
//printf("z accel bias = %f\n\r", accelBias[2]);
//printf("nach calibrate\n\r");
usleep(2000000);
// Initialize device for active mode read of acclerometer, gyroscope, and temperature
initMPU9250();
printf("MPU9250 initialized for active data mode...\n\r");
// Initialize device for active mode read of magnetometer
initAK8963(magCalibration);
printf("AK8963 initialized for active data mode...\n\r");
printf("Accelerometer full-scale range = %f g\n\r", 2.0f*(float)(1<<Ascale));
printf("Gyroscope full-scale range = %f deg/s\n\r", 250.0f*(float)(1<<Gscale));
if(Mscale == 0) printf("Magnetometer resolution = 14 bits\n\r");
if(Mscale == 1) printf("Magnetometer resolution = 16 bits\n\r");
if(Mmode == 2) printf("Magnetometer ODR = 8 Hz\n\r");
if(Mmode == 6) printf("Magnetometer ODR = 100 Hz\n\r");
usleep(1000000);
} else {
printf("Could not connect to MPU9250: \n\r");
printf("%#x \n", data);
while(1) ; // Loop forever if communication doesn't happen
}
getAres(); // Get accelerometer sensitivity
getGres(); // Get gyro sensitivity
getMres(); // Get magnetometer sensitivity
printf("Accelerometer sensitivity is %f LSB/g \n\r", 1.0f/aRes);
printf("Gyroscope sensitivity is %f LSB/deg/s \n\r", 1.0f/gRes);
printf("Magnetometer sensitivity is %f LSB/G \n\r", 1.0f/mRes);
magbias[0] = +470.; // User environmental x-axis correction in milliGauss, should be automatically calculated
magbias[1] = +120.; // User environmental x-axis correction in milliGauss
magbias[2] = +125.; // User environmental x-axis correction in milliGauss
while(1) {
// If intPin goes high, all data registers have new data
// On interrupt, check if data ready interrupt
//if (i2c_readByte(0, MPU9250_ADDRESS, INT_STATUS, &rdByte) & 0x01) {
i2c_readByte(0, MPU9250_ADDRESS, INT_STATUS, &rdByte);
if (rdByte & 0x01) {
readAccelData(accelCount); // Read the x/y/z adc values
// Now we'll calculate the accleration value into actual g's
ax = (float)accelCount[0]*aRes - accelBias[0]; // get actual g value, this depends on scale being set
ay = (float)accelCount[1]*aRes - accelBias[1];
az = (float)accelCount[2]*aRes - accelBias[2];
readGyroData(gyroCount); // Read the x/y/z adc values
// Calculate the gyro value into actual degrees per second
gx = (float)gyroCount[0]*gRes - gyroBias[0]; // get actual gyro value, this depends on scale being set
gy = (float)gyroCount[1]*gRes - gyroBias[1];
gz = (float)gyroCount[2]*gRes - gyroBias[2];
readMagData(magCount); // Read the x/y/z adc values
// Calculate the magnetometer values in milliGauss
// Include factory calibration per data sheet and user environmental corrections
mx = (float)magCount[0]*mRes*magCalibration[0] - magbias[0]; // get actual magnetometer value, this depends on scale being set
my = (float)magCount[1]*mRes*magCalibration[1] - magbias[1];
mz = (float)magCount[2]*mRes*magCalibration[2] - magbias[2];
}
//Now = t.read_us();
deltat = (float)((Now - lastUpdate)/1000000.0f) ; // set integration time by time elapsed since last filter update
lastUpdate = Now;
sum += deltat;
sumCount++;
// if(lastUpdate - firstUpdate > 10000000.0f) {
// beta = 0.04; // decrease filter gain after stabilized
// zeta = 0.015; // increasey bias drift gain after stabilized
// }
// Pass gyro rate as rad/s
// mpu9250.MadgwickQuaternionUpdate(ax, ay, az, gx*PI/180.0f, gy*PI/180.0f, gz*PI/180.0f, my, mx, mz);
//MahonyQuaternionUpdate(ax, ay, az, gx*PI/180.0f, gy*PI/180.0f, gz*PI/180.0f, my, mx, mz);
// Serial print and/or display at 0.5 s rate independent of data rates
//delt_t = t.read_ms() - count;
//if (delt_t > 50) { // update LCD once per half-second (500) independent of read rate
// ouput as csv
long timeinusec = getMicrotime();
printf("%lu", timeinusec);
printf(";%f", 1000*ax);
printf(";%f", 1000*ay);
printf(";%f\n\r", 1000*az);
//printf("ax = %f", 1000*ax);
//printf(" ay = %f", 1000*ay);
//printf(" az = %f mg\n\r", 1000*az);
//printf("gx = %f", gx);
//printf(" gy = %f", gy);
//printf(" gz = %f deg/s\n\r", gz);
//printf("mx = %f", mx);
//printf(" my = %f", my);
//printf(" mz = %f mG\n\r", mz);
// tempCount = mpu9250.readTempData(); // Read the adc values
//temperature = ((float) tempCount) / 333.87f + 21.0f; // Temperature in degrees Centigrade
//printf(" temperature = %f C\n\r", temperature);
//printf("q0 = %f\n\r", q[0]);
//printf("q1 = %f\n\r", q[1]);
//printf("q2 = %f\n\r", q[2]);
//printf("q3 = %f\n\r", q[3]);
/* lcd.clear();
lcd.printString("MPU9250", 0, 0);
lcd.printString("x y z", 0, 1);
sprintf(buffer, "%d %d %d mg", (int)(1000.0f*ax), (int)(1000.0f*ay), (int)(1000.0f*az));
lcd.printString(buffer, 0, 2);
sprintf(buffer, "%d %d %d deg/s", (int)gx, (int)gy, (int)gz);
lcd.printString(buffer, 0, 3);
sprintf(buffer, "%d %d %d mG", (int)mx, (int)my, (int)mz);
lcd.printString(buffer, 0, 4);
*/
// Define output variables from updated quaternion---these are Tait-Bryan
// angles, commonly used in aircraft orientation.
// In this coordinate system, the positive z-axis is down toward Earth.
// Yaw is the angle between Sensor x-axis and Earth magnetic North (or true North if corrected for local declination, looking down on the sensor positive yaw is counterclockwise.
// Pitch is angle between sensor x-axis and Earth ground plane, toward the Earth is positive, up toward the sky is negative.
// Roll is angle between sensor y-axis and Earth ground plane, y-axis up is positive roll.
// These arise from the definition of the homogeneous rotation matrix constructed from quaternions.
// Tait-Bryan angles as well as Euler angles are non-commutative; that is, the get the correct orientation the rotations must be
// applied in the correct order which for this configuration is yaw, pitch, and then roll.
// For more see http://en.wikipedia.org/wiki/Conversion_between_quaternions_and_Euler_angles which has additional links.
//yaw = atan2(2.0f * (q[1] * q[2] + q[0] * q[3]), q[0] * q[0] + q[1] * q[1] - q[2] * q[2] - q[3] * q[3]);
//pitch = -asin(2.0f * (q[1] * q[3] - q[0] * q[2]));
//roll = atan2(2.0f * (q[0] * q[1] + q[2] * q[3]), q[0] * q[0] - q[1] * q[1] - q[2] * q[2] + q[3] * q[3]);
//pitch *= 180.0f / PI;
//yaw *= 180.0f / PI;
//yaw -= 13.8f; // Declination at Danville, California is 13 degrees 48 minutes and 47 seconds on 2014-04-04
//roll *= 180.0f / PI;
// printf("Yaw, Pitch, Roll: %f %f %f\n\r", yaw, pitch, roll);
// printf("average rate = %f\n\r", (float) sumCount/sum);
// sprintf(buffer, "YPR: %f %f %f", yaw, pitch, roll);
// lcd.printString(buffer, 0, 4);
// sprintf(buffer, "rate = %f", (float) sumCount/sum);
// lcd.printString(buffer, 0, 5);
//myled= !myled;
// count = t.read_ms();
// if(count > 1<<21) {
// t.start(); // start the timer over again if ~30 minutes has passed
// count = 0;
// deltat= 0;
// lastUpdate = t.read_us();
// }
// sum = 0;
// sumCount = 0;
//}
}
}
|
C
|
#include <fs/myfs/file.h>
#include <fs/myfs/inode.h>
#include <device/ata.h>
#include <thread/thread.h>
#include <fs/myfs/fs_types.h>
#include <fs/myfs/dir.h>
#include <fs/myfs/utils.h>
#include <mm/kvmm.h>
#include <string.h>
#include <thread/process.h>
#include <kprintf.h>
#include <common/utils.h>
static file_t file_table[MAX_FILE_OPEN];
int file_table_get_free_slot() {
for (int i = 0; i < MAX_FILE_OPEN; i++) {
if (file_table[i].im_inode == NULL) {
return i;
}
}
return -1;
}
void file_table_reclaim(int gfd) {
file_table[gfd].im_inode = NULL;
}
/**
* @brief install the global fd into task's own fd_table
* @return private fd
*/
int install_global_fd(int gfd) {
task_t *task = get_current_thread();
ASSERT(task->fd_table != NULL);
for (int i = 3; i < NR_OPEN; i++) {
if (task->fd_table[i] == -1) {
task->fd_table[i] = gfd;
return i;
}
}
return -1;
}
void task_reclaim_fd(int lfd) {
task_t *task = get_current_thread();
ASSERT(task->fd_table != NULL);
task->fd_table[lfd] = -1;
}
int file_create(
partition_t *part, /* dir_t *pdir, */ im_inode_t *pdir,
const char *filename, uint32_t flags,
void *io_buf
) {
ASSERT(strlen(filename) <= MAX_FILE_NAME_LENGTH);
int rollback = -1, err = FSERR_NOERR;
// alloc in memory inode struct
im_inode_t *file_im_ino = kmalloc(sizeof(im_inode_t));
if (file_im_ino == NULL) {
err = -FSERR_NOMEM;
rollback = 0;
goto __fail__;
}
// alloc an inode
int file_ino = inode_alloc(part);
if (file_ino == -1) {
err = -FSERR_NOINODE;
rollback = 0;
goto __fail__;
}
im_inode_init(file_im_ino, file_ino);
// alloc a global fd
int file_gfd = file_table_get_free_slot();
if (file_gfd == -1) {
err = -FSERR_NOGLOFD;
rollback = 1;
goto __fail__;
}
file_table[file_gfd].file_flags = flags;
file_table[file_gfd].file_pos = 0;
file_table[file_gfd].im_inode = file_im_ino;
// write dir entry
dir_entry_t dir_ent;
create_dir_entry(filename, file_ino, FT_REGULAR, &dir_ent);
err = write_dir_entry(part, pdir, &dir_ent, io_buf);
if (err != FSERR_NOERR) {
rollback = 2;
goto __fail__;
}
int file_lfd = install_global_fd(file_gfd);
if (file_lfd == -1) {
err = -FSERR_NOLOCFD;
rollback = 2;
goto __fail__;
}
// sync inode bitmap
inode_btmp_sync(part, file_ino);
// sync parent inode
inode_sync(part, pdir, io_buf);
// sync file inode
inode_sync(part, file_im_ino, io_buf);
// add file inode to cache
__list_push_front(&(part->open_inodes), file_im_ino, i_tag);
return file_lfd;
__fail__:
ASSERT(err != FSERR_NOERR);
ASSERT(rollback == 2 || rollback == 1 || rollback == 0);
switch (rollback) {
case 2:
file_table_reclaim(file_gfd);
case 1:
inode_reclaim(part, file_ino);
case 0:
kfree(file_im_ino);
}
return err;
}
int file_open(partition_t *part, int i_no, uint32_t flags, file_type_e ft) {
int file_gfd = file_table_get_free_slot();
if (file_gfd == -1) {
return -FSERR_NOGLOFD;
}
int fd = install_global_fd(file_gfd);
if (fd == -1) {
file_table_reclaim(file_gfd);
return -FSERR_NOLOCFD;
}
im_inode_t *file_im = inode_open(part, i_no);
if (file_im == NULL) {
file_table_reclaim(file_gfd);
task_reclaim_fd(fd);
return -FSERR_NOMEM;
}
ASSERT(i_no == file_im->inode.i_no);
file_table[file_gfd].file_flags = flags;
file_table[file_gfd].file_pos = 0;
file_table[file_gfd].im_inode = file_im;
file_table[file_gfd].file_tp = ft;
// if write, check write_deny flag
if (flags & O_WRONLY || flags & O_RDWR) {
// INT_STATUS old_status = disable_int();
if (file_im->write_deny) {
// set_int_status(old_status);
inode_close(file_im);
file_table_reclaim(file_gfd);
task_reclaim_fd(fd);
return -FSERR_EXCWRITE;
} else {
file_im->write_deny = True;
// set_int_status(old_status);
}
}
return fd;
}
file_t *lfd2file(int local_fd) {
kprintf(KPL_DEBUG, "lfd2file: fd=%d\n", local_fd);
if (local_fd < 0 || local_fd >= NR_OPEN) {
return NULL;
}
int *fd_table = get_current_thread()->fd_table;
ASSERT(fd_table != NULL);
int gfd = fd_table[local_fd];
if (gfd == -1) {
return NULL;
}
ASSERT(gfd >= 0 && gfd < MAX_FILE_OPEN);
file_t *file = &(file_table[gfd]);
ASSERT(file->im_inode != NULL);
return file;
}
int file_close(int local_fd) {
// if (local_fd < 0 || local_fd >= NR_OPEN) {
// return -FSERR_BADFD;
// }
// int *fd_table = get_current_thread()->fd_table;
// ASSERT(fd_table != NULL);
// int gfd = fd_table[local_fd];
// // reclaim local_fd
// fd_table[local_fd] = -1;
// if (gfd == -1) {
// return -FSERR_BADFD;
// }
// ASSERT(gfd >= 0 && gfd < MAX_FILE_OPEN);
// file_t *file = &(file_table[gfd]);
// ASSERT(file->im_inode != NULL);
file_t *file = lfd2file(local_fd);
if (file == NULL) {
return -FSERR_BADFD;
}
// after passing check of lfd2file, the following line is safe
get_current_thread()->fd_table[local_fd] = -1;
inode_close(file->im_inode);
file->im_inode = NULL;
return FSERR_NOERR;
}
int file_read(
partition_t *part, file_t *file, void *buffer, size_t count
) {
// file must be FT_REGULAR and flags must not contain O_WRONLY
ASSERT(file->im_inode != NULL && file->file_tp == FT_REGULAR);
ASSERT(!(file->file_flags & O_WRONLY));
if (count == 0 || file->file_pos >= file->im_inode->inode.i_size) {
return 0;
}
void *io_buf = kmalloc(BLOCK_SIZE);
if (io_buf == NULL) {
return -FSERR_NOMEM;
}
count = MIN(count, file->im_inode->inode.i_size - file->file_pos);
ASSERT(count > 0);
// we need to read count bytes starting form file_pos
// and store them in the buffer
int *blks = file->im_inode->inode.i_blocks;
int bytes_read = 0;
while (bytes_read < count) {
int blk_no = file->file_pos / BLOCK_SIZE;
ASSERT(blk_no < 12 && blks[blk_no] != 0);
int blk_off = file->file_pos % BLOCK_SIZE;
int num_bytes = BLOCK_SIZE - blk_off;
num_bytes = MIN(num_bytes, count - bytes_read);
ata_read(part->my_disk, blks[blk_no], io_buf, 1);
memcpy(io_buf + blk_off, buffer + bytes_read, num_bytes);
bytes_read += num_bytes;
file->file_pos += num_bytes;
}
ASSERT(bytes_read == count);
kfree(io_buf);
ASSERT(file->file_flags <= file->im_inode->inode.i_size);
return count;
}
int read_dirent(
partition_t *part, file_t *dfile, void *buffer, size_t count
) {
ASSERT(dfile->file_tp == FT_DIRECTORY);
ASSERT(dfile->file_flags == O_RDONLY);
if (count == 0 || dfile->file_pos >= dfile->im_inode->inode.i_size) {
return 0;
}
int dent_size = part->sb->dir_entry_size;
int blk_size = BLOCK_SIZE - BLOCK_SIZE % dent_size;
ASSERT((dfile->im_inode->inode.i_size - dfile->file_pos) % dent_size == 0);
count = MIN(
count - count % dent_size,
dfile->im_inode->inode.i_size - dfile->file_pos
);
ASSERT(count % dent_size == 0);
kprintf(KPL_DEBUG, "dir_file_read: count = %d\n", count);
if (count == 0) {
return 0;
}
// we need to read count bytes starting form file_pos
// and store them in the buffer
void *io_buf = kmalloc(BLOCK_SIZE);
if (io_buf == NULL) {
return -FSERR_NOMEM;
}
int *blks = dfile->im_inode->inode.i_blocks;
uint32_t pos = dfile->file_pos;
int bytes_read = 0;
while (bytes_read < count) {
int blk_no = pos / blk_size;
// only consider the first 12 direct data blks for now
ASSERT(blk_no < 12 && blks[blk_no] != 0);
int blk_off = pos % blk_size;
int num_bytes = blk_size - blk_off;
num_bytes = MIN(num_bytes, count - bytes_read);
ata_read(part->my_disk, blks[blk_no], io_buf, 1);
memcpy(io_buf + blk_off, buffer + bytes_read, num_bytes);
bytes_read += num_bytes;
pos += bytes_read;
}
ASSERT(bytes_read == count);
kfree(io_buf);
dfile->file_pos += count;
ASSERT(pos == dfile->file_pos);
ASSERT(dfile->file_flags <= dfile->im_inode->inode.i_size);
return count;
}
int file_write(
partition_t *part, file_t *file, void *buffer, size_t count
) {
ASSERT(file->im_inode != NULL && file->file_tp == FT_REGULAR);
ASSERT(file->file_flags & (O_WRONLY | O_RDWR));
// there are still <free_bytes> free space of this file
int free_bytes = 12 * BLOCK_SIZE - file->file_pos;
int err = FSERR_NOERR;
if (count == 0 || free_bytes == 0) {
return 0;
}
void *io_buf = kmalloc(BLOCK_SIZE);
if (io_buf == NULL) {
err = -FSERR_NOMEM;
return -FSERR_NOMEM;
}
int *blks = file->im_inode->inode.i_blocks;
int bytes_written = 0;
while (bytes_written < count && free_bytes > 0) {
int blk_no = file->file_pos / BLOCK_SIZE;
int blk_off = file->file_pos % BLOCK_SIZE;
// zero-out the io_buffer
memset(io_buf, 0, BLOCK_SIZE);
bool_t new_blk = False;
if (blks[blk_no] == 0) {
ASSERT(blk_off == 0);
int blk_idx = block_alloc(part);
if (blk_idx == -1) {
err = -FSERR_NOBLOCK;
break;
}
new_blk = True;
block_btmp_sync(part, blk_idx);
blks[blk_no] = part->start_lba + blk_idx;
file->im_inode->dirty = True;
}
uint32_t lba = blks[blk_no];
ASSERT(lba != 0);
int bytes_to_write = MIN(count - bytes_written, BLOCK_SIZE - blk_off);
ASSERT(free_bytes >= bytes_to_write);
if (new_blk) {
memcpy(buffer, io_buf, bytes_to_write);
} else {
ata_read(part->my_disk, lba, io_buf, 1);
memcpy(buffer, io_buf + blk_off, bytes_to_write);
}
ata_write(part->my_disk, lba, io_buf, 1);
free_bytes -= bytes_to_write;
bytes_written += bytes_to_write;
file->file_pos += bytes_to_write;
}
ASSERT(bytes_written <= count);
ASSERT(free_bytes >= 0);
ASSERT(file->file_pos <= 12 * BLOCK_SIZE);
// update file's inode i_size if necessary
if (file->file_pos > file->im_inode->inode.i_size) {
file->im_inode->inode.i_size = file->file_pos;
file->im_inode->dirty = True;
}
// sync file inode if necessary
if (file->im_inode->dirty) {
inode_sync(part, file->im_inode, io_buf);
file->im_inode->dirty = False;
}
kfree(io_buf);
return bytes_written;
}
int file_truncate(file_t *file, size_t length) {
ASSERT(file->im_inode != NULL && file->file_tp == FT_REGULAR);
}
/************* some debug utilities *************/
void print_file_table() {
INT_STATUS old_status = disable_int();
kprintf(KPL_DEBUG, "\nfile_table: [");
for (int i = 0; i < MAX_FILE_OPEN; i++) {
file_t *file = &(file_table[i]);
if (file->im_inode == NULL) {
continue;
}
kprintf(
KPL_DEBUG,
"{(%d)inode={ino=%d,iop=%d,isz=%d},pos=%d,flags=%x,ft=%d}",
i, file->im_inode->inode.i_no, file->im_inode->i_open_times,
file->im_inode->inode.i_size,
file->file_pos, file->file_flags, file->file_tp
);
}
kprintf(KPL_DEBUG, "]\n");
set_int_status(old_status);
}
|
C
|
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>
#include <stdint.h>
#include "file.h"
#include <sys/stat.h>
#include <sys/mman.h>
#include <fcntl.h>
#include <string.h>
void make_file(char* filename, int amount){
FILE* file = fopen(filename,"w");
srand(time(NULL));
for(int i = 0; i < amount; i++) {
int r = rand() % 100;
fprintf(file,"%d ",r);
}
fclose(file);
}
int file_init_array(char* filename, int* array, int array_length){
if(array == NULL){
return -1;
}
FILE* file = fopen(filename, "r");
if (file == NULL) {
return -1;
}
for (int i = 0; i < array_length; i++) {
int number;
if (fscanf(file, "%d", &number) == 1) {
array[i] = number;
} else {
fclose(file);
return -1;
}
}
fclose(file);
return 0;
}
//Попробовал сделать mmap (Не работает)
int file_init_array_mmap(char* filename, int* array, int array_length){
if(array == NULL){
return -1;
}
int file = open(filename, O_RDONLY);
if (file < 0) {
return -1;
}
struct stat size;
stat(filename, &size);
char *file_mmap = mmap(NULL, size.st_size, PROT_READ, MAP_SHARED, file, 0);
if (file_mmap == MAP_FAILED) {
return -1;
}
int number = 0;
for(int i = 0;i < array_length; i++){
number = sscanf(file_mmap,"%d",&number);
array[i] = number;
if(i % 1000000 == 0){
printf("i is:%d", i);
}
file_mmap = strchr(file_mmap,' ');
}
munmap(file_mmap,size.st_size);
return 0;
}
|
C
|
int substr( char dst[], char src[], int start, int len):
{
int dst_index, src_index;
dst_index = 0;
if(start >= 0 && len > 0) {
for( src_index = 0;
src_index < start && src[src_index] != '\0';
src_index++)
while ( len > 0 && src[src_index] != '\0') {
dst[dst_index] = src[src_index];
dst_index++;
src_index++;
len --;
}
}
dst[dst_index] = '\0';
return dst_index;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <error.h>
#include <netinet/in.h>
#include <string.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <pthread.h>
#include <sys/ipc.h>
#include <sys/sem.h>
#include <sys/shm.h>
int semid;
int shmid;
union semun{
int val; /* value for SETVAL */
struct semid_ds *buf; /* buffer for IPC_STAT & IPC_SET */
ushort *array; /* array for GETALL & SETALL */
struct seminfo *__buf; /* buffer for IPC_INFO */
void *__pad;
};
typedef struct{//colocamos un espacio de mas por le terminador de cadena
int flag;
char compania[11];
char operacion[160];
char usuario[20];
}Zona;
Zona *Memoria;
void init_semaphore(unsigned short int* sem_array){
union semun semopts;
semopts.array = sem_array;
if(semctl(semid,0,SETALL,semopts) == -1){
perror("semctl");
exit(1);
}
}
int CreaLigaMemoria(key_t key){
//Verifica si el segmento de memoria existe (IPC_CREAT|IPC_EXCL)
if((shmid = shmget(key,sizeof(Zona),IPC_CREAT|IPC_EXCL|0666)) == -1){
/* El segmento existe - abrir como cliente */
if((shmid = shmget(key,sizeof(Zona),0)) == -1){
perror("shmget");
exit(1);
}
else{
printf("Yo soy el productor y me ligue a la memoria\n");
}
}
else{
printf("Yo soy el productor y cree la memoria\n");
}
//se ata a la zona de memoria creada
if((Memoria = (Zona*)shmat(shmid,(Zona*) 0,0)) == (void *)-1) {
perror("shmat");
exit(1);
}
//printf("%s\n",Memoria); //lee en memoria compartida
return shmid; //regresa el identificador de la memoria
}
void *llamadas(void *argv){
int idUsu = *((int*)argv);
//xprintf("val 2N = %d\n",idUsu);
if(idUsu == 0){
printf("Yo soy la llamada que hace pit\n");
}else{
printf("Yo soy la llamada que hace Hug\n");
}
}
void *mensajes(void *argv){
int idUsu = *((int*)argv);
//printf("val 2N = %d\n",idUsu);
if(idUsu == 0){
printf("Yo soy el mensaje que hace pit\n");
}else{
printf("Yo soy el mensaje que hace Hug\n");
}
}
//funcion que realizará el productor
void *createProductors(void *argv){
int idUsuario = *((int*)argv);
//printf("val 1N = %d\n",idUsuario);
pthread_t operaciones[2];
pthread_create(&operaciones[0],NULL,llamadas,(void *)&idUsuario);
pthread_create(&operaciones[1],NULL,mensajes,(void *)&idUsuario);
for(int i=0;i<2;++i){
pthread_join(operaciones[i],NULL);
}
}
int main(int argc, char const *argv[])
{
//creacion de los semaforos
key_t key;//lave para los semaforos
unsigned short int sem_array[20]={1,1,1,1,1,0,0,0,0,0,1,1,1,1,1,0,0,0,0,0};
if((key = ftok("/bin/ls",'k'))==-1){
perror("error en la creacion de la memoria compartida");// creacion de una llave unica ligada al archivo especificado
exit(1);
}
//creacion de un set de 20 semaforos
if((semid = semget(key,20,0666 |IPC_CREAT | IPC_EXCL))==-1){//arreglo de 20 semáforos
if((semid = semget(key,10,0666))==-1){
perror("erorr en la creacion de los semaforos de las llamadas");
exit(1);
}else
{
printf("Productor: (llamadas) Me ligue exitosamente a los semaforos\n");
}
}else
{
//creamos los semaforos y luego los inicializamos
printf("Productor: (llamadas) Cree exitosamente los semaforos\n");
init_semaphore(sem_array);
}
//creacion de la zona de memoria
if((shmid = CreaLigaMemoria(key))== -1){
perror("Error en la creacion de la memoria");
exit(1);
}
//creacion de los hilos productores de llamadas y mensajes pit y hugo
pthread_t productores[2];
int param[2];
for(int i=0;i<2;++i){
param[i] = i;
pthread_create(&productores[i],NULL,createProductors,(void *)¶m[i]);
}
for(int i=0;i<2;++i){
pthread_join(productores[i],NULL);
}
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
typedef double real;
void vector_project(real *input, real angle, real *output){
angle = angle*3.1415956/180.;
output[0]=input[0]*cos(angle)+input[1]*sin(angle);
output[1]=-input[0]*sin(angle)+input[1]*cos(angle);
}
int main(){
real output[2];
real input[2] = {-1,1};
vector_project(input,45.,output);
printf("%f %f\n",output[0], output[1]);
return 0;
}
|
C
|
#include "tipo.h"
#ifndef PILHA_H
#define PILHA_H
#define STACK_NULL_PTR -5
#define STACK_EMPTY -4
typedef struct stack stack;
/**
* Cria uma pilha inicialmente vazia e retorna o endereço de memória alocado para a pilha.
* @return: um ponteiro para pilha.
*/
stack *stack_create(void);
/**
* Libera o espaço em memória ocupado pela pilha e destroi todos os elementos guardados nela.
* @param stck: ponteiro para pilha em memória.
*/
void stack_free(stack *stck);
/**
* Consulta o elemento do topo da pilha sem removê-lo.
* @param stck: ponteiro para pilha;
* @param elemento: um endereço de memória para armazenar o elemento consultado.
* @return: codigo de erro da funcao.
*/
int stack_peek(stack *stck, item *elemento);
/**
* Remove um elemento do topo da pilha.
* @param stck: ponteiro para pilha;
* @param elemento: um endereço de memória para armazenar o elemento removido da pilha.
* @return: codigo de erro da função.
*/
int stack_pop(stack *stck, item *elemento);
/**
* Insere um elemento no topo da pilha.
* @param stck: ponteiro para pilha;
* @param elemento: um elemento qualquer;
* @return: codigo de erro da funcao.
*/
int stack_push(stack *stck, item elemento);
/**
* Informa o tamanho da pilha.
* @param stck: ponteiro para pilha;
* @param size: endereço de memória onde será armazenado o tamanho da pilha.
* @return: codigo de erro da funcao.
*/
int stack_size(stack *stck, int *size);
#endif // PILHA_H
|
C
|
//
// Created by pioter on 20.05.2020.
//
#ifndef BOMBERMAN_CLIENT_ENEMY_H
#define BOMBERMAN_CLIENT_ENEMY_H
#include <SDL2/SDL.h>
#include "board.h"
#include "bomb.h"
#include <pthread.h>
typedef struct Enemy{
SDL_Texture *texture; // enemie's texture
SDL_Rect image; // bounding box of enemy
int x; // current coordinate x
int y; // current coordinate y
int nextX; // next coordinate x given by server
int nextY; // next coordinate y given by server
int stepCounter; // step counter for smoothing
int stepX; // next step coordinate x
int stepY; // next step coordinate y
int bombId; // assigned bomb
char name[100]; // name of enemy
int isAlive; // status of enemy
} Enemy;
Enemy** enemies; // handle to array of enemies
pthread_mutex_t enemy_lock; // enemy mutex
/**
* Allocates memory for enemies and initialises enemy mutex.
* @param count - amount of enemies to allocate for
*/
void initAllEnemies(int count);
/**
* Initialises enemy structure, sets starting position and assigns bomb.
* @param enemy - enemy to initialise
* @param board - board handle
* @param player_number - determines starting pos
* @param startX - starting coordinate x (on reconnect after restart)
* @param startY - starting coordinate y (on reconnect after restart)
* @param name - name of enemy
* @param bombId - number of assigned bomb
*/
void initEnemy(Enemy* enemy, Board* board, int player_number, int startX, int startY, char* name, int bombId);
/**
* Loads texture resource.
* @param renderer - renderer handle
* @param enemy - enemy to load textures for
* @param player_number - dictates look change (only 1 look implemented now)
*/
void loadEnemy(SDL_Renderer *renderer, Enemy *enemy, int player_number);
/**
* Move enemy depending on step coordinates.
* @param enemy - enemy to move
*/
void moveEnemy(Enemy* enemy);
/**
* Checks if any of the enemies are alive.
* @return 0 - all enemies dead; 1 - at least 1 enemy alive
*/
int checkEnemyLives();
/**
* Renders enemy sprite.
* @param enemy - enemy to render
* @param renderer - renderer handle
*/
void renderEnemy(Enemy* enemy, SDL_Renderer* renderer);
/**
* Frees resources for given enemy.
* @param enemy - enemy to clear
*/
void closeEnemy(Enemy* enemy);
/**
* Frees memory allocated for enemies and destroys enemy mutex.
* @param count - amount of enemies
*/
void closeAllEnemies(int count);
#endif //BOMBERMAN_CLIENT_ENEMY_H
|
C
|
#include <stdio.h>
void itoa(int n, char s[]){
int i, sign; //sign: positive or negative number
if((sign = n) < 0)
n = -n;
i = 0;
do{
s[i++] = n%10 + '0'; //'0' show will ascii value of 0(48) then we can add any number to find out their ascii value
}while((n/=10)>0);
if(sign<0)
s[i++] = '-';
s[i] = '\0';
reverse(s);
}
|
C
|
#include "../includes/libshell.h"
int is_symbol(char c)
{
char **symbols;
int i;
i = 0;
symbols = ft_split(SYMBOL_LIST, ':');
while (symbols[i])
{
if (symbols[i][0] == c)
return (1);
i++;
}
return (0);
}
int is_quote(char c, char type)
{
if (c == type)
return (1);
return (0);
}
void p_putchar_str(char **str, char c)
{
char *ptr;
char *tmp;
ptr = *str;
tmp = NULL;
if (!ptr)
{
ptr = ft_strdup("c");
if (!ptr)
return ;
ptr[0] = c;
*str = ptr;
return ;
}
tmp = ft_strjoin(*str, "c");
tmp[ft_strlen(tmp) - 1] = c;
*str = tmp;
}
t_cut_cmd *fill(char *elem, t_TOKEN TOKEN)
{
t_cut_cmd *ret;
int i;
i = -1;
if (!(ret = (t_cut_cmd*)gc_malloc(sizeof(t_cut_cmd))))
return (0);
ret->is_last = 0;
ret->wild_card_type = -1;
ret->tail_wild_card = NULL;
ret->head_wild_card = NULL;
ret->elem = ft_strdup(elem);
ret->TOKEN = TOKEN;
ret->n = NULL;
ret->p = NULL;
ret->fd_flag = 0;
return (ret);
}
int add(t_msh *msh, char *elem, t_TOKEN TOKEN)
{
t_cut_cmd *ret;
ret = fill(elem, TOKEN);
if (!msh->tools->head)
{
msh->tools->head = ret;
msh->tools->tail = msh->tools->head;
return (1);
}
ret->n = msh->tools->head;
msh->tools->head->p = ret;
msh->tools->head = ret;
return (1);
}
|
C
|
#ifndef _LINKED_STRUCTURES_BASE_H_
#define _LINKED_STRUCTURES_BASE_H_
#define LINKED_MALLOC malloc
#define LINKED_FREE free
#include <stdio.h>
#include <string.h>
#include <inttypes.h>
#include <stdlib.h>
typedef struct Object_vtable Object_vtable;
typedef struct Comparable_vtable Comparable_vtable;
typedef struct Comparator_vtable Comparator_vtable;
#undef TRUE
#undef FALSE
typedef enum BOOLEAN { FALSE=0, TRUE=-1, MAYBE=-2 } BOOLEAN;
typedef struct Object {
const Object_vtable *method;//also can be used as a key for the function type
} Object;
typedef uint64_t hash_t;
struct Object_vtable {//the most basic form of an object
hash_t (*hash)(const Object *self);
char* (*hashable)(const Object *self, size_t *size); //part of object that is hashable
void (*destroy)(const Object *self); //how to destroy our data, NOT deallocate!
Object* (*copy)(const Object *self, void* buffer); //return a copy of the information
BOOLEAN (*equals)(const Object *self, const void* oth);
size_t size;
};
struct Comparable_vtable {//an interface for comparable objects
long (*compare)(const void* self, const void* oth); //how to compare (NULL if undesired)
};
typedef struct Comparator {
const Comparator_vtable *method;
} Comparator;
struct Comparator_vtable {
long (*compare)(const void* self, const void* oth1, const void* oth2);
};
struct Iterator_vtable {
Object_vtable parent;
void* (*next)(const Object *self);
};
#define CALL_POSSIBLE(OBJ, METHOD) (OBJ && OBJ->method && OBJ->method->METHOD)
#define CALL(OBJ, METHOD, ELSE, ...) (CALL_POSSIBLE(OBJ, METHOD)?(OBJ->method->METHOD((void*)OBJ, ## __VA_ARGS__)):(ELSE))
#define CALL_VOID(OBJ, METHOD, ...) do{ if(CALL_POSSIBLE(OBJ, METHOD)) OBJ->method->METHOD ((void*)OBJ, ## __VA_ARGS__); } while(0)
typedef BOOLEAN (*lMapFunc)(Object *data, const void *aux/*auxilarly data (constant between calls)*/, void* node); //a mapping function
typedef BOOLEAN (*lTransFunc)(Object **data, const void* aux, const void* node);/*in-place data transformation, should always return TRUE as FALSE means stop*/
typedef enum TRAVERSAL_STRATEGY {
BREADTH_FIRST=0,
DEPTH_FIRST_PRE=1,
DEPTH_FIRST=2,
DEPTH_FIRST_IN=2,
DEPTH_FIRST_POST=3,
} TRAVERSAL_STRATEGY;
#endif
|
C
|
#include "symboltable.h"
#include "syntaxtree.h"
#include "y.tab.h"
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
Gsymbol *head = NULL;
Gsymbol *tail = NULL;
Lsymbol *LsymbolHead = NULL;
Lsymbol *LsymbolTail = NULL;
paramStruct* paramHead = NULL; //for parameters
paramStruct* paramTail = NULL;
int nextBindingAddr = 4096;
int funcLabel = 0;
int nextLocalBinding = 0;
int nextParamBinding = -3;
void printSymbolTable()
{
Gsymbol*temp = head;
while(temp!=NULL)
{
puts(temp->name);
if(temp->type)
{
printf("%s ", temp->type->name);
}
else
{
printf("Type Error in GSymbolTable\n"); exit(1);
}
printf("\n%d %d \n", temp->size, temp->binding);
printf("Func label: f%d\n",temp->flabel);
printf("Parameters : ");
if(temp->paramlist!=NULL)
{
paramStruct* tempptr = temp->paramlist;
while(tempptr != NULL)
{
if(tempptr->paramType!=NULL)
{
printf("%s ",tempptr->paramType->name);
}
else
{
printf("ERR TYPE");
}
printf("%s ",tempptr->paramName);
tempptr = tempptr->next;
}
printf("\n");
}
printf("\n\n");
temp=temp->next;
}
}
paramStruct* createParamNode(char* name, Typetable* type)
{
paramStruct* newEntry = (paramStruct*)malloc(sizeof(paramStruct));
if(newEntry == NULL)
{
printf("Error in Param node creation"); exit(0);
}
newEntry->paramName = name;
newEntry->paramType = type;
newEntry->next = NULL;
return newEntry;
}
void appendParamNode(char* name, Typetable* type)
{
paramStruct* temp = createParamNode(name, type);
if(paramHead == NULL)
{
paramHead = temp;
paramTail = temp;
}
else
{
paramTail->next = temp;
paramTail = temp;
}
}
Gsymbol* Glookup(char* name)
{
Gsymbol* temp = head;
while(temp!=NULL)
{
if(strcmp(temp->name, name)==0)
{
return temp;
}
temp=temp->next;
}
return NULL;
}
void endIfRedeclared(char* name)
{
Gsymbol* temp = head;
while(temp)
{
if(strcmp(name, temp->name)==0)
{
printf("ERROR : Multiple declaration of global variable\n");
exit(1);
}
temp=temp->next;
}
}
void endIfRedeclaredLocally(char* name)
{
Lsymbol* temp = LsymbolHead;
while(temp)
{
if(strcmp(name, temp->name)==0)
{
printf("ERROR : Multiple declaration of local variable\n");
exit(1);
}
temp=temp->next;
}
}
void resetParamHeadTail()
{
paramHead = NULL;
paramTail = NULL;
}
paramStruct* fetchParamHead()
{
return paramHead;
}
Lsymbol* fetchLsymbolHead()
{
return LsymbolHead;
}
void Ginstall(char* name, Typetable* type, int size, int colSize, int flabel, struct paramStruct* paramlist) // Creates a symbol table entry.
{
endIfRedeclared(name);
if(nextBindingAddr>5119)
{
printf("ERROR: STACK OVERFLOW\n");
exit(1);
}
Gsymbol* newEntry = (Gsymbol*) malloc(sizeof(Gsymbol));
newEntry->name = (char*) malloc(strlen(name) + 1);
strcpy(newEntry->name, name);
newEntry->type = type;
newEntry->size = size;
newEntry->binding = nextBindingAddr;
newEntry->colSize = colSize;
nextBindingAddr += size;
newEntry->flabel = flabel;
newEntry->paramlist = paramlist;
newEntry->next = NULL;
if(head == NULL)
{
head = newEntry;
tail = newEntry;
}
else
{
tail->next = newEntry;
tail = newEntry;
}
}
void GinstallFunc(char* name, Typetable* type, paramStruct* paramlist)
{
Ginstall(name,type,0,0,funcLabel,paramlist);
funcLabel++;
}
void GinstallVar(char* name, Typetable* type, int size, int colSize)
{
Ginstall(name,type,size,colSize,-1,NULL);
}
void Linstall(char* name, struct Typetable* type, int appendToBeg, int binding)
{
endIfRedeclaredLocally(name);
Lsymbol* newEntry = (Lsymbol*)malloc(sizeof(Lsymbol));
newEntry->name = (char*)malloc(strlen(name)+1);
strcpy(newEntry->name, name);
newEntry->type = type;
newEntry->binding = binding;
newEntry->next = NULL;
if(LsymbolHead == NULL)
{
LsymbolHead = newEntry;
LsymbolTail = newEntry;
}
else if(appendToBeg == 1)
{
newEntry->next = LsymbolHead;
LsymbolHead = newEntry;
}
else //addToTheEnd
{
LsymbolTail->next = newEntry;
LsymbolTail = newEntry;
}
}
void LinstallVar(char* name, Typetable* type)
{
Linstall(name, type, 0, ++nextLocalBinding);
}
void LinstallParameters(paramStruct* paramlist)
{
if(paramlist != NULL)
{
Linstall(paramlist->paramName, paramlist->paramType,1,nextParamBinding--);
LinstallParameters(paramlist->next);
}
}
void freeLsymbolTable()
{
//free the entire space?
LsymbolHead = NULL;
LsymbolTail = NULL;
nextLocalBinding = 0;
nextParamBinding = -3;
}
Lsymbol* Llookup(char* name)
{
Lsymbol* temp = LsymbolHead;
while(temp!=NULL)
{
if(strcmp(temp->name, name)==0)
{
return temp;
}
temp=temp->next;
}
return NULL;
}
void printLocalSymbolTable()
{
Lsymbol*temp = LsymbolHead;
while(temp!=NULL)
{
puts(temp->name);
if(temp->type)
{
printf("%s ",temp->type->name);
}
else
{
printf("ERRor in Type in LSymbolTable\n"); exit(1);
}
printf("\n %d \n", temp->binding);
temp=temp->next;
}
}
|
C
|
/** This function will trim a string by eliminating the spaces from
* the start and the end of the string.
*/
void trim(char *s)
{
int origLen, len;
char *sCopy;
int start, end;
origLen = strlen(s);
sCopy = strdup(s);
if (sCopy != NULL) {
len = strlen(sCopy);
for (start=0; start= 0; end--) {
if (!isspace(sCopy[end])) {
break;
}
}
sCopy[end+1] = '\0';
strcpy (s, &(sCopy[start]));
free(sCopy);
}
}
int main()
{
char inputString[64] = " Spaces at start and end ";
printf ("%s\n",inputString);
trim(inputString);
printf ("%s\n",inputString);
}
|
C
|
/*Author: Kartik Jagdale */
#include<stdio.h>
#define MUL(a, b) ((a)*(b)) /*Putting everything in Paraenthesis is is good practice */
#define MAX(a, b) ((a)>(b) ? (a) : (b))
int main(int argc, char**argv){
int a = 10;
int b = 20;
printf("A value is %d, B Value is %d and A * B is %d\n",a, b, MUL(a, b) );
printf("Max of %d and %d is %d\n", a, b, MAX(a, b));
system("pause");
return 0;
}
|
C
|
#include <stdlib.h>
#include <assert.h>
#include <string.h>
#include "dfa.h"
#include "mpool.h"
#include "node.h"
dfa_trie_t *dfa_trie_create()
{
dfa_trie_t *trie = (dfa_trie_t *) malloc(sizeof(dfa_trie_t));
if (NULL == trie)
return NULL;
trie->mp = mpool_create(0);
trie->root = dfa_node_create(trie->mp);
return trie;
}
int dfa_trie_add(dfa_trie_t *trie, char *string, void *argument)
{
assert(trie != NULL);
assert(string != NULL);
char *p = string;
struct rb_root *root = &trie->root->root;
dfa_node_t *n, *new;
while (*p != '\0') {
n = dfa_node_find_child(root, *p);
if (!n) { // insert new node
new = dfa_node_create(trie->mp);
dfa_node_set_chr(new, *p);
dfa_node_insert(root, new);
root = &new->root;
} else {
root = &n->root;
}
p++;
}
n = container_of(root, struct dfa_node, root);
dfa_node_set_final(n, 1);
dfa_pattern_t *patt = mpool_malloc(trie->mp, sizeof(dfa_pattern_t));
patt->string = mpool_strdup(trie->mp, string);
patt->argument = argument;
dfa_node_set_pattern(n, patt);
return 0;
}
static int dfa_trie_find_next_bs(dfa_trie_t *trie, char *text,
enum dfa_match_type mt, dfa_node_t **nnode)
{
int i, len = strlen(text);
int match_len = 0, flag = 0;
dfa_node_t *node = NULL;
struct rb_root *root = &trie->root->root;
for (i = 0; i < len; i++) {
char chr = text[i];
node = dfa_node_find_child(root, chr);
if (!node) { // does not exists
break;
}
// found
match_len++;
if (dfa_node_is_final(node)) {
flag = 1;
*nnode = node;
if (mt == MATCH_TYPE_MIN) {
break;
}
}
root = &node->root;
}
if (!flag) {
match_len = 0;
}
return match_len;
}
int dfa_trie_find_next(dfa_trie_t *trie, char *text, dfa_match_t *match)
{
if (!trie || !text || !match)
return -1;
int len = strlen(text), ml = 0;
dfa_node_t *node;
while (match->pos < len) {
if ((ml = dfa_trie_find_next_bs(trie, text + match->pos,
match->mt, &node)) > 0) {
match->size = ml;
match->pos++;
match->pattern = node->patt;
return 1;
}
match->pos++;
}
return 0;
}
int dfa_trie_match(dfa_trie_t *trie, char *text, enum dfa_match_type mt, dfa_match_cb cb)
{
dfa_match_t match;
match = (mt == MATCH_TYPE_MIN) ? MATCH_INIT_MIN : MATCH_INIT_MAX;
int count = 0;
while (dfa_trie_find_next(trie, text, &match)) {
cb(match.pattern->string, match.pattern->argument);
count++;
}
return count;
}
void dfa_trie_release(dfa_trie_t *trie)
{
mpool_free(trie->mp);
free(trie);
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.