language
large_stringclasses 1
value | text
stringlengths 9
2.95M
|
---|---|
C
|
#include "holberton.h"
/**
* _strchr - locate character in string
* @s: a pointer to the string to search
* @c: the character to search for
*
* Return: If a match is found, return a pointer to it.
* Otherwise, return NULL.
*/
char *_strchr(char *s, char c)
{
for ( ; *s; ++s)
{
if (*s == c)
return (s);
}
if (*s == c)
return (s);
return (NULL);
}
|
C
|
#define TIME struct Time
#define TIME_GET_SECOND(time) ((time).second)
#define TIME_GET_DECISECOND(time) ((time).decisecond)
#define TIME_GET_MINUTE(time) ((time).minute)
#define TIME_GET_HOUR(time) ((time).hour)
#define TIME_SET_SECOND(time, value) ((time).second = (value))
#define TIME_SET_DECISECOND(time, value) ((time).decisecond = (value))
#define TIME_SET_MINUTE(time, value) ((time).minute = (value))
#define TIME_SET_HOUR(time, value) ((time).hour = (value))
struct Time
{
char decisecond;
char second;
char minute;
char hour;
};
void Time_ToString(TIME *time, char hyphen, char hasDeciSecond, char *str);
void Time_Add_1_Decisecond(TIME *time);
void Time_Sub_1_Decisecond(TIME *time);
|
C
|
#define _CRT_SECURE_NO_WARNINGS 1
# include <stdio.h>
# include<math.h>
int main()
{
for (int i = 1; i<10; i++)
{
for (int j = 1; j <= i; j++)
{
int k = i*j;
printf("%d*%d=%d ", i, j, k);
}
printf("\n");
}
return 0;
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* exe_cmd.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: adu-pelo <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2016/03/12 13:42:33 by adu-pelo #+# #+# */
/* Updated: 2016/11/09 12:17:26 by adu-pelo ### ########.fr */
/* */
/* ************************************************************************** */
#include "minishell.h"
static void check_tilde(char **env, char **cmd)
{
int i;
i = -1;
while (cmd[++i])
if (cmd[i][0] == '~')
cmd[i] = add_root_path(env, cmd[i]);
}
char *find_cmdp(char *cmd, char **path)
{
int i;
DIR *dir;
struct dirent *ret;
if (cmd && path && *path)
{
i = -1;
while (path[++i])
if ((dir = opendir(path[i])))
{
while ((ret = readdir(dir)))
if (!ft_strcmp(ret->d_name, cmd))
{
closedir(dir);
return (ft_strdup(path[i]));
}
closedir(dir);
}
}
return (NULL);
}
static char *set_tmp(char *cmdp, char *tmp, char **env, char **cmd)
{
tmp = NULL;
check_tilde(env, cmd);
if (cmdp)
tmp = ft_strjoin(cmdp, "/");
else
tmp = ft_strdup("./");
return (tmp);
}
static int exist(char **env, char *cmd)
{
DIR *dir;
char *cur;
struct dirent *ret;
cur = NULL;
cur = get_var_content(env, "PWD=");
if ((dir = opendir(cur)))
{
while ((ret = readdir(dir)))
{
if (!ft_strcmp(cmd, ret->d_name))
return (1);
}
}
return (0);
}
void execute_cmd(char **cmd, char *cmdp, char **env)
{
char *tmp;
pid_t father;
tmp = NULL;
tmp = set_tmp(cmdp, tmp, env, cmd);
if (access(ft_strjoin(tmp, cmd[0]), X_OK) != -1 && ft_strlen(cmd[0]) > 1)
{
father = fork();
if (father > 0)
wait(0);
else if (father == 0)
{
signal(SIGINT, SIG_DFL);
cmdp = ft_strjoin(tmp, cmd[0]);
execve(cmdp, cmd, env);
ft_strdel(&cmdp);
}
else
ft_putendl("cannot fork");
}
else if (access(cmd[0], X_OK) == -1 && exist(env, cmd[0]))
ft_putstrstr_fd(cmd[0], ": Permission denied\n", 2);
else
ft_putendl_fd("command not found", 2);
ft_strdel(&tmp);
}
|
C
|
/*
* Definitions for a doubly linked list.
*/
#include "patricia.h"
#include <stdlib.h>
#ifndef __LIST_H__
#define __LIST_H__
/* List node structure*/
struct list_node
{
struct list_node *next;
struct list_node *prev;
patricia_node_t *patricia_node;
};
typedef struct list_node list_node_t;
/* Function prototypes */
list_node_t *new_node();
patricia_node_t *get_first_node(list_node_t *);
list_node_t *insert(list_node_t *, patricia_node_t *);
patricia_node_t *pop(list_node_t *);
void remove_first_node(list_node_t *);
#endif
|
C
|
/* ====================================================
# Copyright (C)2019 All rights reserved.
#
# Author : Pandora
# Email : [email protected]
# File Name : linked_table.c
# Last Modified : 2019-05-07 19:35
# Describe :
#
# ====================================================*/
#define LINKED
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#include "date_storage.h"
#include "../chapter11/str.h"
int main(void)
{
FILM *head = NULL;
FILM *current, *prev;
char film[30];
puts("Please input film name : ");
while (s_gets(film, 30) && film[0] != '\0')
{
current = (FILM *)malloc(sizeof(FILM) + strlen(film));
assert(current != NULL);
if (head == NULL)
head = current;
else
prev->next = current;
current->next = NULL;
puts("Please input rate : ");
scanf("%u", ¤t->rate);
strcpy(current->title, film);
while (getchar() != '\n') continue;
prev = current;
puts("Please input next film : ");
}
if (head == NULL)
puts("No date !");
else
puts("film list : ");
current = head;
while (current != NULL)
{
printf("film name : %-12s, rate : %u\n",
current->title, current->rate);
current = current->next;
}
current = head;
while (current != NULL)
{
head = current->next;
free(current);
current = head;
}
return 0;
}
|
C
|
#include <stdio.h>
#include <math.h>
int main (){
int a, b ,c, sum, sum2;
printf("Lutfen degerleri girinis : ");
scanf("%d %d %d" ,&a,&b,&c);
sum = (b*b)*c/(3-a);
printf("ilk isleminizin sonucu : %d", sum);
sum2 = (c*c*c)- log(b) + (a*a) / b;
printf("\nikinci isleminizin sonucu : %d", sum2);
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include "gamelib.h"
char titolo[] = "FORSENNAIT";
int main()
{
// inizializza rand
time_t t;
srand((unsigned) time(&t));
// inizializza automaticamente una scacchiera
auto_scacchiera();
// stampa il titolo
stampa_titolo(titolo);
// variabili controllo menu
int scelta_principale;
int stai_in_menu = true;
do{
int spazi = stampa_titolo_menu("Menu principale");
stampa_scelta_menu(spazi, "1. Crea Mappa");
stampa_scelta_menu(spazi, "2. Gioca");
stampa_scelta_menu(spazi, "3. Esci dal gioco");
stampa_prompt();
scanf("%d", &scelta_principale);
while(getchar()!= '\n');
switch(scelta_principale){
case 1:
crea_schacchiera();
break;
case 2:
gioca();
break;
case 3:
stampa_titolo_menu("Esci dal Gioco\n");
stai_in_menu = false;
break;
default:
stampa_centrato("ERRORE: scelta non disponibile");
stampa_centrato("scegli un numero tra 1 e 3");
break;
}
}while(stai_in_menu);
free_scacchiera();
return 0;
}
|
C
|
#include "list.h"
int Listlenght(const Item* i) {
if (ListIsEmpty(i)) {
return 0;
}
Item* tmp = i;
int cont = 0;
while (!ListIsEmpty(tmp)) {
cont++;
tmp = ListGetTail(tmp);
}
ListDelete(tmp);
return cont;
}
/*
int main(void) {
ElemType e[] = { 2,3,4,5 };
Item* List = ListCreateEmpty();
for (int i = 0; i < 4; i++) {
List = ListInsertHead(&e[i], List);
}
return Listlenght(List);
}*/
|
C
|
/*Задача 11.
Напишете програма, която умножава 2 числа, като
използва пойнтер-и.
Пойнтер-ите не са страшни. Дефинират се като
тип *Х и се използват като *Х. Както променливите,
но със * отпред (и 1 наум!).
Продължение: Опитайте да умножите 2 променливи от
различен тип, използвайки пойнтери.*/
#include <stdio.h>
int main(){
int a,b;
int *ptr =&a;
int *ptr2=&b;
*ptr = 5;
*ptr2=5;
printf("%d\n",(*ptr)*(*ptr2));
int c = 5;
char d = 6;
char *f;
ptr = &c;
f = &d;
printf("%d\n",(*ptr)*(*f));
return 0;
}
|
C
|
#include<stdio.h>
int main() {
while (1) {
printf("Enter the number of natural numbers you would like to be summed (0 to exit): ");
int n;
int r = scanf("%d", &n);
if (r == 1) {
if (n < 0) {
printf("\nError: %d is a non-positive number", n);
} else if (n == 0) {
break;
} else {
int total = 0;
for (int i = 1; i <= n; ++i) {
total += i;
}
printf("The total of 0 - %d numbers is %d\n", n, total);
}
} else {
printf("\nYou must input a positive integer.");
}
}
return 0;
}
|
C
|
#include<windows.h>
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
#include<string.h>
#pragma comment(lib,"winmm.lib") //Ӿ̬
void play();//
void sang(int m);
void sing(const char* mci);
char c ;
char cmd[200];
char music[200]="LONOL LONOL LONO OOMMLLONOL LQPPO LONOM MMOTS PPRRQQ QQNPOONO ONOR LSRQPPPRRQQ QQVUTUV VPOT TTSSSLSRQQRQ QRQ RQPOOQST TTSPPRQ OQST TTSPPRQRQPO PQMMOONO";
char music1[200]="STVTXXTW WWVUVWXWSV VUTUVRRRVVWVSSS SYXWXX STVTXXTW WWVUVWXWSVV VUTUVRRRVVWVSSS STUVVUVV";
char music2[200]="OOSSTTS RRQQPPO SSRRQQP SSRRQQPOOSSTTS RRQQPPO";
int i=0,j=0;
int main()
{
int opt;
loop:
system("cls");//
system("color f4");
printf("\t\t\t\tӭʹ!!!\n\n");
printf("1.\t\t2.Ű\t\t3.\t\t0.˳\n\n");
while(1)
{
printf("ѡ:");
if(scanf("%d",&opt)==0)
{
while(getchar()!='\n');//ջ
opt=-1;
}
switch(opt)
{
case 0:return 1;
case 1:
{
system("cls");//
printf("ѡDzŰ!\n\n");
printf("Կʼ٣س!!!!!\n\n");
play();//
goto loop;
}break;
case 2:
{
system("cls");//
printf("1.ͯ\t2.ʹ\t3.С\t0.\n\n");
printf("Ҫѡŵİ:");
while(1)
{
if(scanf("%d",&opt)==0)
{
while(getchar()!='\n');//ջ
opt=-1;
}
switch(opt)
{case 0:goto loop;
case 1:
{
printf("\n\nڲŰࡶͯ......\n\n");
sing(music);
}
case 2:
{
printf("\n\nڲŰࡶʹ......\n\n");
sing(music1);
}break;
case 3:
{
printf("\n\nڲŰࡶСǡ......\n\n");
sing(music2);
}break;
default:
{
printf("ѡ");
printf("3˳!\n\n");
Sleep(1800);
}
}
}
}break;
case 3:
{
system("cls");//
printf("1.İ\t2.С\t3.\t0.\n\n");
printf("Ҫѡŵĸ:");
while(1)
{
if(scanf("%d",&opt)==0)
{
while(getchar()!='\n');//ջ
opt=-1;
}
switch(opt)
{case 0:goto loop;
case 1:
{
printf("\n\nڲŸİ㡷......\n\n");
sang(1);
}
case 2:
{
printf("\n\nڲŰࡶС......\n\n");
sang(2);
}break;
case 3:
{
printf("\n\nڲŰࡶ衷......\n\n");
sang(3);
}break;
default:
{
printf("ѡ");
printf("3˳!\n\n");
Sleep(1800);
}
}
}
}break;
default:
printf("ѡ");
}
}
return 0;
}
//ֶ
void play()
{
while(1)
{
c=getche();
if(c=='\r') break;
sprintf(cmd,"open sound//%c.mp3 alias s%d",c,i);
mciSendString(cmd,NULL,0,NULL);
sprintf(cmd,"play s%d",i);
mciSendString(cmd,NULL,0,NULL);
i++;
}
}
//
void sang(int m)
{
sprintf(cmd,"play singsang//%d.mp3",m);
mciSendString(cmd,NULL,0,NULL);//ֺ
Sleep(2400000);
}
//Ű
void sing(const char* mci)
{
for(j=0;j < strlen(mci);j++)
{
sprintf(cmd,"open sound//%c.mp3 alias s%d",mci[j],i);
mciSendString(cmd,NULL,0,NULL);
sprintf(cmd,"play s%d",i);
mciSendString(cmd,NULL,0,NULL);
i++;
Sleep(500);
}
}
|
C
|
// Copyright(c) 2021 Jounayd Id Salah
// Distributed under the MIT License (See accompanying file LICENSE.md file or copy at http://opensource.org/licenses/MIT).
#pragma once
#include "math/vector/coVec3_f.h"
inline coFloatx4 coSquareDistancePointTriangle(const coVec3& p, const coVec3& a, const coVec3& b, const coVec3& c)
{
// https://www.iquilezles.org/www/articles/distfunctions/distfunctions.htm
const coVec3 ba = b - a; const coVec3 pa = p - a;
const coVec3 cb = c - b; const coVec3 pb = p - b;
const coVec3 ac = a - c; const coVec3 pc = p - c;
const coVec3 nor = coCross(ba, ac);
const coFloatx4 f = coSign(coDot(coCross(ba, nor), pa))
+ coSign(coDot(coCross(cb, nor), pb))
+ coSign(coDot(coCross(ac, nor), pc));
const coFloatx4 v = f < 2.0f ?
coMin(coMin(
coSquareLength(ba * coClamp01(coDot(ba, pa) / coSquareLength(ba)) - pa),
coSquareLength(cb * coClamp01(coDot(cb, pb) / coSquareLength(cb)) - pb)),
coSquareLength(ac * coClamp01(coDot(ac, pc) / coSquareLength(ac)) - pc))
: coDot(nor, pa) * coDot(nor, pa) / coSquareLength(nor);
return v;
}
coVec3 coClosestPtPointTriangle(const coVec3& p, const coVec3& a, const coVec3& b, const coVec3& c, coFloat& s, coFloat& t);
|
C
|
#ifndef UNMOUNT_H
#define UNMOUNT_H
#include "../var/globals.h"
#include "../fileManager/manager.h"
#include "../fileManager/mpartition.h"
void exec_unmount()
{
if (strlen(values.id) < 0)
{
printf(ANSI_COLOR_RED "[e] Parámetros incompletos\n" ANSI_COLOR_RESET);
return;
}
char id_i = values.id[2];
int id_a = values.id[3] - '0';
int i = getDiskById(id_i);
int j = getPartById(id_a, i);
if (j == _ERROR_)
{
printf(ANSI_COLOR_RED "[e] La partición %s no se encuentra montada\n" ANSI_COLOR_RESET, values.id);
return;
}
clearPartMounted(i, j);
clearDiskMounted(i);
printf(ANSI_COLOR_GREEN "[i] Partición %s desmontada\n" ANSI_COLOR_RESET, values.id);
}
#endif
|
C
|
/* File : vector.c
Author : Richard A. O'Keefe
Updated: 04/20/99
Purpose: support for library(vector)
Copyright (C) 1987, Quintus Computer Systems, Inc. All rights reserved.
*/
/* We currently support four kinds of vectors:
CVECT : character vectors (char*)
IVECT : integer vectors (long*)
SVECT : single-precision floating-point vectors (float*)
DVECT : double-precision floating-point vectors (double*)
A vector has four parts:
- a fill pointer
- a type code
- a size (number of elements)
- a body
The layout has been cunningly hacked so that a character vector
looks exactly like the kind of character vector you get from
QP_string_from_atom, so character vectors built this way can
be given directly to the routines in strings.c, for example.
Unfortunately, this means that no vector can have more than
65,535 elements. Does this restriction really matter?
The layout also ensures that -- provided QPvectors are allocated
on "double" boundaries -- the elements of the body will be
properly aligned. That is why it matters that the header should
be a multiple of 8 bytes long.
*/
#ifndef lint
static char SCCSid[] = "@(#)99/04/20 vectors.c 76.1";
#endif/*lint*/
#include "malloc.h"
#include "quintus.h" /* [PM] 3.5 QP_malloc */
#define CVECT 0
#define IVECT 1
#define SVECT 2
#define DVECT 3
static unsigned type_size[] =
{
sizeof (char), /* CVECT */
sizeof (long), /* IVECT */
sizeof (float), /* SVECT */
sizeof (double) /* DVECT */
};
typedef struct
{
union {
char* cptr;
long* iptr;
float* fptr;
double* dptr;
} fill_pointer;
unsigned short type_code;
unsigned short number_of_elements;
union {
char cvec[sizeof (double)/sizeof (char)];
long ivec[sizeof (double)/sizeof (long)];
float fvec[sizeof (double)/sizeof (float)];
double dvec[sizeof (double)/sizeof (double)];
} vector_body;
} QPvector;
typedef char* POINTER;
#define Null (POINTER)0
/* The following macros convert between a QPvector pointer and
a pointer of the appropriate type.
*/
#define Cvecptr(vec) (vec->vector_body.cvec)
#define Ivecptr(vec) (vec->vector_body.ivec)
#define Svecptr(vec) (vec->vector_body.fvec)
#define Dvecptr(vec) (vec->vector_body.dvec)
#define QPvecsiz (sizeof (QPvector) - sizeof (double))
/* It is the caller's responsibility to ensure that Xptrvec()
is only applied to objects returned by QVmake(), which will
be properly aligned. So we muzzle Lint. When C compilers
support the ANSI C (void*) construct, pointer casting will
be easy. For now, Lint does NOT like it when we case the
result of malloc to some other type, so...
*/
#ifdef lint
static QPvector dummy_vector_header;
/*ARGSUSED*/
static QPvector *Xptrvec(p) POINTER p; {return &dummy_vector_header;}
#else /*real*/
#define Xptrvec(ptr) ((QPvector*)((POINTER)(ptr)-QPvecsiz))
#endif/*lint*/
POINTER QVmake(size, code)
unsigned size;
int code;
{
register QPvector* p;
if (code < CVECT || code > DVECT) return Null;
if (size >= 65536) return Null;
p = Malloc(QPvector *, QPvecsiz + size*type_size[code]);
if (!p) return Null;
p->type_code = code;
p->number_of_elements = size;
switch (code) {
case CVECT: p->fill_pointer.cptr = Cvecptr(p); break;
case IVECT: p->fill_pointer.iptr = Ivecptr(p); break;
case SVECT: p->fill_pointer.fptr = Svecptr(p); break;
case DVECT: p->fill_pointer.dptr = Dvecptr(p); break;
}
return Cvecptr(p);
}
int QVsize(ptr)
register POINTER ptr;
{
if (ptr == Null) return -1;
return Xptrvec(ptr)->number_of_elements;
}
void QVrset(ptr)
POINTER ptr;
{
register QPvector* p = Xptrvec(ptr);
switch (p->type_code) {
case CVECT: p->fill_pointer.cptr = Cvecptr(p); break;
case IVECT: p->fill_pointer.iptr = Ivecptr(p); break;
case SVECT: p->fill_pointer.fptr = Svecptr(p); break;
case DVECT: p->fill_pointer.dptr = Dvecptr(p); break;
}
}
int QVIpsh(element, ptr)
int element;
POINTER ptr;
{
register QPvector* p;
if (ptr == Null) return -1;
p = Xptrvec(ptr);
switch (p->type_code) {
case CVECT: *(p->fill_pointer.cptr)++ = element; break;
case IVECT: *(p->fill_pointer.iptr)++ = element; break;
case SVECT: *(p->fill_pointer.fptr)++ = element; break;
case DVECT: *(p->fill_pointer.dptr)++ = element; break;
}
return 0;
}
int QVDpsh(element, ptr)
double element;
POINTER ptr;
{
register QPvector* p;
if (ptr == Null) return -1;
p = Xptrvec(ptr);
switch (p->type_code) {
case CVECT: return -2;
case IVECT: return -2;
case SVECT: *(p->fill_pointer.fptr)++ = element; break;
case DVECT: *(p->fill_pointer.dptr)++ = element; break;
}
return 0;
}
int QVnext(ptr, ival, fval)
POINTER ptr;
long *ival;
double *fval;
{
register QPvector* p;
if (ptr == Null) return -1;
p = Xptrvec(ptr);
switch (p->type_code) {
case CVECT: *ival = *(p->fill_pointer.cptr)++;
*fval = 0.0; break;
case IVECT: *ival = *(p->fill_pointer.iptr)++;
*fval = 0.0; break;
case SVECT: *fval = *(p->fill_pointer.fptr)++;
*ival = 0; break;
case DVECT: *fval = *(p->fill_pointer.dptr)++;
*ival = 0; break;
}
return p->type_code;
}
void QVkill(ptr)
POINTER ptr;
{
Free(ptr-QPvecsiz);
}
/* QVIget(ptr, inx, &ival) is used to get an element of an integer vector.
0 => ptr and inx are ok, ival has element
-1 => ptr is not valid
-2 => ptr points to a vector of the wrong type.
-3 => inx is not valid
*/
int QVIget(ptr, inx, ival)
POINTER ptr;
int inx;
long *ival;
{
register QPvector* p;
if (ptr == Null) return -1;
p = Xptrvec(ptr);
if ((unsigned)(--inx) >= p->number_of_elements) return -3;
switch (p->type_code) {
case CVECT: *ival = Cvecptr(p)[inx]; return 0;
case IVECT: *ival = Ivecptr(p)[inx]; return 0;
default: return -2;
}
}
int QVFget(ptr, inx, fval)
POINTER ptr;
int inx;
double *fval;
{
register QPvector* p;
if (ptr == Null) return -1;
p = Xptrvec(ptr);
if ((unsigned)(--inx) >= p->number_of_elements) return -3;
switch (p->type_code) {
case SVECT: *fval = Svecptr(p)[inx]; return 0;
case DVECT: *fval = Dvecptr(p)[inx]; return 0;
default: return -2;
}
}
int QVIput(ptr, inx, ival)
POINTER ptr;
int inx;
int ival;
{
register QPvector* p;
if (ptr == Null) return -1;
p = Xptrvec(ptr);
if ((unsigned)(--inx) >= p->number_of_elements) return -3;
switch (p->type_code) {
case CVECT: Cvecptr(p)[inx] = ival; return 0;
case IVECT: Ivecptr(p)[inx] = ival; return 0;
default: return -2;
}
}
int QVFput(ptr, inx, fval)
POINTER ptr;
int inx;
double fval;
{
register QPvector* p;
if (ptr == Null) return -1;
p = Xptrvec(ptr);
if ((unsigned)(--inx) >= p->number_of_elements) return -3;
switch (p->type_code) {
case SVECT: Svecptr(p)[inx] = fval; return 0;
case DVECT: Dvecptr(p)[inx] = fval; return 0;
default: return -2;
}
}
int QVtype(ptr)
POINTER ptr;
{
register QPvector* p;
if (ptr == Null) return -1;
p = Xptrvec(ptr);
return p->type_code;
}
|
C
|
/**
* @file main.c
* @author typeR
* @brief
* @version 0.1
* @date 2018-11-03
*
* @copyright Copyright (c) 2018
*
*/
/**************************************************************************//**
* INCLUDE
******************************************************************************/
#include <stdio.h>
#include <stdint.h>
#include "vector_lib.h"
#include "rotation_matrix_lib.h"
/**************************************************************************//**
* MAIN
******************************************************************************/
int main(void)
{
VECTOR_T vector_A = {0,2,3};
VECTOR_T vector_B = {4,0,0};
VECTOR_T vector_C = {0,0,0};
VECTOR_T vector_D = {0,0,0};
ROT_MAT_T rot_mat[MAX_ROT_MAT_ROW][MAX_ROT_MAT_COL] = {{1,0,0},{0,1,0},{0,0,1}};
int32_t* pD;
VEC_COMPO_INT_T ans = 0;
VECTOR_RELATION_T rc = 0;
pD = (int32_t*)&vector_D;
vector_D.x = 1;
vector_D.y = 10;
vector_D.z = 100;
rotate_vector(rot_mat, &vector_A, &vector_D);
printf("%p\n", &(vector_D));
printf("%p, %p, %p\n", &(vector_D), pD+1, pD+2);
printf("%p, %p, %p\n", &(vector_D.x), &(vector_D.y), &(vector_D.z));
printf("%3d, %3d, %3d\n", vector_D.x, vector_D.y, vector_D.z);
vector_scr_mul(&vector_A, 10, &vector_C);
printf("scalar multiplication\n");
printf("%2d ", vector_C.x);
printf("%2d ", vector_C.y);
printf("%2d\n", vector_C.z);
vector_add(&vector_A, &vector_B, &vector_C);
printf("addition\n");
printf("%2d ", vector_C.x);
printf("%2d ", vector_C.y);
printf("%2d\n", vector_C.z);
vector_sub(&vector_A, &vector_B, &vector_C);
printf("subtract\n");
printf("%2d ", vector_C.x);
printf("%2d ", vector_C.y);
printf("%2d\n", vector_C.z);
vector_inner_prod(&vector_A, &vector_B, &ans);
printf("Inner product\n");
printf("%2d\n", ans);
vector_outer_prod(&vector_A, &vector_B, &vector_C);
printf("Outer product\n");
printf("%2d ", vector_C.x);
printf("%2d ", vector_C.y);
printf("%2d\n", vector_C.z);
vector_norm(&vector_C, &ans);
printf("Area of parallelogram\n");
printf("%2d\n", ans);
vector_norm(&vector_A, &ans);
printf("Norm of vector_A\n");
printf("%2d\n", ans);
printf("Judge orthogonal\n");
rc = judge_orth_vector(&vector_A, &vector_B);
if (rc == VECTOR_ORTHGONAL) {
printf("vector_A and vector_B are orthogonal.\n");
} else if (rc == VECTOR_NON_ORTHGONAL){
printf("vector_A and vector_B are NOT orthogonal.\nCheck other relations.\n");
} else {
// do nothing
}
printf("Judge parallel\n");
rc = judge_para_vector(&vector_A, &vector_B);
if(rc == VECTOR_PARALLEL) {
printf("vector_A and vector_B are parallel.\n");
} else if (rc == VECTOR_NON_PARALLEL){
printf("vector_A and vector_B are NOT parallel.\nCheck other relations.\n");
} else {
// do nothing
}
return (0);
}
|
C
|
// https://leetcode.com/problems/wildcard-matching/
bool isMatch(char * s, char * p){
int slen = strlen(s), plen = strlen(p), str = -1, patt = -1, i = 0, j = 0;
while(i<slen) {
if(j<plen && (p[j] == s[i] || p[j] == '?')) i++,j++;
else if(j<plen && p[j] == '*') {
str = i;
patt = j++;
}
else if(patt != -1) {
i = ++str;
j = 1 + patt;
}
else return false;
}
while(j<plen && p[j] == '*') ++j;
return j == plen;
}
|
C
|
#ifndef __GESTION_FICHIER_H__
#include "Arbre_binaire.h"
#include "liste.h"
#define __GESTION_FICHIER_H__
#define BLOCK_SIZE 4096 // 1 bloc sur disque = 4096 octets
typedef struct {
FILE* file; // identification du fichier
char mode; // lecture 'r' ou criture 'w'
unsigned char record[BLOCK_SIZE]; // tampon pour lire ou criture
int record_length; // nombre d'lments dans le tampon
int i_record; // indice dans le tampon
char octet[8]; // pour expension d'un octet en 8 caractres
int i_octet; // indice dans octet
int nb_octets; // nombre d'octets lus ou crits
} Bin_file;
Bin_file* open_bin_file(char*, char);
void write_bin_file(Bin_file*, char);
char read_bin_file(Bin_file*);
int close_bin_file(Bin_file*);
Bin_file* open_normal_file(char* filename, char mode);
char* lecture_normal_file(Bin_file* input);
void close_normal_file(Bin_file* fichier);
void TEST_GESTION_FICHIER();
#endif
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void draw(int number)
{
int i = 0,j = 0,k = 0,space1 = 0,space2 = 0;
for(i = 0;i<number;i++)
{
if(i == 0){printf("*");}
for(j = 0;j<space1;j++)
{
printf(" ");
}
if(i != 0){ printf("*");}
for(k = i;k< (((2*number) -3) - space2) ;k++)
{
printf(" ");
}
if(i != number -1)
{
printf("*");
}
printf("\n");
space1++;
space2++;
}
}
int main()
{
draw(5);
}
|
C
|
#pragma once
#include <stdint.h>
#ifdef __cplusplus
extern "C" {
#endif
uint32_t platform_time_ms();
void set_throttle_calibration(uint16_t min, uint16_t max);
uint16_t get_throttle_adc();
uint8_t motor_disarm(); //returns armed state
void motor_arm();
static inline void utils_step_towards(float *value, float goal, float step) {
if (*value < goal) {
if ((*value + step) < goal) {
*value += step;
} else {
*value = goal;
}
} else if (*value > goal) {
if ((*value - step) > goal) {
*value -= step;
} else {
*value = goal;
}
}
}
static inline float utils_calc_ratio(float low, float high, float val) {
return (val - low) / (high - low);
}
static inline float utils_map(float x, float in_min, float in_max, float out_min, float out_max) {
return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min;
}
static inline int utils_map_int(int x, int in_min, int in_max, int out_min, int out_max) {
return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min;
}
#define UTILS_LP_FAST(value, sample, filter_constant) (value -= (filter_constant) * ((value) - (sample)))
static inline float clip(float val, float min, float max) {
if(val<min) return min;
if(val>max) return max;
return val;
}
static inline uint32_t utils_get_dt(uint32_t* prev) {
uint32_t time = platform_time_ms();
uint32_t dt = time - *prev;
*prev = time;
return dt;
}
static inline int utils_median_5_int(int a, int b, int c, int d, int e)
{
return b < a ? d < c ? b < d ? a < e ? a < d ? e < d ? e : d
: c < a ? c : a
: e < d ? a < d ? a : d
: c < e ? c : e
: c < e ? b < c ? a < c ? a : c
: e < b ? e : b
: b < e ? a < e ? a : e
: c < b ? c : b
: b < c ? a < e ? a < c ? e < c ? e : c
: d < a ? d : a
: e < c ? a < c ? a : c
: d < e ? d : e
: d < e ? b < d ? a < d ? a : d
: e < b ? e : b
: b < e ? a < e ? a : e
: d < b ? d : b
: d < c ? a < d ? b < e ? b < d ? e < d ? e : d
: c < b ? c : b
: e < d ? b < d ? b : d
: c < e ? c : e
: c < e ? a < c ? b < c ? b : c
: e < a ? e : a
: a < e ? b < e ? b : e
: c < a ? c : a
: a < c ? b < e ? b < c ? e < c ? e : c
: d < b ? d : b
: e < c ? b < c ? b : c
: d < e ? d : e
: d < e ? a < d ? b < d ? b : d
: e < a ? e : a
: a < e ? b < e ? b : e
: d < a ? d : a;
}
#ifndef MAX
#define MAX(a,b) (((a)>(b))?(a):(b))
#endif
#ifdef __cplusplus
}
#endif
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAXBIT 10
#define MAXVALUE 1000
typedef struct{
int weight;
int parent,left,right;
}Hnode,*HTree;
typedef char* *HCode;
HTree HuffmanTree(int *w,int n){
int m,m1,m2,x1,x2,i,j;
HTree ht;
Hnode *p;
if(n<=1) return NULL;
m=2*n-1;
ht=(Hnode*)malloc(sizeof(Hnode)*m);
if(ht==NULL) return ht;
for(p=ht,i=0;i<n;++i,++p,++w){
p->weight=*w;
p->left=-1;
p->right=-1;
p->parent=-1;
}
for(i=n;i<m;++i){
m1=m2=MAXVALUE;
x1=x2=0;
for(j=0;j<i;++j){
if(ht[j].parent==-1&&ht[j].weight<m1){
m2=m1;
x2=x1;
m1=ht[j].weight;
x1=j;
}else if(ht[j].parent==-1&&ht[j].weight<m2){
m2=ht[j].weight;
x2=j;
}
}
ht[x1].parent=i;
ht[x2].parent=i;
ht[i].left=x1;
ht[i].right=x2;
ht[i].weight=m1+m2;
}
return ht;
}
HCode HuffmanCoding(HTree ht,int n){
HCode HC;
char *cd;
int start,i,c,f;
HC=(HCode)malloc(n*sizeof(char*));
cd=(char*)malloc(sizeof(char)*n);
cd[n-1]='\0';
for(i=0;i<n;++i){
start=n-1;
for(c=i,f=ht[i].parent;f!=-1;c=f,f=ht[f].parent){
if(ht[f].left==c) cd[--start]='\0';
else cd[--start]='1';
}
HC[i]=(char*)malloc(sizeof(char)*(n-start));
strcpy(HC[i],&cd[start]);
}
free(cd);
return HC;
}
|
C
|
// C implementation of fibonacci series
#include<stdio.h>
int fibonacci(int n)
{
if (n <= 1)
return n;
return fibonacci(n-1) + fibonacci(n-2);
}
int main ()
{
int n = 10;
printf("Fibonacci number of %d : %d", n, fibonacci(n));
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
int main()
{
int mon_int = 12;
int prix = 12000;
char mon_char = 'A';
int* p_int = 0; //déclaration du pointeur
p_int = &mon_int; //assignation de mon pointeur à p_int
//représentation en décimale, mais on utilise plutot l'Hexadicimale pour représenter l'adresse
printf("mon int = %d, adresse = %p\n", mon_int, &mon_int);
printf("p_int de mon_int = %p, le contenu de *p_int = %d\n", p_int, *p_int); // pour afficher le contenue on utilise "*p_int"
p_int = &prix; //assignation de mon pointeur à p_int
printf("p_int de prix = %p, le contenu de *p_int = %d\n", p_int, *p_int);
//printf("p_int de prix = %p\n", &prix); //meme chose que "p_int = &prix;"
// on utilise Hexadicimale pour représenter l'adresse
printf("mon char = %c, adresse = %p\n", mon_char, &mon_char);
return 0;
}
|
C
|
/** Afisarea matricei de sudoku (in consola) **/
int show_matrix (int **matrix)
{
int i,j,k;
for (i=0; i<9; i++) //parcurge linia
{
for (k=0; k<9; k++) // parcurgere pentru afisarea conturului
{
if (k<8) printf("----");
else printf("-----"); // if-ul a fost scris pentru un aspect decent
}
printf("\n");
for (j=0; j<9; j++)
{
if (j==0) printf("|"); // inainte de primul element, pentru contur stanga
printf(" %d |",matrix[i][j]);
if (i==8 && j==8)
{
printf("\n");
for (k=0; k<9; k++)
{
if (k<8) printf("----");
else printf("-----");
}
}
}
printf("\n");
}
}
/**Afisarea matricei de sudoku (in fisier text)**/
int show_matrix_file (int **matrix,FILE *RezolvareSudoku)
{
int i,j,k;
for (i=0; i<9; i++)
{
for (k=0; k<9; k++)
{
if (k<8) fprintf(RezolvareSudoku,"----");
else fprintf(RezolvareSudoku,"-----");
}
fprintf(RezolvareSudoku,"\n");
for (j=0; j<9; j++)
{
if (j==0) fprintf(RezolvareSudoku,"|");
fprintf(RezolvareSudoku," %d |",matrix[i][j]);
if (i==8 && j==8)
{
fprintf(RezolvareSudoku,"\n");
for (k=0; k<9; k++)
{
if (k<8) fprintf(RezolvareSudoku,"----");
else fprintf(RezolvareSudoku,"-----");
}
}
}
fprintf(RezolvareSudoku,"\n");
}
}
/**Functie de verificare pe o linie **/
int check_row (int **matrix, int number, int row)
{
int i;
for (i=0; i<9; i++)
if (matrix[row][i]==number)
return 0;
return 1;
}
/** Functie de verificare pe o coloana **/
int check_col (int **matrix, int number, int col)
{
int i;
for (i=0; i<9; i++)
if (matrix[i][col]==number)
return 0;
return 1;
}
/** Functie de verificare a unui patrat 3x3 **/
/*Avem nevoie si de o functie de verificare a unui patrat de 3x3
pentru ca exista cazuri in care numerele nu se vor duplica pe linii
si/sau pe coloane, dar pot exista duplicate ale acelorasi numere in
patratul de 3x3 in care se afla pe tabla de joc.*/
int check_square (int **matrix, int row, int col, int number)
{
int RowStart=(row/3)*3, ColStart=(col/3)*3, i,j; //aflu in ce patrat de 3/3 ma aflu
for (i=RowStart; i<RowStart+3; i++)
for (j=ColStart; j<ColStart+3; j++) //parcurg patratul
{
if (!(i==row && j==col)) // nu mai verifiv umarulpe care l am pus deja in matrice, totul in afara de el
if (matrix[i][j]==number) return 0;
}
return 1;
}
/** Functie pentru manipularea rezultatelor celor 3 verificari ale conditiilor
necesare pentru un joc corect. (E mai usor sa scrii o singura functie decat 3) **/
int check_board (int **matrix, int row, int col, int number) //pentru a avea mai putine linii de cod, le am strans pe toate pentru a le verifica
{
if (check_col(matrix,number,col)==1 && check_row(matrix,number,row)==1 && check_square(matrix,row,col,number)==1)
return 1;
else return 0;
}
/**Rezolva sudoku **/
int solve_sudoku (int **matrix, int row, int col)
{
int i;
if (row<9 && col<9)
{
if (matrix[row][col]!=0)
{
if ((col+1)<9) return solve_sudoku(matrix,row,col+1); //recursiv apele funtia in care ma aflu
else if ((row+1)<9) return solve_sudoku(matrix,row+1,0);
else return 1;
}
else
{
for (i=0;i<9;i++)
{
if (check_board(matrix,row,col,i+1)) //
{
matrix[row][col]=i+1;
if ((col+1)<9)
{
if (solve_sudoku(matrix,row,col+1)) return 1; //daca e ok valoarea alea merge mai departe, daca nu imi cauata alta valoare
else matrix[row][col]=0;
}
else if ((row+1)<9)
{
if (solve_sudoku(matrix,row+1,0)) return 1;
else matrix[row][col]=0;
}
else return 1;
}
}
}
return 0;
}
else return 1;
}
int check_square_rows (int **matrix)
{
int row,col,row_checker[9]={0}; // am folosit vector de frecventa
row=0;
while (row<9)
{
for (col=0;col<9;col++)
row_checker[matrix[row][col]-1]++;
for (col=0;col<9;col++)
if (row_checker[col]!=1) return 0;
row++;
for (col=0;col<9;col++)
row_checker[col]=0;
}
return 1;
}
int check_square_cols (int **matrix)
{
int row,col,col_checker[9]={0};
col=0;
while (col<9)
{
for (row=0;row<9;row++) //nr de aparitii
col_checker[matrix[row][col]-1]++;
for (row=0;row<9;row++) //verific vectorul de frecventa sa aibe o singura aparitie
if (col_checker[row]!=1) return 0;
col++;
for (row=0;row<9;row++)
col_checker[row]=0;
}
return 1; //daca a fost totul ok, se pune 0 pe vectorul de fecventa ca sa pregatesc pt urmatoarea verficare
}
|
C
|
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#define size_alocar 100
char *remove_spaces_initals(char *str);
char *remove_space_final(char *str);
char *remove_spaces_both_sides(char *str);
char **split_string2(char *original, char *pattern);
char *spliting_string(char *ptr, char *pattern, int length_pattern, char **returned);
int search_word(char *comando, char *word) /*pesquisa palavra*/
{
int i = (strstr(comando, word) == NULL);
//char* i = (strstr(comando, word));
//printf("%s",i);
return i;//(strstr(comando, word) == NULL);
}
int wait_comand(char *comando)
{
char ands[2] = {'&', '\0'};
return search_word(comando, ands);
}
int comando_exit_search(char *comando)
{
char is_exit[5] = {'e', 'x', 'i', 't', '\0'};
return search_word(comando, is_exit);
}
char *comando_alocar()
{
char *comando = (char *)calloc(size_alocar, sizeof(char));
return comando;
}
char *comando_solicita(char *comando)
{
comando[0] = '\0';
setbuf(stdin, NULL);
printf("user@user-PC: ");
scanf("%[^\n]s", comando);
setbuf(stdin, NULL);
//printf("%s", comando);
return comando;
}
char **args_alocar()
{
char **args = (char **)calloc(size_alocar, sizeof(char *));
for (int i = 0; i < size_alocar; i++)
{
args[i] = (char *)calloc(64, sizeof(char));
}
return args;
}
int args_fill(char **args, char *comando) /*funcao que preenche os args*/
{
if (comando[0] == '\0')
{
//printf("comando sem argumentos!\n");
return 0;
}
remove_spaces_both_sides(comando);
int i = 0, col = 0;
int line = 0;
int tamanho = strlen(comando);
//printf("%d", tamanho);
int controle = 0;
for (i = 0; i <= tamanho; i++)
{
controle = 0;
if (comando[i] != ' ')
{
args[line][col] = comando[i];
col++;
}
else
{
args[line][col] = '\0';
col = 0;
line++;
controle = 1;
}
}
if (controle == 0)
{
args[++line] = NULL;
}
else
{
args[line] = NULL;
}
// args_print(args, *line);
if (strcmp(args[0], "ls") == 0)
{
free(args[line]);
args[line] = strdup("--color");
args[line + 1] = NULL;
}
return 1;
}
/**
*
*
*
* falta arrumar a parte de imprimir os dados, não esta funcionando.
*
*
*
* */
void args_print(char **args) /*funcao pra imprimir o vetor de string*/
{
int i = 0;
while (args[i] != NULL)
{
printf("%s\n", args[i]);
i++;
}
}
void comando_deallocate(char *comando)
{
free(comando);
comando = NULL;
}
void args_deallocate(char **args) /*funcao de desalocar um vetor de string*/
{
/*if (args == NULL)
{
return;
}*/
for (int i = 0; i < size_alocar; i++)
{
free(args[i]);
}
free(args);
args = NULL;
}
/*
int last_space(char *str)
{
int i;
for (i = 0; *str && *str == ' '; i++, str++)
;
return i;
}
void remove_spaces_initals(char *str)
{
int index_last_space = last_space(str);
int i, j;
for (i = 0, j = index_last_space; str[j]; i++, j++)
str[i] = str[j];
str[i + 1] = '\0';
}
*/
void desalocar_Matriz(char **str, int tam)
{
for (int i = 0; i < tam; i++)
{
free(str[i]);
}
free(str);
str = NULL;
}
char *indentify_pattern(char *original, char *pattern)
{
static char *p = NULL;
static char *token = NULL;
static int length_pattern = 0;
if (length_pattern == -1) // Condição de parada
{
length_pattern = 0;
return NULL;
}
if (p == NULL) // Inicializando
{
length_pattern = strlen(pattern);
p = original;
token = strstr(p, pattern);
*token = 0;
return original;
}
if (length_pattern > 0) // Iterando
{
*token = *pattern;
p = token + length_pattern;
token = strstr(p, pattern);
if (token)
{
*token = 0;
return p;
}
else
{
length_pattern = -1;
char *r = p;
p = NULL;
return r;
}
}
}
char *remove_spaces_initals(char *str)
{
int i;
char *p = str;
for (i = 0; *p && *p == ' '; i++, p++)
;
int index_last_space = i;
int j;
for (i = 0, j = index_last_space; str[j]; i++, j++)
str[i] = str[j];
str[i] = '\0';
return str;
}
char *remove_space_final(char *str)
{
int length = strlen(str), i;
for (i = length - 1; i >= 0 && str[i] == ' '; i--)
;
str[i + 1] = '\0';
return str;
}
char *remove_spaces_both_sides(char *str)
{
return remove_spaces_initals(remove_space_final(str));
}
/*-----------------------------------------------------*/
char **split_string2(char *original, char *pattern)
{
size_t pattern_length = strlen(pattern);
size_t n = 0;
char *p;
char *token;
// encontra quantas vezes o modelo aparece na string
for (p = original; token = strstr(p, pattern); p = token + pattern_length)
n++;
char **returned = calloc(n + 2, sizeof(char *)); // MALLOC returned
if (returned != NULL)
{
p = original;
for (int i = 0; p = spliting_string(p, pattern, pattern_length, &returned[i]); i++)
{
if (returned[i] == NULL)
{
while (i--)
free(returned[i - 1]);
free(returned);
return NULL;
}
}
}
return returned;
}
char *spliting_string(char *ptr, char *pattern, int length_pattern, char **returned)
{
char *token = strstr(ptr, pattern);
if (token)
{
*token = 0;
*returned = strdup(ptr);
*token = *pattern;
return token + length_pattern;
}
*returned = strdup(ptr);
return NULL;
}
|
C
|
#include<stdio.h>
#include<stdlib.h>
int main(void)
{
float a, b,BMI;
printf("enter your height in meter and weight in kilogram\n");
scanf_s("%f %f", &a, &b);
BMI = b / (a*a);
printf("your BMI is %f\n", BMI);
if (BMI < 18.5)
{
printf("Underweight");
}
if (BMI >= 18.5&& BMI<24.9)
{
printf("Normal");
}
if (BMI >= 25&&BMI<29.9)
{
printf("Overweight");
}
if (BMI > 30)
{
printf("Obese");
}
return 0;
}
|
C
|
#ifndef _MESSAGEFORMAT_H_
#define _MESSAGEFORMAT_H_
#pragma pack(4)
enum CMD
{
CMD_REGISTER,
CMD_REGISTER_RESULT,
CMD_LOGIN,
CMD_LOGIN_RESULT,
CMD_LOGOUT,
CMD_LOGOUT_RESULT,
CMD_CHATMESSAGE,
CMD_HEART
};
//消息头
struct DataHeader
{
int dataLength;//数据长度
CMD cmd; //具体是什么消息
};
struct Register : public DataHeader
{
Register()
{
dataLength = sizeof(Register) - sizeof(DataHeader);
cmd = CMD_REGISTER;
memset(userName, 0, sizeof(userName));
memset(passWord, 0, sizeof(passWord));
}
char userName[32];
char passWord[32];
};
struct RegisterResult : public DataHeader
{
RegisterResult()
{
dataLength = sizeof(Register) - sizeof(DataHeader);
cmd = CMD_REGISTER_RESULT;
}
bool success;
};
struct Login : public DataHeader
{
Login()
{
dataLength = sizeof(Login) - sizeof(DataHeader);
cmd = CMD_LOGIN;
memset(userName, 0, sizeof(userName));
memset(passWord, 0, sizeof(passWord));
}
char userName[32];
char passWord[32];
};
//通过继承可以不用每次把DataHeader写一遍
struct LoginResult : public DataHeader
{
LoginResult()
{
dataLength = sizeof(LoginResult) - sizeof(DataHeader);
cmd = CMD_LOGIN_RESULT;
}
bool result;
char info[32];//登录成功也可以返回信息
};
struct LoginOut : public DataHeader
{
LoginOut()
{
dataLength = sizeof(LoginOut) - sizeof(DataHeader);
cmd = CMD_LOGOUT;
}
char userName[32];
};
struct LoginOutResult : public DataHeader
{
LoginOutResult()
{
dataLength = sizeof(LoginOutResult) - sizeof(DataHeader);
cmd = CMD_LOGOUT_RESULT;
}
bool result;
char info[32];//登录成功也可以返回信息
};
struct ChatMessage : public DataHeader
{
ChatMessage()
{
dataLength = sizeof(ChatMessage) - sizeof(DataHeader);
cmd = CMD_CHATMESSAGE;
}
char userName[32];
char message[128];
};
struct Heart : public DataHeader
{
Heart()
{
dataLength = sizeof(Heart) - sizeof(DataHeader);
cmd = CMD_HEART;
}
};
#pragma pack()
#endif // MESSAGEFORMAT_H
|
C
|
#include "holberton.h"
/**
* _abs - a function that computes the absolute value of an integer.
* @n: The number
* Return: Return the absolute value of an integer
*/
int _abs(int n)
{
int res;
if (n < 0)
{
res = n * -1;
}
else
{
res = n;
}
return (res);
}
|
C
|
/***
*file: "FirstPart.h"
*synopsis: definitions functions for second part of the first lab
*author: R. Neshta
*written: 01/06/17
*last modified: 01/06/17
****/
#include"SecondPart.h"
/*
The argz_create_sep function converts the null-terminated string into an
argz vector (returned in argz and argz len) by splitting it into elements at every
occurrence of the character sep.
*/
error_t argz_create_sep(const char *string, int sep, char **argz, size_t *argz_len){
int i;
(*argz_len) = strlen(string);
if (NULL == (*argz = (char*)malloc((*argz_len + 1) * sizeof(char))))
exit(1);
for (i = 0; i <= (*argz_len); i++){
if (string[i] == sep){
(*argz)[i] = '\0';
}
else{
(*argz)[i] = string[i];
}
}
return 0;
}
//Returns the number of elements in the argz vector.
size_t argz_count(const char *argz, size_t arg_len){
int i, n = 0;
for (i = 1; i <= arg_len; i++){
if (argz[i] == '\0' && argz[i - 1] != '\0')
++n;
}
return n;
}
//The argz_add function adds the string str to the end of the argz vector // *argz, and updates *argz and *argz_len accordingly.
error_t argz_add(char **argz, size_t *argz_len, const char *str){
int i, j, len;
char *s;
len = strlen(str);
if (NULL == (s = (char*)malloc(((*argz_len) + len + 2) * sizeof(char))))
return 1;
for (i = 0; i <= (*argz_len); i++)
s[i] = (*argz)[i];
j = i;
(*argz_len) += len + 1;
for (i = 0; i <= len; i++, j++)
s[j] = str[i];
free(*argz);
(*argz) = s;
return 0;
}
/*If entry points to the beginning of one of the elements in the argz vector *argz, the argz_delete function will remove this entry and reallocate *argz, modifying *argz and *argz_len accordingly. Note that as destructive argz functions usually reallocate their argz argument, pointers into argz vectors such as entry will then become invalid.
*/
void argz_delete(char **argz, size_t *argz_len, char *entry){
int i = 0, j = 0, len = 0;
char *str, *p = *argz;
while (NULL == strstr(p, entry) && i <= (*argz_len)){
while ((*argz)[i++] != '\0');
p = &(*argz)[i];
}
if (i > *(argz_len))
return;
len = strlen(p) + 1;
if (NULL == (str = (char*)malloc((*argz_len - len + 1) * sizeof(char)))){
printf("Allocation fail\n");
exit(1);
}
while (j < i){
str[j] = (*argz)[j];
j++;
}
j += len;
while (j <= *(argz_len))
str[i++] = (*argz)[j++];
*(argz_len) -= len;
free(*argz);
(*argz) = str;
}
/*
The argz_insert function inserts the string entry into the argz vector *argz at a point just before the existing element pointed to by before, reallocating *argz and updating *argz and *argz_len. If before is 0, entry is added to the end instead (as if by argz_add). Since the first element is in fact the same as *argz, passing in *argz as the value of before will result in entry being inserted at the beginning.
*/
error_t argz_insert(char **argz, size_t *argz_len, char *before, const char *entry){
int i, j, k, len;
char *p, *str;
if (NULL == before){
argz_add(argz, argz_len, entry);
return 0;
}
len = strlen(entry) + 1;
if (NULL == (str = (char*)malloc(((*argz_len) + len + 1) * sizeof(char))))
return 1;
i = 0;
p = *argz;
while (NULL == strstr(p, before) && i <= *(argz_len)){
while ((*argz)[i++] != '\0');
p = &(*argz)[i];
}
j = k = 0;
if (i <= *argz_len){
while (j < i){
str[j] = (*argz)[j];
j++;
}
}
else
i = 0;
while (k < len)
str[j++] = entry[k++];
while (i <= *argz_len)
str[j++] = (*argz)[i++];
*argz_len += len;
free(*argz);
(*argz) = str;
return 0;
}
/*
The argz_next function provides a convenient way of iterating over the elements in the argz vector argz. It returns a pointer to the next element in argz after the element entry, or 0 if there are no elements following entry. If entry is 0, the first element of argz is returned.
This behavior suggests two styles of iteration:
char *entry = 0;
while ((entry = argz_next (argz, argz_len, entry)))
action;
(the double parentheses are necessary to make some C compilers shut up about what they consider a questionable while-test) and:
char *entry;
for (entry = argz; entry; entry = argz_next (argz, argz_len, entry))
action;
Note that the latter depends on argz having a value of 0 if it is empty (rather than a pointer to an empty block of memory); this invariant is maintained for argz vectors created by the functions here.
*/
char * argz_next(char *argz, size_t argz_len, const char *entry){
int i;
char *p;
if (NULL == entry)
return argz;
p = argz;
i = 0;
while (NULL == strstr(p, entry) && i <= argz_len){
while (argz[i++] != '\0');
p = &argz[i];
}
while (argz[i++] != '\0');
p = &argz[i];
if (i < argz_len)
return p;
return NULL;
}
/*
Replace the string str in argz with string with, reallocating argz as
necessary.
*/
error_t argz_replace(char **argz, size_t *argz_len, const char *str, const char *with){
argz_insert(argz, argz_len, str, with);
argz_delete(argz, argz_len, str);
return 0;
}
/*prints argz vector */
void argz_print(const char *argz, size_t argz_len){
int i;
for (i = 0; i <= argz_len; i++)
printf("%c", argz[i]);
printf("\n");
}
|
C
|
#ifndef FILTER_
#define FILTER_
#define MULT_SCALE 100
//Filter API definition
//Filter datatype, holds relevat info about a filter instance properties. f_ stands for filter
typedef struct{
unsigned char f_Q; //Amount of past output values taken into account
unsigned char f_P; //Amount of past input values taken into account
int* f_b; //Coefficients for current and past input values
int* f_input; //Contains all PAST input values
} filter;
//Complementary functions
int mult(int a,int b,int n); //Multiplies a and b, then the result is divided by n
//Methods
//Init method
void init_filter(filter *x,unsigned char f_P,int *f_b,int *f_input);
//Evaluate filter output method
int eval_filter(filter *x,int new_input); //Calc a new output based on a new input
#endif
|
C
|
/* SPDX-License-Identifier: GPL-2.0+ */
/*
* Copyright (C) 2014 Samsung Electronics
* Przemyslaw Marczak <[email protected]>
*/
#ifndef _ERRNO_H
#define _ERRNO_H
#include <linux/errno.h>
extern int errno;
#define __set_errno(val) do { errno = val; } while (0)
/**
* errno_str() - get description for error number
*
* @errno: error number (negative in case of error)
* Return: string describing the error. If CONFIG_ERRNO_STR is not
* defined an empty string is returned.
*/
#ifdef CONFIG_ERRNO_STR
const char *errno_str(int errno);
#else
static const char error_message[] = "";
static inline const char *errno_str(int errno)
{
return error_message;
}
#endif
#endif /* _ERRNO_H */
|
C
|
#include <stdio.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <memory.h>
#include <stdlib.h>
int main(int argc, char *argv[]) {
char *addr = (argv[1]);
int port = atoi(argv[2]);
printf("start TCP Client to connect TCP Server: %s:%d ...\n", addr, port);
int socket_fd;
socket_fd = socket(PF_INET, SOCK_STREAM, 0);
if (socket_fd < 0) {
perror("socket error");
return 1;
}
struct sockaddr_in remote_address;
memset(&remote_address, 0, sizeof(remote_address));
remote_address.sin_family = AF_INET;
remote_address.sin_addr.s_addr = inet_addr(addr);
remote_address.sin_port = htons(port);
struct sockaddr *remote_socket_address = (struct sockaddr *) &remote_address;
size_t socket_address_length = sizeof(struct sockaddr);
int connect_ret = connect(socket_fd, remote_socket_address, socket_address_length);
if (connect_ret < 0) {
perror("connect server failed");
return 1;
}
while (1) {
char buf[BUFSIZ];
printf("please input message:");
scanf("%s", buf);
size_t send_ret = write(socket_fd, buf, strlen(buf));
if (send_ret <= 0) {
perror("send error");
return 1;
}
}
close(socket_fd);
return 0;
}
|
C
|
#include <stdio.h>
#include <string.h>
void delete_number(char *);
int main()
{
int i = 0;
char str1[100] = {0};
gets_s(str1,sizeof(str1));
delete_number(str1);
return 0;
}
void delete_number(char *str1)
{
int i = 0;
int j = 0;
int number = 0;
while(1)
{
printf(" ڿ ȣ ԷϽÿ : ");
scanf("%d", &number);
if(number <= 0)
{
printf(" Ǵ 0 Էϼ̽ϴ. ٽ Էϼ\n");
continue;
}
if(number > strlen(str1))
number = strlen(str1);
for(i=number-1; i<strlen(str1); i++)
{
str1[i] = str1[i+1];
}
printf("ϰ ڿ : %s\n", str1);
printf("ϰ ڿ : %d\n", strlen(str1));
if(strlen(str1) == 1)
{
printf(" ڿ 1 Դϴ. մϴ.\n");
break;
}
}
}
|
C
|
#include "islem.h"
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <jrb.h>
#include <jval.h>
#include <fields.h>
JRB tmpTree;
char *tmp;
int komut_calistir(char** args,JRB tree){
tmp = malloc(sizeof(char) * 1024);
memset(tmp,'\0',1024);
if(strcmp(args[0],"add") == 0){ // Add Komutu
add(tree,tmp,args);
} else if(strcmp(args[0],"search") == 0){ // Search Komutu
int varmi = 0;
jrb_traverse(tmpTree, tree){
if(atoi(args[1]) == jval_i(tmpTree->key)){
printf("%d,%s\n", tmpTree->key,jval_s(tmpTree->val));
varmi = 1;
}
}
if(!varmi)
printf("Aradiğiniz kayit bulunamadi\n");
} else if(strcmp(args[0],"pro") == 0){ // Pro Komutu
IS myis;
myis = new_inputstruct(args[1]);
if(myis == NULL){
perror("Dosya bulunamadi");
return 1;
}
while(get_line(myis) >= 0){
char ** args;
args = term_satir_parcala(myis->fields[0]);
add(tree,tmp,args);
memset(tmp,'\0',1024);
}
jettison_inputstruct(myis);
} else if(strcmp(args[0],"write") == 0){ // Write Komutu
FILE * f;
f = fopen(args[1],"w");
jrb_traverse(tmpTree, tree){
fprintf(f,"%d,%s\n", tmpTree->key,jval_s(tmpTree->val));
}
fclose(f);
} else if(strcmp(args[0],"print") == 0){ // Print Komutu
jrb_traverse(tmpTree, tree){
printf("%d,%s\n", tmpTree->key,jval_s(tmpTree->val));
}
} else if(strcmp(args[0],"quit") == 0){ //Quit Komutu
free(tmp);
return 0;
} else{
printf("Komut geçerli değil\n");
}
free(tmp);
return 1;
}
void append(char* tmp){
int len = strlen(tmp);
tmp[len] = ',';
}
void add(JRB t, char* tmp, char** args){
for(int i=2;i<5;i++){
if(i != 2) append(tmp);
strcat(tmp,args[i]);
}
(void) jrb_insert_int(t,atoi(args[1]),new_jval_s(strdup(tmp)));
}
|
C
|
#pragma once
//Ľ
#include"BiTree.h"
void createBST(BiTree &T,int a[]) {//a[0]ų
initTree(T);
BiTree p = T;
p->data = a[1];
//
for (int i = 2;i <= a[0];i++) {
p = T;
BiTree s = (BiTree)malloc(sizeof(BiNode));
s->data = a[i];
s->lchild = NULL;
s->rchild = NULL;
while (p) {
if (a[i] <= p->data) {
if (p->lchild) {//pӵʱ
p = p->lchild;
}
else {//pΪ
p->lchild = s;
break;
}
}
else {//a[i]ֵp->data
if (p->rchild) {
p = p->rchild;
}
else {
p->rchild = s;
break;
}
}
}
}
}
void insertBST(BiTree &T, ElemType a) {
BiTree p = T;
BiTree s = (BiTree)malloc(sizeof(BiNode));
s->data = a;
s->lchild = NULL;
s->rchild = NULL;
while (p) {
if (a <= p->data) {
if (p->lchild) {//pӵʱ
p = p->lchild;
}
else {//pΪ
p->lchild = s;
break;
}
}
else {//a[i]ֵp->data
if (p->rchild) {
p = p->rchild;
}
else {
p->rchild = s;
break;
}
}
}
}
BiTree searchBST(BiTree T,ElemType key,int length) {
BiTree p = T;
if (p == NULL) {
printf("%d\n",key);
return NULL;
}
if (p->data == key) {
printf("ɹҵ%dѷ,ҳΪ%d\n",key, length);
return p;
}
if (key < p->data) {
searchBST(p->lchild, key, length + 1);
}
else {
searchBST(p->rchild, key, length + 1);
}
}
/*
ɾϵĽ
*/
void Delete(BiTree &p) {
if (p->rchild == NULL) {//ҺΪյ
BiTree q = p;
p = p->lchild;
free(q);
}
else if (p->lchild == NULL) {//Ϊ
BiTree q = p;
p = p->rchild;
free(q);
}
else {//Ҷк
BiTree q = p;
BiTree s = p->lchild;
while (s->rchild != NULL) {
q = s;
s = s->rchild;
}
p->data = s->data;
if (q != p) {
q->rchild = s->lchild;
}
else {
p->lchild = s->lchild;
free(s);
}
}
}
void DeleteBST(BiTree &T, ElemType key) {
if (!T) {
printf("\nڹؼΪ%dĽ\n", key);
return;
}//ڹؼΪkey
else {
if (T->data == key) {
Delete(T);
}
else if (T->data > key) {
DeleteBST(T->lchild, key);
}
else {
DeleteBST(T->rchild, key);
}
}
}
//ӡ
void PrintBiT(BiTree T, int i) {
if (T) {
PrintBiT(T->rchild, i + 1);
for (int j = 0;j < i;j++)
printf(" |");
printf("%d\n", T->data);
PrintBiT(T->lchild, i + 1);
}
}
|
C
|
#include <unistd.h>
#include <fcntl.h>
#include <stdlib.h>
#include <sys/wait.h>
#include <assert.h>
#define MAXLINE 80
int main(){
int n, fd[2];
pid_t pid;
char line[MAXLINE];
if(pipe(fd)<0) exit(1);
if((pid = fork()) <0) exit(2);
if(pid>0){
close(fd[0]);
write(fd[1], "hello world\n", 12);
}
else {
close(fd[1]);
n = read(fd[0], line, MAXLINE);
write(1,line,n);
}
exit(0);
}
|
C
|
#include<stdio.h>
int maximum(int a[5]);
int deletion(int b[5],int index);
int main()
{
int a[5],i;
for(i=0;i<5;i++)
{scanf("%d",&a[i]);}
maximum(a);
return 0;
}
int maximum (int a[5])
{int i,index=0,max;
max=a[0];
for(i=0;i<5;i++)
{
if (max<a[i])
{
max=a[i];
index=i;
}
}
deletion (a,index);
}
int deletion(int b[5],int index)
{
int i;
for(i=index;i<5;i++)
{
b[i]=b[i+1];
}
for(i=0;i<4;i++)
printf("\t%d\n",b[i]);
}
|
C
|
/*
** EPITECH PROJECT, 2017
** C_Object
** File description:
** list3.c
*/
#include <string.h>
#include <stdlib.h>
#include "cobject.h"
#include "private_list.h"
#include "list.h"
__APPROVED_BY(Alexandre)
int *list_front(list_t *this)
{
if (this->_size == 0)
throw_list("list is empty");
return (this->_front->data);
}
__APPROVED_BY(Alexandre)
int *list_back(list_t *this)
{
if (this->_size == 0)
throw_list("list is empty");
return (this->_back->data);
}
__APPROVED_BY(Alexandre)
bool list_empty(list_t *this)
{
return (this->_size == 0);
}
__APPROVED_BY(Alexandre)
size_t list_size(list_t *this)
{
return (this->_size);
}
__APPROVED_BY(Alexandre)
void list_clear(list_t *this)
{
while (this->_size != 0)
list_pop_front(this);
}
|
C
|
#include "time.h"
#include "stdlib.h"
#include "stdio.h"
#include "math.h"
#include "stdbool.h"
#include "unistd.h"
#include "pthread.h"
#define DATA_SET_SIZE 50
typedef struct {
int x;
int y;
int z;
int label;
} datum;
typedef struct {
datum* unknownData;
datum* myData;
int startPoint;
int numCPU;
} threadInput;
void train (datum set[], bool setLabel);
// Need a predict function
void* predict (void* args);
// Figure out which point is the closest
void closest (datum* unknown, datum set[]);
// Gotta calculate distance somehow
double CalculateDistance (int p1[], int p2[], int len);
int main () {
printf ("Splitting up threads\n");
int i;
int numCPU = sysconf(_SC_NPROCESSORS_ONLN) - 1;
pthread_t pth[numCPU];
threadInput input [numCPU];
printf ("Number of worker CPUs: %i\n", numCPU);
printf ("Create Input...\n");
datum myData [DATA_SET_SIZE];
datum testData [DATA_SET_SIZE];
printf ("Training...\n");
srand (time (NULL)); // TEMP
train (myData, true);
train (testData, false);
printf ("Predicting...\n");
// Split up work between workers
for (i=0; i<numCPU; i++) {
// printf ("Starpoint for node %i should be: %i because numCPU = %i and DATA_SET_SIZE = %i\n", i, DATA_SET_SIZE / numCPU * i, numCPU, DATA_SET_SIZE);
input[i].unknownData = &(testData [DATA_SET_SIZE / numCPU * i]);
input[i].myData = myData;
input[i].startPoint = i;
input[i].numCPU = numCPU;
pthread_create (&pth[i], NULL, predict, &input[i]);
}
// Wait for all the workers to finish
for (i=0; i<numCPU; i++) {
pthread_join (pth [i], NULL);
}
return 0;
}
void train (datum set[], bool setLabel) {
int i;
if (setLabel) {
for (i=0; i<DATA_SET_SIZE; i++) {
set[i].x = rand() % 1000; // TEMP
set[i].y = rand() % 1000; // TEMP
set[i].z = rand() % 1000; // TEMP
set[i].label = set[i].x + set[i].y + set[i].z < 1500 ? 0 : 1; // TEMP
// printf ("(%i, %i, %i)\n", set[i].x, set[i].y, set[i].z);
}
} else {
for (i=0; i<DATA_SET_SIZE; i++) {
set[i].x = rand() % 1000; // TEMP
set[i].y = rand() % 1000; // TEMP
set[i].z = rand() % 1000; // TEMP
// printf ("(%i, %i, %i)\n", set[i].x, set[i].y, set[i].z);
}
}
}
void* predict (void* args) {
threadInput* imp = (threadInput*) args;
int count = imp->numCPU;
int i;
// printf ("Start Point = %i", imp->startPoint);
for (i=0; i<DATA_SET_SIZE / count; i++) {
closest (&(imp->unknownData [i]), imp->myData);
}
return NULL;
}
void closest (datum* unknown, datum set [DATA_SET_SIZE]) {
int unknownArray [3] = {unknown->x, unknown->y, unknown->z}; // TEMP
int setArray [3] = {set[0].x, set[0].y, set[0].z}; // TEMP
int len = 3; // TEMP
double bestDist = CalculateDistance (unknownArray, setArray, len);
int bestIndex = 0;
int i;
for (i=0; i<DATA_SET_SIZE; i++) {
setArray [0] = set[i].x; // TEMP
setArray [1] = set[i].y; // TEMP
setArray [2] = set[i].z; // TEMP
double dist = CalculateDistance (unknownArray, setArray, len);
// printf ("dist=%f best=%f\n", dist, bestDist);
if (dist < bestDist) {
bestDist = dist;
bestIndex = i;
}
}
unknown->label = set [bestIndex].label;
printf ("Distance from (%i, %i, %i){%i} to (%i, %i, %i){%i} is %f, making it a %i\n", unknown->x, unknown->y, unknown->z, unknown->x + unknown->y + unknown->z, set [bestIndex].x, set [bestIndex].y, set [bestIndex].z, set [bestIndex].x + set [bestIndex].y + set [bestIndex].z, bestDist, unknown->label);
}
double CalculateDistance (int p1[], int p2[], int len) {
int i;
int diff [len];
double ret = 0.0;
for (i=0; i<len; i++) {
diff [i] = p1[i] - p2[i];
diff [i] = diff [i] * diff [i];
ret += diff [i];
}
return sqrt (ret);
}
|
C
|
/*
** EPITECH PROJECT, 2019
** infinite sub source
** File description:
** source file for the infinite sub
*/
#include "my.h"
#include "infinite.h"
#include <stdlib.h>
void set_mid(char *result, int to_sub, int max)
{
for (int k = max; k > 0; k--) {
if (result[k] >= '1') {
result[k] = result[k] + -1;
break;
}
else {
if (to_sub < 0) {
to_sub = to_sub * -1;
}
result[k] = 10 - to_sub + 48;
to_sub = 1;
}
}
}
void set_mem(char *result, char *nbr)
{
result[0] = '0';
for (int m = 1; m < my_strlen(nbr) + 2; m++)
result[m] = nbr[m - 1];
result[my_strlen(nbr) + 1] = '\0';
}
char *infinite_sub(char *nbr1, char *nbr2)
{
int i = my_strlen(nbr1);
int j = my_strlen(nbr2);
int max = (i < j) ? j : i;
int max_sub = (i < j) ? i : j;
char *result = malloc(max + 2);
set_mem(result, ((i < j) ? nbr2 : nbr1));
char *subnum = subnum = (i < j) ? nbr1 : nbr2;
while (max_sub > 0) {
int to_sub = result[max] - subnum[max_sub - 1];
if (to_sub < 0) {
set_mid(result, to_sub, max);
} else {
result[max] = to_sub + 48;
}
max--;
max_sub--;
}
return (result);
}
|
C
|
#include "ustandard/ustandard_sys.h"
#include "ustandard/udevelop.h"
#include "ustandard/ump_simple.h"
#define MIN_TOTAL (10*1024)
#define DETAILS_USE_PERCENT (1)
#define LEN_BORDER (4)
struct ump_simple_node {
size_t offset;
size_t size_alloc;
size_t size_free;
};
struct ump_simple {
size_t total;
void* addr;
int total_nodes;
int num_nodes;
struct ump_simple_node* nodes;
size_t offset_content;
size_t size_content;
};
static void _ump_simple_free_node(struct ump_simple* ump, int idx);
struct ump_simple* ump_simple_create(size_t total)
{
struct ump_simple* ump = NULL;
if(total <= MIN_TOTAL) {
ulogerr("total less then MIN_TOTAL.\n");
ump = NULL;
return NULL;
}
void* p = um_malloc(total);
if(NULL == p) {
return ump;
}
ump = p;
ump->total = total;
ump->addr = p;
ump->total_nodes =
((total-sizeof(struct ump_simple)) * DETAILS_USE_PERCENT / 100)
/ sizeof(struct ump_simple_node);
ulogdbg("total_nodes = %d.\n", ump->total_nodes);
ump->num_nodes = 0;
ump->nodes = (void*)ump + sizeof(struct ump_simple);
ump->offset_content = sizeof(struct ump_simple) +
ump->total_nodes * sizeof(struct ump_simple_node);
ump->size_content = ump->total - ump->offset_content;
ulogdbg("offset_content = %zd, size_content = %zd.\n",
ump->offset_content, ump->size_content);
/* set the first node. */
struct ump_simple_node* node = &ump->nodes[0];
node->offset = 0;
node->size_alloc = 0;
node->size_free = ump->size_content;
ump->num_nodes ++;
return ump;
}
int ump_simple_destroy(struct ump_simple* ump)
{
int ret = 0;
if(NULL != ump) {
um_free(ump);
ump = NULL;
}
return ret;
}
void* ump_simple_alloc(struct ump_simple* ump, size_t size)
{
void* ptr = NULL;
size_t size_alloc = um_align4(size) + LEN_BORDER + LEN_BORDER;
struct ump_simple_node* node = NULL;
struct ump_simple_node* node_new = NULL;
int i;
for(i=0; i<ump->num_nodes; i++) {
if(ump->nodes[i].size_free >= size_alloc) {
node = &ump->nodes[i];
break;
}
}
if(NULL != node) {
if(0 == node->size_alloc) {
node->size_alloc = size_alloc;
node->size_free -= size_alloc;
ptr = (void*) ump->addr + ump->offset_content
+ node->offset + LEN_BORDER;
}
else {
/* need to add nodes. */
if(ump->num_nodes >= ump->total_nodes) {
ulogerr("nodes full.\n");
}
else {
size_t size_free = node->size_free - size_alloc;
int j;
for(j=ump->num_nodes-1; j>=(i+1); j--) {
ump->nodes[j+1] = ump->nodes[j];
}
ump->num_nodes ++;
node->size_free = 0;
node_new = node + 1;
node_new->offset = node->offset + node->size_alloc;
node_new->size_alloc = size_alloc;
node_new->size_free = size_free;
ptr = (void*) ump->addr + ump->offset_content
+ node_new->offset + LEN_BORDER;
}
}
}
return ptr;
}
int ump_simple_free(struct ump_simple* ump, void* ptr)
{
int ret = 0;
if(ump == NULL
|| ptr == NULL
|| ptr < (ump->addr + ump->offset_content + LEN_BORDER)
|| ptr >= (ump->addr + ump->total)) {
ulogerr("ump_simple_free. ptr(%p) not free.\n", ptr);
ret = -1;
return ret;
}
size_t offset_ptr = ptr - ((void*)ump->addr + ump->offset_content) - LEN_BORDER;
int freed = 0;
int i;
for(i=0; i<ump->num_nodes; i++) {
struct ump_simple_node* tmp = &ump->nodes[i];
if(tmp->offset > offset_ptr) {
ulogerr("node not found.\n");
break;
}
if(tmp->offset == offset_ptr) {
_ump_simple_free_node(ump, i);
freed = 1;
break;
}
/* continue search. */
}
if(!freed) {
ulogerr("ump_simple_free. ptr(%p) not free.\n", ptr);
ret = -1;
return ret;
}
return ret;
}
void _ump_simple_free_node(struct ump_simple* ump, int idx)
{
struct ump_simple_node* node_free = ump->nodes + idx;
struct ump_simple_node* node_prev = NULL;
struct ump_simple_node* node_next = NULL;
node_next = (idx==(ump->num_nodes-1))?NULL:(node_free + 1);
int idx_move;
int interval_move = 0;
if(0 == idx) {
node_free->size_free += node_free->size_alloc;
node_free->size_alloc = 0;
if(NULL != node_next && 0 == node_next->size_alloc) {
node_free->size_free += node_next->size_free;
idx_move = 2;
interval_move = 1;
}
else {
interval_move = 0;
}
}
else {
node_prev = node_free - 1;
node_prev->size_free += (node_free->size_alloc + node_free->size_free);
if(NULL != node_next && 0 == node_next->size_alloc) {
node_prev->size_free += node_next->size_free;
interval_move = 2;
}
else {
interval_move = 1;
}
idx_move = idx + interval_move;
}
if(interval_move > 0) {
int i;
for(i=idx_move;i<ump->num_nodes;i++) {
ump->nodes[i-interval_move] = ump->nodes[i];
}
ump->num_nodes -= interval_move;
}
}
int ump_sumple_get_node_number(struct ump_simple* ump)
{
int num = 0;
num = ump->num_nodes;
return num;
}
int ump_sumple_get_node(struct ump_simple* ump,
int idx, int num, struct ump_simple_node* nodes)
{
int retn = 0;
memset(nodes, 0, sizeof(*nodes)*num);
if(idx>=0 && idx<ump->num_nodes) {
retn = um_min(ump->num_nodes - idx, num);
int i;
for(i=0; i<retn; i++) {
nodes[i] = ump->nodes[idx+i];
}
}
return retn;
}
|
C
|
//Accepted
#include<stdio.h>
int main()
{
unsigned long long int i,sum[50003],x;
sum[0]=0;
for(i=1;i<=50000;i++)
{
sum[i]=i*i*i+sum[i-1];
}
while(scanf("%llu",&x)!=EOF)
{
printf("%llu\n",sum[x]);
}
return 0;
}
|
C
|
main (argc, argv)
char **argv;
{
register void *p, *sp;
int local;
extern void *alloca (), *getsp ();
printf ("&local = %P (%d)\n", &local, &local);
sp = getsp ();
printf ("sp antes = %P (%d)\n", sp, sp);
if (argv[1])
p = alloca (atoi (argv[1]));
else
p = alloca (0);
sp = getsp ();
printf ("sp depois = %P (%d)\n", sp, sp);
printf ("rea = %P (%d)\n", p, p);
sleep (2);
exit (0);
}
|
C
|
/*
* knightrider.c
*
* Created: 03.10.2020 21:34:32
* Author : Michal
*/
/* Defines -----------------------------------------------------------*/
#define LED_RED1 PC0
#define LED_RED2 PC1
#define LED_RED3 PC2
#define LED_RED4 PC3
#define LED_RED5 PC4
#define BTN PD0
#define BLINK_DELAY 150
#ifndef F_CPU
#define F_CPU 16000000 // CPU frequency in Hz required for delay
#endif
/* Includes ----------------------------------------------------------*/
#include <util/delay.h> // Functions for busy-wait delay loops
#include <avr/io.h> // AVR device-specific IO definitions
/* Functions ---------------------------------------------------------*/
/**
* Main function where the program execution begins. Toggle two LEDs
* when a push button is pressed.
*/
int main(void)
{
/* Settings of ports */
/* All diodes */
DDRC = DDRC | (1<<LED_RED1);
PORTC = PORTC & ~(1<<LED_RED1);
DDRC = DDRC | (1<<LED_RED2);
PORTC = PORTC & ~(1<<LED_RED2);
DDRC = DDRC | (1<<LED_RED3);
PORTC = PORTC & ~(1<<LED_RED3);
DDRC = DDRC | (1<<LED_RED4);
PORTC = PORTC & ~(1<<LED_RED4);
DDRC = DDRC | (1<<LED_RED5);
PORTC = PORTC & ~(1<<LED_RED5);
/* Button */
DDRD = DDRD & ~(1<<BTN);
PORTD = PORTD | (1<<BTN);
// Infinite loop
while (1)
{
if (bit_is_clear(PIND, BTN))
{
PORTC = PORTC ^(1<<LED_RED1); /*Turning on first LED */
_delay_ms(BLINK_DELAY);
PORTC = PORTC ^(1<<LED_RED1); /*Turning off first LED */
PORTC = PORTC ^(1<<LED_RED2); /*Turning on second LED */
_delay_ms(BLINK_DELAY);
PORTC = PORTC ^(1<<LED_RED2);
PORTC = PORTC ^(1<<LED_RED3);
_delay_ms(BLINK_DELAY);
PORTC = PORTC ^(1<<LED_RED3);
PORTC = PORTC ^(1<<LED_RED4);
_delay_ms(BLINK_DELAY);
PORTC = PORTC ^(1<<LED_RED4);
PORTC = PORTC ^(1<<LED_RED5);
_delay_ms(BLINK_DELAY);
PORTC = PORTC ^(1<<LED_RED5); /*Reversing of process */
PORTC = PORTC ^(1<<LED_RED4);
_delay_ms(BLINK_DELAY);
PORTC = PORTC ^(1<<LED_RED4);
PORTC = PORTC ^(1<<LED_RED3);
_delay_ms(BLINK_DELAY);
PORTC = PORTC ^(1<<LED_RED3);
PORTC = PORTC ^(1<<LED_RED2);
_delay_ms(BLINK_DELAY);
PORTC = PORTC ^(1<<LED_RED2);
}
}
// Will never reach this
return 0;
}
|
C
|
/*
** EPITECH PROJECT, 2020
** main
** File description:
** main
*/
#include "my.h"
void usage(void)
{
my_putstr("\n =========================================================\n");
my_putstr("| Welcome to my_defender |\n");
my_putstr("| |\n");
my_putstr("| Launch game with ./my_defender map |\n");
my_putstr("| |\n");
my_putstr("| Map is made of '1', '2', '3', corresponding to the |\n");
my_putstr("| monsters that will spawn and 'V' corresponding to the |\n");
my_putstr("| end of the map. |\n");
my_putstr("| |\n");
my_putstr("| Use mouse to interact with the game, and Escape to |\n");
my_putstr("| to enter pause menu |\n");
my_putstr(" =========================================================\n");
}
int main(int ac, char **av)
{
sfRenderWindow *window;
sfVideoMode mode = {1920, 1080, 32};
sfMusic *anthem_music;
if (ac != 2) {
my_putstr("Try ./my_defender -h to learn how to launch the game\n");
return (0);
}
if (ac == 2 && my_strcmp(av[1], "-h") == 0) {
usage();
return (0);
}
anthem_music = sfMusic_createFromFile("assets/anthem.ogg");
sfMusic_setVolume(anthem_music, 6);
sfMusic_setLoop(anthem_music, sfTrue);
sfMusic_play(anthem_music);
window = sfRenderWindow_create(mode, "Defender", sfFullscreen, NULL);
sfRenderWindow_setFramerateLimit(window, 60);
defender(window, av[1]);
}
|
C
|
#include <stdio.h>
/*
void turn(int (*p)[4])
{
int brr[4][4] = {0,};
int i,j,k;
for(j=3;j>=0;j--)
{
for(i=0;i<4;i++)
{
for(k=0;k<4;k++)
brr[j][i] = arr[i][k];
}
}
}
*/
void doChange(int (*arr)[4], int (*brr)[4])
{
int i, j;
int k = 3;
for(i = 0;i<4;i++)
{
for(int j=0; j<4; j++)
{
brr[j][k] = arr[i][j];
}
k--;
}
}
void doPrint(int (*p)[4])
{
int i, j;
for(i=0;i<4;i++){
for(j=0;j<4;j++)
{
printf("%4d", p[i][j]);
}
printf("\n");
}
}
void main()
{
int i,j;
int arr[4][4] = {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16};
int brr[4][4];
doPrint(arr);
printf("\n");
doChange(arr,brr);
doPrint(brr);
printf("\n");
doChange(brr, arr);
doPrint(arr);
}
|
C
|
#include "protocol.h"
#include "ui.h"
//ilość wyswietlanych wiadomosci posczegolnego typu
int all_msg_num = 0;
int priv_msg_num = 0;
int room_msg_num = 0;
//ilość wyświetatlanych kontaktow danego typu
int room_cnt_num = 0;
int ppl_cnt_num = 0;
//liczba lini mozliwych do zadrukowania i iterator po tablicy z trescia dla okienka wiadomosci
int recived_lines = RECIVED_HEIGHT - 2;
int recived_iter;
//liczba lini mozliwych do zadrukowania i iterator po tablicy z trescia dla okienka kontaktow
int contacts_iter = 0;
int contacts_lines = CONTACTS_HEIGHT - 2;
//tytuly okienek wiadomosci i kontaktow
char* msg_title;
char* cnt_title;
//komunikat wyswietlany w oknie komend
char command_message2[RESPONSE_LENGTH * 2];
char* command_message;
//licznik uzywany przy wysylaniu zapytan o liste kontaktow i pokoi
int counter = 0;
//PID procesu przetwarzającego heartbeat
int child_pid;
int get_child_pid(){
return child_pid;
}
void set_child_pid(int pid){
child_pid = pid;
}
void ui_main(){
signal(SIGUSR1, refr_recived);
signal(SIGUSR2, refr_contacts);
signal(SIGALRM, get_contacts_lists);
all_msg_num = 0;
priv_msg_num = 0;
room_msg_num = 0;
//poczatek rysowania okienek
int startx = 1;
int starty = 2;
//wcisniety klawisz klawiatury
int c;
//iteratory: aktywne okno, aktywne kontakty, aktywne wiadomosci
int active_window = 0;
int active_contacts = 0;
int active_messages = 0;
init_strings();
//inicjalizacja ncurses
initscr();
clear();
noecho();
cbreak();
//tworzenie okienek
recived_win = newwin(RECIVED_HEIGHT, RECIVED_WIDTH, starty, startx);
contacts_win = newwin(CONTACTS_HEIGHT, CONTACTS_WIDTH, starty, startx + RECIVED_WIDTH);
command_win = newwin(COMMAND_HEIGHT, COMMAND_WIDTH, starty + RECIVED_HEIGHT, startx);
//wybor aktywnych okien
active_win = recived_win;
active_msg = all_messages;
active_cnt = people_contacts;
//ustawienie iteratora wiadomosci tak by byly wyswietlane ostatnie wiadomosci
recived_iter = 0;
msg_title = "All messages";
cnt_title = "People";
print_content(recived_win, msg_title, active_msg, recived_iter, recived_lines);
print_content(contacts_win, cnt_title, active_cnt, contacts_iter, contacts_lines);
command_window_drawing(command_win, "Command");
curs_set(0);
alarm(1); //żeby pobralo pierwszy raz listy kontaktow
//petla glowna
while(1){
keypad(active_win, TRUE);
nodelay(active_win, TRUE);
process_ipc_msgs();
process_server_responses();
c = wgetch(active_win);
switch(c){//sprawdza ktory klawisz wcisnieto
case KEY_UP://w gore (przesuwanie tresci)
switch(active_window){
case RECIVED:
if(recived_iter > 0){
recived_iter--;
kill(getpid(), SIGUSR1);
}
break;
case CONTACTS:
if(contacts_iter > 0){
contacts_iter--;
kill(getpid(), SIGUSR2);
}
break;
}
break;
case KEY_DOWN://w dol (przesuwanie tresci)
switch(active_window){
case RECIVED:
switch(active_messages){
case MESSAGES_ALL:
if(recived_iter + recived_lines <= all_msg_num){
recived_iter++;
}
break;
case MESSAGES_PRIV:
if(recived_iter + recived_lines <= priv_msg_num){
recived_iter++;
}
break;
case MESSAGES_ROOM:
if(recived_iter + recived_lines <= room_msg_num){
recived_iter++;
}
break;
}
kill(getpid(), SIGUSR1);
break;
case CONTACTS:
switch(active_contacts){
case CONTACTS_PEOPLE:
if(contacts_iter + contacts_lines <= ppl_cnt_num){
contacts_iter++;
}
break;
case CONTACTS_ROOMS:
if(contacts_iter + contacts_lines <= room_cnt_num){
contacts_iter++;
}
break;
}
kill(getpid(), SIGUSR2);
break;
}
break;
case KEY_LEFT://w lewo (zmiana wyswietlanych wiadomosci lub kontaktow)
switch(active_window){
case RECIVED:
if(active_messages > 0){
active_messages--;
}else{
active_messages = 2;
}
switch(active_messages){
case MESSAGES_ALL:
active_msg = all_messages;
recived_iter = all_msg_num - recived_lines;
if(recived_iter < 0){
recived_iter = 0;
}
msg_title = "All messages";
break;
case MESSAGES_PRIV:
active_msg = priv_messages;
recived_iter = priv_msg_num - recived_lines;
if(recived_iter < 0){
recived_iter = 0;
}
msg_title = "Private messages";
break;
case MESSAGES_ROOM:
active_msg = room_messages;
recived_iter = room_msg_num - recived_lines;
if(recived_iter < 0){
recived_iter = 0;
}
msg_title = "Room messages";
break;
}
kill(getpid(), SIGUSR1);
break;
case CONTACTS:
if(active_contacts == 0){
active_contacts = 1;
}else
active_contacts = 0;
switch(active_contacts){
case CONTACTS_PEOPLE:
active_cnt = people_contacts;
cnt_title = "People";
contacts_iter = 0;
break;
case CONTACTS_ROOMS:
active_cnt = rooms_contacts;
cnt_title = "Channels";
contacts_iter = 0;
break;
}
kill(getpid(), SIGUSR2);
break;
}
break;
case KEY_RIGHT://w prawo (zmiana wyswietlanych wiadomosci lub kontaktow)
switch(active_window){
case RECIVED:
if(active_messages < 2){
active_messages++;
}else{
active_messages = 0;
}
switch(active_messages){
case MESSAGES_ALL:
active_msg = all_messages;
recived_iter = all_msg_num - recived_lines;
if(recived_iter < 0){
recived_iter = 0;
}
msg_title = "All messages";
break;
case MESSAGES_PRIV:
active_msg = priv_messages;
recived_iter = priv_msg_num - recived_lines;
if(recived_iter < 0){
recived_iter = 0;
}
msg_title = "Private messages";
break;
case MESSAGES_ROOM:
active_msg = room_messages;
recived_iter = room_msg_num - recived_lines;
if(recived_iter < 0){
recived_iter = 0;
}
msg_title = "Room messages";
break;
}
kill(getpid(), SIGUSR1);
break;
case CONTACTS:
if(active_contacts == 0){
active_contacts = 1;
}else
active_contacts = 0;
switch(active_contacts){
case CONTACTS_PEOPLE:
active_cnt = people_contacts;
cnt_title = "People";
contacts_iter = 0;
break;
case CONTACTS_ROOMS:
active_cnt = rooms_contacts;
cnt_title = "Channels";
contacts_iter = 0;
break;
}
kill(getpid(), SIGUSR2);
break;
}
break;
case 10://ENTER - wpisanie komendy (jezeli aktywne jest okno komend)
if(active_win == command_win){
get_command();
}
break;
case '\t'://TAB - zmiana aktywnego okienka
active_window = (active_window + 1) % 3;
switch(active_window){
case RECIVED: active_win = recived_win;
kill(getpid(), SIGUSR1);
break;
case CONTACTS: active_win = contacts_win;
kill(getpid(), SIGUSR2);
break;
case COMMANDS: active_win = command_win;
break;
}
break;
}
//wyswietlanie tresci
if(get_channel() != NULL){
mvprintw(1,1," ");
mvprintw(1,1,"Username: %s\tChannel: %s", get_nick(), get_channel());
}else{
mvprintw(1,1,"Username: %s\tChannel: ", get_nick());
}
refresh();
print_content(recived_win, msg_title, active_msg, recived_iter, recived_lines);
print_content(contacts_win, cnt_title, active_cnt, contacts_iter, contacts_lines);
command_window_drawing(command_win, "Command");
//wyjscie z petli jezeli wpisano komende logout
if(command_message != NULL){
print_command_message(command_message);
if(strcmp(command_message, "logged out") == 0){
kill(child_pid, SIGTERM);
break;
}
}
}
clrtoeol();
refresh();
//usuniecie okienek
delwin(recived_win);
delwin(contacts_win);
delwin(command_win);
//zamkniecie ncurses
endwin();
}
void init_strings(){
int i;
for(i = 0; i < MSG_BUF_SIZE; ++i){
priv_messages[i] = '\0';
room_messages[i] = '\0';
all_messages[i] = '\0';
}
for(i = 0; i < MAX_SERVERS_NUMBER * MAX_USERS_NUMBER; ++i){
people_contacts[i] = '\0';
rooms_contacts[i] = '\0';
}
}
void print_content(WINDOW *win, char* title, char** content, int begin, int nlines){
int x = 1, y = 1, i = 0;
//wclear(win);
box(win,0,0);
//jezeli okno jest aktywne to wyroznia tytul
if(win == active_win){
wattron(win, A_REVERSE);
mvwprintw(win, 0, 2, "%s", title);
wattroff(win, A_REVERSE);
}else{
mvwprintw(win, 0, 2, "%s", title);
}
//drukowanie tresci
while((content[begin + i] != '\0') && (i < nlines)){
mvwprintw(win, y + i, x, "%s", content[begin + i] );
++i;
}
wrefresh(win);
}
void command_window_drawing(WINDOW *win, char* title){
box(win,0,0);
//jezeli okno jest aktywne to wyroznia tytul
if(win == active_win){
wattron(win, A_REVERSE);
mvwprintw(win, 0, 2, "%s", title);
wattroff(win, A_REVERSE);
}else{
mvwprintw(win, 0, 2, "%s", title);
}
wrefresh(win);
}
void get_command(){
kill(child_pid, SIGCONT);
echo();
nocbreak();
curs_set(1);
nodelay(active_win, FALSE);
int i;
for(i = 0; i<299; ++i){
command[i] = '\0';
}
mvwgetstr(command_win, 1, 1, command);
command[299] = '\0';
command_message = parser(command, people_contacts);
nodelay(active_win, TRUE);
curs_set(0);
cbreak();
noecho();
wclear(command_win);
kill(child_pid, SIGSTOP);
}
void print_command_message(char* message){
mvwprintw(command_win, 6, 1, "%s", message);
}
void add_message(char* message, int msg_type){
int i;
//wszystkie wiadomosci
if(all_msg_num < MSG_BUF_SIZE){
all_messages[all_msg_num] = (char*)malloc(sizeof(char) * (MAX_MSG_LENGTH + USER_NAME_MAX_LENGTH +10));
strcpy(all_messages[all_msg_num], message);
all_msg_num++;
}else{
for(i = 0; i < MSG_BUF_SIZE - 1; ++i){
free(all_messages[i]);
all_messages[i] = (char*)malloc(sizeof(char) * (MAX_MSG_LENGTH + USER_NAME_MAX_LENGTH +10));
strcpy(all_messages[i], all_messages[i+1]);
}
free(all_messages[MSG_BUF_SIZE - 1]);
all_messages[MSG_BUF_SIZE - 1] = (char*)malloc(sizeof(char) * (MAX_MSG_LENGTH + USER_NAME_MAX_LENGTH +10));
strcpy(all_messages[MSG_BUF_SIZE - 1], message);
}
recived_iter = all_msg_num - recived_lines;
if(recived_iter < 0){
recived_iter = 0;
}
//wiadomosc pokoju
if(msg_type == PUBLIC){
FILE *f = fopen(get_channel_messages_file_name(),"a");
fprintf(f,"%s\n",message);
fclose(f);
if(room_msg_num < MSG_BUF_SIZE){
room_messages[room_msg_num] = (char*)malloc(sizeof(char) * (MAX_MSG_LENGTH + USER_NAME_MAX_LENGTH +10));
strcpy(room_messages[room_msg_num], message);
room_msg_num++;
}else{
for(i = 0; i < MSG_BUF_SIZE - 1; ++i){
free(room_messages[i]);
room_messages[i] = (char*)malloc(sizeof(char) * (MAX_MSG_LENGTH + USER_NAME_MAX_LENGTH +10));
strcpy(room_messages[i], room_messages[i+1]);
}
free(room_messages[MSG_BUF_SIZE - 1]);
room_messages[MSG_BUF_SIZE - 1] = (char*)malloc(sizeof(char) * (MAX_MSG_LENGTH + USER_NAME_MAX_LENGTH +10));
strcpy(room_messages[MSG_BUF_SIZE - 1], message);
}
recived_iter = room_msg_num - recived_lines;
if(recived_iter < 0){
recived_iter = 0;
}
}
//wiadomosc prywatna
if(msg_type == PRIVATE){
FILE *f = fopen(get_private_messages_file_name(),"a");
fprintf(f,"%s\n",message);
fclose(f);
if(priv_msg_num < MSG_BUF_SIZE){
priv_messages[priv_msg_num] = (char*)malloc(sizeof(char) * (MAX_MSG_LENGTH + USER_NAME_MAX_LENGTH +10));
strcpy(priv_messages[priv_msg_num], message);
priv_msg_num++;
}else{
for(i = 0; i < MSG_BUF_SIZE - 1; ++i){
free(priv_messages[i]);
priv_messages[i] = (char*)malloc(sizeof(char) * (MAX_MSG_LENGTH + USER_NAME_MAX_LENGTH +10));
strcpy(priv_messages[i], priv_messages[i+1]);
}
free(priv_messages[MSG_BUF_SIZE - 1]);
priv_messages[MSG_BUF_SIZE - 1] = (char*)malloc(sizeof(char) * (MAX_MSG_LENGTH + USER_NAME_MAX_LENGTH +10));
strcpy(priv_messages[MSG_BUF_SIZE - 1], message);
}
recived_iter = priv_msg_num - recived_lines;
if(recived_iter < 0){
recived_iter = 0;
}
}
kill(getpid(), SIGUSR1);
}
void process_ipc_msgs(){
MSG_CHAT_MESSAGE chmsg;
MSG_USERS_LIST ulist;
int i, k;
//odbiór nowej wiadomosci
if(msgrcv(get_my_que_id(), &chmsg, sizeof(MSG_CHAT_MESSAGE) - sizeof(long), MESSAGE, IPC_NOWAIT) != -1){
char *m = (char*)malloc(sizeof(char) * (MAX_MSG_LENGTH + USER_NAME_MAX_LENGTH +10));
for(i = 0; i < (MAX_MSG_LENGTH + USER_NAME_MAX_LENGTH +10); ++i){
m[i] = '\0';
}
strcat(m, chmsg.send_time);
strcat(m, " <");
strcat(m, chmsg.sender);
strcat(m, "> ");
strcat(m, chmsg.message);
add_message(m, chmsg.msg_type);
}
//odbior listy userow
if(msgrcv(get_my_que_id(), &ulist, sizeof(MSG_USERS_LIST) - sizeof(long), USERS_LIST_STR, IPC_NOWAIT) != -1){
for(i = 0; i < MAX_SERVERS_NUMBER * MAX_USERS_NUMBER; ++i){
people_contacts[i] = NULL;
}
ppl_cnt_num = 0;
i=0;
while(ulist.users[i][0] != '\0' && i < MAX_SERVERS_NUMBER * MAX_USERS_NUMBER){
people_contacts[i] = (char*)malloc(USER_NAME_MAX_LENGTH * sizeof(char));
k = 0;
while(ulist.users[i][k] != '\0'){
people_contacts[i][k] = ulist.users[i][k];
k++;
}
ppl_cnt_num++;
i++;
}
kill(getpid(), SIGUSR2);
}
//lista pokoi
if(msgrcv(get_my_que_id(), &ulist, sizeof(MSG_USERS_LIST) - sizeof(long), ROOMS_LIST_STR, IPC_NOWAIT) != -1){
for(i = 0; i < MAX_SERVERS_NUMBER * MAX_USERS_NUMBER; ++i){
rooms_contacts[i] = NULL;
}
room_cnt_num = 0;
i=0;
while(ulist.users[i][0] != '\0' && i < MAX_SERVERS_NUMBER * MAX_USERS_NUMBER){
rooms_contacts[i] = (char*)malloc(USER_NAME_MAX_LENGTH * sizeof(char));
k = 0;
while(ulist.users[i][k] != '\0'){
rooms_contacts[i][k] = ulist.users[i][k];
k++;
}
room_cnt_num++;
i++;
}
kill(getpid(), SIGUSR2);
}
}
void process_server_responses(){
MSG_RESPONSE resp;
if(msgrcv(get_my_que_id(), &resp, sizeof(MSG_RESPONSE) - sizeof(long), RESPONSE, IPC_NOWAIT) != -1){
if(resp.response_type == PING){
MSG_REQUEST req;
req.type = REQUEST;
req.request_type = PONG;
strcpy(req.user_name, get_nick());
msgsnd(get_serv_que_id(), &req, sizeof(MSG_REQUEST) - sizeof(long), 0);
}
if(resp.response_type == MSG_SEND){
}
if(resp.response_type == MSG_NOT_SEND){
int i;
for (i = 0; i < RESPONSE_LENGTH * 2; ++i){
command_message2[i] = '\0';
}
strcpy(command_message2, "Message not send: ");
strcat(command_message2, resp.content);
print_command_message(command_message2);
}
if((resp.response_type == ENTERED_ROOM_SUCCESS) || (resp.response_type == CHANGE_ROOM_SUCCESS)){
int i;
for(i = 0; i < RESPONSE_LENGTH * 2; ++i){
command_message2[i] = '\0';
}
strcpy(get_channel(), get_temp_channel());
strcpy(command_message2, "You've just entered to channel ");
strcat(command_message2, get_temp_channel());
print_command_message(command_message2);
}
if((resp.response_type == ENTERED_ROOM_FAILED) || (resp.response_type == CHANGE_ROOM_FAILED)){
int i;
for (i = 0; i < RESPONSE_LENGTH * 2; ++i){
command_message2[i] = '\0';
}
strcpy(command_message2, "Entering to channel failed: ");
strcat(command_message2, resp.content);
print_command_message(command_message2);
}
if(resp.response_type == LEAVE_ROOM_SUCCESS){
}
if(resp.response_type == LEAVE_ROOM_FAILED){
}
if(resp.response_type == LOGOUT_SUCCESS){
logout();
command_message = (char*)malloc(15 * sizeof(char));
int i;
for(i = 0; i < 15; ++i){
command_message[i] = '\0';
}
strcpy(command_message, "logged_out");
}
}
}
void process_heartbeat(){
MSG_RESPONSE resp;
if(msgrcv(get_my_que_id(), &resp, sizeof(MSG_RESPONSE) - sizeof(long), RESPONSE, IPC_NOWAIT) != -1){
if(resp.response_type == PING){
MSG_REQUEST req;
req.type = REQUEST;
req.request_type = PONG;
strcpy(req.user_name, get_nick());
msgsnd(get_serv_que_id(), &req, sizeof(MSG_REQUEST) - sizeof(long), 0);
}else{
msgsnd(get_my_que_id(), &resp, sizeof(MSG_RESPONSE) - sizeof(long), 0);
}
}
}
void refr_recived(){
wclear(recived_win);
box(recived_win,0,0);
wrefresh(recived_win);
}
void refr_contacts(){
wclear(contacts_win);
box(contacts_win,0,0);
wrefresh(contacts_win);
}
void get_contacts_lists(){
MSG_REQUEST req;
req.type = REQUEST;
req.request_type = USERS_LIST;
strcpy(req.user_name, get_nick());
msgsnd(get_serv_que_id(), &req, sizeof(MSG_REQUEST) - sizeof(long), 0);
req.request_type = ROOMS_LIST;
msgsnd(get_serv_que_id(), &req, sizeof(MSG_REQUEST) - sizeof(long), 0);
alarm(GETTING_CONTACTS_TIME_INTERVAL);
}
|
C
|
#include<stdio.h>
int no_main();
void fun(){
// calling function to print
no_main();
exit(0);
}
int no_main()
{
printf("printing wthout uisng main");
return 0;
}
|
C
|
/*
ļmail.cgi.c
汾v 1.01
˵ύЧݣ e-mail
ߣavatar liu
䣺[email protected]
ڣ20011111
*/
#include <stdio.h>
#include <string.h>
#include "cgi-lib.h"
#include "html-lib.h"
#include "string-lib.h"
#include "config-lib.h"
#define WEBADMIN cgi_val(configs,"WEBADMIN")
#define SENDMAIL cgi_val(configs,"SENDMAIL")
#define TO cgi_val(configs,"TO")
int main()
{
LIST_STRU entries;
LIST_STRU configs;
char *configname = "simple-webmail.conf";
FILE *mail;
char *dest,*name,*from,*subject,*content;
char command[256];
html_header();
read_cgi_input(&entries);
read_configs(&configs,configname);
if( (is_field_empty(entries,"name")) && (is_field_empty(entries,"from")) &&
(is_field_empty(entries,"subject")) && (is_field_empty(entries,"content")) )
{
printf("!");
}
else
{
if (is_field_empty(entries,"to"))
dest = strdup(TO);
else
dest = strdup(cgi_val(entries,"to"));
if (!xstrcmp("*@*.*",dest))
{
printf("ռ %s DZʼʽ *@*.*\n",dest);
exit(-1);
}
name = strdup(cgi_val(entries,"name"));
from = strdup(cgi_val(entries,"from"));
subject = strdup(cgi_val(entries,"subject"));
if (dest[0] == '\0')
strcpy(dest,WEBADMIN);
sprintf(command,"%s %s",SENDMAIL,dest);
mail = popen(command,"w");
if (mail == NULL)
{
html_begin("ϵͳ!");
printf("ϵͳ!");
printf("뷢Ÿ %s \r\n",WEBADMIN);
printf("<hr>\r\nWEBʼͳ v 0.1 . ߣ ");
printf("<i>%s</i>.\r\n",WEBADMIN);
exit(-1);
html_end();
}
else
{
content = strdup(cgi_val(entries,"content"));
fprintf(mail,"From: %s (%s)\n",from,name);
fprintf(mail,"Subject: %s\n",subject);
fprintf(mail,"To: %s\n",dest);
fprintf(mail,"X-Sender: %s\n\n",WEBADMIN);
if (REMOTE_ADDR != NULL)
fprintf(mail," IP ַ %s\n",REMOTE_ADDR);
// http ػжǷдʾԴַ 2003.08.17
if (HTTP_X_FORWARDED_FOR != NULL)
fprintf(mail,"ǰIPַ %s\n",HTTP_X_FORWARDED_FOR);
if (HTTP_CLIENT_IP != NULL)
fprintf(mail,"ַ %s\n",HTTP_CLIENT_IP);
fprintf(mail,"%s\n\n",content);
pclose(mail);
html_begin("ʼͳɹ");
printf("ʼͳɹ");
printf("㷢µϢ:\r\n<pre>\r\n");
printf(": %s \r\n",dest);
printf(": %s (%s)\r\n",from,name);
printf("ꡡ: %s\r\n\r\n",subject);
printf("%s\r\n</pre>\r\n",content);
if (REMOTE_ADDR != NULL)
printf(" IP ַ %s<br>\n",REMOTE_ADDR);
// http ػжǷдʾԴַ 2003.08.17
if (HTTP_X_FORWARDED_FOR != NULL)
printf("ǰIPַ %s<br>\n",HTTP_X_FORWARDED_FOR);
if (HTTP_CLIENT_IP != NULL)
printf("ַ %s<br>\n",HTTP_CLIENT_IP);
printf("ллʹ!<p>\r\n");
printf("<hr>\r\nWEBʼͳ v 0.1 . ߣ ");
printf("<i>%s</i>.\r\n",WEBADMIN);
html_end();
}
}
list_clear(&entries);
list_clear(&configs);
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define SIZE 2001
int main(int argc, char * * argv)
{
int i=0;//counter for the loop
// int ch=0;
char oneline[SIZE];
int count=0;
int count1=0;
// FILE* fptr;
for(i=1;i<argc;i++)
{
if(strcmp(argv[i],"--help")==0)
{
printf("\nUsage: grep-lite [OPTION]... PATTERN\nSearch for PATTERN in standard input. PATTERN is a\nstring. grep-lite will search standard input line by\nline, and (by default) print out those lines which\ncontain pattern as a substring.\n\n -v, --invert-match print non-matching lines\n -n, --line-number print line numbers with output\n -q, --quiet suppress all output\n\nExit status is 0 if any line is selected, 1 otherwise;\nif any error occurs, then the exit status is 2.\n\n");
}
}
for(i=1;i<argc-1;i++)
{
if((strcmp(argv[i],"-v")!=0) && (strcmp(argv[i],"-n")!=0) && (strcmp(argv[i],"-q")!=0) && (strcmp(argv[i],"--invert-match")!=0) && (strcmp(argv[i],"--line-number")!=0) && (strcmp(argv[i],"--quiet")!=0))
{
fprintf(stderr, "You have entered bogus command line arguments\n");
return 2;
}
}
if(argv[argc-1][0]=='-')
{
fprintf(stderr, "You have begun the last argument with a minus sign.\n");
return 2;
}
while(fgets(oneline,SIZE,stdin)!=NULL)
{
++count;
if(argc>2)
{
for(i=1;i<argc-1;i++)
{
if(((strcmp(argv[i],"-v")==0) && (strcmp(argv[i+1],"-n")!=0) && (strcmp(argv[i-1],"-n")!=0) && (strcmp(argv[i+1],"-v")!=0) && (strcmp(argv[i-1],"-v")!=0) && (strcmp(argv[i+1],"-q")!=0)) || ((strcmp(argv[i],"--invert-match")==0) && (strcmp(argv[i+1],"--line-number")!=0) && (strcmp(argv[i-1],"--line-number")!=0) && (strcmp(argv[i+1],"--invert-match")!=0) && (strcmp(argv[i-1],"--invert-match")!=0) && (strcmp(argv[i+1],"--quiet")!=0)))
{
if(strstr(oneline,argv[argc-1])==NULL)
{
printf("%s",oneline);
count1++;
}
}
else if(((strcmp(argv[i],"-n")==0) && (strcmp(argv[i+1],"-v")!=0) && (strcmp(argv[i-1],"-v")!=0) && (strcmp(argv[i+1],"-n")!=0) && (strcmp(argv[i-1],"-n")!=0) && (strcmp(argv[i+1],"-q")!=0)) || ((strcmp(argv[i],"--line-number")==0) && (strcmp(argv[i+1],"--invert-match")!=0) && (strcmp(argv[i-1],"--invert-match")!=0) && (strcmp(argv[i-1],"--line-number")!=0) && (strcmp(argv[i-1],"--line-number")!=0) && (strcmp(argv[i+1],"--quiet")!=0)))
{
if(strstr(oneline,argv[argc-1])!=NULL)
{
printf("%d: %s",count,oneline);
count1++;
}
}
else if(((strcmp(argv[i],"-n")==0) && (strcmp(argv[i+1],"-v")==0)) || ((strcmp(argv[i],"--line-number")==0) && (strcmp(argv[i+1],"--invert-match")==0)))
{
if(strstr(oneline,argv[argc-1])==NULL)
{
printf("%d: %s",count,oneline);
count1++;
}
}
else if(((strcmp(argv[i],"-v")==0) && (strcmp(argv[i+1],"-n")==0)) || ((strcmp(argv[i],"--invert-match")==0) && (strcmp(argv[i+1],"--line-number")==0)))
{
if(strstr(oneline,argv[argc-1])==NULL)
{
printf("%d: %s",count,oneline);
count1++;
}
}
else if(((strcmp(argv[i],"-v")==0) && (strcmp(argv[i+1],"-v")==0)) || ((strcmp(argv[i],"--invert-match")==0) && (strcmp(argv[i+1],"--invert-match")==0)))
{
if(strstr(oneline,argv[argc-1])==NULL)
{
printf("%s",oneline);
count1++;
}
}
else if(((strcmp(argv[i],"-n")==0) && (strcmp(argv[i+1],"-n")==0)) || ((strcmp(argv[i],"--line-number")==0) && (strcmp(argv[i+1],"--line-number")==0)))
{
if(strstr(oneline,argv[argc-1])!=NULL)
{
printf("%d: %s",count,oneline);
count1++;
}
}
else if(((strcmp(argv[i],"-v")==0) && (strcmp(argv[i+1],"-q")==0)) || ((strcmp(argv[i],"--invert-match")==0) && (strcmp(argv[i+1],"--quiet")==0)))
{
return 0;
}
else if(((strcmp(argv[i],"-q")==0) && (strcmp(argv[i+1],"-v")==0)) || ((strcmp(argv[i],"--quiet")==0) && (strcmp(argv[i+1],"--invert-match")==0)))
{
return 0;
}
else if(((strcmp(argv[i],"-n")==0) && (strcmp(argv[i+1],"-q")==0)) || ((strcmp(argv[i],"--line-number")==0) && (strcmp(argv[i+1],"--quiet")==0)))
{
return 0;
}
else if(((strcmp(argv[i],"-q")==0) && (strcmp(argv[i+1],"-n")==0)) || ((strcmp(argv[i],"--quiet")==0) && (strcmp(argv[i+1],"--line-number")==0)))
{
return 0;
}
else if((strcmp(argv[i],"-q")==0) || (strcmp(argv[i],"--quiet")==0))
{
return 0;
}
}
}
else
{
if(strstr(oneline,argv[argc-1])!=NULL)
{
printf("%s",oneline);
count1++;
}
}
}
if(count1>0){return 0;}
else{return 1;}
}
|
C
|
#include <stdio.h>
#include "mythreadextra.h"
int resource = 1;
MySemaphore * s;
MySemaphore * t;
/*
Output:
t0 start
t1 start
t2 start
t0 again
t1 again
t2 again
t0 bye
*/
void t2(void * dummy)
{
printf("t2 start\n");
MySemaphoreWait(t);
printf("t2 access critical section t\n");
MyThreadYield();
MySemaphoreWait(s);
printf("t2 done critical section s\n");
printf("t2 signal\n");
MySemaphoreSignal(s);
printf("t1 signal t\n");
MySemaphoreSignal(t);
MyThreadExit();
printf("t2 did not exit");
}
void t1(void * dummy)
{
printf("t1 start\n");
MySemaphoreWait(s);
printf("t1 access critical section s\n");
MyThreadYield();
MySemaphoreWait(t);
printf("t1 done critical section t\n");
printf("t1 signal t\n");
MySemaphoreSignal(t);
printf("t1 signal s\n");
MySemaphoreSignal(s);
MyThreadExit();
printf("t1 did not exit");
}
int main()
{
s = MySemaphoreInit(resource);
t = MySemaphoreInit(resource);
MyThreadInitExtra();
printf("Root thread start\n");
MyThreadCreate(t1, (void *)1);
MyThreadCreate(t2, (void *)1);
MyThreadYield();
printf("Root thread exit\n");
MyThreadExit();
}
|
C
|
/**
* File: Sensors.c
* Author: Sarah Masimore
* Last Updated Date: 03/14/2018
* Description: Manages init'ing and updating sensors.
*/
#include "Simulator.h"
/**
* Init ports and relevant pins.
*/
void Sensors_Init(struct car * car);
/**
* Based on sensor value, determine and update voltage on its pin.
*/
void Sensors_UpdateOutput(struct car * car);
|
C
|
/*
** EPITECH PROJECT, 2019
** Visual Studio Live Share (Workspace)
** File description:
** init_mob.c
*/
#include "entity.h"
void set_mob(mob_s *element, sfVector2f pos, sfVector2f(stat), sfColor color)
{
element->sprite = sfSprite_create();
element->position = pos;
element->state = 1;
element->rect_i = (sfIntRect){1440, 0, 80, 80};
element->rect_a = (sfIntRect){0, 0, 80, 80};
element->rect_w = (sfIntRect){2000, 0, 80, 80};
element->rect_d = (sfIntRect){800, 0, 80, 80};
element->damage = stat.x;
element->speed = stat.y;
element->alive = 1;
element->life = (stat.x + stat.y) * 20;
element->next = NULL;
sfSprite_setTexture(element->sprite,
find_asset_byname("blob.png")->asset_store.texture, sfTrue);
sfSprite_setTextureRect(element->sprite, element->rect_i);
sfSprite_setScale(element->sprite,
(sfVector2f){(double)settings->WW / 700, (double)settings->WH / 500});
sfSprite_setColor(element->sprite, color);
sfSprite_setOrigin(element->sprite, (sfVector2f){40, 40});
element->clock = sfClock_create();
}
void append_mob(mob_s **mob, sfVector2f pos, sfVector2f dmg_s, sfColor color)
{
mob_s *tmp = *mob;
mob_s *element = malloc(sizeof(mob_s));
set_mob(element, pos, dmg_s, color);
if (tmp == NULL)
*mob = element;
else {
while (tmp->next)
tmp = tmp->next;
tmp->next = element;
}
}
void init_mob(mob_s **mob)
{
*mob = NULL;
append_mob(mob, (sfVector2f){settings->WW, settings->WH * 0.92},
(sfVector2f){(float)5, (float)0.1}, sfWhite);
append_mob(mob, (sfVector2f){settings->WW * 1.2, settings->WH * 0.92},
(sfVector2f){(float)5, (float)0.1}, sfWhite);
append_mob(mob, (sfVector2f){settings->WW * 1.3, settings->WH * 0.89},
(sfVector2f){(float)10, (float)0.3}, sfBlue);
append_mob(mob, (sfVector2f){settings->WW * 1.5, settings->WH * 0.94},
(sfVector2f){(float)10, (float)0.3}, sfBlue);
append_mob(mob, (sfVector2f){settings->WW * 1.7, settings->WH * 0.87},
(sfVector2f){(float)20, (float)0.1}, sfRed);
append_mob(mob, (sfVector2f){settings->WW * 1.8, settings->WH * 0.94},
(sfVector2f){(float)5, (float)0.1}, sfWhite);
append_mob(mob, (sfVector2f){settings->WW * 2.1, settings->WH * 0.90},
(sfVector2f){(float)15, (float)0.5}, sfMagenta);
append_mob(mob, (sfVector2f){settings->WW * 2.5, settings->WH * 0.88},
(sfVector2f){(float)15, (float)0.5}, sfMagenta);
append_mob(mob, (sfVector2f){settings->WW * 2.9, settings->WH * 0.94},
(sfVector2f){(float)15, (float)0.5}, sfMagenta);
}
|
C
|
/*
MCP4922 - Conversor Digital-Analogico de 12-bits e 2 canais.
Autor: Tiago Melo
Blog: Microcontrolandos
Compilador: MikroC PRO PIC
Bibliotecas: Soft_SPI
*/
//Pinos do MCP4922.
sbit SoftSpi_SDI at RB2_bit;
sbit SoftSpi_SDO at RB2_bit;
sbit SoftSpi_CLK at RB0_bit;
sbit MCP4922_CS at RB1_bit;
sbit SoftSpi_SDI_Direction at TRISB2_bit;
sbit SoftSpi_SDO_Direction at TRISB2_bit;
sbit SoftSpi_CLK_Direction at TRISB0_bit;
sbit MCP4922_CS_Direction at TRISB1_bit;
void MCP4922_Init() {
MCP4922_CS_Direction = 0;
MCP4922_CS = 1;
}
void MCP4922_Write(char channel, unsigned value, char gain) {
((char*)&value)[1].B7 = channel; //A/B
((char*)&value)[1].B6 = 0; //BUF
((char*)&value)[1].B5 = !gain.B0; //GA
((char*)&value)[1].B4 = 1; //SHDN
//Habilita a transferencia de dados.
MCP4922_CS = 0;
//Enviamos primeiro o byte MSB.
Soft_SPI_Write(((char*)&value)[1]);
Soft_SPI_Write(((char*)&value)[0]);
//Desabilita a transferencia de dados.
MCP4922_CS = 1;
}
void main() {
unsigned valor = 0;
//Inicializa o MCP4922.
Soft_SPI_Init();
MCP4922_Init();
while(1) {
MCP4922_Write(0, valor, 0); //canal 0, sem ganho.
MCP4922_Write(1, valor, 1); //canal 1, com ganho.
//Incrementa o valor.
valor++;
//Mximo 12 bits.
valor &= 0xFFF;
//Faz nada por 100ms.
Delay_ms(100);
}
}
|
C
|
#include<stdio.h>
void main(void)
{
int a,b;
int x,y,z;
printf("a=\n");
scanf("%d",&a);
printf("b=\n");
scanf("%d",&b);
x=a | b;
y=a & b;
z=(x & b)+(y | a);
printf("x=%d y=%d z=%d\n",x,y,z);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int matrix[0x400][0x400]; //store the path
int ans[0x400];//store answer
int queue[0x400];
int head,curr,flag;
void toZero()
{
flag = 0;
head = 0;
curr = 0;
memset(ans,0,sizeof(ans));
memset(queue,0,sizeof(queue));
memset(matrix,0,sizeof(matrix));
}
int main()
{
int case_num,case_counter,people,dance_num,p1,p2,dance_counter;
printf("%%>");
scanf("%d",&case_num);
for(case_counter = 0; case_counter < case_num; case_counter++)
{
toZero();
printf("\n%%>");
scanf("%d %d",&people,&dance_num);
for(dance_counter = 0; dance_counter < dance_num; dance_counter++)
{
printf("%%>");
scanf("%d %d",&p1,&p2);
matrix[p1][p2]=1;//store the path
matrix[p2][p1]=1;
}
for(int i = 1; i < people; i++)
{
if (matrix[i][0]) //if have a path,then record
{
ans[i] += 1;
queue[head] = i;
head += 1;
}
}
while(curr != head)
{
flag = queue[curr];//pop
curr += 1;
for(int i = 1; i < people; i++)
{
if (matrix[i][flag])
{
if(!ans[i]||ans[flag] + 1 < ans[i]) //if the path isn't travel or the new path is shorter than older one
{
ans[i] = ans[flag]+1;//replace the older path
queue[head] = i;
head += 1;
}
}
}
}
printf("\n");
for(int i = 1; i < people; i++)
{
printf("%%>%d\n",ans[i]);
}
}
return 0;
}
|
C
|
#include <curses.h>
#include <unistd.h>
#include <stdlib.h>
#include <stdbool.h>
#include "fire-engine.h"
#include "fire-renderer.h"
#include "fire-palette.h"
static int useCustomColours;
static int *pixelPalette = NULL;
static int paletteSize = 0;
static void init_colours();
static void init_custom_colours();
int process_additional_args(int argc, char **argv)
{
if (argc < 1)
{
printf(" -c Use a custom colour palette");
printf(" N.B. Using custom palette will alter terminal colours.\n");
return 0;
}
if (argv[0][1] == 'c')
useCustomColours = 1;
return 0;
}
int init_renderer(const DoomFireBuffer *const buffer)
{
(void)buffer;
initscr();
start_color();
cbreak();
noecho();
curs_set(0);
if (useCustomColours == 1)
{
init_custom_colours();
}
else
{
init_colours();
}
clear();
return 0;
}
int get_max_ignition_value()
{
return paletteSize - 1;
}
void draw_buffer(DoomFireBuffer *const buffer)
{
for (int y = 0; y < buffer->height; y++)
{
for (int x = 0; x < buffer->width; x++)
{
int pixel = buffer->buffer[x + (y * buffer->width)];
int colorPair = pixelPalette[pixel];
char output = ' ';
attron(COLOR_PAIR(colorPair));
mvaddch(y, x, output);
attroff(COLOR_PAIR(colorPair));
}
}
refresh();
}
void wait()
{
usleep(10000);
}
bool exit_requested()
{
return false;
}
void cleanup_renderer()
{
free(pixelPalette);
pixelPalette = NULL;
clear();
endwin();
}
void init_colours()
{
printw("Test Palette:\n");
for (int i = 0; i < 256; i++)
{
init_pair(i, COLOR_BLACK, i);
attron(COLOR_PAIR(i));
printw("%i ", i);
attroff(COLOR_PAIR(i));
}
uint8_t reducedPalette[] = {16, 233, 234, 52, 52, 88, 124, 160, 196, 202, 208, 215, 220, 227, 229, 230, 15};
paletteSize = sizeof(reducedPalette)/sizeof(uint8_t);
pixelPalette = malloc(paletteSize * sizeof(int));
printw("\nSelected Palette:\n");
for (int i = 0; i < paletteSize; i++)
{
pixelPalette[i] = reducedPalette[i];
attron(COLOR_PAIR(reducedPalette[i]));
printw("%i ", i);
attroff(COLOR_PAIR(reducedPalette[i]));
}
refresh();
usleep(2000000);
}
void init_custom_colours()
{
printw("Selected Palette:\n");
float colorScalefactor = 1000.0/256;
paletteSize = get_palette_size();
pixelPalette = malloc(paletteSize * sizeof(int));
for (int i = 0; i < paletteSize; i++)
{
int colorIndex = i + 50; // Not saving the terminal colours, try not to hit the common ones.
int paletteIndex = i * 3;
float red = (float)DOOM_RGB_VALUES[paletteIndex] * colorScalefactor;
float green = (float)DOOM_RGB_VALUES[paletteIndex + 1] * colorScalefactor;
float blue = (float)DOOM_RGB_VALUES[paletteIndex + 2] * colorScalefactor;
init_color(colorIndex, (int)red, (int)green, (int)blue);
init_pair(colorIndex, COLOR_BLACK, colorIndex);
pixelPalette[i] = colorIndex;
attron(COLOR_PAIR(colorIndex));
printw("%i ", i);
attroff(COLOR_PAIR(colorIndex));
}
refresh();
usleep(2000000);
}
|
C
|
#pragma once
#include "vector.h"
struct Ray {
Vector3 origin;
Vector3 direction;
Vector3 get_point(float t) const {
return origin + direction * t;
}
bool operator==(const Ray& other) const {
return origin == other.origin && direction == other.direction;
}
bool operator!=(const Ray& other) const {
return !(*this == other);
}
};
// Additional rays around the main ray that allow to determine the size of the pixel footprint on the surface.
// It is used to compute UV derivatives with respect to pixel coordinates and ultimately texture lod level.
struct Differential_Rays {
Ray dx_ray;
Ray dy_ray;
};
|
C
|
/*
* crc32.c - calculate crc32 checksums of data
*
* Written in 2020 by Ayman El Didi
*
* To the extent possible under law, the author(s) have dedicated all
* domain worldwide. This software is distributed without any warranty.
*
* You should have received a copy of the CC0 Public Domain Dedication along
* with this software. If not, see
* <http://creativecommons.org/publicdomain/zero/1.0/>.
*/
#include <stddef.h>
#include <stdint.h>
uint32_t
crc32_for_byte(uint32_t byte)
{
const uint32_t polynomial = 0xEDB88320L;
uint32_t result = byte;
size_t i = 0;
for (; i < 8; i++) {
/* IMPLEMENTATION: the code below always shifts result right by
* 1, but only XORs it by the polynomial if we're on the lowest
* bit.
*
* This is because 1 in binary is 00000001, so ANDing the
* result by 1 will always give 0 unless the lowest bit is set.
* And since XOR by zero does nothing, the other half only
* occurs when we're on the lowest bit.
*
* I didn't leave the above implementation in, despite being
* faster on my machine since it is a more complex operation
* which may be slower on less sophisticated processors. It can
* be added in in place of the loop code below.
*/
result = (result >> 1) ^ (result & 1) * polynomial;
/* Here is the code I replaced with the branch I tried to
* remove:
if (result & 1) {
result = (result >> 1) ^ polynomial;
continue;
}
result >>= 1;
*/
}
return result;
}
uint32_t
crc32(const void *input, size_t size)
{
const uint8_t *current = input;
uint32_t result = 0xFFFFFFFF;
size_t i = 0;
for (; i < size; i++) {
result ^= current[i];
result = crc32_for_byte(result);
}
return ~result;
}
|
C
|
#include <stdio.h>
int my_strlen (char *s);
int main (int argc, char const *argv[]) {
char str[1000];
scanf("%s", str);
printf("%d\n", my_strlen(str));
return 0;
}
int my_strlen (char *s) {
int i = 0;
while(s[i] != '\0') i++;
return i;
}
|
C
|
#include "vm/page.h"
#include "threads/vaddr.h"
unsigned
hash_key_func (const struct hash_elem *e, void *aux UNUSED){
const struct spte* spte = hash_entry(e,struct spte,elem);
// return hash_bytes (&spte->upage, sizeof spte->upage);
return hash_int(spte->upage);
}
bool
hash_less_key_func (const struct hash_elem *a, const struct hash_elem *b, void *aux UNUSED){
const struct spte* spte1 = hash_entry(a,struct spte,elem);
const struct spte* spte2 = hash_entry(b,struct spte,elem);
if(spte1->upage<spte2->upage)
return true;
else
return false;
}
void
init_spt(struct hash* spt){
hash_init(spt, hash_key_func, hash_less_key_func, NULL);
}
struct spte*
create_spte(void * upage, enum status state) {
//언제 free해줘야하나
struct spte *spte = (struct spte*)malloc(sizeof(struct spte));
spte->upage=pg_round_down(upage);
spte->state=state;
spte->swap_location = -1;
spte->writable=false;
return spte;
}
struct spte*
get_spte(struct hash* spt,void* fault_addr){
struct spte spte;
spte.upage=pg_round_down(fault_addr);
struct hash_elem* get = hash_find (spt,&spte.elem);
if(get ==NULL){
// printf("hi \n");
return NULL;
}
else{
return hash_entry(get,struct spte, elem);
}
}
void spte_free(struct hash_elem *e, void *aux){
free(hash_entry(e,struct spte, elem));
}
void
destroy_spt(struct thread* thread){
hash_destroy(&thread->spt, spte_free);
}
bool
create_spte_from_exec(struct file *file, int32_t ofs, uint8_t *upage, uint32_t read_bytes, uint32_t zero_bytes,bool writable)
{
struct spte *spte = malloc(sizeof(struct spte));
if (!spte)
return false;
spte->upage = pg_round_down(upage);
spte->state = EXEC_FILE;
spte->file = file;
spte->offset = ofs;
spte->read_bytes = read_bytes;
spte->zero_bytes = zero_bytes;
spte->writable = writable;
return (hash_insert(&thread_current()->spt, &spte->elem) == NULL);
}
bool
create_spte_from_mmf(struct file *file, int32_t ofs, uint8_t *upage, uint32_t read_bytes, uint32_t zero_bytes,bool writable,struct mmap_file* mmf)
{
struct spte *spte = malloc(sizeof(struct spte));
if (!spte)
return false;
spte->upage = pg_round_down(upage);
spte->state = MM_FILE;
spte->mmap_file = mmf;
spte->file = file;
spte->offset = ofs;
spte->read_bytes = read_bytes;
spte->zero_bytes = zero_bytes;
spte->writable = true;
list_push_back(&mmf->spte_list,&spte->mmf_elem);
return (hash_insert(&thread_current()->spt, &spte->elem) == NULL);
}
|
C
|
#include "server.h"
#include <termios.h>
/* Extern Definitions */
int socket_count = 0;
struct pollfd socket_fds[MAX_SOCKETS];
table_entry_t *active_users[MAX_ROOMS] = {NULL};
short spam_message_count[MAX_SOCKETS]; //Spam message counters for each client
short spam_timeout[MAX_SOCKETS]; //Spam timeout for each client
pthread_mutex_t spam_lock;
sqlite3 *user_db;
/* ----------------- */
pthread_attr_t spam_tattr;
pthread_t spam_tid;
bool shutdown_server_flag = false;
unsigned int port_number = DEFAULT_PORT_NUMBER;
int main(int argc, char* argv[]){
//Setup signal handlers to properly close server
signal(SIGINT, terminate_server); //CTRL + C
signal(SIGQUIT, terminate_server); //CTRL + BACKSLASH
signal(SIGSEGV, terminate_server); //Memory access violation
//Get port number from argument
if(argc > 1){
port_number = atoi(argv[1]);
}
//Turn off input echoing
struct termios oldtc, newtc;
tcgetattr(STDIN_FILENO, &oldtc);
newtc = oldtc;
newtc.c_lflag &= ~(ICANON | ECHO);
tcsetattr(STDIN_FILENO, TCSANOW, &newtc);
pthread_mutex_init(&spam_lock, NULL);
printf("**Opening Database**\n");
open_database();
printf("**Starting Server**\n");
start_server();
printf("**Shutting Down Server**\n");
//Turn echoing back on
tcsetattr(STDIN_FILENO, TCSANOW, &oldtc);
pthread_mutex_destroy(&spam_lock);
return 0;
}
void open_database(){
int status;
const char *query;
sqlite3_stmt *stmt;
//Open database of registered users or create one if it doesn't already exist
if(sqlite3_open("users.db", &user_db) != SQLITE_OK){
fprintf(stderr, "Error opening database: %s\n", sqlite3_errmsg(user_db));
sqlite3_close(user_db);
}
//Create "users" table if it doesn't already exist
query = "CREATE TABLE IF NOT EXISTS users (id TEXT PRIMARY KEY NOT NULL, password TEXT NOT NULL, type TEXT NOT NULL);";
sqlite3_prepare_v2(user_db, query, -1, &stmt, NULL);
if(sqlite3_step(stmt) != SQLITE_DONE){
fprintf(stderr, "SQL error while creating table: %s\n", sqlite3_errmsg(user_db));
exit(EXIT_FAILURE);
}
sqlite3_finalize(stmt);
//Check if initial admin account has already been created
query = "SELECT 1 FROM users WHERE type = 'admin';";
sqlite3_prepare_v2(user_db, query, -1, &stmt, NULL);
if((status = sqlite3_step(stmt)) == SQLITE_ROW){
sqlite3_finalize(stmt);
return; //Initial admin account already exists
}else if(status != SQLITE_DONE){
fprintf(stderr, "SQL error while checking for admin: %s\n", sqlite3_errmsg(user_db));
exit(EXIT_FAILURE);
}
sqlite3_finalize(stmt);
//Create initial admin account
create_admin();
}
void create_admin(){
char admin_password[MESSAGE_SIZE];
char admin_password2[MESSAGE_SIZE];
char hashed_password[crypto_pwhash_STRBYTES];
char password_error[MESSAGE_SIZE];
char *matching_error = NULL;
const char *query;
sqlite3_stmt *stmt;
printf("**Creating Admin Account**\n");
//Get admin password from server administrator
do{
//Reset password_error for new iteration
password_error[0] = '\0';
//Print error message from previous iteration
if(matching_error){
printf("%s\n\n", matching_error);
}
do{
if(*password_error){ //Print error message if not blank
printf("%s\n\n", password_error + strlen(SERVER_PREFIX)); //Skip over SERVER_PREFIX
}
printf("Enter password for \"Admin\" account: ");
get_admin_password(admin_password);
printf("\n");
}while(is_password_invalid(admin_password, password_error));
printf("Retype the same password: ");
get_admin_password(admin_password2);
printf("\n");
//Set matching_error message for next loop iteration
matching_error = "The entered passwords do not match";
}while(strncmp(admin_password, admin_password2, PASSWORD_SIZE_MAX) != 0);
//Hash password with libsodium
if(crypto_pwhash_str(hashed_password, admin_password, strlen(admin_password),
PWHASH_OPSLIMIT, PWHASH_MEMLIMIT) != 0){
/* out of memory */
fprintf(stderr, "Ran out of memory during hash function\n");
exit(EXIT_FAILURE);
}
//Clear the plain-text passwords from memory
secure_zero(admin_password, PASSWORD_SIZE_MAX);
secure_zero(admin_password2, PASSWORD_SIZE_MAX);
//Register admin account into database with specified password
query = "INSERT INTO users(id, password, type) VALUES('Admin', ?1, 'admin');";
sqlite3_prepare_v2(user_db, query, -1, &stmt, NULL);
sqlite3_bind_text(stmt, 1, hashed_password, -1, SQLITE_STATIC);
if(sqlite3_step(stmt) != SQLITE_DONE){
fprintf(stderr, "SQL error while inserting admin account: %s\n", sqlite3_errmsg(user_db));
exit(EXIT_FAILURE);
}else{
printf("**Admin Account Created**\n");
}
sqlite3_finalize(stmt);
}
void start_server(){
int status;
int flags;
//Define the server's IP address and port
struct sockaddr_in server_address;
server_address.sin_family = AF_INET;
server_address.sin_port = htons(port_number);
server_address.sin_addr.s_addr = htonl(INADDR_ANY);
memset(server_address.sin_zero, 0, sizeof(server_address.sin_zero));
//Create the server socket to use for a connection
int server_socket;
server_socket = socket(PF_INET, SOCK_STREAM, 0);
check_status(server_socket, "Error creating server socket");
//Set server socket to nonblocking
flags = fcntl(server_socket, F_GETFL, NULL);
check_status(flags, "Error getting flags for server socket");
status = fcntl(server_socket, F_SETFL, flags | O_NONBLOCK);
check_status(status, "Error setting server socket to nonblocking");
//Bind the socket to our specified IP address and port
status = bind(server_socket, (struct sockaddr*) &server_address, sizeof(server_address));
if(check_status(status, "\nError binding server socket")){
fprintf(stderr, "Server will select an unused port instead of port %d\n", port_number);
server_address.sin_port = 0; //Set port to automatically find an unused port
status = bind(server_socket, (struct sockaddr*) &server_address, sizeof(server_address));
check_status(status, "Error binding server socket");
}
//Print the server port to the terminal
socklen_t len = sizeof(server_address);
if(getsockname(server_socket, (struct sockaddr *)&server_address, &len) == -1){
perror("getsockname error");
return;
}
port_number = ntohs(server_address.sin_port);
printf("Server is using port number: %d\n", port_number);
//Set the socket up to listen for connections
status = listen(server_socket, LISTEN_BACKLOG);
check_status(status, "Error listening on server socket");
//Initialize struct pollfd array to zeros
memset(socket_fds, 0, sizeof(socket_fds));
//Set server file descriptor and event type
socket_fds[0].fd = server_socket;
socket_fds[0].events = POLLIN;
socket_count++;
//Set ignore state for client file descriptors and event type
for(size_t i = 1; i < MAX_SOCKETS; i++){
socket_fds[i].fd = -1;
socket_fds[i].events = POLLIN;
}
//Create thread for spam timer in a detached state
if(pthread_attr_init(&spam_tattr)){
perror("Error initializing pthread attribute");
exit(EXIT_FAILURE);
}
if(pthread_attr_setdetachstate(&spam_tattr, PTHREAD_CREATE_DETACHED)){
perror("Error setting pthread detach state");
exit(EXIT_FAILURE);
}
if(pthread_create(&spam_tid, &spam_tattr, spam_timer, NULL)){
perror("Error creating pthread");
exit(EXIT_FAILURE);
}
if(pthread_attr_destroy(&spam_tattr)){
perror("Error destroying pthread attribute");
exit(EXIT_FAILURE);
}
//Call method for processing clients
monitor_connections(server_socket);
//Close the server socket
check_status(close(server_socket), "Error closing server socket");
//Close database of registered users
status = sqlite3_close(user_db);
if(status != SQLITE_OK){
fprintf(stderr, "Error closing database: %s\n", sqlite3_errmsg(user_db));
}
}
void *spam_timer(){
int current_interval = 0; //Current interval within spam interval window
while(1){
//Each interval is one second long
sleep(1);
current_interval++;
//Reset spam message counters to be used in new spam interval window
if(current_interval % SPAM_INTERVAL_WINDOW == 0){
pthread_mutex_lock(&spam_lock);
memset(spam_message_count, 0, sizeof(spam_message_count));
pthread_mutex_unlock(&spam_lock);
current_interval = 0;
}
//Reduce every client's timeout period by one second until it's zero
pthread_mutex_lock(&spam_lock);
for(size_t i = 1; i < MAX_SOCKETS; i++){
if(spam_timeout[i] > 0){
spam_timeout[i]--;
}
}
pthread_mutex_unlock(&spam_lock);
}
}
void monitor_connections(int server_socket){
int status;
char server_msg_prefixed[MESSAGE_SIZE + 1];
char *server_msg = server_msg_prefixed + 1;
char *who_messages[MAX_ROOMS] = {NULL};
//Add control character to the start of message so we know when it's a
//new message since the message may be split up over multiple packets
server_msg_prefixed[0] = MESSAGE_START;
//Perform initial allocation/build of who_messages
for(int room_id = 0; room_id < MAX_ROOMS; room_id++){
rebuild_who_message(who_messages, room_id);
}
printf("**Awaiting Clients**\n");
while(1){
//Monitor FDs for any activated events
status = poll(socket_fds, MAX_SOCKETS, -1);
//Check if a poll error has occurred
if(status == -1){
perror("Poll Error");
continue;
}
/* ------------------------------------------ */
/* Event has occurred: Check server socket */
/* ------------------------------------------ */
if(socket_fds[0].revents & POLLIN){
accept_clients(server_socket, server_msg_prefixed, who_messages);
}
/* ----------------------------------------------------------------- */
/* Event has occurred: Check all active clients in every chat room */
/* ----------------------------------------------------------------- */
process_clients(server_msg_prefixed, who_messages);
//Check if server has been flagged for shutdown
if(shutdown_server_flag){
break;
}
}
/* --------------- */
/* Shutdown server */
/* --------------- */
shutdown_server(who_messages);
}
void accept_clients(int server_socket, char *server_msg_prefixed, char **who_messages){
int status, flags;
int client_socket;
static size_t index = 0;
char username[USERNAME_SIZE];
char *server_msg = server_msg_prefixed + 1;
const char *server_msg_literal = NULL;
struct sockaddr_in client_addr;
socklen_t client_addr_size = sizeof(client_addr);
char ip_str[INET_ADDRSTRLEN];
unsigned short port;
while(1){
//Check for any pending connections
client_socket = accept(server_socket, (struct sockaddr *) &client_addr, &client_addr_size);
//Accept all pending connections until queue is empty or an error occurs
if(client_socket == -1){
if(errno != EWOULDBLOCK && errno != EAGAIN){
perror("Error accepting new client");
}else{
//No more pending connections
}
return;
}
//Check if server is full
if(socket_count >= MAX_SOCKETS){
printf("**Server has reached the maximum of %d clients**\n", MAX_SOCKETS - 1);
sprintf(server_msg, SERVER_PREFIX "The server has reached the maximum of %d clients", MAX_SOCKETS - 1);
send_message(client_socket, server_msg_prefixed, strlen(server_msg_prefixed) + 1);
status = close(client_socket);
check_status(status, "Error closing client socket");
continue;
}
//Increment socket count and set lobby who_messages for rebuild
socket_count++;
who_messages[LOBBY_ROOM_ID][0] = '\0';
//Set client socket to nonblocking
flags = fcntl(client_socket, F_GETFL, NULL);
check_status(flags, "Error getting flags for client socket");
status = fcntl(client_socket, F_SETFL, flags | O_NONBLOCK);
check_status(status, "Error setting client socket to nonblocking");
//Get the ip address and port number of the connecting user
inet_ntop(AF_INET, &(client_addr.sin_addr), ip_str, sizeof(ip_str));
port = ntohs(client_addr.sin_port);
//Find an available spot in the client FD array
while(socket_fds[index].fd > 0){
index = (index + 1) % MAX_SOCKETS;
}
//Assign the socket to the client FD
socket_fds[index].fd = client_socket;
//Create client's default username
sprintf(username, "Client%zu", index);
//Add client to the lobby room in active_users hash table
add_user(username, false, LOBBY_ROOM_ID, index, client_socket, ip_str, port);
//Send server welcome messages to client
sprintf(server_msg, SERVER_PREFIX "Welcome to the server - Default username is \"%s\"", username);
send_message(client_socket, server_msg_prefixed, strlen(server_msg_prefixed) + 1);
server_msg_literal = MESSAGE_START_STR SERVER_PREFIX "Use the /nick command to change your username";
send_message(client_socket, server_msg_literal, strlen(server_msg_literal) + 1);
server_msg_literal = MESSAGE_START_STR SERVER_PREFIX "Use the /join command to join a chat room";
send_message(client_socket, server_msg_literal, strlen(server_msg_literal) + 1);
//Print client joining message to the server's terminal
printf("**Client%lu on socket %d (%s:%hu) joined the server**\n", index, client_socket, ip_str, port);
}
}
void process_clients(char *server_msg_prefixed, char **who_messages){
ssize_t recv_status = 0;
size_t msg_size = 0;
size_t index = 0;
int client_socket = 0;
int cmd_length = 0;
bool expect_ending_char = false;
char *server_msg = server_msg_prefixed + 1;
const char *server_msg_literal = NULL;
static bool message_recv[MAX_SOCKETS];
static char client_msg[MESSAGE_SIZE + 1];
static char packet_msg[MESSAGE_SIZE + 1];
//Fail-safe to ensure NUL terminated client message
client_msg[MESSAGE_SIZE] = '\0';
packet_msg[MESSAGE_SIZE] = '\0';
char *packet_ptr = packet_msg;
memset(message_recv, false, sizeof(message_recv));
//Iterate through every chat room
for(int room_index = 0; room_index < MAX_ROOMS; room_index++){
//Iterate through all users in the chat room
table_entry_t *user, *tmp;
HASH_ITER(hh, active_users[room_index], user, tmp){ //Uthash deletion-safe iteration
//Get index and socket from user entry
index = user->index;
client_socket = user->socket_fd;
//Check if user has already been processed
if(message_recv[index]){
continue;
}
//Continue if no active event for FD
if(!(socket_fds[index].revents & POLLIN)){
continue;
}
//Receive messages from client sockets with active events
recv_status = recv(client_socket, packet_msg, MESSAGE_SIZE, 0);
if(recv_status == -1){
if(errno != EWOULDBLOCK && errno != EAGAIN){
perror("Error receiving message from client socket");
}
continue;
}
//Check if client has left the server
if(recv_status == 0){
remove_client(user, server_msg_prefixed, who_messages);
continue;
}
//Mark socket as messaged received
message_recv[index] = true;
//Point to first message in packet and reset flag
packet_ptr = packet_msg;
expect_ending_char = false;
while(recv_status > 0){
//Copy packet message to client message
if(packet_ptr[0] == MESSAGE_START){
//Skip over message-start control character
packet_ptr++;
recv_status--;
//Copy the new message
strncpy(client_msg, packet_ptr, recv_status);
client_msg[recv_status] = '\0';
expect_ending_char = true;
}else if(user->message){
//Copy the old incomplete message
strncpy(client_msg, user->message, user->message_size);
//Concatenate the new message
strncat(client_msg, packet_ptr, recv_status);
expect_ending_char = true;
}else{
//Handle message normally
strncpy(client_msg, packet_ptr, recv_status);
expect_ending_char = false;
}
//Prepare client message for processing
msg_size = prepare_client_message(client_msg, &recv_status);
//Check if message is completed or not
if(client_msg[msg_size - 1] == MESSAGE_END){
//Change MESSAGE_END ending to "\0" and process message
client_msg[msg_size - 1] = '\0';
//Reset flag for next message
expect_ending_char = false;
}else if(expect_ending_char){
//Store incomplete message for later processing
char *incomplete_msg = user->message;
if(incomplete_msg == NULL){
incomplete_msg = malloc(MESSAGE_SIZE * sizeof (*incomplete_msg));
if(incomplete_msg == NULL){
perror("Error allocating incomplete message for user");
exit(EXIT_FAILURE);
}
}
//Copy incomplete message to user's message buffer
strncpy(incomplete_msg, client_msg, msg_size);
user->message = incomplete_msg;
user->message_size = msg_size;
//Adjust recv_status to remaining bytes and point to next message
if(msg_size > 1){
recv_status -= (ssize_t) (msg_size - 1);
packet_ptr += (msg_size - 1);
}else{
//Subtract 1 if there is only a single control character remaining
//Fail safe to prevent infinite loop on bad input
recv_status -= 1;
packet_ptr += 1;
}
continue;
}
if(client_msg[0] == '\0'){
/* ----------------------------- */
/* Ignore client's empty message */
/* ----------------------------- */
}else if(client_msg[0] == '/'){
/* ------------------------------- */
/* Process client's server command */
/* ------------------------------- */
if(strcmp(client_msg, "/whois") == 0){
//Return the client's IP address and port
cmd_length = 6;
whois_cmd(cmd_length, user, client_msg);
} //Fallthrough to targeted /whois command
if(strncmp(client_msg, "/whois ", cmd_length = 7) == 0){
//Return the targeted user's IP address and port
whois_arg_cmd(cmd_length, user, client_msg, server_msg_prefixed);
}else if(strcmp(client_msg, "/who") == 0){
//List who's in every chat room
who_cmd(client_socket, who_messages);
}else if(strncmp(client_msg, "/who ", cmd_length = 5) == 0){
//List who's in the specified chat room
who_arg_cmd(cmd_length, client_socket, client_msg, server_msg_prefixed, who_messages);
}else if(strcmp(client_msg, "/join") == 0){
//Inform client of /join usage
join_cmd(client_socket);
}else if(strncmp(client_msg, "/join ", cmd_length = 6) == 0){
//Join the user-specified chat room
join_arg_cmd(cmd_length, &user, client_msg, server_msg_prefixed, who_messages);
}else if(strcmp(client_msg, "/nick") == 0){
//Echo back the client's username
nick_cmd(user, server_msg_prefixed);
}else if(strncmp(client_msg, "/nick ", cmd_length = 6) == 0){
//Change the client's username
nick_arg_cmd(cmd_length, &user, client_msg, server_msg_prefixed, who_messages);
//Clear passwords from every buffer
secure_zero(packet_msg, msg_size);
secure_zero(client_msg, msg_size);
secure_zero(user->message, msg_size);
}else if(strcmp(client_msg, "/where") == 0){
//Return the chat room you are currently in
where_cmd(user, server_msg_prefixed);
}else if(strncmp(client_msg, "/where ", cmd_length = 7) == 0){
//Return the room number that has the specified-user
where_arg_cmd(cmd_length, client_socket, client_msg, server_msg_prefixed);
}else if(strcmp(client_msg, "/kick") == 0){
//Inform client of /kick usage
kick_cmd(client_socket);
}else if(strncmp(client_msg, "/kick ", cmd_length = 6) == 0){
//Kick specified user from the server
kick_arg_cmd(cmd_length, user, &tmp, client_msg, server_msg_prefixed, who_messages);
}else if(strcmp(client_msg, "/register") == 0){
//Inform client of /register usage
register_cmd(client_socket);
}else if(strncmp(client_msg, "/register ", cmd_length = 10) == 0){
//Register username in user database
register_arg_cmd(cmd_length, user, client_msg, server_msg_prefixed);
//Clear passwords from every buffer
secure_zero(packet_msg, msg_size);
secure_zero(client_msg, msg_size);
secure_zero(user->message, msg_size);
}else if(strcmp(client_msg, "/unregister") == 0){
//Inform client of /unregister usage
unregister_cmd(client_socket);
}else if(strncmp(client_msg, "/unregister ", cmd_length = 12) == 0){
//Unregister username from user database
unregister_arg_cmd(cmd_length, user, client_msg, server_msg_prefixed);
//Clear passwords from every buffer
secure_zero(packet_msg, msg_size);
secure_zero(client_msg, msg_size);
secure_zero(user->message, msg_size);
}else if(strcmp(client_msg, "/admin") == 0){
//Inform client of /admin usage
admin_cmd(client_socket);
}else if(strncmp(client_msg, "/admin ", cmd_length = 7) == 0){
//Change account type of targeted user
admin_arg_cmd(cmd_length, user, client_msg, server_msg_prefixed);
}else if(strcmp(client_msg, "/die") == 0){
//Trigger server shutdown if admin
if(die_cmd(user)){
shutdown_server_flag = true;
break;
}
}else{
//Remove arguments after the command if they exist
char *arguments = memchr(client_msg, ' ', msg_size);
if(arguments){
arguments[0] = '\0';
}
//Inform client of invalid command
sprintf(server_msg, SERVER_PREFIX "\"%s\" is not a valid command", client_msg);
send_message(client_socket, server_msg_prefixed, strlen(server_msg_prefixed) + 1);
}
}else{
/* --------------------- */
/* Send client's message */
/* --------------------- */
//Check for and handle spamming clients
if(check_for_spamming(user, server_msg_prefixed)){
//User has spam timeout
break;
}else{
//Increment spam message count for client
pthread_mutex_lock(&spam_lock);
spam_message_count[index]++;
pthread_mutex_unlock(&spam_lock);
}
if(client_msg[0] == '@'){
/* ------------------------------------- */
/* Send private message to targeted user */
/* ------------------------------------- */
private_message(user, client_msg, msg_size, server_msg_prefixed);
}else if(user->room_id == LOBBY_ROOM_ID){
//Inform client they aren't in a chat room
server_msg_literal = MESSAGE_START_STR SERVER_PREFIX "You're not in a chat room - Use the /join command";
send_message(client_socket, server_msg_literal, strlen(server_msg_literal) + 1);
}else{
/* -------------------------------- */
/* Send public message to chat room */
/* -------------------------------- */
public_message(user, client_msg, msg_size);
}
}
//Adjust recv_status to remaining bytes not yet processed
recv_status -= (ssize_t) (msg_size - (user->message_size - 1));
//Point to next message in the packet
packet_ptr += (msg_size - (user->message_size - 1));
//Reset user's message buffer
if(user->message){
free(user->message);
user->message = NULL;
user->message_size = 1; //Set to 1 for empty string size "\0"
}
}
}
}
}
int check_for_spamming(table_entry_t *user, char *server_msg_prefixed){
int index = user->index;
int client_socket = user->socket_fd;
char *server_msg = server_msg_prefixed + 1;
pthread_mutex_lock(&spam_lock);
if(spam_timeout[index] != 0){
//Client currently has a timeout period
sprintf(server_msg, "Spam Timeout: Please wait %d seconds", spam_timeout[index]);
pthread_mutex_unlock(&spam_lock);
send_message(client_socket, server_msg_prefixed, strlen(server_msg_prefixed) + 1);
return 1;
}else if(spam_message_count[index] > SPAM_MESSAGE_LIMIT){
//Give client a timeout period
spam_timeout[index] = SPAM_TIMEOUT_LENGTH;
pthread_mutex_unlock(&spam_lock);
sprintf(server_msg, "Spam Timeout: Please wait %d seconds", SPAM_TIMEOUT_LENGTH);
send_message(client_socket, server_msg_prefixed, strlen(server_msg_prefixed) + 1);
return 1;
}
pthread_mutex_unlock(&spam_lock);
return 0;
}
void private_message(table_entry_t *user, char *client_msg, size_t msg_size, char *server_msg_prefixed){
int client_socket = user->socket_fd;
char *server_msg = server_msg_prefixed + 1;
char target_username[USERNAME_SIZE];
size_t target_username_length = strcspn(client_msg + 1, " ");
//Check if targeted username is too long
if(target_username_length > USERNAME_SIZE - 1){
sprintf(server_msg, SERVER_PREFIX "Username is too long (max %d characters)", USERNAME_SIZE - 1);
send_message(client_socket, server_msg_prefixed, strlen(server_msg_prefixed) + 1);
return;
}
//Copy targeted username from client's message
strncpy(target_username, client_msg + 1, target_username_length);
target_username[target_username_length] = '\0'; //NUL terminate username
target_username[0] = toupper(target_username[0]); //Capitalize username
//Look for user in all chat rooms
table_entry_t *target_user = find_user(target_username);
//Inform client if user was not found
if(target_user == NULL){
sprintf(server_msg, SERVER_PREFIX "The user \"%s\" does not exist", target_username);
send_message(client_socket, server_msg_prefixed, strlen(server_msg_prefixed) + 1);
return;
}
//Remove '@' character, username, and empty space from client's message
char *message = client_msg + 1 + target_username_length + 1;
msg_size -= (1 + target_username_length + 1);
//Check if message to user is blank
if(message[0] == '\0' || message[-1] != ' '){
sprintf(server_msg, SERVER_PREFIX "The message to \"%s\" was blank", target_username);
send_message(client_socket, server_msg_prefixed, strlen(server_msg_prefixed) + 1);
return;
}
//Add sender's username to message
char *username = user->id;
char *postfix = PRIVATE_PREFIX;
message = add_username_to_message(message, username, postfix);
size_t additional_length = strlen(username) + strlen(postfix) + 1; //Add one for MESSAGE_START
//Send message to target user and sender
send_message(target_user->socket_fd, message, msg_size + additional_length);
if(target_user->socket_fd != client_socket){
send_message(client_socket, message, msg_size + additional_length);
}
free(message);
message = NULL;
}
void public_message(table_entry_t *user, char *client_msg, size_t msg_size){
int room_id = user->room_id;
char *username = user->id;
//Add sender's username to message
char *postfix = PUBLIC_PREFIX;
char *message = add_username_to_message(client_msg, username, postfix);
size_t additional_length = strlen(username) + strlen(postfix) + 1; //Add one for MESSAGE_START
//Send message to all clients
send_message_to_all(room_id, message, msg_size + additional_length);
//Print client's message to server console
print_time();
printf("#%d ", room_id);
printf("%s\n", message + 1); //Add one to skip MESSAGE_START character
free(message);
message = NULL;
}
void remove_client(table_entry_t *user, char *server_msg_prefixed, char **who_messages){
int room_id = user->room_id;
char *username = user->id;
char *server_msg = server_msg_prefixed + 1;
//Print message to server terminal
printf("**%s in room #%d left the server**\n", username, room_id);
//Print message to chat room
sprintf(server_msg, SERVER_PREFIX "%s left the server", username);
send_message_to_all(room_id, server_msg_prefixed, strlen(server_msg_prefixed) + 1);
//Remove user entry from server and set who_messages for rebuild
remove_user(&user);
who_messages[room_id][0] = '\0';
}
static void terminate_server(int sig_num){
//Turn echoing back on
struct termios tc;
tcgetattr(STDIN_FILENO, &tc);
tc.c_lflag |= (ICANON | ECHO);
tcsetattr(STDIN_FILENO, TCSANOW, &tc);
exit(EXIT_SUCCESS);
}
void shutdown_server(char **who_messages){
int client_socket = 0;
int message_size = 0;
table_entry_t *user, *tmp;
const char *server_msg_literal = NULL;
//Create server-shutdown message
server_msg_literal = MESSAGE_START_STR SERVER_PREFIX "The server has been shutdown by an admin";
message_size = strlen(server_msg_literal) + 1;
//Free user messages, close client sockets, and delete users from hash table
for(int room_id = 0; room_id < MAX_ROOMS; room_id++){
HASH_ITER(hh, active_users[room_id], user, tmp){ //Uthash deletion-safe iteration
if(user->message){
free(user->message);
user->message = NULL;
}
client_socket = user->socket_fd;
send_message(client_socket, server_msg_literal, message_size);
check_status(close(client_socket), "Error closing client socket");
delete_user(&user);
}
}
//Free who_message strings
for(int i = 0; i < MAX_ROOMS; i++){
free(who_messages[i]);
who_messages[i] = NULL;
}
}
|
C
|
#include "genotype.h"
#include "population.h"
#include "random.h"
#include <webots/supervisor.h>
#include <webots/robot.h>
#include <webots/emitter.h>
#include <webots/display.h>
#include <webots/keyboard.h>
#include <webots/differential_wheels.h>
#include <webots/distance_sensor.h>
#include <webots/receiver.h>
#include <string.h>
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
// time in [ms] of a simulation step
#define TIME_STEP 64
// set neuron numbers and inputs here
static const int NEURON_INPUTS = 3;
static const int NUMBER_OF_NEURONS = 6;
double weights[NUMBER_OF_NEURONS][NEURON_INPUTS];
double inputs[2];
static const int POPULATION_SIZE = 50;
static const int NUM_GENERATIONS = 1;
//static const char *FILE_NAME = "fittest.txt";
#define GENOTYPE_SIZE (NEURON_INPUTS*NUMBER_OF_NEURONS)
// the GA population
static Population population;
// setup neural network.
void setup_neural_net() {
// initialize weights including bias.
int i,j;
int size = sizeof(weights) / sizeof(double);
int size_x = size / (sizeof(weights[0]) / sizeof(double));
int size_y = size / size_x;
for (i = 0; i < size_x; ++i) {
for (j = 0; j < size_y; ++j) {
if (j == 0) {
weights[i][j] = 1.0;
}
else {
weights[i][j] = (rand() % 202 - 101) / 100.0;
}
printf("Weights %f\n", weights[i][j]);
}
}
}
// sguash the ANN output between -1 and 1.
double hyperbolic_tangent(double value) {
return (1.0f - exp(- 2.0f * value)) / (1.0f + exp(-2.0f * value));
}
// Calculate the output based on weights evolved by GA.
double* evolve_neural_net(Genotype genotype) {
double nn_weights[NUMBER_OF_NEURONS][NEURON_INPUTS];
const double* genes = genotype_get_genes(genotype);
int m,n;
// Copy genes as an array in nn_weights format.
for (m = 0; m < NUMBER_OF_NEURONS; ++m) {
for (n = 0; n < NEURON_INPUTS; ++n) {
nn_weights[m][n] = genes[NEURON_INPUTS * m + n];
}
}
int input_size = sizeof(inputs) / sizeof(double);
int i,j, k;
double* h;
h = malloc(input_size);
memcpy(h, inputs, input_size);
for (i = 0; i < input_size; ++i) {
h[i] = hyperbolic_tangent(h[i]);
}
for (i = 0; i < NUMBER_OF_NEURONS; ++i) {
for (k = 0; k < input_size; ++k) {
double output = 0.0;
for (j = 0; j < NEURON_INPUTS; ++j) {
if (j == 0) {
output += nn_weights[i][j];
}
else {
output += nn_weights[i][j] * h[j-1];
}
}
h[k] = output;
}
}
for (i = 0; i < input_size; ++i) {
h[i] = hyperbolic_tangent(h[i]);
}
return h;
}
// compute fitness as the euclidian distance that the load was pushed
double measure_fitness(double *values) {
double V,deltaV;
// Sum of rotation speeds between two wheels.
V = fabs(values[0]) + fabs(values[1]);
// Add +1 to each speed value in order bring them between [0,2].
// This encourages the wheels to move in the same direction.
deltaV = fabs((values[0] + 1.0f) - (values[1] + 1.0f));
printf("V: %f\n", V);
printf("deltaV: %f\n", deltaV);
// Computes all the values together.
return V * (2.0f - sqrt(deltaV))
* (2.0f - ((hyperbolic_tangent(inputs[0])
+ hyperbolic_tangent(inputs[1])) / 2.0f));
}
// evaluate one genotype at a time
void evaluate_genotype(Genotype genotype) {
double* output = evolve_neural_net(genotype);
// measure fitness
double fitness = measure_fitness(output);
printf("Actual fitness: %f\n", fitness);
genotype_set_fitness(genotype, fitness);
printf("fitness: %g\n", fitness);
}
void run_optimization() {
wb_keyboard_disable();
printf("---\n");
printf("starting GA optimization ...\n");
printf("population size is %d, genome size is %d\n", POPULATION_SIZE, GENOTYPE_SIZE);
int i, j;
for (i = 0; i < NUM_GENERATIONS; i++) {
for (j = 0; j < POPULATION_SIZE; j++) {
printf("generation: %d, genotype: %d\n", i, j);
// evaluate genotype
Genotype genotype = population_get_genotype(population, j);
evaluate_genotype(genotype);
}
double best_fitness = genotype_get_fitness(population_get_fittest(population));
//double average_fitness = population_compute_average_fitness(population);
// display results
//plot_fitness(i, best_fitness, average_fitness);
printf("best fitness: %g\n", best_fitness);
//printf("average fitness: %g\n", average_fitness);
// reproduce (but not after the last generation)
if (i < NUM_GENERATIONS - 1)
population_reproduce(population);
}
printf("GA optimization terminated.\n");
//population_destroy(population);
}
// entry point of the controller
int main(int argc, char **argv)
{
// initialize the Webots API
wb_robot_init();
// internal variables
int i;
WbDeviceTag ps[8];
char ps_names[8][4] = {
"ps0", "ps1", "ps2", "ps3",
"ps4", "ps5", "ps6", "ps7"
};
// initialize devices
for (i=0; i<8 ; i++) {
ps[i] = wb_robot_get_device(ps_names[i]);
wb_distance_sensor_enable(ps[i], TIME_STEP);
}
//setup_neural_net();
// get simulation step in milliseconds
//time_step = wb_robot_get_basic_time_step();
// initial population
population = population_create(POPULATION_SIZE, GENOTYPE_SIZE);
//if (demo)
//run_demo();
// feedback loop
while (1) {
// step simulation
int delay = wb_robot_step(TIME_STEP);
if (delay == -1) // exit event from Webots
break;
// read sensors outputs
double ps_values[8];
for (i=0; i<8 ; i++) {
ps_values[i] = wb_distance_sensor_get_value(ps[i]);
if (i == 0) {
inputs[0] = ps_values[i];
}
else if (i == 7) {
inputs[1] = ps_values[i];
}
//printf("sensor %d: %f\n", i, ps_values[i]);
//printf("Sensor %f\n",inputs[i]);
}
// detect obstacles
bool right_obstacle =
ps_values[0] > 100.0 ||
ps_values[1] > 100.0 ||
ps_values[2] > 100.0;
bool left_obstacle =
ps_values[5] > 100.0 ||
ps_values[6] > 100.0 ||
ps_values[7] > 100.0;
// init speeds
double left_speed = 500;
double right_speed = 500;
// modify speeds according to obstacles
if (left_obstacle) {
left_speed += 500;
right_speed -= 500;
}
else if (right_obstacle) {
left_speed -= 500;
right_speed += 500;
}
// write actuators inputs
wb_differential_wheels_set_speed(left_speed, right_speed);
//run GA optimization
run_optimization();
}
// cleanup the Webots API
wb_robot_cleanup();
return 0; //EXIT_SUCCESS
}
|
C
|
// Write a method to replace all spaces in a string with '%20'. You may assume
// that the string has sufficient space at the end of the string to hold
// additional characters, and that you are given the length of the string.
#include "4.h"
void replace_space(char* s, int n){
int i = 0, count = -1, A[n];
char c;
for (; (c = s[i]) != '\0'; ++i){
if (c == ' '){
A[++count] = i;
}
}
for (; i >= 0 && count >= 0; --i){
if (i == A[count]){
s[i + 2*count + 2] = '0';
s[i + 2*count + 1] = '2';
s[i + 2*count] = '%';
--count;
}
else s[i + 2*count + 2] = s[i];
}
}
|
C
|
#include "stdio.h"
typedef struct
{
int data[50];//Ϊ
int top;
}seqstack;
//ջijʼ
void initstack(seqstack *s)
{
s->top=-1;
}
//жջǷΪ
int empty(seqstack *s)
{
if(s->top==-1)
return 1;
else
return 0;
}
//ջ
void push(seqstack *s,int x)
{
if(s->top==49)//ջ±Ϊ0-49
printf("overflow!\n");
else
{
s->top++;
s->data[s->top]=x;
}
}
//ջ
char pop(seqstack *s)
{
int x;
if(empty(s))
{
printf("underflow!\n");
x='\0';
}
else
{
x=s->data[s->top];
s->top--;
}
return x;
}
void multibase(int n,int b)
{
int i;
seqstack s;
initstack(&s);
while(n!=0)
{
push(&s,n%b);//ջ
n=n/b;
}
printf("תĽ:");
while(!empty(&s))
{
i=pop(&s);//ջ
printf("%d",i);
}
printf("\n");
}
main()
{
int n,b;
printf("ʮ:");
scanf("%d",&n);
printf("ҪתĽ:");
scanf("%d",&b);
multibase(n,b);//ת
}
|
C
|
#include "pub.h"
void init_memory_list(struct list *list_head)
{
int index;
pData init_node;
for(index=0; index<10; index++){
init_node = calloc(1, sizeof(sData));
init_node->size = 10;
init_node->start_add = calloc(1, 10);
init_node->end_add = init_node->start_add + 9;
list_add_tail(list_head, &init_node->_list);
}
}
void PrintData(struct list *list_head)
{
struct list *print_node;
pData data_node;
list_each(print_node, list_head){
data_node = list_entry(print_node, sData, _list);
printf("(%d) start:%p end:%p\n",
data_node->size,
data_node->start_add, data_node->end_add);
}
}
void ApplyMemory(struct syslist *sys_list)
{
unsigned int apply_size;
unsigned int sum_size;
pRecordHead new_record_head;
struct list *each_node;
printf("请输入要申请的空间大小\n");
scanf("%d", &apply_size);
list_each(each_node, sys_list->apply_list){
sum_size += list_entry(each_node, sData, _list)->size;
}
if (apply_size > sum_size){
printf("内存不足.\n");
return ;
}
new_record_head = calloc(1, sizeof(sRecordHead));
new_record_head->record_index = record_index++;
list_add_tail(sys_list->record_list, &new_record_head->_list);
new_record_head->record_list.next = &new_record_head->record_list;
new_record_head->record_list.prev = &new_record_head->record_list;
Fun_apply(sys_list, apply_size);
}
void Fun_apply(struct syslist *sys_list, unsigned int apply_size)
{
struct list *max_node = find_max_size(sys_list->apply_list);
if (apply_size <= list_entry(max_node, sData, _list)->size){
Fun_apply_low(sys_list, apply_size, max_node);
return ;
}
if (apply_size > list_entry(max_node, sData, _list)->size){
Fun_apply_high(sys_list, apply_size);
return ;
}
}
void Fun_apply_low(struct syslist *sys_list, unsigned int apply_size, struct list *max_node)
{
struct list *equal_node = find_equal_size(sys_list->apply_list, apply_size);
pRecordHead record_head = list_entry((sys_list->record_list->prev), sRecordHead, _list);
pRecordNode record_node = calloc(1, sizeof(sRecordNode));
pData new_node;
if (NULL==equal_node){
new_node = calloc(1, sizeof(sData));
new_node->size = apply_size;
new_node->start_add = list_entry(max_node, sData, _list)->start_add;
new_node->end_add = list_entry(max_node, sData, _list)->start_add+apply_size-1;
InsertFreeList(sys_list->free_list, new_node);
list_entry(max_node, sData, _list)->start_add += apply_size;
list_entry(max_node, sData, _list)->size -= apply_size;
if (list_entry(max_node, sData, _list)->size == 0){
list_remove(max_node);
free(list_entry(max_node, sData, _list));
}
record_node->address = &new_node->_list;
list_add_tail(&record_head->record_list, &record_node->_list);
}
else{
list_remove(equal_node);
InsertFreeList(sys_list->free_list, list_entry(equal_node, sData, _list));
record_node->address = equal_node;
list_add_tail(&record_head->record_list, &record_node->_list);
}
}
void InsertFreeList(struct list *free_list, pData insert_node)
{
struct list *ergodic_node;
if (free_list->next == free_list){
list_add_tail(free_list, &insert_node->_list);
return ;
}
list_each(ergodic_node, free_list){
if (list_entry(ergodic_node, sData, _list)->size > insert_node->size){
list_add_head(ergodic_node->prev, &insert_node->_list);
return ;
}
}
list_add_tail(free_list, &insert_node->_list);
}
void Fun_apply_high(struct syslist *sys_list, unsigned int apply_size)
{
struct list *max_node = find_max_size(sys_list->apply_list);
apply_size = apply_size - list_entry(max_node, sData, _list)->size;
Fun_apply(sys_list, list_entry(max_node, sData, _list)->size);
Fun_apply(sys_list, apply_size);
}
struct list *find_max_size(struct list *list_head)
{
struct list *max_node = list_head->next;
struct list *find_node;
list_each(find_node, list_head){
if (list_entry(find_node, sData, _list)->size >
list_entry(max_node, sData, _list)->size)
max_node = find_node;
}
return max_node;
}
struct list *find_equal_size(struct list *list_head, unsigned int apply_size)
{
struct list *find_node;
list_each(find_node, list_head){
if (list_entry(find_node, sData, _list)->size == apply_size)
return find_node;
}
return NULL;
}
void FreeMemory(struct syslist *sys_list)
{
unsigned int free_num;
struct list *record_free;
printf("请输入销毁的序号.\n");
scanf("%d", &free_num);
list_each(record_free, sys_list->record_list){
if (list_entry(record_free, sRecordHead, _list)->record_index == free_num){
free_fun(sys_list, list_entry(record_free, sRecordHead, _list));
return ;
}
}
printf("无此序号申请内存.\n");
}
void free_fun(struct syslist *sys_list, pRecordHead record_free)
{
struct list *free_node;
list_each(free_node, (&record_free->record_list)){
list_remove(list_entry(free_node, sRecordNode, _list)->address);
list_add_tail(sys_list->apply_list, list_entry(free_node, sRecordNode, _list)->address);
list_remove(free_node);
free(list_entry(free_node, sRecordNode, _list));
free_node = &record_free->record_list;
}
}
|
C
|
#include <stdio.h>
float average(int a , int b){
float avg =(a+b)/2;
return avg;
}
void getGrades(){
int grade1=0;
printf("Enter your 1st grade: ");
scanf("%d",&grade1);
int grade2=0;
printf("Enter your 2nd grade: ");
scanf("%d",&grade2);
printf("Your 1st grade: %d/100 \n", grade1);
printf("Your 2nd grade: %d/100 \n", grade2);
float avg=average(grade1,grade2);
printf("Your average is %f\n", avg);
}
int main(){
unsigned int age;
printf("Address of var1: %x\n",&age);
char fname[30];
char lname[30];
printf("Please enter your fname: ");
scanf("%s", fname);
printf("Please enter your lname: ");
scanf("%s", lname);
printf("Please enter your age: ");
scanf("%d", &age);
printf("Full name: %s %s \n", fname, lname);
printf("Age: %d \n", age);
getGrades();
return 0;
}
|
C
|
#include "miniasm.h"
#define OP1(a) ((a & 0xff00) >> 8)
#define OP2(a) ((a & 0xff0000) >>16)
#define OP3(a) ((a & 0xff000000) >>24)
#define REG(a) ctx->r[a].value
#define MEM(a) ctx->heap[a]
#define CONV(a) &(ctx->heap[a])
extern bool is_running;
void check(uint32_t adr){
if(adr >=8192){
fprintf(stderr,"Invalid address\n");
exit(1);
}
}
void halt(struct VMContext* ctx, const uint32_t instr){
ctx->is_running = false;
}
void load(struct VMContext* ctx, const uint32_t instr){
uint32_t r2 = REG(OP2(instr));
check(r2);
REG(OP1(instr)) = ((uint32_t)(MEM(r2)) & 0xff);
}
void store(struct VMContext* ctx, const uint32_t instr){
uint32_t r1 = REG(OP1(instr));
check(r1);
MEM(r1) = REG(OP2(instr)) & 0xff;
}
void move(struct VMContext* ctx, const uint32_t instr){
REG(OP1(instr)) = REG(OP2(instr));
}
void puti(struct VMContext* ctx, const uint32_t instr){
REG(OP1(instr)) = OP2(instr);
}
void add(struct VMContext* ctx, const uint32_t instr){
REG(OP1(instr)) = REG(OP2(instr)) + REG(OP3(instr));
}
void sub(struct VMContext* ctx, const uint32_t instr){
REG(OP1(instr)) = REG(OP2(instr)) - REG(OP3(instr));
}
void gt(struct VMContext* ctx, const uint32_t instr){
REG(OP1(instr)) = REG(OP2(instr)) > REG(OP3(instr)) ? 1: 0;
}
void ge(struct VMContext* ctx, const uint32_t instr){
REG(OP1(instr)) = REG(OP2(instr)) >= REG(OP3(instr)) ? 1: 0;
}
void eq(struct VMContext* ctx, const uint32_t instr){
REG(OP1(instr)) = REG(OP2(instr)) == REG(OP3(instr)) ? 1: 0;
}
void ite(struct VMContext* ctx, const uint32_t instr){
ctx->pc = REG(OP1(instr)) >0 ? OP2(instr)-1: OP3(instr)-1;
}
void jump(struct VMContext* ctx, const uint32_t instr){
ctx->pc = OP1(instr) -1;
}
void asm_puts(struct VMContext* ctx, const uint32_t instr){
uint32_t v = REG(OP1(instr));
char *ptr = CONV(v);
for(uint32_t i = 0; i<strlen(ptr); i++){
check(v+i);
write(1,&ptr[i],1);
}
}
void asm_gets(struct VMContext* ctx, const uint32_t instr){
uint32_t v = REG(OP1(instr));
char *ptr = CONV(v);
uint32_t i =0;
char tmp;
while(1){
check(v+i);
if(read(0,&tmp,1)==1){
if(tmp == '\n'){
ptr[i] = '\0';
break;
}else{
ptr[i] = tmp;
i++;
}
}else break;
}
}
|
C
|
#include<stdlib.h>
#include<stdio.h>
#include<omp.h>
#define STB_IMAGE_WRITE_IMPLEMENTATION
#include"stb_image_write.h"
#define STB_IMAGE_IMPLEMENTATION
#include"stb_image.h"
#define MAX 512
/*
**Author: Francisnei Bernardes Lima
**Data: 17/11/20
**Projeto de processamento de imagens em paralelo
**utilizando OpenMP e stb_lib
*/
typedef struct img{
int altura;
int largura;
int canais;
unsigned char *data;
}Imagem;
int carregaImagemFiltro(int x, int y);
int media(int v[8]);
int v[8];
int matriz[MAX][MAX];
int matriz2[MAX][MAX];
int main(){
Imagem img;
img.data = stbi_load("img/lena_gray.gif",&img.largura, &img.altura, &img.canais, 1);
int buffer =img.altura * img.largura;
int x,y,c;
#pragma omp parallel private(c)
{
#pragma omp for ordered
for(c=0; c<buffer; c++){
#pragma omp ordered
if(x == img.largura){
y++;
x = 0;
}
#pragma omp flush(c)
matriz[x][y] = img.data[c];
x++;
}
}
#pragma omp parallel private(x,y)
{
#pragma omp for ordered
for(x=0;x<MAX;x++){
#pragma omp ordered
for(y=0;y<MAX;y++){
carregaImagemFiltro(x,y);
}
}
}
c=0;
#pragma omp parallel private(x,y)
{
#pragma omp for ordered
for(x=0;x<MAX;x++){
#pragma omp ordered
for(y=0;y<MAX;y++){
#pragma omp flush(c)
img.data[c] = matriz2[y][x];
c++;
}
}
}
stbi_write_bmp("suavisada.bmp",MAX,MAX,1,img.data);
return 0;
}
int carregaImagemFiltro(int x, int y){
v[0] = matriz[x-1][y-1];
v[1] = matriz[x-1][y-0];
v[2] = matriz[x-1][y+1];
v[3] = matriz[x-0][y-1];
v[4] = matriz[x-0][y-0];
v[5] = matriz[x-0][y+1];
v[6] = matriz[x+1][y-1];
v[7] = matriz[x+1][y-0];
v[8] = matriz[x+1][y+1];
if(x == 0){
v[0] = 0;
v[1] = 0;
v[2] = 0;
}
if(x == MAX -1){
v[6] = 0;
v[7] = 0;
v[8] = 0;
}
if(y == 0){
v[0] = 0;
v[3] = 0;
v[6] = 0;
}
if(y == MAX - 1){
v[2] = 0;
v[5] = 0;
v[8] = 0;
}
matriz2[x][y] = media(v);
}
int media(int v[8]){
int c;
int soma = 0;
for(c=0;c<8;c++){
soma = soma + v[c];
}
int res;
res = soma/9;
return res;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
int main()
{
int a[10] = {6,3,8,10,16,7,5,2,9,14};
for (int i=0;i<10;i++)
{
printf("%d ",a[i]);
}
printf("\n");
int k=10;
int H[30]={0};
for (int i=0;i<10;i++)
{
if ((k-a[i])>=0 && H[k-a[i]]!=0)
{
printf("%d and %d \n",a[i],k-a[i]);
}
H[a[i]]++;
}
int b[10] = {1,3,4,5,6,8,9,10,12,14};
printf("\n");
for (int i=0;i<10;i++)
{
printf("%d ",b[i]);
}
int i=0,j=9;printf("\n");
while(i<j)
{
if (b[i]+b[j]==k)
{
printf("%d and %d\n",b[i],b[j]);
i++;j--;
}
else if (b[i]+b[j]<k)
{
i++;
}
else
{
j--;
}
}
return 0;
}
|
C
|
#include <stdio.h>
#include <string.h>
int main() {
char text[50];
scnaf("%s", text);
for(int i=0; i<strlen(text); i++){
text[i]=toupper(text[i]);
printf("%c", text[i]);
}
}
|
C
|
/*************************************************************************
* Compilation: javac Heap.java
* Execution: java Heap < input.txt
* Dependencies: StdOut.java StdIn.java
* Data files: http://algs4.cs.princeton.edu/24pq/tiny.txt
* http://algs4.cs.princeton.edu/24pq/words3.txt
*
* Sorts a sequence of strings from standard input using heapsort.
*
* % more tiny.txt
* S O R T E X A M P L E
*
* % java Heap < tiny.txt
* S O R T E X A M P L E A [ one string per line ]
*
* % more words3.txt
* bed bug dad yes zoo ... all bad yet
*
* % java Heap < words3.txt
* all bad bed bug dad ... yes yet zoo [ one string per line ]
*
*************************************************************************/
#include <stdio.h>
/***********************************************************************
* Helper functions for comparisons and swaps.
* Indices are "off-by-one" to support 1-based indexing.
**********************************************************************/
int less01(char *pq[], int i, int j) {
if(strcmp(pq[i-1],pq[j-1]) < 0)
return 1;
else return 0;
}
void exch(char *pq[], int i, int j) {
char *swap;
swap = pq[i-1];
pq[i-1] = pq[j-1];
pq[j-1] = swap;
}
/* is v < w ?*/
int less02(char *v, char *w) {
if(strcmp(v,w) < 0)
return 1;
else return 0;
}
/***********************************************************************
* Helper functions to restore the heap invariant.
**********************************************************************/
void sink(char *pq[], int k, int N) {
int j;
while (2*k <= N) {
j = 2*k;
if (j < N && less01(pq, j, j+1)) j++;
if (!less01(pq, k, j)) break;
exch(pq, k, j);
k = j;
}
}
void sort(char *pq[],int length)
{
int k;
for (k=length/2;k>=1;k--)
sink(pq,k,length);
while (length>1)
{
exch(pq,1,length--);
sink(pq,1,length);
}
}
/***********************************************************************
* Check if array is sorted - useful for debugging
***********************************************************************/
int isSorted(char *a[],int length) {
int i ;
for (i = 1; i < length; i++)
if (less02(a[i], a[i-1])) return 0;
return 1;
}
/* print array to standard output*/
void show(char *a[],int length) {
int i;
for (i = 0; i < length; i++) {
printf("%s\n",a[i]);
}
}
#define MAX 25
char *a[MAX];
/* Read strings from standard input, sort them, and print.*/
void main(int argc, char *argv[]) {
int i;
for(i=1;i<argc;i++)
{
a[i-1] = argv[i];
}
printf("%d\n", isSorted(a, argc-1) );
sort(a,argc-1);
printf("***************** Sorted Strings *****************\n");
show(a,argc-1);
}
|
C
|
#include <stdio.h>
int prime(int n);
int main()
{
int count = 0;
long int num;
printf("Enter the number: ");
scanf("%d", &num);
for (int i = 1; i <= num; i++)
{
if (prime(i) == 3)
{
count++;
printf("%d\n", i);
}
}
printf("Total count: %d\n", count);
return 0;
}
int prime(int n)
{
if (n <= 1)
{
// neither
return 1;
}
for (int i = 2; i < n; i++)
{
if (n % i == 0)
{
// not a prime
return 2;
}
}
// prime
return 3;
}
|
C
|
#include <stdlib.h>
#include <string.h>
#include <stdint.h>
#include "flibs/compiler.h"
#include "flibs/fmbuf.h"
// mbuf, contain the two pointer: the header and tailer, let's see the basic
// use cases:
// 1. the mbuf is empty: when the header == tailer
// 2. the mbuf is full: when the next location of tailer == header
#define MBUF_START(pbuf) ( pbuf->buf )
#define MBUF_END(pbuf) ( pbuf->buf + pbuf->size )
#define MBUF_HEAD(pbuf) ( pbuf->head )
#define MBUF_TAIL(pbuf) ( pbuf->tail )
#define MBUF_SIZE(pbuf) ( pbuf->size )
#define MBUF_USED(pbuf) \
( MBUF_HEAD(pbuf) <= MBUF_TAIL(pbuf) \
? (uintptr_t)(MBUF_TAIL(pbuf) - MBUF_HEAD(pbuf)) \
: MBUF_SIZE(pbuf) - (uintptr_t)(MBUF_HEAD(pbuf) - MBUF_TAIL(pbuf)) + 1 )
#define MBUF_FREE(pbuf) \
( MBUF_HEAD(pbuf) <= MBUF_TAIL(pbuf) \
? MBUF_SIZE(pbuf) - (uintptr_t)(MBUF_TAIL(pbuf) - MBUF_HEAD(pbuf)) \
: (uintptr_t)(MBUF_HEAD(pbuf) - MBUF_TAIL(pbuf)) - (size_t)1 )
#define MBUF_COPY(dst, src, sz) \
if (sz > 0 && dst && src) { \
memcpy(dst, src, sz); \
}
struct _mbuf {
size_t size;
char* head;
char* tail;
char buf[sizeof(void*)];
};
fmbuf* fmbuf_create(size_t size)
{
// must reserve 1 byte for mbuf
fmbuf* mbuf = calloc(1, sizeof(fmbuf) + size + 1);
mbuf->size = size;
mbuf->head = mbuf->tail = mbuf->buf;
return mbuf;
}
void fmbuf_delete(fmbuf* pbuf)
{
free(pbuf);
}
int fmbuf_push(fmbuf* pbuf, const void* data, size_t size)
{
if (data && size > 0 && MBUF_FREE(pbuf) >= size) {
size_t tail_free = fmbuf_tail_free(pbuf) + 1;
if (tail_free >= size) {
memcpy(MBUF_TAIL(pbuf), data, size);
MBUF_TAIL(pbuf) += size;
if(MBUF_TAIL(pbuf) > MBUF_END(pbuf))
MBUF_TAIL(pbuf) = MBUF_START(pbuf);
} else {
memcpy(MBUF_TAIL(pbuf), data, tail_free);
size_t left = size - tail_free;
memcpy(MBUF_START(pbuf), (const char*)data + tail_free, left);
FMEM_BARRIER();
MBUF_TAIL(pbuf) = MBUF_START(pbuf) + left;
}
return 0; //push sucess
}
return 1; //push failed
}
//pop data from head
//if head to end space is less than size then go on to pop from start
int fmbuf_pop(fmbuf* pbuf, void* data, size_t size)
{
if (size > 0 && size <= MBUF_USED(pbuf)) {
size_t tail_use = (size_t)(MBUF_END(pbuf) - MBUF_HEAD(pbuf) + 1);
if (tail_use >= size) {
MBUF_COPY(data, MBUF_HEAD(pbuf), size);
MBUF_HEAD(pbuf) += size;
if (MBUF_HEAD(pbuf) > MBUF_END(pbuf))
MBUF_HEAD(pbuf) = MBUF_START(pbuf);
} else {
size_t left = size - tail_use;
if (data) {
MBUF_COPY(data, MBUF_HEAD(pbuf), tail_use);
MBUF_COPY((char*)data + tail_use, MBUF_START(pbuf), left);
}
FMEM_BARRIER();
MBUF_HEAD(pbuf) = MBUF_START(pbuf) + left;
}
return 0; //pop sucess
}
return 1; //pop failed
}
// ensure you use the return value , that's safe
void* fmbuf_vpop(fmbuf* pbuf, void* data, size_t size)
{
if (data && size > 0 && size <= (size_t)MBUF_USED(pbuf)) {
size_t tail_use = (size_t)(MBUF_END(pbuf) - MBUF_HEAD(pbuf) + 1);
if (tail_use >= size) {
data = MBUF_HEAD(pbuf);
MBUF_HEAD(pbuf) += size;
if(MBUF_HEAD(pbuf) > MBUF_END(pbuf))
MBUF_HEAD(pbuf) = MBUF_START(pbuf);
} else {
memcpy(data, MBUF_HEAD(pbuf), tail_use);
size_t left = size - tail_use;
memcpy((char*)data + tail_use, MBUF_START(pbuf), left);
FMEM_BARRIER();
MBUF_HEAD(pbuf) = MBUF_START(pbuf) + left;
}
return data; //pop sucess
}
return NULL; //pop failed
}
void* fmbuf_rawget(fmbuf* pbuf, void* data, size_t size)
{
if (data && size > 0 && size <= MBUF_USED(pbuf)) {
size_t tail_use = (size_t)(MBUF_END(pbuf) - MBUF_HEAD(pbuf) + 1);
if (tail_use >= size) {
data = MBUF_HEAD(pbuf);
} else {
memcpy(data, MBUF_HEAD(pbuf), tail_use);
size_t left = size - tail_use;
memcpy((char*)data + tail_use, MBUF_START(pbuf), left);
}
return data; //get sucess
}
return NULL; //get failed
}
void* fmbuf_alloc(fmbuf* pbuf, size_t size)
{
if (fmbuf_tail_free(pbuf) < size)
fmbuf_rewind(pbuf);
if (fmbuf_tail_free(pbuf) >= size) {
char* ptr = MBUF_TAIL(pbuf);
MBUF_TAIL(pbuf) += size;
return ptr;
}
return NULL;
}
void fmbuf_rewind(fmbuf* pbuf)
{
size_t head_free = fmbuf_head_free(pbuf);
if (head_free == 0)
return;
memmove(MBUF_START(pbuf), MBUF_HEAD(pbuf), MBUF_USED(pbuf));
fmbuf_head_seek(pbuf, head_free, FMBUF_SEEK_LEFT);
fmbuf_tail_seek(pbuf, head_free, FMBUF_SEEK_LEFT);
}
void fmbuf_clear(fmbuf* pbuf)
{
MBUF_HEAD(pbuf) = MBUF_TAIL(pbuf) = MBUF_START(pbuf);
}
void fmbuf_head_seek(fmbuf* pbuf, size_t offset, int direction)
{
if (direction == FMBUF_SEEK_LEFT) {
MBUF_HEAD(pbuf) -= offset;
} else {
MBUF_HEAD(pbuf) += offset;
}
}
void fmbuf_tail_seek(fmbuf* pbuf, size_t offset, int direction)
{
if (direction == FMBUF_SEEK_LEFT) {
MBUF_TAIL(pbuf) -= offset;
} else {
MBUF_TAIL(pbuf) += offset;
}
}
size_t fmbuf_used(fmbuf* pbuf)
{
return MBUF_USED(pbuf);
}
size_t fmbuf_free(fmbuf* pbuf)
{
return MBUF_FREE(pbuf);
}
size_t fmbuf_tail_free(fmbuf* pbuf)
{
// do worry, the MBUF_END always >= MBUF_TAIL
return (size_t)(MBUF_END(pbuf) - MBUF_TAIL(pbuf));
}
size_t fmbuf_head_free(fmbuf* pbuf)
{
// do worry, the MBUF_HEAD always >= MBUF_START
return (size_t)(MBUF_HEAD(pbuf) - MBUF_START(pbuf));
}
static
fmbuf* _increase_buf(fmbuf* pbuf, size_t size)
{
size_t head_offset = (size_t)(MBUF_HEAD(pbuf) - MBUF_START(pbuf));
size_t tail_offset = (size_t)(MBUF_TAIL(pbuf) - MBUF_START(pbuf));
if (MBUF_HEAD(pbuf) <= MBUF_TAIL(pbuf)) {
fmbuf* new_buf = realloc(pbuf, sizeof(fmbuf) + size + 1);
MBUF_HEAD(new_buf) = MBUF_START(new_buf) + head_offset;
MBUF_TAIL(new_buf) = MBUF_START(new_buf) + tail_offset;
MBUF_SIZE(new_buf) = size;
return new_buf;
} else {
// 1. calculate used buffer size for:
// * start to tailer
// * header to end
// 2. move the min part
// 1.
size_t increased_sz = size - MBUF_SIZE(pbuf);
size_t left_used = tail_offset;
size_t right_used = MBUF_USED(pbuf) - left_used;
fmbuf* new_buf = realloc(pbuf, sizeof(fmbuf) + size + 1);
MBUF_HEAD(new_buf) = MBUF_START(new_buf) + head_offset;
MBUF_TAIL(new_buf) = MBUF_START(new_buf) + tail_offset;
// 2.
if (left_used <= right_used && left_used <= increased_sz) {
void* dst = MBUF_END(new_buf) + 1;
memmove(dst, MBUF_START(new_buf), left_used);
MBUF_TAIL(new_buf) = (char*)dst + left_used;
MBUF_SIZE(new_buf) = size;
if(MBUF_TAIL(new_buf) > MBUF_END(new_buf))
MBUF_TAIL(new_buf) = MBUF_START(new_buf);
} else {
void* dst = MBUF_HEAD(new_buf) + increased_sz;
memmove(dst, MBUF_HEAD(new_buf), right_used);
MBUF_HEAD(new_buf) += increased_sz;
MBUF_SIZE(new_buf) = size;
}
return new_buf;
}
}
static
fmbuf* _decrease_buf(fmbuf* pbuf, size_t size)
{
size_t tail_offset = (size_t)(MBUF_TAIL(pbuf) - MBUF_START(pbuf));
if (MBUF_HEAD(pbuf) <= MBUF_TAIL(pbuf)) {
if (tail_offset > size) {
fmbuf_rewind(pbuf);
tail_offset = (size_t)(MBUF_TAIL(pbuf) - MBUF_START(pbuf));
size = tail_offset > size ? tail_offset : size;
}
size_t head_offset = (size_t)(MBUF_HEAD(pbuf) - MBUF_START(pbuf));
fmbuf* new_buf = realloc(pbuf, sizeof(fmbuf) + size + 1);
MBUF_HEAD(new_buf) = MBUF_START(new_buf) + head_offset;
MBUF_TAIL(new_buf) = MBUF_START(new_buf) + tail_offset;
MBUF_SIZE(new_buf) = size;
return new_buf;
} else {
size_t left_used = tail_offset;
size_t right_used = MBUF_USED(pbuf) - left_used;
size_t decreased_sz = MBUF_SIZE(pbuf) - size;
size_t free_sz = MBUF_FREE(pbuf);
size_t move_sz = free_sz >= decreased_sz ? decreased_sz : free_sz;
size_t actual_sz = MBUF_SIZE(pbuf) - move_sz;
size_t head_offset = (size_t)(MBUF_HEAD(pbuf) - MBUF_START(pbuf));
void* dst = MBUF_HEAD(pbuf) - move_sz;
memmove(dst, MBUF_HEAD(pbuf), right_used);
MBUF_HEAD(pbuf) -= move_sz;
head_offset = (size_t)(MBUF_HEAD(pbuf) - MBUF_START(pbuf));
fmbuf* new_buf = realloc(pbuf, sizeof(fmbuf) + actual_sz + 1);
MBUF_HEAD(new_buf) = MBUF_START(new_buf) + head_offset;
MBUF_TAIL(new_buf) = MBUF_START(new_buf) + tail_offset;
MBUF_SIZE(new_buf) = actual_sz;
return new_buf;
}
}
fmbuf* fmbuf_realloc(fmbuf* pbuf, size_t size)
{
size_t total_size = MBUF_SIZE(pbuf);
if (total_size == size) {
return pbuf;
} else if (total_size < size) {
return _increase_buf(pbuf, size);
} else { // total_size > size
return _decrease_buf(pbuf, size);
}
}
void* fmbuf_head(fmbuf* pbuf)
{
return MBUF_HEAD(pbuf);
}
void* fmbuf_tail(fmbuf* pbuf)
{
return MBUF_TAIL(pbuf);
}
size_t fmbuf_size(fmbuf* pbuf)
{
return MBUF_SIZE(pbuf);
}
bool fmbuf_empty(fmbuf* pbuf) {
return MBUF_USED(pbuf) == 0;
}
|
C
|
#include "local.h"
#include "userp_private.h"
/*
## Userp Diagnostics
### Synopsis
userp_diag d= userp_env_get_last_error(env);
if (userp_diag_get_code(d) == USERP_EALLOC)
...
else
userp_diag_print(d, stderr);
### Description
libuserp reports errors, warnings, and debug information via the userp_diag object.
The library stores useful details into this object, and then (dependong on what
callback you register on the `userp_env`) you receive the object and can make
decisions about what to do based on its attributes, or just format it as text.
### Attributes
#### code
int code= userp_diag_get_code(diag);
const char *name= userp_diag_code_name(code);
The primary attribute is 'code'. This determines which other fields are relevant.
The following codes are defined:
```
```
The following macros let you test the severity of an error code:
```
USERP_IS_FATAL(code)
USERP_IS_ERROR(code)
USERP_IS_WARN(code)
USERP_IS_DEBUG(code)
```
Fatal errors indicate something that even a robust error handler probably can't
recover from. The default handler will call abort().
Regular errors indicate a problem that prevents whatever action was being attempted,
but if the calling code checks the return value it can fail gracefully.
Warnings indicate potential problems that the caller should be aware of but which
are not interrupting use of the library.
Debug messages are diagnostics to record what is occurring inside the library to
help the developer track down problems. These are not generated unless the flag is
set in the userp environment.
*/
int userp_diag_get_code(userp_diag diag) {
return diag->code;
}
const char * userp_diag_code_name(int code) {
#define RETSTR(x) case x: return #x;
switch (code) {
RETSTR(USERP_EFATAL)
RETSTR(USERP_EBADSTATE)
RETSTR(USERP_ERROR)
RETSTR(USERP_EALLOC)
RETSTR(USERP_EDOINGITWRONG)
RETSTR(USERP_ETYPESCOPE)
RETSTR(USERP_ESYS)
RETSTR(USERP_EPROTOCOL)
RETSTR(USERP_EFEEDME)
RETSTR(USERP_ELIMIT)
RETSTR(USERP_ESYMBOL)
RETSTR(USERP_ETYPE)
RETSTR(USERP_WARN)
RETSTR(USERP_WLARGEMETA)
default:
return "unknown";
}
#undef RETSTR
}
/*
#### buffer
char *data;
size_t pos, len;
bool success= userp_diag_get_buffer(diag, &buf, &pos, &len);
Most operations in libuserp happen in the context of a shared buffer. If one was
relevant to this diagnostic, this gives you a reference to it, along with the
current position and length of relevant bytes.
The output parameters are optional (if they are NULL, the value is not copied).
It returns true if a buffer was referenced by this diagnistic.
*
bool userp_diag_get_buffer(userp_diag diag, userp_buffer *buf_p, size_t *pos_p, size_t *len_p) {
if (!diag->buf)
return false;
if (buf_p) *buf_p= diag->buf;
if (pos_p) *pos_p= diag->pos;
if (len_p) *len_p= diag->len;
return true;
}
/*
#### index
Generic attribute for reporting "Nth thing". Returns 0 if unused.
#### size
Generic attribute reporting total size (bytes) of something.
#### count
Generic attribute reporting total number of things.
*/
int userp_diag_get_index(userp_diag diag) {
return diag->index;
}
size_t userp_diag_get_size(userp_diag diag) {
return diag->size;
}
size_t userp_diag_get_count(userp_diag diag) {
return diag->count;
}
/*
### Methods
#### userp_diag_format
char buffer[SOME_NUMBER];
int needed= userp_diag_format(diag, buffer, sizeof(buffer));
Like the snprintf function, this writes data into a buffer up to a maximum allocation size
and then returns the total number of characters (not including NULL) that would have been
written to the buffer if it was infinitely large.
The error message may be translated or modified in any version of the library. Do not
depend on its output.
#### userp_diag_print
int wrote= userp_diag_print(diag, stderr);
Stream the diagnostic message into FILE, returning the total number of bytes written,
or ``` -1 - bytes_written ``` if there is an I/O error.
*/
static int userp_process_diag_tpl(userp_diag diag, char *buf, size_t buf_len, FILE *fh);
int userp_diag_format(userp_diag diag, char *buf, size_t buflen) {
return userp_process_diag_tpl(diag, buf, buflen, NULL);
}
int userp_diag_print(userp_diag diag, FILE *fh) {
return userp_process_diag_tpl(diag, NULL, 0, fh);
}
int userp_process_diag_tpl(userp_diag diag, char *buf, size_t buf_len, FILE *fh) {
const char *from, *pos= diag->tpl, *p1, *p2;
char tmp_buf[sizeof(diag->buffer)*4], id;
size_t n= 0, str_len= 0;
bool hex= false, at_pos;
long long val= 0;
if (!pos)
pos= "(no message)";
if (!diag->code)
pos= "(no error)";
while (*pos) {
// here, *pos is either \x01 followed by a code indicating which variable to insert,
// or any other character means to scan forward.
if (*pos == '\x01') {
from= tmp_buf; // source of next block of character data to emit
n= 0; // number of chars to copy from 'from'
++pos;
switch (id= *pos++) {
// Buffer, displayed as a pointer address
case USERP_DIAG_PTR_ID:
n= snprintf(tmp_buf, sizeof(tmp_buf), "%p", diag->ptr);
break;
// Buffer, hexdump the contents
case USERP_DIAG_BUFHEX_ID:
hex= true;
n= 0;
if (0) {
// Buffer, printed as a string with escapes
case USERP_DIAG_BUFSTR_ID:
hex= false;
tmp_buf[0]= '"';
n= 1;
}
p1= (char*) diag->buffer;
p2= p1 + diag->len;
if (p2 > p1 + sizeof(diag->buffer))
p2= p1 + sizeof(diag->buffer);
for (; n+9 < sizeof(tmp_buf) && p1 < p2; p1++) {
at_pos= p1 == (diag->buffer + diag->pos);
if (hex || *p1 < 32 || *p1 >= 0x7F || *p1 == '\\' || *p1 == '"') {
if (at_pos) {
if (hex) {
tmp_buf[n++]= '>';
} else {
tmp_buf[n++]= '"';
tmp_buf[n++]= ' ';
tmp_buf[n++]= '>';
tmp_buf[n++]= '"';
}
}
if (!hex) {
tmp_buf[n++]= '\\';
tmp_buf[n++]= 'x';
}
tmp_buf[n++]= "0123456789ABCDEF"[(*p1>>4) & 0xF];
tmp_buf[n++]= "0123456789ABCDEF"[*p1 & 0xF];
if (hex) {
tmp_buf[n++]= ' ';
}
}
else tmp_buf[n++]= *p1;
}
if (hex) n--;
else tmp_buf[n++]= '"';
tmp_buf[n]= '\0';
break;
// integer with "power of 2" notation
case USERP_DIAG_ALIGN_ID:
val= diag->align; if (0)
n= snprintf(tmp_buf, sizeof(tmp_buf), "2**%lld", val);
break;
// Generic integer fields
case USERP_DIAG_INDEX_ID:
val= diag->index; if (0)
case USERP_DIAG_POS_ID:
val= diag->pos; if (0)
case USERP_DIAG_POS2_ID:
val= diag->pos2; if (0)
case USERP_DIAG_LEN_ID:
val= diag->len; if (0)
case USERP_DIAG_LEN2_ID:
val= diag->len2; if (0)
case USERP_DIAG_SIZE_ID:
val= diag->size; if (0)
case USERP_DIAG_SIZE2_ID:
val= diag->size2; if (0)
case USERP_DIAG_COUNT_ID:
val= diag->count; if (0)
case USERP_DIAG_COUNT2_ID:
val= diag->count2;
n= snprintf(tmp_buf, sizeof(tmp_buf), "%lld", val);
break;
default:
// If we get here, it's a bug. If the second byte was NUL, back up one, else substitute an error message
if (!pos[-1]) --pos;
from= "(unknown var)";
if (0)
case USERP_DIAG_CSTR1_ID:
from= diag->cstr1; if (0)
case USERP_DIAG_CSTR2_ID:
from= diag->cstr2;
if (!from) from= "(NULL)";
n= strlen(from);
}
}
else {
from= pos;
while (*pos > 1) ++pos;
n= pos-from;
}
if (n) {
if (!from) {
from= "(NULL)";
n= 6;
}
if (buf && str_len+1 < buf_len) // don't call memcpy unless there is room for at least 1 char and NUL
memcpy(buf+str_len, from, (str_len+n+1 <= buf_len)? n : buf_len-1-str_len);
if (fh) {
if (!fwrite(from, 1, n, fh))
return -1 - str_len;
}
str_len += n;
}
}
// at end, NUL-terminate the buffer, if provided and has a length
if (buf && buf_len > 0)
buf[str_len+1 > buf_len? buf_len-1 : str_len]= '\0';
return str_len;
}
void userp_diag_set(userp_diag diag, int code, const char *tpl) {
diag->code= code;
diag->tpl= tpl;
}
void userp_diag_setf(userp_diag diag, int code, const char *tpl, ...) {
const char *from;
size_t skip;
va_list ap;
va_start(ap, tpl);
diag->code= code;
diag->tpl= tpl;
while (*tpl) {
if (*tpl++ == '\x01') {
switch (*tpl++) {
case USERP_DIAG_BUFHEX_ID:
case USERP_DIAG_BUFSTR_ID:
from= va_arg(ap, char*);
diag->pos= va_arg(ap, size_t);
diag->len= va_arg(ap, size_t);
// copy data into buffer, making sure to include 'pos' if the data is
// too large
if (diag->pos > sizeof(diag->buffer)*9/10) {
skip= diag->pos - sizeof(diag->buffer)*9/10;
from += skip;
diag->pos -= skip;
diag->len -= skip;
}
if (diag->len > sizeof(diag->buffer))
diag->len= sizeof(diag->buffer);
memcpy(diag->buffer, from, diag->len);
break;
case USERP_DIAG_ALIGN_ID:
diag->align= va_arg(ap, int);
break;
case USERP_DIAG_INDEX_ID:
diag->index= va_arg(ap, int);
break;
case USERP_DIAG_POS_ID:
diag->pos= va_arg(ap, size_t);
break;
case USERP_DIAG_POS2_ID:
diag->pos2= va_arg(ap, size_t);
break;
case USERP_DIAG_LEN_ID:
diag->len= va_arg(ap, size_t);
break;
case USERP_DIAG_LEN2_ID:
diag->len2= va_arg(ap, size_t);
break;
case USERP_DIAG_SIZE_ID:
diag->size= va_arg(ap, size_t);
break;
case USERP_DIAG_SIZE2_ID:
diag->size2= va_arg(ap, size_t);
break;
case USERP_DIAG_COUNT_ID:
diag->count= va_arg(ap, size_t);
break;
case USERP_DIAG_COUNT2_ID:
diag->count2= va_arg(ap, size_t);
break;
case USERP_DIAG_CSTR1_ID:
diag->cstr1= va_arg(ap, const char *);
break;
case USERP_DIAG_CSTR2_ID:
diag->cstr2= va_arg(ap, const char *);
break;
case USERP_DIAG_PTR_ID:
diag->ptr= va_arg(ap, void *);
break;
default:
fprintf(stderr, "BUG: Unhandled diagnostic variable %d", *tpl);
abort();
}
}
}
va_end(ap);
}
#ifdef UNIT_TEST
UNIT_TEST(diag_simple_string) {
int wrote;
struct userp_diag d;
bzero(&d, sizeof(d));
printf("# simple string\n");
userp_diag_set(&d, 1, "Simple string");
wrote= userp_diag_print(&d, stdout);
printf("\nwrote=%d\n", wrote);
printf("# empty string\n");
userp_diag_set(&d, 1, "");
wrote= userp_diag_print(&d, stdout);
printf("\nwrote=%d\n", wrote);
}
/*OUTPUT
# simple string
Simple string
wrote=13
# empty string
wrote=0
*/
UNIT_TEST(diag_tpl_ref_static_string) {
int wrote;
struct userp_diag d;
bzero(&d, sizeof(d));
printf("# cstr1 in middle\n");
userp_diag_setf(&d, 1, "String ref '" USERP_DIAG_CSTR1 "'", "TEST");
wrote= userp_diag_print(&d, stdout);
printf("\nwrote=%d\n", wrote);
printf("# cstr1 at end\n");
userp_diag_setf(&d, 1, "Ends with " USERP_DIAG_CSTR1, "TEST");
wrote= userp_diag_print(&d, stdout);
printf("\nwrote=%d\n", wrote);
printf("# cstr1 at start\n");
userp_diag_setf(&d, 1, USERP_DIAG_CSTR1 " and things", "TEST");
wrote= userp_diag_print(&d, stdout);
printf("\nwrote=%d\n", wrote);
printf("# cstr1 is entire string\n");
userp_diag_setf(&d, 1, USERP_DIAG_CSTR1, "TEST");
wrote= userp_diag_print(&d, stdout);
printf("\nwrote=%d\n", wrote);
printf("# cstr1 is empty\n");
userp_diag_setf(&d, 1, "'" USERP_DIAG_CSTR1 "'", "");
wrote= userp_diag_print(&d, stdout);
printf("\nwrote=%d\n", wrote);
printf("# cstr1 and cstr2\n");
userp_diag_setf(&d, 1, "String ref '" USERP_DIAG_CSTR2 "', and '" USERP_DIAG_CSTR1 "'", "2", "1");
wrote= userp_diag_print(&d, stdout);
printf("\nwrote=%d\n", wrote);
printf("# empty cstr1 and cstr2\n");
userp_diag_setf(&d, 1, USERP_DIAG_CSTR2 USERP_DIAG_CSTR1, "", "");
wrote= userp_diag_print(&d, stdout);
printf("\nwrote=%d\n", wrote);
}
/*OUTPUT
# cstr1 in middle
String ref 'TEST'
wrote=17
# cstr1 at end
Ends with TEST
wrote=14
# cstr1 at start
TEST and things
wrote=15
# cstr1 is entire string
TEST
wrote=4
# cstr1 is empty
''
wrote=2
# cstr1 and cstr2
String ref '2', and '1'
wrote=23
# empty cstr1 and cstr2
wrote=0
*/
UNIT_TEST(diag_ref_buf_hex) {
int wrote;
struct userp_diag d;
bzero(&d, sizeof(d));
userp_diag_setf(&d, 1, "Some Hex: " USERP_DIAG_BUFHEX,
"\x01\x02\x03\x04", 1, 3);
wrote= userp_diag_print(&d, stdout);
printf("\nwrote=%d\n", wrote);
}
/*OUTPUT
Some Hex: 01 >02 03
wrote=19
*/
UNIT_TEST(diag_ref_bufstr) {
int wrote;
struct userp_diag d;
bzero(&d, sizeof(d));
userp_diag_setf(&d, 1, "String: " USERP_DIAG_BUFSTR,
"test\0\x01\x02", 7, 7);
wrote= userp_diag_print(&d, stdout);
printf("\nwrote=%d\n", wrote);
}
/*OUTPUT
String: "test\\x00\\x01\\x02"
wrote=26
*/
#endif
|
C
|
#include <stdint.h>
#include <stdio.h>
#include "platform.h"
#include "writeUint64AsText.h"
static char * uint64ToBasicText( uint_fast64_t a, char *p )
{
int started;
static const uint_fast64_t largeDecimalDivisors[11] = {
UINT64_C( 10000000000000000000 ),
UINT64_C( 1000000000000000000 ),
UINT64_C( 100000000000000000 ),
UINT64_C( 10000000000000000 ),
UINT64_C( 1000000000000000 ),
UINT64_C( 100000000000000 ),
UINT64_C( 10000000000000 ),
UINT64_C( 1000000000000 ),
UINT64_C( 100000000000 ),
UINT64_C( 10000000000 ),
UINT64_C( 1000000000 )
};
const uint_fast64_t *largeDivisorPtr;
int digitNum;
uint_fast64_t largeDivisor;
int digit;
uint_fast32_t smallA;
static const uint_fast32_t smallDecimalDivisors[8] =
{ 100000000, 10000000, 1000000, 100000, 10000, 1000, 100, 10 };
const uint_fast32_t *smallDivisorPtr;
uint_fast32_t smallDivisor;
started = 0;
if ( 1000000000 <= a ) {
largeDivisorPtr = largeDecimalDivisors;
for ( digitNum = 19; 8 < digitNum; --digitNum ) {
largeDivisor = *largeDivisorPtr;
for ( digit = 0; largeDivisor <= a; ++digit ) a -= largeDivisor;
if ( started || (started = digit) ) *(p++) = '0' + digit;
++largeDivisorPtr;
}
}
smallA = a;
smallDivisorPtr = smallDecimalDivisors;
for ( digitNum = 8; 0 < digitNum; --digitNum ) {
smallDivisor = *smallDivisorPtr;
for ( digit = 0; smallDivisor <= smallA; ++digit ) {
smallA -= smallDivisor;
}
if ( started || (started = digit) ) *(p++) = '0' + digit;
++smallDivisorPtr;
}
*(p++) = '0' + smallA;
return p;
}
void writeUint64AsText( FILE *streamPtr, uint_fast64_t a )
{
char textNumeral[128], *stopPtr;
stopPtr = uint64ToBasicText( a, textNumeral );
fwrite( textNumeral, stopPtr - textNumeral, 1, streamPtr );
}
|
C
|
#include "AsmSem.h"
int sem_create(int* sem, int start_val){
int output;
asm("movl %2, %%eax\n"
"xchgl %%eax, (%1)\n"
"movl %%eax, %0"
: "=r" (output)
: "r" (sem), "r"(start_val)
: "%eax");
return 0;
}
int sem_wait(int* sem){
int output;
asm("1:\n"
"movl $0, %%eax\n"
"xchgl %%eax, (%1)\n"
"testl %%eax, %%eax\n"
"jz 1b\n"
"subl $1, %%eax\n"
"movl %%eax, %0\n"
"xchgl %%eax, (%1)\n"
:"=&r" (output)
:"r" (sem)
:"%eax");
return output;
}
int sem_post(int *sem){
int output;
asm("movl $0, %%eax\n"
"xchgl %%eax, (%1)\n"
"addl $1, %%eax\n"
"xchgl %%eax,(%1)\n"
"addl $1, %%eax\n"
"movl %%eax, %0\n"
:"=r" (output) // no need of & because %eax it's already cloberred!
:"r" (sem)
:"%eax"
);
return output;
}
|
C
|
/*******************************************************************************
* @file ds3231.c
* @author lcc
* @version 1.0
* @date 13-Jun-2019
* @brief 封装 DS3231 时钟模块操作函数
*******************************************************************************/
/* Includes ------------------------------------------------------------------*/
#include <rtdevice.h>
#include "ds3231.h"
#include "i2c_adapter.h"
/* Private typedef -----------------------------------------------------------*/
/* Private macro -------------------------------------------------------------*/
/* Private define ------------------------------------------------------------*/
#define DS3231_I2C_DEVICE "i2c1"
#define DS3231_I2C_ADDRESS 0x68 /* DS3231 的 I2C 地址 */
/* Private variables ---------------------------------------------------------*/
/* Private function prototypes -----------------------------------------------*/
/* Private functions ---------------------------------------------------------*/
static uint8_t BcdToDec(uint8_t val);
static uint8_t DecToBcd(uint8_t val);
static uint8_t ReadControlByte(void);
static void WriteControlByte(uint8_t data);
static uint8_t ReadStatusByte(void);
static void WriteStatusByte(uint8_t data);
/*******************************************************************************
* @brief 初始化 DS3231
* @param None
* @retval None
*******************************************************************************/
void DS3231_Init(void)
{
/* 初始化 I2C 总线 */
rt_base_t ret = I2c_Init(DS3231_I2C_DEVICE);
if (ret != RT_EOK)
{
rt_kprintf("[%d]%s(): i2c init fail\n", __LINE__, __func__);
}
}
/*******************************************************************************
* @brief 获取当前时间, 统一 24 小时制
* @param time - 指向存储当前时间的结构体
* @retval None
*******************************************************************************/
void DS3231_GetTime(DS3231_Time *time)
{
uint8_t buffer[7];
if (time == NULL)
return;
/* 连续读取 7 个字节 */
I2c_Read_nByte(DS3231_I2C_ADDRESS, (uint8_t)0x00, 7, buffer);
time->second = BcdToDec(buffer[0]);
time->minute = BcdToDec(buffer[1]);
/* 处理 12/24 小时制 */
if ((buffer[2] & 0x40) == 0x40) // 12 小时制
{
time->hour = BcdToDec(buffer[2] & 0x1F);
if ((buffer[2] & 0x20) == 0x20) // PM
{
time->hour += 12;
}
}
else
{
time->hour = BcdToDec(buffer[2] & 0x3F);
}
time->day = BcdToDec(buffer[3]);
time->date = BcdToDec(buffer[4]);
time->month = BcdToDec(buffer[5] & 0x7F);
time->year = BcdToDec(buffer[6]);
}
/*******************************************************************************
* @brief 获取当前时钟读数(时, 分, 秒)
* @param time - 指向存储当前时钟读数的结构体
* @retval None
*******************************************************************************/
void DS3231_GetClock(DS3231_Clock *clock)
{
uint8_t buffer[3];
if (clock == NULL)
return;
/* 连续读取存储日期的 3 个字节 */
I2c_Read_nByte(DS3231_I2C_ADDRESS, (uint8_t)0x00, 3, buffer);
clock->second = BcdToDec(buffer[0]);
clock->minute = BcdToDec(buffer[1]);
clock->hour = BcdToDec(buffer[2]);
}
/*******************************************************************************
* @brief 获取当前日期
* @param time - 指向存储当前日期的结构体
* @retval None
*******************************************************************************/
void DS3231_GetDate(DS3231_Date *date)
{
uint8_t buffer[4];
if (date == NULL)
return;
/* 连续读取存储日期的 4 个字节 */
I2c_Read_nByte(DS3231_I2C_ADDRESS, (uint8_t)0x03, 4, buffer);
date->day = BcdToDec(buffer[0]);
date->date = BcdToDec(buffer[1]);
date->month = BcdToDec(buffer[2]);
date->year = BcdToDec(buffer[3]);
}
/*******************************************************************************
* @brief 设置 DS3231 所有计时寄存器
* @param time - 指向要设置的时间的指针
* @retval None
*******************************************************************************/
void DS3231_SetTime(DS3231_Time *time)
{
uint8_t buffer[7];
if (time == NULL)
return;
buffer[0] = DecToBcd(time->second);
buffer[1] = DecToBcd(time->minute);
buffer[2] = DecToBcd(time->hour);
buffer[3] = DecToBcd(time->day);
buffer[4] = DecToBcd(time->date);
buffer[5] = DecToBcd(time->month);
buffer[6] = DecToBcd(time->year);
/* 连续写入 7 个字节 */
I2c_Write_nByte(DS3231_I2C_ADDRESS, 0x00, 7, buffer);
}
/*******************************************************************************
* @brief 设置时, 分, 秒寄存器
* @param clock - 指向要设置的时间的指针
* @retval None
*******************************************************************************/
void DS3231_SetClock(DS3231_Clock *clock)
{
uint8_t buffer[3];
if (clock == NULL)
return;
buffer[0] = DecToBcd(clock->second);
buffer[1] = DecToBcd(clock->minute);
buffer[2] = DecToBcd(clock->hour);
/* 连续写入 3 个字节 */
int ret = I2c_Write_nByte(DS3231_I2C_ADDRESS, 0x00, 3, buffer);
rt_kprintf("DS3231_SetClock: ret = %d\n", ret);
}
/*******************************************************************************
* @brief 设置日期寄存器
* @param date - 指向要设置的日期的指针
* @retval None
*******************************************************************************/
void DS3231_SetDate(DS3231_Date *date)
{
uint8_t buffer[4];
if (date == NULL)
return;
buffer[0] = DecToBcd(date->day);
buffer[1] = DecToBcd(date->date);
buffer[2] = DecToBcd(date->month);
buffer[3] = DecToBcd(date->year);
/* 连续写入 4 个字节 */
I2c_Write_nByte(DS3231_I2C_ADDRESS, 0x03, 4, buffer);
}
/*******************************************************************************
* @brief 设置闹钟 1, 可设置到 秒
* @param mask 闹钟模式
* @param time 要设置的时间
* @retval None
*******************************************************************************/
void DS3231_SetAlarm1(uint8_t mask, DS3231_Time *time)
{
/* 闹钟 1 有连续 4 个寄存器, buffer[0] 存放起始地址 */
uint8_t buffer[4];
if (time == NULL)
return;
buffer[0] = DecToBcd(time->second) | ((mask & 0x01) << 7);
buffer[1] = DecToBcd(time->minute) | ((mask & 0x02) << 6);
buffer[2] = DecToBcd(time->hour) | ((mask & 0x04) << 5);
/* 按星期重复 or 日期重复 */
if ((mask & 0x10) == 0x10)
{
buffer[3] = DecToBcd(time->day) | ((mask & 0x08) << 4);
buffer[3] |= 0x40;
}
else
{
buffer[3] = DecToBcd(time->date) | ((mask & 0x08) << 4);
}
I2c_Write_nByte(DS3231_I2C_ADDRESS, 0x07, 4, buffer);
}
/*******************************************************************************
* @brief 设置闹钟 2, 可设置到 分
* @param mask 闹钟屏蔽位
* @param time 要设置的时间
* @retval None
*******************************************************************************/
void DS3231_SetAlarm2(uint8_t mask, DS3231_Time *time)
{
/* 闹钟 2 有连续 3 个寄存器, buffer[0] 存放起始地址 */
uint8_t buffer[3];
if (time == NULL)
return;
buffer[0] = DecToBcd(time->minute) | ((mask & 0x01) << 7);
buffer[1] = DecToBcd(time->hour) | ((mask & 0x02) << 6);
/* 按星期重复 or 日期重复 */
if ((mask & 0x08) == 0x08)
{
buffer[2] = DecToBcd(time->day) | ((mask & 0x04) << 5);
buffer[2] |= 0x40;
}
else
{
buffer[2] = DecToBcd(time->date) | ((mask & 0x04) << 5);
}
I2c_Write_nByte(DS3231_I2C_ADDRESS, 0x0B, 3, buffer);
}
/*******************************************************************************
* @brief 使能闹钟中断
* @param alarm 闹钟 1 or 2, 缺省为 2
* @retval None
*******************************************************************************/
void DS3231_EnableAlarmIT(uint8_t alarm)
{
uint8_t temp = ReadControlByte();
if (alarm == 1)
temp |= 0x05;
else
temp |= 0x06;
WriteControlByte(temp);
}
/*******************************************************************************
* @brief 关闭闹钟中断
* @param alarm 闹钟 1 or 2, 缺省为 2
* @retval None
*******************************************************************************/
void DS3231_DisableAlarmIT(uint8_t alarm)
{
uint8_t temp = ReadControlByte();
if (alarm == 1)
temp &= 0xFE;
else
temp &= 0xFD;
WriteControlByte(temp);
}
/*******************************************************************************
* @brief 检查指定闹钟中断是否使能
* @param alarm 指定闹钟 1 or 2, 缺省为 2
* @retval RT_TRUE 开启, RT_FALSE 未开启
*******************************************************************************/
rt_bool_t DS3231_CheckAlarmITEnabled(uint8_t alarm)
{
uint8_t result = RT_FALSE;
uint8_t temp = ReadControlByte();
if (!(temp & 0x04))
return RT_FALSE;
if (alarm == 1)
result = temp & 0x01;
else
result = temp & 0x02;
return !!result;
}
/*******************************************************************************
* @brief 检查闹钟是否响
* @param alarm 指定闹钟 1 or 2, 缺省为 2
* @retval RT_TRUE 响, RT_FALSE 未响
*******************************************************************************/
rt_bool_t DS3231_CheckIfAlarm(uint8_t alarm)
{
uint8_t result = RT_FALSE;
uint8_t temp = ReadStatusByte();
/* 判断哪个闹钟响 */
if (alarm == 1)
{
result = temp & 0x01;
temp &= 0xFE;
}
else
{
result = temp & 0x02;
temp &= 0xFD;
}
/* 清除闹钟标志 */
WriteStatusByte(temp);
return !!result;
}
/*--------------------------------- 内部函数 ---------------------------------*/
// 控制寄存器 0x0E
uint8_t ReadControlByte(void)
{
uint8_t val;
I2c_Read_1Byte(DS3231_I2C_ADDRESS, 0x0E, &val);
return val;
}
void WriteControlByte(uint8_t data)
{
I2c_Write_1Byte(DS3231_I2C_ADDRESS, 0x0E, data);
}
// 状态寄存器 0x0F
uint8_t ReadStatusByte(void)
{
uint8_t val;
I2c_Read_1Byte(DS3231_I2C_ADDRESS, 0x0F, &val);
return val;
}
void WriteStatusByte(uint8_t data)
{
I2c_Write_1Byte(DS3231_I2C_ADDRESS, 0x0F, data);
}
// 二十进制转换
uint8_t BcdToDec(uint8_t val)
{
return (val >> 4) * 10 + (val & 0x0F);
}
uint8_t DecToBcd(uint8_t val)
{
return ((val / 10) << 4) + val % 10;
}
|
C
|
#include "func_2d.h"
#include "mersenne_twister.h"
#include <math.h>
#include <stdio.h>
int main(void)
{
const int seed = 12345;
double x[2] = { -15.0, 3.0 };
const double dx = 0.1;
const int n = 10000;
const double tinit = 10;
const double tfinal = 0.01;
/* set seed of Mersenne-Twister pseudo random number generator */
init_genrand(seed);
double diff = sqrt((x[0] - minx) * (x[0] - minx) + (x[1] - miny) * (x[1] - miny));
printf("%d %lf %lf %lf %20.12lf %20.12lf\n", 0, 0.0, x[0], x[1], f(x), diff);
for (int i = 1; i < n; ++i)
{
const double t = tinit + i * (tfinal - tinit) / n;
const double xnew[2] = {
x[0] + 2 * dx * (genrand_real3() - 0.5),
x[1] + 2 * dx * (genrand_real3() - 0.5)
};
if (genrand_real3() < exp(-(f(xnew) - f(x)) / t))
{
x[0] = xnew[0];
x[1] = xnew[1];
}
diff = sqrt((x[0] - minx) * (x[0] - minx) + (x[1] - miny) * (x[1] - miny));
printf("%d %lf %lf %lf %20.12lf %20.12lf\n", i, t, x[0], x[1], f(x), diff);
}
return 0;
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_drawcolle.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: tcarlena <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2020/03/15 16:19:14 by tcarlena #+# #+# */
/* Updated: 2020/03/15 16:51:04 by tcarlena ### ########.fr */
/* */
/* ************************************************************************** */
#include "ft_colle.h"
char *ft_drawcolle(int n, char a, char b, char c)
{
int i;
int j;
char *str;
i = 0;
j = 0;
if (!(str = malloc(sizeof(char) * n + 2)))
return (0);
str[j++] = a;
if (n > 2)
while (i++ < n - 2)
str[j++] = b;
if (n > 1)
str[j++] = c;
str[j++] = '\n';
str[j] = '\0';
return (str);
}
char *rush(int x, int y, char *tab)
{
int i;
char *top;
char *middle;
char *bottom;
i = 0;
if (!(top = malloc(sizeof(char) * (y + 1))))
return (0);
if (!(middle = malloc(sizeof(char) * (x + 1) * (y + 1))))
return (0);
if (!(bottom = malloc(sizeof(char) * (y + 1))))
return (0);
if (x > 0)
{
if (y > 0)
top = ft_drawcolle(x, tab[0], tab[1], tab[2]);
if (y > 2)
middle = ft_drawcolle(x, tab[3], ' ', tab[3]);
if (y > 1)
bottom = ft_drawcolle(x, tab[4], tab[1], tab[5]);
}
return (ft_combine(top, middle, bottom, y));
}
char *ft_combine(char *top, char *middle, char *bottom, int row)
{
int len;
char *str;
int pos;
int y;
pos = 0;
len = ft_strlen(top);
if (!(str = malloc(sizeof(char) * row * len + 1)))
return (0);
while (*top)
str[pos++] = *top++;
while (row > 2)
{
y = 0;
while (middle[y])
str[pos++] = middle[y++];
row--;
}
while (*bottom)
str[pos++] = *bottom++;
str[pos] = '\0';
return (str);
}
|
C
|
//Author: Michael Harrison
//Lab 4: Filesystem Structures
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <math.h>
//Size of...
#define FS_SIZE 0xa00000 //10MB filesystem
#define B_SIZE 512 //block size in bytes
#define MF_SIZE 16384 //max file size in bytes
#define NUM_INODES 512 //number of inodes allocated during mounting
#define NUM_DIRECT_BLOCKS 14
//Flag Definitions
#define MFILE 0x00 //0000 0000
#define DIRECTORY 0x01 //0000 0001
#define READ 0x02 //0000 0010
#define WRITE 0x04 //0000 0100
#define EXECUTE 0x08 //0000 1000
#define APPEND 0x10 //0001 0000
#define DELETE 0x20 //0010 0000
#define DIRTY 0x40 //0100 0000
#define IN_USE 0x80 //1000 0000
#ifndef HEADER
#define HEADER
struct open_file{
char name[32];
unsigned long dir_num;
unsigned long node_num;
unsigned int count;
unsigned int access_rights;
};
struct block{
unsigned int block;
};
struct fBlock{
struct block prev;
struct block next;
};
struct address_space{
struct block direct[NUM_DIRECT_BLOCKS];
struct block indirect;
struct block double_indirect;
};
/*
.(current directory)
..(parent directory)
*/
struct directory{
unsigned long i_no; //inode number
char d_id[32]; //file name
};
struct inode{
unsigned long i_num; //inode number
unsigned int uid, gid; //user id and group id for permission
unsigned long i_size; //size of file in bytes
unsigned int i_flags; //Flags described above
time_t creation; //creation date
time_t modified; //modified date
struct address_space i_data; //physical mapping
struct directory parent_dir;
};
struct superblock{
char s_id[32]; //name of filesystem
unsigned long s_block; //size of blocks
unsigned long s_inode; //size of inode
unsigned long s_maxbytes; //max file size in bytes
unsigned int s_free; //number of free blocks
unsigned int s_used; //number of used blocks
unsigned int s_flags; //Flags described above
unsigned int s_first; //first free block
};
#endif
//API Functions
void next_free(void);
void create_fs(char *name);
void mount_fs(char *name);
void sync_fs(void);
void create(char *filename, char type);
void destroy(char *filename);
void write(char *filename, char *message);
void read(char *filename);
void open(char *filename);
void close(char *filename);
|
C
|
/* problem: 10115 - Automatic Editing */
#include <stdio.h>
#include <string.h>
#define Local 0
#define Len1 100
#define Len2 300
int testCases;
char a[10][Len1];
char b[10][Len1];
char c1[Len2],c2[Len2];
void process(char *a, char *b){
char *p = c1;
char *q = NULL;
#if Local
printf("a:%s - b:%s\n",a,b);
#endif
while((q=strstr(p,a))!=NULL){
int len = q - p;
memset(c2,0,sizeof(c2));
strncpy(c2,c1,len);
strncpy(c2+len,b,strlen(b));
strcpy(c2+len+strlen(b),q+strlen(a));
strcpy(c1,c2);
c1[strlen(c2)]='\0';
p = c1;
#if Local
printf("c1:%s\n",c1);
#endif
}
}
int main(){
FILE *fpin, *fpout;
int i;
#if Local
fpin = fopen("autoedit.in","r");
fpout = fopen("autoedit.out","w");
#endif
while(scanf("%d\n",&testCases)!=EOF&&testCases!=0){
memset(a,0,sizeof(a));
memset(b,0,sizeof(b));
memset(c1,0,sizeof(c1));
memset(c2,0,sizeof(c2));
for(i=0;i<testCases;i++){
gets(a[i]);
gets(b[i]);
a[i][strlen(a[i])]='\0';
b[i][strlen(b[i])]='\0';
}
#if 0
for(i=0;i<testCases;i++){
fprintf(stdout,"%s\n",a[i]);
fprintf(stdout,"%s\n",b[i]);
}
#endif
gets(c1);
c1[strlen(c1)] = '\0';
for(i=0;i<testCases;i++){
process(a[i],b[i]);
}
printf("%s\n",c1);
}
return 0;
}
|
C
|
#include<stdio.h>
int pw(int b,int e){
if(e==0)
return 1;
return b*pw(b,e-1);
}
int main()
{
int b,e,p;
scanf("%d",&b);
scanf("%d",&e);
printf("%d",pw(b,e));
return 0;
}
|
C
|
/*
* "Write a program that asks the user to enter a value for x and then
* displays the value of the following polynomial: 3x^5+2x^4-5x^3-x^2+7x-6"
*/
#include <stdio.h>
// This function only handles positive powers. But, since it is only used
// with positive powers, it is sufficient.
int intpow(int base, int exponent) {
int ret = 1;
int iterator;
for (iterator = 0; iterator < exponent; iterator++) {
ret *= base;
}
return ret;
}
int main() {
printf("Please enter your x value: ");
int x;
scanf("%d", &x);
int answer = (3 * intpow(x, 5)) + (2 * intpow(x, 4)) - (5 * intpow(x, 3))
- intpow(x, 3) + (7 * x) - 6;
printf("\nAnswer: %d\n", answer);
return 0;
}
|
C
|
#define e 2.71828
double Exp(int x)
{ double sum=1;
int i=0;
for(i=0;i<x;i++)
sum*=e;
return sum;
}
double Pow(double x,int y)
{
double sum=1;
int i=0;
for(i=0;i<y;i++)
sum*=x;
return sum;
}
|
C
|
#include "test_runner.h"
unsigned short int swap_bytes(unsigned short i)
{
return i << 8 | i >> 8;
}
int swap_bytes_test(void)
{
_assert(swap_bytes(0x1234) == 0x3412);
_assert(swap_bytes(0xFF00) == 0x00FF);
return 0;
}
int all_tests(void)
{
_run(swap_bytes_test);
return 0;
}
|
C
|
//#include <stdio.h>
//
//int main()
//{
// int year;
// printf("请输入一个年份:");
// scanf("%d", &year);
//
// if (year % 400 == 0 || (year % 4 == 0 && year % 100 != 0)) {
// printf("闰年\n");
// } else {
// printf("平年\n");
// }
//
// //从键盘输入一个年份和月份值 输出该年该月的天数
// int year1;
// int month;
// printf("请输入一个年份:");
// scanf("%d", &year1);
// printf("请输入一个月份:");
// scanf("%d", &month);
//
// int days = 31;
// if (month == 4 || month == 6 || month == 9 || month ==11) {
// days = 30;
// } else if (month == 2) {
// days = 28 + (year1 % 400 == 0 || (year1 % 4 == 0 && year1 % 100 != 0));
// }
// printf("%d年%d月有%d天\n", year1, month, days);
//
// return 0;
//}
|
C
|
int main()
{
int s,x,i,j,n,a1,a2,b1,b2;
a1=0;a2=0;b1=0;b2=0;
scanf("%d",&n);
for (i=1;i<(n+1);i++)
{
for (j=1;j<(n+1);j++)
{
scanf("%d",&x);
if ((x==0) && (a1==0)) {a1=i;a2=j;}
if (x==0) {b1=i;b2=j;}
}
}
s=(b1-a1-1)*(b2-a2-1);
printf("%d\n",s);
return 0;
}
|
C
|
#include "Vec.h"
#include <iostream>
#include <iomanip>
#include <cmath>
using namespace std;
Vec::Vec(int n, double val) : N(n), entries(new double[n])
{
for (int i = 0; i < n; ++i)
entries[i] = val;
#ifdef DEBUG
cout << __PRETTY_FUNCTION__ << endl;
#endif
}
Vec::Vec(int n, double* pval) : N(n), entries(new double[n])
{
for (int i = 0; i < n; ++i)
entries[i] = pval[i];
#ifdef DEBUG
cout << __PRETTY_FUNCTION__ << endl;
#endif
}
Vec::Vec(const vector<double>& vect) : N((int)vect.size()), entries(new double[vect.size()])
{
for (int i = 0; i < vect.size(); ++i)
entries[i] = vect[i];
#ifdef DEBUG
cout << __PRETTY_FUNCTION__ << endl;
#endif
}
Vec::Vec(const Vec& vec) : N(vec.N), entries(new double[vec.N])
{
for (int i = 0; i < vec.N; ++i)
entries[i] = vec.entries[i];
#ifdef DEBUG
cout << __PRETTY_FUNCTION__ << endl;
#endif
}
Vec::Vec(Vec&& vec) : N(vec.N), entries(new double[vec.N])
{
entries = vec.entries;
vec.N = 0;
vec.entries = nullptr;
#ifdef DEBUG
cout << __PRETTY_FUNCTION__ << endl;
#endif
}
Vec::~Vec()
{
if (entries) delete [] entries;
#ifdef DEBUG
cout << __PRETTY_FUNCTION__ << endl;
#endif
}
//=============== assignments ===============
const Vec& Vec::operator= (const Vec& vec)
{
N = vec.N;
if (entries) delete[] entries;
entries = new double[vec.N];
for (int i = 0; i < N; ++i)
entries[i] = vec.entries[i];
#ifdef DEBUG
cout << __PRETTY_FUNCTION__ << endl;
#endif
return *this;
}
Vec& Vec::operator= (Vec&& vec)
{
N = vec.N;
if (entries) delete[] entries;
entries = vec.entries;
vec.N = 0;
vec.entries = nullptr;
#ifdef DEBUG
cout << __PRETTY_FUNCTION__ << endl;
#endif
return *this;
}
//=============== set Vec entries ===============
void Vec::SetEntries (int n, double* arr)
{
if (entries) delete [] entries;
N = n;
entries = new double[n];
for (int i = 0; i < n; ++i)
entries[i] = arr[i];
#ifdef DEBUG
cout << __PRETTY_FUNCTION__ << endl;
#endif
}
//=============== operators [] ===============
double& Vec::operator[] (int i)
{
#ifdef DEBUG
cout << __PRETTY_FUNCTION__ << endl;
#endif
return entries[i];
}
const double& Vec::operator[] (int i) const
{
#ifdef DEBUG
cout << __PRETTY_FUNCTION__ << endl;
#endif
return entries[i];
}
//=============== binary operators ===============
Vec Vec::operator+ (const Vec& vec) const
{
Vec a(*this);
a += vec;
#ifdef DEBUG
cout << __PRETTY_FUNCTION__ << endl;
#endif
return a;
}
Vec Vec::operator- (const Vec& vec) const
{
Vec a(*this);
a -= vec;
#ifdef DEBUG
cout << __PRETTY_FUNCTION__ << endl;
#endif
return a;
}
Vec Vec::operator* (const Vec& vec) const
{
Vec a(*this);
a *= vec;
#ifdef DEBUG
cout << __PRETTY_FUNCTION__ << endl;
#endif
return a;
}
Vec Vec::operator* (double cc) const
{
Vec ret(N);
for (int i = 0; i < N; ++i)
ret[i] = entries[i] * cc;
#ifdef DEBUG
cout << __PRETTY_FUNCTION__ << endl;
#endif
return ret;
}
Vec Vec::operator/ (const Vec& vec) const
{
Vec a(*this);
a /= vec;
#ifdef DEBUG
cout << __PRETTY_FUNCTION__ << endl;
#endif
return a;
}
Vec Vec::operator/ (double cc) const
{
Vec ret(N);
if(cc != 0.)
{
for (int i = 0; i < N; ++i)
ret[i] = entries[i] / cc;
}
else
{
cout << "Error! Cannot divide by zero." << endl;
exit(1);
}
#ifdef DEBUG
cout << __PRETTY_FUNCTION__ << endl;
#endif
return ret;
}
// Friend Function
Vec operator* (double cc, const Vec& vec)
{
Vec ret(vec.size());
for (int i = 0; i < vec.size(); ++i)
ret[i] = vec[i] * cc;
#ifdef DEBUG
cout << __PRETTY_FUNCTION__ << endl;
#endif
return ret;
}
//=============== unary operators ===============
void Vec::operator+= (const Vec& vec)
{
if(N < vec.size())
{
double copy[vec.size()] = {0.};
for (int i = 0; i < N; ++i)
copy[i] = entries[i];
delete [] entries;
entries = new double[vec.size()];
N = vec.size();
for (int i = 0; i < vec.size(); ++i)
entries[i] = copy[i] + vec[i];
}
else
{
for (int i = 0; i < vec.size(); ++i)
entries[i] += vec[i];
}
#ifdef DEBUG
cout << __PRETTY_FUNCTION__ << endl;
#endif
}
void Vec::operator-= (const Vec& vec)
{
if(N < vec.size())
{
double copy[vec.size()] = {0.};
for (int i = 0; i < N; ++i)
copy[i] = entries[i];
delete [] entries;
entries = new double[vec.size()];
N = vec.size();
for (int i = 0; i < vec.size(); ++i)
entries[i] = copy[i] - vec[i];
}
else
{
for (int i = 0; i < vec.size(); ++i)
entries[i] -= vec[i];
}
#ifdef DEBUG
cout << __PRETTY_FUNCTION__ << endl;
#endif
}
void Vec::operator*= (const Vec& vec)
{
if(N < vec.size())
{
double copy[vec.size()] = {0.};
for (int i = 0; i < N; ++i)
copy[i] = entries[i];
delete [] entries;
entries = new double[vec.size()];
int N_old = N;
N = vec.size();
for (int i = 0; i < N_old; ++i)
entries[i] = copy[i] * vec[i];
}
else
{
for (int i = 0; i < vec.size(); ++i)
entries[i] *= vec[i];
}
#ifdef DEBUG
cout << __PRETTY_FUNCTION__ << endl;
#endif
}
void Vec::operator*= (double cc)
{
for (int i = 0; i < N; ++i)
entries[i] *= cc;
#ifdef DEBUG
cout << __PRETTY_FUNCTION__ << endl;
#endif
}
void Vec::operator/= (const Vec& vec)
{
for (int i = 0; i < vec.size(); ++i)
{
if (vec[i] == 0.)
{
cout << "Error! Cannot divide these 2 Vecs. Element v[" << i << "] is zero." << endl;
exit(1);
}
}
if(N < vec.size())
{
double copy[vec.size()] = {0.};
for (int i = 0; i < N; ++i)
copy[i] = entries[i];
delete [] entries;
entries = new double[vec.size()];
int N_old = N;
N = vec.size();
for (int i = 0; i < N_old; ++i)
entries[i] = copy[i] / vec[i];
}
else
{
for (int i = 0; i < vec.size(); ++i)
entries[i] /= vec[i];
}
#ifdef DEBUG
cout << __PRETTY_FUNCTION__ << endl;
#endif
}
void Vec::operator/= (double cc)
{
if(cc != 0.)
{
for (int i = 0; i < N; ++i)
entries[i] /= cc;
}
else
{
cout << "Error! Cannot divide by zero." << endl;
exit(1);
}
#ifdef DEBUG
cout << __PRETTY_FUNCTION__ << endl;
#endif
}
Vec Vec::operator-() const
{
Vec ret(N);
for (int i = 0; i < N; ++i)
ret[i] = -entries[i];
#ifdef DEBUG
cout << __PRETTY_FUNCTION__ << endl;
#endif
return ret;
}
double Vec::operator! () const
{
return sqrt(this->dot(*this));
}
//=============== others ===============
double Vec::dot (const Vec& vec) const
{
double res = 0.;
for (int i = 0; i < vec.size() && i < N; ++i)
res += entries[i] * vec[i];
#ifdef DEBUG
cout << __PRETTY_FUNCTION__ << endl;
#endif
return res;
}
void Vec::swap(int a, int b)
{
if(a < N && a >= 0 && b < N && b >= 0){
double C = entries[a];
entries[a] = entries[b];
entries[b] = C;
}
else {
cout << "Error! Indexes do not belong to this Vec." << endl;
exit(1);
}
#ifdef DEBUG
cout << __PRETTY_FUNCTION__ << endl;
#endif
}
unsigned int Vec::size() const
{
#ifdef DEBUG
cout << __PRETTY_FUNCTION__ << endl;
#endif
return (unsigned int)N;
}
//=============== Print ===============
void Vec::Print(short int p, short int w) const
{
streamsize pp = cout.precision();
streamsize ww = cout.width();
if (p != 0){
if (w == 0)
w = p + 1;
cout.precision(p);
}
for (int i = 0; i < N; ++i)
cout << setw(w) << entries[i] << "\t";
cout << endl;
if (p != 0 || w != 0){
cout.precision(pp);
cout << setw(ww);
}
#ifdef DEBUG
cout << __PRETTY_FUNCTION__ << endl;
#endif
}
|
C
|
/*
* Hash table operations
* This hash table is an implementation of the Map ADT
* (The distinction between a Map and a Dictionary is that the keys
* in a Map form a Set - are unique, while in a Dictionary form
* a Collection - the same key can appear multiple times)
* There are additional methods to:
* add a large collection of objects to the hash table
* clear the hash table
*
*/
#ifndef _HASH_TABLE_H_
#define _HASH_TABLE_H_
#include "../bds/bucket_array.h"
typedef ulong (*hash_code_func_t)(key_t key);
typedef uint (*compress_func_t)(ulong code);
typedef struct {
hash_code_func_t hash;
compress_func_t compress;
} hash_func_t;
typedef struct {
struct bucket_array *buckets;
hash_func_t *func;
} hash_tbl_t;
/* Returns a newly initialized hash table using FNV-1 and MAD */
hash_tbl_t* ht_init();
/* Returns a newly initialized hash table, using hash_it as hash function */
hash_tbl_t* ht_init_func(hash_func_t hash_it);
/* Frees the memory allocated for a hash table initialized with ht_init() */
void ht_delete(hash_tbl_t *h);
/* Returns the number of elements stored in the hash table */
size_t ht_size(hash_tbl_t *h);
/* Returns 0 if hash table has elements, 1 otherwise */
char ht_isEmpty(hash_tbl_t *h);
/* Removes all entries in the hash table */
void ht_clear(hash_tbl_t *h);
/* Returns the value stored for key qKey */
int ht_get(hash_tbl_t *h, key_t qKey);
/* If nValue is not present, add it,
* otherwise replace the existing value with this new one */
void ht_put(hash_tbl_t *h, key_t nKey, int nValue);
/* Adds a large number of entries at once in the hash table
* Faster than calling ht_put for each entry */
void ht_multiple_put(hash_tbl_t *h, struct generic_data *entrySet, size_t *len);
/* Remove and return the value with key qKey; if there is no such key, return NULL */
int ht_remove(hash_tbl_t *h, key_t qKey);
/* Returns in keySet a set of all keys stored in the hash table */
void ht_keySet(hash_tbl_t *h, key_t *keySet, size_t *len);
/* Returns in values a collection of all values stored in the hash table */
void ht_values(hash_tbl_t *h, int *values, size_t *len);
/* Returns in entrySet a collection containing all the key-value entries in the hash table
* Entries can be sorted using a comp_func_t function */
void ht_entrySet(hash_tbl_t *h, struct generic_data *entrySet, size_t *len);
/* Below are provided some hash functions and compression methods */
/* The hash code returned is the memory location of the key of the data entry
* This could change if there is a garbage collector (if possible, rehash after
* calling the gc)
* Also, for similar strings, this function will generate different results */
uint32_t hash_code_mem_loc(key_t *key) {
return (uint32_t)key;
}
/* FNV-1 32 bit hashing algorithm
* Very fast */
uint64_t hash_code_fnv1(key_t key) {
uint32_t fnv_prime = 16777619, offset_basis = 2166136261;
uint64_t hash_code = offset_basis;
int i;
for(i=0;i<key.len;i++) {
hash_code *= fnv_prime;
hash_code ^= key.name[i];
}
return hash_code;
}
/* MAD compression function */
uint32_t compress_mad(uint64_t code, uint32_t ba_size) {
uint64_t p = 2305843009213693951;
return ((101*code+41)%p)%ba_size;
}
#endif
|
C
|
#include <stdio.h>
int main()
{
int t1=0,t2=1,next;
int n,i;
scanf("%d",&n);
next=t1+t2;
printf("The Fibonacci Series %d %d", t1, t2);
for(i=3;i<=n;i++)
{
printf(" %d",next);
t1=t2;
t2=next;
next=t1+t2;
}
return 0;
}
|
C
|
// Temp.c
// 1. Include section
#include "Temp.h"
// 2. Variable declaration section
uint32_t ui32_ADC0_vector; // Sample buffer (size = number of samples)
static float f_TempCelsius; // Temperature variable
static uint32_t ui32_temp_intpart; // Integer part of temperature
static uint32_t ui32_temp_decpart; // Decimal part of temperature
// 3. Function declaration section
// 3.1. Configure the ADC0 peripheral
void ConfigLib_Temp_ADC0Set(void)
{
SysCtlPeripheralEnable(SYSCTL_PERIPH_ADC0); // Enable ADC0 peripheral
SysCtlDelay(ADC_INITDELAY_CYCLES); // 300 cycle delay to stabilize peripheral before further configuration
// Select sequencer 3 (1 sample, FIFO = 1), ADC sequence triggered by the processor, highest priority
ADCSequenceConfigure(ADC0_BASE, ADC_SEQUENCE, ADC_TRIGGER_PROCESSOR, ADC_STEP);
// Sample the temperature sensor, set the interrupt flag only when the sampling is done and
// set this step as the last conversion step to the ADC0 sequencer
ADCSequenceStepConfigure(ADC0_BASE, ADC_SEQUENCE, ADC_STEP, (ADC_CTL_TS | ADC_CTL_IE | ADC_CTL_END));
// Enable ADC0 sequencer
ADCSequenceEnable(ADC0_BASE, ADC_SEQUENCE);
// Clear the interrupt status flag before we sample
ADCIntClear(ADC0_BASE, ADC_SEQUENCE);
}
// 3.2. Activate ADC0 to measure temperature sample
void ConfigLib_Temp_Measure(void)
{
ADCSequenceEnable(ADC0_BASE, ADC_SEQUENCE);
// Clear ADC interrupt flag
ADCIntClear(ADC0_BASE, ADC_SEQUENCE);
// Enable ADC acquisition
ADCProcessorTrigger(ADC0_BASE, ADC_SEQUENCE);
// While interrupt flag is not clear, wait
while(!ADCIntStatus(ADC0_BASE, ADC_SEQUENCE, false))
{
}
// Put measured value in the sample buffer
ADCSequenceDataGet(ADC0_BASE, ADC_SEQUENCE, &ui32_ADC0_vector);
// Convert binary to float value
f_TempCelsius = (1475 - ((2475 * ui32_ADC0_vector)) / 4096)/10;
// Split integer and decimal parts from float value
ui32_temp_intpart = (uint32_t) f_TempCelsius;
ui32_temp_decpart = (uint32_t)(f_TempCelsius * 10) - ui32_temp_intpart;
// Disable ADC0 sequencer
ADCSequenceDisable(ADC0_BASE, ADC_SEQUENCE);
}
// 3.3. Return integer part of temperature
uint32_t ui32_TempCelsius_IntegerPart_Read(void)
{
return(ui32_temp_intpart);
}
// 3.4. Return decimal part of temperature
uint32_t ui32_TempCelsius_DecimalPart_Read(void)
{
return(ui32_temp_decpart);
}
|
C
|
#include "stack.h"
struct stack{
element_type *a;
size_t capacity;
position base;
position top;
};
stack make_stack(size_t size)
{
stack p = (stack) malloc (sizeof(struct stack));
if(p == NULL)
return (stack) p;
element_type* tmp = (element_type*) malloc (size * sizeof(element_type));
if(tmp == NULL)
return (stack) p;
p->a = tmp;
p->capacity = size;
p->base = 0;
p->top = -1;
return p;
}
element_type pop(stack s)
{
if(!is_empty(s))
return s->a[s->top--];
return STACK_MAX;
}
void push(element_type item,stack s)
{
if(!is_full(s))
s->a[++s->top] = item;
else printf("stack is full\n");
}
status is_empty(stack s)
{
return s->top == -1;
}
status is_full(stack s)
{
return s->top == (position) s->capacity - 1;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
//find the smallest multiple
//The lowest common multiple
int gcd(int m , int n) {
int t;
while(n != 0){
t = n;
n = m % n;
m = t;
}
return m;
}
int main(int argc, char** argv) {
int n;
if(argc == 1) n = 20;
else n = atoi(argv[1]);
long long ans = 1;
for(int i = 1; i <= n; i++){
ans = (ans * i) / gcd(ans, i);
}
printf("The smallest multiple is %lld\n", ans);
return 0;
}
|
C
|
/* libppm1.c - ppm utility library part 1
**
** Copyright (C) 1989 by Jef Poskanzer.
**
** Permission to use, copy, modify, and distribute this software and its
** documentation for any purpose and without fee is hereby granted, provided
** that the above copyright notice appear in all copies and that both that
** copyright notice and this permission notice appear in supporting
** documentation. This software is provided "as is" without express or
** implied warranty.
*/
/* See pmfileio.c for the complicated explanation of this 32/64 bit file
offset stuff.
*/
#define _FILE_OFFSET_BITS 64
#define _LARGE_FILES
#include <string.h>
#include <stdio.h>
#include <errno.h>
#include "netpbm/mallocvar.h"
#include "nstring.h"
#include "ppm.h"
#include "libppm.h"
#include "pgm.h"
#include "libpgm.h"
#include "pbm.h"
#include "libpbm.h"
#include "pam.h"
#include "libpam.h"
#include "fileio.h"
pixel *
ppm_allocrow(unsigned int const cols) {
pixel * pixelrow;
MALLOCARRAY(pixelrow, cols);
if (pixelrow == 0)
pm_error("Unable to allocate space for a %u-column pixel row", cols);
return pixelrow;
}
void
ppm_init(int * const argcP, char ** const argv) {
pgm_init( argcP, argv );
}
void
ppm_nextimage(FILE * const fileP,
int * const eofP) {
pm_nextimage(fileP, eofP);
}
void
ppm_readppminitrest(FILE * const fileP,
int * const colsP,
int * const rowsP,
pixval * const maxvalP) {
unsigned int maxval;
/* Read size. */
*colsP = (int)pm_getuint(fileP);
*rowsP = (int)pm_getuint(fileP);
/* Read maxval. */
maxval = pm_getuint(fileP);
if (maxval > PPM_OVERALLMAXVAL)
pm_error("maxval of input image (%u) is too large. "
"The maximum allowed by the PPM format is %u.",
maxval, PPM_OVERALLMAXVAL);
if (maxval == 0)
pm_error("maxval of input image is zero.");
*maxvalP = maxval;
}
static void
validateComputableSize(unsigned int const cols,
unsigned int const rows) {
/*----------------------------------------------------------------------------
Validate that the dimensions of the image are such that it can be
processed in typical ways on this machine without worrying about
overflows. Note that in C, arithmetic is always modulus
arithmetic, so if your values are too big, the result is not what
you expect. That failed expectation can be disastrous if you use
it to allocate memory.
It is very normal to allocate space for a pixel row, so we make sure
the size of a pixel row, in bytes, can be represented by an 'int'.
A common operation is adding 1 or 2 to the highest row or
column number in the image, so we make sure that's possible.
-----------------------------------------------------------------------------*/
if (cols > INT_MAX/(sizeof(pixval) * 3) || cols > INT_MAX - 2)
pm_error("image width (%u) too large to be processed", cols);
if (rows > INT_MAX - 2)
pm_error("image height (%u) too large to be processed", rows);
}
void
ppm_readppminit(FILE * const fileP,
int * const colsP,
int * const rowsP,
pixval * const maxvalP,
int * const formatP) {
int realFormat;
/* Check magic number. */
realFormat = pm_readmagicnumber(fileP);
switch (PAM_FORMAT_TYPE(realFormat)) {
case PPM_TYPE:
*formatP = realFormat;
ppm_readppminitrest(fileP, colsP, rowsP, maxvalP);
break;
case PGM_TYPE:
*formatP = realFormat;
pgm_readpgminitrest(fileP, colsP, rowsP, maxvalP);
break;
case PBM_TYPE:
*formatP = realFormat;
/* See comment in pgm_readpgminit() about this maxval */
*maxvalP = PPM_MAXMAXVAL;
pbm_readpbminitrest(fileP, colsP, rowsP);
break;
case PAM_TYPE:
pnm_readpaminitrestaspnm(fileP, colsP, rowsP, maxvalP, formatP);
break;
default:
pm_error("bad magic number 0x%x - not a PPM, PGM, PBM, or PAM file",
realFormat);
}
validateComputableSize(*colsP, *rowsP);
}
static void
readPpmRow(FILE * const fileP,
pixel * const pixelrow,
unsigned int const cols,
pixval const maxval,
int const format) {
unsigned int col;
for (col = 0; col < cols; ++col) {
pixval const r = pm_getuint(fileP);
pixval const g = pm_getuint(fileP);
pixval const b = pm_getuint(fileP);
if (r > maxval)
pm_error("Red sample value %u is greater than maxval (%u)",
r, maxval);
if (g > maxval)
pm_error("Green sample value %u is greater than maxval (%u)",
g, maxval);
if (b > maxval)
pm_error("Blue sample value %u is greater than maxval (%u)",
b, maxval);
PPM_ASSIGN(pixelrow[col], r, g, b);
}
}
static void
interpRasterRowRaw(const unsigned char * const rowBuffer,
pixel * const pixelrow,
unsigned int const cols,
unsigned int const bytesPerSample) {
unsigned int bufferCursor;
bufferCursor = 0; /* start at beginning of rowBuffer[] */
if (bytesPerSample == 1) {
unsigned int col;
for (col = 0; col < cols; ++col) {
pixval const r = rowBuffer[bufferCursor++];
pixval const g = rowBuffer[bufferCursor++];
pixval const b = rowBuffer[bufferCursor++];
PPM_ASSIGN(pixelrow[col], r, g, b);
}
} else {
/* two byte samples */
unsigned int col;
for (col = 0; col < cols; ++col) {
pixval r, g, b;
r = rowBuffer[bufferCursor++] << 8;
r |= rowBuffer[bufferCursor++];
g = rowBuffer[bufferCursor++] << 8;
g |= rowBuffer[bufferCursor++];
b = rowBuffer[bufferCursor++] << 8;
b |= rowBuffer[bufferCursor++];
PPM_ASSIGN(pixelrow[col], r, g, b);
}
}
}
static void
validateRppmRow(pixel * const pixelrow,
unsigned int const cols,
pixval const maxval,
const char ** const errorP) {
/*----------------------------------------------------------------------------
Check for sample values above maxval in input.
Note: a program that wants to deal with invalid sample values itself can
simply make sure it uses a sufficiently high maxval on the read function
call, so this validation never fails.
-----------------------------------------------------------------------------*/
if (maxval == 255 || maxval == 65535) {
/* There's no way a sample can be invalid, so we don't need to look at
the samples individually.
*/
*errorP = NULL;
} else {
unsigned int col;
for (col = 0, *errorP = NULL; col < cols && !*errorP; ++col) {
pixval const r = PPM_GETR(pixelrow[col]);
pixval const g = PPM_GETG(pixelrow[col]);
pixval const b = PPM_GETB(pixelrow[col]);
if (r > maxval)
pm_asprintf(
errorP,
"Red sample value %u is greater than maxval (%u)",
r, maxval);
else if (g > maxval)
pm_asprintf(
errorP,
"Green sample value %u is greater than maxval (%u)",
g, maxval);
else if (b > maxval)
pm_asprintf(
errorP,
"Blue sample value %u is greater than maxval (%u)",
b, maxval);
}
}
}
static void
readRppmRow(FILE * const fileP,
pixel * const pixelrow,
unsigned int const cols,
pixval const maxval,
int const format) {
unsigned int const bytesPerSample = maxval < 256 ? 1 : 2;
unsigned int const bytesPerRow = cols * 3 * bytesPerSample;
unsigned char * rowBuffer;
const char * error = NULL;
MALLOCARRAY(rowBuffer, bytesPerRow);
if (rowBuffer == NULL)
pm_asprintf(&error, "Unable to allocate memory for row buffer "
"for %u columns", cols);
else {
ssize_t rc;
rc = fread(rowBuffer, 1, bytesPerRow, fileP);
if (feof(fileP))
pm_asprintf(&error, "Unexpected EOF reading row of PPM image.");
else if (ferror(fileP))
pm_asprintf(&error, "Error reading row. fread() errno=%d (%s)",
errno, strerror(errno));
else {
size_t const bytesRead = rc;
if (bytesRead != bytesPerRow)
pm_asprintf(&error,
"Error reading row. Short read of %u bytes "
"instead of %u", (unsigned)bytesRead, bytesPerRow);
else {
interpRasterRowRaw(rowBuffer, pixelrow, cols, bytesPerSample);
validateRppmRow(pixelrow, cols, maxval, &error);
}
}
free(rowBuffer);
}
if (error) {
pm_errormsg("%s", error);
pm_strfree(error);
pm_error(NULL);
}
}
static void
readPgmRow(FILE * const fileP,
pixel * const pixelrow,
unsigned int const cols,
pixval const maxval,
int const format) {
jmp_buf jmpbuf;
jmp_buf * origJmpbufP;
gray * grayrow;
grayrow = pgm_allocrow(cols);
if (setjmp(jmpbuf) != 0) {
pgm_freerow(grayrow);
pm_setjmpbuf(origJmpbufP);
pm_longjmp();
} else {
unsigned int col;
pm_setjmpbufsave(&jmpbuf, &origJmpbufP);
pgm_readpgmrow(fileP, grayrow, cols, maxval, format);
for (col = 0; col < cols; ++col) {
pixval const g = grayrow[col];
PPM_ASSIGN(pixelrow[col], g, g, g);
}
pm_setjmpbuf(origJmpbufP);
}
pgm_freerow(grayrow);
}
static void
readPbmRow(FILE * const fileP,
pixel * const pixelrow,
unsigned int const cols,
pixval const maxval,
int const format) {
jmp_buf jmpbuf;
jmp_buf * origJmpbufP;
bit * bitrow;
bitrow = pbm_allocrow_packed(cols);
if (setjmp(jmpbuf) != 0) {
pbm_freerow_packed(bitrow);
pm_setjmpbuf(origJmpbufP);
pm_longjmp();
} else {
unsigned int col;
pm_setjmpbufsave(&jmpbuf, &origJmpbufP);
pbm_readpbmrow_packed(fileP, bitrow, cols, format);
for (col = 0; col < cols; ++col) {
pixval const g =
((bitrow[col/8] >> (7 - col%8)) & 0x1) == PBM_WHITE ?
maxval : 0;
PPM_ASSIGN(pixelrow[col], g, g, g);
}
pm_setjmpbuf(origJmpbufP);
}
pbm_freerow(bitrow);
}
void
ppm_readppmrow(FILE * const fileP,
pixel * const pixelrow,
int const cols,
pixval const maxval,
int const format) {
switch (format) {
case PPM_FORMAT:
readPpmRow(fileP, pixelrow, cols, maxval, format);
break;
/* For PAM, we require a depth of 3, which means the raster format
is identical to Raw PPM! How convenient.
*/
case PAM_FORMAT:
case RPPM_FORMAT:
readRppmRow(fileP, pixelrow, cols, maxval, format);
break;
case PGM_FORMAT:
case RPGM_FORMAT:
readPgmRow(fileP, pixelrow, cols, maxval, format);
break;
case PBM_FORMAT:
case RPBM_FORMAT:
readPbmRow(fileP, pixelrow, cols, maxval, format);
break;
default:
pm_error("Invalid format code");
}
}
pixel**
ppm_readppm(FILE * const fileP,
int * const colsP,
int * const rowsP,
pixval * const maxvalP) {
jmp_buf jmpbuf;
jmp_buf * origJmpbufP;
pixel ** pixels;
int cols, rows;
pixval maxval;
int format;
ppm_readppminit(fileP, &cols, &rows, &maxval, &format);
pixels = ppm_allocarray(cols, rows);
if (setjmp(jmpbuf) != 0) {
ppm_freearray(pixels, rows);
pm_setjmpbuf(origJmpbufP);
pm_longjmp();
} else {
unsigned int row;
pm_setjmpbufsave(&jmpbuf, &origJmpbufP);
for (row = 0; row < rows; ++row)
ppm_readppmrow(fileP, pixels[row], cols, maxval, format);
*colsP = cols;
*rowsP = rows;
*maxvalP = maxval;
pm_setjmpbuf(origJmpbufP);
}
return pixels;
}
void
ppm_check(FILE * const fileP,
enum pm_check_type const checkType,
int const format,
int const cols,
int const rows,
pixval const maxval,
enum pm_check_code * const retvalP) {
if (rows < 0)
pm_error("Invalid number of rows passed to ppm_check(): %d", rows);
if (cols < 0)
pm_error("Invalid number of columns passed to ppm_check(): %d", cols);
if (checkType != PM_CHECK_BASIC) {
if (retvalP)
*retvalP = PM_CHECK_UNKNOWN_TYPE;
} else if (PPM_FORMAT_TYPE(format) == PBM_TYPE) {
pbm_check(fileP, checkType, format, cols, rows, retvalP);
} else if (PPM_FORMAT_TYPE(format) == PGM_TYPE) {
pgm_check(fileP, checkType, format, cols, rows, maxval, retvalP);
} else if (format != RPPM_FORMAT) {
if (retvalP)
*retvalP = PM_CHECK_UNCHECKABLE;
} else {
pm_filepos const bytesPerRow = cols * 3 * (maxval > 255 ? 2 : 1);
pm_filepos const needRasterSize = rows * bytesPerRow;
pm_check(fileP, checkType, needRasterSize, retvalP);
}
}
|
C
|
#include <stdio.h>
unsigned char f(float a)
{
return a;
}
int main(void)
{
printf("return value : %d\n",f(128.5));
return 0;
}
|
C
|
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
//
// INSTITUTO POLITCNICO DO CVADO E DO AVE
// 2016/2017
// ENGENHARIA DE SISTEMAS INFORMTICOS
// VISO POR COMPUTADOR
// CDIGO AULAS
//
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
#define VC_DEBUG
#define MAX(a,b)(a>b?a:b)
//Estrutura para representar cor, assume por defeito 3 canais e 255 niveis
//Tambm possui um campo chamado gray que converte automaticamente de rgb para grayscale
typedef struct {
unsigned char r, g, b;
unsigned char gray;
}COLOR;
typedef enum
{
UNDEFINED = 0, SQUARE = 1, CIRCLE = 2
} Shape;
typedef enum
{
ARROWLEFT = 1, ARROWRIGHT, ARROWUP, CAR, FORBIDDEN, HIGHWAY, STOP
} Signal;
typedef enum
{
ERROR, SUCCESS, WARNING, INFO
} LogType;
typedef enum {
false, true
} bool;
int drawBoundingBox(IVC *imagem, OVC *blobs, int *nlabels, COLOR *color);
COLOR* newColor(int r, int g, int b);
int paintPixel(IVC *imagem, int position, COLOR *cor);
int meanBlur(IVC *src, IVC *dst, int kernel);
int drawGravityCentre(IVC *imagem, OVC *blobs, int *nlabels, COLOR *color);
IVC *vc_image_copy(IVC *src);
int blueSignalsToBinary(IVC *src, IVC *dst, IVC *hsvImage);
int redSignalsToBinary(IVC *src, IVC *dst, IVC *hsvImage);
int analiza(char *caminho);
int getSignals(IVC *src, IVC *dst, IVC *hsvImage);
IVC* sumBinaryImages(IVC *imagem1, IVC *imagem2);
void log(LogType tipo, char *mensagem);
Shape getBlobShape(OVC blob, IVC *image);
int analizaBlobs(OVC *blobs, int nlabels, IVC *labels, IVC *original, IVC *binaryImage);
Signal identifySignal(OVC blob, Shape shape, IVC *original, IVC *binaria, IVC *hsvImage);
bool isBlue(int hue, int sat, int value);
bool isRed(int hue, int sat, int value);
int vc_rgb_to_hsv(IVC *srcdst);
int value100To255(int value);
int value255To100(int value);
int vc_binary_dilate(IVC *src, IVC *dst, int size);
int vc_binary_erode(IVC *src, IVC *dst, int size);
int vc_binary_open(IVC *src, IVC *dst, int sizeErode, int sizeDilate);
int vc_binary_close(IVC *src, IVC *dst, int sizeErode, int sizeDilate);
int vc_gray_dilate(IVC *src, IVC *dst, int size);
int vc_gray_erode(IVC *src, IVC *dst, int size);
int vc_gray_open(IVC *src, IVC *dst, int sizeErode, int sizeDilate);
int vc_gray_close(IVC *src, IVC *dst, int sizeErode, int sizeDilate);
int vc_gray_to_binary_mean(IVC *srcdst);
int vc_gray_to_binary_midpoint(IVC *src, IVC *dst, int kernel);
int vc_gray_to_binary(IVC *srcdst, int threshold);
int vc_gray_to_binary_bernsen(IVC *src, IVC *dst, int kernel);
int vc_gray_to_binary_adapt(IVC *src, IVC *dst, int kernel);
int vc_gray_negative(IVC *srcdst);
int vc_rgb_negative(IVC *srcdst);
int vc_red_filter(IVC *srcdst);
int vc_remove_red(IVC *srcdst);
int vc_rgb_to_gray(IVC *src, IVC *dst);
int vc_rgb_to_gray(IVC *src, IVC *dst);
int vc_rgb_to_gray_mean(IVC *src, IVC *dst);
|
C
|
/*
* This file is part of the libemb project.
*
* Copyright (C) 2011 Stefan Wendler <[email protected]>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "shell.h"
/*
* @brief calculates the length of a c string
* @param str pointer to a c string
* @return integer length of the c string
*/
int shell_str_len(char *str)
{
int i = 0;
while(str[i++] != 0);
return i - 1;
}
/*
* @brief compares two c strings
* @param str1 pointer to the first c string
* @param str2 pointer to the second c string
* @param len1 length of the first c string
* @param len2 length of the second c string
* @return 1 if str1 is longer than str2,
* 2 if str1 and str2 don't match (excluding trailing blanks in str2)
* 0 if str1 and str2 match (ignoring trailing blanks in str2)
*/
int shell_str_cmp(char *str1, char *str2, int len1, int len2)
{
int i;
if(len1 > len2) return 1;
for(i = 0; i < len1; i++) {
if(str1[i] != str2[i]) return 2;
}
// make sure we matched a whole command, and not only
// a containing substring ...
if(len2 > len1 && str2[i] != ' ') {
return 2;
}
return 0;
}
int shell_parse_int(char *str)
{
int val = 0;
int i = 0;
char c;
while((c = str[i++]) != 0) {
if(c < '0' || c > '9') break;
val = val * 10 + (c - '0');
}
return val;
}
int shell_arg_parser(char *cmd_line, int len, shell_cmd_args *args)
{
int i;
int j;
int spos = 0;
int argc = 0;
for(i = 0; i < len; i++) {
// to many arguments
if(argc > SHELL_MAX_ARGS) return 1;
if(cmd_line[i] == ' ' || i == len - 1) {
// catch last argument ...
if(i == len - 1) i++;
// ignore first since it is the cmd itself
if(spos == 0) {
spos = i;
} else {
// argument value to long
if(i - spos > SHELL_MAX_ARG_LEN) return 2;
for(j = 0; j < i - spos - 1; j++) {
args->args[argc].val[j] = cmd_line[spos + 1 + j];
}
args->args[argc++].val[j] = 0;
spos = i;
}
}
}
args->count = argc;
return 0;
}
int shell_process_cmds(shell_cmds *cmds, char *cmd_line)
{
int i;
int ret;
int cmd_len;
int cmd_line_len;
shell_cmd_args args;
for(i = 0; i < cmds->count; i++) {
cmd_line_len = shell_str_len(cmd_line);
cmd_len = shell_str_len((char *)(cmds->cmds[i].cmd));
if(shell_str_cmp((char *)(cmds->cmds[i].cmd), cmd_line, cmd_len, cmd_line_len) == 0) {
ret = shell_arg_parser(cmd_line, cmd_line_len, &args);
if(ret == 1)
return SHELL_PROCESS_ERR_ARGS_MAX;
if(ret == 2)
return SHELL_PROCESS_ERR_ARGS_LEN;
return (cmds->cmds[i].func)(&args);
}
}
return SHELL_PROCESS_ERR_CMD_UNKN;
}
|
C
|
#include<stdio.h>
int main()
{
int c,t,b,n;
t=b=n=0;
while((c=getchar())!=EOF)
{
if(c=='\t')
{
t++;
}
else if(c=='\n')
{
n++;
}
else if(c==' ')
{
b++;
}
//putchar(c);
printf("Blank = %d,Tab = %d,Newline = %d",b,t,n);
}
return 0;
}
|
C
|
//
// circle_list.c
// struct_combine
//
// Created by 暴走的小钢镚儿 on 2018/3/21.
// Copyright © 2018年 暴走的小钢镚儿. All rights reserved.
//
#include "circle_list.h"
static int circle_list_count=0;
circle_list_pnode circle_list_creat1(circle_list_pnode head) //尾插法创建链表,头结点为空
{
circle_list_pnode p,q;
p=head;
while(p->next)
p=p->next;
printf("请输入一组数据(0截止):\n");
q=(circle_list_pnode)malloc(sizeof(circle_list_node));
scanf("%d",&q->data);
q->next=NULL;
while(q->data!=0)
{
p->next=q;
p=q;
q=(circle_list_pnode)malloc(sizeof(circle_list_node));
scanf("%d",&q->data);
circle_list_count++;
q->next=NULL;
}
p->next=head->next;
return head;
}
circle_list_pnode circle_list_creat2(circle_list_pnode head)//头插法创建
{
circle_list_pnode q;
printf("请输入一组数据(0截止):\n");
q=(circle_list_pnode)malloc(sizeof(circle_list_node));
scanf("%d",&q->data);
q->next=NULL;
while(q->data!=0)
{
q->next=head->next;
head->next=q;
q=(circle_list_pnode)malloc(sizeof(circle_list_node));
scanf("%d",&q->data);
circle_list_count++;
}
return head;
}
void circle_list_insert1(circle_list_pnode head,int pos,int k)//按位置插入
{
int i=0;
circle_list_pnode p,q;
q=(circle_list_pnode)malloc(sizeof(circle_list_node));
q->data=k;
q->next=NULL;
p=head;
while(p->next&&i<pos%circle_list_count-1)
{
i++;
p=p->next;
}
q->next=p->next;
p->next=q;
circle_list_count++;
}
void circle_list_insert2(circle_list_pnode head,int num,int key)//按数值插入
{
circle_list_pnode p=head;
int i=0;
circle_list_pnode q=(circle_list_pnode)malloc(sizeof(circle_list_node));
q->next=NULL;
q->data=key;
while(p->next&&p->next->data!=num&&i<circle_list_count)
{
i++;
p=p->next;
}
if(i>=circle_list_count)
{
printf("can not find!\n");
return;
}
else
{
q->next=p->next;
p->next=q;
circle_list_count++;
}
}
void circle_list_del1(circle_list_pnode head,int pos)//按位置删除
{
int i=0;
circle_list_pnode p,q;
p=head;
if(circle_list_count==0)
{
printf("NULL\n");
return ;
}
while(p->next&&i<pos%circle_list_count-1)
{
i++;
p=p->next;
}
q=p->next;
p->next=q->next;
circle_list_count--;
}
void circle_list_del2(circle_list_pnode head,int num)//按数值删除
{
circle_list_pnode p=head;
circle_list_pnode q;
int i=0;
while(p->next&&p->next->data!=num&&i<circle_list_count)
{
i++;
p=p->next;
}
if(i>=circle_list_count)
{
return;
}
else
{
q=p->next;
p->next=q->next;
free(q);
circle_list_count--;
}
return circle_list_del2(head,num);
}
void circle_list_search(circle_list_pnode head,int num)//按数值搜索
{
circle_list_pnode p=head;
int i=0;
while(p->next&&p->next->data!=num&&i<circle_list_count)
{
i++;
p=p->next;
}
if(i>=circle_list_count)
{
printf("not exist!\n");
return;
}
else
printf("exist pos:%3d\n",i);
}
void circle_list_print(circle_list_pnode head)//链表打印
{
circle_list_pnode p=head->next;
int i=0;
while(i<circle_list_count)
{
printf("%3d",p->data);
p=p->next;
i++;
}
printf("\n");
}
void circle_list_initial_document()
{
FILE*fp;
char ch;
fp=fopen(__FILE__,"r");
while((ch=fgetc(fp))!=EOF)
putchar(ch);
fclose(fp);
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.