language
large_stringclasses 1
value | text
stringlengths 9
2.95M
|
|---|---|
C
|
#include "ft_stock_str.h"
#include <stdio.h>
#include <stdlib.h>
struct s_stock_str *ft_strs_to_tab(int ac, char **av);
int main(void)
{
int i;
t_stock_str *stock;
char **arr;
arr = (char **)malloc(sizeof(char *) * 4);
i = 0;
while (i < 3)
{
arr[i] = (char *)malloc(sizeof(char ) * 4);
i++;
}
arr[0] = "HY";
arr[1] = "MYOUNG";
arr[2] = "ZZ";
stock = ft_strs_to_tab(3, arr);
i = 0;
while (i < 4)
{
printf("%d str : %s size : %d copy : %s \n", i, stock[i].str, stock[i].size, stock[i].copy);
i++;
}
return (0);
}
|
C
|
#include<stdio.h>
int main()
{
int t,n,i,j,key,a[10],l,h,f=0;
printf("Enter the number of testcases\n");
scanf("%d",&t);
for(i=0;i<t;i++)
{
printf("\nEnter the number of elements in array and element to be searched\n");
scanf("%d %d",&n,&key);
printf("Enter the elements of array\n");
for(j=0;j<n;j++)
{
scanf("%d",&a[j]);
}
for(j=0;j<n;j++)
{
if(a[j]==key)
{
printf("1 (Element is present)\n");
f=1;
break;
}
}
if(f==0)
printf("-1 (Element is not present)\n");
}
return 0;
}
|
C
|
#include "ets_sys.h"
#include "osapi.h"
#include "os_type.h"
#include "user_interface.h"
#include "driver/gpio16.h"
#include "driver/buttons.h"
extern float target_temperature;
extern bool change_temp_mode;
extern uint32 change_temp_mode_started;
extern uint8_t pin_num[GPIO_PIN_NUM];
// GPIO_PIN_INTR_NEGEDGE - down
// GPIO_PIN_INTR_POSEDGE - up
// GPIO_PIN_INTR_ANYEDGE - both
// GPIO_PIN_INTR_LOLEVEL - low level
// GPIO_PIN_INTR_HILEVEL - high level
// GPIO_PIN_INTR_DISABLE - disable interrupt
const char *gpio_type_desc[] =
{
"GPIO_PIN_INTR_DISABLE (DISABLE INTERRUPT)",
"GPIO_PIN_INTR_POSEDGE (UP)",
"GPIO_PIN_INTR_NEGEDGE (DOWN)",
"GPIO_PIN_INTR_ANYEDGE (BOTH)",
"GPIO_PIN_INTR_LOLEVEL (LOW LEVEL)",
"GPIO_PIN_INTR_HILEVEL (HIGH LEVEL)"
};
extern int ets_uart_printf(const char *fmt, ...);
int (*console_printf)(const char *fmt, ...) = ets_uart_printf;
void ICACHE_FLASH_ATTR intr_callback(unsigned pin, unsigned level)
{
console_printf("INTERRUPT: GPIO%d = %d\r\n", pin_num[pin], level);
if (change_temp_mode) {
if (pin == 1) {
if (target_temperature > 5) {
target_temperature -= 0.5;
}
}
else if (pin == 2) {
if (target_temperature < 30) {
target_temperature += 0.5;
}
}
}
change_temp_mode = true;
change_temp_mode_started = system_get_rtc_time();
}
ICACHE_FLASH_ATTR void ICACHE_FLASH_ATTR InitButtons(void)
{
GPIO_INT_TYPE gpio_type;
uint8_t gpio_pin;
// Pin number 1 = GPIO5
gpio_pin = 1;
gpio_type = GPIO_PIN_INTR_POSEDGE;
if (set_gpio_mode(gpio_pin, GPIO_INPUT, GPIO_PULLUP)) {
console_printf("GPIO%d set interrupt mode\r\n", pin_num[gpio_pin]);
if (gpio_intr_init(gpio_pin, gpio_type)) {
console_printf("GPIO%d enable %s mode\r\n", pin_num[gpio_pin], gpio_type_desc[gpio_type]);
gpio_intr_attach(intr_callback);
} else {
console_printf("Error: GPIO%d not enable %s mode\r\n", pin_num[gpio_pin], gpio_type_desc[gpio_type]);
}
} else {
console_printf("Error: GPIO%d not set interrupt mode\r\n", pin_num[gpio_pin]);
}
// Pin number 2 = GPIO4
gpio_pin = 2;
gpio_type = GPIO_PIN_INTR_POSEDGE;
if (set_gpio_mode(gpio_pin, GPIO_INPUT, GPIO_PULLUP)) {
console_printf("GPIO%d set interrupt mode\r\n", pin_num[gpio_pin]);
if (gpio_intr_init(gpio_pin, gpio_type)) {
console_printf("GPIO%d enable %s mode\r\n", pin_num[gpio_pin], gpio_type_desc[gpio_type]);
gpio_intr_attach(intr_callback);
} else {
console_printf("Error: GPIO%d not enable %s mode\r\n", pin_num[gpio_pin], gpio_type_desc[gpio_type]);
}
} else {
console_printf("Error: GPIO%d not set interrupt mode\r\n", pin_num[gpio_pin]);
}
}
|
C
|
/*
This program is used with traditional phase-shifting
Unwraps high-frequencies phases using gradually higher frequencies
Input 16bits high/low freq phase-maps, outputs the LUT
*/
#include <stdlib.h>
#include <stdio.h>
#include <omp.h>
#include <string.h>
#include <math.h>
#include <time.h>
#include "args.h"
#include "helpers.c"
float chop(float x, float low, float high) {
return fmin(fmax(x, low), high);
}
int main(int argc, char** argv) {
int nthreads = 4, offset = 0;
// Args parsing
ARGBEGIN
ARG_CASE('t')
nthreads = ARGI;
ARG_CASE('O')
offset = ARGI;
WRONG_ARG
usage:
printf("usage: %s [-t nthreads=%d] [-O offset=%d]\n"
"\thighest-x.png ... lowest-x.png highest-y.png ... lowest-y.png lowest-period ... highest-period lut.png\n",
argv0, nthreads, offset);
exit(1);
ARGEND
omp_set_num_threads(nthreads);
srand(time(NULL));
if(argc < 7 || (argc - 1) % 3 != 0) {
fprintf(stderr, "Wrong number of args\n");
goto usage;
}
int w, h;
int nb_freqs = (argc - 1) / 3;
float*** phases_x = malloc(sizeof(float**) * nb_freqs);
float*** phases_y = malloc(sizeof(float**) * nb_freqs);
float* frequencies = malloc(sizeof(float) * nb_freqs);
for(int i=0; i<nb_freqs; i++) {
phases_x[i] = load_gray(argv[i], &w, &h);
phases_y[i] = load_gray(argv[nb_freqs + i], &w, &h);
frequencies[i] = 1.0/atof(argv[nb_freqs * 2 + i]);
}
float*** lut = malloc_f32cube(3, w, h);
// Start with the lowest frequency & iteratively update next ones
// Normalize lowest frequency
for(int i=0; i<h; i++) {
for(int j=0; j<w; j++) {
phases_x[nb_freqs - 1][i][j] = phases_x[nb_freqs - 1][i][j] / 65535.0;
phases_y[nb_freqs - 1][i][j] = phases_y[nb_freqs - 1][i][j] / 65535.0;
}
}
for(int k=nb_freqs - 2; k >= 0; k--) {
for(int i=0; i<h; i++) {
for(int j=0; j<w; j++) {
float prev_phi_x = phases_x[k + 1][i][j];
float prev_phi_y = phases_y[k + 1][i][j];
float phi_x = phases_x[k][i][j] / 65535.0;
float phi_y = phases_y[k][i][j] / 65535.0;
float prev_freq = frequencies[k + 1];
float freq = frequencies[k];
phases_x[k][i][j] = phi_x - round(phi_x - freq/prev_freq * prev_phi_x);
phases_y[k][i][j] = phi_y - round(phi_y - freq/prev_freq * prev_phi_y);
lut[X][i][j] = chop(phases_x[k][i][j] / frequencies[k], 0, w);
lut[Y][i][j] = chop(phases_y[k][i][j] / frequencies[k], 0, h);
lut[DIST][i][j] = 0;
}
}
/* char filename[FNAME_MAX_LEN]; */
/* sprintf(filename, "phases-%d.png", k); */
/* save_color_map(filename, lut, w, h, w, h, 1); */
}
for(int i=0; i<h; i++) {
for(int j=0; j<w; j++) {
float unwrapped_x = phases_x[0][i][j];
float unwrapped_y = phases_y[0][i][j];
lut[X][i][j] = chop(unwrapped_x / frequencies[0] - offset, 0, w - 1);
lut[Y][i][j] = chop(unwrapped_y / frequencies[0] - offset, 0, h - 1);
lut[DIST][i][j] = 0;
}
}
// TODO : Allow different sizes of cam/proj pairs
save_color_map(argv[argc - 1], lut, w, h, w, h, 1);
return EXIT_SUCCESS;
}
|
C
|
//----------------------------------------------------------------------------------------------
// float sqrt(float x)
//
// Description:
//
// square root
//
// Input:
// float x
//
// Output:
// square root of x
//
//----------------------------------------------------------------------------------------------
#include <errno.h>
#include <math.h>
#include "_mathlib.h"
float sqrt(float x)
{
int n;
tUfloat32 Ret;
tIEEE xIEEE;
FTYPE type;
Ret.f = x;
type = _UnpkMath(Ret, &xIEEE);
if(type == _NANTYPE)
Ret.l = NaN;
else if(Ret.f < 0)
{
errno = EDOM;
Ret.l = NaN;
}
else if(type & (_ZEROTYPE | _INFTYPE) )
return Ret.f;
else
{
int i;
int round;
int sticky;
unsigned long q;
unsigned long r;
unsigned long b;
n = xIEEE.exp + (2 - FLT_BIAS);
r = xIEEE.sig;
if(n & 1)
{
n--;
r <<= 1;
}
n /= 2;
q = 0;
b = 0x04000000ul >> 2;
for(i = 1; i < 26; ++i)
{
long t;
r = r << 1;
t = r - ( (q<<1) + b);
if(t > 0)
{
r = t;
q |= b;
}
b >>= 1;
}
round = q & 1;
sticky = r;
q >>= 1;
if(round && (sticky || (q & 1)))
{
q++;
}
xIEEE.sgn = 0;
xIEEE.sig = q;
xIEEE.exp = - 1 + FLT_BIAS;
_PackMath(&xIEEE, &Ret);
Ret.f = ldexp( Ret.f, n);
}
return(Ret.f);
}
|
C
|
/* util.c */
#include "SubMtxManager.h"
#define MYDEBUG 0
/*--------------------------------------------------------------------*/
/*
-----------------------------------------------
return a pointer to a SubMtx object that has
been initialized with the input parameters
created -- 98may02, cca
-----------------------------------------------
*/
SubMtx *
SubMtxManager_newObjectOfSizeNbytes (
SubMtxManager *manager,
int nbytesNeeded
) {
SubMtx *mtx, *prev ;
int nbytesAvailable, newinstance ;
/*
---------------
check the input
---------------
*/
if ( manager == NULL || nbytesNeeded <= 0 ) {
fprintf(stderr,
"\n fatal error in SubMtxMananger_newObjectOfSizeNbytes(%p,%d)"
"\n bad input\n", manager, nbytesNeeded) ;
exit(-1) ;
}
#if MYDEBUG > 1
fprintf(stdout,
"\n\n new mtx request, nbytes needed = %d", nbytesNeeded) ;
fflush(stdout) ;
#endif
if ( manager->lock != NULL ) {
/*
-----------------------------------------------
lock the lock, get exclusive access to the list
-----------------------------------------------
*/
Lock_lock(manager->lock) ;
#if MYDEBUG > 1
fprintf(stdout, "\n manager: lock is locked") ;
fflush(stdout) ;
#endif
manager->nlocks++ ;
#if MYDEBUG > 1
fprintf(stdout, "\n %d locks so far", manager->nlocks) ;
fflush(stdout) ;
#endif
}
/*
---------------------------------------------------------
find a SubMtx object with the required number of bytes
---------------------------------------------------------
*/
for ( mtx = manager->head, prev = NULL ;
mtx != NULL ;
mtx = mtx->next ) {
nbytesAvailable = SubMtx_nbytesInWorkspace(mtx) ;
#if MYDEBUG > 1
fprintf(stdout, "\n free mtx %p, nbytes = %d",
mtx, nbytesAvailable) ;
fflush(stdout) ;
#endif
if ( nbytesNeeded <= nbytesAvailable ) {
break ;
}
prev = mtx ;
}
if ( mtx != NULL ) {
/*
---------------------------------------
suitable object found, remove from list
---------------------------------------
*/
#if MYDEBUG > 1
fprintf(stdout, "\n mtx = %p, %d nbytes available",
mtx, nbytesAvailable) ;
fflush(stdout) ;
#endif
if ( prev == NULL ) {
manager->head = mtx->next ;
} else {
prev->next = mtx->next ;
}
newinstance = 0 ;
} else {
/*
------------------------------------------------------------------
no suitable object found, create new instance and allocate storage
------------------------------------------------------------------
*/
mtx = SubMtx_new() ;
#if MYDEBUG > 1
fprintf(stdout,
"\n no suitable object found, new mtx = %p, bytes = %d",
mtx, nbytesNeeded) ;
fflush(stdout) ;
#endif
newinstance = 1 ;
DV_setSize(&mtx->wrkDV, nbytesNeeded/sizeof(double)) ;
}
if ( newinstance == 1 ) {
manager->nbytesalloc += SubMtx_nbytesInWorkspace(mtx) ;
}
manager->nactive++ ;
manager->nbytesactive += SubMtx_nbytesInWorkspace(mtx) ;
manager->nbytesrequested += nbytesNeeded ;
#if MYDEBUG > 1
fprintf(stdout, "\n %d bytes active, %d bytes requested",
manager->nbytesactive, manager->nbytesrequested) ;
#endif
manager->nrequests++ ;
if ( manager->lock != NULL ) {
/*
-----------------------------------------------------
unlock the lock, release exclusive access to the list
-----------------------------------------------------
*/
manager->nunlocks++ ;
#if MYDEBUG > 1
fprintf(stdout, "\n manager: unlocking, %d unlocks so far",
manager->nunlocks) ;
fflush(stdout) ;
#endif
Lock_unlock(manager->lock) ;
}
return(mtx) ; }
/*--------------------------------------------------------------------*/
/*
----------------------------
release a SubMtx instance
created -- 98may02, cca
----------------------------
*/
void
SubMtxManager_releaseObject (
SubMtxManager *manager,
SubMtx *mtx1
) {
SubMtx *mtx2, *prev ;
int nbytes1, nbytes2 ;
/*
---------------
check the input
---------------
*/
if ( manager == NULL || mtx1 == NULL ) {
fprintf(stderr,
"\n fatal error in SubMtxManager_releaseObject(%p,%p)"
"\n bad input\n", manager, mtx1) ;
exit(-1) ;
}
if ( manager->lock != NULL ) {
/*
-----------------------------------------------
lock the lock, get exclusive access to the list
-----------------------------------------------
*/
Lock_lock(manager->lock) ;
manager->nlocks++ ;
#if MYDEBUG > 1
fprintf(stdout, "\n\n manager : locking in releaseObject, %d locks",
manager->nlocks) ;
fflush(stdout) ;
#endif
}
manager->nreleases++ ;
manager->nbytesactive -= SubMtx_nbytesInWorkspace(mtx1) ;
manager->nactive-- ;
if ( manager->mode == 0 ) {
/*
---------------
release storage
---------------
*/
SubMtx_free(mtx1) ;
} else {
/*
--------------------------------------------------------
find a place in the list where the SubMtx objects are
sorted in ascending order of the size of their workspace
--------------------------------------------------------
*/
nbytes1 = SubMtx_nbytesInWorkspace(mtx1) ;
#if MYDEBUG > 1
fprintf(stdout, "\n\n trying to release mtx %p with %d bytes",
mtx1, nbytes1) ;
#endif
for ( mtx2 = manager->head, prev = NULL ;
mtx2 != NULL ;
mtx2 = mtx2->next ) {
nbytes2 = SubMtx_nbytesInWorkspace(mtx2) ;
#if MYDEBUG > 1
fprintf(stdout, "\n list mtx %p with %d bytes", mtx2, nbytes2) ;
#endif
if ( nbytes2 >= nbytes1 ) {
break ;
}
prev = mtx2 ;
}
if ( prev == NULL ) {
manager->head = mtx1 ;
#if MYDEBUG > 1
fprintf(stdout, "\n manager->head = %p", mtx1) ;
#endif
} else {
prev->next = mtx1 ;
#if MYDEBUG > 1
fprintf(stdout, "\n %p->next = %p", prev, mtx1) ;
#endif
}
mtx1->next = mtx2 ;
#if MYDEBUG > 1
fprintf(stdout, "\n %p->next = %p", mtx1, mtx2) ;
#endif
}
if ( manager->lock != NULL ) {
/*
-----------------------------------------------------
unlock the lock, release exclusive access to the list
-----------------------------------------------------
*/
manager->nunlocks++ ;
#if MYDEBUG > 1
fprintf(stdout,
"\n manager : unlocking in releaseObject, %d unlocks",
manager->nunlocks) ;
fflush(stdout) ;
#endif
Lock_unlock(manager->lock) ;
}
return ; }
/*--------------------------------------------------------------------*/
/*
-----------------------------------
release a list of SubMtx objects
created -- 98may02, cca
-----------------------------------
*/
void
SubMtxManager_releaseListOfObjects (
SubMtxManager *manager,
SubMtx *head
) {
SubMtx *mtx1, *mtx2, *prev ;
int nbytes1, nbytes2 ;
/*
---------------
check the input
---------------
*/
if ( manager == NULL || head == NULL ) {
fprintf(stderr,
"\n fatal error in SubMtxManager_releaseListOfObjects(%p,%p)"
"\n bad input\n", manager, head) ;
exit(-1) ;
}
if ( manager->lock != NULL ) {
/*
-----------------------------------------------
lock the lock, get exclusive access to the list
-----------------------------------------------
*/
Lock_lock(manager->lock) ;
manager->nlocks++ ;
#if MYDEBUG > 1
fprintf(stdout,
"\n\n manager : locking in releaseListOfObjects, %d locks",
manager->nlocks) ;
fflush(stdout) ;
#endif
}
if ( manager->mode == 0 ) {
/*
---------------
release storage
---------------
*/
while ( (mtx1 = head) != NULL ) {
head = head->next ;
manager->nbytesactive -= SubMtx_nbytesInWorkspace(mtx1) ;
manager->nactive-- ;
manager->nreleases++ ;
SubMtx_free(mtx1) ;
}
} else {
/*
-------------------
recycle the objects
-------------------
*/
while ( head != NULL ) {
mtx1 = head ;
head = mtx1->next ;
/*
--------------------------------------------------------
find a place in the list where the SubMtx objects are
sorted in ascending order of the size of their workspace
--------------------------------------------------------
*/
nbytes1 = SubMtx_nbytesInWorkspace(mtx1) ;
#if MYDEBUG > 1
fprintf(stdout, "\n\n trying to release mtx %p with %d bytes",
mtx1, nbytes1) ;
#endif
for ( mtx2 = manager->head, prev = NULL ;
mtx2 != NULL ;
mtx2 = mtx2->next ) {
nbytes2 = SubMtx_nbytesInWorkspace(mtx2) ;
#if MYDEBUG > 1
fprintf(stdout,
"\n list mtx %p with %d bytes", mtx2, nbytes2) ;
#endif
if ( nbytes2 >= nbytes1 ) {
break ;
}
prev = mtx2 ;
}
if ( prev == NULL ) {
manager->head = mtx1 ;
#if MYDEBUG > 1
fprintf(stdout, "\n manager->head = %p", mtx1) ;
#endif
} else {
prev->next = mtx1 ;
#if MYDEBUG > 1
fprintf(stdout, "\n %p->next = %p", prev, mtx1) ;
#endif
}
mtx1->next = mtx2 ;
#if MYDEBUG > 1
fprintf(stdout, "\n %p->next = %p", mtx1, mtx2) ;
#endif
manager->nbytesactive -= SubMtx_nbytesInWorkspace(mtx1) ;
manager->nactive-- ;
manager->nreleases++ ;
#if MYDEBUG > 1
fprintf(stdout, "\n # releases = %d", manager->nreleases) ;
for ( mtx1 = manager->head ; mtx1 != NULL ; mtx1 = mtx1->next ) {
fprintf(stdout, "\n mtx (%d,%d), nbytes %d",
mtx1->rowid, mtx1->colid,
SubMtx_nbytesInWorkspace(mtx1)) ;
}
#endif
}
}
if ( manager->lock != NULL ) {
/*
-----------------------------------------------------
unlock the lock, release exclusive access to the list
-----------------------------------------------------
*/
manager->nunlocks++ ;
#if MYDEBUG > 1
fprintf(stdout,
"\n manager : unlocking in releaseListOfObjects, %d unlocks",
manager->nunlocks) ;
fflush(stdout) ;
#endif
Lock_unlock(manager->lock) ;
}
return ; }
/*--------------------------------------------------------------------*/
|
C
|
#include <stdio.h>
int main(void){
int i1=0, i2=1, n, res;
scanf("%d",&n);
for(;n;--n){ res=i2; i2+=i1; i1=res; }
printf("%d\n",res);
}
|
C
|
#include "holberton.h"
#include <stdio.h>
/**
* main - natural_numbers
*
* Return: Always 0
*/
int main(void)
{
int num1 = 1;
int num2 = 1;
int cont = 0;
for(cont = 0; cont <= 50;cont++ )
{
printf("%d\n", num);
num= num+num;
}
return (0);
}
|
C
|
#include <sys/stat.h>
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include "dirent.h"
#define T Dirent_T
struct T {
char name[FILE_MAXNAME];
char shortname[FILE_MAXNAME];
long ino;
int type;
int statreturn;
};
T Dirent_new( char *name ) {
struct stat stbuf;
int res;
res = stat(name, &stbuf);
T fl;
fl = (T)malloc(sizeof(struct T));
strncpy(fl->name, name, FILE_MAXNAME);
fl->name[FILE_MAXNAME-1] = '\0';
fl->statreturn = res;
return fl;
}
char *Dirent_getname( T fl ) {
return fl->name;
}
void Dirent_free( T *fl ) {
free(*fl);
*fl = NULL;
}
#undef T
|
C
|
// Jordan Chalupka 0928528
#include "avl.h"
int balanceFactor (BinNode * tree) {
int bf = getHeight(tree->left) - getHeight(tree->right);
return bf;
}
/* Left Left Rotate */
BinNode *avl_rotate_leftleft(BinNode *node) {
BinNode *a = node;
BinNode *b = a->left;
a->left = b->right;
b->right = a;
return(b);
}
/* Left Right Rotate */
BinNode *avl_rotate_leftright(BinNode *node) {
BinNode *a = node;
BinNode *b = a->left;
BinNode *c = b->right;
a->left = c->right;
b->right = c->left;
c->left = b;
c->right = a;
return(c);
}
/* Right Left Rotate */
BinNode *avl_rotate_rightleft(BinNode *node) {
BinNode *a = node;
BinNode *b = a->right;
BinNode *c = b->left;
a->right = c->left;
b->left = c->right;
c->right = b;
c->left = a;
return(c);
}
/* Right Right Rotate */
BinNode *avl_rotate_rightright(BinNode *node) {
BinNode *a = node;
BinNode *b = a->right;
a->right = b->left;
b->left = a;
return(b);
}
BinNode* avlBalanceNode(BinNode *node) {
BinNode *newroot = NULL;
if(node->left) node->left = avlBalanceNode(node->left);
if(node->right) node->right = avlBalanceNode(node->right);
int bf = balanceFactor(node);
if(bf >= 2) {
/* Left Side is Overloaded */
if(balanceFactor(node->left) <= -1)
newroot = avl_rotate_leftright(node);
else
newroot = avl_rotate_leftleft(node);
} else if(bf <= -2) {
/* Right Side is Overloaded */
if(balanceFactor(node->right) >= 1)
newroot = avl_rotate_rightleft(node);
else
newroot = avl_rotate_rightright(node);
} else {
/* Balanced */
newroot = node;
}
return(newroot);
}
void avlBalance(BinTree * tree) {
BinNode *newNode = NULL;
//printf("Here %s\n", tree->root->data);
newNode = avlBalanceNode(tree->root);
if (newNode != tree->root) {
tree->root = newNode;
}
}
|
C
|
#ifndef __GET_KEY_PROC_H__
#define __GET_KEY_PROC_H__
/* 키보드 입력을 처리 해주는 함수 모음 */
/* 키보드 입력을 사용할 윈도우는 커서 위치를 저장하고 통신을 할 수 있는 아래의 변수를 반드시 가져야 한다.
* int i_cursor_y;
* int i_cursor_x;
* int high_level;
* int low_level;
* 위의 변수 값을 참고하여 키보드 입력을 받고 지정해둔 기능에 맞게 수행하게 된다. */
void get_keyboard_input(char *high_level, char *low_level); // 키보드의 입력을 받는다.
void move_cursor(int page, int y, int x); // 커서를 인자를 받아서 이동 시킨다.
/* 커서를 이동한다. 커서는 주어진 공간을 벗어나지 못 한다.*/
void move_cursor_left(int y, int x, int width, int height, int **i_cursor_y, int **i_cursor_x, int high_level);
void move_cursor_right(int y, int x, int width, int height, int **i_cursor_y, int **i_cursor_x, int high_level);
void move_cursor_up(int y, int x, int width, int height, int **i_cursor_y, int **i_cursor_x, int high_level);
void move_cursor_down(int y, int x, int width, int height, int **i_cursor_y, int **i_cursor_x, int high_level);
void move_cursor_new_line(int y, int x, int width, int height, int **i_cursor_y, int **i_cursor_x, int low_level);
void type_words(int y, int x, int width, int height, int **i_cursor_y, int **i_cursor_x, int low_level);
#endif // __GET_KEY_PROC_H__
|
C
|
#include "dht11.h"
#include <stdio.h>
uint8 DHT11_ReadData(void)
{
uint8 i,temp=0;
for(i=0;i<8;i++)
{
while(!rDHT11);//ÿһbitݶ50us͵ƽʱ϶ʼ
Delay_us(33);//ȷʱ33us
if(rDHT11)//λΪ1
{
temp=temp<<1 | 0x01;
while(rDHT11);
}
else//λΪ0
temp<<=1;
}
return temp;
}
uint8 DHT11_GetValue(uint8 *p)
{
uint8 temp,temp1,temp2;
//߿״̬Ϊߵƽ,͵ȴDHT11Ӧ,ͱ18,֤DHT11ܼʼźš
GPIO_ResetBits(GPIOA,PA12);
Delay_ms(20);//ȷʱ20ms
GPIO_SetBits(GPIOA,PA12);
//ͿʼźŽ,ʱȴ20-40us, ȡDHT11Ӧźš
Delay_us(40);//ȷʱ40us
//Ϊ͵ƽ,˵DHT11Ӧź
if(!rDHT11)
{
//жϴӻĵ͵ƽӦźǷ
while(!rDHT11);
//DHT11Ӧźź,ٰ80us
while(rDHT11);
p[0]=DHT11_ReadData();//8bitʪ
temp1=DHT11_ReadData();//Ч
p[1]=DHT11_ReadData();//8bit¶
temp2=DHT11_ReadData();//Ч
temp=DHT11_ReadData();//8bitУ
GPIO_SetBits(GPIOA,PA12);
if(temp==(p[0]+p[1]+temp1+temp2))
{
return 1;
}
}
return 0;
}
|
C
|
/*======================================================================
modIBPRRIOAP(M,I,B,k; L,t)
Integral bivariate polynomial real root isolation over an algebraic point
Inputs
M : the minimal integral polynomial of an algebraic number
\alpha.
I : an open standard logarithmic isolating interval for \alpha.
B : a bivariate polynomial such that B(alpha,y) is squarefree, and
\alpha is a simple (i.e. multiplicity one) root of disc_y(B).
k : if k is NIL, only root isolation is performed. Otherwise, k
is the target precision of refinement - i.e. we try to refine
isolating intervals to a width of 1/2^k.
Outputs
L : If t = 0, L is a list (I_1,...,I_m)
of the form I_i = (a,b,e,F,t)
where (a,b) is strongly disjoint interval with
logarithmic binary rational endpoints and is either open
or one-point, e is 0 or 1, and F is 2-variate integral polynomial.
If e is zero, then (a,b) is an isolating interval for exactly one
simple root of B(alpha,y), and F = B and t is the trend.
If e is 1, then (a,b) is an isolating interval for a double root
of B(alpha,y) and for a simple root of F (a factor of B'(\alpha,y))
with trend t, and the two roots are equal.
t : 0, 1 or 2.
If t = 0, L is as described above
If t = 1, the program failed to produce an
isolation list L because of exponent limitation.
If t = 2, the failure was due to mantissa limitation.
If t = 3 then either the leading coefficient's sign couldn't
be determined, or
we encountered more than one "don't know" interval for a given poly.
======================================================================*/
#include "lift2d.h"
Word ProveNotRoot(Word A, Word M, Word I, Word a, Word b, Word Ap, Word K);
void modIBPRRIOAP(Word M, Word I, Word B, Word k, Word *L_, BDigit *t_)
{
Word L,CFP,Bp,Ls,Lp,Ld,td,a,b,Jp;
BDigit t,n,n1,n2,np,u,s,e,i,j,t1,tc,c;
ieee F1,F2;
double p,w1,w2;
interval *A = NULL,K,*Q = NULL,*HICFP,J;
Step1: /* Convert the isolating interval for \alpha to a
hardware interval. */
L = NIL;
LBRNIEEEE(FIRST(I), &t,&F1,&n1);
if (t != 0)
goto Return;
w1 = F1.num;
LBRNIEEEE(SECOND(I), &t,&F2,&n2);
if (t != 0)
goto Return;
w2 = F2.num;
np = MIN(n1,n2);
Step2: /* Convert the minimal polynomial to a hardware interval
polynomial and refine the hardware interval. */
FPCATCH();
IUPHIP(M,&A,&t); // If t != 0, remember to free A!
if (t == 0) {
A = NULL;
t = 1;
goto Return; }
n = PDEG(M);
t = HIPFES(n,A,w2);
if (FPCHECK() == 1) {
t = 1;
goto Return; }
if (t == NIL) {
t = 2;
goto Return; }
u = 0;
while (u == 0 && np > 0) {
p = (w1 + w2) / 2.0;
s = HIPFES(n,A,p);
if ((FPCHECK() == 1) || (s == NIL))
u = 1;
else if (s == t)
w2 = p;
else if (s == -t)
w1 = p;
else {
w1 = p;
w2 = p; }
np = np - 1; }
K.left = w1;
K.right = w2;
Step3: /* Isolate the roots of B(alpha,y) */
/* Get hardware interval array to store B(alpha,y) (init to zero) */
Q = GETHIPARRAY(PDEG(B));
for(i = 0; i < PDEG(B) + 1; i++)
IHI(0,&(Q[i]),&t); /* this can't fail! */
/* Compute B(alpha,y) and store in Q */
for(Bp = B; Bp != NIL; Bp = RED2(Bp)) {
FIRST2(Bp,&e,&CFP);
IUPHIP(CFP,&HICFP,&c);
Q[e] = HIPIEVAL(PDEG(CFP),HICFP,K);
if (c != 0)
FREEARRAY(HICFP);
}
/* Check leading coefficient */
s = HISIGN(Q[PDEG(B)]);
if (s == NIL) {
t = 3;
goto Return; }
/* get trend of first root */
if ((PDEG(B) % 2 == 0 && s == 1) || (PDEG(B) % 2 == 1 && s == -1))
t1 = -1;
else
t1 = 1;
/* Isolate the roots of B(alpha,y) */
modHIPRRID(PDEG(B),Q, &L,&t);
if (t != 0)
goto Return; // isolation failed
/* If there are multiple don't knows ... we have failed. */
else {
Word failCount = 0;
for(Word Lp = L; Lp != NIL; Lp = RED(Lp))
if (THIRD(FIRST(Lp)) != 0)
failCount++;
if (failCount > 1) {
t = 3;
goto Return;
}
}
Step4: /* Refine roots? */
//PushOutputContext(cerr); OWRITE(L); SWRITE("\n"); PopOutputContext();
if (k == NIL)
goto Return;
Ls = NIL;
for(Lp = L, tc = t1; Lp != NIL; Lp = RED(Lp))
{
FIRST3(FIRST(Lp),&a,&b,&t); // iso interval is (a,b), with t=0 for simple root, t=1 for double
/* Take proper care of 1-point intervals! */
if (LBRNCOMP(a,b) == 0) {
// (a,a) is a root of B(alpha,y), and it is a simple root of linear poly
Word Jpnew;
if (a == 0 && t == 0) {
Jpnew = LIST5(0,0,0,LIST2(1,LIST2(0,1)),1);
tc *= -1;
}
else if (a == 0 && t != 0) {
Jpnew = LIST5(0,0,1,LIST2(1,LIST2(0,1)),0);
}
else {
Jpnew = LIST5(a,b,0,LIST4(1,LIST2(0,IMP2(1,SECOND(a))),0,LIST2(0,INEG(FIRST(a)))),1);
if (t == 0)
tc *= -1;
}
Ls = COMP(Jpnew,Ls);
continue;
}
/* Compute j, current width. */
Jp = LIST2(a,b);
LBRIHI(FIRST(Lp),&J,&t);
j = -LSILW(Jp);
/***** (a,b) is an isolating interval for a single, simple root ***********/
if (THIRD(FIRST(Lp)) == 0) {
HIPIR(PDEG(B),Q,J,tc,j,k,&J,&j);
Jp = HILBRI(J);
Jp = LIST5(FIRST(Jp),SECOND(Jp),0,B,tc);
tc *= -1;
}
/***** (a,b) is the only "don't know" interval. ***************************/
/* isolate and refine all the roots of the the derivative of B w.r.t. y over alpha, and if only
one root is in (a,b), it must be the double root of B(alpha,y), and no other root of of
B(alpha,y) can be in the interval (y the mean value theorem!).
*/
else {
/* PushOutputContext(cerr); */
/* SWRITE("Don't know interval ("); LBRNWRITE(a); SWRITE(","); LBRNWRITE(b); SWRITE(") must be refined!\n"); */
/* PopOutputContext(); */
Word Bp = IPDER(2,B,2);
Word Bpsqf = IPPGSD(2,Bp);
IBPRRIOAP(M,I,Bpsqf,k,&Ld,&td);
if (td != 0) {
IBPRRIOAPSF(M,I,Bpsqf,8,k,&td,&Ld);
td = !Ld;
}
if (td == 0) {
//PushOutputContext(cerr); SWRITE("Ld = "); OWRITE(Ld); SWRITE("\n"); PopOutputContext();
// Filter out all isolating intervals not overlapping (a,b)
/* PushOutputContext(cerr); SWRITE("Before: |Ld| = "); IWRITE(LENGTH(Ld)); SWRITE("\n"); PopOutputContext(); */
Word Leftover = NIL;
for(Word Ldp = Ld; Ldp != NIL; Ldp = RED(Ldp)) {
int tst = ProveNotRoot(B,M,I,a,b,Bp,FIRST(Ldp));
if (!tst)
Leftover = COMP(FIRST(Ldp),Leftover);
}
if (LENGTH(Leftover) == 1) {
Word ap, bp, tb;
FIRST3(FIRST(Leftover),&ap,&bp,&tb);
Jp = LIST5(ap,bp,1,Bpsqf,tb);
/* PushOutputContext(cerr); SWRITE("Successfully found the root of deriviative!"); PopOutputContext(); */
}
else {
// We failed to determine which derivative root is the root of A we are looking for!
/* PushOutputContext(cerr); SWRITE("Failed to find the root of deriviative!"); PopOutputContext(); */
t = 4;
L = NIL;
goto Return;
}
}
}
/* PushOutputContext(cerr); SWRITE("Jp = "); OWRITE(Jp); SWRITE("\n"); PopOutputContext(); */
Ls = COMP(Jp,Ls);
}
L = CINV(Ls);
t = 0;
Return: /* Return L and t. */
if (Q != NULL)
FREEARRAY(Q);
if (A != NULL)
FREEARRAY(A);
*L_ = L;
*t_ = t;
return;
}
/*
IUPSHIFTISPR - Integral univariate polynomial shift, integral similar polynomial result
Inputs:
A : integral univariate polynomial
q : a rational number
Outputs:
B : integral polynomial similar to A(x + q)
Word IUPSHIFTISPR(Word A, Word q)
{
if (q == 0)
return A;
Word a_n = FIRST(q);
Word a_d = SECOND(q);
// construct a_d*y - (a_d*x + a_n)
Word tmp = LIST4(1,LIST2(0,a_d), 0,IPNEG(1,LIST4(1,a_d,0,a_n)));
// construct p_o(x,z) over x,y,z from p_o(x,y) over x,y
Word p_n = NIL;
for(Word A = p_o; A != NIL; A = RED2(A)) {
p_n = COMP(FIRST(A),p_n);
p_n = COMP(LIST2(0,SECOND(A)),p_n);
}
p_n = INV(p_n);
Word B = IPRES(2,p_n,tmp);
return B;
}
*/
// just cherry pick the positive root parts of IPRRID
Word IPRRIDPOS(Word A)
{
Word n,k;
Word Ab,As,I,L,Ls,a,b;
Step1: /* Degree zero. */
n = PDEG(A);
L = NIL;
if (n == 0)
goto Return;
Step2: /* Isolate positive roots. */
Ab = PDBORD(A);
b = IUPPRB(Ab);
if (b == 0)
goto Return;
k = -SECOND(b);
As = IUPBHT(Ab,k);
L = IPRRISD(As,0,b);
Return: /* Prepare for return. */
return(L);
}
// just cherry pick the negative root parts of IPRRID
Word IPRRIDNEG(Word A)
{
Word n,k;
Word Ab,As,I,L,Ls,a,b;
Step1: /* Degree zero. */
n = PDEG(A);
L = NIL;
if (n == 0)
goto Return;
Step4: /* Isolate negative roots. */
Ab = IUPNT(Ab);
b = IUPPRB(Ab);
if (b == 0)
goto Return;
k = -SECOND(b);
As = IUPBHT(Ab,k);
Ls = IPRRISD(As,0,b);
while (Ls != NIL) {
ADV(Ls,&I,&Ls);
FIRST2(I,&a,&b);
I = LIST2(LBRNNEG(b),LBRNNEG(a));
L = COMP(I,L); }
Return: /* Prepare for return. */
return(L);
}
Word IPIISFLBRN(Word A1, Word I1, Word q, Word* J1_);
/*
Inputs:
A : poly in x, y
M : minpoly for root alpha of disc_y(A)
I : isolating interval for alpha
NOTE: alpha is a simple root of disc_y(A)!!!
a,b : LBRNs, an isolating interval for beta, a multiplicity two root of A(alpha,y) (necessarily the only such)
Ap: derivative of A wrt y
K : an isolating interval for a root of Ap(alpha,y)
Outputs:
R : TRUE if we can *prove* that beta is not in K, FALSE otherwise
NOTE: our attempt to prove is just to ensure no roots of A on the permieter of the rectangle
formed by I and (J intersect K).
*/
Word ProveNotRoot(Word A, Word M, Word I, Word a, Word b, Word Ap, Word K)
{
// if (a,b) and K are non-intersecting, return TRUE
Word ap = FIRST(K);
Word bp = SECOND(K);
if (LBRNCOMP(bp,a) <= 0 || LBRNCOMP(b,ap) <= 0)
return TRUE;
// restrict interval: (low,hi) = (a,b) intersect K.
Word low = LBRNCOMP(a,ap) < 0 ? ap : a;
Word hi = LBRNCOMP(b,bp) > 0 ? bp : b;
// I should check whether (low,hi) still contains a root of Ap!
// each rectangle edge creates a univariate polynomial!
Word Abot = IPBREI(2,A,2,LBRNRN(low));
Word Atop = IPBREI(2,A,2,LBRNRN(hi));
Word Aleft = IPBREI(2,A,1,LBRNRN(FIRST(I)));
Word Aright = IPBREI(2,A,1,LBRNRN(SECOND(I)));
// check that Abot and Atop have no roots in I TODO: make these squarefree!
/* Word Lbot = IPRRISD(Abot,FIRST(I),SECOND(I)); */
/* if (Lbot != NIL) return FALSE; */
/* Word Ltop = IPRRISD(Atop,FIRST(I),SECOND(I)); */
/* if (Ltop != NIL) return FALSE; */
Word Lbot = IPRRID(Abot);
for(Word Lp = Lbot; Lp != NIL; Lp = RED(Lp)) {
Word R = FIRST(Lp);
if (IPIISFLBRN(Abot,R,FIRST(I),&R) > 0 && IPIISFLBRN(Abot,R,SECOND(I),&R) < 0)
return FALSE;
}
Word Ltop = IPRRID(Atop);
for(Word Lp = Ltop; Lp != NIL; Lp = RED(Lp)) {
Word R = FIRST(Lp);
if (IPIISFLBRN(Atop,R,FIRST(I),&R) > 0 && IPIISFLBRN(Atop,R,SECOND(I),&R) < 0)
return FALSE;
}
// check that Aleft and Aright have no roots in (low,high) TODO: make these squarefree!
//Word r_low = LBRNRN(low);
//Word C = IUPSHIFTISPR(Aleft,r_low);
//Word newtop = LBRNDIF(hi-low);
Word L = IPRRID(Aleft);
for(Word Lp = L; Lp != NIL; Lp = RED(Lp)) {
Word R = FIRST(Lp);
if (IPIISFLBRN(Aleft,R,low,&R) > 0 && IPIISFLBRN(Aleft,R,hi,&R) < 0)
return FALSE;
}
Word Ls = IPRRID(Aright);
for(Word Lp = Ls; Lp != NIL; Lp = RED(Lp)) {
Word R = FIRST(Lp);
if (IPIISFLBRN(Aright,R,low,&R) > 0 && IPIISFLBRN(Aright,R,hi,&R) < 0)
return FALSE;
}
return TRUE;
}
/*======================================================================
IPIISFLBRN(A1,I1,q;J1,s)
Integral polynomial isolating interval separation from LBRN.
Inputs
A1 : integral univariate polynomial
I1 : logarithmic binary rational isolating intervals for
simple real root alpha_1 of A1
q : logarimic binary rational number
Outputs
J1 : logarithmic binary rational subinterval of I1.
s : s = -1 if alpha_1 < q, s = +1 if alpha_1 > q, s = 0 otherwise
======================================================================*/
#include "saclib.h"
Word IPIISFLBRN(Word A1, Word I1, Word q, Word* J1_)
{
Word a1,b1,c,J1,s, ta, tq;
Step1: /* Get the interval endpoints. */
FIRST2(I1,&a1,&b1);
if (LBRNCOMP(a1,b1) == 0) {
J1 = I1;
s = LBRNCOMP(a1,q);
goto Return;
}
Step2: /* Case that the intervals are already disjoint. */
if (LBRNCOMP(b1,q) <= 0) {
J1 = I1;
s = -1;
goto Return; }
else if (LBRNCOMP(q,a1) <= 0) {
J1 = I1;
s = 1;
goto Return; }
else
s = 0;
ta = IUPBRES(A1,a1);
tq = IUPBRES(A1,q);
if (tq == 0) {
J1 = LIST2(q,q);
s = 0;
}
else if (ta == tq) {
J1 = LIST2(q,b1);
s = 1;
}
else {
J1 = LIST2(a1,q);
s = -1;
}
Return: /* Return J1, J2 and s. */
*J1_ = J1;
return s;
}
|
C
|
int main(){
setlocale(LC_ALL, "portuguese");
float a, b, c; // Lados
printf("Entre com o angulo A: ");
scanf("%f", &a);
printf("Entre com o angulo B: ");
scanf("%f", &b);
printf("Entre com o angulo C: ");
scanf("%f", &c);
if (a + b >= c && a + c >= b && b + c >= a){
if (a < 90 && b < 90 && c < 90) printf("Triângulo acutangulo");
else if (a > 90 || b > 90 || c > 90) printf("Triângulo obtusangulo");
else if (a == 90 || b == 90 || c == 90) printf("Triângulo retangulo");
} else printf("\nNão é possível formar um triângulo.\n");
return 0;
}
|
C
|
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <pthread.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include "nnbc.h"
#include "storage.h"
#include "subscribers.h"
#include "globals.h"
#include "netmap.h"
#include "parse_config.h"
float t1_threshold;
float t2_threshold;
int VERBOSE;
int under_attack;
float t1_epsilon;
float t1_attack_epsilon;
float t2_epsilon;
float t2_attack_epsilon;
float t2_initial_access_multiplier;
char *dbname;
char *dbuser;
char *dbpass;
char *sensor_channel;
char *t1_threshold_channel;
char *t2_threshold_channel;
int
start_threads()
{
__attribute__((unused)) pthread_t thread_id;
thread_id = pthread_create(&thread_id, NULL, &under_attack_listener, NULL);
thread_id = pthread_create(&thread_id, NULL, &t1_thresholds_listener, NULL);
thread_id = pthread_create(&thread_id, NULL, &t2_thresholds_listener, NULL);
return 0;
}
/**
* Return 0 on success, non-zero on error
*/
int
initialize_nnbc(const char* config_file)
{
if (parse_config(config_file)) {
fprintf(stderr, "parse_config failed with file <%s>\n", config_file);
return -1;
}
if (start_threads()) {
fprintf(stderr, "launch_threads failed!");
return -1;
}
if (clear_connections()) {
fprintf(stderr, "First try at clear_connections failed; sleep one second and try again.\n");
sleep(1);
if (clear_connections()) {
fprintf(stderr, "Second try at clear_connections failed; getting on with it.\n");
}
}
return 0;
}
/*
int
enable_streaming(void)
{
int fd = open("/tmp/NNBC_COUNT_CONNECTIONS", O_CREAT, S_IRUSR | S_IWUSR);
if (fd < 0) {
perror("Failed to open/create '/tmp/NNBC_COUNT_CONNECTIONS'");
return -1;
}
close(fd);
return 0;
}
*/
int
nnbc_is_in_whitelist(const char *addr, int len)
{
char address[len+1];
memcpy(address, addr, len);
address[len] = '\0';
return netmap_is_in_whitelist(address);
}
int
nnbc_is_in_proxylist(const char *addr, int len)
{
char address[len+1];
memcpy(address, addr, len);
address[len] = '\0';
return netmap_is_in_proxylist(address);
}
static void
create_entry(char *address, float* t1_score, float* t2_score)
{
if (VERBOSE) {
fprintf(stderr, "client <%s> not in yet in database, adding now\n", address);
}
if (under_attack) {
*t1_score = t1_threshold + t1_attack_epsilon;
*t2_score = t2_threshold + t2_attack_epsilon;
} else {
*t1_score = t1_threshold + t1_epsilon;
*t2_score = 0.0f;
}
if (*t1_score > 0) {
*t1_score = 0;
}
if (*t2_score > 0) {
*t2_score = 0;
}
if (initialize_new_client(address, *t1_score, *t2_score, t2_initial_access_multiplier)) {
fprintf(stderr, "failed to add client <%s> to database\n", address);
}
}
/**
* Return 0 if the client is granted access.
* Return 1 if the client is blocked at the first tier.
* Return 2 if the client is blocked at the second tier.
*/
int
nnbc_get_bin(const char *id, int len)
{
char address[len+1];
memcpy(address, id, len);
address[len] = '\0';
float t1_score, t2_score;
int i = get_scores(address, t2_threshold, &t1_score, &t2_score);
if (i == 1) {
create_entry(address, &t1_score, &t2_score);
}
int result = 0;
if (t1_score < t1_threshold && t2_score > t2_threshold) {
result = 1;
} else if (t2_score < t2_threshold) {
result = 2;
}
if (VERBOSE) {
fprintf(stderr, "Entry: <%s>, t1_score: %.2f, t2_score: %.2f, nnbc_get_bin result: %d\n", address, t1_score, t2_score, result);
}
return result;
}
/**
* Indicate that the client has misbehaved.
* Args:
* weight the amount of the misbehavior. zero is a no-op.
* id the identity of the client that misbehaved.
* len the length of the identity, not including the terminating nil.
*/
void
nnbc_misbehaved(int weight, const char *id, int len)
{
char address[len+1];
memcpy(address, id, len);
address[len] = '\0';
float t1_score, t2_score;
int i = add_to_misbehavior(address, weight, &t1_score, &t2_score);
if (i == 1) {
create_entry(address, &t1_score, &t2_score);
add_to_misbehavior(address, weight, &t1_score, &t2_score);
}
}
/**
* Invoked by software that is checking connection access (i.e.,
* whether or not a socket is allowed). If software invokes this
* method, it MUST invoke disconnected() when the client terminates
* the connection, else the client will be associated with too many
* connections.
*
* Return 0 if the client is granted access.
* Return 1 if the client is blocked at the first tier.
* Return 2 if the client is blocked at the second tier.
*/
int
nnbc_connecting(const char *id, int len)
{
char address[len+1];
memcpy(address, id, len);
address[len] = '\0';
float t1_score, t2_score;
int i = increment_connections(address, &t1_score, &t2_score);
if (i == 1) {
create_entry(address, &t1_score, &t2_score);
}
int result = 0;
if (t1_score < t1_threshold && t2_score > t2_threshold) {
result = 1;
} else if (t2_score < t2_threshold) {
result = 2;
}
if (VERBOSE) {
fprintf(stderr, "Entry: <%s>, t1_score: %.2f, t2_score: %.2f, nnbc_connecting result: %d\n", address, t1_score, t2_score, result);
}
return result;
}
/**
* Invoked by software that is tracking client connections (see
* nnbc_connected() above). Every client that has nnbc_connecting
* invoked for it must also have nnbc_disconnected invoked--and the
* same id must be passed.
*/
void
nnbc_disconnected(const char *id, int len)
{
char address[len+1];
memcpy(address, id, len);
address[len] = '\0';
decrement_connections(address);
return;
}
|
C
|
/** \brief Suma dos numeros float.
*
* \param float primer miembro de la suma.
* \param float segundo miembro de la suma.
* \return float resultado de la suma.
*
*/
float suma(float numeroA, float numeroB)
{
float resultado=0.0;
resultado=numeroA+numeroB;
return resultado;
}
/** \brief Resta dos numeros float.
*
* \param float primer miembro de la resta.
* \param float segundo miembro de la resta.
* \return float resultado de la operacin.
*
*/
float resta(float numeroA, float numeroB)
{
float resultado=0.0;
resultado=numeroA-numeroB;
return resultado;
}
/** \brief Realiza el cociente entre dos nmeros float.
*
* \param float divisor.
* \param float dividendo.
* \return float resultado del cociente.
*
*/
float cociente(float numeroA, float numeroB)
{
float resultado=0.0;
if(numeroB!=0)
{
resultado=numeroA/numeroB;
}
return resultado;
}
/** \brief Calcula el producto de dos nmeros float
*
* \param float primer miembro del producto.
* \param float segundo miembro del producto.
* \return float resultado del producto.
*
*/
float producto(float numeroA, float numeroB)
{
float resultado=0.0;
resultado=numeroA*numeroB;
return resultado;
}
/** \brief Calcula el factorial de un nmero entero
*
* \param numero (int) es el nmero al que se le v a calcular el factorial
* \return el resultado del factorial
*
*/
int factorial(int numero)
{
if(numero==1) //Si el numero es 1, se devuelve el factorial de 1 (1).
{
return 1;
}
else{ //Sino se calcula el factorial del numero-1 y lo multiplico por el numero (recursividad)
return ( numero * factorial(numero-1) );
}
}
|
C
|
#include<stdio.h>
#include<pthread.h>
FILE *fp;
int readflag=0;
int completed=0;
void *thread1(void *arg)
{
fp = fopen("New.txt","r");
char ch;
while(1)
{
if(completed==1)
break;
if(readflag==0)
{
ch = getc(fp);
if(ch==EOF)
{
completed=1;
break;
}
printf("%c",ch);
readflag=1;
}
}
}
void *thread2(void *arg)
{
sleep(1);
char ch;
while(1)
{
if(completed==1)
break;
if(readflag==1)
{
ch = getc(fp);
if(ch==EOF)
{
fclose(fp);
completed=1;
break;
}
printf("%c",ch);
readflag=0;
}
}
}
int main()
{
pthread_t t1,t2;
pthread_create(&t1,NULL,thread1,NULL);
pthread_create(&t2,NULL,thread2,NULL);
pthread_join(t1,NULL);
pthread_join(t2,NULL);
printf("\n");
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
int n, i, tmp, flag;
while (scanf("%d", &n) != EOF && n != 0) {
flag = 0;
for (i = 2; i * i <= n; i ++) {
tmp = i * i;
if (n % tmp == 0) {
flag = 1;
break;
}
}
if (flag == 1) {
printf("Yes\n");
} else {
printf("No\n");
}
}
return 0;
}
|
C
|
#include "bh-sd-gooroom.h"
int main(int argc, char *argv[]) {
int socket_fd;
char buf[OUTPUT_BUF_SIZE];
struct sockaddr_in server_addr;
int n, len;
int signal;
pid_t pid;
int status;
if ((socket_fd = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
fprintf(stderr, "socket creation failed");
exit(EXIT_FAILURE);
}
memset(&server_addr, 0, sizeof(server_addr));
len = sizeof(server_addr);
server_addr.sin_family = AF_INET;
server_addr.sin_addr.s_addr = INADDR_ANY;
server_addr.sin_port = htons(G_EMU_UDP_PORT);
for (;;) {
puts("#########################");
puts("# GCli #");
puts("#=======================#");
puts("# 1: Launch AppA #");
puts("# 2: Stop AppA #");
puts("# 3: Print Log #");
puts("# 4: Quit GCli #");
puts("#=======================#");
puts("# 5: Launch Services #");
puts("# 6: Print Status #");
puts("# 7: Kill Services #");
puts("#########################");
printf("\nCommand: ");
scanf("%d", &signal);
puts ("");
buf[0] = signal + '0';
buf[1] = '\0';
switch (signal) {
case 0: case 1: case 2: case 3:
sendto(socket_fd,
(const char*)buf,
strlen(buf),
MSG_CONFIRM,
(const struct sockaddr*)&server_addr,
sizeof(server_addr));
n = recvfrom(socket_fd,
(char*)buf,
OUTPUT_BUF_SIZE,
MSG_WAITALL,
(struct sockaddr*)&server_addr,
&len);
buf[n] = '\0';
printf("[Result]\n%s\n", buf);
break;
case 4:
goto finish;
break;
case 5:
pid = fork();
if (pid == 0) {
execl("/bin/bash", "/bin/bash", "/home/haru/dbus_project/c/sdbus/scripts/bh_sd_launch_services.sh");
exit(EXIT_SUCCESS);
} else
waitpid(pid, &status, 0);
break;
case 6:
pid = fork();
if (pid == 0) {
execl("/bin/bash", "/bin/bash", "/home/haru/dbus_project/c/sdbus/scripts/bh_sd_status_services.sh");
exit(EXIT_SUCCESS);
} else
waitpid(pid, &status, 0);
break;
case 7:
pid = fork();
if (pid == 0) {
execl("/bin/bash", "/bin/bash", "/home/haru/dbus_project/c/sdbus/scripts/bh_sd_kill_services.sh");
exit(EXIT_SUCCESS);
} else
waitpid(pid, &status, 0);
break;
default:
break;
}
}
finish:
close(socket_fd);
exit(EXIT_SUCCESS);
}
|
C
|
#include <stdio.h>
int main(void) {
printf("%d %d %lfԴϴ.", 1, 2, 1 / 2);
return 0;
}
|
C
|
/**********************************************
* file name: buffer.h
* description: sample memory buffer
*
*********************************************/
//
// remvoe the macro below may case issues when include<stdio.h>
//
#if (defined __USE_XOPEN || defined __USE_XOPEN2K8)
#undef __USE_XOPEN
#undef __USE_XOPEN2K8
#endif
#if (defined __USE_XOPEN || defined __USE_XOPEN2K8)
#undef __USE_XOPEN
#undef __USE_XOPEN2K8
#endif
#include <stdlib.h>
#include <stdio.h>
#include "buffer.h"
#include "log.h"
bool init_buffer(buffer_st* buff)
{
if (NULL == buff) {
Log(stdout, "NULL pointer Exception %s:%d\n", __FILE__, __LINE__);
return false;
}
if (buff->length <= 0) {
Log(stdout, "Buffer length Exception %d %s:%d\n", buff->length, __FILE__, __LINE__);
return false;
}
buff->base = (char*)malloc(buff->length);
if (NULL == buff->base) {
Log(stdout, "Failed malloc memory %s:%d\n", __FILE__, __LINE__);
return false;
}
return true;
}
buffer_st* alloc_buffer(uint32 size)
{
if (size <= 0) {
Log(stdout, "Buffer length Exception %d %s:%d\n", size, __FILE__, __LINE__);
return NULL;
}
buffer_st *buffer = (buffer_st*)malloc(sizeof(buffer_st));
if (NULL == buffer) {
Log(stdout, "Failed malloc memory %s:%d\n", __FILE__, __LINE__);
return NULL;
}
buffer->length = size;
if (init_buffer(buffer)) {
return buffer;
}
else {
return NULL;
}
}
bool free_buffer(buffer_st* buffer)
{
if (NULL != buffer) {
if (NULL != buffer->base) {
free(buffer->base);
buffer->base = NULL;
}
free(buffer);
buffer = NULL;
}
return true;
}
|
C
|
#include <stdio.h>
int main(void) {
// your code goes here
int t;
scanf("%d",&t);
while(t--)
{
long long int n;
scanf("%lld",&n);
long long int a[n],i,pos=0,neg=0,zer=0;
for(i=0;i<n;i++)
{
scanf("%lld",&a[i]);
}
for(i=0;i<n;i++)
{
if(a[i]<0)
neg++;
else if(a[i]>0)
pos++;
else
zer++;
}
if(zer==0 )
{
if(pos>neg && neg!=0)
printf("%lld %lld\n",pos,neg);
else if(pos>neg && neg==0)
printf("%lld %lld\n",pos,pos);
if(neg>pos && pos!=0)
printf("%lld %lld\n",neg,pos);
else if(neg>pos && pos==0)
printf("%lld %lld\n",neg,neg);
}
else
{
if(pos>neg && neg!=0)
printf("%lld %lld\n",pos+zer,neg);
else if(pos>neg && neg==0)
printf("%lld %lld\n",pos+zer,pos);
if(neg>pos && pos!=0)
printf("%lld %lld\n",neg+zer,pos);
else if(neg>pos && pos==0)
printf("%lld %lld\n",neg+zer,neg);
}
}
return 0;
}
|
C
|
#include <stdio.h>
int
isPalindrome(unsigned long n) {
unsigned long nreverse = 0, orign = n;
while (n > 0) {
nreverse = nreverse * 10 + n % 10;
n /= 10;
}
return(orign == nreverse);
}
int
main(void) {
unsigned long palindrome = 0, prod;
int i1, i2;
for (i1 = 99; i1 < 999; ++i1) {
for (i2 = 99; i2 < 999; ++i2) {
prod = i1 * i2;
if (isPalindrome(prod) && palindrome < prod)
palindrome = prod;
}
}
printf("%d\n", palindrome);
return 0;
}
|
C
|
/*
* Copyright 2015 International Business Machines
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/* Description : read_write_disconnect.c
*
* This test performs large numbers of reads and writes using the Test AFU
* but terminates the test without properly shutting down the AFU first.
*/
#include <errno.h>
#include <getopt.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include "libcxl.h"
#include "libcxl_internal.h"
#include "psl_interface_t.h"
#include "TestAFU_config.h"
#include "utils.h"
void usage(char *name)
{
printf("Usage: %s [OPTION]...\n\n", name);
printf(" -s, --seed [SEED] \tseed for random number generation\n");
printf(" -d, --delay [SECONDS]\ttime in seconds to let test run\n");
printf(" --help\tdisplay this help and exit\n\n");
}
void stop_afu(struct cxl_afu_h *afu_h)
{
if (afu_h) {
// Unmap AFU MMIO registers
if(cxl_mmio_unmap(afu_h) < 0) {
printf("FAILED: cxl_mmio_unmap\n");
exit(-1);
}
// Free AFU
cxl_afu_free(afu_h);
}
}
struct cxl_afu_h *start_test(struct cxl_afu_h *afu_h, MachineConfig *machine, char *area, int init)
{
uint16_t command;
uint8_t response;
int i;
// Have each AFU Machine read a unique cacheline in memory area to
// get initial values into AFU
if (init) {
for (i = 0; i < 64; i++) {
if (config_and_enable_machine(afu_h, machine, i, 0,
PSL_COMMAND_READ_CL_NA,
CACHELINE_BYTES, 0, 0,
(uint64_t)area +
CACHELINE_BYTES*i,
CACHELINE_BYTES, 0,
DEDICATED) < 0)
{
printf("FAILED:config_and_enable_machine");
stop_afu(afu_h);
exit(-1);
}
}
}
// Check for valid response
for (i = 0; i < 64; i++) {
if ((response = get_response(afu_h, machine, i, DEDICATED))!=0)
{
printf("FAILED: Unexpected response code 0x%x\n", response);
stop_afu(afu_h);
exit(-1);
}
}
printf("Enabling AFU machine for random read/write commands\n");
// Have each AFU Machine read or write repeatedly to memory area
set_machine_config_enable_always(machine);
for (i = 0; i < 64; i++) {
switch (rand() % 8) {
case 1:
command = PSL_COMMAND_READ_CL_NA;
break;
case 2:
command = PSL_COMMAND_READ_CL_S;
break;
case 3:
command = PSL_COMMAND_READ_CL_M;
break;
case 4:
command = PSL_COMMAND_READ_PNA;
break;
case 5:
command = PSL_COMMAND_WRITE_MI;
break;
case 6:
command = PSL_COMMAND_WRITE_MS;
break;
case 7:
command = PSL_COMMAND_WRITE_INJ;
break;
default:
command = PSL_COMMAND_WRITE_NA;
}
set_machine_config_command_code(machine, command);
set_machine_config_command_size(machine, 0x1 << (rand() % 8));
if (enable_machine(afu_h, machine, i, DEDICATED) < 0) {
printf("FAILED: enable_machine\n");
stop_afu(afu_h);
exit(-1);
}
}
return afu_h;
}
void stop_test(struct cxl_afu_h *afu_h, MachineConfig *machine)
{
int i;
uint8_t response;
// Stop AFU machines
set_machine_config_disable(machine);
for (i = 0; i < 64; i++) {
if(enable_machine(afu_h, machine, i, DEDICATED) < 0) {
stop_afu(afu_h);
exit(-1);
}
}
// Wait for all AFU machines to complete last command
for (i = 0; i < 64; i++) {
if ((response = get_response(afu_h, machine, i, DEDICATED))!=0)
{
printf("FAILED: Unexpected response code 0x%x\n", response);
stop_afu(afu_h);
exit(-1);
}
}
}
struct afu_list {
struct cxl_afu_h *afu;
struct afu_list *_next;
};
void start_iteration(MachineConfig *machine, char *area, unsigned delay,
int init)
{
struct cxl_afu_h *afu_h;
uint64_t wed;
// Find AFU
afu_h = cxl_afu_next(NULL);
// Open AFU
printf("Opening %s\n", cxl_afu_dev_name(afu_h));
if (!afu_h) {
fprintf(stderr, "\nNo AFU found!\n\n");
exit(-1);
}
afu_h = cxl_afu_open_h(afu_h, CXL_VIEW_DEDICATED);
if (!afu_h) {
perror("cxl_afu_open_h");
exit(-1);
}
// Set WED to random value
wed = rand();
wed <<= 32;
wed |= rand();
// Start AFU
cxl_afu_attach(afu_h, wed);
// Map AFU MMIO registers
if ((cxl_mmio_map(afu_h, CXL_MMIO_BIG_ENDIAN)) < 0) {
perror("cxl_mmio_map");
cxl_afu_free(afu_h);
exit(-1);
}
// Start AFU machines
printf("Starting random cacheline accesses\n");
start_test(afu_h, machine, area, init);
// Wait delay seconds while AFU runs
printf("Waiting %d seconds...\n", delay);
fflush(stdout);
sleep(delay);
// Wait for each AFU to complete
printf("Stopping %s\n", cxl_afu_dev_name(afu_h));
stop_afu(afu_h);
}
int main(int argc, char *argv[])
{
MachineConfig machine;
char *area, *name;
unsigned seed;
unsigned delay;
int i, opt, option_index;
name = strrchr(argv[0], '/');
if (name)
name++;
else
name = argv[0];
static struct option long_options[] = {
{"help", no_argument, 0, 'h'},
{"seed", required_argument, 0, 's'},
{"delay", required_argument, 0, 'd'},
{NULL, 0, 0, 0}
};
option_index = 0;
seed = time(NULL);
delay = 1;
while ((opt = getopt_long (argc, argv, "hs:d:",
long_options, &option_index)) >= 0) {
switch (opt)
{
case 0:
break;
case 's':
seed = strtoul(optarg, NULL, 0);
break;
case 'd':
delay = strtoul(optarg, NULL, 0);
break;
case 'h':
default:
usage(name);
return 0;
}
}
// Seed random number generator
srand(seed);
printf("%s: seed=%d\n", name, seed);
// Allocate aligned memory area of 64 cachelines
printf("Allocating and polluting memory area\n");
if (posix_memalign((void **)&area, CACHELINE_BYTES, 64*CACHELINE_BYTES) != 0) {
printf("FAILED:posix_memalign\n");
return 0;
}
// Pollute memory area with random values
for (i = 0; i < 64*CACHELINE_BYTES; i++)
area[i] = rand();
// Initialize machine configuration
init_machine(&machine);
// Run test iterations
start_iteration(&machine, area, delay, 1);
start_iteration(&machine, area, delay, 0);
start_iteration(&machine, area, delay, 0);
// Report if test passed
printf("PASSED\n");
return 0;
}
|
C
|
#include <stdio.h>
void add();
int main ()
{
printf("addition of two nos.");
add();
return 0;
}
void add()
{
int a,b,c;
printf("enter a and b");
scanf("%d%d",&a,&b);
c=a+b;
printf("%d",c);
}
|
C
|
#include<stdio.h>
#include<malloc.h>
struct node {
int id;
struct node * next;
};
struct node *start, *new_node, *ptr;
int main()
{
int n,k, round = 0;
printf("\nEnter the number of players: ");
scanf("%d",&n);
printf("\nEnter the value after which each member is eliminated: ");
scanf("%d",&k);
start = (struct node*)malloc(sizeof(struct node));
start->id = 1;
ptr = start;
for (int i = 2; i <= n; i++)
{
new_node = (struct node*)malloc(sizeof(struct node));
ptr->next = new_node;
new_node->id = i;
new_node->next=start;
ptr=new_node;
}
for (int count = n; count>1; count--)
{
for (int i = 0; i < k-1; i++)
{
ptr=ptr->next;
}
round++;
printf("The player elininated in round %d is %d.\n",round,ptr->next->id);
ptr->next=ptr->next->next;
}
printf("\nPlayer %d is the winner.",ptr->id);
return 0;
}
|
C
|
#pragma once
/**
* Intrusive doubly-linked list.
*
* The list is looped, and when empty its head node must have both
* pointers have the same value pointing to the head.
*/
struct list
{
struct list *prev;
struct list *next;
};
#define list_head(head) \
{ \
.prev = &head, .next = &head \
}
/**
* Inserts new element into the list.
* @return new list head.
*/
struct list *list_insert (struct list *, struct list *);
/**
* Remove element from the list.
* @return new list head or NULL.
*/
struct list *list_remove (struct list *);
|
C
|
#include<stdio.h>
int divisible(int num1, int num2);
int main()
{
int num1, num2;
printf("Enter range numbers: ");
scanf("%d%d", &num1, &num2);
divisible(num1,num2);
}
int divisible(int num1, int num2)
{
int i, count1=0, count2=0;
for (i = num1; i < num2; i++)
{
if (i % 5 == 0)
{
count1++;
}
if(i % 7 == 0)
{
count2++;
}
}
printf("Number of integers divisible by 5 between %d and %d = %d\n", num1, num2, count1);
printf("Number of integers divisible by 7 between %d and %d = %d\n", num1, num2, count2);
}
|
C
|
#ifndef SERVEUR_H /* Include guard */
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <stdint.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <pthread.h>
#include <signal.h>
#include <semaphore.h>
#include <dirent.h>
#include <ctype.h>
#include <fcntl.h>
#define SERVEUR_H
struct CLIENT{
int dSC;
int dSF;
char pseudo[100];
pthread_t thread;
char salon[100];
};
struct SALON {
char nom_salon[100];
char description[200];
int nb_connecte;
int capacite;
int admin; // 1 si on autorise la suppression/modification du salon , 0 sinon
};
/* GENERAL METHODS */
/**
* @brief fonction qui envoie un message
* @param socket, buffer
* @return -1 si erreur envoi 0 si pas d'envoi et 1 en cas de succes
*/
int envoi(int socket, char* buffer);
/**
* @brief fonction qui permet d'obtenir le numero associe a la commande tapee
* @param command
* @return le numero associe a la commande tapee
*/
int command_id(char* command);
/**
* @brief fonction qui gere le lien entre le client et tous les autres
* @param *args correspond au client
*
*/
void *transmission(void *args);
/**
* @brief fonction main qui initialise tout le serveur
*
*
*/
int main(int argc, char* argv[]);
/**
* @brief fonction qui ouvre le readme
*
*
*/
void open_readme();
/**
* @brief fonction qui retourne le nombre d'arguments minimum lies a une fonction
* @param msg[], mini
* @return nombre arguments minimum
*/
int arg_minimum(char msg[],int mini);
/* USERS METHODS */
/**
* @brief fonction qui permet de supprimer un client
* @param *c : client a supprimer
*
*/
void supprimer_client(struct CLIENT *c);
/* FILES METHODS */
/**
* @brief fonction qui permet de telecharger un fichier
*
*
*/
void* get_file();
/**
* @brief fonction qui transfere un fichier envoye par le premier client a l'autre client
* @param CLIENT *src, CLIENT *dest, file_name[], message[]
*
*/
void transmit_file(struct CLIENT *src, struct CLIENT *dest, char file_name[], char message[]);
/* ROOMS METHODS */
/**
* @brief fonction qui retourne l'id du salon
* @param nom_salon[] : nom du salon
* @return l'id du salon
*/
int recherche_tab_salon(char nom_salon[]);
/**
* @brief fonction qui initialise tous les salons enregistrés à partir d'un fichier
*/
void init_salon();
/**
* @brief fonction qui permet de retirer un salon de la liste des salons du fichier
* @param nom_salon[] : nom du salon
*
*/
void save_salon(char nom_salon[]);
/**
* @brief fonction qui permet de retirer un salon de la liste des salons du fichier
* @param nom_salon[] : nom du salon
*
*/
void unsave_salon(char nom_salon[]);
/**
* @brief fonction qui sauvegarde la liste des derniers messages envoyés
* @param last_message[], nom_salon[]
*
*/
void save_last_messages(char last_message[], char nom_salon[]);
/**
* @brief fonction qui recupere les 10 derniers messages d'un salon
* @param last_messages[] : 10 derniers messages, nom_salon[] : nom du salon
* @return le nombre de messages
*/
int get_last_messages(char* last_messages[], char nom_salon[]);
/**
* @brief fonction qui permet d'ajouter un utilisateur dans un salon
* @param CLIENT *c, nom_salon[]
*
*/
void *add_to_salon(struct CLIENT *c, char nom_salon[]);
/**
* @brief fonction qui permet de retirer un utilisateur d'un salon
* @param CLIENT *c, nom_salon[]
*
*/
void *remove_from_salon(struct CLIENT *c, char nom_salon[]);
/**
* @brief fonction qui retourne si le salon a bien été cree ou les erreurs si ce n'est pas le cas
* @param nom_salon[], capa, description[], admin
* @return 0 or -1 or -2 (en fonction de l'erreur)
*/
int nouveau_salon(char nom_salon[], int capa, char description[],int admin);
/**
* @brief fonction qui retourne si le salon a bien ete modifie ou les erreurs si ce n'est pas le cas
* @param nom_salon[] : nom du salon a modifie
* @return 0 or -1 or -2 (en fonction de l'erreur)
*/
int modif_salon(char salon_base[],char new_nom_salon[], int new_capa, char new_description[]);
/**
* @brief fonction qui retourne si le client a bien rejoint le salon ou les erreurs si ce n'est pas le cas
* @param nom_salon[] : nom du salon a rejoindre
* @return 0 or -1 or -2 (en fonction de l'erreur)
*/
int rejoindre_salon(struct CLIENT *c,char nom_salon[]);
/**
* @brief fonction qui retourne si le salon a bien été supprime ou les erreurs si ce n'est pas le cas
* @param nom_salon[] : nom du salon a supprimer
* @return 0 or -1 or -2 (en fonction de l'erreur)
*/
int supprime_salon(char nom_salon[]);
#endif // SERVEUR_H
|
C
|
// 7**0 = 1 - 1
// 7**1 = 7 - 7
// 7**2 = 49 - 9
// 7**3 = 343 - 3
// 7**4 = 2401 - 1
// 7**5 = 16807 - 7
// 7**6 = 117649 - 9
// 7**7 = 823543 - 3
// 7**8 = 5764801 - 1
// O ciclo se repete a cada a cada 4 pulos...
// Então, temos a sequencia [ 1,7,9,3 ] (?).
// O expoente % 4 nos daria o index do valor esperado da exponenciação
#include <stdio.h>
int main (int args){
unsigned long long n, cases;
char sequence[] = { 1, 7, 9, 3 };
scanf("%llu", &cases);
while (cases--)
scanf("%llu", &n), printf("%hhd\n", sequence[n % 4]);
return 0;
}
|
C
|
//二级指针字符串
#include<stdio.h>
#include <string.h>
void change(char **str);
char str1[20] ="notepad";
char str2[20] ="calc";
int main()
{
char *p =str1;
printf("p in main:p= %p,str1=%p\n",p,str1); //p in main: 00403008,00403008
change(&p); //change把p的指向给改变,等价于p=str2
printf("after change: p=%s,p=%p\n",p,p); //after change: calc,0040301c
}
void change(char **str)
{ //函数有副本机制,会新建一个二级指针变量str来存储main函数中p传过来str1的首地址
printf("str in change:*str=%p str= %p,str2=%p \n",*str,str,str2); //str in change: 00403008,0040301C
//char *p=str2;
//str=&p;这个只是改变了str的指向,但是*str 还是没改变的
*str =str2; // *str就相当于一级指针 char * 用来改变main中p指针变量自己的首地址 *str=p=str2
printf("change:str=%s,str=%p\n",*str,*str); //change:calc,0040301c
}
|
C
|
/*****************************************************
*@file DirectionControl.c
*
*@core K60FX
*@date 2019
******************************************************/
#include "include.h"
/**********ȫֱ********/
float Direction_P = 10; //P PƫӦ ת估ʱǹ˾ӦP
float Direction_D = 10; //D
float Direction_PZJ = 30;
float Direction_DZJ = 10;
float Direction_PHD = 30;
float Direction_DHD = 10;
float DirectionErr[(AD_MAX>>1)-1][SENSOR_SIZE] = {0}; //ƫg_fDirectionError[0]ΪһˮƽеIJȺƫ 0ͭ࣡
//ǰΪһֺͰֵеIJȺͣҰŴߵм һֱIJȺ
//g_fDirectionError[1]ΪһԴֱеIJȺƫ
float DirectionErr_dot[8] = {0};//ƫ֣g_fDirectionError_dot[0]ΪһˮƽеIJȺƫ֣
//g_fDirectionError_dot[1]ΪһԴֱеIJȺƫ)
uint16 sensor[10][SENSOR_SIZE]={0}; //ȡĵֵ
uint32 Servo_PWM_now = SERVO_CENTER,Servo_PWM_old = SERVO_CENTER;
/********/
int Servo_PWM = 0,old_Servo_PWM = 0;
int HD_HOLD = 0;
int HD_FLAG = 0;
int ZJ_HOLD = 0;
/***ݳʼ***/
void Direction_Data_Update(void){
for(int i=SENSOR_SIZE-1;i>=1;i--){ //ϴεֵƴ洢
for(int j = 1;j<=((AD_MAX>>1)-1);j++){
DirectionErr[j-1][i] = DirectionErr[j-1][i-1];
}
}
for(int i = SENSOR_SIZE;i>=1;i--)DirectionErr_dot[i] =DirectionErr_dot[i-1];
for(ADC_e i = ADP1;i<AD_MAX;i++){ //ϴεֵƴ洢
for(int j = SENSOR_SIZE-1;j>=1;j--){
sensor[i][j] = sensor[i][j-1];
}
}
Read_ADC(); //ȡµֵ
for(ADC_e i = ADP1; i < AD_MAX; i++)sensor[i][0] = (sensor[i][0]<10?10:sensor[i][0]);// Ǽ˲
for(int i = 0;i<((AD_MAX>>1)-2);i++){ //ˮƽӰֵIJȺ
DirectionErr[i][0] = (my_sqrt((float)(sensor[i][0]),0)-my_sqrt((float)(sensor[ADP6-i][0]),0))/(sensor[i][0] + sensor[ADP6-i][0]) * 1000;
}
DirectionErr[(AD_MAX>>1)-2][0] = ((my_sqrt((float)(sensor[ADVR-1][0]),0)-my_sqrt((float)(sensor[ADVR+1][0]),0))/(sensor[ADVR-1][0] + sensor[ADVR+1][0])) * 1000;
}
/****ƺ****/
/**
*С0ʱ,ƫ,ҪҴ
*0ʱ,ƫ,Ҫ
*/
void Direction_Control2(void){
/****ͣ****/
if((sensor[ADPR][0]<40&&my_abs(DirectionErr[2][0])<40)&&sensor[ADVR][0]<20){ //ʹȷ //һֲȺΪ0ʱĵֵСΪ sensor[ADPR][0]<100&&DirectionErr[2][0]<40
Stop_Count++;
if(Stop_Count>=100){
Stop_Flag = 1; //ͣ
SAIDAO_FLAG = STOP;
}
lcd_showuint8(30,9,9);
}
else{
if(HD_HOLD!=0)SAIDAO_FLAG = HD; //HDرʹΪHD
else SAIDAO_FLAG = SAIDAO_MAX; //ͷˢ£жʱжάһεpwm
lcd_showuint8(30,9,22);
Stop_Count = 0;
}
/***ʮ>>ֱ**/
if(SAIDAO_FLAG != STOP&&HD_HOLD == 0){ //رʹ STOP ʱ
/***ж**/
if(sensor[ADPR][0]<40&&DirectionErr[2][0]<40&&sensor[ADVR][0]<20){ //MISS
SAIDAO_FLAG = MISS;
//Stop_Count = 0; //Stop־
}else if(sensor[ADV1][0]>140&&sensor[ADV2][0]>140){ //ʮ
SAIDAO_FLAG = SZ;
lcd_showuint8(30,9,44);
}else if(((sensor[ADP2][0]>=120&&sensor[ADP5][0]>=120))&&(sensor[ADPR][0]>=240)) //л //οл //sensor[ADP2][0]>=240&&sensor[ADP5][0]>=160)||(sensor[ADP5][0]>=240&&sensor[ADP2][0]>=160)
{
SAIDAO_FLAG = HD;
if(HD_FLAG == 0){ //ֻһΣHD_HOLDرʹ
//뻷ź źcommon ڽҲпܱ
if(sensor[ADV1][0]>sensor[ADV2][0]){
HD_FLAG = 1;
HD_HOLD = 1;
lcd_showuint8(30,9,12);
}
else if(sensor[ADV1][0]<sensor[ADV2][0]){
HD_FLAG = 1;
HD_HOLD = -1;
lcd_showuint8(30,9,22);
}
else if(sensor[ADP2][0]>sensor[ADP5][0]){
HD_FLAG = 1;
HD_HOLD = 1;
lcd_showuint8(30,9,12);
}
else if(sensor[ADP2][0]<sensor[ADP5][0]){
HD_FLAG = 1;
HD_HOLD = -1;
lcd_showuint8(30,9,22);
}
else{
SAIDAO_FLAG = COMMON; //ֱӦˮƽѭ
lcd_showuint8(30,9,42);
}
}else{ //
SAIDAO_FLAG = COMMON;
lcd_showuint8(30,9,32);
}
}else if(((sensor[ADV1][0]>140&&sensor[ADV2][0]<20)||(sensor[ADV1][0]<20&&sensor[ADV2][0]>140))&&sensor[ADPR][0]<100){ //ֱ
SAIDAO_FLAG = ZJ;
if(sensor[ADV1][0]>30)ZJ_HOLD = 1;
else if(sensor[ADV2][0]>30)ZJ_HOLD = -1;
lcd_showuint8(30,9,33);
}else if(sensor[ADPR][0]>100&&(sensor[ADP3][0]>20||sensor[ADP4][0]>20)){ //COMMON //sensor[ADV1][0]<60&&sensor[ADV2][0]<60&&
//if(SAIDAO_FLAG ==ZJ)SAIDAO_FLAG = HD;
if(SAIDAO_FLAG ==ZJ)SAIDAO_FLAG = ZJ; //ֱǴԼͷŻʱֱ״̬
else{
if((sensor[ADP2][1]>=240||sensor[ADP5][1]>=160)&&HD_FLAG == 1){ //ճʱ뻷ź
HD_FLAG = 0;
}
SAIDAO_FLAG = COMMON;
ZJ_HOLD = 0;
}
lcd_showuint8(30,9,0);
}
}
/**************************************************/
//
Servo_PWM_old = Servo_PWM_now;
if(SAIDAO_FLAG == STOP){
// = 0;
//PWM_Out();
lcd_showuint8(0,9,101);
Servo_PWM_now = Servo_PWM_old;
}
else if(SAIDAO_FLAG == SAIDAO_MAX){
if( Servo_PWM_old>SERVO_CENTER){
Servo_PWM_now = SERVO_MAX;
}
else if( Servo_PWM_old<SERVO_CENTER){
Servo_PWM_now = SERVO_MIN;
}
}
else if(SAIDAO_FLAG == COMMON){
//float servo_pwm_delta = 0;
//servo_pwm_delta = Direction_P*(DirectionErr[3][0] - DirectionErr[3][1]) + (DirectionErr[3][2]-2*DirectionErr[3][1]+DirectionErr[3][0])*Direction_D;
Servo_PWM_now = SERVO_CENTER - Direction_P*DirectionErr[2][0] - (DirectionErr[2][0]-DirectionErr[2][1])*Direction_D; //λʽ //ͨˮƽPD
//Servo_PWM_now = Servo_PWM_n ow - servo_pwm_delta;
//Servo_PWM_now = SERVO_CENTER - Direction_P*DirectionErr[2][0];
}
else if(SAIDAO_FLAG == HD){
if(sensor[ADP2][0]>=120&&sensor[ADP5][0]>=120){//۲ǷΪHD//if(sensor[ADVR][0]>10){ //ֱ뻷
if(HD_HOLD>0){
//DirectionErr[1][0]=(mysqrt((float)(sensor[ADVR][0]),0)-my_sqrt((float)(sensor[ADV1][0]),0))/(sensor[ADVR][0] + sensor[ADV1][0]) * 1000; //ֱһ
Servo_PWM_now = 5900 - Direction_PHD*DirectionErr[2][0] - (DirectionErr[2][0] - DirectionErr[2][1])*Direction_DHD;
}
else if(HD_HOLD<0){
//DirectionErr[1][0]=(my_sqrt((float)(sensor[ADV2][0]),0)-my_sqrt((float)(sensor[ADVR][0]),0))/(sensor[ADV2][0] + sensor[ADVR][0]) * 1000; //ֱ
Servo_PWM_now = 7400 - Direction_PHD*DirectionErr[2][0] - (DirectionErr[2][0] - DirectionErr[2][1])*Direction_DHD;
}
}else{
HD_HOLD = 0 ;//HDرʹܱ־
}
}
else if(SAIDAO_FLAG == MISS){
if(ZJ_HOLD!=0){ //屣
Stop_Count = 0;
if(ZJ_HOLD == 1)Servo_PWM_now = SERVO_MIN;
else Servo_PWM_now = SERVO_MAX;
}
else if(HD_HOLD!=0){ //
if(HD_HOLD > 0)Servo_PWM_now = SERVO_MIN;
else Servo_PWM_now = SERVO_MAX;
}
else{ //
if( Servo_PWM_old>SERVO_CENTER){
Servo_PWM_now = SERVO_MAX;
}
else if( Servo_PWM_old<SERVO_CENTER){
Servo_PWM_now = SERVO_MIN;
}
}
}
else if(SAIDAO_FLAG == ZJ){
if(ZJ_HOLD == -1)Servo_PWM_now = SERVO_MAX- Direction_PZJ*DirectionErr[3][0] - (DirectionErr[3][0]-DirectionErr[3][1])*Direction_DZJ;
if(ZJ_HOLD == 1)Servo_PWM_now = SERVO_MIN- Direction_PZJ*DirectionErr[3][0] - (DirectionErr[3][0]-DirectionErr[3][1])*Direction_DZJ;
}else if(SAIDAO_FLAG == SZ){
Servo_PWM_now = SERVO_CENTER - Direction_P*DirectionErr[2][0] - (DirectionErr[2][0]-DirectionErr[2][1])*Direction_D;
}
if(Servo_PWM_now>SERVO_MAX)Servo_PWM_now = SERVO_MAX;
else if(Servo_PWM_now<SERVO_MIN)Servo_PWM_now = SERVO_MIN;
//Setted_Speed = 340;
ServoPWM(Servo_PWM_now);
}
/****lcdʾ*****/
void Direction_Control(void){
/****ͣ****/
if((sensor[ADPR][0]<40&&my_abs(DirectionErr[2][0])<40)&&sensor[ADVR][0]<20){ //ʹȷ //һֲȺΪ0ʱĵֵСΪ sensor[ADPR][0]<100&&DirectionErr[2][0]<40
Stop_Count++;
if(Stop_Count>=10){
Stop_Flag = 1; //ͣ
SAIDAO_FLAG = STOP;
}
//lcd_showuint8(30,9,9);
}
else{
if(HD_HOLD!=0)SAIDAO_FLAG = HD; //HDرʹΪHD
else SAIDAO_FLAG = SAIDAO_MAX; //ͷˢ£жʱжάһεpwm
//lcd_showuint8(30,9,22);
Stop_Count = 0;
}
/***ʮ>>ֱ**/
if(SAIDAO_FLAG != STOP&&HD_HOLD == 0){ //رʹ STOP ʱ
/***ж**/
if(sensor[ADPR][0]<40&&DirectionErr[2][0]<40&&sensor[ADVR][0]<20){ //MISS
SAIDAO_FLAG = MISS;
//Stop_Count = 0; //Stop־
}else if(sensor[ADV1][0]>140&&sensor[ADV2][0]>140){ //ʮ
SAIDAO_FLAG = SZ;
//lcd_showuint8(30,9,44);
}else if(((sensor[ADP2][0]>=120&&sensor[ADP5][0]>=120))&&(sensor[ADPR][0]>=240)) //л //οл //sensor[ADP2][0]>=240&&sensor[ADP5][0]>=160)||(sensor[ADP5][0]>=240&&sensor[ADP2][0]>=160)
{
SAIDAO_FLAG = HD;
if(HD_FLAG == 0){ //ֻһΣHD_HOLDرʹ
//뻷ź źcommon ڽҲпܱ
if(sensor[ADV1][0]>sensor[ADV2][0]){
HD_FLAG = 1;
HD_HOLD = 1;
//lcd_showuint8(30,9,12);
}
else if(sensor[ADV1][0]<sensor[ADV2][0]){
HD_FLAG = 1;
HD_HOLD = -1;
//lcd_showuint8(30,9,22);
}
else if(sensor[ADP2][0]>sensor[ADP5][0]){
HD_FLAG = 1;
HD_HOLD = 1;
//lcd_showuint8(30,9,12);
}
else if(sensor[ADP2][0]<sensor[ADP5][0]){
HD_FLAG = 1;
HD_HOLD = -1;
//lcd_showuint8(30,9,22);
}
else{
SAIDAO_FLAG = COMMON; //ֱӦˮƽѭ
//lcd_showuint8(30,9,42);
}
}else{ //
SAIDAO_FLAG = COMMON;
//lcd_showuint8(30,9,32);
}
}else if(((sensor[ADV1][0]>140&&sensor[ADV2][0]<20)||(sensor[ADV1][0]<20&&sensor[ADV2][0]>140))&&sensor[ADPR][0]<100){ //ֱ
SAIDAO_FLAG = ZJ;
if(sensor[ADV1][0]>30)ZJ_HOLD = 1;
else if(sensor[ADV2][0]>30)ZJ_HOLD = -1;
//lcd_showuint8(30,9,33);
}else if(sensor[ADPR][0]>100&&(sensor[ADP3][0]>20||sensor[ADP4][0]>20)){ //COMMON //sensor[ADV1][0]<60&&sensor[ADV2][0]<60&&
//if(SAIDAO_FLAG ==ZJ)SAIDAO_FLAG = HD;
if(SAIDAO_FLAG ==ZJ)SAIDAO_FLAG = ZJ; //ֱǴԼͷŻʱֱ״̬
else{
if((sensor[ADP2][1]>=240||sensor[ADP5][1]>=160)&&HD_FLAG == 1){ //ճʱ뻷ź
HD_FLAG = 0;
}
SAIDAO_FLAG = COMMON;
ZJ_HOLD = 0;
}
//lcd_showuint8(30,9,0);
}
}
/**************************************************/
//
Servo_PWM_old = Servo_PWM_now;
if(SAIDAO_FLAG == STOP){
// = 0;
//PWM_Out();
//lcd_showuint8(0,9,101);
Servo_PWM_now = Servo_PWM_old;
}
else if(SAIDAO_FLAG == SAIDAO_MAX){
if( Servo_PWM_old>SERVO_CENTER){
Servo_PWM_now = SERVO_MAX;
}
else if( Servo_PWM_old<SERVO_CENTER){
Servo_PWM_now = SERVO_MIN;
}
}
else if(SAIDAO_FLAG == COMMON){
//float servo_pwm_delta = 0;
//servo_pwm_delta = Direction_P*(DirectionErr[3][0] - DirectionErr[3][1]) + (DirectionErr[3][2]-2*DirectionErr[3][1]+DirectionErr[3][0])*Direction_D;
Servo_PWM_now = SERVO_CENTER - Direction_P*DirectionErr[2][0] - (DirectionErr[2][0]-DirectionErr[2][1])*Direction_D; //λʽ //ͨˮƽPD
//Servo_PWM_now = Servo_PWM_n ow - servo_pwm_delta;
//Servo_PWM_now = SERVO_CENTER - Direction_P*DirectionErr[2][0];
}
else if(SAIDAO_FLAG == HD){
if(sensor[ADP2][0]>=120&&sensor[ADP5][0]>=120){//۲ǷΪHD//if(sensor[ADVR][0]>10){ //ֱ뻷
if(HD_HOLD>0){
//DirectionErr[1][0]=(mysqrt((float)(sensor[ADVR][0]),0)-my_sqrt((float)(sensor[ADV1][0]),0))/(sensor[ADVR][0] + sensor[ADV1][0]) * 1000; //ֱһ
Servo_PWM_now = 5900 - Direction_PHD*DirectionErr[2][0] - (DirectionErr[2][0] - DirectionErr[2][1])*Direction_DHD;
}
else if(HD_HOLD<0){
//DirectionErr[1][0]=(my_sqrt((float)(sensor[ADV2][0]),0)-my_sqrt((float)(sensor[ADVR][0]),0))/(sensor[ADV2][0] + sensor[ADVR][0]) * 1000; //ֱ
Servo_PWM_now = SERVO_MAX - Direction_PHD*DirectionErr[2][0] - (DirectionErr[2][0] - DirectionErr[2][1])*Direction_DHD;
}
}else{
HD_HOLD = 0 ;//HDرʹܱ־
}
}
else if(SAIDAO_FLAG == MISS){
if(ZJ_HOLD!=0){ //屣
Stop_Count = 0;
if(ZJ_HOLD == 1)Servo_PWM_now = SERVO_MIN;
else Servo_PWM_now = SERVO_MAX;
}
else if(HD_HOLD!=0){ //
if(HD_HOLD > 0)Servo_PWM_now = SERVO_MIN;
else Servo_PWM_now = SERVO_MAX;
}
else{ //
if( Servo_PWM_old>SERVO_CENTER){
Servo_PWM_now = SERVO_MAX;
}
else if( Servo_PWM_old<SERVO_CENTER){
Servo_PWM_now = SERVO_MIN;
}
}
}
else if(SAIDAO_FLAG == ZJ){
if(ZJ_HOLD == -1)Servo_PWM_now = SERVO_MAX- Direction_PZJ*DirectionErr[3][0] - (DirectionErr[3][0]-DirectionErr[3][1])*Direction_DZJ;
if(ZJ_HOLD == 1)Servo_PWM_now = SERVO_MIN- Direction_PZJ*DirectionErr[3][0] - (DirectionErr[3][0]-DirectionErr[3][1])*Direction_DZJ;
}else if(SAIDAO_FLAG == SZ){
Servo_PWM_now = SERVO_CENTER - Direction_P*DirectionErr[2][0] - (DirectionErr[2][0]-DirectionErr[2][1])*Direction_D;
}
if(Servo_PWM_now>SERVO_MAX)Servo_PWM_now = SERVO_MAX;
else if(Servo_PWM_now<SERVO_MIN)Servo_PWM_now = SERVO_MIN;
//Setted_Speed = 340;
ServoPWM(Servo_PWM_now);
}
void Read_ADC(){
My_adc_once(ADC_8bit);//&&(ÿвɼ5)
//=================ֵ˲============================
for(ADC_e i = ADP1;i < AD_MAX; i++){//һֵ
ad_val[i][0] = (ad_val[i][2]+ad_val[i][3]+ad_val[i][4])/3; //ֵ˲
sensor[i][0] = (uint16)(ad_val[i][0]/10*10); //ʱȴ.ps:Ժõ(13)
//֮ҪȴΪӲȵƣڸֵϵͳƵ
//Ҫ
//sensor_p[i] = ad_p[i][0];
}
}
|
C
|
/*
27 - 29
*/
#include <stdio.h>
int main(void)
{
{
unsigned char a = 0x46; // 01000110b
unsigned char b = 0x44; // 01000100b
unsigned char mask = 0x06; // 00000110b
printf("a & mask %x, res %d\n", a & mask, (a & mask) == mask);
printf("b & mask %x, res %d\n", b & mask, (b & mask) == mask);
}
{
unsigned char a = 0x46; // 01000110b
unsigned char mask_1 = 0xbf; // 10111111b
unsigned char mask_2 = 0xf9; // 11111001b
printf("a & mask_1 %x\n", a & mask_1);
printf("a & mask_2 %x\n", a & mask_2);
}
{
unsigned char a = 0x40; // 01000000b
unsigned char mask_1 = 0x06; // 00000110b
unsigned char mask_2 = 0x44; // 01000100b
printf("a | mask_1 %x\n", a | mask_1);
printf("a | mask_2 %x\n", a | mask_2);
}
{
unsigned char a = 0x46; // 01000110b
unsigned char mask_1 = 0x44; // 01000100b
unsigned char mask_2 = 0xFF; // 11111111b
printf("a ^ mask_1 %x\n", a ^ mask_1);
printf("a ^ mask_2 %x\n", a ^ mask_2);
}
{
unsigned char a = 0xFF; // 11111111b
printf("a >> 1 = %2x\n", a >> 1);
printf("a >> 4 = %2x\n", a >> 4);
}
{
unsigned char a = 0x01; // 00000001b
printf("a << 1 = %2x\n", a << 1);
printf("a << 4 = %2x\n", a << 4);
}
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_backtraking_fillit.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: mbelalou <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2017/12/15 16:18:21 by mbelalou #+# #+# */
/* Updated: 2017/12/20 18:09:28 by mbelalou ### ########.fr */
/* */
/* ************************************************************************** */
#include "fillit_p_2.h"
static int ft_sqrt_fillit(int nbr)
{
int result;
result = 0;
if (nbr <= 0)
return (0);
while ((result * result) < nbr)
result++;
return (result - 1);
}
static int ft_get_dim_mat(int nbr_tetri)
{
if (nbr_tetri <= 0)
return (0);
return (ft_sqrt_fillit(nbr_tetri * 4) + 1);
}
static char **ft_init_mat(int dim_mat_result)
{
char **mat_result;
int i;
i = 0;
if (dim_mat_result < 2)
return (0);
mat_result = (char **)malloc((dim_mat_result + 1) * sizeof(mat_result));
if (mat_result == NULL)
return (0);
while (i < dim_mat_result)
{
mat_result[i] = ft_strnew(dim_mat_result);
if (mat_result[i] == NULL)
return (0);
ft_memset(mat_result[i], '.', dim_mat_result);
i++;
}
mat_result[i] = NULL;
return (mat_result);
}
char **ft_backtracking_fillit(t_tetri *lst_tetri, int nbr_tetri)
{
int dim_mat_result;
char **mat_result;
dim_mat_result = ft_get_dim_mat(nbr_tetri);
mat_result = NULL;
mat_result = ft_init_mat(dim_mat_result);
while (!ft_put_tetri_mat(&mat_result, lst_tetri, dim_mat_result))
{
ft_memdel((void**)mat_result);
dim_mat_result++;
mat_result = ft_init_mat(dim_mat_result);
}
return (mat_result);
}
|
C
|
#include "stdio.h"
struct venky
{
int mar;
float per;
char gd;
};
union siri
{
int mar;
float per;
char gd;
};
main()
{
struct venky v;
v.mar=500;
v.per=300;
v.gd='A';
printf("mar:%d\n per:%f\n gd:%c\n",v.mar,v.per,v.gd);
printf("size of struct:%d\n",sizeof(struct venky));
printf("add of mar:%u\n add of per:%u\n add of gd:%u\n",&v.mar,&v.per,&v.gd);
union siri s;
s.mar=300;
s.per=300;
s.gd='A';
printf("mar:%d\n per:%f\n gd:%c\n",s.mar,s.per,s.gd);
//printf("mar:%d\n gd:%c\n",s.mar,s.gd);
printf("size of union:%d\n",sizeof(union siri));
printf("add of mar:%u\n add of per:%u\n add of gd:%u\n",&s.mar,&s.per,&s.gd);
//printf("add of mar:%u\n add of gd:%u\n",&s.mar,&s.gd);
}
|
C
|
#include<stdio.h>
#include<stdlib.h>
int main()
{
char* pmem;
printf("sizeof(int)의 길이는 %ld 입니다. \n",sizeof(int));
pmem = calloc(100,sizeof(int));
if(pmem == NULL)
puts("메모리 할당에 실패하였습니다.");
else{
puts("int형변수 100개 할당에 성공하였습니다.");
printf("%ld \n",sizeof(pmem));
free(pmem);
}
}
|
C
|
*
* * *
* * * *
Imprime o mesmo padrão, porém com dez linha e dezenove colunas
#include <stdio.h>
main ()
{
int c,l, i;
{
for (l=1, l<=19; l**) putchar ('*');
putchar ('n');
}
return=0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
int main()
{
int a;
int b;
int c;
int d;
scanf("%d %d %d %d", &a, &b, &c, &d);
printf("%d \n",a);
printf("%d \n",b);
printf("%d \n",c);
printf("%d \n",d);
return 0;
}
|
C
|
#include <stdio.h>
#include <string.h>
#include <microhttpd.h>
#include <wait.h>
#include "frontend.h"
#include "httpserver.h"
#include "types.h"
#include "storage.h"
#include "routes.h"
#define ROUTES_COUNT 5
struct Route routes[ROUTES_COUNT];
int handle_add_channel(struct Request *request, struct Response *response, struct Channel **channel) {
if (!strlen(request->name) || !strlen(request->password))
return MHD_HTTP_BAD_REQUEST;
*channel = add_channel(request->name, request->password);
if (!*channel)
return MHD_HTTP_INTERNAL_SERVER_ERROR;
response->buffer = malloc(16);
if (!response->buffer){
perror("malloc failed");
return MHD_HTTP_INTERNAL_SERVER_ERROR;
}
sprintf(response->buffer, "id:%d", (*channel)->id);
response->buffer_size = strlen(response->buffer);
return MHD_HTTP_CREATED;
}
int handle_add_post(struct Request *request, struct Response *response, struct Channel **channel) {
if (!strlen(request->text))
return MHD_HTTP_BAD_REQUEST;
char *text = malloc(strlen(request->text) + 1);
if (!text){
perror("malloc failed");
return MHD_HTTP_INTERNAL_SERVER_ERROR;
}
strcpy(text, request->text);
if (!add_post(*channel, text))
return MHD_HTTP_INTERNAL_SERVER_ERROR;
return MHD_HTTP_CREATED;
}
int handle_get_key(struct Request *request, struct Response *response, struct Channel **channel) {
response->buffer = (*channel)->key;
response->buffer_size = KEY_SIZE;
return MHD_HTTP_OK;
}
int handle_change_password(struct Request *request, struct Response *response, struct Channel **channel) {
if (!strlen(request->new_password))
return MHD_HTTP_BAD_REQUEST;
change_password(*channel, request->new_password);
return MHD_HTTP_OK;
}
char *serialize_channel_data(struct Channel *channel, size_t *buffer_size) {
char *buffer = NULL;
FILE *f = open_memstream(&buffer, buffer_size);
if (!f){
perror("open_memstream failed");
return NULL;
}
// FIXME Possible key address leak
write_str(channel->name, strlen(channel->name), f);
write_channel_posts(channel, f);
fclose(f);
return buffer;
}
int handle_view_channel(struct Request *request, struct Response *response, struct Channel **channel) {
response->buffer = serialize_channel_data(*channel, &response->buffer_size);
return response->buffer ? MHD_HTTP_OK : MHD_HTTP_INTERNAL_SERVER_ERROR;
}
void fill_route(struct Route *route, char *method, char *url, RouteHandler handler, unsigned int flags) {
strcpy(route->method, method);
strcpy(route->url, url);
route->handler = handler;
route->flags = flags;
}
void register_routes() {
fill_route(&routes[0], "POST", "/api/add_channel", handle_add_channel, 0);
fill_route(&routes[1], "POST", "/api/add_post", handle_add_post, ROUTE_CHANNEL_NEEDED | ROUTE_AUTH_NEEDED);
fill_route(&routes[2], "POST", "/api/key", handle_get_key, ROUTE_CHANNEL_NEEDED | ROUTE_AUTH_NEEDED);
fill_route(&routes[3], "POST", "/api/change_password", handle_change_password, ROUTE_CHANNEL_NEEDED | ROUTE_AUTH_NEEDED);
fill_route(&routes[4], "GET", "/api/view", handle_view_channel, ROUTE_CHANNEL_NEEDED);
}
struct Route *find_route(const char *method, const char *url) {
for (int i = 0; i < ROUTES_COUNT; i++) {
if (strcmp(method, routes[i].method) == 0 && strcmp(url, routes[i].url) == 0) {
return &routes[i];
}
}
return 0;
}
int handle_route(struct Route *route, struct Request *request, struct Response *response, struct Channel **channel) {
if (route->flags & ROUTE_CHANNEL_NEEDED){
*channel = get_channel_by_id(request->channel_id);
if (!*channel) {
return MHD_HTTP_NOT_FOUND;
}
if (route->flags & ROUTE_AUTH_NEEDED) {
if (!strlen(request->password)) {
return MHD_HTTP_BAD_REQUEST;
}
if (!auth(*channel, request->password)) {
return MHD_HTTP_FORBIDDEN;
}
}
}
return route->handler(request, response, channel);
}
int handle_request(struct Request *request, struct MHD_Response **mhd_response) {
struct Route *route = find_route(request->method, request->url);
if (!route){
printf("Route handler not found for %s %s\n", request->method, request->url);
return MHD_HTTP_NOT_FOUND;
}
int affected_channel_id;
int status_code;
struct Response response;
memset(&response, 0, sizeof(struct Response));
int pipefd[2];
if (pipe(pipefd) == -1) {
perror("pipe failed");
return MHD_HTTP_INTERNAL_SERVER_ERROR;
}
pid_t pid = fork();
if (pid == -1) {
perror("fork failed");
return MHD_HTTP_INTERNAL_SERVER_ERROR;
} else if (pid == 0) {
struct Channel *channel = NULL;
status_code = handle_route(route, request, &response, &channel);
affected_channel_id = channel ? channel->id : 0;
write(pipefd[1], &affected_channel_id, sizeof(int));
write(pipefd[1], &status_code, sizeof(int));
write(pipefd[1], &response.buffer_size, sizeof(size_t));
write(pipefd[1], response.buffer, response.buffer_size);
exit(0);
} else {
close(pipefd[1]);
wait(NULL);
int read_failed = 0;
if (read(pipefd[0], &affected_channel_id, sizeof(int)) != sizeof(int) ||
read(pipefd[0], &status_code, sizeof(int)) != sizeof(int) ||
read(pipefd[0], &response.buffer_size, sizeof(size_t)) != sizeof(size_t)) {
read_failed = 1;
} else {
response.buffer = calloc(response.buffer_size, 1);
if (!response.buffer) {
perror("calloc failed");
read_failed = 1;
}
if (response.buffer && read(pipefd[0], response.buffer, response.buffer_size) != response.buffer_size){
free(response.buffer);
read_failed = 1;
}
}
close(pipefd[0]);
if (read_failed)
return MHD_HTTP_INTERNAL_SERVER_ERROR;
if (affected_channel_id)
update_channel(affected_channel_id);
*mhd_response = MHD_create_response_from_buffer(response.buffer_size, response.buffer, MHD_RESPMEM_MUST_FREE);
return status_code;
}
}
|
C
|
#include <std.h>
inherit "/d/common/obj/weapon/dagger.c";
create(){
::create();
set_id(({"dagger","quickdagger"}));
set_name("platinum dagger");
set_obvious_short("%^BOLD%^%^WHITE%^A beautiful platinum dagger%^RESET%^");
set_short("%^BOLD%^%^CYAN%^Whir%^BOLD%^%^BLUE%^l%^BOLD%^%^CYAN%^wind%^RESET%^");
set_long(
"%^BOLD%^%^CYAN%^This exquisite blade is a %^BOLD%^%^YELLOW%^long %^BOLD%^%^CYAN%^dagger"+
" which is elegantly simple in appearance. The pommel of the dagger has a small %^BOLD%^%^WHITE%^skull"+
" %^BOLD%^%^CYAN%^which has %^BOLD%^%^RED%^fiery %^BOLD%^%^CYAN%^red eyes. The handle is wrapped in"+
" %^RESET%^%^BLUE%^cold iron %^BOLD%^%^CYAN%^which fits tightly. The blade is plain with a narrow"+
" blood groove along the lower portion. Well-balanced, this blade would be %^BOLD%^%^RED%^lethal"+
" %^BOLD%^%^CYAN%^in combat.%^RESET%^");
set_property("enchantment",2);
set_value(1300);
set_wield((:TO,"wieldit":));
set_unwield((:TO,"unwieldit":));
set_hit((:TO,"hitit":));
}
int wieldit() {
tell_object(ETO,"%^BOLD%^%^CYAN%^You feel light-headed for a moment as you wield the blade.%^RESET%^");
tell_room(environment(ETO),"%^BOLD%^%^CYAN%^"+ETO->query_cap_name()+" wields the "+ETO->query_possessive()+" and looks %^BOLD%^%^YELLOW%^dizzy %^BOLD%^%^CYAN%^for a moment.%^RESET%^",ETO);
return 1;
}
int unwieldit() {
tell_object(ETO,"%^BOLD%^%^YELLOW%^You lose your orientation for a moment as you unwield the blade.%^RESET%^");
tell_room(environment(ETO),"%^BOLD%^%^YELLOW%^"+ETO->query_cap_name()+" unwield the blade and stumbles slightly, as if disorientated.%^RESET%^",ETO);
return 1;
}
int hitit(object targ){
if(random(1000) < 200){
if(!objectp(targ)) {
return roll_dice(1,6)+2;
}
// ETO->execute_attack();
// removed one, this weapon was sick overpowered even wielding just one. N, 7/12.
ETO->execute_attack();
tell_object(ETO,"%^BOLD%^%^CYAN%^Suddenly you feel the world slow down around you as you quickly slice at "+targ->query_cap_name()+" with unnatural speed!");
tell_object(targ,"%^BOLD%^%^WHITE%^"+ETO->query_cap_name()+" %^BOLD%^%^YELLOW%^blurs %^BOLD%^%^WHITE%^for a moment as they strike you with unnatural speed!%^RESET%^");
tell_room(environment(query_wielded()),"%^BOLD%^%^CYAN%^" +ETO->query_cap_name()+" turns into a %^BOLD%^%^YELLOW%^blur %^BOLD%^%^CYAN%^for a moment as they slash "+targ->query_cap_name()+" with unnatural speed!%^RESET%^",({ETO,targ}));
return roll_dice(1,6)+2;
}
}
|
C
|
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
//#include <gtk/gtk.h>
//#include "Cuadros.h"
#include "Arboles.h"
#include "Arbol.h"
#include "Proyecto.h"
void Arbol1(int argc, char *argv[])
{
gtk_init (&argc, &argv);//Se inicia el modo gtk
// Se crea la ventana principal VPrincipal.
VPrincipal = gtk_window_new (GTK_WINDOW_TOPLEVEL);
// Le ponemos nombre a la ventana.
gtk_window_set_title (GTK_WINDOW (VPrincipal), "Árboles");
// Deja la ventana estatica.
gtk_window_set_resizable(GTK_WINDOW(VPrincipal),FALSE);
// Definimos la dimencion de la ventana.
gtk_widget_set_size_request (VPrincipal,1366 , 768);
// Pocionamos la ventana siempre en el centro de la pantalla.
gtk_window_set_position(GTK_WINDOW(VPrincipal), GTK_WIN_POS_CENTER);
// Inicializamos el contenedor.
marco=gtk_fixed_new(); // se declara dentro de donde va a quedar la imagen
// Se agrega la ventana al marco.
gtk_container_add (GTK_CONTAINER(VPrincipal),marco);
//imagenes de fondo
fondo=gtk_image_new_from_file("fondo.png");
gtk_fixed_put(GTK_FIXED(marco),fondo,-28,-70);
//crea el icono del programa
gtk_window_set_icon(GTK_WINDOW(VPrincipal), create_pixbuf("C.jpg"));
//crea las cajas de texto
int tamagno=50;
caja_Insertar=gtk_entry_new();
gtk_fixed_put (GTK_FIXED (marco),caja_Insertar,1180,tamagno+10);
gtk_widget_set_size_request(caja_Insertar, 145,50);
caja_Eliminar=gtk_entry_new();
gtk_fixed_put (GTK_FIXED (marco),caja_Eliminar,1180,tamagno+200);
gtk_widget_set_size_request(caja_Eliminar, 145,50);
//crea los botones
Inserta= gtk_button_new_with_label(" Insertar ");//boton para Insertar nuevos nodos
gtk_fixed_put (GTK_FIXED (marco),Inserta,1183,150);
InsertarI=gtk_image_new_from_file("Insert.png");
gtk_fixed_put(GTK_FIXED(marco),InsertarI,500,135);
Elimina= gtk_button_new_with_label(" Eliminar ");//boton para Eliminar nodos existentes
gtk_fixed_put (GTK_FIXED (marco),Elimina,1184,340);
EliminarI=gtk_image_new_from_file("ELIM.png");
gtk_fixed_put(GTK_FIXED(marco),EliminarI,1180,325);
//Acciones de los botones
g_signal_connect (G_OBJECT (Inserta), "clicked",G_CALLBACK (Inserta_nodos),NULL);
g_signal_connect (G_OBJECT (Elimina), "clicked",G_CALLBACK (Elimina_nodos),NULL);
/*Acerca= gtk_button_new_with_label("Acerca de...");//boton para la ventana de programadores
gtk_fixed_put (GTK_FIXED (marco),Acerca,150,10);
g_signal_connect (G_OBJECT (Acerca), "clicked",G_CALLBACK (AcercaD), NULL);
//al darle click a la funcion de programadores te manda a la ventana de AcercaD*/
gtk_widget_show_all(VPrincipal);//pone en pantalla todo lo que hay en la ventana principal
gtk_main();// Se cierra el modo gtk
}
void Inserta_nodos(GtkWidget *widget, gpointer datos)
{
printf("1");
// int v,t,n;//Variable que almacena el valor retornado por la función Verifica_Numero
// char numero[50];
// const gchar *Insert;
// Insert=gtk_entry_get_text(GTK_ENTRY(caja_Insertar));
// strcpy(numero,Insert);
// t=strlen(numero);
// n=atoi(Insert);
// if (t==0)
// mostrar_advertencia("No ha introducido ningún elemento\n Intente de nuevo",VPrincipal);
// else
// {
// v=Verifica_Numero(numero);
// if (v==0)
// {
// gtk_entry_set_text(GTK_ENTRY(caja_Insertar),"");
// F_insertar(n);
// }
// else
// {
// mostrar_error("Elemento no valido\n Intente de nuevo",VPrincipal);
// gtk_entry_set_text(GTK_ENTRY(caja_Insertar),"");
// }
// }
}
void Elimina_nodos(GtkWidget *widget, gpointer datos)
{
int v,t;//Variable que almacena el valor retornado por la función Verifica_Numero
char numero[50];
const gchar *Elim;
Elim=gtk_entry_get_text(GTK_ENTRY(caja_Eliminar));
strcpy(numero,Elim);
t=strlen(numero);
if (t==0)
mostrar_advertencia("No ha introducido ningún elemento\n Intente de nuevo",VPrincipal);
else
{
v=Verifica_Numero(numero);
if (v==0)
gtk_entry_set_text(GTK_ENTRY(caja_Eliminar),"");
else
{
mostrar_error("Elemento no valido\n Intente de nuevo",VPrincipal);
gtk_entry_set_text(GTK_ENTRY(caja_Eliminar),"");
}
}
}
int Verifica_Numero(char numero[50])
{
int k=0,sw=0,j;
//char numero[50];
j=strlen(numero); // cuenta la cantidad de caracteres que hay dentro de una cadena
while(k<j && sw==0)
{
if(isdigit(numero[k])!=0)
k++;
else
sw=1;
}
if (sw==0)
printf("%s es dígito\n",numero);
else
printf("%s no es dígito\n",numero);
return sw;
}
// Para la creacion del icono del programa
GdkPixbuf *create_pixbuf(const gchar * filename)
{
GdkPixbuf *pixbuf;
GError *error = NULL;
pixbuf = gdk_pixbuf_new_from_file(filename, &error);
if(!pixbuf) {
fprintf(stderr, "%s\n", error->message);
g_error_free(error);
}
return pixbuf;
}
|
C
|
#include "util.h"
#include <dirent.h>
#define EXIT 1
#define GETDENTS 141
#define STDERR 2
#define SYS_WRITE 4
#define STDOUT 1
#define STDERR 2
#define SYS_OPEN 5
#define O_RDONLY 0
#define DT_UNKNOWN 0
# define DT_FIFO 1
# define DT_CHR 2
# define DT_DIR 4
# define DT_BLK 6
# define DT_REG 8
# define DT_LNK 10
# define DT_SOCK 12
extern int system_call(int,...);
extern void infaction();
extern void infector(char*);
extern void code_start;
extern void code_end;
void printMode(int modeA ,int modeP, char *prefix){
int file;
int getdents;
char buffer[8191];
struct dirent *directory;
int k;
char type;
if(modeA){
infaction();
system_call(SYS_WRITE,STDOUT,"\n",1);
}
file=system_call(SYS_OPEN,".",O_RDONLY,0644);
if (file < 0)
{
system_call(EXIT,0x55,"\n",1); }
for ( ; ; ) {
getdents = system_call(GETDENTS, file, buffer, 8191);
if (getdents < 0){
system_call(EXIT,0x55,"\n",1);
}
if (getdents == 0)
break;
for (k = 0; k < getdents;)
{
directory= (struct dirent *) (buffer + k);
type = *(buffer + k + (directory->d_reclen)-1);
if(modeP)
{
if(strncmp(prefix, (directory->d_name)-1, strlen(prefix)) == 0 )
{
system_call(SYS_WRITE,STDOUT,(directory->d_name)-1,strlen(directory->d_name)+1);
system_call(SYS_WRITE,STDERR,"\ntype: ",7);
if(type==DT_UNKNOWN)
system_call(SYS_WRITE,STDERR,"unknown\n",8);
else if(type==DT_BLK)
system_call(SYS_WRITE,STDERR,"block\n",6);
else if(type==DT_REG)
system_call(SYS_WRITE,STDERR,"regular file\n",13);
else if(type==DT_DIR)
system_call(SYS_WRITE,STDERR,"directory\n",10);
else if(type==DT_FIFO)
system_call(SYS_WRITE,STDERR,"FIFO\n",5);
else if(type==DT_SOCK)
system_call(SYS_WRITE,STDERR,"socket\n",7);
if(modeA){
system_call(SYS_WRITE,STDERR,"\n\nCalling to infector..\n",24);
system_call(SYS_WRITE,STDOUT,"\n\n",2);
infector((directory->d_name)-1);
system_call(SYS_WRITE,STDOUT,"\n\n",2);
}
system_call(SYS_WRITE,STDOUT," ",1);
}
k += directory->d_reclen;
}
else{
system_call(SYS_WRITE,STDOUT,(directory->d_name)-1,strlen(directory->d_name)+1);
system_call(SYS_WRITE,STDERR,"\ntype: ",7);
if(type==DT_UNKNOWN)
system_call(SYS_WRITE,STDERR,"unknown\n",8);
else if(type==DT_BLK)
system_call(SYS_WRITE,STDERR,"block\n",6);
else if(type==DT_REG)
system_call(SYS_WRITE,STDERR,"regular file\n",13);
else if(type==DT_DIR)
system_call(SYS_WRITE,STDERR,"directory\n",10);
else if(type==DT_FIFO)
system_call(SYS_WRITE,STDERR,"FIFO\n",5);
else if(type==DT_SOCK)
system_call(SYS_WRITE,STDERR,"socket\n",7);
else if(type==DT_CHR)
system_call(SYS_WRITE,STDERR,"char device\n",13);
else if(type==DT_LNK)
system_call(SYS_WRITE,STDERR,"symbolic link\n",14);
system_call(SYS_WRITE,STDOUT," ",1);
k += directory->d_reclen;
}
}
}
}
void DebugMode(int modeP, char *prefix){
int result;
int file, getdents;
char buffer[8191];
struct dirent *directory;
int k;
char type;
file=system_call(SYS_OPEN,".",O_RDONLY,0777);
system_call(SYS_WRITE, STDERR, "\nSystem call ID: ", 16);
system_call(SYS_WRITE,STDERR,itoa(SYS_WRITE),1);
system_call(SYS_WRITE, STDERR, "\nReturn Code: ", 15);
system_call(SYS_WRITE,STDERR,itoa(file),1);
if (file < 0)
{
system_call(EXIT,0x55,"\n",1);
}
for ( ; ; ) {
getdents = system_call(GETDENTS, file, buffer, 8191);
system_call(SYS_WRITE, STDERR, "\nSystem call ID: ", 17);
system_call(SYS_WRITE,STDERR,itoa(GETDENTS),3);
system_call(SYS_WRITE, STDERR, "\nReturn Code: ", 15);
system_call(SYS_WRITE,STDERR,itoa(getdents),1);
system_call(SYS_WRITE,STDERR,"\n",1);
if (getdents <0){
system_call(EXIT,0x55,"\n",1);
}
if (getdents == 0)
break;
for (k = 0; k < getdents;) {
directory = (struct dirent *) (buffer + k);
if(strncmp(prefix, (directory->d_name)-1, strlen(prefix)) == 0 )
{
type = *(buffer + k + (directory->d_reclen)-1);
system_call(SYS_WRITE,STDERR,"\n",1);
result=system_call(SYS_WRITE,STDERR,(directory->d_name)-1,strlen(directory->d_name)+1);
system_call(SYS_WRITE,STDERR,": length: ",10);
system_call(SYS_WRITE,STDERR,(itoa(directory->d_reclen))-1,strlen(itoa(directory->d_reclen))+1);
system_call(SYS_WRITE,STDERR,": file serial number: ",22);
system_call(SYS_WRITE,STDERR,(itoa(directory->d_ino))-1,strlen(itoa(directory->d_ino))+1);
system_call(SYS_WRITE,STDERR,"\ntype: ",7);
if(type==DT_UNKNOWN)
system_call(SYS_WRITE,STDERR,"unknown\n",8);
else if(type==DT_BLK)
system_call(SYS_WRITE,STDERR,"block\n",6);
else if(type==DT_REG)
system_call(SYS_WRITE,STDERR,"regular file\n",13);
else if(type==DT_DIR)
system_call(SYS_WRITE,STDERR,"directory\n",10);
else if(type==DT_FIFO)
system_call(SYS_WRITE,STDERR,"FIFO\n",5);
else if(type==DT_SOCK)
system_call(SYS_WRITE,STDERR,"socket\n",7);
else if(type==DT_CHR)
system_call(SYS_WRITE,STDERR,"char device\n",13);
else if(type==DT_LNK)
system_call(SYS_WRITE,STDERR,"symbolic link\n",14);
system_call(SYS_WRITE,STDERR,"\n",1);
k += directory->d_reclen;
system_call(SYS_WRITE, STDERR, "\nSystem call ID: ", 17);
system_call(SYS_WRITE,STDERR,itoa(SYS_WRITE),1);
system_call(SYS_WRITE, STDERR, "\nReturn Code: ", 15);
system_call(SYS_WRITE,STDERR,itoa(result)-1,2);
system_call(SYS_WRITE,STDERR,"\n",1);
}
else{ k += directory->d_reclen;}
}
}
}
int main (int argc , char* argv[], char* envp[])
{
int modeP = 0;
int modeA = 0;
char *prefix;
int i;
int mode=0;
char *a = "\nFlame 2 strikes!\n";
for (i = 0; i < argc; i++) {
if (strcmp(argv[i], "-D") == 0) {
system_call(SYS_WRITE,STDOUT,"-D\n",3);
mode = 1;
}
else if(strncmp(argv[i], "-p",2) == 0)
{
system_call(SYS_WRITE,STDOUT,"-P\n",3);
modeP = 1;
prefix = argv[i]+2;
}
else if(strncmp(argv[i], "-a",2) == 0)
{
system_call(SYS_WRITE,STDOUT,"-A\n",3);
modeA=1;
modeP=1;
prefix = argv[i]+2;
}
}
system_call(4, 1, a,18);
if(mode==0){
printMode(modeA, modeP, prefix);
}
else{
DebugMode(modeP, prefix);
}
return 0;
}
|
C
|
#include <stdio.h>
#include <malloc.h>
int _multiple(int n, int *a, int size) {
int overflow = 0;
for (int i = 0; i < size; i++) {
int t = a[i] * n + overflow;
a[i] = t % 10;
overflow = t / 10;
}
if (overflow > 0) {
while (overflow > 0) {
a[size++] = overflow % 10;
overflow = overflow / 10;
}
}
return size;
}
int _add(int *a, int *b, int a_size, int b_size) {
int overflow = 0;
int *x;
int min_size;
int max_size;
if (a_size > b_size) {
max_size = a_size;
min_size = b_size;
x = a;
} else {
max_size = b_size;
min_size = a_size;
x = b;
}
for (int i = 0; i < min_size; i++) {
int t = a[i] + b[i] + overflow;
a[i] = t % 10;
overflow = t / 10;
}
for (int i = min_size; i < max_size; i++) {
int t = x[i] + overflow;
a[i] = t % 10;
overflow = t / 10;
}
if (overflow > 0) {
while (overflow > 0) {
a[max_size++] = overflow % 10;
overflow = overflow / 10;
}
}
return max_size;
}
void add_frac(int n, int *num, int *denorm, int *num_size, int *denorm_size) {
/*int t = n * (*a) + (*b);
*b = *a;
*a = t;*/
int t[1000];
int t_size = *denorm_size;
for (int i = 0; i < t_size; i++) {
t[i] = denorm[i];
}
t_size = _multiple(n, t, t_size);
t_size = _add(t, num, t_size, *num_size);
for (int i = 0; i < *denorm_size; i++) {
num[i] = denorm[i];
}
*num_size = *denorm_size;
for (int i = 0; i < t_size; i++) {
denorm[i] = t[i];
}
*denorm_size = t_size;
}
void calc_e(int n, int *frac, int *num, int *denorm,
int *num_size, int *denorm_size, int size) {
if (n == 1) {
num[0] = frac[0];
denorm[0] = 1;
*num_size = 1;
*denorm_size = 1;
return;
}
/*if (n == 1) {
*num = 3;
*denorm = 1;
*num_size = 1;
*denorm_size = 1;
return;
}*/
num[0] = 1;
denorm[0] = frac[n - 1];
for (int i = 1; i < size; i++) {
num[i] = 0;
denorm[i] = 0;
}
*num_size = 1;
*denorm_size = 1;
for (int i = n - 2; i > 0; i--) {
add_frac(frac[i], num, denorm, num_size, denorm_size);
}
int t[1000];
int t_size = *denorm_size;
for (int i = 0; i < t_size; i++) {
t[i] = denorm[i];
}
t_size = _multiple(frac[0], t, t_size);
*num_size = _add(num, t, *num_size, t_size);
}
void solve() {
int frac[120];
frac[0] = 2;
int j = 1;
int k = 1;
for (int i = 0; i <= 102/3; i++) {
frac[j++] = 1;
frac[j++] = 2*(k++);
frac[j++] = 1;
}
/*for (int i = 0 ; i < 101; i++) {
printf("%d ", frac[i]);
}
printf("\n");
return 0;*/
int num[1000];
int denorm[1000];
int num_size = 0;
int denorm_size = 0;
int size = 1000;
calc_e(100, frac, num, denorm, &num_size, &denorm_size, size);
for (int i = num_size - 1; i >= 0; i--) printf("%d", num[i]);
printf("(%d)/", num_size);
for (int i = denorm_size - 1; i >= 0; i--) printf("%d", denorm[i]);
printf("(%d)\n", denorm_size);
/*for (int i = 1; i < 101; i++) {
calc_e(i, frac, num, denorm, &num_size, &denorm_size, size);
for (int i = num_size - 1; i >= 0; i--) printf("%d", num[i]);
printf("/");
for (int i = denorm_size - 1; i >= 0; i--) printf("%d", denorm[i]);
printf("\n");
}*/
int sum = 0;
for (int i = 0; i < num_size; i++) sum = sum + num[i];
printf("sum=%d\n", sum);
}
typedef struct _bigint {
int num[1000];
int size;
} BigInt;
void solve1() {
int a[120];
a[0] = 2;
int j = 1;
int k = 1;
for (int i = 0; i <= 102/3; i++) {
a[j++] = 1;
a[j++] = 2*(k++);
a[j++] = 1;
}
BigInt *num = (BigInt*) malloc(3*sizeof(BigInt));
BigInt *p0 = num;
BigInt *p1 = p0 + 1;
BigInt *p2 = p1 + 1;
p0->num[0] = 1;
p0->size = 1;
p1->num[0] = 0;
p1->size = 1;
BigInt *p;
for (int i = 0; i < 100; i++) {
p = p2;
p2 = p1;
p1 = p0;
p0 = p;
p0->size = p1->size;
for (int i = 0; i < p1->size; i++) {
p0->num[i] = p1->num[i];
}
p0->size = _multiple(a[i], p0->num, p0->size);
p0->size = _add(p0->num, p2->num, p0->size, p2->size);
}
for (int i = p0->size - 1; i >= 0; i--) printf("%d", p0->num[i]);
printf("(%d)\n", p0->size);
int sum = 0;
for (int i = 0; i < p0->size; i++) sum = sum + p0->num[i];
printf("sum=%d\n", sum);
}
int main(int argc, char* argv) {
//solve();
solve1();
}
|
C
|
#include <stdio.h>
int main()
{
float ResistenciaTotal;
float resistencia1;
float resistencia2;
float resistencia3;
float paralelo01;
float VIn;
float ITotal;
float I1;
float I2;
float I3;
float Comprobar;
resistencia1 = 0;
resistencia2 = 0;
resistencia3 =0;
paralelo01 = 0;
ResistenciaTotal =0;
printf ("Escribe el valor del Voltaje de entrada");
scanf ("%f", &VIn);
printf("Escribe el valor de la primera resistencia");
scanf("%f", &resistencia1);
printf("Escribe el valor de la segunda resistencia");
scanf("%f", &resistencia2);
printf("Escribe el valor de la tercera resistencia");
scanf("%f", &resistencia3);
paralelo01 = (resistencia1 * resistencia2)/(resistencia1 + resistencia2);
ResistenciaTotal = (paralelo01 * resistencia3)/(paralelo01 + resistencia3);
printf("Resistencia Total: %.2f \n", ResistenciaTotal);
ITotal= VIn/ResistenciaTotal;
printf("Corriente total %f\n",ITotal);
printf("Voltaje total = V1 = V2 = V3 = %f\n",VIn);
printf("Corrientes en cada resistencia\n");
I1= VIn/resistencia1;
printf("Corriente de resistencia 1= %f\n",I1);
I2= VIn/resistencia2;
printf("Corriente de resistencia 2= %f\n",I2);
I3= VIn/resistencia3;
printf("Corriente de resistencia 3= %f\n",I3);
Comprobar= I1+I2+I3;
printf("Comprobacion de la suma de las corrientes I1, I2, I3= %f\n",Comprobar);
return 0;
}
|
C
|
/* Write a function check(x, y, n) that returns 1 if both x and y fall between
* 0 and n - 1, inclusive. The function should return 0 otherwise. Assume that
* x, y, and n are all of type int.
*/
int check(int x,y,n)
{
if(x>0&&y>0&&x<n-1&&y<n-1)
return 1;
else
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <malloc.h>
#include <fcntl.h>
#include <unistd.h>
#include <math.h>
#include <GL/glut.h>
#include <GL/rgb.h>
#define STEPCOUNT 40
#define FALSE 0
#define TRUE 1
#define MAX(a, b) (((a) > (b)) ? (a) : (b))
#define MIN(a, b) (((a) < (b)) ? (a) : (b))
enum {
OP_NOOP = 0,
OP_STRETCH,
OP_DRAWPOINT,
OP_DRAWIMAGE
};
typedef struct _cRec {
float x, y;
} cRec;
typedef struct _vertexRec {
float x, y;
float dX, dY;
float tX, tY;
} vertexRec;
GLenum doubleBuffer;
int imageSizeX, imageSizeY;
RGBImageRec *image = NULL;
cRec cList[50];
vertexRec vList[5];
int cCount, cIndex[2], cStep;
GLenum op = OP_NOOP;
void DrawImage(void)
{
glRasterPos2i(0, 0);
glDrawPixels(image->sizeX, image->sizeY, GL_RGB, GL_UNSIGNED_BYTE,
image->data);
if (doubleBuffer) {
glutSwapBuffers();
} else {
glFlush();
}
glRasterPos2i(0, 0);
glDrawPixels(image->sizeX, image->sizeY, GL_RGB, GL_UNSIGNED_BYTE,
image->data);
}
void DrawPoint(void)
{
int i;
glColor3f(1.0, 0.0, 1.0);
glPointSize(3.0);
glBegin(GL_POINTS);
for (i = 0; i < cCount; i++) {
glVertex2f(cList[i].x, cList[i].y);
}
glEnd();
if (doubleBuffer) {
glutSwapBuffers();
} else {
glFlush();
}
}
void InitVList(void)
{
vList[0].x = 0.0;
vList[0].y = 0.0;
vList[0].dX = 0.0;
vList[0].dY = 0.0;
vList[0].tX = 0.0;
vList[0].tY = 0.0;
vList[1].x = (float)imageSizeX;
vList[1].y = 0.0;
vList[1].dX = 0.0;
vList[1].dY = 0.0;
vList[1].tX = 1.0;
vList[1].tY = 0.0;
vList[2].x = (float)imageSizeX;
vList[2].y = (float)imageSizeY;
vList[2].dX = 0.0;
vList[2].dY = 0.0;
vList[2].tX = 1.0;
vList[2].tY = 1.0;
vList[3].x = 0.0;
vList[3].y = (float)imageSizeY;
vList[3].dX = 0.0;
vList[3].dY = 0.0;
vList[3].tX = 0.0;
vList[3].tY = 1.0;
vList[4].x = cList[0].x;
vList[4].y = cList[0].y;
vList[4].dX = (cList[1].x - cList[0].x) / STEPCOUNT;
vList[4].dY = (cList[1].y - cList[0].y) / STEPCOUNT;
vList[4].tX = cList[0].x / (float)imageSizeX;
vList[4].tY = cList[0].y / (float)imageSizeY;
}
void ScaleImage(int sizeX, int sizeY)
{
GLubyte *buf;
buf = (GLubyte *)malloc(3*sizeX*sizeY);
gluScaleImage(GL_RGB, image->sizeX, image->sizeY, GL_UNSIGNED_BYTE,
image->data, sizeX, sizeY, GL_UNSIGNED_BYTE, buf);
free(image->data);
image->data = buf;
image->sizeX = sizeX;
image->sizeY = sizeY;
}
void SetPoint(int x, int y)
{
cList[cCount].x = (float)x;
cList[cCount].y = (float)y;
cCount++;
}
void Stretch(void)
{
glBegin(GL_TRIANGLES);
glTexCoord2f(vList[0].tX, vList[0].tY);
glVertex2f(vList[0].x, vList[0].y);
glTexCoord2f(vList[1].tX, vList[1].tY);
glVertex2f(vList[1].x, vList[1].y);
glTexCoord2f(vList[4].tX, vList[4].tY);
glVertex2f(vList[4].x, vList[4].y);
glEnd();
glBegin(GL_TRIANGLES);
glTexCoord2f(vList[1].tX, vList[1].tY);
glVertex2f(vList[1].x, vList[1].y);
glTexCoord2f(vList[2].tX, vList[2].tY);
glVertex2f(vList[2].x, vList[2].y);
glTexCoord2f(vList[4].tX, vList[4].tY);
glVertex2f(vList[4].x, vList[4].y);
glEnd();
glBegin(GL_TRIANGLES);
glTexCoord2f(vList[2].tX, vList[2].tY);
glVertex2f(vList[2].x, vList[2].y);
glTexCoord2f(vList[3].tX, vList[3].tY);
glVertex2f(vList[3].x, vList[3].y);
glTexCoord2f(vList[4].tX, vList[4].tY);
glVertex2f(vList[4].x, vList[4].y);
glEnd();
glBegin(GL_TRIANGLES);
glTexCoord2f(vList[3].tX, vList[3].tY);
glVertex2f(vList[3].x, vList[3].y);
glTexCoord2f(vList[0].tX, vList[0].tY);
glVertex2f(vList[0].x, vList[0].y);
glTexCoord2f(vList[4].tX, vList[4].tY);
glVertex2f(vList[4].x, vList[4].y);
glEnd();
if (doubleBuffer) {
glutSwapBuffers();
} else {
glFlush();
}
if (++cStep < STEPCOUNT) {
vList[4].x += vList[4].dX;
vList[4].y += vList[4].dY;
} else {
cIndex[0] = cIndex[1];
cIndex[1] = cIndex[1] + 1;
if (cIndex[1] == cCount) {
cIndex[1] = 0;
}
vList[4].dX = (cList[cIndex[1]].x - cList[cIndex[0]].x) / STEPCOUNT;
vList[4].dY = (cList[cIndex[1]].y - cList[cIndex[0]].y) / STEPCOUNT;
cStep = 0;
}
}
void Key(unsigned char key, int x, int y)
{
switch (key) {
case ' ':
if (cCount > 1) {
InitVList();
cIndex[0] = 0;
cIndex[1] = 1;
cStep = 0;
glEnable(GL_TEXTURE_2D);
op = OP_STRETCH;
}
glutPostRedisplay();
break;
case 27:
free(image->data);
exit(0);
}
}
void Mouse(int button, int state, int mouseX, int mouseY)
{
if (state == GLUT_DOWN) {
if (op == OP_STRETCH) {
glDisable(GL_TEXTURE_2D);
cCount = 0;
op = OP_DRAWIMAGE;
} else {
SetPoint(mouseX, imageSizeY-mouseY);
op = OP_DRAWPOINT;
}
glutPostRedisplay();
}
}
void Animate(void)
{
switch (op) {
case OP_STRETCH:
Stretch();
break;
case OP_DRAWPOINT:
DrawPoint();
break;
case OP_DRAWIMAGE:
DrawImage();
break;
}
}
static void Args(int argc, char **argv)
{
GLint i;
doubleBuffer = GL_FALSE;
for (i = 1; i < argc; i++) {
if (strcmp(argv[i], "-sb") == 0) {
doubleBuffer = GL_FALSE;
} else if (strcmp(argv[i], "-db") == 0) {
doubleBuffer = GL_TRUE;
} else if (strcmp(argv[i], "-f") == 0) {
if (i+1 >= argc || argv[i+1][0] == '-') {
printf("-f (No file name).\n");
exit(1);
} else {
image = rgbImageLoad(argv[++i]);
if (image == NULL) {
printf("-f (Bad file name).\n");
exit(1);
}
}
}
}
}
int main(int argc, char **argv)
{
GLenum type;
glutInit(&argc, argv);
Args(argc, argv);
if (image == NULL) {
printf("No texture file.\n");
exit(1);
}
imageSizeX = (int)powf(2.0, (float)((int)(logf(image->sizeX)/logf(2.0))));
imageSizeY = (int)powf(2.0, (float)((int)(logf(image->sizeY)/logf(2.0))));
type = GLUT_RGB;
type |= (doubleBuffer) ? GLUT_DOUBLE : GLUT_SINGLE;
glutInitDisplayMode(type);
glutInitWindowSize(imageSizeX, imageSizeY);
glutCreateWindow("Stretch");
glViewport(0, 0, imageSizeX, imageSizeY);
gluOrtho2D(0, imageSizeX, 0, imageSizeY);
glClearColor(0.0, 0.0, 0.0, 0.0);
glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
glPixelStorei(GL_PACK_ALIGNMENT, 1);
ScaleImage(imageSizeX, imageSizeY);
glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_DECAL);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexImage2D(GL_TEXTURE_2D, 0, 3, image->sizeX, image->sizeY, 0,
GL_RGB, GL_UNSIGNED_BYTE, (unsigned char *)image->data);
cCount = 0;
cIndex[0] = 0;
cIndex[1] = 0;
cStep = 0;
op = OP_DRAWIMAGE;
glutKeyboardFunc(Key);
glutMouseFunc(Mouse);
glutIdleFunc(Animate);
glutDisplayFunc(Animate);
glutMainLoop();
}
|
C
|
#include "bit_array.h"
#include <stdlib.h>
inline void* create_bit_array(bit_array* array, uintmax_t size)
{
// TODO, CHECKING, MAYBE THIS IS A STUPID MISTAKE
array->data = calloc(size, sizeof((size + 7) / 8));
array->size = size;
return array->data;
}
inline void destroy_bit_array(bit_array* array)
{
free(array->data);
}
inline bool get_bit(bit_array* array, uintmax_t index)
{
index %= array->size;
return array->data[index / 8] & (1 << (index % 8));
}
inline void set_bit(bit_array* array, uintmax_t index)
{
index %= array->size;
array->data[index / 8] |= (1 << (index % 8));
}
|
C
|
#include "types.h"
#include "x86.h"
#include "defs.h"
#include "date.h"
#include "param.h"
#include "memlayout.h"
#include "mmu.h"
#include "proc.h"
int
sys_fork(void)
{
return fork();
}
int
sys_exit(void)
{
exit();
return 0; // not reached
}
int
sys_wait(void)
{
return wait();
}
int
sys_thread_create(void)
{
// retrive args
// int thread_create(void(*fcn)(void*), void *arg, void*stack)
char* fcn;
char* arg;
char* stack;
if(argptr(0, &fcn, 4)<0)
cprintf("Arg#1 function error.\n");
if(argptr(1, &arg, 4)<0)
cprintf("Arg#2 args error.\n");
if(argptr(2, &stack, 4)<0)
cprintf("Arg#3 stack error.\n");
return thread_create((void*)fcn, arg, stack);
}
int
sys_thread_join(void)
{
return thread_join();
}
int
sys_thread_exit(void){
return thread_exit();
}
int
sys_kill(void)
{
int pid;
if(argint(0, &pid) < 0)
return -1;
return kill(pid);
}
int
sys_getpid(void)
{
return myproc()->pid;
}
int
sys_sbrk(void)
{
int addr;
int n;
if(argint(0, &n) < 0)
return -1;
addr = myproc()->sz;
if(growproc(n) < 0)
return -1;
return addr;
}
int
sys_sleep(void)
{
int n;
uint ticks0;
if(argint(0, &n) < 0)
return -1;
acquire(&tickslock);
ticks0 = ticks;
while(ticks - ticks0 < n){
if(myproc()->killed){
release(&tickslock);
return -1;
}
sleep(&ticks, &tickslock);
}
release(&tickslock);
return 0;
}
// return how many clock tick interrupts have occurred
// since start.
int
sys_uptime(void)
{
uint xticks;
acquire(&tickslock);
xticks = ticks;
release(&tickslock);
return xticks;
}
//extern int backtrace(struct proc*);
int
sys_backtrace(void)
{
backtrace();
return 0;
}
int
sys_getprocinfo()
{
// iterate through the process table, get info for each process
//struct uproc *up = malloc(sizeof(struct proc));
/*
int pid = 0;
char *up;
if(argint(0, &pid) < 0 || argptr(1, &up, sizeof(struct uproc)) < 0){
return -1;
}
getprocinfo(pid, (struct uproc*)up);
cprintf("going through sysproc.c\n");
*/
//struct uproc *up = malloc(sizeof(struct uproc));
struct uproc* up = 0;
int i = 0;
//process name, process id, parent process id, size of process memory, process state, whether process is waiting on a channel, and whether it's been killed
cprintf("Process name PID ParentID Size Killed State\n");
for(i = 0; i < 64; i++){
if(getprocinfo(i, (struct uproc*)up) == 0){
cprintf("\t%s\t\t %d\t %d\t %d\t\t %d\t",up->name, up->pid, up->parent_pid, up->sz, up->killed);
switch(up->state){
case UNUSED:
cprintf("UNUSED\n");
break;
case EMBRYO:
cprintf("EMBRYO\n");
break;
case SLEEPING:
cprintf("SLEEPING\n");
break;
case RUNNABLE:
cprintf("RUNNABLE\n");
break;
case RUNNING:
cprintf("RUNNING\n");
break;
case ZOMBIE:
cprintf("ZOMBIE\n");
break;
}
}
}
//free(up);
return 0;
}
|
C
|
/*
SYNOPSIS
Solution for chapter 48.
SOLUTION
All of exercise of chapter 48 are skiped because
we should avoid System V shared memory. System V shared memory doesn't
complicate as message queues or semaphores, but it required message queues
or semaphores to synchronize read/write. So avoid it.
AUTHORS
Kevin Leptons <kevin.leptons@gmail.com>
*/
#include <stdlib.h>
#include <stdio.h>
int main(int argc, char *argv[])
{
printf("Goto %s to see solution\n", __FILE__);
return EXIT_SUCCESS;
}
|
C
|
/**
* Structure declaration
* A struct is a type consisting of a sequence of members whose storage is
* allocated in an order sequence (as opposed to union, which is a type
* consisting of a sequence of members whose storage overlaps).
* The {type specifier} for struct is identical to the union type specifier
* except for the keyword used:
* Syntax:
* struct name(optional) { struct-declaration-list } (1)
* struct name (2)
* 1) Struct definition: introduces the new type struce name and defines
* its meaning
* 2) If used on line of its own, as in struct <name>;, declares but
* doesn't define the struct name (see forward declaration below). In
* other contexts, names the previously-declared struct.
* name - the name of the struct that's being defined
* struct-declaration-list - any number of variable declarations, {bit
* field} declarations, and static assert
* declarations. Members of incomplete type and
* members of function type are not allowed
* (except for the flexible array member
* described below)
* Explalnation:
* Within a struct object, addresses of its elements (and the addresses of
* the bit field allocation units) increase in order in which the members
* were defined. A pointer to a struct can be cast to a pointer to its
* first member (or, if the member is a bit field, to its allocation unit).
* Likewise, a pointer to the first member of a struct can be cast to a
* pointer to the enclosing struct. There may be unnamed padding between
* any two members of a struct or after the last member, but not before the
* first member. The size of a struct is at least as large as the sum of
* the sizes of its members.
* If a struct defines at least one named member, it is allowed to
* additionally declare its last member with incomplete array type. When an
* element of the flexible array member is accessed (in an expression that
* uses operator . or -> with the flexible array member's name as the
* right-hand-side operand), then the struct behaves as if the array member
* had the longest size fitting in the memory allocated for this object. If
* no additional storage was allocated, it behaves as if an array with 1
* element, except that the behavior is undefined if that element is
* accessed or a pointer one past that element is produced. Initialization,
* sizeof, and the assignment operator ignore the flexible array member.
* Structures with flexible array members (or unions whose last member is
* a structure with flexible array member) cannot appear as array elements
* or as members of other structures.
* Similar to union, an unnamed member of a struct whose type is a struct
* without name is known as anonymous struct. Every member of an anonumous
* struct is considered to be a member of the enclosing struct or union.
* This applies recursively if the enclosing struct or union is also
* anonymous.
* Similar to union, the behavior of the program is undefined if struct is
* defined without any named members (including those obtained via
* anonymous nested structs or unions)
* Forward declaration:
* A declaration of the following form
* struct name;
* hides any previously declared meaning for the name <name> in the tag
* name space and declares name as a new struct name in current scope,
* which will be defined later. Until the definition appears, this struct
* name has incomplete type.
* This allows structs that refer to each other.
* Note that a new struct name may also be introduced just by using a
* struct tag within another declaration, but if a previously declared
* struct with the same name exists in the tag {name space}, the tag would
* refer to that name.
* Note:
* See { struct initialization } for the rules of regarding the
* initializers for structs.
* Because members of incomplete type are not allowed, and a struct type is
* not complete until the end of the definition, a struct cannot have a
* member of its own type. A pointer to its own type is allowed, and is
* commonly used to implement nodes in linked list or trees.
* Because a struct declaration does not establish scope, nested types,
* enumerations and enumerators is introduced by declarations within
* <struct-declaration-list> are visible in the surrounding scope where the
* struct is defined.
*/
// flexible array member
void f()
{
struct s { int n; double d[]; }; // s.d is a flexible array member
struct s t1 = { 0 }; // ok, d is as if double d[1], but UB to access
struct s t2 = { 1, { 4.2} }; // error: initialization ignores flexible array
// if sizeof (double) == 8
struct s *s1 = malloc(sizeof (struct s) + 64); // as if d was double d[8]
struct s *s2 = malloc(sizeof (struct s) + 46); // as if d was double d[5]
s1 = malloc(sizeof (struct s) + 10); // now as if d was double[1]
s2 = malloc(sizeof (struct s) + 6); // same but UB to access
double *dp = &(s1->d[0]); // ok
*dp = 42; // ok
dp = &(s2->d[0]); // ok
*dp = 42; // undefined
*s1 = *s2; // only copies s.n, not any element of s.d
// except those caught in sizeof (struct s)
}
// anonymous struct
void g()
{
struct v {
union { // anonymous union
struct { int i, j; }; // anonymous struct
struct { long k, l; } w;
};
int m;
} v1;
v1.i = 2; // valid
v1.k = 3; // invalid: inner structure is not anonymous
v1.w.k = 5; // valid
}
// forward declaration
void h()
{
struct y;
struct x { struct y *p; /* ... */ };
struct y { struct x *p; /* ... */ };
struct s* p = null; // tag naming an unknown struct declares it
struct s { int a; }; // definition for the struct pointed by p
{
struct s; // forward declaration of a new, local struct s
// this hides outer scope struct s until the end of this block
struct s* p; // pointer to local struct s
// without the forward declaration above,
// this would point at the outer-scope s
struct s { char *p; }; // definitions of the local struct s
}
}
int main()
{
struct car { char *make; char *model; int year; }; // declares the struct type
// declares and initializes an object of a previously-declared struct type
struct car c = {.year = 1923, .make="Nash", .model="48 Sports Touring Car"};
// declares a struct type, an object of that type, and a pointer to it
struct spaceship { char *make; char *model; char *year; }
ship = {"Incom Corporation", "T-65 X-wing starfighter", "128 ABY"},
*pship = &ship;
// A pointer to a struct can be cast to a pointer to its first member,
// and vice versa
char* pmake = (char *) &ship;
pship = (struct spaceship*) pmake;
}
|
C
|
#ifndef LISTA_ENCADEADA_H_
#define LISTA_ENCADEADA_H_
/*Lista Encadeada Genéria que recebe qualquer tipo de dados como parametro*/
#include <stdio.h>
#include <stdlib.h>
typedef struct lista_encadeada* Lista_Encadeada;
Lista_Encadeada construtor_lista_encadeada (void);
Lista_Encadeada destrutor_lista_encadeada (Lista_Encadeada lista,void (*destrutor_elemento)(void* elem));
Lista_Encadeada push_lista_encadeada (Lista_Encadeada lista, void* elem);
Lista_Encadeada pop_lista_encadeada (Lista_Encadeada lista);
Lista_Encadeada insere_ordenado_lista_encadeada (Lista_Encadeada lista,void* elem, int (*cmp)(void* elem1,void* elem2));
int insere_final (void *a, void* b);
void* busca_lista_encadeada (Lista_Encadeada lista,void* elem,int (*cmp)(void* a,void* b));
void imprime_lista_encadeada (FILE* arquivo,Lista_Encadeada lista, void (*imprime)(FILE* _arquivo_,void *elem));
void imprime_lista (Lista_Encadeada lista,void (*imprime)());
void destrutor_void (void* elem);
Lista_Encadeada retorna_prox (Lista_Encadeada lista);
void* retorna_conteudo (Lista_Encadeada lista);
int tam_lista(Lista_Encadeada l);
#endif
|
C
|
#include<stdio.h>
#include<stdlib.h>
#define SIZE(a) sizeof(a) / sizeof(a[0])
int main112()
{
char murder[4] = { 'a', 'b', 'c', 'd' };
char killer;
int i;
/*
A˵ҡ
B˵C
C˵D
D˵Cں˵
*/
for (i = 0; i < SIZE(murder); i++){
killer = murder[i];
if ((murder[0] != killer) + (murder[2] == killer)
+ (murder[3] == killer) + (murder[3] != killer)==3){
printf("killer is %c\n", killer);
}
}
system("pause");
return 0;
}
|
C
|
#ifndef BSTREE_H
#define BSTREE_H
//typedef struct tree tree;
struct bstree{
char *value;
int key;
struct bstree *left;
struct bstree *right;
};
struct bstree *bstree_create(char *value, int key);
void bstree_add(struct bstree *tree, char *value, int key);
struct bstree *bstree_lookup(struct bstree *tree, int key);
struct bstree *bstree_min(struct bstree *tree);
struct bstree *bstree_max(struct bstree *tree);
#endif
|
C
|
#include <stdio.h>
#include <unistd.h>
void leer(int * fd);
void escribir(int * fd);
int main(int argc, const char * argv[]){
int tuberia[2];
pid_t pid;
int n = atoi(argv[1]);
int i = 0;
for(;i<n;i++){
pid = fork();
pipe(tuberia);
if (pid == -1){
printf("Error al crear el proceso hijo");
//exit(-1);
}else if (pid == 0){
sleep(3);
leer(tuberia);
}else {
escribir(tuberia);
}
}
return 0;
}
void leer(int * fd){
//printf("leyendo\n");
int c;
close(fd[1]);
read(fd[0],&c,sizeof(int));
printf("—->Soy el proceso con PID %d y recibí el testigo %d, el cual tendré por 3 segundos\n",getpid(),c);
}
void escribir(int * fd){
//printf("escribiendo\n");
int n = 0;
sleep(3);
close(fd[0]);
printf("<—- Soy el proceso con PID %d y acabo de enviar el testigo %d\n",getpid(),n);
write(fd[1],&n, sizeof(int));
}
|
C
|
#include<stdio.h>
#include<stdlib.h>
int main()
{
FILE *f1,*f2,*f3;
char c;
f1=fopen("1.txt","r");
f2=fopen("2.txt","r");
f3=fopen("3.txt","w");
if((f1==NULL)||(f2==NULL)||(f3==NULL))
{
printf("error");
exit(0);
}
while((c=fgetc(f1))!=EOF)
{
fputc(c,f3);
}
while((c=fgetc(f2))!=EOF)
{
fputc(c,f3);
}
fclose(f1);
fclose(f2);
fclose(f3);
}
return 0;
}
|
C
|
#include <stdio.h>
/*
Example of using getchar and putchar
*/
main() {
char c;
printf("Please enter a character: ");
c = getchar();
printf("Your character is: ");
putchar(c);
printf("\n\n");
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_recursive_factorial.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: ylevy <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2018/08/23 19:22:43 by ylevy #+# #+# */
/* Updated: 2018/08/23 23:47:56 by ylevy ### ########.fr */
/* */
/* ************************************************************************** */
#include <unistd.h>
#include <stdio.h>
int ft_recursive_factorial(int nb)
{
if (nb < 0 || nb > 12)
return(0);
else if (nb == 1 || nb == 0)
return(1);
if (nb > 0)
{
nb = nb * ft_recursive_factorial(nb - 1);
}
return(nb);
}
int main()
{
int f = 0;
int a = 9;
int c = 13;
int t = -4;
ft_recursive_factorial(f);
ft_recursive_factorial(a);
ft_recursive_factorial(c);
ft_recursive_factorial(t);
printf("Factorial of %d = 1 || %d\n", f, ft_recursive_factorial(f));
printf("Factorial of %d = 362880 || %d\n", a, ft_recursive_factorial(a));
printf("Factorial of %d = 0 || %d\n", c, ft_recursive_factorial(c));
printf("Factorial of %d = 0 || %d\n\n", t, ft_recursive_factorial(t));
}
|
C
|
#include<stdio.h>
struct Ournode{
char x,y,z;
};
int main()
{
struct Ournode p={'a','0','a'+2};
struct Ournode *q=&p;
printf("%c\t%c",*((char *)q+1),*((char *)q+2));
return 0;
}
|
C
|
#include <stdio.h>
int main(void)
{
int num;
printf(" Էϼ : ");
scanf("%d", &num);
num = num/10;
switch (num) {
case 10:
case 9:
printf("A\n");
break;
case 8:
printf("B\n");
break;
default:
printf("F\n");
break;
}
return 0;
}
/*
Է¹ 100 ̹Ƿ ̸ 10 10 ˴ϴ.
Է¹ 10 10, 9 ( Է¹ 90~100 ) A
8 ( Է¹ 80~89 ) B
쿡 F ϸ ˴ϴ.
*/
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* utilitaries_3.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: glecler <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2019/09/04 17:26:42 by glecler #+# #+# */
/* Updated: 2019/10/19 13:01:14 by glecler ### ########.fr */
/* */
/* ************************************************************************** */
#include "ft_printf.h"
int ft_strlen(char *str)
{
int i;
i = 0;
while (str[i] != '\0')
i++;
return (i);
}
int f_get_nb(long double nb)
{
int i;
i = 0;
if (nb < 0)
{
nb = -1.0 * nb;
i++;
}
if (nb < 1)
return (1);
while (nb >= 1)
{
nb = nb / 10;
i++;
}
return (i);
}
long double part_ent(long double d)
{
long double part_en;
int x;
int i;
i = f_get_nb(d);
part_en = 0;
while (i > 0)
{
x = d / f_ft_pow(10, i - 1);
d = d - (x * f_ft_pow(10, i - 1));
part_en = part_en + x * f_ft_pow(10, i - 1);
i--;
}
return (part_en);
}
char *i_ftoa(long double n, int i, char *nb, int precision)
{
long double ncpy;
int x;
ncpy = n;
x = 0;
if (part_ent(n) == 0)
nb[i++] = '0';
while (ncpy >= 1)
{
ncpy = ncpy / 10;
x++;
}
if ((i > 0 && nb[0] != '-') || (i > 1 && nb[0] == '-'))
x = (precision > x ? precision : x);
while (x > 0 && nb[i])
{
nb[i] = (part_ent(n / ft_pow(10, x - 1)) + 48);
n = n - ((nb[i] - 48) * ft_pow(10, x - 1));
x--;
i++;
}
return (nb);
}
char *ftoa(long double n, int i, int precision)
{
char *nb;
long double dec;
nb = NULL;
if (!(nb = ft_strnew_gr(f_get_nb(n) + precision + (precision != 0))))
return (NULL);
if (n < 0)
{
n = -1 * n;
nb[i++] = '-';
}
dec = part_ent((((n - part_ent(n)) * ft_pow(10, precision + 1))) / 10);
if (((n * f_ft_pow(10, precision + 1)) - (part_ent(n *
f_ft_pow(10, precision)) * 10)) >= 5 && precision > 0)
dec += 1;
if (((n * f_ft_pow(10, precision + 1)) - (part_ent(n *
f_ft_pow(10, precision)) * 10)) >= 5 && precision == 0)
n += 1;
nb = i_ftoa(part_ent(n), i, nb, precision);
i += f_get_nb(part_ent(n));
if (precision != 0)
nb[i] = '.';
nb = i_ftoa(dec, i + 1, nb, precision);
return (nb);
}
|
C
|
#include<stdio.h>
#include<string.h>
int main(){
char num1[101],num2[101];
int i,c,length1,length2;
int range=0;
while(scanf("%s%s",num1,num2)!=EOF){
length1=strlen(num1);
length2=strlen(num2);
if(length1>length2){printf("LARGE\n");}
else if(length2>length1){printf("LITTLE\n");}
else{//ͬ
for(i=0;i<length1;i++){
if(num1[i]>num2[i]){printf("LARGE\n");range=0;}
else if(num2[i]>num1[i]){printf("LITTLE\n");range=0;}
else{range=1;}
}
if(range==1){printf("EQUAL\n");}
}}
}
|
C
|
#include<stdio.h>
int main()
{
int blorf;
blorf=22;
printf("The value of blorf is %d.\n",blorf);
printf("The value of blorf plus 16 is %d.\n",16+blorf);
printf("The value of blorf times itself is %d.\n",blorf*blorf);
return(0);
}
|
C
|
int main ()
{
x = 10;
y = 2.5 / x;
z = 2.5 + x;
print(x, y, z);
}
|
C
|
/********************************************************
* RSBS WS 13/14 - Blatt 09 Aufgabe 3 *
* *
* Author : Michael Krane 2233018 *
* *
* Purpose: Analyse der ELF-Datenstruktur *
* *
* Usage : A3 *
* *
********************************************************/
#include <stdio.h>
#include <stdlib.h>
int global_nicht_init;
int global_gleich_zero = 0;
int global_ungleich_zero = 1;
const int const_ungleich_zero = 2;
int main (int argc, char *argv[]) {
// &var liefert einen Pointer der auf die Adresse im Speicher zeigt an dem var gespeichert ist
// %p formatiert einen Pointer im hex-Format
printf("#### Globale Variablen#####\n");
// Hier werden die Adresse der globalen Variablen nacheinander ausgegeben
printf("\t Globale Variable ohne Initialisierungswert:\t\t %p \n", &global_nicht_init);
printf("\t Globale Variable mit 0 initialisiert:\t\t\t %p \n", &global_gleich_zero);
printf("\t Globale Variable mit Initialisierungswert ungleich 0:\t %p \n", &global_ungleich_zero);
printf("\t Globale Datenkonstante:\t\t\t\t %p \n", &const_ungleich_zero);
printf("#### Heap Variablen ####\n");
//Eine Heap Variable wird mittels malloc erzeugt
// Pointer der auf den "reservierten" Speicher zeigt
int *heap_int;
// malloc reserviert genug Speicher um einen int zuspeichern
heap_int = (int *) malloc(sizeof(int));
// Variable wird auf den Wert 25 gesetzt
*heap_int = 25;
printf("\t Heap Variable = %d : \t\t\t %p \n", *heap_int, heap_int);
// free() gibt den benutzten Speicher wieder frei
free(heap_int);
printf("#### Stack Variablen ####\n");
//Variablen die nicht über malloc erzeugt werden, werden au dem Stack erzeugt
int first_int_stack = 42;
int second_int_stack = 43;
int third_int_stack = 44;
printf("\t Erster int auf dem Stack:\t\t %p \n", &first_int_stack);
printf("\t Zweiter int auf dem Stack:\t\t %p \n", &second_int_stack);
printf("\t Dritter int auf dem Stack:\t\t %p \n", &third_int_stack);
return 0;
}
|
C
|
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/sem.h>
#include <sys/shm.h>
//#include "shmem.h"
#include <stdio.h>
#include <stdlib.h>
#define MAXBUFF 80
#define PERM 0666
/*Структура данных в разделяемой памяти*/
typedef struct mem_msg {
int segment;
char buff[MAXBUFF];
} Message;
main() {
Message *msgptr;
key_t key;
int shmid, semid;
struct sembuf mybuf2;
struct sembuf mybuf4;
struct sembuf mybuf5;
struct sembuf mybuf6;
struct sembuf mybuf3;
struct sembuf mybuf;
struct sembuf mybuf7;
/* */
if ((key = ftok("client_.c", 0)) < 0) {
printf("Невозможно получить ключ\n");
exit(1);
}
/* */
if ((shmid = shmget(key, sizeof(Message), 0)) < 0) {
printf("Ошибка доступа к разделяемой памяти\n");
exit(1);
}
/* */
if ((msgptr = (Message*)shmat(shmid, 0, 0)) < 0) {
prinf("Ошибка присоединения разделяемой памяти\n");
exit(1);
}
/* */
if ((semid = semget(key, 2, PERM)) < 0) {
printf("Ошибка доступа к семафорам\n");
exit(1);
}
/* */
mybuf.sem_num = 0;
mybuf.sem_op = 0;
mybuf.sem_flg = 0;
if(semop(semid, &mybuf, 1) < 0){
printf("Can\'t wait for condition\n");
exit(-1);
}
mybuf2.sem_num = 0;
mybuf2.sem_op = 1;
mybuf2.sem_flg = 0;
if(semop(semid, &mybuf2, 1) < 0){
printf("Can\'t wait for condition\n");
exit(-1);
}
mybuf4.sem_num = 1;
mybuf4.sem_op = 1;
mybuf4.sem_flg = 0;
if(semop(semid, &mybuf4, 1) < 0){
printf("Can\'t wait for condition\n");
exit(-1);
}
/* */
sprintf(msgptr->buff, "Здравствуй мир!\n");
/* */
mybuf3.sem_num = 0;
mybuf3.sem_op = -1;
mybuf3.sem_flg = 0;
if(semop(semid, &mybuf3, 1) < 0){
printf("Can\'t wait for condition\n");
exit(-1);
}
mybuf.sem_num = 0;
mybuf.sem_op = 0;
mybuf.sem_flg = 0;
if(semop(semid, &mybuf, 1) < 0){
printf("Can\'t wait for condition\n");
exit(-1);
}
/* mybuf6.sem_num = 0;
mybuf6.sem_op = 1;
mybuf6.sem_flg = 0;
if(semop(semid, &mybuf6, 1) < 0){
printf("Can\'t wait for condition\n");
exit(-1);
}*/
mybuf7.sem_num = 0;
mybuf7.sem_op = -1;
mybuf7.sem_flg = 0;
if(semop(semid, &mybuf7, 1) < 0){
printf("Can\'t wait for condition7\n");
exit(-1);
}
/* */
if (shmdt(msgptr) < 0) {
printf("Ошибка отключения разделяемой памяти\n");
exit(1);
}
/* */
if (shmctl(shmid, IPC_RMID, 0) < 0) {
printf("Незвожно удалить область разделяемой памяти\n");
exit(1);
}
if (semctl(semid, 0, IPC_RMID) < 0) {
printf("Невозможно удалить семафоры\n");
exit(1);
}
exit(0);
}
|
C
|
/*
Disciplina: Algoritmos Computacionais
(matutino)
Prof.: Orlewilson B. Maia
Autor(a): Seu nome
Data: 21/05/2018
Descrio: Ler N valores informado pelo
usurio, calcular soma e mdia
*/
// Bibliotecas
#include <stdio.h>
// Programa Principal
int main()
{
// variveis
int qtdValores, // quantidade de valores
valor, // valor informado pelo usurio
cont; // auxiliar para ler os valores
// informados pelo usurio
float soma, // soma dos N valores
media; // mdia dos N valores
printf("Informar quantidade de valor: ");
scanf("%d", &qtdValores);
// vers0 1.0 (usando while)
cont = 1;
soma = 0;
while (cont <= qtdValores) {
// ler valor
printf("Informe um valor: ");
scanf("%d", &valor);
// soma
soma = soma + valor;
cont = cont + 1;
}
// vers0 2.0 (usando for)
/*soma = 0;
for (cont = 1; cont <= qtdValores; cont++) {
// ler valor
printf("Informe um valor: ");
scanf("%d", &valor);
// soma
soma = soma + valor;
}*/
media = soma / qtdValores;
// mostrar resultado
printf("Soma dos valores: %.2f \n", soma);
printf("Media dos valores: %.2f", media);
}
|
C
|
int main(int argc, char **argv)
{
/* This is essentially the same main function from readdemo.c */
libtrace_t *trace = NULL;
libtrace_packet_t *packet = NULL;
/* Ensure we have at least one argument after the program name */
if (argc < 4) {
fprintf(stderr, "Usage: %s <trace file> <packet count> <array file>\n", argv[0]);
return 1;
}
packet = trace_create_packet();
if (packet == NULL) {
perror("Creating libtrace packet");
libtrace_cleanup(trace, packet);
return 1;
}
}
|
C
|
#include<stdio.h>
main()
{
int num[]={24,34,12,44,56,17};
display(num,6);
}
display(int *j,int n)
{
int i;
for(i=0;i<n;i++)
{
printf("%d",*j);
j++;
}
}
|
C
|
#include "hash_tables.h"
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
/**
* hash_table_set - sets hash table
* @ht: hash table
* @key: key
* @value: value
*
* Return: 1 if successful, 0 if fails
*/
int hash_table_set(hash_table_t *ht, const char *key, const char *value)
{
unsigned long int idx;
hash_node_t *temp;
if (!ht || !key || !*key || !*value)
return (0);
idx = key_index((unsigned char *)key, ht->size);
temp = ht->array[idx];
while (temp != NULL)
{
if (strcmp(temp->key, key) == 0)
{
free(temp->value);
temp->value = strdup(value);
if (temp->value == NULL)
{
free(temp->value);
return (0);
}
return (1);
}
temp = temp->next;
}
if (add_node(&ht->array[idx], key, value) == NULL)
return (0);
return (1);
}
/**
* add_node - adds node to beginning of list
* @head: head
* @key: key
* @value: value
*
* Return: address of new node
*/
hash_node_t *add_node(hash_node_t **head, const char *key, const char *value)
{
hash_node_t *new = NULL;
new = malloc(sizeof(hash_node_t *));
new->key = strdup(key);
if (new->key == NULL)
return (NULL);
new->value = strdup(value);
if (new->value == NULL)
{
free(new);
return (NULL);
}
new->next = *head;
*head = new;
return (*head);
}
|
C
|
#include "filereader.h"
char* readFileBytes(const char *name)
{
FILE *fl = fopen(name, "r");
fseek(fl, 0, SEEK_END);
long len = ftell(fl);
char *ret = malloc(len);
fseek(fl, 0, SEEK_SET);
fread(ret, 1, len, fl);
fclose(fl);
return ret;
}
int writeFileBytes(char* fileBytes, char* fileName, int size){
void * file_to_write = fopen(fileName, "w");
if(file_to_write != NULL){
int i = 0;
for(i;i<size;i++){
fwrite(&fileBytes[i], 1, sizeof(fileBytes[i]), file_to_write);
}
fclose(file_to_write);
return 0;
}
else{
fclose(file_to_write);
return 1;
}
}
int is_big_endian(void){
union{
uint32_t i;
char c[4];
} e = { 0x01000000 };
return e.c[0];
}
|
C
|
#include <stdio.h>
#define MAX 100
#define NOT_CALCULATED (-1)
#define q (1 - (p)) /* Вероятност B да спечели отделен мач */
const float p = 0.5; /* Вероятност A да спечели отделен мач */
const unsigned n = 5;
float PS[MAX][MAX];
float pDyn(unsigned i, unsigned j) /* Динамично оптимиране */
{ if (PS[i][j] < 0)
PS[i][j] = p * pDyn(i - 1, j) + q * pDyn(i, j - 1);
return PS[i][j];
}
float pDynamic2(unsigned i, unsigned j)
{ unsigned k, l;
for (k = 1; k <= i; k++)
for (l = 1; l <= j; l++)
PS[k][l] = NOT_CALCULATED;
for (k = 1; k <= i; k++)
PS[k][0] = 0.0;
for (k = 1; k <= j; k++)
PS[0][k] = 1.0;
return pDyn(i, j);
}
int main(void) {
unsigned i, j;
pDynamic2(n,n);
for (i = 0; i < n; i++) {
for (j = 0; j < n; j++)
printf("%f ", PS[i][j]);
printf("\n");
}
return 0;
}
|
C
|
#include <pthread.h>
#include <stdio.h>
enum
{
TC = 10
};
void* cal (void* ptr)
{
int c = *(int*) ptr;
printf("%d\n",c);
return NULL;
}
int main()
{
int counts[TC] = {0};
pthread_t threads[TC] = {0};
size_t count = 0;
while (count < TC)
{
counts[count] = count;
pthread_create(&threads[count], NULL, cal, &counts[count]);
pthread_join(threads[count], NULL);
++count;
}
}
|
C
|
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <string.h>
int main()
{
char str[1000000];
int sum = 0;
gets(str);
char *ptr = strtok(str," ");
while (ptr != NULL)
{
//printf("%s\n", ptr);
ptr = strtok(NULL, " ");
sum++;
}
printf("%d\n",sum);
return 0;
}
/*첫 줄에 영어 대소문자와 띄어쓰기로 이루어진 문자열이 주어진다. 이 문자열의 길이는 1,000,000을 넘지 않는다.
단어는 띄어쓰기 한 개로 구분되며, 공백이 연속해서 나오는 경우는 없다. 또한 문자열의 앞과 뒤에는 공백이 있을 수도 있다.*/
|
C
|
/*print chord formed on intersection of line and circle*/
#include<stdio.h>
#include<math.h>
void main()
{
int h, k, r,s ;
printf ("please enter thr coordinates of center");
scanf("%d%d",&h,&k);
printf("please enter the radius of circle and value of x for eqn x=s");
scanf("%d%d",&r,&s);
float dist, p, chrd;
dist=s-h;
p=sqrt(pow(r,2)-pow(dist,2));
chrd=2*p;
printf("the length of chord is%f",chrd);
}
|
C
|
#define period 10
//const int leftMotorPin = 9;
//const int rightMotorPin = 8;
//
//const int forwardMotorPin = 10;
//const int backwardMotorPin = 11;
int pwm_a = 3; //PWM control for motor outputs 1 and 2
int pwm_b = 9; //PWM control for motor outputs 3 and 4
int dir_a = 2; //direction control for motor outputs 1 and 2
int dir_b = 8; //direction control for motor outputs 3 and 4
int temp = 0;
int speedy = 0;
const int headlightsL = 6;
const int headlightsR = 7;
const int horn = 5;
int tilt = 12;
const int EEGpin = 4;
const int led = 13;
char go;
char oneDirection;
char hornChar;
char headlightsChar;
boolean headlightsOn = false;
boolean tiltFlag = true;
const char s = 'M';
void setup() {
Serial.begin(9600);
pinMode(pwm_a, OUTPUT); //Set control pins to be outputs
pinMode(pwm_b, OUTPUT);
pinMode(dir_a, OUTPUT);
pinMode(dir_b, OUTPUT);
pinMode(tilt, INPUT);
pinMode(headlightsL, OUTPUT);
pinMode(headlightsR, OUTPUT);
pinMode(horn, OUTPUT);
pinMode(EEGpin, INPUT);
pinMode(led, OUTPUT);
analogWrite(pwm_a, 0);
analogWrite(pwm_b, 0);
// pinMode(leftMotorPin, OUTPUT);
// pinMode(rightMotorPin, OUTPUT);
// pinMode(forwardMotorPin, OUTPUT);
// pinMode(backwardMotorPin, OUTPUT);
}
// the loop routine runs over and over again forever:
void loop() {
//Serial.print("Tilt: ");
//Serial.print(digitalRead(tilt));
//Serial.print('\n');
//EEG More 80% attention, go forward
if(digitalRead(EEGpin)){
digitalWrite(led, HIGH);
while(digitalRead(EEGpin)){
digitalWrite(dir_b, HIGH);
analogWrite(pwm_b, 210);
//Serial.flush();
}
}
if(!(digitalRead(EEGpin))){
digitalWrite(led, LOW);
//Serial.flush();
Stop();
straight();
}
if (temp > 79)
{
//Serial.println("Tilt Flag true");
tiltFlag = false;
Stop();
}
else
{
tiltFlag = true; //false
// Serial.println("Tilt Flag false");
}
if (Serial.available() > 0)
{
speedy = Serial.read();
Serial.print("Speed: ");
Serial.print(speedy);
Serial.print('\n');
}
if (Serial.available() > 0)
{
temp = Serial.read();
Serial.print("Temp: ");
Serial.print(temp);
Serial.print('\n');
}
if (Serial.available() > 0)
{
go = Serial.read();
// stop
if (go == 's' && tiltFlag == true)
{
Serial.print("Car is STOPPED and ");
Stop();
}
// go
else if (go == 'g' && tiltFlag == true)
{
Serial.print("Car is GOING and ");
forward(speedy);
}
// reverse
else if (go == 'r' && tiltFlag == true)
{
Serial.print("Car is REVERSING and ");
backward(speedy);
}
}
if (Serial.available() > 0)
{
oneDirection = Serial.read();
// staight
if (oneDirection == 's' && tiltFlag)
{
Serial.println("wheels are turned STRAIGHT");
straight();
}
// left
else if (oneDirection == 'l' && tiltFlag)
{
Serial.println("wheels are turned LEFT");
left();
}
// right
else if (oneDirection == 'r' && tiltFlag)
{
Serial.println("wheels are turned RIGHT");
right();
}
}
if (Serial.available() > 0)
{
hornChar = Serial.read();
if (hornChar == 'h')
{
analogWrite(horn, 50);
}
else
{
analogWrite(horn, 0);
}
}
if (Serial.available() > 0)
{
headlightsChar = Serial.read();
if (headlightsChar == s)
{
headlightsOn = !headlightsOn;
}
}
if (headlightsOn)
{
digitalWrite(headlightsL, HIGH);
digitalWrite(headlightsR, HIGH);
}
else
{
digitalWrite(headlightsL, LOW);
digitalWrite(headlightsR, LOW);
}
// Serial.print("go = ");
// Serial.println(go);
// Serial.print("left = ");
// Serial.println(oneDirection);
delay(180);
}
void left(){
digitalWrite(dir_a, LOW);
analogWrite(pwm_a, 225);
}
void right(){
digitalWrite(dir_a, HIGH);
analogWrite(pwm_a, 200);
}
void forward(int speedy){
digitalWrite(dir_b, HIGH);
analogWrite(pwm_b, speedSet);
}
void backward(int speedy){
int speedSet = speedy * 2;
digitalWrite(dir_b, LOW);
analogWrite(pwm_b, speedSet);
}
void straight(){
// digitalWrite(dir_a, LOW);
analogWrite(pwm_a, 0);
}
void Stop(){
analogWrite(pwm_b, 0);
}
|
C
|
#include <stdio.h>
// without argument with return value
int takenumber()
{ int n;
printf("enter a number:\n");
scanf("%d",&n);
return n;
}
int main()
{ int c;
c=takenumber();
printf("The entered number is %d",c);
return 0;
}
|
C
|
/*NOTE : priority of dot(.) operator is more than dereferencing (*) operator and address (&) operator*/
#include<stdio.h>
int main()
{
int i,j;
struct stu
{
char name[20];
float marks[2];
int rollno;
};
struct stu s1[2],*ptr;
ptr=s1;
printf("Enter the student details :\n");
for(i=0;i<2;i++)
{
printf("Enter the name :\n");
scanf("%s",ptr->name);
printf("Enter the roll no :\n");
scanf("%d",&((*(ptr+i)).rollno));
for(j=0;j<2;j++)
{
printf("Enter the marks in %d subject : \n",(j+1));
scanf("%f",&((*(ptr+i)).marks[j]));
}
}
printf("Student details :\n");
for(i=0;i<2;i++)
{
printf("Name : %s\n",(*(ptr+i)).name);
printf("Roll No : %d\n",(*(ptr+i)).rollno);
for(j=0;j<2;j++)
{
printf("Marks : %f\n",((*(ptr+i)).marks[j]));
}
}
return 0;
}
|
C
|
#include <stdio.h>
struct entry
{
int value;
struct entry *next;
};
void insertEntry(struct entry *toInsert, struct entry *after)
{
toInsert->next = after->next;
after->next = toInsert;
}
int main (int argc, char *argv[])
{
void insertEntry(struct entry *toInsert, struct entry *after);
struct entry n1, n2, n3, insert, *lPtr = &n1;
n1.value = 100;
n1.next = &n2;
n2.value = 200;
n2.next = &n3;
n3.value = 300;
n3.next = NULL;
insert.value = 250;
insert.next = NULL;
printf("Original list: \n");
while (lPtr) {
printf("%i\n", lPtr->value);
lPtr = lPtr->next;
}
printf("\nInserting entry: \n");
insertEntry(&insert, &n2);
lPtr = &n1;
while (lPtr) {
printf("%i\n", lPtr->value);
lPtr = lPtr->next;
}
return 0;
}
|
C
|
#include "lb_matrix.h"
#include <stdlib.h>
// Assume A.num_cols == B.num_rows
// C.num_rows == A.num_rows
// C.num_cols == B.num_cols
void lbmm(Matrix A, Matrix B, Matrix result) {
int col,row,offset,vec_length;
double vec_sum;
vec_length = A.num_cols;
for(col = 0; col < B.num_cols; col++) {
for(row = 0; row < A.num_rows; row++) {
// Dot Product Row(A) with Col(B)
vec_sum = 0.0;
for(offset = 0; offset < vec_length; offset++) {
double a = lb_mat_row_element(A,row,offset);
double b = lb_mat_col_element(B,col,offset);
double product = a * b;
vec_sum += product;
}
lb_mat_element(result,row,col) = vec_sum;
}
}
}
// Assume A.num_cols == B.num_cols
// Assume A.num_rows == B.num_rows
void lbma(Matrix A, Matrix B, Matrix result) {
int col,row;
for(col = 0; col < A.num_cols; col++) {
for(row = 0; row < A.num_rows; row++) {
lb_mat_element(result,row,col) = lb_mat_element(A,row,col) + lb_mat_element(B,row,col);
}
}
}
Matrix lb_create_matrix(double* data, unsigned int num_rows, unsigned int num_cols) {
Matrix m;
m.data = data;
m.num_rows = num_rows;
m.num_cols = num_cols;
return m;
}
Matrix lb_allocate_matrix(unsigned int num_rows, unsigned int num_cols) {
double* ptr = (double*)malloc(sizeof(double) * num_rows * num_cols);
return lb_create_matrix(ptr,num_rows,num_cols);
}
|
C
|
#include<stdio.h>
int main()
{
char str[100];
int i;
printf("请输入一行英文\n");
gets(str);
for(i=0;str[i]!='\0';i++)
{
if(str[i]>=97 && str[i]<=122)
{
str[i]-=32;
}
}
printf("the sorted words:\n");
for(i=0;str[i]!='\0';i++)
{
printf("%c",str[i]);
}
printf("\n");
}
|
C
|
#include "apue.h"
#include <errno.h>
#include <sys/wait.h>
void pr_exit(int status)
{
if (WIFEXITED(status))
printf("normal termination , exut status = %d\n", WEXITSTATUS(status));
else if (WIFSIGNALED(status))
printf("normal termination , exut status = %d\n", WTERMSIG(status)
#ifdef WCOREDUMP
,
WCOREDUMP(status) ? " (core file generated)" : "");
#else
);
#endif
else if (WIFSTOPPED(status))
printf("child stopped, signal number = %d\n", WSTOPSIG(status));
}
int m_system(const char* cmdstring) /* version without signal handling */
{
pid_t pid;
int status;
if (cmdstring == NULL)
return (1); /* always a command processor with UNIX */
if ((pid = fork()) < 0)
{
status = -1; /* probably out of processes */
}
else if (pid == 0)
{ /* child */
execl("/bin/sh", "sh", "-c", cmdstring, (char*)0);
_exit(127); /* execl error */
}
else
{ /* parent */
while (waitpid(pid, &status, 0) < 0)
{
if (errno != EINTR)
{
status = -1; /* error other than EINTR from waitpid() */
break;
}
}
}
return (status);
}
int main(void)
{
int status;
if ((status = m_system("date")) < 0)
err_sys("system() error");
pr_exit(status);
if ((status = m_system("nosuchcommand")) < 0)
err_sys("system() error");
pr_exit(status);
if ((status = m_system("who; exit 44")) < 0)
err_sys("system() error");
pr_exit(status);
exit(0);
}
|
C
|
/**
* @file cstr.c
* @author ln
* @brief the c string process
**/
#include "cstr.h"
#ifdef __cplusplus
extern "C" {
#endif
/**
* @brief Convert a string to lowercase
* @param s String to convert
* @return pointer to the new string
**/
char* strlwr(char *s)
{
char *p = s;
if (p) {
while (*p) {
*p = (char)tolower((int)(*p));
p++;
}
}
return s;
}
/**
* @brief Convert a string to uppercase
* @param s String to convert
* @return pointer to the new string
**/
char* strupr(char *s)
{
char *p = s;
if (p) {
while (*p) {
*p = (char)toupper((int)(*p));
p++;
}
}
return s;
}
/**
* @brief Remove blanks at the beginning and the end of a string
* @param s String to parse and alter
* @return New size of the string
**/
int strstrip(char *s)
{
char *last = NULL ;
char *dest = s;
if (s == NULL)
return 0;
last = s + strlen(s);
while (isspace((int)*s) && *s)
s++;
while (last > s) {
if (!isspace((int)*(last-1)))
break ;
last-- ;
}
*last = (char)0;
memmove(dest, s, last-s+1);
return last - s;
}
/**
* @brief Convert bin to hex
* @param hex Output string buffer
* bin bin to convert
* len lenght of the bin to convert
*
* @return the number of char(exclude '\0') in hex buffer
**/
int bin2hex(char *hex, const void *bin, unsigned len)
{
if (bin == NULL || hex == NULL || len == 0)
return 0;
unsigned i = 0;
for (i = 0; i < len; i++) {
sprintf(&hex[i*2], "%02x", ((unsigned char *)bin)[i]);
}
hex[i*2] = '\0';
return i*2;
}
/**
* @brief Convert bin to hex & allocate output buffer
* @param bin bin to convert
* len lenght of the bin to convert
*
* @return pointer to the ouput char buffer
*
* Need to free the pointer returned from this func
**/
char* abin2hex(const void *bin, unsigned len)
{
if (bin == NULL || len == 0) {
errno = EINVAL;
return NULL;
}
char *s = (char*)malloc((len * 2) + 1);
if (s != NULL) {
bin2hex(s, bin, len);
} else {
errno = ENOMEM;
return NULL;
}
return s;
}
/**
* @brief Convert hex to bin
* @param bin Output bin buffer
* hex hex to convert
* len lenght of output bin buffer
*
* @return Number of byte in bin buffer
*
* the string 'fde' is same as '0fde'
**/
int hex2bin(void *bin, const char *hex, unsigned len)
{
if (bin == NULL || hex == NULL || len == 0)
return 0;
unsigned len2 = len;
char buf[4] = {0};
if (strlen(hex) % 2) {
buf[0] = *hex++;
*((unsigned char *)bin) = (unsigned char)strtol(buf, NULL, 16);
len--;
bin = (unsigned char *)bin + 1;
}
while (*hex && len) {
buf[0] = *hex++;
buf[1] = *hex++;
*((unsigned char *)bin) = (unsigned char)strtol(buf, NULL, 16);
len--;
bin = (unsigned char *)bin + 1;
}
return len2 - len;
}
/**
* @brief Convert hex to bin
* @param hex hex to convert
* len lenght of the hex to convert
*
* @return pointer to the ouput bin buffer
*
* the string 'fde' is same as '0fde'
* Need to free the pointer returned from this func
**/
void * ahex2bin(const char *hex)
{
if (hex == NULL) {
errno = EINVAL;
return NULL;
}
unsigned len = strlen(hex);
unsigned char *b = (unsigned char*)malloc(len/2 + 1);
if (b != NULL) {
hex2bin(b, hex, len/2 + 1);
} else {
errno = ENOMEM;
return NULL;
}
return (void *)b;
}
/**
* @brief reverse/swap specified length memory byte-to-byte
* @param out output buffer
* in input buffer
* len size of input buffer
* section_size size of memory section to swap
*
* len = 4:
* section_size=2:[0][1][2][3] ===> [1][0][3][2]
* section_size=4:[0][1][2][3] ===> [3][2][1][0], the same as big/small endian convert on integer
*
* section_size = 0 means section_size is the len
*
* @return 0 is ok
**/
int memswap(void *out, const void *in, unsigned len, unsigned section_size)
{
if (out == NULL || in == NULL || len % section_size)
return -1;
if (len <= 1 || section_size <= 1)
return 0;
if (section_size == 0) {
section_size = len;
}
unsigned num = len/section_size;
for (unsigned i=0; i<num; i++) {
char *pin = (char *)in + i*section_size;
char *pout = (char *)out + i*section_size;
unsigned ss = 0;
while (ss < section_size/2) {
char c = pin[ss];
pout[ss] = pin[section_size - ss - 1];
pout[section_size - ss - 1] = c;
ss++;
}
}
return 0;
}
#ifdef __cplusplus
}
#endif
|
C
|
/*! \file thread.h
*
* Declarations for the kernel threading functionality in PintOS.
*/
#ifndef THREADS_THREAD_H
#define THREADS_THREAD_H
#include <debug.h>
#include <hash.h>
#include <list.h>
#include <stdint.h>
#include "synch.h"
/* Open file. This is for a linked list of open files in each thread. */
struct sys_file {
struct file *file;
int fd;
struct list_elem file_elem;
};
/* Memory mapped files. This is for a linked list of mmapped files in each thread. */
struct mmap_file {
void *addr; /*!< Virtual address to which file is mapped. */
int fd; /*!< Mapped file. */
int mapping; /*!< Unique mmap ID. */
struct list_elem mmap_elem;
};
/*! Initial thread, the thread running init.c:main(). */
struct thread *initial_thread;
/*! States in a thread's life cycle. */
enum thread_status {
THREAD_RUNNING, /*!< Running thread. */
THREAD_READY, /*!< Not running but ready to run. */
THREAD_BLOCKED, /*!< Waiting for an event to trigger. */
THREAD_DYING /*!< About to be destroyed. */
};
/*! Thread identifier type.
You can redefine this to whatever type you like. */
typedef int tid_t;
#define TID_ERROR ((tid_t) -1) /*!< Error value for tid_t. */
/* Thread priorities. */
#define PRI_MIN 0 /*!< Lowest priority. */
#define PRI_DEFAULT 31 /*!< Default priority. */
#define PRI_MAX 63 /*!< Highest priority. */
/* Open files' file descriptors. */
#define CONSOLE_FD 2 /*!< fd 0 and 1 reserved. */
/*! A kernel thread or user process.
Each thread structure is stored in its own 4 kB page. The
thread structure itself sits at the very bottom of the page
(at offset 0). The rest of the page is reserved for the
thread's kernel stack, which grows downward from the top of
the page (at offset 4 kB). Here's an illustration:
\verbatim
4 kB +---------------------------------+
| kernel stack |
| | |
| | |
| V |
| grows downward |
| |
| |
| |
| |
| |
| |
| |
| |
+---------------------------------+
| magic |
| : |
| : |
| name |
| status |
| tid |
0 kB +---------------------------------+
\endverbatim
The upshot of this is twofold:
1. First, `struct thread' must not be allowed to grow too
big. If it does, then there will not be enough room for
the kernel stack. Our base `struct thread' is only a
few bytes in size. It probably should stay well under 1
kB.
2. Second, kernel stacks must not be allowed to grow too
large. If a stack overflows, it will corrupt the thread
state. Thus, kernel functions should not allocate large
structures or arrays as non-static local variables. Use
dynamic allocation with malloc() or palloc_get_page()
instead.
The first symptom of either of these problems will probably be
an assertion failure in thread_current(), which checks that
the `magic' member of the running thread's `struct thread' is
set to THREAD_MAGIC. Stack overflow will normally change this
value, triggering the assertion.
The `elem' member has a dual purpose. It can be an element in
the run queue (thread.c), or it can be an element in a
semaphore wait list (synch.c). It can be used these two ways
only because they are mutually exclusive: only a thread in the
ready state is on the run queue, whereas only a thread in the
blocked state is on a semaphore wait list.
*/
struct thread {
/*! Owned by thread.c. */
/**@{*/
tid_t tid; /*!< Thread identifier. */
enum thread_status status; /*!< Thread state. */
char name[16]; /*!< Name (for debugging purposes). */
uint8_t *stack; /*!< Saved stack pointer. */
int priority; /*!< Priority. */
int donated_priority; /*!< Donated priority. */
struct list_elem allelem; /*!< List element for all threads list. */
struct list_elem sleep_elem; /*!< List element for sleeping list. */
int64_t sleep_counter; /*!< Number of ticks left to sleep. */
int niceness; /*!< Niceness value for BSD CPU priority. */
int recent_cpu; /*!< Most recent CPU time usage. Fixed point. */
struct lock *blocking_lock; /*!< Lock that is blocking this thread */
struct list locks_acquired; /*!< Locks this thread is blocking */
/**@}*/
/*! Shared between thread.c and synch.c. */
/**@{*/
struct list_elem elem; /*!< List element. */
struct list_elem lock_elem; /*!< List element for lock's blocked_threads. */
/**@}*/
/*! Shared between thread.c and userprog/syscall.c. */
/**@{*/
int num_files; /*!< Number of open files (counting closed ones). */
struct list open_files; /*!< Open files. */
/**@}*/
/*! Shared between userprog/process.c and thread.c. */
/**@{*/
int exit_status; /*!< Exit status to be retrieved by parent. */
struct list kids; /*!< List of children processes. */
struct list_elem kid_elem; /*!< List element for parent's kids list. */
struct semaphore wait_sema; /*!< Sempahore for process_wait. */
struct semaphore done_sema; /*!< Sempahore for process_exit. */
bool waited_on; /*!< True if process_wait has been called. */
struct lock wait_lock; /*!< Lock for checking waited_on. */
/**@}*/
/*! Shared between by userprog/process.c and userprog.syscall.c and
thread.c. */
/**@{*/
struct thread *parent; /*!< Thread that created this one. */
struct semaphore exec_load; /*!< Semaphore for checking when executable has loaded. */
bool loaded; /*!< Check if exec loaded successfully. */
struct file *executable; /*!< Executable to keep open until done. */
/**@}*/
#ifdef USERPROG
/*! Owned by userprog/process.c. */
/**@{*/
uint32_t *pagedir; /*!< Page directory. */
/**@}*/
#endif
#ifdef VM
struct hash sup_page; /*!< Supplemental Page Table. */
struct list mappings; /*!< Memory mapped files. */
int num_mappings; /*!< Number of mappings (including unmapped). */
uint8_t *esp; /*!< esp to pass to page_fault */
#endif
#ifdef CACHE
struct inode *cur_dir_inode; /*!< Current directory inode. */
#endif
/*! Owned by thread.c. */
/**@{*/
unsigned magic; /* Detects stack overflow. */
/**@}*/
};
/*! If false (default), use priority scheduler.
If true, use multi-level feedback queue scheduler.
Controlled by kernel command-line option "-o mlfqs". */
extern bool thread_mlfqs;
bool is_thread(struct thread *);
void thread_init(void);
void thread_start(void);
void thread_tick(void);
void thread_print_stats(void);
typedef void thread_func(void *aux);
tid_t thread_create(const char *name, int priority, thread_func *, void *);
void thread_block(void);
void thread_unblock(struct thread *);
struct thread *thread_current (void);
tid_t thread_tid(void);
const char *thread_name(void);
void thread_exit(void) NO_RETURN;
void thread_yield(void);
/*! Performs some operation on thread t, given auxiliary data AUX. */
typedef void thread_action_func(struct thread *t, void *aux);
void thread_foreach(thread_action_func *, void *);
int get_priority(struct thread *thread_to_check);
int thread_get_priority(void);
void thread_set_priority(int);
void thread_donate_priority(struct thread *recipient, int new_priority);
void thread_reset_priority(struct thread *recipient);
int thread_get_nice(void);
void thread_set_nice(int);
int thread_get_recent_cpu(void);
int thread_get_load_avg(void);
int highest_priority(int priority);
int get_highest_priority(void);
bool is_highest_priority(int test_priority);
bool is_valid_fd(int fd);
bool is_existing_fd(struct thread *cur, int fd);
int next_fd(struct thread *cur);
int add_open_file(struct thread *cur, struct file *file, int fd);
struct file *get_fd(struct thread *cur, int fd);
void close_fd(struct thread *cur, int fd);
#ifdef VM
bool is_valid_mapping(int mapping);
bool is_existing_mapping(struct thread *cur, int mapping);
int next_mapping(struct thread *cur);
int add_mmap(struct thread *cur, void *addr, int fd, int mapping);
struct mmap_file *get_mmap(struct thread *cur, int mapping);
void remove_mmap(struct thread *cur, int mapping);
#endif
void add_sleep_thread(struct thread *);
void sleep_threads(void);
struct thread *get_initial_thread(void);
struct thread *get_child_thread(tid_t child_tid);
#endif /* threads/thread.h */
|
C
|
#include <stdio.h>
/*Exercise4 (M)
Write a program that calculated are of two squares (A and B). After this the program will tell how many squares B can fit in square A. Print the result of the calculations to the screen.
...
This program calculates how many of square A can fit into square B */
int main(void)
{
printf("How many squares A into square B?\n");
float lengthA, lengthB, resultA, resultB, AintoB;
lengthA = 5;
lengthB = 8;
resultA = (lengthA*lengthA);
resultB = (lengthB*lengthB);
AintoB = (resultB/resultA);
printf("%.1f x %.1f = %.1f\n", lengthA, lengthA, resultA);
printf("%.1f x %.1f = %.1f\n", lengthB, lengthB, resultB);
printf("There are %.1f As that can fit into B.\n", AintoB);
return 0;
}
|
C
|
// Program in C to create a Doubly Circular Linked List
#include <stdio.h>
#include <stdlib.h>
// Structure of a node
struct node {
int data;
struct node *previous;
struct node *next;
};
void printLinkedlist(struct node *p, struct node *start);
void printLinkedlistReversed(struct node *p, struct node *start);
void main() {
// Initialize nodes
struct node *head;
struct node *one = NULL;
struct node *two = NULL;
struct node *three = NULL;
// Allocating Memory
one = malloc(sizeof(struct node));
two = malloc(sizeof(struct node));
three = malloc(sizeof(struct node));
// Assign data values
one->data = 1;
two->data = 2;
three->data = 3;
// Connecting Nodes
one->next = two;
one->previous= three;
two->next = three;
two->previous= one;
three->next = one;
three->previous= two;
head = one;
printLinkedlist(head, head); //Forward Circular Order
printLinkedlistReversed(head, head); //Backward order
}
// print the linked list value in forward order
void printLinkedlist(struct node *p, struct node *start) {
do {
printf("%d ", p->data);
p = p->next;
} while (p->data != start->data);
}
// print the linked list value in backward order
void printLinkedlistReversed(struct node *p, struct node *start) {
do {
p = p->previous;
printf("%d ", p->data);
} while (p != start);
}
|
C
|
//*****************************************************************************
//
// Name(s): Justin Cox & Tyler Travis
//
//
//*****************************************************************************
#include <inc/tm4c123gh6pm.h>
#include <stdint.h>
#include <stdbool.h>
#include <inc/hw_memmap.h>
#include <driverlib/gpio.h>
#include <driverlib/pin_map.h>
#include <driverlib/rom.h>
#include <driverlib/sysctl.h>
#include <driverlib/uart.h>
#include <utils/uartstdio.h>
void echo(void);
int main(void)
{
uint32_t port = 0;
uint32_t baudrate = 115200;
uint32_t srcCLK = 16000000;
// Set the clocking to run directly from the crystal.
ROM_SysCtlClockSet(SYSCTL_SYSDIV_4 | SYSCTL_USE_PLL | SYSCTL_XTAL_16MHZ | SYSCTL_OSC_MAIN);
// Enable the GPIO port that is used for the on-board LED.
ROM_SysCtlPeripheralEnable(SYSCTL_PERIPH_GPIOF);
// Enable the GPIO pins for the LED (PF2 & PF3).
ROM_GPIOPinTypeGPIOOutput(GPIO_PORTF_BASE, GPIO_PIN_2);
//*********************************************
// Initialize the UART.
//*********************************************
// Enable the GPIO Peripheral used by the UART.
ROM_SysCtlPeripheralEnable(SYSCTL_PERIPH_GPIOA);
// Enable UART0
ROM_SysCtlPeripheralEnable(SYSCTL_PERIPH_UART0);
// Configure GPIO Pins for UART mode.
ROM_GPIOPinConfigure(GPIO_PA0_U0RX);
ROM_GPIOPinConfigure(GPIO_PA1_U0TX);
ROM_GPIOPinTypeUART(GPIO_PORTA_BASE, GPIO_PIN_0 | GPIO_PIN_1);
// Use the internal 16MHz oscillator as the UART clock source.
UARTClockSourceSet(UART0_BASE, UART_CLOCK_PIOSC);
// Initialize the UART for console I/O.
UARTStdioConfig(port, baudrate, srcCLK);
while(1)
{
echo();
}
}
void echo(void){
char buffer[32];
UARTgets(buffer, sizeof(buffer));
UARTprintf("%s \n", buffer);
}
|
C
|
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <math.h>
int main() {
char inputStr[14];
char outIntPart[61], outFracPart[61];
char digits[] = "0123456789abcdef";
int b1, b2, i, dotCounts = 0, frac = 0;
int scannedCounts;
scannedCounts = scanf("%d%d%13s", &b1, &b2, inputStr);
if (scannedCounts != 3)
return 0;
int lenInputStr = strlen(inputStr);
for (i = 0; i < lenInputStr; i++) {
if (inputStr[i] == '.')
dotCounts++;
else if (llabs(strchr(digits, tolower(inputStr[i])) - digits) >= b1)
break;
}
if (dotCounts > 1 || inputStr[0] == '.' || inputStr[lenInputStr - 1] == '.' ||
b1 < 2 || b1 > 16 || b2 < 2 || b2 > 16 || i < lenInputStr - 1){
printf("bad input");
return 0;
}
int sizeIntPart;
if (dotCounts == 0) {
sizeIntPart = lenInputStr;
}
else{
frac = 1;
sizeIntPart = strchr(inputStr, '.') - inputStr;
}
long long intPart = 0;
for (i = 0; i < sizeIntPart; i++)
intPart = intPart * b1 + (strchr(digits, tolower(inputStr[i])) - digits);
int indexIntPart = 0;
while (intPart != 0) {
int a = intPart % b2;
outIntPart[indexIntPart++] = digits[a];
intPart = (intPart - a) / b2;
}
double fracPart = 0;
for (i = lenInputStr - 1; i > sizeIntPart; i--)
fracPart = (fracPart + (strchr(digits, tolower(inputStr[i])) - digits)) / b1;
int indexFracPart = 0;
if (frac) {
while (indexFracPart < 12) {
double a = fracPart * b2;
outFracPart[indexFracPart++] = digits[(int) a];
fracPart = fracPart * b2 - floor(a);
}
}
if (indexIntPart == 0)
printf("0");
else
for (i = indexIntPart - 1; i >= 0; i--)
printf("%c", outIntPart[i]);
if (frac) {
printf(".");
for (i = 0; i < indexFracPart; i++)
printf("%c", outFracPart[i]);
}
}
|
C
|
/*
* median.c
*/
#include "Funcs.h"
#define DEFINE_MEDIAN_1D(TYPE_NAME,TYPE)\
static int cmp_##TYPE(a,b) TYPE *a,*b; {return *a - *b;}\
static void median_##TYPE(dest,src,median)\
image dest;\
image src;\
register long median;\
{\
register TYPE **src_data;\
register TYPE **dest_data;\
register long x,y;\
register long xsize,ysize;\
TYPE pix[9];\
\
image__type_check("image__median",src,TYPE_NAME);\
\
xsize = Image.xsize(src);\
ysize = Image.ysize(src);\
\
Image.make(dest,TYPE_NAME,xsize,ysize);\
\
src_data = (TYPE **)Image.data(src);\
dest_data = (TYPE **)Image.data(dest);\
\
for (y = 1; y < ysize - 1; y++)\
for (x = 1; x < xsize - 1; x++)\
{\
pix[0] = src_data[y-1][x-1];\
pix[1] = src_data[y-1][x];\
pix[2] = src_data[y-1][x+1];\
pix[3] = src_data[y][x-1];\
pix[4] = src_data[y][x];\
pix[5] = src_data[y][x+1];\
pix[6] = src_data[y+1][x-1];\
pix[7] = src_data[y+1][x];\
pix[8] = src_data[y+1][x+1];\
qsort(pix,9,sizeof(TYPE),cmp_##TYPE);\
dest_data[y][x] = pix[median];\
}\
\
for (x = 0; x < xsize; x++)\
{\
dest_data[0][x] = dest_data[1][x];\
dest_data[ysize-1][x] = dest_data[ysize-2][x];\
}\
for (y = 0; y < ysize; y++)\
{\
dest_data[y][0] = src_data[y][1];\
dest_data[y][xsize-1] = src_data[y][xsize-2];\
}\
dest_data[0][0] = dest_data[1][1];\
dest_data[ysize-1][0] = dest_data[ysize-2][1];\
dest_data[ysize-1][xsize-1] = dest_data[ysize-2][xsize-1];\
dest_data[0][xsize-1] = dest_data[1][xsize-1];\
}
#define DEFINE_MEDIAN_3D(TYPE_NAME,TYPE)\
static int cmp0_##TYPE(a,b) TYPE *a,*b; {return a->at[0] - b->at[0];}\
static int cmp1_##TYPE(a,b) TYPE *a,*b; {return a->at[1] - b->at[1];}\
static int cmp2_##TYPE(a,b) TYPE *a,*b; {return a->at[2] - b->at[2];}\
static void median_##TYPE(dest,src,median)\
image dest;\
image src;\
long median;\
{\
register TYPE **src_data;\
register TYPE **dest_data;\
register long x,y;\
TYPE pix[9];\
long xsize,ysize;\
\
image__type_check("image__median",src,TYPE_NAME);\
\
xsize = Image.xsize(src);\
ysize = Image.ysize(src);\
\
Image.make(dest,TYPE_NAME,xsize,ysize);\
\
src_data = (TYPE **)Image.data(src);\
dest_data = (TYPE **)Image.data(dest);\
\
for (y = 1; y < ysize - 1; y++)\
for (x = 1; x < xsize - 1; x++)\
{\
pix[0] = src_data[y-1][x-1];\
pix[1] = src_data[y-1][x];\
pix[2] = src_data[y-1][x+1];\
pix[3] = src_data[y][x-1];\
pix[4] = src_data[y][x];\
pix[5] = src_data[y][x+1];\
pix[6] = src_data[y+1][x-1];\
pix[7] = src_data[y+1][x];\
pix[8] = src_data[y+1][x+1];\
\
qsort(pix,9,sizeof(TYPE),cmp0_##TYPE);\
dest_data[y][x].at[0] = pix[median].at[0];\
\
qsort(pix,9,sizeof(TYPE),cmp1_##TYPE);\
dest_data[y][x].at[1] = pix[median].at[1];\
\
qsort(pix,9,sizeof(TYPE),cmp2_##TYPE);\
dest_data[y][x].at[2] = pix[median].at[2];\
}\
\
for (x = 0; x < xsize; x++)\
{\
dest_data[0][x] = dest_data[1][x];\
dest_data[ysize-1][x] = dest_data[ysize-2][x];\
}\
for (y = 0; y < ysize; y++)\
{\
dest_data[y][0] = src_data[y][1];\
dest_data[y][xsize-1] = src_data[y][xsize-2];\
}\
dest_data[0][0] = dest_data[1][1];\
dest_data[ysize-1][0] = dest_data[ysize-2][1];\
dest_data[ysize-1][xsize-1] = dest_data[ysize-2][xsize-1];\
dest_data[0][xsize-1] = dest_data[1][xsize-1];\
}
DEFINE_MEDIAN_1D(UChar,uchar)
DEFINE_MEDIAN_1D(Short,short)
DEFINE_MEDIAN_1D(Long,long)
DEFINE_MEDIAN_1D(Float,float)
DEFINE_MEDIAN_3D(UChar3,uchar3)
typedef void (*f_caller) P ((image dest,image src,long median));
static caller_table table[] = {
{UChar, median_uchar},
{Short, median_short},
{Long, median_long},
{Float, median_float},
{UChar3, median_uchar3}
};
void image__median(dst,src,median)
image dst;
image src;
long median;
{
f_caller caller;
caller = (f_caller)image__caller("image__median",src,Number(table),table);
if (caller) caller(dst,src,median);
}
|
C
|
#include <sys/time.h> //struct timeval
#include <stdlib.h> //rand, srand, RAND_MAX
#include <stdio.h> //fprintf, stderr
#include <time.h> //time
#include "utils.h"
long time_diff_us(struct timeval end , struct timeval start)
{
return (end.tv_sec - start.tv_sec) * 1000000 + end.tv_usec - start.tv_usec;
}
int myrandom(int max_range)
{
if(max_range <= 0 || max_range > RAND_MAX)
{
fprintf(stderr, "ERROR: Invalid argument max_range (=%d) of function myrandom", max_range);
return -1;
}
srand(time(NULL)); //use current time as seed for random generator
return rand() % max_range;
}
|
C
|
/*************************************************************************
> File Name: tcp_client.c
> Author: jack
> Mail: hansheng.jiayou@qq.com
> Created Time: 2018-03-20 14:47:45
************************************************************************/
//此程序的作用为验证-面向连接的套接字
//“传输的数组不存在边界”
#include<stdio.h>
#include<unistd.h>
#include<stdlib.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<arpa/inet.h>
#include<string.h>
int main(int argc, const char *argv[])
{
if(argc != 3)
{
printf("参数错误\n");
exit(1);
}
int sock = socket(PF_INET,SOCK_STREAM,0);
if(sock == -1)
{
perror("socket");
exit(1);
}
struct sockaddr_in serv_addr;
memset(&serv_addr,0,sizeof(serv_addr));
serv_addr.sin_family = PF_INET;
serv_addr.sin_addr.s_addr = inet_addr(argv[1]);
serv_addr.sin_port = htons(atoi(argv[2]));
//客户端创建tcp连接
if(connect(sock,(struct sockaddr*)&serv_addr,sizeof(serv_addr)) == -1)
{
perror("connect");
exit(1);
}
//多次读取
int read_size = 0;
int all_size = 0;
char buf[1024] = {0};
int i = 0;
while(read_size = read(sock,&buf[i++],1))
{
if(read_size == -1)
{
perror("read");
exit(1);
}
all_size += read_size;
}
printf("来自服务器的消息:%s\n",buf);
printf("read函数调用的次数:%d\n",all_size);
close(sock);
return 0;
}
|
C
|
#include <stdio.h>
#define MAX_N (1100)
int prime[300], prime2[300];
int n;
int init_prime()
{
int i, j;
prime[0] = 1;
prime2[0] = 1;
prime[1] = 2;
prime2[1] = 4;
n = 2;
for(i = 3; i < MAX_N; i += 2) {
for (j = 1; prime2[j] <= i; j++)
if (i % prime[j] == 0)
break;
if (prime2[j] > i) {
prime[n] = i;
prime2[n++] = i * i;
}
}
return 0;
}
int main()
{
int i, j;
int k, c, count;
init_prime();
while (scanf("%d%d", &k, &c) == 2) {
printf("%d %d:", k, c);
for (count = 0; prime[count] <= k; count++) ;
if (!count) {
printf("\n\n");
continue;
}
if (c > (count >> 1)) {
for (i = 0; i < count; i++)
printf(" %d", prime[i]);
printf("\n\n");
continue;
}
if (count % 2) {
for (i = (count >> 1) - c + 1, j = 0;
j < 2 * c - 1; i++, j++)
printf(" %d", prime[i]);
printf("\n\n");
continue;
}
for (i = (count >> 1) - c, j = 0;
j < 2 * c; i++, j++)
printf(" %d", prime[i]);
printf("\n\n");
}
return 0;
}
|
C
|
#include<stdio.h>
#include<conio.h>
int main()
{
int a[10],i,item,n,pos;
printf("Enter the no of elements of array:");
scanf("%d",&n);
printf("Enter the elements of array:");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
printf("Enter the value of the item and position to be inserted in array:");
scanf("%d%d",&item,&pos);
for(i=n-1;i>=pos-1;i--)
a[i+1]=a[i];
a[i+1]=item;
n=n+1;
printf("\nafter insertion the array elements are:");
for(i=0;i<n;i++)
printf("\n%d",a[i]);
return 0;
}
|
C
|
/*
** EPITECH PROJECT, 2019
** MyFTP
** File description:
** Helper function
*/
#include <stdio.h>
void print_helper(void)
{
printf("USAGE: ./myftp port path\n");
printf("\tport\tis the port number on which the server socket listens\n");
printf("\tpath\tis the path to the home directory for the anonymous"\
"user\n");
}
|
C
|
// Fibonacci recursion
// 通过算法分析,发现其实 Fibonacci数列其实并不适合用递归啊!
// 因为每次调用求 Fibonacci(num-1) 对 Fibonacci(num-2) 多算了一次,因此递归会霸占更多的内存,
// 程序会变慢,到后面会发现时间复杂度将会呈指数增长。
// 不过题目要求,没办法。。。
// 其实通过分析发现,可以用for用一个buffer数组储存。
// from Eajack <Note>
// 2016.11.17
#include <stdio.h>
int Fibonacci(int num);
int main()
{
int i,len;
while(len)
{
printf("\nEnter the length of Fibonacci's string you want to get:");
scanf("%d",&len);
if(len<=0)
{
printf("len > 0 !\n");
printf("\nEnter the length of Fibonacci's string you want to get:");
}
else
{
for(i=1;i<=len;i++)
{
printf("%d\n",Fibonacci(i));
}
}
}
}
int Fibonacci(int num)
{
if(num<=1)
return 1;
else
return Fibonacci(num-1)+Fibonacci(num-2);
}
|
C
|
#include <stdio.h>
int swap(int *a, int *b);
int main()
{
int a = 2, b = 5;
printf("두 변수의 값을 바꿔주는 함수\n");
printf("바꾸기 전 a : %d, b : %d\n", a, b);
swap(&a, &b);
printf("바꾼 후 a : %d b : %d\n", a, b);
return 0;
}
int swap(int *a, int *b)
{
// XOR Swap : https://en.wikipedia.org/wiki/XOR_swap_algorithm
if (a != b)
{
*a = *a ^ *b;
*b = *a ^ *b;
*a = *a ^ *b;
}
}
|
C
|
/*************************************************************************
> File Name: 1.c
> Author:
> Mail:
> Created Time: 2016年04月26日 星期二 09时22分50秒
************************************************************************/
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
int main(void)
{
int a[10];
int *p =a;
int i;
srand((int)time(NULL));
for(i = 0;i < 10;++i)
{
a[i] = rand() % 100;
printf("%d\n",a[i]);
}
for(i = 9;i >= 0;--i)
{
printf("%d\n",*(p+i));
}
return 0;
}
|
C
|
//////////////////////////////////////////////
// AVR UART LIBRARY
// FOR ATMEGA8
//
// ONLY IMPLEMENTS THE ASYNCHRONOUS MODE
//
// DECEMBER 26, 2016
//
// ANKIT BHATNAGAR
// ANKIT.BHATNAGARINDIA@GMAIL.COM
//////////////////////////////////////////////
#include "AVR_UART_ATMEGA8.h"
int8_t AVR_UART_Init(uint16_t baud, uint8_t data_size, uint8_t parity, uint8_t stop_bits, uint8_t u2x)
{
//INTIALIZE UART PERIPHERAL
//WITH THE SPECIFIED PARAMETERS
//SET BAUDRATE
uint16_t ubbr_val = (F_CPU / (baud * 16UL)) - 1;
UBRRH = (uint8_t)(AVR_UART_URSEL_UBRRH | (ubbr_val >> 8)); //set UBRR register
UBRRL = (uint8_t)ubbr_val;
//SET REMAINING PARAMETERS
UCSRC |= (AVR_UART_URSEL_UCSRC | parity);
UCSRC |= (AVR_UART_URSEL_UCSRC | stop_bits);
//SET U2X IF ENABLED
UCSRA |= u2x;
switch(data_size)
{
case AVR_UART_DATASIZE_5: //NOTHING REQUIRED
break;
case AVR_UART_DATASIZE_6:
UCSRC |= (AVR_UART_URSEL_UCSRC | (1 << 1));
break;
case AVR_UART_DATASIZE_7:
UCSRC |= (AVR_UART_URSEL_UCSRC | (1 << 2));
break;
case AVR_UART_DATASIZE_8:
UCSRC |= (AVR_UART_URSEL_UCSRC | (1 << 2) | (1 << 1));
break;
case AVR_UART_DATASIZE_9:
UCSRC |= (AVR_UART_URSEL_UCSRC | (1 << 2) | (1 << 1));
UCSRB |= (1 << 2);
break;
default:
return AVR_UART_ERROR;
}
return AVR_UART_OK;
}
int8_t AVR_UART_Enable(void)
{
//ENABLE (CLOCK TO) UART PERIPHERAL
//ENABLE BOTH TX AND RX
UCSRB |= ((1 << 4) | (1 << 3));
return AVR_UART_OK;
}
int8_t AVR_UART_Disable(void)
{
//DISBALE (CLOCK TO) UART PERIPHERAL
//DISABLE BOTH TX AND RX
UCSRB &= ~((1 << 4) | (1 << 3));
return AVR_UART_OK;
}
int8_t AVR_UART_Data_Tx(uint8_t data)
{
//SEND SINGLE BYTE OF DATA THROUGH THE
//UART PERIPHERAL
//ENSURE UART TX DATA REGISTER EMPTY
while((UCSRA & (1 << UDRE)) == 0);
UDR = data;
return AVR_UART_OK;
}
int8_t AVR_UART_Data_Tx_Block(uint8_t* data_block, uint8_t size)
{
//SEND MULTIPLE BYTES OF DATA THROUGH UART PERIPHERAL
while(size != 0)
{
AVR_UART_Data_Tx(*data_block++);
size--;
}
return AVR_UART_OK;
}
int8_t AVR_UART_Data_Rx_Blocking(uint8_t* data)
{
//RECEIVE SINGLE BYTE OF DATA THROUGH UART PERIPHERAL
//BLOCKS TILL DATA AVAILABLE
//WAIT FOR DATA TO BE AVAILABLE
while((UCSRA & (1 << RXC)) == 0);
*data = UDR;
return AVR_UART_OK;
}
int8_t AVR_UART_Data_Rx_Non_Blocking(uint8_t* data)
{
//RECEIVE SINGLE BYTE OF DATA THROUGH UART PERIPHERAL
//NON BLOCKING. RETURNS ERROR IF NO DATA AVAILABLE
//CHECK IF DATA AVAILABLE
if((UCSRA & (1 << RXC)) != 0)
{
*data = UDR;
}
else
{
return AVR_UART_ERROR;
}
return AVR_UART_OK;
}
int8_t AVR_UART_Data_Rx_Block(uint8_t* data_block, uint8_t* size)
{
//RECEIVE MULTIPLE BYTES OF DATA THROUGH UART PERIPHERAL
//GET DATA TILL UART SIGNALS RX DATA PRESENT
//THEN COMPARE THE NUMBER OF BYTES RECEIVED WITH NO OF BYTES
//REQUESTED AND DEPENDING ON THAT, RETURN OK OR (ERROR + MODIFY
//SIZE PARAMETER POINTER TO THE NUMBER OF BYTES ACTUALLY READ
uint8_t counter = 0;
while(counter != (*size))
{
AVR_UART_Data_Rx_Blocking(data_block);
//AVR_UART_data_tx(*data_block);
counter++;
data_block++;
}
//AVR_UART_data_tx('\n');
return AVR_UART_OK;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <GL/glut.h>
void keyboard(unsigned char key, int x, int y)
{
if (key == 27)
exit(0);
}
void display()
{
glClear(GL_COLOR_BUFFER_BIT);
glutSwapBuffers();
}
int main(int argc, char *argv[])
{
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_RGBA|GLUT_DOUBLE|GLUT_DEPTH);
glutInitWindowSize(800, 600);
glutInitWindowPosition(100, 100);
glutCreateWindow("Window");
glutKeyboardFunc(keyboard);
glutDisplayFunc(display);
glutMainLoop();
return 0;
}
|
C
|
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/module.h>
#include <linux/list.h>
#include <linux/types.h>
#include <linux/slab.h>
#define SETMEMORY(person) person = kmalloc(sizeof(*person),GFP_KERNEL);
static LIST_HEAD(birthday_list);
struct birthday
{
int day;
int month;
int year;
char *name;
struct list_head list;
};
void set_birthday(struct birthday *person,int day,int month,int year,char name[])
{
person->day = day;
person->month = month;
person->year = year;
person->name = name;
INIT_LIST_HEAD(&person->list);
list_add_tail(&person->list,&birthday_list);
}
static int simple_init(void)
{
struct birthday *mio,*aqua,*shion,*ina,*fbk;
struct birthday *ptr;
char *name;
printk(KERN_INFO "Birthday Module\n");
SETMEMORY(mio);
SETMEMORY(aqua);
SETMEMORY(shion);
SETMEMORY(ina);
SETMEMORY(fbk);
name = "mio\0";
set_birthday(mio,20,8,2000,name);
name = "aqua\0";
set_birthday(aqua,11,1,2001,name);
name = "shion\0";
set_birthday(shion,22,2,2002,name);
name = "ina\0";
set_birthday(ina,3,3,2003,name);
name = "FBK\0";
set_birthday(fbk,4,4,2004,name);
list_for_each_entry(ptr,&birthday_list,list)
{
printk(KERN_INFO "%s -> %d/%d/%d\n",
ptr->name,ptr->year,ptr->month,ptr->day);
}
return 0;
}
static void simple_exit(void)
{
struct birthday *ptr, *next;
printk(KERN_INFO "Remove Module\n");
list_for_each_entry_safe(ptr, next, &birthday_list, list)
{
printk(KERN_INFO "removed %s -> %d/%d/%d\n",
ptr->name,ptr->year,ptr->month,ptr->day);
list_del(&ptr->list);
kfree(ptr);
}
}
module_init(simple_init);
module_exit(simple_exit);
MODULE_DESCRIPTION("Simple ");
MODULE_AUTHOR("107590026");
MODULE_LICENSE("GPL");
|
C
|
/*
** bite_c_4_2
** 2018_10_31
** 0999֮Сˮɻ
*/
#include "stdio.h"
#include "stdlib.h"
#include "math.h"
int main()
{
int i = 0;
int units = 0;
int tens = 0;
int hundreds_digit = 0;
int flag = 0;
printf("ˮɻ: \n");
for (i = 0; i < 1000; i++)
{
if (i < 100)
{
continue;
}
hundreds_digit = i / 100;
tens = i / 10 % 10;
units = i % 10;
flag = pow(hundreds_digit, 3) + pow(tens, 3) + pow(units, 3);
if (i != flag)
{
continue;
}
printf("%d\n", i);
}
system("pause");
return 0;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.