file
stringlengths 18
26
| data
stringlengths 2
1.05M
|
---|---|
the_stack_data/449197.c | /* $Id$
$Logi$
*/
#include <stdio.h>
#include <string.h>
int main (int argc, char **argv)
{
char *line;
size_t llen;
int ret = 1;
while ((line = fgetln(stdin, &llen)))
{
int quote = 0;
while (llen--)
{
char c;
if (quote)
{
while ((c = *line++) != quote && c != '\n')
putchar (c);
quote = ret = 0;
break; // Done for this line
}
if ((c = *line++) == '"' || c == '\'')
quote = c;
}
}
return 0;
}
|
the_stack_data/173579062.c | #include <stdio.h>
int main(int argc, char *argv[])
{
if (argc != 1)
{
printf("Hello %s!", argv[1]);
}
else {
printf("usage: %s name", argv[0]);
}
return 0;
} |
the_stack_data/1209332.c | //1174 - Seleçao em Vetor I
#include <stdio.h>
int main(){
int i = 0;
double vetor[100], num;
for(i = 0; i < 100; i++){
scanf("%lf", &num);
vetor[i] = num;
}
for(i = 0; i < 100; i++){
if(vetor[i] <= 10){
printf("A[%d] = %.1lf\n", i, vetor[i]);
}
}
return 0;
}
//A[i] = x
|
the_stack_data/243892803.c | /****************************************************************************
* libs/libc/pthread/pthread_testcancel.c
*
* Copyright (C) 2016 Gregory Nutt. All rights reserved.
* Author: Gregory Nutt <[email protected]>
*
* 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 NuttX 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 OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
****************************************************************************/
/****************************************************************************
* Included Files
****************************************************************************/
#include <pthread.h>
#include <sched.h>
/****************************************************************************
* Public Functions
****************************************************************************/
/****************************************************************************
* Name: pthread_testcancel
*
* Description:
* The pthread_testcancel() function creates a cancellation point in the
* calling thread. The pthread_testcancel() function has no effect if
* cancelability is disabled
*
****************************************************************************/
void pthread_testcancel(void)
{
/* task_testcancel() does the real work */
task_testcancel();
}
|
the_stack_data/159516456.c | /* { dg-do compile } */
/* { dg-options "-O3 -march=z10 -mzarch --save-temps -mfunction-return-mem=thunk-extern -mindirect-branch-table" } */
int gl = 0;
int __attribute__((noinline,noclone))
bar (int a)
{
return a + 2;
}
void __attribute__((noinline,noclone))
foo (int a)
{
int i;
if (a == 42)
return;
for (i = 0; i < a; i++)
gl += bar (i);
}
int
main ()
{
foo (3);
if (gl != 9)
__builtin_abort ();
return 0;
}
/* With -march=z10 -mzarch the shrink wrapped returns use compare and
swap relative to jump to the exit block instead of making use of
the conditional return pattern.
FIXME: Use compare and branch register for that!!!! */
/* 2 x foo, 1 x main
/* { dg-final { scan-assembler-times "jg\t__s390_indirect_jump" 3 } } */
/* No thunks due to thunk-extern. */
/* { dg-final { scan-assembler-not "exrl" } } */
/* { dg-final { scan-assembler-not ".globl __s390_indirect_jump" } } */
/* { dg-final { scan-assembler-not "section\t.s390_indirect_jump" } } */
/* { dg-final { scan-assembler-not "section\t.s390_indirect_call" } } */
/* { dg-final { scan-assembler-not "section\t.s390_return_reg" } } */
/* { dg-final { scan-assembler "section\t.s390_return_mem" } } */
|
the_stack_data/1167653.c | #include <unistd.h>
int main(int ac, char **av)
{
int i;
char *lw;
i = 0;
if (ac == 2)
{
while (av[1][i] != '\0')
{
if (av[1][i] <= 32 && av[1][i + 1] > 32)
lw = &av[1][i + 1];
i++;
}
i = 0;
while (lw && lw[i] > 32)
{
write(1, &lw[i], 1);
i++;
}
}
write(1, "\n", 1);
return (0);
}
|
the_stack_data/3262920.c | #include <stdio.h>
#include <string.h>
#include <arpa/inet.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/file.h>
#include <errno.h>
#include <signal.h>
#define ECHOMAX (255)
#define TIMEOUT (2)
int SendEchoMessage(struct sockaddr_in *pServAddr);
int ReceiveEchoMessage(struct sockaddr_in *pServAddr);
int sock;
void IOSignalHandler(int signo);
int main(int argc, char *argv[]) {
unsigned short servPort;
struct sockaddr_in servAddr;
struct sigaction sigAction;
/////////////////////////////////////////////////////
char *servIP;
struct sockaddr_in servAddr2;
int maxDescriptor;
fd_set fdSet;
struct timeval tout;
if((argc < 2) || (argc > 3)) {
fprintf(stderr, "Usage: %s <Server IP> [<Echo Port>]\n", argv[0]);
exit(1);
}
servIP = argv[1];
if(argc == 3) {
servPort = atoi(argv[2]);
}
else {
servPort = 7;
}
sock = socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP);
if(sock < 0) {
fprintf(stderr, "socket() failed\n");
exit(1);
}
memset(&servAddr2, 0, sizeof(servAddr2));
servAddr2.sin_family = AF_INET;
servAddr2.sin_addr.s_addr = inet_addr(servIP);
servAddr2.sin_port = htons(servPort);
maxDescriptor = sock;
////////////////////////////////////////////////////////
memset(&servAddr, 0, sizeof(servAddr));
servAddr.sin_family = AF_INET;
servAddr.sin_addr.s_addr = htonl(INADDR_ANY);
servAddr.sin_port = htons(servPort);
if(bind(sock, (struct sockaddr *)&servAddr, sizeof(servAddr)) < 0) {
fprintf(stderr, "bind() failed\n");
exit(1);
}
sigAction.sa_handler = IOSignalHandler;
if(sigfillset(&sigAction.sa_mask) < 0) {
fprintf(stderr, "sigfillset() failed\n");
exit(1);
}
sigAction.sa_flags = 0;
if(sigaction(SIGIO, &sigAction, 0) < 0) {
fprintf(stderr, "sigaction() failed\n");
exit(1);
}
if(fcntl(sock, F_SETOWN, getpid()) < 0) {
fprintf(stderr, "Unable to set process owner to us\n");
exit(1);
}
if(fcntl(sock, F_SETFL, O_NONBLOCK | FASYNC) < 0) {
fprintf(stderr, "Unable to put the sock into nonblocking/async mode\n");
exit(1);
}
for(;;) {
FD_ZERO(&fdSet);
FD_SET(STDIN_FILENO, &fdSet);
FD_SET(sock, &fdSet);
tout.tv_sec = TIMEOUT;
tout.tv_usec = 0;
if(select(maxDescriptor +1, &fdSet, NULL, NULL, &tout) == 0) {
//printf(".\n");
continue;
}
if(FD_ISSET(STDIN_FILENO, &fdSet)) {
if(SendEchoMessage(&servAddr2) < 0) {
break;
}
}
if(FD_ISSET(sock, &fdSet)) {
if(ReceiveEchoMessage(&servAddr2) < 0) {
break;
}
}
}
close(sock);
exit(0);
}
void IOSignalHandler(int signo) {
struct sockaddr_in clntAddr;
unsigned int clntAddrLen;
char msgBuffer[ECHOMAX];
int recvMsgLen;
int sendMsgLen;
do {
clntAddrLen = sizeof(clntAddr);
recvMsgLen = recvfrom(sock, msgBuffer, ECHOMAX, 0,
(struct sockaddr *)&clntAddr, &clntAddrLen);
if(recvMsgLen < 0) {
if(errno != EWOULDBLOCK) {
fprintf(stderr, "recvfrom() failed\n");
exit(1);
}
} else {
printf("Handling client %s\n", inet_ntoa(clntAddr.sin_addr));
sendMsgLen = sendto(sock, msgBuffer, recvMsgLen, 0,
(struct sockaddr *)&clntAddr, sizeof(clntAddr));
if(recvMsgLen != sendMsgLen) {
fprintf(stderr, "sendto() sent a differrent number of bytes than expected\n");
exit(1);
}
}
} while(recvMsgLen >= 0);
}
int SendEchoMessage(struct sockaddr_in *pServAddr) {
char echoString[ECHOMAX + 1];
int echoStringLen;
int sendMsgLen;
if(fgets(echoString, ECHOMAX +1, stdin) == NULL) {
return -1;
}
echoStringLen = strlen(echoString);
if(echoStringLen < 1 ) {
fprintf(stderr, "No input string.\n");
return -1;
}
sendMsgLen = sendto(sock, echoString, echoStringLen, 0,
(struct sockaddr*)pServAddr, sizeof(*pServAddr));
if(echoStringLen != sendMsgLen) {
fprintf(stderr, "sendto() sent a different number of bytes than expected\n");
return -1;
}
return 0;
}
int ReceiveEchoMessage(struct sockaddr_in *pServAddr) {
struct sockaddr_in fromAddr;
unsigned int fromAddrLen;
char msgBuffer[ECHOMAX +1];
int recvMsgLen;
fromAddrLen = sizeof(fromAddr);
recvMsgLen = recvfrom(sock, msgBuffer, ECHOMAX, 0,
(struct sockaddr *)&fromAddr, &fromAddrLen);
if(recvMsgLen < 0) {
fprintf(stderr, "recvfrom() failed\n");
return -1;
}
if(fromAddr.sin_addr.s_addr != pServAddr->sin_addr.s_addr) {
fprintf(stderr, "Error: received a packet from unknown source.\n");
return -1;
}
msgBuffer[recvMsgLen] = '\0';
printf("Received: %s\n", msgBuffer);
return 0;
}
|
the_stack_data/140765577.c | #ifdef ACTION_ENABLED
#define TOTAL_ACTION_COUNTS (1)
static TYPE_DEF_TEMPLATE_INT sg_light_blink_in_time = 0;
static TYPE_DEF_TEMPLATE_BOOL sg_light_blink_in_color = 0;
static TYPE_DEF_TEMPLATE_INT sg_light_blink_in_total_time = 0;
static DeviceProperty g_actionInput_light_blink[] = {
{.key = "time", .data = &sg_light_blink_in_time, .type = TYPE_TEMPLATE_INT},
{.key = "color", .data = &sg_light_blink_in_color, .type = TYPE_TEMPLATE_BOOL},
{.key = "total_time", .data = &sg_light_blink_in_total_time, .type = TYPE_TEMPLATE_INT},
};
static TYPE_DEF_TEMPLATE_BOOL sg_light_blink_out_err_code = 0;
static DeviceProperty g_actionOutput_light_blink[] = {
{.key = "err_code", .data = &sg_light_blink_out_err_code, .type = TYPE_TEMPLATE_BOOL},
};
static DeviceAction g_actions[] = {
{
.pActionId = "light_blink",
.timestamp = 0,
.input_num = sizeof(g_actionInput_light_blink) / sizeof(g_actionInput_light_blink[0]),
.output_num = sizeof(g_actionOutput_light_blink) / sizeof(g_actionOutput_light_blink[0]),
.pInput = g_actionInput_light_blink,
.pOutput = g_actionOutput_light_blink,
},
};
#endif
|
the_stack_data/11033.c | #include <stdio.h>
#include <stdlib.h>
/* Flip a coin, 10 times. */
int
main()
{
int i;
srand(time(NULL));
for (i = 0; i < 10; i++)
puts((rand() % 2) ? "heads" : "tails");
return 0;
}
|
the_stack_data/97013438.c | #include <stdio.h>#include <stdlib.h>
#include <math.h>
float converterGrausEmRadianos(float);
float areaDoTriangulo(float, float, float);
main ()
{
float ladoA, ladoB, angulo, anguloEmRad, area;
printf("Digite o valor do angulo: ");
scanf("%f", &angulo);
printf("Digite o valor do lado a: ");
scanf("%f", &ladoA);
printf("Digite o valor do lado b: ");
scanf("%f", &ladoB);
anguloEmRad = converterGrausEmRadianos(angulo);
area = areaDoTriangulo(ladoA, ladoB, anguloEmRad);
printf("Area do triangulo: %.2f", area);
}
float converterGrausEmRadianos(float angulo)
{
const float PI = 3.141592;
return (PI * angulo) /180;
}
float areaDoTriangulo(float ladoA, float ladoB, float angulo)
{
return (ladoA * ladoB * sin(angulo))/2;
}
|
the_stack_data/119582.c | struct a {int x;};
int main() {}
|
the_stack_data/36775.c | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <openssl/sha.h>
const char *string = "a";
int main()
{
int sha1;
unsigned char result[SHA_DIGEST_LENGTH];
SHA1(string, strlen(string), result);
//output
for(sha1 = 0; sha1 < SHA_DIGEST_LENGTH; sha1++)
printf("%02x", result[sha1]);
printf("\n");
return EXIT_SUCCESS;
}
|
the_stack_data/242331354.c | /****************************************************************************
*
* Copyright 2017 Samsung Electronics All Rights Reserved.
*
* 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.
*
****************************************************************************/
/****************************************************************************
*
* Copyright © 2005-2014 Rich Felker, et al.
*
* 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.
*
***************************************************************************/
/************************************************************************
* Included Files
************************************************************************/
#include <math.h>
#include <stdint.h>
/************************************************************************
* Public Functions
************************************************************************/
#ifdef CONFIG_HAVE_LONG_DOUBLE
double remquo(double x, double y, int *quo)
{
union {
double f;
uint64_t i;
} ux = { x }, uy = { y };
int ex = ux.i >> 52 & 0x7ff;
int ey = uy.i >> 52 & 0x7ff;
int sx = ux.i >> 63;
int sy = uy.i >> 63;
uint32_t q;
uint64_t i;
uint64_t uxi = ux.i;
*quo = 0;
if (uy.i << 1 == 0 || isnan(y) || ex == 0x7ff) {
return (x * y) / (x * y);
}
if (ux.i << 1 == 0) {
return x;
}
/* normalize x and y */
if (!ex) {
for (i = uxi << 12; i >> 63 == 0; ex--, i <<= 1)
;
uxi <<= -ex + 1;
} else {
uxi &= -1ULL >> 12;
uxi |= 1ULL << 52;
}
if (!ey) {
for (i = uy.i << 12; i >> 63 == 0; ey--, i <<= 1)
;
uy.i <<= -ey + 1;
} else {
uy.i &= -1ULL >> 12;
uy.i |= 1ULL << 52;
}
q = 0;
if (ex < ey) {
if (ex + 1 == ey) {
goto end;
}
return x;
}
/* x mod y */
for (; ex > ey; ex--) {
i = uxi - uy.i;
if (i >> 63 == 0) {
uxi = i;
q++;
}
uxi <<= 1;
q <<= 1;
}
i = uxi - uy.i;
if (i >> 63 == 0) {
uxi = i;
q++;
}
if (uxi == 0) {
ex = -60;
} else {
for (; uxi >> 52 == 0; uxi <<= 1, ex--)
;
}
end:
/* scale result and decide between |x| and |x|-|y| */
if (ex > 0) {
uxi -= 1ULL << 52;
uxi |= (uint64_t)ex << 52;
} else {
uxi >>= -ex + 1;
}
ux.i = uxi;
x = ux.f;
if (sy) {
y = -y;
}
if (ex == ey || (ex + 1 == ey && (2 * x > y || (2 * x == y && q % 2)))) {
x -= y;
q++;
}
q &= 0x7fffffff;
*quo = sx ^ sy ? -(int)q : (int)q;
return sx ? -x : x;
}
#endif
|
the_stack_data/4163.c | // 在排序数组中找到目标值索引,如果目标值不存在,返回其按顺序插入的索引
// 二分查找
int searchInsert(int* nums, int numsSize, int target)
{
int l = 0;
int r = numsSize;
while (l < r) {
int mid = l + (r - l) >> 1;
if (nums[mid] < target) {
l = mid + 1;
} else if (nums[mid] > target) {
r = mid;
} else {
return mid;
}
}
return r;
}
|
the_stack_data/472946.c | #include <term.h>
#define micro_col_size tigetnum("mcs")
/** character step size when in micro mode **/
/*
TERMINFO_NAME(mcs)
TERMCAP_NAME(Yf)
XOPEN(400)
*/
|
the_stack_data/159514905.c | #include <ncurses.h>
typedef struct _winBorderStruct {
chtype ls, rs, ts, bs; /* sides */
chtype tl, tr, bl, br; /* corners */
} WinBorder;
typedef struct _winStruct {
int startx, starty;
int height, width;
WinBorder border;
} Win;
void init_win_params(Win* p_win) {
p_win->height = 5;
p_win->width = 10;
p_win->starty = (LINES - p_win->height)/2;
p_win->startx = (COLS - p_win->width)/2;
p_win->border.ls = '|';
p_win->border.rs = '|';
p_win->border.ts = '-';
p_win->border.bs = '-';
p_win->border.tl = '+';
p_win->border.tr = '+';
p_win->border.bl = '+';
p_win->border.br = '+';
}
void print_win_params(Win* p_win) {
mvprintw(25, 0, "%d %d %d %d", p_win->startx, p_win->starty,
p_win->width, p_win->height);
refresh();
}
void create_box(Win* p_win, bool flag) {
int x = p_win->startx;
int y = p_win->starty;
int w = p_win->width;
int h = p_win->height;
if (flag == TRUE) {
mvaddch(y, x, p_win->border.tl);
mvaddch(y, x+w, p_win->border.tr);
mvaddch(y+h, x, p_win->border.bl);
mvaddch(y+h, x+w, p_win->border.br);
mvhline(y, x+1, p_win->border.ts, w-1);
mvhline(y+h, x+1, p_win->border.bs, w-1);
mvvline(y+1, x, p_win->border.ls, h-1);
mvvline(y+1, x+w, p_win->border.rs, h-1);
}
else {
int i, j;
for (i = y ; i <= y + h ; ++i)
for (j = x ; j <= x+w ; ++j)
mvaddch(i, j, ' ');
}
refresh();
}
int main() {
initscr();
start_color();
cbreak();
keypad(stdscr, TRUE);
noecho();
init_pair(1, COLOR_CYAN, COLOR_BLACK);
Win win;
/* Initialize the window parameters */
init_win_params(&win);
#ifdef _DEBUG
print_win_params(&win);
#endif
attron(COLOR_PAIR(1));
printw("Press q to exit");
refresh();
attroff(COLOR_PAIR(1));
create_box(&win, TRUE);
int ch;
while ((ch = getch()) != 'q') {
switch (ch) {
case KEY_LEFT:
create_box(&win, FALSE);
--win.startx;
create_box(&win, TRUE);
break;
case KEY_RIGHT:
create_box(&win, FALSE);
++win.startx;
create_box(&win, TRUE);
break;
case KEY_UP:
create_box(&win, FALSE);
--win.starty;
create_box(&win, TRUE);
break;
case KEY_DOWN:
create_box(&win, FALSE);
++win.starty;
create_box(&win, TRUE);
break;
}
}
endwin();
return 0;
}
|
the_stack_data/72013037.c | /*numPass=5, numTotal=5
Verdict:ACCEPTED, Visibility:1, Input:"2", ExpOutput:"2*
*1
", Output:"2*
*1
"
Verdict:ACCEPTED, Visibility:1, Input:"4", ExpOutput:"432*
43*1
4*21
*321
", Output:"432*
43*1
4*21
*321
"
Verdict:ACCEPTED, Visibility:1, Input:"5", ExpOutput:"5432*
543*1
54*21
5*321
*4321
", Output:"5432*
543*1
54*21
5*321
*4321
"
Verdict:ACCEPTED, Visibility:0, Input:"1", ExpOutput:"*
", Output:"*
"
Verdict:ACCEPTED, Visibility:0, Input:"10", ExpOutput:"1098765432*
109876543*1
10987654*21
1098765*321
109876*4321
10987*54321
1098*654321
109*7654321
10*87654321
*987654321
", Output:"1098765432*
109876543*1
10987654*21
1098765*321
109876*4321
10987*54321
1098*654321
109*7654321
10*87654321
*987654321
"
*/
#include<stdio.h>
int main(){
int i,j,n;
scanf("%d",&n);
for(i=n;i>=1;i=i-1){
for(j=1;j<=n;j=j+1){
if(i!=j){
printf("%d",n+1-j);
}else{
printf("*");
}
}
printf("\n");
}
return 0;
} |
the_stack_data/68886760.c | #include <stdio.h>
extern void run();
float addition(float a, int b) {
printf("a=%f b=%d\n", a, b);
return a+b;
}
int main() {
run(); // start kodu asm
return 0;
} |
the_stack_data/840681.c | #include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#define WIDTH 100
#define HEIGHT 100
#define NUM_GRIDS 5
#define POS(w, h) ((h) * WIDTH + (w))
#define NPOS(w, h) ((h) * WIDTH * NUM_GRIDS + (w))
size_t next(size_t pos, size_t *ret, size_t width, size_t height) {
size_t x = pos % width;
size_t y = pos / width;
size_t ret_sz = 0;
if (x > 0)
ret[ret_sz++] = pos - 1;
if (x + 1 < width)
ret[ret_sz++] = pos + 1;
if (y > 0)
ret[ret_sz++] = pos - width;
if (y + 1 < height)
ret[ret_sz++] = pos + width;
return ret_sz;
}
void read_grid(char *grid, FILE *fp) {
for (size_t h = 0; h < HEIGHT; h++) {
for (size_t w = 0; w < WIDTH; w++) {
char c = fgetc(fp);
grid[POS(w, h)] = c - 48;
}
fgetc(fp); // \n
}
}
unsigned long dijkstra(char *grid, size_t width, size_t height) {
size_t pos = 0;
bool qset[width * height];
unsigned long risk[width * height];
ssize_t prev[width * height];
for (size_t i = 0; i < width * height; i++) {
qset[i] = 1;
risk[i] = 0 - 1;
prev[i] = -1;
}
risk[pos] = 0;
while (1) {
bool q_empty = 1;
size_t min = 0;
for (size_t i = 0; i < width * height; i++) {
if (qset[i]) {
q_empty = 0;
if (!qset[min] || risk[i] < risk[min])
min = i;
}
}
if (q_empty)
break;
qset[min] = 0;
size_t neighbours[4];
for (size_t i = 0; i < next(min, neighbours, width, height); i++) {
size_t v = neighbours[i];
if (qset[v]) {
unsigned long alt = risk[min] + grid[v];
if (alt < risk[v]) {
risk[v] = alt;
prev[v] = min;
}
}
}
}
return risk[width * height - 1];
}
int main() {
FILE *fp = fopen("input/day-15.input", "r");
char grid[WIDTH * HEIGHT];
read_grid(grid, fp);
fclose(fp);
printf("PART 1: %lu\n", dijkstra(grid, WIDTH, HEIGHT));
char newgrid[WIDTH * HEIGHT * NUM_GRIDS * NUM_GRIDS];
for (size_t hh = 0; hh < NUM_GRIDS; hh++)
for (size_t ww = 0; ww < NUM_GRIDS; ww++)
for (size_t h = 0; h < HEIGHT; h++)
for (size_t w = 0; w < WIDTH; w++)
newgrid[NPOS(w + WIDTH * ww, h + HEIGHT * hh)] =
(grid[POS(w, h)] + ww + hh - 1) % 9 + 1;
printf("PART 2: %lu\n",
dijkstra(newgrid, WIDTH * NUM_GRIDS, HEIGHT * NUM_GRIDS));
return 0;
} |
the_stack_data/774665.c | #include <stdio.h>
int avg(int *arr) {
const int LEN = (int) (sizeof(arr) / sizeof(arr[0]));
int i; int sum = 0;
for(i = 0; i < LEN; i++) {
sum += arr[i];
}
return sum;
}
void arrcpy(int *dest, int *src) {
*dest = *src;
}
int len(int* arr) {
int i = 0; int* poi = arr;
while(1) {
if(*(poi + i) == NULL) return i;
i++;
}
return 0;
}
|
the_stack_data/70449407.c |
/**
* main.c
*/
int ADC_samples[10] =
{
1522,
1812,
2177,
2488,
2472,
0,
512,
1024,
2048,
4095
};
int main(void)
{
int *ADC_Buffer = ADC_samples;
float OutBuff[10];
int i;
for(i=0; i < 10; i++)
{
OutBuff[i] = ( ( ( (float) *ADC_Buffer ) / 4096 ) * 3.0 ) - 1.5; // convert ADC data into volts and remove DC offset
ADC_Buffer++;
}
return OutBuff[0];
}
|
the_stack_data/957430.c | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define __DEBUG__
// Defines valid digits for integer token
const char DIGITS[] = "0123456789";
typedef enum {INTEGER, PLUS, MINUS, MUL, DIV, END} token;
/*
* Prints an error message and exit immediately.
*/
void error()
{
fprintf(stderr, "Error! Check your input.\n");
exit(-1);
}
/*
* Separates input string into tokens
*/
token get_token(char *current_pos)
{
// Read first character, and check wether its a DIGIT or a operator
switch (current_pos[0]) {
case '+':
return PLUS;
case '-':
return MINUS;
case '*':
return MUL;
case '/':
return DIV;
case '\0':
return END;
default:
return INTEGER;
}
}
/*
* Read the token type, and process the information accordingly.
*/
int expr(char *input)
{
int result = 0;
int op;
int num;
char *current_pos = input;
// Skip whitespaces
while (current_pos[0] == ' ')
current_pos++;
// Expect an integer first
if (get_token(current_pos) != INTEGER) {
error();
return 0;
}
// Set the result to the first integer value
result = atoi(current_pos);
// Advance the pointer to the next character after the INTEGER
current_pos += strspn(current_pos, DIGITS);
// Now read an operator followed by an integer until EOF
while (get_token(current_pos) != END) {
// Skip whitespaces
while (current_pos[0] == ' ')
current_pos++;
// Get the operator
op = get_token(current_pos);
current_pos++;
// Skip whitespaces
while (current_pos[0] == ' ')
current_pos++;
// Get another integer
if (get_token(current_pos) != INTEGER) {
error();
return 0;
}
num = atoi(current_pos);
current_pos += strspn(current_pos, DIGITS);
switch (op) {
case PLUS:
result += num;
break;
case MINUS:
result -= num;
break;
case MUL:
result *= num;
break;
case DIV:
result /= num;
break;
}
}
return result;
}
int main(int argc, char **argv)
{
char input[256];
printf("Calc> ");
fgets(input, 255, stdin);
// Strip the \n at the end
input[strlen(input) - 1] = '\0';
#ifdef __DEBUG__
fprintf(stderr, "Input: %s\n", input);
#endif
printf("%d\n", expr(input));
exit(0);
}
|
the_stack_data/43128.c | #include<stdio.h>
int main(int argc, char const *argv[])
{
long ssquare,sum,n,answer;
printf("Enter the number:");
scanf("%ld",&n);
sum=(n*(n+1))/2;
ssquare=(n*(n+1)*(2*n+1))/6;
answer=ssquare-sum*sum;
printf("%ld",answer);
return 0;
}
|
the_stack_data/345847.c |
/* Assignment No A1-set Operation
Second year Computer Engineering class of M students, set A of students play cricket and
set B of students play badminton. Write C/C++ program to find and display-
i.Set of students who play either cricket or badminton or both
ii.Set of students who play both cricket and badminton
iii. Set of students who play only cricket
iv.Set of students who play only badminton
v.Number of students who play neither cricket nor badminton
(Note- While realizing the set duplicate entries are to avoided)
*/
//header files
#define MAX 30
#include<stdio.h>
#include<stdlib.h>
//declaration
void insert(int []);
void display(int []);
void Union(int [],int [],int []);
void difference(int [],int[] ,int[]);
int total;
int main()
{
int setA[MAX],setB[MAX],setC[MAX],setT[MAX],setC1[MAX],setC2[MAX],setC3[MAX],setC4[MAX],setC5[MAX];
int x,ch;
int ch1;
setA[0]=setB[0]=setC[0]=setT[0]=setC1[0]=setC2[0]=setC3[0]=setC4[0]=setC5[0]=0;
//Menu
do
{
printf("\n\n\t\t------------------------------------------------------------");
printf("\n\n\t\t\t*** MENU ***");
printf("\n\n\t\t1.Enter the choice of student\n\n\t\t2.Student Who play Badminton \n\n\t\t3.Student Who play Cricket");
printf("\n\n\t\t4.Student Who play Badminton ,Cricket Or Both\n\n\t\t5.Student Who play neither Badminton nor Cricket ");
printf("\n\n\t\t6.Student Who play only Badminton(A-B)\n\n\t\t7.Student Who play only Cricket(B-A)\n\n\t\t8.Student Who play Both Games \n\n\t\t9.Exit");
printf("\n\n\t\t------------------------------------------------------------");
printf("\n\n\n\t\tEnter Your Choice:");
scanf("%d",&ch);
switch(ch)
{
case 1:
printf("\n\n\t\t Enter students present in class");
insert(setT);
printf("\n\n\t\t Student Who play Badminton \n\n");
insert(setA);
printf("\n\n\t\t Student Who play Cricket \n\n");
insert(setB);
break;
case 2:
printf("\n\n\n\t\t *** Student Who play Badminton *** :\n\n");
printf("\n\n\n\t\t Roll No of Students :-->\n");
display(setA);
break;
case 3:
printf("\n\n\n\t\t *** Student Who play Cricket*** :\n\n");
printf("\n\n\n\t\t Roll No of Students :-->\n");
display(setB);
break;
case 4:
Union(setA,setB,setC);
printf("\n\n\n\t\t Student Who play Badminton ,Cricket Or Both(AUB):-->\n");
display(setC);
break;
case 5:
difference(setT,setC,setC1);
printf("\n\n\n\t\t Student Who play neither Badminton nor Cricket:-->\n");
display(setC1);
break;
case 6:
difference(setA,setB,setC2);
printf("\n\n\n\t\t Student Who play only Badminton (A-B):-->\n");
display(setC2);
break;
case 7:
difference(setB,setA,setC3);
printf("\n\n\n\t\t Student Who play only Cricket (B-A):-->\n");
display(setC3);
break;
case 8:
//Union(setC2,setC3,setC4);
difference(setA,setC2,setC5);
printf("\n\n\n\t\t Student Who both the game:-->\n");
display(setC5);
break;
case 9:
exit(0);
}
printf("\n\n\n\t\tDo u want to continue............");
scanf("%d",&ch1);
if(ch1==0)
break;
}while(ch!=8);
return 0;
}
// Function definations
//defination for insert
void insert(int set[])
{
int n,i,x;
set[0]=0;
printf("\n\n\t\tEnter No. of Students :\t");
scanf("%d",&n);
set[0]=n;
printf("\n\n\n\t\tEnter Roll no of Student :\n");
for(i=1;i<=n;i++)
scanf("%d",&set[i]);
}
void display(int set[])
{
int i,n;
n=set[0];
if(n==0)
printf("\n\n\n\t\t\tNULL SET");
else
{
printf("\n\n\t\t{ ");
for(i=1;i<=n;i++)
printf("%d ",set[i]);
printf("}");
}
}
/*Defination for union */
void Union(int setA[],int setB[],int setC[])
{
int i,n,n1,m,j,flag;
n=setA[0];
for(i=0;i<=n;i++)
setC[i]=setA[i];
m=n;
m++;
n1=setB[0];
for(i=1;i<=n1;i++)
{
for(j=1;j<=n;j++)
{
if(setB[i]!=setA[j])
{
flag=1;
}
else
{ flag=0;
break;
}
}
if(flag==1)
{
setC[0]++;
setC[m]=setB[i];
m++;
}
}
}
/*defination for difference */
void difference(int setA[],int setB[],int setC[])
{
int i,n,n1,m=1,j,flag=1;
n=setA[0];
n1=setB[0];
setC[0]=0;
for(i=1;i<=n;i++)
{
for(j=1;j<=n1;j++)
{
if(setA[i]!=setB[j])
flag=1;
else
{
flag=0;
break;
}
}
if(flag==1)
{
setC[m]=setA[i];
setC[0]++;
m++;
}
}
}
|
the_stack_data/165766743.c | #include <stdio.h>
#include <malloc.h>
#include <stdbool.h>
typedef struct bst_t {
int data;
struct bst_t *left;
struct bst_t *right;
} bst_t;
void append(bst_t **tree, int data) {
if(*tree && (data > (*tree)->data))
append(&(*tree)->right, data);
else if(*tree && (data <= (*tree)->data))
append(&(*tree)->left, data);
else {
*tree = (bst_t *)malloc(sizeof(bst_t));
(*tree)->data = data;
(*tree)->left = NULL;
(*tree)->right = NULL;
}
}
int get_height(bst_t *tree) {
int h = 1, left = 0, right = 0;
if(tree->left == NULL && tree->right == NULL)
return 0;
if(tree->left)
left += get_height(tree->left);
if(tree->right)
right += get_height(tree->right);
h += (left>right)?left:right;
return h;
}
void display(bst_t *tree) {
if(tree->right)
display(tree->right);
printf("%d->", tree->data);
if(tree->left)
display(tree->left);
}
int main() {
bst_t *tree = NULL;
int values[] = {3, 5, 2, 1, 4, 6, 7};
for(int i=0; i<7; ++i)
append(&tree, values[i]);
display(tree);
printf("\nHeight: %d\n", get_height(tree));
return 0;
}
|
the_stack_data/57949100.c | /*
* pr_pset11_09.c
*
* Write a function that replaces the contents of a string with the string
* reversed. Test the function in a complete program that uses a loop
* to provide input values for feeding to the functions.
*
* Implementation of revstr() with a temporary variable.
* Created by gres.cher on 01/04/19.
*/
#include <stdio.h>
#define SIZE 61 // Maximum input line size
void header(int n);
char * mygets(char * s, int n);
void revstr(char * str);
int main(void)
{
char input[SIZE];
header(SIZE-1);
while (mygets(input, SIZE))
{
printf("Initial string: %s\n", input);
revstr(input);
printf("Reversed string: %s\n", input);
puts("Enter new string (Enter to quit):");
}
puts("done");
return 0;
}
// Output initial program info
void header(int lim)
{
puts("*** Test the revstr() function ***");
puts("It replaces the contents of a string with the string reversed\n");
printf("Enter a string up to %d characters: \n", lim);
}
// Read string; return st address if st[] has at list one character
char * mygets(char * st, int lim)
{
int c, i;
for (i=0, c=0; i<lim-1 && (c=getchar())!=EOF && c!='\n'; i++)
st[i] = c;
// Mark the end of the string and discard the rest of the line
st[i] = '\0';
if (c != '\n' && c != EOF)
while (getchar() != '\n')
continue;
if (i > 0)
/* String has more elements than '\0' character */
return st;
else
return NULL;
}
// Replaces the contents of `str` with the string reversed; use `tmp` variable
void revstr(char * str)
{
int slen = 0;
// Determine length of the string
while (*(str + slen))
slen++;
// String can be reversed
if (slen > 1)
{
char tmp;
for (int i = 0, half = slen/2; i < half; i++)
{
tmp = str[i];
str[i] = str[slen - 1 - i];
str[slen - 1 - i] = tmp;
}
}
}
|
the_stack_data/231392805.c | /* Functions in C */
#include <stdio.h>
/*
Add `int max_of_four(int a, int b, int c, int d)` here.
*/
int max_of_four(int a, int b, int c, int d){
int max1 = a > b ? a : b;
int max2 = c > d ? c : d;
return max1 > max2 ? max1 : max2;
}
int main() {
int a, b, c, d;
scanf("%d %d %d %d", &a, &b, &c, &d);
int ans = max_of_four(a, b, c, d);
printf("%d", ans);
return 0;
}
|
the_stack_data/84328.c | /* Generated by CIL v. 1.7.0 */
/* print_CIL_Input is false */
struct _IO_FILE;
struct timeval;
extern float strtof(char const *str , char const *endptr ) ;
extern void signal(int sig , void *func ) ;
typedef struct _IO_FILE FILE;
extern int atoi(char const *s ) ;
extern double strtod(char const *str , char const *endptr ) ;
extern int fclose(void *stream ) ;
extern void *fopen(char const *filename , char const *mode ) ;
extern void abort() ;
extern void exit(int status ) ;
extern int raise(int sig ) ;
extern int fprintf(struct _IO_FILE *stream , char const *format , ...) ;
extern int strcmp(char const *a , char const *b ) ;
extern int rand() ;
extern unsigned long strtoul(char const *str , char const *endptr , int base ) ;
void RandomFunc(unsigned short input[1] , unsigned short output[1] ) ;
extern int strncmp(char const *s1 , char const *s2 , unsigned long maxlen ) ;
extern int gettimeofday(struct timeval *tv , void *tz , ...) ;
extern int printf(char const *format , ...) ;
int main(int argc , char *argv[] ) ;
void megaInit(void) ;
extern unsigned long strlen(char const *s ) ;
extern long strtol(char const *str , char const *endptr , int base ) ;
extern unsigned long strnlen(char const *s , unsigned long maxlen ) ;
extern void *memcpy(void *s1 , void const *s2 , unsigned long size ) ;
struct timeval {
long tv_sec ;
long tv_usec ;
};
extern void *malloc(unsigned long size ) ;
extern int scanf(char const *format , ...) ;
void RandomFunc(unsigned short input[1] , unsigned short output[1] )
{
unsigned short state[1] ;
unsigned short local1 ;
char copy11 ;
{
state[0UL] = (input[0UL] + 914778474UL) * (unsigned short)64278;
local1 = 0UL;
while (local1 < input[1UL]) {
if (state[0UL] < local1) {
copy11 = *((char *)(& state[0UL]) + 1);
*((char *)(& state[0UL]) + 1) = *((char *)(& state[0UL]) + 0);
*((char *)(& state[0UL]) + 0) = copy11;
state[local1] += state[local1];
} else {
state[0UL] += state[0UL];
}
local1 ++;
}
output[0UL] = (state[0UL] * 166502562UL) * (unsigned short)34066;
}
}
int main(int argc , char *argv[] )
{
unsigned short input[1] ;
unsigned short output[1] ;
int randomFuns_i5 ;
unsigned short randomFuns_value6 ;
int randomFuns_main_i7 ;
{
megaInit();
if (argc != 2) {
printf("Call this program with %i arguments\n", 1);
exit(-1);
} else {
}
randomFuns_i5 = 0;
while (randomFuns_i5 < 1) {
randomFuns_value6 = (unsigned short )strtoul(argv[randomFuns_i5 + 1], 0, 10);
input[randomFuns_i5] = randomFuns_value6;
randomFuns_i5 ++;
}
RandomFunc(input, output);
if (output[0] == (unsigned short)31026) {
printf("You win!\n");
} else {
}
randomFuns_main_i7 = 0;
while (randomFuns_main_i7 < 1) {
printf("%u\n", output[randomFuns_main_i7]);
randomFuns_main_i7 ++;
}
}
}
void megaInit(void)
{
{
}
}
|
the_stack_data/405248.c | #include <stdio.h>
int soma(int a,int b,int c)
{
return a+b+c;
}
main()
{
int n1,n2,n3,n4,resusoma;
printf("digite 3 valores: ");
scanf("%d %d %d",&n1,&n2,&n3);
resusoma=soma(n1,n2,n3);
printf("a resultado e: %d",resusoma);
}
|
the_stack_data/203536.c | #include <stdio.h>
int main()
{
int num[10];
int primos[10];
for (int i = 0; i < 10; i++){
primos[i] = 1;
}
for (int i = 0; i < 10; i++){
printf("Digite um numero: ");
scanf("%d", &num[i]);
}
for(int i = 0; i < 10; i++){
for(int j = 2; j < num[i]; j++)
if (num[i] % j == 0){
primos[i] = 0;
break;
}
}
int soma = 0;
printf("os numeros primos sao: ");
for(int i = 0; i < 10; i++){
if(primos[i] == 1){
soma = soma + num[i];
printf("%d, ", num[i]);
}
}
printf("\nA soma eh: %d", soma);
} |
the_stack_data/14201587.c | /* Taxonomy Classification: 0000000000000142000300 */
/*
* WRITE/READ 0 write
* WHICH BOUND 0 upper
* DATA TYPE 0 char
* MEMORY LOCATION 0 stack
* SCOPE 0 same
* CONTAINER 0 no
* POINTER 0 no
* INDEX COMPLEXITY 0 constant
* ADDRESS COMPLEXITY 0 constant
* LENGTH COMPLEXITY 0 N/A
* ADDRESS ALIAS 0 none
* INDEX ALIAS 0 none
* LOCAL CONTROL FLOW 0 none
* SECONDARY CONTROL FLOW 1 if
* LOOP STRUCTURE 4 non-standard for
* LOOP COMPLEXITY 2 one
* ASYNCHRONY 0 no
* TAINT 0 no
* RUNTIME ENV. DEPENDENCE 0 no
* MAGNITUDE 3 4096 bytes
* CONTINUOUS/DISCRETE 0 discrete
* SIGNEDNESS 0 no
*/
/*
Copyright 2004 M.I.T.
Permission is hereby granted, without written agreement or royalty fee, to use,
copy, modify, and distribute this software and its documentation for any
purpose, provided that the above copyright notice and the following three
paragraphs appear in all copies of this software.
IN NO EVENT SHALL M.I.T. BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT, SPECIAL,
INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OF THIS SOFTWARE
AND ITS DOCUMENTATION, EVEN IF M.I.T. HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMANGE.
M.I.T. SPECIFICALLY DISCLAIMS ANY WARRANTIES INCLUDING, BUT NOT LIMITED TO
THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE,
AND NON-INFRINGEMENT.
THE SOFTWARE IS PROVIDED ON AN "AS-IS" BASIS AND M.I.T. HAS NO OBLIGATION TO
PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
*/
int main(int argc, char *argv[])
{
int inc_value;
int loop_counter;
char buf[10];
inc_value = 4105 - (4105 - 1);
for(loop_counter = 0; ; loop_counter += inc_value)
{
if (loop_counter > 4105) break;
/* BAD */
buf[4105] = 'A';
}
return 0;
}
|
the_stack_data/730760.c | #include <stdio.h>
int main()
{
printf("hello world\n");
return 0;
} |
the_stack_data/28262653.c | /*******************************************************************************
*
* Copyright (C) 2009-2011 Broadcom Corporation
*
* 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.
*
******************************************************************************/
/*****************************************************************************
**
** Name: brcm_patchram_plus_h5.c
**
** Description: This program downloads a patchram files in the HCD format
** to Broadcom Bluetooth based silicon and combo chips and
** and other utility functions.
**
** It can be invoked from the command line in the form
** <-d> to print a debug log
** <--patchram patchram_file>
** <--baudrate baud_rate>
** <--bd_addr bd_address>
** <--enable_lpm>
** <--enable_h4 | --enable_h5>
** <--use_baudrate_for_download>
** <--scopcm=sco_routing,pcm_interface_rate,frame_type,
** sync_mode,clock_mode,lsb_first,fill_bits,
** fill_method,fill_num,right_justify>
**
** Where
**
** sco_routing is 0 for PCM, 1 for Transport,
** 2 for Codec and 3 for I2S,
**
** pcm_interface_rate is 0 for 128KBps, 1 for
** 256 KBps, 2 for 512KBps, 3 for 1024KBps,
** and 4 for 2048Kbps,
**
** frame_type is 0 for short and 1 for long,
**
** sync_mode is 0 for slave and 1 for master,
**
** clock_mode is 0 for slabe and 1 for master,
**
** lsb_first is 0 for false and 1 for true,
**
** fill_bits is the value in decimal for unused bits,
**
** fill_method is 0 for 0's and 1 for 1's, 2 for
** signed and 3 for programmable,
**
** fill_num is the number or bits to fill,
**
** right_justify is 0 for false and 1 for true
**
** <--i2s=i2s_enable,is_master,sample_rate,clock_rate>
**
** Where
**
** i2s_enable is 0 for disable and 1 for enable,
**
** is_master is 0 for slave and 1 for master,
**
** sample_rate is 0 for 8KHz, 1 for 16Khz and
** 2 for 4 KHz,
**
** clock_rate is 0 for 128KHz, 1 for 256KHz, 3 for
** 1024 KHz and 4 for 2048 KHz.
**
** <--no2bytes skips waiting for two byte confirmation
** before starting patchram download. Newer chips
** do not generate these two bytes.>
** <--tosleep=number of microsseconds to sleep before
** patchram download begins.>
** uart_device_name
**
** For example:
**
** brcm_patchram_plus -d --patchram \
** BCM2045B2_002.002.011.0348.0349.hcd /dev/ttyHS0
**
** It will return 0 for success and a number greater than 0
** for any errors.
**
** For Android, this program invoked using a
** "system(2)" call from the beginning of the bt_enable
** function inside the file
** system/bluetooth/bluedroid/bluetooth.c.
**
** If the Android system property "ro.bt.bcm_bdaddr_path" is
** set, then the bd_addr will be read from this path.
** This is overridden by --bd_addr on the command line.
**
******************************************************************************/
#include <stdio.h>
#include <getopt.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdlib.h>
#include <unistd.h>
#ifdef ANDROID
#include <termios.h>
#else
#include <sys/termios.h>
#include <sys/ioctl.h>
#include <limits.h>
#endif
#include <string.h>
#include <signal.h>
#include <time.h>
#ifdef ANDROID
#include <cutils/properties.h>
#define LOG_TAG "brcm_patchram_plus"
#include <cutils/log.h>
#undef printf
#define printf LOGD
#undef fprintf
#define fprintf(x, ...) \
{ if(x==stderr) LOGE(__VA_ARGS__); else fprintf(x, __VA_ARGS__); }
#endif //ANDROID
#ifndef N_HCI
#define N_HCI 15
#endif
#define HCIUARTSETPROTO _IOW('U', 200, int)
#define HCIUARTGETPROTO _IOR('U', 201, int)
#define HCIUARTGETDEVICE _IOR('U', 202, int)
#define HCI_UART_H4 0
#define HCI_UART_BCSP 1
#define HCI_UART_3WIRE 2
#define HCI_UART_H4DS 3
#define HCI_UART_LL 4
#define HCI_UART_H5 5
#define CHIP_ID_4330B2 0x43
#define CHIP_ID_4329B1 0x29
typedef unsigned char uchar;
int uart_fd = -1;
int hcdfile_fd = -1;
int termios_baudrate = 0;
int bdaddr_flag = 0;
int enable_lpm = 0;
int enable_h4 = 0;
int enable_h5 = 0;
int use_baudrate_for_download = 0;
int debug = 0;
int scopcm = 0;
int i2s = 0;
int no2bytes = 0;
int tosleep = 0;
struct termios termios;
uchar buffer[1024];
uchar hci_reset[] = { 0x01, 0x03, 0x0c, 0x00 };
uchar hci_download_minidriver[] = { 0x01, 0x2e, 0xfc, 0x00 };
uchar hci_update_baud_rate[] = { 0x01, 0x18, 0xfc, 0x06, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00 };
uchar hci_write_bd_addr[] = { 0x01, 0x01, 0xfc, 0x06,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
uchar hci_write_sleep_mode[] = { 0x01, 0x27, 0xfc, 0x0c,
0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x00, 0x00, 0x00,
0x00, 0x00 };
uchar hci_write_sco_pcm_int[] =
{ 0x01, 0x1C, 0xFC, 0x05, 0x00, 0x00, 0x00, 0x00, 0x00 };
uchar hci_write_pcm_data_format[] =
{ 0x01, 0x1e, 0xFC, 0x05, 0x00, 0x00, 0x00, 0x00, 0x00 };
uchar hci_write_i2spcm_interface_param[] =
{ 0x01, 0x6d, 0xFC, 0x04, 0x00, 0x00, 0x00, 0x00 };
uchar hci_read_verbose_config_version_info[] =
{ 0x01, 0x79, 0xfc, 0x00 };
uchar slip_sync[] =
{ 0xc0, 0x00, 0x2f, 0x00, 0xd0, 0x01, 0x7e, 0xc0 };
uchar slip_sync_response[] =
{ 0xc0, 0x00, 0x2f, 0x00, 0xd0, 0x02, 0x7d, 0xc0 };
uchar slip_config[] =
{ 0xc0, 0x00, 0x3f, 0x00, 0xdb, 0xdc, 0x03, 0xfc, 0x1b, 0xc0 };
uchar slip_config_response[] =
{ 0xc0, 0x00, 0x3f, 0x00, 0xdb, 0xdc, 0x04, 0x7b, 0x1b, 0xc0 };
uchar slip_config_null_response[] =
{ 0xc0, 0x00, 0x2f, 0x00, 0xd0, 0x04, 0x7b, 0xc0 };
uchar slip_read_local_version_info[] =
{ 0xc0, 0xdb, 0xdc, 0x31, 0x00, 0x0e, 0x01, 0x10, 0x00, 0x06, 0x09, 0xc0 };
uchar slip_ack[] =
{ 0xc0, 0x48, 0x00, 0x00, 0xb7, 0x5e, 0x8c, 0xc0 };
int
parse_patchram(char *optarg)
{
char *p;
if (!(p = strrchr(optarg, '.'))) {
fprintf(stderr, "file %s not an HCD file\n", optarg);
exit(3);
}
p++;
if (strcasecmp("hcd", p) != 0) {
fprintf(stderr, "file %s not an HCD file\n", optarg);
exit(4);
}
if ((hcdfile_fd = open(optarg, O_RDONLY)) == -1) {
fprintf(stderr, "file %s could not be opened, error %d\n", optarg, errno);
exit(5);
}
return(0);
}
void
BRCM_encode_baud_rate(uint baud_rate, uchar *encoded_baud)
{
if(baud_rate == 0 || encoded_baud == NULL) {
fprintf(stderr, "Baudrate not supported!");
return;
}
encoded_baud[3] = (uchar)(baud_rate >> 24);
encoded_baud[2] = (uchar)(baud_rate >> 16);
encoded_baud[1] = (uchar)(baud_rate >> 8);
encoded_baud[0] = (uchar)(baud_rate & 0xFF);
}
typedef struct {
int baud_rate;
int termios_value;
} tBaudRates;
tBaudRates baud_rates[] = {
{ 115200, B115200 },
{ 230400, B230400 },
{ 460800, B460800 },
{ 500000, B500000 },
{ 576000, B576000 },
{ 921600, B921600 },
{ 1000000, B1000000 },
{ 1152000, B1152000 },
{ 1500000, B1500000 },
{ 2000000, B2000000 },
{ 2500000, B2500000 },
{ 3000000, B3000000 },
#ifndef __CYGWIN__
{ 3500000, B3500000 },
{ 4000000, B4000000 }
#endif
};
int
validate_baudrate(int baud_rate, int *value)
{
unsigned int i;
for (i = 0; i < (sizeof(baud_rates) / sizeof(tBaudRates)); i++) {
if (baud_rates[i].baud_rate == baud_rate) {
*value = baud_rates[i].termios_value;
return(1);
}
}
return(0);
}
int
parse_baudrate(char *optarg)
{
int baudrate = atoi(optarg);
if (validate_baudrate(baudrate, &termios_baudrate)) {
BRCM_encode_baud_rate(baudrate, &hci_update_baud_rate[6]);
} else {
return(1);
}
return(0);
}
int
parse_bdaddr(char *optarg)
{
int bd_addr[6];
int i;
sscanf(optarg, "%02X:%02X:%02X:%02X:%02X:%02X",
&bd_addr[5], &bd_addr[4], &bd_addr[3],
&bd_addr[2], &bd_addr[1], &bd_addr[0]);
for (i = 0; i < 6; i++) {
hci_write_bd_addr[4 + i] = bd_addr[i];
}
bdaddr_flag = 1;
return(0);
}
int
parse_enable_lpm(char *optarg)
{
enable_lpm = 1;
return(0);
}
int
parse_use_baudrate_for_download(char *optarg)
{
use_baudrate_for_download = 1;
return(0);
}
int
parse_enable_h4(char *optarg)
{
enable_h4 = 1;
return(0);
}
int
parse_enable_h5(char *optarg)
{
enable_h5 = 1;
return(0);
}
int
parse_scopcm(char *optarg)
{
int param[10];
int ret;
int i;
ret = sscanf(optarg, "%d,%d,%d,%d,%d,%d,%d,%d,%d,%d",
¶m[0], ¶m[1], ¶m[2], ¶m[3], ¶m[4],
¶m[5], ¶m[6], ¶m[7], ¶m[8], ¶m[9]);
if (ret != 10) {
return(1);
}
scopcm = 1;
for (i = 0; i < 5; i++) {
hci_write_sco_pcm_int[4 + i] = param[i];
}
for (i = 0; i < 5; i++) {
hci_write_pcm_data_format[4 + i] = param[5 + i];
}
return(0);
}
int
parse_i2s(char *optarg)
{
int param[4];
int ret;
int i;
ret = sscanf(optarg, "%d,%d,%d,%d", ¶m[0], ¶m[1], ¶m[2],
¶m[3]);
if (ret != 4) {
return(1);
}
i2s = 1;
for (i = 0; i < 4; i++) {
hci_write_i2spcm_interface_param[4 + i] = param[i];
}
}
int
parse_no2bytes(char *optarg)
{
no2bytes = 1;
return(0);
}
int
parse_tosleep(char *optarg)
{
tosleep = atoi(optarg);
if (tosleep <= 0) {
return(1);
}
return(0);
}
void
usage(char *argv0)
{
printf("Usage %s:\n", argv0);
printf("\t<-d> to print a debug log\n");
printf("\t<--patchram patchram_file>\n");
printf("\t<--baudrate baud_rate>\n");
printf("\t<--bd_addr bd_address>\n");
printf("\t<--enable_lpm>\n");
printf("\t<--enable_h4 |--enable_h5>\n");
printf("\t<--use_baudrate_for_download> - Uses the\n");
printf("\t\tbaudrate for downloading the firmware\n");
printf("\t<--scopcm=sco_routing,pcm_interface_rate,frame_type,\n");
printf("\t\tsync_mode,clock_mode,lsb_first,fill_bits,\n");
printf("\t\tfill_method,fill_num,right_justify>\n");
printf("\n\t\tWhere\n");
printf("\n\t\tsco_routing is 0 for PCM, 1 for Transport,\n");
printf("\t\t2 for Codec and 3 for I2S,\n");
printf("\n\t\tpcm_interface_rate is 0 for 128KBps, 1 for\n");
printf("\t\t256 KBps, 2 for 512KBps, 3 for 1024KBps,\n");
printf("\t\tand 4 for 2048Kbps,\n");
printf("\n\t\tframe_type is 0 for short and 1 for long,\n");
printf("\t\tsync_mode is 0 for slave and 1 for master,\n");
printf("\n\t\tclock_mode is 0 for slabe and 1 for master,\n");
printf("\n\t\tlsb_first is 0 for false aand 1 for true,\n");
printf("\n\t\tfill_bits is the value in decimal for unused bits,\n");
printf("\n\t\tfill_method is 0 for 0's and 1 for 1's, 2 for\n");
printf("\t\tsigned and 3 for programmable,\n");
printf("\n\t\tfill_num is the number or bits to fill,\n");
printf("\n\t\tright_justify is 0 for false and 1 for true\n");
printf("\n\t<--i2s=i2s_enable,is_master,sample_rate,clock_rate>\n");
printf("\n\t\tWhere\n");
printf("\n\t\ti2s_enable is 0 for disable and 1 for enable,\n");
printf("\n\t\tis_master is 0 for slave and 1 for master,\n");
printf("\n\t\tsample_rate is 0 for 8KHz, 1 for 16Khz and\n");
printf("\t\t2 for 4 KHz,\n");
printf("\n\t\tclock_rate is 0 for 128KHz, 1 for 256KHz, 3 for\n");
printf("\t\t1024 KHz and 4 for 2048 KHz.\n\n");
printf("\t<--no2bytes skips waiting for two byte confirmation\n");
printf("\t\tbefore starting patchram download. Newer chips\n");
printf("\t\tdo not generate these two bytes.>\n");
printf("\t<--tosleep=microseconds>\n");
printf("\tuart_device_name\n");
}
int
parse_cmd_line(int argc, char **argv)
{
int c;
int ret = 0;
typedef int (*PFI)();
PFI parse[] = { parse_patchram, parse_baudrate,
parse_bdaddr, parse_enable_lpm, parse_enable_h4,
parse_enable_h5, parse_use_baudrate_for_download,
parse_scopcm, parse_i2s, parse_no2bytes, parse_tosleep};
while (1) {
int this_option_optind = optind ? optind : 1;
int option_index = 0;
static struct option long_options[] = {
{"patchram", 1, 0, 0},
{"baudrate", 1, 0, 0},
{"bd_addr", 1, 0, 0},
{"enable_lpm", 0, 0, 0},
{"enable_h4", 0, 0, 0},
{"enable_h5", 0, 0, 0},
{"use_baudrate_for_download", 0, 0, 0},
{"scopcm", 1, 0, 0},
{"i2s", 1, 0, 0},
{"no2bytes", 0, 0, 0},
{"tosleep", 1, 0, 0},
{0, 0, 0, 0}
};
c = getopt_long_only (argc, argv, "d", long_options,
&option_index);
if (c == -1) {
break;
}
switch (c) {
case 0:
if (debug) {
printf ("option %s",
long_options[option_index].name);
if (optarg)
printf (" with arg %s", optarg);
printf ("\n");
}
ret = (*parse[option_index])(optarg);
break;
case 'd':
debug = 1;
break;
case '?':
// nobreak;
default:
usage(argv[0]);
break;
}
if (ret) {
usage(argv[0]);
break;
}
}
if (ret) {
return(1);
}
if (optind < argc) {
if (debug)
printf ("%s \n", argv[optind]);
if ((uart_fd = open(argv[optind], O_RDWR | O_NOCTTY)) == -1) {
fprintf(stderr, "port %s could not be opened, error %d\n",
argv[2], errno);
}
}
return(0);
}
void
init_uart()
{
tcflush(uart_fd, TCIOFLUSH);
tcgetattr(uart_fd, &termios);
#ifndef __CYGWIN__
cfmakeraw(&termios);
#else
termios.c_iflag &= ~(IGNBRK | BRKINT | PARMRK | ISTRIP
| INLCR | IGNCR | ICRNL | IXON);
termios.c_oflag &= ~OPOST;
termios.c_lflag &= ~(ECHO | ECHONL | ICANON | ISIG | IEXTEN);
termios.c_cflag &= ~(CSIZE | PARENB);
termios.c_cflag |= CS8;
#endif
termios.c_cflag &= ~CRTSCTS;
tcsetattr(uart_fd, TCSANOW, &termios);
tcflush(uart_fd, TCIOFLUSH);
tcsetattr(uart_fd, TCSANOW, &termios);
tcflush(uart_fd, TCIOFLUSH);
tcflush(uart_fd, TCIOFLUSH);
cfsetospeed(&termios, B115200);
cfsetispeed(&termios, B115200);
tcsetattr(uart_fd, TCSANOW, &termios);
}
void
dump(uchar *out, int len)
{
int i;
for (i = 0; i < len; i++) {
if (i && !(i % 16)) {
fprintf(stderr, "\n");
}
fprintf(stderr, "%02x ", out[i]);
}
fprintf(stderr, "\n");
}
void
read_event(int fd, uchar *buffer)
{
int i = 0;
int len = 3;
int count;
i = 0;
len = 3;
while ((count = read(fd, &buffer[i], len)) < len) {
if (debug) {
count += i;
fprintf(stderr, "received %d len %d\n", count, len);
dump(buffer, count);
}
i += count;
len -= count;
}
i += count;
len = buffer[2];
while ((count = read(fd, &buffer[i], len)) < len) {
i += count;
len -= count;
}
if (debug) {
count += i;
fprintf(stderr, "received %d\n", count);
dump(buffer, count);
}
}
void
hci_send_cmd(uchar *buf, int len)
{
if (debug) {
fprintf(stderr, "writing\n");
dump(buf, len);
}
write(uart_fd, buf, len);
}
void
expired(int sig)
{
hci_send_cmd(hci_reset, sizeof(hci_reset));
alarm(4);
}
void
slip_expired(int sig)
{
hci_send_cmd(slip_sync, sizeof(slip_sync));
alarm(4);
}
void
slip_config_expired(int sig)
{
hci_send_cmd(slip_config, sizeof(slip_config));
alarm(4);
}
void
proc_reset()
{
signal(SIGALRM, expired);
hci_send_cmd(hci_reset, sizeof(hci_reset));
alarm(4);
read_event(uart_fd, buffer);
alarm(0);
}
void
proc_patchram()
{
int len;
uchar chip_id;
hci_send_cmd(hci_read_verbose_config_version_info,
sizeof(hci_read_verbose_config_version_info));
read_event(uart_fd, buffer);
chip_id = buffer[7];
if (debug) {
fprintf(stderr, "chip_id is %02x\n", chip_id);
}
if (chip_id == CHIP_ID_4330B2) {
no2bytes = 1;
}
hci_send_cmd(hci_download_minidriver, sizeof(hci_download_minidriver));
read_event(uart_fd, buffer);
if (!no2bytes) {
read(uart_fd, &buffer[0], 2);
}
if (tosleep) {
usleep(tosleep);
}
while (read(hcdfile_fd, &buffer[1], 3)) {
buffer[0] = 0x01;
len = buffer[3];
read(hcdfile_fd, &buffer[4], len);
hci_send_cmd(buffer, len + 4);
read_event(uart_fd, buffer);
}
if (use_baudrate_for_download) {
cfsetospeed(&termios, B115200);
cfsetispeed(&termios, B115200);
tcsetattr(uart_fd, TCSANOW, &termios);
}
proc_reset();
}
void
proc_baudrate()
{
hci_send_cmd(hci_update_baud_rate, sizeof(hci_update_baud_rate));
read_event(uart_fd, buffer);
cfsetospeed(&termios, termios_baudrate);
cfsetispeed(&termios, termios_baudrate);
tcsetattr(uart_fd, TCSANOW, &termios);
if (debug) {
fprintf(stderr, "Done setting baudrate\n");
}
sleep(1);
}
void
proc_bdaddr()
{
hci_send_cmd(hci_write_bd_addr, sizeof(hci_write_bd_addr));
read_event(uart_fd, buffer);
}
void
proc_enable_lpm()
{
hci_send_cmd(hci_write_sleep_mode, sizeof(hci_write_sleep_mode));
read_event(uart_fd, buffer);
}
void
proc_scopcm()
{
hci_send_cmd(hci_write_sco_pcm_int,
sizeof(hci_write_sco_pcm_int));
read_event(uart_fd, buffer);
hci_send_cmd(hci_write_pcm_data_format,
sizeof(hci_write_pcm_data_format));
read_event(uart_fd, buffer);
}
void
proc_i2s()
{
hci_send_cmd(hci_write_i2spcm_interface_param,
sizeof(hci_write_i2spcm_interface_param));
read_event(uart_fd, buffer);
}
void
proc_enable_hci()
{
int i = N_HCI;
int proto = (enable_h4 ? HCI_UART_H4 : HCI_UART_H5);
if (ioctl(uart_fd, TIOCSETD, &i) < 0) {
fprintf(stderr, "Can't set line discipline\n");
return;
}
if (ioctl(uart_fd, HCIUARTSETPROTO, proto) < 0) {
fprintf(stderr, "Can't set hci protocol\n");
return;
}
if (debug) {
fprintf(stderr, "Done setting line discpline\n");
}
return;
}
#ifdef ANDROID
void
read_default_bdaddr()
{
int sz;
int fd;
char path[PROPERTY_VALUE_MAX];
char bdaddr[18];
int len = 17;
memset(bdaddr, 0, (len + 1) * sizeof(char));
property_get("ro.bt.bdaddr_path", path, "");
if (path[0] == 0)
return;
fd = open(path, O_RDONLY);
if (fd < 0) {
fprintf(stderr, "open(%s) failed: %s (%d)", path, strerror(errno),
errno);
return;
}
sz = read(fd, bdaddr, len);
if (sz < 0) {
fprintf(stderr, "read(%s) failed: %s (%d)", path, strerror(errno),
errno);
close(fd);
return;
} else if (sz != len) {
fprintf(stderr, "read(%s) unexpected size %d", path, sz);
close(fd);
return;
}
if (debug) {
printf("Read default bdaddr of %s\n", bdaddr);
}
parse_bdaddr(bdaddr);
}
#endif
int
proc_slip_sync()
{
int count;
int ret = 0;
signal(SIGALRM, slip_expired);
hci_send_cmd(slip_sync, sizeof(slip_sync));
alarm(4);
while (!ret) {
count = read(uart_fd, buffer, sizeof(slip_sync));
if (debug) {
fprintf(stderr, "received slip sync %d\n", count);
dump(buffer, count);
}
if (buffer[6] == 0x7d) {
alarm(0);
ret = 1;
} else {
hci_send_cmd(slip_sync_response, sizeof(slip_sync_response));
}
}
return(ret);
}
int
proc_slip_config()
{
int count;
int ret = 0;
signal(SIGALRM, slip_config_expired);
hci_send_cmd(slip_config, sizeof(slip_config));
alarm(4);
while (!ret) {
count = read(uart_fd, buffer, sizeof(slip_config_response));
if (debug) {
fprintf(stderr, "received slip config %d\n", count);
dump(buffer, count);
}
if (count == 8) {
if (buffer[5] == 0x03 && buffer[6] == 0xfc) {
hci_send_cmd(slip_config_null_response,
sizeof(slip_config_null_response));
} else {
hci_send_cmd(slip_sync_response, sizeof(slip_sync_response));
}
} else if (buffer[7] == 0x7b) {
alarm(0);
ret = 1;
} else {
hci_send_cmd(slip_config_response, sizeof(slip_config_response));
}
}
return(ret);
}
slip_read()
{
int count;
count = read(uart_fd, buffer, 1024);
if (debug) {
fprintf(stderr, "received slip config %d\n", count);
dump(buffer, count);
}
}
int
main (int argc, char **argv)
{
char byte;
#ifdef ANDROID
read_default_bdaddr();
#endif
if (parse_cmd_line(argc, argv)) {
exit(1);
}
if (uart_fd < 0) {
exit(2);
}
init_uart();
proc_reset();
if (use_baudrate_for_download) {
if (termios_baudrate) {
proc_baudrate();
}
}
if (hcdfile_fd > 0) {
proc_patchram();
}
if (termios_baudrate) {
proc_baudrate();
}
if (bdaddr_flag) {
proc_bdaddr();
}
if (enable_lpm) {
proc_enable_lpm();
}
if (scopcm) {
proc_scopcm();
}
if (i2s) {
proc_i2s();
}
if (enable_h5) {
time_t t;
time(&t);
fprintf(stderr, "start %s\n", ctime(&t));
while (!proc_slip_sync()) {
sleep(4);
}
proc_slip_config();
time(&t);
fprintf(stderr, "end %s\n", ctime(&t));
}
if (enable_h4 && enable_h5) {
fprintf(stderr, "Both H4 and H5 cannot be enabled at the same time\n");
exit(1);
}
if (enable_h4 || enable_h5) {
if (enable_h5) {
// turn XON/XOFF back on
tcgetattr(uart_fd, &termios);
termios.c_iflag |= (IXON | IXOFF);
termios.c_lflag |= ICANON;
tcsetattr(uart_fd, TCSANOW, &termios);
}
proc_enable_hci();
while (1) {
sleep(UINT_MAX);
}
}
exit(0);
}
|
the_stack_data/98574664.c | /* Convert a `struct tm' to a time_t value.
Copyright (C) 1993, 94, 95, 96, 97, 98, 99 Free Software Foundation, Inc.
This file is part of the GNU C Library.
Contributed by Paul Eggert ([email protected]).
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 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 General Public License for more details.
You should have received a copy of the GNU 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. */
/* Define this to have a standalone program to test this implementation of
mktime. */
/* #define DEBUG 1 */
#ifdef HAVE_CONFIG_H
# include <config.h>
#endif
#ifdef _LIBC
# define HAVE_LIMITS_H 1
# define STDC_HEADERS 1
#endif
/* Assume that leap seconds are possible, unless told otherwise.
If the host has a `zic' command with a `-L leapsecondfilename' option,
then it supports leap seconds; otherwise it probably doesn't. */
#ifndef LEAP_SECONDS_POSSIBLE
# define LEAP_SECONDS_POSSIBLE 1
#endif
#include <sys/types.h> /* Some systems define `time_t' here. */
#include <time.h>
#if HAVE_LIMITS_H
# include <limits.h>
#endif
#if DEBUG
# include <stdio.h>
# if STDC_HEADERS
# include <stdlib.h>
# endif
/* Make it work even if the system's libc has its own mktime routine. */
# define mktime my_mktime
#endif /* DEBUG */
#ifndef __P
# if defined __GNUC__ || (defined __STDC__ && __STDC__)
# define __P(args) args
# else
# define __P(args) ()
# endif /* GCC. */
#endif /* Not __P. */
#ifndef CHAR_BIT
# define CHAR_BIT 8
#endif
/* The extra casts work around common compiler bugs. */
#define TYPE_SIGNED(t) (! ((t) 0 < (t) -1))
/* The outer cast is needed to work around a bug in Cray C 5.0.3.0.
It is necessary at least when t == time_t. */
#define TYPE_MINIMUM(t) ((t) (TYPE_SIGNED (t) \
? ~ (t) 0 << (sizeof (t) * CHAR_BIT - 1) : (t) 0))
#define TYPE_MAXIMUM(t) ((t) (~ (t) 0 - TYPE_MINIMUM (t)))
#ifndef INT_MIN
# define INT_MIN TYPE_MINIMUM (int)
#endif
#ifndef INT_MAX
# define INT_MAX TYPE_MAXIMUM (int)
#endif
#ifndef TIME_T_MIN
# define TIME_T_MIN TYPE_MINIMUM (time_t)
#endif
#ifndef TIME_T_MAX
# define TIME_T_MAX TYPE_MAXIMUM (time_t)
#endif
#define TM_YEAR_BASE 1900
#define EPOCH_YEAR 1970
#ifndef __isleap
/* Nonzero if YEAR is a leap year (every 4 years,
except every 100th isn't, and every 400th is). */
# define __isleap(year) \
((year) % 4 == 0 && ((year) % 100 != 0 || (year) % 400 == 0))
#endif
/* How many days come before each month (0-12). */
const unsigned short int __mon_yday[2][13] =
{
/* Normal years. */
{ 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365 },
/* Leap years. */
{ 0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335, 366 }
};
#ifdef _LIBC
# define my_mktime_localtime_r __localtime_r
#else
/* If we're a mktime substitute in a GNU program, then prefer
localtime to localtime_r, since many localtime_r implementations
are buggy. */
static struct tm *
my_mktime_localtime_r (const time_t *t, struct tm *tp)
{
struct tm *l = localtime (t);
if (! l)
return 0;
*tp = *l;
return tp;
}
#endif /* ! _LIBC */
/* Yield the difference between (YEAR-YDAY HOUR:MIN:SEC) and (*TP),
measured in seconds, ignoring leap seconds.
YEAR uses the same numbering as TM->tm_year.
All values are in range, except possibly YEAR.
If TP is null, return a nonzero value.
If overflow occurs, yield the low order bits of the correct answer. */
static time_t
ydhms_tm_diff (int year, int yday, int hour, int min, int sec,
const struct tm *tp)
{
if (!tp)
return 1;
else
{
/* Compute intervening leap days correctly even if year is negative.
Take care to avoid int overflow. time_t overflow is OK, since
only the low order bits of the correct time_t answer are needed.
Don't convert to time_t until after all divisions are done, since
time_t might be unsigned. */
int a4 = (year >> 2) + (TM_YEAR_BASE >> 2) - ! (year & 3);
int b4 = (tp->tm_year >> 2) + (TM_YEAR_BASE >> 2) - ! (tp->tm_year & 3);
int a100 = a4 / 25 - (a4 % 25 < 0);
int b100 = b4 / 25 - (b4 % 25 < 0);
int a400 = a100 >> 2;
int b400 = b100 >> 2;
int intervening_leap_days = (a4 - b4) - (a100 - b100) + (a400 - b400);
time_t years = year - (time_t) tp->tm_year;
time_t days = (365 * years + intervening_leap_days
+ (yday - tp->tm_yday));
return (60 * (60 * (24 * days + (hour - tp->tm_hour))
+ (min - tp->tm_min))
+ (sec - tp->tm_sec));
}
}
/* Use CONVERT to convert *T to a broken down time in *TP.
If *T is out of range for conversion, adjust it so that
it is the nearest in-range value and then convert that. */
static struct tm *
ranged_convert (struct tm *(*convert) (const time_t *, struct tm *),
time_t *t, struct tm *tp)
{
struct tm *r;
if (! (r = (*convert) (t, tp)) && *t)
{
time_t bad = *t;
time_t ok = 0;
struct tm tm;
/* BAD is a known unconvertible time_t, and OK is a known good one.
Use binary search to narrow the range between BAD and OK until
they differ by 1. */
while (bad != ok + (bad < 0 ? -1 : 1))
{
time_t mid = *t = (bad < 0
? bad + ((ok - bad) >> 1)
: ok + ((bad - ok) >> 1));
if ((r = (*convert) (t, tp)))
{
tm = *r;
ok = mid;
}
else
bad = mid;
}
if (!r && ok)
{
/* The last conversion attempt failed;
revert to the most recent successful attempt. */
*t = ok;
*tp = tm;
r = tp;
}
}
return r;
}
/* Convert *TP to a time_t value, inverting
the monotonic and mostly-unit-linear conversion function CONVERT.
Use *OFFSET to keep track of a guess at the offset of the result,
compared to what the result would be for UTC without leap seconds.
If *OFFSET's guess is correct, only one CONVERT call is needed. */
time_t
__mktime_internal (struct tm *tp,
struct tm *(*convert) (const time_t *, struct tm *),
time_t *offset)
{
time_t t, dt, t0, t1, t2;
struct tm tm;
/* The maximum number of probes (calls to CONVERT) should be enough
to handle any combinations of time zone rule changes, solar time,
leap seconds, and oscillations around a spring-forward gap.
POSIX.1 prohibits leap seconds, but some hosts have them anyway. */
int remaining_probes = 6;
/* Time requested. Copy it in case CONVERT modifies *TP; this can
occur if TP is localtime's returned value and CONVERT is localtime. */
int sec = tp->tm_sec;
int min = tp->tm_min;
int hour = tp->tm_hour;
int mday = tp->tm_mday;
int mon = tp->tm_mon;
int year_requested = tp->tm_year;
int isdst = tp->tm_isdst;
/* Ensure that mon is in range, and set year accordingly. */
int mon_remainder = mon % 12;
int negative_mon_remainder = mon_remainder < 0;
int mon_years = mon / 12 - negative_mon_remainder;
int year = year_requested + mon_years;
/* The other values need not be in range:
the remaining code handles minor overflows correctly,
assuming int and time_t arithmetic wraps around.
Major overflows are caught at the end. */
/* Calculate day of year from year, month, and day of month.
The result need not be in range. */
int yday = ((__mon_yday[__isleap (year + TM_YEAR_BASE)]
[mon_remainder + 12 * negative_mon_remainder])
+ mday - 1);
int sec_requested = sec;
#if LEAP_SECONDS_POSSIBLE
/* Handle out-of-range seconds specially,
since ydhms_tm_diff assumes every minute has 60 seconds. */
if (sec < 0)
sec = 0;
if (59 < sec)
sec = 59;
#endif
/* Invert CONVERT by probing. First assume the same offset as last time.
Then repeatedly use the error to improve the guess. */
tm.tm_year = EPOCH_YEAR - TM_YEAR_BASE;
tm.tm_yday = tm.tm_hour = tm.tm_min = tm.tm_sec = 0;
t0 = ydhms_tm_diff (year, yday, hour, min, sec, &tm);
for (t = t1 = t2 = t0 + *offset;
(dt = ydhms_tm_diff (year, yday, hour, min, sec,
ranged_convert (convert, &t, &tm)));
t1 = t2, t2 = t, t += dt)
if (t == t1 && t != t2
&& (isdst < 0 || tm.tm_isdst < 0
|| (isdst != 0) != (tm.tm_isdst != 0)))
/* We can't possibly find a match, as we are oscillating
between two values. The requested time probably falls
within a spring-forward gap of size DT. Follow the common
practice in this case, which is to return a time that is DT
away from the requested time, preferring a time whose
tm_isdst differs from the requested value. In practice,
this is more useful than returning -1. */
break;
else if (--remaining_probes == 0)
return -1;
/* If we have a match, check whether tm.tm_isdst has the requested
value, if any. */
if (dt == 0 && isdst != tm.tm_isdst && 0 <= isdst && 0 <= tm.tm_isdst)
{
/* tm.tm_isdst has the wrong value. Look for a neighboring
time with the right value, and use its UTC offset.
Heuristic: probe the previous three calendar quarters (approximately),
looking for the desired isdst. This isn't perfect,
but it's good enough in practice. */
int quarter = 7889238; /* seconds per average 1/4 Gregorian year */
int i;
/* If we're too close to the time_t limit, look in future quarters. */
if (t < TIME_T_MIN + 3 * quarter)
quarter = -quarter;
for (i = 1; i <= 3; i++)
{
time_t ot = t - i * quarter;
struct tm otm;
ranged_convert (convert, &ot, &otm);
if (otm.tm_isdst == isdst)
{
/* We found the desired tm_isdst.
Extrapolate back to the desired time. */
t = ot + ydhms_tm_diff (year, yday, hour, min, sec, &otm);
ranged_convert (convert, &t, &tm);
break;
}
}
}
*offset = t - t0;
#if LEAP_SECONDS_POSSIBLE
if (sec_requested != tm.tm_sec)
{
/* Adjust time to reflect the tm_sec requested, not the normalized value.
Also, repair any damage from a false match due to a leap second. */
t += sec_requested - sec + (sec == 0 && tm.tm_sec == 60);
if (! (*convert) (&t, &tm))
return -1;
}
#endif
if (TIME_T_MAX / INT_MAX / 366 / 24 / 60 / 60 < 3)
{
/* time_t isn't large enough to rule out overflows in ydhms_tm_diff,
so check for major overflows. A gross check suffices,
since if t has overflowed, it is off by a multiple of
TIME_T_MAX - TIME_T_MIN + 1. So ignore any component of
the difference that is bounded by a small value. */
double dyear = (double) year_requested + mon_years - tm.tm_year;
double dday = 366 * dyear + mday;
double dsec = 60 * (60 * (24 * dday + hour) + min) + sec_requested;
/* On Irix4.0.5 cc, dividing TIME_T_MIN by 3 does not produce
correct results, ie., it erroneously gives a positive value
of 715827882. Setting a variable first then doing math on it
seems to work. ([email protected]) */
const time_t time_t_max = TIME_T_MAX;
const time_t time_t_min = TIME_T_MIN;
if (time_t_max / 3 - time_t_min / 3 < (dsec < 0 ? - dsec : dsec))
return -1;
}
*tp = tm;
return t;
}
static time_t localtime_offset;
/* Convert *TP to a time_t value. */
time_t
mktime (tp)
struct tm *tp;
{
#ifdef _LIBC
/* POSIX.1 8.1.1 requires that whenever mktime() is called, the
time zone names contained in the external variable `tzname' shall
be set as if the tzset() function had been called. */
__tzset ();
#endif
return __mktime_internal (tp, my_mktime_localtime_r, &localtime_offset);
}
#ifdef weak_alias
weak_alias (mktime, timelocal)
#endif
#if DEBUG
static int
not_equal_tm (a, b)
struct tm *a;
struct tm *b;
{
return ((a->tm_sec ^ b->tm_sec)
| (a->tm_min ^ b->tm_min)
| (a->tm_hour ^ b->tm_hour)
| (a->tm_mday ^ b->tm_mday)
| (a->tm_mon ^ b->tm_mon)
| (a->tm_year ^ b->tm_year)
| (a->tm_mday ^ b->tm_mday)
| (a->tm_yday ^ b->tm_yday)
| (a->tm_isdst ^ b->tm_isdst));
}
static void
print_tm (tp)
struct tm *tp;
{
if (tp)
printf ("%04d-%02d-%02d %02d:%02d:%02d yday %03d wday %d isdst %d",
tp->tm_year + TM_YEAR_BASE, tp->tm_mon + 1, tp->tm_mday,
tp->tm_hour, tp->tm_min, tp->tm_sec,
tp->tm_yday, tp->tm_wday, tp->tm_isdst);
else
printf ("0");
}
static int
check_result (tk, tmk, tl, lt)
time_t tk;
struct tm tmk;
time_t tl;
struct tm *lt;
{
if (tk != tl || !lt || not_equal_tm (&tmk, lt))
{
printf ("mktime (");
print_tm (&tmk);
printf (")\nyields (");
print_tm (lt);
printf (") == %ld, should be %ld\n", (long) tl, (long) tk);
return 1;
}
return 0;
}
int
main (argc, argv)
int argc;
char **argv;
{
int status = 0;
struct tm tm, tmk, tml;
struct tm *lt;
time_t tk, tl;
char trailer;
if ((argc == 3 || argc == 4)
&& (sscanf (argv[1], "%d-%d-%d%c",
&tm.tm_year, &tm.tm_mon, &tm.tm_mday, &trailer)
== 3)
&& (sscanf (argv[2], "%d:%d:%d%c",
&tm.tm_hour, &tm.tm_min, &tm.tm_sec, &trailer)
== 3))
{
tm.tm_year -= TM_YEAR_BASE;
tm.tm_mon--;
tm.tm_isdst = argc == 3 ? -1 : atoi (argv[3]);
tmk = tm;
tl = mktime (&tmk);
lt = localtime (&tl);
if (lt)
{
tml = *lt;
lt = &tml;
}
printf ("mktime returns %ld == ", (long) tl);
print_tm (&tmk);
printf ("\n");
status = check_result (tl, tmk, tl, lt);
}
else if (argc == 4 || (argc == 5 && strcmp (argv[4], "-") == 0))
{
time_t from = atol (argv[1]);
time_t by = atol (argv[2]);
time_t to = atol (argv[3]);
if (argc == 4)
for (tl = from; tl <= to; tl += by)
{
lt = localtime (&tl);
if (lt)
{
tmk = tml = *lt;
tk = mktime (&tmk);
status |= check_result (tk, tmk, tl, tml);
}
else
{
printf ("localtime (%ld) yields 0\n", (long) tl);
status = 1;
}
}
else
for (tl = from; tl <= to; tl += by)
{
/* Null benchmark. */
lt = localtime (&tl);
if (lt)
{
tmk = tml = *lt;
tk = tl;
status |= check_result (tk, tmk, tl, tml);
}
else
{
printf ("localtime (%ld) yields 0\n", (long) tl);
status = 1;
}
}
}
else
printf ("Usage:\
\t%s YYYY-MM-DD HH:MM:SS [ISDST] # Test given time.\n\
\t%s FROM BY TO # Test values FROM, FROM+BY, ..., TO.\n\
\t%s FROM BY TO - # Do not test those values (for benchmark).\n",
argv[0], argv[0], argv[0]);
return status;
}
#endif /* DEBUG */
/*
Local Variables:
compile-command: "gcc -DDEBUG -DHAVE_LIMITS_H -DSTDC_HEADERS -Wall -W -O -g mktime.c -o mktime"
End:
*/
|
the_stack_data/1227526.c | // Example code for allocating a 3D int array on the heap, many other more efficient solutions are possible
#include <stdio.h>
#include <stdlib.h>
int ***malloc3dArray(int dim1, int dim2, int dim3)
{
int i, j, k;
int ***array = (int ***) malloc(dim1 * sizeof(int **));
for (i = 0; i < dim1; i++) {
array[i] = (int **) malloc(dim2 * sizeof(int *));
for (j = 0; j < dim2; j++) {
array[i][j] = (int *) malloc(dim3 * sizeof(int));
}
}
return array;
}
main()
{
int ***ipppArr;
int dim1 = 10, dim2 = 20, dim3 = 30;
int i, j, k;
ipppArr = malloc3dArray(dim1, dim2, dim3);
for (i = 0; i < dim1; ++i)
for (j = 0; j < dim2; ++j)
for (k = 0; k < dim3; ++k)
ipppArr[i][j][k] = i * j * k;
for (i = 0; i < dim1; ++i)
for (j = 0; j < dim2; ++j)
for (k = 0; k < dim3; ++k)
printf("[%d]",ipppArr[i][j][k]);
} |
the_stack_data/36075013.c | unsigned char oiram_1_fire_data[412] =
{
0x10,0x1b,0x07,0x04,0x18,0x18,0x18,0x18,0x05,0x05,0x07,0x18,0x18,0x15,0x01,0x01,0x01,0x18,0x04,0x04,0x08,0x18,0x05,0x15,0x15,0x15,0x01,0x01,0x18,0x04,0x03,0x0b,
0x18,0x05,0x15,0x15,0x15,0x18,0x18,0x18,0x18,0x18,0x18,0x02,0x02,0x0d,0x18,0x05,0x05,0x05,0x18,0x18,0x18,0x18,0x18,0x18,0x18,0x18,0x18,0x01,0x02,0x0c,0x18,0x05,
0x05,0x18,0x18,0x27,0x27,0x27,0x27,0x27,0x18,0x18,0x02,0x01,0x0c,0x18,0x18,0x18,0x18,0x18,0x27,0x0f,0x0f,0x18,0x0f,0x18,0x18,0x03,0x01,0x0d,0x18,0x0f,0x0f,0x18,
0x18,0x27,0x0f,0x0f,0x18,0x0f,0x18,0x18,0x18,0x02,0x01,0x0e,0x18,0x0f,0x0f,0x18,0x18,0x18,0x27,0x0f,0x0f,0x0f,0x0f,0x11,0x11,0x18,0x01,0x01,0x0e,0x18,0x27,0x0f,
0x27,0x18,0x27,0x0f,0x18,0x27,0x27,0x0f,0x0f,0x0f,0x18,0x01,0x02,0x0e,0x18,0x27,0x27,0x27,0x0f,0x18,0x18,0x18,0x18,0x27,0x27,0x18,0x18,0x18,0x03,0x0b,0x18,0x18,
0x27,0x27,0x0f,0x0f,0x18,0x18,0x18,0x18,0x18,0x02,0x02,0x0a,0x18,0x18,0x13,0x18,0x27,0x27,0x27,0x27,0x27,0x18,0x04,0x01,0x0a,0x18,0x05,0x15,0x18,0x13,0x18,0x18,
0x18,0x18,0x18,0x05,0x01,0x0b,0x18,0x15,0x15,0x01,0x18,0x18,0x18,0x05,0x01,0x18,0x18,0x01,0x01,0x18,0x02,0x00,0x0f,0x18,0x05,0x15,0x01,0x18,0x01,0x01,0x01,0x18,
0x05,0x01,0x18,0x18,0x01,0x18,0x01,0x00,0x0f,0x18,0x05,0x15,0x18,0x11,0x01,0x01,0x01,0x01,0x18,0x05,0x15,0x18,0x11,0x18,0x01,0x00,0x0e,0x18,0x05,0x05,0x18,0x11,
0x11,0x01,0x01,0x01,0x18,0x18,0x18,0x18,0x18,0x02,0x00,0x0e,0x18,0x18,0x05,0x05,0x18,0x11,0x11,0x11,0x18,0x01,0x1f,0x1f,0x01,0x18,0x02,0x01,0x0d,0x18,0x18,0x18,
0x0a,0x18,0x18,0x18,0x01,0x01,0x1f,0x1f,0x01,0x18,0x02,0x01,0x0d,0x18,0x0a,0x0a,0x0a,0x13,0x13,0x1f,0x13,0x1f,0x1f,0x1f,0x13,0x18,0x02,0x02,0x0d,0x18,0x0a,0x13,
0x13,0x1f,0x13,0x0a,0x13,0x13,0x13,0x13,0x18,0x18,0x01,0x01,0x01,0x18,0x01,0x0d,0x18,0x0a,0x13,0x13,0x0a,0x18,0x0a,0x0a,0x13,0x18,0x22,0x19,0x18,0x01,0x01,0x18,
0x01,0x05,0x18,0x0a,0x0a,0x0a,0x18,0x01,0x07,0x18,0x0a,0x18,0x22,0x19,0x28,0x18,0x01,0x01,0x18,0x01,0x04,0x19,0x18,0x18,0x18,0x03,0x05,0x18,0x19,0x19,0x28,0x18,
0x01,0x02,0x06,0x18,0x28,0x19,0x19,0x28,0x18,0x02,0x04,0x18,0x28,0x28,0x18,0x02,0x03,0x05,0x18,0x18,0x18,0x18,0x18,0x03,0x02,0x18,0x18,0x03
};
|
the_stack_data/111758.c | #define MALLOC_UNIT 5000
void strobogrammaticHelper(char ***ret, int *retCtr, int *memUnit, char *tmp, int cur, int n, char isOdd)
{
char *nums1 = "01689";
char *nums2 = "01986";
if (cur == n/2)
{
if (isOdd)
{
int midIdx = n/2;
(*ret)[*retCtr] = calloc(n+1, sizeof(char));
(*ret)[*retCtr+1] = calloc(n+1, sizeof(char));
(*ret)[*retCtr+2] = calloc(n+1, sizeof(char));
memcpy((*ret)[*retCtr], tmp, sizeof(char)*n);
memcpy((*ret)[*retCtr+1], tmp, sizeof(char)*n);
memcpy((*ret)[*retCtr+2], tmp, sizeof(char)*n);
(*ret)[*retCtr][midIdx] = '0';
(*ret)[*retCtr+1][midIdx] = '1';
(*ret)[*retCtr+2][midIdx] = '8';
*retCtr += 3;
*memUnit += 3;
} else
{
(*ret)[*retCtr] = calloc(n+1, sizeof(char));
memcpy((*ret)[*retCtr], tmp, sizeof(char)*n);
*retCtr += 1;
*memUnit += 1;
}
if (*memUnit + 3 >= MALLOC_UNIT)
{
*ret = realloc(*ret, sizeof(char *)*(*retCtr+MALLOC_UNIT));
*memUnit = 0;
}
return ;
}
for (int i = 0; i < 5; i++)
{
// string can not start from '0'
if (cur == 0 && i == 0)
{
continue;
}
tmp[cur] = nums1[i];
tmp[n-cur-1] = nums2[i];
strobogrammaticHelper(ret, retCtr, memUnit, tmp, cur+1, n, isOdd);
}
}
/**
* Note: The returned array must be malloced, assume caller calls free().
*/
char ** findStrobogrammatic(int n, int* returnSize)
{
int **ret = malloc(sizeof(char*)*MALLOC_UNIT);
*returnSize = 0;
char *tmp = calloc(n+1, sizeof(char));
char isOdd = ((n & 0x1) == 0x1 ? 1 : 0);
int memUnit = 0;
strobogrammaticHelper(&ret, returnSize, &memUnit, tmp, 0, n, isOdd);
free(tmp);
return ret;
}
|
the_stack_data/218891937.c | /*
* C program to test the memexec script.
* The C program writes the command line arguments to stdout.
* One text line will be written to stderr.
* The exit code of the program is number of arguments - 2,
* so the call "echo_argument a" will return 0. (The program
* name is the first command line argument.)
*
* The C program can be compiled to a binary program
* with the command:
* gcc echo_arguments.c -o echo_arguments
*
* Then the binary program echo_arguments can be stored
* on a web server to load it with the memexec script.
*/
#include <stdio.h>
int main ( int argc, char** argv )
{
int i;
puts( "The echo_arguments test program" );
fputs( "This is a output line to stderr\n", stderr );
for( i = 0; i < argc; ++i)
printf( "argument %2d is '%s'\n", i, argv[i] );
printf( "exit code of the test program is %d\n", argc-2 );
return argc-2;
}
|
the_stack_data/247017498.c | #include<stdio.h>
#include<stdlib.h>
//describe: Verificador de maior numero.
//autor: GumblarZ < [email protected] >
//version: 0.1
//license: MIT License
int main(int argc, char const *argv[])
{
int lance[] = {8,6,5,5,31,100,800,4,31,4,6};
int maior = 0;
for (int i = 0; i < 11; ++i)
{
if (lance[i] > maior)
{
maior = lance[i];
}
}
printf("maior numero e %d",maior );
return 0;
} |
the_stack_data/248579796.c | // printf関数、及びscanf関数を使用するために必要
#include <stdio.h>
// int型を返すmain関数の宣言
int main() {
// 変数の宣言
// 配列の宣言は name[size] で行う。添字は0〜(size-1)まで占有している。
int i;
int a[11];
float tmp;
// 入力
for (i = 0; i <= 10; i++) {
// scanf関数。標準入力から入力を取得する。
// scanfには変数のアドレスを渡すため、& を語頭に付与する。
// scanf(フォーマット指定子, 変数)
scanf("%d", &a[i]);
}
// 計算
tmp = a[10];
for (i = 10; i >= 1; i--) {
tmp = a[i-1] + (1 / tmp);
}
// printf関数。フォーマット指定子に従って標準出力に出力する。
// printf(フォーマット指定子, 変数)
printf("%f\n", tmp);
// main関数の正常終了
return 0;
}
|
the_stack_data/18161.c | //Credits: serenity os
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#ifdef DEBUG
void
__assertion_failed ( const char* msg,
const char* file,
unsigned line,
const char* func )
{
printf ("USERSPACE(%d) ASSERTION FAILED: ", getpid() );
printf (" %s \n %s:%u in %s \n", msg, file, line, func );
stdlib_die ( "__assertion_failed: *hang");
// Suspended.
// fprintf (stderr, "ASSERTION FAILED: %s\n%s:%u in %s\n", msg, file, line, func);
//abort ();
//for (;;)
}
#endif
/*
static int
fmtassert(char *buf, size_t len, const char *file, int line,
const char *function, const char *failedexpr);
static int
fmtassert(char *buf, size_t len, const char *file, int line,
const char *function, const char *failedexpr)
{
return snprintf_ss(buf, len,
"assertion \"%s\" failed: file \"%s\", line %d%s%s%s\n",
failedexpr, file, line,
function ? ", function \"" : "",
function ? function : "",
function ? "\"" : "");
}
*/
/*
void
__assert13(const char *file, int line, const char *function,
const char *failedexpr);
void
__assert13(const char *file, int line, const char *function,
const char *failedexpr)
{
char buf[1024];
int l = fmtassert(buf, sizeof(buf), file, line, function, failedexpr);
if (l < 0)
abort();
(void)write(STDERR_FILENO, buf, (size_t)l);
abort();
//NOTREACHED
}
*/
/*
void
__assert(const char *file, int line, const char *failedexpr);
void
__assert(const char *file, int line, const char *failedexpr)
{
__assert13(file, line, NULL, failedexpr);
//NOTREACHED
}
*/
enum {
DIAGASSERT_ABORT = 1<<0,
DIAGASSERT_STDERR = 1<<1,
DIAGASSERT_SYSLOG = 1<<2
};
static int diagassert_flags = -1;
/*
void
__diagassert13(const char *file, int line, const char *function,
const char *failedexpr);
void
__diagassert13(const char *file, int line, const char *function,
const char *failedexpr)
{
//#todo
}
*/
/*
void
__diagassert(const char *file, int line, const char *failedexpr);
void
__diagassert(const char *file, int line, const char *failedexpr)
{
__diagassert13(file, line, NULL, failedexpr);
}
*/
|
the_stack_data/137396.c | /*
* Copyright (c) 1988 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. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* This product includes software developed by the University of
* California, Berkeley and its contributors.
* 4. 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.
*/
#ifndef lint
char copyright[] =
"@(#) Copyright (c) 1988 Regents of the University of California.\n\
All rights reserved.\n";
#endif /* not lint */
#ifndef lint
//static char sccsid[] = "@(#)sleep.c 5.5 (Berkeley) 4/8/91";
#endif /* not lint */
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
int
main(argc, argv)
int argc;
char **argv;
{
int secs;
if (argc != 2) {
(void)fprintf(stderr, "usage: sleep time\n");
exit(1);
}
if ((secs = atoi(argv[1])) > 0)
(void)sleep(secs);
exit(0);
}
|
the_stack_data/234519285.c | #include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
int main() {
int n, d;
scanf("%d %d", &n, &d);
int num[201];
memset(num, 0, sizeof(int) * 201);
int type;
int half;
if (0 == d % 2) {
// two nums
type = 2;
half = d / 2 - 1;
}
else {
// only one num
type = 1;
half = d / 2;
}
int cnt = 0;
int * e = malloc(sizeof(int) * n);
for (size_t i = 0; i < n; i ++) {
scanf("%d", &e[i]);
if (i >= d) {
int remain = half;
int j = 0;
int median = 0;
while (remain > 0 && j <= 200) {
if (num[j]) {
remain -= num[j];
}
j ++;
}
if (0 == remain) {
if (1 == type) {
for (j; j <= 200; j++) {
if (num[j]) {
median = j * 2;
break;
}
}
}
else {
while (remain > -2 && j <= 200) {
if (num[j]) {
remain -= num[j];
if (-1 == remain) {
median += j;
}
else {
if (0 == median) {
median = 2 * j;
}
else {
median += j;
}
break;
}
}
j ++;
}
}
}
else if (-1 == remain) {
if (1 == type) {
median = 2 * (j - 1);
}
else {
median = j - 1;
for (j; j <= 200; j++) {
if (num[j]) {
median += j;
break;
}
}
}
}
else {
median = 2 * (j - 1);
}
if (e[i] >= median) {
cnt ++;
}
num[e[i - d]] --;
}
num[e[i]] ++;
}
printf("%d\n", cnt);
free(e);
return 0;
}
|
the_stack_data/190767686.c | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* aff_first_param.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: angavrel <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2016/12/03 15:00:02 by angavrel #+# #+# */
/* Updated: 2017/07/14 12:25:39 by fwuensch ### ########.fr */
/* */
/* ************************************************************************** */
#include <unistd.h>
int main(int ac, char **av)
{
if (ac > 1)
while (*av[1])
write(1, av[1]++, 1);
write(1, "\n", 1);
return (0);
}
|
the_stack_data/129152.c | #include <stdlib.h>
#include <stdint.h>
void swap_direct(uint32_t *x, uint32_t *y) {
uint32_t tmp;
tmp = *x;
*x = *y;
*y = tmp;
}
|
the_stack_data/148577585.c | #include <stdio.h>
#define ROWS 3
#define COLS 5
void input_array(int rows, double arr[][COLS]);
double col_average(int cols, const double arr[]);
double array_average(int rows, const double arr[][COLS]);
double array_max_number(int rows, const double arr[][COLS]);
void show_result(int rows, const double arr[][COLS]);
int main(void)
{
double array[ROWS][COLS];
input_array(ROWS, array);
show_result(ROWS, array);
printf("\n");
return 0;
}
void input_array(int rows, double arr[][COLS])
{
printf("Enter the array number.\n");
for (int i = 0; i < rows; i++)
{
printf("Enter five double number seprate by enter:\n");
for (int j = 0; j < COLS; j++)
{
scanf("%lf", &arr[i][j]);
}
}
return;
}
double col_average(int cols, const double arr[])
{
double sum = 0;
for (int i = 0; i < cols; i++)
{
sum += arr[i];
}
return sum/cols;
}
double array_average(int rows, const double arr[][COLS])
{
double sum = 0;
for (int i = 0; i < rows; i++)
{
sum += col_average(COLS, arr[i]);
}
return sum / rows;
}
double array_max_number(int rows, const double arr[][COLS])
{
double max = arr[0][0];
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < COLS; j++)
{
if (max < arr[i][j])
{
max = arr[i][j];
}
}
}
return max;
}
void show_result(int rows, const double arr[][COLS])
{
printf("Now, Let\'s check the array!\n");
printf("The array you input is:\n");
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < COLS; j++)
{
printf("%5g", arr[i][j]);
}
printf("\n");
}
printf("The Average of every column is:\n");
for (int i = 0; i < rows; i++)
{
printf("The %d column's average is %g.\n", i, col_average(COLS, arr[i]));
}
printf("The array's data average is %g\n", array_average(ROWS, arr));
printf("The max datum in the array is %g", array_max_number(ROWS, arr));
return;
} |
the_stack_data/140898.c | /* Taxonomy Classification: 0010000000000000000200 */
/*
* WRITE/READ 0 write
* WHICH BOUND 0 upper
* DATA TYPE 1 int
* MEMORY LOCATION 0 stack
* SCOPE 0 same
* CONTAINER 0 no
* POINTER 0 no
* INDEX COMPLEXITY 0 constant
* ADDRESS COMPLEXITY 0 constant
* LENGTH COMPLEXITY 0 N/A
* ADDRESS ALIAS 0 none
* INDEX ALIAS 0 none
* LOCAL CONTROL FLOW 0 none
* SECONDARY CONTROL FLOW 0 none
* LOOP STRUCTURE 0 no
* LOOP COMPLEXITY 0 N/A
* ASYNCHRONY 0 no
* TAINT 0 no
* RUNTIME ENV. DEPENDENCE 0 no
* MAGNITUDE 2 8 bytes
* CONTINUOUS/DISCRETE 0 discrete
* SIGNEDNESS 0 no
*/
/*
Copyright 2004 M.I.T.
Permission is hereby granted, without written agreement or royalty fee, to use,
copy, modify, and distribute this software and its documentation for any
purpose, provided that the above copyright notice and the following three
paragraphs appear in all copies of this software.
IN NO EVENT SHALL M.I.T. BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT, SPECIAL,
INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OF THIS SOFTWARE
AND ITS DOCUMENTATION, EVEN IF M.I.T. HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMANGE.
M.I.T. SPECIFICALLY DISCLAIMS ANY WARRANTIES INCLUDING, BUT NOT LIMITED TO
THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE,
AND NON-INFRINGEMENT.
THE SOFTWARE IS PROVIDED ON AN "AS-IS" BASIS AND M.I.T. HAS NO OBLIGATION TO
PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
*/
int main(int argc, char *argv[])
{
int buf[10];
/* BAD */
buf[17] = 55;
return 0;
}
|
the_stack_data/7951396.c | extern const unsigned char GREENWOODVersionString[];
extern const double GREENWOODVersionNumber;
const unsigned char GREENWOODVersionString[] __attribute__ ((used)) = "@(#)PROGRAM:GREENWOOD PROJECT:GREENWOOD-1" "\n";
const double GREENWOODVersionNumber __attribute__ ((used)) = (double)1.;
|
the_stack_data/934273.c | #include <stdio.h>
#include <stdint.h>
uint8_t triwave8(uint8_t in) {
if( in & 0x80) {
in = 255 - in;
}
uint8_t out = (uint8_t) (in << 1);
return out;
}
int main () {
for ( uint16_t i = 0; i < 256; i++ ) {
printf("%d, %d\n", i, triwave8((uint8_t)(i)));
}
return 0;
}
|
the_stack_data/179829679.c | // Check that useless until loops are removed
// Check that effects are taken into account when available
// See also until06.c
#include <stdio.h>
void foo(int *i)
{
*i = 0;
}
void bar(int *i)
{
;
}
void until05()
{
int old, new;
do {
old = new;
foo(&new);
} while(old!=new);
do {
old = new;
bar(&new);
} while(old!=new);
printf("%d", old);
}
|
the_stack_data/11075277.c | /*
DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
Copyright 2009 Sun Microsystems, Inc. All rights reserved.
The contents of this file are subject to the terms of the BSD License("BSD")(the "License").
You can obtain a copy of the License at: http://www.opensparc.net/pubs/t1/licenses/BSD+_License.txt
The BSD License
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistribution of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistribution 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 Sun Microsystems, Inc. or the names of
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
This software is provided "AS IS," without a warranty of any kind. ALL
EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING ANY
IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR
NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MICROSYSTEMS, INC. ("SUN") AND
ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A
RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS DERIVATIVES.
IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST REVENUE, PROFIT
OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL, INCIDENTAL OR
PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY OF LIABILITY,
ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE, EVEN IF SUN HAS
BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
You acknowledge that this software is not designed, licensed or intended for
use in the design, construction, operation or maintenance of any nuclear facility.
*/
#include <stdio.h>
#include <stdlib.h>
#ifdef _OPENMP
#include <omp.h>
#define TRUE 1
#define FALSE 0
#else
#define omp_get_thread_num() 0
#define omp_get_num_threads() 1
#endif
int main()
{
int n = 9;
int i, a, b[n];
#ifdef _OPENMP
(void) omp_set_dynamic(FALSE);
if (omp_get_dynamic()) {printf("Warning: dynamic adjustment of threads has been set\n");}
(void) omp_set_num_threads(4);
#endif
for (i=0; i<n; i++)
b[i] = -1;
#pragma omp parallel shared(a,b) private(i)
{
#pragma omp master
{
a = 10;
printf("Master construct is executed by thread %d\n",
omp_get_thread_num());
}
#pragma omp barrier
#pragma omp for
for (i=0; i<n; i++)
b[i] = a;
} /*-- End of parallel region --*/
printf("After the parallel region:\n");
for (i=0; i<n; i++)
printf("b[%d] = %d\n",i,b[i]);
return(0);
}
|
the_stack_data/37636961.c | #include <stdio.h>
#include <stdint.h>
static inline uint64_t fillBits(int begin, int last) {
if (last == 63)
return ~((1ull << begin) - 1ull);
if (begin == 0)
return (1ull << (last + 1ull)) - 1ull;
return (~((1ull << begin) - 1ull)) & ((1ull << (last + 1ull)) - 1ull);
}
void printit(int a, int b) {
printf("[%d,%d] = %08lx\n", a, b, fillBits(a, b));
}
int main() {
printit(0, 63);
printit(1, 63);
printit(2, 63);
printit(3, 63);
printit(4, 63);
printit(5, 63);
printit(6, 63);
printit(7, 63);
printit(8, 63);
printit(9, 63);
printit(10, 63);
printit(7, 62);
printit(8, 61);
printit(9, 60);
printit(10, 59);
printit(10, 58);
printit(10, 57);
printit(10, 56);
printit(10, 55);
printit(10, 54);
printit(4, 4);
}
|
the_stack_data/302799.c | #include <stdlib.h>
#include <string.h>
#include <stdio.h>
/*
* main heap:
*
* ptr[1]
* ptr[2]
* ptr[3]
* top chunk
*
*
* */
void malloc_all();
void free1();
void free2();
void free3();
void free4();
void free5();
void free6();
#define NBSIZE 128 //NormnalBinSize
#define FBSIZE 64 //FastBinSize
#define CHUNKSIZE NBSIZE
void(*free_ptr[])() = {NULL,free1,free2,free3,free4,free5,free6};
int i;
char *ptr[10];
int main(int argc, char *argv[])
{
malloc_all();
i = (argc <= 1) ? 1 : (atoi(argv[1]) % 7 ? atoi(argv[1]) % 7 : 1 );
free_ptr[i]();
}
void malloc_all()
{
ptr[1] = (char*)malloc(CHUNKSIZE);
ptr[2] = (char*)malloc(CHUNKSIZE);
ptr[3] = (char*)malloc(CHUNKSIZE);
ptr[4] = (char*)malloc(256*1024); // will mmap
for (i=1 ; i<10;i++) {
if(ptr[i]) {
printf("ptr[%02d] = %p\n",i,ptr[i]);
}
}
}
void free1()
{
printf("call free1: ptr1 -> ptr2 -> ptr3\n");
getchar();
free(ptr[1]);
getchar();
free(ptr[2]);
getchar();
free(ptr[3]);
getchar();
}
void free2()
{
printf("call free2: ptr1 -> ptr3 -> ptr2\n");
getchar();
free(ptr[1]);
getchar();
free(ptr[3]);
getchar();
free(ptr[2]);
getchar();
}
void free3()
{
printf("call free3: ptr2 -> ptr1 -> ptr3 \n");
getchar();
free(ptr[2]);
getchar();
free(ptr[1]);
getchar();
free(ptr[3]);
getchar();
}
void free4()
{
printf("call free4: ptr2 -> ptr3 -> ptr1\n");
getchar();
free(ptr[2]);
getchar();
free(ptr[3]);
getchar();
free(ptr[1]);
getchar();
}
void free5()
{
printf("call free5: ptr3 -> ptr1 -> ptr2\n");
getchar();
free(ptr[3]);
getchar();
free(ptr[1]);
getchar();
free(ptr[2]);
getchar();
}
void free6()
{
printf("call free6: ptr3 -> ptr2 -> ptr1\n");
getchar();
free(ptr[3]);
getchar();
free(ptr[2]);
getchar();
free(ptr[1]);
getchar();
}
|
the_stack_data/15762718.c | /**
* This file has no copyright assigned and is placed in the Public Domain.
* This file is part of the mingw-w64 runtime package.
* No warranty is given; refer to the file DISCLAIMER.PD within this package.
*/
#include <math.h>
long double
fminl (long double _x, long double _y)
{
return ((islessequal(_x, _y) || __isnanl (_y)) ? _x : _y );
}
|
the_stack_data/911866.c | /* { dg-do run } */
/* { dg-require-weak "" } */
/* { dg-additional-options "--param vect-epilogues-nomask=1 -mavx2" { target avx2_runtime } } */
#define SIZE 1023
#define ALIGN 64
extern int posix_memalign(void **memptr, __SIZE_TYPE__ alignment, __SIZE_TYPE__ size) __attribute__((weak));
extern void free (void *);
void __attribute__((noinline))
test_citer (int * __restrict__ a,
int * __restrict__ b,
int * __restrict__ c)
{
int i;
a = (int *)__builtin_assume_aligned (a, ALIGN);
b = (int *)__builtin_assume_aligned (b, ALIGN);
c = (int *)__builtin_assume_aligned (c, ALIGN);
for (i = 0; i < SIZE; i++)
c[i] = a[i] + b[i];
}
void __attribute__((noinline))
test_viter (int * __restrict__ a,
int * __restrict__ b,
int * __restrict__ c,
int size)
{
int i;
a = (int *)__builtin_assume_aligned (a, ALIGN);
b = (int *)__builtin_assume_aligned (b, ALIGN);
c = (int *)__builtin_assume_aligned (c, ALIGN);
for (i = 0; i < size; i++)
c[i] = a[i] + b[i];
}
void __attribute__((noinline))
init_data (int * __restrict__ a,
int * __restrict__ b,
int * __restrict__ c,
int size)
{
for (int i = 0; i < size; i++)
{
a[i] = i;
b[i] = -i;
c[i] = 0;
asm volatile("": : :"memory");
}
a[size] = b[size] = c[size] = size;
}
void __attribute__((noinline))
run_test ()
{
int *a;
int *b;
int *c;
int i;
if (posix_memalign ((void **)&a, ALIGN, (SIZE + 1) * sizeof (int)) != 0)
return;
if (posix_memalign ((void **)&b, ALIGN, (SIZE + 1) * sizeof (int)) != 0)
return;
if (posix_memalign ((void **)&c, ALIGN, (SIZE + 1) * sizeof (int)) != 0)
return;
init_data (a, b, c, SIZE);
test_citer (a, b, c);
for (i = 0; i < SIZE; i++)
if (c[i] != a[i] + b[i])
__builtin_abort ();
if (a[SIZE] != SIZE || b[SIZE] != SIZE || c[SIZE] != SIZE)
__builtin_abort ();
init_data (a, b, c, SIZE);
test_viter (a, b, c, SIZE);
for (i = 0; i < SIZE; i++)
if (c[i] != a[i] + b[i])
__builtin_abort ();
if (a[SIZE] != SIZE || b[SIZE] != SIZE || c[SIZE] != SIZE)
__builtin_abort ();
free (a);
free (b);
free (c);
}
int
main (int argc, const char **argv)
{
if (!posix_memalign)
return 0;
run_test ();
return 0;
}
/* { dg-final { scan-tree-dump-times "LOOP VECTORIZED" 2 "vect" { target avx2_runtime } } } */
/* { dg-final { scan-tree-dump-times "LOOP EPILOGUE VECTORIZED \\(VS=16\\)" 2 "vect" { target avx2_runtime } } } */
|
the_stack_data/164105.c | #include <stdio.h>
#define toString(X) toString2(X)
#define toString2(X) #X
int main(void)
{
printf("FILE: " toString(FILE) "\n");
return 0;
}
|
the_stack_data/143643.c | #include <stdio.h>
int find_max(int, int, int);
int main(){
int newmax;
newmax = find_max(30, 40, 15);
printf("%d",newmax);
return 0;
}
int newmax(int num1, int num2, int num3){
int max;
max = num1;
if(num2> max)
max = num2;
if(num3>max)
max = num3;
return max;
} |
the_stack_data/15763490.c | int isPrime(int n) {
// returns 0 if not prime, 1 if prime
if (n<2) return 0; // first prime number is 2
if (n==2) return 1; // ensure 2 is identified as a prime
if ((n % 2)==0) return 0; // all even numbers above 2 are not prime
int i;
for (i=3; i*i < n; i++) { // test divisibility up to sqrt(n)
if ((n % i) == 0) {
return 0;
}
}
return 1;
}
|
the_stack_data/225142175.c | // RUN: %clang @%S/Inputs/cc1-response.txt -fsyntax-only -disable-llvm-passes
int main() {}
|
the_stack_data/890717.c | #include <stdio.h>
char relation(int first, int second)
{
if (first > second)
{
return '>';
} else if (first < second)
{
return '<';
} else
{
return '=';
}
}
void test(int first, int second, char expected)
{
char actual = relation(first, second);
printf("%d vs %d. Expected: %c. Actual: %c\n", first, second, expected, actual);
}
int main()
{
// test(10, 20, '<');
// test(20, 10, '>');
// test(10, 10, '=');
int numCases, first, second;
scanf("%d", &numCases);
char results[numCases], result;
for (int i = 0; i < numCases; i++)
{
scanf("%d %d", &first, &second);
result = relation(first, second);
results[i] = result;
}
for (int j = 0; j < numCases ; j++)
{
result = results[j];
printf("%c\n", result);
}
return 0;
} |
the_stack_data/72670.c | #include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
int main(void)
{
pid_t child1, child2;
int pid, status;
if ((child1 = fork()) == 0)
execlp("date", "date", (char *)0);
if ((child2 = fork()) == 0)
execlp("who", "who", (char *)0);
printf("parent: waiting for children\n");
while ((pid = wait(&status)) != -1)
{
if (child1 == pid)
printf("parent: first child: %d\n", (status >> 8));
else if (child2 == pid)
printf("parent: second child: %d\n", (status >> 8));
}
printf("parent: all children terminated\n");
exit(0);
}
|
the_stack_data/218893464.c | void confuse() {}
|
the_stack_data/55136.c | /***********************************************************************
*
* program readST2.c
*
* Program for NCEP stage 4 files in binary
*
* This program read data from specific file and print them out to
* file outIowa.dat in array 174 x 134.
* M.K 5/4/03
***********************************************************************/
#include<stdio.h>
#define nc 987601
float farray[nc]={0.0}, harray[nc]={0.0};
main(int argc, char *argv[])
{
int x,y,j,i,l,m,k,n,cnt;
FILE *fp1, *fp2, *fp3;
/******************/
/*open binary file*/
/******************/
fp1=fopen(argv[1],"rb");
/********************/
/*read data to array*/
/********************/
cnt=fread(farray, sizeof(float), nc, fp1);
/* printf("read %d characters\n",cnt);*/
/****************************************/
/* Print to file data for Iowa */
/* 134 lines (each line has 173 values) */
/****************************************/
/*Array is flipped, so print it to file from the last line*/
/*printf("Printing data to file outIowa.dat...\n");*/
i=0;
j=0;
k=0;
fp3=fopen("outIowa.dat","w");
j=502756; /*Jump to the first character in last line for Iowa*/
for (k=0; k<134; k++) /*Iowa area consists 134 lines*/
{
for (i=0; i<173; i++) /*Each line for Iowa consists 173 characters*/
{
fprintf(fp3, "%f ", farray[j+i]);
}
fprintf(fp3,"\n");
j=j+1121; /*Jump to the begining of previous line*/
}
/*************/
/*close files*/
/*************/
fclose(fp1);
fclose(fp3);
/*fclose(fp2);*/
return 0;
}
|
the_stack_data/694204.c | #ifdef _WIN32
#include <windows.h>
#elif __linux
#include <unistd.h>
#endif
|
the_stack_data/176705548.c | #include <stdio.h>
#include <string.h>
struct student{
char name[20]; /* student name */
double testScore; /* test score */
double examScore; /* exam score */
double total; /* total = (testScore+examScore)/2 */
};
double average();
int main()
{
printf("average(): %.2f\n", average());
return 0;
}
/* creates a database of maximum 50 students using an array of structures.
For each student, it takes in the test score, exam score and compute the total score.
End when the student name is "END", returning the average score of all students */
double average()
{
/* Write your program code here */
int count = 0;
double students_total = 0; // total score of all students
char temp; // buffer
struct student stud[50];
while (count < 50){
printf("Enter student name: \n");
scanf("%[^\n]", &stud[count].name);
if (strcmp(stud[count].name, "END")==0){
break;
} else {
printf("Enter test score: \n");
scanf("%lf", &stud[count].testScore);
printf("Enter exam score: \n");
scanf("%lf", &stud[count].examScore);
// calculate total score of the student
stud[count].total = (stud[count].examScore + stud[count].testScore) / 2;
students_total += stud[count].total; // add to total score
printf("Student %s total = %.2f\n", stud[count].name, stud[count].total);
}
count++;
scanf("%c", &temp); // temp statement to clear buffer
}
if (count == 0){
return 0;
} else {
return students_total / count;
}
}
|
the_stack_data/572861.c | /*
* hugepage-mmap:
*
* Example of using huge page memory in a user application using the mmap
* system call. Before running this application, make sure that the
* administrator has mounted the hugetlbfs filesystem (on some directory
* like /mnt) using the command mount -t hugetlbfs nodev /mnt. In this
* example, the app is requesting memory of size 256MB that is backed by
* huge pages.
*
* For the ia64 architecture, the Linux kernel reserves Region number 4 for
* huge pages. That means that if one requires a fixed address, a huge page
* aligned address starting with 0x800000... will be required. If a fixed
* address is not required, the kernel will select an address in the proper
* range.
* Other architectures, such as ppc64, i386 or x86_64 are not so constrained.
*/
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/mman.h>
#include <fcntl.h>
#define FILE_NAME "huge/hugepagefile"
#define LENGTH (256UL*1024*1024)
#define PROTECTION (PROT_READ | PROT_WRITE)
/* Only ia64 requires this */
#ifdef __ia64__
#define ADDR (void *)(0x8000000000000000UL)
#define FLAGS (MAP_SHARED | MAP_FIXED)
#else
#define ADDR (void *)(0x0UL)
#define FLAGS (MAP_SHARED)
#endif
static void check_bytes(char *addr)
{
printf("First hex is %x\n", *((unsigned int *)addr));
}
static void write_bytes(char *addr)
{
unsigned long i;
for (i = 0; i < LENGTH; i++)
*(addr + i) = (char)i;
}
static int read_bytes(char *addr)
{
unsigned long i;
check_bytes(addr);
for (i = 0; i < LENGTH; i++)
if (*(addr + i) != (char)i) {
printf("Mismatch at %lu\n", i);
return 1;
}
return 0;
}
int main(void)
{
void *addr;
int fd, ret;
fd = open(FILE_NAME, O_CREAT | O_RDWR, 0755);
if (fd < 0) {
perror("Open failed");
exit(1);
}
addr = mmap(ADDR, LENGTH, PROTECTION, FLAGS, fd, 0);
if (addr == MAP_FAILED) {
perror("mmap");
unlink(FILE_NAME);
exit(1);
}
printf("Returned address is %p\n", addr);
check_bytes(addr);
write_bytes(addr);
ret = read_bytes(addr);
munmap(addr, LENGTH);
close(fd);
unlink(FILE_NAME);
return ret;
}
|
the_stack_data/112983.c | #include<stdio.h>
void upset(int n)
{
int flag = 0;
while(n)
{
if(n%10 || flag)
{
printf("%d", n%10);
flag = 1;
}
n = n/10;
}
}
int main()
{
int n;
scanf("%d", &n);
if(n == 0)
printf("0");
else
if(n < 0)
{
printf("-");
upset(-1 * n);
}
else
upset(n);
return 0;
} |
the_stack_data/92336.c | #include<stdio.h>
#define MAX 1000
int escreve_vetor(int n, int v[MAX]);
int main(void){
int i,vetor[MAX],n,m,v[MAX];
scanf("%d", &n);
for(i=0;i<n;i++)
{
scanf("%d", &m);
vetor[i] = escreve_vetor(m,v);
}
for(i =0;i<n;i++)
{
printf("%d\n", vetor[i]);
}
return 0;
}
int escreve_vetor(int n, int v[MAX])
{
int aux,i,j,cont=0;
for ( i = 0; i < n; i++)
{
scanf("%d", &v[i]);
}
for( i=0;i<n;i++)
{
for( j=i+1; j<n;j++)
{
if(v[i] <= v[j])
{
aux= v[i];
v[i] = v[j];
v[j] = aux;
cont =cont+2;
}
}
}
return cont;
}
|
the_stack_data/12637606.c | /**
******************************************************************************
* @file stm32l4xx_ll_rcc.c
* @author MCD Application Team
* @brief RCC 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 "stm32l4xx_ll_rcc.h"
#ifdef USE_FULL_ASSERT
#include "stm32_assert.h"
#else
#define assert_param(expr) ((void)0U)
#endif
/** @addtogroup STM32L4xx_LL_Driver
* @{
*/
#if defined(RCC)
/** @addtogroup RCC_LL
* @{
*/
/* Private types -------------------------------------------------------------*/
/* Private variables ---------------------------------------------------------*/
/* Private constants ---------------------------------------------------------*/
/* Private macros ------------------------------------------------------------*/
/** @addtogroup RCC_LL_Private_Macros
* @{
*/
#if defined(RCC_CCIPR_USART3SEL)
#define IS_LL_RCC_USART_CLKSOURCE(__VALUE__) (((__VALUE__) == LL_RCC_USART1_CLKSOURCE) \
|| ((__VALUE__) == LL_RCC_USART2_CLKSOURCE) \
|| ((__VALUE__) == LL_RCC_USART3_CLKSOURCE))
#else
#define IS_LL_RCC_USART_CLKSOURCE(__VALUE__) (((__VALUE__) == LL_RCC_USART1_CLKSOURCE) \
|| ((__VALUE__) == LL_RCC_USART2_CLKSOURCE))
#endif /* RCC_CCIPR_USART3SEL */
#if defined(RCC_CCIPR_UART4SEL) && defined(RCC_CCIPR_UART5SEL)
#define IS_LL_RCC_UART_CLKSOURCE(__VALUE__) (((__VALUE__) == LL_RCC_UART4_CLKSOURCE) \
|| ((__VALUE__) == LL_RCC_UART5_CLKSOURCE))
#elif defined(RCC_CCIPR_UART4SEL)
#define IS_LL_RCC_UART_CLKSOURCE(__VALUE__) ((__VALUE__) == LL_RCC_UART4_CLKSOURCE)
#elif defined(RCC_CCIPR_UART5SEL)
#define IS_LL_RCC_UART_CLKSOURCE(__VALUE__) ((__VALUE__) == LL_RCC_UART5_CLKSOURCE)
#endif /* RCC_CCIPR_UART4SEL && RCC_CCIPR_UART5SEL*/
#define IS_LL_RCC_LPUART_CLKSOURCE(__VALUE__) (((__VALUE__) == LL_RCC_LPUART1_CLKSOURCE))
#if defined(RCC_CCIPR_I2C2SEL)&&defined(RCC_CCIPR_I2C3SEL)
#define IS_LL_RCC_I2C_CLKSOURCE(__VALUE__) (((__VALUE__) == LL_RCC_I2C1_CLKSOURCE) \
|| ((__VALUE__) == LL_RCC_I2C2_CLKSOURCE) \
|| ((__VALUE__) == LL_RCC_I2C3_CLKSOURCE))
#elif !defined(RCC_CCIPR_I2C2SEL)&&defined(RCC_CCIPR_I2C3SEL)
#define IS_LL_RCC_I2C_CLKSOURCE(__VALUE__) (((__VALUE__) == LL_RCC_I2C1_CLKSOURCE) \
|| ((__VALUE__) == LL_RCC_I2C3_CLKSOURCE))
#else
#define IS_LL_RCC_I2C_CLKSOURCE(__VALUE__) ((__VALUE__) == LL_RCC_I2C1_CLKSOURCE)
#endif /* RCC_CCIPR_I2C2SEL && RCC_CCIPR_I2C3SEL */
#define IS_LL_RCC_LPTIM_CLKSOURCE(__VALUE__) (((__VALUE__) == LL_RCC_LPTIM1_CLKSOURCE) \
|| ((__VALUE__) == LL_RCC_LPTIM2_CLKSOURCE))
#if defined(RCC_CCIPR_SAI2SEL)
#define IS_LL_RCC_SAI_CLKSOURCE(__VALUE__) (((__VALUE__) == LL_RCC_SAI1_CLKSOURCE) \
|| ((__VALUE__) == LL_RCC_SAI2_CLKSOURCE))
#else
#define IS_LL_RCC_SAI_CLKSOURCE(__VALUE__) ((__VALUE__) == LL_RCC_SAI1_CLKSOURCE)
#endif /* RCC_CCIPR_SAI2SEL */
#if defined(RCC_CCIPR2_SDMMCSEL)
#define IS_LL_RCC_SDMMC_KERNELCLKSOURCE(__VALUE__) (((__VALUE__) == LL_RCC_SDMMC1_KERNELCLKSOURCE))
#endif /* RCC_CCIPR2_SDMMCSEL */
#define IS_LL_RCC_SDMMC_CLKSOURCE(__VALUE__) (((__VALUE__) == LL_RCC_SDMMC1_CLKSOURCE))
#define IS_LL_RCC_RNG_CLKSOURCE(__VALUE__) (((__VALUE__) == LL_RCC_RNG_CLKSOURCE))
#if defined(USB_OTG_FS) || defined(USB)
#define IS_LL_RCC_USB_CLKSOURCE(__VALUE__) (((__VALUE__) == LL_RCC_USB_CLKSOURCE))
#endif /* USB_OTG_FS || USB */
#define IS_LL_RCC_ADC_CLKSOURCE(__VALUE__) (((__VALUE__) == LL_RCC_ADC_CLKSOURCE))
#if defined(SWPMI1)
#define IS_LL_RCC_SWPMI_CLKSOURCE(__VALUE__) (((__VALUE__) == LL_RCC_SWPMI1_CLKSOURCE))
#endif /* SWPMI1 */
#if defined(DFSDM1_Channel0)
#define IS_LL_RCC_DFSDM_CLKSOURCE(__VALUE__) (((__VALUE__) == LL_RCC_DFSDM1_CLKSOURCE))
#if defined(RCC_CCIPR2_DFSDM1SEL)
#define IS_LL_RCC_DFSDM_AUDIO_CLKSOURCE(__VALUE__) (((__VALUE__) == LL_RCC_DFSDM1_AUDIO_CLKSOURCE))
#endif /* RCC_CCIPR2_DFSDM1SEL */
#endif /* DFSDM1_Channel0 */
#if defined(DSI)
#define IS_LL_RCC_DSI_CLKSOURCE(__VALUE__) (((__VALUE__) == LL_RCC_DSI_CLKSOURCE))
#endif /* DSI */
#if defined(LTDC)
#define IS_LL_RCC_LTDC_CLKSOURCE(__VALUE__) (((__VALUE__) == LL_RCC_LTDC_CLKSOURCE))
#endif /* LTDC */
#if defined(OCTOSPI1)
#define IS_LL_RCC_OCTOSPI_CLKSOURCE(__VALUE__) (((__VALUE__) == LL_RCC_OCTOSPI_CLKSOURCE))
#endif /* OCTOSPI */
/**
* @}
*/
/* Private function prototypes -----------------------------------------------*/
/** @defgroup RCC_LL_Private_Functions RCC Private functions
* @{
*/
uint32_t RCC_GetSystemClockFreq(void);
uint32_t RCC_GetHCLKClockFreq(uint32_t SYSCLK_Frequency);
uint32_t RCC_GetPCLK1ClockFreq(uint32_t HCLK_Frequency);
uint32_t RCC_GetPCLK2ClockFreq(uint32_t HCLK_Frequency);
uint32_t RCC_PLL_GetFreqDomain_SYS(void);
uint32_t RCC_PLL_GetFreqDomain_SAI(void);
uint32_t RCC_PLL_GetFreqDomain_48M(void);
uint32_t RCC_PLLSAI1_GetFreqDomain_SAI(void);
uint32_t RCC_PLLSAI1_GetFreqDomain_48M(void);
uint32_t RCC_PLLSAI1_GetFreqDomain_ADC(void);
#if defined(RCC_PLLSAI2_SUPPORT)
uint32_t RCC_PLLSAI2_GetFreqDomain_SAI(void);
#if defined(LTDC)
uint32_t RCC_PLLSAI2_GetFreqDomain_LTDC(void);
#else
uint32_t RCC_PLLSAI2_GetFreqDomain_ADC(void);
#endif /* LTDC */
#if defined(DSI)
uint32_t RCC_PLLSAI2_GetFreqDomain_DSI(void);
#endif /* DSI */
#endif /*RCC_PLLSAI2_SUPPORT*/
/**
* @}
*/
/* Exported functions --------------------------------------------------------*/
/** @addtogroup RCC_LL_Exported_Functions
* @{
*/
/** @addtogroup RCC_LL_EF_Init
* @{
*/
/**
* @brief Reset the RCC clock configuration to the default reset state.
* @note The default reset state of the clock configuration is given below:
* - MSI ON and used as system clock source
* - HSE, HSI, PLL and PLLSAIxSource OFF
* - AHB, APB1 and APB2 prescaler set to 1.
* - CSS, MCO OFF
* - All interrupts disabled
* @note This function doesn't modify the configuration of the
* - Peripheral clocks
* - LSI, LSE and RTC clocks
* @retval An ErrorStatus enumeration value:
* - SUCCESS: RCC registers are de-initialized
* - ERROR: not applicable
*/
ErrorStatus LL_RCC_DeInit(void)
{
uint32_t vl_mask = 0U;
/* Set MSION bit */
LL_RCC_MSI_Enable();
/* Insure MSIRDY bit is set before writing default MSIRANGE value */
while (LL_RCC_MSI_IsReady() == 0U)
{
__NOP();
}
/* Set MSIRANGE default value */
LL_RCC_MSI_SetRange(LL_RCC_MSIRANGE_6);
/* Set MSITRIM bits to the reset value*/
LL_RCC_MSI_SetCalibTrimming(0);
/* Set HSITRIM bits to the reset value*/
LL_RCC_HSI_SetCalibTrimming(0x10U);
/* Reset CFGR register */
LL_RCC_WriteReg(CFGR, 0x00000000U);
vl_mask = 0xFFFFFFFFU;
/* Reset HSION, HSIKERON, HSIASFS, HSEON, PLLSYSON bits */
CLEAR_BIT(vl_mask, (RCC_CR_HSION | RCC_CR_HSIASFS | RCC_CR_HSIKERON | RCC_CR_HSEON |
RCC_CR_PLLON));
/* Reset PLLSAI1ON bit */
CLEAR_BIT(vl_mask, RCC_CR_PLLSAI1ON);
#if defined(RCC_PLLSAI2_SUPPORT)
/* Reset PLLSAI2ON bit */
CLEAR_BIT(vl_mask, RCC_CR_PLLSAI2ON);
#endif /*RCC_PLLSAI2_SUPPORT*/
/* Write new mask in CR register */
LL_RCC_WriteReg(CR, vl_mask);
/* Reset PLLCFGR register */
LL_RCC_WriteReg(PLLCFGR, 16U << RCC_PLLCFGR_PLLN_Pos);
/* Reset PLLSAI1CFGR register */
LL_RCC_WriteReg(PLLSAI1CFGR, 16U << RCC_PLLSAI1CFGR_PLLSAI1N_Pos);
#if defined(RCC_PLLSAI2_SUPPORT)
/* Reset PLLSAI2CFGR register */
LL_RCC_WriteReg(PLLSAI2CFGR, 16U << RCC_PLLSAI2CFGR_PLLSAI2N_Pos);
#endif /*RCC_PLLSAI2_SUPPORT*/
/* Reset HSEBYP bit */
LL_RCC_HSE_DisableBypass();
/* Disable all interrupts */
LL_RCC_WriteReg(CIER, 0x00000000U);
return SUCCESS;
}
/**
* @}
*/
/** @addtogroup RCC_LL_EF_Get_Freq
* @brief Return the frequencies of different on chip clocks; System, AHB, APB1 and APB2 buses clocks
* and different peripheral clocks available on the device.
* @note If SYSCLK source is MSI, function returns values based on MSI_VALUE(*)
* @note If SYSCLK source is HSI, function returns values based on HSI_VALUE(**)
* @note If SYSCLK source is HSE, function returns values based on HSE_VALUE(***)
* @note If SYSCLK source is PLL, function returns values based on HSE_VALUE(***)
* or HSI_VALUE(**) or MSI_VALUE(*) multiplied/divided by the PLL factors.
* @note (*) MSI_VALUE is a constant defined in this file (default value
* 4 MHz) but the real value may vary depending on the variations
* in voltage and temperature.
* @note (**) HSI_VALUE is a constant defined in this file (default value
* 16 MHz) but the real value may vary depending on the variations
* in voltage and temperature.
* @note (***) HSE_VALUE is a constant defined in this file (default value
* 8 MHz), user has to ensure that HSE_VALUE is same as the real
* frequency of the crystal used. Otherwise, this function may
* have wrong result.
* @note The result of this function could be incorrect when using fractional
* value for HSE crystal.
* @note This function can be used by the user application to compute the
* baud-rate for the communication peripherals or configure other parameters.
* @{
*/
/**
* @brief Return the frequencies of different on chip clocks; System, AHB, APB1 and APB2 buses clocks
* @note Each time SYSCLK, HCLK, PCLK1 and/or PCLK2 clock changes, this function
* must be called to update structure fields. Otherwise, any
* configuration based on this function will be incorrect.
* @param RCC_Clocks pointer to a @ref LL_RCC_ClocksTypeDef structure which will hold the clocks frequencies
* @retval None
*/
void LL_RCC_GetSystemClocksFreq(LL_RCC_ClocksTypeDef *RCC_Clocks)
{
/* Get SYSCLK frequency */
RCC_Clocks->SYSCLK_Frequency = RCC_GetSystemClockFreq();
/* HCLK clock frequency */
RCC_Clocks->HCLK_Frequency = RCC_GetHCLKClockFreq(RCC_Clocks->SYSCLK_Frequency);
/* PCLK1 clock frequency */
RCC_Clocks->PCLK1_Frequency = RCC_GetPCLK1ClockFreq(RCC_Clocks->HCLK_Frequency);
/* PCLK2 clock frequency */
RCC_Clocks->PCLK2_Frequency = RCC_GetPCLK2ClockFreq(RCC_Clocks->HCLK_Frequency);
}
/**
* @brief Return USARTx clock frequency
* @param USARTxSource This parameter can be one of the following values:
* @arg @ref LL_RCC_USART1_CLKSOURCE
* @arg @ref LL_RCC_USART2_CLKSOURCE
* @arg @ref LL_RCC_USART3_CLKSOURCE (*)
*
* (*) value not defined in all devices.
* @retval USART clock frequency (in Hz)
* - @ref LL_RCC_PERIPH_FREQUENCY_NO indicates that oscillator (HSI or LSE) is not ready
*/
uint32_t LL_RCC_GetUSARTClockFreq(uint32_t USARTxSource)
{
uint32_t usart_frequency = LL_RCC_PERIPH_FREQUENCY_NO;
/* Check parameter */
assert_param(IS_LL_RCC_USART_CLKSOURCE(USARTxSource));
if (USARTxSource == LL_RCC_USART1_CLKSOURCE)
{
/* USART1CLK clock frequency */
switch (LL_RCC_GetUSARTClockSource(USARTxSource))
{
case LL_RCC_USART1_CLKSOURCE_SYSCLK: /* USART1 Clock is System Clock */
usart_frequency = RCC_GetSystemClockFreq();
break;
case LL_RCC_USART1_CLKSOURCE_HSI: /* USART1 Clock is HSI Osc. */
if (LL_RCC_HSI_IsReady())
{
usart_frequency = HSI_VALUE;
}
break;
case LL_RCC_USART1_CLKSOURCE_LSE: /* USART1 Clock is LSE Osc. */
if (LL_RCC_LSE_IsReady())
{
usart_frequency = LSE_VALUE;
}
break;
case LL_RCC_USART1_CLKSOURCE_PCLK2: /* USART1 Clock is PCLK2 */
default:
usart_frequency = RCC_GetPCLK2ClockFreq(RCC_GetHCLKClockFreq(RCC_GetSystemClockFreq()));
break;
}
}
else if (USARTxSource == LL_RCC_USART2_CLKSOURCE)
{
/* USART2CLK clock frequency */
switch (LL_RCC_GetUSARTClockSource(USARTxSource))
{
case LL_RCC_USART2_CLKSOURCE_SYSCLK: /* USART2 Clock is System Clock */
usart_frequency = RCC_GetSystemClockFreq();
break;
case LL_RCC_USART2_CLKSOURCE_HSI: /* USART2 Clock is HSI Osc. */
if (LL_RCC_HSI_IsReady())
{
usart_frequency = HSI_VALUE;
}
break;
case LL_RCC_USART2_CLKSOURCE_LSE: /* USART2 Clock is LSE Osc. */
if (LL_RCC_LSE_IsReady())
{
usart_frequency = LSE_VALUE;
}
break;
case LL_RCC_USART2_CLKSOURCE_PCLK1: /* USART2 Clock is PCLK1 */
default:
usart_frequency = RCC_GetPCLK1ClockFreq(RCC_GetHCLKClockFreq(RCC_GetSystemClockFreq()));
break;
}
}
else
{
#if defined(RCC_CCIPR_USART3SEL)
if (USARTxSource == LL_RCC_USART3_CLKSOURCE)
{
/* USART3CLK clock frequency */
switch (LL_RCC_GetUSARTClockSource(USARTxSource))
{
case LL_RCC_USART3_CLKSOURCE_SYSCLK: /* USART3 Clock is System Clock */
usart_frequency = RCC_GetSystemClockFreq();
break;
case LL_RCC_USART3_CLKSOURCE_HSI: /* USART3 Clock is HSI Osc. */
if (LL_RCC_HSI_IsReady())
{
usart_frequency = HSI_VALUE;
}
break;
case LL_RCC_USART3_CLKSOURCE_LSE: /* USART3 Clock is LSE Osc. */
if (LL_RCC_LSE_IsReady())
{
usart_frequency = LSE_VALUE;
}
break;
case LL_RCC_USART3_CLKSOURCE_PCLK1: /* USART3 Clock is PCLK1 */
default:
usart_frequency = RCC_GetPCLK1ClockFreq(RCC_GetHCLKClockFreq(RCC_GetSystemClockFreq()));
break;
}
}
#endif /* RCC_CCIPR_USART3SEL */
}
return usart_frequency;
}
#if defined(RCC_CCIPR_UART4SEL) || defined(RCC_CCIPR_UART5SEL)
/**
* @brief Return UARTx clock frequency
* @param UARTxSource This parameter can be one of the following values:
* @arg @ref LL_RCC_UART4_CLKSOURCE
* @arg @ref LL_RCC_UART5_CLKSOURCE
* @retval UART clock frequency (in Hz)
* - @ref LL_RCC_PERIPH_FREQUENCY_NO indicates that oscillator (HSI or LSE) is not ready
*/
uint32_t LL_RCC_GetUARTClockFreq(uint32_t UARTxSource)
{
uint32_t uart_frequency = LL_RCC_PERIPH_FREQUENCY_NO;
/* Check parameter */
assert_param(IS_LL_RCC_UART_CLKSOURCE(UARTxSource));
#if defined(RCC_CCIPR_UART4SEL)
if (UARTxSource == LL_RCC_UART4_CLKSOURCE)
{
/* UART4CLK clock frequency */
switch (LL_RCC_GetUARTClockSource(UARTxSource))
{
case LL_RCC_UART4_CLKSOURCE_SYSCLK: /* UART4 Clock is System Clock */
uart_frequency = RCC_GetSystemClockFreq();
break;
case LL_RCC_UART4_CLKSOURCE_HSI: /* UART4 Clock is HSI Osc. */
if (LL_RCC_HSI_IsReady())
{
uart_frequency = HSI_VALUE;
}
break;
case LL_RCC_UART4_CLKSOURCE_LSE: /* UART4 Clock is LSE Osc. */
if (LL_RCC_LSE_IsReady())
{
uart_frequency = LSE_VALUE;
}
break;
case LL_RCC_UART4_CLKSOURCE_PCLK1: /* UART4 Clock is PCLK1 */
default:
uart_frequency = RCC_GetPCLK1ClockFreq(RCC_GetHCLKClockFreq(RCC_GetSystemClockFreq()));
break;
}
}
#endif /* RCC_CCIPR_UART4SEL */
#if defined(RCC_CCIPR_UART5SEL)
if (UARTxSource == LL_RCC_UART5_CLKSOURCE)
{
/* UART5CLK clock frequency */
switch (LL_RCC_GetUARTClockSource(UARTxSource))
{
case LL_RCC_UART5_CLKSOURCE_SYSCLK: /* UART5 Clock is System Clock */
uart_frequency = RCC_GetSystemClockFreq();
break;
case LL_RCC_UART5_CLKSOURCE_HSI: /* UART5 Clock is HSI Osc. */
if (LL_RCC_HSI_IsReady())
{
uart_frequency = HSI_VALUE;
}
break;
case LL_RCC_UART5_CLKSOURCE_LSE: /* UART5 Clock is LSE Osc. */
if (LL_RCC_LSE_IsReady())
{
uart_frequency = LSE_VALUE;
}
break;
case LL_RCC_UART5_CLKSOURCE_PCLK1: /* UART5 Clock is PCLK1 */
default:
uart_frequency = RCC_GetPCLK1ClockFreq(RCC_GetHCLKClockFreq(RCC_GetSystemClockFreq()));
break;
}
}
#endif /* RCC_CCIPR_UART5SEL */
return uart_frequency;
}
#endif /* RCC_CCIPR_UART4SEL || RCC_CCIPR_UART5SEL */
/**
* @brief Return I2Cx clock frequency
* @param I2CxSource This parameter can be one of the following values:
* @arg @ref LL_RCC_I2C1_CLKSOURCE
* @arg @ref LL_RCC_I2C2_CLKSOURCE (*)
* @arg @ref LL_RCC_I2C3_CLKSOURCE
* @arg @ref LL_RCC_I2C4_CLKSOURCE (*)
*
* (*) value not defined in all devices.
* @retval I2C clock frequency (in Hz)
* - @ref LL_RCC_PERIPH_FREQUENCY_NO indicates that HSI oscillator is not ready
*/
uint32_t LL_RCC_GetI2CClockFreq(uint32_t I2CxSource)
{
uint32_t i2c_frequency = LL_RCC_PERIPH_FREQUENCY_NO;
/* Check parameter */
assert_param(IS_LL_RCC_I2C_CLKSOURCE(I2CxSource));
if (I2CxSource == LL_RCC_I2C1_CLKSOURCE)
{
/* I2C1 CLK clock frequency */
switch (LL_RCC_GetI2CClockSource(I2CxSource))
{
case LL_RCC_I2C1_CLKSOURCE_SYSCLK: /* I2C1 Clock is System Clock */
i2c_frequency = RCC_GetSystemClockFreq();
break;
case LL_RCC_I2C1_CLKSOURCE_HSI: /* I2C1 Clock is HSI Osc. */
if (LL_RCC_HSI_IsReady())
{
i2c_frequency = HSI_VALUE;
}
break;
case LL_RCC_I2C1_CLKSOURCE_PCLK1: /* I2C1 Clock is PCLK1 */
default:
i2c_frequency = RCC_GetPCLK1ClockFreq(RCC_GetHCLKClockFreq(RCC_GetSystemClockFreq()));
break;
}
}
#if defined(RCC_CCIPR_I2C2SEL)
else if (I2CxSource == LL_RCC_I2C2_CLKSOURCE)
{
/* I2C2 CLK clock frequency */
switch (LL_RCC_GetI2CClockSource(I2CxSource))
{
case LL_RCC_I2C2_CLKSOURCE_SYSCLK: /* I2C2 Clock is System Clock */
i2c_frequency = RCC_GetSystemClockFreq();
break;
case LL_RCC_I2C2_CLKSOURCE_HSI: /* I2C2 Clock is HSI Osc. */
if (LL_RCC_HSI_IsReady())
{
i2c_frequency = HSI_VALUE;
}
break;
case LL_RCC_I2C2_CLKSOURCE_PCLK1: /* I2C2 Clock is PCLK1 */
default:
i2c_frequency = RCC_GetPCLK1ClockFreq(RCC_GetHCLKClockFreq(RCC_GetSystemClockFreq()));
break;
}
}
#endif /*RCC_CCIPR_I2C2SEL*/
else
{
if (I2CxSource == LL_RCC_I2C3_CLKSOURCE)
{
/* I2C3 CLK clock frequency */
switch (LL_RCC_GetI2CClockSource(I2CxSource))
{
case LL_RCC_I2C3_CLKSOURCE_SYSCLK: /* I2C3 Clock is System Clock */
i2c_frequency = RCC_GetSystemClockFreq();
break;
case LL_RCC_I2C3_CLKSOURCE_HSI: /* I2C3 Clock is HSI Osc. */
if (LL_RCC_HSI_IsReady())
{
i2c_frequency = HSI_VALUE;
}
break;
case LL_RCC_I2C3_CLKSOURCE_PCLK1: /* I2C3 Clock is PCLK1 */
default:
i2c_frequency = RCC_GetPCLK1ClockFreq(RCC_GetHCLKClockFreq(RCC_GetSystemClockFreq()));
break;
}
}
#if defined(RCC_CCIPR2_I2C4SEL)
else
{
if (I2CxSource == LL_RCC_I2C4_CLKSOURCE)
{
/* I2C4 CLK clock frequency */
switch (LL_RCC_GetI2CClockSource(I2CxSource))
{
case LL_RCC_I2C4_CLKSOURCE_SYSCLK: /* I2C4 Clock is System Clock */
i2c_frequency = RCC_GetSystemClockFreq();
break;
case LL_RCC_I2C4_CLKSOURCE_HSI: /* I2C4 Clock is HSI Osc. */
if (LL_RCC_HSI_IsReady())
{
i2c_frequency = HSI_VALUE;
}
break;
case LL_RCC_I2C4_CLKSOURCE_PCLK1: /* I2C4 Clock is PCLK1 */
default:
i2c_frequency = RCC_GetPCLK1ClockFreq(RCC_GetHCLKClockFreq(RCC_GetSystemClockFreq()));
break;
}
}
}
#endif /*RCC_CCIPR2_I2C4SEL*/
}
return i2c_frequency;
}
/**
* @brief Return LPUARTx clock frequency
* @param LPUARTxSource This parameter can be one of the following values:
* @arg @ref LL_RCC_LPUART1_CLKSOURCE
* @retval LPUART clock frequency (in Hz)
* - @ref LL_RCC_PERIPH_FREQUENCY_NO indicates that oscillator (HSI or LSE) is not ready
*/
uint32_t LL_RCC_GetLPUARTClockFreq(uint32_t LPUARTxSource)
{
uint32_t lpuart_frequency = LL_RCC_PERIPH_FREQUENCY_NO;
/* Check parameter */
assert_param(IS_LL_RCC_LPUART_CLKSOURCE(LPUARTxSource));
/* LPUART1CLK clock frequency */
switch (LL_RCC_GetLPUARTClockSource(LPUARTxSource))
{
case LL_RCC_LPUART1_CLKSOURCE_SYSCLK: /* LPUART1 Clock is System Clock */
lpuart_frequency = RCC_GetSystemClockFreq();
break;
case LL_RCC_LPUART1_CLKSOURCE_HSI: /* LPUART1 Clock is HSI Osc. */
if (LL_RCC_HSI_IsReady())
{
lpuart_frequency = HSI_VALUE;
}
break;
case LL_RCC_LPUART1_CLKSOURCE_LSE: /* LPUART1 Clock is LSE Osc. */
if (LL_RCC_LSE_IsReady())
{
lpuart_frequency = LSE_VALUE;
}
break;
case LL_RCC_LPUART1_CLKSOURCE_PCLK1: /* LPUART1 Clock is PCLK1 */
default:
lpuart_frequency = RCC_GetPCLK1ClockFreq(RCC_GetHCLKClockFreq(RCC_GetSystemClockFreq()));
break;
}
return lpuart_frequency;
}
/**
* @brief Return LPTIMx clock frequency
* @param LPTIMxSource This parameter can be one of the following values:
* @arg @ref LL_RCC_LPTIM1_CLKSOURCE
* @arg @ref LL_RCC_LPTIM2_CLKSOURCE
* @retval LPTIM clock frequency (in Hz)
* - @ref LL_RCC_PERIPH_FREQUENCY_NO indicates that oscillator (HSI, LSI or LSE) is not ready
*/
uint32_t LL_RCC_GetLPTIMClockFreq(uint32_t LPTIMxSource)
{
uint32_t lptim_frequency = LL_RCC_PERIPH_FREQUENCY_NO;
/* Check parameter */
assert_param(IS_LL_RCC_LPTIM_CLKSOURCE(LPTIMxSource));
if (LPTIMxSource == LL_RCC_LPTIM1_CLKSOURCE)
{
/* LPTIM1CLK clock frequency */
switch (LL_RCC_GetLPTIMClockSource(LPTIMxSource))
{
case LL_RCC_LPTIM1_CLKSOURCE_LSI: /* LPTIM1 Clock is LSI Osc. */
if (LL_RCC_LSI_IsReady())
{
lptim_frequency = LSI_VALUE;
}
break;
case LL_RCC_LPTIM1_CLKSOURCE_HSI: /* LPTIM1 Clock is HSI Osc. */
if (LL_RCC_HSI_IsReady())
{
lptim_frequency = HSI_VALUE;
}
break;
case LL_RCC_LPTIM1_CLKSOURCE_LSE: /* LPTIM1 Clock is LSE Osc. */
if (LL_RCC_LSE_IsReady())
{
lptim_frequency = LSE_VALUE;
}
break;
case LL_RCC_LPTIM1_CLKSOURCE_PCLK1: /* LPTIM1 Clock is PCLK1 */
default:
lptim_frequency = RCC_GetPCLK1ClockFreq(RCC_GetHCLKClockFreq(RCC_GetSystemClockFreq()));
break;
}
}
else
{
if (LPTIMxSource == LL_RCC_LPTIM2_CLKSOURCE)
{
/* LPTIM2CLK clock frequency */
switch (LL_RCC_GetLPTIMClockSource(LPTIMxSource))
{
case LL_RCC_LPTIM2_CLKSOURCE_LSI: /* LPTIM2 Clock is LSI Osc. */
if (LL_RCC_LSI_IsReady())
{
lptim_frequency = LSI_VALUE;
}
break;
case LL_RCC_LPTIM2_CLKSOURCE_HSI: /* LPTIM2 Clock is HSI Osc. */
if (LL_RCC_HSI_IsReady())
{
lptim_frequency = HSI_VALUE;
}
break;
case LL_RCC_LPTIM2_CLKSOURCE_LSE: /* LPTIM2 Clock is LSE Osc. */
if (LL_RCC_LSE_IsReady())
{
lptim_frequency = LSE_VALUE;
}
break;
case LL_RCC_LPTIM2_CLKSOURCE_PCLK1: /* LPTIM2 Clock is PCLK1 */
default:
lptim_frequency = RCC_GetPCLK1ClockFreq(RCC_GetHCLKClockFreq(RCC_GetSystemClockFreq()));
break;
}
}
}
return lptim_frequency;
}
/**
* @brief Return SAIx clock frequency
* @param SAIxSource This parameter can be one of the following values:
* @arg @ref LL_RCC_SAI1_CLKSOURCE
* @arg @ref LL_RCC_SAI2_CLKSOURCE (*)
*
* (*) value not defined in all devices.
* @retval SAI clock frequency (in Hz)
* - @ref LL_RCC_PERIPH_FREQUENCY_NO indicates that PLL is not ready
* - @ref LL_RCC_PERIPH_FREQUENCY_NA indicates that external clock is used
*/
uint32_t LL_RCC_GetSAIClockFreq(uint32_t SAIxSource)
{
uint32_t sai_frequency = LL_RCC_PERIPH_FREQUENCY_NO;
/* Check parameter */
assert_param(IS_LL_RCC_SAI_CLKSOURCE(SAIxSource));
if (SAIxSource == LL_RCC_SAI1_CLKSOURCE)
{
/* SAI1CLK clock frequency */
switch (LL_RCC_GetSAIClockSource(SAIxSource))
{
case LL_RCC_SAI1_CLKSOURCE_PLLSAI1: /* PLLSAI1 clock used as SAI1 clock source */
if (LL_RCC_PLLSAI1_IsReady())
{
sai_frequency = RCC_PLLSAI1_GetFreqDomain_SAI();
}
break;
#if defined(RCC_PLLSAI2_SUPPORT)
case LL_RCC_SAI1_CLKSOURCE_PLLSAI2: /* PLLSAI2 clock used as SAI1 clock source */
if (LL_RCC_PLLSAI2_IsReady())
{
sai_frequency = RCC_PLLSAI2_GetFreqDomain_SAI();
}
break;
#endif /* RCC_PLLSAI2_SUPPORT */
case LL_RCC_SAI1_CLKSOURCE_PLL: /* PLL clock used as SAI1 clock source */
if (LL_RCC_PLL_IsReady())
{
sai_frequency = RCC_PLL_GetFreqDomain_SAI();
}
break;
case LL_RCC_SAI1_CLKSOURCE_PIN: /* External input clock used as SAI1 clock source */
default:
sai_frequency = LL_RCC_PERIPH_FREQUENCY_NA;
break;
}
}
else
{
#if defined(RCC_CCIPR_SAI2SEL)
if (SAIxSource == LL_RCC_SAI2_CLKSOURCE)
{
/* SAI2CLK clock frequency */
switch (LL_RCC_GetSAIClockSource(SAIxSource))
{
case LL_RCC_SAI2_CLKSOURCE_PLLSAI1: /* PLLSAI1 clock used as SAI2 clock source */
if (LL_RCC_PLLSAI1_IsReady())
{
sai_frequency = RCC_PLLSAI1_GetFreqDomain_SAI();
}
break;
#if defined(RCC_PLLSAI2_SUPPORT)
case LL_RCC_SAI2_CLKSOURCE_PLLSAI2: /* PLLSAI2 clock used as SAI2 clock source */
if (LL_RCC_PLLSAI2_IsReady())
{
sai_frequency = RCC_PLLSAI2_GetFreqDomain_SAI();
}
break;
#endif /* RCC_PLLSAI2_SUPPORT */
case LL_RCC_SAI2_CLKSOURCE_PLL: /* PLL clock used as SAI2 clock source */
if (LL_RCC_PLL_IsReady())
{
sai_frequency = RCC_PLL_GetFreqDomain_SAI();
}
break;
case LL_RCC_SAI2_CLKSOURCE_PIN: /* External input clock used as SAI2 clock source */
default:
sai_frequency = LL_RCC_PERIPH_FREQUENCY_NA;
break;
}
}
#endif /* RCC_CCIPR_SAI2SEL */
}
return sai_frequency;
}
#if defined(RCC_CCIPR2_SDMMCSEL)
/**
* @brief Return SDMMCx kernel clock frequency
* @param SDMMCxSource This parameter can be one of the following values:
* @arg @ref LL_RCC_SDMMC1_KERNELCLKSOURCE
* @retval SDMMC clock frequency (in Hz)
* - @ref LL_RCC_PERIPH_FREQUENCY_NO indicates that oscillator (MSI) or PLL is not ready
* - @ref LL_RCC_PERIPH_FREQUENCY_NA indicates that no clock source selected
*/
uint32_t LL_RCC_GetSDMMCKernelClockFreq(uint32_t SDMMCxSource)
{
uint32_t sdmmc_frequency = LL_RCC_PERIPH_FREQUENCY_NO;
/* Check parameter */
assert_param(IS_LL_RCC_SDMMC_KERNELCLKSOURCE(SDMMCxSource));
/* SDMMC1CLK kernel clock frequency */
switch (LL_RCC_GetSDMMCKernelClockSource(SDMMCxSource))
{
case LL_RCC_SDMMC1_KERNELCLKSOURCE_48CLK: /* 48MHz clock from internal multiplexor used as SDMMC1 clock source */
sdmmc_frequency = LL_RCC_GetSDMMCClockFreq(LL_RCC_SDMMC1_CLKSOURCE);
break;
case LL_RCC_SDMMC1_KERNELCLKSOURCE_PLLP: /* PLL "P" output (PLLSAI3CLK) clock used as SDMMC1 clock source */
if (LL_RCC_PLL_IsReady())
{
sdmmc_frequency = RCC_PLL_GetFreqDomain_SAI();
}
break;
default:
sdmmc_frequency = LL_RCC_PERIPH_FREQUENCY_NA;
break;
}
return sdmmc_frequency;
}
#endif
/**
* @brief Return SDMMCx clock frequency
* @param SDMMCxSource This parameter can be one of the following values:
* @arg @ref LL_RCC_SDMMC1_CLKSOURCE
* @retval SDMMC clock frequency (in Hz)
* - @ref LL_RCC_PERIPH_FREQUENCY_NO indicates that oscillator (MSI) or PLL is not ready
* - @ref LL_RCC_PERIPH_FREQUENCY_NA indicates that no clock source selected
*/
uint32_t LL_RCC_GetSDMMCClockFreq(uint32_t SDMMCxSource)
{
uint32_t sdmmc_frequency = LL_RCC_PERIPH_FREQUENCY_NO;
/* Check parameter */
assert_param(IS_LL_RCC_SDMMC_CLKSOURCE(SDMMCxSource));
/* SDMMC1CLK clock frequency */
switch (LL_RCC_GetSDMMCClockSource(SDMMCxSource))
{
#if defined(LL_RCC_SDMMC1_CLKSOURCE_PLLSAI1)
case LL_RCC_SDMMC1_CLKSOURCE_PLLSAI1: /* PLLSAI1 clock used as SDMMC1 clock source */
if (LL_RCC_PLLSAI1_IsReady())
{
sdmmc_frequency = RCC_PLLSAI1_GetFreqDomain_48M();
}
break;
#endif
case LL_RCC_SDMMC1_CLKSOURCE_PLL: /* PLL clock used as SDMMC1 clock source */
if (LL_RCC_PLL_IsReady())
{
sdmmc_frequency = RCC_PLL_GetFreqDomain_48M();
}
break;
#if defined(LL_RCC_SDMMC1_CLKSOURCE_MSI)
case LL_RCC_SDMMC1_CLKSOURCE_MSI: /* MSI clock used as SDMMC1 clock source */
if (LL_RCC_MSI_IsReady())
{
sdmmc_frequency = __LL_RCC_CALC_MSI_FREQ(LL_RCC_MSI_IsEnabledRangeSelect(),
(LL_RCC_MSI_IsEnabledRangeSelect() ?
LL_RCC_MSI_GetRange() :
LL_RCC_MSI_GetRangeAfterStandby()));
}
break;
#endif
#if defined(RCC_HSI48_SUPPORT)
case LL_RCC_SDMMC1_CLKSOURCE_HSI48: /* HSI48 used as SDMMC1 clock source */
if (LL_RCC_HSI48_IsReady())
{
sdmmc_frequency = HSI48_VALUE;
}
break;
#else
case LL_RCC_SDMMC1_CLKSOURCE_NONE: /* No clock used as SDMMC1 clock source */
#endif
default:
sdmmc_frequency = LL_RCC_PERIPH_FREQUENCY_NA;
break;
}
return sdmmc_frequency;
}
/**
* @brief Return RNGx clock frequency
* @param RNGxSource This parameter can be one of the following values:
* @arg @ref LL_RCC_RNG_CLKSOURCE
* @retval RNG clock frequency (in Hz)
* - @ref LL_RCC_PERIPH_FREQUENCY_NO indicates that oscillator (MSI) or PLL is not ready
* - @ref LL_RCC_PERIPH_FREQUENCY_NA indicates that no clock source selected
*/
uint32_t LL_RCC_GetRNGClockFreq(uint32_t RNGxSource)
{
uint32_t rng_frequency = LL_RCC_PERIPH_FREQUENCY_NO;
/* Check parameter */
assert_param(IS_LL_RCC_RNG_CLKSOURCE(RNGxSource));
/* RNGCLK clock frequency */
switch (LL_RCC_GetRNGClockSource(RNGxSource))
{
case LL_RCC_RNG_CLKSOURCE_PLLSAI1: /* PLLSAI1 clock used as RNG clock source */
if (LL_RCC_PLLSAI1_IsReady())
{
rng_frequency = RCC_PLLSAI1_GetFreqDomain_48M();
}
break;
case LL_RCC_RNG_CLKSOURCE_PLL: /* PLL clock used as RNG clock source */
if (LL_RCC_PLL_IsReady())
{
rng_frequency = RCC_PLL_GetFreqDomain_48M();
}
break;
case LL_RCC_RNG_CLKSOURCE_MSI: /* MSI clock used as RNG clock source */
if (LL_RCC_MSI_IsReady())
{
rng_frequency = __LL_RCC_CALC_MSI_FREQ(LL_RCC_MSI_IsEnabledRangeSelect(),
(LL_RCC_MSI_IsEnabledRangeSelect() ?
LL_RCC_MSI_GetRange() :
LL_RCC_MSI_GetRangeAfterStandby()));
}
break;
#if defined(RCC_HSI48_SUPPORT)
case LL_RCC_RNG_CLKSOURCE_HSI48: /* HSI48 used as SDMMC1 clock source */
if (LL_RCC_HSI48_IsReady())
{
rng_frequency = HSI48_VALUE;
}
break;
#else
case LL_RCC_RNG_CLKSOURCE_NONE: /* No clock used as SDMMC1 clock source */
#endif
default:
rng_frequency = LL_RCC_PERIPH_FREQUENCY_NA;
break;
}
return rng_frequency;
}
#if defined(USB_OTG_FS)||defined(USB)
/**
* @brief Return USBx clock frequency
* @param USBxSource This parameter can be one of the following values:
* @arg @ref LL_RCC_USB_CLKSOURCE
* @retval USB clock frequency (in Hz)
* - @ref LL_RCC_PERIPH_FREQUENCY_NO indicates that oscillator (MSI) or PLL is not ready
* - @ref LL_RCC_PERIPH_FREQUENCY_NA indicates that no clock source selected
*/
uint32_t LL_RCC_GetUSBClockFreq(uint32_t USBxSource)
{
uint32_t usb_frequency = LL_RCC_PERIPH_FREQUENCY_NO;
/* Check parameter */
assert_param(IS_LL_RCC_USB_CLKSOURCE(USBxSource));
/* USBCLK clock frequency */
switch (LL_RCC_GetUSBClockSource(USBxSource))
{
case LL_RCC_USB_CLKSOURCE_PLLSAI1: /* PLLSAI1 clock used as USB clock source */
if (LL_RCC_PLLSAI1_IsReady())
{
usb_frequency = RCC_PLLSAI1_GetFreqDomain_48M();
}
break;
case LL_RCC_USB_CLKSOURCE_PLL: /* PLL clock used as USB clock source */
if (LL_RCC_PLL_IsReady())
{
usb_frequency = RCC_PLL_GetFreqDomain_48M();
}
break;
case LL_RCC_USB_CLKSOURCE_MSI: /* MSI clock used as USB clock source */
if (LL_RCC_MSI_IsReady())
{
usb_frequency = __LL_RCC_CALC_MSI_FREQ(LL_RCC_MSI_IsEnabledRangeSelect(),
(LL_RCC_MSI_IsEnabledRangeSelect() ?
LL_RCC_MSI_GetRange() :
LL_RCC_MSI_GetRangeAfterStandby()));
}
break;
#if defined(RCC_HSI48_SUPPORT)
case LL_RCC_USB_CLKSOURCE_HSI48: /* HSI48 used as USB clock source */
if (LL_RCC_HSI48_IsReady())
{
usb_frequency = HSI48_VALUE;
}
break;
#else
case LL_RCC_USB_CLKSOURCE_NONE: /* No clock used as USB clock source */
#endif
default:
usb_frequency = LL_RCC_PERIPH_FREQUENCY_NA;
break;
}
return usb_frequency;
}
#endif /* USB_OTG_FS || USB */
/**
* @brief Return ADCx clock frequency
* @param ADCxSource This parameter can be one of the following values:
* @arg @ref LL_RCC_ADC_CLKSOURCE
* @retval ADC clock frequency (in Hz)
* - @ref LL_RCC_PERIPH_FREQUENCY_NO indicates that oscillator (MSI) or PLL is not ready
* - @ref LL_RCC_PERIPH_FREQUENCY_NA indicates that no clock source selected
*/
uint32_t LL_RCC_GetADCClockFreq(uint32_t ADCxSource)
{
uint32_t adc_frequency = LL_RCC_PERIPH_FREQUENCY_NO;
/* Check parameter */
assert_param(IS_LL_RCC_ADC_CLKSOURCE(ADCxSource));
/* ADCCLK clock frequency */
switch (LL_RCC_GetADCClockSource(ADCxSource))
{
case LL_RCC_ADC_CLKSOURCE_PLLSAI1: /* PLLSAI1 clock used as ADC clock source */
if (LL_RCC_PLLSAI1_IsReady())
{
adc_frequency = RCC_PLLSAI1_GetFreqDomain_ADC();
}
break;
#if defined(RCC_PLLSAI2_SUPPORT) && defined(LL_RCC_ADC_CLKSOURCE_PLLSAI2)
case LL_RCC_ADC_CLKSOURCE_PLLSAI2: /* PLLSAI2 clock used as ADC clock source */
if (LL_RCC_PLLSAI2_IsReady())
{
adc_frequency = RCC_PLLSAI2_GetFreqDomain_ADC();
}
break;
#endif /* RCC_PLLSAI2_SUPPORT && LL_RCC_ADC_CLKSOURCE_PLLSAI2 */
case LL_RCC_ADC_CLKSOURCE_SYSCLK: /* SYSCLK clock used as ADC clock source */
adc_frequency = RCC_GetSystemClockFreq();
break;
case LL_RCC_ADC_CLKSOURCE_NONE: /* No clock used as ADC clock source */
default:
adc_frequency = LL_RCC_PERIPH_FREQUENCY_NA;
break;
}
return adc_frequency;
}
#if defined(SWPMI1)
/**
* @brief Return SWPMIx clock frequency
* @param SWPMIxSource This parameter can be one of the following values:
* @arg @ref LL_RCC_SWPMI1_CLKSOURCE
* @retval SWPMI clock frequency (in Hz)
* - @ref LL_RCC_PERIPH_FREQUENCY_NO indicates that oscillator (HSI) is not ready
*/
uint32_t LL_RCC_GetSWPMIClockFreq(uint32_t SWPMIxSource)
{
uint32_t swpmi_frequency = LL_RCC_PERIPH_FREQUENCY_NO;
/* Check parameter */
assert_param(IS_LL_RCC_SWPMI_CLKSOURCE(SWPMIxSource));
/* SWPMI1CLK clock frequency */
switch (LL_RCC_GetSWPMIClockSource(SWPMIxSource))
{
case LL_RCC_SWPMI1_CLKSOURCE_HSI: /* SWPMI1 Clock is HSI Osc. */
if (LL_RCC_HSI_IsReady())
{
swpmi_frequency = HSI_VALUE;
}
break;
case LL_RCC_SWPMI1_CLKSOURCE_PCLK1: /* SWPMI1 Clock is PCLK1 */
default:
swpmi_frequency = RCC_GetPCLK1ClockFreq(RCC_GetHCLKClockFreq(RCC_GetSystemClockFreq()));
break;
}
return swpmi_frequency;
}
#endif /* SWPMI1 */
#if defined(DFSDM1_Channel0)
/**
* @brief Return DFSDMx clock frequency
* @param DFSDMxSource This parameter can be one of the following values:
* @arg @ref LL_RCC_DFSDM1_CLKSOURCE
* @retval DFSDM clock frequency (in Hz)
*/
uint32_t LL_RCC_GetDFSDMClockFreq(uint32_t DFSDMxSource)
{
uint32_t dfsdm_frequency = LL_RCC_PERIPH_FREQUENCY_NO;
/* Check parameter */
assert_param(IS_LL_RCC_DFSDM_CLKSOURCE(DFSDMxSource));
/* DFSDM1CLK clock frequency */
switch (LL_RCC_GetDFSDMClockSource(DFSDMxSource))
{
case LL_RCC_DFSDM1_CLKSOURCE_SYSCLK: /* DFSDM1 Clock is SYSCLK */
dfsdm_frequency = RCC_GetSystemClockFreq();
break;
case LL_RCC_DFSDM1_CLKSOURCE_PCLK2: /* DFSDM1 Clock is PCLK2 */
default:
dfsdm_frequency = RCC_GetPCLK2ClockFreq(RCC_GetHCLKClockFreq(RCC_GetSystemClockFreq()));
break;
}
return dfsdm_frequency;
}
#if defined(RCC_CCIPR2_DFSDM1SEL)
/**
* @brief Return DFSDMx Audio clock frequency
* @param DFSDMxSource This parameter can be one of the following values:
* @arg @ref LL_RCC_DFSDM1_AUDIO_CLKSOURCE
* @retval DFSDM clock frequency (in Hz)
* - @ref LL_RCC_PERIPH_FREQUENCY_NO indicates that oscillator is not ready
*/
uint32_t LL_RCC_GetDFSDMAudioClockFreq(uint32_t DFSDMxSource)
{
uint32_t dfsdm_frequency = LL_RCC_PERIPH_FREQUENCY_NO;
/* Check parameter */
assert_param(IS_LL_RCC_DFSDM_AUDIO_CLKSOURCE(DFSDMxSource));
/* DFSDM1CLK clock frequency */
switch (LL_RCC_GetDFSDMAudioClockSource(DFSDMxSource))
{
case LL_RCC_DFSDM1_AUDIO_CLKSOURCE_SAI1: /* SAI1 clock used as DFSDM1 audio clock */
dfsdm_frequency = LL_RCC_GetSAIClockFreq(LL_RCC_SAI1_CLKSOURCE);
break;
case LL_RCC_DFSDM1_AUDIO_CLKSOURCE_MSI: /* MSI clock used as DFSDM1 audio clock */
if (LL_RCC_MSI_IsReady())
{
dfsdm_frequency = __LL_RCC_CALC_MSI_FREQ(LL_RCC_MSI_IsEnabledRangeSelect(),
(LL_RCC_MSI_IsEnabledRangeSelect() ?
LL_RCC_MSI_GetRange() :
LL_RCC_MSI_GetRangeAfterStandby()));
}
break;
case LL_RCC_DFSDM1_AUDIO_CLKSOURCE_HSI: /* HSI clock used as DFSDM1 audio clock */
default:
if (LL_RCC_HSI_IsReady())
{
dfsdm_frequency = HSI_VALUE;
}
break;
}
return dfsdm_frequency;
}
#endif /* RCC_CCIPR2_DFSDM1SEL */
#endif /* DFSDM1_Channel0 */
#if defined(DSI)
/**
* @brief Return DSI clock frequency
* @param DSIxSource This parameter can be one of the following values:
* @arg @ref LL_RCC_DSI_CLKSOURCE
* @retval DSI clock frequency (in Hz)
* - @ref LL_RCC_PERIPH_FREQUENCY_NO indicates that oscillator is not ready
* - @ref LL_RCC_PERIPH_FREQUENCY_NA indicates that external clock is used
*/
uint32_t LL_RCC_GetDSIClockFreq(uint32_t DSIxSource)
{
uint32_t dsi_frequency = LL_RCC_PERIPH_FREQUENCY_NO;
/* Check parameter */
assert_param(IS_LL_RCC_DSI_CLKSOURCE(DSIxSource));
/* DSICLK clock frequency */
switch (LL_RCC_GetDSIClockSource(DSIxSource))
{
case LL_RCC_DSI_CLKSOURCE_PLL: /* DSI Clock is PLLSAI2 Osc. */
if (LL_RCC_PLLSAI2_IsReady())
{
dsi_frequency = RCC_PLLSAI2_GetFreqDomain_DSI();
}
break;
case LL_RCC_DSI_CLKSOURCE_PHY: /* DSI Clock is DSI physical clock. */
default:
dsi_frequency = LL_RCC_PERIPH_FREQUENCY_NA;
break;
}
return dsi_frequency;
}
#endif /* DSI */
#if defined(LTDC)
/**
* @brief Return LTDC clock frequency
* @param LTDCxSource This parameter can be one of the following values:
* @arg @ref LL_RCC_LTDC_CLKSOURCE
* @retval LTDC clock frequency (in Hz)
* - @ref LL_RCC_PERIPH_FREQUENCY_NO indicates that oscillator PLLSAI is not ready
*/
uint32_t LL_RCC_GetLTDCClockFreq(uint32_t LTDCxSource)
{
uint32_t ltdc_frequency = LL_RCC_PERIPH_FREQUENCY_NO;
/* Check parameter */
assert_param(IS_LL_RCC_LTDC_CLKSOURCE(LTDCxSource));
if (LL_RCC_PLLSAI2_IsReady())
{
ltdc_frequency = RCC_PLLSAI2_GetFreqDomain_LTDC();
}
return ltdc_frequency;
}
#endif /* LTDC */
#if defined(OCTOSPI1)
/**
* @brief Return OCTOSPI clock frequency
* @param OCTOSPIxSource This parameter can be one of the following values:
* @arg @ref LL_RCC_OCTOSPI_CLKSOURCE
* @retval OCTOSPI clock frequency (in Hz)
* - @ref LL_RCC_PERIPH_FREQUENCY_NO indicates that oscillator PLLSAI is not ready
*/
uint32_t LL_RCC_GetOCTOSPIClockFreq(uint32_t OCTOSPIxSource)
{
uint32_t octospi_frequency = LL_RCC_PERIPH_FREQUENCY_NO;
/* Check parameter */
assert_param(IS_LL_RCC_OCTOSPI_CLKSOURCE(OCTOSPIxSource));
/* OCTOSPI clock frequency */
switch (LL_RCC_GetOCTOSPIClockSource(OCTOSPIxSource))
{
case LL_RCC_OCTOSPI_CLKSOURCE_SYSCLK: /* OCTOSPI clock is SYSCLK */
octospi_frequency = RCC_GetSystemClockFreq();
break;
case LL_RCC_OCTOSPI_CLKSOURCE_MSI: /* MSI clock used as OCTOSPI clock */
if (LL_RCC_MSI_IsReady())
{
octospi_frequency = __LL_RCC_CALC_MSI_FREQ(LL_RCC_MSI_IsEnabledRangeSelect(),
(LL_RCC_MSI_IsEnabledRangeSelect() ?
LL_RCC_MSI_GetRange() :
LL_RCC_MSI_GetRangeAfterStandby()));
}
break;
case LL_RCC_OCTOSPI_CLKSOURCE_PLL: /* PLL clock used as OCTOSPI source */
if (LL_RCC_PLL_IsReady())
{
octospi_frequency = RCC_PLL_GetFreqDomain_48M();
}
break;
default:
octospi_frequency = LL_RCC_PERIPH_FREQUENCY_NO;
break;
}
return octospi_frequency;
}
#endif /* OCTOSPI1 */
/**
* @}
*/
/**
* @}
*/
/** @addtogroup RCC_LL_Private_Functions
* @{
*/
/**
* @brief Return SYSTEM clock frequency
* @retval SYSTEM clock frequency (in Hz)
*/
uint32_t RCC_GetSystemClockFreq(void)
{
uint32_t frequency = 0U;
/* Get SYSCLK source -------------------------------------------------------*/
switch (LL_RCC_GetSysClkSource())
{
case LL_RCC_SYS_CLKSOURCE_STATUS_MSI: /* MSI used as system clock source */
frequency = __LL_RCC_CALC_MSI_FREQ(LL_RCC_MSI_IsEnabledRangeSelect(),
(LL_RCC_MSI_IsEnabledRangeSelect() ?
LL_RCC_MSI_GetRange() :
LL_RCC_MSI_GetRangeAfterStandby()));
break;
case LL_RCC_SYS_CLKSOURCE_STATUS_HSI: /* HSI used as system clock source */
frequency = HSI_VALUE;
break;
case LL_RCC_SYS_CLKSOURCE_STATUS_HSE: /* HSE used as system clock source */
frequency = HSE_VALUE;
break;
case LL_RCC_SYS_CLKSOURCE_STATUS_PLL: /* PLL used as system clock source */
frequency = RCC_PLL_GetFreqDomain_SYS();
break;
default:
frequency = __LL_RCC_CALC_MSI_FREQ(LL_RCC_MSI_IsEnabledRangeSelect(),
(LL_RCC_MSI_IsEnabledRangeSelect() ?
LL_RCC_MSI_GetRange() :
LL_RCC_MSI_GetRangeAfterStandby()));
break;
}
return frequency;
}
/**
* @brief Return HCLK clock frequency
* @param SYSCLK_Frequency SYSCLK clock frequency
* @retval HCLK clock frequency (in Hz)
*/
uint32_t RCC_GetHCLKClockFreq(uint32_t SYSCLK_Frequency)
{
/* HCLK clock frequency */
return __LL_RCC_CALC_HCLK_FREQ(SYSCLK_Frequency, LL_RCC_GetAHBPrescaler());
}
/**
* @brief Return PCLK1 clock frequency
* @param HCLK_Frequency HCLK clock frequency
* @retval PCLK1 clock frequency (in Hz)
*/
uint32_t RCC_GetPCLK1ClockFreq(uint32_t HCLK_Frequency)
{
/* PCLK1 clock frequency */
return __LL_RCC_CALC_PCLK1_FREQ(HCLK_Frequency, LL_RCC_GetAPB1Prescaler());
}
/**
* @brief Return PCLK2 clock frequency
* @param HCLK_Frequency HCLK clock frequency
* @retval PCLK2 clock frequency (in Hz)
*/
uint32_t RCC_GetPCLK2ClockFreq(uint32_t HCLK_Frequency)
{
/* PCLK2 clock frequency */
return __LL_RCC_CALC_PCLK2_FREQ(HCLK_Frequency, LL_RCC_GetAPB2Prescaler());
}
/**
* @brief Return PLL clock frequency used for system domain
* @retval PLL clock frequency (in Hz)
*/
uint32_t RCC_PLL_GetFreqDomain_SYS(void)
{
uint32_t pllinputfreq = 0U, pllsource = 0U;
/* PLL_VCO = (HSE_VALUE or HSI_VALUE or MSI_VALUE/ PLLM) * PLLN
SYSCLK = PLL_VCO / PLLR
*/
pllsource = LL_RCC_PLL_GetMainSource();
switch (pllsource)
{
case LL_RCC_PLLSOURCE_MSI: /* MSI used as PLL clock source */
pllinputfreq = __LL_RCC_CALC_MSI_FREQ(LL_RCC_MSI_IsEnabledRangeSelect(),
(LL_RCC_MSI_IsEnabledRangeSelect() ?
LL_RCC_MSI_GetRange() :
LL_RCC_MSI_GetRangeAfterStandby()));
break;
case LL_RCC_PLLSOURCE_HSI: /* HSI used as PLL clock source */
pllinputfreq = HSI_VALUE;
break;
case LL_RCC_PLLSOURCE_HSE: /* HSE used as PLL clock source */
pllinputfreq = HSE_VALUE;
break;
default:
pllinputfreq = __LL_RCC_CALC_MSI_FREQ(LL_RCC_MSI_IsEnabledRangeSelect(),
(LL_RCC_MSI_IsEnabledRangeSelect() ?
LL_RCC_MSI_GetRange() :
LL_RCC_MSI_GetRangeAfterStandby()));
break;
}
return __LL_RCC_CALC_PLLCLK_FREQ(pllinputfreq, LL_RCC_PLL_GetDivider(),
LL_RCC_PLL_GetN(), LL_RCC_PLL_GetR());
}
/**
* @brief Return PLL clock frequency used for SAI domain
* @retval PLL clock frequency (in Hz)
*/
uint32_t RCC_PLL_GetFreqDomain_SAI(void)
{
uint32_t pllinputfreq = 0U, pllsource = 0U;
/* PLL_VCO = (HSE_VALUE or HSI_VALUE or MSI_VALUE / PLLM) * PLLN
SAI Domain clock = PLL_VCO / PLLP
*/
pllsource = LL_RCC_PLL_GetMainSource();
switch (pllsource)
{
case LL_RCC_PLLSOURCE_MSI: /* MSI used as PLL clock source */
pllinputfreq = __LL_RCC_CALC_MSI_FREQ(LL_RCC_MSI_IsEnabledRangeSelect(),
(LL_RCC_MSI_IsEnabledRangeSelect() ?
LL_RCC_MSI_GetRange() :
LL_RCC_MSI_GetRangeAfterStandby()));
break;
case LL_RCC_PLLSOURCE_HSI: /* HSI used as PLL clock source */
pllinputfreq = HSI_VALUE;
break;
case LL_RCC_PLLSOURCE_HSE: /* HSE used as PLL clock source */
pllinputfreq = HSE_VALUE;
break;
default:
pllinputfreq = __LL_RCC_CALC_MSI_FREQ(LL_RCC_MSI_IsEnabledRangeSelect(),
(LL_RCC_MSI_IsEnabledRangeSelect() ?
LL_RCC_MSI_GetRange() :
LL_RCC_MSI_GetRangeAfterStandby()));
break;
}
return __LL_RCC_CALC_PLLCLK_SAI_FREQ(pllinputfreq, LL_RCC_PLL_GetDivider(),
LL_RCC_PLL_GetN(), LL_RCC_PLL_GetP());
}
/**
* @brief Return PLL clock frequency used for 48 MHz domain
* @retval PLL clock frequency (in Hz)
*/
uint32_t RCC_PLL_GetFreqDomain_48M(void)
{
uint32_t pllinputfreq = 0U, pllsource = 0U;
/* PLL_VCO = (HSE_VALUE or HSI_VALUE or MSI_VALUE/ PLLM) * PLLN
48M Domain clock = PLL_VCO / PLLQ
*/
pllsource = LL_RCC_PLL_GetMainSource();
switch (pllsource)
{
case LL_RCC_PLLSOURCE_MSI: /* MSI used as PLL clock source */
pllinputfreq = __LL_RCC_CALC_MSI_FREQ(LL_RCC_MSI_IsEnabledRangeSelect(),
(LL_RCC_MSI_IsEnabledRangeSelect() ?
LL_RCC_MSI_GetRange() :
LL_RCC_MSI_GetRangeAfterStandby()));
break;
case LL_RCC_PLLSOURCE_HSI: /* HSI used as PLL clock source */
pllinputfreq = HSI_VALUE;
break;
case LL_RCC_PLLSOURCE_HSE: /* HSE used as PLL clock source */
pllinputfreq = HSE_VALUE;
break;
default:
pllinputfreq = __LL_RCC_CALC_MSI_FREQ(LL_RCC_MSI_IsEnabledRangeSelect(),
(LL_RCC_MSI_IsEnabledRangeSelect() ?
LL_RCC_MSI_GetRange() :
LL_RCC_MSI_GetRangeAfterStandby()));
break;
}
return __LL_RCC_CALC_PLLCLK_48M_FREQ(pllinputfreq, LL_RCC_PLL_GetDivider(),
LL_RCC_PLL_GetN(), LL_RCC_PLL_GetQ());
}
#if defined(DSI)
/**
* @brief Return PLL clock frequency used for DSI clock
* @retval PLL clock frequency (in Hz)
*/
uint32_t RCC_PLLSAI2_GetFreqDomain_DSI(void)
{
uint32_t pllinputfreq = 0U, pllsource = 0U;
/* PLLSAI2_VCO = (HSE_VALUE or HSI_VALUE or MSI_VALUE/ PLLSAI2M) * PLLSAI2N */
/* DSICLK = PLLSAI2_VCO / PLLSAI2R */
pllsource = LL_RCC_PLL_GetMainSource();
switch (pllsource)
{
case LL_RCC_PLLSOURCE_MSI: /* MSI used as PLLSAI2 clock source */
pllinputfreq = __LL_RCC_CALC_MSI_FREQ(LL_RCC_MSI_IsEnabledRangeSelect(),
(LL_RCC_MSI_IsEnabledRangeSelect() ?
LL_RCC_MSI_GetRange() :
LL_RCC_MSI_GetRangeAfterStandby()));
break;
case LL_RCC_PLLSOURCE_HSI: /* HSI used as PLLSAI2 clock source */
pllinputfreq = HSI_VALUE;
break;
case LL_RCC_PLLSOURCE_HSE: /* HSE used as PLLSAI2 clock source */
pllinputfreq = HSE_VALUE;
break;
default:
pllinputfreq = __LL_RCC_CALC_MSI_FREQ(LL_RCC_MSI_IsEnabledRangeSelect(),
(LL_RCC_MSI_IsEnabledRangeSelect() ?
LL_RCC_MSI_GetRange() :
LL_RCC_MSI_GetRangeAfterStandby()));
break;
}
return __LL_RCC_CALC_PLLSAI2_DSI_FREQ(pllinputfreq, LL_RCC_PLLSAI2_GetDivider(),
LL_RCC_PLLSAI2_GetN(), LL_RCC_PLLSAI2_GetR());
}
#endif /* DSI */
/**
* @brief Return PLLSAI1 clock frequency used for SAI domain
* @retval PLLSAI1 clock frequency (in Hz)
*/
uint32_t RCC_PLLSAI1_GetFreqDomain_SAI(void)
{
uint32_t pllinputfreq = 0U, pllsource = 0U;
#if defined(RCC_PLLSAI2M_DIV_1_16_SUPPORT)
/* PLLSAI1_VCO = (HSE_VALUE or HSI_VALUE or MSI_VALUE/ PLLSAI1M) * PLLSAI1N */
#else
/* PLLSAI1_VCO = (HSE_VALUE or HSI_VALUE or MSI_VALUE/ PLLM) * PLLSAI1N */
#endif
/* SAI Domain clock = PLLSAI1_VCO / PLLSAI1P */
pllsource = LL_RCC_PLL_GetMainSource();
switch (pllsource)
{
case LL_RCC_PLLSOURCE_MSI: /* MSI used as PLLSAI1 clock source */
pllinputfreq = __LL_RCC_CALC_MSI_FREQ(LL_RCC_MSI_IsEnabledRangeSelect(),
(LL_RCC_MSI_IsEnabledRangeSelect() ?
LL_RCC_MSI_GetRange() :
LL_RCC_MSI_GetRangeAfterStandby()));
break;
case LL_RCC_PLLSOURCE_HSI: /* HSI used as PLLSAI1 clock source */
pllinputfreq = HSI_VALUE;
break;
case LL_RCC_PLLSOURCE_HSE: /* HSE used as PLLSAI1 clock source */
pllinputfreq = HSE_VALUE;
break;
default:
pllinputfreq = __LL_RCC_CALC_MSI_FREQ(LL_RCC_MSI_IsEnabledRangeSelect(),
(LL_RCC_MSI_IsEnabledRangeSelect() ?
LL_RCC_MSI_GetRange() :
LL_RCC_MSI_GetRangeAfterStandby()));
break;
}
return __LL_RCC_CALC_PLLSAI1_SAI_FREQ(pllinputfreq, LL_RCC_PLL_GetDivider(),
LL_RCC_PLLSAI1_GetN(), LL_RCC_PLLSAI1_GetP());
}
/**
* @brief Return PLLSAI1 clock frequency used for 48Mhz domain
* @retval PLLSAI1 clock frequency (in Hz)
*/
uint32_t RCC_PLLSAI1_GetFreqDomain_48M(void)
{
uint32_t pllinputfreq = 0U, pllsource = 0U;
#if defined(RCC_PLLSAI2M_DIV_1_16_SUPPORT)
/* PLLSAI1_VCO = (HSE_VALUE or HSI_VALUE or MSI_VALUE/ PLLSAI1M) * PLLSAI1N */
#else
/* PLLSAI1_VCO = (HSE_VALUE or HSI_VALUE or MSI_VALUE/ PLLM) * PLLSAI1N */
#endif
/* 48M Domain clock = PLLSAI1_VCO / PLLSAI1Q */
pllsource = LL_RCC_PLL_GetMainSource();
switch (pllsource)
{
case LL_RCC_PLLSOURCE_MSI: /* MSI used as PLLSAI1 clock source */
pllinputfreq = __LL_RCC_CALC_MSI_FREQ(LL_RCC_MSI_IsEnabledRangeSelect(),
(LL_RCC_MSI_IsEnabledRangeSelect() ?
LL_RCC_MSI_GetRange() :
LL_RCC_MSI_GetRangeAfterStandby()));
break;
case LL_RCC_PLLSOURCE_HSI: /* HSI used as PLLSAI1 clock source */
pllinputfreq = HSI_VALUE;
break;
case LL_RCC_PLLSOURCE_HSE: /* HSE used as PLLSAI1 clock source */
pllinputfreq = HSE_VALUE;
break;
default:
pllinputfreq = __LL_RCC_CALC_MSI_FREQ(LL_RCC_MSI_IsEnabledRangeSelect(),
(LL_RCC_MSI_IsEnabledRangeSelect() ?
LL_RCC_MSI_GetRange() :
LL_RCC_MSI_GetRangeAfterStandby()));
break;
}
return __LL_RCC_CALC_PLLSAI1_48M_FREQ(pllinputfreq, LL_RCC_PLL_GetDivider(),
LL_RCC_PLLSAI1_GetN(), LL_RCC_PLLSAI1_GetQ());
}
/**
* @brief Return PLLSAI1 clock frequency used for ADC domain
* @retval PLLSAI1 clock frequency (in Hz)
*/
uint32_t RCC_PLLSAI1_GetFreqDomain_ADC(void)
{
uint32_t pllinputfreq = 0U, pllsource = 0U;
#if defined(RCC_PLLSAI2M_DIV_1_16_SUPPORT)
/* PLLSAI1_VCO = (HSE_VALUE or HSI_VALUE or MSI_VALUE/ PLLSAI1M) * PLLSAI1N */
#else
/* PLLSAI1_VCO = (HSE_VALUE or HSI_VALUE or MSI_VALUE/ PLLM) * PLLSAI1N */
#endif
/* 48M Domain clock = PLLSAI1_VCO / PLLSAI1R */
pllsource = LL_RCC_PLL_GetMainSource();
switch (pllsource)
{
case LL_RCC_PLLSOURCE_MSI: /* MSI used as PLLSAI1 clock source */
pllinputfreq = __LL_RCC_CALC_MSI_FREQ(LL_RCC_MSI_IsEnabledRangeSelect(),
(LL_RCC_MSI_IsEnabledRangeSelect() ?
LL_RCC_MSI_GetRange() :
LL_RCC_MSI_GetRangeAfterStandby()));
break;
case LL_RCC_PLLSOURCE_HSI: /* HSI used as PLLSAI1 clock source */
pllinputfreq = HSI_VALUE;
break;
case LL_RCC_PLLSOURCE_HSE: /* HSE used as PLLSAI1 clock source */
pllinputfreq = HSE_VALUE;
break;
default:
pllinputfreq = __LL_RCC_CALC_MSI_FREQ(LL_RCC_MSI_IsEnabledRangeSelect(),
(LL_RCC_MSI_IsEnabledRangeSelect() ?
LL_RCC_MSI_GetRange() :
LL_RCC_MSI_GetRangeAfterStandby()));
break;
}
return __LL_RCC_CALC_PLLSAI1_ADC_FREQ(pllinputfreq, LL_RCC_PLL_GetDivider(),
LL_RCC_PLLSAI1_GetN(), LL_RCC_PLLSAI1_GetR());
}
#if defined(RCC_PLLSAI2_SUPPORT)
/**
* @brief Return PLLSAI2 clock frequency used for SAI domain
* @retval PLLSAI2 clock frequency (in Hz)
*/
uint32_t RCC_PLLSAI2_GetFreqDomain_SAI(void)
{
uint32_t pllinputfreq = 0U, pllsource = 0U;
#if defined(RCC_PLLSAI2M_DIV_1_16_SUPPORT)
/* PLLSAI2_VCO = (HSE_VALUE or HSI_VALUE or MSI_VALUE/ PLLSAI2M) * PLLSAI2N */
#else
/* PLLSAI2_VCO = (HSE_VALUE or HSI_VALUE or MSI_VALUE/ PLLM) * PLLSAI2N */
#endif
/* SAI Domain clock = PLLSAI2_VCO / PLLSAI2P */
pllsource = LL_RCC_PLL_GetMainSource();
switch (pllsource)
{
case LL_RCC_PLLSOURCE_MSI: /* MSI used as PLLSAI2 clock source */
pllinputfreq = __LL_RCC_CALC_MSI_FREQ(LL_RCC_MSI_IsEnabledRangeSelect(),
(LL_RCC_MSI_IsEnabledRangeSelect() ?
LL_RCC_MSI_GetRange() :
LL_RCC_MSI_GetRangeAfterStandby()));
break;
case LL_RCC_PLLSOURCE_HSI: /* HSI used as PLLSAI2 clock source */
pllinputfreq = HSI_VALUE;
break;
case LL_RCC_PLLSOURCE_HSE: /* HSE used as PLLSAI2 clock source */
pllinputfreq = HSE_VALUE;
break;
default:
pllinputfreq = __LL_RCC_CALC_MSI_FREQ(LL_RCC_MSI_IsEnabledRangeSelect(),
(LL_RCC_MSI_IsEnabledRangeSelect() ?
LL_RCC_MSI_GetRange() :
LL_RCC_MSI_GetRangeAfterStandby()));
break;
}
#if defined(RCC_PLLSAI2M_DIV_1_16_SUPPORT)
return __LL_RCC_CALC_PLLSAI2_SAI_FREQ(pllinputfreq, LL_RCC_PLLSAI2_GetDivider(),
LL_RCC_PLLSAI2_GetN(), LL_RCC_PLLSAI2_GetP());
#else
return __LL_RCC_CALC_PLLSAI2_SAI_FREQ(pllinputfreq, LL_RCC_PLL_GetDivider(),
LL_RCC_PLLSAI2_GetN(), LL_RCC_PLLSAI2_GetP());
#endif
}
#if defined(LTDC)
/**
* @brief Return PLLSAI2 clock frequency used for LTDC domain
* @retval PLLSAI2 clock frequency (in Hz)
*/
uint32_t RCC_PLLSAI2_GetFreqDomain_LTDC(void)
{
uint32_t pllinputfreq = 0U, pllsource = 0U;
/* PLLSAI2_VCO = (HSE_VALUE or HSI_VALUE or MSI_VALUE/ PLLSAI2M) * PLLSAI2N */
/* LTDC Domain clock = (PLLSAI2_VCO / PLLSAI2R) / PLLSAI2DIVR */
pllsource = LL_RCC_PLL_GetMainSource();
switch (pllsource)
{
case LL_RCC_PLLSOURCE_MSI: /* MSI used as PLLSAI2 clock source */
pllinputfreq = __LL_RCC_CALC_MSI_FREQ(LL_RCC_MSI_IsEnabledRangeSelect(),
(LL_RCC_MSI_IsEnabledRangeSelect() ?
LL_RCC_MSI_GetRange() :
LL_RCC_MSI_GetRangeAfterStandby()));
break;
case LL_RCC_PLLSOURCE_HSI: /* HSI used as PLLSAI2 clock source */
pllinputfreq = HSI_VALUE;
break;
case LL_RCC_PLLSOURCE_HSE: /* HSE used as PLLSAI2 clock source */
pllinputfreq = HSE_VALUE;
break;
default:
pllinputfreq = __LL_RCC_CALC_MSI_FREQ(LL_RCC_MSI_IsEnabledRangeSelect(),
(LL_RCC_MSI_IsEnabledRangeSelect() ?
LL_RCC_MSI_GetRange() :
LL_RCC_MSI_GetRangeAfterStandby()));
break;
}
return __LL_RCC_CALC_PLLSAI2_LTDC_FREQ(pllinputfreq, LL_RCC_PLLSAI2_GetDivider(),
LL_RCC_PLLSAI2_GetN(), LL_RCC_PLLSAI2_GetR(), LL_RCC_PLLSAI2_GetDIVR());
}
#else
/**
* @brief Return PLLSAI2 clock frequency used for ADC domain
* @retval PLLSAI2 clock frequency (in Hz)
*/
uint32_t RCC_PLLSAI2_GetFreqDomain_ADC(void)
{
uint32_t pllinputfreq = 0U, pllsource = 0U;
/* PLLSAI2_VCO = (HSE_VALUE or HSI_VALUE or MSI_VALUE/ PLLM) * PLLSAI2N */
/* 48M Domain clock = PLLSAI2_VCO / PLLSAI2R */
pllsource = LL_RCC_PLL_GetMainSource();
switch (pllsource)
{
case LL_RCC_PLLSOURCE_MSI: /* MSI used as PLLSAI2 clock source */
pllinputfreq = __LL_RCC_CALC_MSI_FREQ(LL_RCC_MSI_IsEnabledRangeSelect(),
(LL_RCC_MSI_IsEnabledRangeSelect() ?
LL_RCC_MSI_GetRange() :
LL_RCC_MSI_GetRangeAfterStandby()));
break;
case LL_RCC_PLLSOURCE_HSI: /* HSI used as PLLSAI2 clock source */
pllinputfreq = HSI_VALUE;
break;
case LL_RCC_PLLSOURCE_HSE: /* HSE used as PLLSAI2 clock source */
pllinputfreq = HSE_VALUE;
break;
default:
pllinputfreq = __LL_RCC_CALC_MSI_FREQ(LL_RCC_MSI_IsEnabledRangeSelect(),
(LL_RCC_MSI_IsEnabledRangeSelect() ?
LL_RCC_MSI_GetRange() :
LL_RCC_MSI_GetRangeAfterStandby()));
break;
}
return __LL_RCC_CALC_PLLSAI2_ADC_FREQ(pllinputfreq, LL_RCC_PLL_GetDivider(),
LL_RCC_PLLSAI2_GetN(), LL_RCC_PLLSAI2_GetR());
}
#endif /* LTDC */
#endif /*RCC_PLLSAI2_SUPPORT*/
/**
* @}
*/
/**
* @}
*/
#endif /* defined(RCC) */
/**
* @}
*/
#endif /* USE_FULL_LL_DRIVER */
/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
|
the_stack_data/28261888.c | /*
* Copyright (C) Bull S.A. 2001
* Copyright (c) International Business Machines Corp., 2001
*
* 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 2 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, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
/******************************************************************************/
/* */
/* Dec-03-2001 Created: Jacky Malcles & Jean Noel Cordenner */
/* These tests are adapted from AIX float PVT tests. */
/* */
/******************************************************************************/
#include <float.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <limits.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include <sys/signal.h>
#include <math.h>
static int create_Result_file(void)
{
int i, nbVal;
double tabR[20000], Inc;
char *F_name;
int fp;
F_name = "y1_out.ref2";
nbVal = 20000;
Inc = sqrt(2);
for (i = 0; i < nbVal; i++)
tabR[i] = y1(Inc * i);
fp = open(F_name, O_RDWR | O_CREAT | O_TRUNC, 0777);
if (!fp) {
printf("error opening file");
close(fp);
return -1;
} else {
for (i = 0; i < nbVal; i++) {
write(fp, &tabR[i], sizeof(double));
}
close(fp);
return 0;
}
return (0);
}
static int create_Data_file(void)
{
int i, nbVal;
double tabD[20000], Inc;
char *F_name;
int fp;
F_name = "y1_inp.ref";
nbVal = 20000;
Inc = sqrt(2);
for (i = 0; i < nbVal; i++)
tabD[i] = (Inc * i);
fp = open(F_name, O_RDWR | O_CREAT | O_TRUNC, 0777);
if (!fp) {
printf("error opening file");
close(fp);
return -1;
} else {
for (i = 0; i < nbVal; i++) {
write(fp, &tabD[i], sizeof(double));
}
close(fp);
return 0;
}
return (0);
}
int main(int argc, char *argv[])
{
if (argc > 1) {
switch (atoi(argv[1])) {
case 1:
if (create_Data_file() == 0)
printf("Data file created\n");
else
printf("problem during %s data file creation\n",
argv[0]);
break;
case 2:
if (create_Result_file() == 0)
printf("Result file created\n");
else
printf
("problem during %s result file creation\n",
argv[0]);
break;
default:
printf("Bad arglist code for: '%s'\n", argv[0]);
return -1;
break;
}
} else {
if (create_Data_file() != 0)
printf("problem during %s data file creation\n",
argv[0]);
if (create_Result_file() != 0)
printf("problem during %s result file creation\n",
argv[0]);
}
return (0);
}
|
the_stack_data/153719.c | /*Escreva um código em C para gerar uma onda quadrada de 1 Hz em um pino GPIO do Raspberry Pi*/
#include <unistd.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
int fd;
void fechar(){
close(fd);
fd = open("/sys/class/gpio/unexport",O_WRONLY); //unexportanto o GPIO para n ter problemas.
write(fd,"16",2);
printf("Fechando programa\n");
close(fd);
sleep(1);
exit(0);
}
int main(){
//Sinal para fechar corretamente o programa.
signal(SIGINT,fechar);
//Setando como export
printf("Realizando o export\n");
fd = open("/sys/class/gpio/export",O_WRONLY);
write(fd,"4",2);
close(fd);
sleep(1);
//Setando como saída
printf("Iniciando o pin como saída\n");
fd = open("/sys/class/gpio/gpio4/direction",O_WRONLY);
write(fd,"out",4);
close(fd);
sleep(1);
fd = open("/sys/class/gpio/gpio4/value",O_WRONLY);
printf("Iniciando o blink\n");
/*Função que ira ficar sobescrevendo o gpio 4 acada 1/1s = 1hz */
while(1){
write(fd,"1",2);
usleep(500000); // 0.5s
write(fd,"0",2);
usleep(500000); // 0.5s
}
return 0;
}
|
the_stack_data/12638610.c | // Copyright (C) 2016 and later: Unicode, Inc. and others.
// License & terms of use: http://www.unicode.org/copyright.html
/*
********************************************************************************
* Copyright (C) 2005-2015, International Business Machines
* Corporation and others. All Rights Reserved.
********************************************************************************
*
* File WINTZ.CPP
*
********************************************************************************
*/
#include "unicode/utypes.h"
#if U_PLATFORM_HAS_WIN32_API
#include "wintz.h"
#include "cmemory.h"
#include "cstring.h"
#include "unicode/ures.h"
#include "unicode/ustring.h"
# define WIN32_LEAN_AND_MEAN
# define VC_EXTRALEAN
# define NOUSER
# define NOSERVICE
# define NOIME
# define NOMCX
#include <windows.h>
#define MAX_LENGTH_ID 40
/* The layout of the Tzi value in the registry */
typedef struct
{
int32_t bias;
int32_t standardBias;
int32_t daylightBias;
SYSTEMTIME standardDate;
SYSTEMTIME daylightDate;
} TZI;
/**
* Various registry keys and key fragments.
*/
static const char CURRENT_ZONE_REGKEY[] = "SYSTEM\\CurrentControlSet\\Control\\TimeZoneInformation\\";
/* static const char STANDARD_NAME_REGKEY[] = "StandardName"; Currently unused constant */
static const char STANDARD_TIME_REGKEY[] = " Standard Time";
static const char TZI_REGKEY[] = "TZI";
static const char STD_REGKEY[] = "Std";
/**
* HKLM subkeys used to probe for the flavor of Windows. Note that we
* specifically check for the "GMT" zone subkey; this is present on
* NT, but on XP has become "GMT Standard Time". We need to
* discriminate between these cases.
*/
static const char* const WIN_TYPE_PROBE_REGKEY[] = {
/* WIN_9X_ME_TYPE */
"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Time Zones",
/* WIN_NT_TYPE */
"SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Time Zones\\GMT"
/* otherwise: WIN_2K_XP_TYPE */
};
/**
* The time zone root subkeys (under HKLM) for different flavors of
* Windows.
*/
static const char* const TZ_REGKEY[] = {
/* WIN_9X_ME_TYPE */
"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Time Zones\\",
/* WIN_NT_TYPE | WIN_2K_XP_TYPE */
"SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Time Zones\\"
};
/**
* Flavor of Windows, from our perspective. Not a real OS version,
* but rather the flavor of the layout of the time zone information in
* the registry.
*/
enum {
WIN_9X_ME_TYPE = 1,
WIN_NT_TYPE = 2,
WIN_2K_XP_TYPE = 3
};
static int32_t gWinType = 0;
static int32_t detectWindowsType()
{
int32_t winType;
LONG result;
HKEY hkey;
/* Detect the version of windows by trying to open a sequence of
probe keys. We don't use the OS version API because what we
really want to know is how the registry is laid out.
Specifically, is it 9x/Me or not, and is it "GMT" or "GMT
Standard Time". */
for (winType = 0; winType < 2; winType++) {
result = RegOpenKeyExA(HKEY_LOCAL_MACHINE,
WIN_TYPE_PROBE_REGKEY[winType],
0,
KEY_QUERY_VALUE,
&hkey);
RegCloseKey(hkey);
if (result == ERROR_SUCCESS) {
break;
}
}
return winType+1; /* +1 to bring it inline with the enum */
}
static LONG openTZRegKey(HKEY *hkey, const char *winid)
{
char subKeyName[110]; /* TODO: why 96?? */
char *name;
LONG result;
/* This isn't thread safe, but it's good enough because the result should be constant per system. */
if (gWinType <= 0) {
gWinType = detectWindowsType();
}
uprv_strcpy(subKeyName, TZ_REGKEY[(gWinType != WIN_9X_ME_TYPE)]);
name = &subKeyName[strlen(subKeyName)];
uprv_strcat(subKeyName, winid);
if (gWinType == WIN_9X_ME_TYPE) {
/* Remove " Standard Time" */
char *pStd = uprv_strstr(subKeyName, STANDARD_TIME_REGKEY);
if (pStd) {
*pStd = 0;
}
}
result = RegOpenKeyExA(HKEY_LOCAL_MACHINE,
subKeyName,
0,
KEY_QUERY_VALUE,
hkey);
return result;
}
static LONG getTZI(const char *winid, TZI *tzi)
{
DWORD cbData = sizeof(TZI);
LONG result;
HKEY hkey;
result = openTZRegKey(&hkey, winid);
if (result == ERROR_SUCCESS) {
result = RegQueryValueExA(hkey,
TZI_REGKEY,
NULL,
NULL,
(LPBYTE)tzi,
&cbData);
}
RegCloseKey(hkey);
return result;
}
static LONG getSTDName(const char *winid, char *regStdName, int32_t length) {
DWORD cbData = length;
LONG result;
HKEY hkey;
result = openTZRegKey(&hkey, winid);
if (result == ERROR_SUCCESS) {
result = RegQueryValueExA(hkey,
STD_REGKEY,
NULL,
NULL,
(LPBYTE)regStdName,
&cbData);
}
RegCloseKey(hkey);
return result;
}
static LONG getTZKeyName(char* tzKeyName, int32_t length) {
HKEY hkey;
LONG result = FALSE;
DWORD cbData = length;
if(ERROR_SUCCESS == RegOpenKeyExA(
HKEY_LOCAL_MACHINE,
CURRENT_ZONE_REGKEY,
0,
KEY_QUERY_VALUE,
&hkey))
{
result = RegQueryValueExA(
hkey,
"TimeZoneKeyName",
NULL,
NULL,
(LPBYTE)tzKeyName,
&cbData);
}
return result;
}
/*
This code attempts to detect the Windows time zone, as set in the
Windows Date and Time control panel. It attempts to work on
multiple flavors of Windows (9x, Me, NT, 2000, XP) and on localized
installs. It works by directly interrogating the registry and
comparing the data there with the data returned by the
GetTimeZoneInformation API, along with some other strategies. The
registry contains time zone data under one of two keys (depending on
the flavor of Windows):
HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Time Zones\
HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Time Zones\
Under this key are several subkeys, one for each time zone. These
subkeys are named "Pacific" on Win9x/Me and "Pacific Standard Time"
on WinNT/2k/XP. There are some other wrinkles; see the code for
details. The subkey name is NOT LOCALIZED, allowing us to support
localized installs.
Under the subkey are data values. We care about:
Std Standard time display name, localized
TZI Binary block of data
The TZI data is of particular interest. It contains the offset, two
more offsets for standard and daylight time, and the start and end
rules. This is the same data returned by the GetTimeZoneInformation
API. The API may modify the data on the way out, so we have to be
careful, but essentially we do a binary comparison against the TZI
blocks of various registry keys. When we find a match, we know what
time zone Windows is set to. Since the registry key is not
localized, we can then translate the key through a simple table
lookup into the corresponding ICU time zone.
This strategy doesn't always work because there are zones which
share an offset and rules, so more than one TZI block will match.
For example, both Tokyo and Seoul are at GMT+9 with no DST rules;
their TZI blocks are identical. For these cases, we fall back to a
name lookup. We attempt to match the display name as stored in the
registry for the current zone to the display name stored in the
registry for various Windows zones. By comparing the registry data
directly we avoid conversion complications.
Author: Alan Liu
Since: ICU 2.6
Based on original code by Carl Brown <[email protected]>
*/
/**
* Main Windows time zone detection function. Returns the Windows
* time zone, translated to an ICU time zone, or NULL upon failure.
*/
U_CFUNC const char* U_EXPORT2
uprv_detectWindowsTimeZone() {
UErrorCode status = U_ZERO_ERROR;
UResourceBundle* bundle = NULL;
char* icuid = NULL;
char apiStdName[MAX_LENGTH_ID];
char regStdName[MAX_LENGTH_ID];
char tmpid[MAX_LENGTH_ID];
int32_t len;
int id;
int errorCode;
UChar ISOcodeW[3]; /* 2 letter iso code in UTF-16*/
char ISOcodeA[3]; /* 2 letter iso code in ansi */
LONG result;
TZI tziKey;
TZI tziReg;
TIME_ZONE_INFORMATION apiTZI;
BOOL isVistaOrHigher;
BOOL tryPreVistaFallback;
OSVERSIONINFO osVerInfo;
/* Obtain TIME_ZONE_INFORMATION from the API, and then convert it
to TZI. We could also interrogate the registry directly; we do
this below if needed. */
uprv_memset(&apiTZI, 0, sizeof(apiTZI));
uprv_memset(&tziKey, 0, sizeof(tziKey));
uprv_memset(&tziReg, 0, sizeof(tziReg));
GetTimeZoneInformation(&apiTZI);
tziKey.bias = apiTZI.Bias;
uprv_memcpy((char *)&tziKey.standardDate, (char*)&apiTZI.StandardDate,
sizeof(apiTZI.StandardDate));
uprv_memcpy((char *)&tziKey.daylightDate, (char*)&apiTZI.DaylightDate,
sizeof(apiTZI.DaylightDate));
/* Convert the wchar_t* standard name to char* */
uprv_memset(apiStdName, 0, sizeof(apiStdName));
wcstombs(apiStdName, apiTZI.StandardName, MAX_LENGTH_ID);
tmpid[0] = 0;
id = GetUserGeoID(GEOCLASS_NATION);
errorCode = GetGeoInfoW(id,GEO_ISO2,ISOcodeW,3,0);
u_strToUTF8(ISOcodeA, 3, NULL, ISOcodeW, 3, &status);
bundle = ures_openDirect(NULL, "windowsZones", &status);
ures_getByKey(bundle, "mapTimezones", bundle, &status);
/*
Windows Vista+ provides us with a "TimeZoneKeyName" that is not localized
and can be used to directly map a name in our bundle. Try to use that first
if we're on Vista or higher
*/
uprv_memset(&osVerInfo, 0, sizeof(osVerInfo));
osVerInfo.dwOSVersionInfoSize = sizeof(osVerInfo);
GetVersionEx(&osVerInfo);
isVistaOrHigher = osVerInfo.dwMajorVersion >= 6; /* actually includes Windows Server 2008 as well, but don't worry about it */
tryPreVistaFallback = TRUE;
if(isVistaOrHigher) {
result = getTZKeyName(regStdName, sizeof(regStdName));
if(ERROR_SUCCESS == result) {
UResourceBundle* winTZ = ures_getByKey(bundle, regStdName, NULL, &status);
if(U_SUCCESS(status)) {
const UChar* icuTZ = NULL;
if (errorCode != 0) {
icuTZ = ures_getStringByKey(winTZ, ISOcodeA, &len, &status);
}
if (errorCode==0 || icuTZ==NULL) {
/* fallback to default "001" and reset status */
status = U_ZERO_ERROR;
icuTZ = ures_getStringByKey(winTZ, "001", &len, &status);
}
if(U_SUCCESS(status)) {
int index=0;
while (! (*icuTZ == '\0' || *icuTZ ==' ')) {
tmpid[index++]=(char)(*icuTZ++); /* safe to assume 'char' is ASCII compatible on windows */
}
tmpid[index]='\0';
tryPreVistaFallback = FALSE;
}
}
ures_close(winTZ);
}
}
if(tryPreVistaFallback) {
/* Note: We get the winid not from static tables but from resource bundle. */
while (U_SUCCESS(status) && ures_hasNext(bundle)) {
UBool idFound = FALSE;
const char* winid;
UResourceBundle* winTZ = ures_getNextResource(bundle, NULL, &status);
if (U_FAILURE(status)) {
break;
}
winid = ures_getKey(winTZ);
result = getTZI(winid, &tziReg);
if (result == ERROR_SUCCESS) {
/* Windows alters the DaylightBias in some situations.
Using the bias and the rules suffices, so overwrite
these unreliable fields. */
tziKey.standardBias = tziReg.standardBias;
tziKey.daylightBias = tziReg.daylightBias;
if (uprv_memcmp((char *)&tziKey, (char*)&tziReg, sizeof(tziKey)) == 0) {
const UChar* icuTZ = NULL;
if (errorCode != 0) {
icuTZ = ures_getStringByKey(winTZ, ISOcodeA, &len, &status);
}
if (errorCode==0 || icuTZ==NULL) {
/* fallback to default "001" and reset status */
status = U_ZERO_ERROR;
icuTZ = ures_getStringByKey(winTZ, "001", &len, &status);
}
if (U_SUCCESS(status)) {
/* Get the standard name from the registry key to compare with
the one from Windows API call. */
uprv_memset(regStdName, 0, sizeof(regStdName));
result = getSTDName(winid, regStdName, sizeof(regStdName));
if (result == ERROR_SUCCESS) {
if (uprv_strcmp(apiStdName, regStdName) == 0) {
idFound = TRUE;
}
}
/* tmpid buffer holds the ICU timezone ID corresponding to the timezone ID from Windows.
* If none is found, tmpid buffer will contain a fallback ID (i.e. the time zone ID matching
* the current time zone information)
*/
if (idFound || tmpid[0] == 0) {
/* if icuTZ has more than one city, take only the first (i.e. terminate icuTZ at first space) */
int index=0;
while (! (*icuTZ == '\0' || *icuTZ ==' ')) {
tmpid[index++]=(char)(*icuTZ++); /* safe to assume 'char' is ASCII compatible on windows */
}
tmpid[index]='\0';
}
}
}
}
ures_close(winTZ);
if (idFound) {
break;
}
}
}
/*
* Copy the timezone ID to icuid to be returned.
*/
if (tmpid[0] != 0) {
len = uprv_strlen(tmpid);
icuid = (char*)uprv_calloc(len + 1, sizeof(char));
if (icuid != NULL) {
uprv_strcpy(icuid, tmpid);
}
}
ures_close(bundle);
return icuid;
}
#endif /* U_PLATFORM_HAS_WIN32_API */
|
the_stack_data/532573.c | /*
* Copyright (C) 2014 Freie Universität Berlin
*
* This file is subject to the terms and conditions of the GNU Lesser
* General Public License v2.1. See the file LICENSE in the top level
* directory for more details.
*/
/**
* @file
* @brief Check if the libcoap package builds.
*
* @author Ludwig Knüpfer <[email protected]>
*
*/
#include <stdio.h>
int main(void)
{
puts("SUCCESS: Libcoap compiled!");
return 0;
}
|
the_stack_data/54825478.c | /*******************************************************************************
* Copyright 2017 ROBOTIS CO., LTD.
*
* 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.
*******************************************************************************/
/* Author: Ryu Woon Jung (Leon) */
#if defined(_WIN32) || defined(_WIN64)
#include <stdio.h>
#include <string.h>
#include <time.h>
#include "port_handler_windows.h"
#define LATENCY_TIMER 16 // msec (USB latency timer)
// You should adjust the latency timer value. In Windows, the default latency timer of the usb serial is '16 msec'.
// When you are going to use sync / bulk read, the latency timer should be loosen.
// the lower latency timer value, the faster communication speed.
// Note:
// You can either checking or changing its value by:
// [Device Manager] -> [Port (COM & LPT)] -> the port you use but starts with COMx-> mouse right click -> properties
// -> [port settings] -> [details] -> change response time from 16 to the value you need
typedef struct
{
HANDLE serial_handle;
LARGE_INTEGER freq, counter;
int baudrate;
char port_name[100];
double packet_start_time;
double packet_timeout;
double tx_time_per_byte;
}PortData;
static PortData *portData;
int portHandlerWindows(const char *port_name)
{
int port_num;
char buffer[15];
sprintf_s(buffer, sizeof(buffer), "\\\\.\\%s", port_name);
if (portData == NULL)
{
port_num = 0;
g_used_port_num = 1;
portData = (PortData*)calloc(1, sizeof(PortData));
g_is_using = (uint8_t*)calloc(1, sizeof(uint8_t));
}
else
{
for (port_num = 0; port_num < g_used_port_num; port_num++)
{
if (!strcmp(portData[port_num].port_name, buffer))
break;
}
if (port_num == g_used_port_num)
{
for (port_num = 0; port_num < g_used_port_num; port_num++)
{
if (portData[port_num].serial_handle != INVALID_HANDLE_VALUE)
break;
}
if (port_num == g_used_port_num)
{
g_used_port_num++;
portData = (PortData*)realloc(portData, g_used_port_num * sizeof(PortData));
g_is_using = (uint8_t*)realloc(g_is_using, g_used_port_num * sizeof(uint8_t));
}
}
else
{
printf("[PortHandler setup] The port number %d has same device name... reinitialize port number %d!!\n", port_num, port_num);
}
}
portData[port_num].serial_handle = INVALID_HANDLE_VALUE;
portData[port_num].baudrate = DEFAULT_BAUDRATE;
portData[port_num].packet_start_time = 0.0;
portData[port_num].packet_timeout = 0.0;
portData[port_num].tx_time_per_byte = 0.0;
g_is_using[port_num] = False;
setPortNameWindows(port_num, buffer);
return port_num;
}
uint8_t openPortWindows(int port_num)
{
return setBaudRateWindows(port_num, portData[port_num].baudrate);
}
void closePortWindows(int port_num)
{
if (portData[port_num].serial_handle != INVALID_HANDLE_VALUE)
{
CloseHandle(portData[port_num].serial_handle);
portData[port_num].serial_handle = INVALID_HANDLE_VALUE;
}
}
void clearPortWindows(int port_num)
{
PurgeComm(portData[port_num].serial_handle, PURGE_RXABORT | PURGE_RXCLEAR);
}
void setPortNameWindows(int port_num, const char *port_name)
{
strcpy_s(portData[port_num].port_name, sizeof(portData[port_num].port_name), port_name);
}
char *getPortNameWindows(int port_num)
{
return portData[port_num].port_name;
}
uint8_t setBaudRateWindows(int port_num, const int baudrate)
{
closePortWindows(port_num);
portData[port_num].baudrate = baudrate;
return setupPortWindows(port_num, baudrate);
}
int getBaudRateWindows(int port_num)
{
return portData[port_num].baudrate;
}
int readPortWindows(int port_num, uint8_t *packet, int length)
{
DWORD dwRead = 0;
if (ReadFile(portData[port_num].serial_handle, packet, (DWORD)length, &dwRead, NULL) == FALSE)
return -1;
return (int)dwRead;
}
int writePortWindows(int port_num, uint8_t *packet, int length)
{
DWORD dwWrite = 0;
if (WriteFile(portData[port_num].serial_handle, packet, (DWORD)length, &dwWrite, NULL) == FALSE)
return -1;
return (int)dwWrite;
}
void setPacketTimeoutWindows(int port_num, uint16_t packet_length)
{
portData[port_num].packet_start_time = getCurrentTimeWindows(port_num);
portData[port_num].packet_timeout = (portData[port_num].tx_time_per_byte * (double)packet_length) + (LATENCY_TIMER * 2.0) + 2.0;
}
void setPacketTimeoutMSecWindows(int port_num, double msec)
{
portData[port_num].packet_start_time = getCurrentTimeWindows(port_num);
portData[port_num].packet_timeout = msec;
}
uint8_t isPacketTimeoutWindows(int port_num)
{
if (getTimeSinceStartWindows(port_num) > portData[port_num].packet_timeout)
{
portData[port_num].packet_timeout = 0;
return True;
}
return False;
}
double getCurrentTimeWindows(int port_num)
{
QueryPerformanceCounter(&portData[port_num].counter);
QueryPerformanceFrequency(&portData[port_num].freq);
return (double)portData[port_num].counter.QuadPart / (double)portData[port_num].freq.QuadPart * 1000.0;
}
double getTimeSinceStartWindows(int port_num)
{
double time_since_start;
time_since_start = getCurrentTimeWindows(port_num) - portData[port_num].packet_start_time;
if (time_since_start < 0.0)
portData[port_num].packet_start_time = getCurrentTimeWindows(port_num);
return time_since_start;
}
uint8_t setupPortWindows(int port_num, const int baudrate)
{
DCB dcb;
COMMTIMEOUTS timeouts;
DWORD dwError;
closePortWindows(port_num);
portData[port_num].serial_handle = CreateFileA(portData[port_num].port_name, GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
if (portData[port_num].serial_handle == INVALID_HANDLE_VALUE)
{
printf("[PortHandlerWindows::SetupPort] Error opening serial port!\n");
return False;
}
dcb.DCBlength = sizeof(DCB);
if (GetCommState(portData[port_num].serial_handle, &dcb) == FALSE)
goto DXL_HAL_OPEN_ERROR;
// Set baudrate
dcb.BaudRate = (DWORD)baudrate;
dcb.ByteSize = 8; // Data bit = 8bit
dcb.Parity = NOPARITY; // No parity
dcb.StopBits = ONESTOPBIT; // Stop bit = 1
dcb.fParity = NOPARITY; // No Parity check
dcb.fBinary = 1; // Binary mode
dcb.fNull = 0; // Get Null byte
dcb.fAbortOnError = 0;
dcb.fErrorChar = 0;
// Not using XOn/XOff
dcb.fOutX = 0;
dcb.fInX = 0;
// Not using H/W flow control
dcb.fDtrControl = DTR_CONTROL_DISABLE;
dcb.fRtsControl = RTS_CONTROL_DISABLE;
dcb.fDsrSensitivity = 0;
dcb.fOutxDsrFlow = 0;
dcb.fOutxCtsFlow = 0;
if (SetCommState(portData[port_num].serial_handle, &dcb) == FALSE)
goto DXL_HAL_OPEN_ERROR;
if (SetCommMask(portData[port_num].serial_handle, 0) == FALSE) // Not using Comm event
goto DXL_HAL_OPEN_ERROR;
if (SetupComm(portData[port_num].serial_handle, 4096, 4096) == FALSE) // Buffer size (Rx,Tx)
goto DXL_HAL_OPEN_ERROR;
if (PurgeComm(portData[port_num].serial_handle, PURGE_TXABORT | PURGE_TXCLEAR | PURGE_RXABORT | PURGE_RXCLEAR) == FALSE) // Clear buffer
goto DXL_HAL_OPEN_ERROR;
if (ClearCommError(portData[port_num].serial_handle, &dwError, NULL) == FALSE)
goto DXL_HAL_OPEN_ERROR;
if (GetCommTimeouts(portData[port_num].serial_handle, &timeouts) == FALSE)
goto DXL_HAL_OPEN_ERROR;
// Timeout (Not using timeout)
// Immediatly return
timeouts.ReadIntervalTimeout = 0;
timeouts.ReadTotalTimeoutMultiplier = 0;
timeouts.ReadTotalTimeoutConstant = 1; // must not be zero.
timeouts.WriteTotalTimeoutMultiplier = 0;
timeouts.WriteTotalTimeoutConstant = 0;
if (SetCommTimeouts(portData[port_num].serial_handle, &timeouts) == FALSE)
goto DXL_HAL_OPEN_ERROR;
portData[port_num].tx_time_per_byte = (1000.0 / (double)portData[port_num].baudrate) * 10.0;
return True;
DXL_HAL_OPEN_ERROR:
closePortWindows(port_num);
return False;
}
#endif
|
the_stack_data/755067.c | // minitest.c
// A minimal, single-header test suite, along with demonstration code for its
// usage. This code requires at least C99 or C++98 to run.
// Author: Dénes Fintha
// Year: 2022
// -------------------------------------------------------------------------- //
// Interface
#if !defined(MINITEST_HEADER_VERSION)
#define MINITEST_HEADER_VERSION 1
#include <float.h>
#include <math.h>
#include <stdarg.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef bool(*minitest_test_case)(void *user_data);
typedef void(*minitest_setup_function)(void *user_data);
typedef void(*minitest_teardown_function)(void *user_data);
#define minitest_str(s) #s
#define minitest_xstr(s) minitest_str(s)
static void * const minitest_no_user_data = NULL;
static minitest_setup_function const minitest_no_setup_fn = NULL;
static minitest_teardown_function const minitest_no_teardown_fn = NULL;
#define minitest_assert_internal(criteria, file, line, fn, msg, ...) \
do { \
if (!(criteria)) { \
printf("failed\n"); \
printf(" error: "); \
printf(msg, __VA_ARGS__); \
printf("\n at %s:%d", file, line); \
printf("\n in %s\n", fn); \
return false; \
} \
} while (false)
#define minitest_assert_unreachable() \
minitest_assert_internal( \
false, \
__FILE__, \
__LINE__, \
__func__, \
"%s", \
"unreachable code reached" \
)
#define minitest_assert_intcompare(int1, rel, int2) \
minitest_assert_internal( \
int1 rel int2, \
__FILE__, \
__LINE__, \
__func__, \
"integer comparison failed (%d " minitest_xstr(rel) " %d)", \
int1, int2 \
)
#define minitest_assert_fltcompare(flt1, rel, flt2, eps) \
minitest_assert_internal( \
(fabs(flt1 - flt2) < eps) rel true, \
__FILE__, \
__LINE__, \
__func__, \
"floating-point comparison failed (%f " minitest_xstr(rel) " %f)", \
flt1, flt2 \
)
#define minitest_assert_strcompare(str1, rel, str2) \
minitest_assert_internal( \
strcmp(str1, str2) rel 0, \
__FILE__, \
__LINE__, \
__func__, \
"string comparison failed (\"%s\" " minitest_xstr(rel) " \"%s\")", \
str1, str2 \
)
#define minitest_assert_objcompare(obj1, rel, obj2, cmp) \
minitest_assert_internal( \
cmp(obj1, obj2) rel true, \
__FILE__, \
__LINE__, \
__func__, \
"%s", \
"object comparison failed" \
)
#define minitest_assert_that(expr) \
minitest_assert_internal( \
expr, \
__FILE__, \
__LINE__, \
__func__, \
"%s", \
"assertion failed (" minitest_xstr(expr) ")" \
)
#define minitest_test_case(name) \
minitest_xstr(name), name
static void
minitest_run_test_group(
const char *test_group_name,
minitest_setup_function setup,
minitest_teardown_function teardown,
void *user_data,
...
)
{
va_list list;
va_start(list, user_data);
const char *current_name = NULL;
minitest_test_case current_test = NULL;
printf("\nrunning test group '%s'\n", test_group_name);
size_t counter = 0;
size_t failed_counter = 0;
while (true) {
if (counter % 2 == 0) {
current_name = va_arg(list, const char *);
if (current_name == NULL)
break;
} else {
current_test = va_arg(list, minitest_test_case);
if (current_test == NULL)
break;
printf(" %s/%s: ", test_group_name, current_name);
if (setup != NULL)
setup(user_data);
const bool result = current_test(user_data);
if (teardown != NULL)
teardown(user_data);
if (result) {
printf("passed\n");
} else {
++failed_counter;
}
}
++counter;
}
va_end(list);
if (failed_counter == 0) {
printf("all tests passed\n\n");
} else {
printf("%ld of %ld tests failed\n\n", failed_counter, counter / 2);
}
}
#endif /* MINITEST_HEADER_VERSION */
// Demonstration
typedef struct {
int a;
double b;
} fixture_t;
void fixture_setup(void *user_data) {
fixture_t *fixture = (fixture_t *) user_data;
fixture->a = 42;
fixture->b = 3.14;
}
void fixture_teardown(void *user_data) {
(void)(user_data);
}
bool fixture_compare(fixture_t *lhs, fixture_t *rhs) {
return (lhs->a == rhs->a) && ((lhs->b - rhs->b) < DBL_EPSILON);
}
bool check_setup_and_object_comparison(void *user_data) {
fixture_t reference = { .a = 42, .b = 3.14 };
fixture_t *fixture = (fixture_t *) user_data;
minitest_assert_objcompare(fixture, ==, &reference, fixture_compare);
return true;
minitest_assert_unreachable();
}
bool check_primitive_comparison(void *user_data) {
(void)(user_data);
minitest_assert_intcompare(1, ==, 1);
minitest_assert_fltcompare(3.14, ==, 3.14, FLT_EPSILON);
minitest_assert_strcompare("testing", ==, "testing");
return true;
}
bool check_test_failure_with_custom_assertion(void *user_data) {
(void)(user_data);
minitest_assert_that((1 > 3.14 && "test") || false);
}
int main(void) {
fixture_t fixture;
minitest_run_test_group(
"minitest_test_with_fixture",
fixture_setup,
fixture_teardown,
&fixture,
minitest_test_case(check_setup_and_object_comparison),
minitest_test_case(check_setup_and_object_comparison),
NULL
);
minitest_run_test_group(
"minitest_test_without_fixture",
minitest_no_setup_fn,
minitest_no_teardown_fn,
minitest_no_user_data,
minitest_test_case(check_primitive_comparison),
minitest_test_case(check_test_failure_with_custom_assertion),
NULL
);
return 0;
}
|
the_stack_data/57951280.c | #include <stdio.h>
#include <stdlib.h>
static double findMedianSortedArrays(int* nums1, int nums1Size, int* nums2, int nums2Size)
{
int sum = nums1Size + nums2Size;
int *nums = malloc(sizeof(int) * sum);
int i = 0, j = 0, k = 0;
int half = sum / 2 + 1;
while (k < half) {
int n;
if (i < nums1Size && j < nums2Size) {
n = (nums1[i] < nums2[j]) ? nums1[i++] : nums2[j++];
} else if (i < nums1Size) {
n = nums1[i++];
} else if (j < nums2Size) {
n = nums2[j++];
}
nums[k++] = n;
}
if (sum % 2) {
return nums[k-1];
} else {
return (nums[k-1] + nums[k-2]) / 2.0;
}
}
int main(int argc, char **argv)
{
int r1[] = {1};
int r2[] = {2};
int n1 = sizeof(r1)/sizeof(r1[0]);
int n2 = sizeof(r2)/sizeof(r2[0]);
printf("Median is 1.5 = %f\n", findMedianSortedArrays(r1, n1, r2, n2));
int ar1[] = {1, 12, 15, 26, 38};
int ar2[] = {2, 13, 17, 30, 45, 50};
n1 = sizeof(ar1)/sizeof(ar1[0]);
n2 = sizeof(ar2)/sizeof(ar2[0]);
printf("Median is 17 = %f\n", findMedianSortedArrays(ar1, n1, ar2, n2));
int ar11[] = {1, 12, 15, 26, 38};
int ar21[] = {2, 13, 17, 30, 45 };
n1 = sizeof(ar11)/sizeof(ar11[0]);
n2 = sizeof(ar21)/sizeof(ar21[0]);
printf("Median is 16 = %f\n", findMedianSortedArrays(ar11, n1, ar21, n2));
int a1[] = {1, 2, 5, 6, 8 };
int a2[] = {13, 17, 30, 45, 50};
n1 = sizeof(a1)/sizeof(a1[0]);
n2 = sizeof(a2)/sizeof(a2[0]);
printf("Median is 10.5 = %f\n", findMedianSortedArrays(a1, n1, a2, n2));
int a10[] = {1, 2, 5, 6, 8, 9, 10 };
int a20[] = {13, 17, 30, 45, 50};
n1 = sizeof(a10)/sizeof(a10[0]);
n2 = sizeof(a20)/sizeof(a20[0]);
printf("Median is 9.5 = %f\n", findMedianSortedArrays(a10, n1, a20, n2));
int a11[] = {1, 2, 5, 6, 8, 9 };
int a21[] = {13, 17, 30, 45, 50};
n1 = sizeof(a11)/sizeof(a11[0]);
n2 = sizeof(a21)/sizeof(a21[0]);
printf("Median is 9 = %f\n", findMedianSortedArrays(a11, n1, a21, n2));
int a12[] = {1, 2, 5, 6, 8 };
int a22[] = {11, 13, 17, 30, 45, 50};
return 0;
}
|
the_stack_data/2027.c | /* This file is part of the YAZ toolkit.
* Copyright (C) Index Data
* See the file LICENSE for details.
*/
/**
* \file
* \brief UTF-16 string utilities for ICU
*/
#if HAVE_CONFIG_H
#include "config.h"
#endif
#if YAZ_HAVE_ICU
#include <yaz/xmalloc.h>
#include <yaz/icu_I18N.h>
#include <yaz/log.h>
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <assert.h>
#include <unicode/ustring.h> /* some more string fcns*/
#include <unicode/uchar.h> /* char names */
struct icu_buf_utf16 *icu_buf_utf16_create(size_t capacity)
{
struct icu_buf_utf16 *buf16
= (struct icu_buf_utf16 *) xmalloc(sizeof(struct icu_buf_utf16));
buf16->utf16_len = 0;
buf16->utf16_cap = capacity;
if (capacity > 0)
{
buf16->utf16 = (UChar *) xmalloc(sizeof(UChar) * capacity);
buf16->utf16[0] = (UChar) 0;
}
else
buf16->utf16 = 0;
return buf16;
}
struct icu_buf_utf16 *icu_buf_utf16_clear(struct icu_buf_utf16 *buf16)
{
assert(buf16);
if (buf16->utf16)
buf16->utf16[0] = (UChar) 0;
buf16->utf16_len = 0;
return buf16;
}
struct icu_buf_utf16 *icu_buf_utf16_resize(struct icu_buf_utf16 *buf16,
size_t capacity)
{
assert(buf16);
if (capacity > 0)
{
if (0 == buf16->utf16)
buf16->utf16 = (UChar *) xmalloc(sizeof(UChar) * capacity);
else
buf16->utf16
= (UChar *) xrealloc(buf16->utf16, sizeof(UChar) * capacity);
buf16->utf16_cap = capacity;
}
return buf16;
}
struct icu_buf_utf16 *icu_buf_utf16_copy(struct icu_buf_utf16 *dest16,
const struct icu_buf_utf16 *src16)
{
if (!dest16 || !src16 || dest16 == src16)
return 0;
if (dest16->utf16_cap < src16->utf16_len)
icu_buf_utf16_resize(dest16, src16->utf16_len * 2);
u_strncpy(dest16->utf16, src16->utf16, src16->utf16_len);
dest16->utf16_len = src16->utf16_len;
return dest16;
}
struct icu_buf_utf16 *icu_buf_utf16_append(struct icu_buf_utf16 *dest16,
const struct icu_buf_utf16 *src16)
{
assert(dest16);
if (!src16)
return dest16;
if (dest16 == src16)
return 0;
if (dest16->utf16_cap <= src16->utf16_len + dest16->utf16_len)
icu_buf_utf16_resize(dest16, dest16->utf16_len + src16->utf16_len * 2);
u_strncpy(dest16->utf16 + dest16->utf16_len,
src16->utf16, src16->utf16_len);
dest16->utf16_len += src16->utf16_len;
return dest16;
}
void icu_buf_utf16_destroy(struct icu_buf_utf16 *buf16)
{
if (buf16)
xfree(buf16->utf16);
xfree(buf16);
}
void icu_buf_utf16_log(const char *lead, struct icu_buf_utf16 *src16)
{
if (src16)
{
struct icu_buf_utf8 *dst8 = icu_buf_utf8_create(0);
UErrorCode status = U_ZERO_ERROR;
icu_utf16_to_utf8(dst8, src16, &status);
yaz_log(YLOG_LOG, "%s=%s", lead, dst8->utf8);
icu_buf_utf8_destroy(dst8);
}
else
{
yaz_log(YLOG_LOG, "%s=NULL", lead);
}
}
#endif /* YAZ_HAVE_ICU */
/*
* Local variables:
* c-basic-offset: 4
* c-file-style: "Stroustrup"
* indent-tabs-mode: nil
* End:
* vim: shiftwidth=4 tabstop=8 expandtab
*/
|
the_stack_data/474802.c | int main() {
int c = 0, sum = 0;
if(c == 0) sum=sum+10; else sum=sum+11;
if(c == 0) sum=sum+20; else sum=sum+21;
if(c == 0) sum=sum+30; else sum=sum+31;
if(c == 0) sum=sum+40; else sum=sum+41;
if(c == 0) sum=sum+50; else sum=sum+51;
if(c == 0) sum=sum+60; else sum=sum+61;
if(c == 0) sum=sum+70; else sum=sum+71;
if(c == 0) sum=sum+80; else sum=sum+81;
if(c == 0) sum=sum+90; else sum=sum+91;
if(c == 0) sum=sum+100; else sum=sum+101;
if(c == 0) sum=sum+110; else sum=sum+111;
if(c == 0) sum=sum+120; else sum=sum+121;
_ABORT(sum == 808);
return 0;
}
|
the_stack_data/152491.c | #include <curses.h>
#include <stddef.h>
int meta(WINDOW * win, bool bf)
{
return ERR;
}
/*
XOPEN(400)
LINK(curses)
*/
|
the_stack_data/57950108.c | #include <assert.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <time.h>
#include <stdlib.h>
#include <stdarg.h>
#include <sys/sysinfo.h>
#include <limits.h>
#include <sys/types.h>
#include <ifaddrs.h>
#include <net/if.h>
#include <sys/socket.h>
#include <netdb.h>
#define LIKELY(b) __builtin_expect(!!(b), 1)
#define UNLIKELY(b) __builtin_expect(!!(b), 0)
#define free(x) free((void *)(x))
static void
print_header(void)
{
puts("{\"version\":1}\n[");
}
struct section_data {
const char *name;
const char *instance;
const char *color;
const char *full_text;
const char *short_text;
const char *min_width;
int separator_block_width;
int disabled;
enum {
URGENT_DEFAULT = 0,
URGENT_YES,
URGENT_NO
} urgent;
enum {
SEPARATOR_DEFAULT = 0,
SEPARATOR_YES,
SEPARATOR_NO
} separator;
enum {
ALIGN_DEFAULT = 0,
ALIGN_LEFT,
ALIGN_CENTER,
ALIGN_RIGHT
} align;
enum {
MARKUP_DEFAULT = 0,
MARKUP_NONE,
MARKUP_PANGO
} markup;
};
typedef int (*section_func)(struct section_data *);
static int
sprintf_s(char **text, const char *fmt, ...)
{
int err, len;
va_list vl;
va_start(vl, fmt);
len = vsnprintf(*text, 0, fmt, vl);
if (len < 0) {
return -1;
}
va_end(vl);
++len;
*text = malloc((unsigned int)len * sizeof(**text));
if (*text == NULL) {
return -1;
}
va_start(vl, fmt);
err = vsnprintf(*text, (unsigned int)len, fmt, vl);
if (err < len - 1) {
free(*text);
*text = NULL;
return -1;
}
va_end(vl);
return 0;
}
static void
tz(void)
{
static int b = 1;
if (UNLIKELY(b)) {
tzset();
b = 0;
}
}
static int
datetime(struct section_data *data)
{
time_t t;
struct tm tm;
char *text;
int err;
t = time(NULL);
if (t == (time_t)-1) {
return -1;
}
tz();
if (localtime_r(&t, &tm) == NULL) {
return -1;
}
err = sprintf_s(&text, "%04d-%02d-%02d %02d:%02d:%02d", tm.tm_year + 1900,
tm.tm_mon + 1, tm.tm_mday, tm.tm_hour, tm.tm_min, tm.tm_sec);
if (err < 0) {
return -1;
}
data->name = "datetime";
data->full_text = text;
return 0;
}
static int
free_datetime(struct section_data *data)
{
free(data->full_text);
return 0;
}
static int n_processors = 0;
static int
cpu_load(struct section_data *data)
{
double avgs[3];
char *text;
int err;
err = getloadavg(avgs, 3);
if (err != 3) {
return -1;
}
err = sprintf_s(&text, "%.2f %.2f %.2f", avgs[0], avgs[1], avgs[2]);
if (err < 0) {
return -1;
}
data->name = "cpu_load";
data->full_text = text;
if (n_processors > 0) {
if (avgs[0] > n_processors + 1
|| avgs[1] > n_processors
|| avgs[2] > n_processors - 1) {
data->color = "#ffff00";
}
if (avgs[0] > n_processors * 2 + 1
|| avgs[1] > n_processors * 2
|| avgs[2] > n_processors + 1) {
data->color = "#ff0000";
}
}
return 0;
}
static int
free_cpu_load(struct section_data *data)
{
free(data->full_text);
return 0;
}
static int
battery(struct section_data *data)
{
FILE *f;
char *text, *p;
size_t len;
long percent;
text = malloc(5 * sizeof(char));
if (!text) {
return -1;
}
f = fopen("/sys/class/power_supply/BAT1/capacity", "r");
if (f == NULL) {
free(text);
return -1;
}
len = fread(text, sizeof(char), 5, f);
if (len < 1 || len > 4 || ferror(f) || !feof(f)) {
fclose(f);
free(text);
return -1;
}
fclose(f);
p = strchr(text, '\n');
if (p == NULL) {
free(text);
return -1;
}
p[0] = '%';
p[1] = '\0';
percent = strtol(text, NULL, 10);
if (percent <= 0 || percent > 100) {
free(text);
return -1;
}
if (percent < 10) {
data->color = "#ff0000";
} else if (percent < 15) {
data->color = "#ffff00";
}
data->name = "battery";
data->full_text = text;
return 0;
}
static int
free_battery(struct section_data *data)
{
free(data->full_text);
return 0;
}
static int
cpu_temp(struct section_data *data)
{
FILE *f;
char buf[8] = {0};
size_t len;
long temp;
char *text;
int err;
f = fopen("/sys/class/thermal/thermal_zone0/temp", "r");
if (f == NULL) {
return -1;
}
len = fread(buf, sizeof(char), 8, f);
assert(len <= 8);
if (len == 8 || ferror(f) || !feof(f)) {
fclose(f);
return -1;
}
fclose(f);
temp = strtol(buf, NULL, 10);
if (temp == 0 || temp == LONG_MIN || temp == LONG_MAX) {
return -1;
}
temp /= 1000;
err = sprintf_s(&text, "%ld°C", temp);
if (err < 0) {
return -1;
}
if (temp >= 80) {
data->color = "#ff0000";
} else if (temp > 75) {
data->color = "#ffff00";
}
data->name = "cpu_temp";
data->full_text = text;
return 0;
}
static int
free_cpu_temp(struct section_data *data)
{
free(data->full_text);
return 0;
}
static int
ip(struct section_data *data)
{
int err;
struct ifaddrs *ifaddrs;
char host[512];
err = getifaddrs(&ifaddrs);
if (err < 0) {
return -1;
}
for (struct ifaddrs *p = ifaddrs; p != NULL; p = p->ifa_next) {
if (p->ifa_addr == NULL || p->ifa_addr->sa_family != AF_INET) {
continue;
}
if (!strncasecmp("lo", p->ifa_name, 2)) {
continue;
}
// This is the check i3status makes.
// TODO - check for IFF_UP?
if (!(p->ifa_flags & IFF_RUNNING)) {
continue;
}
err = getnameinfo(p->ifa_addr, sizeof(*p->ifa_addr), host,
sizeof(host), NULL, 0, NI_NUMERICHOST);
if (err != 0) {
goto error;
}
data->full_text = strdup(host);
if (data->full_text == NULL) {
goto error;
}
data->name = "ip";
freeifaddrs(ifaddrs);
return 0;
}
error:
freeifaddrs(ifaddrs);
return -1;
}
static int
free_ip(struct section_data *data)
{
free(data->full_text);
return 0;
}
static void
print_data(struct section_data *data)
{
int comma = 0;
putchar('{');
#define COMMA() do { \
if (comma) { \
putchar(','); \
} else { \
comma = 1; \
} \
} while (0)
#define PRINT_STRING(name) do { \
if (data->name) { \
COMMA(); \
printf("\"" #name "\":\"%s\"", data->name); \
} \
} while (0)
PRINT_STRING(name);
PRINT_STRING(instance);
PRINT_STRING(color);
PRINT_STRING(full_text);
PRINT_STRING(short_text);
PRINT_STRING(min_width);
if (data->separator_block_width >= 0) {
COMMA();
printf("\"separator_block_width\":%d", data->separator_block_width);
}
if (data->urgent != URGENT_DEFAULT) {
COMMA();
printf("\"urgent\":%s", data->urgent == URGENT_YES ? "true" :
"false");
}
if (data->separator != SEPARATOR_DEFAULT) {
COMMA();
printf("\"separator\":%s", data->separator == SEPARATOR_NO ? "false"
: "true");
}
if (data->align != ALIGN_DEFAULT) {
COMMA();
printf("\"align\":%s", data->align == ALIGN_RIGHT ? "right" :
data->align == ALIGN_CENTER ? "center" : "left");
}
if (data->markup != MARKUP_DEFAULT) {
COMMA();
printf("\"markup\":\"%s\"", data->markup == MARKUP_PANGO ? "pango" :
"none");
}
putchar('}');
#undef PRINT_STRING
#undef COMMA
}
struct section {
section_func func;
section_func free_func;
};
static void
print_all_data(void)
{
const struct section sections[] = {
{ip, free_ip},
{cpu_temp, free_cpu_temp},
{cpu_load, free_cpu_load},
{battery, free_battery},
{datetime, free_datetime}
};
for (unsigned int i = 0, n = 0; i < sizeof(sections) / sizeof(sections[0]);
++i) {
int err;
struct section_data data;
memset(&data, 0, sizeof(data));
data.separator_block_width = -1;
assert(data.name == NULL);
assert(data.instance == NULL);
assert(data.color == NULL);
assert(data.full_text == NULL);
assert(data.short_text == NULL);
assert(data.min_width == NULL);
assert(data.separator_block_width < 0);
assert(data.urgent == URGENT_DEFAULT);
assert(data.separator == SEPARATOR_DEFAULT);
assert(!data.disabled);
assert(data.align == ALIGN_DEFAULT);
assert(data.markup == MARKUP_DEFAULT);
err = sections[i].func(&data);
if (err == 0 && !data.disabled) {
if (n++ > 0) {
putchar(',');
}
print_data(&data);
}
err = sections[i].free_func(&data);
assert(err == 0);
}
}
int
main(void)
{
n_processors = get_nprocs();
assert(n_processors > 0);
print_header();
// These gotos allow for an efficient solution to the comma problem without
// duplicating code.
putchar('[');
goto print;
loop:
fputs(",[", stdout);
print:
print_all_data();
puts("]");
fflush(stdout);
sleep(1);
goto loop;
// Probably won't get here
puts("]");
return 0;
}
|
the_stack_data/29825572.c | #include <stdio.h>
#include <string.h>
|
the_stack_data/104826765.c | #include <stdio.h>
void swap(int *m, int *n) {
int temp = *m;
*m = *n;
*n = temp;
}
void reverse(int marks[], int size) {
for (int low = 0, high = size - 1; low < high; low++, high--)
swap(&marks[low], &marks[high]);
}
int main(void) {
int marks[5];
for (int i = 1; i <= 5; i++)
scanf("%d", &marks[i - 1]);
reverse(marks, 5);
for (int i = 0; i < 5; i++)
printf("%d ", marks[i]);
printf("\n");
}
|
the_stack_data/126701701.c | #include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <unistd.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <semaphore.h>
#include <time.h>
#include <sys/wait.h>
enum process {MAIN, SANTA, ELF, REINDEER};
typedef struct{
int type;
int id;
}Proc;
typedef struct{
int reindeers_away;
int reindeers_hitched;
bool closed;
int elves_wait;
int elves_get_help;
int order;
int shmid;
sem_t sem_write;
sem_t sem_vacation;
sem_t sem_help;
sem_t sem_close_workshop;
sem_t sem_christmas;
sem_t sem_get_hitched;
sem_t sem_santa;
sem_t sem_elves;
sem_t sem_all_get_help;
}SharedMem;
#define shared_mem_key 4242
// Validate arguments
int check_arguments(int argc, char* argv[], int* NE, int* NR, int* TE, int *TR)
{
for (int i = 1; i < argc; i++)
{
int tmp = atoi(argv[i]);
switch (i)
{
case 1:
if (tmp <= 0 || tmp >= 1000)
{
fprintf(stderr, "%s %d\n", "Incorrect argument", i);
return 1;
}
*NE = tmp;
break;
case 2:
if (tmp <= 0 || tmp >= 20)
{
fprintf(stderr, "%s %d\n", "Incorrect argument", i);
return 1;
}
*NR = tmp;
break;
case 3:
if (tmp < 0 || tmp > 1000)
{
fprintf(stderr, "%s %d\n", "Incorrect argument", i);
return 1;
}
*TE = tmp;
break;
case 4:
if (tmp < 0 || tmp > 1000)
{
fprintf(stderr, "%s %d\n", "Incorrect argument", i);
return 1;
}
*TR = tmp;
break;
}
}
return 0;
}
// Semaphore inicialization
int sem_inicialization(sem_t *sem, int init_value)
{
if (sem_init(sem, 1, init_value) == -1)
{
fprintf(stderr, "%s\n", "Error: Sem_init failed.");
return 1;
}
return 0;
}
// Create process using fork
int create_process(int set_type, int *type)
{
pid_t pid;
// Child process
if ((pid = fork()) == 0)
{
*type = set_type;
}
// Fork error
else if (pid < 0)
{
fprintf(stderr, "Error: Fork failed to create child process\n");
return 1;
}
return 0;
}
// Create processes
int create_processes(int set_type, int *type, int *id, int n)
{
for (int i = 0; i < n; i++)
{
if (create_process(set_type, type) == 1) return 1;
*id = i + 1;
if (*type != MAIN) return 0;
}
return 0;
}
// Print output to file
int print_message(FILE *file, Proc process, SharedMem *shm, const char *msg)
{
sem_wait(&shm->sem_write);
char *name;
switch (process.type)
{
case SANTA: name = "Santa";
break;
case ELF: name = "Elf";
break;
case REINDEER: name = "RD";
break;
default:
break;
}
if (process.type != SANTA)
fprintf(file," %d: %s %d: %s\n", (shm->order)++, name, process.id, msg);
else
fprintf(file," %d: %s: %s\n", (shm->order)++, name, msg);
fflush(file);
setbuf(file, NULL);
sem_post(&shm->sem_write);
return 0;
}
// Elves processes
void* elves_lives(FILE *file, Proc process, SharedMem *shm, int TE)
{
while (true)
{
int time = random() % (TE + 1);
usleep(time);
print_message(file, process, shm, "need help");
sem_wait(&shm->sem_help);
shm->elves_wait++;
sem_post(&shm->sem_help);
if (shm->elves_wait == 3) sem_post(&shm->sem_santa);
sem_wait(&shm->sem_elves);
// Workshop is closed
if (shm->closed)
break;
print_message(file, process, shm, "get help");
sem_wait(&shm->sem_help);
shm->elves_get_help++;
sem_post(&shm->sem_help);
if (shm->elves_get_help == 3) sem_post(&shm->sem_all_get_help);
}
print_message(file, process, shm, "taking holidays");
exit(0);
}
// Reindeers processes
void* reindeers_lives(FILE *file, Proc process, SharedMem *shm, int TR)
{
int time = random() % (TR + 1 - TR/2) + (TR / 2);
usleep(time);
print_message(file, process, shm, "return home");
// Return home from vacation
sem_wait(&shm->sem_vacation);
shm->reindeers_away--;
sem_post(&shm->sem_vacation);
// All reindeers are at home
if (shm->reindeers_away == 0) sem_post(&shm->sem_santa);
// Hitching reindeers
sem_wait(&shm->sem_get_hitched);
print_message(file, process, shm, "get hitched");
shm->reindeers_hitched--;
sem_post(&shm->sem_get_hitched);
// All hitched
if (shm->reindeers_hitched == 0)
sem_post(&shm->sem_christmas);
exit(0);
}
// Santa's life
void* santa_life(FILE *file, Proc process, SharedMem *shm, int NE, int NR)
{
while (true)
{
sem_wait(&shm->sem_santa);
if(shm->reindeers_away == 0)
{
print_message(file, process, shm, "closing workshop");
shm->closed = true;
int waiting = NE;
while (waiting--) sem_post(&shm->sem_elves);
waiting = NR;
while (waiting--) sem_post(&shm->sem_get_hitched);
sem_post(&shm->sem_get_hitched);
break;
}
else
{
sem_wait(&shm->sem_help);
shm->elves_get_help = 0;
sem_post(&shm->sem_help);
print_message(file, process, shm, "helping elves");
int count = 3;
while (count--) sem_post(&shm->sem_elves);
sem_wait(&shm->sem_all_get_help);
print_message(file, process, shm, "going to sleep");
}
}
// Semaphore will open when the last reindeer is hitched
sem_wait(&shm->sem_christmas);
print_message(file, process, shm, "Christmas started");
exit(0);
}
// Main
int main(int argc, char *argv[])
{
// ------------------- Check arguments --------------------------
if (argc != 5)
{
fprintf(stderr, "Incorrect number of arguments\n");
return 1;
}
int NE, NR, TE, TR = 0;
check_arguments(argc, argv, &NE, &NR, &TE, &TR);
// ------------------- Shared memory ----------------------------
int shmid = shmget(shared_mem_key, sizeof(SharedMem), IPC_CREAT | 0666);
if (shmid < 0)
{
fprintf(stderr, "%s\n", "Error: Shmget failed.");
return 1;
}
SharedMem *shm = shmat(shmid, NULL, 0);
if (shm == (SharedMem*) -1)
{
fprintf(stderr, "%s\n", "Error: Shmat failed.");
return 1;
}
// Share memory inicialization
shm->shmid = shmid;
shm->order = 1;
shm->reindeers_away = NR;
shm->reindeers_hitched = NR;
shm->closed = false;
shm->elves_wait = 0;
shm->elves_get_help = 0;
// ------------------- Inicialize semaphores --------------------
if (sem_inicialization(&shm->sem_write, 1) == 1) return 1;
if (sem_inicialization(&shm->sem_vacation, 1) == 1) return 1;
if (sem_inicialization(&shm->sem_help, 1) == 1) return 1;
if (sem_inicialization(&shm->sem_christmas, 0) == 1) return 1;
if (sem_inicialization(&shm->sem_get_hitched, 0) == 1) return 1;
if (sem_inicialization(&shm->sem_santa, 0) == 1) return 1;
if (sem_inicialization(&shm->sem_elves, 0) == 1) return 1;
if (sem_inicialization(&shm->sem_all_get_help, 0) == 1) return 1;
// ------------------- Open output file -------------------------
FILE *output;
if ((output = fopen("proj2.out", "w")) == NULL)
{
fprintf(stderr, "%s\n", "Error: File does not exist.");
return 1;
}
// -------------------------- Messages --------------------------
const char *start[] = {"nic", "going to sleep", "started", "rstarted"};
srand(time(NULL));
// ------------------- Create processes -------------------------
// Process info
Proc process_info;
process_info.type = MAIN;
// Create SANTA process
if (process_info.type == MAIN)
if (create_process(SANTA, &process_info.type) == 1) return 1;
// Create ELVES processes
if (process_info.type == MAIN)
create_processes(ELF, &process_info.type, &process_info.id, NE);
// Create REINDEERS processes
if (process_info.type == MAIN)
create_processes(REINDEER, &process_info.type, &process_info.id, NR);
// Start message from each process
if (process_info.type != MAIN)
print_message(output, process_info, shm, start[process_info.type]);
// Process life cycles
switch(process_info.type)
{
case SANTA: santa_life(output, process_info, shm, NE, NR);
break;
case ELF: elves_lives(output, process_info, shm, TE);
break;
case REINDEER: reindeers_lives(output, process_info, shm, TR);
break;
default:
break;
}
// Wait for all child processes
while(wait(NULL) >= 0);
// DELETE semaphores
sem_destroy(&shm->sem_write);
sem_destroy(&shm->sem_vacation);
sem_destroy(&shm->sem_help);
sem_destroy(&shm->sem_get_hitched);
sem_destroy(&shm->sem_christmas);
sem_destroy(&shm->sem_santa);
sem_destroy(&shm->sem_elves);
sem_destroy(&shm->sem_all_get_help);
// DELETE shared memory
shmid = shm->shmid;
if (shmdt(shm))
{
fprintf(stderr, "%s\n", "Error: Shmdt failed");
return 1;
}
if (shmctl(shmid, IPC_RMID, NULL) == -1)
{
fprintf(stderr, "%s\n", "Error: Shmctl failed");
}
// Close file
if (fclose(output) == EOF)
{
fprintf(stderr, "%s\n", "Error: File could not be closed.");
return 1;
}
return 0;
}
|
the_stack_data/232955871.c | /* Написать программу, в которой определить две параллельные области, каждая из которых
содержит итерационную конструкцию for выполняющую инициализацию элементов
одномерных массивов целых чисел a[12], b[12] и c[12]. Число нитей перед первой областью
задать равным 3, перед второй – равным 4. Первая параллельная область выполняет
инициализацию элементов массивов a и b с использованием статического распределения
итераций, размер порции итераций выбрать самостоятельно, вторая параллельная область
выполняет инициализацию элементов массива c по следующему правилу c[i] = a[i] + b[i], с
использованием динамического распределения итераций, размер порции итераций выбрать
самостоятельно. В каждой области определить и выдать на экран количество нитей, номер
нити и результат выполнения цикла. Убедиться в правильности работы программы. */
#include <stdio.h>
#include <omp.h>
#include <time.h>
#include <stdlib.h>
#define N 12
int main(int argc, char *argv[])
{
srand(time(NULL));
int a[N], b[N], c[N];
#pragma omp parallel num_threads(3)
{
printf("Количество нитей первой области: %d\n", omp_get_num_threads());
#pragma omp for schedule(static,4)
for (int i=0; i < N; i++){
a[i] = rand() % 20;
b[i] = rand() % 20;
printf("a[i]: %d, b[i]: %d, Нить номер: %d\n", a[i], b[i], omp_get_thread_num());
}
}
#pragma omp parallel num_threads(4)
{
printf("Количество нитей второй области: %d\n", omp_get_num_threads());
#pragma omp for schedule(dynamic, 4)
for (int i=0; i < N; i++){
c[i] = a[i] + b[i];
printf("c[i]: %d, Нить номер: %d\n", a[i], omp_get_thread_num());
}
}
} |
the_stack_data/817805.c | #include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int nohup_main(int argc, char *argv[])
{
if (argc < 2) {
fprintf(stderr, "Usage: %s [-n] program args...\n", argv[0]);
return EXIT_FAILURE;
}
signal(SIGHUP, SIG_IGN);
argv++;
if (strcmp(argv[0], "-n") == 0) {
argv++;
signal(SIGINT, SIG_IGN);
signal(SIGSTOP, SIG_IGN);
signal(SIGTTIN, SIG_IGN);
signal(SIGTTOU, SIG_IGN);
signal(SIGQUIT, SIG_IGN);
signal(SIGTERM, SIG_IGN);
}
execvp(argv[0], argv);
perror(argv[0]);
return EXIT_FAILURE;
}
|
the_stack_data/107953215.c | /* Hanoi Tower Troubles Again */
#include <stdio.h>
#include <math.h>
#define C
#ifdef C
typedef char bool;
#define TRUE 1
#define FALSE 0
#undef C
#endif
#define MAXV 2400
#define MAXDEGREE 70
#define MAXPEGS 50
typedef struct {
int edges[MAXV+1][MAXDEGREE];
int degree[MAXV+1];
int nvertices;
} graph;
typedef struct {
int balls[100];
int top;
} peg;
graph g;
peg p[MAXPEGS];
typedef struct {
int q[MAXV+1];
int first;
int last;
int count;
} queue;
void init_queue(queue *q) {
q -> first = 0;
q -> last = MAXV-1;
q -> count = 0;
}
void enqueue(queue *q, int x) {
q -> last = (q->last + 1) % MAXV;
q -> q[q -> last] = x;
(q -> count)++;
}
int dequeue(queue *q) {
int x;
x = q -> q[q->first];
q -> first = (q -> first+1) % MAXV;
(q -> count)--;
return (x);
}
bool empty(queue *q) {
if (q -> count <= 0) return TRUE;
return FALSE;
}
bool possible(int a, int b) {
int r;
r = sqrt(a+b);
if ((a+b) == (r*r))
return (TRUE);
else
return (FALSE);
}
void construct_graph(graph *g) {
int i;
int r, k, p;
for (i=1; i<=MAXV; i++) g->degree[i] = 0;
for (r = 2; r < 70; r++) {
p = r*r;
for (k = p-1; k+k > p; k--) {
g->edges[p-k][g->degree[p-k]] = k;
g->degree[p-k]++;
}
}
}
void compute_indegrees(graph *g, int in[]) {
int i,j;
for (i=1; i<=g->nvertices; i++) in[i] = 0;
for (i=1; i<=g->nvertices; i++)
for (j=0; j<g->degree[i]; j++)
if (g->edges[i][j] <= g->nvertices)
in[g->edges[i][j]]++;
else
break;
}
bool topsort(graph *g, int n) {
int indegree[MAXV];
queue zeroin;
int x, y;
int i;
int index;
int maxin;
compute_indegrees(g,indegree);
init_queue(&zeroin);
/*printf("Topsort:\nvertices:%d\nIndegrees:\n", g->nvertices);
for (i = 1; i <= g->nvertices; i++)
printf("%d: %d\n",i, indegree[i]);
putchar('\n');*/
for (i=1; i<=g->nvertices; i++)
if (indegree[i] == 0) enqueue(&zeroin,i);
while (empty(&zeroin) == FALSE) {
if (zeroin.count > n)
return (FALSE);
x = dequeue(&zeroin);
maxin = -1;
for (i = 0; i < n; i++) {
if (p[i].top == -1) {
p[i].top = p[i].top + 1;
p[i].balls[p[i].top] = x;
index = -1;
break;
}
else {
if (possible(p[i].balls[p[i].top], x) && (x > p[i].balls[p[i].top])) {
if (indegree[p[i].balls[p[i].top]] > maxin) {
maxin = indegree[p[i].balls[p[i].top]];
index = i;
}
}
}
}
if (index != -1) {
p[index].top = p[index].top + 1;
p[index].balls[p[index].top] = x;
}
for (i=0; (i<g->degree[x]) && (g->edges[x][i] <= g->nvertices); i++) {
y = g->edges[x][i];
indegree[y]--;
if (indegree[y] == 0) enqueue(&zeroin,y);
}
}
return (TRUE);
}
int maxballs(graph *g, int n) {
int k, i, j;
bool v;
for (k = 1; k <= MAXV; k++) {
g->nvertices = k;
for (i = 0; i < n; i++) p[i].top = -1;
v = topsort(g, n);
/*for (i = 0; i < n; i++) {
printf("%d: ", i);
for (j = 0; j <= p[i].top; j++)
printf("%d ", p[i].balls[j]);
putchar('\n');
}
getchar();*/
if (v == FALSE)
break;
}
return (k-1);
}
void print_graph(graph *g) {
int i, j;
for (i = 0; i < 3001; i++) {
printf("%d: ", i);
for (j = 0; j < g->degree[i]; j++)
printf(" %d", g -> edges[i][j]);
putchar('\n');
}
}
int main() {
int t, n;
//scanf("%d", &t);
construct_graph(&g);
//print_graph(&g);
for (n = 1; n < 51; n++)
printf("f[%d] = %d;\n", n, maxballs(&g, n));
return 0;
}
|
the_stack_data/90763909.c | /* Check that the decrement-and-test instruction is generated. */
/* { dg-do compile } */
/* { dg-options "-O1" } */
/* { dg-final { scan-assembler-times "dt\tr" 2 } } */
int
test_00 (int* x, int c)
{
int s = 0;
int i;
for (i = 0; i < c; ++i)
s += x[i];
return s;
}
int
test_01 (int* x, int c)
{
int s = 0;
int i;
for (i = 0; i < c; ++i)
s += *--x;
return s;
}
|
the_stack_data/976232.c | #include <stdio.h>
int main() {
unsigned int n = 0;
printf("n = ");
scanf("%u", &n);
double a_n = (n % 2 ? -1.0 : 1.0) / (n + 2);
printf("a_n = %f\n", a_n);
return 0;
}
|
the_stack_data/145452069.c | #include <stdio.h>
int main(){
int n;
printf("\n======== Par ou impar ========\n");
printf("Digite um numero inteiro: ");
scanf("%d", &n);
if (n % 2 == 0) //O resto da divisao é um número inteiro
{
printf("O numero %d e par \n", n);
}
else
{
printf("O numero %d e impar \n", n);
}
return 0;
}
|
the_stack_data/211081869.c | #include <string.h>
int main(void) {
int a = 0;
int *array[10];
int *array2[10];
int **p = array;
int **q = array2;
array[3] = &a;
memcpy(q, p, sizeof(array));
*array2[3] = 13;
test_assert(13 == a);
return 0;
}
|
the_stack_data/190769518.c | #include <ncurses.h>
int main()
{
initscr();
addch(ACS_ULCORNER);
addch(ACS_HLINE);
addch(ACS_URCORNER);
addch('\n');
addch(ACS_VLINE);
addch(' ');
addch(ACS_VLINE);
addch('\n');
addch(ACS_LLCORNER);
addch(ACS_HLINE);
addch(ACS_LRCORNER);
addch('\n');
refresh();
getch();
endwin();
return(0);
}
|
the_stack_data/92324126.c | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
char * input(char * str){
char t;
while((t=getchar())!='\n') *(str++)=t;
return str;
}
int main(void){
int i=0,tmp=0;
int sum=0;
char *str=(char *)malloc(sizeof(char *)+1);
str=input(str);
strcat(str,"a0");
while(*(str+i)!='\0'){
if(isdigit(*(str+i)))
tmp=(tmp*10)+(*(str+i)-48);
else
{
sum+=tmp;
tmp=0;
}
i++;
}
printf("the sum of digites in the string is %d\n",sum);
return 0;
} |
the_stack_data/100140144.c | //
// Created by weibin on 2022-01-26.
//
#include <stdio.h>
int main() {
char a[] = "FishC";
int b[5] = {1, 3, 3, 4, 5};
float c[5] = {1.1, 2.2, 3.3, 4.4, 5.5};
double d[5] = {1.1, 2.2, 3.3, 4.4, 5.5};
printf("a[0] -> %p,a[1] -> %p,a[2] -> %p \n", &a[0], &a[1], &a[2]);
printf("b[0] -> %p,b[1] -> %p,b[2] -> %p \n", &a[0], &a[1], &a[2]);
printf("c[0] -> %p,c[1] -> %p,c[2] -> %p \n", &a[0], &a[1], &a[2]);
printf("d[0] -> %p,d[1] -> %p,d[2] -> %p \n", &a[0], &a[1], &a[2]);
return 0;
}
|
the_stack_data/833198.c | #include <stdio.h>
int main(int argc, char *argv[])
{
int areas[]={12, 20, 14};
char name[]="Hckrtst";
char full_name[]={'h',
'c','k','r','t', '\0'}; // Try removing this \0 and run with valgrind
printf("Size of int is %d\n", sizeof(int));
printf("Num of ints in areas is %d\n", sizeof(areas)/sizeof(int));
printf("Size of areas %ld\n", sizeof(areas));
printf("Size of name %ld\n", sizeof(name));
printf("Size of full_name %ld\n", sizeof(full_name));
return 0;
}
|
the_stack_data/154830925.c | #include<stdio.h>
void callByValue(int p){
p=25;//In call by values we cannot alter the values of actual variables through function calls.
}
void callByReference(int *q){
*q=100;//In call by reference we can alter the values of variables through function calls.
}
int main(){
int a=5,b=10;
callByValue(a);
callByReference(&b);
printf("%d %d",a,b);//The value of a remains the same, whereas value of b is changed.
}
|
the_stack_data/115766897.c | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/syscall.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#define __NR_memfd_create 319
#define MFD_CLOEXEC 1
static inline int memfd_create(const char *name, unsigned int flags) {
return syscall(__NR_memfd_create, name, flags);
}
extern char **environ;
int main(int argc, char* argv[]) {
int s, fd;
struct sockaddr_in addr;
char buf[1024] = {0};
char *args[2]= {getenv("Z_PROC_NAME"), NULL};
int count;
if(argc < 2) exit(1);
memset(&addr, 0, sizeof(struct sockaddr_in));
addr.sin_family = AF_INET;
if (inet_pton(AF_INET, argv[1], &addr.sin_addr) <= 0) exit(1);
addr.sin_port = htons(atoi(argv[2]));
if ((s = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0) exit(1);
if (connect(s, (struct sockaddr*)&addr, sizeof(struct sockaddr_in)) < 0) exit(1);
if ((fd = memfd_create(getenv("Z_PROC_NAME"), MFD_CLOEXEC)) < 0) exit(1);
while (1) {
count = read(s, buf, sizeof(buf));
if (count <= 0 || count < sizeof(buf))
break;
write(fd, buf, count);
}
close(s);
if (fexecve(fd, args, environ) < 0) exit(1);
return 0;
}
|
the_stack_data/187642818.c | // RUN: %clang -target i386-unknown-linux-gnu -march=i386 -mx87 %s -### -o %t.o 2>&1 | FileCheck -check-prefix=X87 %s
// RUN: %clang -target i386-unknown-linux-gnu -march=i386 -mno-x87 %s -### -o %t.o 2>&1 | FileCheck -check-prefix=NO-X87 %s
// RUN: %clang -target i386-unknown-linux-gnu -march=i386 -m80387 %s -### -o %t.o 2>&1 | FileCheck -check-prefix=X87 %s
// RUN: %clang -target i386-unknown-linux-gnu -march=i386 -mno-80387 %s -### -o %t.o 2>&1 | FileCheck -check-prefix=NO-X87 %s
// X87: "-target-feature" "+x87"
// NO-X87: "-target-feature" "-x87"
// RUN: %clang -target i386-unknown-linux-gnu -march=i386 -mmmx -m3dnow -m3dnowa %s -### -o %t.o 2>&1 | FileCheck -check-prefix=MMX %s
// RUN: %clang -target i386-unknown-linux-gnu -march=i386 -mno-mmx -mno-3dnow -mno-3dnowa %s -### -o %t.o 2>&1 | FileCheck -check-prefix=NO-MMX %s
// MMX: "-target-feature" "+mmx" "-target-feature" "+3dnow" "-target-feature" "+3dnowa"
// NO-MMX: "-target-feature" "-mmx" "-target-feature" "-3dnow" "-target-feature" "-3dnowa"
// RUN: %clang -target i386-unknown-linux-gnu -march=i386 -msse -msse2 -msse3 -mssse3 -msse4a -msse4.1 -msse4.2 %s -### -o %t.o 2>&1 | FileCheck -check-prefix=SSE %s
// RUN: %clang -target i386-unknown-linux-gnu -march=i386 -mno-sse -mno-sse2 -mno-sse3 -mno-ssse3 -mno-sse4a -mno-sse4.1 -mno-sse4.2 %s -### -o %t.o 2>&1 | FileCheck -check-prefix=NO-SSE %s
// SSE: "-target-feature" "+sse" "-target-feature" "+sse2" "-target-feature" "+sse3" "-target-feature" "+ssse3" "-target-feature" "+sse4a" "-target-feature" "+sse4.1" "-target-feature" "+sse4.2"
// NO-SSE: "-target-feature" "-sse" "-target-feature" "-sse2" "-target-feature" "-sse3" "-target-feature" "-ssse3" "-target-feature" "-sse4a" "-target-feature" "-sse4.1" "-target-feature" "-sse4.2"
// RUN: %clang -target i386-unknown-linux-gnu -march=i386 -msse4 -maes %s -### -o %t.o 2>&1 | FileCheck -check-prefix=SSE4-AES %s
// RUN: %clang -target i386-unknown-linux-gnu -march=i386 -mno-sse4 -mno-aes %s -### -o %t.o 2>&1 | FileCheck -check-prefix=NO-SSE4-AES %s
// SSE4-AES: "-target-feature" "+sse4.2" "-target-feature" "+aes"
// NO-SSE4-AES: "-target-feature" "-sse4.1" "-target-feature" "-aes"
// RUN: %clang -target i386-unknown-linux-gnu -march=i386 -mavx -mavx2 -mavx512f -mavx512cd -mavx512er -mavx512pf -mavx512dq -mavx512bw -mavx512vl -mavx512vbmi -mavx512vbmi2 -mavx512ifma %s -### -o %t.o 2>&1 | FileCheck -check-prefix=AVX %s
// RUN: %clang -target i386-unknown-linux-gnu -march=i386 -mno-avx -mno-avx2 -mno-avx512f -mno-avx512cd -mno-avx512er -mno-avx512pf -mno-avx512dq -mno-avx512bw -mno-avx512vl -mno-avx512vbmi -mno-avx512vbmi2 -mno-avx512ifma %s -### -o %t.o 2>&1 | FileCheck -check-prefix=NO-AVX %s
// AVX: "-target-feature" "+avx" "-target-feature" "+avx2" "-target-feature" "+avx512f" "-target-feature" "+avx512cd" "-target-feature" "+avx512er" "-target-feature" "+avx512pf" "-target-feature" "+avx512dq" "-target-feature" "+avx512bw" "-target-feature" "+avx512vl" "-target-feature" "+avx512vbmi" "-target-feature" "+avx512vbmi2" "-target-feature" "+avx512ifma"
// NO-AVX: "-target-feature" "-avx" "-target-feature" "-avx2" "-target-feature" "-avx512f" "-target-feature" "-avx512cd" "-target-feature" "-avx512er" "-target-feature" "-avx512pf" "-target-feature" "-avx512dq" "-target-feature" "-avx512bw" "-target-feature" "-avx512vl" "-target-feature" "-avx512vbmi" "-target-feature" "-avx512vbmi2" "-target-feature" "-avx512ifma"
// RUN: %clang -target i386-unknown-linux-gnu -march=i386 -mpclmul -mrdrnd -mfsgsbase -mbmi -mbmi2 %s -### -o %t.o 2>&1 | FileCheck -check-prefix=BMI %s
// RUN: %clang -target i386-unknown-linux-gnu -march=i386 -mno-pclmul -mno-rdrnd -mno-fsgsbase -mno-bmi -mno-bmi2 %s -### -o %t.o 2>&1 | FileCheck -check-prefix=NO-BMI %s
// BMI: "-target-feature" "+pclmul" "-target-feature" "+rdrnd" "-target-feature" "+fsgsbase" "-target-feature" "+bmi" "-target-feature" "+bmi2"
// NO-BMI: "-target-feature" "-pclmul" "-target-feature" "-rdrnd" "-target-feature" "-fsgsbase" "-target-feature" "-bmi" "-target-feature" "-bmi2"
// RUN: %clang -target i386-unknown-linux-gnu -march=i386 -mlzcnt -mpopcnt -mtbm -mfma -mfma4 %s -### -o %t.o 2>&1 | FileCheck -check-prefix=FMA %s
// RUN: %clang -target i386-unknown-linux-gnu -march=i386 -mno-lzcnt -mno-popcnt -mno-tbm -mno-fma -mno-fma4 %s -### -o %t.o 2>&1 | FileCheck -check-prefix=NO-FMA %s
// FMA: "-target-feature" "+lzcnt" "-target-feature" "+popcnt" "-target-feature" "+tbm" "-target-feature" "+fma" "-target-feature" "+fma4"
// NO-FMA: "-target-feature" "-lzcnt" "-target-feature" "-popcnt" "-target-feature" "-tbm" "-target-feature" "-fma" "-target-feature" "-fma4"
// RUN: %clang -target i386-unknown-linux-gnu -march=i386 -mxop -mf16c -mrtm -mprfchw -mrdseed %s -### -o %t.o 2>&1 | FileCheck -check-prefix=XOP %s
// RUN: %clang -target i386-unknown-linux-gnu -march=i386 -mno-xop -mno-f16c -mno-rtm -mno-prfchw -mno-rdseed %s -### -o %t.o 2>&1 | FileCheck -check-prefix=NO-XOP %s
// XOP: "-target-feature" "+xop" "-target-feature" "+f16c" "-target-feature" "+rtm" "-target-feature" "+prfchw" "-target-feature" "+rdseed"
// NO-XOP: "-target-feature" "-xop" "-target-feature" "-f16c" "-target-feature" "-rtm" "-target-feature" "-prfchw" "-target-feature" "-rdseed"
// RUN: %clang -target i386-unknown-linux-gnu -march=i386 -msha -mpku -madx -mcx16 -mfxsr %s -### -o %t.o 2>&1 | FileCheck -check-prefix=SHA %s
// RUN: %clang -target i386-unknown-linux-gnu -march=i386 -mno-sha -mno-pku -mno-adx -mno-cx16 -mno-fxsr %s -### -o %t.o 2>&1 | FileCheck -check-prefix=NO-SHA %s
// SHA: "-target-feature" "+sha" "-target-feature" "+pku" "-target-feature" "+adx" "-target-feature" "+cx16" "-target-feature" "+fxsr"
// NO-SHA: "-target-feature" "-sha" "-target-feature" "-pku" "-target-feature" "-adx" "-target-feature" "-cx16" "-target-feature" "-fxsr"
// RUN: %clang -target i386-unknown-linux-gnu -march=i386 -mxsave -mxsaveopt -mxsavec -mxsaves %s -### -o %t.o 2>&1 | FileCheck -check-prefix=XSAVE %s
// RUN: %clang -target i386-unknown-linux-gnu -march=i386 -mno-xsave -mno-xsaveopt -mno-xsavec -mno-xsaves %s -### -o %t.o 2>&1 | FileCheck -check-prefix=NO-XSAVE %s
// XSAVE: "-target-feature" "+xsave" "-target-feature" "+xsaveopt" "-target-feature" "+xsavec" "-target-feature" "+xsaves"
// NO-XSAVE: "-target-feature" "-xsave" "-target-feature" "-xsaveopt" "-target-feature" "-xsavec" "-target-feature" "-xsaves"
// RUN: %clang -target i386-unknown-linux-gnu -march=i386 -mclflushopt %s -### -o %t.o 2>&1 | FileCheck -check-prefix=CLFLUSHOPT %s
// RUN: %clang -target i386-unknown-linux-gnu -march=i386 -mno-clflushopt %s -### -o %t.o 2>&1 | FileCheck -check-prefix=NO-CLFLUSHOPT %s
// CLFLUSHOPT: "-target-feature" "+clflushopt"
// NO-CLFLUSHOPT: "-target-feature" "-clflushopt"
// RUN: %clang -target i386-unknown-linux-gnu -march=i386 -mclwb %s -### -o %t.o 2>&1 | FileCheck -check-prefix=CLWB %s
// RUN: %clang -target i386-unknown-linux-gnu -march=i386 -mno-clwb %s -### -o %t.o 2>&1 | FileCheck -check-prefix=NO-CLWB %s
// CLWB: "-target-feature" "+clwb"
// NO-CLWB: "-target-feature" "-clwb"
// RUN: %clang -target i386-unknown-linux-gnu -march=i386 -mwbnoinvd %s -### -o %t.o 2>&1 | FileCheck -check-prefix=WBNOINVD %s
// RUN: %clang -target i386-unknown-linux-gnu -march=i386 -mno-wbnoinvd %s -### -o %t.o 2>&1 | FileCheck -check-prefix=NO-WBNOINVD %s
// WBNOINVD: "-target-feature" "+wbnoinvd"
// NO-WBNOINVD: "-target-feature" "-wbnoinvd"
// RUN: %clang -target i386-unknown-linux-gnu -march=i386 -mmovbe %s -### -o %t.o 2>&1 | FileCheck -check-prefix=MOVBE %s
// RUN: %clang -target i386-unknown-linux-gnu -march=i386 -mno-movbe %s -### -o %t.o 2>&1 | FileCheck -check-prefix=NO-MOVBE %s
// MOVBE: "-target-feature" "+movbe"
// NO-MOVBE: "-target-feature" "-movbe"
// RUN: %clang -target i386-unknown-linux-gnu -march=i386 -mmpx %s -### -o %t.o 2>&1 | FileCheck -check-prefix=MPX %s
// RUN: %clang -target i386-unknown-linux-gnu -march=i386 -mno-mpx %s -### -o %t.o 2>&1 | FileCheck -check-prefix=NO-MPX %s
// MPX: the flag '-mmpx' has been deprecated and will be ignored
// NO-MPX: the flag '-mno-mpx' has been deprecated and will be ignored
// RUN: %clang -target i386-unknown-linux-gnu -march=i386 -mshstk %s -### -o %t.o 2>&1 | FileCheck -check-prefix=CETSS %s
// RUN: %clang -target i386-unknown-linux-gnu -march=i386 -mno-shstk %s -### -o %t.o 2>&1 | FileCheck -check-prefix=NO-CETSS %s
// CETSS: "-target-feature" "+shstk"
// NO-CETSS: "-target-feature" "-shstk"
// RUN: %clang -target i386-unknown-linux-gnu -march=i386 -msgx %s -### -o %t.o 2>&1 | FileCheck -check-prefix=SGX %s
// RUN: %clang -target i386-unknown-linux-gnu -march=i386 -mno-sgx %s -### -o %t.o 2>&1 | FileCheck -check-prefix=NO-SGX %s
// SGX: "-target-feature" "+sgx"
// NO-SGX: "-target-feature" "-sgx"
// RUN: %clang -target i386-unknown-linux-gnu -march=i386 -mprefetchwt1 %s -### -o %t.o 2>&1 | FileCheck -check-prefix=PREFETCHWT1 %s
// RUN: %clang -target i386-unknown-linux-gnu -march=i386 -mno-prefetchwt1 %s -### -o %t.o 2>&1 | FileCheck -check-prefix=NO-PREFETCHWT1 %s
// PREFETCHWT1: "-target-feature" "+prefetchwt1"
// NO-PREFETCHWT1: "-target-feature" "-prefetchwt1"
// RUN: %clang -target i386-unknown-linux-gnu -march=i386 -mclzero %s -### -o %t.o 2>&1 | FileCheck -check-prefix=CLZERO %s
// RUN: %clang -target i386-unknown-linux-gnu -march=i386 -mno-clzero %s -### -o %t.o 2>&1 | FileCheck -check-prefix=NO-CLZERO %s
// CLZERO: "-target-feature" "+clzero"
// NO-CLZERO: "-target-feature" "-clzero"
// RUN: %clang -target i386-unknown-linux-gnu -march=i386 -mvaes %s -### -o %t.o 2>&1 | FileCheck -check-prefix=VAES %s
// RUN: %clang -target i386-unknown-linux-gnu -march=i386 -mno-vaes %s -### -o %t.o 2>&1 | FileCheck -check-prefix=NO-VAES %s
// VAES: "-target-feature" "+vaes"
// NO-VAES: "-target-feature" "-vaes"
// RUN: %clang -target i386-unknown-linux-gnu -march=i386 -mgfni %s -### -o %t.o 2>&1 | FileCheck -check-prefix=GFNI %s
// RUN: %clang -target i386-unknown-linux-gnu -march=i386 -mno-gfni %s -### -o %t.o 2>&1 | FileCheck -check-prefix=NO-GFNI %s
// GFNI: "-target-feature" "+gfni"
// NO-GFNI: "-target-feature" "-gfni
// RUN: %clang -target i386-unknown-linux-gnu -march=i386 -mvpclmulqdq %s -### -o %t.o 2>&1 | FileCheck -check-prefix=VPCLMULQDQ %s
// RUN: %clang -target i386-unknown-linux-gnu -march=i386 -mno-vpclmulqdq %s -### -o %t.o 2>&1 | FileCheck -check-prefix=NO-VPCLMULQDQ %s
// VPCLMULQDQ: "-target-feature" "+vpclmulqdq"
// NO-VPCLMULQDQ: "-target-feature" "-vpclmulqdq"
// RUN: %clang -target i386-unknown-linux-gnu -march=i386 -mavx512bitalg %s -### -o %t.o 2>&1 | FileCheck -check-prefix=BITALG %s
// RUN: %clang -target i386-unknown-linux-gnu -march=i386 -mno-avx512bitalg %s -### -o %t.o 2>&1 | FileCheck -check-prefix=NO-BITALG %s
// BITALG: "-target-feature" "+avx512bitalg"
// NO-BITALG: "-target-feature" "-avx512bitalg"
// RUN: %clang -target i386-unknown-linux-gnu -march=i386 -mavx512vnni %s -### -o %t.o 2>&1 | FileCheck -check-prefix=VNNI %s
// RUN: %clang -target i386-unknown-linux-gnu -march=i386 -mno-avx512vnni %s -### -o %t.o 2>&1 | FileCheck -check-prefix=NO-VNNI %s
// VNNI: "-target-feature" "+avx512vnni"
// NO-VNNI: "-target-feature" "-avx512vnni"
// RUN: %clang -target i386-unknown-linux-gnu -march=i386 -mavx512vbmi2 %s -### -o %t.o 2>&1 | FileCheck -check-prefix=VBMI2 %s
// RUN: %clang -target i386-unknown-linux-gnu -march=i386 -mno-avx512vbmi2 %s -### -o %t.o 2>&1 | FileCheck -check-prefix=NO-VBMI2 %s
// VBMI2: "-target-feature" "+avx512vbmi2"
// NO-VBMI2: "-target-feature" "-avx512vbmi2"
// RUN: %clang -target i386-linux-gnu -mavx512vp2intersect %s -### -o %t.o 2>&1 | FileCheck -check-prefix=VP2INTERSECT %s
// RUN: %clang -target i386-linux-gnu -mno-avx512vp2intersect %s -### -o %t.o 2>&1 | FileCheck -check-prefix=NO-VP2INTERSECT %s
// VP2INTERSECT: "-target-feature" "+avx512vp2intersect"
// NO-VP2INTERSECT: "-target-feature" "-avx512vp2intersect"
// RUN: %clang -target i386-unknown-linux-gnu -march=i386 -mrdpid %s -### -o %t.o 2>&1 | FileCheck -check-prefix=RDPID %s
// RUN: %clang -target i386-unknown-linux-gnu -march=i386 -mno-rdpid %s -### -o %t.o 2>&1 | FileCheck -check-prefix=NO-RDPID %s
// RDPID: "-target-feature" "+rdpid"
// NO-RDPID: "-target-feature" "-rdpid"
// RUN: %clang -target i386-linux-gnu -mretpoline %s -### -o %t.o 2>&1 | FileCheck -check-prefix=RETPOLINE %s
// RUN: %clang -target i386-linux-gnu -mno-retpoline %s -### -o %t.o 2>&1 | FileCheck -check-prefix=NO-RETPOLINE %s
// RETPOLINE: "-target-feature" "+retpoline-indirect-calls" "-target-feature" "+retpoline-indirect-branches"
// NO-RETPOLINE-NOT: retpoline
// RUN: %clang -target i386-linux-gnu -mretpoline -mretpoline-external-thunk %s -### -o %t.o 2>&1 | FileCheck -check-prefix=RETPOLINE-EXTERNAL-THUNK %s
// RUN: %clang -target i386-linux-gnu -mretpoline -mno-retpoline-external-thunk %s -### -o %t.o 2>&1 | FileCheck -check-prefix=NO-RETPOLINE-EXTERNAL-THUNK %s
// RETPOLINE-EXTERNAL-THUNK: "-target-feature" "+retpoline-external-thunk"
// NO-RETPOLINE-EXTERNAL-THUNK: "-target-feature" "-retpoline-external-thunk"
// RUN: %clang -target i386-linux-gnu -mspeculative-load-hardening %s -### -o %t.o 2>&1 | FileCheck -check-prefix=SLH %s
// RUN: %clang -target i386-linux-gnu -mretpoline -mspeculative-load-hardening %s -### -o %t.o 2>&1 | FileCheck -check-prefix=RETPOLINE %s
// RUN: %clang -target i386-linux-gnu -mno-speculative-load-hardening %s -### -o %t.o 2>&1 | FileCheck -check-prefix=NO-SLH %s
// SLH-NOT: retpoline
// SLH: "-target-feature" "+retpoline-indirect-calls"
// SLH-NOT: retpoline
// SLH: "-mspeculative-load-hardening"
// NO-SLH-NOT: retpoline
// RUN: %clang -target i386-linux-gnu -mlvi-cfi %s -### -o %t.o 2>&1 | FileCheck -check-prefix=LVICFI %s
// RUN: %clang -target i386-linux-gnu -mno-lvi-cfi %s -### -o %t.o 2>&1 | FileCheck -check-prefix=NO-LVICFI %s
// LVICFI: "-target-feature" "+lvi-cfi"
// NO-LVICFI-NOT: lvi-cfi
// RUN: %clang -target i386-linux-gnu -mlvi-cfi -mspeculative-load-hardening %s -### -o %t.o 2>&1 | FileCheck -check-prefix=LVICFI-SLH %s
// LVICFI-SLH: error: invalid argument 'mspeculative-load-hardening' not allowed with 'mlvi-cfi'
// RUN: %clang -target i386-linux-gnu -mlvi-cfi -mretpoline %s -### -o %t.o 2>&1 | FileCheck -check-prefix=LVICFI-RETPOLINE %s
// LVICFI-RETPOLINE: error: invalid argument 'mretpoline' not allowed with 'mlvi-cfi'
// RUN: %clang -target i386-linux-gnu -mlvi-cfi -mretpoline-external-thunk %s -### -o %t.o 2>&1 | FileCheck -check-prefix=LVICFI-RETPOLINE-EXTERNAL-THUNK %s
// LVICFI-RETPOLINE-EXTERNAL-THUNK: error: invalid argument 'mretpoline-external-thunk' not allowed with 'mlvi-cfi'
// RUN: %clang -target i386-linux-gnu -mwaitpkg %s -### -o %t.o 2>&1 | FileCheck -check-prefix=WAITPKG %s
// RUN: %clang -target i386-linux-gnu -mno-waitpkg %s -### -o %t.o 2>&1 | FileCheck -check-prefix=NO-WAITPKG %s
// WAITPKG: "-target-feature" "+waitpkg"
// NO-WAITPKG: "-target-feature" "-waitpkg"
// RUN: %clang -target i386-unknown-linux-gnu -march=i386 -mmovdiri %s -### -o %t.o 2>&1 | FileCheck -check-prefix=MOVDIRI %s
// RUN: %clang -target i386-unknown-linux-gnu -march=i386 -mno-movdiri %s -### -o %t.o 2>&1 | FileCheck -check-prefix=NO-MOVDIRI %s
// MOVDIRI: "-target-feature" "+movdiri"
// NO-MOVDIRI: "-target-feature" "-movdiri"
// RUN: %clang -target i386-unknown-linux-gnu -march=i386 -mmovdir64b %s -### -o %t.o 2>&1 | FileCheck -check-prefix=MOVDIR64B %s
// RUN: %clang -target i386-unknown-linux-gnu -march=i386 -mno-movdir64b %s -### -o %t.o 2>&1 | FileCheck -check-prefix=NO-MOVDIR64B %s
// MOVDIR64B: "-target-feature" "+movdir64b"
// NO-MOVDIR64B: "-target-feature" "-movdir64b"
// RUN: %clang -target i386-unknown-linux-gnu -march=i386 -mpconfig %s -### -o %t.o 2>&1 | FileCheck -check-prefix=PCONFIG %s
// RUN: %clang -target i386-unknown-linux-gnu -march=i386 -mno-pconfig %s -### -o %t.o 2>&1 | FileCheck -check-prefix=NO-PCONFIG %s
// PCONFIG: "-target-feature" "+pconfig"
// NO-PCONFIG: "-target-feature" "-pconfig"
// RUN: %clang -target i386-unknown-linux-gnu -march=i386 -mptwrite %s -### -o %t.o 2>&1 | FileCheck -check-prefix=PTWRITE %s
// RUN: %clang -target i386-unknown-linux-gnu -march=i386 -mno-ptwrite %s -### -o %t.o 2>&1 | FileCheck -check-prefix=NO-PTWRITE %s
// PTWRITE: "-target-feature" "+ptwrite"
// NO-PTWRITE: "-target-feature" "-ptwrite"
// RUN: %clang -target i386-unknown-linux-gnu -march=i386 -minvpcid %s -### -o %t.o 2>&1 | FileCheck -check-prefix=INVPCID %s
// RUN: %clang -target i386-unknown-linux-gnu -march=i386 -mno-invpcid %s -### -o %t.o 2>&1 | FileCheck -check-prefix=NO-INVPCID %s
// INVPCID: "-target-feature" "+invpcid"
// NO-INVPCID: "-target-feature" "-invpcid"
// RUN: %clang -target i386-unknown-linux-gnu -march=i386 -mavx512bf16 %s -### -o %t.o 2>&1 | FileCheck -check-prefix=AVX512BF16 %s
// RUN: %clang -target i386-unknown-linux-gnu -march=i386 -mno-avx512bf16 %s -### -o %t.o 2>&1 | FileCheck -check-prefix=NO-AVX512BF16 %s
// AVX512BF16: "-target-feature" "+avx512bf16"
// NO-AVX512BF16: "-target-feature" "-avx512bf16"
// RUN: %clang -target i386-unknown-linux-gnu -march=i386 -menqcmd %s -### -o %t.o 2>&1 | FileCheck --check-prefix=ENQCMD %s
// RUN: %clang -target i386-unknown-linux-gnu -march=i386 -mno-enqcmd %s -### -o %t.o 2>&1 | FileCheck --check-prefix=NO-ENQCMD %s
// ENQCMD: "-target-feature" "+enqcmd"
// NO-ENQCMD: "-target-feature" "-enqcmd"
// RUN: %clang -target i386-unknown-linux-gnu -march=i386 -mvzeroupper %s -### -o %t.o 2>&1 | FileCheck --check-prefix=VZEROUPPER %s
// RUN: %clang -target i386-unknown-linux-gnu -march=i386 -mno-vzeroupper %s -### -o %t.o 2>&1 | FileCheck --check-prefix=NO-VZEROUPPER %s
// VZEROUPPER: "-target-feature" "+vzeroupper"
// NO-VZEROUPPER: "-target-feature" "-vzeroupper"
// RUN: %clang -target i386-unknown-linux-gnu -march=i386 -mserialize %s -### -o %t.o 2>&1 | FileCheck -check-prefix=SERIALIZE %s
// RUN: %clang -target i386-unknown-linux-gnu -march=i386 -mno-serialize %s -### -o %t.o 2>&1 | FileCheck -check-prefix=NO-SERIALIZE %s
// SERIALIZE: "-target-feature" "+serialize"
// NO-SERIALIZE: "-target-feature" "-serialize"
// RUN: %clang -target i386-unknown-linux-gnu -march=i386 -mtsxldtrk %s -### -o %t.o 2>&1 | FileCheck --check-prefix=TSXLDTRK %s
// RUN: %clang -target i386-unknown-linux-gnu -march=i386 -mno-tsxldtrk %s -### -o %t.o 2>&1 | FileCheck --check-prefix=NO-TSXLDTRK %s
// TSXLDTRK: "-target-feature" "+tsxldtrk"
// NO-TSXLDTRK: "-target-feature" "-tsxldtrk"
|
the_stack_data/101602.c | //Classification: #intrinsic/n/IVO/MIE/aS/sqrt/lc/ln
//Written by: Sergey Pomelov
//Reviewed by: Igor Eremeev
//Comment:
#include <math.h>
#include <stdio.h>
int main(void) {
double a;
double b;
a = sqrt(-1.);
b = 1 / a;
printf("%f",b);
return 0;
}
|
the_stack_data/148578593.c | char movenames[] = "FLBRUDE", *alg_table[4][24] = {
{ // solve DF
"F2", // UF
"U1F2", // UR
"U2F2", // UB
"U3F2", // UL
0, // DF
"R2U1F2", // DR
"B2U2F2", // DB
"D1", // DL
"D1R3D3", // FR
"D3L1D1", // FL
"D1R1D3", // BR
"D3L3D1", // BL
"U1L1F3L3", // UF
"R3F1R1", // UR
"U1R3F1R1", // UB
"L1F3L3", // UL
"F3D1R3D3", // DF
"R1F1", // DR
"B1D1R1D3", // DB
"L3F3", // DL
"F1", // FR
"F3", // FL
"R2F1R2", // BR
"L2F3L2", // BL
}, { // solve DRF
"R1B1U2B3R3", // UFR*
"F3U2F1R1U1R3", // URB*
"F3L1F3L3F2", // UBL*
"R1U2R3F3U3F1", // ULF*
0, // DRF*
"L3U3L1R1U1R3", // DFL*
"R2B2R2B2", // DLB*
"R3U3R1F3U2F1", // DBR*
"R1U1R3", // RUF*
"F3U1F1", // BUR*
"F3U2F1", // LUB*
"U3R1U1R3", // FUL*
"R1U3R3F3U3F1", // FDR*
"L3R1U3R3L1", // LDF*
"B3R1U2R3B1", // BDL*
"R3U2R2U3R3", // RDB*
"F3U3F1", // FRU*
"U1F3U3F1", // RBU*
"R1U2R3", // BLU*
"R1U3R3", // LFU*
"F3U1F1R1U1R3", // RFD*
"F1U2F2U1F1", // FLD*
"L1F3U2F1L3", // LBD*
"F3B1U1B3F1", // BRD*
}, { // solve FR
"R1U3R3", // UF
"U1R1U3R3", // UR
"R1U1R3", // UB
"R1U2R3", // UL
0, // DF
0, // DR
0, // DB
0, // DL
0, // FR
"F2U2F2U2F2", // FL
"R2U2R2U2R2", // BR
"F2D3L2D1F2", // BL
"U3F3U1F1", // UF
"F3U1F1", // UR
"F3U2F1", // UB
"F3U3F1", // UL
0, // DF
0, // DR
0, // DB
0, // DL
"F3U2F1R1U1R3", // FR
"R3D3F3D1R1", // FL
"F1D1R1D3F3", // BR
"L1F3U3L1F1L2", // BL
}, { // solve final FR
"U2F3U1F1U1R1U3R3", // UF
"U3F3U1F1U1R1U3R3", // UR
"F3U1F1U1R1U3R3", // UB
"U1F3U1F1U1R1U3R3", // UL
0, // DF
0, // DR
0, // DB
0, // DL
0, // FR
0, // FL
0, // BR
0, // BL
"U1R1U3R3U3F3U1F1", // UF
"U2R1U3R3U3F3U1F1", // UR
"U3R1U3R3U3F3U1F1", // UB
"R1U3R3U3F3U1F1", // UL
0, // DF
0, // DR
0, // DB
0, // DL
"R2U2F1R2F3U2R3U1R3", // FR
0, // FL
0, // BR
//0, // BL
//"U1D3E3" // y
//"D1" //D1
//"U1" //U1
//"F1U1R1U3R3F3" // LL flip UF and UR
//"F1R1U1R3U3F3" // LL flip UF and UR
}
};
//UF UR UB UL DF DR DB DL FR FL BR BL UFR URB UBL ULF DRF DFL DLB DBR
//00 00 00 00 00 11 11 11 11 11 22 22 222 222 333 333 333 344 444 444
//01 23 45 67 89 01 23 45 67 89 01 23 456 789 012 345 678 901 234 567
//
//0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
//FLBRUD
static int move_table[32][4] = {
{ 1,16, 9,18},{ 0,17, 8,19},{35,25,38,40},{33,26,36,41},{24,37,39,34}, //F
{ 7,19,15,23},{ 6,18,14,22},{32,34,41,43},{30,35,39,44},{33,40,42,31}, //L
{ 5,22,13,20},{21, 4,23,12},{29,31,44,46},{47,27,32,42},{28,30,43,45}, //B
{ 3,21,11,17},{ 2,20,10,16},{26,28,47,37},{24,29,45,38},{27,46,36,25}, //R
{ 6, 4, 2, 0},{ 3, 1, 7, 5},{33,30,27,24},{26,35,32,29},{28,25,34,31}, //U
{10,12,14, 8},{11,13,15, 9},{36,45,42,39},{37,46,43,40},{47,44,41,38}, //D
{17,20,23,18},{21,22,19,16}, //E
};
main() {
int i,j,k=0,m,x;
for(i=0;i<4;i++) {
for(j=0;j<24;j++) {
if(alg_table[i][j]) {
if(k) {
printf("%c", k-1+'#');
k=0;
}
for(m=0;alg_table[i][j][m];m+=2) {
/* printf("%c",(strchr(movenames,alg_table[i][j][m])-movenames)*4+ */
/* alg_table[i][j][m+1]-'0'+','); */
printf("%c",(strchr(movenames,alg_table[i][j][m])-movenames)*3+
alg_table[i][j][m+1]-'1'+',');
}
}
k++;
}
}
if(k>1) {
printf("%c", k-1+'#');
}
printf("\n\n",k);
for(i=0;i<32;i++) {
for(j=0;j<4;j++) {
printf("%c", move_table[i][j]+',');
}
}
printf("\n");
}
|
the_stack_data/189906.c | #define _XOPEN_SOURCE 700
#include <errno.h>
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
int
head(FILE *f, int n) {
int i;
ssize_t bytes;
char *buf = NULL;
size_t len = 0;
for (i = 0; i < n; i++) {
bytes = getline(&buf, &len, f);
if (bytes == -1) {
if (ferror(f)) {
fprintf(stderr, "head: %s\n", strerror(errno));
return 1;
}
if (feof(f))
break;
}
if (write(1, buf, bytes) == -1) {
fprintf(stderr, "head: %s\n", strerror(errno));
return 1;
}
}
free(buf);
return 0;
}
int
main(int argc, char **argv) {
int n = 10;
int ret = 0;
int c;
while ((c = getopt(argc, argv, ":n:")) != -1) {
switch (c) {
case 'n':
n = atoi(optarg);
if (n <= 0) {
fprintf(stderr, "head: invalid number '%s'\n", optarg);
return 1;
}
break;
case ':':
case '?':
fprintf(stderr, "usage: %s [-n num] [file...]\n", *argv);
return 1;
}
}
argc -= optind;
argv += optind - 1;
if (argc == 0)
return head(stdin, n);
FILE *f;
while (*++argv) {
if (**argv == '-' && *(*argv + 1) == '\0')
f = stdin;
else {
f = fopen(*argv, "r");
if (f == NULL) {
fprintf(stderr, "head: %s: %s\n", *argv, strerror(errno));
ret = 1;
continue;
}
}
if (head(f, n) != 0)
ret = 1;
if (f != stdin && fclose(f) == EOF) {
fprintf(stderr, "head: %s: %s\n", *argv, strerror(errno));
ret = 1;
continue;
}
}
return ret;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.