file
stringlengths 18
26
| data
stringlengths 3
1.04M
|
---|---|
the_stack_data/99644.c | /* Generated by CIL v. 1.7.0 */
/* print_CIL_Input is false */
struct _IO_FILE;
struct timeval;
extern float strtof(char const *str , char const *endptr ) ;
extern void signal(int sig , void *func ) ;
typedef struct _IO_FILE FILE;
extern int atoi(char const *s ) ;
extern double strtod(char const *str , char const *endptr ) ;
extern int fclose(void *stream ) ;
extern void *fopen(char const *filename , char const *mode ) ;
extern void abort() ;
extern void exit(int status ) ;
extern int raise(int sig ) ;
extern int fprintf(struct _IO_FILE *stream , char const *format , ...) ;
extern int strcmp(char const *a , char const *b ) ;
extern int rand() ;
extern unsigned long strtoul(char const *str , char const *endptr , int base ) ;
void RandomFunc(unsigned long input[1] , unsigned long output[1] ) ;
extern int strncmp(char const *s1 , char const *s2 , unsigned long maxlen ) ;
extern int gettimeofday(struct timeval *tv , void *tz , ...) ;
extern int printf(char const *format , ...) ;
int main(int argc , char *argv[] ) ;
void megaInit(void) ;
extern unsigned long strlen(char const *s ) ;
extern long strtol(char const *str , char const *endptr , int base ) ;
extern unsigned long strnlen(char const *s , unsigned long maxlen ) ;
extern void *memcpy(void *s1 , void const *s2 , unsigned long size ) ;
struct timeval {
long tv_sec ;
long tv_usec ;
};
extern void *malloc(unsigned long size ) ;
extern int scanf(char const *format , ...) ;
void megaInit(void)
{
{
}
}
void RandomFunc(unsigned long input[1] , unsigned long output[1] )
{
unsigned long state[1] ;
unsigned long local2 ;
unsigned long local1 ;
char copy11 ;
{
state[0UL] = input[0UL] + 1373777115UL;
local1 = 0UL;
while (local1 < input[1UL]) {
local2 = 0UL;
while (local2 < input[1UL]) {
copy11 = *((char *)(& state[0UL]) + 1);
*((char *)(& state[0UL]) + 1) = *((char *)(& state[0UL]) + 4);
*((char *)(& state[0UL]) + 4) = copy11;
local2 ++;
}
local1 ++;
}
output[0UL] = (state[0UL] + 45871808UL) - 33819252UL;
}
}
int main(int argc , char *argv[] )
{
unsigned long input[1] ;
unsigned long output[1] ;
int randomFuns_i5 ;
unsigned long randomFuns_value6 ;
int randomFuns_main_i7 ;
{
megaInit();
if (argc != 2) {
printf("Call this program with %i arguments\n", 1);
exit(-1);
} else {
}
randomFuns_i5 = 0;
while (randomFuns_i5 < 1) {
randomFuns_value6 = strtoul(argv[randomFuns_i5 + 1], 0, 10);
input[randomFuns_i5] = randomFuns_value6;
randomFuns_i5 ++;
}
RandomFunc(input, output);
if (output[0] == 4242424242UL) {
printf("You win!\n");
} else {
}
randomFuns_main_i7 = 0;
while (randomFuns_main_i7 < 1) {
printf("%lu\n", output[randomFuns_main_i7]);
randomFuns_main_i7 ++;
}
}
}
|
the_stack_data/243892170.c | #include<stdio.h>
int main()
{
int y,a,b,c,d,ans;
scanf("%d", &y);
while(1)
{
y++;
ans=y;
a=y%10;
y=y/10;
b=y%10;
y=y/10;
c=y%10;
y=y/10;
d=y%10;
y=y/10;
if(a!=b&&a!=c&&a!=d&&b!=c&&b!=d&&c!=d)
{
printf("%d",ans);
break;
}
y=ans;
}
}
|
the_stack_data/3262053.c | // zadatak by @who.so ([email protected])
#include <stdio.h>
#include <string.h>
struct Kurs
{
char valuta[5];
float vrijednost;
};
float razmjena(struct Kurs p[], int velicina, const char* string, float iznos)
{
int i=0;
for(i=0 ; i<velicina; i++)
{
if(strcmp(p[i].valuta, string)==0)
{
return p[i].vrijednost*iznos;
}
}
return 0;
}
int main()
{
return 0;
} |
the_stack_data/6543.c | /**
******************************************************************************
* @file stm32f1xx_ll_i2c.c
* @author MCD Application Team
* @brief I2C LL module driver.
******************************************************************************
* @attention
*
* <h2><center>© Copyright (c) 2016 STMicroelectronics.
* All rights reserved.</center></h2>
*
* This software component is licensed by ST under BSD 3-Clause license,
* the "License"; You may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
* opensource.org/licenses/BSD-3-Clause
*
******************************************************************************
*/
#if defined(USE_FULL_LL_DRIVER)
/* Includes ------------------------------------------------------------------*/
#include "stm32f1xx_ll_i2c.h"
#include "stm32f1xx_ll_bus.h"
#include "stm32f1xx_ll_rcc.h"
#ifdef USE_FULL_ASSERT
#include "stm32_assert.h"
#else
#define assert_param(expr) ((void)0U)
#endif
/** @addtogroup STM32F1xx_LL_Driver
* @{
*/
#if defined (I2C1) || defined (I2C2)
/** @defgroup I2C_LL I2C
* @{
*/
/* Private types -------------------------------------------------------------*/
/* Private variables ---------------------------------------------------------*/
/* Private constants ---------------------------------------------------------*/
/* Private macros ------------------------------------------------------------*/
/** @addtogroup I2C_LL_Private_Macros
* @{
*/
#define IS_LL_I2C_PERIPHERAL_MODE(__VALUE__) (((__VALUE__) == LL_I2C_MODE_I2C) || \
((__VALUE__) == LL_I2C_MODE_SMBUS_HOST) || \
((__VALUE__) == LL_I2C_MODE_SMBUS_DEVICE) || \
((__VALUE__) == LL_I2C_MODE_SMBUS_DEVICE_ARP))
#define IS_LL_I2C_CLOCK_SPEED(__VALUE__) (((__VALUE__) > 0U) && ((__VALUE__) <= LL_I2C_MAX_SPEED_FAST))
#define IS_LL_I2C_DUTY_CYCLE(__VALUE__) (((__VALUE__) == LL_I2C_DUTYCYCLE_2) || \
((__VALUE__) == LL_I2C_DUTYCYCLE_16_9))
#define IS_LL_I2C_OWN_ADDRESS1(__VALUE__) ((__VALUE__) <= 0x000003FFU)
#define IS_LL_I2C_TYPE_ACKNOWLEDGE(__VALUE__) (((__VALUE__) == LL_I2C_ACK) || \
((__VALUE__) == LL_I2C_NACK))
#define IS_LL_I2C_OWN_ADDRSIZE(__VALUE__) (((__VALUE__) == LL_I2C_OWNADDRESS1_7BIT) || \
((__VALUE__) == LL_I2C_OWNADDRESS1_10BIT))
/**
* @}
*/
/* Private function prototypes -----------------------------------------------*/
/* Exported functions --------------------------------------------------------*/
/** @addtogroup I2C_LL_Exported_Functions
* @{
*/
/** @addtogroup I2C_LL_EF_Init
* @{
*/
/**
* @brief De-initialize the I2C registers to their default reset values.
* @param I2Cx I2C Instance.
* @retval An ErrorStatus enumeration value:
* - SUCCESS I2C registers are de-initialized
* - ERROR I2C registers are not de-initialized
*/
uint32_t LL_I2C_DeInit(I2C_TypeDef *I2Cx)
{
ErrorStatus status = SUCCESS;
/* Check the I2C Instance I2Cx */
assert_param(IS_I2C_ALL_INSTANCE(I2Cx));
if (I2Cx == I2C1)
{
/* Force reset of I2C clock */
LL_APB1_GRP1_ForceReset(LL_APB1_GRP1_PERIPH_I2C1);
/* Release reset of I2C clock */
LL_APB1_GRP1_ReleaseReset(LL_APB1_GRP1_PERIPH_I2C1);
}
#if defined(I2C2)
else if (I2Cx == I2C2)
{
/* Force reset of I2C clock */
LL_APB1_GRP1_ForceReset(LL_APB1_GRP1_PERIPH_I2C2);
/* Release reset of I2C clock */
LL_APB1_GRP1_ReleaseReset(LL_APB1_GRP1_PERIPH_I2C2);
}
#endif /* I2C2 */
else
{
status = ERROR;
}
return status;
}
/**
* @brief Initialize the I2C registers according to the specified parameters in I2C_InitStruct.
* @param I2Cx I2C Instance.
* @param I2C_InitStruct pointer to a @ref LL_I2C_InitTypeDef structure.
* @retval An ErrorStatus enumeration value:
* - SUCCESS I2C registers are initialized
* - ERROR Not applicable
*/
uint32_t LL_I2C_Init(I2C_TypeDef *I2Cx, LL_I2C_InitTypeDef *I2C_InitStruct)
{
LL_RCC_ClocksTypeDef rcc_clocks;
/* Check the I2C Instance I2Cx */
assert_param(IS_I2C_ALL_INSTANCE(I2Cx));
/* Check the I2C parameters from I2C_InitStruct */
assert_param(IS_LL_I2C_PERIPHERAL_MODE(I2C_InitStruct->PeripheralMode));
assert_param(IS_LL_I2C_CLOCK_SPEED(I2C_InitStruct->ClockSpeed));
assert_param(IS_LL_I2C_DUTY_CYCLE(I2C_InitStruct->DutyCycle));
assert_param(IS_LL_I2C_OWN_ADDRESS1(I2C_InitStruct->OwnAddress1));
assert_param(IS_LL_I2C_TYPE_ACKNOWLEDGE(I2C_InitStruct->TypeAcknowledge));
assert_param(IS_LL_I2C_OWN_ADDRSIZE(I2C_InitStruct->OwnAddrSize));
/* Disable the selected I2Cx Peripheral */
LL_I2C_Disable(I2Cx);
/* Retrieve Clock frequencies */
LL_RCC_GetSystemClocksFreq(&rcc_clocks);
/*---------------------------- I2Cx SCL Clock Speed Configuration ------------
* Configure the SCL speed :
* - ClockSpeed: I2C_CR2_FREQ[5:0], I2C_TRISE_TRISE[5:0], I2C_CCR_FS,
* and I2C_CCR_CCR[11:0] bits
* - DutyCycle: I2C_CCR_DUTY[7:0] bits
*/
LL_I2C_ConfigSpeed(I2Cx, rcc_clocks.PCLK1_Frequency, I2C_InitStruct->ClockSpeed, I2C_InitStruct->DutyCycle);
/*---------------------------- I2Cx OAR1 Configuration -----------------------
* Disable, Configure and Enable I2Cx device own address 1 with parameters :
* - OwnAddress1: I2C_OAR1_ADD[9:8], I2C_OAR1_ADD[7:1] and I2C_OAR1_ADD0 bits
* - OwnAddrSize: I2C_OAR1_ADDMODE bit
*/
LL_I2C_SetOwnAddress1(I2Cx, I2C_InitStruct->OwnAddress1, I2C_InitStruct->OwnAddrSize);
/*---------------------------- I2Cx MODE Configuration -----------------------
* Configure I2Cx peripheral mode with parameter :
* - PeripheralMode: I2C_CR1_SMBUS, I2C_CR1_SMBTYPE and I2C_CR1_ENARP bits
*/
LL_I2C_SetMode(I2Cx, I2C_InitStruct->PeripheralMode);
/* Enable the selected I2Cx Peripheral */
LL_I2C_Enable(I2Cx);
/*---------------------------- I2Cx CR2 Configuration ------------------------
* Configure the ACKnowledge or Non ACKnowledge condition
* after the address receive match code or next received byte with parameter :
* - TypeAcknowledge: I2C_CR2_NACK bit
*/
LL_I2C_AcknowledgeNextData(I2Cx, I2C_InitStruct->TypeAcknowledge);
return SUCCESS;
}
/**
* @brief Set each @ref LL_I2C_InitTypeDef field to default value.
* @param I2C_InitStruct Pointer to a @ref LL_I2C_InitTypeDef structure.
* @retval None
*/
void LL_I2C_StructInit(LL_I2C_InitTypeDef *I2C_InitStruct)
{
/* Set I2C_InitStruct fields to default values */
I2C_InitStruct->PeripheralMode = LL_I2C_MODE_I2C;
I2C_InitStruct->ClockSpeed = 5000U;
I2C_InitStruct->DutyCycle = LL_I2C_DUTYCYCLE_2;
I2C_InitStruct->OwnAddress1 = 0U;
I2C_InitStruct->TypeAcknowledge = LL_I2C_NACK;
I2C_InitStruct->OwnAddrSize = LL_I2C_OWNADDRESS1_7BIT;
}
/**
* @}
*/
/**
* @}
*/
/**
* @}
*/
#endif /* I2C1 || I2C2 */
/**
* @}
*/
#endif /* USE_FULL_LL_DRIVER */
/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
|
the_stack_data/923896.c | /* While this program cannot output value 1 in any interleaving
optimising compilers often reuse the constant 1 assigned to
data in Thread 1 and replace the print data with print 1. */
#include <pthread.h>
int requestReady = 0;
int responseReady = 0;
int data = 0;
void thr1() {
data = 1;
requestReady = 1;
if (responseReady == 1) {
// print data;
assert (data != 1); // it is incorrect to print 1, because data might be different than 1
}
}
void thr2() {
if (requestReady == 1) {
data = 2;
responseReady = 1;
}
}
int main() {
pthread_t t1, t2;
pthread_create(&t1, NULL, thr1, NULL);
pthread_create(&t2, NULL, thr2, NULL);
return 0;
}
|
the_stack_data/79302.c | #include <stdio.h>
int main()
{
long long int n;
int count = 0;
printf("Enter Value : ");
scanf("%lld",&n);
while(n!=0) {
n/=10;
++count;
}
printf("%d",count);
return 0;
}
|
the_stack_data/140766394.c | #include <stdio.h>
#include <complex.h>
int main (void){
_Complex double z;
printf("z = %f + %fI\n", __real__(z),__imag__(z));
return 0;
}
|
the_stack_data/35196.c | /* Taxonomy Classification: 0000000000000161000300 */
/*
* WRITE/READ 0 write
* WHICH BOUND 0 upper
* DATA TYPE 0 char
* MEMORY LOCATION 0 stack
* SCOPE 0 same
* CONTAINER 0 no
* POINTER 0 no
* INDEX COMPLEXITY 0 constant
* ADDRESS COMPLEXITY 0 constant
* LENGTH COMPLEXITY 0 N/A
* ADDRESS ALIAS 0 none
* INDEX ALIAS 0 none
* LOCAL CONTROL FLOW 0 none
* SECONDARY CONTROL FLOW 1 if
* LOOP STRUCTURE 6 non-standard while
* LOOP COMPLEXITY 1 zero
* ASYNCHRONY 0 no
* TAINT 0 no
* RUNTIME ENV. DEPENDENCE 0 no
* MAGNITUDE 3 4096 bytes
* CONTINUOUS/DISCRETE 0 discrete
* SIGNEDNESS 0 no
*/
/*
Copyright 2005 Massachusetts Institute of Technology
All rights reserved.
Redistribution and use of software in source and binary forms, with or without
modification, are permitted provided that the following conditions are met.
- Redistributions of source code must retain the above copyright notice,
this set of conditions and the disclaimer below.
- Redistributions in binary form must reproduce the copyright notice, this
set of conditions, and the disclaimer below in the documentation and/or
other materials provided with the distribution.
- Neither the name of the Massachusetts Institute of Technology nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS".
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED.
IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
int main(int argc, char *argv[])
{
int loop_counter;
char buf[10];
loop_counter = 0;
while(++loop_counter)
{
/* BAD */
buf[4105] = 'A';
if (loop_counter >= 4105) break;
}
return 0;
}
|
the_stack_data/795893.c | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_print_reverse_alphabet.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: ayip <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2017/08/09 22:55:01 by ayip #+# #+# */
/* Updated: 2017/08/09 22:59:22 by ayip ### ########.fr */
/* */
/* ************************************************************************** */
int ft_putchar(char c);
void ft_print_reverse_alphabet(void)
{
char c;
c = 'z';
while (c >= 'a')
ft_putchar(c--);
ft_putchar('\n');
}
|
the_stack_data/13558.c | #include <stdio.h>
void insertionSort(int a[], int l) {
int i, j, k;
// Sort elements one by one
// starting from element at index 1
for (i = 1; i < l; i++) {
k = a[i];
j = i - 1;
// Shift greater elements to right
while (j >= 0 && a[j] > k) {
a[j + 1] = a[j];
j--;
}
// Put element at correct location
// which is at (j + 1)
a[j + 1] = k;
}
}
// driver code to check the program
int main(int argc, char *argv[]) {
int a[] = {5, 4, 2, 1, 3};
int l = sizeof(a) / sizeof(int);
insertionSort(a, l);
for (int i = 0; i < l; i++) printf("%d, ", a[i]);
puts("End");
return 0;
} |
the_stack_data/6387783.c | /*
* cp
*/
#include <stdio.h>
#define CHUNK_SIZE 4096
int main(int argc, char ** argv) {
FILE * fd;
FILE * fout;
if (argc < 3) {
fprintf(stderr, "usage: %s [source] [destination]\n", argv[0]);
return 1;
}
fd = fopen(argv[1], "r");
if (!fd) {
fprintf(stderr, "%s: %s: no such file or directory\n", argv[0], argv[1]);
return 1;
}
fout = fopen(argv[2], "w");
size_t length;
fseek(fd, 0, SEEK_END);
length = ftell(fd);
fseek(fd, 0, SEEK_SET);
char buf[CHUNK_SIZE];
while (length > CHUNK_SIZE) {
fread( buf, 1, CHUNK_SIZE, fd);
fwrite(buf, 1, CHUNK_SIZE, fout);
length -= CHUNK_SIZE;
}
if (length > 0) {
fread( buf, 1, length, fd);
fwrite(buf, 1, length, fout);
}
fclose(fd);
fclose(fout);
return 0;
}
/*
* vim:tabstop=4
* vim:noexpandtab
* vim:shiftwidth=4
*/
|
the_stack_data/564047.c | #include <stdio.h>
#define SIZE 100
int linearSearch( const int array[], int key, int size );
int main( void )
{
int a[ SIZE ];
int x;
int searchKey;
int element;
for ( x = 0; x < SIZE; x++ ) {
a[ x ] = 2 * x;
}
printf( "Enter integer search key:\n" );
scanf( "%d", &searchKey );
element = linearSearch( a, searchKey, SIZE );
if ( element != -1 ) {
printf( "Found value in element %d\n", element );
}
else {
printf( "Value not found\n" );
}
return 0;
}
int linearSearch( const int array[], int key, int size )
{
int n;
for ( n = 0; n < size; ++n ) {
if ( array[ n ] == key ) {
return n;
}
}
return -1;
}
|
the_stack_data/57949938.c | #include<stdio.h>
#include<math.h>
int main(void){
int a,b,c;
double x1,x2;
a=1.0;
b=3.0;
c=2.0;
x1=(-b+sqrt((b^2)-(4*a*c)))/(2*a);
x2=(-b-sqrt((b^2)-(4*a*c)))/(2*a);
printf("x1=%lf\n",x1);
printf("x2=%lf\n",x2);
return 0;
} |
the_stack_data/43910.c | #include "stdio.h"
#include "math.h"
int main()
{
int n,a0=1, index;
float sum= pow(a0, 5) + a0,x,f1,f2;
printf("Insert the n number.\n");
scanf("%d", &n);
index = n;
for (index=1;index<n;index++)
{
sum = pow(sum, 5) + sum;
}
printf("The a%d clause is equal to %f.\n",index,sum);
printf("Insert a real number.\n");
scanf("%f", &x);
f1 = pow(x, 5) - pow(x, 3) + 3 * x;
printf("The value of f1(x)=x^5-x^3+3x for x=%f is equal to %f.\n", x, f1);
if (x > 0)
{
f2 = exp(x) + 4 * log(x) - pow(x, 2);
printf("The value of f2(x)=e^x+4lnx-x^2 for x=%f is equal to %f.\n", x, f2);
}
else
{
printf("It is not defined f2(x)=e^x+4lnx-x^2 for x=%.\n", x);
}
return 0;
}
|
the_stack_data/48575376.c | /*
Copyright 2017-2019 Siemens AG
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
Author(s): Thomas Riedmaier, Pascal Eckmann
*/
#define _GNU_SOURCE
#include <unistd.h>
#include<stdio.h>
#include<stdlib.h>
#include <sys/stat.h>
#include <string.h>
/*
sudo su
cd /home/odroid/TestRoot/cpio-root
gcc -static -msoft-float -mfpu=vfpv3-d16 -o cgicaller cgicaller.c
chroot . ./cgicaller
gdb --args chroot . /cgicaller
set stop-on-solib-events 1
break *0x9884
*/
int main(int argc, char* argv[])
{
if (argc < 2) {
printf("Usage %s <Inputfile>\n", argv[0]);
return -1;
}
struct stat st;
int exist = stat(argv[1], &st);
if (exist != 0) {
printf("%s can not be opened as input file\n", argv[1]);
return -1;
}
char content_length[32];
memset(content_length, 0, sizeof(content_length));
strcpy(content_length, "CONTENT_LENGTH=");
sprintf(content_length + 15, "%d", (int)st.st_size);
//http://www.cgi101.com/book/ch3/text.html
char* envp[] = { content_length, "CONTENT_TYPE=application/x-www-form-urlencoded","QUERY_STRING=","REMOTE_ADDR=127.0.0.1","REMOTE_PORT=22222","REQUEST_METHOD=POST" , NULL };
char* target[] = { "/etc/httpd/swarm.cgi", NULL };
stdin = freopen(argv[1], "r", stdin);
execvpe(target[0], target, envp);
//should never reach this
return 0;
}
|
the_stack_data/919284.c | #include <yaml.h>
#include <stdlib.h>
#include <stdio.h>
#include <assert.h>
void print_escaped(yaml_char_t * str, size_t length);
int usage(int ret);
int main(int argc, char *argv[])
{
FILE *input;
yaml_parser_t parser;
yaml_event_t event;
int flow = 0; // default flow style collections
int i = 0;
int foundfile = 0;
for (i = 1; i < argc; i++) {
if (strncmp(argv[i], "--flow", 6) == 0) {
if (i == argc)
return usage(1);
i++;
if (strncmp(argv[i], "keep", 4) == 0)
flow = 0;
else if (strncmp(argv[i], "on", 2) == 0)
flow = 1;
else if (strncmp(argv[i], "off", 3) == 0)
flow = -1;
else
return usage(1);
}
else if (strncmp(argv[i], "--help", 6) == 0)
return usage(0);
else if (strncmp(argv[i], "-h", 2) == 0)
return usage(0);
else if (!foundfile) {
input = fopen(argv[i], "rb");
foundfile = 1;
}
else
return usage(1);
}
if (!foundfile) {
input = stdin;
}
assert(input);
if (!yaml_parser_initialize(&parser)) {
fprintf(stderr, "Could not initialize the parser object\n");
return 1;
}
yaml_parser_set_input_file(&parser, input);
while (1) {
yaml_event_type_t type;
if (!yaml_parser_parse(&parser, &event)) {
fprintf(stderr, "Parse error: %s\n", parser.problem);
return 1;
}
type = event.type;
if (type == YAML_NO_EVENT)
printf("???\n");
else if (type == YAML_STREAM_START_EVENT)
printf("+STR\n");
else if (type == YAML_STREAM_END_EVENT)
printf("-STR\n");
else if (type == YAML_DOCUMENT_START_EVENT) {
printf("+DOC");
if (!event.data.document_start.implicit)
printf(" ---");
printf("\n");
}
else if (type == YAML_DOCUMENT_END_EVENT) {
printf("-DOC");
if (!event.data.document_end.implicit)
printf(" ...");
printf("\n");
}
else if (type == YAML_MAPPING_START_EVENT) {
printf("+MAP");
if (flow == 0 && event.data.mapping_start.style == YAML_FLOW_MAPPING_STYLE)
printf(" {}");
else if (flow == 1)
printf(" {}");
if (event.data.mapping_start.anchor)
printf(" &%s", event.data.mapping_start.anchor);
if (event.data.mapping_start.tag)
printf(" <%s>", event.data.mapping_start.tag);
printf("\n");
}
else if (type == YAML_MAPPING_END_EVENT)
printf("-MAP\n");
else if (type == YAML_SEQUENCE_START_EVENT) {
printf("+SEQ");
if (flow == 0 && event.data.sequence_start.style == YAML_FLOW_SEQUENCE_STYLE)
printf(" []");
else if (flow == 1)
printf(" []");
if (event.data.sequence_start.anchor)
printf(" &%s", event.data.sequence_start.anchor);
if (event.data.sequence_start.tag)
printf(" <%s>", event.data.sequence_start.tag);
printf("\n");
}
else if (type == YAML_SEQUENCE_END_EVENT)
printf("-SEQ\n");
else if (type == YAML_SCALAR_EVENT) {
printf("=VAL");
if (event.data.scalar.anchor)
printf(" &%s", event.data.scalar.anchor);
if (event.data.scalar.tag)
printf(" <%s>", event.data.scalar.tag);
switch (event.data.scalar.style) {
case YAML_PLAIN_SCALAR_STYLE:
printf(" :");
break;
case YAML_SINGLE_QUOTED_SCALAR_STYLE:
printf(" '");
break;
case YAML_DOUBLE_QUOTED_SCALAR_STYLE:
printf(" \"");
break;
case YAML_LITERAL_SCALAR_STYLE:
printf(" |");
break;
case YAML_FOLDED_SCALAR_STYLE:
printf(" >");
break;
case YAML_ANY_SCALAR_STYLE:
abort();
}
print_escaped(event.data.scalar.value, event.data.scalar.length);
printf("\n");
}
else if (type == YAML_ALIAS_EVENT)
printf("=ALI *%s\n", event.data.alias.anchor);
else
abort();
yaml_event_delete(&event);
if (type == YAML_STREAM_END_EVENT)
break;
}
assert(!fclose(input));
yaml_parser_delete(&parser);
fflush(stdout);
return 0;
}
void print_escaped(yaml_char_t * str, size_t length)
{
int i;
char c;
for (i = 0; i < length; i++) {
c = *(str + i);
if (c == '\\')
printf("\\\\");
else if (c == '\0')
printf("\\0");
else if (c == '\b')
printf("\\b");
else if (c == '\n')
printf("\\n");
else if (c == '\r')
printf("\\r");
else if (c == '\t')
printf("\\t");
else
printf("%c", c);
}
}
int usage(int ret) {
fprintf(stderr, "Usage: libyaml-parser [--flow (on|off|keep)] [<input-file>]\n");
return ret;
}
|
the_stack_data/90765075.c | /* { dg-do compile { target { lp64 } } } */
/* { dg-additional-options "-mno-speculate-indirect-jumps" } */
/* Test for deliberate misprediction of indirect calls. */
extern int (*f)();
int bar ()
{
return (*f) ();
}
/* { dg-final { scan-assembler "crset 2" } } */
/* { dg-final { scan-assembler "beqctrl-" } } */
|
the_stack_data/85898.c | #include<stdio.h>
void knapsack(int n, float weight[], float profit[], float capacity) {
float x[20], tp = 0;
int i, j, u;
u = capacity;
for (i = 0; i < n; i++)
x[i] = 0.0;
for (i = 0; i < n; i++) {
if (weight[i] > u)
break;
else {
x[i] = 1.0;
tp = tp + profit[i];
u = u - weight[i];
}
}
if (i < n)
x[i] = u / weight[i];
tp = tp + (x[i] * profit[i]);
printf("\nThe result vector is:- ");
for (i = 0; i < n; i++)
printf("%f\t", x[i]);
printf("\nMaximum profit is:- %f", tp);
}
int main() {
float weight[20], profit[20], capacity;
int num, i, j;
float ratio[20], temp;
printf("\nEnter the no. of objects:- ");
scanf("%d", &num);
printf("\nEnter the weights and profits of each object:- ");
for (i = 0; i < num; i++) {
scanf("%f %f", &weight[i], &profit[i]);
}
printf("\nEnter the capacity of knapsack:- ");
scanf("%f", &capacity);
for (i = 0; i < num; i++) {
ratio[i] = profit[i] / weight[i];
}
for (i = 0; i < num; i++) {
for (j = i + 1; j < num; j++) {
if (ratio[i] < ratio[j]) {
temp = ratio[j];
ratio[j] = ratio[i];
ratio[i] = temp;
temp = weight[j];
weight[j] = weight[i];
weight[i] = temp;
temp = profit[j];
profit[j] = profit[i];
profit[i] = temp;
}
}
}
knapsack(num, weight, profit, capacity);
return(0);
} |
the_stack_data/120838.c | #include <stdio.h>
#define SIZE 100
int main(){
char s[SIZE];
gets(s);
printf("Hey ");
puts(s);
}
|
the_stack_data/111077484.c | #include <stdio.h>
unsigned float_to_unsigned (float f) {
union {
float f;
unsigned u;
} tmp_union;
tmp_union.f = f;
return tmp_union.u;
}
int main(int argc, char const *argv[]) {
unsigned res = float_to_unsigned(10.0);
printf("%u\n", res);
return 0;
}
// 1092616192
// _float_to_unsigned:
// 100000f20: 55 pushq %rbp
// 100000f21: 48 89 e5 movq %rsp, %rbp
// 100000f24: f3 0f 11 45 fc movss %xmm0, -4(%rbp)
// 100000f29: f3 0f 10 45 fc movss -4(%rbp), %xmm0
// 100000f2e: f3 0f 11 45 f8 movss %xmm0, -8(%rbp)
// 100000f33: 8b 45 f8 movl -8(%rbp), %eax // 把入口参数 f 送到 eax 返回值。
// 100000f36: 5d popq %rbp
// 100000f37: c3 retq
// 100000f38: 0f 1f 84 00 00 00 00 00 nopl (%rax,%rax) |
the_stack_data/95449830.c | // wcsstr_ex.c : wcsstr() example
// -------------------------------------------------------------
#include <wchar.h> // size_t wcsstr( const wchar_t *s1,
// const wchar_t *s2 );
#include <stdlib.h>
#include <stdio.h>
#define MAX_LINE 1024
int main( int argc, char **argv )
{
FILE *fpIn = NULL;
wchar_t keyword[MAX_LINE] = { L'\0' };
wchar_t line[MAX_LINE] = { L'\0' };
if ( argc != 3 )
{
wprintf( L"Syntax: %s <keyword> <filename>\n", argv[0] );
return -1;
}
if (( fpIn = fopen( argv[2], "r" )) == NULL )
return -2;
else
fwide( fpIn, 1 );
if ( mbstowcs( keyword, argv[1], MAX_LINE ) == -1 )
return -3;
int count = 0;
while ( fgetws( line, MAX_LINE, fpIn ) != NULL )
if ( wcsstr( line, keyword ) != NULL )
{
++count;
fputws( line, stdout );
}
if ( !feof( fpIn ))
return -4;
else
return count;
}
|
the_stack_data/66305.c | int Fibonacci ( int loop );
int Fibonacci ( int loop ) {
int i, x, y, z;
x = y = 1;
for ( i = 0; i < loop; i++) {
z = x + y;
y = x;
x = z;
}
return z;
}
int main() {
int ret;
ret = Fibonacci(20);
return ret+1;
}
|
the_stack_data/187644164.c | /**/
#include <stdio.h>
#include <math.h>
int main() {
int a, b, c, d, num_1, num_2, num_3, num_4;
printf("Please enter 4 numbers seperated by spaces > ");
scanf("%d%d%d%d", &num_1, &num_2, &num_3, &num_4);
a = (num_1);
b = (num_2);
c = (num_3);
d = (num_4);
if (a<b && a<c && a<d)
printf("%d is the smallest\n",a);
else if (b<a && b<c && b<d)
printf("%d is the smalles\n",b);
else if (c<a && c<b && c<d)
printf("%d is the smallest\n",c);
else if (d<a && d<b && d<c)
printf("%d is the smallest\n",d);
return 0;
}
|
the_stack_data/41443.c | #include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
int main() {
printf("Digite o número 1: \n");
char c;
c = getchar();
if(c == '1'){
printf("O caracter digitado está correto! \n");
}
else{
printf("O valor digitado é inválido! \n");
printf("Você digitou o caracter >%c<.\n", c);
}
return 0;
} |
the_stack_data/165764228.c | #ifdef CONFIG_EVM_MODULE_TIMERS
#include "evm_module.h"
#include <time.h>
#include <signal.h>
#include <errno.h>
static evm_t *timer_e;
static void callback_handler(union sigval v)
{
evm_val_t *callback = evm_module_registry_get(timer_e, v.sival_int);
if (callback == NULL)
return;
evm_val_t args = *callback;
evm_module_next_tick(timer_e, 1, &args);
}
static timer_t timer(int id, int delay, int once)
{
timer_t timerid;
int ret;
struct sigevent sev;
// handle in thread when timeout
memset(&sev, 0, sizeof(struct sigevent));
sev.sigev_value.sival_ptr = &timerid;
sev.sigev_notify = SIGEV_THREAD;
sev.sigev_notify_function = callback_handler;
sev.sigev_value.sival_int = id;
struct itimerspec its; // duration settings
ret = timer_create(CLOCK_REALTIME, &sev, &timerid);
if (ret == -1)
{
return NULL;
}
// set timeout, only once
// it_value the first timeout duration
// it_interval the next timeout duration
if (delay >= 1000)
{
its.it_value.tv_sec = delay / 1000;
its.it_value.tv_nsec = (delay % 1000) * 1000000;
}
else
{
its.it_value.tv_sec = 0;
its.it_value.tv_nsec = delay * 1000000;
}
if( !once ) {
its.it_interval.tv_sec = its.it_value.tv_sec;
its.it_interval.tv_nsec = its.it_value.tv_nsec;
}
ret = timer_settime(timerid, TIMER_ABSTIME, &its, NULL);
if (ret == -1)
{
return NULL;
}
return timerid;
}
//setTimeout(callback, delay[, args..])
static evm_val_t evm_module_timers_setTimeout(evm_t *e, evm_val_t *p, int argc, evm_val_t *v)
{
if (argc < 2 || !evm_is_script(v) || !evm_is_integer(v + 1))
{
return EVM_VAL_UNDEFINED;
}
int id = evm_module_registry_add(e, v);
if (id < 0)
return EVM_VAL_UNDEFINED;
timer_t timerid = timer(id, evm_2_integer(v + 1), 1);
if (timerid == NULL)
return EVM_VAL_UNDEFINED;
evm_object_set_ext_data(v, (intptr_t)timerid);
return EVM_VAL_UNDEFINED;
}
//clearTimeout(timeout)
static evm_val_t evm_module_timers_clearTimeout(evm_t *e, evm_val_t *p, int argc, evm_val_t *v)
{
if (argc < 1 || !evm_is_integer(v))
{
return EVM_VAL_UNDEFINED;
}
evm_val_t *callback = evm_module_registry_get(e, evm_2_integer(v));
if (callback == NULL)
return EVM_VAL_UNDEFINED;
timer_t timerid = evm_object_get_ext_data(callback);
if (timerid == NULL)
return EVM_VAL_UNDEFINED;
timer_delete(timerid);
evm_module_registry_remove(e, evm_2_integer(v));
return EVM_VAL_UNDEFINED;
}
//setInterval(callback, delay[, args..])
static evm_val_t evm_module_timers_setInterval(evm_t *e, evm_val_t *p, int argc, evm_val_t *v)
{
if (argc < 2 || !evm_is_script(v) || !evm_is_integer(v + 1))
{
return EVM_VAL_UNDEFINED;
}
int id = evm_module_registry_add(e, v);
if (id < 0)
return EVM_VAL_UNDEFINED;
timer_t timerid = timer(id, evm_2_integer(v + 1), 0);
if (timerid == NULL)
return EVM_VAL_UNDEFINED;
evm_object_set_ext_data(v, (intptr_t)timerid);
return evm_mk_number(id);
}
//clearInterval(timeout)
static evm_val_t evm_module_timers_clearInterval(evm_t *e, evm_val_t *p, int argc, evm_val_t *v)
{
if (argc < 1 || !evm_is_integer(v))
{
return EVM_VAL_UNDEFINED;
}
evm_module_timers_clearTimeout(e, p, argc, v);
return EVM_VAL_UNDEFINED;
}
evm_err_t evm_module_timers(evm_t *e) {
timer_e = e;
evm_builtin_t builtin[] = {
{"setTimeout", evm_mk_native((intptr_t)evm_module_timers_setTimeout)},
{"clearTimeout", evm_mk_native((intptr_t)evm_module_timers_clearTimeout)},
{"setInterval", evm_mk_native((intptr_t)evm_module_timers_setInterval)},
{"clearInterval", evm_mk_native((intptr_t)evm_module_timers_clearInterval)},
{NULL, NULL}};
return evm_native_add(e, builtin);
}
#endif
|
the_stack_data/227493.c |
#include <stdio.h>
void scilab_rt_xtitle_s2s2s2_(int in00, int in01, char* matrixin0[in00][in01],
int in10, int in11, char* matrixin1[in10][in11],
int in20, int in21, char* matrixin2[in20][in21])
{
int i;
int j;
for (i = 0; i < in00; ++i) {
for (j = 0; j < in01; ++j) {
printf("%s", matrixin0[i][j]);
}
}
for (i = 0; i < in10; ++i) {
for (j = 0; j < in11; ++j) {
printf("%s", matrixin1[i][j]);
}
}
for (i = 0; i < in20; ++i) {
for (j = 0; j < in21; ++j) {
printf("%s", matrixin2[i][j]);
}
}
}
|
the_stack_data/168893205.c | #include <stdio.h>
#include <stdlib.h>
#define MAX 100
int verdopple(int);
int mystrlen(char str []);
void test();
int myStrCopy(char dest[], char source []);
int myStrCat(char dest[], char source []);
int main()
{
char str[] = "Hallo";
printf("Laenge %d\n", mystrlen(str));
printf("%d\n", verdopple(2));
printf("Hello world!\n");
return 0;
}
int verdopple(int z)
{
return z*z;
}
int mystrlen(char str [])
{
int i = 0;
while(str[i] != '\0')
i++;
return i;
}
void test()
{
char src[MAX] = "Hallo";
char des[MAX];
}
int myStrCopy(char dest[], char source [])
{
int i = 0;
for (i = 0; i <= mystrlen(source); i++)
dest[i] = source[i];
return i;
}
int myStrCat(char dest[], char source [])
{
int i = 0;
int offset = mystrlen(dest);
for (i = 0; i <= mystrlen(source); i++)
dest[offset+i] = source[i];
return i;
}
|
the_stack_data/86643.c | #include <string.h>
void*
memmove(void* dstptr, const void* srcptr, size_t size) {
unsigned char* dst = (unsigned char*)dstptr;
const unsigned char* src = (const unsigned char*)srcptr;
if (dst < src)
for (size_t i = 0; i < size; ++i)
dst[i] = src[i];
else
for (size_t i = size; i != 0; --i)
dst[i-1] = src[i-1];
return dstptr;
}
|
the_stack_data/3262118.c | /*
-*- coding: utf-8 -*-
Copyright (c) 2017 - for information on the respective copyright owner
see the NOTICE file and/or the repository https://github.com/boschresearch/statestream
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
/*
* Some functions to enable hebbian and hebbian-like plasticities.
*/
void chebb_raw(float* src,
float* tgt,
float* upd,
float tgt_eps,
int agents,
int src_X,
int src_Y,
int src_C,
int tgt_X,
int tgt_Y,
int tgt_C,
int rf_X,
int rf_Y,
int dil_X,
int dil_Y,
int ignore_border)
{
/*
* We assume a all arrays to be flattened in row-major style.
* We also assume upd = [tgt_c, src_c, rf_X, rf_Y].
*/
// Some counter and pointer counter.
long int I;
long int J;
int a;
int src_x;
int src_y;
int src_c;
int tgt_x;
int tgt_y;
int tgt_c;
int rf_x;
int rf_y;
int rf_Xh = rf_X / 2;
int rf_Yh = rf_Y / 2;
int stride_x = src_X / tgt_X;
int stride_y = src_Y / tgt_Y;
int border_x = rf_Xh * dil_X / stride_x;
int border_y = rf_Yh * dil_Y / stride_y;
float* ptr_f1;
float* ptr_f2;
// Loop over target neurons.
ptr_f1 = tgt;
for (a=0; a<agents; ++a)
for (tgt_c=0; tgt_c<tgt_C; ++tgt_c)
for (tgt_x=0; tgt_x<tgt_X; ++tgt_x)
for (tgt_y=0; tgt_y<tgt_Y; ++tgt_y)
{
// Check if activation exceeds eps.
if (fabs(*ptr_f1) > tgt_eps)
{
// Check if to ignore borders.
if (ignore_border == 1)
{
// Check if inside borders.
if (tgt_x < border_x || tgt_x > tgt_X - border_x || tgt_y < border_y || tgt_y > tgt_Y - border_y)
continue;
else
{
// Loop over receptive field.
ptr_f2 = upd + tgt_c * tgt_X * tgt_Y * src_C;
I = a * src_C * src_X * src_Y + stride_x * tgt_x * src_Y + stride_y * tgt_y;
for (src_c=0; src_c<src_C; ++src_c)
{
for (rf_x=-rf_Xh; rf_x<=rf_Xh; ++rf_x)
{
// Compute source neuron index (local rf_x).
J = I + rf_x * dil_X * src_Y;
for (rf_y=-rf_Yh; rf_y<=rf_Yh; ++rf_y)
{
// Compute source neuron index (local rf_y).
J += rf_y * dil_Y;
// Update update with hebbian.
*ptr_f2 += *ptr_f1 * src[J];
// Count up pointer in update.
++ptr_f2;
}
}
// Compute source neuron index (next src channel).
I += src_X * src_Y;
}
}
}
else
{
// Loop over receptive field.
ptr_f2 = upd + tgt_c * tgt_X * tgt_Y * src_C;
// TODO: do not ignore borders case.
}
}
// Count up pointer over target in any case.
++ptr_f1;
}
}
|
the_stack_data/6408.c | #include <stdio.h>
#include <stdlib.h>
int main(){
float n;
printf("Digite a distancia em milhas:");
scanf("%f",&n);
printf("\nVelocidade em Quilometros: %.2f\n\n", n = 1.61 * n);
system("PAUSE");
return 0;
}
|
the_stack_data/98487.c | #include <stdio.h>
int main (int argc, char *argv[]) {
int arg;
if (argc > 1) {
arg = atoi(argv[1]);
}
fprintf (stderr, "This is the standard error message! "
"Check to see if test%d.out exists\n", arg);
fprintf (stdout, "This is the standard output message!\n");
return 0;
}
|
the_stack_data/79249.c | #include <stdio.h>
#include <stdbool.h>
int main(int argc, char *argv[])
{
int integer = sizeof(int);
printf("%d", integer);
return 0;
}
|
the_stack_data/1247586.c | #include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
int main(int c, char **v)
{
while (--c > 1 && !fork());
sleep(c = atoi(v[c]));
printf("%d\n", c);
wait(0);
return 0;
}
|
the_stack_data/777086.c | /* dlasq3.f -- translated by f2c (version 20061008) */
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <float.h>
#include <assert.h>
/* Subroutine */ int odsq3_(int *i0, int *n0, double *z__,
int *pp, double *dmin__, double *sigma, double *desig,
double *qmax, int *nfail, int *iter, int *ndiv,
int *ieee, int *ttype, double *dmin1, double *dmin2,
double *dn, double *dn1, double *dn2, double *g,
double *tau)
{
/* System generated locals */
int i__1;
double d__1, d__2;
/* Builtin functions */
// double sqrt(double);
/* Local variables */
double s, t;
int j4, nn;
double eps, tol;
int n0in, ipn4;
double tol2, temp;
extern /* Subroutine */ int odsq4_(int *, int *, double *,
int *, int *, double *, double *, double *,
double *, double *, double *, double *, int *,
double *), odsq5_(int *, int *, double *,
int *, double *, double *, double *, double *,
double *, double *, double *, int *), odsq6_(
int *, int *, double *, int *, double *,
double *, double *, double *, double *,
double *);
// extern double odmch_(char *);
extern int odnan_(double *);
/* -- LAPACK routine (version 3.2) -- */
/* -- Contributed by Osni Marques of the Lawrence Berkeley National -- */
/* -- Laboratory and Beresford Parlett of the Univ. of California at -- */
/* -- Berkeley -- */
/* -- November 2008 -- */
/* -- LAPACK is a software package provided by Univ. of Tennessee, -- */
/* -- Univ. of California Berkeley, Univ. of Colorado Denver and NAG Ltd..-- */
/* .. Scalar Arguments .. */
/* .. */
/* .. Array Arguments .. */
/* .. */
/* Purpose */
/* ======= */
/* ODSQ3 checks for deflation, computes a shift (TAU) and calls dqds. */
/* In case of failure it changes shifts, and tries again until output */
/* is positive. */
/* Arguments */
/* ========= */
/* I0 (input) INT */
/* First index. */
/* N0 (input) INT */
/* Last index. */
/* Z (input) DOUBLE PRECISION array, dimension ( 4*N ) */
/* Z holds the qd array. */
/* PP (input/output) INT */
/* PP=0 for ping, PP=1 for pong. */
/* PP=2 indicates that flipping was applied to the Z array */
/* and that the initial tests for deflation should not be */
/* performed. */
/* DMIN (output) DOUBLE PRECISION */
/* Minimum value of d. */
/* SIGMA (output) DOUBLE PRECISION */
/* Sum of shifts used in current segment. */
/* DESIG (input/output) DOUBLE PRECISION */
/* Lower order part of SIGMA */
/* QMAX (input) DOUBLE PRECISION */
/* Maximum value of q. */
/* NFAIL (output) INT */
/* Number of times shift was too big. */
/* ITER (output) INT */
/* Number of iterations. */
/* NDIV (output) INT */
/* Number of divisions. */
/* IEEE (input) INT */
/* Flag for IEEE or non IEEE arithmetic (passed to ODSQ5). */
/* TTYPE (input/output) INT */
/* Shift type. */
/* DMIN1, DMIN2, DN, DN1, DN2, G, TAU (input/output) DOUBLE PRECISION */
/* These are passed as arguments in order to save their values */
/* between calls to ODSQ3. */
/* ===================================================================== */
/* .. Parameters .. */
/* .. */
/* .. Local Scalars .. */
/* .. */
/* .. External Subroutines .. */
/* .. */
/* .. External Function .. */
/* .. */
/* .. Intrinsic Functions .. */
/* .. */
/* .. Executable Statements .. */
/* Parameter adjustments */
--z__;
/* Function Body */
n0in = *n0;
eps = DBL_EPSILON; // odmch_("Precision");
tol = eps * 100.;
/* Computing 2nd power */
d__1 = tol;
tol2 = d__1 * d__1;
/* Check for deflation. */
L10:
if (*n0 < *i0) {
return 0;
}
if (*n0 == *i0) {
goto L20;
}
nn = (*n0 << 2) + *pp;
if (*n0 == *i0 + 1) {
goto L40;
}
/* Check whether E(N0-1) is negligible, 1 eigenvalue. */
if (z__[nn - 5] > tol2 * (*sigma + z__[nn - 3]) && z__[nn - (*pp << 1) -
4] > tol2 * z__[nn - 7]) {
goto L30;
}
L20:
z__[(*n0 << 2) - 3] = z__[(*n0 << 2) + *pp - 3] + *sigma;
--(*n0);
goto L10;
/* Check whether E(N0-2) is negligible, 2 eigenvalues. */
L30:
if (z__[nn - 9] > tol2 * *sigma && z__[nn - (*pp << 1) - 8] > tol2 * z__[
nn - 11]) {
goto L50;
}
L40:
if (z__[nn - 3] > z__[nn - 7]) {
s = z__[nn - 3];
z__[nn - 3] = z__[nn - 7];
z__[nn - 7] = s;
}
if (z__[nn - 5] > z__[nn - 3] * tol2) {
t = (z__[nn - 7] - z__[nn - 3] + z__[nn - 5]) * .5;
s = z__[nn - 3] * (z__[nn - 5] / t);
if (s <= t) {
s = z__[nn - 3] * (z__[nn - 5] / (t * (sqrt(s / t + 1.) + 1.)));
} else {
s = z__[nn - 3] * (z__[nn - 5] / (t + sqrt(t) * sqrt(t + s)));
}
t = z__[nn - 7] + (s + z__[nn - 5]);
z__[nn - 3] *= z__[nn - 7] / t;
z__[nn - 7] = t;
}
z__[(*n0 << 2) - 7] = z__[nn - 7] + *sigma;
z__[(*n0 << 2) - 3] = z__[nn - 3] + *sigma;
*n0 += -2;
goto L10;
L50:
if (*pp == 2) {
*pp = 0;
}
/* Reverse the qd-array, if warranted. */
if (*dmin__ <= 0. || *n0 < n0in) {
if (z__[(*i0 << 2) + *pp - 3] * 1.5 < z__[(*n0 << 2) + *pp - 3]) {
ipn4 = *i0 + *n0 << 2;
i__1 = *i0 + *n0 - 1 << 1;
for (j4 = *i0 << 2; j4 <= i__1; j4 += 4) {
temp = z__[j4 - 3];
z__[j4 - 3] = z__[ipn4 - j4 - 3];
z__[ipn4 - j4 - 3] = temp;
temp = z__[j4 - 2];
z__[j4 - 2] = z__[ipn4 - j4 - 2];
z__[ipn4 - j4 - 2] = temp;
temp = z__[j4 - 1];
z__[j4 - 1] = z__[ipn4 - j4 - 5];
z__[ipn4 - j4 - 5] = temp;
temp = z__[j4];
z__[j4] = z__[ipn4 - j4 - 4];
z__[ipn4 - j4 - 4] = temp;
/* L60: */
}
if (*n0 - *i0 <= 4) {
z__[(*n0 << 2) + *pp - 1] = z__[(*i0 << 2) + *pp - 1];
z__[(*n0 << 2) - *pp] = z__[(*i0 << 2) - *pp];
}
/* Computing MIN */
d__1 = *dmin2, d__2 = z__[(*n0 << 2) + *pp - 1];
*dmin2 = fmin(d__1,d__2);
/* Computing MIN */
d__1 = z__[(*n0 << 2) + *pp - 1], d__2 = z__[(*i0 << 2) + *pp - 1]
, d__1 = fmin(d__1,d__2), d__2 = z__[(*i0 << 2) + *pp + 3];
z__[(*n0 << 2) + *pp - 1] = fmin(d__1,d__2);
/* Computing MIN */
d__1 = z__[(*n0 << 2) - *pp], d__2 = z__[(*i0 << 2) - *pp], d__1 =
fmin(d__1,d__2), d__2 = z__[(*i0 << 2) - *pp + 4];
z__[(*n0 << 2) - *pp] = fmin(d__1,d__2);
/* Computing MAX */
d__1 = *qmax, d__2 = z__[(*i0 << 2) + *pp - 3], d__1 = fmax(d__1,
d__2), d__2 = z__[(*i0 << 2) + *pp + 1];
*qmax = fmax(d__1,d__2);
*dmin__ = -0.;
}
}
/* Choose a shift. */
odsq4_(i0, n0, &z__[1], pp, &n0in, dmin__, dmin1, dmin2, dn, dn1, dn2,
tau, ttype, g);
/* Call dqds until DMIN > 0. */
L70:
odsq5_(i0, n0, &z__[1], pp, tau, dmin__, dmin1, dmin2, dn, dn1, dn2,
ieee);
*ndiv += *n0 - *i0 + 2;
++(*iter);
/* Check status. */
if (*dmin__ >= 0. && *dmin1 > 0.) {
/* Success. */
goto L90;
} else if (*dmin__ < 0. && *dmin1 > 0. && z__[(*n0 - 1 << 2) - *pp] < tol
* (*sigma + *dn1) && fabs(*dn) < tol * *sigma) {
/* Convergence hidden by negative DN. */
z__[(*n0 - 1 << 2) - *pp + 2] = 0.;
*dmin__ = 0.;
goto L90;
} else if (*dmin__ < 0.) {
/* TAU too big. Select new TAU and try again. */
++(*nfail);
if (*ttype < -22) {
/* Failed twice. Play it safe. */
*tau = 0.;
} else if (*dmin1 > 0.) {
/* Late failure. Gives excellent shift. */
*tau = (*tau + *dmin__) * (1. - eps * 2.);
*ttype += -11;
} else {
/* Early failure. Divide by 4. */
*tau *= .25;
*ttype += -12;
}
goto L70;
} else if (odnan_(dmin__)) {
/* NaN. */
if (*tau == 0.) {
goto L80;
} else {
*tau = 0.;
goto L70;
}
} else {
/* Possible underflow. Play it safe. */
goto L80;
}
/* Risk of underflow. */
L80:
odsq6_(i0, n0, &z__[1], pp, dmin__, dmin1, dmin2, dn, dn1, dn2);
*ndiv += *n0 - *i0 + 2;
++(*iter);
*tau = 0.;
L90:
if (*tau < *sigma) {
*desig += *tau;
t = *sigma + *desig;
*desig -= t - *sigma;
} else {
t = *sigma + *tau;
*desig = *sigma - (t - *tau) + *desig;
}
*sigma = t;
return 0;
/* End of ODSQ3 */
} /* odsq3_ */
|
the_stack_data/154829115.c | //https://www.codechef.com/MARCH20B/problems/CHPINTU
#include<stdio.h>
int main(){
int p;
scanf("%d",&p);
int z[p];
for(int i=0;i<p;i++) {
int a;
int count1=0;
int p,w;
scanf("%d",&p);
scanf("%d",&w);
int l[p],h[p];
for(int j=0;j<p;j++) {
scanf("%d",&l[j]);
}
for(int d=0;d<p;d++) {
scanf("%d",&h[d]);
}
int max=10000000;
for(int y=1;y<=w;y++) {
a=0;
int count=0;
for(int m=0;m<p;m++) {
if(l[m]==y) {
count=count+h[m];
a=1;
}
}
if(count<max&&a==1){
max=count;
}
count=0;
}
z[i]=max;
}
for(int i=0;i<p;i++) {
printf("%d\n",z[i]);
}
}
|
the_stack_data/7780.c | /* This testcase is part of GDB, the GNU debugger.
Copyright 2016-2017 Free Software Foundation, Inc.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>. */
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
static void
marker (void)
{}
int
main (void)
{
int pid;
pid = fork ();
if (pid == 0) /* child */
{
_exit (0);
}
else
{
}
pid = fork ();
if (pid == 0) /* child */
{
marker ();
_exit (0);
}
else
{
marker ();
}
}
|
the_stack_data/3263290.c | #include <stdio.h>
#include <inttypes.h>
int main() {
int y=2, x=1;
uintptr_t p = (uintptr_t)(&x + 1);
uintptr_t q = (uintptr_t)&y;
printf("Addresses: p=%" PRIxPTR " q=%" PRIxPTR "\n",
(unsigned long)p,(unsigned long)q);
_Bool b = (p==q);
// can this be false even with identical addresses?
printf("(p==q) = %s\n", b?"true":"false");
return 0;
}
|
the_stack_data/884262.c | /*
* Copyright (c) 2018, Olivier DEBON
* All rights reserved.
* Please checkout LICENSE file.
*/
#include <X11/Xlib.h>
#include <X11/Xutil.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>
#include <unistd.h>
static Display *dpy;
static Window win;
static int screen;
static GC gc;
static Font font;
static XFontStruct *font_info;
static pthread_t thread;
static Atom wm_delete_window, wm_protocols, cm_hide_window;
static char *message = "";
void
hideWindow() {
XEvent event;
event.type = ClientMessage;
event.xclient.window = win;
event.xclient.message_type = cm_hide_window;
event.xclient.format = 8;
XSendEvent(dpy, win, False, 0, &event);
XFlush(dpy);
}
void
showMessage(char *msg) {
message = msg;
XEvent event;
event.type = Expose;
event.xexpose.count = 0;
event.xexpose.window = win;
XSendEvent(dpy, win, False, ExposureMask, &event);
XFlush(dpy);
}
static void *
mainLoop(void *arg) {
int *go = arg;
while(1) {
XEvent event;
XNextEvent(dpy, &event);
if (event.type == Expose && event.xexpose.count == 0) {
int width;
XClearWindow(dpy, win);
width = XTextWidth(font_info, message, strlen(message));
XDrawString(dpy, win, gc, (350-width)/2, 40, message, strlen(message));
XFlush(dpy);
}
if (event.type == ClientMessage) {
if (event.xclient.message_type == wm_protocols) {
if (event.xclient.data.l[0] == wm_delete_window) {
break;
}
}
if (event.xclient.message_type == cm_hide_window) {
XIconifyWindow(dpy, win, screen);
}
}
}
XCloseDisplay(dpy);
*go = 0;
exit(0);
}
int
gui_init(int *go) {
*go = 1;
XInitThreads();
dpy = XOpenDisplay(NULL);
if (dpy == NULL) {
return -1;
}
screen = DefaultScreen(dpy);
win = XCreateSimpleWindow(dpy, RootWindow(dpy, screen),
10, 10, 350, 80, 1,
BlackPixel(dpy, screen), WhitePixel(dpy, screen));
gc = XCreateGC(dpy, win, 0, 0);
XSelectInput(dpy, win, ExposureMask);
font_info = XLoadQueryFont(dpy, "-*-fixed-*-*-*-*-18-*-*-*-*-*-*-*");
if (font_info == NULL) {
font_info = XLoadQueryFont(dpy, "fixed");
}
font = font_info->fid;
XSetFont(dpy, gc, font);
XMapRaised(dpy, win);
// WM stuff
char *name = "Promys";
XStoreName(dpy, win, name);
XClassHint *classHint = XAllocClassHint();
if (classHint) {
classHint->res_name = name;
classHint->res_class = name;
}
XSetClassHint(dpy, win, classHint);
XFree(classHint);
// Some WM client message atoms
wm_protocols = XInternAtom(dpy, "WM_PROTOCOLS", False);
wm_delete_window = XInternAtom(dpy, "WM_DELETE_WINDOW", False);
XSetWMProtocols(dpy, win, &wm_delete_window, 1);
// Create our client message
cm_hide_window = XInternAtom(dpy, "PROMYS_HIDE_WINDOW", False);
pthread_create(&thread, NULL, mainLoop, go);
return 0;
}
|
the_stack_data/211079697.c | #include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
int main(int argc, char **argv)
{
if (argc == 1)
{
printf("Sleep missing opperant\n");
}
sleep(atoi(argv[1]));
} |
the_stack_data/751448.c | /*
* Copyright 2017 ARM Limited
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
#ifdef __unix__
# include <unistd.h>
#elif defined _WIN32
# include <windows.h>
#define sleep(x) Sleep(1000 * x)
#endif
// To follow normal usecases
// We need to be able to stop cleanly
// with SIGTERM and SIGINT
static void sig_handler(int sig)
{
exit(0);
}
int main(void) {
char line[256] = {0};
int int_number = 0;
int sleep_secs = 0;
// Register signal handlers for SIGINT and SIGTERM
signal(SIGINT, sig_handler);
signal(SIGTERM, sig_handler);
while (1)
{
int retcode = 0;
//if (getline(&line, NULL, stdin) == -1) {
if (fgets(line,254, stdin)) {
printf("[DBG ][TRC ]: '%s'\r\n", line);
} else {
continue;
}
// Very simple command prompt for testing purpose
if( strncmp(line, "ping", 4) == 0 ) {
puts("Pinging [fd00:db8::2c12:a6aa:2ea8:e53d] with 56 bytes of data:");
puts("Reply[0001] from fd00:db8::2c12:a6aa:2ea8:e53d: bytes=56 time<0ms");
puts("Ping statistics for fd00:db8::2c12:a6aa:2ea8:e53d:");
puts("Packets: Sent = 1, Received: 1, Lost = 0 (0.000000 loss),");
puts("Approximate roung trip times in milli-seconds:");
puts("Minimum = 0ms, Maximum = 0ms, Average = 0ms");
}
else if( strncmp(line, "trace", 5) == 0 ) {
printf("[DBG ][TRC ]:%s\r\n", line+5);
}
else if( strncmp(line, "set ", 4) == 0 ) {
}
else if( strncmp(line, "echo off", 8) == 0 ) {
}
else if( strncmp(line, "exit 1", 8) == 0 ) {
puts("exit.."); /* prints !!!Hello World!!! */
break;
}
else if( strncmp(line, "if", 2) == 0 ) {
}
else if( sscanf(line, "retcode %d", &int_number) == 1 ) {
retcode = int_number;
}
else if( strncmp(line, "exit", 4) == 0 ) {
return 0;
}
else if( strncmp(line, "crash", 5) == 0 ) {
abort();
}
else if( sscanf(line, "sleep %d", &sleep_secs) == 1 ) {
sleep(sleep_secs);
}
else if( strncmp(line, "echo", 4) == 0 ) {
puts(line + 4);
}
else {
puts("cmd success"); /* prints !!!Hello World!!! */
}
printf( "retcode: %d\r\n", retcode );
fflush( stdout );
//todo loppu viela c:lla: if line.startswith("exit()"): ...
}
return 0;
}
|
the_stack_data/8796.c | #include <stdio.h>
#include <sys/socket.h>
#include <stdlib.h>
#include <unistd.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <string.h>
#define PORT 8080
#define SVR_IP_ADDR "127.0.0.1"
int main( int argc, char* argv[] ){
int n, ptr = 0, clientSocket;
char buffer[1024];
struct sockaddr_in serverAddr;
socklen_t addr_size;
memset(buffer, '\0', 1024);
// create the socket
if (-1 == (clientSocket = socket(PF_INET, SOCK_STREAM, 0))) {
strcpy( buffer, "socket error" );
} else {
// configure the server address
serverAddr.sin_family = AF_INET;
serverAddr.sin_port = htons(PORT);
serverAddr.sin_addr.s_addr = inet_addr(SVR_IP_ADDR);
memset(serverAddr.sin_zero, '\0', sizeof serverAddr.sin_zero);
// onnect to the server
addr_size = sizeof serverAddr;
if (-1 == connect(clientSocket, (struct sockaddr *) &serverAddr, addr_size)) {
strcpy( buffer, "connect error: enguage server down?" );
} else {
// read the args into a string
if (argc>1) { // GET
while (--argc && ++argv) {
// strip '.' from last arg
if (argc == 1) {
int len = strlen( argv[ 0 ]);
if (len && argv[ 0 ][ len - 1 ] == '.')
argv[ 0 ][ len - 1 ] = '\0';
}
strcat( buffer, argv[ 0 ]);
if (argc>1) strcat( buffer, " " ); // add sep
}
strcat( buffer, "\n" );
} else { // POST
ptr = 0;
while (0 < (n = read( 0, buffer+ptr, 1024 - ptr )))
ptr += n;
}
// send teh string to the server
if (-1 == send(clientSocket, buffer, 1024, 0)) {
strcpy( buffer, "send() error: enguage server down?" );
} else {
// read the reply
memset(buffer, '\0', 1024);
ptr = 0;
while (0 < (n = recv(clientSocket, buffer+ptr, 1024 - ptr, 0)))
ptr += n;
if (-1 == n) strcpy( buffer, "recv() error: enguage server down?" );
} } }
// print it:- http-style
printf("Content-type: text/plain\n\n%s",buffer);
return 0;
}
|
the_stack_data/96719.c | #include <stdio.h>
int main (){
int a,b,c,d;
scanf("%d %d %d %d",&a,&b,&c,&d);
if( (a<=(b+c)) && (b<=(a+c)) && (c<=(b+a)) ){
printf("S\n");
} else if( (a<=(b+d)) && (b<=(a+d)) && (d<=(b+a)) ) {
printf("S\n");
} else if( (a<=(c+d)) && (c<=(a+d)) && (d<=(a+c)) ) {
printf("S\n");
} else if( (b<=(c+d)) && (c<=(b+d)) && (d<=(b+c)) ) {
printf("S\n");
} else{
printf("N\n");
}
return 0;
} |
the_stack_data/170453174.c | /* empty source code file */
#include <stdio.h>
|
the_stack_data/50691.c | #include <stdio.h>
#include <malloc.h>
int nextPrime(int i, char *sieve, int max) {
while(i < max && !sieve[i]) {
i++;
}
return i;
}
void setNotPrime(int i, char *sieve, int max) {
int j;
for(j = i; j < max; j += i) {
sieve[j] = 0;
}
}
int main(int argc, char**argv) {
int n = atoi(argv[1]);
char *sieve = (char*) malloc(sizeof(char));
int i;
for(i = 0; i < n; i++) {
sieve[i] = 1;
}
for(i = 2; i < n; i = nextPrime(i, sieve, n)) {
printf("%d ", i);
setNotPrime(i, sieve, n);
}
return 0;
}
|
the_stack_data/220456138.c | #include <stdio.h>
#include <time.h>
#define BYTE unsigned char
#define UINT unsigned long
#define BITS 25
#define HASHSIZE 32
#define SEED 0xFAFAECECFAFAECEC
UINT firstrand = 2458719153079158768;
UINT firstb = 4631534797403582785;
UINT firstv = 3523455478921636871;
UINT mapSizeBits = BITS;
UINT mapSize = 1 << BITS;
UINT passes = 5;
BYTE bytemap[1 << BITS];
void generate() {
UINT offset = SEED ^ firstrand;
UINT b = SEED ^ firstb;
UINT v = firstv;
UINT mask = mapSize - 1;
long rand(UINT i) {
offset = offset<<9 ^ offset>>1 ^ offset>>7 ^ b;
v = (UINT)(bytemap[(offset^b)&mask]) ^ v<<8 ^ v>>1;
b = v<<7 ^ v<<13 ^ v<<33 ^ v<<52 ^ b<<9 ^ b>>1;
return (long)((UINT)(offset) & (UINT)(mask));
}
for (int i = 0; i < mapSize; i++) {
bytemap[i] = (BYTE)i;
}
for (int loops = 0; loops < passes; loops++) {
//printf("Pass %d\n", loops);
for (int i = 0; i < mapSize; i++) {
long j = rand(i);
BYTE tmp = bytemap[i];
bytemap[i] = bytemap[j];
bytemap[j] = tmp;
}
}
}
BYTE * hash(BYTE src[], int len) {
UINT hs[HASHSIZE];
for (int i = 0; i < HASHSIZE; i++) {
hs[i] = 0;
}
UINT as = SEED;
UINT s1 = 0, s2 = 0, s3 = 0;
UINT mk = mapSize -1;
UINT B(UINT v) {
return (UINT)(bytemap[v&mk]);
}
BYTE b(UINT v) {
return bytemap[v&mk];
}
void faststep(UINT v2, UINT idx) {
UINT b = B(as ^ v2);
as = as<<7 ^ as>>5 ^ v2<<20 ^ v2<<16 ^ v2 ^ b<<20 ^ b<<12 ^ b<<4;
s1 = s1<<9 ^ s1>>3 ^ hs[idx];
hs[idx] = s1 ^ as;
UINT t1 = s1;
UINT t2 = s2;
UINT t3 = s3;
s1 = t3;
s2 = t1;
s3 = t2;
}
void step(UINT v2, UINT idx) {
s1 = s1<<9 ^ s1>>1 ^ as ^ B(as>>5^v2)<<3;
s1 = s1<<5 ^ s1>>3 ^ B(s1^v2)<<7;
s1 = s1<<7 ^ s1>>7 ^ B(as^s1>>7)<<5;
s1 = s1<<11 ^ s1>>5 ^ B(v2^as>>11^s1)<<27;
hs[idx] = s1 ^ as ^ hs[idx]<<7 ^ hs[idx]>>13 ;
as = as<<17 ^ as>>5 ^ s1 ^ B(as^s1>>27^v2)<<3 ;
as = as<<13 ^ as>>3 ^ B(as^s1)<<7;
as = as<<15 ^ as>>7 ^ B(as>>7^s1)<<11 ;
as = as<<9 ^ as>>11 ^ B(v2^as^s1)<<3 ;
s1 = s1<<7 ^ s1>>27 ^ as ^ B(as>>3)<<13 ;
s1 = s1<<3 ^ s1>>13 ^ B(s1^v2)<<11 ;
s1 = s1<<8 ^ s1>>11 ^ B(as^s1>>11)<<9 ;
s1 = s1<<6 ^ s1>>9 ^ B(v2^as^s1)<<3 ;
as = as<<23 ^ as>>3 ^ s1 ^ B(as^v2^s1>>3)<<7;
as = as<<17 ^ as>>7 ^ B(as^s1>>3)<<5;
as = as<<13 ^ as>>5 ^ B(as>>5^s1)<<1;
as = as<<11 ^ as>>1 ^ B(v2^as^s1)<<7;
s1 = s1<<5 ^ s1>>3 ^ as ^ B(as>>7^s1>>3)<<6;
s1 = s1<<8 ^ s1>>6 ^ B(s1^v2)<<11;
s1 = s1<<11 ^ s1>>11 ^ B(as^s1>>11)<<5;
s1 = s1<<7 ^ s1>>5 ^ B(v2^as>>7^as^s1)<<17;
s2 = s2<<3 ^ s2>>17 ^ s1 ^ B(as^s2>>5^v2)<<13;
s2 = s2<<6 ^ s2>>13 ^ B(s2)<<11;
s2 = s2<<11 ^ s2>>11 ^ B(as^s1^s2>>11)<<23;
s2 = s2<<4 ^ s2>>23 ^ B(v2^as>>8^as^s2>>10)<<1;
s1 = s2<<3 ^ s2>>1 ^ hs[idx] ^ v2;
as = as<<9 ^ as>>7 ^ s1>>1 ^ B(s2>>1^hs[idx])<<5;
UINT t1 = s1;
UINT t2 = s2;
UINT t3 = s3;
s1 = t3;
s2 = t1;
s3 = t2;
}
UINT idx = 0;
for (int i = 0; i < len; i++) {
if (idx > HASHSIZE) {
idx = 0;
}
faststep(src[i], idx);
idx++;
}
idx = 0;
for (int i = 0; i < len; i++) {
if (idx > HASHSIZE) {
idx = 0;
}
step(src[i], idx);
idx++;
}
static BYTE bytes[HASHSIZE];
for (int i = 0; i < HASHSIZE; i++) {
bytes[i] = 0;
}
for (int i = HASHSIZE - 1; i >= 0; i--) {
step(hs[i], i);
bytes[i] = b(as) ^ b(hs[i]);
}
return bytes;
}
int main() {
//mapSize = 1 << mapSizeBits;
//printf("%lX\n", SEED);
//printf("%lu\n", mapSize);
clock_t t;
t = clock();
generate();
t = clock() - t;
double time_taken = ((double)t)/CLOCKS_PER_SEC;
printf("generate() took %f seconds to execute \n", time_taken);
BYTE src[32] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
BYTE * hs = src;
t = clock();
BYTE * res;
for (int i = 0; i < 100000; i++) {
hs = hash(hs, 32);
}
t = clock() - t;
time_taken = ((double)t)/CLOCKS_PER_SEC;
printf("hash() took %f seconds to execute \n", time_taken);
for (int i = 0; i < HASHSIZE; i++) {
printf("%X", *(hs+i));
}
printf("\n");
return 0;
} |
the_stack_data/51519.c | #include <stdio.h>
#include <string.h>
int main() {
int k;
char s3[100]="fucckyou";
for(k=7;k<=strlen(s3);k++) s3[k]=s3[k+1];
printf("%s",s3);
}
|
the_stack_data/97491.c | extern const unsigned char ESTabBarController_swiftVersionString[];
extern const double ESTabBarController_swiftVersionNumber;
const unsigned char ESTabBarController_swiftVersionString[] __attribute__ ((used)) = "@(#)PROGRAM:ESTabBarController_swift PROJECT:Pods-1" "\n";
const double ESTabBarController_swiftVersionNumber __attribute__ ((used)) = (double)1.;
|
the_stack_data/130962.c | #include <stdlib.h>
#if defined(__STDC__) || defined(__cplusplus)
int compare_short(const void *a, const void *b)
#else
int compare_short(a,b)
void *a, *b;
#endif
{
short sa = *(short*)a, sb = *(short*)b;
if (sa < sb) return(-1);
else if (sa > sb) return (1);
else return (0);
}
#if defined(__STDC__) || defined(__cplusplus)
int compare_int(const void *a, const void *b)
#else
int compare_int(a,b)
void *a, *b;
#endif
{
int ia = *(int*)a, ib = *(int*)b;
if (ia < ib) return(-1);
else if (ia > ib) return (1);
else return (0);
}
#if defined(__STDC__) || defined(__cplusplus)
int sort_short(short *v, int count)
#else
int sort_short(v,count)
short *v;
int count;
#endif
{
qsort(v, count, sizeof(short), compare_short);
return 1;
}
#if defined(__STDC__) || defined(__cplusplus)
int sort_int(int *v, int count)
#else
int sort_int(v,count)
int *v;
int count;
#endif
{
qsort(v, count, sizeof(int), compare_int);
return 1;
}
|
the_stack_data/167330586.c | #include <stdio.h>
void fill_data(void);
int get_int(void);
int get_name(char [], int);
int get_std_num(int[], int);
int get_scores(float [], int);
float get_avg(float [], int, int);
void copy_arr(float from[], float to[], int len);
void simultaneous_sort(float [], int [], float [], int[], int, int);
int power(int, int);
int len_int(int);
int main(void) {
fill_data();
return 0;
}
int get_int(void) {
// get a single integer until new line
int c, res;
res = 0;
while ((c = getchar()) != '\n' && c >= '0' && c <= '9') {
res = 10 * res + c - '0';
}
return res;
}
int get_name(char names[], int pos_names) {
// get a name and increase the position by the length of the name
int c;
while ((c = getchar()) != '\n') {
names[pos_names] = c;
pos_names++;
}
names[pos_names] = '\0'; // terminate the name
pos_names++;
return pos_names;
}
int get_std_num(int std_num[], int std_num_pos) {
// get student numbers and return len of the std_num array
std_num[std_num_pos] = get_int();
std_num_pos++;
return std_num_pos;
}
int power(int a, int b) {
// calculate power of a ^ b
int res, i;
res = 1;
for (i = 0; i < b; ++i) {
res *= a;
}
return res;
}
int len_int(int num) {
// calculate the length of a number
int len;
len = 1;
while (num / 10 != 0) {
num /= 10;
len++;
}
return len;
}
int get_scores(float scores[], int score_pos) {
// gets scores and returns the number of scores
int c, dec;
float res, is_float;
res = dec = 0;
is_float = 0;
while ((c = getchar()) != '\n') {
if (c != ' ' && c != '\t' && c >= '0' && c <= '9' && !is_float) {
res = 10 * res + c - '0';
}
else if (c == '.') {
is_float = 1;
}
else if (c != ' ' && c != '\t' && c >= '0' && c <= '9' && is_float) {
dec = 10 * dec + c - '0';
}
else {
scores[score_pos] = res + (float) dec / power(10, len_int(dec));
score_pos++;
res = 0;
dec = 0;
is_float = 0;
}
}
scores[score_pos] = res + (float) dec / power(10, len_int(dec));
score_pos++;
return score_pos;
}
float get_avg(float scores[], int start, int end) {
// get average of the score from index start to index end
int i;
float sum;
sum = 0;
for (i = start; i < end; ++i) {
sum += scores[i];
}
return sum / (end - start);
}
void copy_arr(float from[], float to[], int len) {
int i;
for (i = 0; i < len; ++i) {
to[i] = from[i];
}
}
void simultaneous_sort(float a1[], int a2[], float scores[], int n_scores[], int len, int score_len) {
float res[1000];
// sort two same length arrays with respect to array 1
int index_n_scores[1000], len_index; // an array for index of n_score before sort
len_index = 0;
index_n_scores[len_index] = 0; // assume that the 0th index is sort
len_index++;
if (len < 1) {
return;
}
// sort a2 and index_n_score based on a1 by insertion sort
int i;
for (i = 1; i < len; ++i) {
index_n_scores[len_index] = i; // add index to end of the array
len_index++;
float key1;
int j, key2, key3;
key1 = a1[i];
key2 = a2[i];
key3 = index_n_scores[i];
for (j = i - 1; j >= 0 && key1 > a1[j]; --j) {
a1[j + 1] = a1[j];
a2[j + 1] = a2[j];
index_n_scores[j + 1] = index_n_scores[j];
}
a1[j + 1] = key1;
a2[j + 1] = key2;
index_n_scores[j + 1] = key3;
}
// now based on index_n_score fill the res array with scores
int len_res;
len_res = 0; // position an the len of res array
for (i = 0; i < score_len; ++i) {
int j, lower_bound;
lower_bound = 0; // starting index in the res array
for (j = 0; j < index_n_scores[i]; ++j) {
lower_bound += n_scores[j];
}
// fill the res array
int k;
for (k = 0; k < n_scores[index_n_scores[i]]; ++k) {
res[len_res] = scores[lower_bound + k];
len_res++;
}
}
copy_arr(res, scores, score_len);
}
void fill_data(void) {
int n;
char names[1000]; // for names
float scores[1000]; // for scores
int n_sc[10000]; // number of each student scores
int std_num[1000]; // student numbers
printf("How many students should I take?\n");
n = get_int();
int i;
int pos_names, std_num_pos, scores_pos, n_sc_pos; //position of pointer in names array
pos_names = std_num_pos = scores_pos = n_sc_pos = 0; // at beginning
for (i = 1; i <= n; ++i) {
printf("Ok. What is the name of student %d?\n", i);
pos_names = get_name(names, pos_names);
printf("What are his/her scores?\n");
int last_pos; // for number of scores
last_pos = scores_pos;
scores_pos = get_scores(scores, scores_pos);
n_sc[n_sc_pos] = scores_pos - last_pos;
n_sc_pos++;
printf("What is student number?\n");
std_num_pos = get_std_num(std_num, std_num_pos);
printf("Done!\n");
}
// calculate average of scores
float avg[1000];
int j, k;
for (j = k = 0; j < std_num_pos; ++j) {
avg[j] = get_avg(scores, k, k + n_sc[j]);
k += n_sc[j];
}
simultaneous_sort(avg, std_num, scores, n_sc, std_num_pos, scores_pos);
printf("The Result:\n");
for (j = 0; j < std_num_pos; ++j) {
printf("%d %.2f\n", std_num[j], avg[j]);
}
} |
the_stack_data/61074613.c | /*
* Math Tools in C
* nPr
*
* https://afaan.ml/math-tools-in-c
*
* (c) Afaan Bilal (https://google.com/+AfaanBilal)
*
*/
#include <stdio.h>
unsigned long int factorial(unsigned int n)
{
return (n == 0) ? 1 : n * factorial(n - 1);
}
unsigned long int npr(unsigned int n, unsigned int r)
{
return factorial(n) / factorial(n - r);
}
int main()
{
unsigned int n, r;
printf("Enter n and r (space separated): ");
scanf("%d %d", &n, &r);
printf("nPr for n = %d and r = %d is %d", n, r, npr(n, r));
getch();
return 0;
}
|
the_stack_data/89655.c | /* { dg-do compile } */
/* { dg-options "-O3 -g" } */
/* { dg-require-effective-target ptr32plus } */
int d0, sj, v0, rp, zi;
void
zn(void)
{
if (v0 != 0)
{
int *js, *r3;
int pm, gc;
for (gc = 0; gc < 1; ++gc)
{
sj = 1;
while (sj != 0)
;
}
r3 = ±
*js = (long)&gc;
ka:
for (d0 = 0; d0 < 2; ++d0)
{
d0 = zi;
if (zi)
for (pm = 2; pm != 0; --pm)
;
}
while (*r3 != 0)
{
while (pm)
;
++r3;
}
}
rp = 0;
goto ka;
}
|
the_stack_data/175143516.c | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_strncmp.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: aborboll <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2019/09/12 13:46:41 by aborboll #+# #+# */
/* Updated: 2019/09/16 15:01:51 by aborboll ### ########.fr */
/* */
/* ************************************************************************** */
int ft_strncmp(char *s1, char *s2, unsigned int n)
{
unsigned int i;
i = 0;
while (s1[i] != '\0' && s2[i] != '\0' && s1[i] == s2[i] && i < n - 1)
i++;
return (s1[i] - s2[i]);
}
|
the_stack_data/589844.c | #include <stdio.h>
#include <sqlite3.h>
#include <string.h>
void print_result(sqlite3_stmt *stmt);
int main (int argc,char **argv){
sqlite3 *db;
sqlite3_stmt *stmt;
int rc;
rc=sqlite3_open("openflights.sql",&db);
if (rc) {
fprintf(stderr,"Can't open database: %s\n",sqlite3_errmsg(db));
sqlite3_close(db);
return(1);
}
char *sql_qry ="select r.Source_airport,r.Destination_airport from airlines a1,routes r where a1.active='Y'and a1.Airline_ID=r.Airline_ID and (a1.IATA <> '/N' or a1.ICAO <> '/N' or a1.Callsign <> '/N' or a1.country <> '/N') except select r1.Source_airport,r1.Destination_airport from airlines a,routes r1,routes r2 where r1.Source_airport_ID== r2.Destination_airport_ID and a.active='Y'and a.Airline_ID=r1.Airline_ID and a.Airline_ID=r2.Airline_ID and r1.Destination_airport_ID ==r2.Source_airport_ID except select r1.Source_airport,r1.Destination_airport from routes r1,airports ap1,airports ap2 where r1.Source_airport_ID=ap1.Airport_ID and r1.Destination_airport_ID=ap2.Airport_ID and ap1.country==ap2.country;";
rc=sqlite3_prepare_v2(db, sql_qry, -1, &stmt, 0);
if (rc!=SQLITE_OK) {
fprintf(stderr, "Preparation failed: %s\n",sqlite3_errmsg(db));
sqlite3_close(db);
return 1;
}
print_result(stmt);
sqlite3_finalize(stmt); //always finalize a statement
sqlite3_close(db);
return 0;
}
void print_result(sqlite3_stmt *stmt){
int rc;
while((rc = sqlite3_step(stmt)) == SQLITE_ROW) {
int col;
for(col=0; col<sqlite3_column_count(stmt)-1; col++) {
printf("%s|", sqlite3_column_text(stmt, col));
}
printf("%s", sqlite3_column_text(stmt, col));
printf("\n");
}
}
|
the_stack_data/20450269.c | #include <stdio.h>
int wcount(char *s)
{
int k = 0, test = 0, i;
for(i = 0; s[i] != '\0'; i++)
if (s[i] != ' ')
test = 1;
if (test == 0)
return k;
if (s[0] != ' ')
k++;
for(i = 0; s[i] != '\0';i++)
if (s[i] == ' ' && s[i+1] != ' ')
k++;
if (s[i-1] == ' ')
return k - 1;
else
return k;
}
int main(int argc, char **argv)
{
char str[10000];
gets(str);
printf("%d\n", wcount(str));
return 0;
} |
the_stack_data/248581968.c | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/uio.h>
static void dump_iovec(const struct iovec *v, size_t len) {
fprintf(stderr, "Dumping struct iovec at %p:\n", v);
for (size_t i = 0; i < len; ++i) {
fprintf(stderr, " [%zu]: %p with len=%zu\n", i, v[i].iov_base, v[i].iov_len);
}
}
int main(int argc, const char *argv[]) {
char *buffer1 = malloc(32 * sizeof(char));
if (!buffer1) {
fputs(stderr, "Failed to allocate buffer1!");
return 1;
}
fprintf(stderr, "buffer1 = %p\n", buffer1);
char *buffer2 = malloc(16 * sizeof(char));
if (!buffer2) {
fputs(stderr, "Failed to allocate buffer2!");
return 1;
}
fprintf(stderr, "buffer2 = %p\n", buffer2);
char *str_part1 = strcpy(buffer1, "Hello");
char *str_part2 = strcpy(buffer1 + strlen(str_part1) + 1, " world");
char *str_part3 = strcpy(buffer2, " again!\n");
struct iovec iov[3];
iov[0].iov_base = str_part1;
iov[0].iov_len = strlen(str_part1);
iov[1].iov_base = str_part2;
iov[1].iov_len = strlen(str_part2);
iov[2].iov_base = str_part3;
iov[2].iov_len = strlen(str_part3);
dump_iovec(iov, 3);
ssize_t nwritten = writev(STDOUT_FILENO, iov, 3);
fprintf(stderr, "Written %ld bytes\n", nwritten);
dump_iovec(iov, 3);
free(buffer2);
free(buffer1);
return 0;
}
|
the_stack_data/1016506.c | volatile int x, x1, y, y2, z, z1;
int main(int argc, char **argv)
{
x1 = __builtin_bswap16(x);
y2 = __builtin_bswap32(y);
z1 = __builtin_bswap64(z);
}
|
the_stack_data/237643511.c | #include <stdio.h>
int main(){
char a[40];
printf("Digite o seu nome: ");
scanf("%s", &a); // -> Vai pegar so o PRIMEIRO nome
printf("Ola %s, prazer em conhece-lo", a);
return 0;
}
|
the_stack_data/1150877.c | //Algoritimo que le 5 valores e identifica o numero de valores negativos
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main()
{
system("cls");
int cont, cont_neg = 0;
float v1;
for (cont = 0; cont < 5; cont++)
{
printf("\n\nPor favor insira um numero real: ");
scanf("%f", &v1);
if (v1 < 0)
{
cont_neg = cont_neg + 1;
}
}
printf("\n\n O total de numeros negativos digitados foi de %i", cont_neg);
printf("\n\n");
return 0;
} |
the_stack_data/69313.c | /*BEGIN_LEGAL
Intel Open Source License
Copyright (c) 2002-2017 Intel Corporation. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer. Redistributions
in binary form must reproduce the above copyright notice, this list of
conditions and the following disclaimer in the documentation and/or
other materials provided with the distribution. Neither the name of
the Intel Corporation nor the names of its contributors may be used to
endorse or promote products derived from this software without
specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE INTEL OR
ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
END_LEGAL */
// This little application tests calling application functions.
//
#include <stdio.h>
#include <limits.h>
#if defined (TARGET_WINDOWS)
#define EXPORT_SYM __declspec( dllexport )
#else
#define EXPORT_SYM extern
#endif
EXPORT_SYM void * Bar4( long one, long two )
{
printf(" Hello from Bar4: one = %ld, two = %ld!\n ", one, two );
return (void *)0xc0decafe00;
}
EXPORT_SYM void * Blue4( long one, long two )
{
printf(" Hello from Blue4: one = %ld, two = %ld!\n ", one, two );
return (void *)0xdeadbeef00;
}
EXPORT_SYM short Bar13( short s1, short s2, unsigned short us1,
long l1, long l2, unsigned long ul1,
short s3, short s4, unsigned short us2,
long l3, long l4, unsigned long ul2 )
{
printf(" Hello from Bar13: \n");
printf(" s1 = %hd, s2 = %hd, us1 = %hu\n ", s1, s2, us1 );
printf(" s3 = %hd, s4 = %hd, us2 = %hu\n ", s3, s4, us2 );
printf(" l1 = %ld, l2 = %ld, ul1 = %lu\n ", l1, l2, ul1 );
printf(" l3 = %ld, l4 = %ld, ul2 = %lu\n ", l3, l4, ul2 );
return 1;
}
EXPORT_SYM short Green13( short s1, short s2, unsigned short us1,
long l1, long l2, unsigned long ul1,
short s3, short s4, unsigned short us2,
long l3, long l4, unsigned long ul2 )
{
printf(" Green13: ");
if ( s1 == SHRT_MIN &&
s2 == SHRT_MAX &&
us1 == USHRT_MAX &&
l1 == LONG_MIN &&
l2 == LONG_MAX &&
ul1 == ULONG_MAX &&
s3 == SHRT_MIN &&
s4 == SHRT_MAX &&
us2 == USHRT_MAX &&
l3 == LONG_MIN &&
l4 == LONG_MAX &&
ul2 == ULONG_MAX )
{
printf(" Test passed\n" );
return 1;
}
else
{
printf(" Test failed\n" );
if ( s1 != SHRT_MIN )
printf (" s1 != SHRT_MIN\n");
if ( s2 != SHRT_MAX )
printf(" s2 != SHRT_MIN\n");
if ( us1 != USHRT_MAX )
printf(" us1 != USHRT_MAX\n");
if ( l1 != LONG_MIN )
printf(" l1 != LONG_MIN\n");
if ( l2 != LONG_MAX )
printf(" l2 != LONG_MAX\n");
if ( ul1 != ULONG_MAX )
printf(" ul1 == ULONG_MAX\n");
if ( s3 != SHRT_MIN )
printf(" s3 != SHRT_MIN\n");
if ( s4 != SHRT_MAX )
printf(" s4 != SHRT_MAX\n");
if ( us2 != USHRT_MAX )
printf(" us2 != USHRT_MAX\n");
if ( l3 != LONG_MIN )
printf(" l3 != LONG_MIN\n");
if ( l4 != LONG_MAX )
printf(" l4 != LONG_MAX\n");
if ( ul2 != ULONG_MAX )
printf(" ul2 != LONG_MAX\n");
}
return 1;
}
|
the_stack_data/111078492.c | #include <stdio.h>
#include <stdlib.h>
int main()
{
char lista[5][30] , pesquisa[30];
int i;
printf ("Preencha uma lista com 5 nomes \n\n");
for (i=0;i<5;i++)
{
printf ("\n NOME %d : ",i+1);
fgets (lista[i],30,stdin);
}
printf ("\n\n");
for (i=0;i<5;i++)
{
printf (" [%d] = %s",i+1,lista[i]);
}
printf ("\n\n QUE NOME VOCE PROCURA ? ");
fgets(pesquisa,30,stdin);
for (i=0;i<5;i++)
{
if (strcmp(pesquisa,lista[i])==0)
{
printf("\n O elemento %s esta na posicao : %d \n",pesquisa,i+1);
}
}
}
|
the_stack_data/237642699.c | #include <stdio.h> /*Autorise l'emploi de printf et de scanf.*/
/*!\author Lilian Naretto <[email protected]>
\date 15 octobre 2019
\file tp3q3.c
\brief question 3 du tp3
\version 0.1 premier jet*/
/*! \fn int echange(int nb1,int nb2)
\param int nb1
\param int nb2
\brief echange la valeur de deux variables*/
int echange(int nb1,int nb2){
int tmp;
printf("avant echange\n");
printf("nb1=%d\n",nb1);
printf("nb2=%d\n",nb2);
tmp=nb1;
nb1=nb2;
nb2=tmp;
printf("apres echange\n");
printf("nb1=%d\n",nb1);
printf("nb2=%d\n",nb2);
}
/*! \fn int main(int argc, char** argv)
\param argc nombre d'arguments en entrée
\param argv valeur des arguments en entrée
\return 0 si tout c'est bien passé
\brief échange la valeur de deux variables*/
int main(int argc, char** argv){
int nb1;
int nb2;
nb1=5;
nb2=7;
printf("avant appel de la fonction\n");
printf("nb1=%d\n",nb1);
printf("nb2=%d\n",nb2);
printf("appel de la fonction echange\n");
echange(nb1,nb2);
printf("apres appel de la fonction\n");
printf("nb1=%d\n",nb1);
printf("nb2=%d\n",nb2);
return 0;
} |
the_stack_data/67326600.c | #include <stdio.h>
/*
Napišite funkciju sortiraj koja slaže po veličini niz realnih brojeva,
pri čemu dimenzija niza nije unaprijed poznata nego predstavlja jedan od parametara funkcije.
Napravite kratak glavni program koji testira ovu funkciju. Primjer algoritma za sortiranje nalazi se na početku Tutorijala 6.
Pri rješavanju zadatka obavezno koristiti pokazivačku aritmetiku.*/
void sortiraj(double *niz, int vel){
double *pok, *pomocni;
pok=niz;
pomocni=niz+1;
while(pok<niz+vel){
while(pomocni<niz+vel)
{
if(*pok>*pomocni){
double temp;
temp=*pok;
*pok=*pomocni;
*pomocni=temp;
}
pomocni++;
}
pok++;
pomocni=pok;
}
}
int main() {
int i; int vel;
double niz[100];
printf("Unesi niz za sortat: ");
for(i=0;;i++)
{
scanf("%lf", &niz[i]);
if(niz[i]==-1) break;
}
vel=i;
sortiraj(niz, vel);
for(i=0;i<vel;i++)
{
printf("%g ", niz[i]);
}
return 0;
}
|
the_stack_data/237641842.c | #include <stdio.h>
#include <string.h>
#define NLEN 30
struct namect {
char fname[NLEN];
char lname[NLEN];
int letters;
};
struct namect getinfo();
struct namect makeinfo(struct namect);
void showinfo(struct namect);
char * s_gets(char *, int);
int main(void)
{
struct namect person;
person = getinfo();
person = makeinfo(person);
showinfo(person);
return 0;
}
struct namect getinfo()
{
struct namect pst;
printf("Enter your first name: ");
s_gets(pst.fname, NLEN);
printf("Enter your last name: ");
s_gets(pst.lname, NLEN);
return pst;
}
struct namect makeinfo(struct namect pst)
{
pst.letters = strlen(pst.fname) +
strlen(pst.lname);
return pst;
}
void showinfo(struct namect pst)
{
printf("%s %s, your name contains %d letters.\n",
pst.fname, pst.lname, pst.letters);
}
char * s_gets(char * st, int n)
{
char *ret_val;
char *find;
ret_val = fgets(st, n, stdin);
if (ret_val)
{
find = strchr(st, '\n');
if (find)
*find = 0;
else
while (getchar() != '\n')
continue;
}
return ret_val;
} |
the_stack_data/175141845.c | #include <stdio.h>
/* STUDENT NAME : MOHAMAD FARIS AIMAN BIN MOHD FAIZAL MATRIC NO : 201155
DESCRIPTION : SIMPLE PROGRAM THAT READS MARKS FROM 0-100 FROM USER IN A LOOP AND RETURNS EACH GROUP OF GRADE UNTIL INPUT N IS READ.
*/
int main()
{
int mark,a,b,c,d,e;
char input;
c = 0;
d = 0;
e = 0;
do{
printf("Enter marks:");
scanf("%d",&mark);
if (mark >= 80 && mark <=100)
{
printf("Correspending grade is A\n");
a++;
}
else if(mark >= 60 && mark <= 79)
{
printf("Correspending grade is B\n");
b++;
}
else if (mark >= 50 && mark <=59)
{
printf("Correspending grade is C\n");
c++;
}
else if (mark >= 40 && mark <= 49)
{
printf("Correspending grade is D\n");
d++;
}
else if (mark == 999)
{
printf("Invalid.\n");
printf("Analysis:\n");
printf("%d student(s) obtained A\n",a);
printf("%d student(s) obtained B\n",b);
printf("%d student(s) obtained C\n",c);
printf("%d student(s) obtained D\n",d);
printf("%d student(s) obtained E\n",e);
printf("Do you want to continue: YES- Y or NO - N:");
scanf(" %c",&input);
}
else if (mark >= 0 && mark <40)
{
printf("Correspending grade is E\n");
e++;
}
}while(input!='n');
return 0;
} |
the_stack_data/162879.c | /*******************************************************************************
*
* log-user-session:
* - creates a full log of the user session
*
* Usage:
* log-user-session [command]
*
*
* The MIT License (MIT)
*
* Copyright (c) 2014 Open Systems AG
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
*
* Written by Konrad Bucheli ([email protected]), January 2014
*
*
* Process Hierarchy
*
* sshd -> log-user-session (forward data and merge for log - non-blocking I/O)
* \ \
* \ |-> bash
* \
* |-> log-user-session (write log to file - blocking I/O)
*
*
* Data Flow
*
* I/O from bash is piped to log-user-session which does I/O to sshd and merges
* all data and forwards it to another process which is writing the log file.
* If that second process fails for whatever reason (disk full, etc), the user
* session still continues without logging.
*
*
* Data Stored
*
* For interactive shells we do not store input. Input is echoed by
* the shell except for passwords and those should not be logged.
* On non-interactive use first the command to be executed is logged.
*
*
* Data Structure
*
* The I/O data is stored in a buffer structure which is in two linked list at the
* same time: first in the specific I/O channel (stdin, stdout, stderr) and second
* in a list with all merged I/O to be logged
*
*
* Error Handling
*
* If there is a problem,, we print the error on stderr and try to continue with
* least impact on the user session, even if the session might not be recorded
* correctly.
*
*
* Login Shell
*
* A login shell is only started if log-user-session has been started like a login
* shell (e.g. because it is configured in /etc/passwd) or if there is no command
* provided and there is no prompt (PS1 environment variable) defined yet (e.g.
* started by ForcedCommand via ssh).
* If it is started on a shell (e.g. for testing purposes) or there is a specific
* command provided to execute, no login shell should be started.
*
*******************************************************************************/
#define _GNU_SOURCE
#include <ctype.h>
#include <errno.h>
#include <fcntl.h>
#include <libgen.h>
#include <pty.h>
#include <pwd.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/select.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <time.h>
#include <unistd.h>
/* log directory is predefined so that it cannot be change by the user */
#ifndef DEFAULT_LOG_FILE
#define DEFAULT_LOG_FILE "/var/log/user-session/%h-%u-%y%m%d-%H%M%S-%c-%p.log"
#endif
#ifndef DEFAULT_SHELL
#define DEFAULT_SHELL "/bin/bash"
#endif
#ifndef CONFIG_FILE
#define CONFIG_FILE "/etc/log-user-session.conf"
#endif
char *original_command = NULL;
char *opt_command = NULL;
char *opt_shell = NULL;
char *opt_user = NULL;
char *opt_client = NULL;
char *opt_logfile = NULL;
char **opt_argv = NULL;
char *opt_disabledloggingusers = NULL;
int opt_log_remote_command_data = 1;
int opt_log_non_interactive_data = 1;
struct buffer;
struct buffer {
char data[1024];
size_t size;
size_t pos[2]; /* user stream is at index 0 */
struct buffer *next[2]; /* log stream is at index 1 */
};
struct list {
struct buffer *head;
struct buffer *tail;
};
struct fd_pair {
int write_side;
int read_side;
};
/* keep the last freed buffer in reserve for the next use */
struct buffer *reserve;
/* window resize signal forwarding */
int original_tty;
int child_tty;
void free_options() {
if (opt_command) free(opt_command);
if (opt_shell) free(opt_shell);
if (opt_user) free(opt_user);
if (opt_client) free(opt_client);
if (opt_logfile) free(opt_logfile);
if (opt_disabledloggingusers) free(opt_disabledloggingusers);
if (opt_argv) {
int i;
for (i = 0; opt_argv[i]; i++) {
free(opt_argv[i]);
}
free(opt_argv);
}
}
struct buffer *new_buffer() {
struct buffer *buffer = reserve;
if (NULL == buffer) {
buffer = (struct buffer*) malloc(sizeof(struct buffer));
}
else {
reserve = NULL;
}
int i;
for (i = 0; i<=1; i++) {
buffer->pos[i] = 0;
buffer->next[i] = NULL;
}
buffer->size = 0;
return buffer;
}
void free_buffer(struct buffer *buffer) {
if (NULL == reserve) {
reserve = buffer;
}
else {
free(buffer);
}
}
struct buffer* next_buffer(struct buffer *buffer, int index) {
int other = index ? 0 : 1;
struct buffer* next = buffer;
if (buffer->pos[index] == buffer->size) {
next = buffer->next[index];
/* free buffer if it has been written to other stream too */
if (buffer->pos[other] == buffer->size) {
free_buffer(buffer);
}
}
return next;
}
void empty_buffer(struct list *list, int index) {
struct buffer *buffer = list->head;
/* consume all buffers */
while(buffer = next_buffer(buffer, index)) {
buffer->pos[index] = buffer->size;
}
list->head = NULL;
list->tail = NULL;
}
int read_to_buffer(int fd, struct list *out, struct list *log) {
struct buffer *buffer = new_buffer();
/* read data to buffer */
ssize_t count = read(fd, &(buffer->data), 1024);
/* error handling */
if (count < 0) {
free_buffer(buffer);
if (EINTR == errno || EAGAIN == errno || EWOULDBLOCK == errno) {
return 1; /* try again */
}
return 0; /* stop */
}
/* stream closed */
if (0 == count) {
free_buffer(buffer);
return 0;
}
buffer->size = (size_t) count;
/* add to output buffer */
if (NULL == out->head) {
out->head = buffer;
out->tail = buffer;
}
else {
out->tail->next[0] = buffer;
out->tail = buffer;
}
/* add to log buffer */
if (log) {
if (NULL == log->head) {
log->head = buffer;
log->tail = buffer;
}
else {
log->tail->next[1] = buffer;
log->tail = buffer;
}
}
else {
/* mark as consumed by log */
buffer->pos[1] = count;
}
return 1;
}
int write_from_buffer(int fd, struct list *list, int log) {
int index = log ? 1 : 0;
struct buffer *buffer = list->head;
/* make sure there is anything to write */
if (NULL == buffer) return 1;
size_t pos = buffer->pos[index];
size_t size = buffer->size;
ssize_t count = write(fd, buffer->data + pos, size - pos);
if (count < 0) {
if (EINTR == errno || EAGAIN == errno || EWOULDBLOCK == errno) {
return 1; /* try again */
}
empty_buffer(list, index);
return 0;
}
/* buffer cleanup */
buffer->pos[index] = pos + count;
list->head = next_buffer(buffer, index);
if (NULL == list->head) list->tail = NULL;
return 1;
}
void run_log_forwarder(struct fd_pair *internal, struct fd_pair *input, struct fd_pair *output,
struct fd_pair *error, int interactive) {
int i;
fd_set read_set;
fd_set write_set;
struct timeval timeout;
int stdin_open = 1;
int stdout_open = 1;
int stderr_open = 1;
int internal_open = 1;
int input_open = 1;
int output_open = 1;
int error_open = error ? 1 : 0;
int max_fd = internal->write_side;
if (input->write_side > max_fd) max_fd = input->write_side;
if (output->read_side > max_fd) max_fd = output->read_side;
if (error_open && error->read_side > max_fd) max_fd = error->read_side;
max_fd++;
reserve = NULL;
struct list internal_buffer = {NULL, NULL};
struct list input_buffer = {NULL, NULL};
struct list stdout_buffer = {NULL, NULL};
struct list stderr_buffer = {NULL, NULL};
/* non-blocking read/write */
int flags = fcntl(STDIN_FILENO, F_GETFL, 0);
fcntl(STDIN_FILENO, F_SETFL, flags | O_NONBLOCK);
flags = fcntl(STDOUT_FILENO, F_GETFL, 0);
fcntl(STDOUT_FILENO, F_SETFL, flags | O_NONBLOCK);
flags = fcntl(STDERR_FILENO, F_GETFL, 0);
fcntl(STDERR_FILENO, F_SETFL, flags | O_NONBLOCK);
flags = fcntl(internal->write_side, F_GETFL, 0);
fcntl(internal->write_side, F_SETFL, flags | O_NONBLOCK);
flags = fcntl(input->write_side, F_GETFL, 0);
fcntl(input->write_side, F_SETFL, flags | O_NONBLOCK);
flags = fcntl(output->read_side, F_GETFL, 0);
fcntl(output->read_side, F_SETFL, flags | O_NONBLOCK);
if (error_open) {
flags = fcntl(error->read_side, F_GETFL, 0);
fcntl(error->read_side, F_SETFL, flags | O_NONBLOCK);
}
/* as long as there is a parent process and something to read */
while (getppid() > 1 && (output_open || error_open)) {
/* prepare read set */
FD_ZERO(&read_set);
if (stdin_open) FD_SET(STDIN_FILENO, &read_set);
if (output_open) FD_SET(output->read_side, &read_set);
if (error_open) FD_SET(error->read_side, &read_set);
/* prepare write set */
FD_ZERO(&write_set);
if (internal_buffer.head && internal_open) FD_SET(internal->write_side, &write_set);
if (input_buffer.head && input_open) FD_SET(input->write_side, &write_set);
if (stdout_buffer.head && stdout_open) FD_SET(STDOUT_FILENO, &write_set);
if (stderr_buffer.head && stderr_open) FD_SET(STDERR_FILENO, &write_set);
/* timeout to avoid hanging processes if PPID changes to 1 between getppid and select */
timeout.tv_sec = 300;
timeout.tv_usec = 0;
/* what to do */
int result = select(max_fd, &read_set, &write_set, NULL, &timeout);
/* error handling */
if (result < 0) {
if (EINTR == errno) continue;
perror("select");
break;
}
/* timeout */
else if (0 == result) {
continue;
}
/* non-blocking write */
if (FD_ISSET(input->write_side, &write_set)) {
input_open = write_from_buffer(input->write_side, &input_buffer, 0);
}
if (FD_ISSET(STDERR_FILENO, &write_set)) {
stderr_open = write_from_buffer(STDERR_FILENO, &stderr_buffer, 0);
}
if (FD_ISSET(STDOUT_FILENO, &write_set)) {
stdout_open = write_from_buffer(STDOUT_FILENO, &stdout_buffer, 0);
}
if (FD_ISSET(internal->write_side, &write_set)) {
internal_open = write_from_buffer(internal->write_side, &internal_buffer, 1);
}
/* non-blocking read */
if (FD_ISSET(STDIN_FILENO, &read_set)) {
stdin_open = read_to_buffer(STDIN_FILENO, &input_buffer,
(internal_open && !interactive) ? &internal_buffer : NULL);
}
if (error_open && FD_ISSET(error->read_side, &read_set)) {
error_open = read_to_buffer(error->read_side, &stderr_buffer,
internal_open ? &internal_buffer : NULL);
}
if (FD_ISSET(output->read_side, &read_set)) {
output_open = read_to_buffer(output->read_side, &stdout_buffer,
internal_open ? &internal_buffer : NULL);
}
/* propagate closed input */
if (!stdin_open && !input_buffer.head && input_open) {
close(input->write_side);
input_open = 0;
}
}
/* do we have something left out for writing? (reset to blocking mode before writing) */
flags = fcntl(STDERR_FILENO, F_GETFL, 0);
fcntl(STDERR_FILENO, F_SETFL, flags & (~O_NONBLOCK));
flags = fcntl(STDOUT_FILENO, F_GETFL, 0);
fcntl(STDOUT_FILENO, F_SETFL, flags & (~O_NONBLOCK));
flags = fcntl(internal->write_side, F_GETFL, 0);
fcntl(internal->write_side, F_SETFL, flags & (~O_NONBLOCK));
while (stderr_buffer.head) {
write_from_buffer(STDERR_FILENO, &stderr_buffer, 0);
}
while (stdout_buffer.head) {
write_from_buffer(STDOUT_FILENO, &stdout_buffer, 0);
}
while (internal_open && internal_buffer.head) {
internal_open = write_from_buffer(internal->write_side, &internal_buffer, 1);
}
/* still some input? Write it out immediately 1:1, but bail out if there was nothing read
(we seam to get EAGAIN for ever if parent is killed) */
if (internal_open) {
while (error_open && read_to_buffer(error->read_side, &stderr_buffer, &internal_buffer)) {
if (NULL == stderr_buffer.head) break;
write_from_buffer(STDERR_FILENO, &stderr_buffer, 0);
write_from_buffer(internal->write_side, &internal_buffer, 1);
}
while (read_to_buffer(output->read_side, &stdout_buffer, &internal_buffer)) {
if (NULL == stdout_buffer.head) break;
write_from_buffer(STDOUT_FILENO, &stdout_buffer, 0);
write_from_buffer(internal->write_side, &internal_buffer, 1);
}
}
else {
while (error_open && read_to_buffer(error->read_side, &stderr_buffer, NULL)) {
if (NULL == stderr_buffer.head) break;
write_from_buffer(STDERR_FILENO, &stderr_buffer, 0);
}
while (read_to_buffer(output->read_side, &stdout_buffer, NULL)) {
if (NULL == stdout_buffer.head) break;
write_from_buffer(STDOUT_FILENO, &stdout_buffer, 0);
}
}
/* final cleanup */
if (NULL != reserve) {
free(reserve);
}
}
void write_log(int fd_input, int fd_log, char *buffer, size_t size) {
for (;;) {
ssize_t r_count = read(fd_input, buffer, size);
if (0 == r_count) return; /* done */
if (r_count < 0 ) { /* error handling */
if (EINTR == errno || EAGAIN == errno || EWOULDBLOCK == errno) {
continue; /* try again */
}
return;
}
int pos = 0;
while(pos < r_count) {
ssize_t w_count = write(fd_log, buffer + pos, r_count - pos);
if (0 == w_count) return; /* done!? */
if (w_count < 0 ) { /* error handling */
if (EINTR == errno || EAGAIN == errno || EWOULDBLOCK == errno) {
continue; /* try again */
}
return;
}
pos += w_count;
}
}
}
int should_log_data(int interactive, const char *original_command) {
if (!interactive && !opt_log_non_interactive_data) return 0;
if (original_command && !opt_log_remote_command_data) return 0;
return 1;
}
void run_log_writer(int fd_read, int fd_log) {
char *buffer = (char*) malloc(1024*sizeof(char));
write_log(fd_read, fd_log, buffer, 1024);
free(buffer);
}
struct fd_pair new_pipe() {
int fd[2];
if (pipe(fd) != 0) perror("creating pipes failed");
struct fd_pair ret = {fd[1], fd[0]};
return ret;
}
struct fd_pair clone_pseudo_terminal(int fd_original) {
struct termios term;
struct winsize ts;
int master_fd, slave_fd;
/* create new pseudo terminal */
tcgetattr(fd_original, &term);
ioctl(fd_original, TIOCGWINSZ, &ts);
openpty(&master_fd, &slave_fd, NULL, &term, &ts);
struct fd_pair ret = {master_fd, slave_fd};
return ret;
}
void set_raw_input(int fd, struct termios *old_term) {
/* put input into raw mode */
struct termios tnew;
tcgetattr(STDIN_FILENO, &tnew);
if (old_term) *old_term = tnew;
/* Noncanonical mode, disable signals, extended input processing, and echoing */
tnew.c_lflag &= ~(ICANON | ISIG | IEXTEN | ECHO);
/* Disable special handling of CR, NL, and BREAK.
* No 8th-bit stripping or parity error handling.
* Disable START/STOP output flow control. */
tnew.c_iflag &= ~(BRKINT | ICRNL | IGNBRK | IGNCR | INLCR | INPCK | ISTRIP | IXON | PARMRK);
tcsetattr(STDIN_FILENO, TCSAFLUSH, &tnew);
}
void debug_process_state(const char *hint) {
fprintf(stderr, "%s: id: %d, session leader: %d, process group leader: %d\n",
hint, getpid(), getsid(0), getpgid(0));
}
void resize_handler(int signal) {
if (SIGWINCH == signal) {
struct winsize ts;
ioctl(original_tty, TIOCGWINSZ, &ts);
ioctl(child_tty, TIOCSWINSZ, &ts);
}
}
void prepare_dir(const char *dir) {
struct stat st;
if (0 == stat(dir, &st)) return;
char* parent = dirname(strdup(dir));
prepare_dir(parent);
free(parent);
if (0 != mkdir(dir, 0700)) perror(dir);
}
void print_config_file_warning(const char *config_file, const char *log_dir) {
/* print a warning if there is no config file and no directory -- this is the very first startup */
struct stat st;
if (0 == stat(log_dir, &st)) return;
if (0 == stat(config_file, &st)) return;
fprintf(stderr, "using default configuration\n");
return;
}
int prepare_log_file(const char *log_file, const char *original_command) {
char* dir = dirname(strdup(log_file));
print_config_file_warning(CONFIG_FILE, dir);
prepare_dir(dir);
free(dir);
int fd_log = open(log_file, O_WRONLY|O_APPEND|O_CREAT, S_IRUSR);
if (fd_log < 0) {
perror(log_file);
}
else {
if (original_command) {
size_t s = write(fd_log, original_command, strlen(original_command));
s = write(fd_log, "\n", 1);
}
}
return fd_log;
}
void start_logger(const char *log_file, const char *original_command, uid_t uid) {
struct fd_pair input;
struct fd_pair output[2];
int output_count;
int i;
int has_tty = isatty(STDIN_FILENO);
int do_log_data = should_log_data(has_tty, original_command);
pid_t child_pid;
if (!do_log_data) {
/* we just log the command in child process and return, no remaining logging process at the end */
child_pid = fork();
if (child_pid == 0) {
int fd_log = prepare_log_file(log_file, original_command);
if (fd_log < 0) {
exit(1);
}
close(fd_log);
exit(0);
}
return;
}
if (has_tty) {
/* use psedo terminal for communication */
input = clone_pseudo_terminal(STDIN_FILENO);
if (uid && fchown(input.read_side, uid, -1) < 0) perror("change owner of tty to user");
output[0].write_side = dup(input.read_side);
output[0].read_side = dup(input.write_side);
output_count = 1;
}
else {
/* use pipes for communication */
input = new_pipe();
output[0] = new_pipe();
output[1] = new_pipe();
output_count = 2;
}
/* child will return and execute the command */
child_pid = fork();
if (child_pid == 0) {
if (has_tty) {
/* need to be session leader to be able to set the controlling terminal later on */
if (setsid() < 0) perror("create new session");
/* the controlling terminal is required by the shell for job control */
if (ioctl(input.read_side, TIOCSCTTY, NULL) != 0) perror("set controlling terminal");
}
/* parent process runs session and redirects I/O to the pipes or pseudterminal */
dup2(input.read_side, STDIN_FILENO);
dup2(output[0].write_side, STDOUT_FILENO);
dup2(output[output_count-1].write_side, STDERR_FILENO);
close(input.read_side);
close(input.write_side);
for (i = 0; i < output_count; i++) {
close(output[i].write_side);
close(output[i].read_side);
}
return;
}
/* parent will collect and forward the session content */
close(input.read_side);
for (i = 0; i < output_count; i++) {
close(output[i].write_side);
}
/* signal handling */
signal(SIGINT, SIG_IGN);
signal(SIGHUP, SIG_IGN);
signal(SIGPIPE, SIG_IGN);
/* child will do blocking writes on file */
struct fd_pair internal = new_pipe();
if (fork() == 0) {
close(input.write_side);
for (i = 0; i < output_count; i++) {
close(output[i].read_side);
}
close(internal.write_side);
int fd_log = prepare_log_file(log_file, original_command);
free_options();
if (fd_log < 0) {
exit(1);
}
close(STDIN_FILENO);
close(STDOUT_FILENO);
close(STDERR_FILENO);
run_log_writer(internal.read_side, fd_log);
exit(0);
}
free_options();
close(internal.read_side);
struct termios original_term;
if (has_tty) {
original_tty = dup(STDIN_FILENO); /* trick from bash */
set_raw_input(original_tty, &original_term);
child_tty = input.write_side;
signal(SIGWINCH, resize_handler);
}
/* do the logging */
run_log_forwarder(&internal, &input, output,
2 == output_count ? output + 1 : NULL,
has_tty
);
/* reset terminal */
if (has_tty) {
if (tcsetattr(original_tty, TCSAFLUSH, &original_term) != 0) {
perror("reseting terminal");
}
}
/* forward exit value of child -- if there is still anyone that might be interested */
if (getppid() > 1) {
int status;
waitpid(child_pid, &status, 0);
exit(WEXITSTATUS(status));
}
exit(0);
}
void debug_uid(const char *hint) {
fprintf(stderr, "%s: ruid=%d, euid=%d\n", hint, getuid(), geteuid());
}
char *prepare_log_file_name(const char *template) {
time_t current_time = time(NULL);
struct tm local_time;
localtime_r(¤t_time, &local_time);
local_time.tm_mon++;
local_time.tm_year += 1900;
size_t len = strlen(template);
char *logfile = NULL;
for(;;) {
/* if we were too small, we just try again bigger */
len += 100;
if (logfile) free(logfile);
logfile = (char*) malloc(len * sizeof(char));
const char *pos_t = template;
char *pos_l = logfile;
for (;;) {
/* check if there is still some space left over */
int remaining = len - (pos_l - logfile);
if (0 >= remaining) break;
if ('%' == *pos_t) {
pos_t++;
/* add just one % sign */
if ('%' == *pos_t) {
*pos_l = *pos_t;
pos_l++;
}
/* add user name */
else if ('u' == *pos_t) {
int r = snprintf(pos_l, remaining, "%s", opt_user);
if (r >= remaining) break;
while('\0' != *pos_l) pos_l++;
}
/* add client host */
else if ('c' == *pos_t) {
if (opt_client) {
int r = snprintf(pos_l, remaining, "%s", opt_client);
if (r >= remaining) break;
while('\0' != *pos_l) pos_l++;
}
}
/* add hostname */
else if ('h' == *pos_t) {
int r = gethostname(pos_l, remaining);
if (r < 0 && ENAMETOOLONG == errno) break;
while(*pos_l != '\0') pos_l++;
}
/* add process ID */
else if ('p' == *pos_t) {
int r = snprintf(pos_l, remaining, "%d", (int) getpid());
if (r >= remaining) break;
while('\0' != *pos_l) pos_l++;
}
/* add unix timestamp */
else if ('s' == *pos_t) {
int r = snprintf(pos_l, remaining, "%lld", (long long)current_time);
if (r >= remaining) break;
while('\0' != *pos_l) pos_l++;
}
/* add year */
else if ('y' == *pos_t) {
int r = snprintf(pos_l, remaining, "%d", (int)local_time.tm_year);
if (r >= remaining) break;
while('\0' != *pos_l) pos_l++;
}
/* add month */
else if ('m' == *pos_t) {
int r = snprintf(pos_l, remaining, "%02d", (int)local_time.tm_mon);
if (r >= remaining) break;
while('\0' != *pos_l) pos_l++;
}
/* add day of month */
else if ('d' == *pos_t) {
int r = snprintf(pos_l, remaining, "%02d", (int)local_time.tm_mday);
if (r >= remaining) break;
while('\0' != *pos_l) pos_l++;
}
/* add hour */
else if ('H' == *pos_t) {
int r = snprintf(pos_l, remaining, "%02d", (int)local_time.tm_hour);
if (r >= remaining) break;
while('\0' != *pos_l) pos_l++;
}
/* add minute */
else if ('M' == *pos_t) {
int r = snprintf(pos_l, remaining, "%02d", (int)local_time.tm_min);
if (r >= remaining) break;
while('\0' != *pos_l) pos_l++;
}
/* add second */
else if ('S' == *pos_t) {
int r = snprintf(pos_l, remaining, "%02d", (int)local_time.tm_sec);
if (r >= remaining) break;
while('\0' != *pos_l) pos_l++;
}
}
else {
/* everything else */
*pos_l = *pos_t;
if ('\0' == *pos_l) {
return logfile;
}
pos_l++;
}
pos_t++;
}
}
}
void parse_configuration_option(const char *start, const char *end) {
/* look for "text = text " */
/* trim whitespaces at the end */
while(isspace(*end)) {
end--;
}
/* find equal sign */
char *equal = strchrnul(start, '=');
if (equal < end) {
/* extract option name */
char *option_end = equal - 1;
while(isspace(*option_end)) {
option_end--;
}
/* extract value */
char *value_start = equal + 1;
while(isspace(*value_start)) {
value_start++;
}
/* check options*/
size_t len = strlen("LogFile");
if (len == option_end - start + 1 && 0 == strncasecmp("LogFile", start, len)) {
char *path_template = strndup(value_start, end - value_start + 1);
if (opt_logfile) free(opt_logfile);
opt_logfile = prepare_log_file_name(path_template);
free(path_template);
return;
}
len = strlen("LogRemoteCommandData");
if (len == option_end - start + 1 && 0 == strncasecmp("LogRemoteCommandData", start, len)) {
if (value_start == end) {
if ('1' == *value_start) {
opt_log_remote_command_data = 1;
return;
}
else if ('0' == *value_start) {
opt_log_remote_command_data = 0;
return;
}
}
}
len = strlen("LogNonInteractiveData");
if (len == option_end - start + 1 && 0 == strncasecmp("LogNonInteractiveData", start, len)) {
if (value_start == end) {
if ('1' == *value_start) {
opt_log_non_interactive_data = 1;
return;
}
else if ('0' == *value_start) {
opt_log_non_interactive_data = 0;
return;
}
}
}
len = strlen("DisabledLoggingUsers");
if (len == option_end - start + 1 && 0 == strncasecmp("DisabledLoggingUsers", start, len)) {
if (opt_disabledloggingusers) free(opt_disabledloggingusers);
opt_disabledloggingusers = (char *) malloc(1024*sizeof(char));
opt_disabledloggingusers = strndup(value_start, end - value_start + 1);
return;
}
}
/* Noop */
fprintf(stderr,"error while parsing configuration file %s:\n", CONFIG_FILE);
fwrite(start, sizeof(char), end - start + 1, stderr);
fprintf(stderr,"\n");
return;
}
void read_configuration_file() {
/* read all file content */
struct stat st;
if (0 != stat(CONFIG_FILE, &st)) {
return;
}
size_t filesize = (size_t)st.st_size;
FILE *f = fopen(CONFIG_FILE, "r");
if (!f) {
perror(CONFIG_FILE);
fprintf(stderr, "using default configuration\n");
return;
}
char *data = (char*) malloc(filesize + 1);
size_t s = fread(data, 1, filesize, f);
if (0 == s) {
if (ferror(f)) {
perror(CONFIG_FILE);
fprintf(stderr, "using default configuration\n");
}
free(data);
return;
}
data[filesize] = '\0';
fclose(f);
/* parse it */
char *pos = data;
do {
/* comments */
if ('#' == *pos) {
pos = strchrnul(pos, '\n');
}
/* parse config option */
else if (!isspace(*pos)) {
char *end = strchrnul(pos, '\n');
parse_configuration_option(pos, end);
pos = end;
}
else {
pos++;
}
} while (*pos != '\0');
free(data);
}
void process_options(int argc, char **argv) {
/* get command to execute */
if (argc > 1) {
int len = argc; /* enough space for whitespaces and null byte */
int i;
for (i = 1; i < argc; i++) {
len += strlen(argv[i]);
}
opt_command = (char *) malloc(len * sizeof(char));
opt_command[0] = '\0';
char *pos = opt_command;
for (i = optind; i < argc; i++) {
strcat(opt_command, argv[i]);
strcat(opt_command, " ");
}
opt_command[strlen(opt_command) - 1] = '\0';
}
/* remote command? */
original_command = getenv("SSH_ORIGINAL_COMMAND");
if (original_command && 0 == strcmp("(null)",original_command)) {
original_command = NULL;
}
/* get user name and shell */
uid_t uid = getuid();
struct passwd *user = getpwuid(uid);
if (NULL != user) {
if (NULL != user->pw_name) {
opt_user = strdup(user->pw_name);
}
else {
fprintf(stderr, "reading user name failed\n");
}
if (NULL != user->pw_shell) {
opt_shell = strdup(user->pw_shell);
}
else {
fprintf(stderr, "reading user shell failed\n");
}
}
else {
fprintf(stderr, "reading user information failed\n");
}
if (!opt_shell) {
opt_shell = strdup(DEFAULT_SHELL);
}
/* client host */
char *ssh_client = getenv("SSH_CLIENT");
if (ssh_client && 0 != strcmp("(null)",ssh_client)) {
int i;
for (i = 0; ssh_client[i] && !isspace(ssh_client[i]); i++);
opt_client = strndup(ssh_client, i);
}
/* configured options */
read_configuration_file();
fprintf(stderr, "*** USER = %s *** \n", opt_user);
fprintf(stderr, "*** opt_disabledloggingusers = %s *** \n", opt_disabledloggingusers);
if(strcmp(opt_user,opt_disabledloggingusers) == 0){
fprintf(stderr, "*** Disabling Shell Logging *** \n");
}else{
fprintf(stderr, "*** Shell Logging *** \n");
}
if (!opt_logfile) {
opt_logfile = prepare_log_file_name(DEFAULT_LOG_FILE);
}
/* prepare ARGV to execute */
/* run (command line option/original ssh) command */
char * command = opt_command ? opt_command : original_command ? original_command : NULL;
/* have we been started like a login shell? */
int login_shell = 0;
if (argv && argv[0] && '-' == *argv[0]) {
login_shell = 1;
}
else {
if (!command) {
char *prompt = getenv("PS1");
if (!prompt || *prompt == '\0') {
login_shell = 1;
}
}
}
opt_argv = (char**) malloc((command ? 4 : 2) * sizeof(char*));
if (login_shell) {
opt_argv[0] = (char*) malloc((strlen(opt_shell) + 2) * sizeof(char));
opt_argv[0][0] = '-';
strcpy(&(opt_argv[0][1]), opt_shell);
}
else {
opt_argv[0] = strdup(opt_shell);
}
if (command) {
opt_argv[1] = strdup("-c");
opt_argv[2] = strdup(command);
opt_argv[3] = NULL;
}
else {
opt_argv[1] = NULL;
}
}
int main(int argc, char **argv) {
process_options(argc, argv);
/* setuid */
uid_t uid = getuid();
if (uid && setreuid(0, 0) < 0) {
perror("could not change to root");
}
/* fork logger */
start_logger(opt_logfile, original_command, uid);
/* back to original user */
if (uid && setuid(uid) < 0) {
perror("could not change back to user");
/* here we cannot continue if there is an error as we did not manage to drop priviledges */
return 1;
}
execv(opt_shell, opt_argv);
perror("executing shell");
free_options();
return 1;
}
|
the_stack_data/24344.c | #include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/wait.h>
#include <unistd.h>
int main(int argc, char *argv[]) {
int status = 0;
if (argc < 4) {
return 1;
}
int pipe_fd[2];
if (pipe(pipe_fd) == -1) exit(1);
pid_t pid1 = fork();
if (pid1 < 0) exit(1);
if (!pid1) {
close(pipe_fd[0]);
pid_t pid2 = fork();
if (pid2 < 0) exit(1);
if (!pid2) {
dup2(pipe_fd[1], 1);
close(pipe_fd[0]);
close(pipe_fd[1]);
execlp(argv[1], argv[1], NULL);
_exit(0);
}
status = 0;
wait(&status);
pid_t pid3 = fork();
if (pid3 < 0) exit(1);
if (!pid3)
{
dup2(pipe_fd[1], 1);
close(pipe_fd[0]);
close(pipe_fd[1]);
execlp(argv[2], argv[2], NULL);
_exit(0);
}
close(pipe_fd[1]);
status = 0;
wait(&status);
_exit(0);
}
pid_t pid4 = fork();
if (pid4 < 0) exit(1);
if (!pid4)
{
dup2(pipe_fd[0], 0);
int file = open(argv[4], O_WRONLY | O_CREAT | O_TRUNC, 0600);
dup2(file, 1);
close(pipe_fd[0]);
close(pipe_fd[1]);
close(file);
execlp(argv[3], argv[3], NULL);
_exit(0);
}
close(pipe_fd[0]);
close(pipe_fd[1]);
status = 0;
while (wait(&status) > 0)
{
status = 0;
}
}
|
the_stack_data/45451512.c | #include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <pthread.h>
#define MAXLINE 128
#define SERV_PORT 8001
void* readthread(void* arg)
{
pthread_detach(pthread_self());
int sockfd = (int)arg;
int n = 0;
char buf[MAXLINE];
while (1)
{
n = read(sockfd, buf, MAXLINE);
if (n == 0)
{
printf("the other side has been closed.\n");
close(sockfd);
exit(0);
}
else
write(STDOUT_FILENO, buf, n);
}
return (void*)0;
}
int main(int argc, char *argv[])
{
struct sockaddr_in servaddr;
int sockfd;
char buf[MAXLINE];
sockfd = socket(AF_INET, SOCK_STREAM, 0);
bzero(&servaddr, sizeof(servaddr));
servaddr.sin_family = AF_INET;
inet_pton(AF_INET, "127.0.0.1", &servaddr.sin_addr);
servaddr.sin_port = htons(SERV_PORT);
connect(sockfd, (struct sockaddr *)&servaddr, sizeof(servaddr));
pthread_t thid;
pthread_create(&thid, NULL, readthread, (void*)sockfd);
while (fgets(buf, MAXLINE, stdin) != NULL)
write(sockfd, buf, strlen(buf));
close(sockfd);
return 0;
}
|
the_stack_data/178265161.c | #include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/stat.h>
int main(void)
{
struct stat buf; /* 存储文件状态信息 */
if(stat("/home/linux-c", &buf) == -1){ /* 得到文件状态信息 */
perror("fail to stat");
exit(1);
}
if(!S_ISDIR(buf.st_mode)){ /* 非目录文件 */
printf( "this is not a directory file\n");
exit(1);
}
if(S_IRUSR & buf.st_mode) /* 所有者用户具有读目录权限 */
printf("user can read the dir\n");
if(S_IWUSR & buf.st_mode) /* 所有者用户具有写目录权限 */
printf("user can write the dir\n");
if(S_IXUSR & buf.st_mode) /* 所有者用户具有执行目录权限 */
printf("user can through the dir\n");
return 0;
}
|
the_stack_data/445762.c | /*
Ten program używa poll(), aby równocześnie obsługiwać wielu klientów
bez tworzenia procesów ani wątków.
*/
#include <limits.h>
#include <poll.h>
#include <signal.h>
#include <stdio.h>
#include <string.h>
#include <sys/socket.h>
#include <netdb.h>
#include <unistd.h>
#include <stdlib.h>
#include <errno.h>
#include "err.h"
#define TRUE 1
#define FALSE 0
#define BUF_SIZE 1024
static int finish = FALSE;
static int active_clients = 0;
static int all_server_clients = 0;
static int active_server_clients = 0;
static void catch_int (int sig);
void clean_clients_revents(struct pollfd *client);
void close_socket_if_interrupted(struct pollfd *client);
void resolve_pool(struct pollfd *client, int *client_type, char *buf);
void resolve_pool_if_count_negative();
void resolve_pool_if_count_positive(struct pollfd *client, int *client_type, char *buf);
void resolve_connection(struct pollfd *client, int *client_type, char *buf);
void create_socket_port(struct pollfd *client, const int client_index, const char *port_message, const int port);
void create_new_connection(struct pollfd *client, int *client_type, int client_index);
void receive_data_from_client(struct pollfd *client, char *buf, ssize_t rval, int *client_type, int i);
void send_control_info(struct pollfd *client, int i, char *buf, int *client_type);
void close_connection(struct pollfd *client, int *client_type, int i);
int compare_strings(const char *s1, const char *s2, const int n);
int main (int argc, char *argv[]) {
struct pollfd client[_POSIX_OPEN_MAX];
int client_type[_POSIX_OPEN_MAX];
char buf[BUF_SIZE];
struct sigaction action;
sigset_t block_mask;
if (argc != 3) {
fatal("Usage: %s <port> <control port> ", argv[0]);
}
const int port = atoi(argv[1]);
const int control_port = atoi(argv[2]);
fprintf(stderr,"_POSIX_OPEN_MAX = %d\n", _POSIX_OPEN_MAX);
/* Po Ctrl-C kończymy */
sigemptyset (&block_mask);
action.sa_handler = catch_int;
action.sa_mask = block_mask;
action.sa_flags = SA_RESTART;
if (sigaction (SIGINT, &action, 0) == -1) {
syserr("sigaction");
}
/* Inicjujemy tablicę z gniazdkami klientów, client[0] to gniazdko centrali */
for (int i = 0; i < _POSIX_OPEN_MAX; ++i) {
client[i].fd = -1;
client[i].events = POLLIN;
client[i].revents = 0;
}
create_socket_port(client, 0, "Socket port ", port);
create_socket_port(client, 1, "Control port ", control_port);
/* Do pracy */
do {
clean_clients_revents(client);
close_socket_if_interrupted(client);
resolve_pool(client, client_type, buf);
} while (finish == FALSE || active_clients > 0);
if (client[0].fd >= 0 && close(client[0].fd) < 0) {
syserr("Closing main socket");
}
exit(EXIT_SUCCESS);
}
void create_socket_port(struct pollfd *client, const int client_index, const char *port_message, const int port) {
struct sockaddr_in server;
server.sin_family = AF_INET;
server.sin_addr.s_addr = htonl(INADDR_ANY);
server.sin_port = htons(port);
client[client_index].fd = socket(PF_INET, SOCK_STREAM, 0);
if (client[client_index].fd == -1) {
syserr("Opening stream socket");
}
if (bind(client[client_index].fd, (struct sockaddr*) &server, (socklen_t)sizeof(server)) == -1) {
syserr("Binding stream socket");
}
size_t length = sizeof(server);
if (getsockname (client[client_index].fd, (struct sockaddr*)&server,
(socklen_t*)&length) == -1) {
syserr("Getting socket name");
}
printf("%s #%u\n", port_message, (unsigned)ntohs(server.sin_port));
if (listen(client[client_index].fd, 5) == -1) {
syserr("Starting to listen");
}
}
void catch_int(int sig) {
finish = TRUE;
fprintf(stderr, "Signal %d catched. No new connections will be accepted.\n", sig);
}
void resolve_pool(struct pollfd *client, int *client_type, char *buf) {
int descriptors_count = poll(client, _POSIX_OPEN_MAX, -1);
if (descriptors_count == -1) {
resolve_pool_if_count_negative();
}
else if (descriptors_count > 0) {
resolve_pool_if_count_positive(client, client_type, buf);
} else {
fprintf(stderr, "Do something else\n");
}
}
void resolve_pool_if_count_positive(struct pollfd *client, int *client_type, char *buf) {
create_new_connection(client, client_type, 0);
create_new_connection(client, client_type, 1);
resolve_connection(client, client_type, buf);
}
void create_new_connection(struct pollfd *client, int *client_type, int client_index) {
if (finish == FALSE && (client[client_index].revents & POLLIN)) {
int msgsock = accept(client[client_index].fd, (struct sockaddr*)0, (socklen_t*)0);
if (msgsock == -1) {
syserr("accept");
}
else {
int i;
for (i = 2; i < _POSIX_OPEN_MAX; ++i) {
if (client[i].fd == -1) {
fprintf(stderr, "Received new connection (%d)\n", i);
client[i].fd = msgsock;
client[i].events = POLLIN;
client_type[i] = client_index;
active_clients++;
if (client_index == 0) {
active_server_clients++;
all_server_clients++;
}
break;
}
}
if (i >= _POSIX_OPEN_MAX) {
fprintf(stderr, "Too many clients\n");
if (close(msgsock) < 0) {
syserr("close");
}
}
}
}
}
void resolve_connection(struct pollfd *client, int *client_type, char *buf) {
for (int i = 2; i < _POSIX_OPEN_MAX; ++i) {
if (client[i].fd != -1 && (client[i].revents & (POLLIN | POLLERR))) {
ssize_t rval = read(client[i].fd, buf, BUF_SIZE);
if (rval < 0) {
fprintf(stderr, "Reading message (%d, %s)\n", errno, strerror(errno));
if (close(client[i].fd) < 0) {
syserr("close");
}
client[i].fd = -1;
if (client_type[i] == 0) {
active_server_clients--;
}
client_type[i] = -1;
active_clients--;
} else if (rval == 0) {
close_connection(client, client_type, i);
} else {
receive_data_from_client(client, buf, rval, client_type, i);
}
}
}
}
void receive_data_from_client(struct pollfd *client, char *buf, ssize_t rval, int *client_type, int i) {
if (client_type[i] == 0) {
printf("-->%.*s\n", (int) rval, buf);
} else if (client_type[i] == 1) {
send_control_info(client, i, buf, client_type);
} else {
printf("cos nie dziala\n");
}
}
void send_control_info(struct pollfd *client, int i, char *buf, int *client_type) {
char command[] = "count";
if (strlen(buf) == 7 && compare_strings(command, buf, 5)) {
char str[BUF_SIZE];
sprintf(str, "Number of active clients: %d\nTotal number of clients: %d\n", active_server_clients, all_server_clients);
write(client[i].fd, str, strlen(str));
}
close_connection(client, client_type, i);
}
int compare_strings(const char *s1, const char *s2, const int n) {
for (int i = 0; i < n; i++) {
if (s1[i] != s2[i]) {
return 0;
}
}
return 1;
}
void close_connection(struct pollfd *client, int *client_type, int i) {
fprintf(stderr, "Ending connection\n");
if (close(client[i].fd) < 0) {
syserr("close");
}
client[i].fd = -1;
if (client_type[i] == 0) {
active_server_clients--;
}
client_type[i] = -1;
active_clients--;
}
void resolve_pool_if_count_negative() {
if (errno == EINTR) {
fprintf(stderr, "Interrupted system call\n");
} else {
syserr("poll");
}
}
void close_socket_if_interrupted(struct pollfd *client) {
if (finish == TRUE && client[0].fd >= 0) {
if (close(client[0].fd) < 0) {
syserr("close");
}
client[0].fd = -1;
}
}
void clean_clients_revents(struct pollfd *client) {
for (int i = 0; i < _POSIX_OPEN_MAX; ++i) {
client[i].revents = 0;
}
}
|
the_stack_data/826765.c | #include <pthread.h>
int g;
void *t1(void *arg)
{
int a1, *aptr1;
aptr1=(int *)arg;
a1=*aptr1;
g=0;
// this should pass
assert(a1==10);
assert(g==0);
return NULL;
}
void *t2(void *arg)
{
int a2, *aptr2;
aptr2=(int *)arg;
a2=*aptr2;
g=0;
// this should pass
assert(a2==20);
return NULL;
}
int main()
{
pthread_t id1, id2;
int arg1=10, arg2=20;
pthread_create(&id1, NULL, t1, &arg1);
pthread_create(&id2, NULL, t2, &arg2);
assert(g==0);
pthread_join(id1, NULL);
pthread_join(id2, NULL);
return 0;
}
|
the_stack_data/59513069.c | #include <stdio.h>
void print_lib_1_additional_source_string() {
printf("Hello from lib_1_additional_source!\n");
}
|
the_stack_data/132953080.c | #include <stdio.h>
#include <pthread.h>
#include <assert.h>
int token;
_Bool event_E1=0, event_E2=0, event_E3=0, event_E4=0, event_E5=0, event_EM=0;
int nondet_int();
void __ESBMC_atomic_begin();
void __ESBMC_atomic_end();
void wait_event(_Bool e1, _Bool *e2)
{
__ESBMC_atomic_begin();
_Bool unlocked = (e1==0);
if (unlocked)
__ESBMC_assume(0);
else
e2=0;
__ESBMC_atomic_end();
}
int notify_event(void)
{
__ESBMC_atomic_begin();
return 1;
__ESBMC_atomic_end();
}
void* SC_THREAD_master(void* arg)
{
int local;
// while(1) {
token = nondet_int();
local = token;
event_E1 = notify_event();
wait_event(event_EM, &event_EM);
assert(token == (local + 3));
// }
// return NULL;
}
void* SC_THREAD_transmit1(void* arg)
{
// while(1) {
wait_event(event_E1, &event_E1);
token = token + 1;
event_E2 = notify_event();
// }
// return NULL;
}
void* SC_THREAD_transmit2(void* arg)
{
// while(1) {
wait_event(event_E2, &event_E2);
token = token + 1;
event_E3 = notify_event();
// }
// return NULL;
}
void* SC_THREAD_transmit3(void* arg)
{
// while(1) {
wait_event(event_E3, &event_E3);
token = token + 1;
event_EM = notify_event();
// }
// return NULL;
}
#if 0
void* SC_THREAD_transmit4(void* arg)
{
// while(1) {
wait_event(event_E4, &event_E4);
token = token + 1;
event_EM = notify_event();
// }
// return NULL;
}
void* SC_THREAD_transmit5(void* arg)
{
// while(1) {
wait_event(event_E5,event_E5);
token = token + 1;
event_EM = notify_event();
// }
// return NULL;
}
#endif
int main(void)
{
pthread_t id[6];
pthread_create(&id[0], NULL, SC_THREAD_master, NULL);
pthread_create(&id[1], NULL, SC_THREAD_transmit1, NULL);
pthread_create(&id[2], NULL, SC_THREAD_transmit2, NULL);
pthread_create(&id[3], NULL, SC_THREAD_transmit3, NULL);
// pthread_create(&id[4], NULL, SC_THREAD_transmit4, NULL);
// pthread_create(&id[5], NULL, SC_THREAD_transmit5, NULL);
#if 0
pthread_join(id[0], NULL);
pthread_join(id[1], NULL);
pthread_join(id[2], NULL);
pthread_join(id[3], NULL);
pthread_join(id[4], NULL);
pthread_join(id[5], NULL);
#endif
return 0;
}
|
the_stack_data/156393840.c | #include <stdio.h>
#define LEN 20
const char * msg[5] =
{
" Thank you for the wordeful evening, ",
"You certanly prove that a ",
"is special kind of guy. We must get together",
"over a delicious ",
" and have a few laught"
};
struct names {
char first[LEN];
char last[LEN];
};
struct guy {
struct names handle;
char favfood[LEN];
char job[LEN];
float income;
};
int main(void)
{
struct guy fellow = {
{"Even", "Villard"},
"grilled salmon",
"personality coach",
168112.0
};
printf("Dear %s, \n\n", fellow.handle.first);
printf("%s%s\n", msg[0], fellow.handle.first);
printf("%s%s\n", msg[1], fellow.job);
printf("%s\n", msg[2]);
printf("%s%s%s", msg[3], fellow.favfood, msg[4]);
if (fellow.income > 150000.0)
puts("!!");
else if (fellow.income > 75000.0)
puts("!");
else puts(".");
printf("\n%40s%s\n", " ", "See you soon,");
printf("%40s%s\n", " ", "Shalala");
return 0;
} |
the_stack_data/6388795.c | #include <stdio.h>
int add4digits()
{
int a;
int pin[5];
printf("Give Pin no.");
scanf("%d",&a);
printf("Print is = %d",a);
}
|
the_stack_data/132952308.c | /***
* This code is a part of EvoApproxLib library (ehw.fit.vutbr.cz/approxlib) distributed under The MIT License.
* When used, please cite the following article(s): V. Mrazek, L. Sekanina, Z. Vasicek "Libraries of Approximate Circuits: Automated Design and Application in CNN Accelerators" IEEE Journal on Emerging and Selected Topics in Circuits and Systems, Vol 10, No 4, 2020
* This file contains a circuit from a sub-set of pareto optimal circuits with respect to the pwr and wce parameters
***/
// MAE% = 0.00 %
// MAE = 0
// WCE% = 0.00 %
// WCE = 0
// WCRE% = 0.00 %
// EP% = 0.00 %
// MRE% = 0.00 %
// MSE = 0
// PDK45_PWR = 0.198 mW
// PDK45_AREA = 436.0 um2
// PDK45_DELAY = 1.34 ns
#include <stdint.h>
#include <stdlib.h>
uint64_t mul8x5u_4E8(const uint64_t A,const uint64_t B)
{
uint64_t dout_13, dout_14, dout_15, dout_16, dout_17, dout_18, dout_19, dout_20, dout_21, dout_22, dout_23, dout_24, dout_25, dout_26, dout_27, dout_28, dout_29, dout_30, dout_31, dout_32, dout_34, dout_35, dout_36, dout_37, dout_38, dout_39, dout_40, dout_41, dout_42, dout_43, dout_44, dout_45, dout_46, dout_47, dout_48, dout_49, dout_50, dout_51, dout_52, dout_53, dout_54, dout_55, dout_56, dout_57, dout_58, dout_59, dout_60, dout_61, dout_62, dout_63, dout_64, dout_65, dout_66, dout_67, dout_68, dout_69, dout_70, dout_71, dout_72, dout_73, dout_74, dout_75, dout_76, dout_77, dout_78, dout_79, dout_80, dout_81, dout_82, dout_83, dout_84, dout_85, dout_86, dout_87, dout_88, dout_89, dout_90, dout_91, dout_92, dout_93, dout_94, dout_95, dout_96, dout_97, dout_98, dout_99, dout_100, dout_101, dout_102, dout_103, dout_104, dout_105, dout_106, dout_107, dout_108, dout_109, dout_110, dout_111, dout_112, dout_113, dout_114, dout_115, dout_116, dout_117, dout_118, dout_119, dout_120, dout_121, dout_122, dout_123, dout_124, dout_125, dout_126, dout_127, dout_128, dout_129, dout_130, dout_131, dout_132, dout_133, dout_134, dout_135, dout_136, dout_137, dout_138, dout_139, dout_140, dout_141, dout_142, dout_143, dout_144, dout_145, dout_146, dout_147, dout_148, dout_149, dout_150, dout_151, dout_152, dout_153, dout_154, dout_155, dout_156, dout_157, dout_158, dout_159, dout_160, dout_161, dout_162, dout_163, dout_164, dout_165, dout_166, dout_167, dout_168, dout_169, dout_170, dout_171, dout_172, dout_173, dout_174, dout_175, dout_176, dout_177, dout_178, dout_179, dout_180, dout_181, dout_182, dout_183, dout_184, dout_185, dout_186, dout_187, dout_188, dout_189, dout_190, dout_191, dout_192, dout_193, dout_194, dout_195, dout_196, dout_197;
uint64_t O;
dout_13=((A >> 0)&1)&((B >> 0)&1);
dout_14=((A >> 1)&1)&((B >> 0)&1);
dout_15=((A >> 2)&1)&((B >> 0)&1);
dout_16=((A >> 3)&1)&((B >> 0)&1);
dout_17=((A >> 4)&1)&((B >> 0)&1);
dout_18=((A >> 5)&1)&((B >> 0)&1);
dout_19=((A >> 6)&1)&((B >> 0)&1);
dout_20=((A >> 7)&1)&((B >> 0)&1);
dout_21=((A >> 0)&1)&((B >> 1)&1);
dout_22=((A >> 1)&1)&((B >> 1)&1);
dout_23=((A >> 2)&1)&((B >> 1)&1);
dout_24=((A >> 3)&1)&((B >> 1)&1);
dout_25=((A >> 4)&1)&((B >> 1)&1);
dout_26=((A >> 5)&1)&((B >> 1)&1);
dout_27=((A >> 6)&1)&((B >> 1)&1);
dout_28=((A >> 7)&1)&((B >> 1)&1);
dout_29=dout_14&dout_21;
dout_30=dout_14^dout_21;
dout_31=dout_15^dout_22;
dout_32=dout_15&dout_22;
dout_34=dout_31^dout_29;
dout_35=dout_32|dout_29;
dout_36=dout_16^dout_23;
dout_37=dout_16&dout_23;
dout_38=dout_36&dout_35;
dout_39=dout_36^dout_35;
dout_40=dout_37|dout_38;
dout_41=dout_17^dout_24;
dout_42=dout_17&dout_24;
dout_43=dout_41&dout_40;
dout_44=dout_41^dout_40;
dout_45=dout_42|dout_43;
dout_46=dout_18^dout_25;
dout_47=dout_18&dout_25;
dout_48=dout_46&dout_45;
dout_49=dout_46^dout_45;
dout_50=dout_47|dout_48;
dout_51=dout_19^dout_26;
dout_52=dout_19&dout_26;
dout_53=dout_51&dout_50;
dout_54=dout_51^dout_50;
dout_55=dout_52|dout_53;
dout_56=dout_20^dout_27;
dout_57=dout_20&dout_27;
dout_58=dout_56&dout_55;
dout_59=dout_56^dout_55;
dout_60=dout_57|dout_58;
dout_61=dout_60&dout_28;
dout_62=dout_60^dout_28;
dout_63=((A >> 0)&1)&((B >> 2)&1);
dout_64=((A >> 1)&1)&((B >> 2)&1);
dout_65=((A >> 2)&1)&((B >> 2)&1);
dout_66=((A >> 3)&1)&((B >> 2)&1);
dout_67=((A >> 4)&1)&((B >> 2)&1);
dout_68=((A >> 5)&1)&((B >> 2)&1);
dout_69=((A >> 6)&1)&((B >> 2)&1);
dout_70=((A >> 7)&1)&((B >> 2)&1);
dout_71=dout_34&dout_63;
dout_72=dout_34^dout_63;
dout_73=dout_39^dout_64;
dout_74=dout_39&dout_64;
dout_75=dout_73&dout_71;
dout_76=dout_73^dout_71;
dout_77=dout_74|dout_75;
dout_78=dout_44^dout_65;
dout_79=dout_44&dout_65;
dout_80=dout_78&dout_77;
dout_81=dout_78^dout_77;
dout_82=dout_79|dout_80;
dout_83=dout_49^dout_66;
dout_84=dout_49&dout_66;
dout_85=dout_83&dout_82;
dout_86=dout_83^dout_82;
dout_87=dout_84|dout_85;
dout_88=dout_54^dout_67;
dout_89=dout_54&dout_67;
dout_90=dout_88&dout_87;
dout_91=dout_88^dout_87;
dout_92=dout_89|dout_90;
dout_93=dout_59^dout_68;
dout_94=dout_59&dout_68;
dout_95=dout_93&dout_92;
dout_96=dout_93^dout_92;
dout_97=dout_94|dout_95;
dout_98=dout_62^dout_69;
dout_99=dout_62&dout_69;
dout_100=dout_98&dout_97;
dout_101=dout_98^dout_97;
dout_102=dout_99|dout_100;
dout_103=dout_61^dout_70;
dout_104=dout_61&dout_70;
dout_105=dout_103&dout_102;
dout_106=dout_103^dout_102;
dout_107=dout_104|dout_105;
dout_108=((A >> 0)&1)&((B >> 3)&1);
dout_109=((A >> 1)&1)&((B >> 3)&1);
dout_110=((A >> 2)&1)&((B >> 3)&1);
dout_111=((A >> 3)&1)&((B >> 3)&1);
dout_112=((A >> 4)&1)&((B >> 3)&1);
dout_113=((A >> 5)&1)&((B >> 3)&1);
dout_114=((A >> 6)&1)&((B >> 3)&1);
dout_115=((A >> 7)&1)&((B >> 3)&1);
dout_116=dout_76&dout_108;
dout_117=dout_76^dout_108;
dout_118=dout_81^dout_109;
dout_119=dout_81&dout_109;
dout_120=dout_118&dout_116;
dout_121=dout_118^dout_116;
dout_122=dout_119|dout_120;
dout_123=dout_86^dout_110;
dout_124=dout_86&dout_110;
dout_125=dout_123&dout_122;
dout_126=dout_123^dout_122;
dout_127=dout_124|dout_125;
dout_128=dout_91^dout_111;
dout_129=dout_91&dout_111;
dout_130=dout_128&dout_127;
dout_131=dout_128^dout_127;
dout_132=dout_129|dout_130;
dout_133=dout_96^dout_112;
dout_134=dout_96&dout_112;
dout_135=dout_133&dout_132;
dout_136=dout_133^dout_132;
dout_137=dout_134|dout_135;
dout_138=dout_101^dout_113;
dout_139=dout_101&dout_113;
dout_140=dout_138&dout_137;
dout_141=dout_138^dout_137;
dout_142=dout_139|dout_140;
dout_143=dout_106^dout_114;
dout_144=dout_106&dout_114;
dout_145=dout_143&dout_142;
dout_146=dout_143^dout_142;
dout_147=dout_144|dout_145;
dout_148=dout_107^dout_115;
dout_149=dout_107&dout_115;
dout_150=dout_148&dout_147;
dout_151=dout_148^dout_147;
dout_152=dout_149|dout_150;
dout_153=((A >> 0)&1)&((B >> 4)&1);
dout_154=((A >> 1)&1)&((B >> 4)&1);
dout_155=((A >> 2)&1)&((B >> 4)&1);
dout_156=((A >> 3)&1)&((B >> 4)&1);
dout_157=((A >> 4)&1)&((B >> 4)&1);
dout_158=((A >> 5)&1)&((B >> 4)&1);
dout_159=((A >> 6)&1)&((B >> 4)&1);
dout_160=((A >> 7)&1)&((B >> 4)&1);
dout_161=dout_121&dout_153;
dout_162=dout_121^dout_153;
dout_163=dout_126^dout_154;
dout_164=dout_126&dout_154;
dout_165=dout_163&dout_161;
dout_166=dout_163^dout_161;
dout_167=dout_164|dout_165;
dout_168=dout_131^dout_155;
dout_169=dout_131&dout_155;
dout_170=dout_168&dout_167;
dout_171=dout_168^dout_167;
dout_172=dout_169|dout_170;
dout_173=dout_136^dout_156;
dout_174=dout_136&dout_156;
dout_175=dout_173&dout_172;
dout_176=dout_173^dout_172;
dout_177=dout_174|dout_175;
dout_178=dout_141^dout_157;
dout_179=dout_141&dout_157;
dout_180=dout_178&dout_177;
dout_181=dout_178^dout_177;
dout_182=dout_179|dout_180;
dout_183=dout_146^dout_158;
dout_184=dout_146&dout_158;
dout_185=dout_183&dout_182;
dout_186=dout_183^dout_182;
dout_187=dout_184|dout_185;
dout_188=dout_151^dout_159;
dout_189=dout_151&dout_159;
dout_190=dout_188&dout_187;
dout_191=dout_188^dout_187;
dout_192=dout_189|dout_190;
dout_193=dout_152^dout_160;
dout_194=dout_152&dout_160;
dout_195=dout_193&dout_192;
dout_196=dout_193^dout_192;
dout_197=dout_194|dout_195;
O = 0;
O |= (dout_13&1) << 0;
O |= (dout_30&1) << 1;
O |= (dout_72&1) << 2;
O |= (dout_117&1) << 3;
O |= (dout_162&1) << 4;
O |= (dout_166&1) << 5;
O |= (dout_171&1) << 6;
O |= (dout_176&1) << 7;
O |= (dout_181&1) << 8;
O |= (dout_186&1) << 9;
O |= (dout_191&1) << 10;
O |= (dout_196&1) << 11;
O |= (dout_197&1) << 12;
return O;
}
|
the_stack_data/150140722.c | /** @file patest_mono.c
@ingroup test_src
@brief Play a monophonic sine wave using the Portable Audio api for several seconds.
@author Phil Burk http://www.softsynth.com
*/
/*
* $Id: patest_mono.c 1915 2014-01-16 17:51:26Z philburk $
*
* Authors:
* Ross Bencina <[email protected]>
* Phil Burk <[email protected]>
*
* This program uses the PortAudio Portable Audio Library.
* For more information see: http://www.portaudio.com
* Copyright (c) 1999-2000 Ross Bencina and Phil Burk
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files
* (the "Software"), to deal in the Software without restriction,
* including without limitation the rights to use, copy, modify, merge,
* publish, distribute, sublicense, and/or sell copies of the Software,
* and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR
* ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
/*
* The text above constitutes the entire PortAudio license; however,
* the PortAudio community also makes the following non-binding requests:
*
* Any person wishing to distribute modifications to the Software is
* requested to send the modifications to the original developer so that
* they can be incorporated into the canonical version. It is also
* requested that these non-binding requests be included along with the
* license above.
*/
#include <stdio.h>
#include <math.h>
#include "portaudio.h"
#define NUM_SECONDS (10)
#define SAMPLE_RATE (44100)
#define AMPLITUDE (0.8)
#define FRAMES_PER_BUFFER (64)
#define OUTPUT_DEVICE Pa_GetDefaultOutputDevice()
#ifndef M_PI
#define M_PI (3.14159265)
#endif
#define TABLE_SIZE (200)
typedef struct
{
float sine[TABLE_SIZE];
int phase;
}
paTestData;
/* This routine will be called by the PortAudio engine when audio is needed.
** It may called at interrupt level on some machines so don't do anything
** that could mess up the system like calling malloc() or free().
*/
static int patestCallback( const void *inputBuffer, void *outputBuffer,
unsigned long framesPerBuffer,
const PaStreamCallbackTimeInfo* timeInfo,
PaStreamCallbackFlags statusFlags,
void *userData )
{
paTestData *data = (paTestData*)userData;
float *out = (float*)outputBuffer;
unsigned long i;
int finished = 0;
/* avoid unused variable warnings */
(void) inputBuffer;
(void) timeInfo;
(void) statusFlags;
for( i=0; i<framesPerBuffer; i++ )
{
*out++ = data->sine[data->phase]; /* left */
data->phase += 1;
if( data->phase >= TABLE_SIZE ) data->phase -= TABLE_SIZE;
}
return finished;
}
/*******************************************************************/
int main(void);
int main(void)
{
PaStreamParameters outputParameters;
PaStream *stream;
PaError err;
paTestData data;
int i;
printf("PortAudio Test: output MONO sine wave. SR = %d, BufSize = %d\n", SAMPLE_RATE, FRAMES_PER_BUFFER);
/* initialise sinusoidal wavetable */
for( i=0; i<TABLE_SIZE; i++ )
{
data.sine[i] = (float) (AMPLITUDE * sin( ((double)i/(double)TABLE_SIZE) * M_PI * 2. ));
}
data.phase = 0;
err = Pa_Initialize();
if( err != paNoError ) goto error;
outputParameters.device = OUTPUT_DEVICE;
outputParameters.channelCount = 1; /* MONO output */
outputParameters.sampleFormat = paFloat32; /* 32 bit floating point output */
outputParameters.suggestedLatency = Pa_GetDeviceInfo( outputParameters.device )->defaultLowOutputLatency;
outputParameters.hostApiSpecificStreamInfo = NULL;
err = Pa_OpenStream(
&stream,
NULL, /* no input */
&outputParameters,
SAMPLE_RATE,
FRAMES_PER_BUFFER,
paClipOff, /* we won't output out of range samples so don't bother clipping them */
patestCallback,
&data );
if( err != paNoError ) goto error;
err = Pa_StartStream( stream );
if( err != paNoError ) goto error;
printf("Play for %d seconds.\n", NUM_SECONDS ); fflush(stdout);
Pa_Sleep( NUM_SECONDS * 1000 );
err = Pa_StopStream( stream );
if( err != paNoError ) goto error;
err = Pa_CloseStream( stream );
if( err != paNoError ) goto error;
Pa_Terminate();
printf("Test finished.\n");
return err;
error:
Pa_Terminate();
fprintf( stderr, "An error occured while using the portaudio stream\n" );
fprintf( stderr, "Error number: %d\n", err );
fprintf( stderr, "Error message: %s\n", Pa_GetErrorText( err ) );
return err;
}
|
the_stack_data/115377.c | #include <stdio.h>
#include <stdlib.h>
#include <netinet/in.h>
#include <netdb.h>
int main(int argc, char* argv[])
{
int i;
/* Indirizzo nella forma alfanumerica */
char* ind_alphanum = "www.lwn.com";
/* I sistemi operativi che utilizzano lo standard POSIX conservano gli
indirizzi in una variabile di tipo in_addr_t */
in_addr_t ind;
/* La funzione gethostbyname() restituisce un puntatore alla struttura
hostent, contenente svariate informazioni relative all'host, nel caso
specifico le informazioni riguardano l'host ind_alphanum */
struct hostent* host_info;
host_info = gethostbyname(ind_alphanum);
if (host_info == NULL) {
perror("gethostbyname");
return -1;
}
printf("Informazioni circa il nodo: %s\n", ind_alphanum);
/* Si estrae il primo indirizzo numerico mediante un cast */
ind = *((in_addr_t*)(host_info->h_addr_list[0]));
/* Si stampano tutte le informazioni circa il nodo ind_alphanum */
printf("h_name - nome ufficiale: ");
for (i = 0; host_info->h_name[i] != 0; i++) {
printf("%c", host_info->h_name[i]);
}
printf("\n");
printf("h_addrtype - tipo di indirizzo: %d\n", host_info->h_addrtype);
printf("h_length - dimensioni indirizzo: %d byte\n", host_info->h_length);
printf("h_addr_list- lista degli indirizzi (IP 32bit): %u\n", ind);
return (EXIT_SUCCESS);
}
|
the_stack_data/132431.c | /*
* This is the lowest address in Mesa
*/
void glx_lowpc(void) { }
|
the_stack_data/1162517.c | // Square of number using functions
#include <stdio.h>
int main()
{
int square(int);
int num;
printf("Enter Number : ");
scanf("%d", &num);
printf("Result is %d", square(num));
return 0;
}
int square(int num)
{
return (num * num);
} |
the_stack_data/192330328.c |
// The Computer Language Benchmarks Game
// http://benchmarksgame.alioth.debian.org/
//
// Contributed by Kevin Miller
//
// ver 2: added a couple of optimizations
// - Reduced number of times a vector of 8 was checked to see if
// they had all escaped, similar to Dominic Letz's C #5 entry.
// - Processed 64 pixels at a time if width was a multiple of 64,
// thereby reducing writes to the bitmap.
//
// compile with following gcc flags
// -pipe -Wall -O3 -ffast-math -fno-finite-math-only -march=native -mfpmath=sse -msse3 -fopenmp
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <emmintrin.h>
long numDigits(long n)
{
long len = 0;
while(n)
{
n=n/10;
len++;
}
return len;
}
inline long vec_nle(__m128d *v, double f)
{
return (v[0][0] <= f ||
v[0][1] <= f ||
v[1][0] <= f ||
v[1][1] <= f ||
v[2][0] <= f ||
v[2][1] <= f ||
v[3][0] <= f ||
v[3][1] <= f) ? 0 : -1;
}
inline void clrPixels_nle(__m128d *v, double f, unsigned long * pix8)
{
if(!(v[0][0] <= f)) *pix8 &= 0x7f;
if(!(v[0][1] <= f)) *pix8 &= 0xbf;
if(!(v[1][0] <= f)) *pix8 &= 0xdf;
if(!(v[1][1] <= f)) *pix8 &= 0xef;
if(!(v[2][0] <= f)) *pix8 &= 0xf7;
if(!(v[2][1] <= f)) *pix8 &= 0xfb;
if(!(v[3][0] <= f)) *pix8 &= 0xfd;
if(!(v[3][1] <= f)) *pix8 &= 0xfe;
}
inline void calcSum(__m128d *r, __m128d *i, __m128d *sum, __m128d *init_r, __m128d init_i)
{
for(long pair=0; pair<4; pair++)
{
__m128d r2 = r[pair] * r[pair];
__m128d i2 = i[pair] * i[pair];
__m128d ri = r[pair] * i[pair];
sum[pair] = r2 + i2;
r[pair]=r2 - i2 + init_r[pair];
i[pair]=ri + ri + init_i;
}
}
inline unsigned long mand8(__m128d *init_r, __m128d init_i)
{
__m128d r[4], i[4], sum[4];
for(long pair=0; pair<4; pair++)
{
r[pair]=init_r[pair];
i[pair]=init_i;
}
unsigned long pix8 = 0xff;
for (long j = 0; j < 6; j++)
{
for(long k=0; k<8; k++)
calcSum(r, i, sum, init_r, init_i);
if (vec_nle(sum, 4.0))
{
pix8 = 0x00;
break;
}
}
if (pix8)
{
calcSum(r, i, sum, init_r, init_i);
calcSum(r, i, sum, init_r, init_i);
clrPixels_nle(sum, 4.0, &pix8);
}
return pix8;
}
unsigned long mand64(__m128d *init_r, __m128d init_i)
{
unsigned long pix64 = 0;
for(long byte=0; byte<8; byte++)
{
unsigned long pix8 = mand8(init_r, init_i);
pix64 = (pix64 >> 8) | (pix8 << 56);
init_r += 4;
}
return pix64;
}
int main(int argc, char ** argv)
{
// get width/height from arguments
long wid_ht = 16000;
if (argc >= 2)
{
wid_ht = atoi(argv[1]);
}
wid_ht = (wid_ht+7) & ~7;
// allocate memory for header and pixels
long headerLength = numDigits(wid_ht)*2+5;
long pad = ((headerLength + 7) & ~7) - headerLength; // pad aligns pixels on 8
long dataLength = headerLength + wid_ht*(wid_ht>>3);
unsigned char * const buffer = malloc(pad + dataLength);
unsigned char * const header = buffer + pad;
unsigned char * const pixels = header + headerLength;
// generate the bitmap header
sprintf((char *)header, "P4\n%ld %ld\n", wid_ht, wid_ht);
// calculate initial values, store in r0, i0
__m128d r0[wid_ht/2];
double i0[wid_ht];
for(long xy=0; xy<wid_ht; xy+=2)
{
r0[xy>>1] = 2.0 / wid_ht * (__m128d){xy, xy+1} - 1.5;
i0[xy] = 2.0 / wid_ht * xy - 1.0;
i0[xy+1] = 2.0 / wid_ht * (xy+1) - 1.0;
}
// generate the bitmap
long use8 = wid_ht%64;
if (use8)
{
// process 8 pixels (one byte) at a time
#pragma omp parallel for schedule(guided)
for(long y=0; y<wid_ht; y++)
{
__m128d init_i = (__m128d){i0[y], i0[y]};
long rowstart = y*wid_ht/8;
for(long x=0; x<wid_ht; x+=8)
{
pixels[rowstart + x/8] = mand8(r0+x/2, init_i);
}
}
}
else
{
// process 64 pixels (8 bytes) at a time
#pragma omp parallel for schedule(guided)
for(long y=0; y<wid_ht; y++)
{
__m128d init_i = (__m128d){i0[y], i0[y]};
long rowstart = y*wid_ht/64;
for(long x=0; x<wid_ht; x+=64)
{
((unsigned long *)pixels)[rowstart + x/64] = mand64(r0+x/2, init_i);
}
}
}
// write the data
long ret = ret = write(STDOUT_FILENO, header, dataLength);
free(buffer);
return 0;
}
/*
NOTES:
64-bit Ubuntu quad core
gcc (Ubuntu 6.3.0-12ubuntu2) 6.3.0 20170406
Fri, 14 Apr 2017 17:27:08 GMT
MAKE:
/usr/bin/gcc -pipe -Wall -O3 -fomit-frame-pointer -march=native -mno-fma -fno-finite-math-only -mfpmath=sse -msse2 -fopenmp mandelbrot.gcc-6.c -o mandelbrot.gcc-6.gcc_run
rm mandelbrot.gcc-6.c
0.30s to complete and log all make actions
COMMAND LINE:
./mandelbrot.gcc-6.gcc_run 16000
(BINARY) PROGRAM OUTPUT NOT SHOWN
*/
|
the_stack_data/75136430.c |
int maxProfit(int *prices, int prices_sz)
{
/* sanity check */
if (!prices_sz)
return 0;
int profit = 0;
/**
* tran_head[i]: max profix from day 0 to day i
* tran_tail[i]: max profix from day i to last day
*/
int *tran_head = malloc(sizeof(int) * prices_sz);
int *tran_tail = malloc(sizeof(int) * prices_sz);
tran_head[0] = 0, tran_tail[prices_sz - 1] = 0;
int min_idx = 0;
for (int i = 1; i < prices_sz; i++) {
int diff = prices[i] - prices[min_idx];
tran_head[i] = (tran_head[i - 1] > diff ? tran_head[i - 1] : diff);
min_idx = (prices[i] < prices[min_idx] ? i : min_idx);
}
int max_idx = prices_sz - 1;
for (int i = prices_sz - 2; i >= 0; i--) {
int diff = prices[max_idx] - prices[i];
tran_tail[i] = (tran_tail[i + 1] > diff ? tran_tail[i + 1] : diff);
max_idx = (prices[i] > prices[max_idx] ? i : max_idx);
}
/* calculate the possible max value of twice tranaction */
for (int i = 1; i < prices_sz - 2; i++) {
int cur = tran_head[i] + tran_tail[i + 1];
profit = (profit > cur ? profit : cur);
}
/* consider one transaction case */
profit =
(profit > tran_head[prices_sz - 1] ? profit : tran_head[prices_sz - 1]);
/* release memory */
free(tran_head);
free(tran_tail);
return profit;
}
|
the_stack_data/33431.c | /* Test40.c
*
* Test select(...) system call
*
*/
#include <sys/types.h>
#include <sys/wait.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <stdarg.h>
int main(int argc, char **argv) {
char *tests[] = {"t40a", "t40b", "t40c", "t40d", "t40e", "t40f"};
int no_tests, i, forkres, status = 0, errorct = 0;
no_tests = sizeof(tests) / sizeof(char *);
printf("Test 40 ");
fflush(stdout);
for(i = 0; i < no_tests; i++) {
char subtest[2];
sprintf(subtest, "%d", i+1);
forkres = fork();
if(forkres == 0) { /* Child */
execl(tests[i], tests[i], subtest, (char *) 0);
printf("Failed to execute subtest %s\n", tests[i]);
exit(-2);
} else if(forkres > 0) { /* Parent */
if(waitpid(forkres, &status, 0) > 0 && WEXITSTATUS(status) < 20) {
errorct += WEXITSTATUS(status); /* Count errors */
}
status = 0; /* Reset */
} else {
printf("Failed to fork\n");
exit(-2);
}
}
if(errorct == 0) {
printf("ok\n");
exit(0);
} else {
printf("%d error(s)\n", errorct);
exit(1);
}
return (-1); /* Impossible */
}
|
the_stack_data/14377.c | /* { dg-do compile } */
/* { dg-options "-O2 -mno-indirect-branch-register -mfunction-return=keep -mindirect-branch=thunk-inline -fno-pic" } */
typedef void (*dispatch_t)(long offset);
dispatch_t dispatch[256];
int
male_indirect_jump (long offset)
{
dispatch[offset](offset);
return 0;
}
/* { dg-final { scan-assembler "mov(?:l|q)\[ \t\]*_?dispatch" { target *-*-linux* } } } */
/* { dg-final { scan-assembler-times "jmp\[ \t\]*\.LIND" 2 } } */
/* { dg-final { scan-assembler-times "call\[ \t\]*\.LIND" 2 } } */
/* { dg-final { scan-assembler-times {\tpause} 1 } } */
/* { dg-final { scan-assembler-times {\tlfence} 1 } } */
/* { dg-final { scan-assembler-not "__x86_indirect_thunk" } } */
/* { dg-final { scan-assembler-not "pushq\[ \t\]%rax" { target x32 } } } */
|
the_stack_data/73574264.c |
#include <stdlib.h>
#include <stdio.h>
#include <stdbool.h>
#include <string.h>
#include <time.h>
#include <math.h>
void dump(int a[], int size) {
if (size <= 0) { return; }
printf("\n");
int i = 0;
for (i = 0; i < size; i++) { printf("%d ", a[i]); }
printf("\n");
return;
}
//----------------------------
//桶排序
//将数据分在一个个桶里,每个桶里面用快速排序
int partition(int a[], int left, int right) {
int i = left, j = left, key = a[right];
for (; j < right; j++) {
if (a[j] < key ) {
if (i != j) {
int tmp1 = a[j];
a[j] = a[i];
a[i] = tmp1;
}
i++;
}
}
int tmp2 = a[i];
a[i] = a[right];
a[right] = tmp2;
return i;
}
void quick_sort(int a[], int left, int right) {
if (left >= right) { return; }
int m = partition(a, left, right);
quick_sort(a, left, m - 1);
quick_sort(a, m + 1, right);
}
struct barrel {
int node[10];
int count;
};
void bucket_sort(int data[], int size) {
int max, min, num, pos;
int i, j, k;
struct barrel *pBarrel;
max = min = data[0];
for (i = 1; i < size; i++) {
if (data[i] > max) {
max = data[i];
} else if(data[i] < min) {
min = data[i];
}
}
num = (max - min + 1) / 10 + 1; //根据数据范围,确定要创建多少个桶,每个桶里放的不多于10个
pBarrel = (struct barrel *)malloc(sizeof(struct barrel) * num);
memset(pBarrel, 0, sizeof(struct barrel) * num);
//将数据放入对应的桶中,每个桶中的数据范围 k*10+(0...9)
for (i = 0; i < size; i++) {
k = (data[i] - min + 1) / 10;
(pBarrel + k)->node[(pBarrel + k)->count] = data[i];
(pBarrel + k)->count++;
}
//分别对各个桶中的数据进行排序
pos = 0;
for (i = 0; i < num; i++) {
if ((pBarrel + i)->count > 0) {
quick_sort((pBarrel + i)->node, 0, (pBarrel + i)->count - 1);
for (j = 0; j < (pBarrel + i)->count; j++) {
data[pos] = (pBarrel + i)->node[j];
pos++;
}
}
}
free(pBarrel);
}
//----------------------------
//计数排序。跟桶排序类似,排序的数据非负数,只能用在数据范围不大的场景中
//时间复杂度 O(n), 非原地排序
void count_sort(int a[], int size) {
int max = 0, i = 0, *count = 0, *res = 0;
//找到最大值
for (i = 0; i < size; i++) {
if (a[i] > max) {
max = a[i];
}
}
//计数
count = (int *)malloc(sizeof(int) * (max + 1));
if (count == NULL) { return; }
memset(count, 0, sizeof(int) * (max + 1));
for (i = 0; i < size; i++) {
count[a[i]]++;
}
//依次累加,当前位的值是前面累加的和
for (i = 1; i <= max; i++) {
count[i] += count[i - 1];
}
//核心代码,count[a[i]] - 1 就是排序好的s下标。思考一下为什么
res = (int *)malloc(sizeof(int) * size);
if (res == NULL) { return; }
for (i = size - 1; i >= 0; i--) {
res[count[a[i]] - 1] = a[i];
count[a[i]]--;
}
memcpy(a, res, sizeof(int) * size);
free(res);
free(count);
return;
}
//----------------------------
//基数排序
//
#define NUM_OF_POS(a,pval) ((a)/pval)%10
void radix_sort(int a[], int size, int num_count) {
int count[10] = {0};
int *pres = NULL;
int i = 0, j = 0, pval = 10, index = 0, break_flg = 0;
pres = (int *)malloc(sizeof(int) * size);
if (pres == NULL) { return; }
for (i = 0; i < num_count; i++) {
memset(count, 0, sizeof(int) * 10);
//求当前的基数
pval = pow(10, i);
//计数
for (j = 0; j < size; j++) {
index = (a[j]/pval)%10;
count[index]++;
}
if (count[0] == 9) {
break_flg++;
}
if (break_flg >= 2) {
printf("%i", i);
break;
}
for (j = 1; j < 10; j++) {
count[j] += count[j - 1];
}
for (j = size - 1; j >= 0; j--) {
index = (a[j]/pval)%10;
pres[count[index] - 1] = a[j];
count[index]--;
}
memcpy(a, pres, sizeof(int) * size);
}
return;
}
//----------------------------
int main(int argc, const char * argv[]) {
// insert code here...
printf("Hello, World!\n");
int a[] = {2,7,6,8,1,3,0,9,5,11,15,23,16,4,18,26};
int size = sizeof(a)/sizeof(int);
bucket_sort(a, size);
//count_sort(a, size);
dump(a, size);
// //桶排序
// int testa1[200][2000];
// int i = 0, j = 0;
// for (i = 0; i < 200; i++) {
// for (j = 0; j < 2000; j++) {
// int value = arc4random() % 100000;
// testa1[i][j] = value + 1;
// }
// }
//
// clock_t start1, end1;
// double cpu_time_used;
// start1 = clock();
// for (i = 0; i < 200; i++) {
// bucket_sort(testa1[i], 2000);
// }
// end1 = clock();
// cpu_time_used = ((double) (end1 - start1)) / CLOCKS_PER_SEC;
// printf("--------- = %.8lf\n", cpu_time_used);
// //--------- = 0.02081200
//基数排序
int a2[10] = {123,12341,1232134,124,236,128,1112313129,98,9,8989};
radix_sort(a2,10,10);
dump(a2,10);
return 0;
}
|
the_stack_data/63879.c | /**
******************************************************************************
* @file stm32f1xx_ll_usart.c
* @author MCD Application Team
* @version V1.1.1
* @date 12-May-2017
* @brief USART LL module driver.
******************************************************************************
* @attention
*
* <h2><center>© COPYRIGHT(c) 2016 STMicroelectronics</center></h2>
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. Neither the name of STMicroelectronics nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
******************************************************************************
*/
#if defined(USE_FULL_LL_DRIVER)
/* Includes ------------------------------------------------------------------*/
#include "stm32f1xx_ll_usart.h"
#include "stm32f1xx_ll_rcc.h"
#include "stm32f1xx_ll_bus.h"
#ifdef USE_FULL_ASSERT
#include "stm32_assert.h"
#else
#define assert_param(expr) ((void)0U)
#endif
/** @addtogroup STM32F1xx_LL_Driver
* @{
*/
#if defined (USART1) || defined (USART2) || defined (USART3) || defined (UART4) || defined (UART5)
/** @addtogroup USART_LL
* @{
*/
/* Private types -------------------------------------------------------------*/
/* Private variables ---------------------------------------------------------*/
/* Private constants ---------------------------------------------------------*/
/** @addtogroup USART_LL_Private_Constants
* @{
*/
/**
* @}
*/
/* Private macros ------------------------------------------------------------*/
/** @addtogroup USART_LL_Private_Macros
* @{
*/
/* __BAUDRATE__ The maximum Baud Rate is derived from the maximum clock available
* divided by the smallest oversampling used on the USART (i.e. 8) */
#define IS_LL_USART_BAUDRATE(__BAUDRATE__) ((__BAUDRATE__) <= 10000000U)
#define IS_LL_USART_DIRECTION(__VALUE__) (((__VALUE__) == LL_USART_DIRECTION_NONE) \
|| ((__VALUE__) == LL_USART_DIRECTION_RX) \
|| ((__VALUE__) == LL_USART_DIRECTION_TX) \
|| ((__VALUE__) == LL_USART_DIRECTION_TX_RX))
#define IS_LL_USART_PARITY(__VALUE__) (((__VALUE__) == LL_USART_PARITY_NONE) \
|| ((__VALUE__) == LL_USART_PARITY_EVEN) \
|| ((__VALUE__) == LL_USART_PARITY_ODD))
#define IS_LL_USART_DATAWIDTH(__VALUE__) (((__VALUE__) == LL_USART_DATAWIDTH_8B) \
|| ((__VALUE__) == LL_USART_DATAWIDTH_9B))
#define IS_LL_USART_OVERSAMPLING(__VALUE__) (((__VALUE__) == LL_USART_OVERSAMPLING_16) \
|| ((__VALUE__) == LL_USART_OVERSAMPLING_8))
#define IS_LL_USART_LASTBITCLKOUTPUT(__VALUE__) (((__VALUE__) == LL_USART_LASTCLKPULSE_NO_OUTPUT) \
|| ((__VALUE__) == LL_USART_LASTCLKPULSE_OUTPUT))
#define IS_LL_USART_CLOCKPHASE(__VALUE__) (((__VALUE__) == LL_USART_PHASE_1EDGE) \
|| ((__VALUE__) == LL_USART_PHASE_2EDGE))
#define IS_LL_USART_CLOCKPOLARITY(__VALUE__) (((__VALUE__) == LL_USART_POLARITY_LOW) \
|| ((__VALUE__) == LL_USART_POLARITY_HIGH))
#define IS_LL_USART_CLOCKOUTPUT(__VALUE__) (((__VALUE__) == LL_USART_CLOCK_DISABLE) \
|| ((__VALUE__) == LL_USART_CLOCK_ENABLE))
#define IS_LL_USART_STOPBITS(__VALUE__) (((__VALUE__) == LL_USART_STOPBITS_0_5) \
|| ((__VALUE__) == LL_USART_STOPBITS_1) \
|| ((__VALUE__) == LL_USART_STOPBITS_1_5) \
|| ((__VALUE__) == LL_USART_STOPBITS_2))
#define IS_LL_USART_HWCONTROL(__VALUE__) (((__VALUE__) == LL_USART_HWCONTROL_NONE) \
|| ((__VALUE__) == LL_USART_HWCONTROL_RTS) \
|| ((__VALUE__) == LL_USART_HWCONTROL_CTS) \
|| ((__VALUE__) == LL_USART_HWCONTROL_RTS_CTS))
/**
* @}
*/
/* Private function prototypes -----------------------------------------------*/
/* Exported functions --------------------------------------------------------*/
/** @addtogroup USART_LL_Exported_Functions
* @{
*/
/** @addtogroup USART_LL_EF_Init
* @{
*/
/**
* @brief De-initialize USART registers (Registers restored to their default values).
* @param USARTx USART Instance
* @retval An ErrorStatus enumeration value:
* - SUCCESS: USART registers are de-initialized
* - ERROR: USART registers are not de-initialized
*/
ErrorStatus LL_USART_DeInit(USART_TypeDef *USARTx)
{
ErrorStatus status = SUCCESS;
/* Check the parameters */
assert_param(IS_UART_INSTANCE(USARTx));
if (USARTx == USART1)
{
/* Force reset of USART clock */
LL_APB2_GRP1_ForceReset(LL_APB2_GRP1_PERIPH_USART1);
/* Release reset of USART clock */
LL_APB2_GRP1_ReleaseReset(LL_APB2_GRP1_PERIPH_USART1);
}
else if (USARTx == USART2)
{
/* Force reset of USART clock */
LL_APB1_GRP1_ForceReset(LL_APB1_GRP1_PERIPH_USART2);
/* Release reset of USART clock */
LL_APB1_GRP1_ReleaseReset(LL_APB1_GRP1_PERIPH_USART2);
}
#if defined(USART3)
else if (USARTx == USART3)
{
/* Force reset of USART clock */
LL_APB1_GRP1_ForceReset(LL_APB1_GRP1_PERIPH_USART3);
/* Release reset of USART clock */
LL_APB1_GRP1_ReleaseReset(LL_APB1_GRP1_PERIPH_USART3);
}
#endif /* USART3 */
#if defined(UART4)
else if (USARTx == UART4)
{
/* Force reset of UART clock */
LL_APB1_GRP1_ForceReset(LL_APB1_GRP1_PERIPH_UART4);
/* Release reset of UART clock */
LL_APB1_GRP1_ReleaseReset(LL_APB1_GRP1_PERIPH_UART4);
}
#endif /* UART4 */
#if defined(UART5)
else if (USARTx == UART5)
{
/* Force reset of UART clock */
LL_APB1_GRP1_ForceReset(LL_APB1_GRP1_PERIPH_UART5);
/* Release reset of UART clock */
LL_APB1_GRP1_ReleaseReset(LL_APB1_GRP1_PERIPH_UART5);
}
#endif /* UART5 */
else
{
status = ERROR;
}
return (status);
}
/**
* @brief Initialize USART registers according to the specified
* parameters in USART_InitStruct.
* @note As some bits in USART configuration registers can only be written when the USART is disabled (USART_CR1_UE bit =0),
* USART IP should be in disabled state prior calling this function. Otherwise, ERROR result will be returned.
* @note Baud rate value stored in USART_InitStruct BaudRate field, should be valid (different from 0).
* @param USARTx USART Instance
* @param USART_InitStruct: pointer to a LL_USART_InitTypeDef structure
* that contains the configuration information for the specified USART peripheral.
* @retval An ErrorStatus enumeration value:
* - SUCCESS: USART registers are initialized according to USART_InitStruct content
* - ERROR: Problem occurred during USART Registers initialization
*/
ErrorStatus LL_USART_Init(USART_TypeDef *USARTx, LL_USART_InitTypeDef *USART_InitStruct)
{
ErrorStatus status = ERROR;
uint32_t periphclk = LL_RCC_PERIPH_FREQUENCY_NO;
LL_RCC_ClocksTypeDef rcc_clocks;
/* Check the parameters */
assert_param(IS_UART_INSTANCE(USARTx));
assert_param(IS_LL_USART_BAUDRATE(USART_InitStruct->BaudRate));
assert_param(IS_LL_USART_DATAWIDTH(USART_InitStruct->DataWidth));
assert_param(IS_LL_USART_STOPBITS(USART_InitStruct->StopBits));
assert_param(IS_LL_USART_PARITY(USART_InitStruct->Parity));
assert_param(IS_LL_USART_DIRECTION(USART_InitStruct->TransferDirection));
assert_param(IS_LL_USART_HWCONTROL(USART_InitStruct->HardwareFlowControl));
#if defined(USART_CR1_OVER8)
assert_param(IS_LL_USART_OVERSAMPLING(USART_InitStruct->OverSampling));
#endif /* USART_OverSampling_Feature */
/* USART needs to be in disabled state, in order to be able to configure some bits in
CRx registers */
if (LL_USART_IsEnabled(USARTx) == 0U)
{
/*---------------------------- USART CR1 Configuration -----------------------
* Configure USARTx CR1 (USART Word Length, Parity, Mode and Oversampling bits) with parameters:
* - DataWidth: USART_CR1_M bits according to USART_InitStruct->DataWidth value
* - Parity: USART_CR1_PCE, USART_CR1_PS bits according to USART_InitStruct->Parity value
* - TransferDirection: USART_CR1_TE, USART_CR1_RE bits according to USART_InitStruct->TransferDirection value
* - Oversampling: USART_CR1_OVER8 bit according to USART_InitStruct->OverSampling value.
*/
#if defined(USART_CR1_OVER8)
MODIFY_REG(USARTx->CR1,
(USART_CR1_M | USART_CR1_PCE | USART_CR1_PS |
USART_CR1_TE | USART_CR1_RE | USART_CR1_OVER8),
(USART_InitStruct->DataWidth | USART_InitStruct->Parity |
USART_InitStruct->TransferDirection | USART_InitStruct->OverSampling));
#else
MODIFY_REG(USARTx->CR1,
(USART_CR1_M | USART_CR1_PCE | USART_CR1_PS |
USART_CR1_TE | USART_CR1_RE),
(USART_InitStruct->DataWidth | USART_InitStruct->Parity |
USART_InitStruct->TransferDirection));
#endif /* USART_OverSampling_Feature */
/*---------------------------- USART CR2 Configuration -----------------------
* Configure USARTx CR2 (Stop bits) with parameters:
* - Stop Bits: USART_CR2_STOP bits according to USART_InitStruct->StopBits value.
* - CLKEN, CPOL, CPHA and LBCL bits are to be configured using LL_USART_ClockInit().
*/
LL_USART_SetStopBitsLength(USARTx, USART_InitStruct->StopBits);
/*---------------------------- USART CR3 Configuration -----------------------
* Configure USARTx CR3 (Hardware Flow Control) with parameters:
* - HardwareFlowControl: USART_CR3_RTSE, USART_CR3_CTSE bits according to USART_InitStruct->HardwareFlowControl value.
*/
LL_USART_SetHWFlowCtrl(USARTx, USART_InitStruct->HardwareFlowControl);
/*---------------------------- USART BRR Configuration -----------------------
* Retrieve Clock frequency used for USART Peripheral
*/
LL_RCC_GetSystemClocksFreq(&rcc_clocks);
if (USARTx == USART1)
{
periphclk = rcc_clocks.PCLK2_Frequency;
}
else if (USARTx == USART2)
{
periphclk = rcc_clocks.PCLK1_Frequency;
}
#if defined(USART3)
else if (USARTx == USART3)
{
periphclk = rcc_clocks.PCLK1_Frequency;
}
#endif /* USART3 */
#if defined(UART4)
else if (USARTx == UART4)
{
periphclk = rcc_clocks.PCLK1_Frequency;
}
#endif /* UART4 */
#if defined(UART5)
else if (USARTx == UART5)
{
periphclk = rcc_clocks.PCLK1_Frequency;
}
#endif /* UART5 */
else
{
/* Nothing to do, as error code is already assigned to ERROR value */
}
/* Configure the USART Baud Rate :
- valid baud rate value (different from 0) is required
- Peripheral clock as returned by RCC service, should be valid (different from 0).
*/
if ((periphclk != LL_RCC_PERIPH_FREQUENCY_NO)
&& (USART_InitStruct->BaudRate != 0U))
{
status = SUCCESS;
#if defined(USART_CR1_OVER8)
LL_USART_SetBaudRate(USARTx,
periphclk,
USART_InitStruct->OverSampling,
USART_InitStruct->BaudRate);
#else
LL_USART_SetBaudRate(USARTx,
periphclk,
USART_InitStruct->BaudRate);
#endif /* USART_OverSampling_Feature */
}
}
/* Endif (=> USART not in Disabled state => return ERROR) */
return (status);
}
/**
* @brief Set each @ref LL_USART_InitTypeDef field to default value.
* @param USART_InitStruct: pointer to a @ref LL_USART_InitTypeDef structure
* whose fields will be set to default values.
* @retval None
*/
void LL_USART_StructInit(LL_USART_InitTypeDef *USART_InitStruct)
{
/* Set USART_InitStruct fields to default values */
USART_InitStruct->BaudRate = 9600U;
USART_InitStruct->DataWidth = LL_USART_DATAWIDTH_8B;
USART_InitStruct->StopBits = LL_USART_STOPBITS_1;
USART_InitStruct->Parity = LL_USART_PARITY_NONE ;
USART_InitStruct->TransferDirection = LL_USART_DIRECTION_TX_RX;
USART_InitStruct->HardwareFlowControl = LL_USART_HWCONTROL_NONE;
#if defined(USART_CR1_OVER8)
USART_InitStruct->OverSampling = LL_USART_OVERSAMPLING_16;
#endif /* USART_OverSampling_Feature */
}
/**
* @brief Initialize USART Clock related settings according to the
* specified parameters in the USART_ClockInitStruct.
* @note As some bits in USART configuration registers can only be written when the USART is disabled (USART_CR1_UE bit =0),
* USART IP should be in disabled state prior calling this function. Otherwise, ERROR result will be returned.
* @param USARTx USART Instance
* @param USART_ClockInitStruct: pointer to a @ref LL_USART_ClockInitTypeDef structure
* that contains the Clock configuration information for the specified USART peripheral.
* @retval An ErrorStatus enumeration value:
* - SUCCESS: USART registers related to Clock settings are initialized according to USART_ClockInitStruct content
* - ERROR: Problem occurred during USART Registers initialization
*/
ErrorStatus LL_USART_ClockInit(USART_TypeDef *USARTx, LL_USART_ClockInitTypeDef *USART_ClockInitStruct)
{
ErrorStatus status = SUCCESS;
/* Check USART Instance and Clock signal output parameters */
assert_param(IS_UART_INSTANCE(USARTx));
assert_param(IS_LL_USART_CLOCKOUTPUT(USART_ClockInitStruct->ClockOutput));
/* USART needs to be in disabled state, in order to be able to configure some bits in
CRx registers */
if (LL_USART_IsEnabled(USARTx) == 0U)
{
/*---------------------------- USART CR2 Configuration -----------------------*/
/* If Clock signal has to be output */
if (USART_ClockInitStruct->ClockOutput == LL_USART_CLOCK_DISABLE)
{
/* Deactivate Clock signal delivery :
* - Disable Clock Output: USART_CR2_CLKEN cleared
*/
LL_USART_DisableSCLKOutput(USARTx);
}
else
{
/* Ensure USART instance is USART capable */
assert_param(IS_USART_INSTANCE(USARTx));
/* Check clock related parameters */
assert_param(IS_LL_USART_CLOCKPOLARITY(USART_ClockInitStruct->ClockPolarity));
assert_param(IS_LL_USART_CLOCKPHASE(USART_ClockInitStruct->ClockPhase));
assert_param(IS_LL_USART_LASTBITCLKOUTPUT(USART_ClockInitStruct->LastBitClockPulse));
/*---------------------------- USART CR2 Configuration -----------------------
* Configure USARTx CR2 (Clock signal related bits) with parameters:
* - Enable Clock Output: USART_CR2_CLKEN set
* - Clock Polarity: USART_CR2_CPOL bit according to USART_ClockInitStruct->ClockPolarity value
* - Clock Phase: USART_CR2_CPHA bit according to USART_ClockInitStruct->ClockPhase value
* - Last Bit Clock Pulse Output: USART_CR2_LBCL bit according to USART_ClockInitStruct->LastBitClockPulse value.
*/
MODIFY_REG(USARTx->CR2,
USART_CR2_CLKEN | USART_CR2_CPHA | USART_CR2_CPOL | USART_CR2_LBCL,
USART_CR2_CLKEN | USART_ClockInitStruct->ClockPolarity |
USART_ClockInitStruct->ClockPhase | USART_ClockInitStruct->LastBitClockPulse);
}
}
/* Else (USART not in Disabled state => return ERROR */
else
{
status = ERROR;
}
return (status);
}
/**
* @brief Set each field of a @ref LL_USART_ClockInitTypeDef type structure to default value.
* @param USART_ClockInitStruct: pointer to a @ref LL_USART_ClockInitTypeDef structure
* whose fields will be set to default values.
* @retval None
*/
void LL_USART_ClockStructInit(LL_USART_ClockInitTypeDef *USART_ClockInitStruct)
{
/* Set LL_USART_ClockInitStruct fields with default values */
USART_ClockInitStruct->ClockOutput = LL_USART_CLOCK_DISABLE;
USART_ClockInitStruct->ClockPolarity = LL_USART_POLARITY_LOW; /* Not relevant when ClockOutput = LL_USART_CLOCK_DISABLE */
USART_ClockInitStruct->ClockPhase = LL_USART_PHASE_1EDGE; /* Not relevant when ClockOutput = LL_USART_CLOCK_DISABLE */
USART_ClockInitStruct->LastBitClockPulse = LL_USART_LASTCLKPULSE_NO_OUTPUT; /* Not relevant when ClockOutput = LL_USART_CLOCK_DISABLE */
}
/**
* @}
*/
/**
* @}
*/
/**
* @}
*/
#endif /* USART1 || USART2 || USART3 || UART4 || UART5 */
/**
* @}
*/
#endif /* USE_FULL_LL_DRIVER */
/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
|
the_stack_data/37638624.c | #ifdef STM32F0xx
#include "stm32f0xx_hal_uart.c"
#endif
#ifdef STM32F1xx
#include "stm32f1xx_hal_uart.c"
#endif
#ifdef STM32F2xx
#include "stm32f2xx_hal_uart.c"
#endif
#ifdef STM32F3xx
#include "stm32f3xx_hal_uart.c"
#endif
#ifdef STM32F4xx
#include "stm32f4xx_hal_uart.c"
#endif
#ifdef STM32F7xx
#include "stm32f7xx_hal_uart.c"
#endif
#ifdef STM32G0xx
#include "stm32g0xx_hal_uart.c"
#endif
#ifdef STM32G4xx
#include "stm32g4xx_hal_uart.c"
#endif
#ifdef STM32H7xx
#include "stm32h7xx_hal_uart.c"
#endif
#ifdef STM32L0xx
#include "stm32l0xx_hal_uart.c"
#endif
#ifdef STM32L1xx
#include "stm32l1xx_hal_uart.c"
#endif
#ifdef STM32L4xx
#include "stm32l4xx_hal_uart.c"
#endif
#ifdef STM32MP1xx
#include "stm32mp1xx_hal_uart.c"
#endif
#ifdef STM32WBxx
#include "stm32wbxx_hal_uart.c"
#endif
|
the_stack_data/125344.c | /* { dg-do compile } */
/* { dg-options "-O1 -fdump-tree-dom2" } */
struct rtx_def;
typedef struct rtx_def *rtx;
struct rtvec_def;
typedef struct rtvec_def *rtvec;
union tree_node;
typedef union tree_node *tree;
typedef struct mem_attrs
{
long alias;
}
mem_attrs;
union rtunion_def
{
mem_attrs *rtmem;
};
typedef union rtunion_def rtunion;
struct rtx_def
{
int code;
rtunion fld[1];
};
struct tree_decl
{
rtx rtl;
};
union tree_node
{
struct tree_decl decl;
};
int make_decl_rtl (tree, void *);
long
get_alias_set (t)
tree t;
{
if (t->decl.rtl != (void *) 0)
return (((t->decl.rtl->fld[1]).rtmem) ==
0 ? 0
: ((((t->decl.
rtl ? 0 : (make_decl_rtl (t, ((void *) 0)),
t->decl.rtl)))->fld[1]).rtmem)->alias);
}
/* The calls to make_decl_rtl should be eliminated. */
/* { dg-final { scan-tree-dump-not "make_decl_rtl \\(\\)" "dom2" } } */
/* There should be two IF conditionals. */
/* { dg-final { scan-tree-dump-times "if " 2 "dom2"} } */
/* There should be one load of decl.rtl. */
/* { dg-final { scan-tree-dump-times "decl\\.rtl" 1 "dom2"} } */
/* There should be two loads of rtmem. */
/* { dg-final { scan-tree-dump-times "rtmem" 2 "dom2"} } */
/* There should be one load of alias. */
/* { dg-final { scan-tree-dump-times "->alias" 1 "dom2"} } */
|
the_stack_data/102402.c | /*
*****************************************************************************
* @file scope.c
* @author Y3288231
* @date Dec 15, 2014
* @brief This file contains oscilloscope functions
*****************************************************************************
*/
// Includes ===================================================================
#ifdef USE_GEN
#include "cmsis_os.h"
#include "mcu_config.h"
#include "comms.h"
#include "generator.h"
#include "dac.h"
#include "tim.h"
// External variables definitions =============================================
xQueueHandle generatorMessageQueue;
uint8_t validateGenBuffUsage(void);
void clearGenBuffer(void);
static volatile generatorTypeDef generator;
uint16_t blindValue=0;
uint16_t generatorBuffer[MAX_GENERATOR_BUFF_SIZE/2];
// Function definitions =======================================================
/**
* @brief Oscilloscope task function.
* task is getting messages from other tasks and takes care about oscilloscope functions
* @param Task handler, parameters pointer
* @retval None
*/
//portTASK_FUNCTION(vScopeTask, pvParameters){
void GeneratorTask(void const *argument){
generatorMessageQueue = xQueueCreate(5, 20);
generatorSetDefault();
char message[20];
while(1){
xQueueReceive(generatorMessageQueue, message, portMAX_DELAY);
if(message[0]=='1'){
}else if(message[0]=='2'){
}else if(message[0]=='3'){ //invalidate
if(generator.state==GENERATOR_IDLE){
}
}else if(message[0]=='4'){ //start
if(generator.state==GENERATOR_IDLE){
genInit();
GeneratingEnable();
generator.state=GENERATOR_RUN;
}
}else if(message[0]=='5'){ //stop
if(generator.state==GENERATOR_RUN){
GeneratingDisable();
generator.state=GENERATOR_IDLE;
}
}
}
}
/**
* @brief Oscilloscope set Default values
* @param None
* @retval None
*/
void generatorSetDefault(void){
generator.bufferMemory=generatorBuffer;
for(uint8_t i = 0;i<MAX_DAC_CHANNELS;i++){
generator.generatingFrequency[i]=DEFAULT_GENERATING_FREQ;
generator.realGenFrequency[i]=DEFAULT_GENERATING_FREQ;
}
generator.numOfChannles=1;
generator.maxOneChanSamples=MAX_GENERATOR_BUFF_SIZE/2;
generator.oneChanSamples[0]=MAX_GENERATOR_BUFF_SIZE/2;
generator.pChanMem[0]=generatorBuffer;
generator.state=GENERATOR_IDLE;
generator.DAC_res=DAC_DATA_DEPTH;
}
void genInit(void){
for(uint8_t i = 0;i<MAX_DAC_CHANNELS;i++){
TIM_Reconfig_gen(generator.generatingFrequency[i],i,0);
if(generator.numOfChannles>i){
DAC_DMA_Reconfig(i,(uint32_t *)generator.pChanMem[i], generator.oneChanSamples[i]);
}else{
DAC_DMA_Reconfig(i,(uint32_t *)&blindValue, 1);
}
}
}
uint8_t genSetData(uint16_t index,uint8_t length,uint8_t chan){
uint8_t result = GEN_INVALID_STATE;
if(generator.state==GENERATOR_IDLE ){
if ((index*2+length)/2<=generator.oneChanSamples[chan-1] && generator.numOfChannles>=chan){
if(commBufferReadNBytes((uint8_t *)generator.pChanMem[chan-1]+index*2,length)==length && commBufferReadByte(&result)==0 && result==';'){
result = 0;
xQueueSendToBack(generatorMessageQueue, "3Invalidate", portMAX_DELAY);
}else{
result = GEN_INVALID_DATA;
}
}else{
result = GEN_OUT_OF_MEMORY;
}
}
return result;
}
uint8_t genSetFrequency(uint32_t freq,uint8_t chan){
uint8_t result = GEN_TO_HIGH_FREQ;
uint32_t realFreq;
if(freq<=MAX_GENERATING_FREQ){
generator.generatingFrequency[chan-1] = freq;
result = TIM_Reconfig_gen(generator.generatingFrequency[chan-1],chan-1,&realFreq);
generator.realGenFrequency[chan-1] = realFreq;
}
return result;
}
void genSendRealSamplingFreq(void){
xQueueSendToBack(messageQueue, "2SendGenFreq", portMAX_DELAY);
}
void genDataOKSendNext(void){
xQueueSendToBack(messageQueue, "7GenNext", portMAX_DELAY);
}
void genStatusOK(void){
xQueueSendToBack(messageQueue, "8GenOK", portMAX_DELAY);
}
uint32_t genGetRealSmplFreq(uint8_t chan){
return generator.realGenFrequency[chan-1];
}
uint8_t genSetLength(uint32_t length,uint8_t chan){
uint8_t result=GEN_INVALID_STATE;
if(generator.state==GENERATOR_IDLE){
uint32_t smpTmp=generator.maxOneChanSamples;
if(length<=generator.maxOneChanSamples){
generator.oneChanSamples[chan-1]=length;
clearGenBuffer();
result=0;
}else{
result = GEN_BUFFER_SIZE_ERR;
}
xQueueSendToBack(generatorMessageQueue, "3Invalidate", portMAX_DELAY);
}
return result;
}
uint8_t genSetNumOfChannels(uint8_t chan){
uint8_t result=GEN_INVALID_STATE;
uint8_t chanTmp=generator.numOfChannles;
if(generator.state==GENERATOR_IDLE){
if(chan<=MAX_DAC_CHANNELS){
generator.numOfChannles=chan;
generator.maxOneChanSamples=MAX_GENERATOR_BUFF_SIZE/2/chan;
for(uint8_t i=0;i<chan;i++){
generator.pChanMem[i]=(uint16_t *)&generatorBuffer[i*generator.maxOneChanSamples];
}
result=0;
xQueueSendToBack(generatorMessageQueue, "3Invalidate", portMAX_DELAY);
}
}
return result;
}
/**
* @brief Checks if scope settings doesn't exceed memory
* @param None
* @retval err/ok
*/
uint8_t validateGenBuffUsage(){
uint8_t result=1;
uint32_t data_len=generator.maxOneChanSamples;
if(generator.DAC_res>8){
data_len=data_len*2;
}
data_len=data_len*generator.numOfChannles;
if(data_len<=MAX_GENERATOR_BUFF_SIZE){
result=0;
}
return result;
}
/**
* @brief Clears generator buffer
* @param None
* @retval None
*/
void clearGenBuffer(void){
for(uint32_t i=0;i<MAX_GENERATOR_BUFF_SIZE/2;i++){
generatorBuffer[i]=0;
}
}
void genSetOutputBuffer(void){
DACSetOutputBuffer();
}
void genUnsetOutputBuffer(void){
DACUnsetOutputBuffer();
}
/**
* @brief Start scope sampling
* @param None
* @retval None
*/
void genStart(void){
xQueueSendToBack(generatorMessageQueue, "4Start", portMAX_DELAY);
}
/**
* @brief Stop scope sampling
* @param None
* @retval None
*/
void genStop(void){
xQueueSendToBack(generatorMessageQueue, "5Stop", portMAX_DELAY);
}
#endif //USE_GEN
|
the_stack_data/162643344.c | #include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define DATA_MIN 0
#define DATA_MAX 1024
#define DATA_LENGTH 1000
typedef enum { false, true } bool;
int get_random_bool() {
return random() % 2;
}
int get_random_number(int min, int max) {
return min + rand() % ( max - min + 1 );
}
void print_high_timelocality(FILE *fp) {
const int FREQUENTLY_USED_VALUE = 0;
const int MIN_GAP = 1;
const int MAX_GAP = 10;
int gap_between_fuv = 0;
int current_gap_idx = 0;
int i; // used in for loop
for (i = 0;i < DATA_LENGTH;i++) {
if(current_gap_idx == gap_between_fuv) {
gap_between_fuv = get_random_number(MIN_GAP, MAX_GAP);
current_gap_idx = 0;
fprintf(fp, "%d\n", FREQUENTLY_USED_VALUE);
} else {
fprintf(fp, "%d\n", get_random_number(DATA_MIN, DATA_MAX));
current_gap_idx++;
}
}
}
void print_high_spacelocality(FILE* fp) {
const int MIN_SECTOR_LENGTH = 3;
const int MAX_SECTOR_LENGTH = 10;
int sector_length = 0;
int sector_idx = 0;
int center_value;
bool direction_up = false;
int i;
for(i=0;i<DATA_LENGTH;i++) {
if(sector_idx == sector_length) {
sector_length = get_random_number(MIN_SECTOR_LENGTH, MAX_SECTOR_LENGTH);
sector_idx = 0;
center_value = get_random_number(DATA_MIN, DATA_MAX);
}
else {
// get random direction
if(center_value <= DATA_MIN) {
direction_up = true;
}
else if(center_value >= DATA_MAX) {
direction_up = false;
}
else {
direction_up = get_random_bool();
}
if(direction_up) {
// center value go up
center_value++;
}
else {
// center value go down
center_value--;
}
sector_idx++;
}
fprintf(fp, "%d\n", center_value);
}
}
void print_pseudorandom(FILE *fp) {
int i;
for(i=0;i<DATA_LENGTH;i++) {
fprintf(fp, "%d\n", get_random_number(DATA_MIN, DATA_MAX));
}
}
int main(int argc, char *argv[]) {
FILE* output;
// Set seed
srand(time(NULL));
// Make sure there are 4 arguments given on command line.
if (argc != 3) {
perror("Error: Invalid Number of Arguments!");
return EXIT_FAILURE;
}
// Open file and check to see if it's opened correctly.
if ( (output = fopen(argv[2], "w")) == NULL ) {
perror("Error: Inavlid File!\n");
return EXIT_FAILURE;
}
char mod = argv[1][0];
switch(mod) {
case 't':
print_high_timelocality(output);
break;
case 's':
print_high_spacelocality(output);
break;
case 'r':
print_pseudorandom(output);
break;
default:
perror("Error: Invalid Argument!");
fclose(output);
return EXIT_FAILURE;
}
fclose(output);
return EXIT_SUCCESS;
} |
the_stack_data/232954722.c | #include <stdlib.h>
#include <stdio.h>
#ifdef USE_READLINE
#include <readline/readline.h>
#include <readline/history.h>
char *
read_line (char prompt[]) {
char *line;
line = readline (prompt);
if (!line) return NULL;
add_history (line);
return line;
}
#else
char * read_line(char prompt[]) {
char *buffer = NULL;
int read;
size_t len;
printf ("%s", prompt);
read = getline (&buffer, &len, stdin);
buffer[read - 1] = 0;
return buffer;
}
#endif |
the_stack_data/51701478.c | int sub(int i , int j)
{
return i-j;
}
|
the_stack_data/92327326.c | #ifdef P2P_ENABLED
/* PlantUML documentation
== Connection ==
group Part 1
"Swadge_AB:AB:AB:AB:AB:AB" -> "Swadge_12:12:12:12:12:12" : "p2p_con" (broadcast)
"Swadge_12:12:12:12:12:12" -> "Swadge_AB:AB:AB:AB:AB:AB" : "p2p_str_00_AB:AB:AB:AB:AB:AB"
note left: Stop Broadcasting, set p2p->cnc.rxGameStartMsg
"Swadge_AB:AB:AB:AB:AB:AB" -> "Swadge_12:12:12:12:12:12" : "p2p_ack_00_12:12:12:12:12:12"
note right: set p2p->cnc.rxGameStartAck
end
group Part 2
"Swadge_12:12:12:12:12:12" -> "Swadge_AB:AB:AB:AB:AB:AB" : "p2p_con" (broadcast)
"Swadge_AB:AB:AB:AB:AB:AB" -> "Swadge_12:12:12:12:12:12" : "p2p_str_01_12:12:12:12:12:12"
note right: Stop Broadcasting, set p2p->cnc.rxGameStartMsg, become CLIENT
"Swadge_12:12:12:12:12:12" -> "Swadge_AB:AB:AB:AB:AB:AB" : "p2p_ack_01_AB:AB:AB:AB:AB:AB"
note left: set p2p->cnc.rxGameStartAck, become SERVER
end
== Unreliable Communication Example ==
group Retries & Sequence Numbers
"Swadge_AB:AB:AB:AB:AB:AB" ->x "Swadge_12:12:12:12:12:12" : "p2p_cnt_04_12:12:12:12:12:12_up"
note right: msg not received
"Swadge_AB:AB:AB:AB:AB:AB" -> "Swadge_12:12:12:12:12:12" : "p2p_cnt_04_12:12:12:12:12:12_up"
note left: first retry, up to five retries
"Swadge_12:12:12:12:12:12" ->x "Swadge_AB:AB:AB:AB:AB:AB" : "p2p_ack_04_AB:AB:AB:AB:AB:AB"
note left: ack not received
"Swadge_AB:AB:AB:AB:AB:AB" -> "Swadge_12:12:12:12:12:12" : "p2p_cnt_04_12:12:12:12:12:12_up"
note left: second retry
note right: duplicate seq num, ignore message
"Swadge_12:12:12:12:12:12" -> "Swadge_AB:AB:AB:AB:AB:AB" : "p2p_ack_05_AB:AB:AB:AB:AB:AB"
end
*/
/*============================================================================
* Includes
*==========================================================================*/
#include <osapi.h>
#include <user_interface.h>
#include <mem.h>
#include "user_main.h"
#include "p2pConnection.h"
#include "printControl.h"
/*============================================================================
* Defines
*==========================================================================*/
// The time we'll spend retrying messages
#define RETRY_TIME_MS 3000
// Time to wait between connection events and game rounds.
// Transmission can be 3s (see above), the round @ 12ms period is 3.636s
// (240 steps of rotation + (252/4) steps of decay) * 12ms
#define FAILURE_RESTART_MS 8000
// Indices into messages
#define CMD_IDX 4
#define SEQ_IDX 8
#define MAC_IDX 11
#define EXT_IDX 29
/*============================================================================
* Variables
*==========================================================================*/
// Messages to send.
const char p2pConnectionMsgFmt[] = "%s_con";
const char p2pNoPayloadMsgFmt[] = "%s_%s_%02d_%02X:%02X:%02X:%02X:%02X:%02X";
const char p2pPayloadMsgFmt[] = "%s_%s_%02d_%02X:%02X:%02X:%02X:%02X:%02X_%s";
const char p2pMacFmt[] = "%02X:%02X:%02X:%02X:%02X:%02X";
/*============================================================================
* Function Prototypes
*==========================================================================*/
void ICACHE_FLASH_ATTR p2pConnectionTimeout(void* arg);
void ICACHE_FLASH_ATTR p2pTxAllRetriesTimeout(void* arg);
void ICACHE_FLASH_ATTR p2pTxRetryTimeout(void* arg);
void ICACHE_FLASH_ATTR p2pStartRestartTimer(void* arg);
void ICACHE_FLASH_ATTR p2pProcConnectionEvt(p2pInfo* p2p, connectionEvt_t event);
void ICACHE_FLASH_ATTR p2pGameStartAckRecv(void* arg);
void ICACHE_FLASH_ATTR p2pSendAckToMac(p2pInfo* p2p, uint8_t* mac_addr);
void ICACHE_FLASH_ATTR p2pSendMsgEx(p2pInfo* p2p, char* msg, uint16_t len,
bool shouldAck, void (*success)(void*), void (*failure)(void*));
void ICACHE_FLASH_ATTR p2pModeMsgSuccess(void* arg);
void ICACHE_FLASH_ATTR p2pModeMsgFailure(void* arg);
/*============================================================================
* Functions
*==========================================================================*/
/**
* @brief Initialize the p2p connection protocol
*
* @param p2p The p2pInfo struct with all the state information
* @param msgId A three character, null terminated message ID. Must be
* unique per-swadge mode.
* @param conCbFn A function pointer which will be called when connection
* events occur
* @param msgRxCbFn A function pointer which will be called when a packet
* is received for the swadge mode
* @param connectionRssi The strength needed to start a connection with another
* swadge, 0 is first one to see around 55 the swadges need
* to be right next to eachother.
*/
void ICACHE_FLASH_ATTR p2pInitialize(p2pInfo* p2p, char* msgId,
p2pConCbFn conCbFn,
p2pMsgRxCbFn msgRxCbFn, uint8_t connectionRssi)
{
P2P_PRINTF("\n");
// Make sure everything is zero!
ets_memset(p2p, 0, sizeof(p2pInfo));
// Set the callback functions for connection and message events
p2p->conCbFn = conCbFn;
p2p->msgRxCbFn = msgRxCbFn;
// Set the initial sequence number at 255 so that a 0 received is valid.
p2p->cnc.lastSeqNum = 255;
// Set the connection Rssi, the higher the value, the closer the swadges
// need to be.
p2p->connectionRssi = connectionRssi;
// Set the three character message ID
ets_strncpy(p2p->msgId, msgId, sizeof(p2p->msgId));
// Get and save the string form of our MAC address
uint8_t mymac[6];
wifi_get_macaddr(SOFTAP_IF, mymac);
ets_snprintf(p2p->cnc.macStr, sizeof(p2p->cnc.macStr), p2pMacFmt,
mymac[0],
mymac[1],
mymac[2],
mymac[3],
mymac[4],
mymac[5]);
// Set up the connection message
ets_snprintf(p2p->conMsg, sizeof(p2p->conMsg), p2pConnectionMsgFmt,
p2p->msgId);
// Set up dummy ACK message
ets_snprintf(p2p->ackMsg, sizeof(p2p->ackMsg), p2pNoPayloadMsgFmt,
p2p->msgId,
"ack",
0,
0xFF,
0xFF,
0xFF,
0xFF,
0xFF,
0xFF);
// Set up dummy start message
ets_snprintf(p2p->startMsg, sizeof(p2p->startMsg), p2pNoPayloadMsgFmt,
p2p->msgId,
"str",
0,
0xFF,
0xFF,
0xFF,
0xFF,
0xFF,
0xFF);
// Set up a timer for acking messages
timerDisarm(&p2p->tmr.TxRetry);
timerSetFn(&p2p->tmr.TxRetry, p2pTxRetryTimeout, p2p);
// Set up a timer for when a message never gets ACKed
timerDisarm(&p2p->tmr.TxAllRetries);
timerSetFn(&p2p->tmr.TxAllRetries, p2pTxAllRetriesTimeout, p2p);
// Set up a timer to restart after abject failure
timerDisarm(&p2p->tmr.Reinit);
timerSetFn(&p2p->tmr.Reinit, p2pRestart, p2p);
// Set up a timer to do an initial connection
timerDisarm(&p2p->tmr.Connection);
timerSetFn(&p2p->tmr.Connection, p2pConnectionTimeout, p2p);
}
/**
* Start the connection process by sending broadcasts and notify the mode
*
* @param p2p The p2pInfo struct with all the state information
*/
void ICACHE_FLASH_ATTR p2pStartConnection(p2pInfo* p2p)
{
P2P_PRINTF("\n");
p2p->cnc.isConnecting = true;
timerArm(&p2p->tmr.Connection, 1, false);
if(NULL != p2p->conCbFn)
{
p2p->conCbFn(p2p, CON_STARTED);
}
}
/**
* Stop a connection in progress. If the connection is already established,
* this does nothing
*
* @param p2p The p2pInfo struct with all the state information
*/
void ICACHE_FLASH_ATTR p2pStopConnection(p2pInfo* p2p)
{
if(true == p2p->cnc.isConnecting)
{
P2P_PRINTF("\n");
p2p->cnc.isConnecting = false;
timerDisarm(&p2p->tmr.Connection);
if(NULL != p2p->conCbFn)
{
p2p->conCbFn(p2p, CON_STOPPED);
}
p2pRestart((void*)p2p);
}
}
/**
* Stop up all timers
*
* @param p2p The p2pInfo struct with all the state information
*/
void ICACHE_FLASH_ATTR p2pDeinit(p2pInfo* p2p)
{
P2P_PRINTF("\n");
ets_memset(&(p2p->msgId), 0, sizeof(p2p->msgId));
ets_memset(&(p2p->conMsg), 0, sizeof(p2p->conMsg));
ets_memset(&(p2p->ackMsg), 0, sizeof(p2p->ackMsg));
ets_memset(&(p2p->startMsg), 0, sizeof(p2p->startMsg));
p2p->conCbFn = NULL;
p2p->msgRxCbFn = NULL;
p2p->msgTxCbFn = NULL;
p2p->connectionRssi = 0;
ets_memset(&(p2p->cnc), 0, sizeof(p2p->cnc));
ets_memset(&(p2p->ack), 0, sizeof(p2p->ack));
timerDisarm(&p2p->tmr.Connection);
timerDisarm(&p2p->tmr.TxRetry);
timerDisarm(&p2p->tmr.Reinit);
timerDisarm(&p2p->tmr.TxAllRetries);
}
/**
* Send a broadcast connection message
*
* Called periodically, with some randomness mixed in from the tmr.Connection
* timer. The timer is set when connection starts and is stopped when we
* receive a response to our connection broadcast
*
* @param arg The p2pInfo struct with all the state information
*/
void ICACHE_FLASH_ATTR p2pConnectionTimeout(void* arg)
{
p2pInfo* p2p = (p2pInfo*)arg;
// Send a connection broadcast
p2pSendMsgEx(p2p, p2p->conMsg, ets_strlen(p2p->conMsg), false, NULL, NULL);
// os_random returns a 32 bit number, so this is [500ms,1500ms]
uint32_t timeoutMs = 100 * (5 + (os_random() % 11));
// Start the timer again
P2P_PRINTF("retry broadcast in %dms\n", timeoutMs);
timerArm(&p2p->tmr.Connection, timeoutMs, false);
}
/**
* Retries sending a message to be acked
*
* Called from the tmr.TxRetry timer. The timer is set when a message to be
* ACKed is sent and cleared when an ACK is received
*
* @param arg The p2pInfo struct with all the state information
*/
void ICACHE_FLASH_ATTR p2pTxRetryTimeout(void* arg)
{
P2P_PRINTF("\n");
p2pInfo* p2p = (p2pInfo*)arg;
if(p2p->ack.msgToAckLen > 0)
{
P2P_PRINTF("Retrying message \"%s\"\n", p2p->ack.msgToAck);
p2pSendMsgEx(p2p, p2p->ack.msgToAck, p2p->ack.msgToAckLen, true, p2p->ack.SuccessFn, p2p->ack.FailureFn);
}
}
/**
* Stops a message transmission attempt after all retries have been exhausted
* and calls p2p->ack.FailureFn() if a function was given
*
* Called from the tmr.TxAllRetries timer. The timer is set when a message to
* be ACKed is sent for the first time and cleared when the message is ACKed.
*
* @param arg The p2pInfo struct with all the state information
*/
void ICACHE_FLASH_ATTR p2pTxAllRetriesTimeout(void* arg)
{
P2P_PRINTF("\n");
p2pInfo* p2p = (p2pInfo*)arg;
// Disarm all timers
timerDisarm(&p2p->tmr.TxRetry);
timerDisarm(&p2p->tmr.TxAllRetries);
// Save the failure function
void (*FailureFn)(void*) = p2p->ack.FailureFn;
P2P_PRINTF("Message totally failed \"%s\"\n", p2p->ack.msgToAck);
// Clear out the ack variables
ets_memset(&p2p->ack, 0, sizeof(p2p->ack));
// Call the failure function
if(NULL != FailureFn)
{
FailureFn(p2p);
}
}
/**
* Send a message from one Swadge to another. This must not be called before
* the CON_ESTABLISHED event occurs. Message addressing, ACKing, and retries
* all happen automatically
*
* @param p2p The p2pInfo struct with all the state information
* @param msg The mandatory three char message type
* @param payload An optional message payload string, may be NULL, up to 32 chars
* @param len The length of the optional message payload string. May be 0
* @param msgTxCbFn A callback function when this message is ACKed or dropped
*/
void ICACHE_FLASH_ATTR p2pSendMsg(p2pInfo* p2p, char* msg, char* payload,
uint16_t len, p2pMsgTxCbFn msgTxCbFn)
{
P2P_PRINTF("\n");
char builtMsg[64] = {0};
if(NULL == payload || len == 0)
{
ets_snprintf(builtMsg, sizeof(builtMsg), p2pNoPayloadMsgFmt,
p2p->msgId,
msg,
0, // sequence number
p2p->cnc.otherMac[0],
p2p->cnc.otherMac[1],
p2p->cnc.otherMac[2],
p2p->cnc.otherMac[3],
p2p->cnc.otherMac[4],
p2p->cnc.otherMac[5]);
}
else
{
ets_snprintf(builtMsg, sizeof(builtMsg), p2pPayloadMsgFmt,
p2p->msgId,
msg,
0, // sequence number, filled in later
p2p->cnc.otherMac[0],
p2p->cnc.otherMac[1],
p2p->cnc.otherMac[2],
p2p->cnc.otherMac[3],
p2p->cnc.otherMac[4],
p2p->cnc.otherMac[5],
payload);
}
p2p->msgTxCbFn = msgTxCbFn;
p2pSendMsgEx(p2p, builtMsg, ets_strlen(builtMsg), true, p2pModeMsgSuccess, p2pModeMsgFailure);
}
/**
* Callback function for when a message sent by the Swadge mode, not during
* the connection process, is ACKed
*
* @param arg The p2pInfo struct with all the state information
*/
void ICACHE_FLASH_ATTR p2pModeMsgSuccess(void* arg)
{
P2P_PRINTF("\n");
p2pInfo* p2p = (p2pInfo*)arg;
if(NULL != p2p->msgTxCbFn)
{
p2p->msgTxCbFn(p2p, MSG_ACKED);
}
}
/**
* Callback function for when a message sent by the Swadge mode, not during
* the connection process, is dropped
*
* @param arg The p2pInfo struct with all the state information
*/
void ICACHE_FLASH_ATTR p2pModeMsgFailure(void* arg)
{
P2P_PRINTF("\n");
p2pInfo* p2p = (p2pInfo*)arg;
if(NULL != p2p->msgTxCbFn)
{
p2p->msgTxCbFn(p2p, MSG_FAILED);
}
}
/**
* Wrapper for sending an ESP-NOW message. Handles ACKing and retries for
* non-broadcast style messages
*
* @param p2p The p2pInfo struct with all the state information
* @param msg The message to send, may contain destination MAC
* @param len The length of the message to send
* @param shouldAck true if this message should be acked, false if we don't care
* @param success A callback function if the message is acked. May be NULL
* @param failure A callback function if the message isn't acked. May be NULL
*/
void ICACHE_FLASH_ATTR p2pSendMsgEx(p2pInfo* p2p, char* msg, uint16_t len,
bool shouldAck, void (*success)(void*), void (*failure)(void*))
{
P2P_PRINTF("\n");
// If this is a first time message and longer than a connection message
if( (p2p->ack.msgToAck != msg) && ets_strlen(p2p->conMsg) < len)
{
// Insert a sequence number
msg[SEQ_IDX + 0] = '0' + (p2p->cnc.mySeqNum / 10);
msg[SEQ_IDX + 1] = '0' + (p2p->cnc.mySeqNum % 10);
// Increment the sequence number, 0-99
p2p->cnc.mySeqNum++;
if(100 == p2p->cnc.mySeqNum++)
{
p2p->cnc.mySeqNum = 0;
}
}
#ifdef P2P_DEBUG_PRINT
char* dbgMsg = (char*)os_zalloc(sizeof(char) * (len + 1));
ets_memcpy(dbgMsg, msg, len);
P2P_PRINTF("%s\n", dbgMsg);
os_free(dbgMsg);
#endif
if(shouldAck)
{
// Set the state to wait for an ack
p2p->ack.isWaitingForAck = true;
// If this is not a retry
if(p2p->ack.msgToAck != msg)
{
P2P_PRINTF("sending for the first time\n");
// Store the message for potential retries
ets_memcpy(p2p->ack.msgToAck, msg, len);
p2p->ack.msgToAckLen = len;
p2p->ack.SuccessFn = success;
p2p->ack.FailureFn = failure;
// Start a timer to retry for 3s total
timerDisarm(&p2p->tmr.TxAllRetries);
timerArm(&p2p->tmr.TxAllRetries, RETRY_TIME_MS, false);
}
else
{
P2P_PRINTF("this is a retry\n");
}
// Mark the time this transmission started, the retry timer gets
// started in p2pSendCb()
p2p->ack.timeSentUs = system_get_time();
}
espNowSend((const uint8_t*)msg, len);
}
/**
* This is must be called whenever an ESP NOW packet is received
*
* @param p2p The p2pInfo struct with all the state information
* @param mac_addr The MAC of the swadge that sent the data
* @param data The data
* @param len The length of the data
* @param rssi The RSSI of th received message, a proxy for distance
* @return false if the message was processed here,
* true if the message should be processed by the swadge mode
*/
void ICACHE_FLASH_ATTR p2pRecvCb(p2pInfo* p2p, uint8_t* mac_addr, uint8_t* data, uint8_t len, uint8_t rssi)
{
#ifdef P2P_DEBUG_PRINT
char* dbgMsg = (char*)os_zalloc(sizeof(char) * (len + 1));
ets_memcpy(dbgMsg, data, len);
P2P_PRINTF("%s\n", dbgMsg);
os_free(dbgMsg);
#endif
// Check if this message matches our message ID
if(len < CMD_IDX ||
(0 != ets_memcmp(data, p2p->conMsg, CMD_IDX)))
{
// This message is too short, or does not match our message ID
P2P_PRINTF("DISCARD: Not a message for '%s'\n", p2p->msgId);
return;
}
// If this message has a MAC, check it
if(len >= ets_strlen(p2p->ackMsg) &&
0 != ets_memcmp(&data[MAC_IDX], p2p->cnc.macStr, ets_strlen(p2p->cnc.macStr)))
{
// This MAC isn't for us
P2P_PRINTF("DISCARD: Not for our MAC\n");
return;
}
// If this is anything besides a broadcast, check the other MAC
if(p2p->cnc.otherMacReceived &&
len > ets_strlen(p2p->conMsg) &&
0 != ets_memcmp(mac_addr, p2p->cnc.otherMac, sizeof(p2p->cnc.otherMac)))
{
// This isn't from the other known swadge
P2P_PRINTF("DISCARD: Not from the other MAC\n");
return;
}
// By here, we know the received message matches our message ID, either a
// broadcast or for us. If this isn't an ack message, ack it
if(len >= SEQ_IDX &&
0 != ets_memcmp(data, p2p->ackMsg, SEQ_IDX))
{
p2pSendAckToMac(p2p, mac_addr);
}
// After ACKing the message, check the sequence number to see if we should
// process it or ignore it (we already did!)
if(len >= ets_strlen(p2p->ackMsg))
{
// Extract the sequence number
uint8_t theirSeq = 0;
theirSeq += (data[SEQ_IDX + 0] - '0') * 10;
theirSeq += (data[SEQ_IDX + 1] - '0');
// Check it against the last known sequence number
if(theirSeq == p2p->cnc.lastSeqNum)
{
P2P_PRINTF("DISCARD: Duplicate sequence number\n");
return;
}
else
{
p2p->cnc.lastSeqNum = theirSeq;
P2P_PRINTF("Store lastSeqNum %d\n", p2p->cnc.lastSeqNum);
}
}
// ACKs can be received in any state
if(p2p->ack.isWaitingForAck)
{
// Check if this is an ACK
if(ets_strlen(p2p->ackMsg) == len &&
0 == ets_memcmp(data, p2p->ackMsg, SEQ_IDX))
{
P2P_PRINTF("ACK Received\n");
// Clear ack timeout variables
timerDisarm(&p2p->tmr.TxRetry);
// Disarm the whole transmission ack timer
timerDisarm(&p2p->tmr.TxAllRetries);
// Save the success function
void (*successFn)(void*) = p2p->ack.SuccessFn;
// Clear out ACK variables
ets_memset(&p2p->ack, 0, sizeof(p2p->ack));
// Call the function after receiving the ack
if(NULL != successFn)
{
successFn(p2p);
}
}
// Don't process anything else when waiting for an ack
return;
}
if(false == p2p->cnc.isConnected)
{
if(true == p2p->cnc.isConnecting)
{
// Received another broadcast, Check if this RSSI is strong enough
if(!p2p->cnc.broadcastReceived &&
rssi > p2p->connectionRssi &&
ets_strlen(p2p->conMsg) == len &&
0 == ets_memcmp(data, p2p->conMsg, len))
{
// We received a broadcast, don't allow another
p2p->cnc.broadcastReceived = true;
// And process this connection event
p2pProcConnectionEvt(p2p, RX_BROADCAST);
// Save the other ESP's MAC
ets_memcpy(p2p->cnc.otherMac, mac_addr, sizeof(p2p->cnc.otherMac));
p2p->cnc.otherMacReceived = true;
// Send a message to that ESP to start the game.
ets_snprintf(p2p->startMsg, sizeof(p2p->startMsg), p2pNoPayloadMsgFmt,
p2p->msgId,
"str",
0,
mac_addr[0],
mac_addr[1],
mac_addr[2],
mac_addr[3],
mac_addr[4],
mac_addr[5]);
// If it's acked, call p2pGameStartAckRecv(), if not reinit with p2pRestart()
p2pSendMsgEx(p2p, p2p->startMsg, ets_strlen(p2p->startMsg), true, p2pGameStartAckRecv, p2pRestart);
}
// Received a response to our broadcast
else if (!p2p->cnc.rxGameStartMsg &&
ets_strlen(p2p->startMsg) == len &&
0 == ets_memcmp(data, p2p->startMsg, SEQ_IDX))
{
P2P_PRINTF("Game start message received, ACKing\n");
// This is another swadge trying to start a game, which means
// they received our p2p->conMsg. First disable our p2p->conMsg
timerDisarm(&p2p->tmr.Connection);
// And process this connection event
p2pProcConnectionEvt(p2p, RX_GAME_START_MSG);
}
}
return;
}
else
{
P2P_PRINTF("cnc.isconnected is true\n");
// Let the mode handle it
if(NULL != p2p->msgRxCbFn)
{
P2P_PRINTF("letting mode handle message\n");
char msgType[4] = {0};
ets_memcpy(msgType, &data[CMD_IDX], 3 * sizeof(char));
p2p->msgRxCbFn(p2p, msgType, &data[EXT_IDX], len - EXT_IDX);
}
}
}
/**
* Helper function to send an ACK message to the given MAC
*
* @param p2p The p2pInfo struct with all the state information
* @param mac_addr The MAC to address this ACK to
*/
void ICACHE_FLASH_ATTR p2pSendAckToMac(p2pInfo* p2p, uint8_t* mac_addr)
{
P2P_PRINTF("\n");
ets_snprintf(p2p->ackMsg, sizeof(p2p->ackMsg), p2pNoPayloadMsgFmt,
p2p->msgId,
"ack",
0,
mac_addr[0],
mac_addr[1],
mac_addr[2],
mac_addr[3],
mac_addr[4],
mac_addr[5]);
p2pSendMsgEx(p2p, p2p->ackMsg, ets_strlen(p2p->ackMsg), false, NULL, NULL);
}
/**
* This is called when p2p->startMsg is acked and processes the connection event
*
* @param arg The p2pInfo struct with all the state information
*/
void ICACHE_FLASH_ATTR p2pGameStartAckRecv(void* arg)
{
P2P_PRINTF("\n");
p2pInfo* p2p = (p2pInfo*)arg;
p2pProcConnectionEvt(p2p, RX_GAME_START_ACK);
}
/**
* Two steps are necessary to establish a connection in no particular order.
* 1. This swadge has to receive a start message from another swadge
* 2. This swadge has to receive an ack to a start message sent to another swadge
* The order of events determines who is the 'client' and who is the 'server'
*
* @param p2p The p2pInfo struct with all the state information
* @param event The event that occurred
*/
void ICACHE_FLASH_ATTR p2pProcConnectionEvt(p2pInfo* p2p, connectionEvt_t event)
{
P2P_PRINTF("evt: %d, p2p->cnc.rxGameStartMsg %d, p2p->cnc.rxGameStartAck %d\n", event,
p2p->cnc.rxGameStartMsg, p2p->cnc.rxGameStartAck);
switch(event)
{
case RX_GAME_START_MSG:
{
// Already received the ack, become the client
if(!p2p->cnc.rxGameStartMsg && p2p->cnc.rxGameStartAck)
{
p2p->cnc.playOrder = GOING_SECOND;
}
// Mark this event
p2p->cnc.rxGameStartMsg = true;
break;
}
case RX_GAME_START_ACK:
{
// Already received the msg, become the server
if(!p2p->cnc.rxGameStartAck && p2p->cnc.rxGameStartMsg)
{
p2p->cnc.playOrder = GOING_FIRST;
}
// Mark this event
p2p->cnc.rxGameStartAck = true;
break;
}
case CON_STARTED:
case RX_BROADCAST:
case CON_ESTABLISHED:
case CON_LOST:
case CON_STOPPED:
default:
{
break;
}
}
if(NULL != p2p->conCbFn)
{
p2p->conCbFn(p2p, event);
}
// If both the game start messages are good, start the game
if(p2p->cnc.rxGameStartMsg && p2p->cnc.rxGameStartAck)
{
// Connection was successful, so disarm the failure timer
timerDisarm(&p2p->tmr.Reinit);
p2p->cnc.isConnecting = false;
p2p->cnc.isConnected = true;
// tell the mode it's connected
if(NULL != p2p->conCbFn)
{
p2p->conCbFn(p2p, CON_ESTABLISHED);
}
}
else
{
// Start a timer to reinit if we never finish connection
p2pStartRestartTimer(p2p);
}
}
/**
* This starts a timer to call p2pRestart(), used in case of a failure
* The timer is set when one half of the necessary connection messages is received
* The timer is disarmed when the connection is established
*
* @param arg The p2pInfo struct with all the state information
*/
void ICACHE_FLASH_ATTR p2pStartRestartTimer(void* arg)
{
P2P_PRINTF("\n");
p2pInfo* p2p = (p2pInfo*)arg;
// If the connection isn't established in FAILURE_RESTART_MS, restart
timerArm(&p2p->tmr.Reinit, FAILURE_RESTART_MS, false);
}
/**
* Restart by deiniting then initing. Persist the msgId and p2p->conCbFn
* fields
*
* @param arg The p2pInfo struct with all the state information
*/
void ICACHE_FLASH_ATTR p2pRestart(void* arg)
{
P2P_PRINTF("\n");
p2pInfo* p2p = (p2pInfo*)arg;
if(NULL != p2p->conCbFn)
{
p2p->conCbFn(p2p, CON_LOST);
}
// Save what's necessary for init
char msgId[4] = {0};
ets_strncpy(msgId, p2p->msgId, sizeof(msgId));
p2pConCbFn conCbFn = p2p->conCbFn;
p2pMsgRxCbFn msgRxCbFn = p2p->msgRxCbFn;
uint8_t connectionRssi = p2p->connectionRssi;
// Stop and clear everything
p2pDeinit(p2p);
// Start it up again
p2pInitialize(p2p, msgId, conCbFn, msgRxCbFn, connectionRssi);
}
/**
* This must be called by whatever function is registered to the Swadge mode's
* fnEspNowSendCb
*
* This is called after an attempted transmission. If it was successful, and the
* message should be acked, start a retry timer. If it wasn't successful, just
* try again
*
* @param p2p The p2pInfo struct with all the state information
* @param mac_addr unused
* @param status Whether the transmission succeeded or failed
*/
void ICACHE_FLASH_ATTR p2pSendCb(p2pInfo* p2p, uint8_t* mac_addr __attribute__((unused)), mt_tx_status status)
{
P2P_PRINTF("s:%d, t:%d\n", status, p2p->ack.timeSentUs);
switch(status)
{
case MT_TX_STATUS_OK:
{
if(0 != p2p->ack.timeSentUs)
{
uint32_t transmissionTimeUs = system_get_time() - p2p->ack.timeSentUs;
P2P_PRINTF("Transmission time %dus\n", transmissionTimeUs);
// The timers are all millisecond, so make sure that
// transmissionTimeUs is at least 1ms
if(transmissionTimeUs < 1000)
{
transmissionTimeUs = 1000;
}
// Round it to the nearest Ms, add 69ms (the measured worst case)
// then add some randomness [0ms to 15ms random]
uint32_t waitTimeMs = ((transmissionTimeUs + 500) / 1000) + 69 + (os_random() & 0b1111);
// Start the timer
P2P_PRINTF("ack timer set for %dms\n", waitTimeMs);
timerArm(&p2p->tmr.TxRetry, waitTimeMs, false);
}
break;
}
case MT_TX_STATUS_FAILED:
{
// If a message is stored
if(p2p->ack.msgToAckLen > 0)
{
// try again in 1ms
timerArm(&p2p->tmr.TxRetry, 1, false);
}
break;
}
default:
{
break;
}
}
}
/**
* After the swadge is connected to another, return whether this Swadge is
* player 1 or player 2. This can be used to determine client/server roles
*
* @param p2p The p2pInfo struct with all the state information
* @return GOING_SECOND, GOING_FIRST, or NOT_SET
*/
playOrder_t ICACHE_FLASH_ATTR p2pGetPlayOrder(p2pInfo* p2p)
{
if(p2p->cnc.isConnected)
{
return p2p->cnc.playOrder;
}
else
{
return NOT_SET;
}
}
/**
* Override whether the Swadge is player 1 or player 2. You probably shouldn't
* do this, but you might want to for single player modes
*
* @param p2p The p2pInfo struct with all the state information
*/
void ICACHE_FLASH_ATTR p2pSetPlayOrder(p2pInfo* p2p, playOrder_t order)
{
p2p->cnc.playOrder = order;
}
#endif // P2P_ENABLED |
the_stack_data/104827836.c | #include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define MIN_ELEMENT 1
#define MAX_ELEMENT 1000000
int sum (int count,...) {
int total = 0;
va_list xs;
va_start(xs, count);
for (int i = 0; i < count; ++i)
total += va_arg(xs, int);
va_end(xs);
return total;
}
int min(int count,...) {
int minx = MAX_ELEMENT;
va_list xs;
va_start(xs, count);
for (int i = 0; i < count; ++i) {
int x = va_arg(xs, int);
if (x < minx)
minx = x;
}
va_end(xs);
return minx;
}
int max(int count,...) {
int maxx = MIN_ELEMENT;
va_list xs;
va_start(xs, count);
for (int i = 0; i < count; ++i) {
int x = va_arg(xs, int);
if (x > maxx)
maxx = x;
}
va_end(xs);
return maxx;
}
int test_implementations_by_sending_three_elements() {
srand(time(NULL));
int elements[3];
elements[0] = rand() % (MAX_ELEMENT - MIN_ELEMENT + 1) + MIN_ELEMENT;
elements[1] = rand() % (MAX_ELEMENT - MIN_ELEMENT + 1) + MIN_ELEMENT;
elements[2] = rand() % (MAX_ELEMENT - MIN_ELEMENT + 1) + MIN_ELEMENT;
fprintf(stderr, "Sending following three elements:\n");
for (int i = 0; i < 3; i++) {
fprintf(stderr, "%d\n", elements[i]);
}
int elements_sum = sum(3, elements[0], elements[1], elements[2]);
int minimum_element = min(3, elements[0], elements[1], elements[2]);
int maximum_element = max(3, elements[0], elements[1], elements[2]);
fprintf(stderr, "Your output is:\n");
fprintf(stderr, "Elements sum is %d\n", elements_sum);
fprintf(stderr, "Minimum element is %d\n", minimum_element);
fprintf(stderr, "Maximum element is %d\n\n", maximum_element);
int expected_elements_sum = 0;
for (int i = 0; i < 3; i++) {
if (elements[i] < minimum_element) {
return 0;
}
if (elements[i] > maximum_element) {
return 0;
}
expected_elements_sum += elements[i];
}
return elements_sum == expected_elements_sum;
}
int test_implementations_by_sending_five_elements() {
srand(time(NULL));
int elements[5];
elements[0] = rand() % (MAX_ELEMENT - MIN_ELEMENT + 1) + MIN_ELEMENT;
elements[1] = rand() % (MAX_ELEMENT - MIN_ELEMENT + 1) + MIN_ELEMENT;
elements[2] = rand() % (MAX_ELEMENT - MIN_ELEMENT + 1) + MIN_ELEMENT;
elements[3] = rand() % (MAX_ELEMENT - MIN_ELEMENT + 1) + MIN_ELEMENT;
elements[4] = rand() % (MAX_ELEMENT - MIN_ELEMENT + 1) + MIN_ELEMENT;
fprintf(stderr, "Sending following five elements:\n");
for (int i = 0; i < 5; i++) {
fprintf(stderr, "%d\n", elements[i]);
}
int elements_sum = sum(5, elements[0], elements[1], elements[2], elements[3], elements[4]);
int minimum_element = min(5, elements[0], elements[1], elements[2], elements[3], elements[4]);
int maximum_element = max(5, elements[0], elements[1], elements[2], elements[3], elements[4]);
fprintf(stderr, "Your output is:\n");
fprintf(stderr, "Elements sum is %d\n", elements_sum);
fprintf(stderr, "Minimum element is %d\n", minimum_element);
fprintf(stderr, "Maximum element is %d\n\n", maximum_element);
int expected_elements_sum = 0;
for (int i = 0; i < 5; i++) {
if (elements[i] < minimum_element) {
return 0;
}
if (elements[i] > maximum_element) {
return 0;
}
expected_elements_sum += elements[i];
}
return elements_sum == expected_elements_sum;
}
int test_implementations_by_sending_ten_elements() {
srand(time(NULL));
int elements[10];
elements[0] = rand() % (MAX_ELEMENT - MIN_ELEMENT + 1) + MIN_ELEMENT;
elements[1] = rand() % (MAX_ELEMENT - MIN_ELEMENT + 1) + MIN_ELEMENT;
elements[2] = rand() % (MAX_ELEMENT - MIN_ELEMENT + 1) + MIN_ELEMENT;
elements[3] = rand() % (MAX_ELEMENT - MIN_ELEMENT + 1) + MIN_ELEMENT;
elements[4] = rand() % (MAX_ELEMENT - MIN_ELEMENT + 1) + MIN_ELEMENT;
elements[5] = rand() % (MAX_ELEMENT - MIN_ELEMENT + 1) + MIN_ELEMENT;
elements[6] = rand() % (MAX_ELEMENT - MIN_ELEMENT + 1) + MIN_ELEMENT;
elements[7] = rand() % (MAX_ELEMENT - MIN_ELEMENT + 1) + MIN_ELEMENT;
elements[8] = rand() % (MAX_ELEMENT - MIN_ELEMENT + 1) + MIN_ELEMENT;
elements[9] = rand() % (MAX_ELEMENT - MIN_ELEMENT + 1) + MIN_ELEMENT;
fprintf(stderr, "Sending following ten elements:\n");
for (int i = 0; i < 10; i++) {
fprintf(stderr, "%d\n", elements[i]);
}
int elements_sum = sum(10, elements[0], elements[1], elements[2], elements[3], elements[4],
elements[5], elements[6], elements[7], elements[8], elements[9]);
int minimum_element = min(10, elements[0], elements[1], elements[2], elements[3], elements[4],
elements[5], elements[6], elements[7], elements[8], elements[9]);
int maximum_element = max(10, elements[0], elements[1], elements[2], elements[3], elements[4],
elements[5], elements[6], elements[7], elements[8], elements[9]);
fprintf(stderr, "Your output is:\n");
fprintf(stderr, "Elements sum is %d\n", elements_sum);
fprintf(stderr, "Minimum element is %d\n", minimum_element);
fprintf(stderr, "Maximum element is %d\n\n", maximum_element);
int expected_elements_sum = 0;
for (int i = 0; i < 10; i++) {
if (elements[i] < minimum_element) {
return 0;
}
if (elements[i] > maximum_element) {
return 0;
}
expected_elements_sum += elements[i];
}
return elements_sum == expected_elements_sum;
}
int main ()
{
int number_of_test_cases;
scanf("%d", &number_of_test_cases);
while (number_of_test_cases--) {
if (test_implementations_by_sending_three_elements()) {
printf("Correct Answer\n");
} else {
printf("Wrong Answer\n");
}
if (test_implementations_by_sending_five_elements()) {
printf("Correct Answer\n");
} else {
printf("Wrong Answer\n");
}
if (test_implementations_by_sending_ten_elements()) {
printf("Correct Answer\n");
} else {
printf("Wrong Answer\n");
}
}
return 0;
}
|
the_stack_data/1131784.c | #include <assert.h>
int printf(const char *, ...);
static void test1(void)
{
typedef int A[];
A a = { 1, 2 };
A b = { 3, 4, 5 };
assert(sizeof(a) / sizeof(*a) == 2);
assert(sizeof(b) / sizeof(*b) == 3);
}
static void test2(void)
{
typedef int A[];
A a = { 1, 2 }, b = { 3, 4, 5 };
assert(sizeof(a) / sizeof(*a) == 2);
assert(sizeof(b) / sizeof(*b) == 3);
}
typedef char T[][2];
static T const g1 = {{'a', 'b'}, {'c'}};
T g2 = {'1', '2', 'a', 'b', '8', '0', '='};
static void test3(void)
{
int i;
printf("g1: ");
for (i = 0; i < sizeof(g1) / sizeof(*g1); ++i) {
printf("{%c, %c} ", g1[i][0], g1[i][1]);
}
printf("\n");
printf("g2: ");
for (i = 0; i < sizeof(g2) / sizeof(*g2); ++i) {
printf("{%c, %c} ", g2[i][0], g2[i][1]);
}
printf("\n");
}
typedef const char S[];
static void test4(void)
{
S s1 = "Hello world", s2 = {'h', 'i', '\0'};
printf("%s, %lu\n", s1, sizeof(s1));
printf("%s, %lu\n", s2, sizeof(s2));
}
int main(void)
{
test1();
test2();
test3();
test4();
return 0;
}
|
the_stack_data/100951.c | /*-
* Copyright (c) 2002 Atsushi Onoe
* Copyright (c) 2002-2005 Sam Leffler, Errno Consulting
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* Alternatively, this software may be distributed under the terms of the
* GNU General Public License ("GPL") version 2 as published by the Free
* Software Foundation.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* $Id$
*/ |
the_stack_data/126703689.c | /**
<> REVERSE ELEMENT OF DOUBLY LINKEDLIST <>
*/
#include<stdio.h>
#include<stdlib.h>
struct node {
int data;
struct node *next;
struct node *prev;
};
struct node *head = NULL;
struct node *tail = NULL;
// function prototype called
void createDLL();
void reverseDLL();
void displayDLL();
int main() {
// insert element of doubly linkedlist
createDLL();
displayDLL(); // print all element after reverse doubly linkedlist
// reverse element of doubly linkedlist
reverseDLL();
displayDLL(); // print all element before reverse doubly linkedlist
return 0;
}
// make a function to create linkedlist
void createDLL() {
struct node *newnode;
head = 0;
int chose = 1;
while(chose) {
newnode = (struct node*) malloc(sizeof(struct node));
printf("\n\t Please enter element of doubly linkedlist: ");
scanf("%d", &newnode ->data);
newnode ->prev = 0;
newnode ->next = 0;
if(head == 0) {
head = tail = newnode;
} else {
tail ->next = newnode;
newnode ->prev = tail;
tail = newnode;
}
printf("\n\t Do you add more element of doubly linkedlist? Enter: 1 or Exit: 0 \n\t\t Enter decision: ");
scanf("%d", &chose);
}
}
// make a function to reverse element of doubly linkedlist
void reverseDLL() {
struct node *current, *nextnode;
current = head;
while (current != 0) {
nextnode = current->next;
current->next = current->prev;
current->prev = nextnode;
}
current = head;
head = tail;
tail = current;
}
// make a function to print / traverse doubly linkedlist elements
void displayDLL() {
struct node *temp;
temp = head;
int count=0;
// traverse / print elements of linkedList
temp = head;
while (temp != 0) {
printf("\n\t Linked elements of [%d] = %d", count+1, temp -> data);
temp = temp -> next;
count ++;
}
printf("\n");
}
|
the_stack_data/93886522.c | //*****************************************************************************
//
// startup_gcc.c - Startup code for use with GNU tools.
//
// Copyright (c) 2009-2012 Texas Instruments Incorporated. All rights reserved.
// Software License Agreement
//
// Texas Instruments (TI) is supplying this software for use solely and
// exclusively on TI's microcontroller products. The software is owned by
// TI and/or its suppliers, and is protected under applicable copyright
// laws. You may not combine this software with "viral" open-source
// software in order to form a larger program.
//
// THIS SOFTWARE IS PROVIDED "AS IS" AND WITH ALL FAULTS.
// NO WARRANTIES, WHETHER EXPRESS, IMPLIED OR STATUTORY, INCLUDING, BUT
// NOT LIMITED TO, IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE APPLY TO THIS SOFTWARE. TI SHALL NOT, UNDER ANY
// CIRCUMSTANCES, BE LIABLE FOR SPECIAL, INCIDENTAL, OR CONSEQUENTIAL
// DAMAGES, FOR ANY REASON WHATSOEVER.
//
// This is part of revision 9107 of the EK-LM3S9B92 Firmware Package.
//
//*****************************************************************************
//*****************************************************************************
//
// Forward declaration of the default fault handlers.
//
//*****************************************************************************
void ResetISR(void);
static void NmiSR(void);
static void FaultISR(void);
static void IntDefaultHandler(void);
//*****************************************************************************
//
// External declarations for the interrupt handlers used by the application.
//
//*****************************************************************************
extern void SysTickHandler(void);
extern void UART1IntHandler(void);
extern void uDMAIntHandler(void);
extern void uDMAErrorHandler(void);
//*****************************************************************************
//
// The entry point for the application.
//
//*****************************************************************************
extern int main(void);
//*****************************************************************************
//
// Reserve space for the system stack.
//
//*****************************************************************************
static unsigned long pulStack[256];
//*****************************************************************************
//
// The vector table. Note that the proper constructs must be placed on this to
// ensure that it ends up at physical address 0x0000.0000.
//
//*****************************************************************************
__attribute__ ((section(".isr_vector")))
void (* const g_pfnVectors[])(void) =
{
(void (*)(void))((unsigned long)pulStack + sizeof(pulStack)),
// The initial stack pointer
ResetISR, // The reset handler
NmiSR, // The NMI handler
FaultISR, // The hard fault handler
IntDefaultHandler, // The MPU fault handler
IntDefaultHandler, // The bus fault handler
IntDefaultHandler, // The usage fault handler
0, // Reserved
0, // Reserved
0, // Reserved
0, // Reserved
IntDefaultHandler, // SVCall handler
IntDefaultHandler, // Debug monitor handler
0, // Reserved
IntDefaultHandler, // The PendSV handler
SysTickHandler, // The SysTick handler
IntDefaultHandler, // GPIO Port A
IntDefaultHandler, // GPIO Port B
IntDefaultHandler, // GPIO Port C
IntDefaultHandler, // GPIO Port D
IntDefaultHandler, // GPIO Port E
IntDefaultHandler, // UART0 Rx and Tx
UART1IntHandler, // UART1 Rx and Tx
IntDefaultHandler, // SSI0 Rx and Tx
IntDefaultHandler, // I2C0 Master and Slave
IntDefaultHandler, // PWM Fault
IntDefaultHandler, // PWM Generator 0
IntDefaultHandler, // PWM Generator 1
IntDefaultHandler, // PWM Generator 2
IntDefaultHandler, // Quadrature Encoder 0
IntDefaultHandler, // ADC Sequence 0
IntDefaultHandler, // ADC Sequence 1
IntDefaultHandler, // ADC Sequence 2
IntDefaultHandler, // ADC Sequence 3
IntDefaultHandler, // Watchdog timer
IntDefaultHandler, // Timer 0 subtimer A
IntDefaultHandler, // Timer 0 subtimer B
IntDefaultHandler, // Timer 1 subtimer A
IntDefaultHandler, // Timer 1 subtimer B
IntDefaultHandler, // Timer 2 subtimer A
IntDefaultHandler, // Timer 2 subtimer B
IntDefaultHandler, // Analog Comparator 0
IntDefaultHandler, // Analog Comparator 1
IntDefaultHandler, // Analog Comparator 2
IntDefaultHandler, // System Control (PLL, OSC, BO)
IntDefaultHandler, // FLASH Control
IntDefaultHandler, // GPIO Port F
IntDefaultHandler, // GPIO Port G
IntDefaultHandler, // GPIO Port H
IntDefaultHandler, // UART2 Rx and Tx
IntDefaultHandler, // SSI1 Rx and Tx
IntDefaultHandler, // Timer 3 subtimer A
IntDefaultHandler, // Timer 3 subtimer B
IntDefaultHandler, // I2C1 Master and Slave
IntDefaultHandler, // Quadrature Encoder 1
IntDefaultHandler, // CAN0
IntDefaultHandler, // CAN1
IntDefaultHandler, // CAN2
IntDefaultHandler, // Ethernet
IntDefaultHandler, // Hibernate
IntDefaultHandler, // USB0
IntDefaultHandler, // PWM Generator 3
uDMAIntHandler, // uDMA Software Transfer
uDMAErrorHandler, // uDMA Error
IntDefaultHandler, // ADC1 Sequence 0
IntDefaultHandler, // ADC1 Sequence 1
IntDefaultHandler, // ADC1 Sequence 2
IntDefaultHandler, // ADC1 Sequence 3
IntDefaultHandler, // I2S0
IntDefaultHandler, // External Bus Interface 0
IntDefaultHandler // GPIO Port J
};
//*****************************************************************************
//
// The following are constructs created by the linker, indicating where the
// the "data" and "bss" segments reside in memory. The initializers for the
// for the "data" segment resides immediately following the "text" segment.
//
//*****************************************************************************
extern unsigned long _etext;
extern unsigned long _data;
extern unsigned long _edata;
extern unsigned long _bss;
extern unsigned long _ebss;
//*****************************************************************************
//
// This is the code that gets called when the processor first starts execution
// following a reset event. Only the absolutely necessary set is performed,
// after which the application supplied entry() routine is called. Any fancy
// actions (such as making decisions based on the reset cause register, and
// resetting the bits in that register) are left solely in the hands of the
// application.
//
//*****************************************************************************
void
ResetISR(void)
{
unsigned long *pulSrc, *pulDest;
//
// Copy the data segment initializers from flash to SRAM.
//
pulSrc = &_etext;
for(pulDest = &_data; pulDest < &_edata; )
{
*pulDest++ = *pulSrc++;
}
//
// Zero fill the bss segment.
//
__asm(" ldr r0, =_bss\n"
" ldr r1, =_ebss\n"
" mov r2, #0\n"
" .thumb_func\n"
"zero_loop:\n"
" cmp r0, r1\n"
" it lt\n"
" strlt r2, [r0], #4\n"
" blt zero_loop");
//
// Call the application's entry point.
//
main();
}
//*****************************************************************************
//
// This is the code that gets called when the processor receives a NMI. This
// simply enters an infinite loop, preserving the system state for examination
// by a debugger.
//
//*****************************************************************************
static void
NmiSR(void)
{
//
// Enter an infinite loop.
//
while(1)
{
}
}
//*****************************************************************************
//
// This is the code that gets called when the processor receives a fault
// interrupt. This simply enters an infinite loop, preserving the system state
// for examination by a debugger.
//
//*****************************************************************************
static void
FaultISR(void)
{
//
// Enter an infinite loop.
//
while(1)
{
}
}
//*****************************************************************************
//
// This is the code that gets called when the processor receives an unexpected
// interrupt. This simply enters an infinite loop, preserving the system state
// for examination by a debugger.
//
//*****************************************************************************
static void
IntDefaultHandler(void)
{
//
// Go into an infinite loop.
//
while(1)
{
}
}
|
the_stack_data/154831676.c | /* mbed Microcontroller Library
* SPDX-License-Identifier: BSD-3-Clause
******************************************************************************
*
* Copyright (c) 2015-2021 STMicroelectronics.
* All rights reserved.
*
* This software component is licensed by ST under BSD 3-Clause license,
* the "License"; You may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
* opensource.org/licenses/BSD-3-Clause
*
******************************************************************************
*/
#if DEVICE_FLASH
#include "flash_api.h"
#include "flash_data.h"
#include "platform/mbed_critical.h"
static uint32_t GetSector(uint32_t Address);
static uint32_t GetSectorSize(uint32_t Sector);
int32_t flash_init(flash_t *obj)
{
return 0;
}
int32_t flash_free(flash_t *obj)
{
return 0;
}
int32_t flash_erase_sector(flash_t *obj, uint32_t address)
{
static FLASH_EraseInitTypeDef EraseInitStruct;
uint32_t FirstSector;
uint32_t SectorError = 0;
int32_t status = 0;
if ((address >= (FLASH_BASE + FLASH_SIZE)) || (address < FLASH_BASE)) {
return -1;
}
if (HAL_FLASH_Unlock() != HAL_OK) {
return -1;
}
core_util_critical_section_enter();
/* Get the 1st sector to erase */
FirstSector = GetSector(address);
/* Fill EraseInit structure*/
EraseInitStruct.TypeErase = FLASH_TYPEERASE_SECTORS;
EraseInitStruct.VoltageRange = FLASH_VOLTAGE_RANGE_3;
EraseInitStruct.Sector = FirstSector;
EraseInitStruct.NbSectors = 1;
if (HAL_FLASHEx_Erase(&EraseInitStruct, &SectorError) != HAL_OK) {
status = -1;
}
core_util_critical_section_exit();
if (HAL_FLASH_Lock() != HAL_OK) {
return -1;
}
return status;
}
int32_t flash_program_page(flash_t *obj, uint32_t address, const uint8_t *data, uint32_t size)
{
int32_t status = 0;
if ((address >= (FLASH_BASE + FLASH_SIZE)) || (address < FLASH_BASE)) {
return -1;
}
if (HAL_FLASH_Unlock() != HAL_OK) {
return -1;
}
/* Note: If an erase operation in Flash memory also concerns data in the data or instruction cache,
you have to make sure that these data are rewritten before they are accessed during code
execution. If this cannot be done safely, it is recommended to flush the caches by setting the
DCRST and ICRST bits in the FLASH_CR register. */
__HAL_FLASH_DATA_CACHE_DISABLE();
__HAL_FLASH_INSTRUCTION_CACHE_DISABLE();
__HAL_FLASH_DATA_CACHE_RESET();
__HAL_FLASH_INSTRUCTION_CACHE_RESET();
__HAL_FLASH_INSTRUCTION_CACHE_ENABLE();
__HAL_FLASH_DATA_CACHE_ENABLE();
while ((size > 0) && (status == 0)) {
if (HAL_FLASH_Program(FLASH_TYPEPROGRAM_BYTE, address, (uint64_t)*data) != HAL_OK) {
status = -1;
} else {
size--;
address++;
data++;
}
}
if (HAL_FLASH_Lock() != HAL_OK) {
return -1;
}
return status;
}
uint32_t flash_get_sector_size(const flash_t *obj, uint32_t address)
{
if ((address >= (FLASH_BASE + FLASH_SIZE)) || (address < FLASH_BASE)) {
return MBED_FLASH_INVALID_SIZE;
}
return (GetSectorSize(GetSector(address)));
}
uint32_t flash_get_page_size(const flash_t *obj)
{
// Flash of STM32F4 devices can be programed 1 byte at a time
return (1);
}
uint32_t flash_get_start_address(const flash_t *obj)
{
return FLASH_BASE;
}
uint32_t flash_get_size(const flash_t *obj)
{
return FLASH_SIZE;
}
/**
* @brief Gets the sector of a given address
* @param None
* @retval The sector of a given address
*/
static uint32_t GetSector(uint32_t address)
{
uint32_t sector = 0;
uint32_t tmp = address - ADDR_FLASH_SECTOR_0;
/* This function supports 1Mb and 2Mb flash sizes */
#if defined(ADDR_FLASH_SECTOR_16)
if (address & 0x100000) { // handle 2nd bank
/* Sector will be at least 12 */
sector = FLASH_SECTOR_12;
tmp -= 0x100000;
address -= 0x100000;
}
#endif
if (address < ADDR_FLASH_SECTOR_4) { // 16k sectorsize
sector += tmp >> 14;
}
#if defined(ADDR_FLASH_SECTOR_5)
else if (address < ADDR_FLASH_SECTOR_5) { //64k sector size
sector += FLASH_SECTOR_4;
} else {
sector += 4 + (tmp >> 17);
}
#else
// In case ADDR_FLASH_SECTOR_5 is not defined, sector 4 is the last one.
else { //64k sector size
sector += FLASH_SECTOR_4;
}
#endif
return sector;
}
/**
* @brief Gets sector Size
* @param None
* @retval The size of a given sector
*/
static uint32_t GetSectorSize(uint32_t Sector)
{
uint32_t sectorsize = 0x00;
#if defined(FLASH_SECTOR_16)
if ((Sector == FLASH_SECTOR_0) || (Sector == FLASH_SECTOR_1) || (Sector == FLASH_SECTOR_2) || \
(Sector == FLASH_SECTOR_3) || (Sector == FLASH_SECTOR_12) || (Sector == FLASH_SECTOR_13) || \
(Sector == FLASH_SECTOR_14) || (Sector == FLASH_SECTOR_15)) {
sectorsize = 16 * 1024;
} else if ((Sector == FLASH_SECTOR_4) || (Sector == FLASH_SECTOR_16)) {
#else
if ((Sector == FLASH_SECTOR_0) || (Sector == FLASH_SECTOR_1) || (Sector == FLASH_SECTOR_2) || \
(Sector == FLASH_SECTOR_3)) {
sectorsize = 16 * 1024;
} else if (Sector == FLASH_SECTOR_4) {
#endif
sectorsize = 64 * 1024;
} else {
sectorsize = 128 * 1024;
}
return sectorsize;
}
uint8_t flash_get_erase_value(const flash_t *obj)
{
(void)obj;
return 0xFF;
}
#endif
|
the_stack_data/126702501.c | #include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<ctype.h>
#include<math.h>
typedef struct stack
{
int top ;
char items[100] ;
}stack;
int pop(stack * s)
{
return s->items[s->top--] ;
}
void inserttobottom(stack * s , int data)
{
int ele ;
ele = pop(s) ;
if(s->top==-1)
{
s->items[++s->top] = data ;
s->items[++s->top] = ele ;
return ;
}
inserttobottom(s , data) ;
s->items[++s->top] = ele ;
}
void display(stack s)
{
if(s.top==-1)
return ;
int i =0 ;
printf("\n") ;
for(i =0 ; i<=s.top ; i++)
printf("%d " , s.items[i]) ;
}
int main()
{
stack s={-1} ;
for(int i = 0 ; i< 10 ; i++)
s.items[++s.top] = i ;
display(s) ;
inserttobottom(&s , 100) ;
display(s) ;
} |
the_stack_data/90761881.c | #include <stdio.h>
#include <stdlib.h>
void bad (int x) {
if (x > 10)
abort();
if (x > 5)
exit(1);
char buf[10];
char *a = getenv("AA");
system("echo");
}
int main() {
bad(2);
return 0;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.