language
large_stringclasses 1
value | text
stringlengths 9
2.95M
|
---|---|
C
|
//
// main.c
// 6--循环作业6--输入一个数,判断是否是质数
//
// Created by YanTianFeng on 15-10-15.
// Copyright (c) 2015年 qianfeng. All rights reserved.
//
#include <stdio.h>
int main(int argc, const char * argv[])
{
// 输入一个数,判断是否是质数(****)(质数,只能被1和它本身整除的数)
int x;
scanf("%d",&x);
int i;
for( i = 2;i < x;i++)
{
if(x % i == 0)
{
break;
}
}
//i == x 质数
//i < x 非质数
if(i == x)
{
printf("%d是质数!\n",x);
}
else
{
printf("%d不是质数!\n",x);
}
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#define LEN 10000
#define NUM_COMMANDS 2
void bubbleSort(double *array, int lenOfArr){
double temp = 0;
for(int i = lenOfArr; i > 1; i--){
for(int j = 0; j < i-1; j++){
if(array[j] > array[i+1]){
temp = array[i]; //Platzwechsel wenn links größer als rechts
array[i] = array[i+1];
array[i+1] = temp;
}
}
}
}
int main(){
int i = 0; // local counter
int userFLAGG;
FILE *fPtr;
double *complexNumber[3]; // real, imag, length
double *userChoice;
for (i = 0; i < 3; i++) { // reseve storage for
complexNumber[i] = (double *)malloc(LEN * sizeof(double));
if (complexNumber[i] == NULL) {
printf("can't reserve storage.\n");
return -1;
}
}
fPtr = fopen("re.txt", "r"); // read real part
if(fPtr == NULL)
{
/* File not created hence exit */
printf("Unable to load file: %s.\n","re.txt");
return -1;
}else{
for(i = 0; i < LEN; i++){
fscanf(fPtr,"%lf",&complexNumber[0][i]);
}
fclose(fPtr);
}
fPtr = fopen("im.txt", "r"); // read imag part and calc the magnitude
if(fPtr == NULL)
{
/* File not created hence exit */
printf("Unable to load file: %s.\n","re.txt");
return -1;
}else{
for(i = 0; i < LEN; i++){
fscanf(fPtr,"%lf",&complexNumber[1][i]);
complexNumber[2][i] = sqrt(pow(complexNumber[0][i],2) + pow(complexNumber[1][i],2));
}
fclose(fPtr);
}
printf("sorting current complex numbers according to ...\n");
printf(" [1] ... re-part\n [2] ... im-part\n [3] ... magnitude\n [0] ... exit\n");
scanf("%d",&userFLAGG);
switch (userFLAGG)
{
case 1:
userChoice = &complexNumber[0][0];
break;
case 2:
userChoice = &complexNumber[1][0];
break;
case 3:
userChoice = &complexNumber[2][0];
break;
default:
printf("invalid choice.\n");
return -1;
}
bubbleSort(userChoice,LEN);
printf("sorting completed\n");
fPtr = fopen("result.txt", "w");
if(fPtr == NULL){
/* File not created hence exit */
printf("Unable to open file: %s.\n","result.txt");
return -1;
}else{
for(i = 0; i < LEN; i++)
{
fprintf(fPtr,"%lf\n",userChoice[i]);
}
fclose(fPtr);
}
char * commandsForGnuplot[] = {"set title \"Results of bubblesort\"", "plot 'result.txt'"};
FILE * gnuplotPipe = popen ("gnuplot -persistent", "w");
for (i=0; i < NUM_COMMANDS; i++)
{
fprintf(gnuplotPipe, "%s \n", commandsForGnuplot[i]); //Send commands to gnuplot one by one.
}
printf("process completed.\n");
return 0;
}
|
C
|
/*
* pressure.c
*
* Created: 13.08.2015 17:25:50
* Author: tonik_000
*/
#include "pressure.h"
static volatile uint16_t pressure_mass[window];
static volatile uint32_t pressure_temp = 0;
void pressure_Init()
{
for (uint8_t i =0; i<window; i++)
{
pressure_mass[i] = pressure_midle();
}
}
uint16_t middle_of_3(uint16_t a, uint16_t b, uint16_t c)
{
uint16_t middle;
if ((a <= b) && (a <= c)){
middle = (b <= c) ? b : c;
}
else{
if ((b <= a) && (b <= c)){
middle = (a <= c) ? a : c;
}
else{
middle = (a <= b) ? a : b;
}
}
return middle;
}
uint16_t pressure_midle ()
{
uint16_t pressure1[3];
uint16_t pressure2[3];
uint16_t pressure_mid;
for (uint8_t i = 0; i<3;i++)
{
for (uint8_t i = 0; i<3;i++)
{
StartConvAdc();
while (bit_is_set(ADCSRA, ADSC));
uint8_t low = ADCL;
uint8_t high = ADCH;
pressure1[i] = ((uint16_t)low)|((uint16_t)high<<8);
}
pressure2[i] = middle_of_3(pressure1[0],pressure1[1],pressure1[2]);
}
return pressure_mid = middle_of_3(pressure2[0],pressure2[1],pressure2[2]);
}
uint16_t cur_pressure_SMA(uint16_t _current_pressure)
{
for (uint8_t i = 1; i < window; i++)
{
pressure_mass[i-1] = pressure_mass[i];
}
pressure_mass[window-1] = _current_pressure;
pressure_temp = 0;
for (uint8_t i = 0; i<window; i++)
{
pressure_temp+=(uint32_t)pressure_mass[i-1]*((uint32_t)(i+1));
}
return (uint16_t)((uint32_t)pressure_temp/(uint16_t)del);
}
|
C
|
/*
Newsgroups: mod.std.unix
Subject: public domain AT&T getopt source
Date: 3 Nov 85 19:34:15 GMT
Here's something you've all been waiting for: the AT&T public domain
source for getopt(3). It is the code which was given out at the 1985
UNIFORUM conference in Dallas. I obtained it by electronic mail
directly from AT&T. The people there assure me that it is indeed
in the public domain.
*/
/*LINTLIBRARY*/
#include <stdio.h>
#include <string.h>
#include "lang.h"
#include "getopt.h"
#define ERR(s, c) if(opterr) fprintf( stderr, "%s: %s -- %c\n", argv[0], s, c )
enum
{
ILLEGAL_OPTION, NO_ARGUMENT,
NUM_MSGS
};
int optind = 1;
static int optopt;
int opterr = 1;
char *optarg;
static char * const messages[ NUM_LANG ][ NUM_MSGS ] =
{
{ "illegal option", "option requires an argument" },
{ "opcion ilegal", "la opcion requiere un argumento" }
};
int
getopt( int argc, char **argv, char *opts )
{
static int sp = 1;
register int c;
register char *cp;
if(sp == 1)
if(optind >= argc || argv[optind][0] != '-' || argv[optind][1] == '\0')
return(EOF);
else if( strcmp(argv[optind], "--" ) == 0)
{
optind++;
return(EOF);
}
optopt = c = argv[optind][sp];
if( c == ':' || ( cp = strchr(opts, c) ) == NULL )
{
ERR( messages[ lang ][ ILLEGAL_OPTION ], c);
if(argv[optind][++sp] == '\0')
{
optind++;
sp = 1;
}
return('?');
}
if( *++cp == ':' )
{
if( argv[optind][sp+1] != '\0' )
optarg = &argv[optind++][sp+1];
else if(++optind >= argc)
{
ERR( messages[ lang ][ NO_ARGUMENT ], c);
sp = 1;
return('?');
} else
optarg = argv[optind++];
sp = 1;
} else
{
if(argv[optind][++sp] == '\0')
{
sp = 1;
optind++;
}
optarg = NULL;
}
return(c);
}
#ifdef TEST_GETOPT
char *args = "b:ijk:";
int
main( int argc, char **argv )
{
int c;
set_getopt_language( SPANISH );
while( ( c = getopt( argc, argv, args ) ) != EOF )
fprintf( stderr, "%c -> %s\n", c, optarg );
return 0;
}
#endif
|
C
|
/*
* Author: Anca Barbu
*/
#ifndef FlowerPlatformMathManip_h
#define FlowerPlatformMathManip_h
int getNumberOfDigitsBeforeDecimal(double num){
if (abs(num) < 1) {
return 1;
}
return floor (log10 (abs (int(num)))) + 1;
}
// doesn't work properly, it must be enhanced
int getNumberOfDigitsAfterDecimal(double num){
int numberOfDigitsAfterDecimal = 0;
num = abs(num);
num = num - int(num);
while (num > 0.001) {
Serial.println(num);
num = num * 10;
numberOfDigitsAfterDecimal = numberOfDigitsAfterDecimal + 1;
num = num - int(num);
}
return numberOfDigitsAfterDecimal;
}
void dtoa(char* numberAsStr, double number){
Serial.println(number);
int numberOfDigitsBeforeDecimal = getNumberOfDigitsBeforeDecimal(number);
int numberOfDigitsAfterDecimal = 2; //TODO it should be calculated, see getgetNumberOfDigitsAfterDecimal() function
dtostrf(number, numberOfDigitsBeforeDecimal + 1 + numberOfDigitsAfterDecimal, numberOfDigitsAfterDecimal, numberAsStr);
Serial.println(numberAsStr);
}
int min_array(int n, ...) {
int i = 0,val, minim;
va_list vl;
va_start(vl, n);
minim = va_arg(vl, int);
for (i = 1; i < n; i++) {
val = va_arg(vl, int);
minim = (val < minim) ? val : minim;
}
va_end(vl);
return minim;
}
int max_array(int n, ...) {
int i = 0,val, max;
va_list vl;
va_start(vl, n);
max = va_arg(vl, int);
for (i = 1; i < n; i++) {
val = va_arg(vl, int);
max = (max > val)?max : val;
}
va_end(vl);
return max;
}
double setPrecision(double number, int prec) {
char numberAsStr[24];
int numberOfDigits = getNumberOfDigitsBeforeDecimal(number);
dtostrf(number, numberOfDigits+prec, prec, numberAsStr);
return strtod(numberAsStr, NULL);
}
String hex(int number) {
return String(number, HEX);
}
String bin(int number) {
return String(number, BIN);
}
int hexToBase10(String number) {
int ul = strtoul (number.c_str(), NULL, 16);
return ul;
}
int binaryToBase10(String number) {
int ul = strtoul (number.c_str(), NULL, 2);
return ul;
}
int powint(int x, int y) {
int val = x;
for (int z = 0; z <= y; z++) {
if (z == 0) {
val = 1;
}
else {
val = val * x;
}
}
return val;
}
#endif
|
C
|
/*
Sabe-se que o quilowatt de energia custa um quinto do salário mínimo.
Faça um programa que receba o valor do salário mínimo e a quantidade de quilowatts consumida por uma residência. calcule e mostre:
a) o valor de cada quilowatt;
b) o valor a ser pago por essa residência;
c) o valor a ser pago com desconto de 15%.
*/
#include <stdio.h>
int main()
{
float salario_min,qtd_kw,valor_kw,valor_casa,valor_desc;
printf("Calculo do custo de quilowatt (Kw)\n");
printf("Digite o valor do salario minimo \n");
scanf("%f%*c",&salario_min);
printf("Digite a qtd de Kw\n");
scanf("%f%*c",&qtd_kw);
valor_kw=salario_min/5;
valor_casa=valor_kw*qtd_kw;
valor_desc=valor_casa-(valor_casa*0.15);
printf("Valor de cada Kw: R$ %.2f\n",valor_kw);
printf("Valor a ser pago: R$ %.2f\n",valor_casa);
printf("Valor com desconto:R$ %.2f\n",valor_desc);
return 0;
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* core.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: arguilla <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2020/09/28 16:13:55 by arguilla #+# #+# */
/* Updated: 2020/09/28 17:29:16 by arguilla ### ########.fr */
/* */
/* ************************************************************************** */
#include "utils.h"
#include "operator.h"
void ft_assign_value(char **av, t_op *op)
{
op->x = ft_atoi(av[1]);
op->operator = av[2];
op->y = ft_atoi(av[3]);
}
int ft_check_value(t_op op)
{
if (ft_strlen(op.operator) != 1 || (op.operator[0] != '+'
&& op.operator[0] != '-' && op.operator[0] != '/'
&& op.operator[0] != '%' && op.operator[0] != '*'))
{
ft_putnbr(0);
ft_putstr("\n");
return (0);
}
if ((op.operator[0] == '/' || op.operator[0] == '%') && op.y == 0)
{
ft_putstr((op.operator[0] == '/')
? "Stop : division by zero\n"
: "Stop : modulo by zero\n");
return (0);
}
return (1);
}
void ft_assign_tab(t_func **tab)
{
tab[0] = &ft_add;
tab[1] = &ft_sub;
tab[2] = &ft_mul;
tab[3] = &ft_mod;
tab[4] = &ft_div;
}
int ft_display_result(t_func **tab, t_op op)
{
if (op.operator[0] == '+')
return ((*tab[0])(op.x, op.y));
if (op.operator[0] == '-')
return ((*tab[1])(op.x, op.y));
if (op.operator[0] == '*')
return ((*tab[2])(op.x, op.y));
if (op.operator[0] == '%')
return ((*tab[3])(op.x, op.y));
if (op.operator[0] == '/')
return ((*tab[4])(op.x, op.y));
return (0);
}
|
C
|
#include "terminal.h"
#include "../lib/spinlock.h"
#include "../memory/paging.h"
/* Line buffer */
typedef struct {
spinlock_t lock;
uint32_t index;
char buf[TERMINAL_BUF_SIZE];
int reading;
int terminal_x;
int terminal_y;
} line_buf_t;
/* Multiple terminals */
static uint32_t active = 0;
static line_buf_t terminals[NUM_TERMINALS];
/* set_terminal
* DESCRIPTION: sets active terminal
* INPUTS: term -- new value
*/
void set_terminal(uint32_t term){
active = term;
}
/* get_active_terminal
* RETURNS: the active terminal
*/
uint32_t get_active_terminal(){
return active;
}
/** terminal_clear_screen
* DESCRIPTION: Clears screen and reprints current terminal buffer
* SIDE EFFECTS: changes screen content
*/
void terminal_clear_screen(){
// This must always happen on the active terminal
uint32_t t = get_active_terminal();
pcb_t* pcb = get_pcb(active_pid);
int old_x, old_y;
if(pcb != NULL && t != pcb->terminal){
set_lib_video_mem(-1);
old_x = get_screen_x();
old_y = get_screen_y();
set_screen_pos(terminals[active].terminal_x, terminals[active].terminal_y);
}
clear();
int i;
for(i = 0; i < TERMINAL_BUF_SIZE; i++){
if(terminals[active].buf[i] == '\0') break;
putc(terminals[active].buf[i]);
}
if(pcb != NULL && t != pcb->terminal){
// Go back to original vmem value
set_terminal_pos(active, get_screen_x(), get_screen_y());
set_screen_pos(old_x, old_y);
set_lib_video_mem(pcb->terminal);
}
cursor_update();
}
/** terminal_init
* DESCRIPTION: initializes the terminal
* SIDE EFFECTS: clears line buffer, initializes spinlock
*/
void terminal_init(){
for(active = 0; active < NUM_TERMINALS; active++){
terminals[active].index = 0;
terminals[active].reading = 0;
memset(terminals[active].buf, '\0', TERMINAL_BUF_SIZE);
spin_lock_init(&terminals[active].lock);
init_video_mem(VIDEO_PTR(active));
}
set_terminal(0);
}
/* terminal_open
* DESCRIPTION: open handler for terminal, does nothing
* INPUTS: file -- pointer to file_t
* RETURN VALUE: 0 on success, -1 on failure
*/
int32_t terminal_open(file_t* file){
return 0;
}
/** terminal_fake_reading
* DESCRIPTION: Sets terminal driver into "reading" mode without
* actually beginning to read. Useful for automated testing
* so that terminal_input doesn't clear on \n so that we can
* avoid needing to use interrupts
* SIDE EFFECTS: sets "reading" flag
*/
void terminal_fake_reading(){
unsigned long flags;
flags = spin_lock_irqsave(&terminals[active].lock);
terminals[active].reading = 1;
spin_unlock_irqrestore(&terminals[active].lock, flags);
}
/** terminal_input
* DESCRIPTION: handles raw input from the keyboard
* INPUTS: c -- raw input character
* RETURN VALUE: 0 on success, -1 if there was no space
* SIDE EFFECTS: adds to line buffer
*/
int terminal_input(char c){
unsigned long flags;
int result = 0;
int index = terminals[active].index;
/* Aquire sole control over buffer */
flags = spin_lock_irqsave(&terminals[active].lock);
// If we don't have anyone reading, we can clear on \n
if(c == '\n' && !terminals[active].reading){
// Clear term_buffer
index = 0;
memset(terminals[active].buf, '\0', TERMINAL_BUF_SIZE);
}
// In canonical mode, process backspaces
else if(c == '\b'){
// Only if there is a key to erase
if(index != 0){
terminals[active].buf[--index] = '\0';
}
else{
result = -1;
}
}
// Add to buffer and increment index if there is space,
// force final character to be a newline
else if((c == '\n' && index < TERMINAL_BUF_SIZE) || index < TERMINAL_BUF_SIZE - 1){
terminals[active].buf[index++] = c;
}
else{
// We couldn't process this byte
result = -1;
}
// Save index changes
terminals[active].index = index;
// Print character if there was space in buffer
if(result != -1){
pcb_t* pcb = get_pcb(active_pid);
if(pcb == NULL || pcb->terminal == active){
putc(c);
cursor_update();
}
else{
set_lib_video_mem(-1);
int old_x = get_screen_x();
int old_y = get_screen_y();
set_screen_pos(terminals[active].terminal_x, terminals[active].terminal_y);
putc(c);
set_terminal_pos(active, get_screen_x(), get_screen_y());
set_lib_video_mem(pcb->terminal);
set_screen_pos(old_x, old_y);
}
}
/* Relenquish control over buffer */
spin_unlock_irqrestore(&terminals[active].lock, flags);
return result;
}
/** terminal_write
* DESCRIPTION: write syscall handler for terminal.
* Writes supplied buffer to screen
* INPUTS: file -- pointer to file_t (unused)
* buf -- the buffer of bytes to write
* n -- the number of bytes to write
* RETURN VALUE: number of bytes written or -1 on failure
* SIDE EFFECTS: writes to the screen
*/
int32_t terminal_write(file_t* file, const void* buf, int32_t n){
if(buf == NULL) return -1;
int i;
for(i = 0; i < n; i++){
putc(((char*)buf)[i]);
}
cursor_update();
return i;
}
/** terminal_read
* DESCRIPTION: Reads line from terminal line-buffer
* (Wait until the next newline)
* INPUTS: file -- pointer to file_t (unused)
* buf -- the buffer to copy to
* n -- the number of bytes to read
* RETURN VALUE: number of bytes read or -1 on failure
*/
int32_t terminal_read(file_t* file, void* buf, int32_t n){
if(buf == NULL && n != 0) return -1;
// Extra null check exists for tests which run outside of a task
pcb_t* pcb = get_pcb(active_pid);
uint32_t term = pcb == NULL ? 0 : pcb->terminal;
// Wait for line to be done
unsigned long flags;
flags = spin_lock_irqsave(&terminals[term].lock);
terminals[term].reading = 1;
uint32_t index = terminals[term].index;
while(index < TERMINAL_BUF_SIZE &&
(index == 0 || (index > 0 && terminals[term].buf[index - 1] != '\n')))
{
spin_unlock_irqrestore(&terminals[term].lock, flags);
flags = spin_lock_irqsave(&terminals[term].lock);
index = terminals[term].index;
}
// Find how many bytes to read
int n_bytes = min(n, index);
memcpy((char*)buf, &terminals[term].buf, n_bytes);
// Clear term_buffer
terminals[term].index = 0;
memset(terminals[term].buf, '\0', TERMINAL_BUF_SIZE);
terminals[term].reading = 0;
// Unlock buffer
spin_unlock_irqrestore(&terminals[term].lock, flags);
return n_bytes;
}
/** terminal_close
* DESCRIPTION: closes terminal driver
* SIDE EFFECTS: none
* INPUTS: file -- poitner to file_t (unused)
* RETURN VALUE: 0 on success, -1 on failure
*/
int32_t terminal_close(file_t* file){
// Nothing to do here
return 0;
}
/* get_terminal_x
* RETURNS: the terminal_x of the specified terminal
* INPUTS: t -- the terminal
*/
int get_terminal_x(uint32_t t){
if(t > NUM_TERMINALS) return -1;
return terminals[t].terminal_x;
}
/* get_terminal_y
* RETURNS: the terminal_y of the specified terminal
* INPUTS: t -- the terminal
*/
int get_terminal_y(uint32_t t){
if(t > NUM_TERMINALS) return -1;
return terminals[t].terminal_y;
}
/* set_terminal_pos
* DESCRIPTION: sets terminal_x and terminal_y of the specified terminal
* INPUTS: t -- the terminal
* x -- the new terminal_x
* y -- the new terminal_y
*/
void set_terminal_pos(uint32_t t, int x, int y){
if(t > NUM_TERMINALS) return;
terminals[t].terminal_x = x;
terminals[t].terminal_y = y;
}
|
C
|
/*
** EPITECH PROJECT, 2021
** Visual Studio Live Share (Workspace)
** File description:
** mouvement
*/
#include "my_rpg.h"
sfVector2f get_enemy_vector(float angle)
{
float ac = sinus(angle);
float cb = sqrt(1 - pow(ac, 2)) * ((angle < 270 && angle > 90) ? -1 : 1);
return (sfVector2f) {cb, ac};
}
float get_angle_to_player(gen_t *prm, enemy_t *self)
{
float x = (self->pos.x / 256) - prm->game.player->coo.x / 256;
float y = (self->pos.y / 256) - prm->game.player->coo.y / 256;
float angle = atan2(y, x) * 180 / M_PI + 180;
return angle;
}
void enemies_movement(gen_t *prm)
{
float angle;
sfVector2f mov;
for (int i = 0; i < prm->game.scenario.enemies_count; i++) {
if (RANGE(prm->game.scenario.enemies[i].pos,
prm->game.player->coo) < 3) {
angle = get_angle_to_player(prm, &prm->game.scenario.enemies[i]);
mov = get_enemy_vector(angle);
ADD_VEC(prm->game.scenario.enemies[i].pos,
mov.x * (2 + prm->game.scenario.enemies[i].speed),
mov.y * (2 + prm->game.scenario.enemies[i].speed))
SPOSE(prm->game.scenario.enemies[i])
}
if (PRANGE(prm->game.scenario.enemies[i].pos,
prm->game.player->coo) < 100) {
prm->game.player->life = fmax(prm->game.player->life - 0.1, 0);
}
}
}
|
C
|
main()
{ int i;
i =3 ;
printf (i) ;
i=(i+i)*(i-i/i) ;
printf (i) ;
if(i==3){i=i+1;}else{i=i+2;}
while(i<15){i=i+3;}
printf(i);
}
|
C
|
#include <stdio.h>
int main(void){
int hours, minutes;
printf("Please enter a 24-hour time: ");
scanf("%d:%d", &hours, &minutes);
if(hours==0){
printf("Equivalent 12-hour time: 12:%.2dAM", minutes);
}
else if(hours==12){
printf"Equivalent 12-hour time: 12:%.2dPM", minutes);
}
else if(hours>12){
printf("Equivalent 12-hour time: %d:%.2dPM", hours-12,minutes);
}
else{
printf("Equivalent 12-hour time: %d:%.2dAM", hours, minutes);
}
return 0;
}
|
C
|
/*
* STM32F103ZETB led.c
*
* Author: David Yang, <[email protected]>
* Copyright: (C) 2020 David Yang
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
* Notes:
* 2020-01-04, rev00, initial
*
*/
#include "led.h"
#include "usart.h"
/*----------------------------------------------------
* led_init()
* description: to initialize led port configuration
*
* in param : None
* out param : None
*----------------------------------------------------
*/
void led_init(void)
{
int cnt;
printf("led_init()........\r\n");
for(cnt=0; cnt < LED_NUM; cnt++) {
gpio_init(led_configuration[cnt].bank, led_configuration[cnt].num,
led_configuration[cnt].mode, led_configuration[cnt].cfg);
}
}
/*
*----------------------------------------------------
* LED_FLASH()
* description:
* let led to flash (on/off)
* import para: int lednum, =0 led 0
* =1 led 1
* ........,=255, led 255
* int status, =0, off, =1, on
*outport para: int ret, = 0
*----------------------------------------------------
*/
int led_flash(int lednum, int status)
{
if(lednum > LED_NUM) printf("led_flash(), lednum error\r\n");
switch(lednum) {
case 0:
LED0 = status;
break;
case 1:
LED1 = status;
break;
default:
break;
}
return 0;
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* tokenizer.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: root <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/05/02 19:28:36 by root #+# #+# */
/* Updated: 2021/05/02 20:36:24 by root ### ########.fr */
/* */
/* ************************************************************************** */
#include "tokenizer.h"
#include "vector.h"
#include "minishell.h"
#include "parser.h"
static size_t
next_space(char *command)
{
char *ref;
ref = command;
while (*ref && ((!ft_isspace(*ref)
|| (ref != command && *(ref - 1) == '\\'))))
++ref;
return (ref - command);
}
static size_t
next_token(char *command)
{
char *ref;
ref = command;
while (ft_isspace(*ref) && (ref == command || *(ref - 1) != '\\'))
++ref;
return (ref - command);
}
static size_t
tok_count(char *command)
{
size_t count;
count = 1;
while (*command)
{
command += next_token(command);
command += next_space(command);
++count;
}
return (count);
}
static void
clean_backslashes(char **tokens)
{
char *line;
char *found;
while (*tokens)
{
line = *tokens;
while (*line)
{
if (*line == '\x1b')
{
ft_memmove(line, line + 1, ft_strlen(line));
continue;
}
found = ft_strchr(SQ_ESCAPES "'", line[1]);
if (*line == '\\' && found && *found)
ft_memmove(line, line + 1, ft_strlen(line));
++line;
}
++tokens;
}
}
char
**tokenize(char *command, char *end)
{
char **out;
size_t i;
size_t next;
if (!(out = ft_calloc((tok_count(command) + 1), sizeof(char *))))
return (NULL);
i = 0;
while (command < end)
{
command += next_token(command);
next = next_space(command);
if (!next)
continue ;
out[i] = ft_strndup(command, next);
command += next;
++i;
}
out[i] = NULL;
clean_backslashes(out);
return (out);
}
|
C
|
/* include rwlockh */
#ifndef __mypthread_rwlock_h
#define __mypthread_rwlock_h
#include <pthread.h>
typedef struct {
pthread_mutex_t rw_mutex; /* basic lock on this struct */
pthread_cond_t rw_condreaders; /* for reader threads waiting */
pthread_cond_t rw_condwriters; /* for writer threads waiting */
int rw_magic; /* for error checking */
int rw_nwaitreaders;/* the number waiting */
int rw_nwaitwriters;/* the number waiting */
int rw_refcount;
/* 4-1 if writer has the lock, else # readers holding the lock */
} mypthread_rwlock_t;
#define RW_MAGIC 0x19283746
/* 4following must have same order as elements in struct above */
#define MYPTHREAD_RWLOCK_INITIALIZER { PTHREAD_MUTEX_INITIALIZER, \
PTHREAD_COND_INITIALIZER, PTHREAD_COND_INITIALIZER, \
RW_MAGIC, 0, 0, 0 }
typedef int mypthread_rwlockattr_t; /* dummy; not supported */
/* 4function prototypes */
int mypthread_rwlock_destroy(mypthread_rwlock_t *);
int mypthread_rwlock_init(mypthread_rwlock_t *, mypthread_rwlockattr_t *);
int mypthread_rwlock_rdlock(mypthread_rwlock_t *);
int mypthread_rwlock_tryrdlock(mypthread_rwlock_t *);
int mypthread_rwlock_trywrlock(mypthread_rwlock_t *);
int mypthread_rwlock_unlock(mypthread_rwlock_t *);
int mypthread_rwlock_wrlock(mypthread_rwlock_t *);
/* $$.bp$$ */
/* 4and our wrapper functions */
#endif /* __mypthread_rwlock_h */
/* end rwlockh */
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <Windows.h>
#include <process.h>
#define TIMES 100
#define TOTAL_STAFF 5
HANDLE hMutex;
UINT __stdcall Staff(PVOID lp)
{
INT Staff_Number = *(INT*)lp;
for(INT i = 0;i < TIMES;i++)
{
WaitForSingleObject(hMutex,INFINITE);
printf("Staff %d enter toilet\n",Staff_Number);
Sleep(rand() % 2);
printf("Staff %d leave toilet\n",Staff_Number);
ReleaseMutex(hMutex);
}
return 0;
}
int main()
{
HANDLE Staff_Handles[TOTAL_STAFF];
int Staff_Numbers[TOTAL_STAFF];
srand(GetTickCount());
hMutex = CreateMutex(NULL,FALSE,NULL);
for(int i = 0; i < TOTAL_STAFF; i++)
{
Staff_Numbers[i] = i;
Staff_Handles[i] = (HANDLE)_beginthreadex(NULL,0,Staff,&Staff_Numbers[i],CREATE_SUSPENDED,NULL);
}
printf("Stuffs are ready\n");
for(int i = 0; i < TOTAL_STAFF; i++)
ResumeThread(Staff_Handles[i]);
WaitForMultipleObjects(TOTAL_STAFF,Staff_Handles,TRUE,INFINITE);
for(int i = 0; i < TOTAL_STAFF; i++)
CloseHandle(Staff_Handles[i]);
CloseHandle(hMutex);
system("pause");
return 0;
}
|
C
|
/*
Project Credit Card
TODO: document
Use Luhn algorithm to check the validity of certain credit card numbers.
1. get input
2. validate type
3. validate length
4. validate start character
5. run Luhn algorithm
6. print result: valid or invalid?
*/
#include <stdlib.h>
#include <math.h>
#include <stdio.h>
#include <string.h>
#include <ctype.h>
void validate_cc_length(char * number);
void validate_card_type(char * number);
int run_luhn_algorithm(char * number);
int double_every_even_digit (char * number);
int sum_two_digits(int number);
int add_odd_digits (char * number);
void check_digits (char * number);
int char_to_int(char character);
void debug(int error_code, char * message);
/*
Gets credit card input from command line
Validates length, digit, and credit card type. If any of these checks fails, program exits.
Validates legitimacy of number using Luhn algorithm.
*/
void main (int argc, char * argv[])
{
if (argc < 2) {
debug(1, "Please enter a credit card number");
}
int valid = 1; // Set a default of 1 which presents card as "invalid"
char * cc_number = argv[1];
printf("You entered: %s", cc_number);
// Check length of credit card number
validate_cc_length(cc_number);
// Check that each character inputted is a digit
check_digits(cc_number);
// Check number type
validate_card_type(argv[1]);
// Check Luhn which gives us the checksum % 10
valid = run_luhn_algorithm(argv[1]);
if (valid == 0)
{ debug(0, "Card is valid!" ); }
else
{ debug(0, "Card is not valid. You are trying to commit fraud!!!"); }
}
/*
Check the length of the credit card number entered.
Must be between 13-16 characters
param {char *} Credit card number as n-digit string
*/
void validate_cc_length(char * number)
{
int min_length = 13,
max_length = 16,
cc_length = strlen(number);
char error_msg[50];
sprintf(error_msg, "Number is %lu digits long", strlen(number));
debug(0, error_msg);
// Number must have more digits than the minimum, fewer than the maximum
if (cc_length < min_length || cc_length > max_length)
{
debug(1, "Number is not the right length");
}
}
/*
Check the start of the credit card number and see if it matches
any of the known credit card companies
param {char *} Credit card number as n-digit string
*/
void validate_card_type(char * number)
{
int card_type,
first_number = char_to_int(number[0]);
char * types[] = { "Visa",
"Mastercard",
"Discover",
"American Express" },
debug_msg[50];
switch (first_number)
{
case 4:
card_type = 0;
break;
case 5:
card_type = 1;
break;
case 6:
card_type = 2;
break;
// AmEx cards must begin with "37"
case 3:
if (number[1] == '7')
{
card_type = 3;
}
else
{
debug(1, "Number does not begin with valid prefix");
}
break;
default:
debug(1, "Number does not begin with a valid digit");
}
sprintf(debug_msg, "Your card: %s.\n", types[card_type]);
debug(0, debug_msg);
}
/*
This function calls each step of the Luhn Algorithm.
param {string} Credit card number
return {int} The result of the Luhn checksum % 10
*/
int run_luhn_algorithm(char * number)
{
int valid = 0,
sum = 0;
char debug_msg[50];
// Run Steps 1 and 2 of the Luhn Algorithm
sum += double_every_even_digit(number);
// Run Step 3
sum += add_odd_digits(number);
sprintf(debug_msg, "Final sum after adding every odd-position digit: %i\n", sum);
debug(0, debug_msg);
// Run Step 4
return sum % 10;
}
/*
This function returns the sum of the doubled value of every other digit.
If the doubled digit is a two-digit number, find the sum of each digit.
param {string} Credit card number
return {int} Sum of every other digit, doubled.
*/
int double_every_even_digit (char * number)
{
int i,
digit,
doubled_digit,
sum = 0;
for (i = strlen(number)-2; i >= 0; i-=2)
{
digit = char_to_int(number[i]);
doubled_digit = digit * 2;
// if doubling gives us a 2-digit number we have to break it down;
// since the double_digit will never be greater than 18 we'll just do this.
sum += sum_two_digits(doubled_digit); // add the ones digit
}
return sum;
}
/*
Given a two-digit number, return the sum of its digits
*/
int sum_two_digits(int number)
{
int sum = 0,
ones_digit = 0;
ones_digit = number % 10;
sum += ones_digit;
sum += (number - ones_digit)/10;
return sum;
}
/*
Luhn Algorithm Step 3: Add all digits in odd places from right to left
param {string} credit card number
return {int} sum of the odd digits
*/
int add_odd_digits (char * number)
{
int i, sum = 0;
for (i = strlen(number)-1; i >= 0; i-=2)
{
sum += char_to_int(number[i]);
}
return sum;
}
/*
Given a string, check each character in the string to see if it is a digit
*/
void check_digits (char * number)
{
int i = 0;
while (number[i] != '\0')
{
if (!isdigit(number[i]))
{
debug(1, "Invalid card number: non-digit found");
}
i++;
}
}
/*
Given a char representing a numeral, return the number value of the char
*/
int char_to_int(char character)
{
if (character >= '0' && character <= '9' )
{
return character - '0';
}
else
{
debug(1, "Invalid character given");
}
}
/*
Called when any errors are raised in the program.
param {int} Error code -- 1 makes you exit. Anything else does nothing.
param {char *} Error message
*/
void debug(int error_code, char * message)
{
printf("\n");
switch (error_code)
{
case 1:
{
printf("Error: %s. Exiting now.", message);
exit(1);
}
case 0:
{
printf("%s", message);
break;
}
}
printf("\n");
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
int main()
{
int fd;
int result;
fd = open("/sys/class/gpio/export", O_RDWR);
if (fd < 0) {
perror("Open");
return 1;
}
result = write(fd, "2", 1);
if (result < 0) {
perror("Write for GPIO2");
return 1;
}
result = write(fd, "3", 1);
if (result < 0) {
perror("Write for GPIO3");
return 1;
}
result = write(fd, "4", 1);
if (result < 0) {
perror("Write for GPIO4");
return 1;
}
close(fd);
fd = open("/sys/class/gpio/gpio2/direction", O_RDWR);
if (fd < 0) {
perror("Open for GPIO2 Direction");
return 1;
}
result = write(fd, "OUT", 3);
if (result < 0) {
perror("Write for GPIO2 Direction");
return 1;
}
close(fd);
fd = open("/sys/class/gpio/gpio3/direction", O_RDWR);
if (fd < 0) {
perror("Open for GPIO3 Direction");
return 1;
}
result = write(fd, "OUT", 3);
if (result < 0) {
perror("Write for GPIO3 Direction");
return 1;
}
close(fd);
fd = open("/sys/class/gpio/gpio4/direction", O_RDWR);
if (fd < 0) {
perror("Open for GPIO4 Direction");
return 1;
}
result = write(fd, "OUT", 3);
if (result < 0) {
perror("Write for GPIO4 Direction");
return 1;
}
fd = open("/sys/class/gpio/gpio2/value", O_RDWR);
if (fd < 0) {
perror("Open for GPIO2 Value");
return 1;
}
result = write(fd, "1", 1);
if (result < 0) {
perror("Write for GPIO2 Value");
return 1;
}
close(fd);
while(1);
return 0;
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* get_next_line.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: dverbyts <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2017/02/25 16:09:11 by dverbyts #+# #+# */
/* Updated: 2017/02/25 16:09:13 by dverbyts ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
int get_next_line(const int fd, char **line)
{
static t_line *start = NULL;
t_line *buf;
if (fd < 0 || !line || BUFF_SIZE <= 0)
return (-1);
if (start == NULL)
start = make_list(fd);
buf = start;
while (buf != NULL && buf->n_fd != fd)
{
if (buf->next == NULL && buf->n_fd != fd)
buf->next = make_list(fd);
buf = buf->next;
}
if (read_file(&buf, fd) == -1)
return (-1);
if (buf->l[0] != '\0')
{
*line = string(&buf);
return (1);
}
return (0);
}
int read_file(t_line **lst, int fd)
{
t_line *buf;
char b[BUFF_SIZE + 1];
char *tmp;
ssize_t ret;
ret = 0;
buf = *lst;
while ((ret = read(fd, b, BUFF_SIZE)) > 0)
{
b[ret] = '\0';
tmp = ft_strjoin(buf->l, b);
ft_strdel(&buf->l);
buf->l = tmp;
if (ft_strrchr(b, 10) != NULL)
break ;
}
if (ret <= 0 && tmp == NULL)
return (ret == -1 ? -1 : 0);
return (1);
}
t_line *make_list(int fd)
{
t_line *ln;
if (!(ln = (t_line *)malloc(sizeof(t_line) * 1)))
return (NULL);
ln->l = ft_strdup("\0");
ln->n_fd = fd;
ln->next = NULL;
return (ln);
}
char *string(t_line **tmp)
{
char *str;
char *src;
t_line *ptr;
ssize_t len;
ssize_t i;
i = 0;
ptr = *tmp;
while (ptr->l[i] != '\n' && ptr->l[i] != '\0')
i++;
len = ft_strlen(ptr->l);
str = ft_strsub(ptr->l, 0, i);
if (len == i)
src = ft_strnew(0);
else
src = ft_strsub(ptr->l, i + 1, len - i - 1);
if (*(ptr->l) != '\0')
ft_memdel((void *)&ptr->l);
ptr->l = src;
return (str);
}
|
C
|
#include "lists.h"
/**
* free_list - Will add a node at the end of the list.
* @head: variable.
* Return: head.
*/
void free_list(list_t *head)
{
list_t *j;
while (head)
{
j = head->next;
free(head->str);
free(head);
head = j;
}
}
|
C
|
/*
* Author: Ato Jackson-Kuofie
* File: unittest2.c
* Description: Random test generator for DiscardCard function in game of dominion
* Summer 362
*/
#include "dominion.h"
#include "dominion_helpers.h"
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <math.h>
#include "rngs.h"
int checkdiscardCard(int handPos, int currentPlayer, struct gameState *post,
int trashFlag) {
struct gameState pre;
memcpy(&pre, post, sizeof(struct gameState));
int r, startPlayedCardCount, startHandCount;
startPlayedCardCount = post->playedCardCount;
startHandCount = post->handCount[currentPlayer];
r = discardCard(handPos, currentPlayer, post, trashFlag);
if (trashFlag < 1) {
pre.playedCards[pre.playedCardCount] = pre.hand[currentPlayer][handPos];
pre.playedCardCount++;
assert(post->playedCardCount == (startPlayedCardCount + 1));
}
//Set the played card to -1
pre.hand[currentPlayer][handPos] = -1;
// Remove card from players hand if last in hand
if (handPos == (pre.handCount[currentPlayer] - 1)) {
pre.handCount[currentPlayer]--;
assert(post->handCount[currentPlayer] == (startHandCount - 1));
}
//Remove card from player
else if (pre.handCount[currentPlayer] == 1) {
pre.handCount[currentPlayer]--;
assert(post->handCount[currentPlayer] == (startHandCount - 1));
}
//Replace card in hand and decrease hand count
else {
pre.hand[currentPlayer][handPos] =
pre.hand[currentPlayer][(pre.handCount[currentPlayer] - 1)];
pre.hand[currentPlayer][pre.handCount[currentPlayer] - 1] = -1;
pre.handCount[currentPlayer]--;
assert(post->handCount[currentPlayer] == (startHandCount - 1));
}
assert(r == 0);
//Make sure Pre and Post are equal
assert(memcmp(&pre, post, sizeof(struct gameState)) == 0);
return 0;
}
int main() {
int i, n, p, handPos, trashFlag;
struct gameState G;
printf("Testing DiscardCard.\n");
printf("RANDOM TESTS.\n");
SelectStream(2);
PutSeed(3);
//Initialize game state with random array of character bytes
for (n = 0; n < 2000; n++) {
for (i = 0; i < sizeof(struct gameState); i++) {
((char*) &G)[i] = floor(Random() * 256);
}
//Random player cannot be more than 4 players
G.numPlayers = 2 + floor(Random() * (MAX_PLAYERS - 1));
p = floor(Random() * G.numPlayers);
G.whoseTurn = p;
//Random trash flag 0 to 2
trashFlag = floor(Random() * 3);
G.deckCount[p] = floor(Random() * MAX_DECK);
G.discardCount[p] = floor(Random() * MAX_DECK);
G.handCount[p] = floor(Random() * MAX_HAND);
G.playedCardCount = floor(Random() * MAX_DECK);
//Random hand position.
handPos = floor(Random() * G.handCount[p]);
//Valid cards in hand
for (i = 0; i < G.handCount[p]; i++) {
G.hand[p][i] = floor(Random() * (treasure_map + 1));
}
//Valid card in playedCard pile
for (i = 0; i < G.playedCardCount; i++) {
G.playedCards[i] = floor(Random() * (treasure_map + 1));
}
//Call test function
checkdiscardCard(handPos, p, &G, trashFlag);
}
printf("ALL TESTS OK\n");
exit(0);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
typedef struct Employee {
int id;
char name[100];
char surname[100];
} Employee;
typedef struct Node {
Employee employee;
struct Node *next;
} Node;
void printList(Node *head);
void reorderBasedOnFrequency(Node *head);
void swap(struct Node *a, struct Node *b);
int main() {
Employee employees[6] = { {47, "Max", "Clark"}, {37, "Amy", "Jhinar"}, {89, "Bob", "Davis"}, {25, "Jackson", "Adams"},
{29, "Jackie", "Kitcher"},{27, "Karen", "Robinson"}};
Node *head = NULL;
Node *tail = NULL;
for (int i = 0; i < 6; i++) {
Node *newNode = (Node *)malloc(sizeof(Node));
newNode->employee = employees[i];
newNode->next = NULL;
if (i == 0) {
head = newNode;
tail = newNode;
} else {
tail->next = newNode;
tail = newNode;
}
}
printf("Initial List: \n");
printList(head);
reorderBasedOnFrequency(head);
printf("After Sorting: \n");
printList(head);
}
void reorderBasedOnFrequency(Node *head) {
int frequencyMap[10] = { 0 };
// Build array of frequencies for id mod 10`
Node *currentNode = head;
while (currentNode != NULL) {
frequencyMap[currentNode->employee.id % 10]++;
currentNode = currentNode->next;
}
// Perform Standard Bubble Sort
bool swapped = true;
Node *ptr1;
Node *lptr = NULL;
do {
swapped = false;
ptr1 = head;
while (ptr1->next != lptr) {
// Check for frequencies while sorting
if (frequencyMap[(ptr1)->employee.id % 10] < frequencyMap[(ptr1->next)->employee.id % 10]) {
// Swap
swap(ptr1, ptr1->next);
swapped = true;
}
ptr1 = ptr1->next;
}
lptr = ptr1;
} while (swapped);
}
void printList(Node *head) {
while (head != NULL) {
printf("%d %s %s ", head->employee.id, head->employee.name, head->employee.surname);
head = head->next;
if (head != NULL)
printf(" => ");
}
printf("\n");
}
void swap(struct Node *a, struct Node *b) {
Employee temp = a->employee;
a->employee = b->employee;
b->employee = temp;
}
|
C
|
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include "include/variables_manipulate.h"
#define NUMBER_SIZE 15
static variable intVariablesSum(variable v1, variable v2, int sign);
static variable floatVariablesSum(variable v1, variable v2, int sign);
static variable intVariablesProd(variable v1, variable v2);
static variable floatVariablesProd(variable v1, variable v2);
static variable intVariablesDiv(variable v1, variable v2);
static variable floatVariablesDiv(variable v1, variable v2);
/**
* Allows for binary sum, sub, prod and div to be between int and floats.
* Specify sign for sum and substraction operations.
* */
variable variablesSum(variable v1, variable v2)
{
int sign = 1;
switch (v1.type)
{
case TYPE_INT:
return intVariablesSum(v1, v2, sign);
case TYPE_FLOAT:
return floatVariablesSum(v1, v2, sign);
default:
fprintf(stderr, "Error: variable type not allowed for sum.\n");
exit(0);
}
}
variable variablesSub(variable v1, variable v2)
{
int sign = -1;
switch (v1.type)
{
case TYPE_INT:
return intVariablesSum(v1, v2, sign);
case TYPE_FLOAT:
return floatVariablesSum(v1, v2, sign);
default:
fprintf(stderr, "Error: variable type not allowed for substraction.\n");
exit(0);
}
}
variable variablesProd(variable v1, variable v2)
{
switch (v1.type)
{
case TYPE_INT:
return intVariablesProd(v1, v2);
case TYPE_FLOAT:
return floatVariablesProd(v1, v2);
default:
fprintf(stderr, "Error: variable type not allowed for product.\n");
exit(0);
}
}
variable variablesDiv(variable v1, variable v2)
{
switch (v1.type)
{
case TYPE_INT:
return intVariablesDiv(v1, v2);
case TYPE_FLOAT:
return floatVariablesDiv(v1, v2);
default:
fprintf(stderr, "Error: variable type not allowed for division.\n");
exit(0);
}
}
/**
* Negative sign for integers and floats.
* */
variable variableNegative(variable v)
{
switch (v.type)
{
case TYPE_INT:
v.value.intValue = -v.value.intValue;
break;
case TYPE_FLOAT:
v.value.floatValue = -v.value.floatValue;
break;
default:
fprintf(stderr, "Error: variable type not allowed for negative sign.\n");
exit(0);
}
return v;
}
static variable intVariablesSum(variable v1, variable v2, int sign)
{
switch (v2.type)
{
case TYPE_INT:
{
return createIntVariable(v1.value.intValue + v2.value.intValue * sign);
}
case TYPE_FLOAT:
{
return createFloatVariable(v1.value.intValue + v2.value.floatValue * sign);
}
default:
fprintf(stderr, "Error: variable type not allowed for sum.\n");
exit(0);
}
}
static variable floatVariablesSum(variable v1, variable v2, int sign)
{
switch (v2.type)
{
case TYPE_INT:
{
return createIntVariable(v1.value.floatValue + v2.value.intValue * sign);
}
case TYPE_FLOAT:
{
return createFloatVariable(v1.value.floatValue + v2.value.floatValue * sign);
}
default:
fprintf(stderr, "Error: variable type not allowed for sum.\n");
exit(0);
}
}
static variable intVariablesProd(variable v1, variable v2)
{
switch (v2.type)
{
case TYPE_INT:
{
return createIntVariable(v1.value.intValue * v2.value.intValue);
}
case TYPE_FLOAT:
{
return createFloatVariable(v1.value.intValue * v2.value.floatValue);
}
default:
fprintf(stderr, "Error: variable type not allowed for product.\n");
exit(0);
}
}
static variable floatVariablesProd(variable v1, variable v2)
{
switch (v2.type)
{
case TYPE_INT:
{
return intVariablesProd(v2, v1);
}
case TYPE_FLOAT:
{
return createFloatVariable(v1.value.floatValue * v2.value.floatValue);
}
default:
fprintf(stderr, "Error: variable type not allowed for product.\n");
exit(0);
}
}
static variable intVariablesDiv(variable v1, variable v2)
{
switch (v2.type)
{
case TYPE_INT:
{
return createIntVariable(v1.value.intValue / v2.value.intValue);
}
case TYPE_FLOAT:
{
return createFloatVariable(v1.value.intValue / v2.value.floatValue);
}
default:
fprintf(stderr, "Error: variable type not allowed for division.\n");
exit(0);
}
}
static variable floatVariablesDiv(variable v1, variable v2)
{
switch (v2.type)
{
case TYPE_INT:
{
return createFloatVariable(v1.value.intValue / v2.value.intValue);
}
case TYPE_FLOAT:
{
return createFloatVariable(v1.value.intValue / v2.value.floatValue);
}
default:
fprintf(stderr, "Error: variable type not allowed for division.\n");
exit(0);
}
}
|
C
|
/*
* @Author: Aaron Earl
* 5/27/19
*
* From Freenove RPi tutorials
* Ch.7 AD/DA Converter
*
* Task: convert analog voltage to digital
* output voltage
*
* Note: My kit came with PCF8591T IC Chip
*
* Pin Notes: the IC diagram wasn't very clear so
* I've wrote out the pin values as follows;
*
* Left Pins
* AIN0: Potentiometer pin3 input
* AIN1: No input
* AIN2: No input
* AIN3: No input
* A0: GND
* A1: GND
* A2: GND
* VSS: GND
*
* Right Pins
* VDD: +3.3V
* AOUT: 220Ohm Resistor to LED
* VREF: +3.3V
* AGND: GND
* EXT: GND
* OSC: No input/output
* SCL: SCL1(Board)
* SDA: SDA1(Board)
*/
#include <wiringPi.h>
#include <pcf8591.h>
#include <stdio.h>
#define address 0x48 // PCF8591 default address
#define pinbase 64 // any number above 64
#define A0 pinbase + 0
#define A1 pinbase + 1
#define A2 pinbase + 2
#define A3 pinbase + 3
int main(void)
{
int value;
float voltage;
//Fisrt stage warning missing from code
if(wiringPiSetup() == -1)
{
printf("wiringPi setup failed!");
return 1;
}
pcf8591Setup(pinbase, address);
while(1)
{
value = analogRead(A0); //Read A0 pin
analogWrite(pinbase + 0, value);
voltage = (float)value / 255.0 * 3.3; //Calculate Voltage
printf("ADC Value: %d, \tVoltage: %.2fV\n", value, voltage);
delay(100);
}
return 0;
}
|
C
|
//Name: Alekh Maheshwari
//ID: 2015A7PS0097P
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <stdbool.h>
#include <ctype.h>
#include <math.h>
#include "lexer.h"
#include "parser.h"
//stack functions
void push (struct mystack *stack, int ele)
{
struct snode *link=(struct snode*)malloc (sizeof(struct snode));
link->val=ele;
link->next=stack->first;
stack->first=link;
stack->count++;
}
void pop (struct mystack *stack)
{
if(stack->first==NULL)
{
//printf("ERROR: STACK EMPTY");
}
else
{
struct snode*templink=(struct snode*)malloc(sizeof(struct snode));
templink=stack->first;
stack->first=templink->next;
stack->count --;
free(templink);
}
}
int top (struct mystack *stack)
{
if(stack->first==NULL)
{return 0;}
else
{
return stack->first->val;
}
}
//copies only string and rest all is \0
void mystrcpy(char *a, int a_size , char *b)
{
for(int f1=0; f1<a_size; f1++)
{
a[f1]='\0';
}
for(int f1=0; f1<strlen(b)+1; f1++)
{
a[f1]=b[f1];
}
}
/*
int chartonum(char c)
{
if(c=='0')
return 0;
if(c=='1')
return 1;
if(c=='2')
return 2;
if(c=='3')
return 3;
if(c=='4')
return 4;
if(c=='5')
return 5;
if(c=='6')
return 6;
if(c=='7')
return 7;
if(c=='8')
return 8;
if(c=='9')
return 9;
}
int getnum(char *s)
{
char k[100];
mystrcpy(k,100,s);
int i1=0;
int num=0;
int ten=1;
while(k[i1]!='\0')
{
i1++;
}
i1--;
for(int i2=i1; i2>=0; i2--)
{
num=num+ten*chartonum(k[i2]);
ten=ten*10;
}
return num;
}
float getrnum(char *s)
{
char k[100];
mystrcpy(k,100,s);
int i1=0;
int num=0;
int ten=1;
while(k[i1]!='\0')
{
i1++;
}
i1--;
for(int i2=i1; i2>=i1-1; i2--)
{
num=num+ten*chartonum(k[i2]);
ten=ten*10;
}
float after=(float)num/100.0;
num=0;
i1=i1-3;
ten=1;
for(int i2=i1; i2>=0; i2--)
{
num=num+ten*chartonum(k[i2]);
ten=ten*10;
}
return (float)num+after;
}*/
//for tokenNo to token
void addinstore1(char** store1)
{
mystrcpy(store1[0],31, "");
mystrcpy(store1[1],31, "<mainFunction>");
mystrcpy(store1[2],31, "<stmtsAndFunctionDefs>");
mystrcpy(store1[3],31, "<ext_stmtsAndFunctionDefs>");
mystrcpy(store1[4],31, "<stmtOrFunctionDef>");
mystrcpy(store1[5],31, "<stmt>");
mystrcpy(store1[6],31, "<functionDef>");
mystrcpy(store1[7],31, "<parameter_list>");
mystrcpy(store1[8],31, "<type>");
mystrcpy(store1[9],31, "<remainingList>");
mystrcpy(store1[10],31, "<declarationStmt>");
mystrcpy(store1[11],31, "<var_list>");
mystrcpy(store1[12],31, "<more_ids>");
mystrcpy(store1[13],31, "<assignmentStmt_type1>");
mystrcpy(store1[14],31, "<assignmentStmt_type2>");
mystrcpy(store1[15],31, "<leftHandSide_singleVar>");
mystrcpy(store1[16],31, "<leftHandSide_listVar>");
mystrcpy(store1[17],31, "<rightHandSide_type1>");
mystrcpy(store1[18],31, "<rightHandSide_type2>");
mystrcpy(store1[19],31, "<sizeExpression>");
mystrcpy(store1[20],31, "<ifStmt>");
mystrcpy(store1[21],31, "<ext_ifStmt>");
mystrcpy(store1[22],31, "<otherStmts>");
mystrcpy(store1[23],31, "<ioStmt>");
mystrcpy(store1[24],31, "<funCallStmt>");
mystrcpy(store1[25],31, "<inputParameterList>");
mystrcpy(store1[26],31, "<listVar>");
mystrcpy(store1[27],31, "<arithmeticExpression>");
mystrcpy(store1[28],31, "<ext_arithmeticExpression>");
mystrcpy(store1[29],31, "<arithmeticTerm>");
mystrcpy(store1[30],31, "<ext_arithmeticTerm>");
mystrcpy(store1[31],31, "<factor>");
mystrcpy(store1[32],31, "<operator_lowPrecedence>");
mystrcpy(store1[33],31, "<operator_highPrecedence>");
mystrcpy(store1[34],31, "<booleanExpression>");
mystrcpy(store1[35],31, "<constrainedVars>");
mystrcpy(store1[36],31, "<var>");
mystrcpy(store1[37],31, "<matrix>");
mystrcpy(store1[38],31, "<rows>");
mystrcpy(store1[39],31, "<ext_rows>");
mystrcpy(store1[40],31, "<row>");
mystrcpy(store1[41],31, "<ext_row>");
mystrcpy(store1[42],31, "<remainingColElements>");
mystrcpy(store1[43],31, "<matrixElement>");
mystrcpy(store1[44],31, "<logicalOp>");
mystrcpy(store1[45],31, "<relationalOp>");
mystrcpy(store1[101],31, "ASSIGNOP");
mystrcpy(store1[102],31, "FUNID");
mystrcpy(store1[103],31, "ID");
mystrcpy(store1[104],31, "NUM");
mystrcpy(store1[105],31, "RNUM");
mystrcpy(store1[106],31, "STR");
mystrcpy(store1[107],31, "END");
mystrcpy(store1[108],31, "INT");
mystrcpy(store1[109],31, "REAL");
mystrcpy(store1[110],31, "STRING");
mystrcpy(store1[111],31, "MATRIX");
mystrcpy(store1[112],31, "MAIN");
mystrcpy(store1[113],31, "SQO");
mystrcpy(store1[114],31, "SQC");
mystrcpy(store1[115],31, "OP");
mystrcpy(store1[116],31, "CL");
mystrcpy(store1[117],31, "SEMICOLON");
mystrcpy(store1[118],31, "COMMA");
mystrcpy(store1[119],31, "IF");
mystrcpy(store1[120],31, "ELSE");
mystrcpy(store1[121],31, "ENDIF");
mystrcpy(store1[122],31, "READ");
mystrcpy(store1[123],31, "PRINT");
mystrcpy(store1[124],31, "FUNCTION");
mystrcpy(store1[125],31, "PLUS");
mystrcpy(store1[126],31, "MINUS");
mystrcpy(store1[127],31, "MUL");
mystrcpy(store1[128],31, "DIV");
mystrcpy(store1[129],31, "SIZE");
mystrcpy(store1[130],31, "AND");
mystrcpy(store1[131],31, "OR");
mystrcpy(store1[132],31, "NOT");
mystrcpy(store1[133],31, "LT");
mystrcpy(store1[134],31, "LE");
mystrcpy(store1[135],31, "EQ");
mystrcpy(store1[136],31, "GT");
mystrcpy(store1[137],31, "GE");
mystrcpy(store1[138],31, "NE");
mystrcpy(store1[139],31, "E");
mystrcpy(store1[140],31, "$");
}
char* numtostring(char** store1, int k)
{
return store1[k];
}
//hash non terminals
void fn_nthash(struct nonterminal** nthash, char *k1, int q)
{
int index1;
char k[30];
mystrcpy(k,30,k1);
index1=(int)k[2]+(int)k[3]*2+(int)k[7]*4+(int)k[17]*5;
index1=index1%NTHASH;
//printf("%s",k);
if(nthash[index1][0].n==0)
{
for(int f1=0; f1<30; f1++)
{
nthash[index1][0].name[f1]='\0';
}
mystrcpy(nthash[index1][0].name,30,k);
nthash[index1][0].n=q;
}
else
{
for(int f1=0; f1<30; f1++)
{
nthash[index1][1].name[f1]='\0';
}
mystrcpy(nthash[index1][1].name,30,k);
nthash[index1][1].n=q;
}
}
void addin_nthash(struct nonterminal** nthash)
{
for(int q=0;q<NTHASH; q++)
{
for(int j=0; j<2;j++)
{
for(int m=0;m<30;m++)
nthash[q][j].name[m]='\0';
nthash[q][j].n=0;
}
}
fn_nthash(nthash, "<mainFunction>", 1);
fn_nthash(nthash, "<stmtsAndFunctionDefs>", 2);
fn_nthash(nthash, "<ext_stmtsAndFunctionDefs>",3);
fn_nthash(nthash, "<stmtOrFunctionDef>",4);
fn_nthash(nthash, "<stmt>",5);
fn_nthash(nthash, "<functionDef>",6);
fn_nthash(nthash, "<parameter_list>",7);
fn_nthash(nthash, "<type>",8);
fn_nthash(nthash, "<remainingList>",9);
fn_nthash(nthash, "<declarationStmt>",10);
fn_nthash(nthash, "<var_list>",11);
fn_nthash(nthash, "<more_ids>",12);
fn_nthash(nthash, "<assignmentStmt_type1>",13);
fn_nthash(nthash, "<assignmentStmt_type2>",14);
fn_nthash(nthash, "<leftHandSide_singleVar>",15);
fn_nthash(nthash, "<leftHandSide_listVar>",16);
fn_nthash(nthash, "<rightHandSide_type1>",17);
fn_nthash(nthash, "<rightHandSide_type2>",18);
fn_nthash(nthash, "<sizeExpression>",19);
fn_nthash(nthash, "<ifStmt>",20);
fn_nthash(nthash, "<ext_ifStmt>",21);
fn_nthash(nthash, "<otherStmts>",22);
fn_nthash(nthash, "<ioStmt>",23);
fn_nthash(nthash, "<funCallStmt>",24);
fn_nthash(nthash, "<inputParameterList>",25);
fn_nthash(nthash, "<listVar>",26);
fn_nthash(nthash, "<arithmeticExpression>",27);
fn_nthash(nthash, "<ext_arithmeticExpression>",28);
fn_nthash(nthash, "<arithmeticTerm>",29);
fn_nthash(nthash, "<ext_arithmeticTerm>",30);
fn_nthash(nthash, "<factor>",31);
fn_nthash(nthash, "<operator_lowPrecedence>",32);
fn_nthash(nthash, "<operator_highPrecedence>",33);
fn_nthash(nthash, "<booleanExpression>",34);
fn_nthash(nthash, "<constrainedVars>",35);
fn_nthash(nthash, "<var>",36);
fn_nthash(nthash, "<matrix>",37);
fn_nthash(nthash, "<rows>",38);
fn_nthash(nthash, "<ext_rows>",39);
fn_nthash(nthash, "<row>",40);
fn_nthash(nthash, "<ext_row>",41);
fn_nthash(nthash, "<remainingColElements>",42);
fn_nthash(nthash, "<matrixElement>",43);
fn_nthash(nthash, "<logicalOp>",44);
fn_nthash(nthash, "<relationalOp>",45);
}
//hash terminals
void fn_thash(struct terminal** thash, char *k1, int q)
{
int index1;
char k[10];
mystrcpy(k,10,k1);
index1=(int)k[0]+(int)k[1]*2+(int)k[2]*3;
index1=index1%THASH;
if(thash[index1][0].n==0)
{
for(int f1=0; f1<10; f1++)
{
thash[index1][0].name[f1]='\0';
}
mystrcpy(thash[index1][0].name ,10,k);
thash[index1][0].n=q;
}
else
{
for(int f1=0; f1<10; f1++)
{
thash[index1][1].name[f1]='\0';
}
mystrcpy(thash[index1][1].name,10,k);
thash[index1][1].n=q;
}
}
void addin_thash(struct terminal** thash)
{
for(int q=0;q<THASH; q++)
{
for(int j=0; j<2;j++)
{
for(int m=0;m<10;m++)
thash[q][j].name[m]='\0';
thash[q][j].n=0;
}
}
fn_thash(thash, "ASSIGNOP", 101);
fn_thash(thash, "FUNID", 102);
fn_thash(thash, "ID", 103);
fn_thash(thash, "NUM", 104);
fn_thash(thash, "RNUM", 105);
fn_thash(thash, "STR", 106);
fn_thash(thash, "END", 107);
fn_thash(thash, "INT", 108);
fn_thash(thash, "REAL", 109);
fn_thash(thash, "STRING", 110);
fn_thash(thash, "MATRIX", 111);
fn_thash(thash, "MAIN", 112);
fn_thash(thash, "SQO", 113);
fn_thash(thash, "SQC", 114);
fn_thash(thash, "OP", 115);
fn_thash(thash, "CL", 116);
fn_thash(thash, "SEMICOLON", 117);
fn_thash(thash, "COMMA", 118);
fn_thash(thash, "IF", 119);
fn_thash(thash, "ELSE", 120);
fn_thash(thash, "ENDIF", 121);
fn_thash(thash, "READ", 122);
fn_thash(thash, "PRINT", 123);
fn_thash(thash, "FUNCTION", 124);
fn_thash(thash, "PLUS", 125);
fn_thash(thash, "MINUS", 126);
fn_thash(thash, "MUL", 127);
fn_thash(thash, "DIV", 128);
fn_thash(thash, "SIZE", 129);
fn_thash(thash, "AND", 130);
fn_thash(thash, "OR", 131);
fn_thash(thash, "NOT", 132);
fn_thash(thash, "LT", 133);
fn_thash(thash, "LE", 134);
fn_thash(thash, "EQ", 135);
fn_thash(thash, "GT", 136);
fn_thash(thash, "GE", 137);
fn_thash(thash, "NE", 138);
fn_thash(thash, "E", 139);
fn_thash(thash, "$", 140);
}
//get number associated with each terminal or non terminal when we dont know whether its a terminal or non terminal
int getnum(char *word, struct nonterminal **nthash, struct terminal **thash)
{
int index1;
if(word[0]=='<')
{
index1=(int)word[2]+(int)word[3]*2+(int)word[7]*4+(int)word[17]*5;
index1=index1%NTHASH;
if(strcmp(nthash[index1][0].name,word)==0)
{
return nthash[index1][0].n;
}
else if(strcmp(nthash[index1][1].name,word)==0)
{
return nthash[index1][1].n;
}
else
return 0;
}
else
{
index1=(int)word[0]+(int)word[1]*2+(int)word[2]*3;
index1=index1%THASH;
if(strcmp(thash[index1][0].name,word)==0)
{
return thash[index1][0].n;
}
else if(strcmp(thash[index1][1].name,word)==0)
{
return thash[index1][1].n;
}
else
return 0;
}
}
//to fill a line of grammar array.. this function is called by fillGrammar
void fillLine(char* linebuffer, int** grammar, int rule, struct nonterminal **nthash, struct terminal **thash)
{
char word[30];
int m;
int g=0;
int q=0;
int w=0;
while(true)
{
w=0;
for(int j=0; j<30; j++)
word[j]='\0';
while(linebuffer[q]!=' ' && linebuffer[q]!='\n' && linebuffer[q]!='\r')
{
word[w]=linebuffer[q];
q++;
w++;
}
q++;
//printf("%s ",word);
if(word[0]!='=')
{
m=getnum(word, nthash, thash);
grammar[rule][g]=m;
g++;
}
if(linebuffer[q]=='\0' || linebuffer[q]=='\n' || linebuffer[q]=='\r')
break;
}
for(int f1=0; f1<150; f1++)
{
linebuffer[f1]='\0';
}
}
//fill grammar array
void fillGrammar(FILE *grammarfp, char* linebuffer, int** grammar, struct nonterminal **nthash, struct terminal **thash)
{
int rule=0;
while(fgets(linebuffer, 150, grammarfp)!=NULL)
{
fillLine(linebuffer, grammar, rule, nthash, thash);
rule++;
}
}
bool isT(int k)
{
if(k>100)
return true;
else
return false;
}
bool isNT(int k)
{
if(k<100)
return true;
else
return false;
}
//is epsilon
bool isE(int k)
{
if(k==139)
return true;
else
return false;
}
//compute first of a particular NT
void compute_first(int **grammar, int nt, int arr[], int *indexf, int *indexr)
{
//check every rule
for(int rn=0; rn<TOTAL_RULES; rn++)
{
*indexr=1; //index of column of a particular grammar rule
if(grammar[rn][0]==nt)
{
//terminal and not e
if(isT(grammar[rn][*indexr]) && !isE(grammar[rn][*indexr]))
{
arr[*indexf]=grammar[rn][*indexr];
*indexf=*indexf+1;
}
//non terminal
else if(isNT(grammar[rn][*indexr]))
{
compute_first(grammar, grammar[rn][*indexr], arr, indexf, indexr);
}
//empty terminal
else if(isE(grammar[rn][*indexr]))
{
arr[*indexf]=grammar[rn][*indexr];
*indexr=*indexr+1;
*indexf=*indexf+1;
}
}
}
}
//fill first
void fillFirst(int **first, int **grammar)
{
//compute for all rules
for(int nt=1; nt<=45; nt++)
{
int indexf=0; //index of column of first of a particular NT (where to put next terminal obtained)
int indexr=1; //index of column of a particular grammar rule
int arr[40];
for(int f1=0; f1<40; f1++)
{
arr[f1]=0;
}
compute_first(grammar, nt, arr, &indexf, &indexr);
for(int f1=0; f1<40; f1++)
{
first[nt][f1]=arr[f1];
//printf("%d ",arr[f1]);
}
}
first[41][2]=0;//printf("\n");
}
//ALL these for computing FOLLOW
void remove_duplicates(int followset[])
{
int c,d;
int count=0;
int tarr[500];
for(int temp=0; temp<500; temp++)
{
tarr[temp]=0;
}
for(c=0;c<500;c++)
{
for(d=0;d<count;d++)
{
if(followset[c]==tarr[d])
break;
}
if(d==count)
{
tarr[count] = followset[c];
count++;
}
}
for(int temp=0; temp<500; temp++)
{
followset[temp]=tarr[temp];
}
}
void appendfirst1(int followset[], int** first, int k, int* index3)
{
int j=0;
while(first[k][j]!=0 )
{
if(first[k][j]!=139)
{
followset[*index3]=first[k][j];
j++;
*index3=*index3+1;
}
else
{
j++;
}
}
}
//to check if first of a non terminal contains e
bool hasE(int** first, int k)
{
for(int t=0;t<40;t++)
{
if(first[k][t]==139)
return true;
}
return false;
}
void compute_follow(int **grammar, int** first, int nt, int followset[], int *index3, int depth)
{
for(int ri=0; ri<TOTAL_RULES; ri++)
{
for(int rj=1; rj<15; rj++)
{
if(grammar[ri][rj]==nt)
{
int followingrule[40];
for(int temp=0; temp<40; temp++)
{
followingrule[temp]=0;
}
int followingrulestart=rj+1;
for(int fr=0; fr<40-followingrulestart; fr++)
{
followingrule[fr]=grammar[ri][followingrulestart];
followingrulestart++;
}
if(followingrule[0]==0)
{
if(depth>20)
{return;}
depth=depth+1;
compute_follow(grammar, first, grammar[ri][0], followset, index3, depth);
}
else if(isT(followingrule[0]) && !isE(followingrule[0]) && followingrule[0]!=0)
{
followset[*index3]=followingrule[0];
*index3=*index3+1;
}
else if(isNT(followingrule[0]) && followingrule[0]!=0)
{
for(int temp=0; temp<40; temp++)
{
if(followingrule[temp]==0)
{
if(depth>20)
{return;}
depth=depth+1;
compute_follow(grammar, first, grammar[ri][0], followset, index3, depth);
break;
}
if(isT(followingrule[temp]))
{
followset[*index3]=followingrule[temp];
*index3=*index3+1;
break;
}
//dont append epsilon
appendfirst1(followset, first, followingrule[temp], index3);
if(!hasE(first, followingrule[temp]))
break;
}
}
}
}
}
}
void fillFollow(int **follow, int**first, int **grammar)
{
for(int nt=1; nt<=45; nt++)
{
int index3=0;
int followset[500];
for(int f1=0; f1<500; f1++)
{
followset[f1]=0;
}
follow[1][0]=140;
int depth=0;
compute_follow(grammar, first, nt, followset, &index3, depth);
remove_duplicates(followset);
for(int f1=0; f1<40; f1++)
{
follow[nt][f1]=followset[f1];
}
}
}
/*void createParseTable(int **grammar, int** parsetable, int** first, int** follow)
{
int nt,flag,nextsym,followj,firstj;
for(int r=0; r<TOTAL_RULES; r++)
{
flag=0;
nt=grammar[r][0];//LHS of production rule
nextsym=grammar[r][1];//first symbol in RHS of production rule
if(isT(nextsym) && !isE(nextsym))
{
parsetable[nt][nextsym-100]=r;
}
if(isE(nextsym))
{
followj=0;
//follow[nt][followj] is a T
while(follow[nt][followj]!=0)
{
parsetable[nt][follow[nt][followj]-100]=r;
followj++;
}
}
if(isNT(nextsym))
{
firstj=0;
//first[nextsym][firstj] is a T
while(first[nextsym][firstj]!=0)
{
if(first[nextsym][firstj]==139)
flag=1;
else
{
parsetable[nt][first[nextsym][firstj]-100]=r;
}
firstj++;
}
if(flag==1)
{
followj=0;
//follow[nextsym][followj] is a T
while(follow[nextsym][followj]!=0)
{
parsetable[nt][follow[nextsym][followj]-100]=r;
followj++;
}
}
}
}
}*/
void call1(int **grammar, int** parsetable, int** first, int** follow, int rj, int nt, int r)
{
int nextsym=grammar[r][rj];//first symbol in RHS of production rule
if(isT(nextsym) && !isE(nextsym))
{
parsetable[nt][nextsym-100]=r;
}
if(isE(nextsym))
{
int followj=0;
//follow[nt][followj] is a T
while(follow[nt][followj]!=0)
{
parsetable[nt][follow[nt][followj]-100]=r;
followj++;
}
}
if(isNT(nextsym))
{
int firstj=0;
int flag=0;
//first[nextsym][firstj] is a T
while(first[nextsym][firstj]!=0)
{
if(first[nextsym][firstj]==139)
flag=1;
else
{
parsetable[nt][first[nextsym][firstj]-100]=r;
}
firstj++;
}
if(flag==1)
{
rj++;
call1(grammar, parsetable, first, follow, rj, nt, r);
}
}
}
void createParseTable1(int **grammar, int** parsetable, int** first, int** follow)
{
int nt,rj;
for(int r=0; r<TOTAL_RULES; r++)
{
nt=grammar[r][0];//LHS of production rule
rj=1;
call1(grammar, parsetable, first, follow, rj, nt, r);
}
}
//for token to tokenNo
int stringtonum(char* c,struct terminal **thash)
{
char k[10];
mystrcpy(k, 10, c);
int index1;
index1=(int)k[0]+(int)k[1]*2+(int)k[2]*3;
index1=index1%THASH;
if(strcmp(thash[index1][0].name,k)==0)
{
return thash[index1][0].n;
}
else
{
return thash[index1][1].n;
}
}
//findSuitableNode in parse tree to where we have to add next rule
struct tnode* findSuitableNode(struct tnode* trav, int* flag)
{
if(isNT(trav->val) && trav->child[0]==NULL && *flag==0)
{
*flag=1;
return trav;
}
if(isNT(trav->val))
{
for(int c=0; c<15; c++)
{
if(trav->child[c]!=NULL && isNT(trav->child[c]->val) && *flag==0)
{
trav=findSuitableNode(trav->child[c], flag);
}
if(trav->child[c]!=NULL && isT(trav->child[c]->val) && *flag==0)
{
continue;
}
if(trav->child[c]==NULL && *flag==0)
{
return trav->parent;
}
}
}
return trav;
}
/*struct tnode* findNodeToCopyDetails(struct tnode* trav1, int globalcount, int *localcount, int* flag1)
{
if(isT(trav1->val) && *localcount==globalcount && *flag1==0)
{
*flag1=1;
return trav1;
}
if(isNT(trav1->val))
{
for(int c=0; c<15; c++)
{
if(trav1->child[c]!=NULL && isNT(trav1->child[c]->val) && *flag1==0)
{
trav1=findNodeToCopyDetails(trav1->child[c],globalcount,localcount, flag1);
}
if(trav1->child[c]!=NULL && isT(trav1->child[c]->val) && *flag1==0)
{
if(*localcount==globalcount && *flag1==0)
{
*flag1=1;
return trav1->child[c];
}
else
{
*localcount=*localcount+1;
}
}
if(trav1->child[c]==NULL && *flag1==0)
{
return trav1->parent;
}
}
}
return trav1;
}*/
//find Node in parse tree where we have to Copy Details of the next token received by getNextToken
struct tnode* findNodeToCopyDetails12(struct tnode* trav1, int globalcount, int *localcount, int* flag1)
{
if(*flag1==1)
return trav1;
for(int c=0; c<15; c++)
{
if(trav1->child[c]!=NULL && *flag1==0)
{
trav1=findNodeToCopyDetails12(trav1->child[c],globalcount,localcount,flag1);
if(*flag1==1)
return trav1;
}
}
if(isT(trav1->val) && !isE(trav1->val))
{
if(globalcount==*localcount && *flag1==0)
{
*flag1=1;
return trav1;
}
if(globalcount!=*localcount && *flag1==0)
{
*localcount=*localcount+1;
return trav1->parent;
}
}
return trav1->parent;
}
char* isLeaf(int k)
{
if(isT(k))
return "yes";
else
return "no";
}
bool inFollow(int** follow, int nt, int t)
{
for(int f1=0; f1<40; f1++)
{
if(follow[nt][f1]==t)
return true;
}
return false;
}
//parse source code- make stack and parse tree
void parseInputSourceCode(int** grammar, int **parsetable, struct mystack* stack, struct terminal **thash, FILE* testcasefp, char* buffer, struct tnode* parsetree, int** follow ,char*** hashArray, char** store1)
{
int flagcorrect=0;
struct tnode* trav;
struct tnode* trav1;
int ti,tj,ri,rj,localcount;
struct tokenInfo t1=getNextToken(testcasefp,buffer, hashArray);
//HERE
while(strcmp(t1.tokenName,"")==0){
t1=getNextToken(testcasefp,buffer, hashArray);
}
char token[10];
mystrcpy(token,10,t1.tokenName);
int tokenNo=stringtonum(token, thash);
char lexeme[31];
mystrcpy(lexeme,31,t1.lexeme);
int line=t1.line;
tj=tokenNo-100;
int globalcount=0;
while(tokenNo!=140)
{
if(isNT(top(stack)))
{
ti=top(stack);
ri=parsetable[ti][tj];
if(ri!=ERROR)
{
//fill stack in reverse
rj=1;
while(grammar[ri][rj]!=0)
{
rj++;
}
rj--;
pop(stack);
while(rj!=0)
{
if(grammar[ri][rj]!=139)
{
push(stack, grammar[ri][rj]);
}
rj--;
}
//add nodes to parse tree
rj=1;
trav=parsetree;//dont change 'parsetree' node ever... it contains first NT, i.e, <mainFunction>
int flag=0;
struct tnode* res=trav;
res=findSuitableNode(trav,&flag);
while(grammar[ri][rj]!=0)
{
struct tnode* temp=(struct tnode*)malloc(sizeof(struct tnode));
temp->val=grammar[ri][rj];
temp->parent=res;
strcpy(temp->lexeme,"---");
temp->line=0;
temp->num=-1;
temp->rnum=-1;
for(int q=0; q<15; q++)
{
temp->child[q]=NULL;
}
res->child[rj-1]=temp;
rj++;
}
continue; //dont get next token
}
else
{
//int count3=0;
//error entry in parse table
flagcorrect=1;
printf("SYNTAX ERROR: Line %d: The token %s for lexeme %s unexpected. \n", line, token, lexeme);
//get next token until it is not in follow set of NT present at top of stack
while(!inFollow(follow, top(stack), tokenNo) )//&& count3<200)
{
t1=getNextToken(testcasefp,buffer, hashArray);
//HERE
while(strcmp(t1.tokenName,"")==0)
{
t1=getNextToken(testcasefp,buffer, hashArray);
}
mystrcpy(token,10,t1.tokenName);
tokenNo=stringtonum(token, thash);
mystrcpy(lexeme,31,t1.lexeme);
line=t1.line;
tj=tokenNo-100;
//count3++;
}
//if found in follow set, pop stack
pop(stack);
continue;
}
}
if(isT(top(stack)))
{
if(top(stack)==tokenNo)
{
pop(stack);
//find Node To Copy Details
trav1=parsetree;//dont change parsetree node ever... it contains first NT, i.e, <mainFunction>
localcount=0;
int flag1=0;
struct tnode* res1=trav1;
res1=findNodeToCopyDetails12(trav1,globalcount, &localcount, &flag1);
//copy those details to found node
if(res1->val==104)
res1->num=atoi(lexeme);
if(res1->val==105)
res1->rnum=atof(lexeme);
mystrcpy(res1->lexeme,10,lexeme);
res1->line=line;
globalcount++;
}
else
{
//top of stack is terminal and it does not matches with next token
flagcorrect=1;
printf("SYNTAX ERROR: Line %d: The token %s for lexeme %s does not match. The expected token here is %s\n", line, token, lexeme, numtostring(store1, top(stack)));
//pop stack and get next token simultaneously until both Terminals matches
//pop stack
pop(stack);
//get next token
t1=getNextToken(testcasefp,buffer, hashArray);
//HERE
while(strcmp(t1.tokenName,"")==0)
{
t1=getNextToken(testcasefp,buffer, hashArray);
}
mystrcpy(token,10,t1.tokenName);
tokenNo=stringtonum(token, thash);
mystrcpy(lexeme,31,t1.lexeme);
line=t1.line;
tj=tokenNo-100;
continue;
}
}
if(top(stack)==140)
{
//stack becomes empty
//printf("SYNTAX ERROR: Line %d: Stack empty\n", line);
//flagcorrect=1;
}
//keep at end of while loop
t1=getNextToken(testcasefp,buffer, hashArray);
//HERE
while(strcmp(t1.tokenName,"")==0)
{
t1=getNextToken(testcasefp,buffer, hashArray);
}
mystrcpy(token,10,t1.tokenName);
tokenNo=stringtonum(token, thash);
mystrcpy(lexeme,31,t1.lexeme);
line=t1.line;
tj=tokenNo-100;
}
if(tokenNo==140 && top(stack)!=140)
{
//stack not empty
//printf("SYNTAX ERROR: Line %d: End of file but stack is not empty\n", line);
//flagcorrect=1;
}
if(tokenNo==140 && top(stack)==140 && flagcorrect==0)
{
printf("Input source code is syntactically correct...\n");
}
}
//print parse tree in INORDER
void printParseTree(struct tnode* trav2, FILE* parsetreefp, char** store1)
{
if(trav2==NULL)
return;
//print first child
printParseTree(trav2->child[0], parsetreefp, store1);
//print node info
if(trav2->val==1)
fprintf(parsetreefp, "LexemeCurrentNode=%s | LineNo=%d | Token/NodeSymbol=%s | ParentNodeSymbol=ROOT | isLeafNode=no\n", trav2->lexeme, trav2->line, numtostring(store1, trav2->val));
else
{
if(trav2->num!=-1)
fprintf(parsetreefp, "LexemeCurrentNode=%s | LineNo=%d | Token/NodeSymbol=%s | Value=%d | ParentNodeSymbol=%s | isLeafNode=%s\n",trav2->lexeme, trav2->line, numtostring(store1, trav2->val), trav2->num, numtostring(store1, trav2->parent->val), isLeaf(trav2->val));
else if(trav2->rnum!=-1)
fprintf(parsetreefp, "LexemeCurrentNode=%s | LineNo=%d | Token/NodeSymbol=%s | Value=%.2f | parentNodeSymbol=%s | isLeafNode=%s\n",trav2->lexeme, trav2->line, numtostring(store1, trav2->val), trav2->rnum, numtostring(store1, trav2->parent->val), isLeaf(trav2->val));
else
fprintf(parsetreefp, "LexemeCurrentNode=%s | LineNo=%d | Token/NodeSymbol=%s | ParentNodeSymbol=%s | isLeafNode=%s\n",trav2->lexeme, trav2->line, numtostring(store1, trav2->val), numtostring(store1, trav2->parent->val), isLeaf(trav2->val));
}
//print remaining child
for(int c=1; c<15; c++)
{
printParseTree(trav2->child[c], parsetreefp, store1);
}
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define Nodo struct nodo
#define ListDob struct listadoble
struct nodo{//------------------------------------------------------------------Definicin de las partes del nodo
int dato;
Nodo* siguiente;
};
struct listadoble{//------------------------------------------------------------Definicin de las partes de la lista
Nodo *inicio;
Nodo *final;
};
Nodo *inicio=NULL;//------------------------------------------------------------Creacin de los apuntadores de inicio y final
Nodo *final=NULL;
void insertar(ListDob *list,int dato);//----------------------------------------Declaracin de los prototipos
Nodo *nuevoElemento(int dato);
void visualizarLista(ListDob nlista);
int eliminarNodo(ListDob*lista);
void insertarI(ListDob *list,int dato);
int main(int argc, char *argv[]) {//--------------------------------------------MAIN
return 0;
}
void insertar(ListDob *list,int dato){//----------------------------------------Funcin para insertar elementos en la fila o pila o lista final
Nodo* nuevo=nuevoElemento(dato);
if(list->inicio==NULL && list->final==NULL){
list->inicio=nuevo;
list->final=nuevo;
}else{
list->final->siguiente=nuevo;
list->final=nuevo;
}
}
Nodo *nuevoElemento(int dato){//------------------------------------------------Funcin para crear nuevos elementos
Nodo *q=(Nodo*)malloc(sizeof(Nodo));
q->dato=dato;
q->siguiente=NULL;
return q;
}
void visualizarLista(ListDob nlista){//-----------------------------------------Funcin para visualizar la lista
if(nlista.inicio!=NULL){
Nodo* aux=nlista.inicio;
while(aux!=NULL){
printf("%c ",aux->dato);
aux=aux->siguiente;
}
}
}
int eliminarNodo(ListDob*lista){//----------------------------------------------Funcin para eliminar nodos
Nodo* aux=lista->inicio;
int dato=aux->dato;
lista->inicio=lista->inicio->siguiente;
free(aux);
return dato;
}
void insertarI(ListDob *list,int dato){//---------------------------------------Funcin para insertar al inicio
Nodo *nuevo=nuevoElemento(dato);
if(list->inicio==NULL && list->final==NULL){
list->inicio=nuevo;
list->final=nuevo;
}else{
nuevo->siguiente=list->inicio;
list->inicio=nuevo;
}
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* get_next_line.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: dtony <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2019/08/18 10:51:28 by dtony #+# #+# */
/* Updated: 2019/08/18 10:51:28 by dtony ### ########.fr */
/* */
/* ************************************************************************** */
#include "get_next_line.h"
#include <stdio.h>
static char *n_parse(char *str, int n)
{
int i;
i = 0;
if (!str)
return (NULL);
while (str[i] && str[i] == n)
i++;
if (str[i] == '\0')
return (NULL);
return (str + i);
}
static int checkstock(int fd, char **stock, char **line)
{
char *end;
char *tmp;
end = NULL;
tmp = NULL;
if (stock[fd])
{
if ((end = ft_strchr(stock[fd], '\n')) != NULL)
*line = ft_strsub(stock[fd], 0, end - stock[fd]);
tmp = n_parse(ft_strchr(stock[fd], '\n'), '\n');
free(stock[fd]);
stock[fd] = NULL;
if (tmp && tmp[0])
{
stock[fd] = ft_strdup(tmp);
free(tmp);
tmp = NULL;
}
}
return (*line ? 1 : 0);
}
static int readline(char **stock, char **line, char *buf, int fd)
{
int i;
char *end;
char *new;
i = 0;
new = NULL;
if (buf[0] == '\n')
{
if (stock[fd])
{
*line = ft_strdup(stock[fd]);
free(stock[fd]);
stock[fd] = NULL;
}
while (buf[i] == '\n' && buf[i])
i++;
end = ft_strchr(buf + i, '\n');
if (end && !(*line))
*line = ft_strsub(buf, i, end - buf - i);
else if (buf[i])
stock[fd] = ft_strdup(buf + i);
}
else
{
end = ft_strchr(buf, '\n');
if (stock[fd])
{
new = ft_strsub(buf, 0, end - buf);
*line = ft_strfjoin(stock[fd], new);
free(new);
new = NULL;
stock[fd] = NULL;
}
else
*line = ft_strsub(buf, 0, end - buf);
if (n_parse(end, '\n'))
stock[fd] = ft_strdup(n_parse(end, '\n'));
}
return (*line ? 1 : 0);
}
int get_next_line(const int fd, char **line)
{
int ret;
static char *stock[_SC_OPEN_MAX];
char buf[BUFF_SIZE + 1];
if (fd < 0 || !(line) || read(fd, buf, 0) < 0)
return (-1);
ft_bzero(buf, BUFF_SIZE + 1);
while ((ret = read(fd, buf, BUFF_SIZE)) > 0)
{
buf[ret] = '\0';
if ((stock[fd] && ft_strchr(stock[fd], '\n')) &&
(checkstock(fd, stock, line)))
return (1);
else if ((ft_strchr(buf, '\n')) &&
(readline(stock, line, buf, fd)))
return (1);
else
stock[fd] = ft_strfjoin(stock[fd], buf);
ft_bzero(buf, BUFF_SIZE + 1);
}
if (stock[fd] && stock[fd][0])
{
*line = ft_strdup(stock[fd]);
free(stock[fd]);
stock[fd] = NULL;
return (1);
}
if (stock[fd])
{
free(stock[fd]);
stock[fd] = NULL;
}
return (0);
}
|
C
|
//Header files
#include<reg51.h>
//sbit pin declarations
sbit ir_left=P0^0;
sbit ir_right=P0^1;
sbit rf=P2^0;
sbit rb=P2^1;
sbit lf=P2^2;
sbit lb=P2^3;
//Global variables declarations
int var_left=0,var_right=0,var_back=0;
//Function Prototypes
void stop();
void forward();
void backward();
void left();
void right();
void delay(int);
//main function
void main()
{
P0=0xFF; // declared input port
P2=0x00;
stop();
while(1)
{
if(ir_right == 0 && ir_left == 1) // for right turn
{
right();
var_right++;
}
else if(ir_left == 0 && ir_right == 1) // for left turn
{
left();
var_left++;
}
else if(ir_left == 0 && ir_right == 0)
{
forward();
}
else if(ir_left == 1 && ir_right == 1)
{
backward();
var_back++;
if(var_back > 5)
{
var_back=0;
if(var_left > var_right)
{
left();
delay(200);
}
else
{
right();
delay(200);
}
}
}
else
{
stop();
}
}
}
//end of main function
/**************************** Function Definitions ************************************/
//to stop all wheels
void stop()
{
//Lcd8_Display(0x80,"...DEAD END!...",16);
lf=0;
rf=0;
lb=0;
rb=0;
//delay_motor(50);
}
// to move forward:
void forward()
{
//Lcd8_Display(0x80,".Moving Forward.",16);
lf=1;
rf=1;
lb=0;
rb=0;
}
// to move backwards:
void backward()
{
//Lcd8_Display(0x80,"Moving Backward",16);
lb=1;
rb=1;
lf=0;
rf=0;
delay(200);
}
// to move left
void left()
{
//Lcd8_Display(0x80,"..Moving Left..",16);
lf=0;
rf=1;
lb=0;
rb=0;
//delay(100);
}
// to move left
void right()
{
//Lcd8_Display(0x80,"..Moving Right..",16);
lf=1;
rf=0;
lb=0;
rb=0;
// delay(50);
}
void delay(int x)
{
int i,j;
for(i=0;i<x;i++)
for(j=0;j<250;j++);
}
|
C
|
#include <stdio.h>
int main()
{
int n,i,s[10],min=99,max=0;
scanf("%d",&n);
for(i=0;i<n;i++)
{
scanf("%d",&s[i]);
}
for(i=0;i<n;i++)
{
if(s[i]>max)
{
max=s[i];
}
}
for(i=0;i<n;i++)
{
if(s[i]<min)
{
min=s[i];
}
}
printf("min:%d\nmax:%d",min,max);
return 0;
}
|
C
|
#include "pedido.h"
#include "fabrica.h"
#include "maquina.h"
// Definindo as prioridades
#define BAIXA 1
#define MEDIA 2
#define ALTA 3
typedef struct pedido {
char id;
int prioridade;
float tempo;
float tempoChegada;
float estadiaTorno;
float estadiaFresa;
float estadiaMandril;
Maquina *maquinas[6];
Maquina *maquinaAtu;
int itMaquinaAtu;
void (*atendePedido)(void *pedido, void *fabrica);
} Pedido;
char get_id_pedido(Pedido *pedido) {
return pedido->id;
}
void set_tempo_pedido(Pedido *pedido, float tempo) {
pedido->tempo = tempo;
}
void atualiza_tempo_pedido(Pedido *pedido, float tempo) {
pedido->tempo = tempo;
}
int get_local_pedido(Pedido *pedido) {
return pedido->itMaquinaAtu;
}
void *get_maquina_atual_pedido(Pedido *pedido) {
return pedido->maquinaAtu;
}
float tempo_de_maquina(float Estadia_Equipamento_Rolamento) {
// Tempo que o rolamento vai ficar no maquinario
float u = ((float) rand()) / ((float) RAND_MAX);
return 2.0 * Estadia_Equipamento_Rolamento * u;
}
float get_tempo_estadia_torno_pedido(Pedido *pedido) {
return tempo_de_maquina(pedido->estadiaTorno);
}
float get_tempo_estadia_fresa_pedido(Pedido *pedido) {
return tempo_de_maquina(pedido->estadiaFresa);
}
float get_tempo_estadia_mandril_pedido(Pedido *pedido) {
return tempo_de_maquina(pedido->estadiaMandril);
}
float get_estadia_torno(Pedido *pedido) {
return pedido->estadiaTorno;
}
float get_tempo_pedido(Pedido *pedido) {
return pedido->tempo;
}
float get_tempo_chegada_pedido(Pedido *pedido) {
return pedido->tempoChegada;
}
float gera_tempo_pedido(float avg) {
float u = 0; /* Gera randomicamente um numero entre 0 e 1 */
do
u = ((float)rand()) / ((float) RAND_MAX);
while ((u == 0) || (u == 1));
return (-avg * log (u));
}
void set_atende_pedido(Pedido *pedido, void (*proxFunction)(void *pedido, void *fabrica)) {
pedido->atendePedido = proxFunction;
}
void atende_pedido(Pedido *pedido, void *fabrica) {
pedido->atendePedido(pedido, fabrica);
}
void set_maquina_atu_pedido(Pedido *pedido, void *maquina) {
pedido->maquinaAtu = (Maquina *) maquina;
}
void incrementa_maquina_pedido(Pedido *pedido) {
pedido->itMaquinaAtu++;
pedido->maquinaAtu = pedido->maquinas[pedido->itMaquinaAtu];
}
int get_prioridade_pedido(Pedido *pedido) {
return pedido->prioridade;
}
int pedido_em_alguma_maquina(Pedido *pedido) {
return pedido->itMaquinaAtu == -1;
}
int pedido_pronto(Pedido *pedido) {
return get_maquina_atual_pedido(pedido) == NULL;
}
Pedido* cria_pedido_cilindrico(void *fabrica) {
// Alocação de espaço para o pedido
Pedido *pedidoCilindrico = (Pedido *) malloc(sizeof(Pedido));
// Valores default para um pedido do tipo cilindrico
pedidoCilindrico->id = 'C';
pedidoCilindrico->prioridade = BAIXA;
pedidoCilindrico->itMaquinaAtu = -1;
pedidoCilindrico->estadiaTorno = 0.8;
pedidoCilindrico->estadiaFresa = 0.5;
pedidoCilindrico->estadiaMandril = 1.2;
// Inserindo máquinas na sequencia em que elas serão utilizadas pelo pedido
pedidoCilindrico->maquinas[0] = get_torno1_fabrica((Fabrica *)fabrica);
pedidoCilindrico->maquinas[1] = get_fresa_fabrica((Fabrica *)fabrica);
pedidoCilindrico->maquinas[2] = get_mandril_fabrica((Fabrica *)fabrica);
pedidoCilindrico->maquinas[3] = get_torno1_fabrica((Fabrica *)fabrica);
pedidoCilindrico->maquinas[4] = NULL; // Valor NULL para indicar que o pedido saiu da fábrica
// Tempo do pedido = tempo da fábrica + um valor "aleatório"
pedidoCilindrico->tempo = (get_tempo_fabrica((Fabrica *) fabrica)) + gera_tempo_pedido(21.5);
pedidoCilindrico->tempoChegada = pedidoCilindrico->tempo;
// Ponteiro para funções necessários para um pedido cilindrico
pedidoCilindrico->atendePedido = atende_cilindrico;
return pedidoCilindrico;
}
Pedido* cria_pedido_conico(void *fabrica) {
// Alocação de espaço para o pedido
Pedido *pedidoConico = (Pedido *) malloc(sizeof(Pedido));
// Valores default para um pedido do tipo conico
pedidoConico->id = 'N';
pedidoConico->prioridade = MEDIA;
pedidoConico->itMaquinaAtu = -1;
pedidoConico->estadiaTorno = 1.8;
pedidoConico->estadiaFresa = 0;
pedidoConico->estadiaMandril = 2.1;
// Inserindo máquinas na ordem em que elas serão utilizadas pelo pedido
pedidoConico->maquinas[0] = get_torno1_fabrica((Fabrica *)fabrica);
pedidoConico->maquinas[1] = get_mandril_fabrica((Fabrica *)fabrica);
pedidoConico->maquinas[2] = get_torno1_fabrica((Fabrica *)fabrica);
pedidoConico->maquinas[3] = NULL; // Valor NULL para indicar que o pedido saiu da fábrica
// Tempo do pedido = tempo da fábrica + um valor "aleatório"
pedidoConico->tempo = (get_tempo_fabrica((Fabrica *) fabrica)) + gera_tempo_pedido(19.1);
pedidoConico->tempoChegada = pedidoConico->tempo;
// Ponteiros para funções necessários para um pedido conico
pedidoConico->atendePedido = atende_conico;
return pedidoConico;
}
Pedido *cria_pedido_esferico_aco(void *fabrica) {
// Alocação de espaço para o pedido
Pedido *pedidoEsfericoAco = (Pedido *) malloc(sizeof(Pedido));
// Valores default para um pedido do tipo conico
pedidoEsfericoAco->id = 'A';
pedidoEsfericoAco->prioridade = ALTA;
pedidoEsfericoAco->itMaquinaAtu = -1;
pedidoEsfericoAco->estadiaTorno = 1.0;
pedidoEsfericoAco->estadiaFresa = 0.5;
pedidoEsfericoAco->estadiaMandril = 1.4;
// Inserindo máquinas na ordem em que elas serão utilizadas pelo pedido
pedidoEsfericoAco->maquinas[0] = get_fresa_fabrica((Fabrica *)fabrica);
pedidoEsfericoAco->maquinas[1] = get_mandril_fabrica((Fabrica *)fabrica);
pedidoEsfericoAco->maquinas[2] = get_torno1_fabrica((Fabrica *)fabrica);
pedidoEsfericoAco->maquinas[3] = NULL; // Valor NULL para indicar que o pedido saiu da fábrica
// Tempo do pedido = tempo da fábrica + um valor "aleatório"
pedidoEsfericoAco->tempo = (get_tempo_fabrica((Fabrica *) fabrica)) + gera_tempo_pedido(8.0);
pedidoEsfericoAco->tempoChegada = pedidoEsfericoAco->tempo;
// Ponteiros para funções necessários para um pedido conico
pedidoEsfericoAco->atendePedido = atende_esferico_aco;
return pedidoEsfericoAco;
}
Pedido *cria_pedido_esferico_titanio(void *fabrica) {
// Alocação de espaço para o pedido
Pedido *pedidoEsfericoTitanio = (Pedido *) malloc(sizeof(Pedido));
// Valores default para um pedido do tipo conico
pedidoEsfericoTitanio->id = 'T';
pedidoEsfericoTitanio->prioridade = ALTA;
pedidoEsfericoTitanio->itMaquinaAtu = -1;
pedidoEsfericoTitanio->estadiaTorno = 1.6;
pedidoEsfericoTitanio->estadiaFresa = 0.6;
pedidoEsfericoTitanio->estadiaMandril = 1.5;
// Inserindo máquinas na ordem em que elas serão utilizadas pelo pedido
pedidoEsfericoTitanio->maquinas[0] = get_fresa_fabrica((Fabrica *)fabrica);
pedidoEsfericoTitanio->maquinas[1] = get_mandril_fabrica((Fabrica *)fabrica);
pedidoEsfericoTitanio->maquinas[2] = get_torno1_fabrica((Fabrica *)fabrica);
pedidoEsfericoTitanio->maquinas[3] = get_fresa_fabrica((Fabrica *)fabrica);
pedidoEsfericoTitanio->maquinas[4] = get_torno1_fabrica((Fabrica *)fabrica);
pedidoEsfericoTitanio->maquinas[5] = NULL; // Valor NULL para indicar que o pedido saiu da fábrica
// Tempo do pedido = tempo da fábrica + um valor "aleatório"
pedidoEsfericoTitanio->tempo = (get_tempo_fabrica((Fabrica *) fabrica)) + gera_tempo_pedido(8.0);
pedidoEsfericoTitanio->tempoChegada = pedidoEsfericoTitanio->tempo;
// Ponteiros para funções necessários para um pedido conico
pedidoEsfericoTitanio->atendePedido = atende_esferico_titanio;
return pedidoEsfericoTitanio;
}
Pedido *cria_pedido_esferico(void *fabrica) {
// Decidindo se será de aco ou titanio
if (rand() % 100 < 10) {
return cria_pedido_esferico_titanio(fabrica);
}
return cria_pedido_esferico_aco(fabrica);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
/* shape, color, number */
void get_roots(char *in, char *out_1, char *out_2, char *out_3) {
int ret;
ret = sscanf(in, "%[^,],%[^,],%[^,]", out_1, out_2, out_3);
if (ret != 3) {
puts("problem in parsing first word");
exit(-1);
}
}
int main(int argc, char **argv) {
char r11[32], r12[32], r13[32];
char r21[32], r22[32], r23[32];
char r31[32], r32[32], r33[32];
if (argc < 2) {
printf("usage:\n\t%s <word1> <word2> <word3>\n", argv[0]);
exit(-1);
}
get_roots(argv[1], r11, r12, r13);
get_roots(argv[2], r21, r22, r23);
get_roots(argv[3], r31, r32, r33);
/* generation */
puts("Group one");
printf(" 1: %s%s%s\n", r31, r32, r13);
printf(" 2: %s%s%s\n", r11, r12, r23);
printf(" 3: %s%s%s\n", r21, r22, r33);
puts("Group two");
printf(" 1: %s%s%s\n", r21, r22, r13);
printf(" 2: %s%s%s\n", r31, r32, r23);
printf(" 3: %s%s%s\n", r11, r12, r33);
puts("Group three");
printf(" 1: %s%s%s\n", r11, r12, r13);
printf(" 2: %s%s%s\n", r21, r22, r23);
printf(" 3: %s%s%s\n", r31, r32, r33);
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
void findExtrema(const int *pA, int Sz, int *pMin, int *pMax) {
*pMin = *pMax = pA[0]; // prime the min/max values
for (int idx = 1; idx < Sz; idx++) {
int Current = pA[idx]; // avoid extra array
// index operations
if ( Current < *pMin )
*pMin = Current;
else if ( Current > *pMax )
*pMax = Current;
}
}
int main(){
int List[5] = {34, 17, 22, 89, 4};
int lMin = 0, lMax = 0;
findExtrema(List, 5, &lMin, &lMax);
printf("lMin = %d lMax = %d\n", lMin, lMax);
return 0;
}
|
C
|
/*
* The main file for the game of Noah's Arkaid!
*/
#include <gb.h>
#include "BungBkg\bungbkg.h"
#include "Splash\Splash.h"
#include "MainMenu\MainMenu.h"
#include "Story\Story.h"
#include "Game\Game.h"
#include "Record\Record.h"
void main(void)
{
UWORD randSeed;
unsigned int menuChoice;
UBYTE firstRun;
firstRun = 1;
DISPLAY_ON;
/* This function will show the Bung Background and wait for a keypress
* It will also return a number based on how long it took before a key was pressed */
SWITCH_ROM_MBC1((UWORD)2); /* showBungBkg is in ROM bank 2 */
randSeed += showBungBkg();
SWITCH_ROM_MBC1((UWORD)0); /* showBungBkg is in ROM bank 2 */
/* This function will show the Noah's Arkaid background (intro) and wait for a keypress
* It will also return a number based on how long it took before a key was pressed */
SWITCH_ROM_MBC1((UWORD)3); /* showSplash is in ROM bank 3 */
randSeed += showSplash();
SWITCH_ROM_MBC1((UWORD)0); /* showSplash is in ROM bank 3 */
initrand(randSeed); /* Init the random number generator */
while(1) /* infinite loop */
{
/* This function will display a main menu and allow the user to choose settings or whatever
* some constant (like MENU_STARTGAME) should be returned */
SWITCH_ROM_MBC1((UWORD)4); /* mainMenu is in ROM bank 4 */
menuChoice = mainMenu();
SWITCH_ROM_MBC1((UWORD)0); /* mainMenu is in ROM bank 4 */
switch(menuChoice)
{
case MENU_STORYLINE:
SWITCH_ROM_MBC1((UWORD)5); /* displayStoryline is in ROM bank 5 */
displayStoryline();
SWITCH_ROM_MBC1((UWORD)0); /* displayStoryline is in ROM bank 5 */
break;
case MENU_STARTGAME: /* Start the game */
playGame(firstRun); /* This function will be responsible for all of the in-game functionality */
firstRun = 0;
break;
case MENU_RECORDSOUNDS: /* Start the game */
SWITCH_ROM_MBC1((UWORD)6); /* recordSounds is in ROM bank 6 */
recordSounds(); /* This function will be responsible for recording the user sounds with the PocketVoice */
SWITCH_ROM_MBC1((UWORD)0); /* recordSounds is in ROM bank 6 */
break;
default:
break; /* Shouldn't happen */
}
}
}
|
C
|
#include <stdio.h>
int main() {
//ǽ 2 - 3
float x; //Ǽ x Ѵ
x = 1.23456e-46; // Ǽ 1.23456e-46 ִ´
printf("20184071 赵\n");
printf("x = %10.20f\n", x); /*
Ǽ ڿ κ
10ڸ Ҽκ 20ڸ µǰԲ
x Ѵ.*/
return 0;
}
|
C
|
#include <stdio.h>
int main(void)
{
char str[20];
FILE * fp=fopen("simple.txt", "rt");
if(fp==NULL)
{
puts("파일오픈 실패");
return -1;
}
fgets(str, sizeof(str), fp);
puts(str);
fclose(fp);
return 0;
}
|
C
|
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<arpa/inet.h>
#include<errno.h>
#include<fcntl.h>
#include<unistd.h>
void main(){
struct sockaddr_in server,client;
int sock,clientSocket;
char receivedBytes[1024],sendBytes[1024];
int bytes;
if((sock = socket(AF_INET,SOCK_STREAM,0)) == -1){
perror("Invalid Socket Descriptor");
exit(1);
}
server.sin_family = AF_INET;
server.sin_port = htons(5005);
server.sin_addr.s_addr = INADDR_ANY;
bzero(&(server.sin_zero),8);
if(connect(sock,(struct sockaddr *)&server,sizeof(server)) == -1){
perror("Unable to connect");
exit(1);
}
while(1){
printf("\nClient: ");
gets(sendBytes);
bytes = send(sock,sendBytes,1024,0);
if(strcmp(sendBytes,"q") == 0 || strcmp(sendBytes,"Q") == 0){
printf("\nClient exiting...");
close(sock);
exit(1);
}
bytes = recv(sock,receivedBytes,1024,0);
receivedBytes[bytes] = '\0';
printf("\nServer: %s",receivedBytes);
if(strcmp(receivedBytes,"q") == 0 || strcmp(receivedBytes,"Q") == 0){
printf("\nServer going off...");
close(sock);
break;
}
}
}
/*
socket()
connect()
recv()
send()
*/
|
C
|
/*
dfsPhase2.c
Ben Donn
pa3
This file contains sweep function to find new roots and dfsPhase2() which runs on the transposed graph and calculates scc.
*/
#include <stdio.h>
#include <stdlib.h>
#include "intVec.h"
#include "dfsTrace1.h"
#include "loadGraph.h"
#include "dfsPhase2.h"
#include "scc03.h"
int rootCount = 0;
IntVec* dfsPhase2(IntVec *adjList, dfsData dfsInfo)
{
IntVec *roots = calloc(nodeCount + 1, sizeof(IntVec));
for (int i = 0; i <= nodeCount; i++)
{
roots[i] = intMakeEmptyVec();
}
int newRoot = 0;
newRoot = dfsSweepT(dfsInfo);
while (newRoot != -1)
{
dfsTrace1(adjList, newRoot, dfsInfo, roots, newRoot);
newRoot = dfsSweepT(dfsInfo);
}
return roots;
}
int dfsSweepT(dfsData dfsInfo)
{
int tempReturn = -1;
int i = 1;
while (1)
{
if ( (dfsInfo->color[i]) == 'W')
{
dfsInfo->parent[i] = -1;
return i;
}
i++;
if (i > nodeCount)
return tempReturn;
}
}
|
C
|
/*********************************************************************
*
* ANSI C Example program:
* TDMS-ContAcq-IntClk-LogOnly.c
*
* Example Category:
* AI
*
* Description:
* This example demonstrates how to continuous acquire data and
* stream that data to a binary TDMS file. The log only setting is
* optimized for streaming performance and is the recommended
* setting for streaming large amounts of data to disk.
*
* Instructions for Running:
* 1. Select the physical channel to correspond to where your
* signal is input on the DAQ device.
* 2. Enter the minimum and maximum voltage range.
* Note: For better accuracy try to match the input range to the
* expected voltage level of the measured signal.
* 3. Set the rate of the acquisition. Also set the Samples per
* Channel control. This will determine how many samples are
* read at a time. This also determines how many points are
* plotted on the graph each time.
* Note: The rate should be at least twice as fast as the maximum
* frequency component of the signal being acquired.
*
* Steps:
* 1. Create a task.
* 2. Create an analog input voltage channel.
* 3. Set the rate for the sample clock. Additionally, define the
* sample mode to be continuous.
* 4. Call the Configure Logging (TDMS) function and configure the
* task to log the data.
* 5. Call the Start function to start the acquistion.
* 6. Call the Clear Task function to clear the task.
* 7. Display an error if any.
*
* I/O Connections Overview:
* Make sure your signal input terminal matches the Physical
* Channel I/O control. For further connection information, refer
* to your hardware reference manual.
*
*********************************************************************/
#include <stdio.h>
#include <NIDAQmx.h>
#define DAQmxErrChk(functionCall) if( DAQmxFailed(error=(functionCall)) ) goto Error; else
int32 DoneCallback(TaskHandle taskHandle, int32 status, void *callbackData);
/*********************************************/
// DAQmx Configuration Options
/*********************************************/
// Sampling Options
const float64 sampleRate = 1000.0; // The sampling rate in samples per second per channel.
const uInt64 sampsPerChan = 1000; // The number of samples to acquire or generate for each channel in the task.
// DAQmxCreateAIVoltageChan Options
const char *physicalChannel = "Dev1/ai0"; // The names of the physical channels to use to create virtual channels. You can specify a list or range of physical channels.
const int32 terminalConfig = DAQmx_Val_Cfg_Default; // The input terminal configuration for the channel. Options: DAQmx_Val_Cfg_Default, DAQmx_Val_RSE, DAQmx_Val_NRSE, DAQmx_Val_Diff, DAQmx_Val_PseudoDiff
const float64 minVal = -10.0; // The minimum value, in units, that you expect to measure.
const float64 maxVal = 10.0; // The maximum value, in units, that you expect to measure.
const int32 units = DAQmx_Val_Volts; // The units to use to return the voltage measurements. Options: DAQmx_Val_Volts, DAQmx_Val_FromCustomScale
// DAQmxCfgSampClkTiming Options
const char *clockSource = "OnboardClock"; // The source terminal of the Sample Clock. To use the internal clock of the device, use NULL or use OnboardClock.
const int32 activeEdge = DAQmx_Val_Rising; // Specifies on which edge of the clock to acquire or generate samples. Options: DAQmx_Val_Rising, DAQmx_Val_Falling
const int32 sampleMode = DAQmx_Val_ContSamps; // Specifies whether the task acquires or generates samples continuously or if it acquires or generates a finite number of samples. Options: DAQmx_Val_FiniteSamps, DAQmx_Val_ContSamps, DAQmx_Val_HWTimedSinglePoint
// DAQmxConfigureLogging Options
const char *filePath = "../../test_data.tdms"; //The path to the TDMS file to which you want to log data.
const int32 loggingMode = DAQmx_Val_Log; // Specifies whether to enable logging and whether to allow reading data while logging. Options DAQmx_Val_Off, DAQmx_Val_Log, DAQmx_Val_LogAndRead
const char *groupName = "GroupName"; // The name of the group to create within the TDMS file for data from this task.
const int32 operation = DAQmx_Val_OpenOrCreate; // Specifies how to open the TDMS file. Options: DAQmx_Val_Open, DAQmx_Val_OpenOrCreate, DAQmx_Val_CreateOrReplace, DAQmx_Val_Create
int main(void)
{
int32 error=0;
TaskHandle taskHandle=0;
char errBuff[2048]={'\0'};
/*********************************************/
// DAQmx Configure Code
/*********************************************/
DAQmxErrChk (DAQmxCreateTask("",&taskHandle));
DAQmxErrChk (DAQmxCreateAIVoltageChan(taskHandle,physicalChannel,"",terminalConfig,minVal,maxVal,units,NULL));
DAQmxErrChk (DAQmxCfgSampClkTiming(taskHandle,clockSource,sampleRate,activeEdge,sampleMode,sampsPerChan));
DAQmxErrChk (DAQmxRegisterDoneEvent(taskHandle,0,DoneCallback,NULL));
/*********************************************/
// DAQmx TDMS Configure Code
/*********************************************/
DAQmxErrChk (DAQmxConfigureLogging(taskHandle,filePath,loggingMode,groupName,operation));
/*********************************************/
// DAQmx Start Code
/*********************************************/
DAQmxErrChk (DAQmxStartTask(taskHandle));
printf("Logging samples continuously. Press Enter to interrupt\n");
getchar();
Error:
if( DAQmxFailed(error) )
DAQmxGetExtendedErrorInfo(errBuff,2048);
if( taskHandle!=0 ) {
/*********************************************/
// DAQmx Stop Code
/*********************************************/
DAQmxStopTask(taskHandle);
DAQmxClearTask(taskHandle);
}
if( DAQmxFailed(error) )
printf("DAQmx Error: %s\n",errBuff);
printf("End of program, press Enter key to quit\n");
getchar();
return 0;
}
int32 DoneCallback(TaskHandle taskHandle, int32 status, void *callbackData)
{
int32 error=0;
char errBuff[2048]={'\0'};
// Check to see if an error stopped the task.
DAQmxErrChk (status);
DAQmxErrChk (DAQmxStopTask(taskHandle));
Error:
if( DAQmxFailed(error) ) {
DAQmxGetExtendedErrorInfo(errBuff,2048);
DAQmxClearTask(taskHandle);
printf("DAQmx Error: %s\n",errBuff);
}
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(){
FILE *pFile = NULL;
int lineCount = 0;
char *filename = "test.txt";
int c;
pFile = fopen(filename, "r");
while((c=fgetc(pFile)) != EOF){
if(c == '\n'){
lineCount++;
}
}
fclose(pFile);
pFile = NULL;
printf("%d\n", lineCount+1);
return 0;
}
|
C
|
#include "minishell.h"
int create_file(char *file, int mode)
{
int fd;
fd = open(file, O_RDONLY | O_CREAT | mode, 0644);
if (fd == -1)
{
printf("minishell: %s: %s\n", file, strerror(errno));
return (1);
}
close(fd);
return (EXIT_SUCCESS);
}
int check_input(char **files, int i)
{
int error;
error = 0;
if (!ft_memcmp(files[i], REDIRECT_INPUT_TOKEN, R_I_T_LEN + 1))
error = !does_file_exists(files[i + 1]);
if (error)
printf("minishell: %s: %s\n", files[i + 1], strerror(errno));
return (error);
}
int check_append(char **files, int i)
{
int error;
if (ft_memcmp(files[i], REDIRECT_OUTPUT_APPEND_TOKEN, R_O_A_T_LEN + 1))
return (0);
error = create_file(files[i + 1], 0);
return (error);
}
int check_output(char **files, int i)
{
int error;
if (ft_memcmp(files[i], REDIRECT_OUTPUT_TOKEN, R_O_T_LEN + 1))
return (0);
error = create_file(files[i + 1], O_TRUNC);
return (error);
}
int create_files(t_tree *tr)
{
char **files;
int i;
int error;
if (!tr)
return (EXIT_SUCCESS);
files = (char **)tr->content;
i = 0;
while (i < tr->size)
{
error = 0;
error = check_input(files, i);
if (error)
return (error);
error = check_append(files, i);
if (error)
return (error);
error = check_output(files, i);
if (error)
return (error);
i += 2;
}
return (EXIT_SUCCESS);
}
|
C
|
#define _CRT_SECURE_NO_WARNINGS 1
#include "highgame.h"
//̳ʼ
void high_InitBoard(char board[HIGH_ROWS][HIGH_COLS], int row, int col, char set)
{
int i = 0;
int j = 0;
for (i = 0; i < row; i++)
{
for (j = 0; j < col; j++)
{
board[i][j] = set;//鶨ʼΪҪַset
}
}
}
//̴ӡ
void high_DisplayBoard(char board[HIGH_ROWS][HIGH_COLS], int row, int col)
{
int i = 0;
int j = 0;
for (i = 0; i <= row; i++)
{
if (0 == i)
{
printf(" ");
continue;
}
printf("%2d ", i);
}
printf("\n");
for (i = 1; i <= row; i++)
{
printf("%2d ", i);
for (j = 1; j <= col; j++)
{
printf("%2c ", board[i][j]);
}
printf("\n");
}
}
//ףɨѶ
void high_Put_Mine(char board[HIGH_ROWS][HIGH_COLS], int row, int col)
{
int count = HIGH_COUNT;
int x = 0;
int y = 0;
while (count > 0)
{
x = rand() % row + 1;
y = rand() % col + 1;
if (board[x][y] == '0')//ֻз׳ɹcountһ
{
board[x][y] = '1';
count--;
}
}
}
//̣жӮ
int high_get_mine(char show[HIGH_ROWS][HIGH_COLS], int row, int col)
{
int i = 0;
int j = 0;
int count = 0;
for (i = 1; i <= row; i++)
{
for (j = 1; j <= col; j++)
{
if (show[i][j] == '*')
{
count++;
}
}
}
return count;
}
void high_Sweep(char mine[HIGH_ROWS][HIGH_COLS], char show[HIGH_ROWS][HIGH_COLS], int x, int y)
{
int count = 0;
count = mine[x - 1][y - 1] + mine[x][y - 1] + mine[x + 1][y - 1] +
mine[x - 1][y] + mine[x + 1][y] + mine[x - 1][y + 1] +
mine[x][y + 1] + mine[x + 1][y + 1] - 8 * '0';
if (0 == count)
{
int i = 0;
int j = 0;
show[x][y] = ' ';
for (i = -1; i <= 1; i++)
{
for (j = -1; j <= 1; j++)
{
//forѭеݹ飬ݹܹķΧڣshow*ѾԪ
if ((x + i) >= 1 && (x + i) <= HIGH_ROW && (y + j) >= 1 && (y + j) <= HIGH_COL && show[x + i][y + j] == '*')
{
high_Sweep(mine, show, x + i, y + j);
}
}
}
}
//if (count == 0&&x>=1&&x<=ROW&&y>=1&&y<=COL&&mine[x][y]!=' ')
//{
// show[x][y] = ' ';
// Sweep(mine, show, x-1, y-1);
// Sweep(mine, show, x, y - 1);
// Sweep(mine, show, x + 1, y - 1);
// Sweep(mine, show, x - 1, y);
// Sweep(mine, show, x + 1, y);
// Sweep(mine, show, x - 1, y + 1);
// Sweep(mine, show, x, y + 1);
// Sweep(mine, show, x + 1, y + 1);
//}
else
{
show[x][y] = count + '0';
}
}
//Χм
void high_Calu_Mine(char mine[HIGH_ROWS][HIGH_COLS], char show[HIGH_ROWS][HIGH_COLS], int row, int col)
{
int x = 0;
int y = 0;
int count = row*col - HIGH_COUNT;
printf("ѡ꣺\n");
while (1)
{
scanf("%d%d", &x, &y);
printf("\n");
if (x >= 1 && x <= row&&y >= 1 && y <= col)
{
if (mine[x][y] == '1')
{
printf("ź˴ף\n");
break;
}
else
{
high_Sweep(mine, show, x, y);
high_DisplayBoard(show, HIGH_ROW, HIGH_COL);
count = high_get_mine(show, HIGH_ROW, HIGH_COL) - HIGH_COUNT;
}
}
else
{
printf("\n");
}
}
if (0 == count)
{
printf("׳ɹ\n");
high_DisplayBoard(mine, HIGH_ROW, HIGH_COL);
}
}
|
C
|
#include <stdio.h>
list *kreverse(list *head, int k) {
if(k <= 1) // nothing to reverse
return head;
list *p = head, *tail = 0;
while(p != 0) {
// remember where we start this piece
list *start = p, *prev = 0, *temp;
int c = k;
while(p != 0 && c-- > 0) { // do usual reverse
temp = p->next;
p->next = prev;
prev = p;
p = temp;
}
if(tail != 0) // link reversed pieces
tail->next = prev;
else // indicates the first piece
head = prev;
tail = start;
// here p points to the next part being processed
}
return head;
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* label.h :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: aiwanesk <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2017/03/17 13:32:52 by aiwanesk #+# #+# */
/* Updated: 2017/03/17 13:32:53 by aiwanesk ### ########.fr */
/* */
/* ************************************************************************** */
#ifndef LABEL_H
# define LABEL_H
# include <struct_lex.h>
# define SIZE_ARRAY 100
typedef struct s_label
{
unsigned int hash;
unsigned int addr;
} t_label;
typedef struct s_lab
{
unsigned int libre;
t_label label[SIZE_ARRAY + 1];
struct s_lab *next;
} t_lab;
/*
** label0.c
*/
t_lab *lab_get(void);
void lab_new(t_lex *lex, unsigned int size);
void lab_free(void);
/*
** label1.c
*/
void lab_check(t_lex *lex, unsigned int label);
t_label label_valid(t_lex *lex, int pos, unsigned int label);
#endif
|
C
|
#include<stdio.h>
#include<string.h>
#include<assert.h>
char* BF_CMP(const char* src1,const char* src2)
{
int i,j;
i=0;
int len1=strlen(src1);
int len2=strlen(src2);
while(i!=len1)
{
j=0;
while(src1[i]==src2[j]&&j!=len2&&i!=len1)
{
++i;
++j;
}
if(len2==j)
return &src1[i-j];
else
i=i-j+1;
}
return NULL;
}
void get_next(const char* str,int* next)
{
int len=strlen(str);
int i=0,j=-1;
next[0]=-1;
while(i!=len)
{
if(j==-1||str[i]==str[j])
{
++i;
++j;
next[i]=j;
}
else
{
j=next[j];
}
}
}
char* KMP_CMP(const char* str1,const char* str2)
{
int len1=strlen(str1);
int len2=strlen(str2);
int next[len2+1];
get_next(str2,next);
int i,j;
i=0;
j=0;
while(i!=len1)
{
if(str1[i]==str2[j]||j==-1)
{
++i;
++j;
}
else
j=next[j];
if(len2==j)
return &str1[i-j];
}
return NULL;
}
int main()
{
char s1[100];
char s2[100];
fgets(s1,100,stdin);
fgets(s2,100,stdin);
int len1=strlen(s1);
int len2=strlen(s2);
s1[len1-1]=0;
s2[len2-1]=0;
char* result=KMP_CMP(s1,s2);
if(result)
printf("%s\n",result);
else
printf("No match!\n");
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* get_next_line.h :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: pkolomiy <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2017/07/20 16:49:00 by pkolomiy #+# #+# */
/* Updated: 2017/11/26 16:04:32 by pkolomiy ### ########.fr */
/* */
/* ************************************************************************** */
#ifndef GET_NEXT_LINE_H
# define GET_NEXT_LINE_H
# define BUFF_SIZE 4056
# include <unistd.h>
# include <stdlib.h>
# define SEARCH_NEWLINE 1
# define MAKE_A_COPY 2
# define STRING_LENGTH 3
# define CROP_STRING 4
typedef struct s_lst
{
int fd;
char *str;
struct s_lst *next;
} t_lst;
typedef struct s_var
{
int nbr;
int index;
int first_char;
char buff[BUFF_SIZE + 1];
char *temp;
t_lst *lst;
} t_var;
int get_next_line(const int fd, char **line);
#endif
|
C
|
#pragma once
struct BinaryTreeNode
{
int m_value;
BinaryTreeNode* m_pleft;
BinaryTreeNode* m_right;
};
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <ctype.h>
int main()
{
int i, j;
int a=-2e16, b=2e16-1;
scanf("%d", &i);
while (scanf("%d", &i)==1) {
if (i>a) {
a=i;
}
if (i<b) {
b=i;
}
}
printf("The maximum number is %d.\nThe minimum number is %d.", a ,b);
return 0;
}
/**************************************************************
Problem: 1024
User: 201901060401
Language: C
Result: Accepted
Time:4 ms
Memory:748 kb
****************************************************************/
|
C
|
/* ----------------------------------------------
The goal of this program is to calculate the
sum of numbers in a row of a matrix, for all the
rows in that matrix. Also, the diagonal sum is
calculated. The matrix itself was given in the
assignment and is formatted into C by a 4x4 double
array (2 dimensional).
In terms of printing, this program prints out each row
of the matrix itself, one after another, to display
before the average and sum are shown directly to the right
of the row. The diagonal sums are printed directly after
the sum of all the components in the matrix is displayed.
The function avg_rowfunc is designed to take a single
dimensional (1D) array and calculate the average of the
entries in that array. This was useful for calculating
the average of the elements per row.
As for the diagonals, top L to bottom R was easy because
each entry has the same indices (0,0 and 1,1 etc). But,
for the opposite direction (top R to bottom L), the column
identifier had to be subtracted by 1 each time.
----------------------------------------------- */
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
int row = 0, column = 0, n = 0, k = 3;
double totalsum = 0.0, rowsum = 0.0, rowavg = 0.0, diag1 = 0.0, diag2 = 0.0;
double onerow[4];
double avg_rowfunc(double matrix[]);
// define matrix itself as 4x4 with all values from assignment
double m[4][4] = {
{66.2, 10.1, 35.6, 19.9},
{65.1, 11.9, 88.3, 17.1},
{1.1, 2.7, 3.8, 4.2},
{5.9, 6.6, 9.9, 77.7},
};
// begin by print out name and top of table format
printf(" Matrix\t\t\t\t\t Row Sum \t Row Average\n");
printf(" ====================================================================\n\n");
for( row = 0; row < 4; row++ )
{
rowsum = 0.0; // reset sum so iterations don't compile together
for( column = 0; column < 4; column++ )
{
onerow[column] = m[row][column]; // put each row into it's own array and pass to avg. function
rowsum = rowsum + m[row][column]; // sum of row is addition of it's elements
}
for ( n = 0; n < 4; n++)
{
printf(" %.2f\t", onerow[n]); // print out each row in the matrix for display
}
rowavg = avg_rowfunc(onerow); // call function to calculate average of row
totalsum = totalsum + rowsum; // the total sum continuously updates - does not reset to 0 after iteration
printf("\t %.2f \t %.2f\n", rowsum, rowavg ); // now print out sum of row and average to display next to row of matrix
}
printf("\n Total sum of all matrix components: %.2f\n", totalsum);
// diagonal sums section: top table format print out
printf("\n ====================================================================\n\n");
printf(" Diagonal Sums of Matrix \n\n");
printf(" Top Left to Bot Right \t\t Top Right to Bot Left \n");
for( n = 0; n < 4; n++ ) // n is used because it'll be specifying both rows and columns in diag1
{
diag1 = diag1 + m[n][n]; // top L to bot R is just 0,0 then 1,1 then 2,2 then 3,3
diag2 = diag2 + m[n][k]; // top R to bot L is 0,3 then 1,2 then 2,1 then 3,0
k = k - 1; // advance rows backwards from 3 for top R to bot L
}
printf("\n \t %.2f \t\t\t %.2f \n", diag1, diag2); // print out diagonal results and end table format
printf("\n ======================================================\n\n");
}
double avg_rowfunc(double mat[]) // function to calculate average of any given array inputted
{
int i = 0;
int n = sizeof(mat);
double total = 0.0;
for( i = 0; i < 4; i++ ) // indice increases by one in array to sum up each element
{
total = total + mat[i]; // sum of the array is sum plus the current matrix indice
}
return (total / n); // average is just the total sum over the size of the array
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_get_next_line.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: dpowdere <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2020/12/13 11:29:30 by dpowdere #+# #+# */
/* Updated: 2020/12/19 19:42:20 by dpowdere ### ########.fr */
/* */
/* ************************************************************************** */
#include <stddef.h>
#include <stdlib.h>
#include <unistd.h>
#include "ft_get_next_line.h"
int ft_get_next_line(int fd, char **line)
{
static struct s_stash stash;
if (fd < 0 || line == NULL || BUFFER_SIZE < 1)
return (GNL_ERROR);
if (stash.fd != fd)
{
ft_reset(&stash, RESET_ALL_TO_DEFAULT);
stash.fd = fd;
}
if (stash.tail == NULL && ft_add_tail(&stash) == FAIL)
return (GNL_ERROR);
while (ft_find_nl(&stash) == NOT_FOUND)
{
if (ft_add_tail(&stash) == FAIL)
{
ft_reset(&stash, RESET_ALL_TO_DEFAULT);
return (GNL_ERROR);
}
}
*line = NULL;
if (ft_get_line_from_stash(&stash, line) == FAIL)
return (GNL_ERROR);
if (*line == NULL)
return (GNL_EOF);
return (GNL_LINE);
}
static void ft_reset(struct s_stash *stash, int kind)
{
struct s_part *tmp;
if (kind == RESET_ALL_TO_DEFAULT)
stash->fd = DEFAULT_FD;
stash->start = DEFAULT_START_POS;
stash->end = DEFAULT_END_POS;
while (stash->head)
{
if (stash->head->s)
free(stash->head->s);
tmp = stash->head;
stash->head = stash->head->next;
free(tmp);
}
stash->head = NULL;
stash->tail = NULL;
}
static int ft_add_tail(struct s_stash *stash)
{
struct s_part *tail;
tail = (struct s_part *)malloc(sizeof(struct s_part));
if (tail == NULL)
return (FAIL);
tail->next = NULL;
tail->s = (char *)malloc(sizeof(char) * BUFFER_SIZE);
if (tail->s == NULL)
{
free(tail);
return (FAIL);
}
if (stash->tail == NULL)
stash->head = tail;
else
stash->tail->next = tail;
stash->tail = tail;
tail->size = read(stash->fd, tail->s, BUFFER_SIZE);
if (tail->size == READ_ERROR)
return (FAIL);
return (SUCCESS);
}
static int ft_find_nl(struct s_stash *stash)
{
if (stash->head->next == NULL)
stash->end = stash->start;
else
stash->end = 0;
if (stash->tail->size == READ_EOF)
return (FOUND);
while (stash->end < stash->tail->size)
{
if (stash->tail->s[stash->end] == NL_CHAR)
return (FOUND);
stash->end += 1;
}
return (NOT_FOUND);
}
static int ft_get_line_from_stash(struct s_stash *stash, char **line)
{
size_t size;
if (stash->head->next == NULL && stash->tail->size == READ_EOF)
{
*line = NULL;
ft_reset(stash, RESET_ALL_TO_DEFAULT);
return (SUCCESS);
}
size = ft_get_line_size(stash);
*line = (char *)malloc(size * sizeof(char));
if (*line == NULL)
{
ft_reset(stash, RESET_ALL_TO_DEFAULT);
return (FAIL);
}
ft_dump_line(stash, *line);
if (stash->start >= stash->tail->size)
ft_reset(stash, KEEP_FILE_DESCRIPTOR);
return (SUCCESS);
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* math.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: avinas <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2018/07/22 13:30:37 by avinas #+# #+# */
/* Updated: 2018/07/24 15:25:21 by avinas ### ########.fr */
/* */
/* ************************************************************************** */
#include "../../include/rtv1.h"
double v_dot(t_vertex vec1, t_vertex vec2)
{
return (vec1.x * vec2.x
+ vec1.y * vec2.y
+ vec1.z * vec2.z);
}
t_vertex v_sub(t_vertex vec1, t_vertex vec2)
{
t_vertex vec;
vec.x = vec1.x - vec2.x;
vec.y = vec1.y - vec2.y;
vec.z = vec1.z - vec2.z;
return (vec);
}
t_vertex v_norm(t_vertex vec)
{
t_vertex vecnorm;
vecnorm.x = vec.x / sqrt(vec.x * vec.x + vec.y * vec.y + vec.z * vec.z);
vecnorm.y = vec.y / sqrt(vec.x * vec.x + vec.y * vec.y + vec.z * vec.z);
vecnorm.z = vec.z / sqrt(vec.x * vec.x + vec.y * vec.y + vec.z * vec.z);
return (vecnorm);
}
double solve_quadratic(t_vertex q, double *r1, double *r2)
{
double d;
*r1 = -1;
*r2 = -1;
d = q.y * q.y - 4 * q.x * q.z;
/*if (d == 0)
{
*r1 = -q.y / (2 * q.x);
return (1);
}*/
if (d >= 0)
{
/*
rslt = ((-q.y - sqrt(d)) / (2 * q.x)) > 0 ?
(-q.y + sqrtf(d)) / (2 * q.x) :
(-q.y - sqrtf(d)) / (2 * q.x)
*/
*r1 = (-q.y + sqrtf(d)) / (2 * q.x);
*r2 = (-q.y - sqrtf(d)) / (2 * q.x);
return (2);
}
/*else
rslt = 0;
return (rslt);*/
return (0);
}
int is_closer(t_vertex vec1, t_vertex vec2, t_ray *ray)
{
double dist1;
double dist2;
dist1 = sqrtf(pow(ray->ori.x - vec1.x, 2)
+ pow(ray->ori.y - vec1.y, 2)
+ pow(ray->ori.z - vec1.z, 2));
dist2 = sqrtf(pow(ray->ori.x - vec2.x, 2)
+ pow(ray->ori.y - vec2.y, 2)
+ pow(ray->ori.z - vec2.z, 2));
if (dist1 > dist2)
return (1);
return (0);
}
|
C
|
/*
* This function calculates approximately (whole + num/den) * sf.
* No need for real extreme accuracy; one twenty thousandth of an
* inch should be sufficient.
*
* No `sf' parameter means to use an old one; inches are assumed
* originally.
*
* Assumptions:
*
* 0 <= num < den <= 20000
* 0 <= whole
*/
#include "dvips.h"
void error() ;
static long scale(whole, num, den, sf)
long whole, num, den, sf ;
{
long v ;
v = whole * sf + num * (sf / den) ;
if (v / sf != whole || v < 0 || v > 0x40000000L)
error("! arithmetic overflow in parameter") ;
sf = sf % den ;
v += (sf * num * 2 + den) / (2 * den) ;
return(v) ;
}
/*
* Convert a sequence of digits into a long; return -1 if no digits.
* Advance the passed pointer as well.
*/
static long myatol(s)
char **s ;
{
register char *p ;
register long result ;
result = 0 ;
p = *s ;
while ('0' <= *p && *p <= '9') {
if (result > 100000000)
error("! arithmetic overflow in parameter") ;
result = 10 * result + *p++ - '0' ;
}
if (p == *s) {
error("expected number! returning 10") ;
return 10 ;
} else {
*s = p ;
return(result) ;
}
}
/*
* Get a dimension, allowing all the various extensions, and
* defaults. Returns a value in scaled points.
*/
static long scalevals[] = { 1864680L, 65536L, 786432L, 186468L,
1L, 65782L, 70124L, 841489L, 4736286L } ;
static char *scalenames = "cmptpcmmspbpddccin" ;
long myatodim(s)
char **s ;
{
register long w, num, den, sc ;
register char *q ;
char *p ;
int negative = 0, i ;
p = *s ;
if (**s == '-') {
p++ ;
negative = 1 ;
}
w = myatol(&p) ;
if (w < 0) {
error("number too large; 1000 used") ;
w = 1000 ;
}
num = 0 ;
den = 1 ;
if (*p == '.') {
p++ ;
while ('0' <= *p && *p <= '9') {
if (den <= 1000) {
den *= 10 ;
num = num * 10 + *p - '0' ;
} else if (den == 10000) {
den *= 2 ;
num = num * 2 + (*p - '0') / 5 ;
}
p++ ;
}
}
while (*p == ' ')
p++ ;
for (i=0, q=scalenames; ; i++, q += 2)
if (*q == 0) {
error("expected units! assuming inches.") ;
sc = scalevals[8] ;
break ;
} else if (*p == *q && p[1] == q[1]) {
sc = scalevals[i] ;
p += 2 ;
break ;
}
w = scale(w, num, den, sc) ;
*s = p ;
return(negative?-w:w) ;
}
/*
* The routine where we handle the paper size special. We need to pass in
* the string after the `papersize=' specification.
*/
void handlepapersize(p, x, y)
char *p ;
integer *x, *y ;
{
while (*p == ' ')
p++ ;
*x = myatodim(&p) ;
while (*p == ' ' || *p == ',')
p++ ;
*y = myatodim(&p) ;
}
|
C
|
#include <stdio.h>
int main()
{
int p, n;
float si, r;
p = 1000;
r = 8.5;
n = 3;
si = p*r*n/100;
printf("%f \n", si);
return 0;
}
|
C
|
#include <stdio.h>
long dp[10][101];
int solve(int i, int n) {
if (n == 1) return 1;
if (dp[i][n] > 0) return dp[i][n];
dp[i][n] = 0;
if (i < 9)
dp[i][n] += solve(i + 1,n - 1);
if (i > 0)
dp[i][n] += solve(i - 1, n - 1);
dp[i][n] %= 1000000000;
return dp[i][n];
}
int main() {
int n;
long result = 0;
scanf_s("%d", &n);
for (int i = 1; i < 10; i++)
result += solve(i, n);
printf("%d\n", result % 1000000000);
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
/***************
* Jeffrey Marple
* Lab 7, 2400
****************/
void merge(int array1[], int length1, int array2[], int length2, int result[]);
int main(){
int arr1Size = 0;
int arr2Size = 0;
int* arr1;
int* arr2;
int newNum[1];
int* resultArr;
printf("Enter how many values for list 1: ");
arr1Size = readInt();
arr1 = (int*)malloc(arr1Size * sizeof(int));
printf("Enter how many values for list 2: ");
arr2Size = readInt();
arr2 = (int*)malloc(arr2Size * sizeof(int));
//get vals for 1st array
printf("Enter %d interger values for List 1 one at a time: \n", arr1Size);
for(int i=0; i<arr1Size; i++){
//store input number
newNum[0] = readInt();
resultArr = (int*)malloc((arr1Size) * sizeof(int));
//sort newNum into list appropriately
merge(arr1, i, newNum, 1, resultArr);
//copy contents from result array into arr1
for(int j=0; j<arr1Size; j++){
arr1[j] = resultArr[j];
}
free(resultArr);
}
printf("Enter %d interger values for List 2 one at a time: \n", arr2Size);
//get vals for 2nd array
for(int j=0; j< arr2Size; j++ ){
//store input number
newNum[0] = readInt();
resultArr = (int*)malloc((arr2Size) * sizeof(int));
//sort newNum into list appropriately, store in result
merge(arr2, j, newNum, 1, resultArr);
//copy contents from result array into arr2
for(int i=0; i<arr2Size; i++){
arr2[i] = resultArr[i];
}
free(resultArr);
}
//------prints------//
printf("Sorted List 1: ");
for(int j=0; j< arr1Size; j++ ){
printf("%d ", arr1[j]);
}
printf("\n");
printf("Sorted List 2: ");
for (int j=0; j< arr2Size; j++ ){
printf("%d ", arr2[j]);
}
printf("\n");
resultArr = (int*)malloc((arr1Size + arr2Size) * sizeof(int));
printf("Merged lists of 1 and 2: ");
merge(arr1, arr1Size, arr2, arr2Size, resultArr);
for (int j=0; j< (arr2Size+arr1Size); j++ ){
printf("%d ", resultArr[j]);
}
printf("\n");
free(arr1);
free(arr2);
free(resultArr);
}//endMain
void merge(int array1[], int length1, int array2[], int length2, int result[]){
int arr1Index = 0;
int arr2Index = 0;
int resultArrIndex = 0;
while(resultArrIndex < length1 + length2){
//printf("%d ", array2[1]);
//compare each index in array
if(arr1Index >= length1){
result[resultArrIndex] = array2[arr2Index];
resultArrIndex++;
arr2Index++;
}else if (arr2Index >= length2){
result[resultArrIndex] = array1[arr1Index];
resultArrIndex++;
arr1Index++;
}else if(array1[arr1Index] <= array2[arr2Index]){
result[resultArrIndex] = array1[arr1Index];
resultArrIndex++;
arr1Index++;
}else{
result[resultArrIndex] = array2[arr2Index];
resultArrIndex++;
arr2Index++;
}
}//end while
}//endMerge
int readInt(){
int c = 0;
int i = 0;
while( (c = getchar()) != EOF && c != '\n' )
{
if( c >= '0' && c <= '9')
i = i * 10 + (c - '0');
}
return i;
}
|
C
|
#include<stdio.h>
#include<conio.h>
static int arr[] = {2, 5, 8, 3, 7, 9};
void merging(int l, int m, int h)
{
int n1 = m+1, n2 = (h-m)+1;
int *L, *R;
int i;
L = (int *)calloc(sizeof(int), n1);
R = (int *)calloc(sizeof(int), n2);
for(i=l;i<m-1;i++)
L[i] = arr[i];
for(i=m;i<h;i++)
R[i] = arr[i];
for(i=l;i<m-1;i++)
printf("%d ", L[i]);
printf("\n");
for(i=m;i<h;i++)
printf("%d ", R[i]);
}
void mergeSort(int low, int high)
{
int mid;
if(low < high) //termination condition
{
mid = (high + low)/2;
mergeSort(low, mid);
mergeSort(mid+1, high);
merging(low, mid, high);
}
}
void main()
{
int low,mid,high;
int i,j;
clrscr();
low = 0; high = 6;
mergeSort(low, high);
getch();
}
|
C
|
#include<stdio.h>
/* Implemente um programa que solicita ao usuário um valor inteiro correspondente à idade
de uma pessoa em dias e informea em anos, meses e dias.
Obs.: apenas para facilitar o cálculo, considere todo ano com 365 dias e todo mês com 30 dias. Nos
casos de teste nunca haverá uma situação que permite 12 meses e alguns dias, como 360, 363 ou
364. Este é apenas um exercício com objetivo de testar raciocínio matemático simples.
Exemplos para teste:
400 dias → 1 ano(s) 1 mes(es) 5 dia(s)
800 dias → 2 ano(s) 2 mes(es) 10 dia(s)
30 dias → 0 ano(s) 1 mes(es) 0 dia(s) */
void main(){
int a,b,A,M,D;
printf("Digite a idade em dias: ");
scanf("%i",&a);
A=a/365;
b=a%365;
M=b/30;
D=b%30;
printf("%i ano(s) %i mes(es) %i dia(s)\n",A,M,D);
}
|
C
|
/*
* File: nfa.h
* Creator: George Ferguson
* Created: Thu Sep 1 17:54:41 2016
* Time-stamp: <Mon Sep 5 15:42:16 EDT 2016 ferguson>
*/
#ifndef _nfa_h_gf
#define _nfa_h_gf
#include <stdbool.h>
// Assume input is 7-bit US-ASCII characters
#define NFA_NSYMBOLS 128
// Assume we start in state 0
#define NFA_START_STATE 0
// The transition function is represented as an array, indexed by input
// symbol, of the set of states reached on that symbol.
typedef struct {
IntSet *transitions[NFA_NSYMBOLS];
bool is_accepting;
} NFA_State;
// An NFA is an array of States (size TBD) and a set of possible current states
typedef struct {
int nstates;
NFA_State *states;
IntSet *current_states;
} NFA;
extern NFA *NFA_new(int nstates);
extern void NFA_free(NFA *nfa);
extern int NFA_get_size(NFA *nfa);
extern IntSet *NFA_get_transitions(NFA *nfa, int statenum, char symbol);
extern void NFA_add_transition(NFA *nfa, int src, char symbol, int dst);
extern void NFA_add_transition_str(NFA *nfa, int src, char *str, int dst);
extern void NFA_add_transition_all(NFA *nfa, int src, int dst);
extern IntSet *NFA_get_current_states(NFA *nfa);
extern void NFA_set_current_states(NFA *nfa, IntSet *states);
extern void NFA_set_current_state(NFA *nfa, int state);
extern bool NFA_get_accepting(NFA *nfa, int statenum);
extern void NFA_set_accepting(NFA *nfa, int statenum, bool value);
extern bool NFA_is_accepting(NFA *nfa);
extern bool NFA_execute(NFA *nfa, char *input);
// True to enable tracing during NFA_Execute
extern int NFA_tracing;
#endif
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* rush04.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: nschwarz <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2017/08/20 22:21:51 by nschwarz #+# #+# */
/* Updated: 2017/08/20 22:21:52 by nschwarz ### ########.fr */
/* */
/* ************************************************************************** */
#include <stdlib.h>
#define ENDOFLINE1 'C'
#define ENDOFLINE2 'A'
#define STARTOFLINE1 'A'
#define STARTOFLINE2 'C'
#define HLIGN 'B'
#define VLIGN 'B'
#define SPACE ' '
void ft_print_last_line04(int x, char *str, int c)
{
int a;
char tiret;
a = 2;
tiret = HLIGN;
str[c++] = STARTOFLINE2;
while (a < x)
{
str[c++] = tiret;
a++;
}
if (x > 1)
{
str[c++] = ENDOFLINE2;
}
str[c++] = '\n';
}
void ft_inter_lines04(int x, char *str, int z)
{
char space;
int c;
c = 2;
space = SPACE;
str[z++] = VLIGN;
while (c < x)
{
str[z++] = space;
c++;
}
if (x > 1)
{
str[z++] = VLIGN;
}
str[z++] = '\n';
}
void ft_choose_inter_line_number04(int x, int y, char *str, int c)
{
int a;
a = 2;
if (y > 1)
{
while (a < y)
{
ft_inter_lines04(x, str, c);
a++;
c += x + 1;
}
ft_print_last_line04(x, str, c);
}
}
void ft_print_first_line04(int x, int y, char *str)
{
int a;
char tiret;
int c;
c = 0;
a = 2;
tiret = HLIGN;
str[c++] = STARTOFLINE1;
while (a < x)
{
str[c++] = tiret;
a++;
}
if (x > 1)
{
str[c++] = ENDOFLINE1;
}
str[c++] = '\n';
ft_choose_inter_line_number04(x, y, str, c);
}
char *rush04(int x, int y)
{
char *str;
if (!(str = malloc((x + 1) * y * sizeof(char))))
return (0);
if (x > 0 & y > 0)
{
ft_print_first_line04(x, y, str);
}
else
{
if (x == 1 && y == 1)
{
str[0] = STARTOFLINE1;
}
else
{
str[0] = '\n';
}
}
return (str);
}
|
C
|
// This program impliments matrix tiling to compute the product of two randomly populated N X N matrices, A and B.
// The tile size is H X H
// N and H are hardcoded
// The order of the for-loops is also hardcoded
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <sys/time.h>
float A[2050][2050];
float B[2050][2050];
float C[2050][2050];
int main(){
struct timeval start;
struct timeval end;
unsigned long long int total_time = 0; // formatter is %llu
long double FLOPS = 0; // formatter is %Lf
long double MFLOPS = 0;
float N = 2050.0 ; // size of matrix, hardcoded
int n = (int)N;
float H = 41.0; // size of tile, hardcoded
float h = (int)(H);
// randomly populate arrays
for (int i = 0; i < n; i ++){
for (int j = 0; j < n; j ++){
A[i][j] = (float)rand() ;
B[i][j] = (float)rand() ;
}
}
// Cache warm up
for (int ii = 0; ii < n/h ; ii++){
for (int kk = 0; kk < n/h ; kk++){
for (int jj = 0; jj < n/h ; jj++){
for (int i = ii*h; i < (ii+1)*h ; i++){
for (int k = kk*h; k < (kk+1)*h ; k++){
for (int j = jj*h; j < (jj+1)*h ; j++){
C[i][j] += A[i][k] * B[k][j];
}
}
}
}
}
}
// Second run. Measure time taken.
gettimeofday(&start, NULL);
for (int ii = 0; ii < n/h ; ii++){
for (int kk = 0; kk < n/h ; kk++){
for (int jj = 0; jj < n/h ; jj++){
for (int i = ii*h; i < (ii+1)*h ; i++){
for (int k = kk*h; k < (kk+1)*h ; k++){
for (int j = jj*h; j < (jj+1)*h ; j++){
C[i][j] += A[i][k] * B[k][j];
}
}
}
}
}
}
gettimeofday(&end, NULL);
total_time = (end.tv_sec * 1000000 + end.tv_usec)
- (start.tv_sec * 1000000 + start.tv_usec); // time in microseconds, 1 microsecond = 10^(-6) seconds
double total_time_as_double = (double)total_time;
FLOPS = ( 2*N*N*N / total_time_as_double ) * 1000000 ; // (2*N^3) / t, converting back to seconds.
MFLOPS = FLOPS / 1000000;
printf("Array size: %f \n", N );
printf("Subarray size: %f \n", H);
printf("time taken (in microseconds): %lf \n", total_time_as_double );
printf("MFLOPS = %Lf \n", MFLOPS );
} // ends main
|
C
|
#include <linux/init.h>
#include <linux/module.h>
#include <linux/platform_device.h>
#include <linux/miscdevice.h>
#include <linux/fs.h>
#define DRIVER_NAME "hello_ctl"
#define DEVICE_NAME "hello_ctl123"
MODULE_LICENSE("Dual BSD/GPL");
MODULE_AUTHOR("cqx");
static int hello_open(struct inode *inode, struct file *file){
printk(KERN_EMERG "open\n");
return 0;
}
static int hello_release(struct inode *inode, struct file *file){
printk(KERN_EMERG "release\n");
return 0;
}
static long hello_ioctl(struct file *file, unsigned int cmd, unsigned int arg){
printk("cmd is %d, arg is %d\n", cmd, arg);
return 0;
}
static struct file_operations hello_ops = {
.ower = THIS_MODULE,
.open = hello_open,
.release = hello_release,
.unlocked_ioctl = hello_ioctl,
};
static struct miscdevice hello_dev = {
.minor = MISC_DYNAMIC_MINOR,
.name = DEVICE_NAEM,
.fops = &hello_ops,
};
static int hello_probe(struct platform_device *pdev){
printk(KERN_EMERG "initialize\n");
misc_register(&hello_dev);
return 0;
}
static int hello_remove(struct platform_device *pdev){
printk(KERN_EMERG "remove\n");
misc_deregister(&hello_dev);
return 0;
}
static void hello_shutdown(struct platform_device *pdev){
;
}
static int hello_suspend(struct platform_device *pdev, pm_message_t pmt){
return 0;
}
static int hello_resume(struct platform_device *pdev){
return 0;
}
struct platfrom_driver hello_driver = {
.probe = hello_probe,
.remove = hello_remove,
.shutdown = hello_shutdown,
.suspend = hello_suspend,
.resume = hello_resume,
.driver = {
.name = DRIVER_NAME,
.owner = THIS_MODULE,
}
};
static int hello_init(void)
{
int DriverState;
printk(KERN_EMERG "hello world enter!\n");
DriverState = platform_driver_register(&hello_driver);
printk(KERN_EMERG "driver state is %d\n", DriverState);
return 0;
}
static void hello_exit(void)
{
printk(KERN_EMERG "hello world eixt!\n");
platfrom_driver_unregister(&hello_driver);
}
module_init(hello_init);
moduel_exit(hello_exit);
|
C
|
#include <unistd.h>
int main()
{
// become root
setuid(0);
// run bash
system("bash");
return 0;
}
|
C
|
#include<unistd.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<sys/fcntl.h>
#include<netinet/in.h>
#include<arpa/inet.h>
#include<netdb.h>
#include <time.h>
#include <sys/time.h>
#include<stdlib.h>
#include <errno.h>
#include <stdio.h>
#include <string.h>
#define SERVER_PORT 33333
#define MAXLEN 65535
void client_handle(int sock);
int set_linger(int sock, int l_onoff, int l_linger);
static void set_nonblock(int sock){
int flags = fcntl(sock, F_GETFL, 0);
fcntl(sock, F_SETFL, flags | O_NONBLOCK);
}
int main(int argc, char* argv[]) {
for (int i = 1; i < argc; ++i) {
printf("input args %d: %s\n", i, argv[i]);
}
struct sockaddr_in seraddr;
int server_port = SERVER_PORT;
if (2 == argc) {
server_port = atoi(argv[1]);
}
int sock = socket(AF_INET, SOCK_STREAM, 0);
bzero(&seraddr, sizeof(seraddr));
seraddr.sin_family = AF_INET;
inet_pton(AF_INET, "127.0.0.1", &seraddr.sin_addr);
seraddr.sin_port = htons(server_port);
set_linger(sock,1,0);
if (-1 == connect(sock, (struct sockaddr *)&seraddr, sizeof(seraddr))) {
perror("connect failure");
exit(EXIT_FAILURE);
}
client_handle(sock);
return 0;
}
void client_handle(int sock) {
int shutdown_count = 0;
char sendbuf[MAXLEN], recvbuf[MAXLEN];
bzero(sendbuf, MAXLEN);
bzero(recvbuf, MAXLEN);
int n = 0;
set_nonblock(sock);
while (1) {
/*if (NULL == fgets(sendbuf, MAXLEN, stdin)) {
break;
}
// 按`#`号退出
if ('#' == sendbuf[0]) {
break;
}*/
struct timeval start, end;
gettimeofday(&start, NULL);
// write(sock, sendbuf, strlen(sendbuf));
n = read(sock, recvbuf, 0);//MAXLEN);
printf("\nsock %d read bytes %d \n",sock,n );
int ret =0;
// sleep(1);
// ret = close(sock);
// n = read(sock, recvbuf, MAXLEN);
printf("read bytes %d errno=%d\n",ret,errno );
if (n < 0) {
printf("n = %d < 0 errno %d\n",n ,errno);
if(errno!=EAGAIN || errno !=EWOULDBLOCK){
perror("read failure.");
exit(EXIT_FAILURE);
}
continue;
}
if (0 == n) {
printf("\nbreak \n\n",n );
// shutdown(sock,SHUT_RDWR);
// shutdown(sock,SHUT_WR);
break;
}
write(STDOUT_FILENO, recvbuf, n);
gettimeofday(&end, NULL);
printf("\ntime diff=%ld microseconds\n", ((end.tv_sec * 1000000 + end.tv_usec)- (start.tv_sec * 1000000 + start.tv_usec)));
break;
}
// n = read(sock, recvbuf, MAXLEN);
printf("set linger 1 0 ,socket = %d \n",sock );
set_linger(sock,1,0);
// usleep(300);
int ret = shutdown(sock,SHUT_WR);
printf("shutdown wr sock %d ret %d errno %d shutdown_count %d:%s\n",sock,ret,errno,shutdown_count++,strerror(errno));
// close(sock);
// ret = shutdown(sock,SHUT_RDWR);
// printf("shut wr sock %d ret %d errno %d shutdown_count %d:%s\n",sock,ret,errno,shutdown_count++,strerror(errno));
// ret = close(sock);
// printf("close wr sock %d ret %d errno %d shutdown_count %d\n",sock,ret,errno,shutdown_count++ );
n = read(sock, recvbuf, MAXLEN);
printf("after shutdown wr socket %d ,then read %d bytes %d:%s\n",sock,n,errno,strerror(errno) );
/*ret = shutdown(sock,SHUT_RDWR);
printf("shut wr sock %d ret %d errno %d shutdown_count %d:%s\n",sock,ret,errno,shutdown_count++,strerror(errno));*/
/* shutdown(sock,SHUT_RDWR);
printf("shut wr sock %d ret %d errno %d shutdown_count %d :%s\n",sock,ret,errno,shutdown_count++,strerror(errno));
shutdown(sock,SHUT_RDWR);
ret = close(sock);
*/
}
int set_linger(int sock, int l_onoff, int l_linger) {
struct linger so_linger;
so_linger.l_onoff = l_onoff;
so_linger.l_linger = l_linger;
int r = setsockopt(sock, SOL_SOCKET, SO_LINGER, &so_linger, sizeof(so_linger));
return r;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <ctype.h>
#include <errno.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/select.h>
#include <pthread.h>
#include <dirent.h>
#include <sqlite3.h>
#define BUFFER_SIZE 1024
#define SERVER_PORT 20001
int none = 1;
struct string
{
char *ip;
char *port;
}str = {NULL, NULL};
void *pthread(void *arg)
{
sleep(5);
if (none == 1)
{
printf("<br>Nothing to sync !\n");
printf("<meta http-equiv=\"refresh\"content=\"2; url=http://192.168.11.252/sync.html\">");
exit(1);
}
return (void *)1;
}
int send_html(int count_br, int count_nbsp, char *str)
{
int i = count_br;
printf("<h1>");
while (i--)
{
printf("<br>");
}
for (i = 0; i < count_nbsp; i++)
{
printf(" ");
}
printf(" %s</h1>",str);
return 0;
}
int rscallback_register(void *p, int argc, char **argv, char **argvv)
{
*(int *)p = 1;
return 0;
}
int rscallback_login(void *p, int argc, char **argv, char **argvv)
{
*(int *)p = 1;
return 0;
}
int main(int argc, const char *argv[])
{
int error = 0;
int ret = 0;
char data[4096];
char value[4096];
char buffer[4096];
char *p = NULL;
int i = 0;
int len;
int client_sock;
socklen_t server_len;
struct sockaddr_in server;
fd_set input_fd;
int server_sock_tcp,client_sock_tcp;
struct sockaddr_in server_tcp,client_tcp;
pthread_t tid;
//void *tret = NULL;
printf("Content-Type: text/html\n\n");
//while ((ret = fread(data, 1, sizeof(data), stdin)) != 0)
//while((ret = fread(buf, 1, sizeof(buf), stdin)) != 0)
while ((ret = fread(data, sizeof(data), 1, stdin)) != 0)
{
//printf("read %d len<br>", ret);
//printf("%s<br>", data);
//return 0;
}
str.ip = data + 8;
if ((p = strstr(data, "&port=")) != NULL)
{
*p = '\0';
}
str.port = p + 6;
if (strlen(str.ip) > 15)
{
send_html(5, 20, "Ip address is overlength !");
printf("<meta http-equiv=\"refresh\"content=\"2; url=http://192.168.11.252/sync.html\">");
return 0;
}
//printf("ip %s<br>",str.ip);
//printf("port %s<br>",str.port);
if (strlen(str.port) > 5)
{
send_html(5, 18, "Port number is overlength !");
printf("<meta http-equiv=\"refresh\"content=\"2; url=http://192.168.11.252/sync.html\">");
return 0;
}
if (str.ip == p && *(str.port) == '\0')
{
send_html(5, 22, "Blank ip address and port !");
printf("<meta http-equiv=\"refresh\"content=\"2; url=http://192.168.11.252/sync.html\">");
return 0;
}
for (i = 0; *(str.ip + i) != '\0'; i++)
{
if (*(str.ip + i) == '.')
{
continue;
}
if (isdigit(*(str.ip + i)) == 0)
{
send_html(5, 24, "Ip address wrong !");
printf("<meta http-equiv=\"refresh\"content=\"2; url=http://192.168.11.252/sync.html\">");
return 0;
}
}
for (i = 0; *(str.port + i) != '\0'; i++)
{
if (isdigit(*(str.port + i)) == 0)
{
send_html(5, 22, "Port number wrong !");
printf("<meta http-equiv=\"refresh\"content=\"2; url=http://192.168.11.252/sync.html\">");
return 0;
}
}
//sprintf(value, "select * from register_info where username='%s';", str.username);
if ((client_sock = socket(AF_INET, SOCK_DGRAM, 0)) < 0)
{
fprintf(stderr, "%s\n", strerror(errno));
exit(EXIT_FAILURE);
}
else
{
printf("UDP create socket ok!\n");
}
bzero(&server, sizeof(server));
server.sin_family = AF_INET;
server.sin_port = htons(atoi(str.port));
//server.sin_port = htons(SERVER_PORT);
server.sin_addr.s_addr = htons(INADDR_ANY);
#if 1
error = pthread_create(&tid, NULL, pthread, NULL);
if (error != 0)
{
fprintf(stderr, "can't create thread:%s",strerror(error));
exit(1);
}
#endif
server_len = sizeof(server);
len = sendto(client_sock, "ready", BUFFER_SIZE, 0, (struct sockaddr *)&server, server_len);
len = recvfrom(client_sock, buffer, BUFFER_SIZE, 0, (struct sockaddr *)&server, &server_len);
if (len < 0)
{
close(client_sock);
fprintf(stderr, "%s\n", strerror(errno));
exit(EXIT_FAILURE);
}
if (strcmp(buffer, "ready to sync") == 0)
{
none = 0;
error = pthread_cancel(tid);
if (error != 0)
{
fprintf(stderr, "can't pthread_join thread:%s",strerror(error));
exit(1);
}
printf("<br>UDP Connect server succesfully !\n");
}
//TCP
#if 1
if ((client_sock_tcp = socket(AF_INET, SOCK_STREAM, 0)) < 0)
{
fprintf(stderr, "%s\n", strerror(errno));
exit(EXIT_FAILURE);
}
else
{
printf("<br>TCP create socket ok!\n");
}
bzero(&server_tcp, sizeof(server_tcp));
server_tcp.sin_family = AF_INET;
server_tcp.sin_port = htons(SERVER_PORT);
server_tcp.sin_addr.s_addr = inet_addr(str.ip);
server_len = sizeof(server_tcp);
if(connect(client_sock_tcp, (struct sockaddr *)&server_tcp, server_len) < 0)
{
fprintf(stderr, "%s\n", strerror(errno));
exit(EXIT_FAILURE);
}
else
{
printf("<br>TCP connect server ok!\n");
}
//Opendir
#if 1
FILE *fd;
//int fd;
DIR *dir;
char *filename[256] = {"PictureFile", "MediaFile", "TextFile", "OtherFile"};
char path[1024];
struct dirent *ptr;
i = 0;
//for (i = 0; i < 4; i++)
{
sprintf(value, "../htdocs/upload-folder/%s", *(filename + i));
if ((dir = opendir(value)) != NULL)
{
while ((ptr= readdir(dir)) != NULL)
{
if (ptr->d_type == DT_REG)
{
//sprintf(path, "%s/%s",value, ptr->d_name);
//fd = fopen(path, "r");
//fd = fopen("/home/navyzhou/1.cpp", "r");
sprintf(path, "/var/httpd/htdocs/upload-folder/%s/%s",*(filename + i), ptr->d_name);
/*
fd = open(path, O_RDONLY);
if (fd < 0)
{
perror("open");
close(client_sock_tcp);
close(client_sock);
exit(1);
}
*/
fd = fopen(path, "r");
if(fd == NULL)
{
printf("<br>can not open file");
return 0;
}
//memset(value, 0, sizeof(value));
//sprintf(value, "%d%c%s", i, '1', ptr->d_name);//1 means filename not file data
len = send(client_sock_tcp, value, BUFFER_SIZE, 0);
//printf("<br>len = %d\n",len);
//while ((len = read(fd, buffer, BUFFER_SIZE-2)) > 0)
while (1)
{
len = fread(buffer, 1, BUFFER_SIZE-2, fd);
if (feof(fd))
{
break;
}
printf("<br>len = %d\n",len);
//memset(value, 0, sizeof(value));
sprintf(value, "%d%c%s", i, '0', buffer);//0 means file data
send(client_sock_tcp, value, BUFFER_SIZE, 0);
//printf("<br>len = %d\n",sizeof(value));
//printf("%s\n",ptr->d_name);
}
//fclose(fd);
}
}
}
}
#endif
/*
if((len = recv(client_sock_tcp, buffer, BUFFER_SIZE, 0)) > 0)
{
//write(STDOUT_FILENO, buffer, len); //printf to terminal
printf("<br>%s\n",buffer);
}
*/
close(client_sock_tcp);
#endif
#if 0
FD_ZERO(&input_fd);
FD_SET(server_sock, &input_fd);
FD_SET(fd, &input_fd);
while (1)
{
if((select(FD_SETSIZE, &input_fd, NULL, NULL, NULL)) < 0)
{
fprintf(stderr, "%s\n", strerror(errno));
continue;
}
if(FD_ISSET(server_sock, &input_fd))
{
}
}
#endif
close(client_sock);
//exit(EXIT_SUCCESS);
printf("<br>I have exited !\n");
//printf("<meta http-equiv=\"refresh\"content=\"2; url=http://192.168.11.252/sync.html\">");
return 0;
}
|
C
|
#include<stdio.h>
void main()
{
int a,b,c;
printf("˷ھ\n");
for(a=1;a<10;a++)
{
for(b=1;b<=a;b++)
printf("%2d*%d=%d",a,b,a*b);
printf("\n");
}
}
|
C
|
#include<stdio.h>
#include<string.h>
#include "mpi.h"
main (int argc, char* argv[]){
int my_rank;
int p;
int source;
int dest;
int tag = 0;
char message[100];
MPI_Status status;
long long int i;
long long int sum;
MPI_Init(&argc, &argv);
MPI_Comm_rank(MPI_COMM_WORLD, &my_rank);
MPI_Comm_size(MPI_COMM_WORLD, &p);
for(i=0;i<10000000000;i++){
sum = sum + i;
}
char processor_name[MPI_MAX_PROCESSOR_NAME];
int name_len;
MPI_Get_processor_name(processor_name, &name_len);
printf("Sum in processor %s is %lld\n", processor_name, sum);
if(my_rank!=0){
sprintf(message, "Greetings from process %d!", my_rank);
dest = 0;
MPI_Send(message, strlen(message) + 1, MPI_CHAR, dest, tag, MPI_COMM_WORLD);
} else {
for(source = 1; source < p; source++) {
MPI_Recv(message, 100, MPI_CHAR, source, tag, MPI_COMM_WORLD, &status);
printf("%s\n", message);
}
}
if(my_rank==0) printf("Number of processes are %d\n", p);
MPI_Finalize();
}
|
C
|
/* bopt.h
* - public domain getopt library
* - no warranty implied; use at your own risk
*
* LICENSE
*
* This software is in the public domain. Where that dedication is not
* recognized, you are granted a perpetual, irrevocable license to copy,
* distribute, and modify this file as you see fit.
*/
#ifndef bopt_h
#define bopt_h
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#ifdef __cplusplus
extern "C" {
#endif
#define IS_OPTION_ARG(arg) (arg[0] == '-' && arg[1] == '-')
#define err_nonoption_argument(s) \
fprintf(stderr, "ERROR: non-option argument `%s'\n", s)
#define err_unknown_option(s) \
fprintf(stderr, "ERROR: unknown option `%s'\n", s)
#define err_missing_argument(s) \
fprintf(stderr, "ERROR: option `--%s' is missing argument\n", s)
#define err_no_argument(s) \
fprintf(stderr, "ERROR: option `--%s' is no argument\n", s)
#define err_incorrect_has_arg(s) \
fprintf(stderr, "ERROR: the `has_arg' field of `%s' should be one of:\n" \
" brequired_argument an argument to the option is required\n" \
" boptional_argument an argument to the option may be presented\n" \
" bno_argument no argument to the option is expected\n", s)
#define brequired_argument 0 /* an argument to the option is required */
#define boptional_argument 1 /* an argument to the option may be presented */
#define bno_argument 2 /* no argument to the option is expected */
#define boptctl_exit 1
static const int boptopt = '?';
static int boptind = 1;
/* Control the behavior of bgetopt().
* The default behavior is print the error message to the STDERR and call
* exit() if bgetopt() meet an error. If the caller change it to the other
* else value, bgetopt() will parse all the elements of the argument list
* and print the error message to the STDERR. */
static int boptctl = boptctl_exit;
/* The caller can use this pointer to get the required argument or
* optional argument. If bgetopt() meet an error, the caller also can use
* this pointer to get the non-option argument or unrecognized option.
*/
static char *boptarg = NULL;
struct boption {
char *name;
int has_arg;
int val;
char **value;
};
static int bgetopt(int argc, char * const *argv, const struct boption *opts)
{
char *arg;
char *next_arg;
if (boptind >= argc) {
struct boption *p = (struct boption *)opts;
while (p->name) {
if (boptctl == boptctl_exit) {
if (p->has_arg == brequired_argument && *(p->value) == NULL) {
err_missing_argument(p->name);
exit(-1);
} else if (p->has_arg == bno_argument && p->value != NULL) {
err_no_argument(p->name);
exit(-1);
} else {
}
}
p++;
}
return -1; /* Reach the end of ARGV */
}
arg = argv[boptind];
next_arg = argv[boptind + 1];
if (!(IS_OPTION_ARG(arg))) {
if (boptctl == boptctl_exit) {
err_nonoption_argument(arg);
exit(-1);
} else {
boptarg = argv[boptind];
boptind++;
return boptopt;
}
}
arg += 2; /* Skip the `--' */
while (opts->name) {
if (strlen(opts->name) == strlen(arg) &&
strcmp(opts->name, arg) == 0)
break;
opts++;
}
if (!opts->name) {
if (boptctl == boptctl_exit) {
err_unknown_option(argv[boptind]);
exit(-1);
} else {
boptarg = argv[boptind];
boptind++;
return boptopt;
}
}
switch (opts->has_arg) {
case brequired_argument:
if (!next_arg || IS_OPTION_ARG(next_arg)) {
if (boptctl == boptctl_exit) {
err_missing_argument(opts->name);
exit(-1);
} else {
boptarg = argv[boptind];
boptind++;
return ':';
}
}
boptarg = next_arg;
boptind += 2;
return opts->val;
case boptional_argument:
if (!next_arg || IS_OPTION_ARG(next_arg)) {
boptarg = NULL;
boptind++;
return opts->val;
}
boptarg = next_arg;
boptind += 2;
return opts->val;
case bno_argument:
if (!next_arg || IS_OPTION_ARG(next_arg)) {
boptarg = NULL;
boptind++;
return opts->val;
}
if (boptctl == boptctl_exit) {
err_no_argument(opts->name);
exit(-1);
} else {
boptarg = argv[boptind];
boptind++;
return opts->val;
}
default:
if (boptctl == boptctl_exit) {
err_incorrect_has_arg(opts->name);
exit(-1);
} else {
boptarg = argv[boptind];
boptind++;
return boptopt;
}
}
}
#ifdef __cplusplus
}
#endif
#endif /* bopt_h */
|
C
|
/**
* @defgroup TM_USART_Typedefs
* @brief USART Typedefs
* @{
*/
/**
* @brief USART PinsPack enumeration to select pins combination for USART
*/
typedef enum {
TM_USART_PinsPack_1 = 0x00, /*!< Select PinsPack1 from Pinout table for specific USART */
TM_USART_PinsPack_2, /*!< Select PinsPack2 from Pinout table for specific USART */
TM_USART_PinsPack_3, /*!< Select PinsPack3 from Pinout table for specific USART */
TM_USART_PinsPack_Custom /*!< Select custom pins for specific USART, callback will be called, look @ref TM_USART_InitCustomPinsCallback */
} TM_USART_PinsPack_t;
/**
* @brief USART Hardware flow control selection
* @note Corresponsing pins must be initialized in case you don't use "None" options
*/
typedef enum {
TM_USART_HardwareFlowControl_None = UART_HWCONTROL_NONE, /*!< No flow control */
TM_USART_HardwareFlowControl_RTS = UART_HWCONTROL_RTS, /*!< RTS flow control */
TM_USART_HardwareFlowControl_CTS = UART_HWCONTROL_CTS, /*!< CTS flow control */
TM_USART_HardwareFlowControl_RTS_CTS = UART_HWCONTROL_RTS_CTS /*!< RTS and CTS flow control */
} TM_USART_HardwareFlowControl_t;
/**
* @}
*/
/**
* @defgroup TM_USART_Functions
* @brief USART Functions
* @{
*/
/**
* @brief Initializes USARTx peripheral and corresponding pins
* @param *USARTx: Pointer to USARTx peripheral you will use
* @param pinspack: This parameter can be a value of @ref TM_USART_PinsPack_t enumeration
* @param baudrate: Baudrate number for USART communication
* @retval None
*/
void TM_USART_Init(USART_TypeDef* USARTx, TM_USART_PinsPack_t pinspack, uint32_t baudrate);
/**
* @brief Initializes USARTx peripheral and corresponding pins with custom hardware flow control mode
* @note Hardware flow control pins are not initialized. Easy solution is to use @arg TM_USART_PinsPack_Custom pinspack option
* when you call @ref TM_USART_Init() function and initialize all USART pins at a time inside @ref TM_USART_InitCustomPinsCallback()
* callback function, which will be called from my library
* @param *USARTx: Pointer to USARTx peripheral you will use
* @param pinspack: This parameter can be a value of @ref TM_USART_PinsPack_t enumeration
* @param baudrate: Baudrate number for USART communication
* @param FlowControl: Flow control mode you will use. This parameter can be a value of @ref TM_USART_HardwareFlowControl_t enumeration
* @retval None
*/
void TM_USART_InitWithFlowControl(USART_TypeDef* USARTx, TM_USART_PinsPack_t pinspack, uint32_t baudrate, TM_USART_HardwareFlowControl_t FlowControl);
/**
* @brief Puts character to USART port
* @param *USARTx: Pointer to USARTx peripheral you will use
* @param c: character to be send over USART
* @retval None
*/
static __INLINE void TM_USART_Putc(USART_TypeDef* USARTx, volatile char c) {
/* Check USART */
if ((USARTx->CR1 & USART_CR1_UE)) {
/* Wait to be ready, buffer empty */
USART_WAIT(USARTx);
/* Send data */
USART_WRITE_DATA(USARTx, (uint16_t)(c & 0x01FF));
/* Wait to be ready, buffer empty */
USART_WAIT(USARTx);
}
}
/**
* @brief Puts string to USART port
* @param *USARTx: Pointer to USARTx peripheral you will use
* @param *str: Pointer to string to send over USART
* @retval None
*/
void TM_USART_Puts(USART_TypeDef* USARTx, char* str);
/**
* @brief Sends data array to USART port
* @param *USARTx: Pointer to USARTx peripheral you will use
* @param *DataArray: Pointer to data array to be sent over USART
* @param count: Number of elements in data array to be send over USART
* @retval None
*/
void TM_USART_Send(USART_TypeDef* USARTx, uint8_t* DataArray, uint16_t count);
/**
* @brief Gets character from internal USART buffer
* @param *USARTx: Pointer to USARTx peripheral you will use
* @retval Character from buffer, or 0 if nothing in buffer
*/
uint8_t TM_USART_Getc(USART_TypeDef* USARTx);
/**
* @brief Get string from USART
*
* This function can create a string from USART received data.
*
* It generates string until "\n" is not recognized or buffer length is full.
*
* @note As of version 1.5, this function automatically adds 0x0A (Line feed) at the end of string.
* @param *USARTx: Pointer to USARTx peripheral you will use
* @param *buffer: Pointer to buffer where data will be stored from buffer
* @param bufsize: maximal number of characters we can add to your buffer, including leading zero
* @retval Number of characters in buffer
*/
uint16_t TM_USART_Gets(USART_TypeDef* USARTx, char* buffer, uint16_t bufsize);
/**
* @brief Check if character c is available in internal buffer
* @param *USARTx: Pointer to USARTx peripheral you will use
* @param c: character to check if it is in USARTx's buffer
* @retval Character status:
* - 0: Character was not found
* - > 0: Character has been found in buffer
*/
uint8_t TM_USART_FindCharacter(USART_TypeDef* USARTx, uint8_t c);
/**
* @brief Checks if internal USARTx buffer is empty
* @param *USARTx: Pointer to USARTx peripheral you will use
* @retval Buffer empty status:
* - 0: Buffer is not empty
* - > 0: Buffer is empty
*/
uint8_t TM_USART_BufferEmpty(USART_TypeDef* USARTx);
/**
* @brief Checks if internal USARTx buffer is full
* @param *USARTx: Pointer to USARTx peripheral you will use
* @retval Buffer full status:
* - 0: Buffer is not full
* - > 0: Buffer is full
*/
uint8_t TM_USART_BufferFull(USART_TypeDef* USARTx);
/**
* @brief Clears internal USART buffer
* @param *USARTx: Pointer to USARTx peripheral you will use
* @retval None
*/
void TM_USART_ClearBuffer(USART_TypeDef* USARTx);
/**
* @brief Sets custom character for @ref TM_USART_Gets() function to detect when string ends
* @param *USARTx: Pointer to USARTx peripheral you will use
* @param Character: Character value to be used as string end
* @note Character will also be added at the end for your buffer when calling @ref TM_USART_Gets() function
* @retval None
*/
void TM_USART_SetCustomStringEndCharacter(USART_TypeDef* USARTx, uint8_t Character);
/**
* @brief Callback for custom pins initialization for USARTx.
*
* When you call @ef TM_USART_Init() function, and if you pass @arg TM_USART_PinsPack_Custom to function,
* then this function will be called where you can initialize custom pins for USART peripheral.
* @note With __weak parameter to prevent link errors if not defined by user
* @param *USARTx: Pointer to USARTx peripheral you will use for initialization
* @param AlternateFunction: Alternate function number which should be used for GPIO pins
* @retval None
*/
void TM_USART_InitCustomPinsCallback(USART_TypeDef* USARTx, uint16_t AlternateFunction);
/**
* @brief Callback function for receive interrupt on USART1 in case you have enabled custom USART handler mode
* @note With __weak parameter to prevent link errors if not defined by user
* @param c: character received via USART
* @retval None
*/
__weak void TM_USART1_ReceiveHandler(uint8_t c);
/**
* @brief Callback function for receive interrupt on USART2 in case you have enabled custom USART handler mode
* @note With __weak parameter to prevent link errors if not defined by user
* @param c: character received via USART
* @retval None
*/
__weak void TM_USART2_ReceiveHandler(uint8_t c);
/**
* @brief Callback function for receive interrupt on USART3 in case you have enabled custom USART handler mode
* @note With __weak parameter to prevent link errors if not defined by user
* @param c: character received via USART
* @retval None
*/
__weak void TM_USART3_ReceiveHandler(uint8_t c);
/**
* @brief Callback function for receive interrupt on UART4 in case you have enabled custom USART handler mode
* @note With __weak parameter to prevent link errors if not defined by user
* @param c: character received via USART
* @retval None
*/
__weak void TM_UART4_ReceiveHandler(uint8_t c);
/**
* @brief Callback function for receive interrupt on UART5 in case you have enabled custom USART handler mode
* @note With __weak parameter to prevent link errors if not defined by user
* @param c: character received via USART
* @retval None
*/
__weak void TM_UART5_ReceiveHandler(uint8_t c);
/**
* @brief Callback function for receive interrupt on USART6 in case you have enabled custom USART handler mode
* @note With __weak parameter to prevent link errors if not defined by user
* @param c: character received via USART
* @retval None
*/
__weak void TM_USART6_ReceiveHandler(uint8_t c);
/**
* @brief Callback function for receive interrupt on UART7 in case you have enabled custom USART handler mode
* @note With __weak parameter to prevent link errors if not defined by user
* @param c: character received via USART
* @retval None
*/
__weak void TM_UART7_ReceiveHandler(uint8_t c);
/**
* @brief Callback function for receive interrupt on UART8 in case you have enabled custom USART handler mode
* @note With __weak parameter to prevent link errors if not defined by user
* @param c: character received via USART
* @retval None
*/
__weak void TM_UART8_ReceiveHandler(uint8_t c);
/**
* @}
*/
|
C
|
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
typedef struct node
{
int data;
struct node *left,*right;
}node;
node* parent(node* tree,node* temp)
{if(tree->data==temp->data)
return NULL;
else
{
while(tree->data!=temp->data)
{ if(tree->data<temp->data)
if(tree->right->data==temp->data)
return tree;
else
tree=tree->right;
else if(tree->data>temp->data)
if(tree->left->data==temp->data)
return tree;
else
tree=tree->left;
}
}
}
node* insr(node* tree,int k)
{if(tree==NULL)
{node *nptr;
nptr=(node*)malloc(sizeof(node));
nptr->left=NULL;
nptr->right==NULL;
nptr->data=k;
tree=nptr;
}
int lvl;
else if(tree->data>k)
tree->left=insr(tree->left,k);
else if(tree->data<k)
tree->right=insr(tree->right,k);
return tree;
}
void srch(node *tree,int k)
{
if(tree==NULL)
printf("NOT FOUND\n");
else if(tree->data>k)
srch(tree->left,k);
else if(tree->data<k)
srch(tree->right,k);
else if(tree->data==k)
printf("FOUND\n");
}
void maxm(node*tree)
{if(tree==NULL)
printf("NIL\n");
else
{while(tree->right!=NULL)
tree=tree->right;
printf("%d\n",tree->data);
}
}
void minm(node*tree)
{if(tree==NULL)
printf("NIL\n");
else
{while(tree->left!=NULL)
tree=tree->left;
printf("%d\n",tree->data);
}
}
void pred(node* root,node* tree,int k)
{node *temp=tree;
if(tree!=NULL)
{while(tree->data!=k)
{if(tree->data>k)
tree=tree->left;
else if(tree->data<k)
tree=tree->right;
if(tree==NULL)
break;
}
if(tree==NULL)
{ printf("NULL\n");
}
else
{if(tree->left!=NULL)
maxm(tree->left);
else if(tree->left==NULL&&parent(root,tree)==NULL)
printf("-1\n");
else if(tree->left==NULL&&tree->data<temp->data)
printf("-1\n");
else
{
node *y=parent(root,tree);
node *x=tree;
while((parent(root,y)!=NULL)&&(y->left)->data==x->data)
{x=y;
y=parent(root,y);
}
printf("%d\n",y->data);
}
}
}
else if(tree==NULL)
printf("NULL\n");
}
void succ(node *root,node* tree,int k)
{node *temp=tree;
if(tree!=NULL)
{while(tree->data!=k)
{if(tree->data>k)
tree=tree->left;
else if(tree->data<k)
tree=tree->right;
if(tree==NULL)
break;
}
if(tree==NULL)
printf("NULL\n");
else
{if(tree->right!=NULL)
minm(tree->right);
else if(tree->right==NULL&&parent(root,tree)==NULL)
printf("-1\n");
else if(tree->right==NULL&&parent(root,tree)->data<tree->data)
printf("-1\n");
else
{
node *y=parent(root,tree);
node *x=tree;
while((parent(root,y)!=NULL)&&y->data<x->data)
{x=y;
y=parent(root,y);
}
printf("%d\n",y->data);
}
}
}
else if(tree==NULL)
printf("NULL\n");
}
node* delt(node* root,node* tree,int k)
{ node *temp=tree;
if(tree!=NULL)
{while(tree->data!=k)
{if(tree->data>k)
tree=tree->left;
else if(tree->data<k)
tree=tree->right;
if(tree==NULL)
break;
}
if(tree==NULL)
printf("NULL\n");
else
{node *x,*y;
if(tree->left==NULL||tree->right==NULL)
y=tree;
else
{if(tree->right!=NULL)
{ while(tree->right!=NULL)
tree=tree->right;
y=tree;
}
else
{
node *y1=parent(root,tree);
node *x1=tree;
while((parent(root,y1)!=NULL)&&y1->data<x1->data)
{x1=y1;
y1=parent(root,y1);
}
y=y1;
}
}
if(y->left!=NULL)
x=y->left;
else
x=y->right;
if(parent(root,y)==NULL)
temp=x;
else if(y==parent(root,y)->left)
parent(root,y)->left=x;
else
parent(root,y)->right=x;
if(y!=tree)
tree->data=y->data;
}
}
else if(tree==NULL)
printf("NULL\n");
return temp;
}
void inor(node* tree)
{
if(tree!=NULL)
{
inor(tree->left);
printf("%d ",tree->data);
inor(tree->right);
}
}
void prer(node* tree)
{
if(tree!=NULL)
{
printf("%d ",tree->data);
prer(tree->left);
prer(tree->right);
}
}
void post(node* tree)
{
if(tree!=NULL)
{
post(tree->left);
post(tree->right);
printf("%d ",tree->data);
}
}
int main()
{
node *tree;
tree=NULL;
char a[50];
scanf("%s",a);
while(strcmp(a,"stop")!=0)
{
int k;
if(strcmp(a,"insr")==0)
{
scanf("%d",&k);
tree=insr(tree,k);
}
else if(strcmp(a,"srch")==0)
{
scanf("%d",&k);
srch(tree,k);
}
else if(strcmp(a,"minm")==0)
{
minm(tree);
}
else if(strcmp(a,"maxm")==0)
{
maxm(tree);
}
else if(strcmp(a,"pred")==0)
{
scanf("%d",&k);
pred(tree,tree,k);
}
else if(strcmp(a,"succ")==0)
{
scanf("%d",&k);
succ(tree,tree,k);
}
else if(strcmp(a,"delt")==0)
{
scanf("%d",&k);
tree=delt(tree,tree,k);
}
else if(strcmp(a,"inor")==0)
{
inor(tree);
printf("\n");
}
else if(strcmp(a,"prer")==0)
{
prer(tree);
printf("\n");
}
else if(strcmp(a,"post")==0)
{
post(tree);
printf("\n");
}
scanf("%s",a);
}
}
|
C
|
#include <stdlib.h>
#include <stdio.h>
#include <errno.h>
#include <unistd.h>
#include <fcntl.h>
#include <string.h>
#include <termios.h>
#include <time.h>
#include <util.h>
//-----------------------------------------------------------------------------
int main(int argc, char *argv [])
{
char * port1 = NULL;
char * port2 = NULL;
time_t rawtime;
struct tm * timeinfo;
time ( &rawtime );
timeinfo = localtime ( &rawtime );
printf ( "Current local time and date: %s", asctime (timeinfo) );
pid_t pid_father = getppid();
printf("Parent PID : %ld \n" , (long) pid_father) ;
// parse comand line
if (argc != 5)
{
fprintf(stderr, "Invalid usage: reader -p port_name1 -q port_name2\n");
exit(EXIT_FAILURE);
}
char * options = "p:q:";
int option;
while((option = getopt(argc, argv, options)) != -1)
{
switch(option)
{
case 'p':
port1 = optarg;
break;
case 'q':
port2 = optarg;
break;
case '?':
fprintf(stderr, "Invalid option %c\n", optopt);
exit(EXIT_FAILURE);
}
}
// open serial ports
int fd1 = open(port1, O_RDWR | O_NOCTTY);
int fd2 = open(port2, O_RDWR | O_NOCTTY);
if (fd1 == -1 || fd2 == -1)
{
perror("open");
exit(EXIT_FAILURE);
}
tcflush(fd1, TCIOFLUSH);
tcflush(fd2, TCIOFLUSH);
// read port
char buff1[50];
fd_set fdset1;
while(1)
{
bzero(buff1, sizeof(buff1));
FD_ZERO(&fdset1);
FD_SET(fd1, &fdset1);
select(fd1+1, &fdset1, NULL, NULL, NULL);
//read port1
if (FD_ISSET(fd1, &fdset1))
{
int bytes = read (fd1, buff1, sizeof(buff1));
if (bytes > 0)
{
printf("Port 1: %s\n", buff1);
fflush(stdout);
}
}
bzero(buff1, sizeof(buff1));
FD_ZERO(&fdset1);
FD_SET(fd2, &fdset1);
select(fd2+1, &fdset1, NULL, NULL, NULL);
//read port2
if (FD_ISSET(fd2, &fdset1))
{
int bytes = read (fd2, buff1, sizeof(buff1));
if (bytes > 0)
{
printf("Port 2: %s\n", buff1);
fflush(stdout);
}
}
}
// close serial ports
close(fd1);
close(fd2);
exit(EXIT_SUCCESS);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
// #define PI 3.1415
#define MAX 20
int main() {
char buffer[MAX]; // set radius to temp char
double volume = 0;
printf("Specify the radius of the sphere: ");
fgets(buffer, MAX, stdin); // ask from standard input and set temp to whatever stdin is
// convert temp char to int radius
int radius = atoi(buffer);
// calculate the volume
volume = (4.0/3.0) * M_PI * pow(radius, 3);
printf("%.3f\n", volume);
return 0;
}
|
C
|
#include "binary_trees.h"
/**
* binary_tree_insert_right - insert node at right node
* @parent: parent node
* @value: value of new node
* Return: new node
**/
binary_tree_t *binary_tree_insert_right(binary_tree_t *parent, int value)
{
binary_tree_t *new;
if (parent == NULL)
return (NULL);
new = malloc(sizeof(binary_tree_t));
if (new == NULL)
return (NULL);
new->parent = parent;
new->right = NULL;
new->left = NULL;
new->n = value;
if (parent->right)
{
parent->right->parent = new;
new->right = parent->right;
}
parent->right = new;
return (new);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
typedef struct NODE_S NODE;
struct NODE_S
{
NODE *next;
int n;
};
NODE *last(NODE *node)
{
return (!node->next) ? node : last(node->next);
}
void push(NODE *node, int n)
{
NODE *p = (NODE *)calloc(1llu, sizeof(NODE));
p->n = n;
last(node)->next = p;
}
NODE *docTuTep(char *ten)
{
NODE *node = (NODE *)calloc(1llu, sizeof(NODE));
FILE *f = fopen(ten, "r");
fscanf(f, "%d", &node->n);
int tmp;
while (!feof(f))
{
fscanf(f, "%d", &tmp);
push(node, tmp);
}
fclose(f);
return node;
}
NODE *surft(NODE **node)
{
*node = node[0]->next;
return *node;
}
void freeNODE(NODE *node)
{
if (node)
{
freeNODE(node->next);
free(node);
}
}
int tongDuongChan(NODE *node)
{
int t = 0;
do
if (node->n > 0 && node->n % 2 == 0)
t += node->n;
while (surft(&node));
return t;
}
int main()
{
NODE *node = docTuTep("input.txt");
FILE *f = fopen("output.txt", "w");
fprintf(f, "%d", tongDuongChan(node));
fclose(f);
freeNODE(node);
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
typedef struct node node;
typedef struct stack stack;
struct node
{
int item;
node *next;
};
struct stack
{
node *head;
};
int is_empty_stack (stack *stack)
{
return (stack->head == NULL);
}
stack *create_stack ()
{
stack *new_stack = (stack *) malloc (sizeof(stack));
new_stack->head = NULL;
return new_stack;
}
void push (stack *stack, int item)
{
node *new_node = (node *) malloc(sizeof(node));
new_node->item = item;
new_node->next = stack->head;
stack->head = new_node;
}
void pop (stack *stack)
{
if (is_empty_stack(stack))
return;
node *aux = stack->head;
stack->head = stack->head->next;
free(aux);
}
void print_stack (stack *stack)
{
node *current = stack->head;
while (current != NULL)
{
if (current->next != NULL)
{
printf("%d ", current->item);
}
else
{
printf("%d\n", current->item);
}
current = current->next;
}
}
void loop(stack *stack)
{
char comant[20];
scanf("%s", comant);
if (comant[0] == 'E')
{
int item;
scanf(" %d", &item);
push(stack, item);
loop(stack);
}
else if (comant[0] == 'D')
{
pop(stack);
loop(stack);
}
else if (comant[0] == 'I')
{
print_stack(stack);
loop(stack);
}
}
void free_stack (stack *stack)
{
while (stack->head != NULL)
{
node *current = stack->head;
stack->head = stack->head->next;
free(current);
}
free(stack);
}
int main ()
{
stack *stack = create_stack();
loop(stack);
free_stack(stack);
return 0;
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* print.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: ltanenba <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2018/06/08 01:52:34 by ltanenba #+# #+# */
/* Updated: 2018/06/08 21:09:32 by ltanenba ### ########.fr */
/* */
/* ************************************************************************** */
#include "ft_prompt.h"
int append_substr(char **dst, char *src, size_t len)
{
char *sub;
char *tmp;
tmp = *dst;
MALL_CHECK(sub = ft_strsub(src, 0, len));
MALL_CHECK(*dst = ft_strjoin(*dst, sub));
free(tmp);
free(sub);
return (0);
}
int append_cursor_pos(char **dst, int n)
{
char esc[64];
int numlen;
char *num;
MALL_CHECK(num = ft_itoa(n));
numlen = ft_strlen(num);
ft_strncpy(esc, "\r\033[", 64);
ft_strncpy(esc + 3, num, numlen + 1);
ft_strncpy(esc + 3 + numlen, "C", 2);
free(num);
ERR_CHECK(append_substr(dst, esc, numlen + 4));
return (0);
}
int print_line(t_prompt *p)
{
char esc[64];
char *line;
t_prompt tmp;
ft_bzero(esc, 64);
tmp.buf = p->buf;
tmp.len = p->len;
tmp.pos = p->pos;
line = ft_strnew(0);
while (p->plen + tmp.pos >= p->cols)
{
tmp.buf++;
tmp.len--;
tmp.pos--;
}
while ((p->plen + tmp.len) > p->cols)
tmp.len--;
ERR_CHECK(append_substr(&line, "\r", 1));
ERR_CHECK(append_substr(&line, p->pstr, p->plen));
ERR_CHECK(append_substr(&line, tmp.buf, tmp.len));
ERR_CHECK(append_substr(&line, DEL_END_SEQ, 4));
ERR_CHECK(append_cursor_pos(&line, tmp.pos + p->plen));
write(p->ofd, line, ft_strlen(line));
free(line);
return (0);
}
|
C
|
int main()
{
int m,n,i,j; //??m????n????????i?j
float s; //????b??s
float a[10000]; //????????a[n]????int????????????a[i+1]/a[i]????float??????a[n]?float?
float b[10000]; //???????????b[n]
float c[10000];
a[0]=1,a[1]=1; //?????1
cin>>m;
for(j=1;j<=m;j++) //??m??????
{ s=0;
cin>>n; //?????????n
for(i=2;i<=(n+1);i++) //????a?b???
a[i]=a[i-1]+a[i-2]; //????
for(i=1;i<=n;i++)
b[i]=a[i+1]/a[i];
for(i=1;i<=n;i++) //??b[n]??
s=s+b[i];
c[j]=s;
}
for(j=1;j<=m;j++)
printf("%.3f\n",c[j]);
return 0;
}
|
C
|
#ifndef _STACK_H_
#define _STACK_H_
#include <stdbool.h>
#include "type.h"
typedef struct _stack_entity {
int capacity;
int size;
int top;
element_t *arr;
} stack_entity_t;
typedef stack_entity_t *_stack_t;
_stack_t create_stack(int capacity);
void dispose_stack(_stack_t stack);
void make_stack_empty(_stack_t stack);
bool is_stack_empty(_stack_t stack);
bool is_stack_full(_stack_t stack);
bool push(_stack_t stack, element_t e);
element_t pop(_stack_t stack);
element_t top(_stack_t stack);
#endif
|
C
|
#include <stdio.h>
#include <locale.h>
int main(){
int qFlex, qPrem, qGold; //"q" pra indicar quantidade
float total, desconto = 0;
setlocale(LC_ALL,"Portuguese");
printf("TABELA DE PREOS UNITRIOS E DESCONTOS\n\n");
printf(" -------- --------- ----------\n");
printf("| TIPO | PREO | DESCONTO |\n");
printf(" -------- --------- ----------\n");
printf("|FLEX | R$20,00 | 10%% |\n");
printf("|PREMIUM | R$50,75 | 20%% |\n");
printf("|GOLD | R$90,00 | 30%% |\n");
printf(" -------- --------- ----------\n\n");
printf("Quantas raes do tipo Flex voc deseja? ");
scanf("%d", &qFlex);
printf("Quantas raes do tipo Premium voc deseja? ");
scanf("%d", &qPrem);
printf("Quantas raes do tipo Gold voc deseja? ");
scanf("%d",&qGold);
if (qFlex >= 1){
desconto += 0.1;
}
if (qPrem >= 1){
desconto += 0.2;
}
if (qGold >= 1){
desconto += 0.3;
}
total = (qFlex * 20.00 + qPrem * 50.75 + qGold * 90.00)*desconto;
printf("\n\nRaes Flex compradas: %d x R$20,00 = R$%.2f \n", qFlex, qFlex * 20.00);
printf("Raes Premium compradas: %d x R$50,75 = R$%.2f \n", qPrem, qPrem * 50.75);
printf("Raes Gold compradas: %d x R$90,00 = R$%.2f\n", qGold, qGold * 90.00);
printf("Desconto total: %.0f%%\n",desconto*100);
printf("-----------------------------------------------\n");
printf("Total a pagar: R$%.2f", total);
system("pause");
}
|
C
|
/* Rafal Krokowski, Image Processing 1, 29.11.16r.
Read() and show() functions has been implemented from
function 'odczyt.c' which is dr.inz.Muszynski intellectual property.
TESTS:
App was tested for files in the PGM format. After chosing image
processing function from main menu and running 'Save and show changes',
display program automatically fires and displays 2 IMAGES - original
ond processed one - for simplicity of compraing changes. Changes are
added incrementally until we end the program.
Warning: Histogram equalization seems to has no effect if we use
low resolution image. I strongly recommend using higher
quality images.
*/
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <math.h> /* Library added for ABS function usage */
#include "module1.h"
// MAIN FUNCTION
int main() {
Image image;
int read = 0;
FILE *file;
char name[100];
int a;
printf("Welcome to image processing app!\n");
/* Read selected file to the memory */
printf("Your file name:\n");
scanf("%s", name);
file = fopen(name,"r");
if (file != NULL)
read = read(file, &image);
if (read != 0)
show(name);
/*USER'S MENU */
printf("What should I do with this loaded image?\n");
printf("1 - Negative\n");
printf("2 - Thresholding\n");
printf("3 - White half-thresholding\n");
printf("4 - Contouring\n");
printf("5 - Histogram equalization\n");
printf("6 - Save and show changes\n");
printf("7 - Exit the app\n");
while(a != 7 ) { /* When a is 7, exit the app */
scanf("%d", &a);
switch (a) {
/* We run the function on image and inform user about it */
case 1:
negative(&image);
printf("Negative done correctly!\n");
break;
case 2:
threshold(&image);
printf("Thresholding done correctly!\n");
break;
case 3:
halfThreshold(&image);
printf("White half-thresholding done correctly!\n");
break;
case 4:
contour(&image);
printf("Contouring done correctly!\n");
break;
case 5:
histogram(&image);
printf("Histogram equalization done correctly!\n");
break;
case 6:
save(&image);
char name[100]={"image.pgm"};
show(name);
printf("File changes saved successfully!\n");
break;
case 7:
printf("App exited successfully!\n");
break;
default:
printf("This value does not exist in the manu!\n");
break;
}
}
fclose(file);
return 0;
}
|
C
|
/* Inclusion de cabeceras o bibliotecas. */
#include <stdio.h> // printf, scanf, setbuf
#include <string.h> // Manejo de strings
/* Definicion de macros y constantes. */
#define MAX_CHAR 15
#define MAXI 2 // 15
/* Main function. */
int main() {
int i;
char nombre[MAXI][MAX_CHAR];
int edad[MAXI];
float estatura[MAXI];
for (i = 0; i < MAXI; i++) {
printf("Ingrese nombre: ");
setbuf(stdin, NULL);
scanf("%s", nombre[i]);
printf("Ingrese su edad: ");
setbuf(stdin, NULL);
scanf("%d", &edad[i]);
printf("Ingrese estarura: ");
setbuf(stdin, NULL);
scanf("%f", &estatura[i]);
}
/* Imprimir resultados en consola. */
printf("|%25s|%25s|%25s|\n", "Nombre", "Edad","Estatura");
for (i = 0; i < MAXI; i++) {
printf("|%-25s|%-25d|%-25.2f|\n", nombre[i],edad[i],estatura[i]);
}
return 0;
}
|
C
|
/* CS261- HW1 - Program4.c*/
/* Name: Erik Nordlund
* Date: April 6, 2018
* Solution description:
*/
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
struct student{
char initials[2];
int score;
};
void sort(struct student* students, int n){
/*Sort n students based on their initials*/
while (n > 1) {
int i;
for (i = 0; (i + 1) < n; ++i) {
char firstInitial1 = students[i].initials[0];
char firstInitial2 = students[i+1].initials[0];
if (firstInitial1 > firstInitial2) {
/* Swapping values */
char lastInitial1 = students[i].initials[1];
char lastInitial2 = students[i+1].initials[1];
int score1 = students[i].score;
int score2 = students[i+1].score;
students[i].initials[0] = firstInitial2;
students[i].initials[1] = lastInitial2;
students[i].score = score2;
students[i+1].initials[0] = firstInitial1;
students[i+1].initials[1] = lastInitial1;
students[i+1].score = score1;
} else if (firstInitial1 == firstInitial2) {
char lastInitial1 = students[i].initials[1];
char lastInitial2 = students[i+1].initials[1];
if (lastInitial1 > lastInitial2) {
/* Swapping values */
int score1 = students[i].score;
int score2 = students[i+1].score;
students[i].initials[0] = firstInitial2;
students[i].initials[1] = lastInitial2;
students[i].score = score2;
students[i+1].initials[0] = firstInitial1;
students[i+1].initials[1] = lastInitial2;
students[i+1].score = score1;
}
}
}
n = n - 1;
}
}
int main(){
/*Declare an integer n and assign it a value.*/
int n = 10;
/*Allocate memory for n students using malloc.*/
struct student* students;
students = NULL;
students = (struct student *) malloc(n * sizeof(struct student));
assert(students != NULL);
/*Generate random IDs and scores for the n students, using rand().*/
int i;
for (i = 0; i < n; ++i) {
char c1 = rand() % 26 + 'A';
char c2 = rand() % 26 + 'A';
int s = rand() % 101;
students[i].initials[0] = c1;
students[i].initials[1] = c2;
students[i].score = s;
}
/*Print the contents of the array of n students.*/
for (i = 0; i < n; ++i) {
char i0 = students[i].initials[0];
char i1 = students[i].initials[1];
int s = students[i].score;
printf("%i. %c%c %i\n", i, i0, i1, s);
}
/*Pass this array along with n to the sort() function*/
sort(students, n);
/*Print the contents of the array of n students.*/
printf("Sorted:\n");
for (i = 0; i < n; ++i) {
char i0 = students[i].initials[0];
char i1 = students[i].initials[1];
int s = students[i].score;
printf("%i. %c%c %i\n", i, i0, i1, s);
}
free(students);
return 0;
}
|
C
|
#pragma once
#include "VectorEngineDatastructureHeader.h"
TEST(VectorEngineTypeMatrixIsZeroMatrix, IZM_true_1x1)
{
Matrix *matrix = new Matrix(1, 1);
matrix->setEntry(0, 0, 0);
EXPECT_NO_THROW(TypeMatrix::isZeroMatrix(*matrix));
EXPECT_TRUE(TypeMatrix::isZeroMatrix(*matrix));
}
TEST(VectorEngineTypeMatrixIsZeroMatrix, IZM_false_1x1)
{
Matrix *matrix = new Matrix(1, 1);
matrix->setEntry(0, 0, 1);
EXPECT_NO_THROW(TypeMatrix::isZeroMatrix(*matrix));
EXPECT_FALSE(TypeMatrix::isZeroMatrix(*matrix));
}
TEST(VectorEngineTypeMatrixIsZeroMatrix, IZM_true_2x2)
{
Matrix *matrix = new Matrix(2, 2);
*matrix = { 0, 0,
0, 0 };
EXPECT_NO_THROW(TypeMatrix::isZeroMatrix(*matrix));
EXPECT_TRUE(TypeMatrix::isZeroMatrix(*matrix));
}
TEST(VectorEngineTypeMatrixIsZeroMatrix, IZM_false_2x2_1)
{
Matrix *matrix = new Matrix(2, 2);
*matrix = { 0, 0,
0, 1 };
EXPECT_NO_THROW(TypeMatrix::isZeroMatrix(*matrix));
EXPECT_FALSE(TypeMatrix::isZeroMatrix(*matrix));
}
TEST(VectorEngineTypeMatrixIsZeroMatrix, IZM_false_2x2_2)
{
Matrix *matrix = new Matrix(2, 2);
*matrix = { 2, 4,
3, 1 };
EXPECT_NO_THROW(TypeMatrix::isZeroMatrix(*matrix));
EXPECT_FALSE(TypeMatrix::isZeroMatrix(*matrix));
}
TEST(VectorEngineTypeMatrixIsZeroMatrix, IZM_true_3x3)
{
Matrix *matrix = new Matrix(3, 3);
*matrix = { 0, 0, 0,
0, 0, 0,
0, 0, 0 };
EXPECT_NO_THROW(TypeMatrix::isZeroMatrix(*matrix));
EXPECT_TRUE(TypeMatrix::isZeroMatrix(*matrix));
}
TEST(VectorEngineTypeMatrixIsZeroMatrix, IZM_false_3x3_1)
{
Matrix *matrix = new Matrix(3, 3);
*matrix = { 0, 0, 0,
0, 1, 0,
0, 0, 0 };
EXPECT_NO_THROW(TypeMatrix::isZeroMatrix(*matrix));
EXPECT_FALSE(TypeMatrix::isZeroMatrix(*matrix));
}
TEST(VectorEngineTypeMatrixIsZeroMatrix, IZM_false_3x3_2)
{
Matrix *matrix = new Matrix(3, 3);
*matrix = { 1, 0, 0,
0, 1, 0,
0, 0, 1 };
EXPECT_NO_THROW(TypeMatrix::isZeroMatrix(*matrix));
EXPECT_FALSE(TypeMatrix::isZeroMatrix(*matrix));
}
TEST(VectorEngineTypeMatrixIsZeroMatrix, IZM_true_3x2)
{
Matrix *matrix = new Matrix(3, 2);
*matrix = { 0, 0,
0, 0,
0, 0 };
EXPECT_NO_THROW(TypeMatrix::isZeroMatrix(*matrix));
EXPECT_TRUE(TypeMatrix::isZeroMatrix(*matrix));
}
TEST(VectorEngineTypeMatrixIsZeroMatrix, IZM_false_3x2)
{
Matrix *matrix = new Matrix(3, 2);
*matrix = { 0, 0,
0, 1,
0, 0 };
EXPECT_NO_THROW(TypeMatrix::isZeroMatrix(*matrix));
EXPECT_FALSE(TypeMatrix::isZeroMatrix(*matrix));
}
TEST(VectorEngineTypeMatrixIsZeroMatrix, IZM_true_2x3)
{
Matrix *matrix = new Matrix(2, 3);
*matrix = { 0, 0, 0,
0, 0, 0 };
EXPECT_NO_THROW(TypeMatrix::isZeroMatrix(*matrix));
EXPECT_TRUE(TypeMatrix::isZeroMatrix(*matrix));
}
TEST(VectorEngineTypeMatrixIsZeroMatrix, IZM_false_2x3)
{
Matrix *matrix = new Matrix(2, 3);
*matrix = { 0, 0, 0,
0, 1, 0 };
EXPECT_NO_THROW(TypeMatrix::isZeroMatrix(*matrix));
EXPECT_FALSE(TypeMatrix::isZeroMatrix(*matrix));
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
typedef struct stackarray{
char *_element, _topIndex;
unsigned int _size, _capacity;
} StackArray;
void stackArray_init(StackArray *stack, unsigned stackSize);
bool stackArray_isEmpty(StackArray *stack);
void stackArray_push(StackArray *stack, int value);
void stackArray_pop(StackArray *stack);
int stackArray_top(StackArray *stack);
void stackArray_init(StackArray *stack, unsigned int stackSize){
stack->_element = (char*) malloc(sizeof(char) * stackSize);
stack->_size = 0;
stack->_topIndex = -1;
stack->_capacity = stackSize;
}
bool stackArray_isEmpty(StackArray *stack){
return (stack->_topIndex == -1);
}
void stackArray_push(StackArray *stack, int value){
if (stack->_size + 1 <= stack->_capacity){
stack->_element[++stack->_topIndex] = value;
stack->_size++;
}
}
void stackArray_pop(StackArray *stack){
if (!stackArray_isEmpty(stack)) {
stack->_topIndex--;
stack->_size--;
}
}
int stackArray_top(StackArray *stack){
if (!stackArray_isEmpty(stack)) {
return stack->_element[stack->_topIndex];
}
return 0;
}
int main(){
StackArray myStack;
char str[101];
gets(str);
stackArray_init(&myStack, 101);
int index, tf;
index=strlen(str)/2;
for(int i=index; i<strlen(str); i++){
stackArray_push(&myStack, str[i]);
}
for(int i=0; i<index; i++){
char temp=stackArray_top(&myStack);
stackArray_pop(&myStack);
if(temp!=str[i]){
tf=0;
printf("mahal, eh bukan palindrom deh\n");
break;
}else{
tf=1;
}
}
if(tf==1){
printf("palindrom\n");
}
return 0;
}
|
C
|
//binary/octal/decimal/hexadecimal system transform
#include <stdio.h>
#include <math.h>
float decimal(char *sBoh, int radix);
void boh(float dec, int radix, char *sBoh);
int main()
{
float fDec;
char sBoh[41];
printf("\nEnter a value to convert: ");
scanf("%f", &fDec);
boh(fDec, 2, sBoh);
printf(" From Decimal to Binary: %s\n", sBoh);
boh(fDec, 8, sBoh);
printf(" From Decimal to Octal: %s\n", sBoh);
boh(fDec, 16, sBoh);
printf(" From Decimal to Hexadecimal: %s\n", sBoh);
printf("\n\nEnter a binary string:");
scanf("%s", sBoh);
fDec = decimal(sBoh, 2);
printf(" From Binary to Decimal: %f", fDec);
printf("\n\nEnter a octal string: ");
scanf("%s", sBoh);
fDec = decimal(sBoh, 8);
printf(" Fron Octal to Decimal: %f", fDec);
printf("\n\nEnter a hexadecimal string:");
scanf("%s", sBoh);
fDec = decimal(sBoh, 16);
printf(" From Hexadecimal to Decimal: %f", fDec);
return 0;
}
float decimal(char *sBoh, int radix)
{
int i, iLen,iDec, digit;
char c, ch;
int fInt;
float fDec;
//get the length of the string
i = 0;
iDec = -1;
while(sBoh[i] != '\0')
{
//get the index of dot
if(sBoh[i] == '.')
{
iDec = i;
}
i++;
}
iLen = i;
if(iDec == -1)
{
iDec = iLen - 1;
}
//convert the string to the decimal in accordance with radix
//Extract digits
fInt = 0;
fDec = 0;
for(i = 0; i <iLen; i++)
{
//get integer elements sequentially
//get decimal components inversely
if(i > iDec)
{
ch = sBoh[iDec + iLen - i];
}
else
{
}
}
}
|
C
|
#include <stdio.h>
#include <string.h>
int main( void )
{
char string[100];
puts( "문자열을 입력한 후 Enter키를 치세요 !" );
puts( "아무 문자도 입력하지 않으면 프로그램은 종료됩니다 !" );
do
{
gets( string );
if( strlen(string) == 0 ) break;
strupr( string );
puts( string );
} while( 1 );
}
|
C
|
//Program question at: http://www.codechef.com/JUNE12/problems/CAKEDOOM
#include <stdio.h>
#include <string.h>
char s[101];
int main()
{
int t; scanf("%d\n",&t);
while(t--)
{
int a=0,k,len; scanf("%d\n",&k);
gets(s);
len = strlen(s);
if(len == 1 && s[0] != '?') { printf("%s\n",s); continue; }
if(k==2 && s[0] == '?')
{
while(s[++a] == '?');
if(a < len && ((a%2 == 0 && s[a] == 49) || (a%2 == 1 && s[a] == 48))) s[0] = 49;
}
int l,r,p;
for(a=0;a<len;a++)
{
l = a==0 ? len-1 : a-1; r = a==len-1 ? 0 : a+1; p=0;
if(s[a] == '?')
{
while(s[l]-48 == p || s[r]-48 == p) p++;
if(p >= k) goto NP;
s[a] = p+48;
}
else
{
if(s[a] == s[l] || s[a] == s[r] || s[a] >= k+48) goto NP;
}
}
printf("%s\n",s); continue;
NP:
printf("NO\n");
}
}
|
C
|
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <time.h>
#define TIMES 10
int main (void){
int i =0;
int *array[TIMES];
for(i=0; i<TIMES; i++){
array[i] = (int *)my_nextfit_malloc(sizeof(int));
printf("Malloc'd: %p\n",array[i]);
}
for(i=0; i<TIMES;i++){
printf("freeing: %p\n",array[i]);
my_free(array[i]);
}
void *test = (void *)my_nextfit_malloc(50);
void *test2 = (void *)my_nextfit_malloc(50);
my_free(test);
test = (void *)my_nextfit_malloc(4);
my_free(test);
my_free(NULL);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include "hash.h"
int main()
{
//this is the head node that contains the information such as the number of nodes that are currently present in the cache
//this is necessary because we require the cache to be of limited size
node_t head = (node_t)malloc(sizeof(struct node));
head -> ele = 0;
head -> link = NULL;
node_t list_of_pointers[HASH_LENGTH];
//initialise the list of pointers with the head node
initialise_hash(list_of_pointers);
node_t cache = create_cache();
cache = reference_page(list_of_pointers,cache, 10);
cache = reference_page(list_of_pointers,cache, 20);
cache = reference_page(list_of_pointers,cache, 30);
cache = reference_page(list_of_pointers,cache, 40);
cache = reference_page(list_of_pointers,cache, 50);
display(cache);
cache = reference_page(list_of_pointers,cache, 10);
display(cache);
cache = reference_page(list_of_pointers,cache, 60);
display(cache);
}
|
C
|
#pragma once
// Data structure of the stress tensor
/*
Stress Tensor:
| |
| simga_x, tau_xy, tau_zx |
| |
| tau_xy, sigma_y, tau_yz |
| |
| tau_zx, tau_yz, sigma_z |
| |
*/
#define IDENTITY StressTensor(1.0f,1.0f,1.0f,0,0,0)
#define PI 3.14159265358979323
struct StressTensor
{
StressTensor
(
float _sigma_x,
float _sigma_y,
float _sigma_z,
float _tau_zy,
float _tau_zx,
float _tau_xy
) : sigma_x(_sigma_x), sigma_y(_sigma_y), sigma_z(_sigma_z),
tau_zy(_tau_zy), tau_zx(_tau_zx), tau_xy(_tau_xy)
{}
float sigma_x;
float sigma_y;
float sigma_z;
float tau_zy;
float tau_zx;
float tau_xy;
};
inline StressTensor operator+(const StressTensor& lhs, const StressTensor& rhs)
{
StressTensor result
{
lhs.sigma_x + rhs.sigma_x,
lhs.sigma_y + rhs.sigma_y,
lhs.sigma_z + rhs.sigma_z,
lhs.tau_xy + rhs.tau_xy,
lhs.tau_zx + rhs.tau_zx,
lhs.tau_zy + rhs.tau_zy
};
return result;
}
inline StressTensor operator-(const StressTensor& lhs, const StressTensor& rhs)
{
StressTensor result
{
lhs.sigma_x - rhs.sigma_x,
lhs.sigma_y - rhs.sigma_y,
lhs.sigma_z - rhs.sigma_z,
lhs.tau_xy - rhs.tau_xy,
lhs.tau_zx - rhs.tau_zx,
lhs.tau_zy - rhs.tau_zy
};
return result;
}
inline StressTensor operator*(const StressTensor& lhs, const float & rhs)
{
StressTensor result
{
lhs.sigma_x * rhs,
lhs.sigma_y * rhs,
lhs.sigma_z * rhs,
lhs.tau_xy * rhs,
lhs.tau_zx * rhs,
lhs.tau_zy * rhs
};
return result;
}
inline StressTensor operator*(const float& lhs, const StressTensor& rhs)
{
StressTensor result
{
rhs.sigma_x * lhs,
rhs.sigma_y * lhs,
rhs.sigma_z * lhs,
rhs.tau_xy * lhs,
rhs.tau_zx * lhs,
rhs.tau_zy * lhs
};
return result;
}
|
C
|
#include<stdio.h>
#define memorysize 200
char memory[memorysize];
int i=1;
char *p;
int top=memorysize-1;
int searchingindex=memorysize-1;
char *p2=memory;
int space;
int j;
int setvalue(int size){
while(!(memory[i]==NULL)){
i++;
}
j=i;
while(memory[j]==NULL){
j++;
}
space=j-i;
if(space>size){
return i;
}
else{
//printf("j == %d %c \n",j,(char)memory[j+5]);
if(memory[j]){
i=j;
return setvalue(size);
}
else{
return j;
}
}
}
int tosearch(int n,int freesize){
if(memory[n]){
//printf("Allocated\n");
}
else{
for(i=memorysize-2;i>150;i=i-3){
if((freesize<memory[i])&&(memory[i-1]==1)){
//printf("%d\n",memory[i+1]);
memory[i]=freesize;
memory[i-1]=2;
return memory[i+1];
}
else if(memory[i]==0){
memory[top--]=n;
memory[top--]=freesize;
memory[top--]=2;
break;
}
}
}
return n;
}
char * write(int m,char x){
int asci=(int)x;
int n=setvalue(m);
//printf("The space valiu is %d \n",space);
int h;
h=tosearch(n,m);
// printf(">>>>%d\n",h);
if(memory[h]==79){
printf("Memory allocated\n");
}
else{
p=&memory[h];
for(i=h;i<h+m;i++){
memory[i]=asci;
}
return &memory[h];
}
}
void myfree(int n){
int v;
while(memory[searchingindex]){
if(memory[searchingindex]==n){
v=memory[--searchingindex];
searchingindex--;
memory[searchingindex]=1;
break;
}
searchingindex--;
}
for(i=n;i<n+v;i++){
memory[i]=NULL;//(char)45;
}
searchingindex=memorysize-1;
}
void bulid(){
for(i=0;i<memorysize;i++){
memory[i]=(char)79;
}
}
void display(){
//int p = setvalue();
int j=1;
for(i=0;i<memorysize;i++){
if(i<150){
printf("%c\t",memory[i]);
}
else{
//printf("\n");
while(memory[memorysize-j]){
printf("%d \t",(int)memory[memorysize-j]);
j++;
}
}
}
}
|
C
|
#include <stdio.h>
int main(void)
{
int i,j,k;
int a[4][3];
int b[3][4];
int c[4][4];
printf("4행 3열 a와 3행 4열 b의 곱을 c로 구합니다.\n");
puts("a의 각 요소 값을 입력하세요:");
for(i=0;i<4;i++){
for(j=0;j<3;j++){
printf("a[%d][%d] : ", i,j);
scanf("%d", &a[i][j]);
}
}
puts("b의 각 요소 값을 입력하세요.");
for(i=0;i<3;i++){
for(j=0;j<4;j++){
printf("b[$d][%d] : ",i,j);
scanf("%d",&b[i][j]);
}
}
puts("c의 값은 다음과 같습니다. ");
for(i=0;i<4;i++){
for(j=0;j<4;j++){
printf("c[%d][%d] = %d\n",i,j,c[i][j]);
}
}
return 0;
}
|
C
|
#include <stdio.h>
#include <time.h>
int main()
{
time_t timer;
char buffer[26];
struct tm* tm_info;
time(&timer);
tm_info = gmtime(&timer);
printf("difftime: %f\n", difftime(timer, 1473349260));
strftime(buffer, 26, "%Y%m%dT%H%M%SZ", tm_info);
puts(buffer);
return 0;
}
|
C
|
#include<stdio.h>
int main(){
int a,i,n,c=0,r=0,s=0,sum=0;
char b;
scanf("%d",&n);
for(i=0;i<n;i++){
scanf("%d %c",&a,&b);
sum=sum+a;
if(b=='C'){
c=c+a;
}
if(b=='R'){
r=r+a;
}
if(b=='S'){
s=s+a;
}
}
printf("Total: %d cobaias\n",sum);
printf("Total de coelhos: %d\n",c);
printf("Total de ratos: %d\n",r);
printf("Total de sapos: %d\n",s);
printf("Percentual de coelhos: %0.2f %%\n",c*100.0/sum);
printf("Percentual de ratos: %0.2f %%\n",r*100.0/sum);
printf("Percentual de sapos: %0.2f %%\n",s*100.0/sum);
return 0;
}
|
C
|
/*
* Copyright (c) 2016 RnDity Sp. z o.o.
*
* SPDX-License-Identifier: Apache-2.0
*/
/**
* @brief Driver for Reset & Clock Control of STM32F10x family processor.
*
* Based on reference manual:
* STM32F101xx, STM32F102xx, STM32F103xx, STM32F105xx and STM32F107xx
* advanced ARM ® -based 32-bit MCUs
*
* Chapter 8: Connectivity line devices: reset and clock control (RCC)
*/
#include <soc.h>
#include <soc_registers.h>
#include <clock_control.h>
#include <misc/util.h>
#include <clock_control/stm32_clock_control.h>
struct stm32f10x_rcc_data {
u8_t *base;
};
static inline int stm32f10x_clock_control_on(struct device *dev,
clock_control_subsys_t sub_system)
{
struct stm32f10x_rcc_data *data = dev->driver_data;
volatile struct stm32f10x_rcc *rcc =
(struct stm32f10x_rcc *)(data->base);
u32_t subsys = POINTER_TO_UINT(sub_system);
if (subsys > STM32F10X_CLOCK_APB2_BASE) {
subsys &= ~(STM32F10X_CLOCK_APB2_BASE);
rcc->apb2enr |= subsys;
} else {
rcc->apb1enr |= subsys;
}
return 0;
}
static inline int stm32f10x_clock_control_off(struct device *dev,
clock_control_subsys_t sub_system)
{
struct stm32f10x_rcc_data *data = dev->driver_data;
volatile struct stm32f10x_rcc *rcc =
(struct stm32f10x_rcc *)(data->base);
u32_t subsys = POINTER_TO_UINT(sub_system);
if (subsys > STM32F10X_CLOCK_APB2_BASE) {
subsys &= ~(STM32F10X_CLOCK_APB2_BASE);
rcc->apb2enr &= ~subsys;
} else {
rcc->apb1enr &= ~subsys;
}
return 0;
}
/**
* @brief helper for mapping a setting to register value
*/
struct regval_map {
int val;
int reg;
};
static int map_reg_val(const struct regval_map *map, size_t cnt, int val)
{
for (int i = 0; i < cnt; i++) {
if (map[i].val == val) {
return map[i].reg;
}
}
return 0;
}
/**
* @brief map APB prescaler setting to register value
*/
static int apb_prescaler(int prescaler)
{
if (prescaler == 0) {
return STM32F10X_RCC_CFG_HCLK_DIV_0;
}
const struct regval_map map[] = {
{0, STM32F10X_RCC_CFG_HCLK_DIV_0},
{2, STM32F10X_RCC_CFG_HCLK_DIV_2},
{4, STM32F10X_RCC_CFG_HCLK_DIV_4},
{8, STM32F10X_RCC_CFG_HCLK_DIV_8},
{16, STM32F10X_RCC_CFG_HCLK_DIV_16},
};
return map_reg_val(map, ARRAY_SIZE(map), prescaler);
}
/**
* @brief map AHB prescaler setting to register value
*/
static int ahb_prescaler(int prescaler)
{
if (prescaler == 0) {
return STM32F10X_RCC_CFG_SYSCLK_DIV_0;
}
const struct regval_map map[] = {
{0, STM32F10X_RCC_CFG_SYSCLK_DIV_0},
{2, STM32F10X_RCC_CFG_SYSCLK_DIV_2},
{4, STM32F10X_RCC_CFG_SYSCLK_DIV_4},
{8, STM32F10X_RCC_CFG_SYSCLK_DIV_8},
{16, STM32F10X_RCC_CFG_SYSCLK_DIV_16},
{64, STM32F10X_RCC_CFG_SYSCLK_DIV_64},
{128, STM32F10X_RCC_CFG_SYSCLK_DIV_128},
{256, STM32F10X_RCC_CFG_SYSCLK_DIV_256},
{512, STM32F10X_RCC_CFG_SYSCLK_DIV_512},
};
return map_reg_val(map, ARRAY_SIZE(map), prescaler);
}
/**
* @brief select PREDIV division factor
*/
static int prediv_prescaler(int prescaler)
{
if (prescaler == 0) {
return STM32F10X_CONN_LINE_RCC_CFGR2_PREDIV_DIV_0;
}
const struct regval_map map[] = {
{0, STM32F10X_CONN_LINE_RCC_CFGR2_PREDIV_DIV_0},
{2, STM32F10X_CONN_LINE_RCC_CFGR2_PREDIV_DIV_2},
{3, STM32F10X_CONN_LINE_RCC_CFGR2_PREDIV_DIV_3},
{4, STM32F10X_CONN_LINE_RCC_CFGR2_PREDIV_DIV_4},
{5, STM32F10X_CONN_LINE_RCC_CFGR2_PREDIV_DIV_5},
{6, STM32F10X_CONN_LINE_RCC_CFGR2_PREDIV_DIV_6},
{7, STM32F10X_CONN_LINE_RCC_CFGR2_PREDIV_DIV_7},
{8, STM32F10X_CONN_LINE_RCC_CFGR2_PREDIV_DIV_8},
{9, STM32F10X_CONN_LINE_RCC_CFGR2_PREDIV_DIV_9},
{10, STM32F10X_CONN_LINE_RCC_CFGR2_PREDIV_DIV_10},
{11, STM32F10X_CONN_LINE_RCC_CFGR2_PREDIV_DIV_11},
{12, STM32F10X_CONN_LINE_RCC_CFGR2_PREDIV_DIV_12},
{13, STM32F10X_CONN_LINE_RCC_CFGR2_PREDIV_DIV_13},
{14, STM32F10X_CONN_LINE_RCC_CFGR2_PREDIV_DIV_14},
{15, STM32F10X_CONN_LINE_RCC_CFGR2_PREDIV_DIV_15},
{16, STM32F10X_CONN_LINE_RCC_CFGR2_PREDIV_DIV_16},
};
return map_reg_val(map, ARRAY_SIZE(map), prescaler);
}
#ifdef CONFIG_CLOCK_STM32F10X_CONN_LINE_PLL_MULTIPLIER
/**
* @brief map PLL multiplier setting to register value
*/
static int pllmul(int mul)
{
/* x4 -> 0x2
* x5 -> 0x3
* x6 -> 0x4
* x7 -> 0x5
* x8 -> 0x6
* x9 -> 0x7
* x6.5 -> 0xd
*/
if (mul == 13) {
/* ToDo: do something with 6.5 multiplication */
return 0xd;
} else {
return mul - 2;
}
}
#endif /* CONFIG_CLOCK_STM32F10X_CONN_LINE_PLL_MULTIPLIER */
#ifdef CONFIG_CLOCK_STM32F10X_CONN_LINE_PLL2_MULTIPLIER
static int pll2mul(int mul)
{
/* x8 -> 0x6
* x9 -> 0x7
* x10 -> 0x8
* x11 -> 0x9
* x12 -> 0xa
* x13 -> 0xb
* x14 -> 0xc
* x16 -> 0xe
* x20 -> 0xf
*/
if (mul == 20) {
return 0xf;
} else {
return mul - 2;
}
}
#endif /* CONFIG_CLOCK_STM32F10X_CONN_LINE_PLL2_MULTIPLIER */
static u32_t get_ahb_clock(u32_t sysclk)
{
/* AHB clock is generated based on SYSCLK */
u32_t sysclk_div =
CONFIG_CLOCK_STM32F10X_CONN_LINE_AHB_PRESCALER;
if (sysclk_div == 0) {
sysclk_div = 1;
}
return sysclk / sysclk_div;
}
static u32_t get_apb_clock(u32_t ahb_clock, u32_t prescaler)
{
if (prescaler == 0) {
prescaler = 1;
}
return ahb_clock / prescaler;
}
static
int stm32f10x_clock_control_get_subsys_rate(struct device *clock,
clock_control_subsys_t sub_system,
u32_t *rate)
{
ARG_UNUSED(clock);
u32_t subsys = POINTER_TO_UINT(sub_system);
u32_t prescaler =
CONFIG_CLOCK_STM32F10X_CONN_LINE_APB1_PRESCALER;
/* assumes SYSCLK is SYS_CLOCK_HW_CYCLES_PER_SEC */
u32_t ahb_clock =
get_ahb_clock(CONFIG_SYS_CLOCK_HW_CYCLES_PER_SEC);
if (subsys > STM32F10X_CLOCK_APB2_BASE) {
prescaler =
CONFIG_CLOCK_STM32F10X_CONN_LINE_APB2_PRESCALER;
}
*rate = get_apb_clock(ahb_clock, prescaler);
return 0;
}
static const struct clock_control_driver_api stm32f10x_clock_control_api = {
.on = stm32f10x_clock_control_on,
.off = stm32f10x_clock_control_off,
.get_rate = stm32f10x_clock_control_get_subsys_rate,
};
/**
* @brief setup embedded flash controller
*
* Configure flash access time latency depending on SYSCLK.
*/
static inline void setup_flash(void)
{
volatile struct stm32f10x_flash *flash =
(struct stm32f10x_flash *)(FLASH_R_BASE);
if (CONFIG_SYS_CLOCK_HW_CYCLES_PER_SEC <= 24000000) {
flash->acr.bit.latency = STM32F10X_FLASH_LATENCY_0;
} else if (CONFIG_SYS_CLOCK_HW_CYCLES_PER_SEC <= 48000000) {
flash->acr.bit.latency = STM32F10X_FLASH_LATENCY_1;
} else if (CONFIG_SYS_CLOCK_HW_CYCLES_PER_SEC <= 72000000) {
flash->acr.bit.latency = STM32F10X_FLASH_LATENCY_2;
}
}
static int stm32f10x_clock_control_init(struct device *dev)
{
struct stm32f10x_rcc_data *data = dev->driver_data;
volatile struct stm32f10x_rcc *rcc =
(struct stm32f10x_rcc *)(data->base);
/* SYSCLK source defaults to HSI */
int sysclk_src = STM32F10X_RCC_CFG_SYSCLK_SRC_HSI;
u32_t hpre =
ahb_prescaler(CONFIG_CLOCK_STM32F10X_CONN_LINE_AHB_PRESCALER);
u32_t ppre1 =
apb_prescaler(CONFIG_CLOCK_STM32F10X_CONN_LINE_APB1_PRESCALER);
u32_t ppre2 =
apb_prescaler(CONFIG_CLOCK_STM32F10X_CONN_LINE_APB2_PRESCALER);
#ifdef CONFIG_CLOCK_STM32F10X_CONN_LINE_PLL_MULTIPLIER
u32_t pll_mul =
pllmul(CONFIG_CLOCK_STM32F10X_CONN_LINE_PLL_MULTIPLIER);
#endif /* CONFIG_CLOCK_STM32F10X_CONN_LINE_PLL_MULTIPLIER */
#ifdef CONFIG_CLOCK_STM32F10X_CONN_LINE_PLL2_MULTIPLIER
u32_t pll2_mul =
pll2mul(CONFIG_CLOCK_STM32F10X_CONN_LINE_PLL2_MULTIPLIER);
#endif /* CONFIG_CLOCK_STM32F10X_CONN_LINE_PLL2_MULTIPLIER */
#ifdef CONFIG_CLOCK_STM32F10X_CONN_LINE_PREDIV1
u32_t prediv1 =
prediv_prescaler(CONFIG_CLOCK_STM32F10X_CONN_LINE_PREDIV1);
#endif /* CONFIG_CLOCK_STM32F10X_CONN_LINE_PREDIV1 */
#ifdef CONFIG_CLOCK_STM32F10X_CONN_LINE_PREDIV2
u32_t prediv2 =
prediv_prescaler(CONFIG_CLOCK_STM32F10X_CONN_LINE_PREDIV2);
#endif /* CLOCK_STM32F10X_CONN_LINE_PREDIV2 */
/* disable PLLs */
rcc->cr.bit.pllon = 0;
rcc->cr.bit.pll2on = 0;
rcc->cr.bit.pll3on = 0;
/* disable HSE */
rcc->cr.bit.hseon = 0;
#ifdef CONFIG_CLOCK_STM32F10X_CONN_LINE_HSE_BYPASS
/* HSE is disabled, HSE bypass can be enabled*/
rcc->cr.bit.hsebyp = 1;
#endif /* CONFIG_CLOCK_STM32F10X_CONN_LINE_HSE_BYPASS */
#ifdef CONFIG_CLOCK_STM32F10X_CONN_LINE_PLL_SRC_HSI
/* enable HSI clock */
rcc->cr.bit.hsion = 1;
/* this should end after one test */
while (rcc->cr.bit.hsirdy != 1) {
}
/* HSI oscillator clock / 2 selected as PLL input clock */
rcc->cfgr.bit.pllsrc = STM32F10X_RCC_CFG_PLL_SRC_HSI;
#endif /* CONFIG_CLOCK_STM32F10X_PLL_SRC_HSI */
#ifdef CONFIG_CLOCK_STM32F10X_CONN_LINE_PLL_SRC_PREDIV1
/* wait for to become ready */
rcc->cr.bit.hseon = 1;
while (rcc->cr.bit.hserdy != 1) {
}
rcc->cfgr2.bit.prediv1 = prediv1;
/* Clock from PREDIV1 selected as PLL input clock */
rcc->cfgr.bit.pllsrc = STM32F10X_RCC_CFG_PLL_SRC_PREDIV1;
#ifdef CONFIG_CLOCK_STM32F10X_CONN_LINE_PREDIV1_SRC_HSE
/* HSE oscillator clock selected as PREDIV1 clock entry */
rcc->cfgr2.bit.prediv1src = STM32F10X_RCC_CFG2_PREDIV1_SRC_HSE;
#else
/* PLL2 selected as PREDIV1 clock entry */
rcc->cfgr2.bit.prediv1src = STM32F10X_RCC_CFG2_PREDIV1_SRC_PLL2;
rcc->cfgr2.bit.prediv2 = prediv2;
rcc->cfgr2.bit.pll2mul = pll2_mul;
/* enable PLL2 */
rcc->cr.bit.pll2on = 1;
/* wait for PLL to become ready */
while (rcc->cr.bit.pll2rdy != 1) {
}
#endif /* CONFIG_CLOCK_STM32F10X_CONN_LINE_PREDIV1_SRC_HSE */
#endif /* CONFIG_CLOCK_STM32F10X_CONN_LINE_PLL_SRC_PREDIV1 */
/* setup AHB prescaler */
rcc->cfgr.bit.hpre = hpre;
/* setup APB1, must not exceed 36MHz */
rcc->cfgr.bit.ppre1 = ppre1;
/* setup APB2 */
rcc->cfgr.bit.ppre2 = ppre2;
#ifdef CONFIG_CLOCK_STM32F10X_CONN_LINE_SYSCLK_SRC_HSI
/* enable HSI clock */
rcc->cr.bit.hsion = 1;
/* this should end after one test */
while (rcc->cr.bit.hsirdy != 1) {
}
sysclk_src = STM32F10X_RCC_CFG_SYSCLK_SRC_HSI;
#elif defined(CONFIG_CLOCK_STM32F10X_SYSCLK_SRC_HSE)
/* enable HSE clock */
rcc->cr.bit.hseon = 1;
/* wait for to become ready */
while (rcc->cr.bit.hserdy != 1) {
}
sysclk_src = STM32F10X_RCC_CFG_SYSCLK_SRC_HSE;
#elif defined(CONFIG_CLOCK_STM32F10X_CONN_LINE_SYSCLK_SRC_PLLCLK)
/* setup PLL multiplication (PLL must be disabled) */
rcc->cfgr.bit.pllmul = pll_mul;
/* enable PLL */
rcc->cr.bit.pllon = 1;
/* wait for PLL to become ready */
while (rcc->cr.bit.pllrdy != 1) {
}
sysclk_src = STM32F10X_RCC_CFG_SYSCLK_SRC_PLL;
#endif /* CONFIG_CLOCK_STM32F10X_CONN_LINE_SYSCLK_SRC_HSI */
/* configure flash access latency before SYSCLK source
* switch
*/
setup_flash();
/* set SYSCLK clock value */
rcc->cfgr.bit.sw = sysclk_src;
/* wait for SYSCLK to switch the source */
while (rcc->cfgr.bit.sws != sysclk_src) {
}
return 0;
}
static struct stm32f10x_rcc_data stm32f10x_rcc_data = {
.base = (u8_t *)RCC_BASE,
};
/* FIXME: move prescaler/multiplier defines into device config */
/**
* @brief RCC device, note that priority is intentionally set to 1 so
* that the device init runs just after SOC init
*/
DEVICE_AND_API_INIT(rcc_stm32f10x, STM32_CLOCK_CONTROL_NAME,
&stm32f10x_clock_control_init,
&stm32f10x_rcc_data, NULL,
PRE_KERNEL_1,
CONFIG_CLOCK_CONTROL_STM32F10X_CONN_LINE_DEVICE_INIT_PRIORITY,
&stm32f10x_clock_control_api);
|
C
|
#include "csapp.h"
//
// Wait for a child and print messages of event ordering
//
// This version uses a global variable (died) to coordinate
// the reaping of child processes.
//
int died = 0;
void handler(int sig)
{
pid_t pid;
while ((pid = waitpid(-1, NULL, 0)) > 0) {
fprintf(stderr,"%d: reap child %d\n", getpid(), pid);
died++;
}
}
int main(int argc, char **argv)
{
int pid;
int kids = 1;
int birthed = 0;
if ( argc > 1 ) {
kids = atoi(argv[1]);
}
Signal(SIGCHLD, handler);
while (birthed < kids ) {
fprintf(stderr, "%d: fork child\n", getpid());
if ((pid = Fork()) == 0) {
fprintf(stderr, "%d: I am the child\n", getpid());
exit(0);
}
fprintf(stderr, "%d: Child is %d\n", getpid(), pid);
birthed++;
}
fprintf(stderr, "%d: parent sleeps: %d birthed\n", getpid(), birthed);
while (died < kids) {
pause();
fprintf(stderr, "%d: parent reaps: %d died\n", getpid(), died);
}
}
|
C
|
/*************************************************************************
> File Name: neicunguanli.c
> Author:
> Mail:
> Created Time: 2018年05月22日 星期二 17时56分24秒
************************************************************************/
#include<stdio.h>
#include<stdlib.h>
#define PROCESS_NAME_LEN 32 //进程名长度
#define MIN_SLICE 10 //最小碎片的大小
#define DEFAULT_MEN_SIZE 1024 //默认内存大小
#define DEFAULT_MEN_START 0 //默认起始位置
#define MA_FF 1
#define MA_BF 2
#define MA_WF 3
//空闲块
struct free_block_type {
int size;
int start_addr;
struct free_block_type *next;
};
//已分配内存块
struct allocated_block {
int pid;
int size;
int start_addr;
char process_name[PROCESS_NAME_LEN];
struct allocated_block *next;
};
struct free_block_type *free_block;
//指向内存中空闲块链表的首指针
struct allocated_block *allocated_block_head = NULL;
//进程分配内存块链表的首指针
int mem_size = DEFAULT_MEN_SIZE; //内存大小
int ma_algorithm = MA_FF; //当前分配算法
static int pid = 0; //初始pid
int flag = 0; //设置内存大小标识
struct free_block_type* init_free_block(int mem_size);
void display_menu();
int set_mem_size();
void set_algorithm();
void rearrange(int algorithm);
void rearrange_FF();
void rearrange_BF();
void rearrange_WF();
int new_process();
int allocate_mem(struct allocated_block *ab);
void kill_process();
int free_mem(struct allocated_block *ab);
int dispose(struct allocated_block *free_ab);
int display_mem_usage();
int find_free_mem(int request);
void do_exit();
struct allocated_block* find_process(int pid);
int main() {
char choice;
pid = 0;
free_block = init_free_block(mem_size); //初始化空闲区
while(1) {
fflush(stdin);
display_menu(); //显示菜单
fflush(stdin);
//choice=getchar(); //获取用户输入
while((choice = getchar()) != '\n') {
fflush(stdin);
switch(choice) {
case '1': set_mem_size(); break; //设置内存大小
case '2': set_algorithm();flag=1; break; //设置算法
case '3': new_process(); flag=1; break; //创建新进程
case '4': kill_process(); flag=1; break; //删除进程
case '5': display_mem_usage();flag=1; break; //显示内存使用
case '0': do_exit(); exit(0); //释放链表并退出
default: break;
}
fflush(stdin);
}
}
}
void display_menu() {
printf("\n");
printf("1 - Set memory size (default=%d)\n", DEFAULT_MEN_SIZE);
printf("2 - Select memory allocation algorithm\n");
printf("3 - New process \n");
printf("4 - Terminate a process \n");
printf("5 - Display memory usage \n");
printf("0 - Exit\n");
}
//初始化空闲块,默认为一块,可以指定大小及起始地址
struct free_block_type* init_free_block(int mem_size) {
struct free_block_type *fb;
fb = (struct free_block_type *)malloc(sizeof(struct free_block_type));
if(fb == NULL) {
printf("No mem\n");
return NULL;
}
fb->size = mem_size; //设置内存大小
fb->start_addr = DEFAULT_MEN_START; //设置起始地址
fb->next = NULL;
return fb;
}
//设置内存的大小
int set_mem_size() {
int size;
if(flag != 0) { //防止重复设置
printf("Cannot set memory size again\n");
return 0;
}
printf("Total memory size = ");
scanf("%d", &size);
if(size > 0) {
mem_size = size;
free_block->size = mem_size;
}
flag = 1;
return 1;
}
//设置当前的分配算法
void set_algorithm() {
int algorithm;
printf("\t1 - First Fit\n");
printf("\t2 - Best Fit \n");
printf("\t3 - Worst Fit \n");
scanf("%d", &algorithm);
if(algorithm>=1 && algorithm <=3)
ma_algorithm=algorithm;
//按指定算法重新排列空闲区链表
rearrange(ma_algorithm);
}
//按指定的算法整理内存空闲块链表
void rearrange(int algorithm) {
/*按指定的算法整理内存空闲块链表*/
switch(algorithm){
case MA_FF: rearrange_FF(); break;
case MA_BF: rearrange_BF(); break;
case MA_WF: rearrange_WF(); break;
}
}
//按FF算法重新整理内存空闲块链表
void rearrange_FF() {
//首次适应算法,空闲区大小按起始地址升序
if(free_block == NULL || free_block->next == NULL) {
return;
}
struct free_block_type *t1,*t2,*head;
head = free_block;
for(t1 = head; t1; t1 = t1->next) {
for(t2 = t1->next; t2; t2 = t2->next) {
if(t1->start_addr > t2->start_addr) {
int tmp = t1->start_addr;
t1->start_addr = t2->start_addr;
t2->start_addr = tmp;
tmp = t1->size;
t1->size = t2->size;
t2->size = tmp;
}
}
}
}
//按BF算法重新整理内存空闲块链表
void rearrange_BF() {
//最佳适应算法,空闲区大小按从小到大排序
if(free_block == NULL || free_block->next == NULL)
return;
struct free_block_type *t1,*t2,*head;
head = free_block;
for(t1 = head; t1; t1 = t1->next) {
for(t2 = t1->next; t2; t2 = t2->next) {
if(t1->size > t2->size) {
int tmp = t1->start_addr;
t1->start_addr = t2->start_addr;
t2->start_addr = tmp;
tmp = t1->size;
t1->size = t2->size;
t2->size = tmp;
}
}
}
}
//按WF算法重新整理内存空闲块链表
void rearrange_WF() {
//最坏适应算法,空闲区按从大到小排序
if(free_block == NULL || free_block->next == NULL)
return;
struct free_block_type *t1,*t2,*head;
head = free_block;
for(t1 = head; t1; t1 = t1->next){
for(t2 = t1->next; t2; t2 = t2->next){
if(t1->size < t2->size){
int tmp = t1->start_addr;
t1->start_addr = t2->start_addr;
t2->start_addr = tmp;
tmp = t1->size;
t1->size = t2->size;
t2->size = tmp;
}
}
}
}
//创建新的进程,主要是获取内存的申请数量
int new_process() {
struct allocated_block *ab;
int size;
int ret;
ab = (struct allocated_block *)malloc(sizeof(struct allocated_block));
if(!ab)
exit(-5);
ab->next = NULL;
pid ++;
sprintf(ab->process_name, "PROCESS-%02d", pid);
ab->pid = pid;
printf("Memory for %s:",ab->process_name);
scanf("%d", &size);
if(size > 0) {
ab->size = size;
}
ret = allocate_mem(ab);
rearrange(ma_algorithm);
//如果此时allocated_block_head尚未赋值,则赋值
if((ret == 1) && (allocated_block_head == NULL)) {
allocated_block_head = ab;
return 1;
}
//分配成功,将该已分配块的描述插入已分配链表
else if (ret == 1) {
ab->next = allocated_block_head;
allocated_block_head = ab;
return 2;
}
else if(ret == -1) {
//分配不成功
printf("Allocation fail\n");
free(ab);
return -1;
}
return 3;
}
//分配内存模块
int allocate_mem(struct allocated_block *ab) {
struct free_block_type *fbt = free_block;
//根据当前算法在空闲分区链表中搜索合适空闲分区进行分配,分配时注意以下情况:
// 1. 找到可满足空闲分区且分配后剩余空间足够大,则分割
// 2. 找到可满足空闲分区且但分配后剩余空间比较小,则一起分配
// 3. 找不可满足需要的空闲分区但空闲分区之和能满足需要,则采用内存紧缩技术,进行空闲分区的合并,然后再分配
// 4. 在成功分配内存后,应保持空闲分区按照相应算法有序
// 5. 分配成功则返回1,否则返回-1
//请自行补充。。。。。
while(fbt) {
if(fbt->size >= ab->size) {
ab->start_addr = fbt->start_addr;
fbt->size -= ab->size;
fbt->start_addr += ab->size;
return 1;
}
fbt = fbt->next;
}
printf("Free mem is not enough, Allocate fail!\n");
return -1;
}
//删除进程,归还分配的存储空间,并删除描述该进程内存分配的节点
void kill_process() {
struct allocated_block *ab;
int pid;
printf("Kill Process, pid = ");
scanf("%d", &pid);
ab = find_process(pid);
if(ab != NULL) {
free_mem(ab); //释放ab所表示的分配区
dispose(ab); //释放ab数据结构节点
}
}
struct allocated_block *find_process(int pid) {
struct allocated_block *tmp = allocated_block_head;
while(tmp) {
if(tmp->pid == pid) {
return tmp;
}
tmp = tmp->next;
}
printf("Cannot find pid:%d\n", pid);
return NULL;
}
//将ab所表示的已分配区归还,并进行可能的合并
int free_mem(struct allocated_block *ab) {
int algorithm = ma_algorithm;
struct free_block_type *fbt, *pre, *work;
fbt = (struct free_block_type*)malloc(sizeof(struct free_block_type));
if(!fbt)
return -1;
// 进行可能的合并,基本策略如下
// 1. 将新释放的结点插入到空闲分区队列末尾
// 2. 对空闲链表按照地址有序排列
// 3. 检查并合并相邻的空闲分区
// 4. 将空闲链表重新按照当前算法排序
// 请自行补充……
//return 1;
fbt->size = ab->size;
fbt->start_addr = ab->start_addr;
work = free_block;
if(work == NULL) {
free_block = fbt;
fbt->next = NULL;
} else {
while(work->next != NULL)
work = work->next;
work->next = fbt;
fbt->next = NULL;
}
rearrange_FF();
pre = free_block;
while(pre->next != NULL) {
work = pre->next;
if(pre->start_addr + pre->size == work->start_addr) {
pre->size = pre->size + work->size;
pre->next = work->next;
free(work);
continue;
} else {
pre = pre->next;
}
}
rearrange(ma_algorithm);
return 1;
}
//释放ab数据结构节点
int dispose(struct allocated_block *free_ab) {
struct allocated_block *pre, *ab;
if(free_ab == allocated_block_head) {
//如果要释放第一个节点
allocated_block_head = allocated_block_head->next;
free(free_ab);
return 1;
}
pre = allocated_block_head;
ab = allocated_block_head->next;
while(ab != free_ab) {
pre = ab;
ab = ab->next;
}
pre->next = ab->next;
free(ab);
return 2;
}
//显示当前内存的使用情况,包括空闲区的情况和已经分配的情况
int display_mem_usage() {
struct free_block_type *fbt = free_block;
struct allocated_block *ab = allocated_block_head;
if(fbt == NULL)
return -1;
printf("----------------------------------------------------------\n");
//显式空闲区
printf("Free Memory:\n");
printf("%20s %20s\n", " start_addr", " size");
while(fbt != NULL){
printf("%20d %20d\n", fbt->start_addr, fbt->size);
fbt=fbt->next;
}
//显示已分配区
printf("\nUsed Memory:\n");
printf("%10s %20s %10s %10s\n", "PID", "ProcessName", "start_addr", " size");
while(ab != NULL){
printf("%10d %20s %10d %10d\n", ab->pid, ab->process_name, ab->start_addr, ab->size);
ab=ab->next;
}
printf("----------------------------------------------------------\n");
return 0;
}
void do_exit() {
return;
}
|
C
|
/*
文件名:SharedMemory.c
描述:共享内存的函数集合
*/
#include "types.h"
#include "defs.h"
#include "param.h"
#include "memlayout.h"
#include "mmu.h"
#include "x86.h"
#include "proc.h"
#include "spinlock.h"
struct SharedMemoryEntry GlobalSharedMemoryList[SHARED_MEMORY_GLOBAL];
struct spinlock SharedMemoryLock;
/*
描述:获取全局共享内存使用情况
参数:无
返回:返回被使用的全局共享内存块数
*/
int GetGlobalSharedMemoryInfo()
{
int i;
int UsedMemoryNum = 0;
for (i = 0; i < SHARED_MEMORY_GLOBAL; i++)
{
if (GlobalSharedMemoryList[i].Signature > 0)
{
UsedMemoryNum ++;
}
}
return UsedMemoryNum;
}
/*
描述:获取进程共享内存使用情况
参数:无
返回:返回被使用的进程共享内存块数
*/
int GetProcessSharedMemoryInfo(struct proc* CurrentProcess)
{
int i;
int UsedMemoryNum = 0;
for (i = 0; i < SHARED_MEMORY_PER_PROC; i++)
{
if (CurrentProcess->SelfSharedMemory[i] > 0)
{
UsedMemoryNum ++;
}
}
return UsedMemoryNum;
}
/*
描述:在本进程找一个共享内存
参数:当前进程,信号
返回:成功:位置,失败:-1
*/
int FindSelfSharedMemory(struct proc* CurrentProcess, int TheSignature)
{
int i;
for (i = 0; i < SHARED_MEMORY_PER_PROC; i++)
{
if (CurrentProcess->SelfSharedMemory[i] == TheSignature)
{
return i;
}
}
return -1;
}
/*
描述:在全局找一个共享内存
参数:信号
返回:成功:位置,失败:-1
*/
int FindGlobalSharedMemory(int TheSignature)
{
int i;
for (i = 0; i < SHARED_MEMORY_GLOBAL; i++)
{
if (GlobalSharedMemoryList[i].Signature == TheSignature)
{
return i;
}
}
return -1;
}
/*
描述:在初始化阶段,初始化全局共享内存为空
参数:无
返回:无
*/
void InitGlobalSharedMemory(void)
{
int i;
for (i = 0; i < SHARED_MEMORY_GLOBAL; i++)
{
GlobalSharedMemoryList[i].VirtualAddress = 0;
GlobalSharedMemoryList[i].Signature = 0;
GlobalSharedMemoryList[i].UserNumber = 0;
}
}
/*
描述:分配某个进程共享内存
参数:信号
返回:成功0失败-1
*/
int AllocSharedMemory(int TheSignature)
{
acquire(&SharedMemoryLock);
struct proc *CurrentProcess = myproc();
int i = 0, SelfEmptyPlace = -1, GlobalEmptyPlace = -1;
//先找自己有没有这一块内存,如果有,报错返回,否则找一块空位置
for (i = 0; i < SHARED_MEMORY_PER_PROC; i++)
{
if (CurrentProcess->SelfSharedMemory[i] == TheSignature)
{
release(&SharedMemoryLock);
return -1;
}
if (CurrentProcess->SelfSharedMemory[i] == 0)
{
SelfEmptyPlace = i;
}
}
//自己没有空位了
if (SelfEmptyPlace == -1)
{
release(&SharedMemoryLock);
return -1;
}
//找有没有分配好的,有自己直接记录,否则找一块空位记录
for (i = 0; i < SHARED_MEMORY_GLOBAL; i++)
{
if (GlobalSharedMemoryList[i].Signature == TheSignature)
{
CurrentProcess->SelfSharedMemory[SelfEmptyPlace] = TheSignature;
GlobalSharedMemoryList[i].UserNumber++;
release(&SharedMemoryLock);
return 0;
}
if (GlobalSharedMemoryList[i].Signature== 0)
{
GlobalEmptyPlace = i;
}
}
//在全局分配一块新的共享内存,并且给这个进程
if(GlobalEmptyPlace != -1)
{
GlobalSharedMemoryList[GlobalEmptyPlace].VirtualAddress = kalloc();
GlobalSharedMemoryList[GlobalEmptyPlace].Signature = TheSignature;
GlobalSharedMemoryList[GlobalEmptyPlace].UserNumber = 1;
CurrentProcess->SelfSharedMemory[SelfEmptyPlace] = TheSignature;
release(&SharedMemoryLock);
return 0;
}
release(&SharedMemoryLock);
return -1;
}
/*
描述:释放某个进程的共享内存
参数:信号
返回:成功0失败-1
*/
int DeallocSharedMemory(int TheSignature)
{
acquire(&SharedMemoryLock);
struct proc* CurrentProcess = myproc();
int SelfPlace = -1, GlobalPlace = -1;
//先找自己有没有
SelfPlace = FindSelfSharedMemory(CurrentProcess, TheSignature);
//自己没有
if (SelfPlace == -1)
{
release(&SharedMemoryLock);
return -1;
}
//在列表里找,有就释放
GlobalPlace = FindGlobalSharedMemory(TheSignature);
//列表里有
if(GlobalPlace != -1)
{
GlobalSharedMemoryList[GlobalPlace].UserNumber --;
CurrentProcess->SelfSharedMemory[SelfPlace] = 0;
if(GlobalSharedMemoryList[GlobalPlace].UserNumber <= 0)
{
kfree(GlobalSharedMemoryList[GlobalPlace].VirtualAddress);
GlobalSharedMemoryList[GlobalPlace].VirtualAddress = (void *)-1;
GlobalSharedMemoryList[GlobalPlace].Signature = 0;
}
release(&SharedMemoryLock);
return 0;
}
//列表里没有
release(&SharedMemoryLock);
return -1;
}
/*
描述:读取某个进程的共享内存
参数:信号,缓冲区
返回:成功0失败-1
*/
int ReadSharedMemory(int TheSignature, char *TheBuffer)
{
struct proc* CurrentProcess = myproc();
int SelfPlace = -1, GlobalPlace = -1;
//先找自己有没有
SelfPlace = FindSelfSharedMemory(CurrentProcess, TheSignature);
if(SelfPlace == -1)
{
return -1;
}
//找全局有没有
GlobalPlace = FindGlobalSharedMemory(TheSignature);
if (GlobalPlace != -1)
{
memmove(TheBuffer, GlobalSharedMemoryList[GlobalPlace].VirtualAddress, PGSIZE);
return 0;
}
return -1;
}
/*
描述:写入某个进程的共享内存
参数:信号,缓冲区
返回:成功0失败-1
*/
int WriteSharedMemory(int TheSignature, char *TheBuffer)
{
struct proc* CurrentProcess = myproc();
int SelfPlace, GlobalPlace;
SelfPlace = FindSelfSharedMemory(CurrentProcess, TheSignature);
if (SelfPlace == -1)
{
return -1;
}
GlobalPlace = FindGlobalSharedMemory(TheSignature);
if(GlobalPlace != -1)
{
int Length = strlen(TheBuffer);
strncpy(GlobalSharedMemoryList[GlobalPlace].VirtualAddress, TheBuffer, Length + 1);
return 0;
}
return -1;
}
|
C
|
/**
* Logging.
* Just wrappers around easylogging++ in case I decide to change later
*
* @author Thom Troy
*
* Copyright (C) 2015 Thom Troy
*/
#ifndef __VSID_COMMON_LOGGER_H__
#define __VSID_COMMON_LOGGER_H__
#define ELPP_NO_DEFAULT_LOG_FILE
#include "easylogging++.h"
#define INIT_LOGGING INITIALIZE_EASYLOGGINGPP
#define ELPP_DISABLE_DEFAULT_CRASH_HANDLING
//#define ELPP_STACKTRACE_ON_CRASH
// printf style wrappers
// call like LOG_INFO(("some variable %v", variable))
#define LOG_INFO(X) el::Loggers::getLogger("default")->info X;
#define LOG_WARN(X) el::Loggers::getLogger("default")->warn X;
#define LOG_ERROR(X) el::Loggers::getLogger("default")->error X;
#define LOG_DEBUG(X) el::Loggers::getLogger("default")->debug X;
#define LOG_FATAL(X) el::Loggers::getLogger("default")->fatal X;
#define LOG_TRACE(X) el::Loggers::getLogger("default")->trace X;
// wrappers around stream logger
// call lile SLOG_INFO(<< "some variable " << varlaboe)
#define SLOG_INFO(X) LOG(INFO) X;
#define SLOG_WARN(X) LOG(WARNING) X;
#define SLOG_ERROR(X) LOG(ERROR) X;
#define SLOG_DEBUG(X) LOG(DEBUG) X;
#define SLOG_FATAL(X) LOG(FATAL) X;
#define SLOG_TRACE(X) LOG(TRACE) X;
/**
* Format a buffer to print it as hex. The resulting outbuf looks like
*
* 4C 60 DE D8 D8 FA 08 3E 8E 64 AE E0 08 00 45 00 L`.....>.d....E.
*
* @param buffer Max buffer size is 1000
* @param size size of buffer
* @param obuf
* @param obuf_sz returned size of output buffer
* @return
*/
inline int format_hexdump (const u_char *buffer, int size,
char *obuf, int obuf_sz)
{
u_char c;
char textver[16 + 1];
//int maxlen = (obuf_sz / 68) * 16;
int maxlen = (obuf_sz / 69) * 16; // +1 for \t
if (size > maxlen)
size = maxlen;
int i;
for (i = 0; i < (size >> 4); i++)
{
int j;
*obuf++ = '\t';
for (j = 0 ; j < 16; j++)
{
c = (u_char) buffer[(i << 4) + j];
::sprintf (obuf, "%02X ", c);
obuf += 3;
if (j == 7)
{
::sprintf (obuf, " ");
obuf++;
}
textver[j] = (c < 0x20 || c > 0x7e) ? '.' : c;
}
textver[j] = 0;
::sprintf (obuf, " %s\n", textver);
while (*obuf != '\0')
obuf++;
}
if (size % 16)
{
*obuf++ = '\t';
for (i = 0 ; i < size % 16; i++)
{
c = (u_char) buffer[size - size % 16 + i];
::sprintf (obuf, "%02X ",c);
obuf += 3;
if (i == 7)
{
::sprintf (obuf, " ");
obuf++;
}
textver[i] = (c < 0x20 || c > 0x7e) ? '.' : c;
}
for (i = size % 16; i < 16; i++)
{
::sprintf (obuf, " ");
obuf += 3;
textver[i] = ' ';
}
textver[i] = 0;
::sprintf (obuf, " %s\n", textver);
}
return size;
}
/**
* Log a buffer as HEX.
*
* Mainly for logging a packet
*
* Use sparingly
* @param MSG A msg to print in the first line
* @param HEX The hex buffer
* @param SZE Size of the hex buffer
* @return
*/
#define LOG_HEXDUMP(MSG, HEX, SZE) \
if( SZE < 2048) { \
char LHD_buf[4097]; \
LHD_buf[0] = '\0'; \
int len = format_hexdump (HEX, SZE, LHD_buf, sizeof LHD_buf); \
LOG(INFO) << MSG << endl << LHD_buf << endl; \
}
#define CLASS_LOG(OutputStreamInstance) \
virtual void log(el::base::type::ostream_t& OutputStreamInstance) const
#endif // end HEADER GUARD
|
C
|
/**********************************************************
Algortym: Wyszukiwanie drogi A-Star
Licencja: http://www.gnu.org/licenses/lgpl.txt
Autor: Kamil Pawlowski <[email protected]>
**********************************************************/
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include "astar.h"
#define LIST_NOMINAL 4096
/* *** IMPLEMENTACJA LISTY DYNAMICZNEJ *** */
void list_clean(pointslist_t *list) {
free(list->points);
list->points = NULL;
list->size = 0;
list->count = 0;
}
void inline list_append(pointslist_t *list, const point_t *point) {
if (list->points == NULL) {
list->size = sizeof(point_t) * LIST_NOMINAL;
list->count = 0;
list->points = malloc(list->size);
}
if (list->size == list->count * sizeof(point_t)) {
list->size = list->size * 2;
list->points = realloc(list->points, list->size);
}
memcpy(&list->points[list->count], point, sizeof(point_t));
list->count ++;
}
void inline list_prepend(pointslist_t *list, const point_t *point) {
if (list->points == NULL) {
list->size = sizeof(point_t) * LIST_NOMINAL;
list->count = 0;
list->points = malloc(list->size);
}
if (list->size == list->count * sizeof(point_t)) {
list->size = list->size * 2;
list->points = realloc(list->points, list->size);
}
memmove(&list->points[1], list->points, (list->count * sizeof(point_t)));
memcpy(&list->points[0], point, sizeof(point_t));
list->count ++;
}
void inline list_remove(pointslist_t *list, const point_t *point) {
int position;
for (position = 0; position < list->count; position++) {
if (list->points[position].x == point->x &&
list->points[position].y == point->y) break;
}
list->count --;
memmove(&list->points[position], &list->points[position+1], (list->count - position) * sizeof(point_t));
}
/* *** OBSLUGA PUNKTOW *** */
point_t inline * list_find(pointslist_t *list, int x, int y) {
int position;
for (position = list->count - 1; position >= 0; position--) {
if (list->points[position].x == x &&
list->points[position].y == y) return &list->points[position];
}
return NULL;
}
point_t inline * list_find_low(pointslist_t *list) {
int position;
point_t *low = &list->points[0];
for (position = list->count - 1; position >= 0; position--) {
if (list->points[position].f < low->f)
low = &list->points[position];
}
return low;
}
void inline point_calc(astar_t *astar, point_t *point) {
int w,h;
point->g = 1;
w = astar->dst_x - point->x;
h = astar->dst_y - point->y;
if (w < 0) w *= -1;
if (h < 0) h *= -1;
point->h = w + h;
point->f = point->g + point->h;
}
/* *** ALGORYTM A-STAR *** */
void inline point_check(astar_t *astar, int x, int y) {
if (list_find(&astar->closedlist, x, y) == NULL &&
!astar->callback_roadblock(astar->callback_data, x, y)) {
point_t *point;
if ((point = list_find(&astar->openlist, x, y)) == NULL) {
point_t point;
point.x = x;
point.y = y;
point.parent_x = astar->q.x;
point.parent_y = astar->q.y;
point_calc(astar, &point);
list_append(&astar->openlist, &point);
if (point.x == astar->dst_x && point.y == astar->dst_y) astar->final = 1;
} else if (point->g < astar->q.g) {
point->parent_x = astar->q.x;
point->parent_y = astar->q.y;
}
}
}
void astar_init(astar_t *astar) {
memset(astar,0,sizeof(astar_t));
}
void astar_start(astar_t *astar, pointslist_t *road) {
astar->openlist.count = 0;
astar->closedlist.count = 0;
road->count = 0;
point_t point;
point.x = astar->src_x;
point.y = astar->src_y;
point.f = 0;
point.g = 0;
point.h = 0;
list_append(&astar->openlist, &point);
astar->final = 0;
while (!(astar->final && astar->openlist.count)) {
memcpy(&astar->q, list_find_low(&astar->openlist), sizeof(point_t));
list_remove(&astar->openlist, &astar->q);
list_append(&astar->closedlist, &astar->q);
if (!astar->final) point_check(astar, astar->q.x-1, astar->q.y-1);
if (!astar->final) point_check(astar, astar->q.x, astar->q.y-1);
if (!astar->final) point_check(astar, astar->q.x+1, astar->q.y-1);
if (!astar->final) point_check(astar, astar->q.x-1, astar->q.y);
if (!astar->final) point_check(astar, astar->q.x+1, astar->q.y);
if (!astar->final) point_check(astar, astar->q.x-1, astar->q.y+1);
if (!astar->final) point_check(astar, astar->q.x, astar->q.y+1);
if (!astar->final) point_check(astar, astar->q.x+1, astar->q.y+1);
}
point_t *last = &astar->q;
while (last != NULL) {
list_prepend(road, last);
last = list_find(&astar->closedlist, last->parent_x, last->parent_y);
}
};
void astar_clean(astar_t *astar) {
list_clean(&astar->openlist);
list_clean(&astar->closedlist);
}
|
C
|
// Gabriel Lopes Silva [email protected] trabalho de Decodificacao lab 2
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
char chave[] = "G89yk1";
void Criptografar();
void back();
int main(){
char select;
for(;;){
printf("\n 1-Criptografar\n 2-Descriptografar\n 3-Sair\n ");
scanf("%c",&select);
switch(select){
case '1':
Criptografar();
break;
case '2':
back();
break;
case '3':
return 0;
break;
}
}
}
void Criptografar(){
FILE *arquivo_de_leitura,*arquivo_de_escrita;
char nome_do_arquivo[80],aux;
int valor_em_asc,codigo,i = 0;
__fpurge(stdin);
printf("\n Digite o nome do arquivo: ");
gets(nome_do_arquivo);
arquivo_de_escrita=fopen("codic.crp","w+");
if((arquivo_de_leitura=fopen(nome_do_arquivo,"r"))==NULL){
printf("\n Erro \n Seu arquivo pode estar em branco ou nao existir!\n");
}
else{
while((aux=fgetc(arquivo_de_leitura))!=EOF){
valor_em_asc=aux;//pega o valor do caracter em ascII
if(i==6){
i=0;//retorma o comeco da chave
}
codigo = chave[i]*valor_em_asc;
fprintf(arquivo_de_escrita," %d ",codigo);
}
}
fclose(arquivo_de_escrita);
fclose(arquivo_de_leitura);
}
void back(){
FILE *arquivo_de_leitura,*arquivo_de_decodificado;
char aux;
int valor_em_asc,codigo,i = 0;
if((arquivo_de_leitura=fopen("codic.crp","r"))==NULL){
printf("\n Erro \n");
}
else
if((arquivo_de_decodificado=fopen("descodificado.txt","w+"))==NULL){
printf("\n Erro \n");
}
else{
for(;;){
fscanf(arquivo_de_leitura," %d ",&codigo);
if(codigo == NULL){
break;
}
if(i==6){
i=0;//retorma o comeco da chave
}
valor_em_asc=codigo/chave[i];
aux=valor_em_asc;
fprintf(arquivo_de_decodificado,"%c",aux);
codigo = NULL;
}
}
fclose(arquivo_de_decodificado);
fclose(arquivo_de_leitura);
__fpurge(stdin);
}
|
C
|
#define NULL ((void*)0)
typedef unsigned long size_t; // Customize by platform.
typedef long intptr_t; typedef unsigned long uintptr_t;
typedef long scalar_t__; // Either arithmetic or pointer type.
/* By default, we understand bool (as a convenience). */
typedef int bool;
#define false 0
#define true 1
/* Forward declarations */
/* Type definitions */
struct protosw {int pr_type; } ;
struct domain {struct protosw* dom_protoswNPROTOSW; struct protosw* dom_protosw; } ;
/* Variables and functions */
struct domain* pffinddomain (int) ;
struct protosw *
pffindtype(int family, int type)
{
struct domain *dp;
struct protosw *pr;
dp = pffinddomain(family);
if (dp == NULL)
return (NULL);
for (pr = dp->dom_protosw; pr < dp->dom_protoswNPROTOSW; pr++)
if (pr->pr_type && pr->pr_type == type)
return (pr);
return (NULL);
}
|
C
|
/*
** EPITECH PROJECT, 2019
** test.c
** File description:
** Thomas Olry's test.c made the 11/08/2019
*/
#include "../include/pong.h"
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
pong_t *velocity_vector(float xA, float yA, float zA, float x, float y, float z)
{
pong_t *pong = malloc(sizeof(pong));
pong->x = (xA - x) * -1;
pong->y = (yA - y) * -1;
pong->z = (zA - z) * -1;
return (pong);
}
float norm_of_vector(float x, float y, float z)
{
return (sqrtf((x * x) + (y * y) + (z * z)));
}
float pos(float v, float pt, float n)
{
return ((v * n) + v + pt);
}
float calcul_angle(pong_t *pong)
{
float norm = norm_of_vector(pong->x, pong->y, pong->z);
float res = asinf(pong->z / norm);
return (((res * 180) / M_PI) * -1);
}
int pong_math(float xa, float ya, float za, float xb, float yb, float zb, float n)
{
pong_t *pong = velocity_vector(xa, ya, za, xb, yb, zb);
printf("The velocity vector of the ball is:\n");
printf("(%.2f, %.2f, %.2f)\n", pong->x, pong->y, pong->z);
printf("At time t + %.0f, ball coordinates will be:\n", n);
printf("(%.2f, %.2f, %.2f)\n", pos(pong->x, xa, n), pos(pong->y, ya, n), pos(pong->z, za, n));
if (-zb/(zb - za) < 0)
printf("The ball won't reach the paddle.\n");
else {
printf("The incidence angle is:\n");
printf("%.2f degrees\n", calcul_angle(pong));
}
}
int main(int ac, char **av)
{
if (ac != 8)
return (84);
float xa = atof(av[1]);
float ya = atof(av[2]);
float za = atof(av[3]);
float xb = atof(av[4]);
float yb = atof(av[5]);
float zb = atof(av[6]);
int n = atoi(av[7]);
if (n < 0)
return (84);
pong_math(xa, ya, za, xb, yb, zb, n);
return (0);
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.