added
stringdate 2024-11-18 17:54:19
2024-11-19 03:39:31
| created
timestamp[s]date 1970-01-01 00:04:39
2023-09-06 04:41:57
| id
stringlengths 40
40
| metadata
dict | source
stringclasses 1
value | text
stringlengths 13
8.04M
| score
float64 2
4.78
| int_score
int64 2
5
|
---|---|---|---|---|---|---|---|
2024-11-18T22:25:41.843946+00:00 | 2017-12-09T09:02:08 | c512dba3726d48bc204df88d8c32189678b66867 | {
"blob_id": "c512dba3726d48bc204df88d8c32189678b66867",
"branch_name": "refs/heads/master",
"committer_date": "2017-12-09T09:02:08",
"content_id": "0d3f0951894192dc06db1d50d7bee2325067a737",
"detected_licenses": [
"MIT"
],
"directory_id": "703320aa14a4d7c4f8638df5a65e388bde8330bc",
"extension": "c",
"filename": "vertex_extreme.c",
"fork_events_count": 0,
"gha_created_at": "2017-03-02T07:02:12",
"gha_event_created_at": "2017-03-02T07:14:25",
"gha_language": "Matlab",
"gha_license_id": null,
"github_id": 83645821,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1524,
"license": "MIT",
"license_type": "permissive",
"path": "/+ndg_utility/+limiter/+VB/@VB_2d/private/vertex_extreme.c",
"provenance": "stackv2-0115.json.gz:134861",
"repo_name": "RGQTJU/NDG-FEM",
"revision_date": "2017-12-09T09:02:08",
"revision_id": "46f69cf4cbdb8d95fd4cc78118003c6d79a311d3",
"snapshot_id": "15f3411eea5f84255160a455e22f8ea57e7d7472",
"src_encoding": "WINDOWS-1252",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/RGQTJU/NDG-FEM/46f69cf4cbdb8d95fd4cc78118003c6d79a311d3/+ndg_utility/+limiter/+VB/@VB_2d/private/vertex_extreme.c",
"visit_date": "2019-08-05T21:50:13.440636"
} | stackv2 | #include "mex.h"
#ifdef _OPENMP
#include <omp.h>
#endif
#define INFITY 10e10
#define max(a,b) ( (a>b)?a:b )
#define min(a,b) ( (a<b)?a:b )
#define DEBUG 0
/*
* Find max and min vertex values.
*
* Usages:
* [fmax, fmin] = vertex_extreme(Kv, VToE, fmean)
*/
void mexFunction(int nlhs, mxArray *plhs[],
int nrhs, const mxArray *prhs[])
{
/* check input & output */
if (nrhs != 3) mexErrMsgTxt("Wrong number of input arguments.");
if (nlhs != 2) mexErrMsgTxt("Wrong number of output arguments");
/* get inputs */
double *Kv = mxGetPr(prhs[0]);
double *VToE = mxGetPr(prhs[1]);
double *f_mean = mxGetPr(prhs[2]);
size_t maxNe = mxGetM(prhs[1]);
size_t Nv = mxGetN(prhs[1]);
/* allocation of output */
plhs[0] = mxCreateDoubleMatrix((mwSize)Nv, (mwSize)1, mxREAL);
plhs[1] = mxCreateDoubleMatrix((mwSize)Nv, (mwSize)1, mxREAL);
double *f_max = mxGetPr(plhs[0]);
double *f_min = mxGetPr(plhs[1]);
int n,m;
for(n=0;n<Nv;n++){ // initialization
f_max[n] = -INFITY;
f_min[n] = INFITY;
}
#ifdef _OPENMP
#pragma omp parallel for private(m) num_threads(DG_THREADS)
#endif
for(n=0;n<Nv;n++){
int Ne = Kv[n]; // ?????????�?
double *vtoe = VToE + n*maxNe;
#if DEBUG
mexPrintf("n=%d, Ne=%d\n", n, Ne);
#endif
for(m=0;m<Ne;m++){
int eid = (int) vtoe[m]-1; // ???ç¼??
f_max[n] = max(f_max[n], f_mean[eid]);
f_min[n] = min(f_min[n], f_mean[eid]);
#if DEBUG
mexPrintf("m=%d, eid=%d, f_mean=%f\n", m, eid, f_mean[eid]);
#endif
}
}
return;
} | 2.484375 | 2 |
2024-11-18T22:25:42.184039+00:00 | 2017-10-11T15:07:19 | a4a822c835c8b305e836d234a6de1fdceeba9206 | {
"blob_id": "a4a822c835c8b305e836d234a6de1fdceeba9206",
"branch_name": "refs/heads/master",
"committer_date": "2017-10-11T15:07:19",
"content_id": "b670139e0c970e9601da428dbac2cf8fda81bd92",
"detected_licenses": [
"MIT"
],
"directory_id": "a8518e223b82b8b5df6168e0bd6598d178e52300",
"extension": "c",
"filename": "lnx_net.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 53080263,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 8417,
"license": "MIT",
"license_type": "permissive",
"path": "/base/lnx_net.c",
"provenance": "stackv2-0115.json.gz:135248",
"repo_name": "cr88192/bgbtech_engine2",
"revision_date": "2017-10-11T15:07:19",
"revision_id": "e6c0e11f0b70ac8544895a10133a428d5078d413",
"snapshot_id": "22b9ab421ffb973095d861429703e71fc89e88fe",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/cr88192/bgbtech_engine2/e6c0e11f0b70ac8544895a10133a428d5078d413/base/lnx_net.c",
"visit_date": "2020-12-25T16:54:08.057153"
} | stackv2 | //#define CONF_USEIPV6
#include <bgbnet.h>
// #ifdef linux
#if defined(linux) || defined(__EMSCRIPTEN__)
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <sys/param.h>
#include <sys/ioctl.h>
#include <errno.h>
#ifndef MAXHOSTNAMELEN
#define MAXHOSTNAMELEN 64
#endif
char local_hostname[MAXHOSTNAMELEN];
unsigned long local_ipv4addr;
byte local_ipv6addr[16];
static byte in6_addr_any[16]=
{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
static byte in6_addr_loopback[16]=
{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1};
char *ipv4tostr(unsigned long addr)
{
unsigned long addrc;
static char buf[4][16], slot=0;
addrc=ntohl(addr);
slot%=4;
sprintf(buf[slot++], "%d.%d.%d.%d", (addrc>>24)&0xff, (addrc>>16)&0xff,
(addrc>>8)&0xff, addrc&0xff);
return(buf[slot-1]);
}
char *ipv6tostr(byte *addr)
{
unsigned short *addrc;
char *buf, *s;
int i;
addrc=(unsigned short *)addr;
buf=gcralloc(64);
// sprintf(buf, "%04x:%04x:%04x:%04x:%04x:%04x:%04x:%04x",
// ntohs(addrc[0]), ntohs(addrc[1]), ntohs(addrc[2]), ntohs(addrc[3]),
// ntohs(addrc[4]), ntohs(addrc[5]), ntohs(addrc[6]), ntohs(addrc[7]));
s=buf;
i=0;
while(ntohs(addrc[i]))
{
if(i>=8)break;
if(i)*s++=':';
sprintf(s, "%x", ntohs(addrc[i]));
s+=strlen(s);
i++;
}
if((i<8) && !ntohs(addrc[i]))
{
*s++=':';
*s=0;
while(!ntohs(addrc[i]))
i++;
}
while(ntohs(addrc[i]))
{
if(i>=8)break;
if(i)*s++=':';
sprintf(s, "%x", ntohs(addrc[i]));
s+=strlen(s);
i++;
}
return(buf);
}
/*--
Cat pdnet;NET;Sock
Form
char *NET_Addr2Str(VADDR *addr);
Description
Converts addr to a string (allocated with gcralloc).
IPv4: a.b.c.d:port
IPv6: [...]:port, where ... is the typical convention.
--*/
char *NET_Addr2Str(VADDR *addr)
{
char *s, *t;
int addrc;
switch(addr->proto)
{
case PROTO_IPV4UDP:
case PROTO_IPV4TCP:
s=gcralloc(64);
addrc=ntohl(addr->ipv4.addr);
sprintf(s, "%d.%d.%d.%d:%d",
(addrc>>24)&0xff, (addrc>>16)&0xff,
(addrc>>8)&0xff, addrc&0xff,
ntohs(addr->ipv4.port));
break;
case PROTO_IPV6UDP:
case PROTO_IPV6TCP:
s=ipv6tostr(addr->ipv6.addr);
t=gcralloc(strlen(s)+10);
sprintf(t, "[%s]:%d", s, ntohs(addr->ipv6.port));
break;
default:
s=gcralloc(1);
*s=0;
break;
}
return(s);
}
static int str2ipv4(char *s, int *port)
{
int a, b, c, d;
sscanf(s, "%d.%d.%d.%d:%d", &a, &b, &c, &d, port);
return((a<<24)+(b<<16)+(c<<8)+d);
}
static int ishexnum(char c)
{
if((c>='0') && (c<='9'))return(1);
if((c>='A') && (c<='F'))return(1);
if((c>='a') && (c<='f'))return(1);
return(0);
}
static int hexval(char c)
{
if((c>='0') && (c<='9'))return(c-'0');
if((c>='A') && (c<='F'))return((c-'A')+10);
if((c>='a') && (c<='f'))return((c-'a')+10);
return(0);
}
static char *str2ipv6(byte *addr, char *s)
{
short buf1[16], buf2[16];
short *t1, *t2, *t3;
int i;
char buf[16];
char *t;
memset(buf1, 0, 16);
memset(buf2, 0, 16);
if(*s=='[')s++;
t1=buf1;
while(*s)
{
t=buf;
while(ishexnum(*s))*t++=*s++;
*t++=0;
if(buf[0])
{
i=0;
t=buf;
while(*t)i=(i<<4)+hexval(*t++);
*t1++=i;
}
if(*s!=':')break;
s++;
if(*s==':')
{
s++;
break;
}
}
t1=buf2;
while(*s)
{
t=buf;
while(ishexnum(*s))*t++=*s++;
*t++=0;
if(buf[0])
{
i=0;
t=buf;
while(*t)i=(i<<4)+hexval(*t++);
*t1++=i;
}
if(*s!=':')break;
s++;
if(*s==':')
{
s++;
break;
}
}
if(*s==']')s++;
t2=buf1+(8-(t1-buf2));
t3=buf2;
while(t3<t1)*t2++=*t3++;
t=addr;
for(i=0; i<8; i++)
{
*t++=buf1[i]>>8;
*t++=buf1[i]&0xff;
}
return(s);
}
/*--
Cat pdnet;NET;Sock
Form
VADDR *NET_Str2Addr(char *str, int proto);
Description
Parses the address from a string.
proto identifies the expected protocol.
--*/
VADDR *NET_Str2Addr(char *str, int proto)
{
VADDR *tmp;
char *s;
switch(proto)
{
case PROTO_IPV4UDP:
case PROTO_IPV4TCP:
tmp=gcalloc(sizeof(VADDR));
tmp->proto=proto;
// tmp->ipv4.addr=htonl(str2ipv4(str, &tmp->ipv4.port));
tmp->ipv4.port=htons(tmp->ipv4.port);
break;
case PROTO_IPV6UDP:
case PROTO_IPV6TCP:
tmp=gcalloc(sizeof(VADDR));
tmp->proto=proto;
s=str2ipv6(tmp->ipv6.addr, str);
sscanf(s, ":%d", &tmp->ipv6.port);
tmp->ipv6.port=htons(tmp->ipv6.port);
break;
default:
tmp=NULL;
break;
}
return(tmp);
}
/*--
Cat pdnet;NET;Sock
Form
int NET_InitLow ();
Description
Init the low-level portion of the net stuff (namely, sockets).
--*/
int NET_InitLow (void)
{
struct hostent *local;
char buff[MAXHOSTNAMELEN];
char *colon;
// WSADATA wsaData;
int err;
VADDR *addr;
static int started=0;
if(started)return(0);
started=1;
printf("Net Init Low (Linux).\n");
// determine my name & address
// gethostname(buff, MAXHOSTNAMELEN);
strcpy(local_hostname, buff);
local = gethostbyname(buff);
if(local)local_ipv4addr = *(int *)local->h_addr_list[0];
else local_ipv4addr = INADDR_ANY;
printf(" hostname=%s\n", buff);
printf(" IPv4=%s\n", ipv4tostr(local_ipv4addr));
#ifdef CONF_USEIPV6
// local = gethostbyname2(buff, AF_INET6);
// if(local)memcpy(local_ipv6addr, local->h_addr_list[0], 16);
// else memcpy(local_ipv6addr, &in6addr_any, 16);
addr=NET_LookupHost2(buff, NULL, PROTO_IPV6TCP);
if(addr)memcpy(local_ipv6addr, addr->ipv6.addr, 16);
else memcpy(local_ipv6addr, &in6_addr_loopback, 16);
printf(" IPv6: %s\n", ipv6tostr(local_ipv6addr));
#endif
printf("TCP Initialized\n");
}
/*--
Cat pdnet;NET;Sock
Form
VADDR *NET_LookupHost(char *name);
Description
Lookup the host address for name.
--*/
BGBNET_API VADDR *NET_LookupHost(char *name)
{
struct hostent *local;
VADDR *tmp;
#ifdef CONF_USEIPV6
struct addrinfo hint, *inf;
char *serve="0";
struct sockaddr_in6 *addr6;
#endif
int i;
tmp=gcalloc(sizeof(VADDR));
//#ifdef CONF_USEIPV6
#if 0
// local = gethostbyname2(name, AF_INET6);
memset(&hint, 0, sizeof(struct addrinfo));
hint.ai_family=AF_INET6;
i=getaddrinfo(name, NULL, &hint, &inf);
if(!i)
{
addr6=inf->ai_addr;
tmp->proto=PROTO_IPV6TCP;
tmp->ipv6.port=0;
memcpy(tmp->ipv6.addr, &addr6->sin6_addr, 16);
return(tmp);
}
#endif
// local = gethostbyname2(name, AF_INET);
local = gethostbyname(name);
if(local)
{
tmp->proto=PROTO_IPV4TCP;
tmp->ipv4.port=0;
tmp->ipv4.addr = *(int *)local->h_addr_list[0];
return(tmp);
}
gcfree(tmp);
return(NULL);
}
#ifdef CONF_USEIPV6
/*--
Cat pdnet;NET;Sock
Form
VADDR *NET_LookupHost2(char *name, char *serv, int proto);
Description
Also looks up the address for name, but also includes "serve" and proto.
--*/
BGBNET_API VADDR *NET_LookupHost2(char *name, char *serv, int proto)
{
struct hostent *local;
VADDR *tmp;
struct addrinfo hint, *inf;
char *serve="0";
struct sockaddr_in6 *addr6;
int i;
tmp=gcalloc(sizeof(VADDR));
// local = gethostbyname2(name, AF_INET6);
memset(&hint, 0, sizeof(struct addrinfo));
switch(proto)
{
case PROTO_IPV4:
case PROTO_IPV4UDP:
case PROTO_IPV4TCP:
hint.ai_family=AF_INET;
break;
case PROTO_IPV6:
case PROTO_IPV6UDP:
case PROTO_IPV6TCP:
hint.ai_family=AF_INET6;
break;
default:
hint.ai_family=AF_INET;
proto=PROTO_IPV4TCP;
break;
}
i=getaddrinfo(name, serv, &hint, &inf);
if(!i)
{
addr6=inf->ai_addr;
tmp->proto=proto;
tmp->ipv6.port=0;
memcpy(tmp->ipv6.addr, &addr6->sin6_addr, 16);
return(tmp);
}
gcfree(tmp);
return(NULL);
}
#endif
#if 1
/*--
Cat pdnet;NET;Sock
Form
VADDR *NET_DecodeHostname(char *name);
Description
Identifies the protocol and decodes the address if possible, otherwise assuming it is a hostname and performing a lookup.
--*/
BGBNET_API VADDR *NET_DecodeHostnamePort(char *name, int defport)
{
char tb[256];
VADDR *tmp;
char *s, *t;
int port;
if(name[0]=='[')
{
tmp=NET_Str2Addr(name, PROTO_IPV6TCP);
if(tmp && (!tmp->ipv6.port))
tmp->ipv6.port=defport;
return(tmp);
}
if((name[0]>='0') && (name[0]<='9'))
{
tmp=NET_Str2Addr(name, PROTO_IPV4TCP);
if(tmp && (!tmp->ipv4.port))
tmp->ipv4.port=defport;
return(tmp);
}
s=name; t=tb;
while(*s && (*s!=':'))*t++=*s++;
*t++=0;
if(*s==':')port=atoi(s+1);
else port=defport;
#ifdef CONF_USEIPV6
tmp=NET_LookupHost2(name, PROTO_IPV6);
if(tmp)return(tmp);
#endif
tmp=NET_LookupHost(name);
if(tmp && (tmp->proto==PROTO_IPV4TCP))
tmp->ipv4.port=htons(port);
return(tmp);
}
BGBNET_API VADDR *NET_DecodeHostname(char *name)
{ return(NET_DecodeHostnamePort(name, 0)); }
#endif
#endif
| 2.390625 | 2 |
2024-11-18T22:25:42.589959+00:00 | 2022-08-24T08:26:13 | a5b414495e3f994fdbd14b6b188991a5468c8666 | {
"blob_id": "a5b414495e3f994fdbd14b6b188991a5468c8666",
"branch_name": "refs/heads/master",
"committer_date": "2022-08-24T08:45:13",
"content_id": "dc37dada6b0d707f16d427ff9e5be89c92e77d8e",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "8aa62ead9aa06e286f88b71ab93f9b960458a0ed",
"extension": "c",
"filename": "ls_hal_hash.c",
"fork_events_count": 37,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 133309942,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 4715,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/modules/hal/crypto/demo/src/ls_hal_hash.c",
"provenance": "stackv2-0115.json.gz:135767",
"repo_name": "alibaba/id2_client_sdk",
"revision_date": "2022-08-24T08:26:13",
"revision_id": "a8955eb7fc7f4b6d33a8d8810aa93ae3bd176007",
"snapshot_id": "424643ec4b302874ab3b4555497a6bc8860f1dfc",
"src_encoding": "UTF-8",
"star_events_count": 92,
"url": "https://raw.githubusercontent.com/alibaba/id2_client_sdk/a8955eb7fc7f4b6d33a8d8810aa93ae3bd176007/modules/hal/crypto/demo/src/ls_hal_hash.c",
"visit_date": "2023-03-12T21:17:09.629627"
} | stackv2 | /*
* Copyright (C) 2016-2019 Alibaba Group Holding Limited
*/
#include "ls_hal.h"
#include "md5.h"
#include "sha1.h"
#include "sha256.h"
#include "sm3.h"
int ls_hal_md5_get_size(void)
{
int size = sizeof(impl_md5_ctx_t);
return size;
}
int ls_hal_md5_init(void *ctx)
{
impl_md5_ctx_t *impl_ctx;
if (ctx == NULL) {
LS_HAL_LOG("invalid ctx\n");
return HAL_CRYPT_INVALID_CONTEXT;
}
impl_ctx = (impl_md5_ctx_t *)ctx;
impl_md5_init(&impl_ctx->context);
impl_md5_starts(&impl_ctx->context);
return HAL_CRYPT_SUCCESS;
}
int ls_hal_md5_update(void *ctx, const uint8_t *src, size_t size)
{
impl_md5_ctx_t *impl_ctx;
if (ctx == NULL) {
LS_HAL_LOG("invalid ctx\n");
return HAL_CRYPT_INVALID_CONTEXT;
}
if (src == NULL && size != 0) {
LS_HAL_LOG("src is NULL and non-zero size\n");
return HAL_CRYPT_INVALID_ARG;
}
impl_ctx = (impl_md5_ctx_t *)ctx;
impl_md5_update(&impl_ctx->context, src, size);
return HAL_CRYPT_SUCCESS;
}
int ls_hal_md5_finish(void *ctx, uint8_t digest[16])
{
impl_md5_ctx_t *impl_ctx;
if (ctx == NULL) {
LS_HAL_LOG("invalid ctx\n");
return HAL_CRYPT_INVALID_CONTEXT;
}
impl_ctx = (impl_md5_ctx_t *)ctx;
impl_md5_finish(&impl_ctx->context, digest);
return HAL_CRYPT_SUCCESS;
}
int ls_hal_sha1_get_size(void)
{
int size = sizeof(impl_sha1_ctx_t);
return size;
}
int ls_hal_sha1_init(void *ctx)
{
impl_sha1_ctx_t *impl_ctx;
if (ctx == NULL) {
LS_HAL_LOG("invalid ctx\n");
return HAL_CRYPT_INVALID_CONTEXT;
}
impl_ctx = (impl_sha1_ctx_t *)ctx;
impl_sha1_init(&impl_ctx->context);
impl_sha1_starts(&impl_ctx->context);
return HAL_CRYPT_SUCCESS;
}
int ls_hal_sha1_update(void *ctx, const uint8_t *src, size_t size)
{
impl_sha1_ctx_t *impl_ctx;
if (ctx == NULL) {
LS_HAL_LOG("invalid ctx\n");
return HAL_CRYPT_INVALID_CONTEXT;
}
if (src == NULL && size != 0) {
LS_HAL_LOG("NULL src and non-zero size\n");
return HAL_CRYPT_INVALID_ARG;
}
impl_ctx = (impl_sha1_ctx_t *)ctx;
impl_sha1_update(&impl_ctx->context, src, size);
return HAL_CRYPT_SUCCESS;
}
int ls_hal_sha1_finish(void *ctx, uint8_t digest[20])
{
impl_sha1_ctx_t * impl_ctx;
if (ctx == NULL) {
LS_HAL_LOG("invalid ctx\n");
return HAL_CRYPT_INVALID_CONTEXT;
}
impl_ctx = (impl_sha1_ctx_t *)ctx;
impl_sha1_finish(&impl_ctx->context, digest);
return HAL_CRYPT_SUCCESS;
}
int ls_hal_sha256_get_size(void)
{
return sizeof(impl_sha256_ctx_t);
}
int ls_hal_sha256_init(void *ctx)
{
impl_sha256_ctx_t *impl_ctx;
if (ctx == NULL) {
LS_HAL_LOG("invalid ctx\n");
return HAL_CRYPT_INVALID_CONTEXT;
}
impl_ctx = (impl_sha256_ctx_t *)ctx;
impl_sha256_init(&impl_ctx->context);
impl_sha256_starts(&impl_ctx->context, 0);
return HAL_CRYPT_SUCCESS;
}
int ls_hal_sha256_update(void *ctx, const uint8_t *src, size_t size)
{
impl_sha256_ctx_t *impl_ctx;
if (ctx == NULL) {
LS_HAL_LOG("invalid ctx\n");
return HAL_CRYPT_INVALID_CONTEXT;
}
impl_ctx = (impl_sha256_ctx_t *)ctx;
impl_sha256_update(&impl_ctx->context, src, size);
return HAL_CRYPT_SUCCESS;
}
int ls_hal_sha256_finish(void *ctx, uint8_t digest[32])
{
impl_sha256_ctx_t *impl_ctx;
if (ctx == NULL) {
LS_HAL_LOG("invalid ctx\n");
return HAL_CRYPT_INVALID_CONTEXT;
}
impl_ctx = (impl_sha256_ctx_t *)ctx;
impl_sha256_finish(&impl_ctx->context, digest);
return HAL_CRYPT_SUCCESS;
}
int ls_hal_sm3_get_size(void)
{
return sizeof(impl_sm3_ctx_t);
}
int ls_hal_sm3_init(void *ctx)
{
impl_sm3_ctx_t *impl_ctx;
if (ctx == NULL) {
LS_HAL_LOG("invalid ctx\n");
return HAL_CRYPT_INVALID_CONTEXT;
}
impl_ctx = (impl_sm3_ctx_t *)ctx;
impl_sm3_init(&impl_ctx->context);
impl_sm3_starts(&impl_ctx->context);
return HAL_CRYPT_SUCCESS;
}
int ls_hal_sm3_update(void *ctx, const uint8_t *src, size_t size)
{
impl_sm3_ctx_t *impl_ctx;
if (ctx == NULL) {
LS_HAL_LOG("invalid ctx\n");
return HAL_CRYPT_INVALID_CONTEXT;
}
impl_ctx = (impl_sm3_ctx_t *)ctx;
impl_sm3_update(&impl_ctx->context, src, size);
return HAL_CRYPT_SUCCESS;
}
int ls_hal_sm3_finish(void *ctx, uint8_t digest[32])
{
impl_sm3_ctx_t *impl_ctx;
if (ctx == NULL) {
LS_HAL_LOG("invalid ctx\n");
return HAL_CRYPT_INVALID_CONTEXT;
}
impl_ctx = (impl_sm3_ctx_t *)ctx;
impl_sm3_finish(&impl_ctx->context, digest);
return HAL_CRYPT_SUCCESS;
}
| 2.4375 | 2 |
2024-11-18T22:25:42.988145+00:00 | 2020-07-19T05:28:53 | 1b469210c70d7bce46ceada4c5e2d6fb0542f70e | {
"blob_id": "1b469210c70d7bce46ceada4c5e2d6fb0542f70e",
"branch_name": "refs/heads/master",
"committer_date": "2020-07-19T05:28:53",
"content_id": "22aa910450f923fac2b5c6aa39bf06161654406b",
"detected_licenses": [
"Unlicense"
],
"directory_id": "e259867303b525e579bcd96605b19b9c6261de50",
"extension": "c",
"filename": "libfchucker.c",
"fork_events_count": 1,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 280796169,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 9828,
"license": "Unlicense",
"license_type": "permissive",
"path": "/libfchucker.c",
"provenance": "stackv2-0115.json.gz:136411",
"repo_name": "NCDyson/FCHucker",
"revision_date": "2020-07-19T05:28:53",
"revision_id": "9e38eed77a8b78bf78fc0654c440d64042c5493f",
"snapshot_id": "2b882bdf1c6660639db4d885c63548e60292fefb",
"src_encoding": "UTF-8",
"star_events_count": 3,
"url": "https://raw.githubusercontent.com/NCDyson/FCHucker/9e38eed77a8b78bf78fc0654c440d64042c5493f/libfchucker.c",
"visit_date": "2022-11-15T21:45:23.978231"
} | stackv2 | #include "libfchucker.h"
#include "memcard.h"
#include <fcntl.h>
#include <errno.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include "util.h"
u8 Slot1CharacterNames[32 * 3];
u8 Slot2CharacterNames[32 * 3];
u32 Slot1CharacterFlags = 7;
u32 Slot2CharacterFlags = 7;
u8 * SourceInventory = NULL;
u8 * DestInventory = NULL;
int SourceInventoryCount = 0;
int SourceStorageCount = 0;
int DestInventoryCount = 0;
int DestStorageCount = 0;
int SourceGP = 0;
int DestGP = 0;
//For stuff, IDK
int SourceMCSlot = 0;
int SourceCharacterSlot = 0;
int DestMCSlot = 0;
int DestCharacterSlot = 0;
static char MCDIRStr[256];
#define XORPAD_SIZE 9
static u8 xorPad[XORPAD_SIZE] = {0x55, 0xc3, 0x3a, 0xcc, 0xa5, 0xaa, 0x33, 0x5a, 0x3c};
#define SWAPINDICES_SIZE 7
static u8 swapIndices[7] = {0x23, 0xd, 0x17, 0x1, 0x1f, 0x29, 0x13};
//Someday, I suppose
//const char * BackupDIR = "BISLPS-25527HUCKER";
const char * FragmentDIR= "BISLPS-25527DOTHACK";
int CheckForFragmentSave(int slot)
{
sprintf(MCDIRStr, "mc%d:%s/icon.sys", slot, FragmentDIR);
int fd = open(MCDIRStr, O_RDONLY);
if(fd <= 0)
{
if(slot == 0)
{
Slot1CharacterFlags = 0;
}
else
{
Slot2CharacterFlags = 0;
}
if(SourceMCSlot == slot)
{
SourceMCSlot = -1;
SourceCharacterSlot = -1;
}
if(DestMCSlot == slot)
{
DestMCSlot = -1;
DestCharacterSlot = -1;
}
return 0;
}
else
{
close(fd);
return 1;
}
return 0;
}
u32 EnumerateCharacters(int slot)
{
u32 * SlotCharacterFlags = NULL;
u8 * slot1Name = NULL;
u8 * slot2Name = NULL;
u8 * slot3Name = NULL;
if(slot == 0)
{
slot1Name = &Slot1CharacterNames[0];
SlotCharacterFlags = &Slot1CharacterFlags;
}
else
{
slot1Name = &Slot2CharacterNames[0];
SlotCharacterFlags = &Slot2CharacterFlags;
}
slot2Name = &slot1Name[0x20];
slot3Name = &slot1Name[0x40];
//Get main file
sprintf(MCDIRStr, "mc%d:%s/%s", slot, FragmentDIR, FragmentDIR);
int fd = open(MCDIRStr, O_RDONLY);
if(fd <= 0)
{
return -1;
}
u32 fSize = (u32)lseek(fd, 0, SEEK_END);
lseek(fd, 0, SEEK_SET);
u8 * data = malloc(fSize);
if(data == NULL)
{
close(fd);
return -1;
}
read(fd, data, fSize);
close(fd);
DecryptSaveFile(data, fSize);
u8 * Char1 = &data[0xc];
u8 * Char2 = &data[0x54];
u8 * Char3 = &data[0x9c];
*SlotCharacterFlags = 0;
if(*((u32*)Char1) != 0)
{
//Char valid, maybe, copy the name
memcpy(slot1Name, Char1 + 4, 16);
slot1Name[16] = 0;
*SlotCharacterFlags |= 1;
if(SourceMCSlot == -1) SourceMCSlot = slot;
if(SourceCharacterSlot == -1) SourceCharacterSlot = 0;
if(DestMCSlot == -1) DestMCSlot = slot;
if(DestCharacterSlot == -1) DestCharacterSlot = 0;
}
else
{
//*slot1Name = "No Character";
sprintf((char *)slot1Name,"No Character");
*SlotCharacterFlags &= 0xFFFFFFFE;
}
if(*((u32*)Char2) != 0)
{
memcpy(slot2Name, (Char2 + 4), 16);
slot2Name[16] = 0;
*SlotCharacterFlags |= 2;
if(SourceMCSlot == -1) SourceMCSlot = slot;
if(SourceCharacterSlot == -1) SourceCharacterSlot = 1;
if(DestMCSlot == -1) DestMCSlot = slot;
if(DestCharacterSlot == -1) DestCharacterSlot = 1;
}
else
{
//slot2Name = "No Character";
sprintf((char * )slot2Name,"No Character");
*SlotCharacterFlags &= 0xFFFFFFFD;
}
if(*((u32 *)Char3) != 0)
{
memcpy(slot3Name, (Char3 + 4), 16);
slot3Name[16] = 0;
*SlotCharacterFlags |= 4;
//printf("Slot %d, Character 3: %s\n", slot, slot3Name);
if(SourceMCSlot == -1) SourceMCSlot = slot;
if(SourceCharacterSlot == -1) SourceCharacterSlot = 1;
if(DestMCSlot == -1) DestMCSlot = slot;
if(DestCharacterSlot == -1) DestCharacterSlot = 1;
}
else
{
//*slot3Name = "No Character";
sprintf((char *)slot3Name,"No Character");
*SlotCharacterFlags &= 0xFFFFFFFB;
}
free(data);
return *SlotCharacterFlags;
}
int ReadCharacter(int slot, int id, int dest)
{
sprintf(MCDIRStr, "mc%d:%s/dhdata0%d", slot, FragmentDIR, id + 1);
int fd = open(MCDIRStr, O_RDONLY);
if(fd <= 0)
{
return -1;
}
u32 fSize = (u32)lseek(fd, 0, SEEK_END);
lseek(fd, 0, SEEK_SET);
u8 * data = malloc(fSize);
if(data == NULL)
{
close(fd);
return -1;
}
read(fd, data, fSize);
close(fd);
DecryptSaveFile(data, fSize);
u8 * inventory = malloc(INVENTORY_SIZE + STORAGE_SIZE);
memcpy(inventory, data + INVENTORY_OFFSET, INVENTORY_SIZE);
memcpy(inventory + INVENTORY_SIZE, data + STORAGE_OFFSET, STORAGE_SIZE);
//int gp = *(int *)(&data + GPOffset);
int * money = &SourceGP;
if(dest) money = &DestGP;
*money = *(int*)(data + GPOffset);
free(data);
if(dest)
{
if(DestInventory) free(DestInventory);
DestInventory = inventory;
}
else
{
if(SourceInventory) free(SourceInventory);
SourceInventory = inventory;
}
return 0;
}
int WriteCharacter(int slot, int id, int dest)
{
sprintf(MCDIRStr, "mc%d:%s/dhdata0%d", slot, FragmentDIR, id + 1);
int fd = open(MCDIRStr, O_RDONLY);
if(fd <= 0)
{
return -1;
}
u32 fSize = (u32)lseek(fd, 0, SEEK_END);
lseek(fd, 0, SEEK_SET);
u8 * data = malloc(fSize);
if(data == NULL)
{
close(fd);
return -1;
}
read(fd, data, fSize);
close(fd);
DecryptSaveFile(data, fSize);
u8 * inventory = SourceInventory;
if(dest) inventory = DestInventory;
memcpy(data + INVENTORY_OFFSET, inventory, INVENTORY_SIZE);
memcpy(data + STORAGE_OFFSET, inventory + INVENTORY_SIZE, STORAGE_SIZE);
int * money = &SourceGP;
if(dest) money = &DestGP;
//*money = *(int*)(data + GPOffset);
int * dGP = (int *)(data + GPOffset);
*dGP = *money;
EncryptSaveFile(data, fSize, slot + 1);
sprintf(MCDIRStr, "mc%d:%s/dhdata0%d", slot, FragmentDIR, id + 1);
fd = open(MCDIRStr, O_WRONLY);
if(fd <= 0)
{
//Well shit...
free(data);
return -1;
}
write(fd, data, fSize);
free(data);
if(dest)
{
free(DestInventory);
DestInventory = NULL;
}
else
{
free(SourceInventory);
SourceInventory = NULL;
}
return 1;
}
u16 Checksum(u8 *input, u32 size, u32 checksumOffset)
{
u16 * checksumField = (u16*)(input + checksumOffset);
//u16 previousChecksum = *checksumField;
*checksumField = 0;
u32 curSum = 0;
u32 i = 0;
for(i = 0; i < (size-1); i++)
{
curSum += (u8)input[i];
curSum &= 0xFFFF;
}
return curSum;
}
void EncryptSaveFile(u8 *data, int dataSize, int fileType)
{
int checksumOffset = 0;
switch (fileType) {
case 1:
case 2:
case 3:
checksumOffset = CHARACTER_FILE_CHECKSUM_OFFSET;
break;
case 4:
checksumOffset = MAIL_FILE_CHECKSUM_OFFSET;
break;
case 5:
checksumOffset = DISKID__FILE_CHECKSUM_OFFSET;
case 0:
default:
checksumOffset = MAIN_FILE_CHECKSUM_OFFSET;
}
//Do checksum real quick...
u16 * checksumField = (u16 *)(data + checksumOffset);
*checksumField = 0;
u32 curSum = 0;
int i = 0;
for(i = 0; i < (dataSize - 1); i++)
{
curSum += (u8)data[i];
curSum &= 0xFFFF;
}
*checksumField = curSum;
//stage 1, NOR data
i = 0;
for(i = 0; i < (dataSize - 1); i++)
{
data[i] = NOR(data[i], 0);
}
//stage 2, generate seed
u32 seed = 0;
for(i = 0; i < (dataSize - 1); i++)
{
u32 tmpSeed = (xorPad[i % XORPAD_SIZE] ^ data[i]) & 0xff;
seed = (seed + tmpSeed) & 0xFF;
}
//stage 3, swap and xor data
for(i = 0; i < dataSize - 1; i++)
{
u32 curSeed = i + seed;
u8 swap1 = data[i];
u32 swapIndex = (swapIndices[curSeed % SWAPINDICES_SIZE] + (seed & 0x3f) + i) % (dataSize - 1);
u8 swap2 = data[swapIndex];
data[i] = swap2 ^ (xorPad[curSeed % XORPAD_SIZE]);
data[swapIndex] = swap1;
}
//stage 4, shift data and place seed
if((dataSize - 1) > 0x46)
{
for(i = (dataSize - 1); i > 0x45; i--)
{
data[i] = data[i - 1];
}
data[0x45] = seed ^ xorPad[1];
}
}
void DecryptSaveFile(u8 *data, int dataSize)
{
//step 1, read seed, set placeholder to 0
u32 seed = (xorPad[1] ^ data[0x45]) & 0xFF;
//step 2, shift data
int i = 0;
for(i = 0x45; i < (dataSize - 1); i++)
{
data[i] = data[i + 1];
}
//stage 3, xor data and swap it
for(i = (dataSize - 2); i > -1; i--)
{
u32 curSeed = i + seed;
u8 swap1 = data[i] ^ xorPad[curSeed % XORPAD_SIZE];
u32 swapIndex = (swapIndices[curSeed % SWAPINDICES_SIZE] + (seed & 0x3f) + i ) % (dataSize - 1);
u8 swap2 = data[swapIndex];
data[i] = swap2;
data[swapIndex] = swap1;
}
//stage 3, episode 1, set placehold for seed to 0
data[dataSize - 1] = 0;
//stage 4, NOR data
for(i = 0; i < (dataSize - 1); i++)
{
data[i] = NOR(data[i], 0);
}
}
void FreeInventory()
{
if(SourceInventory)
{
free(SourceInventory);
SourceInventory = NULL;
}
if(DestInventory)
{
free(DestInventory);
DestInventory = NULL;
}
}
| 2.359375 | 2 |
2024-11-18T22:25:43.100587+00:00 | 2023-08-22T17:23:00 | fab98d5a7e9916bc3e001d49493c4c2dd39cad87 | {
"blob_id": "fab98d5a7e9916bc3e001d49493c4c2dd39cad87",
"branch_name": "refs/heads/master",
"committer_date": "2023-08-22T17:23:46",
"content_id": "9817e265e44921adb304e78b45f3c6713b98c14e",
"detected_licenses": [
"MIT"
],
"directory_id": "3a4f120f3211a1482b8ba826f4922fa741c5586e",
"extension": "c",
"filename": "main.c",
"fork_events_count": 327,
"gha_created_at": "2015-11-13T18:23:02",
"gha_event_created_at": "2023-08-22T17:23:47",
"gha_language": "C",
"gha_license_id": "MIT",
"github_id": 46139497,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 3639,
"license": "MIT",
"license_type": "permissive",
"path": "/ip/Pmods/PmodAD1_v1_0/drivers/PmodAD1_v1_0/examples/main.c",
"provenance": "stackv2-0115.json.gz:136668",
"repo_name": "Digilent/vivado-library",
"revision_date": "2023-08-22T17:23:00",
"revision_id": "cbfde215a27053004cb41d85535c4a1bd1673e14",
"snapshot_id": "7135129c7e4fec84d17e1fe037598bd2124085eb",
"src_encoding": "UTF-8",
"star_events_count": 512,
"url": "https://raw.githubusercontent.com/Digilent/vivado-library/cbfde215a27053004cb41d85535c4a1bd1673e14/ip/Pmods/PmodAD1_v1_0/drivers/PmodAD1_v1_0/examples/main.c",
"visit_date": "2023-09-05T22:04:31.189589"
} | stackv2 | /******************************************************************************/
/* */
/* main.c -- PmodAD1 Example Project */
/* */
/******************************************************************************/
/* Author: Arthur Brown */
/* Copyright 2017, Digilent Inc. */
/******************************************************************************/
/* Module Description: */
/* */
/* This file contains code for running a demonstration of the PmodAD1 when */
/* used with the PmodAD1 IP core. This demo initializes the PmodAD1 IP core */
/* and then polls its sample register, printing the analog voltage last */
/* sampled by each of the AD1's two channels over UART. */
/* */
/* Messages printed by this demo can be received by using a serial terminal */
/* configured with the appropriate Baud rate. 115200 for Zynq systems, and */
/* whatever the AXI UARTLITE IP is configured with for MicroBlaze systems, */
/* typically 9600 or 115200 Baud. */
/* */
/******************************************************************************/
/* Revision History: */
/* */
/* 08/15/2017(ArtVVB): Created */
/* 02/10/2018(atangzwj): Validated for Vivado 2017.4 */
/* */
/******************************************************************************/
#include <stdio.h>
#include "PmodAD1.h"
#include "sleep.h"
#include "xil_cache.h"
#include "xil_io.h"
#include "xil_types.h"
#include "xparameters.h"
PmodAD1 myDevice;
const float ReferenceVoltage = 3.3;
void DemoInitialize();
void DemoRun();
void DemoCleanup();
void EnableCaches();
void DisableCaches();
int main() {
DemoInitialize();
DemoRun();
DemoCleanup();
return 0;
}
void DemoInitialize() {
EnableCaches();
AD1_begin(&myDevice, XPAR_PMODAD1_0_AXI_LITE_SAMPLE_BASEADDR);
// Wait for AD1 to finish powering on
usleep(1); // 1 us (minimum)
}
void DemoRun() {
AD1_RawData RawData;
AD1_PhysicalData PhysicalData;
while (1) {
AD1_GetSample(&myDevice, &RawData); // Capture raw samples
// Convert raw samples into floats scaled to 0 - VDD
AD1_RawToPhysical(ReferenceVoltage, RawData, &PhysicalData);
printf("Input Data 1: %.02f; ", PhysicalData[0]);
printf("Input Data 2: %.02f\r\n", PhysicalData[1]);
// Do this 10x per second
usleep(100000);
}
}
void DemoCleanup() {
DisableCaches();
}
void EnableCaches() {
#ifdef __MICROBLAZE__
#ifdef XPAR_MICROBLAZE_USE_ICACHE
Xil_ICacheEnable();
#endif
#ifdef XPAR_MICROBLAZE_USE_DCACHE
Xil_DCacheEnable();
#endif
#endif
}
void DisableCaches() {
#ifdef __MICROBLAZE__
#ifdef XPAR_MICROBLAZE_USE_DCACHE
Xil_DCacheDisable();
#endif
#ifdef XPAR_MICROBLAZE_USE_ICACHE
Xil_ICacheDisable();
#endif
#endif
}
| 2.171875 | 2 |
2024-11-18T22:25:43.242587+00:00 | 2017-04-03T14:04:11 | dbe76d8de4fdd9ae24e60dd77ad744391e739de0 | {
"blob_id": "dbe76d8de4fdd9ae24e60dd77ad744391e739de0",
"branch_name": "refs/heads/master",
"committer_date": "2017-04-03T14:04:11",
"content_id": "fb6d977f580d9a3101aff5fde17898aaa5d8ed93",
"detected_licenses": [
"MIT"
],
"directory_id": "9d121733df655028f133c08e0d8f040ffd5cb08d",
"extension": "c",
"filename": "source.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 86966878,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 240,
"license": "MIT",
"license_type": "permissive",
"path": "/public_html/2015/secret-2e44fac40ce121fc2afdc4cd9bbfe607/2546/source/source.c",
"provenance": "stackv2-0115.json.gz:136797",
"repo_name": "Ikhsanhaw/tisigram2017",
"revision_date": "2017-04-03T14:04:11",
"revision_id": "5270610826d16089e1387b0cadd32b8d098ef89d",
"snapshot_id": "49a7afc131a27f554bcb1936473b1ba9a0100603",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/Ikhsanhaw/tisigram2017/5270610826d16089e1387b0cadd32b8d098ef89d/public_html/2015/secret-2e44fac40ce121fc2afdc4cd9bbfe607/2546/source/source.c",
"visit_date": "2021-01-18T20:29:16.979856"
} | stackv2 | #include <stdio.h>
int faktorial(int n){
if(n==0){
return 1;
} else {
return n*(faktorial(n-1));
}
}
int main(){
int N, M;
scanf("%d %d", &N, &M);
printf("%d\n", faktorial(N)/(faktorial(M)*faktorial(N-M)));
}
| 2.90625 | 3 |
2024-11-18T22:25:43.359610+00:00 | 2016-11-03T15:27:18 | 6e552f8651fbc9718312d721e484ab39548f74e4 | {
"blob_id": "6e552f8651fbc9718312d721e484ab39548f74e4",
"branch_name": "refs/heads/master",
"committer_date": "2016-11-03T15:27:18",
"content_id": "00a434842e57abaa20b205641d4b4fd1c5162b04",
"detected_licenses": [
"MIT"
],
"directory_id": "4bad17ae6d01fccbbb20c1f6eb327070138f8cf4",
"extension": "c",
"filename": "printk.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": null,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1931,
"license": "MIT",
"license_type": "permissive",
"path": "/Kernel/printk.c",
"provenance": "stackv2-0115.json.gz:137056",
"repo_name": "Becavalier/playground-linux",
"revision_date": "2016-11-03T15:27:18",
"revision_id": "b6d391f9b3f546bfc9e6f9404774765fc6b52937",
"snapshot_id": "739bb965864f9f2a7888dbe763d87b8dde0c14be",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/Becavalier/playground-linux/b6d391f9b3f546bfc9e6f9404774765fc6b52937/Kernel/printk.c",
"visit_date": "2021-06-08T13:07:17.860692"
} | stackv2 | /*
Note:
grep -R "printk" | wc -l
printk -> vprintk_emit(产生消息头) -> log_store 将消息先输出到环形缓冲区(128k)再输出到 -> {文件、虚拟设备、控制台}
*/
#include <linux/init.h>
#include <linux/kernel.h>
#include <linux/module.h>
static int __init llaolao_init(void) { // static 表示文件内部函数;__init 编译器属性,为初始化函数;
int n = 0x1937;
// printk 在内核中运行的向控制台输出显示的函数;
printk(KERN_INFO "Hi, I am llaolao at address 0x%p\n",
llaolao_init);
printk(KERN_INFO "symbol: 0x%pF\n",
llaolao_init);
printk(KERN_INFO "stack: 0x%p\n",
&n);
printk(KERN_INFO "first 16 bytes: 0x%p\n",
llaolao_init+0x10);
return 0;
}
static void __exit llaolao_exit(void) { // __exit 编译器属性,为卸载函数;
printk("Exiting from 0x%p ... Bye, YHSPY friends.\n", llaolao_exit);
printk(KERN_EMERG "Testing message with different severity level\n");
printk(KERN_ALERT "Testing message with different severity level\n");
printk(KERN_CRIT "Testing message with different severity level\n");
printk(KERN_ERR "Testing message with different severity level\n");
printk(KERN_WARNING "Testing message with different severity level\n");
printk(KERN_NOTICE "Testing message with different severity level\n");
printk(KERN_INFO "Testing message with different severity level\n");
printk(KERN_DEBUG "Testing message with different severity level\n");
}
// 宏,把上述函数挂载到 GCC 的编译工具链上;
// <linux/init.h> 中定义了这两个宏;
module_init(llaolao_init);
module_exit(llaolao_exit);
// 说明模块作者和版权信息的宏调用;
MODULE_AUTHOR("YHSPY");
MODULE_DESCRIPTION("LKM EXAMPLE - YHSPY");
MODULE_LICENSE("GPL"); // 不可随意修改,内核使用的标准协议,用于各个模块之间的交流;
| 2.703125 | 3 |
2024-11-18T22:25:44.338862+00:00 | 2019-07-26T10:40:27 | 352718ffc26d281f234d3c910c93114d238be423 | {
"blob_id": "352718ffc26d281f234d3c910c93114d238be423",
"branch_name": "refs/heads/master",
"committer_date": "2019-07-26T10:40:27",
"content_id": "a7509cadf6d4da92b8fcb1828d4c1560bb58fa4f",
"detected_licenses": [
"MIT"
],
"directory_id": "2725bed874de7d01173ecd2e2fd1f54d702c07dd",
"extension": "c",
"filename": "graph.c",
"fork_events_count": 2,
"gha_created_at": "2017-11-25T04:06:08",
"gha_event_created_at": "2019-07-26T10:40:28",
"gha_language": "C",
"gha_license_id": "MIT",
"github_id": 111975279,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 5344,
"license": "MIT",
"license_type": "permissive",
"path": "/source/graph.c",
"provenance": "stackv2-0115.json.gz:137964",
"repo_name": "duxingzhe/LearningMasteringAlgorithms-C",
"revision_date": "2019-07-26T10:40:27",
"revision_id": "1d3d800e0561a97a0676aec6c483eb9e9e5a5333",
"snapshot_id": "6ea977f0afaa06236ae3410c45d79a2defc4f66b",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/duxingzhe/LearningMasteringAlgorithms-C/1d3d800e0561a97a0676aec6c483eb9e9e5a5333/source/graph.c",
"visit_date": "2021-05-06T18:15:47.051064"
} | stackv2 | //
// graph.c
// Algorithms - Graph
//
// Created by YourtionGuo on 08/05/2017.
// Copyright © 2017 Yourtion. All rights reserved.
//
#include <stdlib.h>
#include <string.h>
#include "graph.h"
#include "list.h"
#include "set.h"
#pragma mark - Public
void graph_init(Graph *graph,
int (*match)(const void *key1, const void *key2),
void (*destroy)(void *data))
{
/// 初始化图
graph->vcount = 0;
graph->ecount = 0;
graph->match = match;
graph->destroy = destroy;
/// 初始化邻接表结构
list_init(&graph->adjlists, NULL);
return;
}
void graph_destroy(Graph *graph)
{
AdjList *adjlist;
/// 销毁每个邻接表
while (list_size(&graph->adjlists) > 0) {
if (list_rem_next(&graph->adjlists, NULL, (void **)&adjlist) == 0) {
set_destroy(&adjlist->adjacent);
if (graph->destroy != NULL) graph->destroy(adjlist->vertex);
free(adjlist);
}
}
/// 销毁邻接表结构
list_destroy(&graph->adjlists);
/// 清理图数据结构
memset(graph, 0, sizeof(Graph));
return;
}
int graph_ins_vertex(Graph *graph, const void *data)
{
ListElmt *element;
AdjList *adjlist;
int retval;
/// 不允许插入重复的顶点
for (element = list_head(&graph->adjlists); element != NULL; element = list_next(element)) {
if (graph->match(data, ((AdjList *)list_data(element))->vertex)) return 1;
}
/// 插入顶点
if ((adjlist = (AdjList *)malloc(sizeof(AdjList))) == NULL) return -1;
adjlist->vertex = (void *)data;
set_init(&adjlist->adjacent, graph->match, graph->destroy);
if ((retval = list_ins_next(&graph->adjlists, list_tail(&graph->adjlists), adjlist)) != 0) {
return retval;
}
/// 更新顶点数量
graph->vcount++;
return 0;
}
int graph_ins_edge(Graph *graph, const void *data1, const void *data2)
{
ListElmt *element;
int retval;
/// 不允许插入顶点不在图中的边
for (element = list_head(&graph->adjlists); element != NULL; element = list_next(element)) {
if (graph->match(data2, ((AdjList *)list_data(element))->vertex)) break;
}
if (element == NULL) return -1;
for (element = list_head(&graph->adjlists); element != NULL; element = list_next(element)) {
if (graph->match(data1, ((AdjList *)list_data(element))->vertex)) break;
}
if (element == NULL) return -1;
/// 将顶点2插入到顶点1的邻接表
if ((retval = set_insert(&((AdjList *)list_data(element))->adjacent, data2)) != 0) return retval;
/// 更新边数量
graph->ecount++;
return 0;
}
int graph_rem_vertex(Graph *graph, void **data)
{
ListElmt *element, *temp, *prev;
AdjList *adjlist;
int found;
/// 遍历每个邻接表及其包含的顶点
temp = NULL;
prev = NULL;
found = 0;
for (element = list_head(&graph->adjlists); element != NULL; element = list_next(element)) {
/// 不允许删除仍存在于邻接表的顶点
if (set_is_member(&((AdjList *)list_data(element))->adjacent, *data)) return -1;
/// 保存将被删除顶点的指针
if (graph->match(*data, ((AdjList *)list_data(element))->vertex)) {
temp = element;
found = 1;
}
/// 在顶点删除前保持它的指针
if (!found) prev = element;
}
/// 如果顶点不存在返回 -1
if (!found) return -1;
/// 不允许删除它的邻接表不为空的顶点
if (set_size(&((AdjList *)list_data(temp))->adjacent) > 0) return -1;
/// 删除顶点
if (list_rem_next(&graph->adjlists, prev, (void **)&adjlist) != 0) return -1;
/// 销毁之前生成的数据结构
*data = adjlist->vertex;
free(adjlist);
/// 更新顶点数量
graph->vcount--;
return 0;
}
int graph_rem_edge(Graph *graph, void *data1, void **data2)
{
ListElmt *element;
/// 找到第一个节点的邻接表
for (element = list_head(&graph->adjlists); element != NULL; element = list_next(element)) {
if (graph->match(data1, ((AdjList *)list_data(element))->vertex)) break;
}
if (element == NULL) return -1;
/// 从邻接表中删除存在顶点2的边
if (set_remove(&((AdjList *)list_data(element))->adjacent, data2) != 0) return -1;
/// 更新边的数量
graph->ecount--;
return 0;
}
int graph_adjlist(const Graph *graph, const void *data, AdjList **adjlist) {
ListElmt *element, *prev;
/// 找到包含该顶点的邻接表
prev = NULL;
for (element = list_head(&graph->adjlists); element != NULL; element = list_next(element)) {
if (graph->match(data, ((AdjList *)list_data(element))->vertex)) break;
prev = element;
}
/// 找不到顶点返回 -1
if (element == NULL) return -1;
/// 返回该顶点的邻接表
*adjlist = list_data(element);
return 0;
}
int graph_is_adjacent(const Graph *graph, const void *data1, const void *data2)
{
ListElmt *element, *prev;
/// 找到第一个节点的邻接表
prev = NULL;
for (element = list_head(&graph->adjlists); element != NULL; element = list_next(element)) {
if (graph->match(data1, ((AdjList *)list_data(element))->vertex)) break;
prev = element;
}
/// 找不到顶点返回 0
if (element == NULL) return 0;
/// 判断顶点2是否在顶点1的邻接表中
return set_is_member(&((AdjList *)list_data(element))->adjacent, data2);
}
| 2.9375 | 3 |
2024-11-18T22:25:44.409983+00:00 | 2019-11-15T20:26:20 | 799254a219d664ee5553bf1ccbbef8c38674825b | {
"blob_id": "799254a219d664ee5553bf1ccbbef8c38674825b",
"branch_name": "refs/heads/master",
"committer_date": "2019-11-15T20:26:20",
"content_id": "27dd12d2b12e584f797b165fc790232fdfa44396",
"detected_licenses": [
"BSD-3-Clause"
],
"directory_id": "7c2ea365f20ff3eaec12b7a5289c21f345373d40",
"extension": "c",
"filename": "mswinprt.c",
"fork_events_count": 1,
"gha_created_at": "2019-07-08T13:51:17",
"gha_event_created_at": "2019-10-02T11:45:39",
"gha_language": "C",
"gha_license_id": "NOASSERTION",
"github_id": 195821881,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 8824,
"license": "BSD-3-Clause",
"license_type": "permissive",
"path": "/src/oc/mswinprt.c",
"provenance": "stackv2-0115.json.gz:138093",
"repo_name": "wwlytton/nrn",
"revision_date": "2019-11-15T20:26:20",
"revision_id": "32b01882064583582a7ac2b563c4babf874b14ea",
"snapshot_id": "95892cb08b993d0cc9377d7136304bc9196723ef",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/wwlytton/nrn/32b01882064583582a7ac2b563c4babf874b14ea/src/oc/mswinprt.c",
"visit_date": "2020-06-17T05:59:34.145205"
} | stackv2 | #ifndef CYGWIN
#include <../../nrnconf.h>
#endif
#if defined(MINGW)
#define CYGWIN
#endif
#include <windows.h>
#include <stdio.h>
#include <stdarg.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include "hoc.h"
#include "../mswin/extra/d2upath.c"
extern char* neuron_home;
extern char* neuron_home_dos;
extern void hoc_quit();
#if !defined(CYGWIN)
extern HWND hCurrWnd;
#endif
static HCURSOR wait_cursor;
static HCURSOR old_cursor;
#if HAVE_IV
extern int bad_install_ok;
#else
int bad_install_ok;
#endif // HAVE_IV
extern FILE* hoc_redir_stdout;
void setneuronhome(p) char* p; {
// if the program lives in .../bin/neuron.exe
// and .../lib exists then use ... as the
// NEURONHOME
char buf[256]; char *s;
int i, j;
// printf("p=|%s|\n", p);
bad_install_ok = 1;
#if 0
if (p[0] == '"') {
strcpy(buf, p+1);
}else{
strcpy(buf, p);
}
#endif
GetModuleFileName(NULL, buf, 256);
for (i=strlen(buf); i >= 0 && buf[i] != '\\'; --i) {;}
buf[i] = '\0'; // /neuron.exe gone
// printf("setneuronhome |%s|\n", buf);
for (j=strlen(buf); j >= 0 && buf[j] != '\\'; --j) {;}
buf[j] = '\0'; // /bin gone
neuron_home_dos = emalloc(strlen(buf) + 1);
strcpy(neuron_home_dos, buf);
neuron_home = hoc_dos2unixpath(buf);
return;
#if 0
// but make sure it was bin Bin or BIN -- damn you bill gates
// printf("i=%d j=%d buf=|%s|\n",i, j, buf);
if (i == j+4
&&(buf[--i] == 'n' || buf[i] == 'N')
&&(buf[--i] == 'i' || buf[i] == 'I')
&&(buf[--i] == 'b' || buf[i] == 'B')
) {
char buf1[256], *nh_old;
// check for nrn.def or nrn.defaults
// if it exists assume valid installation
FILE* f;
sprintf(buf1, "%s/lib/nrn.def", buf);
if ((f = fopen(buf1, "r")) == (FILE*)0) {
sprintf(buf1, "%s/lib/nrn.defaults", buf);
if ((f = fopen(buf1, "r")) == (FILE*)0) {
// printf("couldn't open %s\n", buf1);
// printf("%s not valid neuronhome\n", buf);
return;
}
}
fclose(f);
sprintf(buf1, "NEURONHOME=%s", buf);
nh_old = getenv("NEURONHOME");
// if (nh_old){ printf("nh_old from first getenv is %s\n", nh_old);
// }else{ printf("first getenv of NEURONHOME returns nil\n");}
if (!nh_old || stricmp(buf, nh_old) != 0) {
printf("Setting %s", buf1);
if (nh_old) {
printf(" from old value of %s\n", nh_old);
}else{
printf("\n");
}
s = emalloc(strlen(buf1)+1);
strcpy(s, buf1);
i = putenv(s); // arg must be global
// printf("putenv of %s returned %d\n", s, i);
}
}
neuron_home = getenv("NEURONHOME");
// if (neuron_home){ printf("neuron_home from second getenv is %s\n", neuron_home);
// }else{ printf("second getenv of NEURONHOME returns nil\n");}
if (!neuron_home) MessageBox(NULL, p, "Can't compute NEURONHOME from", MB_OK);
#endif
}
void HandleOutput(char* s) {
printf("%s", s);
}
static long exception_filter(p) LPEXCEPTION_POINTERS p; {
// hoc_execerror("unhandled exception", "");
// return EXCEPTION_CONTINUE_EXECUTION;
static int n = 0;
++n;
if (n == 1) {
hoc_execerror("\nUnhandled Exception. This usually means a bad memory \n\
address.", "It is not possible to make a judgment as to whether it is safe\n\
to continue. If this happened while compiling a template, you will have to\n\
quit.");
}
if (n == 2) {
MessageBox(NULL, "Second Unhandled Exception: Quitting NEURON. You will be asked to save \
any unsaved em buffers before exiting.", "NEURON Internal ERROR", MB_OK);
hoc_quit();
}
return EXCEPTION_EXECUTE_HANDLER;
}
void hoc_set_unhandled_exception_filter() {
SetUnhandledExceptionFilter((LPTOP_LEVEL_EXCEPTION_FILTER)exception_filter);
}
BOOL hoc_copyfile(const char* src, const char* dest) {
return CopyFile(src, dest, FALSE);
}
static FILE* dll_stdio_[] = {(FILE*)0x0, (FILE*)0x20, (FILE*)0x40};
void nrn_mswindll_stdio(i,o,e) FILE* i, *o, *e; {
if (o != dll_stdio_[1]) {
printf("nrn_mswindll_stdio stdio in dll = %p but expected %p\n", o, dll_stdio_[1]);
}
dll_stdio_[0] = i;
dll_stdio_[1] = o;
dll_stdio_[2] = e;
}
#if defined(CYGWIN)
/* the cygwin nrnmech.dll will use these pointers for stdin, stdout, stderr */
/* and when we come back to ncyg_fprintf we compare the stream to them */
FILE __files[4];
#else
#define ncyg_fprintf fprintf
#endif
int ncyg_fprintf(FILE /*_FAR*/ *stream, const char * strFmt, ...)
{
int len;
static char s[4096] = {0};
va_list marker;
va_start(marker, strFmt);
#if defined(CYGWIN)
#if 0
printf("ncyg stdin=%lx\n", (long)stdin);
printf("ncyg stdout=%lx\n", (long)stdout);
printf("ncyg stderr=%lx\n", (long)stderr);
printf("ncyg dll_stdio[0]=%lx\n", (long)dll_stdio_[0]);
printf("ncyg dll_stdio[1]=%lx\n", (long)dll_stdio_[1]);
printf("ncyg dll_sdtio[2]=%lx\n", (long)dll_stdio_[2]);
printf("ncyg stream=%lx\n", (long)stream);
#endif
if (stream == dll_stdio_[1]) {
stream = stdout;
}else if (stream == dll_stdio_[2]) {
stream = stderr;
}
len = vsprintf(s, strFmt, marker);
fputs(s, stream);
return len;
#endif
}
void hoc_forward2back(char* s) {
char* cp;
for (cp = s; *cp; ++cp) {
if (*cp == '/') {
*cp = '\\';
}
}
}
char* hoc_back2forward(char* s) {
char* cp = s;
while(*cp) {
if (*cp == '\\') {
*cp = '/';
}
++cp;
}
return s;
}
#if HAVE_IV
void ivoc_win32_cleanup();
#endif
void hoc_win32_cleanup() {
char buf[256];
char* path;
#if HAVE_IV
ivoc_win32_cleanup();
#endif
path = getenv("TEMP");
if (path) {
sprintf(buf, "%s/oc%d.hl", path, getpid());
unlink(buf);
// DebugMessage("unlinked %s\n", buf);
}
}
void hoc_win_exec(void) {
int i;
i = SW_SHOW;
if (ifarg(2)) {
i = (int)chkarg(2, -1000, 1000);
}
i = WinExec(gargstr(1), i);
ret();
pushx((double)i);
}
#if !defined(CYGWIN)
FILE* popen(char* s1, char* s2) {
printf("no popen\n");
return 0;
}
pclose(FILE* p) {
printf("no pclose\n");
}
void hoc_check_intupt(int intupt) {
#if !OCSMALL
MSG msg;
while (PeekMessage(&msg, hCurrWnd, 0, 0, PM_REMOVE))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
#endif
}
#if defined(__MWERKS__)
void __assertfail() { printf("assertfail\n");}
#endif
#if 0
char* dos_neuronhome() {
static char* dnrnhome;
char* nrnhome, *cp;
if (!dnrnhome) {
nrnhome = getenv("NEURONHOME");
dnrnhome = (char*)emalloc(strlen(nrnhome) + 1);
strcpy(dnrnhome, nrnhome);
for (cp = dnrnhome; *cp; ++cp) {
if (*cp == '/') {
*cp = '\\';
}
}
}
return dnrnhome;
}
#endif
#define HOCXDOS "lib/nrnsys.sh"
#define SEMA1 "tmpdos1.tmp"
#define SEMA2 "tmpdos2.tmp"
int system(const char* s) {
char buf[256], stin[128];
char* redirect;
FILE* fin;
unlink(SEMA1);
unlink(SEMA2);
errno = 0;
redirect = strchr(s, '>');
if (redirect) {/* redirection filename is first arg */
strcpy(stin, redirect+1);
sprintf(buf, "%s\\bin\\sh %s/%s %s %s %s",
neuron_home, neuron_home, HOCXDOS, neuron_home, stin, expand_env_var(s));
redirect = strchr(buf, '>');
*redirect = '\0';
}else{
sprintf(buf, "%s\\bin\\sh %s/%s %s %s %s",
neuron_home, neuron_home, HOCXDOS, neuron_home, SEMA2, expand_env_var(s));
}
//printf("%s\n", buf);
if (WinExec(buf, 0) < 32) {
hoc_execerror("WinExec failed:", buf);
}
while((fin = fopen(SEMA1, "r")) == (FILE*)0) {
Sleep(1);
wmhandler_yield();
}
fclose(fin);
unlink(SEMA1);
if (!redirect && (fin = fopen(SEMA2, "r")) != (FILE*)0) {
while(fgets(buf, 256, fin)) {
printf("%s", buf);
}
fclose(fin);
unlink(SEMA2);
}
return 0;
}
hoc_win_normal_cursor() {
if (old_cursor) {
(HCURSOR)SetClassLong(hCurrWnd, GCL_HCURSOR, (long)old_cursor);
SetCursor(old_cursor);
old_cursor = 0;
}
}
hoc_win_wait_cursor() {
static int ready = 0;
if (!ready) {
wait_cursor = LoadCursor(NULL, IDC_WAIT);
}
if (!old_cursor) {
//DebugMessage("set the wait cursor\n");
old_cursor = (HCURSOR)SetClassLong(hCurrWnd, GCL_HCURSOR, (long)wait_cursor);
SetCursor(wait_cursor);
}
}
#endif /* not CYGWIN */
void hoc_winio_show(int b) {
#ifndef CYGWIN
ShowWindow(hCurrWnd, b ? SW_SHOW : SW_HIDE);
#endif
}
#if 0
void plprint(const char* s) {
printf("%s", s);
}
#endif
int hoc_plttext;
#if !defined(__MWERKS__)
int getpid() {
#if 0
extern int __hInst;
return __hInst;
#else
return 1;
#endif
}
#endif
//hoc_close_plot(){}
//hoc_Graphmode(){ret();pushx(0.);}
//hoc_Graph(){ret();pushx(0.);}
//hoc_regraph(){ret();pushx(0.);}
//hoc_plotx(){ret();pushx(0.);}
//hoc_ploty(){ret();pushx(0.);}
void hoc_Plt() {ret(); pushx(0.);}
void hoc_Setcolor(){ret(); pushx(0.);}
void hoc_Lw(){ret(); pushx(0.);}
void hoc_settext(){ret(); pushx(0.);}
//Plot(){ret();pushx(0.);}
//axis(){ret();pushx(0.);}
//hoc_fmenu() {ret();pushx(0.);}
//int gethostname() {printf("no gethostname\n");}
//plt(int mode, double x, double y) {}
#if 0
hoc_menu_cleanup() {
#if OCSMALL
ShowWindow(hCurrWnd, SW_SHOW);
#endif
}
#endif
//initplot() {}
#if 0
Fig_file(){}
#endif
| 2.15625 | 2 |
2024-11-18T22:25:44.689861+00:00 | 2019-01-07T02:55:23 | 4ee5439854526fc69ebcbebda658bb374823c4fa | {
"blob_id": "4ee5439854526fc69ebcbebda658bb374823c4fa",
"branch_name": "refs/heads/master",
"committer_date": "2019-01-07T02:55:23",
"content_id": "a87456cac4fff349305bb60ddee36ffd923488f8",
"detected_licenses": [
"MIT"
],
"directory_id": "4501b4e1742fe915a3ed3aa722618d5b9755c50c",
"extension": "h",
"filename": "Timer0.h",
"fork_events_count": 1,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 83820701,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 381,
"license": "MIT",
"license_type": "permissive",
"path": "/Timer0/Timer0.h",
"provenance": "stackv2-0115.json.gz:138482",
"repo_name": "wuhanstudio/AVR_Libraries",
"revision_date": "2019-01-07T02:55:23",
"revision_id": "b95cda5392fdf488800b846bb19ba3606879e2a7",
"snapshot_id": "fe8533d07795f55d75c378e47a5a4ac786afad7e",
"src_encoding": "GB18030",
"star_events_count": 6,
"url": "https://raw.githubusercontent.com/wuhanstudio/AVR_Libraries/b95cda5392fdf488800b846bb19ba3606879e2a7/Timer0/Timer0.h",
"visit_date": "2021-01-20T02:37:26.990750"
} | stackv2 | /*
* Timer0.h
*
* Created: 2016/2/17 10:26:03
* Author: WuhanStudio
*/
#include <avr/interrupt.h>
#ifndef TIMER0_H_
#define TIMER0_H_
void TC0_init()
{
SREG = 0x80; // 开总中断
TIMSK = 0x01; // 开T/C0溢出中断
TCNT0 = 99; // 初值
TCCR0 = 0x05; // T/C0预分频比1/1024
}
ISR(TIMER0_OVF_vect)
{
TCNT0 = 99;
// 终端程序
}
#endif /* TIMER0_H_ */ | 2.109375 | 2 |
2024-11-18T22:25:45.186908+00:00 | 2022-10-01T06:42:20 | ccca0c269a9fb52bae1b936ac666c335ce868dcd | {
"blob_id": "ccca0c269a9fb52bae1b936ac666c335ce868dcd",
"branch_name": "refs/heads/master",
"committer_date": "2022-10-01T06:42:20",
"content_id": "3ea45269eb76b25d8034e7d7b59560e40d799f1f",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "f25b3291fd7461124e38c399a27bad16d295021d",
"extension": "c",
"filename": "test_get_log_ent_size.c",
"fork_events_count": 35,
"gha_created_at": "2017-06-30T15:17:11",
"gha_event_created_at": "2022-09-30T13:09:30",
"gha_language": "C++",
"gha_license_id": "Apache-2.0",
"github_id": 95900349,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2264,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/code/testing/test_get_log_ent_size.c",
"provenance": "stackv2-0115.json.gz:138740",
"repo_name": "utsaslab/crashmonkey",
"revision_date": "2022-10-01T06:42:20",
"revision_id": "27ca57f8cf2760d5d4855e03b8d01f8e5de1628c",
"snapshot_id": "ae56c75f4510a3c8c061468e1fc9f609ca87ceb7",
"src_encoding": "UTF-8",
"star_events_count": 182,
"url": "https://raw.githubusercontent.com/utsaslab/crashmonkey/27ca57f8cf2760d5d4855e03b8d01f8e5de1628c/code/testing/test_get_log_ent_size.c",
"visit_date": "2022-10-23T17:24:06.002524"
} | stackv2 | #include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/ioctl.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#include "../disk_wrapper_ioctl.h"
#define TEXT "hello great big world out there"
// Assumes that the hwm module is already inserted into the kernel and is
// properly running.
int main(int argc, char** argv) {
int device_fd = open("/dev/hwm1", O_RDONLY);
if (device_fd == -1) {
printf("Error opening device file\n");
return -1;
}
int fd = open("/mnt/snapshot/testing/test_file2", O_RDWR | O_CREAT);
if (fd == -1) {
printf("Error opening test file\n");
return -1;
}
ioctl(device_fd, HWM_CLR_LOG);
ioctl(device_fd, HWM_LOG_ON);
unsigned int str_len = strlen(TEXT) * sizeof(char);
unsigned int written = 0;
while (written != str_len) {
written = write(fd, TEXT + written, str_len - written);
if (written == -1) {
printf("Error while writing to test file\n");
goto out_1;
}
}
fsync(fd);
close(fd);
unsigned int delay = 30;
while (delay != 0) {
delay = sleep(delay);
}
ioctl(device_fd, HWM_LOG_OFF);
struct disk_write_op_meta* metadata;
void* data = NULL;
unsigned int entry_size;
while (1) {
int result = ioctl(device_fd, HWM_GET_LOG_ENT_SIZE, &entry_size);
if (result == -1) {
if (errno == ENODATA) {
printf("No log data reported by block device\n");
} else if (errno == EFAULT) {
printf("efault occurred\n");
goto out;
}
}
data = calloc(entry_size, sizeof(char));
result = ioctl(device_fd, HWM_GET_LOG_ENT, data);
if (result == -1) {
if (errno == ENODATA) {
printf("end of log data\n");
free(data);
break;
} else if (errno == EFAULT) {
printf("efault occurred\n");
free(data);
goto out;
}
}
metadata = (struct disk_write_op_meta*) data;
char* data_string = data + sizeof(struct disk_write_op_meta);
printf("operation with flags: %lx\n~~~\n%s\n~~~\n", metadata->bi_rw,
data_string);
free(data);
}
close(device_fd);
return 0;
out_1:
close(fd);
out:
ioctl(device_fd, HWM_LOG_OFF);
close(device_fd);
return -1;
}
| 2.578125 | 3 |
2024-11-18T22:25:45.256134+00:00 | 2021-10-01T10:46:14 | 8e2005c4fd9231ce001fd3e23635b8f967127dca | {
"blob_id": "8e2005c4fd9231ce001fd3e23635b8f967127dca",
"branch_name": "refs/heads/main",
"committer_date": "2021-10-01T10:46:14",
"content_id": "8f39b897237407a24fe95fb029d53980a3b5730a",
"detected_licenses": [
"OpenSSL",
"BSD-2-Clause"
],
"directory_id": "e22e03d9761f5c6d581b5af2e77343e8ee4b201d",
"extension": "c",
"filename": "EfiSetMemSSE2.c",
"fork_events_count": 14,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 410938306,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2909,
"license": "OpenSSL,BSD-2-Clause",
"license_type": "permissive",
"path": "/edk2/EdkCompatibilityPkg/Foundation/Library/EfiCommonLib/Ia32/EfiSetMemSSE2.c",
"provenance": "stackv2-0115.json.gz:138871",
"repo_name": "SamuelTulach/SecureFakePkg",
"revision_date": "2021-10-01T10:46:14",
"revision_id": "f34080a6c0efb6ca3dd755365778d0bcdca6b991",
"snapshot_id": "759975fcc84d62f05ac577da48353752e5334878",
"src_encoding": "UTF-8",
"star_events_count": 94,
"url": "https://raw.githubusercontent.com/SamuelTulach/SecureFakePkg/f34080a6c0efb6ca3dd755365778d0bcdca6b991/edk2/EdkCompatibilityPkg/Foundation/Library/EfiCommonLib/Ia32/EfiSetMemSSE2.c",
"visit_date": "2023-08-17T07:51:22.175924"
} | stackv2 | /*++
Copyright (c) 2006, Intel Corporation. All rights reserved.<BR>
This program and the accompanying materials
are licensed and made available under the terms and conditions of the BSD License
which accompanies this distribution. The full text of the license may be found at
http://opensource.org/licenses/bsd-license.php
THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
Module Name:
EfiSetMemSSE2.c
Abstract:
This is the code that supports IA32-optimized SetMem service
--*/
#include "Tiano.h"
VOID
EfiCommonLibSetMem (
IN VOID *Buffer,
IN UINTN Count,
IN UINT8 Value
)
/*++
Input: VOID *Buffer - Pointer to buffer to write
UINTN Count - Number of bytes to write
UINT8 Value - Value to write
Output: None.
Saves:
Modifies:
Description: This function is an optimized set-memory function.
Notes: This function tries to set memory 8 bytes at a time. As a result,
it first picks up any misaligned bytes, then words, before getting
in the main loop that does the 8-byte clears.
--*/
{
UINT64 QWordValue;
UINT64 MmxSave;
__asm {
mov edx, Count
test edx, edx
je _SetMemDone
push ebx
mov eax, Buffer
mov bl, Value
mov edi, eax
mov bh, bl
cmp edx, 256
jb _SetRemindingByte
and al, 0fh
test al, al
je _SetBlock
mov eax, edi
shr eax, 4
inc eax
shl eax, 4
sub eax, edi
cmp eax, edx
jnb _SetRemindingByte
sub edx, eax
mov ecx, eax
mov al, bl
rep stosb
_SetBlock:
mov eax, edx
shr eax, 7
test eax, eax
je _SetRemindingByte
shl eax, 7
sub edx, eax
shr eax, 7
mov WORD PTR QWordValue[0], bx
mov WORD PTR QWordValue[2], bx
mov WORD PTR QWordValue[4], bx
mov WORD PTR QWordValue[6], bx
movq MmxSave, mm0
movq mm0, QWordValue
movq2dq xmm1, mm0
pshufd xmm1, xmm1, 0
_Loop:
movdqa OWORD PTR ds:[edi], xmm1
movdqa OWORD PTR ds:[edi+16], xmm1
movdqa OWORD PTR ds:[edi+32], xmm1
movdqa OWORD PTR ds:[edi+48], xmm1
movdqa OWORD PTR ds:[edi+64], xmm1
movdqa OWORD PTR ds:[edi+80], xmm1
movdqa OWORD PTR ds:[edi+96], xmm1
movdqa OWORD PTR ds:[edi+112], xmm1
add edi, 128
dec eax
jnz _Loop
; Restore mm0
movq mm0, MmxSave
emms ; Exit MMX Instruction
_SetRemindingByte:
mov ecx, edx
mov eax, ebx
shl eax, 16
mov ax, bx
shr ecx, 2
rep stosd
mov ecx, edx
and ecx, 3
rep stosb
pop ebx
_SetMemDone:
}
}
| 2 | 2 |
2024-11-18T22:25:45.608128+00:00 | 2021-10-12T04:48:03 | c3d2bfce77a2d9d2325d73fe7f90f1e75a2859f6 | {
"blob_id": "c3d2bfce77a2d9d2325d73fe7f90f1e75a2859f6",
"branch_name": "refs/heads/main",
"committer_date": "2021-10-12T04:48:03",
"content_id": "7fd46a86d6ba70047347d4c3f681c426e5e9af8f",
"detected_licenses": [
"MIT"
],
"directory_id": "fe661496350c49a400b739135bb0670913153628",
"extension": "c",
"filename": "nokia5110_LCD.c",
"fork_events_count": 1,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 403624093,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 7962,
"license": "MIT",
"license_type": "permissive",
"path": "/firmware/signal-generator-src/Core/Src/nokia5110_LCD.c",
"provenance": "stackv2-0115.json.gz:139129",
"repo_name": "FilipeChagasDev/embedded-signal-generator",
"revision_date": "2021-10-12T04:48:03",
"revision_id": "c754f6007fbb6062de0065a4ebfb36e5d069269f",
"snapshot_id": "a4e2eb2d73d6934c26a9f928f06db9a6fa67ec8c",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/FilipeChagasDev/embedded-signal-generator/c754f6007fbb6062de0065a4ebfb36e5d069269f/firmware/signal-generator-src/Core/Src/nokia5110_LCD.c",
"visit_date": "2023-08-30T18:31:10.755376"
} | stackv2 | #include "nokia5110_LCD.h"
struct LCD_att lcd;
struct LCD_GPIO lcd_gpio;
/*----- GPIO Functions -----*/
/*
* @brief Set functions for GPIO pins used
* @param PORT: port of the pin used
* @param PIN: pin of the pin used
*/
void LCD_setRST(GPIO_TypeDef* PORT, uint16_t PIN){
lcd_gpio.RSTPORT = PORT;
lcd_gpio.RSTPIN = PIN;
}
void LCD_setCE(GPIO_TypeDef* PORT, uint16_t PIN){
lcd_gpio.CEPORT = PORT;
lcd_gpio.CEPIN = PIN;
}
void LCD_setDC(GPIO_TypeDef* PORT, uint16_t PIN){
lcd_gpio.DCPORT = PORT;
lcd_gpio.DCPIN = PIN;
}
void LCD_setDIN(GPIO_TypeDef* PORT, uint16_t PIN){
lcd_gpio.DINPORT = PORT;
lcd_gpio.DINPIN = PIN;
}
void LCD_setCLK(GPIO_TypeDef* PORT, uint16_t PIN){
lcd_gpio.CLKPORT = PORT;
lcd_gpio.CLKPIN = PIN;
}
/*----- Library Functions -----*/
/*
* @brief Send information to the LCD using configured GPIOs
* @param val: value to be sent
*/
void LCD_send(uint8_t val){
uint8_t i;
for(i = 0; i < 8; i++){
HAL_GPIO_WritePin(lcd_gpio.DINPORT, lcd_gpio.DINPIN, !!(val & (1 << (7 - i))));
HAL_GPIO_WritePin(lcd_gpio.CLKPORT, lcd_gpio.CLKPIN, GPIO_PIN_SET);
HAL_GPIO_WritePin(lcd_gpio.CLKPORT, lcd_gpio.CLKPIN, GPIO_PIN_RESET);
}
}
/*
* @brief Writes some data into the LCD
* @param data: data to be written
* @param mode: command or data
*/
void LCD_write(uint8_t data, uint8_t mode){
if(mode == LCD_COMMAND){
HAL_GPIO_WritePin(lcd_gpio.DCPORT, lcd_gpio.DCPIN, GPIO_PIN_RESET);
HAL_GPIO_WritePin(lcd_gpio.CEPORT, lcd_gpio.CEPIN, GPIO_PIN_RESET);
LCD_send(data);
HAL_GPIO_WritePin(lcd_gpio.CEPORT, lcd_gpio.CEPIN, GPIO_PIN_SET);
}
else{
HAL_GPIO_WritePin(lcd_gpio.DCPORT, lcd_gpio.DCPIN, GPIO_PIN_SET);
HAL_GPIO_WritePin(lcd_gpio.CEPORT, lcd_gpio.CEPIN, GPIO_PIN_RESET);
LCD_send(data);
HAL_GPIO_WritePin(lcd_gpio.CEPORT, lcd_gpio.CEPIN, GPIO_PIN_SET);
}
}
/*
* @brief Initialize the LCD using predetermined values
*/
void LCD_init(){
HAL_GPIO_WritePin(lcd_gpio.RSTPORT, lcd_gpio.RSTPIN, GPIO_PIN_RESET);
HAL_GPIO_WritePin(lcd_gpio.RSTPORT, lcd_gpio.RSTPIN, GPIO_PIN_SET);
LCD_write(0x21, LCD_COMMAND); //LCD extended commands.
LCD_write(0xB8, LCD_COMMAND); //set LCD Vop(Contrast).
LCD_write(0x04, LCD_COMMAND); //set temp coefficent.
LCD_write(0x14, LCD_COMMAND); //LCD bias mode 1:40.
LCD_write(0x20, LCD_COMMAND); //LCD basic commands.
LCD_write(LCD_DISPLAY_NORMAL, LCD_COMMAND); //LCD normal.
LCD_clrScr();
lcd.inverttext = false;
}
/*
* @brief Invert the color shown on the display
* @param mode: true = inverted / false = normal
*/
void LCD_invert(bool mode){
if(mode == true){
LCD_write(LCD_DISPLAY_INVERTED, LCD_COMMAND);
}
else{
LCD_write(LCD_DISPLAY_NORMAL, LCD_COMMAND);
}
}
/*
* @brief Invert the colour of any text sent to the display
* @param mode: true = inverted / false = normal
*/
void LCD_invertText(bool mode){
if(mode == true){
lcd.inverttext = true;
}
else{
lcd.inverttext = false;
}
}
/*
* @brief Puts one char on the current position of LCD's cursor
* @param c: char to be printed
*/
void LCD_putChar(char c){
for(int i = 0; i < 6; i++){
if(lcd.inverttext != true)
LCD_write(ASCII[c - 0x20][i], LCD_DATA);
else
LCD_write(~(ASCII[c - 0x20][i]), LCD_DATA);
}
}
/*
* @brief Print a string on the LCD
* @param x: starting point on the x-axis (column)
* @param y: starting point on the y-axis (line)
*/
void LCD_print(char *str, uint8_t x, uint8_t y){
LCD_goXY(x, y);
while(*str){
LCD_putChar(*str++);
}
}
/*
* @brief Clear the screen
*/
void LCD_clrScr(){
for(int i = 0; i < 504; i++){
LCD_write(0x00, LCD_DATA);
lcd.buffer[i] = 0;
}
}
/*
* @brief Set LCD's cursor to position X,Y
* @param x: position on the x-axis (column)
* @param y: position on the y-axis (line)
*/
void LCD_goXY(uint8_t x, uint8_t y){
LCD_write(0x80 | x, LCD_COMMAND); //Column.
LCD_write(0x40 | y, LCD_COMMAND); //Row.
}
/*
* @brief Updates the entire screen according to lcd.buffer
*/
void LCD_refreshScr(){
LCD_goXY(LCD_SETXADDR, LCD_SETYADDR);
for(int i = 0; i < 6; i++){
for(int j = 0; j < LCD_WIDTH; j++){
LCD_write(lcd.buffer[(i * LCD_WIDTH) + j], LCD_DATA);
}
}
}
/*
* @brief Updates a square of the screen according to given values
* @param xmin: starting point on the x-axis
* @param xmax: ending point on the x-axis
* @param ymin: starting point on the y-axis
* @param ymax: ending point on the y-axis
*/
void LCD_refreshArea(uint8_t xmin, uint8_t ymin, uint8_t xmax, uint8_t ymax){
for(int i = 0; i < 6; i++){
if(i * 8 > ymax){
break;
}
//LCD_goXY(xmin, i);
LCD_write(LCD_SETYADDR | i, LCD_COMMAND);
LCD_write(LCD_SETXADDR | xmin, LCD_COMMAND);
for(int j = xmin; j <= xmax; j++){
LCD_write(lcd.buffer[(i * LCD_WIDTH) + j], LCD_DATA);
}
}
}
/*
* @brief Sets a pixel on the screen
*/
void LCD_setPixel(uint8_t x, uint8_t y, bool pixel){
if(x >= LCD_WIDTH)
x = LCD_WIDTH - 1;
if(y >= LCD_HEIGHT)
y = LCD_HEIGHT - 1;
if(pixel != false){
lcd.buffer[x + (y / 8) * LCD_WIDTH] |= 1 << (y % 8);
}
else{
lcd.buffer[x + (y / 8) * LCD_WIDTH] &= ~(1 << (y % 8));
}
}
/*
* @brief Draws a horizontal line
* @param x: starting point on the x-axis
* @param y: starting point on the y-axis
* @param l: length of the line
*/
void LCD_drawHLine(int x, int y, int l){
int by, bi;
if ((x>=0) && (x<LCD_WIDTH) && (y>=0) && (y<LCD_HEIGHT)){
for (int cx=0; cx<l; cx++){
by=((y/8)*84)+x;
bi=y % 8;
lcd.buffer[by+cx] |= (1<<bi);
}
}
}
/*
* @brief Draws a vertical line
* @param x: starting point on the x-axis
* @param y: starting point on the y-axis
* @param l: length of the line
*/
void LCD_drawVLine(int x, int y, int l){
if ((x>=0) && (x<84) && (y>=0) && (y<48)){
for (int cy=0; cy<= l; cy++){
LCD_setPixel(x, y+cy, true);
}
}
}
/*
* @brief abs function used in LCD_drawLine
* @param x: any integer
* @return absolute value of x
*/
int abs(int x){
if(x < 0){
return x*-1;
}
return x;
}
/*
* @brief Draws any line
* @param x1: starting point on the x-axis
* @param y1: starting point on the y-axis
* @param x2: ending point on the x-axis
* @param y2: ending point on the y-axis
*/
void LCD_drawLine(int x1, int y1, int x2, int y2){
int tmp;
double delta, tx, ty;
if (((x2-x1)<0)){
tmp=x1;
x1=x2;
x2=tmp;
tmp=y1;
y1=y2;
y2=tmp;
}
if (((y2-y1)<0)){
tmp=x1;
x1=x2;
x2=tmp;
tmp=y1;
y1=y2;
y2=tmp;
}
if (y1==y2){
if (x1>x2){
tmp=x1;
x1=x2;
x2=tmp;
}
LCD_drawHLine(x1, y1, x2-x1);
}
else if (x1==x2){
if (y1>y2){
tmp=y1;
y1=y2;
y2=tmp;
}
LCD_drawHLine(x1, y1, y2-y1);
}
else if (abs(x2-x1)>abs(y2-y1)){
delta=((double)(y2-y1)/(double)(x2-x1));
ty=(double) y1;
if (x1>x2){
for (int i=x1; i>=x2; i--){
LCD_setPixel(i, (int) (ty+0.5), true);
ty=ty-delta;
}
}
else
{
for (int i=x1; i<=x2; i++){
LCD_setPixel(i, (int) (ty+0.5), true);
ty=ty+delta;
}
}
}
else{
delta=((float) (x2-x1)/(float) (y2-y1));
tx=(float) (x1);
if (y1>y2){
for (int i=y2+1; i>y1; i--){
LCD_setPixel((int) (tx+0.5), i, true);
tx=tx+delta;
}
}
else{
for (int i=y1; i<y2+1; i++){
LCD_setPixel((int) (tx+0.5), i, true);
tx=tx+delta;
}
}
}
}
/*
* @brief Draws a rectangle
* @param x1: starting point on the x-axis
* @param y1: starting point on the y-axis
* @param x2: ending point on the x-axis
* @param y2: ending point on the y-axis
*/
void LCD_drawRectangle(uint8_t x1, uint8_t y1, uint8_t x2, uint8_t y2){
LCD_drawLine(x1, y1, x2, y1);
LCD_drawLine(x1, y1, x1, y2);
LCD_drawLine(x2, y1, x2, y2);
LCD_drawLine(x1, y2, x2, y2);
}
| 2.6875 | 3 |
2024-11-18T22:25:46.005613+00:00 | 2019-09-10T08:47:24 | 76497fbc84b8801726dfccfca86f1d63a3802ccf | {
"blob_id": "76497fbc84b8801726dfccfca86f1d63a3802ccf",
"branch_name": "refs/heads/master",
"committer_date": "2019-09-10T08:47:24",
"content_id": "88205ae9b8f69e3299800e0841266d2bda4da59f",
"detected_licenses": [
"MIT"
],
"directory_id": "d2c54233a96b0de3137d320a86de726f87f6d3b4",
"extension": "c",
"filename": "sigmoid_layer_module.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 177493396,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 655,
"license": "MIT",
"license_type": "permissive",
"path": "/cnn/struct/layer/function/sigmoid_layer_module.c",
"provenance": "stackv2-0115.json.gz:139649",
"repo_name": "hslee1539/cnn",
"revision_date": "2019-09-10T08:47:24",
"revision_id": "816418af0a0057d777f41ac072c3a97fea7e2027",
"snapshot_id": "aa93e6c41e994b409b5ebcd6e1abfaef98cd0c60",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/hslee1539/cnn/816418af0a0057d777f41ac072c3a97fea7e2027/cnn/struct/layer/function/sigmoid_layer_module.c",
"visit_date": "2020-05-01T13:30:25.781805"
} | stackv2 | #include "./sigmoid_layer_module.h"
#include "./../../../computing/sigmoid_layer_module.h"
#include "./standard_layer_define.h"
/*
코딩 실수 줄이기 위해 복사해서 사용하자!
struct Tensor* x = layer->inLayer[0]->out;
struct Tensor* dout = layer->outLayer[0]->dx;
*/
void cnn_sigmoid_layer_forward(struct cnn_Layer *layer, int index, int max_index){
cnn_comput_sigmoid_layer_forward(CNN_LAYER_X(layer), CNN_LAYER_OUT(layer), index, max_index);
}
void cnn_sigmoid_layer_backward(struct cnn_Layer *layer, int index, int max_index){
cnn_comput_sigmoid_layer_backward(CNN_LAYER_DOUT(layer), layer->out, layer->dx, index, max_index);
} | 2.03125 | 2 |
2024-11-18T22:25:46.141490+00:00 | 2017-04-01T19:08:30 | fe67f873577a7c686d0a1539c4b440d5cd80eeb4 | {
"blob_id": "fe67f873577a7c686d0a1539c4b440d5cd80eeb4",
"branch_name": "refs/heads/master",
"committer_date": "2017-04-01T19:08:30",
"content_id": "a2b10406e4417b3c9fa33c54248cb04fffb0e2d2",
"detected_licenses": [
"MIT"
],
"directory_id": "68b8f66d3752f29ec8c39ef73faf02d907c80cb2",
"extension": "c",
"filename": "math_exp.c",
"fork_events_count": 1,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 86936091,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 3175,
"license": "MIT",
"license_type": "permissive",
"path": "/src/klibc/math_exp.c",
"provenance": "stackv2-0115.json.gz:139907",
"repo_name": "RoseLeBlood/CsOS-i386",
"revision_date": "2017-04-01T19:08:30",
"revision_id": "e1b8db4111349c8dfa51aaaa543075f220af50d4",
"snapshot_id": "728073b22b032f1a534392c9af67b98245a414ea",
"src_encoding": "UTF-8",
"star_events_count": 2,
"url": "https://raw.githubusercontent.com/RoseLeBlood/CsOS-i386/e1b8db4111349c8dfa51aaaa543075f220af50d4/src/klibc/math_exp.c",
"visit_date": "2021-01-18T20:05:23.303729"
} | stackv2 |
#include <math.h>
double exp(double x)
{
asm("fldl2e ; fmulp ; f2xm1" : "+t"(x));
return x + 1;
}
float expf(float x)
{
asm("fldl2e ; fmulp ; f2xm1" : "+t"(x));
return x + 1;
}
long double expl(long double x)
{
asm("fldl2e ; fmulp ; f2xm1" : "+t"(x));
return x + 1;
}
double exp2(double x)
{
asm("f2xm1" : "+t"(x));
return x + 1;
}
float exp2f(float x)
{
asm("f2xm1" : "+t"(x));
return x + 1;
}
long double exp2l(long double x)
{
asm("f2xm1" : "+t"(x));
return x + 1;
}
double expm1(double x) {
return exp(x) - 1;
}
float expm1f(float x) {
return expf(x) - 1;
}
long double expm1l(long double x)
{
return expl(x) - 1;
}
double frexp(double x, int* exp);
float frexpf(float x, int* exp);
long double frexpl(long double x, int* exp);
int ilogb(double x);
int ilogbf(float x);
int ilogbl(long double x);
double ldexp(double x, int exp)
{
return x * (1 << exp);
}
float ldexpf(float x, int exp)
{
return x * (1 << exp);
}
long double ldexpl(long double x, int exp)
{
return x * (1 << exp);
}
double log(double x)
{
double ln2;
asm("fldln2" : "=t"(ln2));
return ln2 * log2(x);
}
float logf(float x)
{
float ln2;
asm("fldln2" : "=t"(ln2));
return ln2 * log2f(x);
}
long double logl(long double x)
{
long double ln2;
asm("fldln2" : "=t"(ln2));
return ln2 * log2l(x);
}
double log10(double x)
{
double log10_2;
asm("fldlg2" : "=t"(log10_2));
return log10_2 * log2(x);
}
float log10f(float x)
{
double log10_2;
asm("fldlg2" : "=t"(log10_2));
return log10_2 * log2f(x);
}
long double log10l(long double x)
{
double log10_2;
asm("fldlg2" : "=t"(log10_2));
return log10_2 * log2l(x);
}
double log1p(double x)
{
return log(1 + x);
}
float log1pf(float x)
{
return logf(1 + x);
}
long double log1pl(long double x)
{
return logl(1 + x);
}
double log2(double x)
{
asm("fld1 ; fxch ; fyl2x" : "+t"(x));
return x;
}
float log2f(float x)
{
asm("fld1 ; fxch ; fyl2x" : "+t"(x));
return x;
}
long double log2l(long double x)
{
asm("fld1 ; fxch ; fyl2x" : "+t"(x));
return x;
}
double logb(double x);
float logbf(float x);
long double logbl(long double x);
double modf(double value, double* iptr);
float modff(float value, float* iptr);
long double modfl(long double value, long double* iptr);
double scalbn(double x, int n);
float scalbnf(float x, int n);
long double scalbnl(long double x, int n);
double scalbln(double x, long int n);
float scalblnf(float x, long int n);
long double scalblnl(long double x, long int n);
| 2.515625 | 3 |
2024-11-18T22:25:46.298123+00:00 | 2016-10-30T04:48:22 | 537831a0bcb559df563962b6f66a81b54b6c71d3 | {
"blob_id": "537831a0bcb559df563962b6f66a81b54b6c71d3",
"branch_name": "refs/heads/master",
"committer_date": "2016-10-30T04:48:22",
"content_id": "14e6ee4095e7a508f9ed379f20a239eb68301fda",
"detected_licenses": [
"MIT"
],
"directory_id": "1b2f1e2f6ff221beb9a792faa1ae0d859282bf24",
"extension": "c",
"filename": "ex1.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": null,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 572,
"license": "MIT",
"license_type": "permissive",
"path": "/Week02/ex1.c",
"provenance": "stackv2-0115.json.gz:140165",
"repo_name": "flintlovesam/cab202",
"revision_date": "2016-10-30T04:48:22",
"revision_id": "85eb79b313ad82b41c1553c97fff4caa019b90de",
"snapshot_id": "4d9794f602087c8d4eac7d27b463bfbd51abcf28",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/flintlovesam/cab202/85eb79b313ad82b41c1553c97fff4caa019b90de/Week02/ex1.c",
"visit_date": "2020-04-01T18:20:39.825142"
} | stackv2 | #include <stdio.h>
void list_integers( void ) {
// (a) Print the introductory message
printf("The integer subrange from 63 to 333...\n");
// (b) Declare a counter variable of type int, and initialise it to 41
int counter = 63;
// (c) While the value of the counter is less than or equal to 342
while (counter <= 333) {
// (d) Print the value of the counter
printf("%d\n", counter);
// (e) Add 1 to the counter
counter++;
}
// (f) end of While loop started at (c)
}
int main( void ) {
list_integers();
return 0;
}
| 3.515625 | 4 |
2024-11-18T22:25:46.400968+00:00 | 2018-07-31T19:11:24 | ed5772ed2e487ea22e6ca80ea247fddfd9da2516 | {
"blob_id": "ed5772ed2e487ea22e6ca80ea247fddfd9da2516",
"branch_name": "refs/heads/master",
"committer_date": "2018-07-31T19:11:24",
"content_id": "0298220fa154e1abccdb8a2e397ca42fd44928a9",
"detected_licenses": [
"MIT"
],
"directory_id": "81aebf0869aed8efec938e1119f6bdfe94ca0c52",
"extension": "c",
"filename": "ellipticVectors.c",
"fork_events_count": 1,
"gha_created_at": "2018-08-01T02:56:19",
"gha_event_created_at": "2018-08-01T02:56:20",
"gha_language": null,
"gha_license_id": null,
"github_id": 143096209,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 3797,
"license": "MIT",
"license_type": "permissive",
"path": "/solvers/elliptic/src/ellipticVectors.c",
"provenance": "stackv2-0115.json.gz:140294",
"repo_name": "Mopolino8/libparanumal",
"revision_date": "2018-07-31T19:11:24",
"revision_id": "c52a090ee100f82373ca49ca1c57924636c3242e",
"snapshot_id": "a7a52a1fd97c7cba6c61d3e7815840826e111c57",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/Mopolino8/libparanumal/c52a090ee100f82373ca49ca1c57924636c3242e/solvers/elliptic/src/ellipticVectors.c",
"visit_date": "2020-03-24T22:39:10.805080"
} | stackv2 | /*
The MIT License (MIT)
Copyright (c) 2017 Tim Warburton, Noel Chalmers, Jesse Chan, Ali Karakus
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
#include "elliptic.h"
void ellipticScaledAdd(elliptic_t *elliptic, dfloat alpha, occa::memory &o_a, dfloat beta, occa::memory &o_b){
mesh_t *mesh = elliptic->mesh;
dlong Ntotal = mesh->Nelements*mesh->Np;
// b[n] = alpha*a[n] + beta*b[n] n\in [0,Ntotal)
occaTimerTic(mesh->device,"scaledAddKernel");
elliptic->scaledAddKernel(Ntotal, alpha, o_a, beta, o_b);
occaTimerToc(mesh->device,"scaledAddKernel");
}
dfloat ellipticWeightedInnerProduct(elliptic_t *elliptic, occa::memory &o_w, occa::memory &o_a, occa::memory &o_b){
mesh_t *mesh = elliptic->mesh;
dfloat *tmp = elliptic->tmp;
dlong Nblock = elliptic->Nblock;
dlong Ntotal = mesh->Nelements*mesh->Np;
occa::memory &o_tmp = elliptic->o_tmp;
occaTimerTic(mesh->device,"weighted inner product2");
if(elliptic->options.compareArgs("DISCRETIZATION","CONTINUOUS"))
elliptic->weightedInnerProduct2Kernel(Ntotal, o_w, o_a, o_b, o_tmp);
else
elliptic->innerProductKernel(Ntotal, o_a, o_b, o_tmp);
occaTimerToc(mesh->device,"weighted inner product2");
o_tmp.copyTo(tmp);
dfloat wab = 0;
for(dlong n=0;n<Nblock;++n){
wab += tmp[n];
}
dfloat globalwab = 0;
MPI_Allreduce(&wab, &globalwab, 1, MPI_DFLOAT, MPI_SUM, mesh->comm);
return globalwab;
}
dfloat ellipticWeightedNorm2(elliptic_t *elliptic, occa::memory &o_w, occa::memory &o_a){
mesh_t *mesh = elliptic->mesh;
dfloat *tmp = elliptic->tmp;
dlong Nblock = elliptic->Nblock;
dlong Ntotal = mesh->Nelements*mesh->Np;
occa::memory &o_tmp = elliptic->o_tmp;
occaTimerTic(mesh->device,"weighted inner product2");
if(elliptic->options.compareArgs("DISCRETIZATION","CONTINUOUS"))
elliptic->weightedNorm2Kernel(Ntotal, o_w, o_a, o_tmp);
else
elliptic->norm2Kernel(Ntotal, o_a, o_tmp);
occaTimerToc(mesh->device,"weighted norm2");
o_tmp.copyTo(tmp);
dfloat wab = 0;
for(dlong n=0;n<Nblock;++n){
wab += tmp[n];
}
dfloat globalwab = 0;
MPI_Allreduce(&wab, &globalwab, 1, MPI_DFLOAT, MPI_SUM, mesh->comm);
return globalwab;
}
dfloat ellipticInnerProduct(elliptic_t *elliptic, occa::memory &o_a, occa::memory &o_b){
mesh_t *mesh = elliptic->mesh;
dfloat *tmp = elliptic->tmp;
dlong Nblock = elliptic->Nblock;
dlong Ntotal = mesh->Nelements*mesh->Np;
occa::memory &o_tmp = elliptic->o_tmp;
occaTimerTic(mesh->device,"inner product");
elliptic->innerProductKernel(Ntotal, o_a, o_b, o_tmp);
occaTimerToc(mesh->device,"inner product");
o_tmp.copyTo(tmp);
dfloat ab = 0;
for(dlong n=0;n<Nblock;++n){
ab += tmp[n];
}
dfloat globalab = 0;
MPI_Allreduce(&ab, &globalab, 1, MPI_DFLOAT, MPI_SUM, mesh->comm);
return globalab;
}
| 2.28125 | 2 |
2024-11-18T22:25:46.503091+00:00 | 2020-11-17T06:24:25 | f62829b14714369a143b61de716e248abe08768e | {
"blob_id": "f62829b14714369a143b61de716e248abe08768e",
"branch_name": "refs/heads/master",
"committer_date": "2020-11-17T06:24:25",
"content_id": "3938da3c687979713acdfc32d5918ab895a5714e",
"detected_licenses": [
"PostgreSQL"
],
"directory_id": "7bb21a2f99110e528190463c4e62ba586da57d65",
"extension": "c",
"filename": "directory.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 248058539,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 7373,
"license": "PostgreSQL",
"license_type": "permissive",
"path": "/src/backend/optimizer/path/gpukde/container/directory.c",
"provenance": "stackv2-0115.json.gz:140422",
"repo_name": "sfu-db/feedback-kde",
"revision_date": "2020-11-17T06:24:25",
"revision_id": "96e2a861dbb285b268d712e9076b89d0da104e01",
"snapshot_id": "6489abc70db1c950823fd2dc22c8b7d9a6cdfc8b",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/sfu-db/feedback-kde/96e2a861dbb285b268d712e9076b89d0da104e01/src/backend/optimizer/path/gpukde/container/directory.c",
"visit_date": "2023-01-12T19:30:15.876255"
} | stackv2 | // Inhibit gcc warnings on mixed declarations
#pragma GCC diagnostic ignored "-Wdeclaration-after-statement"
#include <string.h>
#include "directory.h"
// Initialize a directory for the given key size.
directory_t directory_init(size_t key_size, unsigned int initial_capacity) {
directory_tt* result = malloc(sizeof(directory_tt));
result->capacity = initial_capacity;
result->key_size = key_size;
result->entries = 0;
result->payloads = malloc(sizeof(void*)*result->capacity);
result->keys = malloc(key_size*result->capacity);
result->last_access = 0;
return result;
}
// Release a given directory.
void directory_release(directory_t directory, char release_payloads) {
if (release_payloads) {
unsigned int i;
for (i=0; i<directory->entries; ++i) {
free(directory->payloads[i]);
}
}
free(directory->keys);
free(directory->payloads);
free(directory);
}
void directory_clear(directory_t directory, char release_payloads) {
if (release_payloads) {
unsigned int i;
for (i=0; i<directory->entries; ++i) {
free(directory->payloads[i]);
directory->payloads[i] = NULL;
}
}
directory->entries = 0;
}
// Helper function that compares a key against the directory key at a given position.
// The function returns:
// -1 if key < directory[pos]
// 0 if key = directory[pos]
// 1 if key > directory[pos]
static int dir_keycmp(directory_t directory, const unsigned char* key,
unsigned int pos) {
int i;
int cmp = 0;
for (i=directory->key_size - 1; cmp == 0 && i>=0; --i) {
if (key[i] < directory->keys[pos*directory->key_size + i])
cmp = -1;
else if (key[i] > directory->keys[pos*directory->key_size + i])
cmp = 1;
}
return cmp;
}
// Helper function that performs a binary search on the directory.
// The function will return the first position p, such that A[p] >= key.
static unsigned int dir_bsearch(directory_t directory, const unsigned char* key) {
if (directory->entries == 0)
return 0; // Handle the empty case.
unsigned int l = 0;
unsigned int h = directory->entries - 1;
// Binary search:
while (h >= l) {
// Compute the mid-point.
unsigned int mid = (l + h) / 2; // Would overflow for very large l,h. However, we expect the directories to remain reasonably small.
// Compare the key with the mid-point.
int cmp = dir_keycmp(directory, key, mid);
if (cmp < 0) {
if (mid == 0)
return 0; // Prevent an underflow (happens for 1-element arrays if we search for a key that is smaller than the only element)
h = mid - 1;
} else if (cmp > 0) {
l = mid + 1;
} else {
// We found the position.
return mid;
}
}
return l; // Lower bound for insert.
}
// Locate an entry in the directory.
unsigned int directory_find(directory_t directory, const void* key) {
const unsigned char* ckey = (const unsigned char*)key;
if (directory->entries == 0)
return directory->entries; // Handle empty case.
// Check if the last accessed position corresponds to this key.
if (directory->last_access < directory->entries
&& dir_keycmp(directory, ckey, directory->last_access) == 0)
return directory->last_access;
// If it was not, use binary search to find it.
unsigned int pos = dir_bsearch(directory, ckey);
// Check if this is actually the key position, as bsearch might return
// an upper bound for the key position as well.
if (dir_keycmp(directory, ckey, pos) == 0) {
directory->last_access = pos;
return pos;
}
// Indicate KEY_NOT_FOUND.
return directory->entries;
}
void* directory_keyAt(directory_t directory, unsigned int position) {
return &(directory->keys[directory->key_size * position]);
}
void* directory_valueAt(directory_t directory, unsigned int position) {
return directory->payloads[position];
}
void* directory_fetch(directory_t directory, const void* key) {
unsigned int pos = directory_find(directory, key);
if (pos==directory->entries)
return NULL;
else
return directory->payloads[pos];
}
// Insert a payload at a given position.
static void* directory_put(directory_t directory, unsigned int position, void* payload) {
if (position < directory->entries) {
void* tmp = directory->payloads[position];
directory->payloads[position] = payload;
return tmp;
}
return NULL;
}
// Insert a new entry in the directory.
void* directory_insert(directory_t directory, const void* key, void* payload) {
const unsigned char* ckey = (const unsigned char*)key;
// Use bsearch to find the position of the key.
unsigned int insert_position = dir_bsearch(directory, ckey);
// If the key is already stored in the directory, replace it.
if (insert_position < directory->entries
&& dir_keycmp(directory, ckey, insert_position) == 0) {
return directory_put(directory, insert_position, payload);
}
// If it is not, we have to insert the key, make sure that there is enough
// storage left in the directory.
if (directory->capacity <= directory->entries) {
// We dont have any capacity left in the directory, grow it first.
directory->capacity += 10;
directory->keys = realloc(directory->keys,
directory->key_size*directory->capacity);
directory->payloads =
realloc(directory->payloads, sizeof(void*)*directory->capacity);
}
// Now move the keys and payloads forward to make place for the new
// insertion.
memmove(&(directory->keys[(insert_position + 1)*directory->key_size]),
&(directory->keys[insert_position * directory->key_size]),
(directory->entries - insert_position)*directory->key_size);
memmove(&(directory->payloads[insert_position+1]),
&(directory->payloads[insert_position]),
(directory->entries - insert_position)*sizeof(void*));
// Ok, insert the value.
memcpy(&(directory->keys[insert_position * directory->key_size]), ckey,
directory->key_size);
directory->payloads[insert_position] = payload;
directory->entries++;
return NULL;
}
void directory_remove(directory_t directory, const void* key, char release_payload) {
const unsigned char* ckey = (const unsigned char*)key;
// Find the position of the key.
unsigned int position = dir_bsearch(directory, ckey);
if (position >= directory->entries)
return; // Protect against empty deletion.
if (dir_keycmp(directory, ckey, position) != 0)
return; // The key is not contained.
if (release_payload)
free(directory->payloads[position]);
// Move all remaining entries one position to the left.
memmove(&(directory->keys[position*directory->key_size]),
&(directory->keys[(position + 1) * directory->key_size]),
(directory->entries - position - 1)*directory->key_size);
memmove(&(directory->payloads[position]),
&(directory->payloads[position + 1]),
(directory->entries - position - 1)*sizeof(void*));
directory->entries--;
}
| 3.328125 | 3 |
2024-11-18T22:25:46.940354+00:00 | 2012-03-23T03:07:26 | 6d108f597b5eb64bd77e3faa399a7392e5c4c8fb | {
"blob_id": "6d108f597b5eb64bd77e3faa399a7392e5c4c8fb",
"branch_name": "refs/heads/master",
"committer_date": "2012-03-23T03:07:26",
"content_id": "03fb498dd2bd7c8ef0d167f8e8496096f1a8d647",
"detected_licenses": [
"BSD-2-Clause"
],
"directory_id": "c72cfd5592a51876459e9cf5047a07ac89502ba4",
"extension": "h",
"filename": "th.h",
"fork_events_count": 1,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 3804829,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 5424,
"license": "BSD-2-Clause",
"license_type": "permissive",
"path": "/src/th.h",
"provenance": "stackv2-0115.json.gz:140945",
"repo_name": "oopos/fossil",
"revision_date": "2012-03-23T03:07:26",
"revision_id": "a213b3e819ed0ce47b6a5a06270f44ae5d2bb6d0",
"snapshot_id": "665eb05fb877a7094f9302f486b88bf952b004e9",
"src_encoding": "UTF-8",
"star_events_count": 8,
"url": "https://raw.githubusercontent.com/oopos/fossil/a213b3e819ed0ce47b6a5a06270f44ae5d2bb6d0/src/th.h",
"visit_date": "2021-01-01T16:05:25.150627"
} | stackv2 |
/* This header file defines the external interface to the custom Scripting
** Language (TH) interpreter. TH is very similar to TCL but is not an
** exact clone.
*/
/*
** Before creating an interpreter, the application must allocate and
** populate an instance of the following structure. It must remain valid
** for the lifetime of the interpreter.
*/
struct Th_Vtab {
void *(*xMalloc)(unsigned int);
void (*xFree)(void *);
};
typedef struct Th_Vtab Th_Vtab;
/*
** Opaque handle for interpeter.
*/
typedef struct Th_Interp Th_Interp;
/*
** Create and delete interpreters.
*/
Th_Interp * Th_CreateInterp(Th_Vtab *pVtab);
void Th_DeleteInterp(Th_Interp *);
/*
** Evaluate an TH program in the stack frame identified by parameter
** iFrame, according to the following rules:
**
** * If iFrame is 0, this means the current frame.
**
** * If iFrame is negative, then the nth frame up the stack, where n is
** the absolute value of iFrame. A value of -1 means the calling
** procedure.
**
** * If iFrame is +ve, then the nth frame from the bottom of the stack.
** An iFrame value of 1 means the toplevel (global) frame.
*/
int Th_Eval(Th_Interp *interp, int iFrame, const char *zProg, int nProg);
/*
** Evaluate a TH expression. The result is stored in the
** interpreter result.
*/
int Th_Expr(Th_Interp *interp, const char *, int);
/*
** Access TH variables in the current stack frame. If the variable name
** begins with "::", the lookup is in the top level (global) frame.
*/
int Th_GetVar(Th_Interp *, const char *, int);
int Th_SetVar(Th_Interp *, const char *, int, const char *, int);
int Th_LinkVar(Th_Interp *, const char *, int, int, const char *, int);
int Th_UnsetVar(Th_Interp *, const char *, int);
typedef int (*Th_CommandProc)(Th_Interp *, void *, int, const char **, int *);
/*
** Register new commands.
*/
int Th_CreateCommand(
Th_Interp *interp,
const char *zName,
/* int (*xProc)(Th_Interp *, void *, int, const char **, int *), */
Th_CommandProc xProc,
void *pContext,
void (*xDel)(Th_Interp *, void *)
);
/*
** Delete or rename commands.
*/
int Th_RenameCommand(Th_Interp *, const char *, int, const char *, int);
/*
** Push a new stack frame (local variable context) onto the interpreter
** stack, call the function supplied as parameter xCall with the two
** context arguments,
**
** xCall(interp, pContext1, pContext2)
**
** , then pop the frame off of the interpreter stack. The value returned
** by the xCall() function is returned as the result of this function.
**
** This is intended for use by the implementation of commands such as
** those created by [proc].
*/
int Th_InFrame(Th_Interp *interp,
int (*xCall)(Th_Interp *, void *pContext1, void *pContext2),
void *pContext1,
void *pContext2
);
/*
** Valid return codes for xProc callbacks.
*/
#define TH_OK 0
#define TH_ERROR 1
#define TH_BREAK 2
#define TH_RETURN 3
#define TH_CONTINUE 4
/*
** Set and get the interpreter result.
*/
int Th_SetResult(Th_Interp *, const char *, int);
const char *Th_GetResult(Th_Interp *, int *);
char *Th_TakeResult(Th_Interp *, int *);
/*
** Set an error message as the interpreter result. This also
** sets the global stack-trace variable $::th_stack_trace.
*/
int Th_ErrorMessage(Th_Interp *, const char *, const char *, int);
/*
** Access the memory management functions associated with the specified
** interpreter.
*/
void *Th_Malloc(Th_Interp *, int);
void Th_Free(Th_Interp *, void *);
/*
** Functions for handling TH lists.
*/
int Th_ListAppend(Th_Interp *, char **, int *, const char *, int);
int Th_SplitList(Th_Interp *, const char *, int, char ***, int **, int *);
int Th_StringAppend(Th_Interp *, char **, int *, const char *, int);
/*
** Functions for handling numbers and pointers.
*/
int Th_ToInt(Th_Interp *, const char *, int, int *);
int Th_ToDouble(Th_Interp *, const char *, int, double *);
int Th_SetResultInt(Th_Interp *, int);
int Th_SetResultDouble(Th_Interp *, double);
/*
** Drop in replacements for the corresponding standard library functions.
*/
int th_strlen(const char *);
int th_isdigit(char);
int th_isspace(char);
int th_isalnum(char);
int th_isspecial(char);
char *th_strdup(Th_Interp *interp, const char *z, int n);
/*
** Interfaces to register the language extensions.
*/
int th_register_language(Th_Interp *interp); /* th_lang.c */
int th_register_sqlite(Th_Interp *interp); /* th_sqlite.c */
int th_register_vfs(Th_Interp *interp); /* th_vfs.c */
int th_register_testvfs(Th_Interp *interp); /* th_testvfs.c */
int th_register_tcl(Th_Interp *interp, void *pContext); /* th_tcl.c */
/*
** General purpose hash table from th_lang.c.
*/
typedef struct Th_Hash Th_Hash;
typedef struct Th_HashEntry Th_HashEntry;
struct Th_HashEntry {
void *pData;
char *zKey;
int nKey;
Th_HashEntry *pNext; /* Internal use only */
};
Th_Hash *Th_HashNew(Th_Interp *);
void Th_HashDelete(Th_Interp *, Th_Hash *);
void Th_HashIterate(Th_Interp*,Th_Hash*,void (*x)(Th_HashEntry*, void*),void*);
Th_HashEntry *Th_HashFind(Th_Interp*, Th_Hash*, const char*, int, int);
/*
** Useful functions from th_lang.c.
*/
int Th_WrongNumArgs(Th_Interp *interp, const char *zMsg);
typedef struct Th_SubCommand {char *zName; Th_CommandProc xProc;} Th_SubCommand;
int Th_CallSubCommand(Th_Interp*,void*,int,const char**,int*,Th_SubCommand*);
| 2.3125 | 2 |
2024-11-18T22:25:47.143980+00:00 | 2013-01-22T02:21:38 | 5a818fc25caf79e4ac5693abe143e009c7520252 | {
"blob_id": "5a818fc25caf79e4ac5693abe143e009c7520252",
"branch_name": "refs/heads/master",
"committer_date": "2013-01-22T04:31:43",
"content_id": "3927163b6fe540029deb100522e524d2d487ff1a",
"detected_licenses": [
"MIT"
],
"directory_id": "42ecc6065d128db37645e119ab2b0d83fe08ecfc",
"extension": "c",
"filename": "table_descr.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": null,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2424,
"license": "MIT",
"license_type": "permissive",
"path": "/server/table_descr.c",
"provenance": "stackv2-0115.json.gz:141204",
"repo_name": "maxott/oml",
"revision_date": "2013-01-22T02:21:38",
"revision_id": "c0982eb92005a9f7810363ccc35a5e3acab4138d",
"snapshot_id": "e1d14f1317acb9a0f314271f15424b3e1a5d88b2",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/maxott/oml/c0982eb92005a9f7810363ccc35a5e3acab4138d/server/table_descr.c",
"visit_date": "2020-04-08T07:49:42.646358"
} | stackv2 | /*
* Copyright 2007-2013 National ICT Australia (NICTA), Australia
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
*/
#include <stdlib.h>
#include <string.h>
#include "mem.h"
#include "table_descr.h"
TableDescr*
table_descr_new (const char* name, struct schema* schema)
{
if (name == NULL)
return NULL;
/* schema == NULL means metadata table */
char *new_name = xstrndup (name, strlen (name));
TableDescr* t = xmalloc (sizeof(TableDescr));
if (t == NULL) {
xfree (new_name);
return NULL;
}
t->name = new_name;
t->schema = schema;
t->next = NULL;
return t;
}
int
table_descr_have_table (TableDescr* tables, const char* table_name)
{
while (tables)
{
if (strcmp (tables->name, table_name) == 0)
return 1;
tables = tables->next;
}
return 0;
}
void
table_descr_array_free (TableDescr* tables, int n)
{
int i = 0;
for (i = 0; i < n; i++)
{
xfree (tables[i].name);
if (tables[i].schema)
schema_free (tables[i].schema);
}
xfree(tables);
}
void
table_descr_list_free (TableDescr* tables)
{
TableDescr* t = tables;
while (t)
{
TableDescr* next = t->next;
xfree (t->name);
if (t->schema)
schema_free (t->schema);
xfree (t);
t = next;
}
}
/*
Local Variables:
mode: C
tab-width: 2
indent-tabs-mode: nil
End:
vim: sw=2:sts=2:expandtab
*/
| 2.109375 | 2 |
2024-11-18T22:25:47.232067+00:00 | 2023-02-16T11:27:40 | 094f99de31b14c4c2b5cc77cc2736e987ee6f5a2 | {
"blob_id": "094f99de31b14c4c2b5cc77cc2736e987ee6f5a2",
"branch_name": "refs/heads/main",
"committer_date": "2023-02-16T14:59:16",
"content_id": "5f8be73cf742f8d65d4c246d0599e4ab0ba54a91",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "e8302c75d770d1608b317d6af5c483bbad6c0493",
"extension": "c",
"filename": "settings_file.c",
"fork_events_count": 32,
"gha_created_at": "2016-08-05T22:14:50",
"gha_event_created_at": "2022-04-05T17:14:07",
"gha_language": "C",
"gha_license_id": "Apache-2.0",
"github_id": 65052293,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 12128,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/subsys/settings/src/settings_file.c",
"provenance": "stackv2-0115.json.gz:141334",
"repo_name": "intel/zephyr",
"revision_date": "2023-02-16T11:27:40",
"revision_id": "06d5bc51b580777079bb0b7e769e4127598ea5ee",
"snapshot_id": "819362089aa44ae378a5558f3b222197aaa811f7",
"src_encoding": "UTF-8",
"star_events_count": 32,
"url": "https://raw.githubusercontent.com/intel/zephyr/06d5bc51b580777079bb0b7e769e4127598ea5ee/subsys/settings/src/settings_file.c",
"visit_date": "2023-09-04T00:20:35.217393"
} | stackv2 | /*
* Copyright (c) 2018 Nordic Semiconductor ASA
* Copyright (c) 2015 Runtime Inc
*
* SPDX-License-Identifier: Apache-2.0
*/
#include <string.h>
#include <stdbool.h>
#include <zephyr/kernel.h>
#include <zephyr/fs/fs.h>
#include <zephyr/settings/settings.h>
#include "settings/settings_file.h"
#include "settings_priv.h"
#include <zephyr/logging/log.h>
LOG_MODULE_DECLARE(settings, CONFIG_SETTINGS_LOG_LEVEL);
#ifdef CONFIG_SETTINGS_FS
#define SETTINGS_FILE_MAX_LINES CONFIG_SETTINGS_FS_MAX_LINES
#define SETTINGS_FILE_PATH CONFIG_SETTINGS_FS_FILE
#else
#define SETTINGS_FILE_MAX_LINES CONFIG_SETTINGS_FILE_MAX_LINES
#define SETTINGS_FILE_PATH CONFIG_SETTINGS_FILE_PATH
#endif
int settings_backend_init(void);
static int settings_file_load(struct settings_store *cs,
const struct settings_load_arg *arg);
static int settings_file_save(struct settings_store *cs, const char *name,
const char *value, size_t val_len);
static void *settings_file_storage_get(struct settings_store *cs);
static const struct settings_store_itf settings_file_itf = {
.csi_load = settings_file_load,
.csi_save = settings_file_save,
.csi_storage_get = settings_file_storage_get
};
/*
* Register a file to be a source of configuration.
*/
int settings_file_src(struct settings_file *cf)
{
if (!cf->cf_name) {
return -EINVAL;
}
cf->cf_store.cs_itf = &settings_file_itf;
settings_src_register(&cf->cf_store);
return 0;
}
/*
* Register a file to be a destination of configuration.
*/
int settings_file_dst(struct settings_file *cf)
{
if (!cf->cf_name) {
return -EINVAL;
}
cf->cf_store.cs_itf = &settings_file_itf;
settings_dst_register(&cf->cf_store);
return 0;
}
/**
* @brief Check if there is any duplicate of the current setting
*
* This function checks if there is any duplicated data further in the buffer.
*
* @param entry_ctx Current entry context
* @param name The name of the current entry
*
* @retval false No duplicates found
* @retval true Duplicate found
*/
static bool settings_file_check_duplicate(
const struct line_entry_ctx *entry_ctx,
const char * const name)
{
struct line_entry_ctx entry2_ctx = *entry_ctx;
/* Searching the duplicates */
while (settings_next_line_ctx(&entry2_ctx) == 0) {
char name2[SETTINGS_MAX_NAME_LEN + SETTINGS_EXTRA_LEN + 1];
size_t name2_len;
if (entry2_ctx.len == 0) {
break;
}
if (settings_line_name_read(name2, sizeof(name2), &name2_len,
&entry2_ctx)) {
continue;
}
name2[name2_len] = '\0';
if (!strcmp(name, name2)) {
return true;
}
}
return false;
}
static int read_entry_len(const struct line_entry_ctx *entry_ctx, off_t off)
{
if (off >= entry_ctx->len) {
return 0;
}
return entry_ctx->len - off;
}
static int settings_file_load_priv(struct settings_store *cs, line_load_cb cb,
void *cb_arg, bool filter_duplicates)
{
struct settings_file *cf = CONTAINER_OF(cs, struct settings_file, cf_store);
struct fs_file_t file;
int lines;
int rc;
struct line_entry_ctx entry_ctx = {
.stor_ctx = (void *)&file,
.seek = 0,
.len = 0 /* unknown length */
};
lines = 0;
fs_file_t_init(&file);
rc = fs_open(&file, cf->cf_name, FS_O_READ);
if (rc != 0) {
if (rc == -ENOENT) {
return -ENOENT;
}
return -EINVAL;
}
while (1) {
char name[SETTINGS_MAX_NAME_LEN + SETTINGS_EXTRA_LEN + 1];
size_t name_len;
bool pass_entry = true;
rc = settings_next_line_ctx(&entry_ctx);
if (rc || entry_ctx.len == 0) {
break;
}
rc = settings_line_name_read(name, sizeof(name), &name_len,
&entry_ctx);
if (rc || name_len == 0) {
break;
}
name[name_len] = '\0';
if (filter_duplicates &&
(!read_entry_len(&entry_ctx, name_len+1) ||
settings_file_check_duplicate(&entry_ctx, name))) {
pass_entry = false;
}
/*name, val-read_cb-ctx, val-off*/
/* take into account '=' separator after the name */
if (pass_entry) {
cb(name, (void *)&entry_ctx, name_len + 1, cb_arg);
}
lines++;
}
rc = fs_close(&file);
cf->cf_lines = lines;
return rc;
}
/*
* Called to load configuration items.
*/
static int settings_file_load(struct settings_store *cs,
const struct settings_load_arg *arg)
{
return settings_file_load_priv(cs,
settings_line_load_cb,
(void *)arg,
true);
}
static void settings_tmpfile(char *dst, const char *src, char *pfx)
{
int len;
int pfx_len;
len = strlen(src);
pfx_len = strlen(pfx);
if (len + pfx_len >= SETTINGS_FILE_NAME_MAX) {
len = SETTINGS_FILE_NAME_MAX - pfx_len - 1;
}
memcpy(dst, src, len);
memcpy(dst + len, pfx, pfx_len);
dst[len + pfx_len] = '\0';
}
static int settings_file_create_or_replace(struct fs_file_t *zfp,
const char *file_name)
{
struct fs_dirent entry;
if (fs_stat(file_name, &entry) == 0) {
if (entry.type == FS_DIR_ENTRY_FILE) {
if (fs_unlink(file_name)) {
return -EIO;
}
} else {
return -EISDIR;
}
}
return fs_open(zfp, file_name, FS_O_CREATE | FS_O_RDWR);
}
/*
* Try to compress configuration file by keeping unique names only.
*/
static int settings_file_save_and_compress(struct settings_file *cf,
const char *name, const char *value,
size_t val_len)
{
int rc, rc2;
struct fs_file_t rf;
struct fs_file_t wf;
char tmp_file[SETTINGS_FILE_NAME_MAX];
char name1[SETTINGS_MAX_NAME_LEN + SETTINGS_EXTRA_LEN];
char name2[SETTINGS_MAX_NAME_LEN + SETTINGS_EXTRA_LEN];
struct line_entry_ctx loc1 = {
.stor_ctx = &rf,
.seek = 0,
.len = 0 /* unknown length */
};
struct line_entry_ctx loc2;
struct line_entry_ctx loc3 = {
.stor_ctx = &wf
};
int copy;
int lines;
size_t new_name_len;
size_t val1_off;
fs_file_t_init(&rf);
fs_file_t_init(&wf);
if (fs_open(&rf, cf->cf_name, FS_O_CREATE | FS_O_RDWR) != 0) {
return -ENOEXEC;
}
settings_tmpfile(tmp_file, cf->cf_name, ".cmp");
if (settings_file_create_or_replace(&wf, tmp_file)) {
fs_close(&rf);
return -ENOEXEC;
}
lines = 0;
new_name_len = strlen(name);
while (1) {
rc = settings_next_line_ctx(&loc1);
if (rc || loc1.len == 0) {
/* try to amend new value to the compressed file */
break;
}
rc = settings_line_name_read(name1, sizeof(name1), &val1_off,
&loc1);
if (rc) {
/* try to process next line */
continue;
}
if (val1_off + 1 == loc1.len) {
/* Lack of a value so the record is a deletion-record */
/* No sense to copy empty entry from */
/* the oldest sector */
continue;
}
/* avoid copping value which will be overwritten by new value*/
if ((val1_off == new_name_len) &&
!memcmp(name1, name, val1_off)) {
continue;
}
loc2 = loc1;
copy = 1;
while (1) {
size_t val2_off;
rc = settings_next_line_ctx(&loc2);
if (rc || loc2.len == 0) {
/* try to amend new value to */
/* the compressed file */
break;
}
rc = settings_line_name_read(name2, sizeof(name2),
&val2_off, &loc2);
if (rc) {
/* try to process next line */
continue;
}
if ((val1_off == val2_off) &&
!memcmp(name1, name2, val1_off)) {
copy = 0; /* newer version doesn't exist */
break;
}
}
if (!copy) {
continue;
}
loc2 = loc1;
loc2.len += 2;
loc2.seek -= 2;
rc = settings_line_entry_copy(&loc3, 0, &loc2, 0, loc2.len);
if (rc) {
/* compressed file might be corrupted */
goto end_rolback;
}
lines++;
}
/* at last store the new value */
rc = settings_line_write(name, value, val_len, 0, &loc3);
if (rc) {
/* compressed file might be corrupted */
goto end_rolback;
}
rc = fs_close(&wf);
rc2 = fs_close(&rf);
if (rc == 0 && rc2 == 0 && fs_unlink(cf->cf_name) == 0) {
if (fs_rename(tmp_file, cf->cf_name)) {
return -ENOENT;
}
cf->cf_lines = lines + 1;
} else {
rc = -EIO;
}
/*
* XXX at settings_file_load(), look for .cmp if actual file does not
* exist.
*/
return 0;
end_rolback:
(void)fs_close(&wf);
if (fs_close(&rf) == 0) {
(void)fs_unlink(tmp_file);
}
return -EIO;
}
static int settings_file_save_priv(struct settings_store *cs, const char *name,
const char *value, size_t val_len)
{
struct settings_file *cf = CONTAINER_OF(cs, struct settings_file, cf_store);
struct line_entry_ctx entry_ctx;
struct fs_file_t file;
int rc2;
int rc;
if (!name) {
return -EINVAL;
}
fs_file_t_init(&file);
if (cf->cf_maxlines && (cf->cf_lines + 1 >= cf->cf_maxlines)) {
/*
* Compress before config file size exceeds
* the max number of lines.
*/
return settings_file_save_and_compress(cf, name, value,
val_len);
}
/*
* Open the file to add this one value.
*/
rc = fs_open(&file, cf->cf_name, FS_O_CREATE | FS_O_RDWR);
if (rc == 0) {
rc = fs_seek(&file, 0, FS_SEEK_END);
if (rc == 0) {
entry_ctx.stor_ctx = &file;
rc = settings_line_write(name, value, val_len, 0,
(void *)&entry_ctx);
if (rc == 0) {
cf->cf_lines++;
}
}
rc2 = fs_close(&file);
if (rc == 0) {
rc = rc2;
}
}
return rc;
}
/*
* Called to save configuration.
*/
static int settings_file_save(struct settings_store *cs, const char *name,
const char *value, size_t val_len)
{
struct settings_line_dup_check_arg cdca;
if (val_len > 0 && value == NULL) {
return -EINVAL;
}
/*
* Check if we're writing the same value again.
*/
cdca.name = name;
cdca.val = (char *)value;
cdca.is_dup = 0;
cdca.val_len = val_len;
settings_file_load_priv(cs, settings_line_dup_check_cb, &cdca, false);
if (cdca.is_dup == 1) {
return 0;
}
return settings_file_save_priv(cs, name, value, val_len);
}
static int read_handler(void *ctx, off_t off, char *buf, size_t *len)
{
struct line_entry_ctx *entry_ctx = ctx;
struct fs_file_t *file = entry_ctx->stor_ctx;
ssize_t r_len;
int rc;
/* 0 is reserved for reading the length-field only */
if (entry_ctx->len != 0) {
if (off >= entry_ctx->len) {
*len = 0;
return 0;
}
if ((off + *len) > entry_ctx->len) {
*len = entry_ctx->len - off;
}
}
rc = fs_seek(file, entry_ctx->seek + off, FS_SEEK_SET);
if (rc) {
goto end;
}
r_len = fs_read(file, buf, *len);
if (r_len >= 0) {
*len = r_len;
rc = 0;
} else {
rc = r_len;
}
end:
return rc;
}
static size_t get_len_cb(void *ctx)
{
struct line_entry_ctx *entry_ctx = ctx;
return entry_ctx->len;
}
static int write_handler(void *ctx, off_t off, char const *buf, size_t len)
{
struct line_entry_ctx *entry_ctx = ctx;
struct fs_file_t *file = entry_ctx->stor_ctx;
int rc;
/* append to file only */
rc = fs_seek(file, 0, FS_SEEK_END);
if (rc == 0) {
rc = fs_write(file, buf, len);
if (rc > 0) {
rc = 0;
}
}
return rc;
}
void settings_mount_file_backend(struct settings_file *cf)
{
settings_line_io_init(read_handler, write_handler, get_len_cb, 1);
}
static int mkdir_if_not_exists(const char *path)
{
struct fs_dirent entry;
int err;
err = fs_stat(path, &entry);
if (err == -ENOENT) {
return fs_mkdir(path);
} else if (err) {
return err;
}
if (entry.type != FS_DIR_ENTRY_DIR) {
return -EEXIST;
}
return 0;
}
static int mkdir_for_file(const char *file_path)
{
char dir_path[SETTINGS_FILE_NAME_MAX];
int err;
for (size_t i = 0; file_path[i] != '\0'; i++) {
if (i > 0 && file_path[i] == '/') {
dir_path[i] = '\0';
err = mkdir_if_not_exists(dir_path);
if (err) {
return err;
}
}
dir_path[i] = file_path[i];
}
return 0;
}
int settings_backend_init(void)
{
static struct settings_file config_init_settings_file = {
.cf_name = SETTINGS_FILE_PATH,
.cf_maxlines = SETTINGS_FILE_MAX_LINES
};
int rc;
rc = settings_file_src(&config_init_settings_file);
if (rc) {
return rc;
}
rc = settings_file_dst(&config_init_settings_file);
if (rc) {
return rc;
}
settings_mount_file_backend(&config_init_settings_file);
/*
* Must be called after root FS has been initialized.
*/
return mkdir_for_file(config_init_settings_file.cf_name);
}
static void *settings_file_storage_get(struct settings_store *cs)
{
struct settings_file *cf = CONTAINER_OF(cs, struct settings_file, cf_store);
return (void *)cf->cf_name;
}
| 2.296875 | 2 |
2024-11-18T22:25:47.306904+00:00 | 2020-05-08T20:32:48 | 7a93b3323645d9d1dc12ccc7fe0c39b9d0b946a1 | {
"blob_id": "7a93b3323645d9d1dc12ccc7fe0c39b9d0b946a1",
"branch_name": "refs/heads/master",
"committer_date": "2020-05-08T20:32:48",
"content_id": "eb8a3dee559f5b30eb41d6b4047da03e41bea251",
"detected_licenses": [
"MIT"
],
"directory_id": "b573d120637692f75b5e6787d49ddd282b1ce150",
"extension": "c",
"filename": "urp_read_dword.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 261293038,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 222,
"license": "MIT",
"license_type": "permissive",
"path": "/src/urp_read_dword.c",
"provenance": "stackv2-0115.json.gz:141463",
"repo_name": "TurkeyMcMac/urp",
"revision_date": "2020-05-08T20:32:48",
"revision_id": "b736c1866308d919fbc3a0a0782336963efee8ff",
"snapshot_id": "21ff6ebdf800e940926f8907eef1df65a2971a35",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/TurkeyMcMac/urp/b736c1866308d919fbc3a0a0782336963efee8ff/src/urp_read_dword.c",
"visit_date": "2022-08-20T16:31:55.976397"
} | stackv2 | #include "urp.h"
#include <avr/pgmspace.h>
uint32_t urp_read_dword(URPTR ptr)
{
if(URP_IS_RAM(ptr))
return *(uint32_t *)URP_RAM_ADDR(ptr);
else /* if (URP_IS_PGM(ptr)) */
return pgm_read_dword(URP_PGM_ADDR(ptr));
}
| 2.28125 | 2 |
2024-11-18T22:25:47.546992+00:00 | 2016-04-29T22:05:57 | e68ee0e2c3f10fc95431f485346d962901b0f9fa | {
"blob_id": "e68ee0e2c3f10fc95431f485346d962901b0f9fa",
"branch_name": "refs/heads/master",
"committer_date": "2016-04-29T22:05:57",
"content_id": "ba5ec93e09ac08052d931a27d60b124a817d7522",
"detected_licenses": [
"MIT"
],
"directory_id": "2d94fc12c3b4fdedbff8ca935350a5e67b697d6c",
"extension": "c",
"filename": "filter.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": null,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2063,
"license": "MIT",
"license_type": "permissive",
"path": "/Modules/Core/filter.c",
"provenance": "stackv2-0115.json.gz:141725",
"repo_name": "Unionjackjz1/BCI",
"revision_date": "2016-04-29T22:05:57",
"revision_id": "fbd080b047a4754a35f23dc27db8f5d03c1eb728",
"snapshot_id": "11dff45c0565be6e7c0f9760a09a4bd15ae812af",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/Unionjackjz1/BCI/fbd080b047a4754a35f23dc27db8f5d03c1eb728/Modules/Core/filter.c",
"visit_date": "2021-01-24T03:18:23.769343"
} | stackv2 | #ifndef FILTER_C_INCLUDED
#define FILTER_C_INCLUDED
#include "filter.h"
void filter_Init_EMA(EMAFilter *filter)
{
filter->alpha = 1.0;
filter->readIn = 0.0;
filter->output = 0.0;
filter->output_old = 0.0;
}
void filter_Init_DEMA(DEMAFilter *filter)
{
filter->alpha = 1.0;
filter->beta = 1.0;
filter->readIn = 0.0;
filter->outputS = 0.0;
filter->outputB = 0.0;
filter->outputS_old = 0.0;
filter->outputB_old = 0.0;
}
void filter_Init_FUA(FUAFilter *filter)
{
filter->index = 0;
for (int i = 0; i < 5; i++)
{
filter->components[i] = 0;
}
}
void filter_Init_TUA(TUAFilter *filter)
{
filter->index = 0;
for (int i = 0; i < 10; i++)
{
filter->components[i] = 0;
}
}
float filter_EMA(EMAFilter *filter, const float readIn, const float alpha)
{
filter->alpha = alpha;
filter->readIn = readIn;
filter->output = alpha * readIn + (1.0 - alpha) * filter->output_old;
filter->output_old = filter->output;
return filter->output;
}
float filter_DEMA(DEMAFilter *filter, const float readIn, const float alpha, const float beta)
{
filter->alpha = alpha;
filter->beta = beta;
filter->readIn = readIn;
filter->outputS = (alpha * readIn) + ((1.0 - alpha) * (filter->outputS_old + filter->outputB_old));
filter->outputB = (beta * (filter->outputS - filter->outputS_old)) + ((1.0 - beta) * filter->outputB_old);
filter->outputS_old = filter->outputS;
filter->outputB_old = filter->outputB;
return filter->outputS + filter->outputB;
}
float filter_FUA(FUAFilter *filter, const float componentIn)
{
filter->components[filter->index] = componentIn;
filter->index = filter->index + 1 > 4 ? 0 : filter->index + 1;
float avg = 0.0;
for (int i = 0; i < 5; i++)
{
avg += filter->components[i];
}
return avg / 5.0;
}
float filter_TUA(TUAFilter *filter, const float componentIn)
{
filter->components[filter->index] = componentIn;
filter->index = filter->index + 1 > 9 ? 0 : filter->index + 1;
float avg = 0.0;
for (int i = 0; i < 10; i++)
{
avg += filter->components[i];
}
return avg / 10.0;
}
#endif //FILTER_C_INCLUDED
| 2.90625 | 3 |
2024-11-18T22:25:47.620444+00:00 | 2015-09-01T17:20:51 | 7f15c56a9021c5b064d79adf237db31174f73055 | {
"blob_id": "7f15c56a9021c5b064d79adf237db31174f73055",
"branch_name": "refs/heads/master",
"committer_date": "2015-09-01T17:20:51",
"content_id": "1563c1497ad79097f7d96763ce46b820ddecf503",
"detected_licenses": [
"MIT"
],
"directory_id": "d9c81ddbb827d45e72587ec81c0853e309dc263a",
"extension": "c",
"filename": "wrapper.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 32471288,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1378,
"license": "MIT",
"license_type": "permissive",
"path": "/src/wrapper.c",
"provenance": "stackv2-0115.json.gz:141855",
"repo_name": "medsec/catena-axungia",
"revision_date": "2015-09-01T17:20:51",
"revision_id": "9a65c86858ad9e423cad14552b664f14509284c1",
"snapshot_id": "c7ca751bcbd5f0aa311aa44ab745e23ba285328d",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/medsec/catena-axungia/9a65c86858ad9e423cad14552b664f14509284c1/src/wrapper.c",
"visit_date": "2016-09-06T03:17:31.617742"
} | stackv2 | #ifdef DBG
#include "catena-DBG.c"
#else
#include "catena-BRG.c"
#endif
#include "hash.h"
void wrapper(const uint8_t lambda, const uint8_t garlic){
uint8_t x[H_LEN];
uint8_t hv[H_LEN];
uint8_t t[4];
uint8_t c;
//set values. compare to test-catena.c
uint8_t min_garlic = garlic;
uint8_t tweak_id = 0;
uint8_t hashlen = H_LEN;
uint8_t saltlen = 16;
const uint8_t salt[16]=
{0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77,
0x88, 0x99, 0xAA, 0xBB, 0xCC, 0xDD, 0xEE, 0XFF};
uint8_t* pwd = malloc(8);
strncpy((char*)pwd, "Password", 8);
uint8_t pwdlen = 8;
const char *data = "I'm a header";
uint8_t datalen = strlen(data);
uint8_t client = CLIENT;
uint8_t hash[H_LEN];
/*Compute H(V)*/
__Hash1(VERSION_ID, strlen((char*)VERSION_ID), hv);
/* Compute Tweak */
t[0] = tweak_id;
t[1] = lambda;
t[2] = hashlen;
t[3] = saltlen;
/* Compute H(AD) */
__Hash1((uint8_t *) data, datalen,x);
/* Compute the initial value to hash */
__Hash5(hv, H_LEN, t, 4, x, H_LEN, pwd, pwdlen, salt, saltlen, x);
Flap(x, lambda, (min_garlic+1)/2, salt, saltlen, x);
for(c=min_garlic; c <= garlic; c++)
{
Flap(x, lambda, c, salt, saltlen, x);
if( (c==garlic) && (client == CLIENT))
{
memcpy(hash, x, H_LEN);
// return 0;
}
__Hash2(&c,1, x,H_LEN, x);
memset(x+hashlen, 0, H_LEN-hashlen);
}
memcpy(hash, x, hashlen);
} | 2.40625 | 2 |
2024-11-18T22:25:48.502224+00:00 | 2016-03-24T15:44:54 | cca3d56214750a6c738c795a7fca772c4938f0a7 | {
"blob_id": "cca3d56214750a6c738c795a7fca772c4938f0a7",
"branch_name": "refs/heads/master",
"committer_date": "2016-03-24T15:44:54",
"content_id": "2d331a0304a65e178ed205a4730ca8b8a3adacce",
"detected_licenses": [
"MIT"
],
"directory_id": "742d5e783f56a59f5ac3c8f1098f005fd7acb4f9",
"extension": "c",
"filename": "bubble_sort.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 46734037,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 600,
"license": "MIT",
"license_type": "permissive",
"path": "/Sorts/bubble_sort.c",
"provenance": "stackv2-0115.json.gz:142242",
"repo_name": "christopher-henderson/Fun-with-C",
"revision_date": "2016-03-24T15:44:54",
"revision_id": "2a2e67ee8d0b8596ae80f3d0ce08a3e48ed23bb6",
"snapshot_id": "c17936a0703283a9fb6451736ee4919126ec2600",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/christopher-henderson/Fun-with-C/2a2e67ee8d0b8596ae80f3d0ce08a3e48ed23bb6/Sorts/bubble_sort.c",
"visit_date": "2016-08-11T16:42:26.274217"
} | stackv2 | #include <stdio.h>
void bubble_sort(int* collection, int length) {
int temp;
for (int _ = 0; _ < length; _++) {
for (int index=0; index < length - 1; index ++) {
if (*(collection + index) > *(collection + index + 1)) {
temp = *(collection + index);
*(collection + index) = *(collection + index + 1);
*(collection + index + 1) = temp;
}
}
}
}
int main() {
int x[] = {12, 35 ,22 , 34, 2355, 12 ,5};
bubble_sort((int*) x, 7);
for (int i=0; i<7; i++) {
printf("%i\n", x[i]);
}
} | 3.421875 | 3 |
2024-11-18T22:25:48.956559+00:00 | 2023-04-08T01:37:00 | 4440946aa3a25a918cd3900ab2394327e0520a8c | {
"blob_id": "4440946aa3a25a918cd3900ab2394327e0520a8c",
"branch_name": "refs/heads/main",
"committer_date": "2023-04-08T01:37:10",
"content_id": "19947ac58da861e464e095351696816a4a7d91fa",
"detected_licenses": [
"BSD-2-Clause",
"BSD-3-Clause"
],
"directory_id": "6135301f6e393e7197b80307b1d0676505365d24",
"extension": "c",
"filename": "hash.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 32195258,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 14539,
"license": "BSD-2-Clause,BSD-3-Clause",
"license_type": "permissive",
"path": "/libdiffball/hash.c",
"provenance": "stackv2-0115.json.gz:142760",
"repo_name": "ferringb/diffball",
"revision_date": "2023-04-08T01:37:00",
"revision_id": "69c3f07a8982ea35833703fc83632e9a92306d2d",
"snapshot_id": "733406c718e742e0d1e967f8b95bb594df6e9953",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/ferringb/diffball/69c3f07a8982ea35833703fc83632e9a92306d2d/libdiffball/hash.c",
"visit_date": "2023-04-14T10:35:45.275628"
} | stackv2 | // SPDX-License-Identifier: BSD-3-Clause
// Copyright (C) 2003-2015 Brian Harring <ferringb@gmail.com>
#include <stdlib.h>
#include <diffball/defs.h>
#include <errno.h>
#include <string.h>
#include <diffball/adler32.h>
#include <diffball/defs.h>
#include <diffball/hash.h>
#include <diffball/bit-functions.h>
static off_u64
base_rh_bucket_lookup(RefHash *, ADLER32_SEED_CTX *);
static signed int
rh_rbucket_insert_match(RefHash *, ADLER32_SEED_CTX *, off_u64);
static signed int
base_rh_bucket_hash_insert(RefHash *, ADLER32_SEED_CTX *, off_u64);
static signed int rh_rbucket_cleanse(RefHash *rhash);
static signed int
common_rh_bucket_hash_init(RefHash *rhash, cfile *ref_cfh, unsigned int seed_len, unsigned int sample_rate, unsigned long hr_size, unsigned int type);
static signed int internal_loop_block(RefHash *rhash, cfile *ref_cfh, off_u64 ref_start, off_u64 ref_end, hash_insert_func);
#define RH_BUCKET_NEED_RESIZE(x) \
(((x) & ((x)-1)) == 0)
int cmp_chksum_ent(const void *ce1, const void *ce2)
{
chksum_ent *c1 = (chksum_ent *)ce1;
chksum_ent *c2 = (chksum_ent *)ce2;
return (c1->chksum == c2->chksum ? 0 : c1->chksum < c2->chksum ? -1
: 1);
}
signed int
RHash_cleanse(RefHash *rh)
{
if (rh->cleanse_hash)
return rh->cleanse_hash(rh);
return 0;
}
static inline signed int
RH_bucket_find_chksum_insert_pos(unsigned short chksum, unsigned short array[],
unsigned short count)
{
int low = 0, high, mid;
if (count < 32)
{
while (low < count)
{
if (array[low] > chksum)
return low;
else if (array[low] == chksum)
return -1;
low++;
}
return count;
}
high = count - 1;
while (low < high)
{
mid = (low + high) / 2;
if (chksum < array[mid])
high = mid - 1;
else if (chksum > array[mid])
low = mid + 1;
else
{
return -1;
}
}
if (chksum > array[low])
low++;
assert(low >= 0);
return low;
}
/* ripped straight out of K&R C manual. great book btw. */
static inline signed int
RH_bucket_find_chksum(unsigned short chksum, unsigned short array[],
unsigned short count)
{
int low, high, mid;
low = 0;
if (count < 32)
{
for (; low < count; low++)
{
if (chksum == array[low])
return low;
}
return -1;
}
high = count - 1;
while (low <= high)
{
mid = (low + high) / 2;
if (chksum < array[mid])
high = mid - 1;
else if (chksum > array[mid])
low = mid + 1;
else
return mid;
}
return -1;
}
static off_u64
base_rh_bucket_lookup(RefHash *rhash, ADLER32_SEED_CTX *ads)
{
bucket *hash = (bucket *)rhash->hash;
unsigned long index, chksum;
signed int pos;
chksum = get_checksum(ads);
index = chksum & RHASH_INDEX_MASK;
if (hash->depth[index] == 0)
{
return 0;
}
chksum = ((chksum >> 16) & 0xffff);
pos = RH_bucket_find_chksum(chksum, hash->chksum[index], hash->depth[index]);
if (pos >= 0)
{
assert(hash->depth[index] > pos);
return hash->offset[index][pos];
}
return 0;
}
signed int
free_RefHash(RefHash *rhash)
{
dcb_lprintf(2, "free_RefHash\n");
if (rhash->free_hash)
rhash->free_hash(rhash);
else if (rhash->hash)
free(rhash->hash);
rhash->hash = NULL;
rhash->ref_cfh = NULL;
rhash->free_hash = NULL;
rhash->hash_insert = NULL;
rhash->seed_len = rhash->hr_size = rhash->sample_rate = rhash->inserts = rhash->type = rhash->flags = rhash->duplicates = 0;
return 0;
}
void rh_bucket_free(RefHash *rhash)
{
unsigned long x;
bucket *hash = (bucket *)rhash->hash;
for (x = 0; x < rhash->hr_size; x++)
{
if (hash->chksum[x] != NULL)
{
free(hash->chksum[x]);
free(hash->offset[x]);
}
else
{
assert(hash->depth[x] == 0);
}
}
free(hash->chksum);
free(hash->offset);
free(hash->depth);
free(hash);
}
void common_init_RefHash(RefHash *rhash, cfile *ref_cfh, unsigned int seed_len, unsigned int sample_rate, unsigned int type,
hash_insert_func hif, free_hash_func fhf, hash_lookup_offset_func hlof)
{
rhash->flags = 0;
rhash->type = 0;
rhash->seed_len = seed_len;
assert(seed_len > 0);
rhash->sample_rate = sample_rate;
rhash->ref_cfh = ref_cfh;
rhash->inserts = rhash->duplicates = 0;
rhash->hash = NULL;
rhash->type = type;
rhash->hr_size = 0;
rhash->hash_insert = hif;
rhash->insert_match = NULL;
rhash->free_hash = fhf;
rhash->lookup_offset = hlof;
rhash->cleanse_hash = NULL;
}
signed int
rh_bucket_hash_init(RefHash *rhash, cfile *ref_cfh, unsigned int seed_len, unsigned int sample_rate, unsigned long hr_size)
{
return common_rh_bucket_hash_init(rhash, ref_cfh, seed_len, sample_rate, hr_size, RH_BUCKET_HASH);
}
signed int
rh_rbucket_hash_init(RefHash *rhash, cfile *ref_cfh, unsigned int seed_len, unsigned int sample_rate, unsigned long hr_size)
{
return common_rh_bucket_hash_init(rhash, ref_cfh, seed_len, sample_rate, hr_size, RH_RBUCKET_HASH);
}
static signed int
common_rh_bucket_hash_init(RefHash *rhash, cfile *ref_cfh, unsigned int seed_len, unsigned int sample_rate, unsigned long hr_size, unsigned int type)
{
bucket *rh;
common_init_RefHash(rhash, ref_cfh, seed_len, sample_rate, type, base_rh_bucket_hash_insert, rh_bucket_free, base_rh_bucket_lookup);
if (hr_size == 0)
hr_size = DEFAULT_RHASH_SIZE;
if (hr_size < MIN_RHASH_SIZE)
hr_size = MIN_RHASH_SIZE;
assert((hr_size & ~(1 << unsignedBitsNeeded(hr_size))) == hr_size);
rhash->hr_size = hr_size;
rh = (bucket *)malloc(sizeof(bucket));
if (rh == NULL)
return MEM_ERROR;
rh->max_depth = DEFAULT_RHASH_BUCKET_SIZE;
if ((rh->depth = (unsigned char *)calloc(sizeof(unsigned char), rhash->hr_size)) == NULL)
{
free(rh);
return MEM_ERROR;
}
else if ((rh->chksum = (unsigned short **)calloc(sizeof(unsigned short *), rhash->hr_size)) == NULL)
{
free(rh->depth);
free(rh);
return MEM_ERROR;
}
else if ((rh->offset = (off_u64 **)calloc(sizeof(off_u64 *), rhash->hr_size)) == NULL)
{
free(rh->chksum);
free(rh->depth);
free(rh);
return MEM_ERROR;
}
rhash->hash = (void *)rh;
if (type == RH_RBUCKET_HASH)
{
rhash->cleanse_hash = rh_rbucket_cleanse;
rhash->flags |= RH_IS_REVLOOKUP;
rhash->insert_match = rh_rbucket_insert_match;
}
return 0;
}
signed int
RH_bucket_resize(bucket *hash, unsigned long index, unsigned short size)
{
assert(RH_BUCKET_NEED_RESIZE(hash->depth[index]));
if (hash->depth[index] == 0)
{
if ((hash->chksum[index] = (unsigned short *)malloc(size * sizeof(unsigned short))) == NULL)
return MEM_ERROR;
if ((hash->offset[index] = (off_u64 *)malloc(size * sizeof(off_u64))) == NULL)
{
free(hash->chksum[index]);
return MEM_ERROR;
}
return 0;
}
if ((hash->chksum[index] = (unsigned short *)realloc(hash->chksum[index], size * sizeof(unsigned short))) == NULL)
return MEM_ERROR;
else if ((hash->offset[index] = (off_u64 *)realloc(hash->offset[index], size * sizeof(off_u64))) == NULL)
return MEM_ERROR;
return 0;
}
static signed int
base_rh_bucket_hash_insert(RefHash *rhash, ADLER32_SEED_CTX *ads, off_u64 offset)
{
unsigned long chksum, index;
signed int low;
bucket *hash;
hash = (bucket *)rhash->hash;
chksum = get_checksum(ads);
index = (chksum & RHASH_INDEX_MASK);
chksum = ((chksum >> 16) & 0xffff);
if (!hash->depth[index])
{
if (RH_bucket_resize(hash, index, RH_BUCKET_MIN_ALLOC))
{
return MEM_ERROR;
}
hash->chksum[index][0] = chksum;
if (rhash->type & (RH_BUCKET_HASH))
{
hash->offset[index][0] = offset;
}
else
{
hash->offset[index][0] = 0;
}
hash->depth[index]++;
return SUCCESSFULL_HASH_INSERT;
}
else if (hash->depth[index] < hash->max_depth)
{
low = RH_bucket_find_chksum_insert_pos(chksum, hash->chksum[index], hash->depth[index]);
if (low != -1 && (low == hash->depth[index] || hash->chksum[index][low] != chksum))
{
/* expand bucket if needed */
if (RH_BUCKET_NEED_RESIZE(hash->depth[index]))
{
if (RH_bucket_resize(hash, index, MIN(hash->max_depth, (hash->depth[index] * RH_BUCKET_REALLOC_RATE))))
{
return MEM_ERROR;
}
}
if (low == hash->depth[index])
{
hash->chksum[index][low] = chksum;
if (rhash->type & RH_BUCKET_HASH)
{
hash->offset[index][low] = offset;
}
else
{
hash->offset[index][low] = 0;
}
assert(hash->chksum[index][low - 1] < hash->chksum[index][low]);
}
else
{
/* shift low + 1 element to the right */
memmove(hash->chksum[index] + low + 1, hash->chksum[index] + low, (hash->depth[index] - low) * sizeof(unsigned short));
hash->chksum[index][low] = chksum;
if (rhash->type & RH_BUCKET_HASH)
{
memmove(hash->offset[index] + low + 1, hash->offset[index] + low, (hash->depth[index] - low) * sizeof(off_u64));
hash->offset[index][low] = offset;
}
else
{
hash->offset[index][hash->depth[index]] = 0;
}
assert(low == 0 || hash->chksum[index][low - 1] < hash->chksum[index][low]);
assert(low != 0 || hash->chksum[index][0] < hash->chksum[index][1]);
}
hash->depth[index]++;
if (rhash->inserts + 1 == (rhash->hr_size * hash->max_depth))
return SUCCESSFULL_HASH_INSERT_NOW_IS_FULL;
return SUCCESSFULL_HASH_INSERT;
}
}
return FAILED_HASH_INSERT;
}
signed int
RHash_insert_block(RefHash *rhash, cfile *ref_cfh, off_u64 ref_start, off_u64 ref_end)
{
return internal_loop_block(rhash, ref_cfh, ref_start, ref_end, rhash->hash_insert);
}
signed int
RHash_find_matches(RefHash *rhash, cfile *ref_cfh, off_u64 ref_start, off_u64 ref_end)
{
if (rhash->flags & ~RH_IS_REVLOOKUP)
return 0;
return internal_loop_block(rhash, ref_cfh, ref_start, ref_end, rhash->insert_match);
}
static signed int
internal_loop_block(RefHash *rhash, cfile *ref_cfh, off_u64 ref_start, off_u64 ref_end, hash_insert_func hif)
{
ADLER32_SEED_CTX ads;
unsigned long index, skip = 0;
unsigned long len;
signed int result;
cfile_window *cfw;
if (init_adler32_seed(&ads, rhash->seed_len))
return MEM_ERROR;
cseek(ref_cfh, ref_start, CSEEK_FSTART);
cfw = expose_page(ref_cfh);
if (cfw == NULL)
return IO_ERROR;
if (cfw->end == 0)
{
return 0;
}
if (cfw->pos + rhash->seed_len < cfw->end)
{
update_adler32_seed(&ads, cfw->buff + cfw->pos, rhash->seed_len);
cfw->pos += rhash->seed_len;
}
else
{
len = rhash->seed_len;
while (len)
{
skip = MIN(cfw->end - cfw->pos, len);
update_adler32_seed(&ads, cfw->buff + cfw->pos, skip);
len -= skip;
if (len)
cfw = next_page(ref_cfh);
else
cfw->pos += skip;
if (cfw == NULL || cfw->end == 0)
{
return EOF_ERROR;
}
}
}
while (cfw->offset + cfw->pos <= ref_end)
{
if (cfw->pos > cfw->end)
{
cfw = next_page(ref_cfh);
if (cfw == NULL || cfw->end == 0)
{
return MEM_ERROR;
}
}
skip = 0;
len = 1;
result = hif(rhash, &ads, cfw->offset + cfw->pos - rhash->seed_len);
if (result < 0)
{
return result;
}
else if (result == SUCCESSFULL_HASH_INSERT)
{
rhash->inserts++;
if (rhash->sample_rate <= 1)
{
len = 1;
}
else if (rhash->sample_rate > rhash->seed_len)
{
len = rhash->seed_len;
skip = rhash->sample_rate - rhash->seed_len;
}
else if (rhash->sample_rate > 1)
{
len = rhash->sample_rate;
}
}
else if (result == FAILED_HASH_INSERT)
{
rhash->duplicates++;
}
else if (result == SUCCESSFULL_HASH_INSERT_NOW_IS_FULL)
{
rhash->inserts++;
free_adler32_seed(&ads);
return 0;
}
if (cfw->pos + cfw->offset + skip + len > ref_end)
{
break;
}
/* position ourself */
while (cfw->pos + skip >= cfw->end)
{
skip -= (cfw->end - cfw->pos);
cfw = next_page(ref_cfh);
if (cfw == NULL)
{
free_adler32_seed(&ads);
return IO_ERROR;
}
}
cfw->pos += skip;
// loop till we've updated the chksum.
while (len)
{
index = MIN(cfw->end - cfw->pos, len);
update_adler32_seed(&ads, cfw->buff + cfw->pos, index);
cfw->pos += index;
len -= index;
// get next page if we still need more
if (len)
{
cfw = next_page(ref_cfh);
if (cfw == NULL)
{
free_adler32_seed(&ads);
return IO_ERROR;
}
}
}
}
free_adler32_seed(&ads);
return 0;
}
static signed int
rh_rbucket_insert_match(RefHash *rhash, ADLER32_SEED_CTX *ads, off_u64 offset)
{
bucket *hash = (bucket *)rhash->hash;
unsigned long index, chksum;
signed int pos;
chksum = get_checksum(ads);
index = (chksum & RHASH_INDEX_MASK);
if (hash->depth[index])
{
chksum = ((chksum >> 16) & 0xffff);
pos = RH_bucket_find_chksum(chksum, hash->chksum[index], hash->depth[index]);
if (pos >= 0 && hash->offset[index][pos] == 0)
{
hash->offset[index][pos] = offset;
return SUCCESSFULL_HASH_INSERT;
}
}
return FAILED_HASH_INSERT;
}
static signed int
rh_rbucket_cleanse(RefHash *rhash)
{
bucket *hash = (bucket *)rhash->hash;
unsigned long x = 0, y = 0, shift = 0;
rhash->inserts = 0;
for (x = 0; x < rhash->hr_size; x++)
{
if (hash->depth[x] > 0)
{
shift = 0;
for (y = 0; y < hash->depth[x]; y++)
{
assert(y == 0 || hash->chksum[x][y - 1] < hash->chksum[x][y]);
if (hash->offset[x][y] == 0)
{
shift++;
}
else if (shift)
{
hash->offset[x][y - shift] = hash->offset[x][y];
hash->chksum[x][y - shift] = hash->chksum[x][y];
}
}
hash->depth[x] -= shift;
if (hash->depth[x] == 0)
{
assert(NULL != hash->chksum[x]);
assert(NULL != hash->offset[x]);
free(hash->chksum[x]);
free(hash->offset[x]);
hash->chksum[x] = NULL;
hash->offset[x] = NULL;
continue;
}
rhash->inserts += hash->depth[x];
if ((hash->chksum[x] = (unsigned short *)realloc(hash->chksum[x], sizeof(unsigned short) * hash->depth[x])) == NULL ||
(hash->offset[x] = (off_u64 *)realloc(hash->offset[x], sizeof(off_u64) * hash->depth[x])) == NULL)
{
return MEM_ERROR;
}
}
}
rhash->flags |= RH_FINALIZED;
return 0;
}
void print_RefHash_stats(RefHash *rhash)
{
dcb_lprintf(1, "hash stats: inserts(%lu), duplicates(%lu), hash size(%lu)\n",
rhash->inserts, rhash->duplicates, rhash->hr_size);
dcb_lprintf(1, "hash stats: load factor(%f%%)\n",
((float)rhash->inserts / rhash->hr_size * 100));
dcb_lprintf(1, "hash stats: duplicate rate(%f%%)\n",
((float)rhash->duplicates / (rhash->inserts + rhash->duplicates) * 100));
#ifdef DEBUG_HASH
dcb_lprintf(1, "hash stats: bad duplicates(%f%%)\n", ((float)rhash->bad_duplicates / rhash->duplicates * 100));
dcb_lprintf(1, "hash stats: good duplicates(%f%%)\n", 100.0 - ((float)rhash->bad_duplicates / rhash->duplicates * 100));
#endif
dcb_lprintf(1, "hash stats: seed_len(%u), sample_rate(%u)\n", rhash->seed_len,
rhash->sample_rate);
}
| 2.171875 | 2 |
2024-11-18T22:25:49.233844+00:00 | 2015-09-27T07:20:09 | f304ad5c77e418980851b74c656cf0f745dabaa5 | {
"blob_id": "f304ad5c77e418980851b74c656cf0f745dabaa5",
"branch_name": "refs/heads/master",
"committer_date": "2015-09-27T07:20:09",
"content_id": "24403b8d8bef55159a2adbabbed066ebc70f5310",
"detected_licenses": [
"MIT"
],
"directory_id": "862095e2a2af978eee66f5adf41c887370a9c1a6",
"extension": "c",
"filename": "bookkeeper.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 26941459,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 9927,
"license": "MIT",
"license_type": "permissive",
"path": "/bookkeeper.c",
"provenance": "stackv2-0115.json.gz:142888",
"repo_name": "hashbang-legacy/bookkeeper",
"revision_date": "2015-09-27T07:20:09",
"revision_id": "0dfb9aa8723e741d1ee2be5d0cc267b8baff8dc3",
"snapshot_id": "e1483b0f4f38ccfb2e1a80e972bf86b0f015fd83",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/hashbang-legacy/bookkeeper/0dfb9aa8723e741d1ee2be5d0cc267b8baff8dc3/bookkeeper.c",
"visit_date": "2021-01-15T14:02:23.601773"
} | stackv2 | #define _POSIX_C_SOURCE 200809L
#define _XOPEN_SOURCE 700
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <unistd.h>
#include <string.h>
#include <errno.h>
#include <err.h>
#include <signal.h>
#include <syslog.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/time.h>
#include <sys/resource.h>
#include <sys/inotify.h>
#include <sys/signalfd.h>
#include <sys/timerfd.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <sys/uio.h>
#include <sys/epoll.h>
#include <getopt.h>
#include <pwd.h>
#include "config.h"
#include "users.h"
#include "event.h"
#include "protocol.h"
struct config config;
int sockfd = -1;
int inotifyfd = -1;
int sigfd = -1;
int timefd = -1;
int wds[2];
static void print_help(
void)
{
printf("Usage: bookkeeper [OPTION]\n\n"
"Options:\n"
" -h --help Prints this help\n"
" -s --sys-uid-threshold INTEGER This UID and the ones below it will never be considered for\n"
" port reservation\n"
" -p --port-offset INTEGER Adds this number to the users UID as the relevent port offset\n"
" default: 10000\n"
" -u --user STRING User and group to transiton to\n"
" -f --sockpath STRING Path of the socket file to create for client communication.\n"
" default: %s"
"\n\n",
DEFAULT_SOCKPATH);
}
static void parse_config(
const int argc,
char **argv)
{
int c;
struct passwd *p;
static struct option long_options[] = {
{ "help", no_argument, 0, 'h'},
{ "port-offset", required_argument, 0, 'p' },
{ "sys-uid-threshold", required_argument, 0, 's' },
{ "user", required_argument, 0, 'u' },
{ 0, 0, 0, 0 }
};
while (1) {
int opt_idx = 0;
c = getopt_long(argc, argv, "hs:p:u:", long_options, &opt_idx);
if (c == -1)
break;
switch (c) {
case 's':
config.system_user_threshold = atoi(optarg);
if (config.system_user_threshold <= 0)
errx(EXIT_FAILURE, "The sys_uid_threshold must a number be 1 or greater");
break;
case 'f':
/* Dont check the path until later, just check its absolute */
config.sockfile = strdup(optarg);
if (config.sockfile)
err(EXIT_FAILURE, "Cannot setup sockpath");
if (config.sockfile[0] != '/')
err(EXIT_FAILURE, "The socket path must be an absolute path");
break;
case 'h':
print_help();
exit(0);
break;
case 'p':
config.port_offset = atoi(optarg);
if (config.port_offset < PRIVPORTS)
errx(EXIT_FAILURE, "Port offset must be an integer with an offset of at least %d", PRIVPORTS);
break;
case 'u':
config.user = strdup(optarg);
if (!config.user)
err(EXIT_FAILURE, "Cannot assign username");
p = getpwnam(config.user);
if (!p)
errx(EXIT_FAILURE, "Unable to switch to a non-existant user");
config.uid = p->pw_uid;
config.gid = p->pw_gid;
break;
default:
fprintf(stderr, "An unknown option was passed");
print_help();
exit(EXIT_FAILURE);
break;
}
}
if (config.system_user_threshold == 0)
config.system_user_threshold = 1000;
if (config.port_offset == 0)
config.port_offset = 10000;
if (config.user == NULL)
errx(EXIT_FAILURE, "You must supply a username to transition to");
if (config.sockfile == NULL) {
config.sockfile = strdup(DEFAULT_SOCKPATH);
if (!config.sockfile)
err(EXIT_FAILURE, "Cannot setup initial configuration");
}
}
static void set_resource_limits(
void)
{
struct rlimit lim;
lim.rlim_cur = 70000;
lim.rlim_max = 70000;
if (setrlimit(RLIMIT_NOFILE, &lim) < 0)
err(EXIT_FAILURE, "Cannot set file handle limit");
}
static void switch_users(
void)
{
if (setregid(config.gid, config.gid) < 0)
err(EXIT_FAILURE, "Cannot switch users");
if (setreuid(config.uid, config.uid) < 0)
err(EXIT_FAILURE, "Cannot switch users");
}
static void inotify_setup(
void)
{
inotifyfd = -1;
if ((inotifyfd = inotify_init()) < 0)
err(EXIT_FAILURE, "Cannot start inotify");
/* We actually watch etc too because of renames overwriting the original file */
if ((wds[0] = inotify_add_watch(inotifyfd, "/etc", IN_MOVED_TO)) < 0)
err(EXIT_FAILURE, "Cannot add watch of /etc/passwd to inotify");
/* If someone edits passwd directly, we know from here */
if ((wds[1] = inotify_add_watch(inotifyfd, "/etc/passwd", IN_MODIFY)) < 0)
err(EXIT_FAILURE, "Cannot add watch of /etc/passwd to inotify");
}
static int inotify_read(
int fd,
int event,
void *data)
{
int rc;
char buf[2048];
char *p;
struct inotify_event *in;
if ((event & EPOLLERR) == EPOLLERR || (event & EPOLLHUP) == EPOLLHUP)
return -1;
rc = read(fd, buf, sizeof(buf));
if (rc < 0)
return -1;
p = buf;
while (p < (buf+rc)) {
in = (struct inotify_event *)p;
/* The directory being watched */
if (in->wd == wds[0]) {
if (strcmp(in->name, "passwd") != 0)
goto next;
if ((in->mask & IN_MOVED_TO) == IN_MOVED_TO)
users_sync();
}
/* Is /etc/passwd */
else if (in->wd == wds[1]) {
/* The file was edited by hand */
if ((in->mask & IN_MODIFY) == IN_MODIFY)
users_sync();
if ((in->mask & IN_IGNORED) == IN_IGNORED) {
/* In this case, we must re-add the watch */
if ((wds[1] = inotify_add_watch(fd, "/etc/passwd", IN_MODIFY)) < 0)
err(EXIT_FAILURE, "Unable to re-add watch for /etc/passwd!");
}
}
else {
syslog(LOG_WARNING, "Unknown watch descriptor was passed to us: %s", strerror(errno));
}
next:
p += sizeof(struct inotify_event) + in->len;
}
return 0;
}
static void signal_setup(
void)
{
sigset_t sigs;
/* Assume this all just works */
sigemptyset(&sigs);
sigaddset(&sigs, SIGHUP);
sigaddset(&sigs, SIGINT);
sigaddset(&sigs, SIGTERM);
if (sigprocmask(SIG_BLOCK, &sigs, NULL) < 0)
err(EXIT_FAILURE, "Cannot setup signalfd");
if ((sigfd = signalfd(-1, &sigs, 0)) < 0)
err(EXIT_FAILURE, "Cannot setup signalfd");
}
static int signal_read(
int fd,
int event,
void *data)
{
int rc;
struct signalfd_siginfo info;
if ((event & EPOLLERR) == EPOLLERR || (event & EPOLLHUP) == EPOLLHUP)
return -1;
rc = read(fd, &info, sizeof(info));
if (rc != sizeof(info))
return -1;
switch (info.ssi_signo) {
case SIGHUP:
syslog(LOG_WARNING, "Got HUP, re-reading passwd file");
users_sync();
break;
case SIGTERM:
case SIGINT:
exit(0);
break;
}
return 0;
}
static void sockfile_setup(
void)
{
struct sockaddr_un un;
int rc = 1;
memset(&un, 0, sizeof(un));
if (access(config.sockfile, R_OK|W_OK) < 0) {
if (errno != ENOENT)
err(EXIT_FAILURE, "Cannot access sockfile");
}
un.sun_family = AF_UNIX;
strncpy(un.sun_path, config.sockfile, strlen(config.sockfile));
sockfd = socket(AF_UNIX, SOCK_STREAM, 0);
if (sockfd < 0)
err(EXIT_FAILURE, "Could not acquire unix socket");
if (setsockopt(sockfd, SOL_SOCKET, SO_PASSCRED, &rc, sizeof(rc)) < 0)
err(EXIT_FAILURE, "Could not set socket options\n");
/* May not work as file doesn't exist. Dont care about this */
if (unlink(config.sockfile) < 0)
if (errno != ENOENT)
err(EXIT_FAILURE, "Could not remove old socket");
if (bind(sockfd, (struct sockaddr *)&un, sizeof(struct sockaddr_un)) < 0)
err(EXIT_FAILURE, "Could not bind to socket");
if (chmod(config.sockfile, 0777) < 0)
err(EXIT_FAILURE, "Cannot set mode on socket");
if (listen(sockfd, 5) < 0)
err(EXIT_FAILURE, "Cannot listen on socket");
}
static int sockfile_read(
int fd,
int event,
void *data)
{
int clifd = -1;
if ((event & EPOLLERR) == EPOLLERR || (event & EPOLLHUP) == EPOLLHUP)
return -1;
clifd = accept(sockfd, NULL, NULL);
if (clifd < 0)
return 0;
event_add_fd(clifd, decode_packet, NULL, NULL, EPOLLIN);
return 0;
}
static void timer_setup(
void)
{
timefd = timerfd_create(CLOCK_MONOTONIC, 0);
struct itimerspec ts;
ts.it_interval.tv_sec = 60;
ts.it_interval.tv_nsec = 0;
ts.it_value.tv_sec = 60;
ts.it_value.tv_nsec = 0;
if (timefd < 0)
err(EXIT_FAILURE, "Failed to setup timerfd");
if (timerfd_settime(timefd, 0, &ts, NULL) < 0)
err(EXIT_FAILURE, "Failed to setup timerfd");
}
static int timer_read(
int fd,
int event,
void *data)
{
uint64_t triggered;
int rc;
if ((event & EPOLLERR) == EPOLLERR || (event & EPOLLHUP) == EPOLLHUP)
return -1;
rc = read(fd, &triggered, sizeof(triggered));
if (rc != sizeof(triggered))
err(EXIT_FAILURE, "Error reading from timerfd");
/* When the timer is triggered, we read all our reserved ports for released entries */
users_reacquire_ports();
return 0;
}
static void setup_events(
void)
{
if (event_add_fd(timefd, timer_read, NULL, NULL, EPOLLIN) < 0)
err(EXIT_FAILURE, "Cannot add timer event");
if (event_add_fd(sigfd, signal_read, NULL, NULL, EPOLLIN) < 0)
err(EXIT_FAILURE, "Cannot add signal event");
if (event_add_fd(inotifyfd, inotify_read, NULL, NULL, EPOLLIN) < 0)
err(EXIT_FAILURE, "Cannot add inotify event");
if (event_add_fd(sockfd, sockfile_read, NULL, NULL, EPOLLIN) < 0)
err(EXIT_FAILURE, "Cannot add inotify event");
}
int main(
const int argc,
const char **argv)
{
openlog(NULL, LOG_PID, LOG_DAEMON);
chdir("/");
parse_config(argc, (char **)argv);
set_resource_limits();
switch_users();
inotify_setup();
signal_setup();
sockfile_setup();
timer_setup();
users_init();
event_init();
setup_events();
users_sync();
while(1) {
event_loop(128, -1);
}
exit(0);
}
| 2.15625 | 2 |
2024-11-18T22:25:49.433573+00:00 | 2016-10-24T22:58:16 | 1266d0291fab079bfe073e66dafd05f639ad23a4 | {
"blob_id": "1266d0291fab079bfe073e66dafd05f639ad23a4",
"branch_name": "refs/heads/master",
"committer_date": "2016-10-24T22:58:16",
"content_id": "537e84d625bf7dbad3c981690f6c7d54c4878190",
"detected_licenses": [
"MIT"
],
"directory_id": "fb79f501c7587e56c851a4a00af78c1ce3e61d2c",
"extension": "c",
"filename": "UI.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 70123839,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 16883,
"license": "MIT",
"license_type": "permissive",
"path": "/UI.c",
"provenance": "stackv2-0115.json.gz:143148",
"repo_name": "ealn/Hash_Table",
"revision_date": "2016-10-24T22:58:16",
"revision_id": "b1a28913855a9b1a38aed9a7f7dadafe0159902a",
"snapshot_id": "41e977d8ce1f4abad1c68c645f48f5657e1a02a6",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/ealn/Hash_Table/b1a28913855a9b1a38aed9a7f7dadafe0159902a/UI.c",
"visit_date": "2020-05-29T09:14:49.594516"
} | stackv2 | /*
* Copyright (c) 2016 by Adrian Luna
* All Rights Reserved
*
* Author: - Adrian Luna
*
* Porpuse: Implementation of User interface
*/
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include "UI.h"
#include "hash_table.h"
#include "trace.h"
#include "memutils.h"
#include "console_utils.h"
#include "resources.h"
//Constanst
#define INSERT_REG 1
#define SEARCH_REG 2
#define REMOVE_REG 3
#define CHANGE_REG 4
#define SHOW_TABLE 5
#define EXIT 6
#define SHOW_FULL_TABLE 1
#define SHOW_SUMMARY_TABLE 2
#define SEND_TO_CONSOLE 1
#define SEND_TO_FILE 2
#define OUTPUT_FILE_SIZE 20
#define REG_BUF_SIZE 512
#define CHANGE_FIRST_NAME 1
#define CHANGE_LAST_NAME 2
#define CHANGE_ADDRESS 3
#define CHANGE_CITY 4
#define CHANGE_TEL1 5
#define CHANGE_TEL2 6
#define CHANGE_ALL 7
//Definition of static functions
static int32_t showMainMenu(uint8_t *optionSelected);
static void getRegInfo(uint32_t * pID,
char * pFirstName,
char * pLastName,
char * pAddress,
char * pCity,
char * pTel1,
char * pTel2);
static int32_t showInsertRegMenu(void);
static int32_t showSearchRegMenu(void);
static int32_t showRemoveRegMenu(void);
static int32_t showChangeRegMenu(void);
static int32_t showTableView(void);
static int32_t printInfoInTableView(const char *str);
//Type definitions
typedef struct _TableView
{
uint32_t view;
uint32_t output;
char outputFile[OUTPUT_FILE_SIZE];
}TableView;
//global variables
TableView * g_tableView = NULL;
static void setDefaultValuesOfTableView()
{
if (g_tableView != NULL)
{
g_tableView->view = SHOW_FULL_TABLE;
g_tableView->output = SEND_TO_CONSOLE;
}
}
static void createTableView(void)
{
if (g_tableView == NULL)
{
g_tableView = (TableView *)MEMALLOC(sizeof(TableView));
if (g_tableView != NULL)
{
setDefaultValuesOfTableView();
}
else
{
UI_ERROR("Table view could not be allocated\n");
}
}
}
static void destroyTableView(void)
{
if (g_tableView != NULL)
{
MEMFREE((void *)g_tableView);
g_tableView = NULL;
}
else
{
UI_WARNING("Table view is null\n");
}
}
int32_t showUI(void)
{
int32_t ret = SUCCESS;
uint8_t optionSelected = 0;
bool repeat = false;
createTableView();
do
{
repeat = false;
ret = showMainMenu(&optionSelected);
UI_DEBUG("optionSelected=%i\n", optionSelected);
switch (optionSelected)
{
case INSERT_REG: ret = showInsertRegMenu();
break;
case SEARCH_REG: ret = showSearchRegMenu();
break;
case REMOVE_REG: ret = showRemoveRegMenu();
break;
case CHANGE_REG: ret = showChangeRegMenu();
break;
case SHOW_TABLE: ret = showTableView();
break;
default: break;
}
if (optionSelected != EXIT)
{
//waiting for a key input
getchar();
repeat = true;
}
}while (repeat);
destroyTableView();
return ret;
}
static int32_t showMainMenu(uint8_t *optionSelected)
{
int32_t ret = SUCCESS;
bool isValidOption = true;
if (optionSelected != NULL)
{
*optionSelected = createMenuWithMultipleOptions(STR_HASH_TAB_TITLE,
STR_SELECT_OPTION,
STR_MAIN_MENU_OPTIONS,
STR_OPTION_SELECTED,
true,
INSERT_REG,
EXIT,
true);
UI_DEBUG("optionSelected=%i\n", *optionSelected);
}
else
{
UI_ERROR("optionSelected is null");
ret = FAIL;
}
return ret;
}
static void printOutput(int32_t ret, uint32_t numberOfSteps)
{
switch (ret)
{
case SUCCESS: printf(STR_SUCCESS);
break;
case FAIL: printf(STR_FAIL);
break;
case REG_NOT_FOUND: printf(STR_REGISTER_NOT_FOUND);
break;
case REG_DUPLICATED: printf(STR_REGISTER_DUPLICATED);
break;
default:
break;
}
printf(STR_NUMBER_OF_STEPS, numberOfSteps);
}
static void getRegInfo(uint32_t * pID,
char * pFirstName,
char * pLastName,
char * pAddress,
char * pCity,
char * pTel1,
char * pTel2)
{
if (pID != NULL)
{
*pID = getUInt32FromConsole(STR_ID);
}
if (pFirstName != NULL)
{
getStringFromConsole(STR_FIRST_NAME, pFirstName, (FIRST_NAME_SIZE - 1));
}
if (pLastName != NULL)
{
getStringFromConsole(STR_LAST_NAME, pLastName, (LAST_NAME_SIZE - 1));
}
if (pAddress != NULL)
{
getStringFromConsole(STR_ADDRESS, pAddress, (ADD_SIZE - 1));
}
if (pCity != NULL)
{
getStringFromConsole(STR_CITY, pCity, (CITY_SIZE - 1));
}
if (pTel1 != NULL)
{
getStringFromConsole(STR_TEL_1, pTel1, (TEL_SIZE - 1));
}
if (pTel2 != NULL)
{
getStringFromConsole(STR_TEL_2, pTel2, (TEL_SIZE - 1));
}
}
static int32_t showInsertRegMenu(void)
{
int32_t ret = SUCCESS;
uint32_t ID = 0;
uint32_t numberOfSteps = 0;
char first_name[FIRST_NAME_SIZE];
char last_name[LAST_NAME_SIZE];
char address[ADD_SIZE];
char city[CITY_SIZE];
char tel1[TEL_SIZE];
char tel2[TEL_SIZE];
memset(&first_name, 0, sizeof(char)*FIRST_NAME_SIZE);
memset(&last_name, 0, sizeof(char)*LAST_NAME_SIZE);
memset(&address, 0, sizeof(char)*ADD_SIZE);
memset(&city, 0, sizeof(char)*CITY_SIZE);
memset(&tel1, 0, sizeof(char)*TEL_SIZE);
memset(&tel2, 0, sizeof(char)*TEL_SIZE);
cleanScreen();
printf(STR_REG_INFO);
printf(STR_INSERT_REG);
getRegInfo(&ID, first_name, last_name, address, city, tel1, tel2);
UI_DEBUG(" Insert register:\nID: %d \nfirst name: %s\nlast name: %s\naddress: %s\ncity: %s\ntel 1: %s\ntel 2: %s\n",
ID,
first_name,
last_name,
address,
city,
tel1,
tel2);
ret = insertReg(ID, first_name, last_name, address, city, tel1, tel2, &numberOfSteps);
printOutput(ret, numberOfSteps);
return ret;
}
static int32_t showSearchRegMenu(void)
{
int32_t ret = SUCCESS;
uint32_t ID = 0;
uint32_t numberOfSteps = 0;
cleanScreen();
printf(STR_REG_INFO);
printf(STR_SEARCH_REG);
getRegInfo(&ID, NULL, NULL, NULL, NULL, NULL, NULL);
UI_DEBUG("ID=%d\n", ID);
ret = searchReg(ID, &numberOfSteps);
printOutput(ret, numberOfSteps);
return ret;
}
static int32_t showRemoveRegMenu(void)
{
int32_t ret = SUCCESS;
uint32_t ID = 0;
uint32_t numberOfSteps = 0;
cleanScreen();
printf(STR_REG_INFO);
printf(STR_REMOVE_REG);
getRegInfo(&ID, NULL, NULL, NULL, NULL, NULL, NULL);
UI_DEBUG("ID=%d\n", ID);
ret = removeReg(ID, &numberOfSteps);
printOutput(ret, numberOfSteps);
return ret;
}
static int32_t showChangeRegMenu(void)
{
int32_t ret = SUCCESS;
uint32_t ID = 0;
uint32_t numberOfSteps = 0;
cleanScreen();
printf(STR_REG_INFO);
printf(STR_CHANGE_REG);
getRegInfo(&ID, NULL, NULL, NULL, NULL, NULL, NULL);
UI_DEBUG("ID=%d\n", ID);
ret = changeReg(ID, &numberOfSteps);
printOutput(ret, numberOfSteps);
return ret;
}
static int32_t showTableView(void)
{
int32_t ret = SUCCESS;
uint32_t optionSelected = 0;
bool isValidOption = true;
if (g_tableView != NULL)
{
optionSelected = createMenuWithMultipleOptions(STR_SHOW_TAB_TITLE,
STR_SHOW_TAB_OUTPUT_HEADER,
STR_SHOW_TAB_OUTPUT_OPTIONS,
STR_OPTION_SELECTED,
true,
SEND_TO_CONSOLE,
SEND_TO_FILE,
true);
g_tableView->output = optionSelected;
UI_DEBUG("Table output option = %d\n", g_tableView->output);
if (g_tableView->output == SEND_TO_FILE)
{
getStringFromConsole(STR_OUTPUT_FILE,
g_tableView->outputFile,
(OUTPUT_FILE_SIZE - 1));
}
optionSelected = createMenuWithMultipleOptions(STR_SHOW_TAB_TITLE,
STR_SHOW_TAB_VIEW_HEADER,
STR_SHOW_TAB_VIEW_OPTIONS,
STR_OPTION_SELECTED,
true,
SHOW_FULL_TABLE,
SHOW_SUMMARY_TABLE,
true);
g_tableView->view = optionSelected;
UI_DEBUG("Table view option = %d\n", g_tableView->output);
if (g_tableView->output == SEND_TO_CONSOLE)
{
cleanScreen();
}
if (g_tableView->view == SHOW_SUMMARY_TABLE)
{
ret = printInfoInTableView(STR_SUMMARY_FORMAT_HEADER);
}
if (ret == SUCCESS)
{
ret = displayTable();
setDefaultValuesOfTableView();
}
}
else
{
UI_ERROR("Table view is null\n");
ret = FAIL;
}
return ret;
}
static int32_t printInfoInTableView(const char *str)
{
int32_t ret = SUCCESS;
FILE *pFile = NULL;
if (g_tableView != NULL
&& str != NULL)
{
UI_DEBUG("g_tableView->output = %d g_tableView->outputFile = %s\n",
g_tableView->output,
g_tableView->outputFile);
if (g_tableView->output == SEND_TO_CONSOLE)
{
printf(str);
}
else if (g_tableView->output == SEND_TO_FILE)
{
pFile = fopen(g_tableView->outputFile, "a");
if (pFile != NULL)
{
fprintf(pFile,str);
fflush(pFile);
fclose(pFile);
}
else
{
UI_ERROR("Output file %s could not be openned rc = %08lx\n",
g_tableView->outputFile,
pFile);
ret = FAIL;
}
}
else
{
UI_ERROR("Table view output invalid\n");
ret = FAIL;
}
}
else
{
UI_ERROR("Table view is null or string is null\n");
ret = FAIL;
}
return ret;
}
int32_t showRegInfo(uint32_t hashValue,
uint32_t treeLevel,
uint32_t ID,
uint32_t parentID,
uint32_t side,
char * pFirstName,
char * pLastName,
char * pAddress,
char * pCity,
char * pTel1,
char * pTel2)
{
int32_t ret = SUCCESS;
char regBuf[REG_BUF_SIZE];
if (pFirstName != NULL
&& pLastName != NULL
&& pAddress != NULL
&& pCity != NULL
&& pTel1 != NULL
&& pTel2 != NULL)
{
memset(regBuf, 0, sizeof(char)*REG_BUF_SIZE);
if (g_tableView != NULL)
{
UI_DEBUG("g_tableView->view = %d\n", g_tableView->view);
if (g_tableView->view == SHOW_FULL_TABLE)
{
sprintf(regBuf,
STR_OUTPUT_FULL_FORMAT,
hashValue,
ID,
treeLevel,
parentID,
(side > 0)?((side == 1)? STR_LEFT: STR_RIGHT): "",
pFirstName,
pLastName,
pAddress,
pCity,
pTel1,
pTel2);
}
else if (g_tableView->view == SHOW_SUMMARY_TABLE)
{
sprintf(regBuf,
STR_OUTPUT_SUMMARY_FORMAT,
hashValue,
ID,
treeLevel,
parentID,
(side > 0)?((side == 1)? STR_LEFT: STR_RIGHT): "",
pFirstName,
pLastName);
}
printInfoInTableView(regBuf);
}
else
{
UI_ERROR("Table view is null\n");
ret = FAIL;
}
}
else
{
UI_ERROR("At least one parameter is null\n");
ret = FAIL;
}
return ret;
}
int32_t changeFieldsOfReg(char * pFirstName,
char * pLastName,
char * pAddress,
char * pCity,
char * pTel1,
char * pTel2)
{
int32_t ret = SUCCESS;
uint8_t optionSelected = 0;
bool isValidOption = true;
bool repeat = false;
if (pFirstName != NULL
&& pLastName != NULL
&& pAddress != NULL
&& pCity != NULL
&& pTel1 != NULL
&& pTel2 != NULL)
{
UI_DEBUG("Original fields: first name:%s last name:%s address:%s city:%s tel #1:%s tel #2:%s",
pFirstName,
pLastName,
pAddress,
pCity,
pTel1,
pTel2);
do
{
repeat = false;
optionSelected = createMenuWithMultipleOptions(NULL,
STR_CHANGE_REG_HEADER,
STR_CHANGE_REG_OPTIONS,
STR_OPTION_SELECTED,
true,
CHANGE_FIRST_NAME,
CHANGE_ALL,
false);
UI_DEBUG("optionSelected=%i\n", optionSelected);
printf(STR_INSERT_NEW_VALUE);
switch (optionSelected)
{
case CHANGE_FIRST_NAME: getRegInfo(NULL, pFirstName, NULL, NULL, NULL, NULL, NULL);
break;
case CHANGE_LAST_NAME: getRegInfo(NULL, NULL, pLastName, NULL, NULL, NULL, NULL);
break;
case CHANGE_ADDRESS: getRegInfo(NULL, NULL, NULL, pAddress, NULL, NULL, NULL);
break;
case CHANGE_CITY: getRegInfo(NULL, NULL, NULL, NULL, pCity, NULL, NULL);
break;
case CHANGE_TEL1: getRegInfo(NULL, NULL, NULL, NULL, NULL, pTel1, NULL);
break;
case CHANGE_TEL2: getRegInfo(NULL, NULL, NULL, NULL, NULL, NULL, pTel2);
break;
case CHANGE_ALL: getRegInfo(NULL, pFirstName, pLastName, pAddress, pCity, pTel1, pTel2);
break;
default: break;
}
repeat = getYesOrNotFromConsole(STR_REPEAT_CHANGE_REG);
}
while (repeat);
UI_DEBUG("New fields: first name:%s last name:%s address:%s city:%s tel #1:%s tel #2:%s",
pFirstName,
pLastName,
pAddress,
pCity,
pTel1,
pTel2);
}
else
{
UI_ERROR("At least one parameter is null\n");
ret = FAIL;
}
return ret;
}
| 2.5 | 2 |
2024-11-18T22:25:51.009829+00:00 | 2014-11-20T23:31:26 | f96ac7adb13b0043e0d8196996f3dedbcf1dba4e | {
"blob_id": "f96ac7adb13b0043e0d8196996f3dedbcf1dba4e",
"branch_name": "refs/heads/master",
"committer_date": "2014-11-20T23:31:26",
"content_id": "4895444af8f4dea22966c925f30fa428d36559f2",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "dd8c4eb28509b81d19ef134807f2a03c15d55619",
"extension": "c",
"filename": "ybuffer.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": null,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 4540,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/src/core/ybuffer.c",
"provenance": "stackv2-0115.json.gz:143279",
"repo_name": "cwnga/ygloo-yosal",
"revision_date": "2014-11-20T23:31:26",
"revision_id": "7f9dd1c6fdd8451b5d703bd3d64e9f3b2f3e4d92",
"snapshot_id": "7ee06f879e5214f15011dadeb2babf9cefdc8ac9",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/cwnga/ygloo-yosal/7f9dd1c6fdd8451b5d703bd3d64e9f3b2f3e4d92/src/core/ybuffer.c",
"visit_date": "2021-01-24T15:43:48.740916"
} | stackv2 | /**
* Copyright 2013 Yahoo! Inc.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. You may
* obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License. See accompanying LICENSE file.
*/
/*
* A dynamically allocated memory buffer
*/
#include <stdlib.h>
#include <string.h>
#include <stdarg.h>
#include "yosal/yosal.h"
enum {
YBUFFER_STATUS_OK = 0,
YBUFFER_STATUS_CLOSED,
YBUFFER_STATUS_ERROR
};
struct YbufferStruct
{
char *data;
int datalen;
int dataincr;
int pos;
int status;
};
Ybuffer*
Ybuffer_init(int initiallength)
{
char *data;
Ybuffer *membuf;
membuf = (Ybuffer*) Ymem_malloc(sizeof(Ybuffer));
if (membuf == NULL) {
return NULL;
}
if (initiallength <= 0) {
membuf->data = NULL;
membuf->datalen = 0;
membuf->dataincr = 64;
} else {
data = (char*) Ymem_malloc(initiallength);
if (data == NULL) {
Ymem_free(membuf);
return NULL;
}
membuf->data = data;
membuf->datalen = initiallength;
membuf->dataincr = initiallength;
}
membuf->pos = 0;
membuf->status = YBUFFER_STATUS_OK;
return membuf;
}
char*
Ybuffer_detach(Ybuffer *stream, int *datalen)
{
char *data;
if (stream == NULL) {
data = NULL;
if (datalen != NULL) {
*datalen = 0;
}
} else {
data = stream->data;
if (datalen != NULL) {
*datalen = stream->pos;
}
Ymem_free(stream);
}
return data;
}
void
Ybuffer_fini(Ybuffer *stream)
{
char *data;
data = Ybuffer_detach(stream, NULL);
if (data != NULL) {
Ymem_free(data);
}
}
int
Ybuffer_append(Ybuffer *stream, const char *buf, int buflen)
{
if (stream == NULL) {
return -1;
}
if (stream->status != YBUFFER_STATUS_OK) {
return -1;
}
if (buf == NULL || buflen == 0) {
return 0;
}
if (buflen < 0) {
buflen = strlen(buf);
}
if (stream->pos + buflen >= stream->datalen - 1) {
/* Re-allocate larger buffer */
char *newbuf;
int newlen;
newlen = stream->datalen + stream->dataincr;
if (stream->pos + buflen >= newlen - 1) {
newlen = stream->pos + buflen + 1;
}
newbuf = (char*) Ymem_realloc(stream->data, newlen);
if (newbuf == NULL) {
/*
* If failed to allocate larger buffer, abort.
* Older buffer is still valid
*/
stream->status = YBUFFER_STATUS_ERROR;
return -1;
}
stream->data = newbuf;
stream->datalen = newlen;
}
memcpy(stream->data + stream->pos, buf, buflen);
stream->pos += buflen;
stream->data[stream->pos] = '\0';
return buflen;
}
int
Ybuffer_append_format(Ybuffer *stream, const char *format, ...)
{
va_list ap1;
va_list ap2;
int rc;
int space;
if (stream == NULL) {
return -1;
}
if (stream->status != YBUFFER_STATUS_OK) {
return -1;
}
va_start(ap1, format);
va_copy(ap2, ap1);
space = stream->datalen - stream->pos;
rc = vsnprintf(stream->data + stream->pos, space, format, ap1);
if (rc >= space) {
/* Re-allocate larger buffer */
char *newbuf;
int newlen;
newlen = stream->datalen + stream->dataincr;
if (stream->pos + rc >= newlen - 1) {
newlen = stream->pos + rc + 1;
}
newbuf = (char*) Ymem_realloc(stream->data, newlen);
if (newbuf == NULL) {
// Older buffer is still valid.
stream->status = YBUFFER_STATUS_ERROR;
rc = -1;
} else {
stream->data = newbuf;
stream->datalen = newlen;
space = stream->datalen - stream->pos;
rc = vsnprintf(stream->data + stream->pos, space, format, ap2);
if (rc >= space) {
// Older buffer is still valid.
stream->status = YBUFFER_STATUS_ERROR;
rc = -1;
}
}
}
va_end(ap2);
va_end(ap1);
if (rc > 0) {
stream->pos += rc;
}
return rc;
}
int
Ybuffer_append_integer(Ybuffer *stream, int value)
{
/* Buffer large enough to contain INT_MAX */
char buf[32];
int buflen;
buflen = snprintf(buf, sizeof(buf), "%d", value);
if (buflen >= sizeof(buf)) {
/* Buffer too short for integer value (should never happen) */
return -1;
}
return Ybuffer_append(stream, buf, buflen);
}
| 2.59375 | 3 |
2024-11-18T22:25:51.255566+00:00 | 2023-08-10T09:04:44 | 56ebc16b6a144e0f5b8ee13d3a442fa16ecc22d9 | {
"blob_id": "56ebc16b6a144e0f5b8ee13d3a442fa16ecc22d9",
"branch_name": "refs/heads/master",
"committer_date": "2023-08-10T09:04:44",
"content_id": "cb2241bb6011ee9fc9ceccd8f9646b496a1de66d",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "c6759b857e55991fea3ef0b465dbcee53fa38714",
"extension": "c",
"filename": "Cifar10Model.c",
"fork_events_count": 96,
"gha_created_at": "2018-05-14T07:50:29",
"gha_event_created_at": "2023-08-27T19:03:52",
"gha_language": "C",
"gha_license_id": "Apache-2.0",
"github_id": 133324605,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2609,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/examples/gap8/nn/autotiler/Cifar10/Cifar10Model.c",
"provenance": "stackv2-0115.json.gz:143537",
"repo_name": "GreenWaves-Technologies/gap_sdk",
"revision_date": "2023-08-10T09:04:44",
"revision_id": "3fea306d52ee33f923f2423c5a75d9eb1c07e904",
"snapshot_id": "1b343bba97b7a5ce62a24162bd72eef5cc67e269",
"src_encoding": "UTF-8",
"star_events_count": 145,
"url": "https://raw.githubusercontent.com/GreenWaves-Technologies/gap_sdk/3fea306d52ee33f923f2423c5a75d9eb1c07e904/examples/gap8/nn/autotiler/Cifar10/Cifar10Model.c",
"visit_date": "2023-09-01T14:38:34.270427"
} | stackv2 | /*
* Copyright (C) 2020 GreenWaves Technologies
* All rights reserved.
*
* This software may be modified and distributed under the terms
* of the BSD license. See the LICENSE file for details.
*
*/
#include <stdint.h>
#include <stdio.h>
#include "AutoTilerLib.h"
#include "CNN_Generators.h"
void Cifar10Model(unsigned int L1Memory, unsigned int L2Memory, unsigned int L3Memory)
{
SetInlineMode(ALWAYS_INLINE);
SetSymbolDynamics();
SetUsedFilesNames(0, 2, "pmsis.h", "CNN_BasicKernels.h");
SetGeneratedFilesNames("Cifar10Kernels.c", "Cifar10Kernels.h");
//SetL1MemorySize(L1Memory);
SetMemoryDeviceInfos(4,
AT_MEM_L1, L1Memory, "Cifar10_L1_Memory", 0, 0,
AT_MEM_L2, L2Memory, "Cifar10_L2_Memory", 0, 0,
AT_MEM_L3_DEFAULTRAM, L3Memory, "Cifar10_L3_Memory", 0, 1,
AT_MEM_L3_DEFAULTFLASH, 20*1024*1024, "0", "Cnn_Flash_Const.dat", 0
);
LoadCNNLibrary();
// 5x5 Convolution followed by 2x2 Max pooling. Pure SW.
// 1 input plane [32x32], 8 output planes [14x14]
CNN_ConvolutionPoolReLU("Conv5x5MaxPool2x2_SW_0", 0, 2, 2, 2, 2,
12,14,14,12, // Q12 for in and out, Q14 for filter and bias
#ifdef COEF_L2
0, 0, 0, 0,
#else
0, 1, 1, 1, // Filter and Bias from L3, output in L3
#endif
1, 8, 32, 32, KOP_CONV, 5, 5,
1, 1, 1, 1, 0, KOP_MAXPOOL, 2, 2,
1, 1, 2, 2, 1, KOP_NONE);
// 5x5 Convolution followed by 2x2 Max pooling. Pure SW.
// 8 input planes [14x14], 12 output planes [5x5]
CNN_ConvolutionPoolReLU("Conv5x5MaxPool2x2_SW_1", 0, 2, 2, 2, 2,
12,14,14,12,
#ifdef COEF_L2
0, 0, 0, 0,
#else
1, 1, 1, 0, // Filter and Bias from L3, input from L3
#endif
8, 12, 14, 14, KOP_CONV, 5, 5,
1, 1, 1, 1, 0, KOP_MAXPOOL, 2, 2,
1, 1, 2, 2, 1, KOP_NONE);
// Linear Layer
// Input 12 x [5x5], Output 10
CNN_LinearReLU("LinearLayerReLU_1", 0, 2, 2, 2, 2,
12,14,10,16,
#ifdef COEF_L2
0, 0, 0, 0,
#else
0, 1, 1, 0, // Filter and Bias from L3
#endif
12*5*5, 10, KOP_LINEAR, KOP_NONE);
}
int main(int argc, char **argv)
{
// Parse AutoTiler options
if (TilerParseOptions(argc, argv))
{
printf("Failed to initialize or incorrect output arguments directory.\n");
return 1;
}
// Set Auto Tiler configuration, given shared L1 memory is 51200
Cifar10Model(50000, 370*1024, 8*1024*1024);
// Generate code
GenerateTilingCode();
return 0;
}
| 2.140625 | 2 |
2024-11-18T22:25:51.677394+00:00 | 2022-08-31T06:40:22 | 8cb2e84d5e12559cd2bf5447a587773cbf883ccc | {
"blob_id": "8cb2e84d5e12559cd2bf5447a587773cbf883ccc",
"branch_name": "refs/heads/master",
"committer_date": "2022-08-31T06:40:22",
"content_id": "7c9c1179b7561e39b94bbc7af6e23acec82e6d6c",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "47ab431ac0664505946f10b2519e151efcd90d8e",
"extension": "c",
"filename": "proget.c",
"fork_events_count": 0,
"gha_created_at": "2020-03-28T01:15:44",
"gha_event_created_at": "2022-08-31T06:40:23",
"gha_language": null,
"gha_license_id": "Apache-2.0",
"github_id": 250686885,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2124,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/antifake/src/main/jni/property/proget.c",
"provenance": "stackv2-0115.json.gz:143926",
"repo_name": "RyanFu/CacheEmulatorChecker",
"revision_date": "2022-08-31T06:40:22",
"revision_id": "a1057401ffdd6effd8efcc6599b45ac5d9c8dec5",
"snapshot_id": "c8bf1948cbfb0d22c289b5bcdb88fb0dae2e3867",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/RyanFu/CacheEmulatorChecker/a1057401ffdd6effd8efcc6599b45ac5d9c8dec5/antifake/src/main/jni/property/proget.c",
"visit_date": "2022-09-12T17:47:47.817323"
} | stackv2 | /* DO NOT EDIT THIS FILE - it is machine generated */
#include <jni.h>
#include <sys/system_properties.h>
#include <android/log.h>
#include <string.h>
#define LOGI(...) __android_log_print(ANDROID_LOG_INFO,"lishang",__VA_ARGS__)
JNIEXPORT jstring JNICALL
proGetSS
(JNIEnv *env, jclass clazz, jstring keyJ, jstring defJ) {
int len;
const char *key;
char buf[100];
jstring rvJ = NULL;
if (keyJ == NULL) {
LOGI("key must not be null.");
goto error;
}
key = (*env)->GetStringUTFChars(env, keyJ, NULL);
len = __system_property_get(key, buf);
if ((len <= 0) && (defJ != NULL)) {
rvJ = defJ;
} else if (len >= 0) {
rvJ = (*env)->NewStringUTF(env, buf);
} else {
rvJ = (*env)->NewStringUTF(env, "");
}
(*env)->ReleaseStringUTFChars(env, keyJ, key);
error:
return rvJ;
}
JNIEXPORT jstring JNICALL
proGet(JNIEnv *env, jclass clazz, jstring keyJ) {
return proGetSS(env, clazz, keyJ, NULL);
}
static int registerNativeMethods(JNIEnv *env, const char *className,
JNINativeMethod *gMethods, int numMethods) {
jclass clazz;
clazz = (*env)->FindClass(env, className);
if (clazz == NULL)
return JNI_FALSE;
if ((*env)->RegisterNatives(env, clazz, gMethods, numMethods) < 0) {
return JNI_FALSE;
}
return JNI_TRUE;
}
static const char *classPathName = "com/snail/antifake/jni/PropertiesGet";
static JNINativeMethod methods[] = {
{"native_get", "(Ljava/lang/String;)Ljava/lang/String;", (void *) proGet},
{"native_get", "(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String;", (void *) proGetSS},
};
jint JNI_OnLoad(JavaVM* vm, void* reserved)
{
JNIEnv* env = NULL;
jint result = -1;
if ((*vm)->GetEnv(vm, (void**) &env, JNI_VERSION_1_4) != JNI_OK)
goto bail;
if (!registerNativeMethods(env, classPathName, methods, sizeof(methods)/sizeof(methods[0])))
goto bail;
result = JNI_VERSION_1_4;
bail:
//LOGI("Leaving JNI_OnLoad (result=0x%x)\n", result);
return result;
}
| 2.109375 | 2 |
2024-11-18T22:25:52.005764+00:00 | 2020-06-23T12:00:06 | 905eae7d53f76328cdd823642873f19b6fc467a7 | {
"blob_id": "905eae7d53f76328cdd823642873f19b6fc467a7",
"branch_name": "refs/heads/master",
"committer_date": "2020-06-23T12:00:06",
"content_id": "0227eda9344cf11f73cff11c08d45b62ba9c2ce6",
"detected_licenses": [
"MIT"
],
"directory_id": "773c3997c32e2ea9ac0991d233e385f03848cf22",
"extension": "h",
"filename": "Pilha.h",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 274387693,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1359,
"license": "MIT",
"license_type": "permissive",
"path": "/arquivo-fonte/Pilha.h",
"provenance": "stackv2-0115.json.gz:144185",
"repo_name": "Cristina-sil/ED1",
"revision_date": "2020-06-23T12:00:06",
"revision_id": "03ca12bde574c9a99e0fe81d8fb7a7aec56fb114",
"snapshot_id": "c2cd177dc79b7848f4a3752d3bd07c6a98fc3dcd",
"src_encoding": "ISO-8859-1",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/Cristina-sil/ED1/03ca12bde574c9a99e0fe81d8fb7a7aec56fb114/arquivo-fonte/Pilha.h",
"visit_date": "2022-11-06T01:17:19.489732"
} | stackv2 | #ifndef PILHA_H_INCLUDED
#define PILHA_H_INCLUDED
typedef struct pilhalivro PilhaLivro;
typedef struct nolivro NoLivro;
PilhaLivro* cria(void);
/* A função cria tem por objetivo criar uma pilha que irá representar uma pilha de livros,
* e em seguida retorna o endereço dessa pilha.
*/
void pushlivro(PilhaLivro *p, char* nome_livro);
/* A função pushlivro tem por objetivo inserir livros em uma pilha, tendo esta
* como paramentro o endereço pra pilha e uma string nome que representa o nome do livro.
*/
char* poplivro(PilhaLivro*p);
/* A função poplivro tem por objetivo desempilhar a pilha de livros. Recebe
* o endereço da pilha. Essa função retorna o nome do livro desempilhado.
*/
void imprime_pilha (PilhaLivro* p);
/* A função imprime_pilha tem como paramêtro o endereço da pilha e tem por finalidade imprimir todos
* os livros existentes na pilha. Caso a pilha de livros esteja vazia será
* exibida uma mensagem correspondente.
*/
int pilha_vazia(PilhaLivro* p);
/* A função pilha_vazia tem como parâmetro o endereço da pilha e desempenha a função de verificar se há algum livro
* na pilha de livros, ou se a mesma se encontra vazia. Retorna 1 caso esteja vazia e 0 caso contrário.
*/
void libera_pilha(PilhaLivro* p);
/* Recebe o endereço de uma pilha e esta será liberada, apagada. */
#endif // PILHA_H_INCLUDED
| 2.46875 | 2 |
2024-11-18T22:25:52.223343+00:00 | 2019-11-18T04:59:20 | aad4fdbe602b82fd7b76f5c2129ba6104cffa1cb | {
"blob_id": "aad4fdbe602b82fd7b76f5c2129ba6104cffa1cb",
"branch_name": "refs/heads/master",
"committer_date": "2019-11-18T04:59:20",
"content_id": "46aa2963d17d3318ceccd485439a34d90bc47a83",
"detected_licenses": [
"MIT"
],
"directory_id": "485f0f748a66d6b14c630823beb8dcfceabb45fd",
"extension": "c",
"filename": "debugger.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": null,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 4542,
"license": "MIT",
"license_type": "permissive",
"path": "/debugger.c",
"provenance": "stackv2-0115.json.gz:144315",
"repo_name": "tearitco/mocimaf",
"revision_date": "2019-11-18T04:59:20",
"revision_id": "b3bc23100e7f87633107c76629549749d1fceb1d",
"snapshot_id": "d8fcfaf2869f9c2fd05fac4d791cdff4a8ebe529",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/tearitco/mocimaf/b3bc23100e7f87633107c76629549749d1fceb1d/debugger.c",
"visit_date": "2022-03-01T02:45:46.282604"
} | stackv2 | #include "debugger.h"
#include "bus_internal.h"
typedef struct debugger_entry {
struct {
uint8_t breakpoint : 1;
uint8_t breakpoint_hit : 1;
};
} debugger_entry_t;
typedef struct debugger {
debugger_entry_t *entries;
bus_ref shared_bus;
struct {
bool enabled;
int dot;
int line;
} scanline_break;
bool scanline_before;
struct {
bool nmi;
bool rst;
bool irq;
} interruption_break;
debugger_step_mode_t step_mode;
} debugger_t;
void debugger_destroy(debugger_ref self)
{
if (self) {
FREE(self->entries);
FREE(self);
}
}
debugger_ref debugger_create(bus_ref bus)
{
debugger_ref self = NULL;
TALLOC(self);
GUARD(self->shared_bus = bus);
TALLOCS(self->entries, bus_prg_size(self->shared_bus));
return self;
error:
debugger_destroy(self);
return NULL;
}
debugger_step_mode_t debugger_get_step_mode(debugger_ref self)
{
return self->step_mode;
}
void debugger_set_step_mode(debugger_ref self, debugger_step_mode_t step_mode)
{
self->step_mode = step_mode;
}
void debugger_breakpoint_unhit(debugger_ref self, uint16_t virt)
{
uint32_t phys = bus_prg_phys(self->shared_bus, virt);
self->entries[phys].breakpoint_hit = 0;
}
bool debugger_check_breakpoint_hit(debugger_ref self, uint16_t virt)
{
uint32_t phys = bus_prg_phys(self->shared_bus, virt);
debugger_entry_t *entry = &self->entries[phys];
if (entry->breakpoint) {
if (entry->breakpoint_hit) {
entry->breakpoint_hit = 0;
TRACE("got through breakpoint %04x@%05x\n", virt, phys);
} else {
TRACE("hit breakpoint %04x@%05x\n", virt, phys);
entry->breakpoint_hit = 1;
// debugger_event_emit_breakpoint(self->shared_emitter, self);
return true;
}
}
return false;
}
bool debugger_is_breakpoint(debugger_ref self, uint32_t phys)
{
return self->entries[phys % bus_prg_size(self->shared_bus)].breakpoint;
}
bool debugger_breakpoint_toggle(debugger_ref self, uint32_t phys)
{
debugger_entry_t *entry =
&self->entries[phys % bus_prg_size(self->shared_bus)];
entry->breakpoint = !entry->breakpoint;
return entry->breakpoint;
}
bool debugger_interruption_breakpoint_toggle(debugger_ref self,
interruption_type_t type)
{
bool ret = false;
switch (type) {
case INTERRUTPION_TYPE_NMI:
ret = negate(&self->interruption_break.nmi);
break;
case INTERRUTPION_TYPE_RST:
ret = negate(&self->interruption_break.rst);
break;
case INTERRUTPION_TYPE_IRQ:
ret = negate(&self->interruption_break.irq);
break;
default:
WARN("undefined interruption type: %d\n", type);
}
return ret;
}
bool debugger_check_interruption_break(debugger_ref self,
interruption_type_t type)
{
bool ret = false;
switch (type) {
case INTERRUTPION_TYPE_NMI:
ret = self->interruption_break.nmi;
break;
case INTERRUTPION_TYPE_RST:
ret = self->interruption_break.rst;
break;
case INTERRUTPION_TYPE_IRQ:
ret = self->interruption_break.irq;
break;
default:
WARN("undefined interruption type: %d\n", type);
}
// if (ret) {
// debugger_event_emit_interruption_break(self->shared_emitter, self);
//}
return ret;
}
int debugger_set_scanline_break(debugger_ref self, int line, int dot)
{
self->scanline_break.enabled = true;
self->scanline_break.line = line;
self->scanline_break.dot = dot;
return SUCCESS;
}
void debugger_reset_scanline_break(debugger_ref self)
{
self->scanline_break.enabled = false;
self->scanline_break.line = 0;
self->scanline_break.dot = 0;
}
bool debugger_check_scanline_before(debugger_ref self, int x, int y)
{
self->scanline_before = self->scanline_break.enabled &&
(y <= self->scanline_break.line) &&
(x <= self->scanline_break.dot);
return self->scanline_before;
}
bool debugger_check_scanline_after(debugger_ref self, int x, int y)
{
bool hit = self->scanline_before && self->scanline_break.enabled &&
(y >= self->scanline_break.line) &&
(x >= self->scanline_break.dot);
// if (hit) {
// debugger_event_emit_scanline_break(self->shared_emitter, self);
//}
return hit;
}
| 2.40625 | 2 |
2024-11-18T22:25:52.298717+00:00 | 2020-12-04T12:32:10 | 3ebb4ffffbf42ef15e8e661862a6e9ffcf3b406c | {
"blob_id": "3ebb4ffffbf42ef15e8e661862a6e9ffcf3b406c",
"branch_name": "refs/heads/master",
"committer_date": "2020-12-04T12:32:10",
"content_id": "f982c3adb513bc1e85382b713381bc3225f48dc2",
"detected_licenses": [
"Unlicense"
],
"directory_id": "c98cd0c51894606d0ef498fea4f121b071eb4662",
"extension": "c",
"filename": "message_pack_send.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 297974276,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1784,
"license": "Unlicense",
"license_type": "permissive",
"path": "/server/src/router/messages/message_pack_send.c",
"provenance": "stackv2-0115.json.gz:144443",
"repo_name": "6l17ch-3xpl017/uchat",
"revision_date": "2020-12-04T12:32:10",
"revision_id": "15a206010a8a9df5ad8e6ab9a97c22ffff404720",
"snapshot_id": "09d656822d5efff2a09b50b97325017e0452a12e",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/6l17ch-3xpl017/uchat/15a206010a8a9df5ad8e6ab9a97c22ffff404720/server/src/router/messages/message_pack_send.c",
"visit_date": "2023-01-22T02:45:31.115359"
} | stackv2 | #include "server.h"
char *message_pack_send(t_message *Message, int status) {
json_t *users_array, *msg_array, *users, *msg, *json;
char *result;
users = json_object();
msg = json_object();
users_array = json_array();
msg_array = json_array();
json = json_object();
json_object_set_new(json, "type", json_string("send_message"));
json_object_set_new(json, "status", json_integer(status));
t_chat *current_chat = malloc(sizeof(t_chat));
init_chat_struct(current_chat);
current_chat->chat_id = strdup(Message->chat_id);
get_users_list_for_chat(current_chat);
json_object_set_new(json, "chat_id", json_string(Message->chat_id));
for (t_user *head = current_chat->user_in_chat; head; head = head->next) {
json_object_set_new(users, "users_id", json_string(head->id));
json_array_append_new(users_array, users);
users = json_object();
}
json_object_set_new(msg, "author_id", json_string(Message->message_owner_id));
json_object_set_new(msg, "author_nick", json_string(current_chat->user_in_chat->nickname));
json_object_set_new(msg, "type", json_string(Message->type));
json_object_set_new(msg, "msg_id", json_string(Message->message_id));
json_object_set_new(msg, "content", json_string(Message->message_content));
json_object_set_new(msg, "modified", json_integer(Message->changed));
json_object_set_new(msg, "deleted", json_integer(Message->deleted));
json_array_append(msg_array, msg);
json_object_set_new(json, "receivers", users_array);
json_object_set_new(json, "message", msg_array);
result = json_dumps(json, 0);
puts("json from server: ");
puts(result);
free(current_chat->chat_id);
free(current_chat);
return result;
}
| 2.203125 | 2 |
2024-11-18T22:25:52.426597+00:00 | 2021-10-05T07:30:18 | d8d0b5ad02f421739a5847bb1b215bc1aee5099c | {
"blob_id": "d8d0b5ad02f421739a5847bb1b215bc1aee5099c",
"branch_name": "refs/heads/master",
"committer_date": "2021-10-05T07:30:18",
"content_id": "d992663fc4e9aa87b991007247008832a670db10",
"detected_licenses": [
"MIT"
],
"directory_id": "dc15f49cea2f8fa75d0ac487d2510b60cdbae45d",
"extension": "h",
"filename": "task3.h",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 295994311,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 309,
"license": "MIT",
"license_type": "permissive",
"path": "/P1 - Chapter 1 - Intro to C/task3.h",
"provenance": "stackv2-0115.json.gz:144573",
"repo_name": "davwheat-bhasvic/alevel-c-programming",
"revision_date": "2021-10-05T07:30:18",
"revision_id": "771f3134489e8031e4b3d47b229206e1f311f0fc",
"snapshot_id": "c8f72331e872e3c3de38e423479a4ec062d39ab8",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/davwheat-bhasvic/alevel-c-programming/771f3134489e8031e4b3d47b229206e1f311f0fc/P1 - Chapter 1 - Intro to C/task3.h",
"visit_date": "2023-08-16T13:58:28.806320"
} | stackv2 | #include <stdio.h>
int task3() {
const int charDiff = 97 - 65;
char letter;
printf("\nEnter an uppercase character: ");
// space before %c needed to ignore whitespace from enter key
scanf(" %c", &letter);
printf("\nHere's it in lower case: %c", letter + charDiff);
return 0;
}
| 3.515625 | 4 |
2024-11-18T22:25:52.606216+00:00 | 2018-08-16T21:15:27 | 2b91dee6f5d5e5bffbfb40fc138e00e0abd61f11 | {
"blob_id": "2b91dee6f5d5e5bffbfb40fc138e00e0abd61f11",
"branch_name": "refs/heads/master",
"committer_date": "2018-08-16T21:15:27",
"content_id": "45d38cf3d00b09a648de5020d4b7a924c854e553",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "1c75350e4f992c3bfe14d60dcd6daa217f28a54c",
"extension": "c",
"filename": "initialization_multiple.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 120946551,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 4269,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/gnsdk/docs/html/Content/samples/code_snippets/initialization_multiple.c",
"provenance": "stackv2-0115.json.gz:144832",
"repo_name": "jamesthesnake/JamingWithPi",
"revision_date": "2018-08-16T21:15:27",
"revision_id": "d60e4b14db24a3669844879a15d2227d41af61db",
"snapshot_id": "cfd63db04b67f147fb83a984ae81307c4eef4479",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/jamesthesnake/JamingWithPi/d60e4b14db24a3669844879a15d2227d41af61db/gnsdk/docs/html/Content/samples/code_snippets/initialization_multiple.c",
"visit_date": "2021-05-02T00:33:41.221512"
} | stackv2 | //** Standard Gracenote SDK header
#include "gnsdk.h"
//** Standard C headers - used by the sample app, but not required for GNSDK
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
//** Local declarations
gnsdk_error_t init_musicid();
gnsdk_error_t init_musicid_file();
gnsdk_error_t shutdown_all();
//******************************************************************
//**
//** M A I N
//**
//******************************************************************
int main(int argc, char* argv[])
{
gnsdk_error_t error = 0;
gnsdk_cstr_t client_id = GNSDK_NULL;
gnsdk_cstr_t client_id_tag = GNSDK_NULL;
gnsdk_cstr_t license_path = GNSDK_NULL;
gnsdk_manager_handle_t sdkmgr_handle = GNSDK_NULL;
//** Display SDK Versions
printf("\ngnsdk_manager: v%s \t(built %s)\n", gnsdk_manager_get_version(), gnsdk_manager_get_build_date());
printf( "gnsdk_musicid: v%s \t(built %s)\n\n", gnsdk_musicid_get_version(), gnsdk_musicid_get_build_date());
//** Client ID and License file must be passed in
if (argc < 4)
{
printf("usage:\n\n\t\tsample.exe clientid clientidtag license\n");
return -1;
}
client_id = argv[1];
client_id_tag = argv[2];
license_path = argv[3];
//** Initialize SDK Manager - get handle
error = gnsdk_manager_initialize(&sdkmgr_handle, license_path, GNSDK_MANAGER_LICENSEDATA_FILENAME);
error = init_musicid();
error = init_musicid_file();
shutdown_all();
return 0;
} //** main()
//******************************************************************
//**
//** I N I T _ M U S I C I D
//**
//** Initialization of MusicID
//**
//******************************************************************
gnsdk_error_t init_musicid()
{
gnsdk_manager_handle_t sdkmgr_handle = GNSDK_NULL;
gnsdk_error_t error;
//** Retrieve a GNSDK Manager handle to initialize a GNSDK.
//** No license data required after first time.
error = gnsdk_manager_initialize(&sdkmgr_handle, GNSDK_NULL, 0);
if (!error)
{
//** Use retrieved sdkmgr_handle to initialize other GNSDKs
error = gnsdk_musicid_initialize(sdkmgr_handle);
//** Pair the initialize above with a shutdown.
//** Note that this is the 2nd initialize of GNSDK Manager
//** so this shutdown will not cause an actual shutdown
gnsdk_manager_shutdown();
}
return error;
} //** init_musicid()
//******************************************************************
//**
//** I N I T _ M U S I C I D _ F I L E
//**
//** Initialization of MusicID File
//**
//******************************************************************
gnsdk_error_t init_musicid_file()
{
gnsdk_manager_handle_t sdkmgr_handle = GNSDK_NULL;
gnsdk_error_t error;
//** Retrieve a GNSDK Manager handle to initialize another GNSDK
//** No license data required after first time
error = gnsdk_manager_initialize(&sdkmgr_handle, GNSDK_NULL, 0);
if (!error)
{
//** Use the retrieved sdkmgr_handle to initialize another GNSDK
error = gnsdk_musicidfile_initialize(sdkmgr_handle);
//** Pair the initialize above with a shutdown.
//** Note that this is the second initialization of GNSDK Manager
//** so this shutdown will not cause an actual shutdown
gnsdk_manager_shutdown();
}
return error;
} //** init_musicid_file()
//******************************************************************
//**
//** S H U T D O W N _ A L L
//**
//** Shutdown all initialized GNSDKs
//**
//******************************************************************
gnsdk_error_t shutdown_all()
{
gnsdk_error_t error;
//** Shutdown GNSDKs; note that the order is not important
error = gnsdk_musicid_shutdown();
error = gnsdk_musicidfile_shutdown();
error = gnsdk_manager_shutdown(); // Pair the first initialize at top with a shutdown
return error;
} //** shutdown_all()
/*
* Copyright (c) 2012 Gracenote.
*
* This software may not be used in any way or distributed without
* permission. All rights reserved.
*
* Some code herein may be covered by US and international patents.
*/
//**
//** E N D
//** | 2.46875 | 2 |
2024-11-18T22:25:56.934784+00:00 | 2018-10-27T13:33:24 | 727b42cb7385c052ff9315e2d9b2cd3193940563 | {
"blob_id": "727b42cb7385c052ff9315e2d9b2cd3193940563",
"branch_name": "refs/heads/master",
"committer_date": "2018-10-27T13:33:24",
"content_id": "b11805e9dd68473a8854519fd331454a5149d152",
"detected_licenses": [
"MIT"
],
"directory_id": "179a6dfa0e7ef173e21821e537febeb43eecf14e",
"extension": "c",
"filename": "safe_udp.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 113059405,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 919,
"license": "MIT",
"license_type": "permissive",
"path": "/chatting-through-sockets/safe_udp.c",
"provenance": "stackv2-0115.json.gz:144962",
"repo_name": "StefanoDuo/chatting-through-sockets",
"revision_date": "2018-10-27T13:33:24",
"revision_id": "1d49970ed6864dba6b6ea37a4dc0e0f50b37a459",
"snapshot_id": "0f74a7b6b15bf360d8417799f14f8b07fcec9c47",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/StefanoDuo/chatting-through-sockets/1d49970ed6864dba6b6ea37a4dc0e0f50b37a459/chatting-through-sockets/safe_udp.c",
"visit_date": "2021-09-26T06:34:12.560542"
} | stackv2 | #include "safe_udp.h"
#include "safe_socket.h"
#include <sys/socket.h>
#include <sys/types.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int
create_udp_socket(void)
{
return create_socket(SOCK_DGRAM);
}
void
udp_send(int socket_des, const char *message, const char *ip_address,
uint16_t port_number)
{
struct sockaddr_in dest_addr = create_addr_struct(ip_address, port_number);
ssize_t result = sendto(socket_des,
message,
strlen(message) + 1,
0,
(struct sockaddr *)&dest_addr,
sizeof(dest_addr));
if (result == -1) {
perror("Error during sendto():");
exit(-1);
}
}
void
udp_receive(int socket_des, char *message, uint16_t max_message_size)
{
ssize_t result = recvfrom(socket_des,
message,
max_message_size,
0,
NULL,
NULL);
if (result == -1) {
perror("Error during recvfrom():");
exit(-1);
}
}
| 2.53125 | 3 |
2024-11-18T22:25:57.004738+00:00 | 2019-08-02T00:32:06 | edbeac0777af6bcfb8eb20be47c05a507fafc1fa | {
"blob_id": "edbeac0777af6bcfb8eb20be47c05a507fafc1fa",
"branch_name": "refs/heads/master",
"committer_date": "2019-08-02T00:32:06",
"content_id": "77e28e3ae7da16bd7e47d72ebd1f825974e59362",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "c9725b034dfae293d36f7b4dd39179df9bbe6d5c",
"extension": "c",
"filename": "informes.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": null,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 13896,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/ParcialArregladoListo/informes.c",
"provenance": "stackv2-0115.json.gz:145090",
"repo_name": "eliias00/ProgLabo1",
"revision_date": "2019-08-02T00:32:06",
"revision_id": "4a88eb6c34d1c7c5a7107e7025212b3916d40532",
"snapshot_id": "196340baeb02c216b776f8aac564b13589ffb136",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/eliias00/ProgLabo1/4a88eb6c34d1c7c5a7107e7025212b3916d40532/ParcialArregladoListo/informes.c",
"visit_date": "2020-04-30T04:05:32.542463"
} | stackv2 | #include <stdio.h>
//#include <stdio_ext.h>
#include <stdlib.h>
#include <string.h>
#include "menu.h"
#include "orquesta.h"
#include "validaciones.h"
#include "musico.h"
#include "instrumento.h"
#include "informes.h"
#define LLENO 1
#define VACIO -1
void informes(Orquesta *arrayOrq,Instrumento *arrayIns,Musico *arrayMus,int cantOrq,int cantMus,int cantIns)
{
int informe;
printf(" ::::::::::::::::::::\n");
printf(" : 1) INFORME: A :\n");
printf(" : 2) INFORME: B :\n");
printf(" : 3) INFORME: C :\n");
printf(" : 4) INFORME: D :\n");
printf(" : 5) INFORME: E :\n");
printf(" : 6) INFORME: F :\n");
printf(" : 7) INFORME: G :\n");
printf(" : 8) INFORME: H :\n");
printf(" ::::::::::::::::::::\n");
printf("ingrese un informe... ");
scanf("%d",&informe);
switch(informe)
{
case 1:
informeA( arrayOrq,cantOrq);
break;
case 2:
informeB(arrayMus,cantMus,arrayIns,arrayOrq,cantOrq,cantIns);
break;
case 3:
informeC(arrayOrq,cantOrq,arrayMus,cantMus);
break;
case 4:
informeD( arrayOrq,cantOrq,arrayIns,cantIns,arrayMus,cantMus);
break;
case 5:
informeE(arrayOrq,cantOrq,arrayMus,cantMus,arrayIns,cantIns);
break;
case 6:
informeF(arrayOrq,cantOrq,arrayMus,cantMus);
break;
case 7:
informeG(arrayOrq,cantOrq,arrayMus,cantMus,arrayIns,cantIns);
break;
case 8:
informeH(arrayMus,cantMus,arrayIns,cantIns);
break;
}
}
void informeA(Orquesta *arrayOrq,int cantOrq)
{
char auxLugar[50];
int i;
getDireccion(auxLugar,"ingrese un lugar: ","error, vuelva a ingresar\n\n",1,51,1);
for(i=0; i<cantOrq; i++)
{
if(arrayOrq[i].isEmpty==LLENO && strcmp(arrayOrq[i].lugar,auxLugar)==0)
{
printf("id:%d nombre:%s tipo:%d lugar:%s \n",
arrayOrq[i].id,
arrayOrq[i].nombre,
arrayOrq[i].tipo,
arrayOrq[i].lugar);
}
}
}
void informeB(Musico *arrayMus,int cantMus,Instrumento *arrayIns,Orquesta *arrayOrq,int cantOrq,int cantIns)
{
int i;
int j;
int k;
for(i=0; i<cantMus; i++)
{
if(arrayMus[i].isEmpty==LLENO && arrayMus[i].edad < 25)
{
for(j=0; j<cantOrq; j++)
{
if(arrayOrq[j].id==arrayMus[i].idOrq)
{
for(k=0; k<cantIns; k++)
{
if(arrayIns[k].id==arrayMus[i].idIns)
{
if(arrayIns[i].tipo==1)
{
printf(" id:%d nombre:%s apellido:%s edad:%d nombre de la orquesta:%s nombre de intrumento:cuerdas\n",
arrayMus[i].id,
arrayMus[i].nombre,
arrayMus[i].apellido,
arrayMus[i].edad,
arrayOrq[j].nombre);
break;
}
if(arrayIns[i].tipo==2)
{
printf(" id:%d nombre:%s apellido:%s edad:%d nombre de la orquesta:%s nombre de intrumento:viento-madera\n",
arrayMus[i].id,
arrayMus[i].nombre,
arrayMus[i].apellido,
arrayMus[i].edad,
arrayOrq[j].nombre);
break;
}
if(arrayIns[i].tipo==3)
{
printf(" id:%d nombre:%s apellido:%s edad:%d nombre de la orquesta:%s nombre de intrumento:viento-metal\n",
arrayMus[i].id,
arrayMus[i].nombre,
arrayMus[i].apellido,
arrayMus[i].edad,
arrayOrq[j].nombre);
break;
}
if(arrayIns[i].tipo==4)
{
printf(" id:%d nombre:%s apellido:%s edad:%d nombre de la orquesta:%s nombre de intrumento:percusion\n",
arrayMus[i].id,
arrayMus[i].nombre,
arrayMus[i].apellido,
arrayMus[i].edad,
arrayOrq[j].nombre);
break;
}
}
}
break;
}
}
}
}
}
void informeC(Orquesta *arrayOrq,int cantOrq,Musico *arrayMus,int cantMus)
{
int i;
int j;
int k;
int l;
int cont;
char idAut[50];
int auxAut;
int flag=0;
Orquesta auxOrq[cantOrq];
for(i=0; i<cantOrq; i++)
{
if(arrayOrq[i].isEmpty==LLENO )
{
flag=1;
auxOrq[i]=arrayOrq[i];
cont=0;
for(j=0; j<cantMus; j++)
{
if(flag!=0&&arrayOrq[i].id==auxOrq[0].id)
{
if(arrayOrq[i].id==arrayMus[j].idOrq)
{
cont++;
}
}
else if(flag!=0&&arrayOrq[i].id!=auxOrq[0].id)
{
if(arrayOrq[i].id==arrayMus[j].idOrq)
{
cont++;
}
}
}
}
if( cont<6 && arrayOrq[i].isEmpty==LLENO)
{
printf("id:%d nombre:%s tipo:%d lugar:%s \n",
arrayOrq[i].id,
arrayOrq[i].nombre,
arrayOrq[i].tipo,
arrayOrq[i].lugar);
}
}
}
void informeD(Orquesta *arrayOrq,int cantOrq,Instrumento *arrayIns,int cantIns,Musico *arrayMus,int cantMus)
{
char idAut[50];
int auxAut;
int i;
int j;
int k;
int l;
for(l=0; l<cantOrq; l++)
{
if(arrayOrq[l].isEmpty!=VACIO)
{
printf("id de orquesta:%d\n",arrayOrq[l].tipo);
}
}
getInt("ingrese el id de la orquesta: ","\nerror,vuelva a intentar",0,20,1,idAut);
auxAut=atoi(idAut);
for(i=0; i<cantOrq; i++)
{
if(arrayOrq[i].isEmpty==LLENO && auxAut==arrayOrq[i].id)
{
for(j=0; j<cantMus; j++)
{
if(arrayMus[j].isEmpty==LLENO && arrayOrq[i].id==arrayMus[j].idOrq)
{
for(k=0; k<cantIns; k++)
{
if(arrayIns[k].isEmpty==LLENO &&arrayMus[j].idIns==arrayIns[k].id)
{
if(arrayIns[k].tipo==1)
{
printf("nombre:cuerdas tipo:%d nombre de musico:%s\n",
arrayIns[k].tipo,
arrayMus[j].nombre);
}
if(arrayIns[k].tipo==2)
{
printf("nombre:viento-madera tipo:%d nombre de musico:%s\n",
arrayIns[k].tipo,
arrayMus[j].nombre);
}
if(arrayIns[k].tipo==3)
{
printf("nombre:viento-metal tipo:%d nombre de musico:%s\n",
arrayIns[k].tipo,
arrayMus[j].nombre);
}
if(arrayIns[k].tipo==4)
{
printf("nombre:percusion tipo:%d nombre de musico:%s\n",
arrayIns[k].tipo,
arrayMus[j].nombre);
}
}
}
}
}
}
}
}
void informeE(Orquesta *arrayOrq,int cantOrq,Musico *arrayMus,int cantMus,Instrumento *arrayIns,int cantIns)
{
int i;
int j;
int k;
int l;
int contCue=0;
int contPer=0;
int contVie=0;
for(i=0; i<cantOrq; i++)
{
if(arrayOrq[i].isEmpty==LLENO)
{
for(j=0; j<cantMus; j++)
{
if(arrayOrq[i].id==arrayMus[j].idOrq)
{
for(k=0; k<cantIns; k++)
{
if(arrayMus[j].idIns==arrayIns[k].id)
{
if(arrayIns[k].tipo==1)
{
contCue++;
}
if(arrayIns[k].tipo==2||arrayIns[k].tipo==3)
{
contVie++;
}
if(arrayIns[k].tipo==4)
{
contPer++;
}
}
}
}
}
}
}
for(l=0; l<cantOrq; l++)
{
if(contCue >=4 && contVie >=4 && contPer >= 1)
{
printf("nombre:%s lugar:%s tipo:%d\n",arrayOrq[l].nombre,arrayOrq[l].lugar,arrayOrq[l].tipo);
break;
}
}
}
void informeF(Orquesta *arrayOrq,int cantOrq,Musico *arrayMus,int cantMus)
{
int i,j;
int flag=0;
Orquesta minOrq[cantOrq];
int cantidadDeMinimos = 0;
int cantidadDeOrquestas;
int menoscantidadDeOrquestas;
for(i=0; i<cantOrq; i++)
{
if (flag==0 && arrayOrq[i].isEmpty ==LLENO)
{
flag=1;
minOrq[0] = arrayOrq[i];
cantidadDeOrquestas =0;
for(j=0; j<cantMus; j++)
{
if(arrayMus[j].isEmpty == LLENO &&
arrayMus[j].idOrq == arrayOrq[i].id)
{
cantidadDeOrquestas++;
}
}
menoscantidadDeOrquestas = cantidadDeOrquestas;
cantidadDeMinimos = 1;
}
else if(arrayOrq[i].isEmpty ==LLENO)
{
cantidadDeOrquestas = 0;
for(j=0; j<cantOrq; j++)
{
if(arrayMus[j].isEmpty == LLENO )
{
if(arrayMus[j].idOrq == arrayOrq[i].id)
{
cantidadDeOrquestas++;
}
}
}
if(cantidadDeOrquestas < menoscantidadDeOrquestas)
{
cantidadDeMinimos = 1;
menoscantidadDeOrquestas = cantidadDeOrquestas;
minOrq[0] = arrayOrq[i];
}
else if(cantidadDeOrquestas == menoscantidadDeOrquestas)
{
minOrq[cantidadDeMinimos] = arrayOrq[i];
cantidadDeMinimos++;
}
}
}
for(i=0; i<cantidadDeMinimos; i++)
{
if(arrayOrq[i].isEmpty ==LLENO)
{
printf("id:%d nombre:%s lugar:%s tipo:%d\ncantidad de musicos que posee:%d\n",
minOrq[i].id,minOrq[i].nombre,minOrq[i].lugar,minOrq[i].tipo,cantidadDeOrquestas);
}
}
}
void informeG(Orquesta *arrayOrq,int cantOrq,Musico *arrayMus,int cantMus, Instrumento *arrayIns,int cantIns)
{
int i;
int j;
int k;
int contIns=0;
float contOrq=0;
float resul;
for(i=0; i<cantMus; i++)
{
if(arrayMus[i].isEmpty==LLENO)
{
for(j=0; j<cantIns; j++)
{
if(arrayMus[i].idIns==arrayIns[j].id)
{
contIns++;
}
}
}
}
for(k=0; k<cantOrq; k++)
{
if(arrayOrq[k].isEmpty==LLENO)
{
contOrq++;
}
}
resul=contIns/contOrq;
printf("Promedio: %.2f",resul);
}
void informeH(Musico *arrayMus,int cantMus,Instrumento *arrayIns,int cantIns)
{
int i;
int j;
int d;
int a;
Musico aux;
printf(" ordenado alfabeticamente ascendente por apellido:\n");
for(i = 1; i<cantMus; i++)
{
aux = arrayMus[i];
j = i;
while(j > 0 && strcmp( aux.apellido, arrayMus[j - 1].apellido)<0)
{
arrayMus[j] = arrayMus[j - 1];
j--;
}
arrayMus[j] = aux;
}
for (d=0; d<cantMus; d++)
{
if(arrayMus[d].isEmpty==LLENO )
{
for(a=0; a<cantIns; a++)
{
if(arrayMus[d].idIns==arrayIns[a].id && arrayIns[a].isEmpty==LLENO)
{
if(arrayIns[a].tipo!=2 && arrayIns[a].tipo!=3 )
{
printf("nombre:%s apellido:%s edad:%d tipo de intstrumento:%d\n",
arrayMus[d].nombre,
arrayMus[d].apellido,
arrayMus[d].edad,
arrayIns[a].tipo);
}
}
}
}
}
}
| 2.375 | 2 |
2024-11-18T22:25:57.337411+00:00 | 2017-03-31T16:40:34 | d94a2fc8e8ff1b81f3acfaf64c771734111d5b29 | {
"blob_id": "d94a2fc8e8ff1b81f3acfaf64c771734111d5b29",
"branch_name": "refs/heads/master",
"committer_date": "2017-03-31T16:40:34",
"content_id": "6bb1b5d51f461e8c052e31a3c7b85a21752454c3",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "28fd09aacd43dd7c854cee588fd13407ee3b5a05",
"extension": "c",
"filename": "test_readdir.c",
"fork_events_count": 1,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 53446061,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 495,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/acsl/libraries/libc/test/posix/dirent/test_readdir.c",
"provenance": "stackv2-0115.json.gz:145605",
"repo_name": "AnnotationsForAll/annotationsforall",
"revision_date": "2017-03-31T16:40:34",
"revision_id": "16024a9ffecdb72b638e1f942c567f8815183e89",
"snapshot_id": "3e9a444ba689153aa7bd0c027bf74e97ec9c4128",
"src_encoding": "UTF-8",
"star_events_count": 4,
"url": "https://raw.githubusercontent.com/AnnotationsForAll/annotationsforall/16024a9ffecdb72b638e1f942c567f8815183e89/acsl/libraries/libc/test/posix/dirent/test_readdir.c",
"visit_date": "2021-01-13T00:53:00.474354"
} | stackv2 | #include "../../../test_common.h"
#include <dirent.h>
#include <errno.h>
void runSuccess() {
DIR* dir = fdopendir(0);
if (dir != NULL) {
readdir(dir);
}
}
void runFailure() {
readdir(NULL);
}
int f;
void testValues() {
f = 2;
struct dirent * result;
DIR* dir = fdopendir(0);
if (dir != NULL) {
result = readdir(dir);
//@ assert result == \null || \valid(result);
}
//@ assert f == 2;
//@ assert vacuous: \false;
}
| 2.25 | 2 |
2024-11-18T22:25:57.780936+00:00 | 2020-02-11T17:23:54 | c565dfadf644ed39fc04f6d758f00adaadcf7ed0 | {
"blob_id": "c565dfadf644ed39fc04f6d758f00adaadcf7ed0",
"branch_name": "refs/heads/master",
"committer_date": "2020-02-11T17:23:54",
"content_id": "34ccab4d2882441e94235060f092c15f56eed66a",
"detected_licenses": [
"MIT"
],
"directory_id": "021f6dc1a39d4d2aedcd9b6a48b76c90a9586509",
"extension": "c",
"filename": "ft_lstsort.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 174792802,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1965,
"license": "MIT",
"license_type": "permissive",
"path": "/libft/src/list/ft_lstsort.c",
"provenance": "stackv2-0115.json.gz:145735",
"repo_name": "ygarrot/libft",
"revision_date": "2020-02-11T17:23:54",
"revision_id": "7ebf33aa7bd10a5e627b90d428a5613095f7c10b",
"snapshot_id": "656fde42616550101521253a28b3cac018107eb5",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/ygarrot/libft/7ebf33aa7bd10a5e627b90d428a5613095f7c10b/libft/src/list/ft_lstsort.c",
"visit_date": "2022-04-12T17:23:50.395143"
} | stackv2 | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_lstsort.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: tcharrie <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2018/01/17 14:11:01 by tcharrie #+# #+# */
/* Updated: 2018/01/17 14:11:14 by tcharrie ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
static int ft_listsorted(t_list *lst, int (*cmp)(void *, void *))
{
while (lst && lst->next)
{
if (!cmp(lst->content, lst->next->content))
return (0);
lst = lst->next;
}
return (1);
}
static t_list *ft_swap(t_list *prev, t_list *lst, t_list *ne)
{
if (prev)
prev->next = ne;
lst->next = ne->next;
ne->next = lst;
if (prev)
return (prev);
return (ne);
}
static void ft_aux(t_list *tmp, t_list *prec, int (*cmp)(void *, void *))
{
t_list *prev;
prev = prec;
while (tmp && tmp->next)
{
if (!(cmp(tmp->content, tmp->next->content)))
{
ft_swap(prev, tmp, tmp->next);
}
prev = tmp;
tmp = tmp->next;
}
}
t_list *ft_lstsort(t_list *lst, int (*cmp)(void *, void *))
{
t_list *suiv;
t_list *tmp;
t_list *begin;
if (!lst || !(lst->next))
return (lst);
begin = lst;
while (!ft_listsorted(begin, cmp))
{
tmp = begin;
suiv = tmp->next;
if (!cmp(tmp->content, suiv->content))
{
begin = suiv;
tmp->next = suiv->next;
suiv->next = tmp;
}
ft_aux(begin->next, begin, cmp);
}
return (begin);
}
| 2.984375 | 3 |
2024-11-18T22:25:58.495679+00:00 | 2020-05-21T08:55:23 | 63877e9389b292eff6959e373b3dbf63882153dc | {
"blob_id": "63877e9389b292eff6959e373b3dbf63882153dc",
"branch_name": "refs/heads/master",
"committer_date": "2020-05-21T08:55:23",
"content_id": "eeeea8633faae309e835da750884b153ec353dfb",
"detected_licenses": [
"MIT"
],
"directory_id": "bf152b3e2fe977ee26b3b3807e998aa9ba7d5b6f",
"extension": "c",
"filename": "esercizio-C-2020-05-19-procs.c",
"fork_events_count": 0,
"gha_created_at": "2020-05-20T09:39:31",
"gha_event_created_at": "2020-05-20T09:39:32",
"gha_language": null,
"gha_license_id": "MIT",
"github_id": 265518356,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2812,
"license": "MIT",
"license_type": "permissive",
"path": "/src/esercizio-C-2020-05-19-procs.c",
"provenance": "stackv2-0115.json.gz:146124",
"repo_name": "AndreaGonzato/esercizio-C-2020-05-19-procs",
"revision_date": "2020-05-21T08:55:23",
"revision_id": "03349ce2490a673e6742b85a3b6a4d321f0722ec",
"snapshot_id": "9a908b1748df11cd9ac813f829d7579b039d19e1",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/AndreaGonzato/esercizio-C-2020-05-19-procs/03349ce2490a673e6742b85a3b6a4d321f0722ec/src/esercizio-C-2020-05-19-procs.c",
"visit_date": "2022-08-22T04:20:35.820209"
} | stackv2 | #include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/mman.h>
#include <semaphore.h>
#include <pthread.h>
#include <errno.h>
void child_process();
#define N 10
int * countdown;
int * shutdown;
int * process_counter;
sem_t * semaphore;
int main(void) {
countdown = mmap(NULL, sizeof(int), PROT_READ | PROT_WRITE, MAP_SHARED | MAP_ANONYMOUS, -1 ,0);
if (countdown == MAP_FAILED) {
perror("mmap()");
exit(EXIT_FAILURE);
}
*countdown = -1;
shutdown = mmap(NULL, sizeof(int), PROT_READ | PROT_WRITE, MAP_SHARED | MAP_ANONYMOUS, -1 ,0);
if (shutdown == MAP_FAILED) {
perror("mmap()");
exit(EXIT_FAILURE);
}
*shutdown = 0;
process_counter = calloc(N, sizeof(int));
if(process_counter == NULL){
perror("calloc()");
exit(1);
}
process_counter = mmap(process_counter, sizeof(int), PROT_READ | PROT_WRITE, MAP_SHARED | MAP_ANONYMOUS, -1 ,0);
if (process_counter == MAP_FAILED) {
perror("mmap()");
exit(EXIT_FAILURE);
}
semaphore = mmap(NULL, // NULL: è il kernel a scegliere l'indirizzo
sizeof(sem_t), // dimensione della memory map
PROT_READ | PROT_WRITE, // memory map leggibile e scrivibile
MAP_SHARED | MAP_ANONYMOUS, // memory map condivisibile con altri processi e senza file di appoggio
-1,
0); // offset nel file
if (semaphore == MAP_FAILED) {
perror("mmap()");
exit(EXIT_FAILURE);
}
int res = sem_init(semaphore,
1, // 1 => il semaforo è condiviso tra processi, 0 => il semaforo è condiviso tra threads del processo
1 // valore iniziale del semaforo
);
if(res == -1){
perror("sem_init()");
exit(1);
}
// create N children
for (int i = 0; i < N; i++) {
switch (fork()) {
case 0:
child_process(i);
break;
case -1:
perror("fork()");
exit(1);
}
}
// dopo avere avviato i processi figli, il processo padre dorme 1 secondo
int sec = 1;
printf("wait %d second\n", sec);
sleep(sec);
*countdown = 100000;
printf("countdown set to: %d\n", *countdown);
while(1){
if( *countdown == 0){
*shutdown = 1;
break;
}
}
// wait N children
for(int i=0 ; i<N ; i++){
wait(NULL);
}
printf("countdown at the end: %d\n", *countdown);
for(int i=0 ; i<N ; i++){
printf("child %d has decrement countdown %d times\n", i, process_counter[i]);
}
printf("end \n");
exit(0);
}
void child_process(int child_index) {
while(1){
if (sem_wait(semaphore) == -1) {
perror("sem_wait");
exit(EXIT_FAILURE);
}
// sezione critica
if( *countdown > 0 ){
*countdown = (*countdown -1);
process_counter[child_index]++;
}
if (sem_post(semaphore) == -1) {
perror("sem_post");
exit(EXIT_FAILURE);
}
if( *shutdown != 0){
exit(0);
}
}
exit(0);
}
| 3.234375 | 3 |
2024-11-18T22:25:58.591797+00:00 | 2013-08-17T08:36:23 | 95b1430e88dce64feeae1081acf9860b301d568d | {
"blob_id": "95b1430e88dce64feeae1081acf9860b301d568d",
"branch_name": "refs/heads/master",
"committer_date": "2013-08-17T08:36:23",
"content_id": "d5d9f0aa419cbffb4bc777ae6dcf5b6c10daed01",
"detected_licenses": [
"Unlicense"
],
"directory_id": "d44db52f29fee68f0706fdd4120f1e8a7833d2ca",
"extension": "h",
"filename": "clp-app-mgr.h",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": null,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 5171,
"license": "Unlicense",
"license_type": "permissive",
"path": "/src/clp-app-mgr.h",
"provenance": "stackv2-0115.json.gz:146253",
"repo_name": "qianqiusoft/ApplicationManager",
"revision_date": "2013-08-17T08:36:23",
"revision_id": "6e78e24972aa493d184ae293ec8df0756cb468de",
"snapshot_id": "5404e3fac943b88f2cf673a55d11c1bb1c97e292",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/qianqiusoft/ApplicationManager/6e78e24972aa493d184ae293ec8df0756cb468de/src/clp-app-mgr.h",
"visit_date": "2021-01-23T02:49:22.827849"
} | stackv2 | /** \file clp-app-mgr.h
* \brief Application Manager System Object for Celunite Linux Platform
*
* The APIs to be used by the applications to access application manager are declared here.
*/
#ifndef __CLP_APP_MGR_H__
#define __CLP_APP_MGR_H__
#include <glib.h>
#define CLP_APP_MGR_ENTRY_POINT "main" /**< Entry point of the shared object application */
#define CLP_APP_MGR_PRIORITY_CRITICAL 0 /**< Supercritical Application Highest Priority */
#define CLP_APP_MGR_PRIORITY_NORMAL 10 /**< Normal Application Like Browser etc */
#define CLP_APP_MGR_PRIORITY_LOW 100 /**< Lower priority application that may run in background */
#define CLP_APP_MGR_PRIORITY_NICE_APP 1000 /**< Application should run only when noone else is around */
#define NAME_SIZE 256 /**< The maximum size of the application's name*/
#define MAX_SIZE 256 /**< The maximum size for dbus connections*/
#define NO_APPLICATION "none" /**< Returned when no application exists which matches the given criteria */
enum _ClpAppMgrErrorCodes /**< Standard Error Codes for Application Manager*/
{
CLP_APP_MGR_FAILURE = -1, /**< The function failed to return */
CLP_APP_MGR_SUCCESS = 0, /**< The function executed successfully */
CLP_APP_MGR_OUT_OF_MEMORY = 0xd0, /**< Memory overflow error */
CLP_APP_MGR_DBUS_CALL_FAIL = 0xd1, /**< Dbus call failed error */
CLP_APP_MGR_DBUS_REPLY_FAIL = 0xd2, /**< Reply to the method call failed */
CLP_APP_MGR_LIB_NOTIFY_FAIL = 0xd3, /**< Lib notify error */
CLP_APPMGR_GTK_FAIL = 0xd4, /**< Gtk error */
CLP_APP_MGR_DLAPP_FAIL = 0xd5, /**< Dynamic Symbol resolution error */
CLP_APP_MGR_INIT_FAILURE = 0xd6 /**< Init failure */
};
struct _ClpAppMgrActiveApp /**< Struct for active application info */
{
gint pid; /**< pid of the application */
gchar name[NAME_SIZE]; /**< instance name of the application */
gchar title[NAME_SIZE]; /**< title of the application */
gchar *icon; /**< icon of the application */
gboolean visibility; /**< visibility of the application */
gboolean immortal; /**< immortality of the application */
};
struct _ClpAppMgrInstalledApp /**< Struct for installed application info */
{
gchar *name; /**< name of the application */
gchar *generic_name; /**< generic name (class) of the application */
gchar *icon; /**< icon of the application */
gchar *exec_name; /**< exec name of the application */
gchar *menu_path; /**< menu path of the application */
gboolean nodisplay; /**< nodisplay flag (whether to display in menus) */
gint menupos; /**< menu position of the application */
};
/*window manager */
typedef struct _ClpAppMgrWindowInfo
{
gint pid;
guint windowid;
gchar *icon;
gchar *title;
}ClpAppMgrWindowInfo;
typedef struct _ClpAppMgrWinResizeInfo
{
gint windowid;
gint x_move;
gint y_move;
gint width;
gint height;
}ClpAppMgrWinResizeInfo;
/*window manager end */
typedef enum _ClpAppMgrErrorCodes ClpAppMgrErrorCodes; /**< typedef for enum for error codes */
typedef struct _ClpAppMgrActiveApp ClpAppMgrActiveApp; /**< typedef for Active apps structure */
typedef struct _ClpAppMgrInstalledApp ClpAppMgrInstalledApp; /**< typedef for Installed apps struct */
/* API for switiching off the cell ! */
gint clp_app_mgr_power_off(void);
/* APIs for Window manager Support*/
GSList* clp_app_mgr_wm_get_window_list();
gint clp_app_mgr_wm_get_screen_exclusive();
gint clp_app_mgr_wm_release_screen();
gint clp_app_mgr_wm_restore_application(gint pid);
gint clp_app_mgr_wm_restore_window(gint windowid);
gint clp_app_mgr_wm_minimize_application(gint pid);
gint clp_app_mgr_wm_minimize_window(gint windowid);
gint clp_app_mgr_wm_get_available_screen_dimensions(gint *height, gint *width);
gint clp_app_mgr_wm_set_window_priority(gint windowid, gint priority);
gint clp_app_mgr_wm_move_resize_window(ClpAppMgrWinResizeInfo resizeinfo);
gint clp_app_mgr_wm_fullscreen_window(gint windowid, gint flag);
gint clp_app_mgr_wm_toggle_fullscreen_window(void);
gint clp_app_mgr_wm_get_top_window_of_application(gint pid, gchar **top_window);
/* Themeing Support */
GSList* clp_app_mgr_get_installed_themes();
gint clp_app_mgr_apply_theme(const gchar *theme);
/* Querying of information of active applications*/
GList* clp_app_mgr_get_active_apps();
gint clp_app_mgr_get_num_of_active_apps();
GList* clp_app_mgr_get_active_instances_of_app(gchar *appname);
gint clp_app_mgr_get_num_of_active_instances_of_app(gchar *appname);
gint clp_app_mgr_is_app_active(gchar *appname);
gchar* clp_app_mgr_get_application_id(gint pid);
ClpAppMgrActiveApp *clp_app_mgr_get_application_instance_info(gchar *instance_name);
/* Querying of information of installed applications*/
GList* clp_app_mgr_get_installed_apps(gchar *appclass);
/* application configuration APIs */
gchar* clp_app_mgr_get_property (const gchar *application, const gchar *property);
void clp_app_mgr_set_property (const gchar *application, const gchar *property, const gchar *value);
#endif
| 2.234375 | 2 |
2024-11-18T22:25:58.932395+00:00 | 2023-05-16T09:14:24 | f275d645b29aa4344d3b7db5d755416f46415a12 | {
"blob_id": "f275d645b29aa4344d3b7db5d755416f46415a12",
"branch_name": "refs/heads/master",
"committer_date": "2023-05-16T09:14:24",
"content_id": "d3b37818a5664dcb434ccdca61a4a99335c33c47",
"detected_licenses": [
"MIT"
],
"directory_id": "53ada3c2059b315f19073ac9df58d785c7b3678b",
"extension": "c",
"filename": "endian.c",
"fork_events_count": 84,
"gha_created_at": "2011-08-13T20:53:28",
"gha_event_created_at": "2023-05-16T09:14:25",
"gha_language": "C++",
"gha_license_id": "MIT",
"github_id": 2203082,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 624,
"license": "MIT",
"license_type": "permissive",
"path": "/src/HexEdit/endian.c",
"provenance": "stackv2-0115.json.gz:146511",
"repo_name": "strobejb/HexEdit",
"revision_date": "2023-05-16T09:14:24",
"revision_id": "f8ae7cdbecc40f85d83c357882b92c6ca5899988",
"snapshot_id": "946cb21d6bf68c6aaa8e71ab6ea48c99b4f29817",
"src_encoding": "UTF-8",
"star_events_count": 239,
"url": "https://raw.githubusercontent.com/strobejb/HexEdit/f8ae7cdbecc40f85d83c357882b92c6ca5899988/src/HexEdit/endian.c",
"visit_date": "2023-06-02T15:45:18.485383"
} | stackv2 | //
// endian.c
//
// www.catch22.net
//
// Copyright (C) 2012 James Brown
// Please refer to the file LICENCE.TXT for copying permission
//
#include "endian.h"
size_t reverse(BYTE *buf, size_t len)
{
size_t i;
if(buf == 0 || len == 0)
return 0;
for(i = 0; i < len/2; i++)
{
BYTE b = buf[len-i-1];
buf[len-i-1] = buf[i];
buf[i] = b;
}
return len;
}
UINT16 reverse16(UINT16 n16)
{
reverse((BYTE *)&n16, sizeof(n16));
return n16;
}
UINT32 reverse32(UINT32 n32)
{
reverse((BYTE *)&n32, sizeof(n32));
return n32;
}
UINT64 reverse64(UINT64 n64)
{
reverse((BYTE *)&n64, sizeof(n64));
return n64;
}
| 2.5625 | 3 |
2024-11-18T22:25:59.380948+00:00 | 2018-04-12T21:24:44 | 082df4f5e7de54516c53c9e12787daddc142598d | {
"blob_id": "082df4f5e7de54516c53c9e12787daddc142598d",
"branch_name": "refs/heads/master",
"committer_date": "2018-04-12T21:24:44",
"content_id": "b9fd32a77a067a509efc117e03779365e46af6fc",
"detected_licenses": [
"MIT"
],
"directory_id": "7e060283f4409ee673608a2746fb9dc9cac9d1a2",
"extension": "c",
"filename": "background.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 129304318,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 3337,
"license": "MIT",
"license_type": "permissive",
"path": "/src/background.c",
"provenance": "stackv2-0115.json.gz:146768",
"repo_name": "wteiwewte/Shell",
"revision_date": "2018-04-12T21:24:44",
"revision_id": "28548519599470943b23546285994237b9776d1f",
"snapshot_id": "17a018494a2ae3ccfaaac73b302dc237785b2a59",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/wteiwewte/Shell/28548519599470943b23546285994237b9776d1f/src/background.c",
"visit_date": "2020-03-10T09:29:25.985401"
} | stackv2 | #include <stdio.h>
#include <signal.h>
#include <sys/wait.h>
#include <errno.h>
#include "background.h"
volatile int foreground_childs;
volatile arr_status background_childs;
volatile pid_t arr_foreground[FOREGROUND_SIZE];
void handler_sigchld(int sig)
{
/*
blocking sigchld so we won't get one durign execution of our handler
*/
sigset_t blocking;
sigemptyset(&blocking);
sigaddset(&blocking, SIGCHLD);
sigprocmask(SIG_BLOCK, &blocking, NULL);
pid_t p;
int status;
/*
while checking if there is any child zombie
*/
while( (p=waitpid(-1, &status, WNOHANG)) > 0 ){
if( get_index(background_childs.id, p, BACKGROUND_SIZE) == NOT_FOUND_THIS_PID_IN_BACKGROUND ) {
if( get_index(arr_foreground, p, FOREGROUND_SIZE) >= 0 ) {
foreground_childs--;
del_pid(arr_foreground, p, FOREGROUND_SIZE);
}
}
else {
set_status(p, status);
del_pid(background_childs.id, p, BACKGROUND_SIZE);
}
}
sigprocmask(SIG_UNBLOCK, &blocking, NULL);
}
void initiate(volatile pid_t* tab, int SIZE){
/*
setting our arr_status
*/
int i;
for( i = 0; i < SIZE; ++i ) tab[i] = NO_STATUS;
}
int get_index(volatile pid_t* tab, pid_t p, int SIZE){
/*
function returning pid's index in our statuses array
*/
int i = 0;
while( i < SIZE ){
if( tab[i] == p ) return i;
i++;
}
return NOT_FOUND_THIS_PID_IN_BACKGROUND;
}
void add_pid(volatile pid_t* tab, pid_t p, int SIZE){
/*
function adding pid to statuses array
*/
int i = 0;
while( tab[i] != NO_STATUS ){
i++;
}
tab[i] = p;
}
void del_pid(volatile pid_t* tab, pid_t p, int SIZE){
/*
function deleting pid to statuses array
*/
if( SIZE == FOREGROUND_SIZE ) tab[get_index(tab, p, SIZE)] = NO_STATUS;
else tab[get_index(tab, p, SIZE)] = GOT_STATUS;
}
bool is_full(){
/*
function checking if our statuses array is full
*/
int i = 0;
while( i < BACKGROUND_SIZE ){
if( background_childs.id[i] == NO_STATUS ) return false;
i++;
}
return true;
}
void set_status(pid_t p, int status){
/*
function setting pid's status in our statuses array
*/
int id_pid = get_index(background_childs.id, p, BACKGROUND_SIZE);
if( id_pid >= 0 ){
if( WIFEXITED(status) ) {
sprintf((char *) background_childs.status[id_pid], "Background process %d terminated. (exited with status %d)\n", background_childs.id[id_pid], WEXITSTATUS(status));
}
else if( WIFSIGNALED(status) ){
sprintf((char *) background_childs.status[id_pid], "Background process %d terminated. (killed by signal %d)\n", background_childs.id[id_pid], WTERMSIG(status));
}
}
}
void print_statuses(){
/*
function printing all available statuses
*/
int i;
for( i = 0; i < BACKGROUND_SIZE; ++i ) {
if( background_childs.id[i] == GOT_STATUS ){
printf("%s\n", background_childs.status[i]);
background_childs.id[i] = NO_STATUS;
}
}
fflush(stdout);
}
| 2.96875 | 3 |
2024-11-18T22:25:59.550702+00:00 | 2023-08-18T12:54:06 | 328ec48ef2f6b0bcc78655e6bf2efd906e625eb2 | {
"blob_id": "328ec48ef2f6b0bcc78655e6bf2efd906e625eb2",
"branch_name": "refs/heads/master",
"committer_date": "2023-08-18T12:54:06",
"content_id": "fe2953f049be106ae4ab6e3fa54ba009422f8f9a",
"detected_licenses": [
"MIT"
],
"directory_id": "22446075c2e71ef96b4a4777fe966714ac96b405",
"extension": "c",
"filename": "main.c",
"fork_events_count": 68,
"gha_created_at": "2020-09-30T10:18:15",
"gha_event_created_at": "2023-09-08T12:56:11",
"gha_language": "C",
"gha_license_id": "NOASSERTION",
"github_id": 299882138,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2641,
"license": "MIT",
"license_type": "permissive",
"path": "/clicks/clickid/example/main.c",
"provenance": "stackv2-0115.json.gz:147027",
"repo_name": "MikroElektronika/mikrosdk_click_v2",
"revision_date": "2023-08-18T12:54:06",
"revision_id": "49ab937390bef126beb7b703d5345fa8cd6e3555",
"snapshot_id": "2cc2987869649a304763b0f9d27c920d42a11c16",
"src_encoding": "UTF-8",
"star_events_count": 77,
"url": "https://raw.githubusercontent.com/MikroElektronika/mikrosdk_click_v2/49ab937390bef126beb7b703d5345fa8cd6e3555/clicks/clickid/example/main.c",
"visit_date": "2023-08-21T22:15:09.036635"
} | stackv2 | /*!
* @file main.c
* @brief ClickID Example.
*
* # Description
* This example reads the information from ClickID permanent memory.
*
* The demo application is composed of two sections :
*
* ## Application Init
* Initializes the driver and checks the communication with the click board.
*
* ## Application Task
* Reads the information from ClickID permanent manifest every 5 seconds.
*
* @author Stefan Filipovic
*
*/
#include "board.h"
#include "log.h"
#include "clickid.h"
static clickid_t clickid;
static log_t logger;
void application_init ( void )
{
log_cfg_t log_cfg; /**< Logger config object. */
clickid_cfg_t clickid_cfg; /**< ClickID config object. */
/**
* Logger initialization.
* Default baud rate: 115200
* Default log level: LOG_LEVEL_DEBUG
* @note If USB_UART_RX and USB_UART_TX
* are defined as HAL_PIN_NC, you will
* need to define them manually for log to work.
* See @b LOG_MAP_USB_UART macro definition for detailed explanation.
*/
LOG_MAP_USB_UART( log_cfg );
log_init( &logger, &log_cfg );
log_info( &logger, " Application Init " );
// ClickID initialization.
clickid_cfg_setup( &clickid_cfg );
CLICKID_MAP_MIKROBUS( clickid_cfg, MIKROBUS_1 );
if ( ONE_WIRE_ERROR == clickid_init( &clickid, &clickid_cfg ) )
{
log_error( &logger, " Communication init." );
for ( ; ; );
}
if ( CLICKID_ERROR == clickid_check_communication ( &clickid ) )
{
log_error( &logger, " Communication fail." );
log_printf( &logger, "Check if the click is attached to the correct " );
log_printf( &logger, "MIKROBUS socket, and try again.\r\n" );
for ( ; ; );
}
log_info( &logger, " Application Task " );
}
void application_task ( void )
{
clickid_information_t info;
if ( CLICKID_OK == clickid_read_information ( &clickid, &info ) )
{
log_printf ( &logger, "\r\n --- Click info ---\r\n" );
log_printf ( &logger, " Name: %s\r\n", info.name );
log_printf ( &logger, " PID: MIKROE-%u\r\n", info.serial );
log_printf ( &logger, " HW REV.: %u.%.2u\r\n",
( uint16_t ) info.hw_rev.major, ( uint16_t ) info.hw_rev.minor );
log_printf ( &logger, " Type: 0x%.4X\r\n", info.type );
log_printf ( &logger, " Custom: 0x%.2X\r\n", ( uint16_t ) info.custom );
}
Delay_ms ( 5000 );
}
void main ( void )
{
application_init( );
for ( ; ; )
{
application_task( );
}
}
// ------------------------------------------------------------------------ END
| 2.8125 | 3 |
2024-11-18T22:25:59.677137+00:00 | 2022-08-22T22:55:15 | 92c2a2e8b6c051ba20a79c36c53034e716306522 | {
"blob_id": "92c2a2e8b6c051ba20a79c36c53034e716306522",
"branch_name": "refs/heads/master",
"committer_date": "2022-08-22T22:55:15",
"content_id": "85421ea86e181b20f11ce1f0b1289bddf3168e02",
"detected_licenses": [
"BSD-3-Clause"
],
"directory_id": "4e03abc5b44e6da6438da2934a46c098eaacd782",
"extension": "h",
"filename": "gsPlatformThread.h",
"fork_events_count": 9,
"gha_created_at": "2018-10-15T13:55:38",
"gha_event_created_at": "2021-08-06T22:04:22",
"gha_language": "C",
"gha_license_id": "BSD-3-Clause",
"github_id": 153122365,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 5863,
"license": "BSD-3-Clause",
"license_type": "permissive",
"path": "/src/GameSpy/common/gsPlatformThread.h",
"provenance": "stackv2-0115.json.gz:147157",
"repo_name": "OpenXRay/GameSpy",
"revision_date": "2022-08-22T22:55:15",
"revision_id": "1c9eb9af6be4602bceb7b1913c7405f6bb76bea1",
"snapshot_id": "31195110652dae630b70851b7b054a8d57d3a94b",
"src_encoding": "UTF-8",
"star_events_count": 3,
"url": "https://raw.githubusercontent.com/OpenXRay/GameSpy/1c9eb9af6be4602bceb7b1913c7405f6bb76bea1/src/GameSpy/common/gsPlatformThread.h",
"visit_date": "2022-08-30T17:09:42.639021"
} | stackv2 | ///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
#ifndef __GSPLATFORMTHREAD_H__
#define __GSPLATFORMTHREAD_H__
#include "gsPlatform.h"
#ifdef __cplusplus
extern "C" {
#endif
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
// Thread types
#if defined(_WIN32)
typedef CRITICAL_SECTION GSICriticalSection;
typedef HANDLE GSISemaphoreID;
typedef HANDLE GSIThreadID;
typedef DWORD (WINAPI *GSThreadFunc)(void *arg);
#elif defined(_PS2)
typedef int GSIThreadID;
typedef int GSISemaphoreID;
typedef struct
{
// A critical section is a re-entrant semaphore
GSISemaphoreID mSemaphore;
GSIThreadID mOwnerThread;
gsi_u32 mEntryCount; // track re-entry
gsi_u32 mPad; // make 16bytes
} GSICriticalSection;
typedef void (*GSThreadFunc)(void *arg);
#elif defined(_NITRO)
typedef OSMutex GSICriticalSection;
typedef struct
{
OSMutex mLock;
gsi_i32 mValue;
gsi_i32 mMax;
} GSISemaphoreID;
typedef struct
{
OSThread mThread;
void * mStack;
} GSIThreadID;
typedef void (*GSThreadFunc)(void *arg);
#elif defined(_REVOLUTION)
typedef OSMutex GSICriticalSection;
typedef OSSemaphore GSISemaphoreID;
typedef struct
{
OSThread mThread;
void * mStack;
} GSIThreadID;
typedef void *(*GSThreadFunc)(void *arg);
#elif defined(_PSP)
// Todo: Test PSP thread code, then remove this define
#define GSI_NO_THREADS
typedef int GSIThreadID;
typedef int GSISemaphoreID;
typedef struct
{
// A critical section is a re-entrant semaphore
GSISemaphoreID mSemaphore;
GSIThreadID mOwnerThread;
gsi_u32 mEntryCount; // track re-entry
gsi_u32 mPad; // make 16bytes
} GSICriticalSection;
typedef void (*GSThreadFunc)(void *arg);
#elif defined(_PS3)
// Todo: Test PS3 ppu thread code, then remove this define
#define GSI_NO_THREADS
typedef int GSIThreadID;
typedef int GSISemaphoreID;
typedef struct
{
// A critical section is a re-entrant semaphore
GSISemaphoreID mSemaphore;
GSIThreadID mOwnerThread;
gsi_u32 mEntryCount; // track re-entry
gsi_u32 mPad; // make 16bytes
} GSICriticalSection;
typedef void (*GSThreadFunc)(void *arg);
#elif defined(_UNIX) //_LINUX || _MACOSX
typedef pthread_mutex_t GSICriticalSection;
typedef struct
{
pthread_mutex_t mLock;
gsi_i32 mValue;
gsi_i32 mMax;
} GSISemaphoreID;
typedef struct
{
pthread_t thread;
pthread_attr_t attr;
} GSIThreadID;
typedef void (*GSThreadFunc)(void *arg);
#else
#define GSI_NO_THREADS
#endif
#if defined(WIN32)
#define GSI_INFINITE INFINITE
#else
#define GSI_INFINITE (gsi_u32)(-1)
#endif
#if !defined(GSI_NO_THREADS)
// The increment/read operations must not be preempted
#if defined(_WIN32)
#define gsiInterlockedIncrement(a) InterlockedIncrement((long*)a)
#define gsiInterlockedDecrement(a) InterlockedDecrement((long*)a)
#elif defined(_PS2)
gsi_u32 gsiInterlockedIncrement(gsi_u32* num);
gsi_u32 gsiInterlockedDecrement(gsi_u32* num);
#elif defined(_PS3)
// TODO - threading in PS3 uses pthreads, just like Linux
#elif defined(_NITRO)
gsi_u32 gsiInterlockedIncrement(gsi_u32* num);
gsi_u32 gsiInterlockedDecrement(gsi_u32* num);
#elif defined(_REVOLUTION)
gsi_u32 gsiInterlockedIncrement(gsi_u32* num);
gsi_u32 gsiInterlockedDecrement(gsi_u32* num);
#elif defined(_UNIX)
gsi_u32 gsiInterlockedIncrement(gsi_u32* num);
gsi_u32 gsiInterlockedDecrement(gsi_u32* num);
#endif
#else
// Don't worry about concurrancy when GSI_NO_THREADS is defined
#define gsiInterlockedIncrement(a) (++(*a))
#define gsiInterlockedDecrement(a) (--(*a))
#endif
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
#if !defined(GSI_NO_THREADS)
int gsiStartThread(GSThreadFunc aThreadFunc, gsi_u32 theStackSize, void *arg, GSIThreadID* theThreadIdOut);
void gsiCancelThread(GSIThreadID theThreadID);
void gsiExitThread(GSIThreadID theThreadID);
void gsiCleanupThread(GSIThreadID theThreadID);
// Thread Synchronization - Startup/Shutdown
gsi_u32 gsiHasThreadShutdown(GSIThreadID theThreadID);
// Thread Synchronization - Critical Section
void gsiInitializeCriticalSection(GSICriticalSection *theCrit);
void gsiEnterCriticalSection(GSICriticalSection *theCrit);
void gsiLeaveCriticalSection(GSICriticalSection *theCrit);
void gsiDeleteCriticalSection(GSICriticalSection *theCrit);
// Thread Synchronization - Semaphore
GSISemaphoreID gsiCreateSemaphore(gsi_i32 theInitialCount, gsi_i32 theMaxCount, char* theName);
gsi_u32 gsiWaitForSemaphore(GSISemaphoreID theSemaphore, gsi_u32 theTimeoutMs);
void gsiReleaseSemaphore(GSISemaphoreID theSemaphore, gsi_i32 theReleaseCount);
void gsiCloseSemaphore(GSISemaphoreID theSemaphore);
#else
// NO THREADS - stub everything to unused
#define gsiStartThread(a, b, c, d) (-1) // must return something
#define gsiCancelThread(a)
#define gsiExitThread(a)
#define gsiCleanupThread(a)
#define gsiHasThreadShutdown(a) (1) // must return something
#define gsiInitializeCriticalSection(a)
#define gsiEnterCriticalSection(a)
#define gsiLeaveCriticalSection(a)
#define gsiDeleteCriticalSection(a)
#define gsiCreateSemaphore(a,b,c) (-1)
#define gsiWaitForSemaphore(a,b) (0)
#define gsiReleaseSemaphore(a,b)
#define gsiCloseSemaphore(a)
#endif // GSI_NO_THREADS
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
#ifdef __cplusplus
}
#endif
#endif // __GSPLATFORMTHREAD_H__
| 2.28125 | 2 |
2024-11-18T22:26:00.474093+00:00 | 2018-09-08T21:11:03 | 156cc5bf1003cff03c52ce5369e9aed7a9861ca3 | {
"blob_id": "156cc5bf1003cff03c52ce5369e9aed7a9861ca3",
"branch_name": "refs/heads/master",
"committer_date": "2018-09-08T21:11:03",
"content_id": "99a57ee007547083ec9db864324e31bb279c5d9f",
"detected_licenses": [
"MIT"
],
"directory_id": "eecbf6324c35ea3f5beb1518813f9587a249edc2",
"extension": "c",
"filename": "DJB2.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 147966785,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 320,
"license": "MIT",
"license_type": "permissive",
"path": "/src/DJB2.c",
"provenance": "stackv2-0115.json.gz:147677",
"repo_name": "PyDever/c-hash",
"revision_date": "2018-09-08T21:11:03",
"revision_id": "56903d50bdc3453993863879c0d0eb3348548e60",
"snapshot_id": "474745b983c32678ea4c0d5b5eaa20791f795f45",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/PyDever/c-hash/56903d50bdc3453993863879c0d0eb3348548e60/src/DJB2.c",
"visit_date": "2020-03-28T08:27:18.575948"
} | stackv2 |
#include <stdio.h>
#include <string.h>
unsigned long DJB2 (unsigned char *str) {
unsigned long hash = 5381;
int c;
while (c = *str++)
hash = ((hash << 5) + hash) + c; /* hash * 33 + c */
return hash;
}
int main (void) {
unsigned long hash = DJB2("hello, world!");
printf("%lu\n", hash);
return 0;
}
| 2.953125 | 3 |
2024-11-18T22:26:00.561793+00:00 | 2017-10-29T13:21:04 | 85006ebc2b1d9027dd275cf15e86c7ee5b819263 | {
"blob_id": "85006ebc2b1d9027dd275cf15e86c7ee5b819263",
"branch_name": "refs/heads/master",
"committer_date": "2017-10-29T13:21:04",
"content_id": "f0e25fa1f7cdadc66b7aa990a59edbeaf7a82abe",
"detected_licenses": [
"MIT"
],
"directory_id": "cbedf7235a4a971cde7959ee74cfb41c46ec0b7b",
"extension": "c",
"filename": "box.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 101375229,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2126,
"license": "MIT",
"license_type": "permissive",
"path": "/opengl/cg_assignment/assignment/box.c",
"provenance": "stackv2-0115.json.gz:147809",
"repo_name": "ah-khalil/Computer-Graphics",
"revision_date": "2017-10-29T13:21:04",
"revision_id": "29a94897fd65ae33e47045c612a54a7ade18d877",
"snapshot_id": "ab9d64a7632fdacf84c7388509897174a6deef74",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/ah-khalil/Computer-Graphics/29a94897fd65ae33e47045c612a54a7ade18d877/opengl/cg_assignment/assignment/box.c",
"visit_date": "2021-01-20T03:56:24.333198"
} | stackv2 | #include "box.h"
//function: create_box
//use: creates a box with a wooden texture surface
void create_box(GLfloat start_x, GLfloat start_y, GLfloat start_z, GLfloat size, GLuint texture_id) {
GLfloat no_mat[] = { 0.0f, 0.0f, 0.0f, 1.0f };
GLfloat mat_diffuse[] = { 0.1f, 0.5f, 0.8f, 1.0f };
const GLfloat high_shininess = 100.0f;
glEnable(GL_TEXTURE_2D);
glEnable(GL_COLOR_MATERIAL);
glMaterialfv(GL_FRONT, GL_AMBIENT, no_mat);
glMaterialfv(GL_FRONT, GL_DIFFUSE, mat_diffuse);
glMaterialf(GL_FRONT, GL_SHININESS, high_shininess);
glBindTexture(GL_TEXTURE_2D, texture_id);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glPushMatrix();
glTranslatef((size / 2.0) + 0.5, 0.0f, 0.0f);
//texture and normal coordinates done in QUADS
glBegin(GL_QUADS);
//Front
glNormal3f(0.0f, 0.0f, 1.0f);
glTexCoord2f(0.0f, 0.0f); glVertex3f(start_x, start_y, start_z);
glTexCoord2f(0.0f, 1.0f); glVertex3f(size, start_y, start_z);
glTexCoord2f(1.0f, 1.0f); glVertex3f(size, size, start_z);
glTexCoord2f(1.0f, 0.0f); glVertex3f(start_x, size, start_z);
//Right
glNormal3f(1.0f, 0.0f, 0.0f);
glTexCoord2f(0.0f, 0.0f); glVertex3f(size, start_y, start_z);
glTexCoord2f(1.0f, 0.0f); glVertex3f(size, start_y, -size);
glTexCoord2f(1.0f, 1.0f); glVertex3f(size, size, -size);
glTexCoord2f(0.0f, 1.0f); glVertex3f(size, size, start_z);
//Back
glNormal3f(0.0f, 0.0f, -1.0f);
glTexCoord2f(0.0f, 0.0f); glVertex3f(size, start_y, -size);
glTexCoord2f(1.0f, 0.0f); glVertex3f(start_x, start_y, -size);
glTexCoord2f(1.0f, 1.0f); glVertex3f(start_x, size, -size);
glTexCoord2f(0.0f, 1.0f); glVertex3f(size, size, -size);
//Left
glNormal3f(-1.0f, 0.0f, 0.0f);
glTexCoord2f(0.0f, 0.0f); glVertex3f(start_x, start_y, start_z);
glTexCoord2f(1.0f, 0.0f); glVertex3f(start_x, start_y, -size);
glTexCoord2f(1.0f, 1.0f); glVertex3f(start_x, size, -size);
glTexCoord2f(0.0f, 1.0f); glVertex3f(start_x, size, start_z);
glEnd();
glPopMatrix();
glDisable(GL_TEXTURE_2D);
glDisable(GL_COLOR_MATERIAL);
}
| 2.75 | 3 |
2024-11-18T22:26:01.407067+00:00 | 2023-07-07T18:41:40 | c4f5b640558ee5f30d338ef85ecc96ca807c4400 | {
"blob_id": "c4f5b640558ee5f30d338ef85ecc96ca807c4400",
"branch_name": "refs/heads/master",
"committer_date": "2023-07-07T18:41:40",
"content_id": "8eace5d9d0f8b1e707a403836529475d6198c78d",
"detected_licenses": [
"BSD-3-Clause"
],
"directory_id": "c26d7b0ed875357278e61627da2da0650da77986",
"extension": "c",
"filename": "check_out.c",
"fork_events_count": 59,
"gha_created_at": "2014-04-09T13:25:46",
"gha_event_created_at": "2023-07-18T07:35:36",
"gha_language": "C",
"gha_license_id": "BSD-3-Clause",
"github_id": 18598087,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 887,
"license": "BSD-3-Clause",
"license_type": "permissive",
"path": "/src/games/trek/check_out.c",
"provenance": "stackv2-0115.json.gz:148067",
"repo_name": "RetroBSD/retrobsd",
"revision_date": "2023-07-07T18:41:40",
"revision_id": "486f81f6abff01c7dcc207235cd2979b226a95ff",
"snapshot_id": "5343d9e3c424637fc3ad5b03fe720b2744490025",
"src_encoding": "UTF-8",
"star_events_count": 282,
"url": "https://raw.githubusercontent.com/RetroBSD/retrobsd/486f81f6abff01c7dcc207235cd2979b226a95ff/src/games/trek/check_out.c",
"visit_date": "2023-09-02T23:12:05.110883"
} | stackv2 | /*
* Copyright (c) 1980 Regents of the University of California.
* All rights reserved. The Berkeley software License Agreement
* specifies the terms and conditions for redistribution.
*/
# include "trek.h"
/*
** CHECK IF A DEVICE IS OUT
**
** The indicated device is checked to see if it is disabled. If
** it is, an attempt is made to use the starbase device. If both
** of these fails, it returns non-zero (device is REALLY out),
** otherwise it returns zero (I can get to it somehow).
**
** It prints appropriate messages too.
*/
int
check_out(device)
int device;
{
register int dev;
dev = device;
/* check for device ok */
if (!damaged(dev))
return (0);
/* report it as being dead */
out(dev);
/* but if we are docked, we can go ahead anyhow */
if (Ship.cond != DOCKED)
return (1);
printf(" Using starbase %s\n", Device[dev].name);
return (0);
}
| 2.5 | 2 |
2024-11-18T22:26:01.488157+00:00 | 2009-05-28T04:29:43 | 59bf2aaf2299713932c198b145636491e0574de5 | {
"blob_id": "59bf2aaf2299713932c198b145636491e0574de5",
"branch_name": "refs/heads/master",
"committer_date": "2009-05-28T04:29:43",
"content_id": "80901f5753c022826da7d58e1b0183fb23da204e",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "dc933e6c4af6db8e5938612935bb51ead04da9b3",
"extension": "c",
"filename": "drm_rights_manager.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 51474005,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 19882,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/android-x86/frameworks/base/media/libdrm/mobile1/src/objmng/drm_rights_manager.c",
"provenance": "stackv2-0115.json.gz:148196",
"repo_name": "leotfrancisco/patch-hosting-for-android-x86-support",
"revision_date": "2009-05-28T04:29:43",
"revision_id": "e932645af3ff9515bd152b124bb55479758c2344",
"snapshot_id": "213f0b28a7171570a77a3cec48a747087f700928",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/leotfrancisco/patch-hosting-for-android-x86-support/e932645af3ff9515bd152b124bb55479758c2344/android-x86/frameworks/base/media/libdrm/mobile1/src/objmng/drm_rights_manager.c",
"visit_date": "2021-01-10T08:40:36.731838"
} | stackv2 | /*
* Copyright (C) 2007 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <drm_rights_manager.h>
#include <drm_inner.h>
#include <drm_file.h>
#include <drm_i18n.h>
static int32_t drm_getString(uint8_t* string, int32_t len, int32_t handle)
{
int32_t i;
for (i = 0; i < len; i++) {
if (DRM_FILE_FAILURE == DRM_file_read(handle, &string[i], 1))
return FALSE;
if (string[i] == '\n') {
string[i + 1] = '\0';
break;
}
}
return TRUE;
}
static int32_t drm_putString(uint8_t* string, int32_t handle)
{
int32_t i = 0;
for (i = 0;; i++) {
if (string[i] == '\0')
break;
if (DRM_FILE_FAILURE == DRM_file_write(handle, &string[i], 1))
return FALSE;
}
return TRUE;
}
static int32_t drm_writeToUidTxt(uint8_t* Uid, int32_t* id)
{
int32_t length;
int32_t i;
uint8_t idStr[8];
int32_t idMax;
uint8_t(*uidStr)[256];
uint16_t nameUcs2[MAX_FILENAME_LEN];
int32_t nameLen;
int32_t bytesConsumed;
int32_t handle;
int32_t fileRes;
if (*id < 1)
return FALSE;
/* convert in ucs2 */
nameLen = strlen(DRM_UID_FILE_PATH);
nameLen = DRM_i18n_mbsToWcs(DRM_CHARSET_UTF8,
(uint8_t *)DRM_UID_FILE_PATH,
nameLen,
nameUcs2,
MAX_FILENAME_LEN,
&bytesConsumed);
fileRes = DRM_file_open(nameUcs2,
nameLen,
DRM_FILE_MODE_READ,
&handle);
if (DRM_FILE_SUCCESS != fileRes) {
DRM_file_open(nameUcs2,
nameLen,
DRM_FILE_MODE_WRITE,
&handle);
DRM_file_write(handle, (uint8_t *)"0\n", 2);
DRM_file_close(handle);
DRM_file_open(nameUcs2,
nameLen,
DRM_FILE_MODE_READ,
&handle);
}
if (!drm_getString(idStr, 8, handle)) {
DRM_file_close(handle);
return FALSE;
}
idMax = atoi((char *)idStr);
if (idMax < *id)
uidStr = malloc((idMax + 1) * 256);
else
uidStr = malloc(idMax * 256);
for (i = 0; i < idMax; i++) {
if (!drm_getString(uidStr[i], 256, handle)) {
DRM_file_close(handle);
free(uidStr);
return FALSE;
}
}
length = strlen((char *)Uid);
strcpy((char *)uidStr[*id - 1], (char *)Uid);
uidStr[*id - 1][length] = '\n';
uidStr[*id - 1][length + 1] = '\0';
if (idMax < (*id))
idMax++;
DRM_file_close(handle);
DRM_file_open(nameUcs2,
nameLen,
DRM_FILE_MODE_WRITE,
&handle);
sprintf((char *)idStr, "%d", idMax);
if (!drm_putString(idStr, handle)) {
DRM_file_close(handle);
free(uidStr);
return FALSE;
}
if (DRM_FILE_FAILURE == DRM_file_write(handle, (uint8_t *)"\n", 1)) {
DRM_file_close(handle);
free(uidStr);
return FALSE;
}
for (i = 0; i < idMax; i++) {
if (!drm_putString(uidStr[i], handle)) {
DRM_file_close(handle);
free(uidStr);
return FALSE;
}
}
if (DRM_FILE_FAILURE == DRM_file_write(handle, (uint8_t *)"\n", 1)) {
DRM_file_close(handle);
free(uidStr);
return FALSE;
}
DRM_file_close(handle);
free(uidStr);
return TRUE;
}
/* See objmng_files.h */
int32_t drm_readFromUidTxt(uint8_t* Uid, int32_t* id, int32_t option)
{
int32_t i;
uint8_t p[256] = { 0 };
uint8_t idStr[8];
int32_t idMax = 0;
uint16_t nameUcs2[MAX_FILENAME_LEN];
int32_t nameLen = 0;
int32_t bytesConsumed;
int32_t handle;
int32_t fileRes;
if (NULL == id || NULL == Uid)
return FALSE;
DRM_file_startup();
/* convert in ucs2 */
nameLen = strlen(DRM_UID_FILE_PATH);
nameLen = DRM_i18n_mbsToWcs(DRM_CHARSET_UTF8,
(uint8_t *)DRM_UID_FILE_PATH,
nameLen,
nameUcs2,
MAX_FILENAME_LEN,
&bytesConsumed);
fileRes = DRM_file_open(nameUcs2,
nameLen,
DRM_FILE_MODE_READ,
&handle);
if (DRM_FILE_SUCCESS != fileRes) {
DRM_file_open(nameUcs2,
nameLen,
DRM_FILE_MODE_WRITE,
&handle);
DRM_file_write(handle, (uint8_t *)"0\n", 2);
DRM_file_close(handle);
DRM_file_open(nameUcs2,
nameLen,
DRM_FILE_MODE_READ,
&handle);
}
if (!drm_getString(idStr, 8, handle)) {
DRM_file_close(handle);
return FALSE;
}
idMax = atoi((char *)idStr);
if (option == GET_UID) {
if (*id < 1 || *id > idMax) {
DRM_file_close(handle);
return FALSE;
}
for (i = 1; i <= *id; i++) {
if (!drm_getString(Uid, 256, handle)) {
DRM_file_close(handle);
return FALSE;
}
}
DRM_file_close(handle);
return TRUE;
}
if (option == GET_ID) {
*id = -1;
for (i = 1; i <= idMax; i++) {
if (!drm_getString(p, 256, handle)) {
DRM_file_close(handle);
return FALSE;
}
if (strstr((char *)p, (char *)Uid) != NULL
&& strlen((char *)p) == strlen((char *)Uid) + 1) {
*id = i;
DRM_file_close(handle);
return TRUE;
}
if ((*id == -1) && (strlen((char *)p) < 3))
*id = i;
}
if (*id != -1) {
DRM_file_close(handle);
return FALSE;
}
*id = idMax + 1;
DRM_file_close(handle);
return FALSE;
}
DRM_file_close(handle);
return FALSE;
}
static int32_t drm_acquireId(uint8_t* uid, int32_t* id)
{
if (TRUE == drm_readFromUidTxt(uid, id, GET_ID))
return TRUE;
drm_writeToUidTxt(uid, id);
return FALSE; /* The Uid is not exit, then return FALSE indicate it */
}
int32_t drm_writeOrReadInfo(int32_t id, T_DRM_Rights* Ro, int32_t* RoAmount, int32_t option)
{
uint8_t fullname[MAX_FILENAME_LEN] = {0};
int32_t tmpRoAmount;
uint16_t nameUcs2[MAX_FILENAME_LEN];
int32_t nameLen = 0;
int32_t bytesConsumed;
int32_t handle;
int32_t fileRes;
sprintf((char *)fullname, ANDROID_DRM_CORE_PATH"%d"EXTENSION_NAME_INFO, id);
/* convert in ucs2 */
nameLen = strlen((char *)fullname);
nameLen = DRM_i18n_mbsToWcs(DRM_CHARSET_UTF8,
fullname,
nameLen,
nameUcs2,
MAX_FILENAME_LEN,
&bytesConsumed);
fileRes = DRM_file_open(nameUcs2,
nameLen,
DRM_FILE_MODE_READ,
&handle);
if (DRM_FILE_SUCCESS != fileRes) {
if (GET_ALL_RO == option || GET_A_RO == option)
return FALSE;
if (GET_ROAMOUNT == option) {
*RoAmount = -1;
return TRUE;
}
}
DRM_file_close(handle);
DRM_file_open(nameUcs2,
nameLen,
DRM_FILE_MODE_READ | DRM_FILE_MODE_WRITE,
&handle);
switch(option) {
case GET_ROAMOUNT:
if (DRM_FILE_FAILURE == DRM_file_read(handle, (uint8_t*)RoAmount, sizeof(int32_t))) {
DRM_file_close(handle);
return FALSE;
}
break;
case GET_ALL_RO:
DRM_file_setPosition(handle, sizeof(int32_t));
if (DRM_FILE_FAILURE == DRM_file_read(handle, (uint8_t*)Ro, (*RoAmount) * sizeof(T_DRM_Rights))) {
DRM_file_close(handle);
return FALSE;
}
break;
case SAVE_ALL_RO:
if (DRM_FILE_FAILURE == DRM_file_write(handle, (uint8_t*)RoAmount, sizeof(int32_t))) {
DRM_file_close(handle);
return FALSE;
}
if (NULL != Ro && *RoAmount >= 1) {
if (DRM_FILE_FAILURE == DRM_file_write(handle, (uint8_t*) Ro, (*RoAmount) * sizeof(T_DRM_Rights))) {
DRM_file_close(handle);
return FALSE;
}
}
break;
case GET_A_RO:
DRM_file_setPosition(handle, sizeof(int32_t) + (*RoAmount - 1) * sizeof(T_DRM_Rights));
if (DRM_FILE_FAILURE == DRM_file_read(handle, (uint8_t*)Ro, sizeof(T_DRM_Rights))) {
DRM_file_close(handle);
return FALSE;
}
break;
case SAVE_A_RO:
DRM_file_setPosition(handle, sizeof(int32_t) + (*RoAmount - 1) * sizeof(T_DRM_Rights));
if (DRM_FILE_FAILURE == DRM_file_write(handle, (uint8_t*)Ro, sizeof(T_DRM_Rights))) {
DRM_file_close(handle);
return FALSE;
}
DRM_file_setPosition(handle, 0);
if (DRM_FILE_FAILURE == DRM_file_read(handle, (uint8_t*)&tmpRoAmount, sizeof(int32_t))) {
DRM_file_close(handle);
return FALSE;
}
if (tmpRoAmount < *RoAmount) {
DRM_file_setPosition(handle, 0);
DRM_file_write(handle, (uint8_t*)RoAmount, sizeof(int32_t));
}
break;
default:
DRM_file_close(handle);
return FALSE;
}
DRM_file_close(handle);
return TRUE;
}
int32_t drm_appendRightsInfo(T_DRM_Rights* rights)
{
int32_t id;
int32_t roAmount;
if (NULL == rights)
return FALSE;
drm_acquireId(rights->uid, &id);
if (FALSE == drm_writeOrReadInfo(id, NULL, &roAmount, GET_ROAMOUNT))
return FALSE;
if (-1 == roAmount)
roAmount = 0;
/* The RO amount increase */
roAmount++;
/* Save the rights information */
if (FALSE == drm_writeOrReadInfo(id, rights, &roAmount, SAVE_A_RO))
return FALSE;
return TRUE;
}
int32_t drm_getMaxIdFromUidTxt()
{
uint8_t idStr[8];
int32_t idMax = 0;
uint16_t nameUcs2[MAX_FILENAME_LEN] = {0};
int32_t nameLen = 0;
int32_t bytesConsumed;
int32_t handle;
int32_t fileRes;
/* convert in ucs2 */
nameLen = strlen(DRM_UID_FILE_PATH);
nameLen = DRM_i18n_mbsToWcs(DRM_CHARSET_UTF8,
(uint8_t *)DRM_UID_FILE_PATH,
nameLen,
nameUcs2,
MAX_FILENAME_LEN,
&bytesConsumed);
fileRes = DRM_file_open(nameUcs2,
nameLen,
DRM_FILE_MODE_READ,
&handle);
/* this means the uid.txt file is not exist, so there is not any DRM object */
if (DRM_FILE_SUCCESS != fileRes)
return 0;
if (!drm_getString(idStr, 8, handle)) {
DRM_file_close(handle);
return -1;
}
DRM_file_close(handle);
idMax = atoi((char *)idStr);
return idMax;
}
int32_t drm_removeIdInfoFile(int32_t id)
{
uint8_t filename[MAX_FILENAME_LEN] = {0};
uint16_t nameUcs2[MAX_FILENAME_LEN];
int32_t nameLen = 0;
int32_t bytesConsumed;
if (id <= 0)
return FALSE;
sprintf((char *)filename, ANDROID_DRM_CORE_PATH"%d"EXTENSION_NAME_INFO, id);
/* convert in ucs2 */
nameLen = strlen((char *)filename);
nameLen = DRM_i18n_mbsToWcs(DRM_CHARSET_UTF8,
filename,
nameLen,
nameUcs2,
MAX_FILENAME_LEN,
&bytesConsumed);
if (DRM_FILE_SUCCESS != DRM_file_delete(nameUcs2, nameLen))
return FALSE;
return TRUE;
}
int32_t drm_updateUidTxtWhenDelete(int32_t id)
{
uint16_t nameUcs2[MAX_FILENAME_LEN];
int32_t nameLen = 0;
int32_t bytesConsumed;
int32_t handle;
int32_t fileRes;
int32_t bufferLen;
uint8_t *buffer;
uint8_t idStr[8];
int32_t idMax;
if (id <= 0)
return FALSE;
nameLen = strlen(DRM_UID_FILE_PATH);
nameLen = DRM_i18n_mbsToWcs(DRM_CHARSET_UTF8,
(uint8_t *)DRM_UID_FILE_PATH,
nameLen,
nameUcs2,
MAX_FILENAME_LEN,
&bytesConsumed);
bufferLen = DRM_file_getFileLength(nameUcs2, nameLen);
if (bufferLen <= 0)
return FALSE;
buffer = (uint8_t *)malloc(bufferLen);
if (NULL == buffer)
return FALSE;
fileRes = DRM_file_open(nameUcs2,
nameLen,
DRM_FILE_MODE_READ,
&handle);
if (DRM_FILE_SUCCESS != fileRes) {
free(buffer);
return FALSE;
}
drm_getString(idStr, 8, handle);
idMax = atoi((char *)idStr);
bufferLen -= strlen((char *)idStr);
fileRes = DRM_file_read(handle, buffer, bufferLen);
buffer[bufferLen] = '\0';
DRM_file_close(handle);
/* handle this buffer */
{
uint8_t *pStart, *pEnd;
int32_t i, movLen;
pStart = buffer;
pEnd = pStart;
for (i = 0; i < id; i++) {
if (pEnd != pStart)
pStart = ++pEnd;
while ('\n' != *pEnd)
pEnd++;
if (pStart == pEnd)
pStart--;
}
movLen = bufferLen - (pEnd - buffer);
memmove(pStart, pEnd, movLen);
bufferLen -= (pEnd - pStart);
}
if (DRM_FILE_SUCCESS != DRM_file_delete(nameUcs2, nameLen)) {
free(buffer);
return FALSE;
}
fileRes = DRM_file_open(nameUcs2,
nameLen,
DRM_FILE_MODE_WRITE,
&handle);
if (DRM_FILE_SUCCESS != fileRes) {
free(buffer);
return FALSE;
}
sprintf((char *)idStr, "%d", idMax);
drm_putString(idStr, handle);
DRM_file_write(handle, (uint8_t*)"\n", 1);
DRM_file_write(handle, buffer, bufferLen);
free(buffer);
DRM_file_close(handle);
return TRUE;
}
int32_t drm_getKey(uint8_t* uid, uint8_t* KeyValue)
{
T_DRM_Rights ro;
int32_t id, roAmount;
if (NULL == uid || NULL == KeyValue)
return FALSE;
if (FALSE == drm_readFromUidTxt(uid, &id, GET_ID))
return FALSE;
if (FALSE == drm_writeOrReadInfo(id, NULL, &roAmount, GET_ROAMOUNT))
return FALSE;
if (roAmount <= 0)
return FALSE;
memset(&ro, 0, sizeof(T_DRM_Rights));
roAmount = 1;
if (FALSE == drm_writeOrReadInfo(id, &ro, &roAmount, GET_A_RO))
return FALSE;
memcpy(KeyValue, ro.KeyValue, DRM_KEY_LEN);
return TRUE;
}
void drm_discardPaddingByte(uint8_t *decryptedBuf, int32_t *decryptedBufLen)
{
int32_t tmpLen = *decryptedBufLen;
int32_t i;
if (NULL == decryptedBuf || *decryptedBufLen < 0)
return;
/* Check whether the last several bytes are padding or not */
for (i = 1; i < decryptedBuf[tmpLen - 1]; i++) {
if (decryptedBuf[tmpLen - 1 - i] != decryptedBuf[tmpLen - 1])
break; /* Not the padding bytes */
}
if (i == decryptedBuf[tmpLen - 1]) /* They are padding bytes */
*decryptedBufLen = tmpLen - i;
return;
}
int32_t drm_aesDecBuffer(uint8_t * Buffer, int32_t * BufferLen, aes_decrypt_ctx ctx[1])
{
uint8_t dbuf[3 * DRM_ONE_AES_BLOCK_LEN], buf[DRM_ONE_AES_BLOCK_LEN];
uint64_t i, len, wlen = DRM_ONE_AES_BLOCK_LEN, curLen, restLen;
uint8_t *pTarget, *pTargetHead;
pTargetHead = Buffer;
pTarget = Buffer;
curLen = 0;
restLen = *BufferLen;
if (restLen > 2 * DRM_ONE_AES_BLOCK_LEN) {
len = 2 * DRM_ONE_AES_BLOCK_LEN;
} else {
len = restLen;
}
memcpy(dbuf, Buffer, (size_t)len);
restLen -= len;
Buffer += len;
if (len < 2 * DRM_ONE_AES_BLOCK_LEN) { /* The original file is less than one block in length */
len -= DRM_ONE_AES_BLOCK_LEN;
/* Decrypt from position len to position len + DRM_ONE_AES_BLOCK_LEN */
aes_decrypt((dbuf + len), (dbuf + len), ctx);
/* Undo the CBC chaining */
for (i = 0; i < len; ++i)
dbuf[i] ^= dbuf[i + DRM_ONE_AES_BLOCK_LEN];
/* Output the decrypted bytes */
memcpy(pTarget, dbuf, (size_t)len);
pTarget += len;
} else {
uint8_t *b1 = dbuf, *b2 = b1 + DRM_ONE_AES_BLOCK_LEN, *b3 = b2 + DRM_ONE_AES_BLOCK_LEN, *bt;
for (;;) { /* While some ciphertext remains, prepare to decrypt block b2 */
/* Read in the next block to see if ciphertext stealing is needed */
b3 = Buffer;
if (restLen > DRM_ONE_AES_BLOCK_LEN) {
len = DRM_ONE_AES_BLOCK_LEN;
} else {
len = restLen;
}
restLen -= len;
Buffer += len;
/* Decrypt the b2 block */
aes_decrypt((uint8_t *)b2, buf, ctx);
if (len == 0 || len == DRM_ONE_AES_BLOCK_LEN) { /* No ciphertext stealing */
/* Unchain CBC using the previous ciphertext block in b1 */
for (i = 0; i < DRM_ONE_AES_BLOCK_LEN; ++i)
buf[i] ^= b1[i];
} else { /* Partial last block - use ciphertext stealing */
wlen = len;
/* Produce last 'len' bytes of plaintext by xoring with */
/* The lowest 'len' bytes of next block b3 - C[N-1] */
for (i = 0; i < len; ++i)
buf[i] ^= b3[i];
/* Reconstruct the C[N-1] block in b3 by adding in the */
/* Last (DRM_ONE_AES_BLOCK_LEN - len) bytes of C[N-2] in b2 */
for (i = len; i < DRM_ONE_AES_BLOCK_LEN; ++i)
b3[i] = buf[i];
/* Decrypt the C[N-1] block in b3 */
aes_decrypt((uint8_t *)b3, (uint8_t *)b3, ctx);
/* Produce the last but one plaintext block by xoring with */
/* The last but two ciphertext block */
for (i = 0; i < DRM_ONE_AES_BLOCK_LEN; ++i)
b3[i] ^= b1[i];
/* Write decrypted plaintext blocks */
memcpy(pTarget, b3, DRM_ONE_AES_BLOCK_LEN);
pTarget += DRM_ONE_AES_BLOCK_LEN;
}
/* Write the decrypted plaintext block */
memcpy(pTarget, buf, (size_t)wlen);
pTarget += wlen;
if (len != DRM_ONE_AES_BLOCK_LEN) {
*BufferLen = pTarget - pTargetHead;
return 0;
}
/* Advance the buffer pointers */
bt = b1, b1 = b2, b2 = b3, b3 = bt;
}
}
return 0;
}
int32_t drm_updateDcfDataLen(uint8_t* pDcfLastData, uint8_t* keyValue, int32_t* moreBytes)
{
aes_decrypt_ctx ctx[1];
int32_t len = DRM_TWO_AES_BLOCK_LEN;
if (NULL == pDcfLastData || NULL == keyValue)
return FALSE;
aes_decrypt_key128(keyValue, ctx);
if (drm_aesDecBuffer(pDcfLastData, &len, ctx) < 0)
return FALSE;
drm_discardPaddingByte(pDcfLastData, &len);
*moreBytes = DRM_TWO_AES_BLOCK_LEN - len;
return TRUE;
}
| 2.0625 | 2 |
2024-11-18T22:26:02.703434+00:00 | 2023-08-25T04:46:28 | ea2052abbb8766a77aa3e15bd2ec2cd2dec54bfe | {
"blob_id": "ea2052abbb8766a77aa3e15bd2ec2cd2dec54bfe",
"branch_name": "refs/heads/main",
"committer_date": "2023-08-25T07:17:19",
"content_id": "f739155ee650dd81428f7cd282e7e520abb73e4e",
"detected_licenses": [
"BSD-3-Clause"
],
"directory_id": "dc7631ad46c850ad3b491c261c2da42edffabc4e",
"extension": "c",
"filename": "stt.c",
"fork_events_count": 58,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 50835018,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1024,
"license": "BSD-3-Clause",
"license_type": "permissive",
"path": "/zephyr/program/myst/src/stt.c",
"provenance": "stackv2-0115.json.gz:148712",
"repo_name": "coreboot/chrome-ec",
"revision_date": "2023-08-25T04:46:28",
"revision_id": "0bbd46a5aa22eb824b21365f21f4811c9343ca1e",
"snapshot_id": "6eab032c65da77f16a7de81da85921c2ca872ee2",
"src_encoding": "UTF-8",
"star_events_count": 66,
"url": "https://raw.githubusercontent.com/coreboot/chrome-ec/0bbd46a5aa22eb824b21365f21f4811c9343ca1e/zephyr/program/myst/src/stt.c",
"visit_date": "2023-08-25T08:30:03.833636"
} | stackv2 | /* Copyright 2023 The ChromiumOS Authors
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
/* Support code for STT temperature reporting */
#include "chipset.h"
#include "driver/temp_sensor/f75303.h"
#include "temp_sensor/pct2075.h"
#include "temp_sensor/temp_sensor.h"
int board_get_soc_temp_mk(int *temp_mk)
{
if (chipset_in_state(CHIPSET_STATE_HARD_OFF))
return EC_ERROR_NOT_POWERED;
#ifdef CONFIG_TEMP_SENSOR_PCT2075
return pct2075_get_val_mk(PCT2075_SENSOR_ID(DT_NODELABEL(soc_pct2075)),
temp_mk);
#else
return f75303_get_val_mk(F75303_SENSOR_ID(DT_NODELABEL(soc_f75303)),
temp_mk);
#endif
}
int board_get_ambient_temp_mk(int *temp_mk)
{
if (chipset_in_state(CHIPSET_STATE_HARD_OFF))
return EC_ERROR_NOT_POWERED;
#ifdef CONFIG_TEMP_SENSOR_PCT2075
return pct2075_get_val_mk(PCT2075_SENSOR_ID(DT_NODELABEL(amb_pct2075)),
temp_mk);
#else
return f75303_get_val_mk(F75303_SENSOR_ID(DT_NODELABEL(amb_f75303)),
temp_mk);
#endif
}
| 2 | 2 |
2024-11-18T22:26:02.819362+00:00 | 2023-08-02T18:12:00 | 462c62929c5346c9449500f3b65b96d1dae56af8 | {
"blob_id": "462c62929c5346c9449500f3b65b96d1dae56af8",
"branch_name": "refs/heads/master",
"committer_date": "2023-08-02T18:12:00",
"content_id": "15688b46d77ea1568eaff37286a42f91298c2080",
"detected_licenses": [
"0BSD"
],
"directory_id": "9e86aff281c0df8b0b7033dbd5c90c71a51d3600",
"extension": "c",
"filename": "qio.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 85441163,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2624,
"license": "0BSD",
"license_type": "permissive",
"path": "/qio.c",
"provenance": "stackv2-0115.json.gz:148841",
"repo_name": "SirWumpus/quix",
"revision_date": "2023-08-02T18:12:00",
"revision_id": "e1f94da278852c0157e61b4424a89149be1f4197",
"snapshot_id": "0debaf753655e566f1c0049d1fcc2ab2330c9159",
"src_encoding": "UTF-8",
"star_events_count": 8,
"url": "https://raw.githubusercontent.com/SirWumpus/quix/e1f94da278852c0157e61b4424a89149be1f4197/qio.c",
"visit_date": "2023-08-24T16:24:28.512043"
} | stackv2 | /*
qio.c
880924 ACH conversion to Atari ST & Acylon C
880925 ACH + add bonus for captured Quixes
891216 ACH Tidied up code for Sozobon C and general release of source
*/
#include "defs.h"
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#ifdef __WIN32__
# include <conio.h>
static int wait_key;
#else
# include <sys/types.h>
# include <termios.h>
static struct termios otios;
#endif
void
set_io(int wait)
{
#ifdef __WIN32__
wait_key = wait;
#else
struct termios ntios;
ntios = otios;
ntios.c_cc[VMIN] = wait;
ntios.c_cc[VTIME] = 0;
/* ntios.c_lflag |= ISIG; */
ntios.c_lflag &= ~(ICANON|ECHO|ECHONL|ECHOCTL);
/* ntios.c_oflag &= ~(OPOST); */
if (tcsetattr(0, TCSANOW, &ntios)) {
printf("Oops\n");
exit(2);
}
#endif
}
void
init_io(void)
{
setvbuf(stdin, NULL, _IONBF, 0);
setvbuf(stdout, NULL, _IONBF, 0);
#ifdef TERMIOS
if (tcgetattr(0, &otios)) {
printf("Oops\n");
exit(2);
}
set_io(0);
#endif
}
void
fini_io(void)
{
#ifdef TERMIOS
(void) tcsetattr(0, TCSANOW, &otios);
#endif
}
#ifdef __WIN32__
int
getkey(void)
{
if (wait_key || kbhit())
return getch();
return EOF;
}
#else
int
getkey(void)
{
unsigned char ch;
if (read(STDIN_FILENO, &ch, 1) == 1)
return ch;
return EOF;
}
#endif
void
quit(void)
{
#ifdef CURSORON
puts (CURSORON);
#endif
clearscreen();
fini_io();
}
void
init(void)
{
int i;
init_io();
/* Initialise ALL variables */
sparxnum=quixnum=menleft=area_left=last_killed=0;
percent=fildes=startdir=siz=maxarea=xmax=ymax=fuse=0;
bord_min=bord_max=line_min=line_max=lastx=lasty=0;
bonus_men=fuse_lit=nohighscore=0;
for( i=0; i<MAXQUIX; i++ ){
quix[i].x=quix[i].y=quix[i].direction=quix[i].d_time=quix[i].start=0;
quix[i].cought = FALSE;
} /* for */
for(i=0; i<BOUNDARY_LEN; i++) {
boundary[i].x=boundary[i].y=0;
temp[i].x=temp[i].y=0;
} /* for */
inchar = EOF;
C_UP = INT_UP;
C_DOWN = INT_DOWN;
C_LEFT = INT_LEFT;
C_RIGHT = INT_RIGHT;
bonus_men = 1;
bord_min = 2;
line_max = BOUNDARY_LEN - 2;
xmax = MAX_X - 3;
ymax = MAX_Y - 3;
maxarea = (xmax - 2) * (ymax - 2);
clearscreen();
}
void
nap(unsigned int x)
{
#ifdef HAVE_USLEEP
(void) usleep(x * NAP_FACTOR);
#else
for (x *= NAP_FACTOR; x; x--)
;
#endif
} /* nap */
void
move(int x, int y)
{
#ifdef ATARI_ST
Cconws( "\033Y" );
Cconout( y +32 );
Cconout( x +32 );
#endif
#ifdef VT52
(void) printf("\033Y%c%c", y+32, x+32);
#endif
#ifdef ANSI
(void) printf("\033[%d;%dH", y+1, x+1);
#endif
}
void
clearscreen(void)
{
print(HOME);
print(CLEARS);
} /* clearscreen */
int
ISBORDER(int X)
{
return ((X) <= bord_max);
} /* ISBORDER */
| 2.234375 | 2 |
2024-11-18T22:26:03.588289+00:00 | 2020-06-28T14:27:02 | 19b8df550b34ec07d60a036205b51dee1f4f982d | {
"blob_id": "19b8df550b34ec07d60a036205b51dee1f4f982d",
"branch_name": "refs/heads/master",
"committer_date": "2020-06-28T14:27:02",
"content_id": "ba77dc9ba75ef529c7d7b68b0d62af4bea92da7c",
"detected_licenses": [
"MIT"
],
"directory_id": "dfe44688c50737bb4292f268027fd1d8301e75f4",
"extension": "h",
"filename": "memory_allocator.h",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 180216628,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 10834,
"license": "MIT",
"license_type": "permissive",
"path": "/include/ceeds/memory_allocator.h",
"provenance": "stackv2-0115.json.gz:149491",
"repo_name": "doom/ceeds",
"revision_date": "2020-06-28T14:27:02",
"revision_id": "77337d0e109ed27dc4b55b7f3f77f9819d943df3",
"snapshot_id": "7195a3b052663a5dbe609bf1a186303b74bb8f1e",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/doom/ceeds/77337d0e109ed27dc4b55b7f3f77f9819d943df3/include/ceeds/memory_allocator.h",
"visit_date": "2021-07-15T05:40:05.805434"
} | stackv2 | /*
** Created by doom on 17/04/19.
*/
#ifndef CEEDS_MEMORY_ALLOCATOR_H
#define CEEDS_MEMORY_ALLOCATOR_H
#include <ceeds/core.h>
/**
* Memory allocator abstraction, used to build allocator-aware containers
*/
/**
* A handle to an allocator
*
* Allocator-aware objects should use such a handle in order to manage their memory without caring about
* the underlying specific allocator.
*/
typedef struct memory_allocator *memory_allocator_handle_t;
/**
* A memory allocator
*
* Such an object is used only by allocator implementers, and (under the hood) by allocation macros.
*/
struct memory_allocator
{
/**
* Allocate memory
*
* @param[in] alloc a pointer to the allocator handle used for this allocation
* @param[in] size the amount of bytes to allocate
* @param[in] align the minimum alignment required for the allocated memory
* @return a pointer to the beginning of the newly allocated memory
*
* @pre @p align must be a power of 2
*/
void *(*allocate)(memory_allocator_handle_t alloc, size_t size, size_t align);
/**
* Allocate memory, zeroing it
*
* @param[in] alloc a pointer to the allocator handle used for this allocation
* @param[in] size the amount of bytes to allocate
* @param[in] align the minimum alignment required for the allocated memory
* @return a pointer to the beginning of the newly allocated memory
*
* @pre @p align must be a power of 2
*/
void *(*zero_allocate)(memory_allocator_handle_t alloc, size_t size, size_t align);
/**
* Deallocate previously allocated memory
*
* @param[in] alloc a pointer to the allocator handle used for this allocation
* @param[in] ptr a pointer to the allocated memory
*/
void (*deallocate)(memory_allocator_handle_t alloc, void *ptr);
/**
* Resize a previously allocated memory block, keeping the data
*
* If @p ptr is NULL, this is equivalent to a regular allocation.
* If @p old_size is 0, no data will be kept
* If @p new_size is 0, this is equivalent to a regular deallocation
*
* @param[in] alloc a pointer to the allocator handle used for this allocation
* @param[in,out] ptr a pointer to the previously allocated memory
* @param[in] old_size the amount of bytes allocated for @p ptr
* @param[in] new_size the new amount of bytes to allocated
* @param[in] new_align the new minimum alignment required for the allocated memory
* @return a pointer to the beginning of the newly allocated memory
*
* @pre @p ptr must be a pointer to memory previously allocated using @p alloc, or NULL
* @pre @p new_align must be a power of 2
*/
void *(*reallocate)(memory_allocator_handle_t alloc, void *ptr, size_t old_size, size_t new_size, size_t new_align);
};
/**
* Allocate memory from a given allocator to hold an object of a given type, with a given alignment
*
* @param[in] handle a handle to the allocator to use
* @param T the type of object to allocate memory for
* @param[in] align the minimum alignment required for the allocated memory
* @return a pointer to the beginning of the newly allocated memory
*
* @pre @p align must be a power of 2
*/
#define allocator_aligned_new(handle, T, align) ((handle)->allocate((handle), sizeof(T), (align)))
/**
* Allocate memory from a given allocator to hold an object of a given type, with a given alignment, zeroing it
*
* @param[in] handle a handle to the allocator to use
* @param T the type of object to allocate memory for
* @param[in] align the minimum alignment required for the allocated memory
* @return a pointer to the beginning of the newly allocated memory
*
* @pre @p align must be a power of 2
*/
#define allocator_aligned_znew(handle, T, align) ((handle)->zero_allocate((handle), sizeof(T), (align)))
/**
* Allocate memory from a given allocator to hold an array of objects of a given type, with a given alignment
*
* @param[in] handle a handle to the allocator to use
* @param T the type of object to allocate memory for
* @param[in] n the number of elements to allocate memory for
* @param[in] align the minimum alignment required for the allocated memory
* @return a pointer to the beginning of the newly allocated memory
*
* @pre @p align must be a power of 2
*/
#define allocator_aligned_new_array(handle, T, n, align) ((handle)->allocate((handle), sizeof(T) * (n), (align)))
/**
* Allocate memory from a given allocator to hold an array of objects of a given type, with a given alignment, zeroing it
*
* @param[in] handle a handle to the allocator to use
* @param T the type of object to allocate memory for
* @param[in] n the number of elements to allocate memory for
* @param[in] align the minimum alignment required for the allocated memory
* @return a pointer to the beginning of the newly allocated memory
*
* @pre @p align must be a power of 2
*/
#define allocator_aligned_znew_array(handle, T, n, align) ((handle)->zero_allocate((handle), sizeof(T) * (n), (align)))
/**
* Change the size of the memory block allocated using a given allocator for a given array, with a given alignment.
* Data fitting in the new array will be kept.
*
* If @p ptr is NULL, this is equivalent to a regular allocation.
* If @p old_n is 0, no data will be kept
* If @p new_n is 0, this is equivalent to a regular deallocation
*
* @param[in] handle a handle to the allocator
* @param[in,out] ptr a pointer to the allocated memory
* @param T the type of object to allocate memory for
* @param[in] old_n the number of elements allocated in @p ptr
* @param[in] new_n the number of elements to allocate
* @param[in] align the minimum alignment required for the memory to allocate
* @return a pointer to the beginning of the newly allocated memory
*
* @pre @p ptr must be a pointer to memory previously allocated using @p handle, or NULL
* @pre @p align must be a power of 2
*/
#define allocator_aligned_resize_array(handle, ptr, T, old_n, new_n, align) \
((handle)->reallocate((handle), ptr, sizeof(T) * (old_n), sizeof(T) * (new_n), align))
/**
* Allocate memory from a given allocator to hold an object of a given type
*
* @param[in] handle a handle to the allocator to use
* @param T the type of object to allocate memory for
* @return a pointer to the beginning of the newly allocated memory
*/
#define allocator_new(handle, T) allocator_aligned_new(handle, T, alignof(T))
/**
* Allocate memory from a given allocator to hold an object of a given type, zeroing it
*
* @param[in] handle a handle to the allocator to use
* @param T the type of object to allocate memory for
* @return a pointer to the beginning of the newly allocated memory
*/
#define allocator_znew(handle, T) allocator_aligned_znew(handle, T, alignof(T))
/**
* Allocate memory from a given allocator to hold an array of objects of a given type
*
* @param[in] handle a handle to the allocator to use
* @param T the type of object to allocate memory for
* @param[in] n the number of elements to allocate memory for
* @return a pointer to the beginning of the newly allocated memory
*/
#define allocator_new_array(handle, T, n) allocator_aligned_new_array(handle, T, n, alignof(T))
/**
* Allocate memory from a given allocator to hold an array of objects of a given type, zeroing it
*
* @param[in] handle a handle to the allocator to use
* @param T the type of object to allocate memory for
* @param[in] n the number of elements to allocate memory for
* @return a pointer to the beginning of the newly allocated memory
*/
#define allocator_znew_array(handle, T, n) allocator_aligned_znew_array(handle, T, n, alignof(T))
/**
* Change the size of the memory block allocated using a given allocator for a given array
* Data fitting in the new array will be kept.
*
* If @p ptr is NULL, this is equivalent to a regular allocation.
* If @p old_n is 0, no data will be kept
* If @p new_n is 0, this is equivalent to a regular deallocation
*
* @param[in] handle a handle to the allocator
* @param[in,out] ptr a pointer to the allocated memory
* @param T the type of object to allocate memory for
* @param[in] old_n the number of elements allocated in @p ptr
* @param[in] new_n the number of elements to allocate
* @return a pointer to the beginning of the newly allocated memory
*
* @pre @p ptr must be a pointer to memory previously allocated using @p handle, or NULL
*/
#define allocator_resize_array(handle, ptr, T, old_n, new_n) \
allocator_aligned_resize_array(handle, ptr, T, old_n, new_n, alignof(T))
/**
* Deallocate memory previously allocated from a given allocator
*
* @param[in] handle a handle to the allocator to use
* @param[in] ptr a pointer to the memory to deallocate
*/
#define allocator_delete(handle, ptr) ((handle)->deallocate((handle), ptr))
#endif /* !CEEDS_MEMORY_ALLOCATOR_H */
| 2.765625 | 3 |
2024-11-18T22:26:03.710685+00:00 | 2022-10-15T23:51:42 | 1951b336e964423e4977ff7f7e212846312622eb | {
"blob_id": "1951b336e964423e4977ff7f7e212846312622eb",
"branch_name": "refs/heads/devel",
"committer_date": "2022-10-15T23:51:42",
"content_id": "b3f0cdc71d39c64ea42d7c3164c209e5b1efa75e",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "c7450e719c6fd9ea0513ea3e505562b21e53bcc2",
"extension": "c",
"filename": "event.c",
"fork_events_count": 108,
"gha_created_at": "2012-10-21T21:55:11",
"gha_event_created_at": "2022-11-10T01:06:30",
"gha_language": "C",
"gha_license_id": "Apache-2.0",
"github_id": 6326098,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 3884,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/libfreerdp-utils/event.c",
"provenance": "stackv2-0115.json.gz:149620",
"repo_name": "neutrinolabs/NeutrinoRDP",
"revision_date": "2022-10-15T23:51:42",
"revision_id": "50211223318a02db05b57196d03342edb0207c32",
"snapshot_id": "2892440cd469291c2b5151e440949f71059d05e0",
"src_encoding": "UTF-8",
"star_events_count": 42,
"url": "https://raw.githubusercontent.com/neutrinolabs/NeutrinoRDP/50211223318a02db05b57196d03342edb0207c32/libfreerdp-utils/event.c",
"visit_date": "2022-11-16T20:04:23.843326"
} | stackv2 | /**
* FreeRDP: A Remote Desktop Protocol client.
* Events
*
* Copyright 2011 Vic Lee
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <freerdp/utils/memory.h>
#include <freerdp/utils/event.h>
#include <freerdp/plugins/cliprdr.h>
#include <freerdp/plugins/tsmf.h>
#include <freerdp/rail.h>
static RDP_EVENT* freerdp_cliprdr_event_new(uint16 event_type)
{
RDP_EVENT* event = NULL;
switch (event_type)
{
case RDP_EVENT_TYPE_CB_MONITOR_READY:
event = (RDP_EVENT*) xnew(RDP_CB_MONITOR_READY_EVENT);
break;
case RDP_EVENT_TYPE_CB_FORMAT_LIST:
event = (RDP_EVENT*) xnew(RDP_CB_FORMAT_LIST_EVENT);
break;
case RDP_EVENT_TYPE_CB_DATA_REQUEST:
event = (RDP_EVENT*) xnew(RDP_CB_DATA_REQUEST_EVENT);
break;
case RDP_EVENT_TYPE_CB_DATA_RESPONSE:
event = (RDP_EVENT*) xnew(RDP_CB_DATA_RESPONSE_EVENT);
break;
}
return event;
}
static RDP_EVENT* freerdp_tsmf_event_new(uint16 event_type)
{
RDP_EVENT* event = NULL;
switch (event_type)
{
case RDP_EVENT_TYPE_TSMF_VIDEO_FRAME:
event = (RDP_EVENT*) xnew(RDP_VIDEO_FRAME_EVENT);
break;
case RDP_EVENT_TYPE_TSMF_REDRAW:
event = (RDP_EVENT*) xnew(RDP_REDRAW_EVENT);
break;
}
return event;
}
static RDP_EVENT* freerdp_rail_event_new(uint16 event_type)
{
RDP_EVENT* event = NULL;
event = xnew(RDP_EVENT);
return event;
}
RDP_EVENT* freerdp_event_new(uint16 event_class, uint16 event_type,
RDP_EVENT_CALLBACK on_event_free_callback, void* user_data)
{
RDP_EVENT* event = NULL;
switch (event_class)
{
case RDP_EVENT_CLASS_DEBUG:
event = xnew(RDP_EVENT);
break;
case RDP_EVENT_CLASS_CLIPRDR:
event = freerdp_cliprdr_event_new(event_type);
break;
case RDP_EVENT_CLASS_TSMF:
event = freerdp_tsmf_event_new(event_type);
break;
case RDP_EVENT_CLASS_RAIL:
event = freerdp_rail_event_new(event_type);
break;
}
if (event != NULL)
{
event->event_class = event_class;
event->event_type = event_type;
event->on_event_free_callback = on_event_free_callback;
event->user_data = user_data;
}
return event;
}
static void freerdp_cliprdr_event_free(RDP_EVENT* event)
{
switch (event->event_type)
{
case RDP_EVENT_TYPE_CB_FORMAT_LIST:
{
RDP_CB_FORMAT_LIST_EVENT* cb_event = (RDP_CB_FORMAT_LIST_EVENT*)event;
xfree(cb_event->formats);
xfree(cb_event->raw_format_data);
}
break;
case RDP_EVENT_TYPE_CB_DATA_RESPONSE:
{
RDP_CB_DATA_RESPONSE_EVENT* cb_event = (RDP_CB_DATA_RESPONSE_EVENT*)event;
xfree(cb_event->data);
}
break;
}
}
static void freerdp_tsmf_event_free(RDP_EVENT* event)
{
switch (event->event_type)
{
case RDP_EVENT_TYPE_TSMF_VIDEO_FRAME:
{
RDP_VIDEO_FRAME_EVENT* vevent = (RDP_VIDEO_FRAME_EVENT*)event;
xfree(vevent->frame_data);
xfree(vevent->visible_rects);
}
break;
}
}
static void freerdp_rail_event_free(RDP_EVENT* event)
{
}
void freerdp_event_free(RDP_EVENT* event)
{
if (event != NULL)
{
if (event->on_event_free_callback != NULL)
event->on_event_free_callback(event);
switch (event->event_class)
{
case RDP_EVENT_CLASS_CLIPRDR:
freerdp_cliprdr_event_free(event);
break;
case RDP_EVENT_CLASS_TSMF:
freerdp_tsmf_event_free(event);
break;
case RDP_EVENT_CLASS_RAIL:
freerdp_rail_event_free(event);
break;
}
xfree(event);
}
}
| 2.09375 | 2 |
2024-11-18T22:26:04.163446+00:00 | 2023-05-23T01:50:34 | 67ef12ef268813c5af79634850cbe1f3d478559a | {
"blob_id": "67ef12ef268813c5af79634850cbe1f3d478559a",
"branch_name": "refs/heads/master",
"committer_date": "2023-05-23T01:50:34",
"content_id": "cdef60d5c62c16553a4bd3d44c79cbcde5567c86",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "8fceb4702c2e1f9521793e95e87a9621debd625d",
"extension": "c",
"filename": "riscv_max_no_idx_q31.c",
"fork_events_count": 14,
"gha_created_at": "2019-12-27T02:22:55",
"gha_event_created_at": "2021-06-07T01:11:49",
"gha_language": "C",
"gha_license_id": "Apache-2.0",
"github_id": 230358080,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 3373,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/NMSIS/DSP/Source/StatisticsFunctions/riscv_max_no_idx_q31.c",
"provenance": "stackv2-0115.json.gz:150009",
"repo_name": "Nuclei-Software/NMSIS",
"revision_date": "2023-05-23T01:50:34",
"revision_id": "3d9a71ab8e090fac01ea434b045d548671814e69",
"snapshot_id": "763ba90a1aa7cfaa990872d8c42f931dd502838b",
"src_encoding": "UTF-8",
"star_events_count": 51,
"url": "https://raw.githubusercontent.com/Nuclei-Software/NMSIS/3d9a71ab8e090fac01ea434b045d548671814e69/NMSIS/DSP/Source/StatisticsFunctions/riscv_max_no_idx_q31.c",
"visit_date": "2023-05-25T11:08:41.502162"
} | stackv2 | /* ----------------------------------------------------------------------
* Project: NMSIS DSP Library
* Title: riscv_max_no_idx_q31.c
* Description: Maximum value of a q31 vector without returning the index
*
* $Date: 16 November 2021
* $Revision: V1.10.0
*
* Target Processor: RISC-V Cores
* -------------------------------------------------------------------- */
/*
* Copyright (C) 2010-2021 ARM Limited or its affiliates. All rights reserved.
* Copyright (c) 2019 Nuclei Limited. All rights reserved.
*
* SPDX-License-Identifier: Apache-2.0
*
* 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
*
* www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an AS IS BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "dsp/statistics_functions.h"
/**
@ingroup groupStats
*/
/**
@addtogroup Max
@{
*/
/**
@brief Maximum value of a q31 vector without index.
@param[in] pSrc points to the input vector
@param[in] blockSize number of samples in input vector
@param[out] pResult maximum value returned here
@return none
*/
void riscv_max_no_idx_q31(
const q31_t * pSrc,
uint32_t blockSize,
q31_t * pResult)
{
q31_t maxVal1, out; /* Temporary variables to store the output value. */
unsigned long blkCnt; /* Loop counter */
#if defined(RISCV_MATH_VECTOR)
size_t l;
const q31_t *inputx = pSrc;
vint32m8_t v_x;
vint32m1_t v_tempa;
blkCnt = blockSize;
l = vsetvl_e32m1(1);
v_tempa = vmv_s_x_i32m1(v_tempa, pSrc[0], l);
for (; (l = vsetvl_e32m8(blkCnt)) > 0; blkCnt -= l)
{
v_x = vle32_v_i32m8(inputx, l);
inputx += l;
v_tempa = vredmax_vs_i32m8_i32m1(v_tempa, v_x, v_tempa, l);
}
out = vmv_x_s_i32m1_i32(v_tempa);
#else
/* Load first input value that act as reference value for comparision */
out = *pSrc;
#if defined(RISCV_MATH_DSP) && (__RISCV_XLEN == 64)
q63_t in64;
q63_t max64 = read_q31x2((q31_t*)pSrc);
q31_t max_q31[2];
blkCnt = blockSize >> 1U;
while (blkCnt > 0U)
{
in64 = read_q31x2_ia((q31_t**)&pSrc);
max64 = __RV_SMAX32(max64, in64);
blkCnt--;
}
max_q31[0] = (q31_t)max64;
max_q31[1] = (q31_t)(max64 >> 32);
maxVal1 = max_q31[0];
if(maxVal1 < max_q31[1])
{
maxVal1 = max_q31[1];
}
out = maxVal1;
#endif /* defined(RISCV_MATH_DSP) && __RISCV_XLEN == 64 */
#if defined (RISCV_MATH_DSP) && (__RISCV_XLEN == 64)
blkCnt = blockSize & 1U;
#else
blkCnt = blockSize;
#endif /* defined (RISCV_MATH_DSP) && (__RISCV_XLEN == 64) */
while (blkCnt > 0U)
{
/* Initialize maxVal to the next consecutive values one by one */
maxVal1 = *pSrc++;
/* compare for the maximum value */
if (out < maxVal1)
{
/* Update the maximum value */
out = maxVal1;
}
/* Decrement loop counter */
blkCnt--;
}
#endif /* defined(RISCV_MATH_VECTOR) */
/* Store the maximum value into destination pointer */
*pResult = out;
}
/**
@} end of Max group
*/
| 2.234375 | 2 |
2024-11-18T22:26:04.605175+00:00 | 2021-03-27T06:08:55 | f1609cf52bbed15d6910f59da23e48ac055f444e | {
"blob_id": "f1609cf52bbed15d6910f59da23e48ac055f444e",
"branch_name": "refs/heads/main",
"committer_date": "2021-03-27T06:08:55",
"content_id": "88833009b055981ca092d52979df7afc5133f0ff",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "834cd422a7ee36c31118941ded8e0fbdbdb6a492",
"extension": "c",
"filename": "serial_ctrl.c",
"fork_events_count": 1,
"gha_created_at": "2021-03-13T06:17:09",
"gha_event_created_at": "2023-06-01T23:54:38",
"gha_language": "C",
"gha_license_id": "Apache-2.0",
"github_id": 347290313,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 12676,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/STM32_WPAN/ble/mesh/Src/serial_ctrl.c",
"provenance": "stackv2-0115.json.gz:150399",
"repo_name": "xupenghu/stm32wb55_sdk",
"revision_date": "2021-03-27T06:08:55",
"revision_id": "03210c73e9ed25e6b75a07c049488fc3d0f8bc42",
"snapshot_id": "763dec92cd95ec8c5665f3133305e3b24ebed5fb",
"src_encoding": "UTF-8",
"star_events_count": 2,
"url": "https://raw.githubusercontent.com/xupenghu/stm32wb55_sdk/03210c73e9ed25e6b75a07c049488fc3d0f8bc42/STM32_WPAN/ble/mesh/Src/serial_ctrl.c",
"visit_date": "2023-04-16T00:39:22.198673"
} | stackv2 | /**
******************************************************************************
* @file serial_ctrl.c
* @author BLE Mesh Team
* @brief Serial Control file
******************************************************************************
* @attention
*
* <h2><center>© Copyright (c) 2020 STMicroelectronics.
* All rights reserved.</center></h2>
*
* This software component is licensed by ST under Ultimate Liberty license
* SLA0044, the "License"; You may not use this file except in compliance with
* the License. You may obtain a copy of the License at:
* www.st.com/SLA0044
*
******************************************************************************
*/
/* Includes ------------------------------------------------------------------*/
#include <string.h>
#include <stdio.h>
#include <errno.h>
#include "hal_common.h"
#include "serial_if.h"
#include "serial_ctrl.h"
#include "light.h"
#include "light_lc.h"
#include "vendor.h"
#include "appli_vendor.h"
#include "generic_client.h"
#include "light_client.h"
#include "sensors_client.h"
/** @addtogroup BlueNRG_Mesh
* @{
*/
/** @addtogroup Middlewares_Serial_Interface
* @{
*/
/* Private define ------------------------------------------------------------*/
#define SERIAL_MODEL_DATA_OFFSET 15
/* Private macro -------------------------------------------------------------*/
/* Private variables ---------------------------------------------------------*/
const MODEL_OpcodeTableParam_t *Light_OpcodeTable;
const MODEL_OpcodeTableParam_t *Generic_OpcodeTable;
const MODEL_OpcodeTableParam_t *LightLC_OpcodeTable;
const MODEL_OpcodeTableParam_t *Sensor_OpcodeTable;
MOBLEUINT16 Light_OpcodeTableLength;
MOBLEUINT16 Generic_OpcodeTableLength;
MOBLEUINT16 LightLC_OpcodeTableLength;
MOBLEUINT16 Sensor_OpcodeTableLength;
extern MOBLEUINT16 Vendor_Opcodes_Table[] ;
/* Private function prototypes -----------------------------------------------*/
MOBLEUINT8 SerialCtrl_GetMinParamLength(MOBLEUINT32 opcode, const MODEL_OpcodeTableParam_t list[], MOBLEUINT16 length);
MOBLEUINT8 SerialCtrl_GetData(char *rcvdStringBuff, uint16_t rcvdStringSize, MOBLEUINT8 dataOffset, MOBLEUINT8 *data);
/* Private functions ---------------------------------------------------------*/
/**
* @brief This funcrion is used to parse the string given by the user
* @param rcvdStringBuff: buffer to store input string
* @param rcvdStringSize: length of the input string
* @retval void
*/
void SerialCtrlVendorRead_Process(char *rcvdStringBuff, uint16_t rcvdStringSize)
{
MOBLEUINT16 command = 0; /*Opcode command to be executed by the destination node*/
MOBLEUINT8 datalength = 0;
MOBLEUINT8 data [10] = {0}; /*buffer to output property variables */
MOBLE_RESULT result = MOBLE_RESULT_FAIL;
MODEL_MessageHeader_t msgHdr;
/*Initializing the parameters*/
msgHdr.elementIndex = 0;
msgHdr.peer_addr = 0;
msgHdr.dst_peer = 0;
msgHdr.ttl = 0;
msgHdr.rssi = 0;
msgHdr.rcvdAppKeyOffset = 0;
msgHdr.rcvdNetKeyOffset = 0;
sscanf(rcvdStringBuff+5, "%4hx %hx ", &msgHdr.dst_peer, &command);
for(int i = 0; i < 6 ; i++)
{
if(command == Vendor_Opcodes_Table[i])
{
result = MOBLE_RESULT_SUCCESS;
break;
}
}
datalength = SerialCtrl_GetData(rcvdStringBuff, rcvdStringSize, SERIAL_MODEL_DATA_OFFSET, data);
if(result)
{
TRACE_I(TF_SERIAL_PRINTS,"Invalid Command\r\n");
return;
}
else
{
msgHdr.peer_addr = BLEMesh_GetAddress();
result = BLEMesh_ReadRemoteData(&msgHdr,command, data, datalength);
if(result == MOBLE_RESULT_SUCCESS)
{
TRACE_I(TF_SERIAL_PRINTS,"Command Executed Successfully\r\n");
}
else
{
TRACE_I(TF_SERIAL_PRINTS,"Invalid Opcode Parameter\r\n");
}
}
}
void SerialCtrlVendorWrite_Process(char *rcvdStringBuff, uint16_t rcvdStringSize)
{
MOBLE_ADDRESS peer = 0; /*node adderess of the destination node*/
MOBLEUINT16 command = 0; /*Opcode command to be executed by the destination node*/
MOBLEUINT8 elementIndex = 0; /*default element index*/
MOBLE_RESULT result = MOBLE_RESULT_FAIL;
MOBLEBOOL response = MOBLE_FALSE;
MOBLEUINT8 data_buff[VENDOR_DATA_BUFFER_SIZE];
MOBLEUINT16 idx=0;
MOBLEUINT8 length;
MOBLEUINT8 j = 1;
sscanf(rcvdStringBuff+5, "%4hx %hx %hx", &peer,&command,&idx);
if(command == 0x000E)
{
/* Check parameter if data to be send continuously */
if (idx == 0xFF)
{
data_buff[0] = 0x01; /* data write sub command; */
length = sizeof(data_buff)-1;
for(MOBLEUINT8 i=1;i <sizeof(data_buff);i++)
{
data_buff[j] = i;
j++;
}
Appli_Vendor_SetBigDataPacket(data_buff, length, 0 , peer);
Vendor_SendDataFreq(0xFF);
TRACE_I(TF_SERIAL_PRINTS,"Command Executed Successfully\r\n");
return;
}
/* Check parameter if continuously data send operation need to stop */
else if (idx == 0x00)
{
BSP_LED_Off(LED_BLUE);
Vendor_SendDataFreq(0x00);
TRACE_I(TF_SERIAL_PRINTS,"Command Executed Successfully\r\n");
return;
}
/* Data will be sent only once */
else
{
data_buff[0] = 0x01; /* data write sub command; */
length = sizeof(data_buff)-idx;
Vendor_SendDataFreq(0x00); /* To stop sending packets periodically */
for(MOBLEUINT8 i=idx;i <sizeof(data_buff);i++)
{
data_buff[j] = i;
j++;
}
}
}
else
{
length = SerialCtrl_GetData(rcvdStringBuff, rcvdStringSize, SERIAL_MODEL_DATA_OFFSET, data_buff);
}
for(int i = 0; i < 6 ; i++)
{
if(command == Vendor_Opcodes_Table[i])
{
result = MOBLE_RESULT_SUCCESS;
break;
}
}
if(result)
{
TRACE_I(TF_SERIAL_PRINTS,"Invalid Command\r\n");
return;
}
else
{
result = BLEMesh_SetRemoteData(peer,elementIndex,command,
data_buff, length,
response, MOBLE_TRUE);
if(result == MOBLE_RESULT_SUCCESS)
{
TRACE_I(TF_SERIAL_PRINTS,"Command Executed Successfully\r\n");
}
else
{
TRACE_I(TF_SERIAL_PRINTS,"Invalid Opcode Parameter\r\n");
}
}
}
void SerialCtrl_Process(char *rcvdStringBuff, uint16_t rcvdStringSize)
{
MOBLE_ADDRESS peer = 0; /*node adderess of the destination node*/
MOBLEUINT16 command = 0; /*Opcode command to be executed by the destination node*/
MOBLEUINT8 minParamLength = 0; /*minimum number of properties required by a specific command*/
MOBLEUINT8 elementIndex = 0; /*default element index*/
MOBLEUINT8 data [10] = {0}; /*buffer to output property variables */
MOBLE_RESULT result;
MOBLEBOOL response = MOBLE_TRUE;
sscanf(rcvdStringBuff+5, "%4hx %hx ", &peer,&command);
/* Callback to store a pointer to Opcode table starting sddress and length of the table*/
#ifdef ENABLE_GENERIC_MODEL_SERVER
GenericModelServer_GetOpcodeTableCb(&Generic_OpcodeTable,&Generic_OpcodeTableLength);
#else /* Get Generic Client OpCode Table */
#ifdef ENABLE_GENERIC_MODEL_CLIENT
GenericModelClient_GetOpcodeTableCb(&Generic_OpcodeTable,&Generic_OpcodeTableLength);
#endif
#endif
#ifdef ENABLE_LIGHT_MODEL_SERVER
LightModelServer_GetOpcodeTableCb(&Light_OpcodeTable,&Light_OpcodeTableLength);
LightLcServer_GetOpcodeTableCb(&LightLC_OpcodeTable,&LightLC_OpcodeTableLength);
#else /* Get Light Client OpCode Table */
#ifdef ENABLE_LIGHT_MODEL_CLIENT
LightModelClient_GetOpcodeTableCb(&Light_OpcodeTable,&Light_OpcodeTableLength);
//Note: Light LC is included in Lighting Client Model
#endif
#endif
#ifdef ENABLE_SENSOR_MODEL_SERVER
SensorModelServer_GetOpcodeTableCb(&Sensor_OpcodeTable,&Sensor_OpcodeTableLength);
#else /* Get Sensor Client OpCode Table */
#ifdef ENABLE_SENSOR_MODEL_CLIENT
SensorsModelClient_GetOpcodeTableCb(&Sensor_OpcodeTable,&Sensor_OpcodeTableLength);
#endif
#endif
/* Minimum parameter length required for a valid opcade in Generic opcode table */
minParamLength = SerialCtrl_GetMinParamLength(command,
Generic_OpcodeTable,
Generic_OpcodeTableLength);
/* Opcode not found in Generic opcode table
Start finding for opcode in Light Table*/
if (minParamLength == 0xff)
{
minParamLength = SerialCtrl_GetMinParamLength(command,
Light_OpcodeTable,
Light_OpcodeTableLength);
}
/* Opcode not found in Light opcode table
Start finding for opcode in Light LC Table*/
if (minParamLength == 0xff)
{
minParamLength = SerialCtrl_GetMinParamLength(command,
LightLC_OpcodeTable,
LightLC_OpcodeTableLength);
}
/* Opcode not found in Light LC opcode table
Start finding for opcode in Sensor Table*/
if (minParamLength == 0xff)
{
minParamLength = SerialCtrl_GetMinParamLength(command,
Sensor_OpcodeTable,
Sensor_OpcodeTableLength);
TRACE_I(TF_SERIAL_PRINTS, "Min Parameter Length after sensor model check %d\r\n",
minParamLength);
}
if (minParamLength != 0xff) /* Opcode found in one of the models */
{
minParamLength = SerialCtrl_GetData(rcvdStringBuff,
rcvdStringSize,
SERIAL_MODEL_DATA_OFFSET,
data);
result = BLEMesh_SetRemoteData(peer,
elementIndex,
command,
data,
minParamLength,
response,
MOBLE_FALSE);
if(result == MOBLE_RESULT_SUCCESS)
{
TRACE_I(TF_SERIAL_PRINTS, "Command Executed Successfully\r\n");
}
else
{
TRACE_I(TF_SERIAL_PRINTS, "Invalid Opcode Parameter\r\n");
}
}
else
{
TRACE_I(TF_SERIAL_PRINTS, "Unknown Opcode\r\n");
}
}
/**
* @brief Returns the minimum number of parameters required by a particular Opcode
* @param opcode: Opcode of the model whose minimum number of parameters are required
* @param list:
* @param length:
* @retval MOBLEUINT16
*/
MOBLEUINT8 SerialCtrl_GetMinParamLength(MOBLEUINT32 opcode, const MODEL_OpcodeTableParam_t list[], MOBLEUINT16 length)
{
for (int i = 0; i < length; i++)
{
if (list[i].opcode == opcode)
{
return list[i].min_payload_size;
}
}
return 0xff;
}
/**
* @brief This function extract the function parameter from the string
* @param rcvdStringBuff: array of the string parsed from the serial terminal
* @param rcvdStringSize: sizeOf rcvdStringBuff
* @param dataOffset:
* @param data: Output array comprising of Data
* @param dataIndex:
* @retval MOBLEUINT8
*/
MOBLEUINT8 SerialCtrl_GetData(char *rcvdStringBuff, uint16_t rcvdStringSize, MOBLEUINT8 dataOffset, MOBLEUINT8 *data)
{
MOBLEUINT8 byteBuff[10] = {0};
MOBLEUINT8 dataIndex = 0;
int msb, lsb, byteCounter=0;
for(int i=dataOffset ; i<=(rcvdStringSize) ; i++)
{
/* check if space or NULL found */
if(rcvdStringBuff[i] == ' '||rcvdStringBuff[i] == '\0' )
{
/*if number of bytes is one*/
while(byteCounter > 0)
{
data[dataIndex++] = byteBuff[--byteCounter];
}
}
else
{
/* take two consecutive ascii characters from the rcvdStringBuff and convert to hex values */
msb = Serial_CharToHexConvert(rcvdStringBuff[i]);
lsb = Serial_CharToHexConvert(rcvdStringBuff[i + 1 ]);
/*join two hex values to make one hex value*/
byteBuff[byteCounter] = msb << 4;
byteBuff[byteCounter] |= lsb;
i++; /*increament for loop counter as two values are used */
byteCounter++; /*increament byteCounter counter*/
}
}
return dataIndex;
}
/**
* @}
*/
/**
* @}
*/
/******************* (C) COPYRIGHT 2020 STMicroelectronics *****END OF FILE****/
| 2 | 2 |
2024-11-18T22:26:04.757489+00:00 | 2019-11-12T07:04:24 | 85468a79a81f6c5e55642e65a2c1934204fef069 | {
"blob_id": "85468a79a81f6c5e55642e65a2c1934204fef069",
"branch_name": "refs/heads/master",
"committer_date": "2019-11-12T07:04:24",
"content_id": "5d5d37a3c62d818796ee826e4c9d62c7dc264ede",
"detected_licenses": [
"BSD-3-Clause"
],
"directory_id": "6b090dfe77e8d8bf937100e70341cb190213d710",
"extension": "c",
"filename": "easel.c",
"fork_events_count": 0,
"gha_created_at": "2019-11-12T08:16:49",
"gha_event_created_at": "2019-11-12T08:16:54",
"gha_language": null,
"gha_license_id": "NOASSERTION",
"github_id": 221165219,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 88018,
"license": "BSD-3-Clause",
"license_type": "permissive",
"path": "/easel.c",
"provenance": "stackv2-0115.json.gz:150527",
"repo_name": "smsaladi/easel",
"revision_date": "2019-11-12T07:04:24",
"revision_id": "d7679b5a4155bd32017e9b4fe2c8f1f316d15b6b",
"snapshot_id": "58f0a0e89059135db146d896735b615de32d16de",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/smsaladi/easel/d7679b5a4155bd32017e9b4fe2c8f1f316d15b6b/easel.c",
"visit_date": "2020-09-08T14:54:52.494856"
} | stackv2 | /* Easel's foundation.
*
* Contents:
* 1. Exception and fatal error handling.
* 2. Memory allocation/deallocation conventions.
* 3. Standard banner for Easel miniapplications.
* 4. Improved replacements for some C library functions.
* 5. Portable drop-in replacements for nonstandard C functions.
* 6. Additional string functions, esl_str*()
* 7. File path/name manipulation, including tmpfiles.
* 8. Typed comparison functions.
* 9. Unit tests.
* 10. Test driver.
* 11. Examples.
*/
#include "esl_config.h"
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include <errno.h>
#include <string.h>
#include <math.h>
#include <ctype.h>
#ifdef HAVE_UNISTD_H
#include <unistd.h>
#endif
#ifdef _POSIX_VERSION
#include <sys/stat.h>
#include <sys/types.h>
#endif
#ifdef HAVE_MPI
#include <mpi.h> /* MPI_Abort() may be used in esl_fatal() or other program killers */
#endif
#include "easel.h"
#include <syslog.h>
/*****************************************************************
* 1. Exception and fatal error handling.
*****************************************************************/
static esl_exception_handler_f esl_exception_handler = NULL;
/* Function: esl_fail()
* Synopsis: Handle a normal failure code/message before returning to caller.
*
* Purpose: A "failure" is a normal error that we want to handle
* without terminating the program; we're going to return
* control to the caller with a nonzero error code and
* (optionally) an informative error message formatted
* in <errbuf>.
*
* <esl_fail()> is called internally by the <ESL_FAIL()>
* and <ESL_XFAIL()> macros (see easel.h). The reason to
* have the failure macros call such a simple little
* function is to give us a convenient debugging
* breakpoint. For example, in a <_Validate()> routine that
* needs to do a normal return to a caller, you can set a
* breakpoint in <esl_fail()> to see exactly where the
* validation failed.
*/
void
esl_fail(char *errbuf, const char *format, ...)
{
if (format)
{
va_list ap;
/* Check whether we are running as a daemon so we can do the
* right thing about logging instead of printing errors
*/
if (getppid() != 1)
{ // we aren't running as a daemon, so print the error normally
va_start(ap, format);
if (errbuf) vsnprintf(errbuf, eslERRBUFSIZE, format, ap);
va_end(ap);
}
else vsyslog(LOG_ERR, format, ap); // SRE: TODO: check this.
// looks wrong. I think it needs va_start(), va_end().
// also see two more occurrences, below.
}
}
/* Function: esl_exception()
* Synopsis: Throw an exception.
*
* Purpose: Throw an exception. An "exception" is defined by Easel
* as an internal error that shouldn't happen and/or is
* outside the user's control; as opposed to "failures", that
* are to be expected, and within user control, and
* therefore normal. By default, exceptions are fatal.
* A program that wishes to be more robust can register
* a non-fatal exception handler.
*
* Easel programs normally call one of the exception-handling
* wrappers <ESL_EXCEPTION()> or <ESL_XEXCEPTION()>, which
* handle the overhead of passing in <use_errno>, <sourcefile>,
* and <sourceline>. <esl_exception> is rarely called directly.
*
* If no custom exception handler has been registered, the
* default behavior is to print a brief message to <stderr>
* then <abort()>, resulting in a nonzero exit code from the
* program. Depending on what <errcode>, <sourcefile>,
* <sourceline>, and the <sprintf()>-formatted <format>
* are, this output looks like:
*
* Fatal exception (source file foo.c, line 42):
* Something wicked this way came.
*
* Additionally, in an MPI parallel program, the default fatal
* handler aborts all processes (with <MPI_Abort()>), not just
* the one that called <esl_exception()>.
*
* Args: errcode - Easel error code, such as eslEINVAL. See easel.h.
* use_errno - if TRUE, also use perror() to report POSIX errno message.
* sourcefile - Name of offending source file; normally __FILE__.
* sourceline - Name of offending source line; normally __LINE__.
* format - <sprintf()> formatted exception message, followed
* by any additional necessary arguments for that
* message.
*
* Returns: void.
*
* Throws: No abnormal error conditions. (Who watches the watchers?)
*/
void
esl_exception(int errcode, int use_errno, char *sourcefile, int sourceline, char *format, ...)
{
va_list argp;
#ifdef HAVE_MPI
int mpiflag;
#endif
if (esl_exception_handler != NULL)
{ // If the custom exception handler tries to print to stderr/stdout, the error may get eaten if we're running as a daemon
// Not sure how to prevent that, since we can't control what custom handlers get written.
va_start(argp, format);
(*esl_exception_handler)(errcode, use_errno, sourcefile, sourceline, format, argp);
va_end(argp);
return;
}
else
{
/* Check whether we are running as a daemon so we can do the right thing about logging instead of printing errors */
if (getppid() != 1)
{ // we're not running as a daemon, so print the error normally
fprintf(stderr, "Fatal exception (source file %s, line %d):\n", sourcefile, sourceline);
va_start(argp, format);
vfprintf(stderr, format, argp);
va_end(argp);
fprintf(stderr, "\n");
if (use_errno && errno) perror("system error");
fflush(stderr);
}
else vsyslog(LOG_ERR, format, argp);
#ifdef HAVE_MPI
MPI_Initialized(&mpiflag); /* we're assuming we can do this, even in a corrupted, dying process...? */
if (mpiflag) MPI_Abort(MPI_COMM_WORLD, 1);
#endif
abort();
}
}
/* Function: esl_exception_SetHandler()
* Synopsis: Register a different exception handling function.
*
* Purpose: Register a different exception handling function,
* <handler>. When an exception occurs, the handler
* receives at least four arguments: <errcode>, <sourcefile>,
* <sourceline>, and <format>.
*
* <errcode> is an Easel error code, such as
* <eslEINVAL>. See <easel.h> for a list of all codes.
*
* <use_errno> is TRUE for POSIX system call failures. The
* handler may then use POSIX <errno> to format/print an
* additional message, using <perror()> or <strerror_r()>.
*
* <sourcefile> is the name of the Easel source code file
* in which the exception occurred, and <sourceline> is
* the line number.
*
* <format> is a <vprintf()>-formatted string, followed by
* a <va_list> containing any additional arguments that
* formatted message needs. Your custom exception handler
* will probably use <vfprintf()> or <vsnprintf()> to format
* its error message.
*
* Args: handler - ptr to your custom exception handler.
*
* Returns: void.
*
* Throws: (no abnormal error conditions)
*/
void
esl_exception_SetHandler(void (*handler)(int errcode, int use_errno, char *sourcefile, int sourceline, char *format, va_list argp))
{
esl_exception_handler = handler;
}
/* Function: esl_exception_ResetDefaultHandler()
* Synopsis: Restore default exception handling.
*
* Purpose: Restore default exception handling, which is to print
* a simple error message to <stderr> then <abort()> (see
* <esl_exception()>.
*
* An example where this might be useful is in a program
* that only temporarily wants to catch one or more types
* of normally fatal exceptions.
*
* If the default handler is already in effect, this
* call has no effect (is a no-op).
*
* Args: (void)
*
* Returns: (void)
*
* Throws: (no abnormal error conditions)
*/
void
esl_exception_ResetDefaultHandler(void)
{
esl_exception_handler = NULL;
}
/* Function: esl_nonfatal_handler()
* Synopsis: A trivial example of a nonfatal exception handler.
*
* Purpose: This serves two purposes. First, it is the simplest
* example of a nondefault exception handler. Second, this
* is used in test harnesses, when they have
* <eslTEST_THROWING> turned on to test that thrown errors
* are handled properly when a nonfatal error handler is
* registered by the application.
*
* Args: errcode - Easel error code, such as eslEINVAL. See easel.h.
* use_errno - TRUE on POSIX system call failures; use <errno>
* sourcefile - Name of offending source file; normally __FILE__.
* sourceline - Name of offending source line; normally __LINE__.
* format - <sprintf()> formatted exception message.
* argp - <va_list> containing any additional necessary arguments for
* the <format> message.
*
* Returns: void.
*
* Throws: (no abnormal error conditions)
*/
void
esl_nonfatal_handler(int errcode, int use_errno, char *sourcefile, int sourceline, char *format, va_list argp)
{
return;
}
/* Function: esl_fatal()
* Synopsis: Kill a program immediately, for a "violation".
*
* Purpose: Kill a program for a "violation". In general this should only be used
* in development or testing code, not in production
* code. The main use of <esl_fatal()> is in unit tests.
* Another use is in assertions used in dev code.
*
* The only other case (and the only case that should be allowed in
* production code) is in a true "function" (a function that returns
* its answer, rather than an Easel error code), where Easel error
* conventions can't be used (because it can't return an error code),
* AND the error is guaranteed to be a coding error. For an example,
* see <esl_opt_IsOn()>, which triggers a violation if the code
* checks for an option that isn't in the code.
*
* In an MPI-parallel program, the entire job is
* terminated; all processes are aborted (<MPI_Abort()>,
* not just the one that called <esl_fatal()>.
*
* If caller is feeling lazy and just wants to terminate
* without any informative message, use <abort()>.
*
* Args: format - <sprintf()> formatted exception message, followed
* by any additional necessary arguments for that
* message.
*
* Returns: (void)
*
* Throws: (no abnormal error conditions)
*/
void
esl_fatal(const char *format, ...)
{
va_list argp;
#ifdef HAVE_MPI
int mpiflag;
#endif
/* Check whether we are running as a daemon so we can do the right thing about logging instead of printing errors */
if (getppid() != 1)
{ // we're not running as a daemon, so print the error normally
va_start(argp, format);
vfprintf(stderr, format, argp);
va_end(argp);
fprintf(stderr, "\n");
fflush(stderr);
}
else vsyslog(LOG_ERR, format, argp);
#ifdef HAVE_MPI
MPI_Initialized(&mpiflag);
if (mpiflag) MPI_Abort(MPI_COMM_WORLD, 1);
#endif
exit(1);
}
/*---------------- end, error handling conventions --------------*/
/*****************************************************************
* 2. Memory allocation/deallocation conventions.
*****************************************************************/
/* Function: esl_free()
* Synopsis: free(), while allowing ptr to be NULL.
* Incept: SRE, Fri Nov 3 17:12:01 2017
*
* Purpose: Easel uses a convention of initializing ptrs to be NULL
* before allocating them. When cleaning up after errors, a
* routine can check for non-NULL ptrs to know what to
* free(). Easel code is slightly cleaner if we have a
* free() that no-ops on NULL ptrs.
*/
void
esl_free(void *p)
{
if (p) free(p);
}
/* Function: esl_Free2D()
*
* Purpose: Free a 2D pointer array <p>, where first dimension is
* <dim1>. (That is, the array is <p[0..dim1-1][]>.)
* Tolerates any of the pointers being NULL, to allow
* sparse arrays.
*
* Returns: void.
*
* DEPRECATED. Replace with esl_arr2_Destroy()
*/
void
esl_Free2D(void **p, int dim1)
{
int i;
if (p != NULL) {
for (i = 0; i < dim1; i++)
if (p[i] != NULL) free(p[i]);
free(p);
}
return;
}
/* Function: esl_Free3D()
*
* Purpose: Free a 3D pointer array <p>, where first and second
* dimensions are <dim1>,<dim2>. (That is, the array is
* <p[0..dim1-1][0..dim2-1][]>.) Tolerates any of the
* pointers being NULL, to allow sparse arrays.
*
* Returns: void.
*
* DEPRECATED. Replace with esl_arr3_Destroy()
*/
void
esl_Free3D(void ***p, int dim1, int dim2)
{
int i, j;
if (p != NULL) {
for (i = 0; i < dim1; i++)
if (p[i] != NULL) {
for (j = 0; j < dim2; j++)
if (p[i][j] != NULL) free(p[i][j]);
free(p[i]);
}
free(p);
}
}
/*------------- end, memory allocation conventions --------------*/
/*****************************************************************
* 3. Standard banner for Easel miniapplications.
*****************************************************************/
/* Function: esl_banner()
* Synopsis: print standard Easel application output header
*
* Purpose: Print the standard Easel command line application banner
* to <fp>, constructing it from <progname> (the name of the
* program) and a short one-line description <banner>.
* For example,
* <esl_banner(stdout, "compstruct", "compare RNA structures");>
* might result in:
*
* \begin{cchunk}
* # compstruct :: compare RNA structures
* # Easel 0.1 (February 2005)
* # Copyright (C) 2004-2007 HHMI Janelia Farm Research Campus
* # Freely licensed under the Janelia Software License.
* # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
* \end{cchunk}
*
* <progname> would typically be an application's
* <argv[0]>, rather than a fixed string. This allows the
* program to be renamed, or called under different names
* via symlinks. Any path in the <progname> is discarded;
* for instance, if <progname> is "/usr/local/bin/esl-compstruct",
* "esl-compstruct" is used as the program name.
*
* Note:
* Needs to pick up preprocessor #define's from easel.h,
* as set by ./configure:
*
* symbol example
* ------ ----------------
* EASEL_VERSION "0.1"
* EASEL_DATE "May 2007"
* EASEL_COPYRIGHT "Copyright (C) 2004-2007 HHMI Janelia Farm Research Campus"
* EASEL_LICENSE "Freely licensed under the Janelia Software License."
*
* Returns: <eslOK> on success.
*
* Throws: <eslEMEM> on allocation error.
* <eslEWRITE> on write error.
*/
int
esl_banner(FILE *fp, char *progname, char *banner)
{
char *appname = NULL;
int status;
if ((status = esl_FileTail(progname, FALSE, &appname)) != eslOK) return status;
if (fprintf(fp, "# %s :: %s\n", appname, banner) < 0) ESL_XEXCEPTION_SYS(eslEWRITE, "write failed");
if (fprintf(fp, "# Easel %s (%s)\n", EASEL_VERSION, EASEL_DATE) < 0) ESL_XEXCEPTION_SYS(eslEWRITE, "write failed");
if (fprintf(fp, "# %s\n", EASEL_COPYRIGHT) < 0) ESL_XEXCEPTION_SYS(eslEWRITE, "write failed");
if (fprintf(fp, "# %s\n", EASEL_LICENSE) < 0) ESL_XEXCEPTION_SYS(eslEWRITE, "write failed");
if (fprintf(fp, "# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -\n") < 0) ESL_XEXCEPTION_SYS(eslEWRITE, "write failed");
if (appname) free(appname);
return eslOK;
ERROR:
if (appname) free(appname);
return status;
}
/* Function: esl_usage()
* Synopsis: print standard Easel application usage help line
*
* Purpose: Given a usage string <usage> and the name of the program
* <progname>, output a standardized usage/help
* message. <usage> is minimally a one line synopsis like
* "[options] <filename>", but it may extend to multiple
* lines to explain the command line arguments in more
* detail. It should not describe the options; that's the
* job of the getopts module, and its <esl_opt_DisplayHelp()>
* function.
*
* This is used by the Easel miniapps, and may be useful in
* other applications as well.
*
* As in <esl_banner()>, the <progname> is typically passed
* as <argv[0]>, and any path prefix is ignored.
*
* For example, if <argv[0]> is </usr/local/bin/esl-compstruct>,
* then
*
* \begin{cchunk}
* esl_usage(stdout, argv[0], "[options] <trusted file> <test file>">
* \end{cchunk}
*
* produces
*
* \begin{cchunk}
* Usage: esl-compstruct [options] <trusted file> <test file>
* \end{cchunk}
*
* Returns: <eslOK> on success.
*
* Throws: <eslEMEM> on allocation failure.
* <eslEWRITE> on write failure.
*/
int
esl_usage(FILE *fp, char *progname, char *usage)
{
char *appname = NULL;
int status;
if ( (status = esl_FileTail(progname, FALSE, &appname)) != eslOK) return status;
if (fprintf(fp, "Usage: %s %s\n", appname, usage) < 0) ESL_XEXCEPTION_SYS(eslEWRITE, "write failed");
if (appname) free(appname);
return eslOK;
ERROR:
if (appname) free(appname);
return status;
}
/* Function: esl_dataheader()
* Synopsis: Standard #-prefixed header lines for output data table
*
* Purpose: Print column headers for a space-delimited, fixed-column-width
* data table to <fp>.
*
* Takes a variable number of argument pairs. Each pair is
* <width, label>. The absolute value of <width> is the max
* width of the column. <label> is the column label.
*
* If <width> is negative, left justify the label. (This is
* supposed to mirror the %-8s vs %8s of a printf format.)
*
* Caller marks the end of the argument list
* with a 0 sentinel.
*
* Example: <esl_dataheader(stdout, 8, "name", 3, "A", -4, "B", 0)>
* gives three columns:
*
* \begin{cchunk}
* # name A B
* #------- --- ----
* \end{cchunk}
*
* The <width> arguments match the widths given in
* <fprintf()>'s or whatever generates the data rows.
* Because the first header line is prefixed by \verb+#+, the
* first column's width argument is inclusive of these two
* extra chars, and therefore the first column label must
* have no more than its <width>-2 chars. For all other
* column labels, a label's length cannot exceed its
* <width>.
*
* Up to 1024 columns are allowed. (The only reason there's
* a limit is because you're going to forget to add the 0
* sentinel, and we don't want to risk a <while(1)> infinite
* loop.)
*
* Args: <fp> : output stream
* [<width>, <label]... : width, label pairs
* 0 : sentinel for end of argument list
*
* Returns: <eslOK> on success.
*
* Throws: <eslEINVAL> if a label is too wide for its width, or if
* the number of columns exceeds the max limit.
* <eslEWRITE> if a write to <fp> fails, which can happen
* if a disk fills up, for example.
*/
int
esl_dataheader(FILE *fp, ...)
{
va_list ap, ap2;
int width, len;
char *s;
int col = 0;
int maxcols = 1024; // limit, to avoid scary while(1) alternative
int leftjustify;
int status;
va_start(ap, fp);
va_copy(ap2, ap);
if ( fputc('#', fp) == EOF) ESL_XEXCEPTION_SYS(eslEWRITE, "write failed");
for (col = 0; col < maxcols; col++)
{
width = va_arg(ap, int);
if (width == 0) break;
if (width < 0) { leftjustify = TRUE; width = -width; }
else { leftjustify = FALSE; }
if (col == 0) width -= 2; // First column header -2 char for the "# " prefix
s = va_arg(ap, char *);
len = strlen(s);
if (len > width) {
if (col == 0) ESL_XEXCEPTION(eslEINVAL, "esl_dataheader(): first arg (%s) too wide for %d-char column ('# ' leader took 2 chars)", col, s, width+2);
else ESL_XEXCEPTION(eslEINVAL, "esl_dataheader(): arg %d (%s) too wide for %d-char column", col, s, width);
}
if (leftjustify) { if ( fprintf(fp, " %-*s", width, s) < 0) ESL_XEXCEPTION_SYS(eslEWRITE, "write failed"); }
else { if ( fprintf(fp, " %*s", width, s) < 0) ESL_XEXCEPTION_SYS(eslEWRITE, "write failed"); }
}
if (col == maxcols) ESL_XEXCEPTION( eslEINVAL, "esl_dataheader(): too many args");
if ( fputc('\n', fp) == EOF) ESL_XEXCEPTION_SYS(eslEWRITE, "write failed");
maxcols = col;
for (col = 0; col < maxcols; col++)
{
width = va_arg(ap2, int);
if (width < 0) width = -width;
if (col == 0) width -= 1;
(void) va_arg(ap2, char *);
if (col == 0) { if ( fputc('#', fp) == EOF) ESL_EXCEPTION_SYS(eslEWRITE, "write failed"); }
else { if ( fputc(' ', fp) == EOF) ESL_EXCEPTION_SYS(eslEWRITE, "write failed"); }
while (width--)
if ( fputc('-', fp) == EOF) ESL_EXCEPTION_SYS(eslEWRITE, "write failed");
}
if (fputc('\n', fp) == EOF) ESL_EXCEPTION_SYS(eslEWRITE, "write failed");
va_end(ap);
va_end(ap2);
return eslOK;
ERROR:
va_end(ap);
va_end(ap2);
return status;
}
/*-------------------- end, standard miniapp banner --------------------------*/
/******************************************************************************
* 4. Replacements for C library functions
* fgets() -> esl_fgets() fgets() with dynamic allocation
* strdup() -> esl_strdup() strdup() is not ANSI
* strcat() -> esl_strcat() strcat() with dynamic allocation
* strtok() -> esl_strtok() threadsafe strtok()
* sprintf() -> esl_sprintf() sprintf() with dynamic allocation
* strcmp() -> esl_strcmp() strcmp() tolerant of NULL strings
*****************************************************************************/
/* Function: esl_fgets()
*
* Purpose: Dynamic allocation version of fgets(),
* capable of reading almost unlimited line lengths.
*
* Args: buf - ptr to a string (may be reallocated)
* n - ptr to current allocated length of buf,
* (may be changed)
* fp - open file ptr for reading
*
* Before the first call to esl_fgets(),
* initialize buf to NULL and n to 0.
* They're a linked pair, so don't muck with the
* allocation of buf or the value of n while
* you're still doing esl_fgets() calls with them.
*
* Returns: <eslOK> on success.
* Returns <eslEOF> on normal end-of-file.
*
* When <eslOK>:
* <*buf> points to a <NUL>-terminated line from the file.
* <*n> contains the current allocated length for <*buf>.
*
* Caller must free <*buf> eventually.
*
* Throws: <eslEMEM> on an allocation failure.
*
* Example: char *buf = NULL;
* int n = 0;
* FILE *fp = fopen("my_file", "r");
*
* while (esl_fgets(&buf, &n, fp) == eslOK)
* {
* do stuff with buf;
* }
* if (buf != NULL) free(buf);
*/
int
esl_fgets(char **buf, int *n, FILE *fp)
{
int status;
char *s;
int len;
int pos;
if (*n == 0)
{
ESL_ALLOC(*buf, sizeof(char) * 128);
*n = 128;
}
/* Simple case 1. We're sitting at EOF, or there's an error.
* fgets() returns NULL, so we return EOF.
*/
if (fgets(*buf, *n, fp) == NULL) return eslEOF;
/* Simple case 2. fgets() got a string, and it reached EOF doing it.
* return success status, so caller can use
* the last line; on the next call we'll
* return the 0 for the EOF.
*/
if (feof(fp)) return eslOK;
/* Simple case 3. We got a complete string, with \n,
* and don't need to extend the buffer.
*/
len = strlen(*buf);
if ((*buf)[len-1] == '\n') return eslOK;
/* The case we're waiting for. We have an incomplete string,
* and we have to extend the buffer one or more times. Make
* sure we overwrite the previous fgets's \0 (hence +(n-1)
* in first step, rather than 128, and reads of 129, not 128).
*/
pos = (*n)-1;
while (1) {
ESL_REALLOC(*buf, sizeof(char) * (*n+128));
*n += 128;
s = *buf + pos;
if (fgets(s, 129, fp) == NULL) return eslOK;
len = strlen(s);
if (s[len-1] == '\n') return eslOK;
pos += 128;
}
/*NOTREACHED*/
return eslOK;
ERROR:
if (*buf != NULL) free(*buf);
*buf = NULL;
*n = 0;
return status;
}
/* Function: esl_strdup()
*
* Purpose: Makes a duplicate of string <s>, puts it in <ret_dup>.
* Caller can pass string length <n>, if it's known,
* to save a strlen() call; else pass -1 to have the string length
* determined.
*
* Tolerates <s> being <NULL>; in which case,
* returns <eslOK> with <*ret_dup> set to <NULL>.
*
* Args: s - string to duplicate (NUL-terminated)
* n - length of string, if known; -1 if unknown.
* ret_dup - RETURN: duplicate of <s>.
*
* Returns: <eslOK> on success, and <ret_dup> is valid.
*
* Throws: <eslEMEM> on allocation failure.
*/
int
esl_strdup(const char *s, int64_t n, char **ret_dup)
{
int status;
char *new = NULL;
if (s == NULL) {*ret_dup = NULL; return eslOK; }
if (n < 0) n = strlen(s);
ESL_ALLOC(new, sizeof(char) * (n+1));
strcpy(new, s);
*ret_dup = new;
return eslOK;
ERROR:
if (new) free(new);
*ret_dup = NULL;
return status;
}
/* Function: esl_strcat()
*
* Purpose: Dynamic memory version of strcat().
* Appends <src> to the string that <dest> points to,
* extending allocation for dest if necessary. Caller
* can optionally provide the length of <*dest> in
* <ldest>, and the length of <src> in <lsrc>; if
* either of these is -1, <esl_strcat()> calls <strlen()>
* to determine the length. Providing length information,
* if known, accelerates the routine.
*
* <*dest> may be <NULL>, in which case this is equivalent
* to a <strdup()> of <src> (that is, <*dest> is allocated
* rather than reallocated).
*
* <src> may be <NULL>, in which case <dest> is unmodified.
*
* Note: One timing experiment (100 successive appends of
* 1-255 char) shows esl_strcat() has about a 20%
* overhead relative to strcat(). If optional
* length info is passed, esl_strcat() is about 30%
* faster than strcat().
*
* Args: dest - ptr to string (char **), '\0' terminated
* ldest - length of dest, if known; or -1 if length unknown.
* src - string to append to dest, '\0' terminated
* lsrc - length of src, if known; or -1 if length unknown.
*
* Returns: <eslOK> on success; <*dest> is (probably) reallocated,
* modified, and nul-terminated.
*
* Throws: <eslEMEM> on allocation failure; initial state of <dest>
* is unaffected.
*/
int
esl_strcat(char **dest, int64_t ldest, const char *src, int64_t lsrc)
{
int status;
int64_t len1, len2;
if (ldest < 0) len1 = ((*dest == NULL) ? 0 : strlen(*dest));
else len1 = ldest;
if (lsrc < 0) len2 = (( src == NULL) ? 0 : strlen(src));
else len2 = lsrc;
if (len2 == 0) return eslOK;
ESL_REALLOC(*dest, sizeof(char) * (len1+len2+1));
memcpy((*dest)+len1, src, len2);
(*dest)[len1+len2] = '\0';
return eslOK;
ERROR:
return status;
}
/* Function: esl_strmapcat()
* Synopsis: Version of esl_strcat that uses an inmap.
*
* Purpose: Append the contents of string or memory line <src>
* of length <lsrc> to a string. The destination
* string and its length are passed as pointers <*dest>
* and <*ldest>, so the string can be reallocated
* and the length updated. When appending, map each
* character <src[i]> to a new character <inmap[src[i]]>
* in the destination string. The destination string
* <*dest> is NUL-terminated on return (even if it
* wasn't to begin with).
*
* One reason to use the inmap is to enable parsers to
* ignore some characters in an input string or buffer,
* such as whitespace (mapped to <eslDSQ_IGNORED>). Of
* course this means, unlike <esl_strcat()> the new length
* isn't just <ldest+lsrc>, because we don't know how many
* characters get appended until we've processed them
* through the inmap -- that's why this function takes
* <*ldest> by reference, whereas <esl_strcat()> takes it
* by value.
*
* If <*dest> is a NUL-terminated string and the caller
* doesn't know its length, <*ldest> may be passed as -1.
* Providing the length saves a <strlen()> call. If <*dest>
* is a memory line, providing <*ldest> is mandatory. Same
* goes for <src> and <lsrc>.
*
* <*dest> may be <NULL>, in which case it is allocated
* and considered to be an empty string to append to.
* When <*dest> is <NULL> the input <*ldest> should be <0>
* or <-1>.
*
* The caller must provide a <src> that it already knows
* should be entirely appended to <*dest>, except for
* perhaps some ignored characters. No characters may be
* mapped to <eslDSQ_EOL> or <eslDSQ_EOD>. The reason for
* this is that we're going to allocate <*dest> for
* <*ldest+lsrc> chars. If <src> were a large memory buffer,
* only a fraction of which needed to be appended (up to
* an <eslDSQ_EOL> or <eslDSQ_EOD>), this reallocation would
* be inefficient.
*
* Args: inmap - an Easel input map, inmap[0..127];
* inmap[0] is special: set to the 'unknown' character to
* replace invalid input chars.
* *dest - destination string or memory to append to, passed by reference
* *ldest - length of <*dest> (or -1), passed by reference
* src - string or memory to inmap and append to <*dest>
* lsrc - length of <src> to map and append (or -1).
*
* Returns: <eslOK> on success. Upon successful return, <*dest> is
* reallocated and contains the new string (with from 0 to <lsrc>
* appended characters), NUL-terminated.
*
* <eslEINVAL> if one or more characters in the input <src>
* are mapped to <eslDSQ_ILLEGAL>. Appending nonetheless
* proceeds to completion, with any illegal characters
* represented as '?' in <*dest> and counted in <*ldest>.
* This is a normal error, because the string <src> may be
* user input. The caller may want to call some sort of
* validation function on <src> if an <eslEINVAL> error is
* returned, in order to report some helpful diagnostics to
* the user.
*
* Throws: <eslEMEM> on allocation or reallocation failure.
* <eslEINCONCEIVABLE> on internal coding error; for example,
* if the inmap tries to map an input character to <eslDSQ_EOD>,
* <eslDSQ_EOL>, or <eslDSQ_SENTINEL>. On exceptions, <*dest>
* and <*ldest> should not be used by the caller except to
* free <*dest>; their state may have been corrupted.
*
* Note: This deliberately mirrors <esl_abc_dsqcat()>, so
* that sequence file parsers have comparable behavior whether
* they're working with text-mode or digital-mode input.
*
* Might be useful to create a variant that also handles
* eslDSQ_EOD (and eslDSQ_EOL?) and returns the number of
* residues parsed. This'd allow a FASTA parser, for
* instance, to use this method while reading buffer pages
* rather than lines; it could define '>' as eslDSQ_EOD.
*/
int
esl_strmapcat(const ESL_DSQ *inmap, char **dest, int64_t *ldest, const char *src, esl_pos_t lsrc)
{
int status = eslOK;
if (*ldest < 0) *ldest = ( (*dest) ? strlen(*dest) : 0);
if ( lsrc < 0) lsrc = ( (*src) ? strlen(src) : 0);
if (lsrc == 0) goto ERROR; /* that'll return eslOK, leaving *dest untouched, and *ldest its length. */
ESL_REALLOC(*dest, sizeof(char) * (*ldest + lsrc + 1)); /* includes case of a new alloc of *dest */
return esl_strmapcat_noalloc(inmap, *dest, ldest, src, lsrc);
ERROR:
return status;
}
/* Function: esl_strmapcat_noalloc()
* Synopsis: Version of esl_strmapcat() that does no reallocation.
*
* Purpose: Same as <esl_strmapcat()>, but with no reallocation. The
* pointer to the destination string <dest> is passed by
* value, not by reference, because it will not be changed.
* Caller has allocated at least <*ldest + lsrc + 1> bytes
* in <dest>. In this version, <*ldest> and <lsrc> are not
* optional; caller must know the lengths of both the old
* string and the new source.
*
* Note: (see note on esl_abc_dsqcat_noalloc() for rationale)
*/
int
esl_strmapcat_noalloc(const ESL_DSQ *inmap, char *dest, int64_t *ldest, const char *src, esl_pos_t lsrc)
{
int64_t xpos;
esl_pos_t cpos;
ESL_DSQ x;
int status = eslOK;
for (xpos = *ldest, cpos = 0; cpos < lsrc; cpos++)
{
if (! isascii(src[cpos])) { dest[xpos++] = inmap[0]; status = eslEINVAL; continue; }
x = inmap[(int) src[cpos]];
if (x <= 127) dest[xpos++] = x;
else switch (x) {
case eslDSQ_SENTINEL: ESL_EXCEPTION(eslEINCONCEIVABLE, "input char mapped to eslDSQ_SENTINEL"); break;
case eslDSQ_ILLEGAL: dest[xpos++] = inmap[0]; status = eslEINVAL; break;
case eslDSQ_IGNORED: break;
case eslDSQ_EOL: ESL_EXCEPTION(eslEINCONCEIVABLE, "input char mapped to eslDSQ_EOL"); break;
case eslDSQ_EOD: ESL_EXCEPTION(eslEINCONCEIVABLE, "input char mapped to eslDSQ_EOD"); break;
default: ESL_EXCEPTION(eslEINCONCEIVABLE, "bad inmap, no such ESL_DSQ code"); break;
}
}
dest[xpos] = '\0';
*ldest = xpos;
return status;
}
/* Function: esl_strtok()
* Synopsis: Threadsafe version of C's <strtok()>
*
* Purpose: Thread-safe version of <strtok()> for parsing next token in
* a string.
*
* Increments <*s> while <**s> is a character in <delim>,
* then stops; the first non-<delim> character defines the
* beginning of a token. Increments <*s> until it reaches
* the next delim character (or \verb+\0+); this defines the end
* of the token, and this character is replaced with
* \verb+\0+. <*s> is then reset to point to the next character
* after the \verb+\0+ that was written, so successive calls can
* extract tokens in succession. Sets <*ret_tok> to point at
* the beginning of the token, and returns <eslOK>.
*
* If a token is not found -- if <*s> already points to
* \verb+\0+, or to a string composed entirely of characters in
* <delim> -- then returns <eslEOL>, with <*ret_tok> set to
* <NULL>.
*
* <*s> cannot be a constant string, since we write \verb+\0+'s
* to it; caller must be willing to have this string
* modified. And since we walk <*s> through the string as we
* parse, the caller wants to use a tmp pointer <*s>, not
* the original string itself.
*
* Example:
* char *tok;
* char *s;
* char buf[50] = "This is a sentence.";
*
* s = buf;
* esl_strtok(&s, " ", &tok);
* tok is "This"; s is "is a sentence."
* esl_strtok(&s, " ", &tok);
* tok is "is"; s is " a sentence.".
* esl_strtok(&s, " ", &tok);
* tok is "a"; s is "sentence.".
* esl_strtok(&s, " ", &tok, &len);
* tok is "sentence."; s is "\0".
* esl_strtok(&s, " ", &tok, &len);
* returned eslEOL; tok is NULL; s is "\0".
*
* Args: s - a tmp, modifiable ptr to a string
* delim - characters that delimits tokens
* ret_tok - RETURN: ptr to \0-terminated token
*
* Returns: <eslOK> on success, <*ret_tok> points to next token, and
* <*s> points to next character following the token.
*
* Returns <eslEOL> on end of line; in which case <*s>
* points to the terminal \verb+\0+ on the line, and <*ret_tok>
* is <NULL>.
*/
int
esl_strtok(char **s, char *delim, char **ret_tok)
{
return esl_strtok_adv(s, delim, ret_tok, NULL, NULL);
}
/* Function: esl_strtok_adv()
* Synopsis: More advanced interface to <esl_strtok()>
*
* Purpose: Same as <esl_strtok()>, except the caller may also
* optionally retrieve the length of the token in <*opt_toklen>,
* and the token-ending character that was replaced by \verb+\0+
* in <*opt_endchar>.
*
* Args: s - a tmp, modifiable ptr to string
* delim - characters that delimits tokens
* ret_tok - RETURN: ptr to \0-terminated token string
* opt_toklen - optRETURN: length of token; pass NULL if not wanted
* opt_endchar - optRETURN: character that was replaced by <\0>.
*
* Returns: <eslOK> on success, <*ret_tok> points to next token, <*s>
* points to next character following the token,
* <*opt_toklen> is the <strlen()> length of the token in
* characters (excluding its terminal \verb+\0+), and <*opt_endchar>
* is the character that got replaced by \verb+\0+ to form the token.
*
* Returns <eslEOL> if no token is found (end of line); in
* which case <*s> points to the terminal \verb+\0+ on the line,
* <*ret_tok> is <NULL>, <*opt_toklen> is 0 and
* <*opt_endchar> is \verb+\0+.
*/
int
esl_strtok_adv(char **s, char *delim, char **ret_tok, int *opt_toklen, char *opt_endchar)
{
char *end;
char *tok = *s;
char c = '\0';
int n = 0;
int status = eslEOL; /* unless proven otherwise */
/* contract checks */
ESL_DASSERT1(( s != NULL ));
ESL_DASSERT1(( delim != NULL ));
tok += strspn(tok, delim);
if (! *tok) tok = NULL; /* if *tok = 0, EOL, no token left */
else
{
n = strcspn(tok, delim);
end = tok + n;
if (*end == '\0') *s = end; /* a final token that extends to end of string */
else
{
c = *end; /* internal token: terminate with \0 */
*end = '\0';
*s = end+1;
}
status = eslOK;
}
*ret_tok = tok;
if (opt_toklen != NULL) *opt_toklen = n;
if (opt_endchar != NULL) *opt_endchar = c;
return status;
}
/* Function: esl_sprintf()
* Synopsis: Dynamic allocation version of sprintf().
*
* Purpose: Like ANSI C's <sprintf()>, except the string
* result is dynamically allocated, and returned
* through <*ret_s>.
*
* Caller is responsible for free'ing <*ret_s>.
*
* As a special case to facilitate some optional string
* initializations, if <format> is <NULL>, <*ret_s> is set
* to <NULL>.
*
* Returns: <eslOK> on success, and <*ret_s> is the resulting
* string.
*
* Throws: <eslEMEM> on allocation failure.
* <eslESYS> if a <*printf()> library call fails.
*/
int
esl_sprintf(char **ret_s, const char *format, ...)
{
va_list ap;
int status;
va_start(ap, format);
status = esl_vsprintf(ret_s, format, &ap);
va_end(ap);
return status;
}
/* Function: esl_vsprintf()
* Synopsis: Dynamic allocation version of vsprintf()
*
* Purpose: Like ANSI C's <vsprintf>, except the string
* result is dynamically allocated, and returned
* through <*ret_s>.
*
* Caller is responsible for free'ing <*ret_s>.
*
* As a special case to facilitate some optional string
* initializations, if <format> is <NULL>, <*ret_s> is set
* to <NULL>.
*
* Returns: <eslOK> on success, and <*ret_s> is the resulting
* string.
*
* Throws: <eslEMEM> on allocation failure.
* <eslESYS> if a <*printf()> library call fails.
*/
int
esl_vsprintf(char **ret_s, const char *format, va_list *ap)
{
char *s = NULL;
va_list ap2;
int n1, n2;
int status;
if (format == NULL) { *ret_s = NULL; return eslOK; }
va_copy(ap2, *ap);
n1 = strlen(format) * 2; /* initial guess at string size needed */
ESL_ALLOC(s, sizeof(char) * (n1+1));
if ((n2 = vsnprintf(s, n1+1, format, *ap)) >= n1)
{
ESL_REALLOC(s, sizeof(char) * (n2+1));
if (vsnprintf(s, n2+1, format, ap2) == -1) ESL_XEXCEPTION(eslESYS, "vsnprintf() failed");
}
else if (n2 == -1) ESL_XEXCEPTION(eslESYS, "vsnprintf() failed");
va_end(ap2);
*ret_s = s;
return eslOK;
ERROR:
if (s) free(s);
va_end(ap2);
*ret_s = NULL;
return status;
}
/* Function: esl_strcmp()
* Synopsis: a strcmp() that treats NULL as empty string.
*
* Purpose: A version of <strcmp()> that accepts <NULL>
* strings. If both <s1> and <s2> are non-<NULL>
* they are compared by <strcmp()>. If both are
* <NULL>, return 0 (as if they are identical
* strings). If only <s1> (or <s2>) is non-<NULL>,
* return 1 (or -1), corresponding to ordering
* any non-<NULL> string as greater than a <NULL>
* string.
*
* (Easel routinely uses NULL to mean an unset optional
* string, and often needs to compare two strings for
* equality.)
*
* Returns: 0 if <s1 == s2>; 1 if <s1 > s2>; -1 if <s1 < s2>.
*/
int
esl_strcmp(const char *s1, const char *s2)
{
if (s1 && s2) return strcmp(s1, s2);
else if (s1) return 1;
else if (s2) return -1;
else return 0;
}
/*--------- end, improved replacement ANSI C functions ----------*/
/*****************************************************************
* 5. Portable drop-in replacements for non-standard C functions
*****************************************************************/
#ifndef HAVE_STRCASECMP
/* Function: esl_strcasecmp()
*
* Purpose: Compare strings <s1> and <s2>. Return -1 if
* <s1> is alphabetically less than <s2>, 0 if they
* match, and 1 if <s1> is alphabetically greater
* than <s2>. All matching is case-insensitive.
*
* Args: s1 - string 1, \0 terminated
* s2 - string 2, \0 terminated
*
* Returns: -1, 0, or 1, if <s1> is less than, equal, or
* greater than <s2>, case-insensitively.
*
* Throws: (no abnormal error conditions)
*/
int
esl_strcasecmp(const char *s1, const char *s2)
{
int i, c1, c2;
for (i = 0; s1[i] != '\0' && s2[i] != '\0'; i++)
{
c1 = s1[i]; /* total paranoia. don't trust toupper() to */
c2 = s2[i]; /* leave the original unmodified; make a copy. */
if (islower(c1)) c1 = toupper(c1);
if (islower(c2)) c2 = toupper(c2);
if (c1 < c2) return -1;
else if (c1 > c2) return 1;
}
if (s1[i] != '\0') return 1; /* prefixes match, but s1 is longer */
else if (s2[i] != '\0') return -1; /* prefixes match, s2 is longer */
return 0; /* else, a case-insensitive match. */
}
#endif /* ! HAVE_STRCASECMP */
#ifndef HAVE_STRSEP
/* Function: esl_strsep()
* Synopsis: Separate strings.
* Incept: Contributed by Sebastien Jaenick, July 2016.
*
* Purpose: Portable replacement for strsep(). Solaris, for example,
* does not have it.
*
* Get next token from string *stringp, where tokens are
* possibly-empty strings separated by characters from
* delim.
*
* Writes NULs into the string at *stringp to end tokens.
* delim need not remain constant from call to call. On
* return, *stringp points past the last NUL written (if
* there might be further tokens), or is NULL (if there are
* definitely no more tokens).
*
* If *stringp is NULL, strsep returns NULL.
*
* Note:
* Taken from FreeBSD, under BSD open source license:
*
* Copyright (c) 1990, 1993
* The Regents of the University of California. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 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.
*/
char *
esl_strsep(char **stringp, const char *delim)
{
const char *spanp;
char *s;
int c, sc;
char *tok;
if ((s = *stringp) == NULL)
return NULL;
for (tok = s;;) {
c = *s++;
spanp = delim;
do {
if ((sc = *spanp++) == c) {
if (c == 0)
s = NULL;
else
s[-1] = 0;
*stringp = s;
return tok;
}
} while (sc != 0);
}
/* NOTREACHED */
}
#endif
/*------------- end, portable drop-in replacements --------------*/
/*****************************************************************
* 6. Additional string functions, esl_str*()
*****************************************************************/
/* Function: esl_strchop()
*
* Purpose: Chops trailing whitespace off of a string <s> (or if <s>
* is NULL, do nothing).
* <n> is the length of the input string, if known; or pass <n=-1>
* if length is unknown.
*
* Returns: <eslOK> on success.
*
* Throws: (no abnormal error conditions)
*
* Xref: from squid's StringChop().
*/
int
esl_strchop(char *s, int64_t n)
{
int i;
if (s == NULL) return eslOK;
if (n < 0) n = strlen(s);
for (i = n-1; i>=0 && isspace((int) s[i]); i--);
s[i+1] = '\0';
return eslOK;
}
/* Function: esl_strdealign()
* Synopsis: Dealign a string according to gaps in a reference aseq.
*
* Purpose: Dealign string <s> in place, by removing any characters
* aligned to gaps in <aseq>. Gap characters are defined in the
* string <gapstring>; for example, <-_.>. Optionally return the
* unaligned length of <s> in characters in <*opt_rlen>.
*
* By providing a reference <aseq> to dealign against, this
* function can dealign aligned annotation strings, such as
* secondary structure or surface accessibility strings.
* If <s> is the same as <aseq>, then the aligned sequence
* itself is dealigned in place.
*
* To dealign both annotations and sequence, do the
* sequence last, since you need it as the reference <aseq>
* when doing the annotations.
*
* It is safe to pass a <NULL> <s> (an unset optional
* annotation), in which case the function no-ops and
* returns <eslOK>.
*
* Args: s - string to dealign
* aseq - reference aligned sequence seq
* gapchars - definition of gap characters ("-_." for example)
* opt_rlen - optRETURN: number of residues in <s> after dealign
*
* Returns: <eslOK> on success.
*/
int
esl_strdealign(char *s, const char *aseq, const char *gapchars, int64_t *opt_rlen)
{
int64_t n = 0;
int64_t apos;
if (s == NULL) return eslOK;
for (apos = 0; aseq[apos] != '\0'; apos++)
if (strchr(gapchars, aseq[apos]) == NULL)
s[n++] = s[apos];
s[n] = '\0';
if (opt_rlen != NULL) *opt_rlen = n;
return eslOK;
}
/* Function: esl_str_IsBlank()
* Synopsis: Return TRUE if <s> is all whitespace; else FALSE.
*
* Purpose: Given a NUL-terminated string <s>; return <TRUE> if
* string is entirely whitespace (as defined by <isspace()>),
* and return FALSE if not.
*/
int
esl_str_IsBlank(char *s)
{
for (; *s; s++) if (!isspace(*s)) return FALSE;
return TRUE;
}
/* Function: esl_str_IsInteger()
* Synopsis: Return TRUE if <s> represents an integer; else FALSE.
*
* Purpose: Given a NUL-terminated string <s>, return TRUE
* if the complete string is convertible to a base-10 integer
* by the rules of <strtol()> or <atoi()>.
*
* Leading and trailing whitespace is allowed, but otherwise
* the entire string <s> must be convertable. (Unlike <strtol()>
* itself, which will convert a prefix. ' 99 foo' converts
* to 99, but <esl_str_IsInteger()> will return FALSE.
*
* If <s> is <NULL>, FALSE is returned.
*/
int
esl_str_IsInteger(char *s)
{
char *endp;
if (s == NULL) return FALSE; /* it's NULL */
(void) strtol(s, &endp, 10); /* don't need result itself, discard to void */
if (endp == s) return FALSE; /* strtol() can't convert it */
for (s = endp; *s != '\0'; s++)
if (! isspace(*s)) return FALSE; /* it has trailing nonconverted nonwhitespace */
return TRUE;
}
/* Function: esl_str_IsReal()
* Synopsis: Return TRUE if string <s> represents a real number; else FALSE.
*
* Purpose: Given a NUL-terminated string <s>, return <TRUE>
* if the string is completely convertible to a floating-point
* real number by the rules of <strtod()> and <atof()>.
* (Which allow for exponential forms, hexadecimal forms,
* and case-insensitive INF, INFINITY, NAN, all w/ optional
* leading +/- sign.)
*
* No trailing garbage is allowed, unlike <strtod()>. The
* entire string must be convertible, allowing leading and
* trailing whitespace is allowed. '99.0 foo' converts
* to 99.0 with <strtod()> but is <FALSE> for
* <esl_str_IsReal()>. ' 99.0 ' is <TRUE>.
*
* If <s> is <NULL>, return <FALSE>.
*/
int
esl_str_IsReal(char *s)
{
char *endp;
double val;
if (! s) return FALSE; /* <s> is NULL */
val = strtod(s, &endp);
if (val == 0.0f && endp == s) return FALSE; /* strtod() can't convert it */
for (s = endp; *s != '\0'; s++)
if (! isspace(*s)) return FALSE; /* it has trailing nonconverted nonwhitespace */
return TRUE;
}
/* Function: esl_str_GetMaxWidth()
* Synopsis: Returns maximum strlen() in an array of strings.
*
* Purpose: Returns the length of the longest string in
* an array of <n> strings <s[0..n-1]>. If <n=0>,
* returns 0. Any <s[i]> that's <NULL> is counted
* as zero length.
*/
int64_t
esl_str_GetMaxWidth(char **s, int n)
{
int64_t max = 0;
int64_t len;
int i;
for (i = 0; i < n; i++)
if (s[i]) {
len = strlen(s[i]);
if (len > max) max = len;
}
return max;
}
/*-------------- end, additional string functions ---------------*/
/*****************************************************************
* 7. File path/name manipulation, including tmpfiles
*****************************************************************/
/* Function: esl_FileExists()
* Synopsis: Return TRUE if <filename> exists and is readable, else FALSE.
*
* Purpose: Returns TRUE if <filename> exists and is readable, else FALSE.
*
* Xref: squid's FileExists().
*/
int
esl_FileExists(const char *filename)
{
#ifdef _POSIX_VERSION
struct stat fileinfo;
if (stat(filename, &fileinfo) != 0) return FALSE;
if (! (fileinfo.st_mode & S_IRUSR)) return FALSE;
return TRUE;
#else
FILE *fp;
if ((fp = fopen(filename, "r"))) { fclose(fp); return TRUE; }
return FALSE;
#endif
}
/* Function: esl_FileTail()
* Synopsis: Extract filename, removing path prefix.
*
* Purpose: Given a full pathname <path>, extract the filename
* without the directory path; return it via
* <ret_filename>. <ret_filename> space is allocated
* here, and must be free'd by the caller.
* For example:
* </foo/bar/baz.1> becomes <baz.1>;
* <foo/bar> becomes <bar>;
* <foo> becomes <foo>; and
* </> becomes the empty string.
*
* If <nosuffix> is <TRUE>, the rightmost trailing ".foo" extension
* is removed too. The suffix is defined as everything following
* the rightmost period in the filename in <path>:
* with <nosuffix> <TRUE>,
* <foo.2/bar.idx> becomes <bar>,
* <foo.2/bar> becomes <bar>, and
* <foo.2/bar.1.3> becomes <bar.1>.
*
* Args: path - full pathname to process, "/foo/bar/baz.1"
* nosuffix - TRUE to remove rightmost suffix from the filename
* ret_file - RETURN: filename portion of the path.
*
* Returns: <eslOK> on success, and <ret_file> points to a newly
* allocated string containing the filename.
*
* Throws: <eslEMEM> on allocation failure.
*/
int
esl_FileTail(const char *path, int nosuffix, char **ret_file)
{
int status;
char *tail = NULL;
char *lastslash;
char *lastdot;
/* remove directory prefix */
lastslash = strrchr(path, eslDIRSLASH);
ESL_ALLOC(tail, sizeof(char) * (strlen(path)+1)); /* a little overkill */
if (lastslash == NULL) strcpy(tail, path);
else strcpy(tail, lastslash+1);
/* remove trailing suffix */
if (nosuffix) {
if ((lastdot = strrchr(tail, '.')) != NULL)
*lastdot = '\0';
}
*ret_file = tail;
return eslOK;
ERROR:
if (tail != NULL) free(tail);
*ret_file = NULL;
return status;
}
/* Function: esl_file_Extension()
* Synopsis: Find suffix of a file name; set a memory line on it.
*
* Purpose: Given a path or file name <filename>, and ignoring the
* last <n_ignore> characters, find the rightmost suffix;
* return a pointer to its start in <*ret_sfx> (inclusive
* of the ``.''), and its length in <*ret_n>. If no
* suffix is found, return <eslFAIL> with <*ret_sfx = NULL>
* and <ret_n = 0>.
*
* The <n_ignore> argument allows iterating through more
* than one suffix.
*
* For example, if <filename> is ``./foo/bar/baz.xx.yyy''
* and <n_ignore> is 0, <*ret_sfx> points to ``.yyy'' and
* <*ret_n> is 4. If <n_ignore> is 4, then <*ret_sfx>
* points to ``.xx'' and <ret_n> is 3. If <n_ignore> is 7
* then status is <eslFAIL>.
*/
int
esl_file_Extension(char *filename, esl_pos_t n_ignore, char **ret_sfx, esl_pos_t *ret_n)
{
esl_pos_t n1 = strlen(filename) - n_ignore;
esl_pos_t n2;
for (n2 = n1; n2 > 0 && filename[n2-1] != eslDIRSLASH && filename[n2-1] != '.'; n2--) ;
if (n2 <= 0 || filename[n2-1] == eslDIRSLASH)
{ *ret_sfx = NULL; *ret_n = 0; return eslFAIL; }
*ret_sfx = filename + n2 - 1;
*ret_n = n1-n2+1;
return eslOK;
}
/* Function: esl_FileConcat()
*
* Purpose: Concatenates directory path prefix <dir> and a filename
* <file>, and returns the new full pathname through
* <ret_path>. If <dir> does not already end in the
* appropriate delimiter (e.g. / for UNIX), one is added.
*
* If <dir> is NULL, then <ret_path> is just the same as
* <file>. Similarly, if <file> already appears to be a
* full path (because its first character is a /), then
* <dir> is ignored and <ret_path> is the same as
* <file>. It wouldn't normally make sense for a caller to
* call this function with such arguments.
*
* <file> may be a relative path. For example,
* if <dir> is "/usr/local" and <file> is "lib/myapp/data",
* <ret_path> will be "/usr/local/lib/myapp/data".
*
* Returns: <eslOK> on success, and puts the path
* in <ret_path>; this string is allocated here,
* and must be free'd by caller with <free()>.
*
* Throws: <eslEMEM> on allocation failure.
* <eslEINVAL> on bad argument.
* In either case, <ret_path> is returned NULL.
*
* Xref: squid's FileConcat().
*/
int
esl_FileConcat(const char *dir, const char *file, char **ret_path)
{
char *path = NULL;
int nd, nf;
int status;
if (ret_path != NULL) *ret_path = NULL;
if (file == NULL) ESL_EXCEPTION(eslEINVAL, "null file");
nd = (dir != NULL)? strlen(dir) : 0;
nf = strlen(file);
ESL_ALLOC(path, sizeof(char) * (nd+nf+2));
if (dir == NULL) /* 1. silly caller didn't give a path */
strcpy(path, file);
else if (*file == eslDIRSLASH) /* 2. <file> is already a path? */
strcpy(path, file);
else if (dir[nd-1] == eslDIRSLASH) /* 3. <dir><file> (dir is / terminated) */
sprintf(path, "%s%s", dir, file);
else /* 4. <dir>/<file> (usual case) */
sprintf(path, "%s%c%s", dir, eslDIRSLASH, file);
*ret_path = path;
return eslOK;
ERROR:
if (path != NULL) free(path);
if (ret_path != NULL) *ret_path = NULL;
return status;
}
/* Function: esl_FileNewSuffix()
*
* Purpose: Add a file suffix <sfx> to <filename>; or if <filename>
* already has a suffix, replace it with <sfx>. A suffix is
* usually 2-4 letters following a '.' character. Returns
* an allocated string containing the result in <ret_newpath>.
*
* For example, if <filename> is "foo" and <sfx> is "ssi",
* returns "foo.ssi". If <filename> is "foo.db" and <sfx>
* is "idx", returns "foo.idx". You can remove a suffix
* too; if <filename> is "foo.db", and <sfx> is "", the
* result is "foo".
*
* Caller can either ask for <*ret_newpath> to be a new
* allocation by passing <*ret_newpath = NULL>, or can
* provide a ptr to a preallocated space.
*
* Returns: <eslOK> on success, and <ret_newpath> is set
* string "<base_filename>.<sfx>". Caller is
* responsible for free'ing this string, whether it
* provided it as preallocated space or asked for a new
* allocation.
*
* Throws: <eslEMEM> on allocation failure.
*
* Xref: squid's FileAddSuffix().
*/
int
esl_FileNewSuffix(const char *filename, const char *sfx, char **ret_newpath)
{
char *new = *ret_newpath; // caller either provides memory, or asks for allocation w/ <NULL>
char *lastdot;
int nf;
int status;
lastdot = strrchr(filename, '.'); /* check for suffix to replace */
if (lastdot != NULL &&
strchr(lastdot, eslDIRSLASH) != NULL)
lastdot = NULL; /*foo.1/filename case - don't be fooled.*/
nf = (lastdot == NULL)? strlen(filename) : lastdot-filename;
if (! new) ESL_ALLOC(new, sizeof(char) * (nf+strlen(sfx)+2)); /* '.' too */
strncpy(new, filename, nf);
*(new+nf) = '.';
strcpy(new+nf+1, sfx);
*ret_newpath = new;
return eslOK;
ERROR:
if (!(*ret_newpath) && new) free(new);
return status;
}
/* Function: esl_FileEnvOpen()
*
* Purpose: Looks for a file <fname> in a colon-separated list of
* directories that is configured in an environment variable
* <env>. The first occurrence of file <fname> in this directory
* list is opened read-only. The open file ptr is returned
* through <opt_fp>, and the full path name to the file
* that was opened is returned through <opt_path>.
* Caller can pass NULL in place of <opt_fp> or <opt_path>
* if it is not interested in one or both of these.
*
* Does not look in the current directory unless "." is
* explicitly in the directory list provided by <env>.
*
* Note: One reason to pass <opt_path> back to the caller is that
* sometimes we're opening the first in a group of files
* (for example, a database and its SSI index), and we want
* to make sure that after we find the main file, the
* caller can look for the auxiliary file(s) in exactly the
* same directory.
*
* Examples: % setenv BLASTDB /nfs/databases/blast-db:/nfs/databases/nr/
*
* FILE *fp;
* char *path;
* int status;
* status = esl_FileEnvOpen("swiss42", "BLASTDB", &fp, &path);
*
* Returns: <eslOK> on success, and provides <opt_fp> and <opt_path>;
* <opt_fp> is opened here, and must be <fclose()>'d by caller;
* <opt_path> is allocated here, and must be <free()>'d by caller.
*
* Returns <eslENOTFOUND> if the file not found in any directory,
* or if <env> does not contain any directories to look in.
*
* Throws: <eslEMEM> on allocation error.
*
* Xref: squid's EnvFileOpen().
*/
int
esl_FileEnvOpen(const char *fname, const char *env, FILE **opt_fp, char **opt_path)
{
FILE *fp;
char *dirlist; /* :-separated list of directories */
char *s, *s2; /* ptrs into elems in env list */
char *path = NULL;
int np;
int status;
fp = NULL;
if (opt_fp != NULL) *opt_fp = NULL;
if (opt_path != NULL) *opt_path = NULL;
if (env == NULL) return eslENOTFOUND;
if ((s = getenv(env)) == NULL) return eslENOTFOUND;
if (esl_strdup(s, -1, &dirlist) != eslOK) return eslEMEM;
np = strlen(fname) + strlen(s) + 2; /* upper bound on full path len */
ESL_ALLOC(path, sizeof(char) * np);
s = dirlist;
while (s != NULL)
{
if ((s2 = strchr(s, ':')) != NULL) { *s2 = '\0'; s2++;} /* ~=strtok() */
sprintf(path, "%s%c%s", s, eslDIRSLASH, fname); /* // won't hurt */
if ((fp = fopen(path, "r")) != NULL) break;
s = s2;
}
if (fp == NULL) { free(path); free(dirlist); return eslENOTFOUND; }
if (opt_path != NULL) { *opt_path = path; } else free(path);
if (opt_fp != NULL) { *opt_fp = fp; } else fclose(fp);
free(dirlist);
return eslOK;
ERROR:
if (path != NULL) free(path);
if (fp != NULL) fclose(fp);
if (dirlist != NULL) free(dirlist);
if (opt_path != NULL) *opt_path = NULL;
if (opt_fp != NULL) *opt_fp = NULL;
return status;
}
/* Function: esl_tmpfile()
*
* Purpose: Open a secure temporary <FILE *> handle and return it in
* <ret_fp>. The file is opened in read-write mode (<w+b>)
* with permissions 0600, as an atomic operation using the
* POSIX <mkstemp()> function.
*
* The <basename6X> argument is a modifiable string that must
* end in "XXXXXX" (for example, "esltmpXXXXXX"). The
* <basename6X> is used to construct a unique tmpfile name.
*
* Note that this string must be modifiable; do not declare
* it <char *tmpfile = "esltmpXXXXXX";> nor <char tmpfile[]
* = "esltmpXXXXXX";> because these will not work on some
* compilers. Something like <char tmpfile[16] =
* "esltmpXXXXXX";> that explicitly allocates storage will
* suffice.
*
* The file is opened in a standard temporary file
* directory. The path is obtained from the environment
* variable <TMPDIR>; failing that, from the environment
* variable <TMP>; and failing that, </tmp> is used. If the
* process is running <setuid> or <setgid>, then the
* environment variables are ignored, and the temp file is
* always created in </tmp>.
*
* The created tmpfile is not persistent and is not visible
* to a directory listing. The caller may <rewind()> the
* <ret_fp> and do cycles of reading and/or writing, but
* once the <ret_fp> is closed, the file disappears. The
* caller does not need to <remove()> or <unlink()> it (and
* in fact, cannot do so, because it does not know the
* tmpfile's name).
*
* This function is a secure replacement for ANSI C
* <tmpfile()>, which is said to be insecurely implemented on
* some platforms.
*
* Returns: <eslOK> on success, and now <ret_fp> points to a new <FILE *>
* stream for the opened tempfile.
*
* Throws: <eslESYS> if a system call (including the <mkstemp()> call)
* fails, and and <ret_fp> is returned NULL. One possible
* problem is if the temporary directory doesn't exist or
* is not writable. This is considered to be a system
* error, not a user error, so Easel handles it as an exception.
*
* Xref: STL11/85. Substantially copied from David Wheeler,
* "Secure Programming for Linux and Unix HOWTO",
* http://www.dwheeler.com/secure-programs/Secure-Programs-HOWTO/introduction.html.
* Copyright (C) 1999-2001 David A. Wheeler.
* Licensed under the MIT license; see Appendix C of the HOWTO.
* Thanks, David, for the clearest explanation of the issues
* that I've seen.
*
* I also referred to H. Chen, D. Dean, and D. Wagner,
* "Model checking one million lines of C code",
* In: Network and Distributed System Security Symposium, pp 171-185,
* San Diego, CA, February 2004;
* http://www.cs.ucdavis.edu/~hchen/paper/ndss04.pdf.
* Wheeler's implementation obeys Chen et al's "Property 5",
* governing secure use of tempfiles.
*/
int
esl_tmpfile(char *basename6X, FILE **ret_fp)
{
char *tmpdir = NULL;
char *path = NULL;
FILE *fp = NULL;
int fd;
int status;
mode_t old_mode;
/* Determine what tmp directory to use, and construct the
* file name.
*/
if (getuid() == geteuid() && getgid() == getegid())
{
tmpdir = getenv("TMPDIR");
if (tmpdir == NULL) tmpdir = getenv("TMP");
}
if (tmpdir == NULL) tmpdir = "/tmp";
if ((status = esl_FileConcat(tmpdir, basename6X, &path)) != eslOK) goto ERROR;
old_mode = umask(077);
if ((fd = mkstemp(path)) < 0) ESL_XEXCEPTION(eslESYS, "mkstemp() failed.");
umask(old_mode);
if ((fp = fdopen(fd, "w+b")) == NULL) ESL_XEXCEPTION(eslESYS, "fdopen() failed.");
if (unlink(path) < 0) ESL_XEXCEPTION(eslESYS, "unlink() failed.");
*ret_fp = fp;
free(path);
return eslOK;
ERROR:
if (path != NULL) free(path);
if (fp != NULL) fclose(fp);
*ret_fp = NULL;
return status;
}
/* Function: esl_tmpfile_named()
*
* Purpose: Open a persistent temporary file relative to the current
* working directory. The file name is constructed from the
* <basename6X> argument, which must be a modifiable string
* ending in the six characters "XXXXXX". These are
* replaced by a unique character string by a call to POSIX
* <mkstemp()>. For example, <basename6X> might be
* <esltmpXXXXXX> on input, and <esltmp12ab34> on return; or, to
* put the tmp file in a subdirectory under the current
* working directory, something like <my_subdir/esltmpXXXXXX>
* on input resulting in something like
* <my_subdir/esltmp12ab34> on return. The tmpfile is opened
* for reading and writing (in mode <w+b> with permissions
* 0600) and the opened <FILE *> handle is returned through
* <ret_fp>.
*
* The created tmpfile is persistent: it will be visible in
* a directory listing, and will remain after program
* termination unless the caller explicitly removes it by a
* <remove()> or <unlink()> call.
*
* To use this function securely, if you reopen the
* tmpfile, you must only reopen it for reading, not
* writing, and you must not trust the contents.
*
* Because the <basename6X> will be modified, it cannot be
* a string constant (especially on a picky compiler like
* gcc). You have to declare it with something like
* <char tmpfile[32] = "esltmpXXXXXX";>
* not
* <char *tmpfile = "esltmpXXXXXX";>
* because a compiler is allowed to make the <*tmpfile> version
* a constant.
*
* Returns: <eslOK> on success, <basename6X> contains the name of the
* tmpfile, and <ret_fp> contains a new <FILE *> stream for the
* opened file.
*
* <eslFAIL> on failure, and <ret_fp> is returned NULL and
* the contents of <basename6X> are undefined. The most
* common reason for a failure will be that the caller does
* not have write permission for the directory that
* <basename6X> is in. Easel handles this as a normal (user)
* failure, not an exception, because these permissions are
* most likely in the user's control (in contrast to
* <esl_tmpfile()>, which always uses a system <TMPDIR>
* that should always be user-writable on a properly
* configured POSIX system).
*
* Xref: STL11/85.
*/
int
esl_tmpfile_named(char *basename6X, FILE **ret_fp)
{
FILE *fp;
mode_t old_mode;
int fd;
*ret_fp = NULL;
old_mode = umask(077);
if ((fd = mkstemp(basename6X)) < 0) return eslFAIL;
umask(old_mode);
if ((fp = fdopen(fd, "w+b")) == NULL) return eslFAIL;
*ret_fp = fp;
return eslOK;
}
/* Function: esl_getcwd()
* Synopsis: Gets the path for the current working directory.
*
* Purpose: Returns the path for the current working directory
* in <*ret_cwd>, as reported by POSIX <getcwd()>.
* <*ret_cmd> is allocated here and must be freed by
* the caller.
*
* Returns: <eslOK> on success, and <*ret_cwd> points to
* the pathname of the current working directory.
*
* If <getcwd()> is unavailable on this system,
* returns <eslEUNIMPLEMENTED> and <*ret_cwd> is <NULL>.
*
* If the pathname length exceeds a set limit (16384 char),
* returns <eslERANGE> and <*ret_cwd> is <NULL>.
*
* Throws: <eslEMEM> on allocation failure; <*ret_cwd> is <NULL>.
* <eslESYS> on getcwd() failure; <*ret_cwd> is <NULL>.
*
* Xref: J7/54.
*/
int
esl_getcwd(char **ret_cwd)
{
char *cwd = NULL;
int status = eslOK;
#ifdef _POSIX_VERSION
int nalloc = 256;
int maxalloc = 16384;
do {
ESL_ALLOC(cwd, sizeof(char) * nalloc);
if (getcwd(cwd, nalloc) == NULL)
{
if (errno != ERANGE) ESL_XEXCEPTION(eslESYS, "unexpected getcwd() error");
if (nalloc * 2 > maxalloc) { status = eslERANGE; goto ERROR; }
free(cwd);
cwd = NULL;
nalloc *= 2;
}
} while (cwd == NULL);
*ret_cwd = cwd;
return status;
ERROR:
if (cwd) free(cwd);
*ret_cwd = NULL;
return status;
#else
*ret_cwd = NULL;
return eslEUNIMPLEMENTED;
#endif
}
/*----------------- end of file path/name functions ------------------------*/
/*****************************************************************
* 8. Typed comparison routines.
*****************************************************************/
/* Function: esl_DCompare()
*
* Purpose: Compare two floating point scalars <a> and <b> for approximate equality.
* Return <eslOK> if equal, <eslFAIL> if not.
*
* Equality is defined by being within a relative
* epsilon <tol>, as <2*fabs(a-b)/(a+b)> $\leq$ <tol>.
* Additionally, we catch the special cases where <a>
* and/or <b> are 0 or -0. If both are, return <eslOK>; if
* one is, check that the absolute value of the other is
* $\leq$ <tol>.
*
* <esl_DCompare()> and <esl_FCompare()> work on <double> and <float>
* scalars, respectively.
*/
int
esl_DCompare(double a, double b, double tol)
{
if (isinf(a) && isinf(b)) return eslOK;
if (isnan(a) && isnan(b)) return eslOK;
if (!isfinite(a) || !isfinite(b)) return eslFAIL;
if (a == b) return eslOK;
if (fabs(a) == 0. && fabs(b) <= tol) return eslOK;
if (fabs(b) == 0. && fabs(a) <= tol) return eslOK;
if (2.*fabs(a-b) / fabs(a+b) <= tol) return eslOK;
return eslFAIL;
}
int
esl_FCompare(float a, float b, float tol)
{
if (isinf(a) && isinf(b)) return eslOK;
if (isnan(a) && isnan(b)) return eslOK;
if (!isfinite(a) || !isfinite(b)) return eslFAIL;
if (a == b) return eslOK;
if (fabs(a) == 0. && fabs(b) <= tol) return eslOK;
if (fabs(b) == 0. && fabs(a) <= tol) return eslOK;
if (2.*fabs(a-b) / fabs(a+b) <= tol) return eslOK;
return eslFAIL;
}
/* Function: esl_DCompareAbs()
*
* Purpose: Compare two floating point scalars <a> and <b> for
* approximate equality, by absolute difference. Return
* <eslOK> if equal, <eslFAIL> if not.
*
* Equality is defined as <fabs(a-b) $\leq$ tol> for finite
* <a,b>; or <inf=inf>, <NaN=NaN> when either value is not
* finite.
*
* Generally it is preferable to compare floating point
* numbers for equality using relative difference: see
* <esl_{DF}Compare()>, and also Knuth's Seminumerical
* Algorithms. However, cases arise where absolute
* difference comparison is preferred. One such case is in
* comparing the log probability values of DP matrices,
* where numerical error tends to accumulate on an absolute
* scale, dependent more on the number of terms than on
* their magnitudes. DP cells with values that happen to be
* very close to zero can have high relative differences.
*/
int
esl_DCompareAbs(double a, double b, double tol)
{
if (isinf(a) && isinf(b)) return eslOK;
if (isnan(a) && isnan(b)) return eslOK;
if (!isfinite(a) || !isfinite(b)) return eslFAIL;
if (fabs(a-b) <= tol) return eslOK;
return eslFAIL;
}
int
esl_FCompareAbs(float a, float b, float tol)
{
if (isinf(a) && isinf(b)) return eslOK;
if (isnan(a) && isnan(b)) return eslOK;
if (!isfinite(a) || !isfinite(b)) return eslFAIL;
if (fabs(a-b) <= tol) return eslOK;
return eslFAIL;
}
/* Function: esl_CCompare()
* Synopsis: Compare two optional strings for equality.
*
* Purpose: Compare two optional strings <s1> and <s2>
* for equality.
*
* If they're non-<NULL> and identical up to their
* <NUL>-terminator, return <eslOK>.
*
* If they're both <NULL> (unset), return <eslOK>.
*
* Otherwise, they're not identical; return <eslFAIL>.
*/
int
esl_CCompare(char *s1, char *s2)
{
if (s1 == NULL && s2 == NULL) return eslOK;
if (s1 == NULL || s2 == NULL) return eslFAIL;
if (strcmp(s1, s2) != 0) return eslFAIL;
return eslOK;
}
/*-------------- end, typed comparison routines --------------------*/
/*****************************************************************
* 9. Unit tests.
*****************************************************************/
#ifdef eslEASEL_TESTDRIVE
static void
utest_IsInteger(void)
{
char *goodones[] = { " 99 " };
char *badones[] = { "", " 99 foo " };
int ngood = sizeof(goodones) / sizeof(char *);
int nbad = sizeof(badones) / sizeof(char *);
int i;
for (i = 0; i < ngood; i++)
if (! esl_str_IsInteger(goodones[i])) esl_fatal("esl_str_IsInteger() should have recognized %s", goodones[i]);
for (i = 0; i < nbad; i++)
if ( esl_str_IsInteger(badones[i])) esl_fatal("esl_str_IsInteger() should not have recognized %s", badones[i]);
}
static void
utest_IsReal(void)
{
char *goodones[] = { "99", " \t 99", "-99.00", "+99.00e-12", "+0xabc.defp-12", " +INFINITY", "-nan" };
char *badones[] = { "",
"FIBB_BOVIN/67-212", /* testing for a fixed bug, 17 Dec 2012, reported by ER */
};
int ngood = sizeof(goodones) / sizeof(char *);
int nbad = sizeof(badones) / sizeof(char *);
int i;
for (i = 0; i < ngood; i++)
if (! esl_str_IsReal(goodones[i])) esl_fatal("esl_str_IsReal() should have recognized %s", goodones[i]);
for (i = 0; i < nbad; i++)
if ( esl_str_IsReal(badones[i])) esl_fatal("esl_str_IsReal() should not have recognized %s", badones[i]);
}
static void
utest_strmapcat(void)
{
char *msg = "esl_strmapcat() unit test failed";
ESL_DSQ inmap[128];
char *pfx = "testing testing";
char *append = "one two three";
char *bad = "1 2 three";
char *dest;
int64_t L1;
esl_pos_t L2;
int x;
/* a simple input map, for testing */
for (x = 0; x < 128; x++) inmap[x] = eslDSQ_ILLEGAL;
for (x = 'a'; x < 'z'; x++) inmap[x] = x;
for (x = 'A'; x < 'Z'; x++) inmap[x] = x;
inmap[' '] = eslDSQ_IGNORED;
inmap[0] = '?';
L1 = strlen(pfx);
L2 = strlen(append);
if ( ( esl_strdup (pfx, L1, &dest)) != eslOK) esl_fatal(msg);
if ( ( esl_strmapcat(inmap, &dest, &L1, append, L2)) != eslOK) esl_fatal(msg);
if ( strcmp(dest, "testing testingonetwothree") != 0) esl_fatal(msg);
free(dest);
L1 = -1;
L2 = -1;
if ( ( esl_strdup (pfx, L1, &dest)) != eslOK) esl_fatal(msg);
if ( ( esl_strmapcat(inmap, &dest, &L1, append, L2)) != eslOK) esl_fatal(msg);
if ( strcmp(dest, "testing testingonetwothree") != 0) esl_fatal(msg);
free(dest);
L1 = 0;
dest = NULL;
if ( ( esl_strmapcat(inmap, &dest, &L1, pfx, -1)) != eslOK) esl_fatal(msg);
if ( ( esl_strmapcat(inmap, &dest, &L1, append, -1)) != eslOK) esl_fatal(msg);
if ( strcmp(dest, "testingtestingonetwothree") != 0) esl_fatal(msg);
free(dest);
if ( ( esl_strdup(pfx, -1, &dest)) != eslOK) esl_fatal(msg);
L1 = 8;
if ( ( esl_strmapcat(inmap, &dest, &L1, bad, -1)) != eslEINVAL) esl_fatal(msg);
if ( strcmp(dest, "testing ??three") != 0) esl_fatal(msg);
free(dest);
}
static void
utest_strtok(void)
{
char msg[] = "esl_strtok() unit test failed";
char *teststring;
char *s;
char *tok;
int toklen;
char endc;
if (esl_strdup("This is\t a sentence.", -1, &teststring) != eslOK) esl_fatal(msg);
s = teststring;
if (esl_strtok(&s, " ", &tok) != eslOK) esl_fatal(msg);
if (strcmp(tok, "This") != 0) esl_fatal(msg);
if (*s != 'i') esl_fatal(msg);
if (esl_strtok_adv(&s, " \t", &tok, &toklen, &endc) != eslOK) esl_fatal(msg);
if (strcmp(tok, "is") != 0) esl_fatal(msg);
if (*s != ' ') esl_fatal(msg);
if (toklen != 2) esl_fatal(msg);
if (endc != '\t') esl_fatal(msg);
if (esl_strtok_adv(&s, "\n", &tok, NULL, NULL) != eslOK) esl_fatal(msg);
if (strcmp(tok, " a sentence.") != 0) esl_fatal(msg);
if (*s != '\0') esl_fatal(msg);
free(teststring);
return;
}
static void
utest_sprintf(void)
{
char msg[] = "unit tests for esl_[v]sprintf() failed";
int num = 99;
char *what = "beer";
char *s = NULL;
if (esl_sprintf(&s, "%d bottles of %s", num, what) != eslOK) esl_fatal(msg);
if (strcmp(s, "99 bottles of beer") != 0) esl_fatal(msg);
free(s);
if (esl_sprintf(&s, NULL) != eslOK) esl_fatal(msg);
if (s != NULL) esl_fatal(msg);
}
static void
utest_FileExists(void)
{
char msg[] = "FileExists unit test failed";
char tmpfile[32] = "esltmpXXXXXX";
FILE *fp = NULL;
#ifdef _POSIX_VERSION
struct stat st;
mode_t mode;
#endif
/* create a tmpfile */
if (esl_tmpfile_named(tmpfile, &fp) != eslOK) esl_fatal(msg);
fprintf(fp, "Unit test.\n");
fclose(fp);
if (! esl_FileExists(tmpfile)) esl_fatal(msg);
#ifdef _POSIX_VERSION
/* The FileExists doesn't just test existence; it also checks read permission */
if (stat(tmpfile, &st) != 0) esl_fatal(msg);
mode = st.st_mode & ~S_IRUSR;
if (chmod(tmpfile, mode) != 0) esl_fatal(msg);
if (esl_FileExists(tmpfile)) esl_fatal(msg);
#endif
remove(tmpfile);
if (esl_FileExists(tmpfile)) esl_fatal(msg);
return;
}
static void
utest_tmpfile_named(void)
{
char msg[] = "tmpfile_named unit test failed";
char tmpfile[32] = "esltmpXXXXXX";
FILE *fp = NULL;
char buf[256];
if (esl_tmpfile_named(tmpfile, &fp) != eslOK) esl_fatal(msg);
fprintf(fp, "Unit test.\n");
fclose(fp);
if ((fp = fopen(tmpfile, "r")) == NULL) esl_fatal(msg);
if (fgets(buf, 256, fp) == NULL) esl_fatal(msg);
if (strcmp(buf, "Unit test.\n") != 0) esl_fatal(msg);
fclose(fp);
remove(tmpfile);
return;
}
#endif /*eslEASEL_TESTDRIVE*/
/*****************************************************************
* 10. Test driver.
*****************************************************************/
#ifdef eslEASEL_TESTDRIVE
/* gcc -g -Wall -o easel_utest -I. -L. -DeslEASEL_TESTDRIVE easel.c -leasel -lm
* ./easel_utest
*/
#include "easel.h"
int main(void)
{
#ifdef eslTEST_THROWING
esl_exception_SetHandler(&esl_nonfatal_handler);
#endif
utest_IsInteger();
utest_IsReal();
utest_strmapcat();
utest_strtok();
utest_sprintf();
utest_FileExists();
utest_tmpfile_named();
return eslOK;
}
#endif /*eslEASEL_TESTDRIVE*/
/*****************************************************************
* 11. Examples.
*****************************************************************/
#ifdef eslEASEL_EXAMPLE
/*::cexcerpt::easel_example_tmpfiles::begin::*/
/* gcc -g -Wall -o example -I. -L. -DeslEASEL_EXAMPLE_TMPFILES easel.c -leasel -lm
* ./example
*/
#include "easel.h"
int main(void)
{
char tmpfile1[32] = "esltmpXXXXXX"; /* a transient, secure tmpfile: 6 X's are important */
char tmpfile2[32] = "esltmpXXXXXX"; /* a named tmpfile */
FILE *fp = NULL;
char buf[256];
/* Example of using a secure, unnamed tmpfile.
* Note, the new tmpfile is automatically deleted, so to cleanup, just fclose() the FILE */
esl_tmpfile(tmpfile1, &fp);
fprintf(fp, "Hello world!\n");
rewind(fp);
if (fgets(buf, 256, fp) == NULL) esl_fatal("bad fread()");
printf("first temp file says: %s\n", buf);
fclose(fp);
/* Example of reasonably securely using a named tmpfile.
* To cleanup, must both fclose() the FILE and remove() the file by name */
esl_tmpfile_named(tmpfile2, &fp);
fprintf(fp, "Hello insecure world!\n");
fclose(fp); /* tmpfile2 now exists on disk and can be closed/reopened */
fp = fopen(tmpfile2, "r");
if (fgets(buf, 256, fp) == NULL) esl_fatal("bad fread()");
printf("second temp file says: %s\n", buf);
fclose(fp);
remove(tmpfile2); /* disk file cleanup necessary with this version. */
return eslOK;
}
/*::cexcerpt::easel_example_tmpfiles::end::*/
#endif /*eslEASEL_EXAMPLE*/
| 2.34375 | 2 |
2024-11-18T22:26:05.039667+00:00 | 2018-10-08T16:42:24 | 9ee7cbb981bb34f841c708bbb6bccf8b0d92b424 | {
"blob_id": "9ee7cbb981bb34f841c708bbb6bccf8b0d92b424",
"branch_name": "refs/heads/master",
"committer_date": "2018-10-08T16:42:24",
"content_id": "60fbeaabb0b5b0c8c55aa77487fb9c4f177523d3",
"detected_licenses": [
"MIT"
],
"directory_id": "cdb569eae89e93d7861aef47cd70959fcd794f6e",
"extension": "h",
"filename": "API.h",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 152112768,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 9892,
"license": "MIT",
"license_type": "permissive",
"path": "/test_record/API.h",
"provenance": "stackv2-0115.json.gz:150655",
"repo_name": "Waffle-Liu/miniSQL",
"revision_date": "2018-10-08T16:42:24",
"revision_id": "0dbcc23baae78bc2742553abeb847a762cdd643d",
"snapshot_id": "8079ff34c4ee2233c697bf2715691a075a5a7ebc",
"src_encoding": "GB18030",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/Waffle-Liu/miniSQL/0dbcc23baae78bc2742553abeb847a762cdd643d/test_record/API.h",
"visit_date": "2020-03-31T09:50:33.492310"
} | stackv2 | #pragma once
#include "MiniSQL.h"
#include "Buffer.h"
#include "Interpreter.h"
#include "Record.h"
#include "Catalog.h"
#include "IndexManager.h"
Record record;
IndexManager index;
CatalogManager catalog;
Interpreter parsetree;
BufferManager buf;
bool IsComEnd(string input) { // 判断是否遇到了‘;’
int pos = input.rfind(';', input.length() - 1);
if (pos == -1) return false;
else return true;
}
void ShowResult(Data data, Table tableinfo, vector<Attribute> column) {
int i, j, k;
int size = tableinfo.Attributes.size();
int* length = new int[MAX_ATTRNUM];
for (i = 0; i < size; i++) {
if (tableinfo.Attributes[i].length > tableinfo.Attributes[i].name.length())
length[i] = tableinfo.Attributes[i].length;
else length[i] = tableinfo.Attributes[i].name.length();
}
if (column[0].name == "*") {
cout << endl << "+";
for (i = 0; i < tableinfo.AttriNum; i++) {
for (j = 0; j < length[i] + 1; j++) {
cout << "-";
}
cout << "+";
}
cout << endl;
cout << "| ";
for (i = 0; i < tableinfo.AttriNum; i++) {
cout << tableinfo.Attributes[i].name;
int lengthLeft = length[i] - tableinfo.Attributes[i].name.length();
for (j = 0; j < lengthLeft; j++) {
cout << ' ';
}
cout << "| ";
}
cout << endl;
cout << "+";
for (i = 0; i < tableinfo.AttriNum; i++) {
for (j = 0; j < length[i] + 1; j++) {
cout << "-";
}
cout << "+";
}
cout << endl;
//内容
for (i = 0; i < data.Rows.size(); i++) {
cout << "| ";
for (j = 0; j < tableinfo.AttriNum; j++) {
int lengthLeft = length[j];
for (k = 0; k < data.Rows[i].Columns[j].length(); k++) {
if (data.Rows[i].Columns[j].c_str()[k] == EMPTY) break;
else {
cout << data.Rows[i].Columns[j].c_str()[k];
lengthLeft--;
}
}
for (k = 0; k < lengthLeft; k++) cout << " ";
cout << "| ";
}
cout << endl;
}
cout << "+";
for (i = 0; i < tableinfo.AttriNum; i++) {
for (j = 0; j < length[i] + 1; j++) {
cout << "-";
}
cout << "+";
}
cout << endl;
}
else {
cout << endl << "+";
for (i = 0; i < column.size(); i++) {
int col;
for (col = 0; col < tableinfo.Attributes.size(); col++) {
if (tableinfo.Attributes[col].name == column[i].name) break;
}
for (j = 0; j < tableinfo.Attributes[col].length + 1; j++) {
cout << "-";
}
cout << "+";
}
cout << endl;
cout << "| ";
for (i = 0; i < column.size(); i++) {
int col;
for (col = 0; col < tableinfo.Attributes.size(); col++) {
if (tableinfo.Attributes[col].name == column[i].name) break;
}
cout << tableinfo.Attributes[col].name;
int lengthLeft = length[col] - tableinfo.Attributes[col].name.length();
for (j = 0; j < lengthLeft; j++) {
cout << ' ';
}
cout << "| ";
}
cout << endl;
cout << "+";
for (i = 0; i < column.size(); i++) {
int col;
for (col = 0; col < tableinfo.Attributes.size(); col++) {
if (tableinfo.Attributes[col].name == column[i].name) break;
}
for (j = 0; j < tableinfo.Attributes[col].length + 1; j++) {
cout << "-";
}
cout << "+";
}
cout << endl;
//内容
for (i = 0; i < data.Rows.size(); i++) {
cout << "| ";
for (j = 0; j < column.size(); j++) {
int col;
for (col = 0; col < tableinfo.Attributes.size(); col++) {
if (tableinfo.Attributes[col].name == column[j].name) break;
}
int lengthLeft = length[col];
for (k = 0; k < data.Rows[i].Columns[col].length(); k++) {
if (data.Rows[i].Columns[col].c_str()[k] == EMPTY) break;
else {
cout << data.Rows[i].Columns[col].c_str()[k];
lengthLeft--;
}
}
for (k = 0; k < lengthLeft; k++) cout << " ";
cout << "| ";
}
cout << endl;
}
cout << "+";
for (i = 0; i < column.size(); i++) {
int col;
for (col = 0; col < tableinfo.Attributes.size(); col++) {
if (tableinfo.Attributes[col].name == column[i].name) break;
}
for (j = 0; j < length[i] + 1; j++) {
cout << "-";
}
cout << "+";
}
cout << endl;
}
cout << data.Rows.size() << " rows in set" << endl;
}
bool Execute() {
int i, j, k;
Table tableinfo;
Index indexinfo;
string tempKeyValue;
int tempPrimaryPosition = -1;
int rowCount = 0;
Data data;
string command;
string inputword;
bool ComEnd = false;
switch (parsetree.OpState) {
case CRE_TAB:
parsetree.TableIn.AttriNum = parsetree.TableIn.Attributes.size();
catalog.CreateTable(parsetree.TableIn);
record.CreateTable(parsetree.TableIn);
cout << "Table " << parsetree.TableIn.name << " has been created successfully" << endl;
break;
case DRP_TAB:
record.dropTable(parsetree.TableIn);
for (int i = 0; i < parsetree.TableIn.AttriNum; i++) {//把这各表所有的index都删掉
indexinfo = catalog.GetIndex(parsetree.TableIn.name);
if (indexinfo.index_name != "")
index.dropIndex(indexinfo);
}
catalog.DropTable(parsetree.TableIn.name);
cout << "Table " << parsetree.TableIn.name << " has been dropped successfully" << endl;
break;
case INSERT:
tableinfo = parsetree.TableIn;
if (parsetree.PrimaryKeyPosition == -1 && parsetree.UniquePosition == -1) {
record.insertValue(tableinfo, parsetree.rows);
catalog.UpdateTable(tableinfo);
cout << "One record has been inserted successfully" << endl;
break;
}
if (parsetree.PrimaryKeyPosition != -1)
{
data = record.select(tableinfo, parsetree.conditions);
if (data.Rows.size()>0) {
cout << "Primary Key Redundancy occurs, thus insertion failed" << endl;
break;
}
}
if (parsetree.UniquePosition != -1) {
data = record.select(tableinfo, parsetree.UniqueCondition);
if (data.Rows.size()>0) {
cout << "Unique Value Redundancy occurs, thus insertion failed" << endl;
break;
}
}
record.insertValue(tableinfo, parsetree.rows);
catalog.UpdateTable(tableinfo);
cout << "One record has been inserted successfully" << endl;
break;
case SEL_NOCON:
tableinfo = parsetree.TableIn;
data = record.select(tableinfo);
if (data.Rows.size() != 0)
ShowResult(data, tableinfo, parsetree.attributes);
else {
cout << "No data is found!!!" << endl;
}
break;
case SEL_CON:
tableinfo = parsetree.TableIn;
if (parsetree.conditions.size() == 1) {
for (int i = 0; i<parsetree.TableIn.Attributes.size(); i++) {
if ((parsetree.TableIn.Attributes[i].IsPrimeryKey == true || parsetree.TableIn.Attributes[i].IsUnique == true) /*&& parsetree.m_colname == parsetree.TableIn.Attributes[i].name*/) {
tempPrimaryPosition = i;
indexinfo = catalog.GetIndex(tableinfo.name);
break;
}
}
if (tempPrimaryPosition == parsetree.conditions[0].columnNum&&parsetree.conditions[0].op == Eq&&indexinfo.table_name != "") {
tempKeyValue = parsetree.conditions[0].value;
data = index.selectEqual(tableinfo, indexinfo, tempKeyValue);
}
else {
data = record.select(tableinfo, parsetree.conditions);
}
}
else {
data = record.select(tableinfo, parsetree.conditions);
}
if (data.Rows.size() != 0)
ShowResult(data, tableinfo, parsetree.attributes);
else {
cout << "No data is found!!!" << endl;
}
break;
case DEL_CON:
rowCount = record.deleteValue(parsetree.TableIn, parsetree.conditions);
cout << rowCount << " rows have been deleted." << endl;
break;
case CRE_IND:
tableinfo = parsetree.TableIn;
indexinfo = parsetree.IndexIn;
if (!tableinfo.Attributes[indexinfo.column].IsPrimeryKey && !tableinfo.Attributes[indexinfo.column].IsUnique) {//不是primary key,不可以建index
cout << "Column " << tableinfo.Attributes[indexinfo.column].name << " is not unique." << endl;
break;
}
catalog.CreateIndex(indexinfo);
index.createIndex(tableinfo, indexinfo);
catalog.UpdateIndex(indexinfo);
cout << "The index " << indexinfo.index_name << "has been created successfully" << endl;
break;
case DRP_IND:
indexinfo = catalog.GetIndex(parsetree.IndexIn.index_name);
if (indexinfo.index_name == "") {
cout << "Index" << parsetree.IndexIn.index_name << "does not exist!" << endl;
}
index.dropIndex(indexinfo);
catalog.DropIndex(parsetree.IndexIn.index_name);
cout << "The index has been dropped successfully" << endl;
break;
case EXEFILE:
while (parsetree.fin)
{
command = "";
ComEnd = 0;
while (!ComEnd) {
if (parsetree.fin.eof()) break;
getline(parsetree.fin, inputword, '\n');
ComEnd = IsComEnd(inputword);
command += inputword + " ";
}
if (parsetree.fin.eof()) break;
command += '\0';
parsetree.Parse(command);
if (!Execute()) break;
}
parsetree.fin.close();
break;
case QUIT:
cout << "You have already quit the system" << endl;
getchar();
return false;
break;
case EMPTY:
cout << "Empty query! Please enter your command!" << endl;
break;
case UNKNOWN:
cout << "The instruction is illegle." << endl;
break;
case ERR_NOEXISTTABLE:
cout << "ERROR " << ERR_NOEXISTTABLE << ": Table does not exist" << endl;
break;
case ERR_NOEXISTARRT:
cout << "ERROR " << ERR_NOEXISTARRT << ": Attribute does not exist" << endl;
break;
case ERR_NOEXISTINDEX:
cout << "ERROR " << ERR_NOEXISTINDEX << ": Index does not exist" << endl;
break;
case ERR_NOEXISTPRIKEY:
cout << "ERROR " << ERR_NOEXISTPRIKEY << ": Primary key does not exist" << endl;
break;
case ERR_EXISTTABLE:
cout << "ERROR " << ERR_EXISTTABLE << ": Table already exists" << endl;
break;
case ERR_RECREATTR:
cout << "ERROR " << ERR_RECREATTR << ": Attribute recreated" << endl;
break;
case ERR_REPETEKEY:
cout << "ERROR " << ERR_REPETEKEY << ": Primary key recreated" << endl;
break;
case ERR_EXSITINDEX:
cout << "ERROR " << ERR_EXSITINDEX << ": Index '" << parsetree.IndexIn.index_name << "' already exist" << endl;
break;
case ERR_OVERSIZE:
cout << "ERROR " << ERR_OVERSIZE << ": The length of char is oversize " << endl;
break;
}
return true;
}
| 2.140625 | 2 |
2024-11-18T22:26:05.117606+00:00 | 2015-06-28T01:09:50 | 2b494aa6dd12665e49ba527cedbe4dffa1ce210c | {
"blob_id": "2b494aa6dd12665e49ba527cedbe4dffa1ce210c",
"branch_name": "refs/heads/master",
"committer_date": "2015-06-28T01:09:50",
"content_id": "e9d07794a1e69006f8f16b722d85751d4f814a82",
"detected_licenses": [
"MIT"
],
"directory_id": "a30844c3b955489bb8ce2f0f23937d8bea4d8c0a",
"extension": "c",
"filename": "rti.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": null,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2361,
"license": "MIT",
"license_type": "permissive",
"path": "/kinetis/PI-RACK/Source/periph/rti/rti.c",
"provenance": "stackv2-0115.json.gz:150784",
"repo_name": "beankonducta/pi-rack",
"revision_date": "2015-06-28T01:09:50",
"revision_id": "967df7b4bbb754906172d93de66bc37c217d216d",
"snapshot_id": "ef835ce01c0d32d67c5b16f4d50f3eb8ad944fd9",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/beankonducta/pi-rack/967df7b4bbb754906172d93de66bc37c217d216d/kinetis/PI-RACK/Source/periph/rti/rti.c",
"visit_date": "2023-03-16T19:59:11.701793"
} | stackv2 | #include "MKE02Z2.h"
#include "rti.h"
#define RTI_SETPRESCALER(presc) (RTICTL = presc)
#define RTI_ENABLE_INTERRUPTS() (CRGINT_RTIE = 1)
#define RTI_CLEAR_FLAG() (CRGFLG_RTIF = 1)
#define RTI_SET_CLOCK_SOURCE(src) (CLKSEL_PLLSEL = src)
#define RTI_MAX_FCNS 20
#define RTI_IS_VALID_ID(id) (((id >= 0) && (id < RTI_MAX_FCNS)) ? _TRUE : _FALSE)
typedef struct {
int period;
int count;
rti_ptr callback;
void *data;
} rti_cb;
bool rti_isInit = _FALSE;
rti_cb rti_tbl[RTI_MAX_FCNS];
void rti_Init()
{
if (rti_isInit == _TRUE)
return;
rti_isInit = _TRUE;
int i;
for (i = 0; i < RTI_MAX_FCNS; i++)
{
rti_tbl[i].callback = NULL;
}
// The RTI is implemented using the PIT
SIM->SCGC |= SIM_SCGC_PIT_MASK;
PIT->MCR = 0x00; // Enable module
PIT->CHANNEL[RTI_PIT_CH].LDVAL = 20 * 1000 * 1000 / RTI_FREQ; // For a 20MHz clock
PIT->CHANNEL[RTI_PIT_CH].TCTRL |= PIT_TCTRL_TIE_MASK; // Enable interrupts
PIT->CHANNEL[RTI_PIT_CH].TCTRL |= PIT_TCTRL_TEN_MASK; // Start counting
NVIC_EnableIRQ((RTI_PIT_CH == 0) ? PIT_CH0_IRQn : PIT_CH1_IRQn); // Enable interrupts on the NVIC
return;
}
int rti_Register (rti_ptr callback, void *data, int period, int delay)
{
int i;
for (i = 0; i < RTI_MAX_FCNS; i++)
{
if (rti_tbl[i].callback == NULL)
{
rti_tbl[i].callback = callback;
rti_tbl[i].data = data;
rti_tbl[i].period = period;
rti_tbl[i].count = delay;
break;
}
}
if (i == RTI_MAX_FCNS)
{
error("rti: attempted to store a callback but the memory is full.\n");
}
return i;
}
void rti_SetPeriod(int id, int period)
{
if (!RTI_IS_VALID_ID(id))
{
return;
}
rti_tbl[id].period = period;
return;
}
void rti_Cancel(int id)
{
if (!RTI_IS_VALID_ID(id))
return;
rti_tbl[id].callback = NULL;
}
void rti_ISR(void)
{
PIT->CHANNEL[RTI_PIT_CH].TFLG |= PIT_TFLG_TIF_MASK; // Clear interrupt flag
int i;
for (i = 0; i < RTI_MAX_FCNS; i++)
{
if (rti_tbl[i].callback != NULL)
{
if ((--rti_tbl[i].count) == 0)
{
rti_tbl[i].callback(rti_tbl[i].data, rti_tbl[i].period, i);
if (rti_tbl[i].count != 0) // If the callback deleted itself and registered another function in the same place, count wont be 0
break;
if (rti_tbl[i].period == RTI_ONCE)
rti_tbl[i].callback = NULL;
else
rti_tbl[i].count = rti_tbl[i].period;
}
}
}
return;
}
| 2.34375 | 2 |
2024-11-18T22:26:05.217986+00:00 | 2022-11-23T14:16:15 | c6f3dfc1fccdabea521421a31c07a024ba77d96a | {
"blob_id": "c6f3dfc1fccdabea521421a31c07a024ba77d96a",
"branch_name": "refs/heads/master",
"committer_date": "2022-11-23T14:16:15",
"content_id": "32a31f7dbbdf9d2cd5d6153e498d5d75ae21f1ee",
"detected_licenses": [
"BSD-3-Clause-Open-MPI"
],
"directory_id": "e16ebe774e710b19e78006bc45276161a26b40d9",
"extension": "c",
"filename": "PB_Cindxg2p.c",
"fork_events_count": 56,
"gha_created_at": "2018-06-30T23:24:28",
"gha_event_created_at": "2022-11-23T14:16:16",
"gha_language": "Fortran",
"gha_license_id": "NOASSERTION",
"github_id": 139287059,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2822,
"license": "BSD-3-Clause-Open-MPI",
"license_type": "permissive",
"path": "/PBLAS/SRC/PTOOLS/PB_Cindxg2p.c",
"provenance": "stackv2-0115.json.gz:150914",
"repo_name": "Reference-ScaLAPACK/scalapack",
"revision_date": "2022-11-23T14:16:15",
"revision_id": "2072b8602f0a5a84d77a712121f7715c58a2e80d",
"snapshot_id": "1f06618119a19c2b0af51ad7cdee61aee84d835d",
"src_encoding": "UTF-8",
"star_events_count": 108,
"url": "https://raw.githubusercontent.com/Reference-ScaLAPACK/scalapack/2072b8602f0a5a84d77a712121f7715c58a2e80d/PBLAS/SRC/PTOOLS/PB_Cindxg2p.c",
"visit_date": "2022-12-02T05:15:46.251774"
} | stackv2 | /* ---------------------------------------------------------------------
*
* -- PBLAS auxiliary routine (version 2.0) --
* University of Tennessee, Knoxville, Oak Ridge National Laboratory,
* and University of California, Berkeley.
* April 1, 1998
*
* ---------------------------------------------------------------------
*/
/*
* Include files
*/
#include "../pblas.h"
#include "../PBpblas.h"
#include "../PBtools.h"
#include "../PBblacs.h"
#include "../PBblas.h"
#ifdef __STDC__
Int PB_Cindxg2p( Int IG, Int INB, Int NB, Int PROC, Int SRCPROC, Int NPROCS )
#else
Int PB_Cindxg2p( IG, INB, NB, PROC, SRCPROC, NPROCS )
/*
* .. Scalar Arguments ..
*/
Int IG, INB, NB, NPROCS, PROC, SRCPROC;
#endif
{
/*
* Purpose
* =======
*
* PB_Cindxg2p computes the process coordinate which posseses the entry
* of a matrix specified by a global index IG.
*
* Arguments
* =========
*
* IG (global input) INTEGER
* On entry, IG specifies the global index of the matrix entry.
* IG must be at least zero.
*
* INB (global input) INTEGER
* On entry, INB specifies the size of the first block of the
* global matrix. INB must be at least one.
*
* NB (global input) INTEGER
* On entry, NB specifies the size of the blocks used to parti-
* tion the matrix. NB must be at least one.
*
* PROC (local dummy) INTEGER
* On entry, PROC is a dummy argument in this case in order to
* unify the calling sequence of the tool-routines.
*
* SRCPROC (global input) INTEGER
* On entry, SRCPROC specifies the coordinate of the process
* that possesses the first row or column of the matrix. When
* SRCPROC = -1, the data is not distributed but replicated,
* otherwise SRCPROC must be at least zero and strictly less
* than NPROCS.
*
* NPROCS (global input) INTEGER
* On entry, NPROCS specifies the total number of process rows
* or columns over which the matrix is distributed. NPROCS must
* be at least one.
*
* -- Written on April 1, 1998 by
* Antoine Petitet, University of Tennessee, Knoxville 37996, USA.
*
* ---------------------------------------------------------------------
*/
/* ..
* .. Executable Statements ..
*
*/
if( ( IG < INB ) || ( SRCPROC == -1 ) || ( NPROCS == 1 ) )
/*
* IG belongs to the first block, or the data is not distributed, or there is
* just one process in this dimension of the grid.
*/
return( SRCPROC );
/*
* Otherwise, IG is in block 1 + ( IG - INB ) / NB. Add this to SRCPROC and
* take the NPROCS modulo (definition of the block-cyclic data distribution).
*/
PROC = SRCPROC + 1 + ( IG - INB ) / NB;
return( MPosMod( PROC, NPROCS ) );
/*
* End of PB_Cindxg2p
*/
}
| 2.515625 | 3 |
2024-11-18T20:50:19.260508+00:00 | 2021-08-22T15:43:31 | 77592f56876667a43d17d453d03ca73bc6485198 | {
"blob_id": "77592f56876667a43d17d453d03ca73bc6485198",
"branch_name": "refs/heads/master",
"committer_date": "2021-08-22T15:43:31",
"content_id": "f9f676c86d80eca4c56e0c02bfc973dbfe321218",
"detected_licenses": [
"ISC"
],
"directory_id": "dbdbe2a9a124948545a076ab0dd37029eec5b564",
"extension": "c",
"filename": "sort.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": null,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2105,
"license": "ISC",
"license_type": "permissive",
"path": "/tests/arrays/sort.c",
"provenance": "stackv2-0118.json.gz:36661",
"repo_name": "macasieb/ts2c",
"revision_date": "2021-08-22T15:43:31",
"revision_id": "9c54287ff80fed298c256e23cb136aff273e9101",
"snapshot_id": "8e50570b2df7aa8eb289e80ff3ef6e3554effa8f",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/macasieb/ts2c/9c54287ff80fed298c256e23cb136aff273e9101/tests/arrays/sort.c",
"visit_date": "2023-07-14T03:47:31.319285"
} | stackv2 | #include <string.h>
#include <stdlib.h>
#include <assert.h>
#include <stdio.h>
typedef short int16_t;
#define ARRAY_CREATE(array, init_capacity, init_size) {\
array = malloc(sizeof(*array)); \
array->data = malloc((init_capacity) * sizeof(*array->data)); \
assert(array->data != NULL); \
array->capacity = init_capacity; \
array->size = init_size; \
}
#define ARRAY_PUSH(array, item) {\
if (array->size == array->capacity) { \
array->capacity *= 2; \
array->data = realloc(array->data, array->capacity * sizeof(*array->data)); \
assert(array->data != NULL); \
} \
array->data[array->size++] = item; \
}
int array_int16_t_cmp(const void* a, const void* b) {
return ( *(int16_t*)a - *(int16_t*)b );
}
int array_str_cmp(const void* a, const void* b) {
return strcmp(*(const char **)a, *(const char **)b);
}
struct array_string_t {
int16_t size;
int16_t capacity;
const char ** data;
};
struct array_number_t {
int16_t size;
int16_t capacity;
int16_t* data;
};
static struct array_number_t * arr1;
static int16_t i;
static struct array_string_t * arr2;
static struct array_string_t * tmp_result;
static int16_t j;
int main(void) {
ARRAY_CREATE(arr1, 3, 3);
arr1->data[0] = 1;
arr1->data[1] = 3;
arr1->data[2] = 2;
qsort(arr1->data, arr1->size, sizeof(*arr1->data), array_int16_t_cmp);
printf("[ ");
for (i = 0; i < arr1->size; i++) {
if (i != 0)
printf(", ");
printf("%d", arr1->data[i]);
}
printf(" ]\n");
ARRAY_CREATE(arr2, 5, 5);
arr2->data[0] = "def";
arr2->data[1] = "abc";
arr2->data[2] = "aba";
arr2->data[3] = "ced";
arr2->data[4] = "meh";
qsort(arr2->data, arr2->size, sizeof(*arr2->data), array_str_cmp);
tmp_result = ((void *)arr2);
printf("[ ");
for (j = 0; j < tmp_result->size; j++) {
if (j != 0)
printf(", ");
printf("\"%s\"", tmp_result->data[j]);
}
printf(" ]\n");
free(arr1->data);
free(arr1);
free(arr2->data);
free(arr2);
return 0;
}
| 3.25 | 3 |
2024-11-18T20:50:19.357566+00:00 | 2019-02-10T02:46:17 | 2a3c734cb2bde7b3fd33ebda0113198193b394ff | {
"blob_id": "2a3c734cb2bde7b3fd33ebda0113198193b394ff",
"branch_name": "refs/heads/master",
"committer_date": "2019-02-10T02:46:17",
"content_id": "565e73c1cd91c2d925d466111f49a7a83b1585e5",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "6e747ddc6658b3e8cada4cc14269ba18d6f12322",
"extension": "h",
"filename": "MathUtils.h",
"fork_events_count": 1,
"gha_created_at": "2018-09-08T04:18:36",
"gha_event_created_at": "2022-10-01T20:58:53",
"gha_language": "Python",
"gha_license_id": "Apache-2.0",
"github_id": 147900388,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 732,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/YookaiC/Game/SDLEx/Utils/MathUtils.h",
"provenance": "stackv2-0118.json.gz:36790",
"repo_name": "cn-s3bit/YookaiC",
"revision_date": "2019-02-10T02:46:17",
"revision_id": "5f4711ee4217544df9ebe683c1147db3b4c707d7",
"snapshot_id": "d0601e7df39e934bc93c5a323390ed615101f768",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/cn-s3bit/YookaiC/5f4711ee4217544df9ebe683c1147db3b4c707d7/YookaiC/Game/SDLEx/Utils/MathUtils.h",
"visit_date": "2022-10-10T22:17:23.095803"
} | stackv2 | #ifndef SDLEX_MATH_UTILS_H
#define SDLEX_MATH_UTILS_H
#include "../SDLWithPlugins.h"
#define SDLEx_clamp(x, lower, upper) SDL_max(SDL_min(x, upper), lower)
inline SDL_Point new_sdl_point(int x, int y) {
SDL_Point ret;
ret.x = x; ret.y = y;
return ret;
}
inline float sdlex_pong(float x, float lower, float upper) {
if (x > upper) x = lower + x - upper;
return x;
}
inline void sdlex_swap_float(float * x1, float * x2) {
register float tmp = *x1;
*x1 = *x2;
*x2 = tmp;
}
inline float sdlex_map_float(const float old_val, const float lower_old, const float upper_old, const float lower_new, const float upper_new) {
return (old_val - lower_old) / (upper_old - lower_old) * (upper_new - lower_new) + lower_new;
}
#endif
| 2.25 | 2 |
2024-11-18T20:50:23.618627+00:00 | 2021-07-28T23:34:22 | 5c5ae8cee4b375908ecbda0800725c079710c39a | {
"blob_id": "5c5ae8cee4b375908ecbda0800725c079710c39a",
"branch_name": "refs/heads/master",
"committer_date": "2021-07-28T23:34:22",
"content_id": "1561704a7fa08228b1f1b2d0590c3657b37c3623",
"detected_licenses": [
"MIT"
],
"directory_id": "b965cc528e8caa3ba64052792e1dfb4f599cbe4b",
"extension": "c",
"filename": "makepw.c",
"fork_events_count": 1,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 242262479,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1924,
"license": "MIT",
"license_type": "permissive",
"path": "/makepw.c",
"provenance": "stackv2-0118.json.gz:37176",
"repo_name": "deven/phoenix",
"revision_date": "2021-07-28T23:34:22",
"revision_id": "323f68082605af54609d17d22c55f03d99d31e0d",
"snapshot_id": "94928e1641b02cb536a9286356468cc5c3547af2",
"src_encoding": "UTF-8",
"star_events_count": 2,
"url": "https://raw.githubusercontent.com/deven/phoenix/323f68082605af54609d17d22c55f03d99d31e0d/makepw.c",
"visit_date": "2023-04-10T00:09:20.239251"
} | stackv2 | /* -*- C -*-
*
* $Id$
*
* Utility program to encrypt a single password in standard Unix "crypt" form.
*
* Copyright 1992-2021 Deven T. Corzine <deven@ties.org>
*
* SPDX-License-Identifier: MIT
*
*/
#include "config.h"
#include <stdio.h>
#include <time.h>
#ifdef HAVE_STDLIB_H
#include <stdlib.h>
#endif
#ifdef HAVE_UNISTD_H
#include <unistd.h>
#endif
#ifdef HAVE_STRING_H
#include <string.h>
#endif
#ifdef HAVE_STRINGS_H
#include <strings.h>
#endif
#ifdef HAVE_CRYPT_H
#include <crypt.h>
#endif
#ifndef HAVE_GETPASS
#error getpass() required!
#endif
static char *usage = "Usage: %s [<password>]\n";
static char *key = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789./";
int main(int argc, char **argv)
{
char *password = NULL;
int opts = 1;
int arg;
char pw[256], salt[3];
for (arg = 1; arg < argc && argv[arg]; arg++) {
if (opts && !strcmp(argv[arg], "--")) {
opts = 0;
} else if (opts && !strcmp(argv[arg], "--help")) {
fprintf(stdout, usage, argv[0]);
exit(0);
} else if (opts && !strcmp(argv[arg], "--version")) {
fprintf(stdout, "makepw %s\n", VERSION);
exit(0);
} else if (opts && argv[arg][0] == '-') {
fprintf(stderr, usage, argv[0]);
exit(1);
} else if (password == NULL) {
password = argv[arg];
} else {
fprintf(stderr, usage, argv[0]);
exit(1);
}
}
sleep(1);
srandom(time(NULL));
salt[0] = key[random() & 63];
salt[1] = key[random() & 63];
salt[2] = 0;
if (password) {
printf("%s\n", crypt(password, salt));
} else {
while (1) {
strcpy(pw, getpass("Enter password: "));
if (!strcmp(pw, "")) exit(0);
if (!strcmp(pw, getpass("Re-enter password to verify: "))) break;
}
printf("Encrypted password: %s\n", crypt(pw, salt));
}
return 0;
}
| 2.625 | 3 |
2024-11-18T20:50:23.687349+00:00 | 2019-12-08T14:12:03 | b6fd3e2b218e27ab24119ba17fc8a1df5284b692 | {
"blob_id": "b6fd3e2b218e27ab24119ba17fc8a1df5284b692",
"branch_name": "refs/heads/master",
"committer_date": "2019-12-08T14:12:03",
"content_id": "157aa513db30bc74ca97f2c1580a091a5c0f442a",
"detected_licenses": [
"ISC"
],
"directory_id": "ed43224856a57345f0d9ec7f0d6e8334e0ff2962",
"extension": "c",
"filename": "rdfl_utils.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 51709211,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 671,
"license": "ISC",
"license_type": "permissive",
"path": "/lib/rdfl/rdfl_utils.c",
"provenance": "stackv2-0118.json.gz:37304",
"repo_name": "yartff/rdfl",
"revision_date": "2019-12-08T14:12:03",
"revision_id": "27f1847e27907fc654bb0c37761a88f626dade02",
"snapshot_id": "cefad75c51088b51ed719afbecbd85e9185155d2",
"src_encoding": "UTF-8",
"star_events_count": 2,
"url": "https://raw.githubusercontent.com/yartff/rdfl/27f1847e27907fc654bb0c37761a88f626dade02/lib/rdfl/rdfl_utils.c",
"visit_date": "2021-06-07T05:27:43.280605"
} | stackv2 | #include "rdfl.h"
#include "buffer.h"
// Utils
//
inline int rdfl_eofreached(t_rdfl *obj)
{ return (RDFL_OPT_ISSET(obj->settings, LOCAL_REACHED_EOF)); }
void
rdfl_consume_size(t_rdfl *obj, size_t s) {
b_consume_size(&obj->data, s);
if (RDFL_OPT_ISSET(obj->settings, RDFL_FULLEMPTY))
b_fullclean_if_empty(&obj->data);
}
inline
void *
rdfl_getinplace_next_chunk(t_rdfl *obj, size_t *s, size_t *total_s) {
void *ptr;
ptr = b_consumer_ptr(&obj->data, s);
if (total_s) *total_s = obj->data.consumer.total;
return (ptr);
}
#if 0
ssize_t
rdfl_read_ignore_size(t_rdfl *obj, size_t s) {
(void)obj, (void)s; // if monitoring etc...
return (-1);
}
#endif
| 2 | 2 |
2024-11-18T20:50:23.752453+00:00 | 2018-03-24T16:37:00 | d6442c9dd4b77a01be18b795e57c80acaf58f85c | {
"blob_id": "d6442c9dd4b77a01be18b795e57c80acaf58f85c",
"branch_name": "refs/heads/master",
"committer_date": "2018-03-24T16:37:00",
"content_id": "22e521260a13bd9967df2a69bad15d954cfc52a4",
"detected_licenses": [
"MIT"
],
"directory_id": "d756bd304018e01d7aabac7e5b55a73313754cd8",
"extension": "h",
"filename": "number_theory.h",
"fork_events_count": 1,
"gha_created_at": "2018-03-25T09:08:23",
"gha_event_created_at": "2018-03-25T09:08:24",
"gha_language": null,
"gha_license_id": null,
"github_id": 126680921,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 220,
"license": "MIT",
"license_type": "permissive",
"path": "/lib/number_theory.h",
"provenance": "stackv2-0118.json.gz:37433",
"repo_name": "kokil87/mathx",
"revision_date": "2018-03-24T16:37:00",
"revision_id": "553f3656a6eb2da8af83bf2dd275cc24c13db4f5",
"snapshot_id": "2ce9f704b7d53a7e85ff8adecd346c926ce7d60b",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/kokil87/mathx/553f3656a6eb2da8af83bf2dd275cc24c13db4f5/lib/number_theory.h",
"visit_date": "2021-04-18T21:54:45.113246"
} | stackv2 | #ifndef _NUMBER_THEORY_H_
#define _NUMBER_THEORY_H_
int gcd(int a, int b){
while( a * b ){
if(a > b)
a = a % b;
else
b = b % a;
}
return a + b;
}
int lcm(int a, int b) {
return (a * b / gcd(a,b));
}
#endif | 2.15625 | 2 |
2024-11-18T20:50:23.843399+00:00 | 2016-09-20T06:13:17 | 1a8cb738da2e416c0e2089aed6cab0c81aad7ed3 | {
"blob_id": "1a8cb738da2e416c0e2089aed6cab0c81aad7ed3",
"branch_name": "refs/heads/master",
"committer_date": "2016-09-20T06:13:17",
"content_id": "bf1555fcaaf956a7eb0735d14ea9b80e6f31e8ec",
"detected_licenses": [
"MIT"
],
"directory_id": "c7f9d81caf98d9be2be8e26aa6b6fa6757d0bccc",
"extension": "c",
"filename": "convert.c",
"fork_events_count": 1,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 5216618,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 7544,
"license": "MIT",
"license_type": "permissive",
"path": "/ext/php_embed/convert.c",
"provenance": "stackv2-0118.json.gz:37562",
"repo_name": "do-aki/php_embed",
"revision_date": "2016-09-20T06:13:17",
"revision_id": "3d6bff8f2f74c808572cfd729591cbf4ea337f78",
"snapshot_id": "d6e260c9c606da865e06688185a40392b826f0b9",
"src_encoding": "UTF-8",
"star_events_count": 2,
"url": "https://raw.githubusercontent.com/do-aki/php_embed/3d6bff8f2f74c808572cfd729591cbf4ea337f78/ext/php_embed/convert.c",
"visit_date": "2020-05-18T02:17:25.547875"
} | stackv2 | #include "php_embed.h"
VALUE zval_to_array(zval *zv) {
HashTable *ht;
HashPosition pos;
zval **data;
VALUE ret;
convert_to_array(zv);
ht = Z_ARRVAL_P(zv);
ret = rb_ary_new2(zend_hash_num_elements(ht));
zend_hash_internal_pointer_reset_ex(ht, &pos);
while (SUCCESS == zend_hash_get_current_data_ex(ht, (void **)&data, &pos)) {
rb_ary_push(ret, new_php_embed_value(*data));
zend_hash_move_forward_ex(ht, &pos);
}
return ret;
}
VALUE zval_to_hash(zval *zv) {
HashTable *ht;
HashPosition pos;
zval **data;
VALUE ret;
convert_to_array(zv);
ht = Z_ARRVAL_P(zv);
ret = rb_hash_new();
zend_hash_internal_pointer_reset_ex(ht, &pos);
while (zend_hash_get_current_data_ex(ht, (void **)&data, &pos) == SUCCESS) {
char* key_str;
uint key_len;
ulong num_index;
VALUE key = Qnil;
VALUE val = new_php_embed_value(*data);
switch(zend_hash_get_current_key_ex(ht, &key_str, &key_len, &num_index, 0, &pos)) {
case HASH_KEY_IS_STRING:
//key = rb_str_new(key_str, key_len);
key = rb_str_new_cstr(key_str);
break;
case HASH_KEY_IS_LONG:
key = LONG2NUM(num_index);
break;
}
rb_hash_aset(ret, key, val);
zend_hash_move_forward_ex(ht, &pos);
}
return ret;
}
static int hash_to_php_string_array(VALUE key, VALUE value, VALUE ary) {
VALUE k,v,r;
int key_type;
if (key == Qundef) {
return ST_CONTINUE;
}
key_type = TYPE(key);
if (key_type != T_FIXNUM && key_type != T_BIGNUM
&& key_type != T_STRING && key_type != T_SYMBOL) {
rb_raise(rb_eRuntimeError, "invalid key (%d)", key_type);
}
k = convert_value_to_php_string(key);
r = rb_str_new_cstr(RSTRING_PTR(k));
rb_str_cat2(r, "=>");
v = convert_value_to_php_string(value);
rb_str_cat2(r, RSTRING_PTR(v));
rb_ary_push(ary, r);
return ST_CONTINUE;
}
static int hash_to_zval(VALUE key, VALUE value, VALUE zval_array) {
zval *v;
zval *ary;
if (key == Qundef) {
return ST_CONTINUE;
}
ary = (zval *)zval_array;
v = value_to_zval(value);
if (key == Qtrue) {
zend_hash_index_update(Z_ARRVAL_P(ary), 1, &v, sizeof(zval *), NULL);
return ST_CONTINUE;
}
if (key == Qfalse || key == Qnil) {
zend_hash_index_update(Z_ARRVAL_P(ary), 0, &v, sizeof(zval *), NULL);
return ST_CONTINUE;
}
if (TYPE(key) == T_FIXNUM) {
int idx = FIX2INT(key);
zend_hash_index_update(Z_ARRVAL_P(ary), idx, &v, sizeof(zval *), NULL);
return ST_CONTINUE;
}
switch (TYPE(key)) {
case T_BIGNUM:
key = rb_big2str(key, 10);
break;
case T_SYMBOL:
key = rb_sym_to_s(key);
break;
case T_STRING:
key = rb_string_value(&key);
break;
default:
rb_raise(rb_eRuntimeError, "invalid key (%d)", TYPE(key));
}
//ZEND_HANDLE_NUMERIC(RSTRING_PTR(key), RSTRING_LEN(key), zend_hash_index_update(Z_ARRVAL_P(ary), idx, &v, sizeof(zval *), NULL));
zend_symtable_update(Z_ARRVAL_P(ary), RSTRING_PTR(key), RSTRING_LEN(key) + 1, &v, sizeof(zval *), NULL);
return ST_CONTINUE;
}
VALUE convert_value_to_php_string(VALUE v) {
switch (TYPE(v)) {
case T_FALSE:
return rb_str_new_cstr("false");
case T_TRUE:
return rb_str_new_cstr("true");
case T_UNDEF:
case T_NIL:
return rb_str_new_cstr("null");
case T_FIXNUM:
return rb_fix2str(v, 10);
case T_BIGNUM:
return rb_big2str(v, 10);
case T_FLOAT:
return rb_funcall(v, rb_intern("to_s"), 0);
case T_ARRAY:
{
int i;
VALUE ret = rb_str_new_cstr("array(");
for(i=0;i<RARRAY_LEN(v);++i) {
VALUE p = convert_value_to_php_string(RARRAY_PTR(v)[i]);
if (TYPE(p) == T_STRING) {
rb_str_cat2(ret, StringValuePtr(p));
}
if (i != RARRAY_LEN(v)-1) {
rb_str_cat2(ret, ",");
}
}
rb_str_cat2(ret, ")");
return ret;
}
case T_HASH:
{
VALUE ret = rb_str_new_cstr("array(");
VALUE ary = rb_ary_new();
VALUE *p;
int i, len;
rb_hash_foreach(v, hash_to_php_string_array, ary);
len = RARRAY_LEN(ary);
p = RARRAY_PTR(ary);
for(i=0; i<len; ++i) {
rb_str_cat2(ret, StringValuePtr(p[i]));
if (i != len-1) {
rb_str_cat2(ret, ",");
}
}
rb_str_cat2(ret, ")");
return ret;
}
case T_SYMBOL:
{
VALUE symbol_str = rb_sym_to_s(v);
VALUE ret = rb_str_new_cstr("'");
rb_str_cat2(ret, StringValuePtr(symbol_str));
rb_str_cat2(ret, "'");
return ret;
}
case T_STRING:
{
VALUE ret = rb_str_new_cstr("'");
rb_str_cat2(ret, StringValuePtr(v));
rb_str_cat2(ret, "'");
return ret;
}
default:
rb_raise(rb_eRuntimeError, "no implemented");
}
}
zval *value_to_zval(VALUE v) {
zval *zv;
MAKE_STD_ZVAL(zv);
switch (TYPE(v)) {
case T_FALSE:
ZVAL_FALSE(zv);
return zv;
case T_TRUE:
ZVAL_TRUE(zv);
return zv;
case T_UNDEF:
case T_NIL:
ZVAL_NULL(zv);
return zv;
case T_FIXNUM:
ZVAL_LONG(zv, rb_fix2int(v));
return zv;
case T_BIGNUM:
ZVAL_LONG(zv, rb_big2long(v)); // FIXME: bignum over long
return zv;
case T_FLOAT:
ZVAL_DOUBLE(zv, RFLOAT_VALUE(v));
return zv;
case T_ARRAY:
{
int i;
array_init(zv);
for(i=0;i<RARRAY_LEN(v);++i) {
zval *add = value_to_zval(RARRAY_PTR(v)[i]);
zend_hash_next_index_insert(Z_ARRVAL_P(zv), &add, sizeof(zval *), NULL);
}
return zv;
}
case T_HASH:
{
array_init(zv);
rb_hash_foreach(v, hash_to_zval, (VALUE)zv);
return zv;
}
case T_SYMBOL:
{
VALUE symbol_str = rb_sym_to_s(v);
ZVAL_STRINGL(zv, StringValuePtr(symbol_str), RSTRING_LEN(symbol_str), 1);
return zv;
}
case T_STRING:
{
ZVAL_STRINGL(zv, StringValuePtr(v), RSTRING_LEN(v), 1);
return zv;
}
default:
{
if (CLASS_OF(v) == cPhpEmbedValue) {
php_value* pv;
Data_Get_Struct(v, php_value, pv);
MAKE_COPY_ZVAL(&pv->value, zv);
return zv;
}
}
FREE_ZVAL(zv);
rb_raise(rb_eRuntimeError, "no implemented");
}
}
| 2.5 | 2 |
2024-11-18T20:50:24.259143+00:00 | 2023-03-25T17:57:33 | 45b48b0b42f61e6879a2329200618c13ed951d64 | {
"blob_id": "45b48b0b42f61e6879a2329200618c13ed951d64",
"branch_name": "refs/heads/master",
"committer_date": "2023-03-25T17:57:33",
"content_id": "e0c04c0d04d8b8b1fb40a350a619909b0730b8bc",
"detected_licenses": [
"BSD-2-Clause"
],
"directory_id": "6601ed1b6c24e8b7e78312aeaadf816262c4bee3",
"extension": "c",
"filename": "bm_join_bufferless_SPM_sync.c",
"fork_events_count": 90,
"gha_created_at": "2011-03-19T17:01:39",
"gha_event_created_at": "2023-03-25T17:57:35",
"gha_language": "VHDL",
"gha_license_id": "BSD-2-Clause",
"github_id": 1500522,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 6485,
"license": "BSD-2-Clause",
"license_type": "permissive",
"path": "/c/apps/s4noc/bm_join_bufferless_SPM_sync.c",
"provenance": "stackv2-0118.json.gz:37820",
"repo_name": "t-crest/patmos",
"revision_date": "2023-03-25T17:57:33",
"revision_id": "c63dadffa3db2ad241c31ae6e952d6fe2298986a",
"snapshot_id": "bb9764c5897ee8bbac2a336cb09d7bb77d54916a",
"src_encoding": "UTF-8",
"star_events_count": 108,
"url": "https://raw.githubusercontent.com/t-crest/patmos/c63dadffa3db2ad241c31ae6e952d6fe2298986a/c/apps/s4noc/bm_join_bufferless_SPM_sync.c",
"visit_date": "2023-04-11T12:18:37.795018"
} | stackv2 | /*
2-producers/join/consumer benchmark for the S4NOC paper.
Trim the DELAY of the producer until no tokens are lost.
Author: Martin Schoeberl and Luca Pezzarossa
*/
#include <stdio.h>
#include <machine/spm.h>
#include "../../libcorethread/corethread.h"
#include "s4noc.h"
#define PRODUCER1_CORE 1
#define PRODUCER2_CORE 4
#define JOIN_CORE 8
#define CONSUMER_CORE 3
#define SEND_SLOT_PRODU1_TO_JOIN 0
#define SEND_SLOT_PRODU2_TO_JOIN 2
#define SEND_SLOT_JOIN_TO_CONSU 0
//#define LEN 20 // in words
//#define BUF_LEN 16 // in words
volatile _UNCACHED int started_producer1;
volatile _UNCACHED int started_producer2;
volatile _UNCACHED int started_join;
volatile _UNCACHED int started_consumer;
volatile _UNCACHED int finished_producer1;
volatile _UNCACHED int finished_producer2;
volatile _UNCACHED int finished_join;
volatile _UNCACHED int finished_consumer;
volatile _UNCACHED int end_flag;
volatile _UNCACHED int result;
volatile _UNCACHED int time;
volatile _UNCACHED int time1;
volatile _UNCACHED int time2;
volatile _UNCACHED int sync_valid;
volatile _UNCACHED int sync_time;
void consumer(void* arg) {
volatile _SPM int *s4noc = (volatile _SPM int *) (S4NOC_ADDRESS);
_SPM int * sum = (_SPM int *) D_SPM_BASE;
_SPM int * i = (_SPM int *) D_SPM_BASE + 4;
_SPM int * j = (_SPM int *) D_SPM_BASE + 8;
//register int sum = 0;
*sum = 0;
// Get started
started_consumer = 1;
//for (int i=0; i<LEN; ++i) {
for (*i=0; *i<LEN/BUF_LEN; ++(*i)) {
for (*j=0; *j<BUF_LEN; ++(*j)) {
while (!s4noc[RX_READY]) {;}
*sum += s4noc[IN_DATA];
}
}
time = *timer_ptr;
time1 = time - time1;
time2 = time - time2;
result = *sum;
finished_consumer = 1;
// Join threads
int ret = 0;
corethread_exit(&ret);
return;
}
void producer1(void* arg) {
volatile _SPM int *s4noc = (volatile _SPM int *) (S4NOC_ADDRESS);
int val = 0;
// Get started
started_producer1 = 1;
// Synchronizing as much as possible with producer 1
while(sync_valid == 0) {;}
while(*timer_ptr < sync_time) {;}
// Start timing
time1 = *timer_ptr;
for (int i=0; i<LEN/BUF_LEN; ++i) {
for (int j=0; j<BUF_LEN; ++j) {
while (!s4noc[TX_FREE]) {;}
*dead_ptr = DELAY;
val = *dead_ptr;
s4noc[SEND_SLOT_PRODU1_TO_JOIN] = 1;
}
}
finished_producer1 = 1;
while (end_flag==0) {
while (!s4noc[TX_FREE]) {;}
*dead_ptr = DELAY;
val = *dead_ptr;
s4noc[SEND_SLOT_PRODU1_TO_JOIN] = 0;
}
// Join threads
int ret = 0;
corethread_exit(&ret);
return;
}
void producer2(void* arg) {
volatile _SPM int *s4noc = (volatile _SPM int *) (S4NOC_ADDRESS);
int val = 0;
// Get started
started_producer2 = 1;
// Synchronizing as much as possible with producer 1
while(sync_valid == 0) {;}
while(*timer_ptr < sync_time) {;}
// Start timing
time2 = *timer_ptr;
for (int i=0; i<LEN/BUF_LEN; ++i) {
for (int j=0; j<BUF_LEN; ++j) {
while (!s4noc[TX_FREE]) {;}
*dead_ptr = DELAY;
val = *dead_ptr;
s4noc[SEND_SLOT_PRODU2_TO_JOIN] = 2;
}
}
finished_producer2 = 1;
while (end_flag==0) {
while (!s4noc[TX_FREE]) {;}
*dead_ptr = DELAY;
val = *dead_ptr;
s4noc[SEND_SLOT_PRODU2_TO_JOIN] = 0;
}
// Join threads
int ret = 0;
corethread_exit(&ret);
return;
}
void join(void* arg) {
volatile _SPM int *s4noc = (volatile _SPM int *) (S4NOC_ADDRESS);
int val = 0;
_SPM int * tmp = (_SPM int *) D_SPM_BASE;
_SPM int * tmp1 = (_SPM int *) D_SPM_BASE + 4;
_SPM int * tmp2 = (_SPM int *) D_SPM_BASE + 8;
_SPM int * i = (_SPM int *) D_SPM_BASE + 12;
_SPM int * j = (_SPM int *) D_SPM_BASE + 16;
// Get started
started_join=1;
for (*i=0; *i<LEN/BUF_LEN; ++(*i)) {
for (*j=0; *j<BUF_LEN; ++(*j)) {
*tmp = 0;
while (!s4noc[RX_READY]) {;}
*tmp1 = s4noc[IN_DATA];
while (!s4noc[RX_READY]) {;}
*tmp2 = s4noc[IN_DATA];
if ((*tmp2==2 && *tmp1==1) || (*tmp2==1 && *tmp1==2)) {
*tmp = 1;
}
while (!s4noc[TX_FREE]) {;}
s4noc[SEND_SLOT_JOIN_TO_CONSU] = *tmp;
}
}
finished_join=1;
while (end_flag==0) {
while (!s4noc[TX_FREE]) {;}
s4noc[SEND_SLOT_JOIN_TO_CONSU] = 0;
}
// Join threads
int ret = 0;
corethread_exit(&ret);
return;
}
// The main acts as producer
int main() {
int val = 0;
end_flag = 0;
result = 0;
started_producer1 = 0;
started_producer2 = 0;
started_join = 0;
started_consumer = 0;
finished_producer1 = 0;
finished_producer2 = 0;
finished_join = 0;
finished_consumer = 0;
sync_valid = 0;
sync_time = 0;
printf("Synchronized 2-producers/join/consumer benchmark for the S4NOC paper:\n");
printf(" Delay: %d\n", DELAY);
printf(" Number of cores: %d\n", get_cpucnt());
printf(" Total packets sent: %d\n", LEN);
printf(" Buffer size: %d\n", BUF_LEN);
printf("Runnning test:\n");
corethread_create(CONSUMER_CORE, &consumer, NULL);
while(started_consumer == 0) {;}
printf(" Consumer is ready.\n");
corethread_create(JOIN_CORE, &join, NULL);
while(started_join == 0) {;}
printf(" Join is ready.\n");
corethread_create(PRODUCER2_CORE, &producer2, NULL);
corethread_create(PRODUCER1_CORE, &producer1, NULL);
while(started_producer1 == 0) {;}
printf(" Producer-1 has started.\n");
while(started_producer2 == 0) {;}
printf(" Producer-2 has started.\n [...]\n");
sync_time = *timer_ptr + 80000000;
*dead_ptr = 800000;
val = *dead_ptr;
sync_valid = 1;
while(finished_producer1 == 0) {;}
printf(" Producer-1 has finished.\n");
while(finished_producer2 == 0) {;}
printf(" Producer-2 has finished.\n");
while(finished_join == 0) {;}
printf(" Join has finished.\n");
while(finished_consumer == 0) {;}
printf(" Consumer has finished.\n");
*dead_ptr = 8000000;
val = *dead_ptr;
printf("Results: \n");
printf(" %d valid pakets out of of %d received.\n", result, LEN);
printf(" Reception time of %d cycles -> %g cycles per received packet (from Producer-1).\n", time1, 1. * time1/LEN);
printf(" Reception time of %d cycles -> %g cycles per received packet (from Producer-2).\n", time2, 1. * time2/LEN);
// Join threads
int *retval;
end_flag = 1;
corethread_join(PRODUCER1_CORE, (void **)&retval);
corethread_join(PRODUCER2_CORE, (void **)&retval);
corethread_join(JOIN_CORE, (void **)&retval);
corethread_join(CONSUMER_CORE, (void **)&retval);
printf("End of program.\n");
return val;
}
| 2.546875 | 3 |
2024-11-18T20:50:24.671825+00:00 | 2020-08-15T05:41:38 | e6fda0f7c6d8571feb0b8df2b5bcd06dc4669df5 | {
"blob_id": "e6fda0f7c6d8571feb0b8df2b5bcd06dc4669df5",
"branch_name": "refs/heads/master",
"committer_date": "2020-08-15T05:41:38",
"content_id": "65f5c05a4b8db2f1d24675d7f0625c07aa001a91",
"detected_licenses": [
"MIT"
],
"directory_id": "29fc54660ba40c8157e73d42f8bc1a78d708419e",
"extension": "c",
"filename": "FDLST.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 286804171,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 570,
"license": "MIT",
"license_type": "permissive",
"path": "/FDLST.c",
"provenance": "stackv2-0118.json.gz:38337",
"repo_name": "Tejaswini-TR/fdlst",
"revision_date": "2020-08-15T05:41:38",
"revision_id": "d656d258747b027c0b9fc180b72d1d75f6749c2f",
"snapshot_id": "9e8fc74c7fe2f936bfc1e7f4dd9183a05be915d6",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/Tejaswini-TR/fdlst/d656d258747b027c0b9fc180b72d1d75f6749c2f/FDLST.c",
"visit_date": "2022-12-08T16:34:18.371910"
} | stackv2 | #include<stdio.h>
main()
{
int n;
printf("select number between 1 to 5: ");
scanf("%d",&n);
switch(n)
{
case 1:
printf("food item 1-DOSA\n price -rs.150 ");
break;
case 2:
printf("Food item 2- roti\n price -rs.129");
break;
case 3:
printf("food item 3- PIZZA\n price -rs.239");
break;
case 4:
printf("food item 4- ice cream \n price -rs.99");
break;
case 5:
printf("food item 5-SANDWITCH \n price -rs.149");
break;
default:
printf("don't wanna eat?,then go just sleep");
}
return 0;
}
| 2.765625 | 3 |
2024-11-18T20:50:24.724893+00:00 | 2021-07-04T00:55:22 | 5909d4c5133259bcd3e4a0af3b0d353ab2a56db4 | {
"blob_id": "5909d4c5133259bcd3e4a0af3b0d353ab2a56db4",
"branch_name": "refs/heads/main",
"committer_date": "2021-07-04T00:55:22",
"content_id": "4caaccbabb4dacabe9b233184f27cd7a11cfe3db",
"detected_licenses": [
"MIT"
],
"directory_id": "3481c787981fac896f30e1928e257ccf1ccd76b0",
"extension": "c",
"filename": "aula1.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 382696961,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 589,
"license": "MIT",
"license_type": "permissive",
"path": "/Project1/Project1/aula1.c",
"provenance": "stackv2-0118.json.gz:38467",
"repo_name": "FelipeFerreiraSS/linguagem-de-programacao_C_ads",
"revision_date": "2021-07-04T00:55:22",
"revision_id": "c87c57f56bc909a8a9b9d25dad36ac43cfb33b7c",
"snapshot_id": "5670465a4e5d0a5df4a255a3e4fd69f5ea486bd1",
"src_encoding": "WINDOWS-1252",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/FelipeFerreiraSS/linguagem-de-programacao_C_ads/c87c57f56bc909a8a9b9d25dad36ac43cfb33b7c/Project1/Project1/aula1.c",
"visit_date": "2023-06-13T02:06:19.080161"
} | stackv2 | #include <stdio.h>
#include <locale.h>
int main() {
setlocale(LC_ALL, "Portuguese");
// Exercicio
// Primeiro declare todas as valiaveis variavel
int x;
int y;
int res;
printf("Digite um o primeiro valor:\n"); // Sintace de input
scanf_s("%i", &x);
printf("Digite um o segundo valor:\n");
scanf_s("%i", &y);
res = x + y;
printf("A soma de %i mais %i é iqual a %i", x, y, res); //print
// IF e ELSE
int n1 = 1;
int n2 = 2;
if (n1 > n2) {
printf("%i é maior que %i", n1, n2);
}
else {
printf("%i é menor que %i", n1, n2);
}
// Switch case
return 0;
} | 3.53125 | 4 |
2024-11-18T20:50:24.868963+00:00 | 2016-01-29T00:13:11 | 653b847ceb163d84e09f73cf4277af49f3c2d946 | {
"blob_id": "653b847ceb163d84e09f73cf4277af49f3c2d946",
"branch_name": "refs/heads/master",
"committer_date": "2016-01-29T00:13:11",
"content_id": "b90cadfea90c5d136f0d922863360b933df4017b",
"detected_licenses": [
"MIT"
],
"directory_id": "acf69038e2c00c5fcd5125ff27917b6249c1d7a3",
"extension": "c",
"filename": "manager.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 49333117,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 5369,
"license": "MIT",
"license_type": "permissive",
"path": "/manager.c",
"provenance": "stackv2-0118.json.gz:38725",
"repo_name": "hdwilber/um",
"revision_date": "2016-01-29T00:13:11",
"revision_id": "9fbe465084af4fdbdcb009a13c60a1f2f7829b66",
"snapshot_id": "3dd57ade018c16dfa7f0f791491025d1838ae066",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/hdwilber/um/9fbe465084af4fdbdcb009a13c60a1f2f7829b66/manager.c",
"visit_date": "2021-01-10T11:35:24.532640"
} | stackv2 | #include "manager.h"
#include <gtk/gtk.h>
void manager_user_add(GtkButton*, gpointer);
void manager_user_set(GtkButton*, gpointer);
void manager_user_del(GtkButton*, gpointer);
void manager_group_add(GtkButton *, gpointer );
void manager_group_set(GtkButton *, gpointer );
void manager_group_del(GtkButton *, gpointer );
static gboolean
on_delete_event (GtkWidget *widget, GdkEvent *event, gpointer data) {
g_print ("Going out...\n");
gtk_main_quit();
return TRUE;
}
Manager *manager_new(char *p) {
Manager *m = NULL;
m = (Manager *)malloc(sizeof(Manager));
if (m != NULL) {
m->b = gtk_builder_new_from_file(p);
m->main = GTK_WIDGET(gtk_builder_get_object(m->b, "main_window"));
m->us = users_new(m->b);
m->gs = groups_new (m->b);
gtk_widget_show (m->main);
/*Añade las funcionalidades a los eventos */
g_signal_connect (m->main, "delete-event", G_CALLBACK (on_delete_event), NULL);
g_signal_connect (m->main, "destroy", G_CALLBACK (gtk_main_quit), NULL);
g_object_set_data (G_OBJECT(m->us->tv), "manager", (gpointer)m);
g_object_set_data (G_OBJECT(m->gs->tv), "manager", (gpointer)m);
g_signal_connect(m->us->add, "clicked", G_CALLBACK(manager_user_add), m);
g_signal_connect(m->us->set, "clicked", G_CALLBACK(manager_user_set), m);
g_signal_connect(m->us->del, "clicked", G_CALLBACK(manager_user_del), (gpointer)m);
g_signal_connect(m->gs->add, "clicked", G_CALLBACK(manager_group_add), (gpointer)m);
/*g_signal_connect(m->gs->set, "clicked", G_CALLBACK(manager_group_set), m);*/
/*g_signal_connect(m->gs->del, "clicked", G_CALLBACK(manager_group_del), (gpointer)m);*/
}
return m;
}
void manager_group_set(GtkButton *button, gpointer data)
{
}
void manager_group_del(GtkButton *button, gpointer data)
{
}
void manager_group_add(GtkButton *button, gpointer data)
{
Manager *m = (Manager *)data;
GroupsItem grp;
grp.gid= 0;
grp.name = "";
grp.is_new= TRUE;
grp.in_user = FALSE;
groups_insert(m->gs, &grp);
}
void manager_user_add(GtkButton *button, gpointer data)
{
Manager *m = (Manager *)data;
UsersItem user;
user.uid = 0;
user.name = "";
user.home = "";
user.fullname = "";
user.shell = "/usr/bash";
user.is_new= TRUE;
user.n_groups = 0;
user.groups = NULL;
users_insert (m->us, &user);
}
void manager_user_set (GtkButton *btn, gpointer data) {
Manager *m = (Manager *)data;
Users *us = m->us;
UsersItem *ui = users_get_current (us);
users_item_to_string (ui);
char *myoutput=NULL, *mystd=NULL;
int myexit=0;
GError *err ;
char *fullcmd = NULL;
char **myargs =NULL;
if (ui->is_new) {
char cmd[] = "/usr/sbin/useradd";
char *aux = "";
if (g_strcmp0(ui->name, "") == 0) {
}
else {
if (g_strcmp0(ui->fullname, "") != 0) {
aux = g_strdup_printf ("-c|\"%s,,,\"", ui->fullname);
}
if (g_strcmp0(ui->home, "") != 0) {
aux = g_strdup_printf ("%s|-m|-d|%s",aux, ui->home);
}
if (g_strcmp0(ui->shell, "") != 0) {
aux = g_strdup_printf("%s|-s|%s", aux, ui->shell);
}
fullcmd = g_strdup_printf("TOTAL CMD: %s|%s|%s", cmd, aux, ui->name);
}
}
else {
UsersItem *u = _find_by_id (us, ui->uid);
g_print ("Changing: %s to %s\n", u->name, ui->name);
if (u != NULL) {
char cmd[] = "/usr/sbin/usermod";
char *aux = "";
if (g_strcmp0(u->name, ui->name) != 0) {
aux = g_strdup_printf( "-l|%s",ui->name);
}
if(g_strcmp0(u->home, ui->home) != 0) {
aux = g_strdup_printf( "%s|-dm|%s",aux, ui->home);
}
if (g_strcmp0(u->shell, ui->shell) != 0) {
aux = g_strdup_printf( "%s|-s|%s", aux, ui->shell);
}
if (g_strcmp0(u->fullname, ui->fullname) != 0) {
aux = g_strdup_printf( "%s|-c|\"%s,,,\"", aux, ui->fullname);
}
if (g_strcmp0(aux, "") != 0) {
fullcmd = g_strdup_printf("%s|%s|%s",cmd, aux, u->name);
}
}
}
if (fullcmd != NULL) {
myargs = g_strsplit (fullcmd, "|", -1);
g_print ("This command to exec: %s\n", fullcmd);
/*int i = 0;*/
/*char *a = myargs[i];*/
/*while(a != NULL){*/
/*g_print ("Values: %s\t", a);*/
/*i++;*/
/*a = myargs[i];*/
/*}*/
/*g_spawn_sync (NULL, myargs, NULL, G_SPAWN_DEFAULT, NULL,NULL,*/
/*&myoutput, &mystd, &myexit, NULL);*/
/*g_print ("stdout: %s\n", myoutput);*/
/*g_print ("stderr: %s\n", mystd);*/
/*switch (myexit/256){*/
/*case 0: g_print("Success\n");*/
/*break;*/
/*case 1: g_print ("No se puede actualizar el archivo passwd. Insuficientes permisos\n");*/
/*break;*/
/*case 9: g_print ("ya existe el usuario\n");break;*/
/*}*/
}
else {
g_print ("there are no commands to exec\n");
}
}
void manager_user_del (GtkButton *btn, gpointer data)
{
Manager *m = (Manager *)data;
Users *us = m->us;
UsersItem *ui = users_get_current (us);
if (ui->name != NULL) {
char *myoutput=NULL, *mystd=NULL;
int myexit=0;
GError *err ;
char *fullcmd = NULL;
char **myargs =NULL;
if (!ui->is_new) {
char cmd[] = "/usr/sbin/userdel";
fullcmd =g_strdup_printf ("%s|%s", cmd, ui->name);
myargs = g_strsplit (fullcmd, "|", -1);
g_print ("This command to exec: %s\n", fullcmd);
}
}
}
| 2.484375 | 2 |
2024-11-18T20:50:25.091161+00:00 | 2021-08-13T17:00:39 | 761cf667a4b68a53a4c702bf582c7789a70a7d11 | {
"blob_id": "761cf667a4b68a53a4c702bf582c7789a70a7d11",
"branch_name": "refs/heads/master",
"committer_date": "2021-08-13T17:05:13",
"content_id": "7d53ee6672343f4a55b689c537250bd2132e5b03",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "324c8d2188a0a3c5447c61ae0f010b5e4e2c8a0b",
"extension": "c",
"filename": "fan_mec15xx.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": null,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 4493,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/drivers/fan_mec15xx.c",
"provenance": "stackv2-0118.json.gz:38983",
"repo_name": "novleaf/ecfw-zephyr",
"revision_date": "2021-08-13T17:00:39",
"revision_id": "c575e8de85cc783d78658a8956b6c12b526887ab",
"snapshot_id": "1dc9582f87bcc693c61d840416ac639c6cd964ab",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/novleaf/ecfw-zephyr/c575e8de85cc783d78658a8956b6c12b526887ab/drivers/fan_mec15xx.c",
"visit_date": "2023-07-04T02:29:12.644311"
} | stackv2 | /*
* Copyright (c) 2020 Intel Corporation
*
* SPDX-License-Identifier: Apache-2.0
*/
#include <zephyr.h>
#include <drivers/pwm.h>
#include <drivers/sensor.h>
#include <logging/log.h>
#include "gpio_ec.h"
#include "board_config.h"
#include "fan.h"
LOG_MODULE_REGISTER(fan, CONFIG_FAN_LOG_LEVEL);
/*
* PWM channel uses main clock frequency i.e. 48 MHz.
* For desired frequency of 60 kHz, division should be:
*
* division = main clock freq / desired freq.
* = 48 MHz / 60 kHz = 800.
*
* PWM Duty cycle = pulse width / period.
*
* To calculate duty cycle in percentage, multiplier should be:
* multiplier = division / 100
* = 800 / 100 = 8.
*/
#define PWM_FREQ_MULT 8
#define MAX_DUTY_CYCLE 100u
#define DT_PWM_INST(x) DT_NODELABEL(pwm##x)
#define DT_TACH_INST(x) DT_NODELABEL(tach##x)
#define PWM_LABEL(x) DT_LABEL(DT_PWM_INST(x))
#define TACH_LABEL(x) DT_LABEL(DT_TACH_INST(x))
#define PWM_DEV_LIST_SIZE (PWM_CH_08 + 1)
#define TACH_DEV_LIST_SIZE (TACH_CH_03 + 1)
static struct device *pwm_dev[PWM_DEV_LIST_SIZE];
static struct device *tach_dev[TACH_DEV_LIST_SIZE];
static struct fan_dev fan_table[] = {
{ PWM_CH_00, TACH_CH_00 },
{ PWM_CH_UNDEF, TACH_CH_UNDEF },
{ PWM_CH_UNDEF, TACH_CH_UNDEF },
{ PWM_CH_UNDEF, TACH_CH_UNDEF },
};
static void init_pwm_devices(void)
{
#if DT_NODE_HAS_STATUS(DT_PWM_INST(0), okay)
pwm_dev[PWM_CH_00] = device_get_binding(PWM_LABEL(0));
#endif
#if DT_NODE_HAS_STATUS(DT_PWM_INST(1), okay)
pwm_dev[PWM_CH_01] = device_get_binding(PWM_LABEL(1));
#endif
#if DT_NODE_HAS_STATUS(DT_PWM_INST(2), okay)
pwm_dev[PWM_CH_02] = device_get_binding(PWM_LABEL(2));
#endif
#if DT_NODE_HAS_STATUS(DT_PWM_INST(3), okay)
pwm_dev[PWM_CH_03] = device_get_binding(PWM_LABEL(3));
#endif
#if DT_NODE_HAS_STATUS(DT_PWM_INST(4), okay)
pwm_dev[PWM_CH_04] = device_get_binding(PWM_LABEL(4));
#endif
#if DT_NODE_HAS_STATUS(DT_PWM_INST(5), okay)
pwm_dev[PWM_CH_05] = device_get_binding(PWM_LABEL(5));
#endif
#if DT_NODE_HAS_STATUS(DT_PWM_INST(6), okay)
pwm_dev[PWM_CH_06] = device_get_binding(PWM_LABEL(6));
#endif
#if DT_NODE_HAS_STATUS(DT_PWM_INST(7), okay)
pwm_dev[PWM_CH_07] = device_get_binding(PWM_LABEL(7));
#endif
#if DT_NODE_HAS_STATUS(DT_PWM_INST(8), okay)
pwm_dev[PWM_CH_08] = device_get_binding(PWM_LABEL(8));
#endif
}
static void init_tach_devices(void)
{
#if DT_NODE_HAS_STATUS(DT_TACH_INST(0), okay)
tach_dev[TACH_CH_00] = device_get_binding(TACH_LABEL(0));
#endif
#if DT_NODE_HAS_STATUS(DT_TACH_INST(1), okay)
tach_dev[TACH_CH_01] = device_get_binding(TACH_LABEL(1));
#endif
#if DT_NODE_HAS_STATUS(DT_TACH_INST(2), okay)
tach_dev[TACH_CH_02] = device_get_binding(TACH_LABEL(2));
#endif
#if DT_NODE_HAS_STATUS(DT_TACH_INST(3), okay)
tach_dev[TACH_CH_03] = device_get_binding(TACH_LABEL(3));
#endif
}
int fan_init(int size, struct fan_dev *fan_tbl)
{
init_pwm_devices();
init_tach_devices();
if (size > ARRAY_SIZE(fan_table)) {
return -ENOTSUP;
}
for (int idx = 0; idx < size; idx++) {
if (!pwm_dev[fan_tbl[idx].pwm_ch]) {
LOG_ERR("PWM ch %d not found", fan_tbl[idx].pwm_ch);
return -ENODEV;
}
if (!tach_dev[fan_tbl[idx].tach_ch]) {
LOG_ERR("Tach ch %d not found", fan_tbl[idx].tach_ch);
return -ENODEV;
}
fan_table[idx].pwm_ch = fan_tbl[idx].pwm_ch;
fan_table[idx].tach_ch = fan_tbl[idx].tach_ch;
}
return 0;
}
int fan_power_set(bool power_state)
{
/* fan disable circuitry is active low. */
return gpio_write_pin(FAN_PWR_DISABLE_N, power_state);
}
int fan_set_duty_cycle(enum fan_type fan_idx, u8_t duty_cycle)
{
int ret;
if (fan_idx > ARRAY_SIZE(fan_table)) {
return -ENOTSUP;
}
struct fan_dev *fan = &fan_table[fan_idx];
struct device *pwm = pwm_dev[fan->pwm_ch];
if (!pwm) {
return -ENODEV;
}
if (duty_cycle > MAX_DUTY_CYCLE) {
duty_cycle = MAX_DUTY_CYCLE;
}
ret = pwm_pin_set_cycles(pwm, 0, PWM_FREQ_MULT * MAX_DUTY_CYCLE,
PWM_FREQ_MULT * duty_cycle, 0);
if (ret) {
LOG_WRN("Fan setting error: %d", ret);
return ret;
}
return 0;
}
int fan_read_rpm(enum fan_type fan_idx, u16_t *rpm)
{
int ret;
struct sensor_value val;
if (fan_idx > ARRAY_SIZE(fan_table)) {
return -ENOTSUP;
}
struct fan_dev *fan = &fan_table[fan_idx];
struct device *tach = tach_dev[fan->tach_ch];
if (!tach) {
return -ENODEV;
}
ret = sensor_sample_fetch_chan(tach, SENSOR_CHAN_RPM);
if (ret) {
return ret;
}
ret = sensor_channel_get(tach, SENSOR_CHAN_RPM, &val);
if (ret) {
return ret;
}
*rpm = (u16_t) val.val1;
return 0;
}
| 2.21875 | 2 |
2024-11-18T20:50:25.212024+00:00 | 2023-08-09T01:30:11 | 914025976dfd934b902c94a207e76fcc72afbdc5 | {
"blob_id": "914025976dfd934b902c94a207e76fcc72afbdc5",
"branch_name": "refs/heads/master",
"committer_date": "2023-08-09T01:30:11",
"content_id": "3e6b708d299489057aa4581a41cb7cbfa3dda1cf",
"detected_licenses": [
"BSD-3-Clause"
],
"directory_id": "57e03c3f73f572bdc9fda27f3718e29c81c5fbb2",
"extension": "c",
"filename": "strcase.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 228753926,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 515,
"license": "BSD-3-Clause",
"license_type": "permissive",
"path": "/cx/string/strcase.c",
"provenance": "stackv2-0118.json.gz:39111",
"repo_name": "Number5ix/cx",
"revision_date": "2023-08-09T01:30:11",
"revision_id": "ee54c0bf978a3dedb446ddb4044dd49f69571b44",
"snapshot_id": "56d4156a57461d83e4f12c8d914e4f5853aba6d0",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/Number5ix/cx/ee54c0bf978a3dedb446ddb4044dd49f69571b44/cx/string/strcase.c",
"visit_date": "2023-08-10T00:06:14.662663"
} | stackv2 | #include "string_private.h"
void strUpper(string *io)
{
uint32 i, len;
uint8 *buf;
if (!io || !STR_CHECK_VALID(*io))
return;
len = strLen(*io);
buf = strBuffer(io, 0);
for (i = 0; i < len; ++i)
buf[i] = (char)toupper(buf[i]);
}
void strLower(string *io)
{
uint32 i, len;
uint8 *buf;
if (!io || !STR_CHECK_VALID(*io))
return;
len = strLen(*io);
buf = strBuffer(io, 0);
for (i = 0; i < len; ++i)
buf[i] = (char)tolower(buf[i]);
}
| 2.515625 | 3 |
2024-11-18T20:50:25.282724+00:00 | 2022-06-10T14:28:33 | 9ca44047a93d3d844502811d87bdc457888a9da2 | {
"blob_id": "9ca44047a93d3d844502811d87bdc457888a9da2",
"branch_name": "refs/heads/master",
"committer_date": "2022-06-10T14:28:33",
"content_id": "b546293c1b98b993e1a2983da0ac452769be4478",
"detected_licenses": [
"MIT"
],
"directory_id": "c42a251cfe4873d350e2836a51d625ec1d17826e",
"extension": "h",
"filename": "buzzparser.h",
"fork_events_count": 3,
"gha_created_at": "2017-06-23T17:49:17",
"gha_event_created_at": "2022-02-28T21:23:41",
"gha_language": "C",
"gha_license_id": "MIT",
"github_id": 95243176,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1903,
"license": "MIT",
"license_type": "permissive",
"path": "/src/buzz/buzzparser.h",
"provenance": "stackv2-0118.json.gz:39239",
"repo_name": "NESTLab/Buzz",
"revision_date": "2022-06-10T14:28:33",
"revision_id": "6a9a51f9b658b76fc995152546d4b625e74abb6d",
"snapshot_id": "ec0e6d4daaa7e87b408985c595d4f799696086b1",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/NESTLab/Buzz/6a9a51f9b658b76fc995152546d4b625e74abb6d/src/buzz/buzzparser.h",
"visit_date": "2022-07-09T07:47:56.423512"
} | stackv2 | #ifndef BUZZPARSER_H
#define BUZZPARSER_H
#ifndef _GNU_SOURCE
#define _GNU_SOURCE
#endif
#include <buzz/buzzlex.h>
#include <buzz/buzzdarray.h>
#include <buzz/buzzdict.h>
#include <stdio.h>
#ifdef __cplusplus
extern "C" {
#endif
/* Forward declaration to contain a code chunk */
struct chunk_s;
/* The parser state */
struct buzzparser_s {
/* The script file name */
char* scriptfn;
/* The output assembler file name */
char* asmfn;
/* The output assembler file stream */
FILE* asmstream;
/* The lexer */
buzzlex_t lex;
/* The last fetched token */
buzztok_t tok;
/* The list of chunks */
buzzdarray_t chunks;
/* The current chunk being written */
struct chunk_s* chunk;
/* Symbol table stack */
buzzdarray_t symstack;
/* The top of the symbol table stack */
buzzdict_t syms;
/* List of string symbols */
buzzdict_t strings;
/* Label counter */
uint32_t labels;
};
typedef struct buzzparser_s* buzzparser_t;
/*
* Creates a new parser.
* In this function the arguments must be in the following order:
* [0] IGNORED The current command name.
* [1] REQUIRED The input script file name.
* [2] REQUIRED The output assembler file name.
* [3] OPTIONAL The symbol table file name.
* @param argv The number of command line arguments
* @param argv The list of command line arguments
* @return The parser state.
*/
extern buzzparser_t buzzparser_new(int argc,
char** argv);
/*
* Destroys the parser.
* @param par The parser.
*/
extern void buzzparser_destroy(buzzparser_t* par);
/*
* Parses the script.
* @return 1 if successful, 0 in case of error
*/
extern int buzzparser_parse(buzzparser_t par);
#ifdef __cplusplus
}
#endif
#endif
| 2.296875 | 2 |
2024-11-18T20:50:25.399745+00:00 | 2021-06-15T03:14:10 | 476d9fb0d40293052ed73d4cf7d3dc54abfcf2a6 | {
"blob_id": "476d9fb0d40293052ed73d4cf7d3dc54abfcf2a6",
"branch_name": "refs/heads/master",
"committer_date": "2021-06-15T03:14:10",
"content_id": "cae245a2a29d632bb0bf585efb3432a8a74943d8",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "f3181ff5c637e7bfff89266d038273bfd23e5b79",
"extension": "c",
"filename": "audio.c",
"fork_events_count": 2,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 163631526,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2054,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/components/hardware/src/audio.c",
"provenance": "stackv2-0118.json.gz:39367",
"repo_name": "IlyaMZP/emulator-launcher-odroid-go",
"revision_date": "2021-06-15T03:14:10",
"revision_id": "2dc4724a2382571052c611b89478b809b1a9a6d3",
"snapshot_id": "9474e8e3fd8d2b2e470e988733ba0cd5244b27cc",
"src_encoding": "UTF-8",
"star_events_count": 8,
"url": "https://raw.githubusercontent.com/IlyaMZP/emulator-launcher-odroid-go/2dc4724a2382571052c611b89478b809b1a9a6d3/components/hardware/src/audio.c",
"visit_date": "2021-06-24T00:11:39.713706"
} | stackv2 | #include "freertos/FreeRTOS.h"
#include "driver/i2s.h"
#include "driver/rtc_io.h"
#include "audio.h"
#define AUDIO_IO_NEGATIVE GPIO_NUM_25
#define AUDIO_IO_POSITIVE GPIO_NUM_26
#define I2S_NUM I2S_NUM_0
float audio_volume = 1.0f;
void audio_init(int audio_sample_rate)
{
i2s_config_t i2s_config = {
.mode = I2S_MODE_MASTER | I2S_MODE_TX | I2S_MODE_DAC_BUILT_IN,
.sample_rate = audio_sample_rate,
.bits_per_sample = 16,
.channel_format = I2S_CHANNEL_FMT_RIGHT_LEFT,
.communication_format = I2S_COMM_FORMAT_I2S_MSB,
.dma_buf_count = 8,
.dma_buf_len = 64,
.intr_alloc_flags = ESP_INTR_FLAG_LEVEL1,
.use_apll = 0
};
i2s_driver_install(I2S_NUM, &i2s_config, 0, NULL);
i2s_set_pin(I2S_NUM, NULL);
audio_volume = 1.0f;
}
void audio_submit(short* buf, int len)
{
if (audio_volume == 0.0f) {
for (int i = 0; i < len; i += 2) {
buf[i] = 0;
}
} else {
for (int i = 0; i < len * 2; i += 2) {
int dac0, dac1;
/* Down mix stero to mono in sample */
int sample = ((int)buf[i] + (int)buf[i + 1]) >> 1;
/* Normalize */
const float normalized = (float)sample / 0x8000;
/* Scale */
const int magnitude = 127 + 127;
const float range = magnitude * normalized * audio_volume;
/* Convert to differential output */
if (range > 127) {
dac1 = (range - 127);
dac0 = 127;
}
else if (range < -127) {
dac1 = (range + 127);
dac0 = -127;
} else {
dac1 = 0;
dac0 = range;
}
dac0 += 0x80;
dac1 = 0x80 - dac1;
dac0 <<= 8;
dac1 <<= 8;
buf[i] = (short)dac1;
buf[i + 1] = (short)dac0;
}
}
size_t written;
i2s_write(I2S_NUM, buf, len * 2 * sizeof(short), &written, portMAX_DELAY);
}
| 2.25 | 2 |
2024-11-18T20:50:25.599415+00:00 | 2021-06-28T19:49:02 | d82cda6e5002244eae177099f7a0b0595bc55645 | {
"blob_id": "d82cda6e5002244eae177099f7a0b0595bc55645",
"branch_name": "refs/heads/master",
"committer_date": "2021-06-28T19:49:02",
"content_id": "ec6a350d24c11d4389805414b05cfebd251c766a",
"detected_licenses": [
"MIT"
],
"directory_id": "4e86224a73b13d2a1b85aa2e1aed7ede2d92397f",
"extension": "c",
"filename": "tx.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 380608765,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 4857,
"license": "MIT",
"license_type": "permissive",
"path": "/6_Data Manipulation with Sys Calls and Pipes/tx.c",
"provenance": "stackv2-0118.json.gz:39625",
"repo_name": "an36/Data-Structures-N-Algorithms",
"revision_date": "2021-06-28T19:49:02",
"revision_id": "114551d4cd2dcaeb4ee7b0809fb717624de6990b",
"snapshot_id": "99233da1936af0b1db681bfbcfa3f31f1d122ebc",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/an36/Data-Structures-N-Algorithms/114551d4cd2dcaeb4ee7b0809fb717624de6990b/6_Data Manipulation with Sys Calls and Pipes/tx.c",
"visit_date": "2023-05-31T18:51:53.511497"
} | stackv2 | /*
* tx.c
*
* Author: Abdullah Almarzouq (an36@pdx.edu)
*
* Description: The program below creates two process (parent and child) by using fork().
* The child process will execute the twist program and redirect the output (using pipes) to
* the parent process which executes xor. Xor takes its input from the redirected
* output by twist.
*
*
* @argument -i the name of the input file (default: stdin)
* @argument -o the name of the output file (default: stdout)
* @argument -b the number of characters to be twisted (default: 10)
* @argument <string> the mask which must be provided (must be less than 10 characters)
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <unistd.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/wait.h>
int main(int argc, char *argv[])
{
char *inp=NULL, *oup=NULL, *mask=NULL, *b; //char inp is a variable that holds the name of the input file, and char oup hold the name of the output file.
//char mask will hold the character value of the mask for the xor program, while char b will hold the number of cahracters to twist within a block.
int i=0; // int i is a loop index.
for(i=1;i<argc;i++){ //this loop checks the command line entered by user.
if((strcmp(argv[i],"-i")==0)&&i<(argc-1)){
if((strcmp(argv[i+1],"-o")!=0)&&(strcmp(argv[i+1],"-b")!=0)){ //if the command has (-i) then this if statement checks if the preceding is a file name or just a parameter.
inp=argv[i+1];
}
}
if((strcmp(argv[i],"-o")==0)&&i<(argc-1)){
if((strcmp(argv[i+1],"-i")!=0)&&(strcmp(argv[i+1],"-b")!=0)){ //if the command has (-o) then this statement checks if the preceding is a file name of not.
oup=argv[i+1];
}
}
if((strcmp(argv[i],"-b")==0)&&i<(argc-1)){
if((strcmp(argv[i+1],"-o")!=0)&&(strcmp(argv[i+1],"-b")!=0)){ //if the command has (-b) then this statement check if the preceding is a number or not.
b=(argv[i+1]);
}
}
if((strcmp(argv[i],"-b")!=0)&&(strcmp(argv[i],"-i")!=0)&&(strcmp(argv[i],"-o")!=0)){ //while this if statement checks if the command line has a mask for the xor program.
if((strcmp(argv[i-1],"-b")!=0)&&(strcmp(argv[i-1],"-i")!=0)&&(strcmp(argv[i-1],"-o")!=0)){
mask=argv[i];
}
}
}
char *twArg[]={"./twist","-b",b,"-i",inp,(char*)0}; //twist program name and arguments
char *xorArg[]={"./xor",mask,"-o",oup ,(char*)NULL}; //xor prgoram name and arguments
int Pipe[2]; //int Pipe[2] will be the pipe to redirect the output the chile process to the parent process as an input
pipe(Pipe); //creating a pipe.
int rc = fork(); //fork() creates two processes. Parent: xor and child: twist
if(rc<0){ //if fork fails then print error and exit
fprintf(stderr,"Error: fork() failed: %s\n",strerror(errno));
exit(-1);
}
if (rc==0){ //if the value of rc=0 (child process) then this will execute twist
close(1); //closing STDOUT
dup(Pipe[1]); //duplicating Pipe[1] to replace STDOUT
close(Pipe[0]); //closing pipes
close(Pipe[1]);
execvp(twArg[0],twArg); //executes twist and redirect output to parent process (xor)
}
else{ //else executes the xor program
close(0); //closing STDIN
dup(Pipe[0]); //duplicating Pipe[0] to replace STDIN
close(Pipe[0]); //closing pipes
close(Pipe[1]);
wait(NULL); //wait for the child process to execute and finish then begin the parent process
execvp(xorArg[0],xorArg); //executes xor where the input of xor is taken from the output of twist
}
close(Pipe[0]); //closing pipes.
close(Pipe[1]);
return 0;
}
| 3.140625 | 3 |
2024-11-18T20:50:26.242079+00:00 | 2017-04-03T23:52:51 | a8da615eff0010fc504839416e955dfabe2cf8a4 | {
"blob_id": "a8da615eff0010fc504839416e955dfabe2cf8a4",
"branch_name": "refs/heads/qcom/LA.BF64",
"committer_date": "2017-04-04T18:57:02",
"content_id": "6073d959e0c071709e3e958e385cfda2e020ce3d",
"detected_licenses": [
"MIT"
],
"directory_id": "0e7268b0392fb0dddbc2e93bcb8083a45284b063",
"extension": "c",
"filename": "debug.c",
"fork_events_count": 51,
"gha_created_at": "2015-08-12T19:26:26",
"gha_event_created_at": "2019-02-15T08:52:31",
"gha_language": "C",
"gha_license_id": "NOASSERTION",
"github_id": 40619953,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 4039,
"license": "MIT",
"license_type": "permissive",
"path": "/kernel/debug.c",
"provenance": "stackv2-0118.json.gz:39881",
"repo_name": "efidroid/bootloader_lk",
"revision_date": "2017-04-03T23:52:51",
"revision_id": "91bd0e0878af6b6731986519387d17c411482d34",
"snapshot_id": "f7fec3594aa9eb64893ca332f113224f8f51120b",
"src_encoding": "UTF-8",
"star_events_count": 22,
"url": "https://raw.githubusercontent.com/efidroid/bootloader_lk/91bd0e0878af6b6731986519387d17c411482d34/kernel/debug.c",
"visit_date": "2020-04-10T20:33:41.060984"
} | stackv2 | /*
* Copyright (c) 2008-2009 Travis Geiselbrecht
*
* 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.
*/
/**
* @defgroup debug Debug
* @{
*/
/**
* @file
* @brief Debug console functions.
*/
#include <debug.h>
#include <kernel/thread.h>
#include <kernel/timer.h>
#include <platform.h>
#if WITH_LIB_CONSOLE
#include <lib/console.h>
static int cmd_threads(int argc, const cmd_args *argv);
static int cmd_threadstats(int argc, const cmd_args *argv);
static int cmd_threadload(int argc, const cmd_args *argv);
STATIC_COMMAND_START
#if DEBUGLEVEL > INFO
STATIC_COMMAND("threads", "list kernel threads", &cmd_threads)
#endif
#if THREAD_STATS
STATIC_COMMAND("threadstats", "thread level statistics", &cmd_threadstats)
STATIC_COMMAND("threadload", "toggle thread load display", &cmd_threadload)
#endif
STATIC_COMMAND_END(kernel);
#if DEBUGLEVEL > INFO
static int cmd_threads(int argc, const cmd_args *argv)
{
printf("thread list:\n");
dump_all_threads();
return 0;
}
#endif
#if THREAD_STATS
static int cmd_threadstats(int argc, const cmd_args *argv)
{
printf("thread stats:\n");
printf("\ttotal idle time: %lld\n", thread_stats.idle_time);
printf("\ttotal busy time: %lld\n", current_time_hires() - thread_stats.idle_time);
printf("\treschedules: %d\n", thread_stats.reschedules);
printf("\tcontext_switches: %d\n", thread_stats.context_switches);
printf("\tpreempts: %d\n", thread_stats.preempts);
printf("\tyields: %d\n", thread_stats.yields);
printf("\tinterrupts: %d\n", thread_stats.interrupts);
printf("\ttimer interrupts: %d\n", thread_stats.timer_ints);
printf("\ttimers: %d\n", thread_stats.timers);
return 0;
}
static enum handler_return threadload(struct timer *t, time_t now, void *arg)
{
static struct thread_stats old_stats;
static bigtime_t last_idle_time;
bigtime_t idle_time = thread_stats.idle_time;
if (current_thread == idle_thread) {
idle_time += current_time_hires() - thread_stats.last_idle_timestamp;
}
bigtime_t busy_time = 1000000ULL - (idle_time - last_idle_time);
uint busypercent = (busy_time * 10000) / (1000000);
// printf("idle_time %lld, busytime %lld\n", idle_time - last_idle_time, busy_time);
printf("LOAD: %d.%02d%%, cs %d, ints %d, timer ints %d, timers %d\n", busypercent / 100, busypercent % 100,
thread_stats.context_switches - old_stats.context_switches,
thread_stats.interrupts - old_stats.interrupts,
thread_stats.timer_ints - old_stats.timer_ints,
thread_stats.timers - old_stats.timers);
old_stats = thread_stats;
last_idle_time = idle_time;
return INT_NO_RESCHEDULE;
}
static int cmd_threadload(int argc, const cmd_args *argv)
{
static bool showthreadload = false;
static timer_t tltimer;
enter_critical_section();
if (showthreadload == false) {
// start the display
timer_initialize(&tltimer);
timer_set_periodic(&tltimer, 1000, &threadload, NULL);
showthreadload = true;
} else {
timer_cancel(&tltimer);
showthreadload = false;
}
exit_critical_section();
return 0;
}
#endif
#endif
| 2.03125 | 2 |
2024-11-18T20:50:26.364589+00:00 | 2021-05-22T21:49:22 | f6b1f4686e9fc0696a06f06f8514906defeb3ba4 | {
"blob_id": "f6b1f4686e9fc0696a06f06f8514906defeb3ba4",
"branch_name": "refs/heads/main",
"committer_date": "2021-05-22T21:49:22",
"content_id": "2df3c664ad9bb5d8fb8a045188a1f2b1274a98b9",
"detected_licenses": [
"MIT"
],
"directory_id": "0df080130d024ea941de7aa04e01aa981caace0f",
"extension": "c",
"filename": "23.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 317236245,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 287,
"license": "MIT",
"license_type": "permissive",
"path": "/Listas de Exercícios/comandos de repetição/23.c",
"provenance": "stackv2-0118.json.gz:40009",
"repo_name": "heltoncoelho/C",
"revision_date": "2021-05-22T21:49:22",
"revision_id": "7556945abb0f22194fa41eb2aac34ebbe73cad5f",
"snapshot_id": "43eb53a5b7a0455fb89cce293e3a8924b1c39373",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/heltoncoelho/C/7556945abb0f22194fa41eb2aac34ebbe73cad5f/Listas de Exercícios/comandos de repetição/23.c",
"visit_date": "2023-05-05T09:04:10.123218"
} | stackv2 | /*Leia um numero positivo e imprima seus divisores.*/
#include <stdio.h>
int main(){
int numeroPositivo;
int i;
printf("Digite um numero positivo: ");
scanf("%d",&numeroPositivo);
for(i=1;i<=numeroPositivo;i++){
if(numeroPositivo%i == 0)
printf("%d ",i);
}
return 0;
} | 3.609375 | 4 |
2024-11-18T20:50:26.447348+00:00 | 2020-05-10T05:36:24 | d3872fc3aeb885e0e2b167f25b6e3075c96544ee | {
"blob_id": "d3872fc3aeb885e0e2b167f25b6e3075c96544ee",
"branch_name": "refs/heads/master",
"committer_date": "2020-05-10T05:36:24",
"content_id": "3c1bf8126d75beeb046bf8de536ff84b71a9bf23",
"detected_licenses": [
"MIT"
],
"directory_id": "d30d3b3b924ad69491a529066c7edf3e98c51f94",
"extension": "c",
"filename": "lcd.c",
"fork_events_count": 1,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 23544295,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 10464,
"license": "MIT",
"license_type": "permissive",
"path": "/LEDTest/src/lcd.c",
"provenance": "stackv2-0118.json.gz:40138",
"repo_name": "cmacro/ARMsister",
"revision_date": "2020-05-10T05:36:24",
"revision_id": "cba5e2d2a88dae3befedebc2b97419f4503b96a6",
"snapshot_id": "442c5ff2b1c462fe80d726fb0e14ce6679ec31ee",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/cmacro/ARMsister/cba5e2d2a88dae3befedebc2b97419f4503b96a6/LEDTest/src/lcd.c",
"visit_date": "2021-01-17T09:37:25.541469"
} | stackv2 | /**
*
* @file lcd.c
* @author crystalice
* @version v1.0
* @date 2014-08-09
* @brief LCD 驱动,支持LCD_ILI9320
*
*/
#include "lcd.h"
/// LCD control line defines
// PA08 ----------> RS
// PA09 ----------> RW
// PA10 ----------> RD
// PA11 ----------> CS
// PA12 ----------> REST
#define Set_CS GPIOA->BSRR = GPIO_BSRR_BS11
#define Set_RD GPIOA->BSRR = GPIO_BSRR_BS10
#define Set_WR GPIOA->BSRR = GPIO_BSRR_BS9
#define Set_RS GPIOA->BSRR = GPIO_BSRR_BS8
#define Set_RSET GPIOA->BSRR = GPIO_BSRR_BS12
#define Clr_CS GPIOA->BSRR = GPIO_BSRR_BR11
#define Clr_RD GPIOA->BSRR = GPIO_BSRR_BR10
#define Clr_WR GPIOA->BSRR = GPIO_BSRR_BR9
#define Clr_RS GPIOA->BSRR = GPIO_BSRR_BR8
#define Clr_RSET GPIOA->BSRR = GPIO_BSRR_BR12
#define SetDataInputMode GPIOB->CRL = GPIO_CR_PPPDINPUT; \
GPIOB->CRH = GPIO_CR_PPPDINPUT
#define SetDataOutputMode GPIOB->CRL = GPIO_CR_OUT_50MHz | GPIO_CR_GP_PUSHPULL; \
GPIOB->CRH = GPIO_CR_OUT_50MHz | GPIO_CR_GP_PUSHPULL
#define SetData(x) GPIOB->ODR = x // 设置端口数据
#define GetData GPIOB->IDR // 获取端口数据
uint8_t LCD_Succended = 0x1;
uint16_t LCD_DeviceCode = 0x0;
void LCD_DeInit(void)
{
// 卸载屏幕
// 关闭 B组 数据引脚
RCC->APB2ENR &= ~RCC_APB2ENR_IOPBEN;
GPIOB->CRL = GPIO_CR_RESET;
GPIOB->CRH = GPIO_CR_RESET;
LCD_Succended = 0x1;
}
void LCD_Init(void)
{
LCD_CtrlLinesConfig();
Delay(20);
LCD_WriteReg(0x00, 0x0001);
Delay(20);
LCD_DeviceCode = LCD_ReadReg(0x00);
//if (LCD_DeviceCode == LCD_DC_ILI9320) {
LCD_Succended = 0x0;
/* Start Initial Sequence ----------------------------------------------------*/
LCD_WriteReg(LCD_REG_229,0x8000); /* Set the internal vcore voltage */
LCD_WriteReg(LCD_REG_0, 0x0001); /* Start internal OSC. */
LCD_WriteReg(LCD_REG_1, 0x0100); /* set SS and SM bit */
LCD_WriteReg(LCD_REG_2, 0x0700); /* set 1 line inversion */
LCD_WriteReg(LCD_REG_3, 0x1030); /* set GRAM write direction and BGR=1. */
LCD_WriteReg(LCD_REG_4, 0x0000); /* Resize register */
LCD_WriteReg(LCD_REG_8, 0x0202); /* set the back porch and front porch */
LCD_WriteReg(LCD_REG_9, 0x0000); /* set non-display area refresh cycle ISC[3:0] */
LCD_WriteReg(LCD_REG_10, 0x0000); /* FMARK function */
LCD_WriteReg(LCD_REG_12, 0x0000); /* RGB interface setting */
LCD_WriteReg(LCD_REG_13, 0x0000); /* Frame marker Position */
LCD_WriteReg(LCD_REG_15, 0x0000); /* RGB interface polarity */
/* Power On sequence ---------------------------------------------------------*/
LCD_WriteReg(LCD_REG_16, 0x0000); /* SAP, BT[3:0], AP, DSTB, SLP, STB */
LCD_WriteReg(LCD_REG_17, 0x0000); /* DC1[2:0], DC0[2:0], VC[2:0] */
LCD_WriteReg(LCD_REG_18, 0x0000); /* VREG1OUT voltage */
LCD_WriteReg(LCD_REG_19, 0x0000); /* VDV[4:0] for VCOM amplitude */
Delay(20); /* Dis-charge capacitor power voltage (200ms) */
LCD_WriteReg(LCD_REG_16, 0x17B0); /* SAP, BT[3:0], AP, DSTB, SLP, STB */
LCD_WriteReg(LCD_REG_17, 0x0137); /* DC1[2:0], DC0[2:0], VC[2:0] */
Delay(20); /* Delay 50 ms */
LCD_WriteReg(LCD_REG_18, 0x0139); /* VREG1OUT voltage */
Delay(20); /* Delay 50 ms */
LCD_WriteReg(LCD_REG_19, 0x1d00); /* VDV[4:0] for VCOM amplitude */
LCD_WriteReg(LCD_REG_41, 0x0013); /* VCM[4:0] for VCOMH */
Delay(20); /* Delay 50 ms */
LCD_WriteReg(LCD_REG_32, 0x0000); /* GRAM horizontal Address */
LCD_WriteReg(LCD_REG_33, 0x0000); /* GRAM Vertical Address */
/* Adjust the Gamma Curve ----------------------------------------------------*/
LCD_WriteReg(LCD_REG_48, 0x0006);
LCD_WriteReg(LCD_REG_49, 0x0101);
LCD_WriteReg(LCD_REG_50, 0x0003);
LCD_WriteReg(LCD_REG_53, 0x0106);
LCD_WriteReg(LCD_REG_54, 0x0b02);
LCD_WriteReg(LCD_REG_55, 0x0302);
LCD_WriteReg(LCD_REG_56, 0x0707);
LCD_WriteReg(LCD_REG_57, 0x0007);
LCD_WriteReg(LCD_REG_60, 0x0600);
LCD_WriteReg(LCD_REG_61, 0x020b);
/* Set GRAM area -------------------------------------------------------------*/
LCD_WriteReg(LCD_REG_80, 0x0000); /* Horizontal GRAM Start Address */
LCD_WriteReg(LCD_REG_81, 0x00EF); /* Horizontal GRAM End Address */
LCD_WriteReg(LCD_REG_82, 0x0000); /* Vertical GRAM Start Address */
LCD_WriteReg(LCD_REG_83, 0x013F); /* Vertical GRAM End Address */
LCD_WriteReg(LCD_REG_96, 0x2700); /* Gate Scan Line */
LCD_WriteReg(LCD_REG_97, 0x0001); /* NDL,VLE, REV */
LCD_WriteReg(LCD_REG_106, 0x0000); /* set scrolling line */
/* Partial Display Control ---------------------------------------------------*/
LCD_WriteReg(LCD_REG_128, 0x0000);
LCD_WriteReg(LCD_REG_129, 0x0000);
LCD_WriteReg(LCD_REG_130, 0x0000);
LCD_WriteReg(LCD_REG_131, 0x0000);
LCD_WriteReg(LCD_REG_132, 0x0000);
LCD_WriteReg(LCD_REG_133, 0x0000);
/* Panel Control -------------------------------------------------------------*/
LCD_WriteReg(LCD_REG_144, 0x0010);
LCD_WriteReg(LCD_REG_146, 0x0000);
LCD_WriteReg(LCD_REG_147, 0x0003);
LCD_WriteReg(LCD_REG_149, 0x0110);
LCD_WriteReg(LCD_REG_151, 0x0000);
LCD_WriteReg(LCD_REG_152, 0x0000);
/* Set GRAM write direction and BGR = 1 */
/* I/D=01 (Horizontal : increment, Vertical : decrement) */
/* AM=1 (address is updated in vertical writing direction) */
LCD_WriteReg(LCD_REG_3, 0x1018);
LCD_WriteReg(LCD_REG_7, 0x0173); /* 262K color and display ON */
//}
}
void LCD_SetCursor(uint16_t x, uint16_t y)
{
LCD_WriteReg(0x20, y);
LCD_WriteReg(0x21, x);
}
void LCD_Clear(uint16_t Color)
{
unsigned long int i;
LCD_SetCursor(0x0000, 0x0000);
Clr_CS;
LCD_WriteRAM_Prepare();
for(i=0;i<76800;i++)
LCD_WriteRAM(Color);
Set_CS;
}
void LCD_DrawChar(uint16_t X, uint16_t Y, uint8_t c)
{
}
void LCD_TextOut(uint16_t X, uint16_t Y, uint8_t *c)
{
}
void ili9320_WriteIndex(u16 idx)
{
GPIOB->ODR=0XFFFF; //全部输出高
Clr_RS;
Set_RD;
_delay_(1);
GPIOB->ODR = idx;
_delay_(1);
Clr_WR;
Set_WR;
Set_RS;
}
void ili9320_WriteData(u16 data)
{
GPIOB->ODR=0XFFFF; //全部输出高
Set_RS;
Set_RD;
_delay_(1);
GPIOB->ODR= data;
_delay_(1);
Clr_WR;
Set_WR;
}
u16 ili9320_ReadData(void)
{
u16 val = 0;
GPIOB->ODR =0X0000;
Set_RS;
Set_WR;
Clr_RD;
_delay_(1);
val = GPIOB->IDR;
_delay_(1);
Set_RD;
return val;
}
//// 基础函数
void LCD_WriteReg(uint8_t LCD_Reg, uint16_t LCD_RegValue)
{
// 读取寄存器
// 16线模式,P51
//
// Clr_CS;
// Clr_RS;
// Set_RD;
// SetData(LCD_Reg);
// Clr_WR;
// Set_WR;
// Set_RS;
//
// SetData(LCD_RegValue);
// Clr_WR;
// Set_WR;
// Set_CS;
Clr_CS;
ili9320_WriteIndex(LCD_Reg);
ili9320_WriteData(LCD_RegValue);
Set_CS;
}
void LCD_WR_REG(u8 data)
{
//Clr_RS;//写地址
Clr_CS;// LCD_CS_CLR;
SetData(data); // DATAOUT(data);
Clr_WR;// LCD_WR_CLR;
Set_WR;// LCD_WR_SET;
//Set_CS; // LCD_CS_SET;
}
uint16_t LCD_ReadReg(uint8_t LCD_Reg)
{
// // 写寄存器
// // 16线模式, P51
// __IO uint16_t d;
//
// Clr_CS;
// Set_RS;
// Set_RD;
// SetData(LCD_Reg);
// Clr_WR;
// Set_WR;
// Set_RS;
//
// SetDataInputMode;
// Set_RD;
// Clr_RD;
// d = GetData;
// Set_CS;
//
// SetDataOutputMode;
//
// return d;
u16 t;
Clr_RS;
Clr_CS;
LCD_WR_REG(LCD_Reg); //写入要读的寄存器号
GPIOB->CRL=0X88888888; //PB0-7 上拉输入
GPIOB->CRH=0X88888888; //PB8-15 上拉输入
GPIOB->ODR=0XFFFF; //全部输出高
//Set_RS;// LCD_RS_SET;
//Clr_CS;// LCD_CS_CLR;
//读取数据(读寄存器时,并不需要读2次)
Clr_RD;// LCD_RD_CLR;
_delay_(1); // delay_us(5);//FOR 8989,延时5us
Set_RD; // LCD_RD_SET;
t = GetData; // t=DATAIN;
Set_CS; // LCD_CS_SET;
GPIOB->CRL=0X33333333; //PB0-7 上拉输出
GPIOB->CRH=0X33333333; //PB8-15 上拉输出
GPIOB->ODR=0XFFFF; //全部输出高
return t;
// Clr_CS;
// ili9320_WriteIndex(LCD_Reg);
// LCD_Reg = ili9320_ReadData();
// Set_CS;
// return LCD_Reg;
}
void LCD_WriteRAM_Prepare(void)
{
Set_RS;
Set_RD;
SetData(0x22);
Clr_WR;
Set_WR;
Set_RS;
}
void LCD_WriteRAM(uint16_t RGB_Code)
{
SetData(RGB_Code);
Clr_WR;
Set_WR;
}
uint16_t LCD_ReadRAM(void)
{
__IO uint16_t d;
Set_RD;
Clr_RD;
d = GetData;
return d;
}
void LCD_PowerOn(void)
{
}
void LCD_DisplayOn(void)
{
}
void LCD_DisplayOff(void)
{
}
// 底层函数
void LCD_CtrlLinesConfig(void)
{
/**
* LCD GPIO configuration
*
Control line
PA08 ----------> RS
PA09 ----------> RW
PA10 ----------> RD
PA11 ----------> CS
PA12 ----------> REST
Data line
PB00 ----------> DB0
PB01 ----------> DB1
PB02 ----------> DB2
PB03 ----------> DB3
PB04 ----------> DB4
PB05 ----------> DB5
PB06 ----------> DB6
PB07 ----------> DB7
PB08 ----------> DB10
PB09 ----------> DB11
PB10 ----------> DB12
PB11 ----------> DB13
PB12 ----------> DB14
PB13 ----------> DB15
PB14 ----------> DB16
PB15 ----------> DB17
**/
//
// 打开控制线
// 数据线 PB组端口(DB0 ~ DB17) 设置为2MHz开漏输出
// 控制线 PA8 ~ PA12 设置为2MHz推挽输出
//
RCC->APB2ENR |= RCC_APB2ENR_IOPAEN | RCC_APB2ENR_IOPBEN; // | RCC_APB2ENR_AFIOEN;
// 关闭JTAG-DP,释放 PB04、PB05端口
//AFIO->MAPR &= ~AFIO_MAPR_SWJ_CFG;
//AFIO->MAPR |= AFIO_MAPR_SWJ_CFG_JTAGDISABLE;
SetDataOutputMode;
GPIOA->CRH &= ~ (GPIO_CRH_MODE8 | GPIO_CRH_CNF8 |
GPIO_CRH_MODE9 | GPIO_CRH_CNF9 |
GPIO_CRH_MODE10 | GPIO_CRH_CNF10 |
GPIO_CRH_MODE11 | GPIO_CRH_CNF11 |
GPIO_CRH_MODE12 | GPIO_CRH_CNF12);
GPIOA->CRH |= GPIO_CRH_MODE8_1 | GPIO_CRH_MODE9_1 | GPIO_CRH_MODE10_1 | GPIO_CRH_MODE11_1 | GPIO_CRH_MODE12_1;
//GPIOA->ODR |= 0x1f00;
GPIOB->ODR = 0xffff;
Set_CS;
Set_RS;
Set_WR;
Set_RD;
Set_RSET;
}
| 2.296875 | 2 |
2024-11-18T20:50:26.635788+00:00 | 2019-06-14T06:38:11 | e3429e64cbead4fb2549ce702cfd4d2dc9b9d991 | {
"blob_id": "e3429e64cbead4fb2549ce702cfd4d2dc9b9d991",
"branch_name": "refs/heads/master",
"committer_date": "2019-06-14T06:38:11",
"content_id": "bc65929a42a67529f6cb0b85a310d7fcb60eb2e5",
"detected_licenses": [
"MIT"
],
"directory_id": "f5c1d57b79cfe3857cb47171cfa5e6824d806161",
"extension": "c",
"filename": "IfElse.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": null,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1027,
"license": "MIT",
"license_type": "permissive",
"path": "/BasicExamplesC/Branching/IfElse.c",
"provenance": "stackv2-0118.json.gz:40395",
"repo_name": "paullatzelsperger/c_basic_examples",
"revision_date": "2019-06-14T06:38:11",
"revision_id": "35889a684310d4b1bdffc9665ad2ab168cff77ce",
"snapshot_id": "78e765edaffaf9f7079afc51c1ffedc6aec2f943",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/paullatzelsperger/c_basic_examples/35889a684310d4b1bdffc9665ad2ab168cff77ce/BasicExamplesC/Branching/IfElse.c",
"visit_date": "2022-01-13T02:58:09.132487"
} | stackv2 | #include <stdio.h>
#include <stdlib.h>
//void main() {
// int a = 4;
//
// if (a < 5) {
// printf("number was smaller than 5");
// }
// else {
// printf("number was greater than 5");
// }
//}
//void main() {
// srand(time(NULL));
// int a = rand() % 101; // Returns a pseudo-random integer between 0 and 100.
// printf("PRNG yields %d\n", a);
//
// if (a < 10) {
// printf("number was smaller than 10\n");
// }
// if (a < 50) {
// printf("number was smaller than 50\n");
//
// }if (a < 100) {
// printf("number was smaller than 100\n");
// }
// else {
// printf("number was greater than 100\n");
// }
//}
void IfElseDemo3() {
srand(time(NULL));
int a = rand() % 101; // Returns a pseudo-random integer between 0 and 100.
printf("PRNG yields %d\n", a);
if (a < 10) {
printf("number was smaller than 10\n");
}
else if (a < 50) {
printf("number was smaller than 50\n");
}
else if (a < 100) {
printf("number was smaller than 100\n");
}
else {
printf("number was greater than 100\n");
}
} | 3.0625 | 3 |
2024-11-18T20:50:29.595985+00:00 | 2021-04-24T09:49:23 | e73dded48bcd881be0e8d84e06d7749b3dac7d0a | {
"blob_id": "e73dded48bcd881be0e8d84e06d7749b3dac7d0a",
"branch_name": "refs/heads/master",
"committer_date": "2021-04-24T09:49:23",
"content_id": "728204957e4a4718df58cde2e57115bfe309644b",
"detected_licenses": [
"MIT"
],
"directory_id": "ae8af18da1284154189905fc941072d25a183234",
"extension": "c",
"filename": "obj_nfun.c",
"fork_events_count": 3,
"gha_created_at": "2013-01-10T09:18:14",
"gha_event_created_at": "2013-08-09T14:50:30",
"gha_language": "C",
"gha_license_id": null,
"github_id": 7537966,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2440,
"license": "MIT",
"license_type": "permissive",
"path": "/src/obj_nfun.c",
"provenance": "stackv2-0118.json.gz:41555",
"repo_name": "ab25cq/xyzsh",
"revision_date": "2021-04-24T09:49:23",
"revision_id": "d111269fbd630edf5421580f8618f5967149cd4e",
"snapshot_id": "cc42d06ff678c8828385fc0f77fea91007e139ce",
"src_encoding": "UTF-8",
"star_events_count": 48,
"url": "https://raw.githubusercontent.com/ab25cq/xyzsh/d111269fbd630edf5421580f8618f5967149cd4e/src/obj_nfun.c",
"visit_date": "2021-07-19T22:59:17.174416"
} | stackv2 | #include "config.h"
#include "xyzsh.h"
#include <string.h>
#include <stdio.h>
sObject* nfun_new_on_gc(fXyzshNativeFun fun, sObject* parent, BOOL user_object)
{
sObject* self = gc_get_free_object(T_NFUN, user_object);
SNFUN(self).mNativeFun = fun;
SNFUN(self).mParent = parent;
SNFUN(self).mOptions = MALLOC(sizeof(option_hash_it)*XYZSH_OPTION_MAX);
memset(SNFUN(self).mOptions,0, sizeof(option_hash_it)*XYZSH_OPTION_MAX);
return self;
}
void nfun_delete_on_gc(sObject* self)
{
int i;
for(i=0; i<XYZSH_OPTION_MAX; i++) {
if(SNFUN(self).mOptions[i].mKey) { FREE(SNFUN(self).mOptions[i].mKey); }
if(SNFUN(self).mOptions[i].mArg) { FREE(SNFUN(self).mOptions[i].mArg); }
}
FREE(SNFUN(self).mOptions);
}
static int options_hash_fun(char* key)
{
int value = 0;
while(*key) {
value += *key;
key++;
}
return value % XYZSH_OPTION_MAX;
}
BOOL nfun_put_option_with_argument(sObject* self, MANAGED char* key)
{
int hash_value = options_hash_fun(key);
option_hash_it* p = SNFUN(self).mOptions + hash_value;
while(1) {
if(p->mKey) {
p++;
if(p == SNFUN(self).mOptions + hash_value) {
return FALSE;
}
else if(p == SNFUN(self).mOptions + XYZSH_OPTION_MAX) {
p = SNFUN(self).mOptions;
}
}
else {
p->mKey = MANAGED key;
return TRUE;
}
}
}
BOOL nfun_option_with_argument(sObject* self, char* key)
{
int hash_value = options_hash_fun(key);
option_hash_it* p = SNFUN(self).mOptions + hash_value;
while(1) {
if(p->mKey) {
if(strcmp(p->mKey, key) == 0) {
return TRUE;
}
else {
p++;
if(p == SNFUN(self).mOptions + hash_value) {
return FALSE;
}
else if(p == SNFUN(self).mOptions + XYZSH_OPTION_MAX) {
p = SNFUN(self).mOptions;
}
}
}
else {
return FALSE;
}
}
}
int nfun_gc_children_mark(sObject* self)
{
int count = 0;
sObject* parent = SNFUN(self).mParent;
if(parent) {
if(IS_MARKED(parent) == 0) {
SET_MARK(parent);
count++;
count += object_gc_children_mark(parent);
}
}
return count;
}
| 2.53125 | 3 |
2024-11-18T20:50:29.752957+00:00 | 2018-05-16T21:44:18 | eeca31be056020e67c7bb4947988efef668200b4 | {
"blob_id": "eeca31be056020e67c7bb4947988efef668200b4",
"branch_name": "refs/heads/master",
"committer_date": "2018-05-16T21:44:18",
"content_id": "5f263e6470f81bda446ac72e17b74049b0c23f48",
"detected_licenses": [
"ISC"
],
"directory_id": "6c00ab8c0b21f487a9bbaadd57e8f390a7a0ba0e",
"extension": "h",
"filename": "parop_pthread.h",
"fork_events_count": 0,
"gha_created_at": "2019-02-28T15:01:42",
"gha_event_created_at": "2019-02-28T15:01:43",
"gha_language": null,
"gha_license_id": "ISC",
"github_id": 173132430,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 9686,
"license": "ISC",
"license_type": "permissive",
"path": "/sw/benchmarks/include/parop_pthread.h",
"provenance": "stackv2-0118.json.gz:41812",
"repo_name": "domso/rcmc",
"revision_date": "2018-05-16T21:44:18",
"revision_id": "e442772bfcc9607fadfbfc5a4f02af2d330dd8d4",
"snapshot_id": "0ad73ff096a6591bbe869d97c2a8354187fde590",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/domso/rcmc/e442772bfcc9607fadfbfc5a4f02af2d330dd8d4/sw/benchmarks/include/parop_pthread.h",
"visit_date": "2020-04-25T23:04:40.052472"
} | stackv2 | #ifndef _PAROP_PTHREAD_H
#define _PAROP_PTHREAD_H
// -----------------------------------------------------------------------------
// pthread implementation
// -----------------------------------------------------------------------------
#ifndef PAROP_MAX_THREADS
#define PAROP_MAX_THREADS 32
#endif
#include <pthread.h>
#define PAROP_LOCAL _Thread_local
int parop_max_rank;
_Thread_local int parop_my_rank;
typedef struct {
int *colors;
double *data;
double **dptr;
pthread_barrier_t barrier;
} parop_collection_t;
pthread_t parop_thread_tab[PAROP_MAX_THREADS];
void *parop_memblock[PAROP_MAX_THREADS][PAROP_MAX_MEMBLOCK];
int parop_directions[PAROP_MAX_THREADS][PAROP_MAX_DIRECTIONS];
parop_collection_t parop_collections[PAROP_MAX_COLLECTIONS];
static inline void parop_fatal(char *s)
{
machine_fatal(s);
}
// -----------------------------------------------------------------------------
// memory allocation
// -----------------------------------------------------------------------------
void *parop_def_memblock(int handle, size_t n)
{
machine_assert(handle < PAROP_MAX_MEMBLOCK);
void *p = machine_malloc(n);
if (p==0) parop_fatal("Out of memory");
parop_memblock[parop_my_rank][handle] = p;
return p;
}
// -----------------------------------------------------------------------------
// collectives
// -----------------------------------------------------------------------------
void parop_def_collection(int handle, int *colors)
{
machine_assert(handle < PAROP_MAX_COLLECTIONS);
PAROP_ONCE {
parop_collection_t *c = &parop_collections[handle];
c->colors = machine_malloc(parop_max_rank*sizeof(unsigned));
memcpy(c->colors, colors, parop_max_rank*sizeof(unsigned));
c->data = machine_malloc(parop_max_rank*sizeof(double));
c->dptr = machine_malloc(parop_max_rank*sizeof(double*));
pthread_barrier_init(&c->barrier, NULL, parop_max_rank);
}
}
static inline void parop_barrier(int handle)
{
machine_assert(handle==0); // subset barriers not yet supported
pthread_barrier_wait(&parop_collections[handle].barrier);
}
static inline void parop_allgather_int64(int handle, int64_t v, int64_t r[])
{
parop_collection_t *c = &parop_collections[handle];
c->data[parop_my_rank] = v;
pthread_barrier_wait(&c->barrier);
int i, j=0;
unsigned my_color = c->colors[parop_my_rank];
for (i=0; i<parop_max_rank; i++) {
if (c->colors[i]==my_color) {
r[j++] = c->data[i];
}
}
}
// so far only for the world communicator, because the determination of
// the root thread is difficult with sub communicators
static inline void parop_gather_int64_world(int64_t v, int64_t r[])
{
parop_collection_t *c = &parop_collections[0];
c->data[parop_my_rank] = v;
pthread_barrier_wait(&c->barrier);
int i;
PAROP_ONCE {
for (i=0; i<parop_max_rank; i++) {
r[i] = c->data[i];
}
}
}
static inline double parop_allreduce_double(int handle, unsigned op, double v)
{
int my_rank = parop_my_rank;
parop_collection_t *c = &parop_collections[handle];
c->data[my_rank] = v;
pthread_barrier_wait(&c->barrier);
unsigned r;
unsigned my_color = c->colors[my_rank];
double a = c->data[my_rank];
for (r=0; r<parop_max_rank; r++) {
if (c->colors[r]==my_color && r!=my_rank) {
double b = c->data[r];
switch (op) {
case PAROP_OP_ADD: a += b; break;
case PAROP_OP_MUL: a *= b; break;
case PAROP_OP_MIN: if (a>b) a=b; break;
case PAROP_OP_MAX: if (a<b) a=b; break;
default: machine_fatal("Unknown collective operation");
}
}
}
// this second barrier is necessary to avoid race conditions when
// two allrecudes are back to back and c->data is overwritten
// before all threads have read it
pthread_barrier_wait(&c->barrier);
return a;
}
static inline void parop_allreduce_multi_double(
int handle, unsigned op, double result[], unsigned len, double v[])
{
parop_collection_t *c = &parop_collections[handle];
c->dptr[parop_my_rank] = v;
pthread_barrier_wait(&c->barrier);
unsigned i;
for (i=0; i<len; i++) result[i] = 0.0;
unsigned r;
unsigned my_color = c->colors[parop_my_rank];
for (r=0; r<parop_max_rank; r++) {
if (c->colors[r]==my_color) {
double *p=c->dptr[r];
for (i=0; i<len; i++) {
double a = result[i];
double b = p[i];
switch (op) {
case PAROP_OP_ADD: a += b; break;
case PAROP_OP_MUL: a *= b; break;
case PAROP_OP_MAX: if (a>b) a=b; break;
case PAROP_OP_MIN: if (a<b) a=b; break;
default: parop_fatal("Unknown collective operation");
}
result[i] = a;
}
}
}
// this second barrier is necessary to avoid race conditions when
// v is freed immediately after this function.
// Especially critical if v is on the stack of the calling routine
pthread_barrier_wait(&c->barrier);
}
// -----------------------------------------------------------------------------
// point-to-point data transfers
// -----------------------------------------------------------------------------
// Two succeding entries in parop_directions belong together.
// The first on is the next node in this direction, the second
// one the node in the reverse direction (the node that sends to me)
// The direction handle must be a multiple of 2.
// To reverse the direction, the direction is xored with 1.
void parop_def_direction(int handle, int next, int prev)
{
machine_assert(handle < PAROP_MAX_DIRECTIONS && (handle&1)==0);
parop_directions[parop_my_rank][handle] = next;
parop_directions[parop_my_rank][handle+1] = prev;
}
static inline void parop_forward_begin()
{
parop_barrier(0);
}
void parop_forward_double(int direction, int len,
int dmb, int di, int dstride,
int smb, int si, int sstride)
{
int rank = parop_my_rank;
int prev = parop_directions[rank][direction^1];
if (prev >= 0) {
int i;
double *p = ((double *)parop_memblock[rank][dmb]) + di;
double *q = ((double *)parop_memblock[prev][smb]) + si;
for (i=0; i<len; i++) {
*p = *q;
p += dstride;
q += sstride;
}
}
}
void parop_forward_int64(int direction, int len,
int dmb, int di, int dstride,
int smb, int si, int sstride)
{
int rank = parop_my_rank;
int prev = parop_directions[rank][direction^1];
if (prev >= 0) {
int i;
int64_t *p = ((int64_t *)parop_memblock[rank][dmb]) + di;
int64_t *q = ((int64_t *)parop_memblock[prev][smb]) + si;
for (i=0; i<len; i++) {
*p = *q;
p += dstride;
q += sstride;
}
}
}
void parop_forward_end() {}
// -----------------------------------------------------------------------------
// broadcast data transfers
// -----------------------------------------------------------------------------
void parop_broadcast_data(int mb, int i, int len, void *data, int senderRank){
// if this Process is not the sender nothing has to be done.
// Sender Rank is only really necessarry for distributed memory
// computing models like with MPI
if(parop_my_rank != senderRank){
return;
}
else{
char *source = (char *)data;
char *target = 0;
int currentRank;
int currentByte;
for(currentRank = 0; currentRank < parop_max_rank; currentRank++){
// target now points to the start of the correct memblock
target = (char *)parop_memblock[currentRank][mb];
// target now points to the correct index within the memblock
target += i;
for(currentByte = 0; currentByte < len; currentByte++){
target[currentByte] = source[currentByte];
}
}
}
}
// -----------------------------------------------------------------------------
// main application structure
// -----------------------------------------------------------------------------
typedef struct {
int rank;
void (*entry)(void *);
void *params;
} internal_pthread_args_t;
void internal_pthread_thread(internal_pthread_args_t *args)
{
parop_my_rank = args->rank;
args->entry(args->params);
}
int harness_spmd_main(int argc, char **argv,
int params_data_size,
int call_config(int, char **, void *, int),
void call_parallel(void *))
{
int r;
char params[params_data_size];
parop_my_rank = 0;
parop_max_rank = call_config(argc, argv, params, PAROP_MAX_THREADS);
int colors[parop_max_rank];
for (r=0; r<parop_max_rank; r++) colors[r] = 0;
parop_def_collection(0, colors);
for (r=1; r<parop_max_rank; r++) {
internal_pthread_args_t *args =
machine_malloc(sizeof(internal_pthread_args_t));
args->rank = r;
args->entry = call_parallel;
args->params = params;
int e = pthread_create(&parop_thread_tab[r], NULL,
(void * (*)(void *))(internal_pthread_thread), args);
if (e!=0) machine_fatal("Error in pthread_create()");
}
call_parallel(params);
for (r=1; r<parop_max_rank; r++) {
int e = pthread_join(parop_thread_tab[r], NULL);
if (e!=0) machine_fatal("Error in pthread_join()");
}
return 0;
}
#endif // _PAROP_PTHREAD_H
| 2.59375 | 3 |
2024-11-18T20:50:30.185053+00:00 | 2021-07-07T23:20:30 | fd99f9b063acd003f70974b874c58e3d48dc0616 | {
"blob_id": "fd99f9b063acd003f70974b874c58e3d48dc0616",
"branch_name": "refs/heads/game_revamp",
"committer_date": "2021-07-07T23:20:30",
"content_id": "1360dc96544c36d2bdd93740d8bc2f6fdfaf0b08",
"detected_licenses": [
"MIT"
],
"directory_id": "080006d2e09a235f6f29ed2fe2c916d38d782e29",
"extension": "c",
"filename": "pc_gameloader.c",
"fork_events_count": 0,
"gha_created_at": "2022-08-29T20:56:30",
"gha_event_created_at": "2022-08-29T20:56:30",
"gha_language": null,
"gha_license_id": null,
"github_id": 530390953,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2679,
"license": "MIT",
"license_type": "permissive",
"path": "/src/pc/pc_gameloader.c",
"provenance": "stackv2-0118.json.gz:42839",
"repo_name": "Newpersonhere/OpenFNaF",
"revision_date": "2021-07-07T23:20:30",
"revision_id": "048b1afc5e7d87d8dba006685d16f3a530a52398",
"snapshot_id": "879370c3172d63601dee472b1c266db1271c1724",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/Newpersonhere/OpenFNaF/048b1afc5e7d87d8dba006685d16f3a530a52398/src/pc/pc_gameloader.c",
"visit_date": "2023-07-08T10:30:08.898170"
} | stackv2 | //
// MIT License
//
// Copyright (c) 2020 MotoLegacy
//
// 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.
//
//
// pc_gameloader.c - the game loader/chooser for UNIX/PC
//
#include "../defs.h"
void Game_InitializeLoader() {
gamedata_t supported_games[8];
boolean game_selected = FALSE;
int iterer = 0;
int selection;
// Grab a list of only the games supporting PC
for (int i = 0; i < 8; i++) {
if (INI_Games[i].supports_pc == TRUE) {
supported_games[iterer].occupied = TRUE;
supported_games[iterer].window_width = INI_Games[i].window_width;
supported_games[iterer].window_height = INI_Games[i].window_height;
supported_games[iterer].name = INI_Games[i].name;
supported_games[iterer].game_path = INI_Games[i].game_path;
iterer++;
}
}
// Print out the game selection
while(game_selected == FALSE) {
printf("Select a Supported Game from the list\n");
for (int i = 0; i < iterer; i++) {
printf("%d. %s\n", i, supported_games[i].name);
}
scanf("%d", &selection);
if (selection < 0 || selection >= iterer) {
printf("Invalid Selection.\n");
printf("======================\n");
} else {
game_selected = TRUE;
}
}
// Initialize the raylib Window
if (!OPT_NORENDER)
Window_Initialize(supported_games[selection].window_width, supported_games[selection].window_height, supported_games[selection].name);
// Initialize the Game Handler
Game_Initialize(supported_games[selection]);
} | 2.03125 | 2 |
2024-11-18T20:50:32.764918+00:00 | 2021-09-17T09:39:05 | a84254b06581aa50fbf3b8b8fd501de3282e9cd2 | {
"blob_id": "a84254b06581aa50fbf3b8b8fd501de3282e9cd2",
"branch_name": "refs/heads/master",
"committer_date": "2021-09-17T09:39:05",
"content_id": "896f4098c302b45177a8f6675bf7ababd51ab796",
"detected_licenses": [
"MIT"
],
"directory_id": "071db391cb222f38524f420443e3a5cc2b39778a",
"extension": "c",
"filename": "hyper_carray.c",
"fork_events_count": 24,
"gha_created_at": "2013-05-17T15:06:41",
"gha_event_created_at": "2021-09-17T09:39:07",
"gha_language": "Erlang",
"gha_license_id": "MIT",
"github_id": 10125873,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 8990,
"license": "MIT",
"license_type": "permissive",
"path": "/c_src/hyper_carray.c",
"provenance": "stackv2-0118.json.gz:43868",
"repo_name": "GameAnalytics/hyper",
"revision_date": "2021-09-17T09:39:05",
"revision_id": "5bce9df8d6b09e5326fe6e38fbc1eba9c482f3e5",
"snapshot_id": "33693df55b0a8c26ea7e9569d88a1bfa37f23809",
"src_encoding": "UTF-8",
"star_events_count": 70,
"url": "https://raw.githubusercontent.com/GameAnalytics/hyper/5bce9df8d6b09e5326fe6e38fbc1eba9c482f3e5/c_src/hyper_carray.c",
"visit_date": "2021-09-27T05:31:04.242229"
} | stackv2 | // Copyright (c) 2014 Johannes Huning <mail@johanneshuning.com>
// Copyright (c) 2015 Christian Lundgren, Chris de Vries, and Jon Elverkilde
//
// 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.
//
// Format this file with
// indent -kr -i8 -sob c_src/hyper_carray.c
// before committing.
#include <stdint.h>
#include <stdio.h>
#include <string.h>
#include "erl_nif.h"
/*
* Erlang NIF resource type used to 'tag' hyper_carrays.
*/
static ErlNifResourceType *carray_resource;
/*
* Single resource produced and consumed by these NIFs.
* Header placed directly in front of the items it points to.
*/
struct hyper_carray {
/*
* Precision = log_2(size). Handy to have it.
*/
unsigned int precision;
/*
* Number of items.
*/
unsigned int size;
/*
* Array of items each one byte in size.
*/
uint8_t *items;
};
typedef struct hyper_carray *restrict carray_ptr;
#define HYPER_CARRAY_SIZE sizeof(struct hyper_carray)
/*
* Attempts to read a hyper_carray from _term into _varname.
* Returns badarg on failure to do so.
*/
#define HYPER_CARRAY_OR_BADARG(_term, _varname) \
void* _varname_res = NULL; \
if (!enif_get_resource(env, _term, carray_resource, &_varname_res)) \
return enif_make_badarg(env); \
_varname = _varname_res;
/*
* Allocate a new hyper_carray for use as an Erlang NIF resource.
*/
static void carray_alloc(unsigned int precision, carray_ptr * arr)
{
unsigned int nitems = 0x01 << precision;
size_t header_size = HYPER_CARRAY_SIZE;
size_t res_size = header_size + nitems;
void *res = enif_alloc_resource(carray_resource, res_size);
*arr = res;
memset(*arr, 0, header_size);
(*arr)->precision = precision;
(*arr)->size = nitems;
(*arr)->items = res + header_size;
}
/*
* Given an hyper_carray and a valid index, set the value at that index to
* max(current value, given value).
*/
static inline void carray_merge_item(carray_ptr arr,
unsigned int index,
unsigned int value)
{
uint8_t *item = arr->items + index;
*item = (value > *item) ? value : *item;
}
/*
* Create a new hyper_carray resource with all items set to 0.
*/
static ERL_NIF_TERM new_hyper_carray(ErlNifEnv * env, int argc,
const ERL_NIF_TERM argv[])
{
unsigned int precision = 0;
if (!enif_get_uint(env, argv[0], &precision))
return enif_make_badarg(env);
carray_ptr arr = NULL;
carray_alloc(precision, &arr);
memset(arr->items, 0, arr->size);
ERL_NIF_TERM erl_res = enif_make_resource(env, arr);
enif_release_resource(arr);
return erl_res;
}
/*
* NIF variant of carray_merge_item (see above).
*/
static ERL_NIF_TERM set(ErlNifEnv * env, int argc,
const ERL_NIF_TERM argv[])
{
carray_ptr arr = NULL;
HYPER_CARRAY_OR_BADARG(argv[2], arr);
unsigned int index = 0;
unsigned int new_value = 0;
if (!enif_get_uint(env, argv[0], &index)
|| !enif_get_uint(env, argv[1], &new_value))
return enif_make_badarg(env);
// Validate bounds
if (index > arr->size - 1)
return enif_make_badarg(env);
carray_merge_item(arr, index, new_value);
return argv[2];
}
void dtor(ErlNifEnv * env, void *obj);
/*
* Given a list of at least 1 hyper_carrays [A,B,...], merge into a single new
* hyper_carray N. Where the i-ths item N[i] is max(A[i], B[i], ...).
* A, B, and so on are assumed to be _different_ hyper_carrays.
*/
static ERL_NIF_TERM max_merge(ErlNifEnv * env, int argc,
const ERL_NIF_TERM argv[])
{
unsigned int narrays = 0;
ERL_NIF_TERM head;
ERL_NIF_TERM tail;
if (!enif_get_list_length(env, argv[0], &narrays)
|| !enif_get_list_cell(env, argv[0], &head, &tail))
return enif_make_badarg(env);
if (narrays < 1)
return enif_make_badarg(env);
carray_ptr first = NULL;
HYPER_CARRAY_OR_BADARG(head, first);
const unsigned int nitems = first->size;
carray_ptr acc = NULL;
carray_alloc(first->precision, &acc);
memcpy(acc->items, first->items, acc->size);
// Merge arrays
for (int i = 1; i < narrays; ++i) {
carray_ptr curr = NULL;
if (!enif_get_list_cell(env, tail, &head, &tail)
|| !enif_get_resource(env, head, carray_resource,
(void *) &curr))
goto dealloc_and_badarg;
// Require uniform precision.
if (curr->precision != acc->precision)
goto dealloc_and_badarg;
for (uint8_t * accitem = acc->items, *item = curr->items,
*enditem = curr->items + nitems;
item != enditem; ++item, ++accitem) {
*accitem = (*item > *accitem) ? *item : *accitem;
}
continue;
dealloc_and_badarg:
dtor(env, acc);
return enif_make_badarg(env);
}
ERL_NIF_TERM erl_res = enif_make_resource(env, acc);
enif_release_resource(acc);
return erl_res;
}
/*
* Return the total number of bytes allocated for the given hyper_carray.
* Includes the header's size.
*/
static ERL_NIF_TERM bytes(ErlNifEnv * env, int argc,
const ERL_NIF_TERM argv[])
{
carray_ptr arr = NULL;
HYPER_CARRAY_OR_BADARG(argv[0], arr);
return enif_make_int(env, HYPER_CARRAY_SIZE + arr->size);
}
/*
* Sum over 2^-X where X is the value of each item in the given hyper_carray.
*/
static ERL_NIF_TERM register_sum(ErlNifEnv * env, int argc,
const ERL_NIF_TERM argv[])
{
carray_ptr arr = NULL;
HYPER_CARRAY_OR_BADARG(argv[0], arr);
int currval = 0;
double sum = 0.0;
unsigned int size = arr->size;
for (int i = 0; i < size; ++i) {
currval = arr->items[i];
sum += 1.0 / (double) (0x01 << currval);
}
return enif_make_double(env, sum);
}
/*
* Number of items with a 0 as value;
*/
static ERL_NIF_TERM zero_count(ErlNifEnv * env, int argc,
const ERL_NIF_TERM argv[])
{
carray_ptr arr = NULL;
HYPER_CARRAY_OR_BADARG(argv[0], arr);
unsigned int nzeros = 0;
unsigned int size = arr->size;
for (int i = 0; i < size; ++i) {
if (arr->items[i] == 0)
++nzeros;
}
return enif_make_int(env, nzeros);
}
/*
* Encode the given hyper_carray as an Erlang binary.
*/
static ERL_NIF_TERM encode_registers(ErlNifEnv * env, int argc,
const ERL_NIF_TERM argv[])
{
carray_ptr arr = NULL;
HYPER_CARRAY_OR_BADARG(argv[0], arr);
size_t nbytes = arr->size;
ERL_NIF_TERM bin;
unsigned char *buf = enif_make_new_binary(env, nbytes, &bin);
memcpy(buf, arr->items, nbytes);
return bin;
}
/*
* Decode the given serialized hyper_carray into a new resource.
*/
static ERL_NIF_TERM decode_registers(ErlNifEnv * env, int argc,
const ERL_NIF_TERM argv[])
{
unsigned int precision = 0;
ErlNifBinary bin;
if (!enif_get_uint(env, argv[1], &precision)
|| !enif_inspect_binary(env, argv[0], &bin))
return enif_make_badarg(env);
carray_ptr arr = NULL;
carray_alloc(precision, &arr);
memcpy(arr->items, bin.data, arr->size);
ERL_NIF_TERM erl_res = enif_make_resource(env, arr);
enif_release_resource(arr);
return erl_res;
}
/*
* Map of funs to NIFs.
*/
static ErlNifFunc niftable[] = {
{"new", 1, new_hyper_carray},
{"set", 3, set},
{"max_merge", 1, max_merge},
{"bytes", 1, bytes},
{"register_sum", 1, register_sum},
{"zero_count", 1, zero_count},
{"encode_registers", 1, encode_registers},
{"decode_registers", 2, decode_registers}
};
/*
* Destructor for hyper_carray resources.
*/
void dtor(ErlNifEnv * env, void *obj)
{
enif_release_resource(obj);
}
/*
* Creates or opens the hyper_carray resource _type_.
* Registers dtor to be called on garbage collection of hyper_carrays.
* Please see http://www.erlang.org/doc/man/erl_nif.html.
*/
static int load(ErlNifEnv * env, void **priv_data, ERL_NIF_TERM load_info)
{
carray_resource =
enif_open_resource_type(env, NULL, "hyper_carray", &dtor,
ERL_NIF_RT_CREATE |
ERL_NIF_RT_TAKEOVER, 0);
return 0;
}
/*
* Called when the NIF library is loaded and there is old code of this module
* with a loaded NIF library.
*/
static int upgrade(ErlNifEnv * env, void **priv, void **old_priv,
ERL_NIF_TERM load_info)
{
*priv = *old_priv;
return 0;
}
/*
* Initialize the NIF library.
*/
ERL_NIF_INIT(hyper_carray, niftable, &load, NULL, &upgrade, NULL);
| 2.265625 | 2 |
2024-11-18T20:50:33.109584+00:00 | 2014-12-14T04:24:18 | 56413476f2581e1e49bc6e47c7cf9bfee8a7ee32 | {
"blob_id": "56413476f2581e1e49bc6e47c7cf9bfee8a7ee32",
"branch_name": "refs/heads/master",
"committer_date": "2014-12-14T04:24:18",
"content_id": "d803101f02aeffe45f7908d128c38794df15ee57",
"detected_licenses": [
"MIT"
],
"directory_id": "62124aa2d0881d38a76e8e8baed854b177a6911d",
"extension": "h",
"filename": "statusbar.h",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": null,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1202,
"license": "MIT",
"license_type": "permissive",
"path": "/src/statusbar.h",
"provenance": "stackv2-0118.json.gz:43997",
"repo_name": "charliegreen/moss",
"revision_date": "2014-12-14T04:24:18",
"revision_id": "3866ebb3e410ec02bff7ce37490bac86b74f9344",
"snapshot_id": "45fb03548c153faac21a966380d8f03010359b32",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/charliegreen/moss/3866ebb3e410ec02bff7ce37490bac86b74f9344/src/statusbar.h",
"visit_date": "2020-05-18T19:15:26.544967"
} | stackv2 | #ifndef STATUSBAR_H
#define STATUSBAR_H
#include "common.h"
void statusbar_initialize(void);
//================================
// FLAGS
//================================
#define STATUSBAR_NUM_FLAGS 2
/* Our flags are:
* R/B/H - Running, blocking, or halted [running flag]
* /U/H - <nothing>, unhandled/handled interrupt raised [interrupt flag]
*/
#define STATUSBAR_FLAG_BASE (uint16_t*)(CONSOLE_BUFFER+OS_NAME_MAX_LEN+3)
#define STATUSBAR_RUNNING_FLAG_LOC (STATUSBAR_FLAG_BASE)
#define STATUSBAR_INTERRUPT_FLAG_LOC (STATUSBAR_FLAG_BASE+1)
typedef enum running_flag{
RUNNING, BLOCKING, HALTED
} running_flag_t;
typedef enum interrupt_flag{
NONE, UNHANDLED, HANDLED
} interrupt_flag_t;
void statusbar_setRunningFlag(running_flag_t f);
void statusbar_setInterruptFlag(interrupt_flag_t f);
//================================
// MESSAGE AREA
//================================
#define STATUSBAR_MSG_BASE (uint16_t*)(STATUSBAR_FLAG_BASE+STATUSBAR_NUM_FLAGS+2)
#define STATUSBAR_MSG_MAX_LEN (CONSOLE_WIDTH-OS_NAME_MAX_LEN-STATUSBAR_NUM_FLAGS-6)
void statusbar_clearMsg(void);
void statusbar_printMsg(const char*data);
void statusbar_printNum(uint32_t num, uint32_t radix);
#endif
| 2.21875 | 2 |
2024-11-18T20:50:33.183453+00:00 | 2021-02-24T23:07:49 | 021d8faf0fb1ef6f9ee8f595cbcd7a5052719635 | {
"blob_id": "021d8faf0fb1ef6f9ee8f595cbcd7a5052719635",
"branch_name": "refs/heads/master",
"committer_date": "2021-02-24T23:07:49",
"content_id": "c9d4a3c2fbfb928f33c6e968a75d8d2eb46f634c",
"detected_licenses": [
"MIT",
"BSD-3-Clause",
"Apache-2.0",
"BSD-2-Clause"
],
"directory_id": "4876e005b3480dab19c8e4dade81cf0e37448999",
"extension": "c",
"filename": "eeprom.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 334485663,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 16206,
"license": "MIT,BSD-3-Clause,Apache-2.0,BSD-2-Clause",
"license_type": "permissive",
"path": "/Core/Src/eeprom.c",
"provenance": "stackv2-0118.json.gz:44126",
"repo_name": "SG-O/MiniFeedFirmware",
"revision_date": "2021-02-24T23:07:49",
"revision_id": "842d343690de544e147119b9640d8b68f30bc6db",
"snapshot_id": "01d1e11d42e577e56e9a47b570eb5420295932f3",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/SG-O/MiniFeedFirmware/842d343690de544e147119b9640d8b68f30bc6db/Core/Src/eeprom.c",
"visit_date": "2023-03-09T14:27:20.431852"
} | stackv2 | /*
* eeprom.c
*
* Copyright 2021 SG-O (Joerg Bayer)
*
* 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
*
* https://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.
*
*
* Created on: Feb. 15, 2021
* Author: SG-O
*/
#include "eeprom.h"
uint8_t EEPROM_buffer[EEPROM_IO_BUFFER_SIZE];
uint32_t EEPROM_counterValue;
uint16_t EEPROM_counterSlot;
uint8_t EEPROM_initialized = 0;
uint64_t EEPROM_previousTotalFeeds = 0;
void EEPROM_Setup(I2C_HandleTypeDef *hi2c) {
EEPROM_hi2c = hi2c;
EEPROM_UpdateCounterSlot();
EEPROM_CheckHeader();
}
void EEPROM_CheckForReInit() {
if (HW_IsV1() != 1) return;
uint32_t backupData = BACKUP_Read(BACKUP_REG_MESSAGE);
if ((backupData && (BACKUP_MESSAGE_INIT_EEPROM)) == 0) return;
backupData &= ~(BACKUP_MESSAGE_INIT_EEPROM);
BACKUP_Write(BACKUP_REG_MESSAGE, backupData);
EEPROM_WriteHeader();
EEPROM_WriteDefaults();
NVIC_SystemReset();
}
void HW_ReInit() {
uint32_t backupData = BACKUP_Read(BACKUP_REG_MESSAGE);
backupData |= BACKUP_MESSAGE_INIT_EEPROM;
BACKUP_Write(BACKUP_REG_MESSAGE, backupData);
NVIC_SystemReset();
}
uint16_t EEPROM_Read(uint16_t address, uint16_t length) {
if (length > EEPROM_IO_BUFFER_SIZE) return 0;
uint16_t leftInPage; // A page is EEPROM_PAGE_SIZE long. Reading outside the page boundary is not strictly illegal. This is just to be cautious.
uint16_t read = 0; // Total bytes read.
uint32_t tick = HAL_GetTick() + 5;
while (HAL_I2C_GetState(EEPROM_hi2c) != HAL_I2C_STATE_READY)
{
asm("NOP");
if (tick > HAL_GetTick()) return 0;
}
HAL_StatusTypeDef result;
while (length > 0) {
leftInPage = EEPROM_PAGE_SIZE - (address % EEPROM_PAGE_SIZE); // Calculate the number of bytes until the end of the page
if (length < leftInPage) {
leftInPage = length; // Don't read more bytes than required
}
result = HAL_I2C_Mem_Read(EEPROM_hi2c, EEPROM_ADDRESS << 1, address, I2C_MEMADD_SIZE_16BIT, &EEPROM_buffer[read], leftInPage, EEPROM_TIMEOUT); //Read the data into the buffer
if (result != HAL_OK) {
return read; // If something went wrong return the actual number of bytes read.
}
length -= leftInPage; // Remove the bytes read from the bytes to read
address += leftInPage; // Move the address to the next read position
read += leftInPage; // Add the bytes read to the total
HAL_Delay(EEPROM_READ_DELAY); // Just to be safe a little delay
}
return read;
}
uint16_t EEPROM_Write(uint16_t address, uint16_t length) {
if (length > EEPROM_IO_BUFFER_SIZE) return 0;
if (EEPROM_initialized != 1) return 0;
uint16_t leftInPage; // A page is EEPROM_PAGE_SIZE long. Writing outside the page boundary is not permitted.
uint16_t written = 0; // Total bytes written.
uint32_t tick = HAL_GetTick() + 5;
while (HAL_I2C_GetState(EEPROM_hi2c) != HAL_I2C_STATE_READY)
{
asm("NOP");
if (tick > HAL_GetTick()) return 0;
}
HAL_StatusTypeDef result;
while (length > 0) {
leftInPage = EEPROM_PAGE_SIZE - (address % EEPROM_PAGE_SIZE); // Calculate the number of bytes until the end of the page
if (length < leftInPage) {
leftInPage = length; // Don't write more bytes than required
}
result = HAL_I2C_Mem_Write(EEPROM_hi2c, EEPROM_ADDRESS << 1, address, I2C_MEMADD_SIZE_16BIT, &EEPROM_buffer[written], leftInPage, EEPROM_TIMEOUT); //Write the data from the buffer to the EEPROM
if (result != HAL_OK) {
return written; // If something went wrong return the actual number of bytes written.
}
length -= leftInPage; // Remove the bytes written from the bytes to write
address += leftInPage; // Move the address to the next write position
written += leftInPage; // Add the bytes written to the total
HAL_Delay(EEPROM_WRITE_DELAY); // This delay is required
}
return written;
}
//--Reads--
uint16_t EEPROM_ReadString(uint16_t address, char *strg, uint16_t length) {
if (EEPROM_Read(address, length) != length) return 0;
memcpy(strg, EEPROM_buffer, length);
return length;
}
uint32_t EEPROM_ReadUint32(uint16_t address, uint32_t def) {
if (EEPROM_Read(address, CON_INT_LENGTH) != CON_INT_LENGTH) return def;
uint32_t tmp;
memcpy(&tmp, EEPROM_buffer, CON_INT_LENGTH);
return tmp;
}
int32_t EEPROM_ReadInt32(uint16_t address, int32_t def) {
if (EEPROM_Read(address, CON_INT_LENGTH) != CON_INT_LENGTH) return def;
int32_t tmp;
memcpy(&tmp, EEPROM_buffer, CON_INT_LENGTH);
return tmp;
}
uint16_t EEPROM_ReadUint16(uint16_t address, uint16_t def) {
if (EEPROM_Read(address, CON_SHORT_LENGTH) != CON_SHORT_LENGTH) return def;
uint16_t tmp;
memcpy(&tmp, EEPROM_buffer, CON_SHORT_LENGTH);
return tmp;
}
int16_t EEPROM_ReadInt16(uint16_t address, int16_t def) {
if (EEPROM_Read(address, CON_SHORT_LENGTH) != CON_SHORT_LENGTH) return def;
int16_t tmp;
memcpy(&tmp, EEPROM_buffer, CON_SHORT_LENGTH);
return tmp;
}
uint8_t EEPROM_ReadUint8(uint16_t address, uint8_t def) {
if (EEPROM_Read(address, CON_BYTE_LENGTH) != CON_BYTE_LENGTH) return def;
uint8_t tmp;
memcpy(&tmp, EEPROM_buffer, CON_BYTE_LENGTH);
return tmp;
}
int8_t EEPROM_ReadInt8(uint16_t address, int8_t def) {
if (EEPROM_Read(address, CON_BYTE_LENGTH) != CON_BYTE_LENGTH) return def;
int8_t tmp;
memcpy(&tmp, EEPROM_buffer, CON_BYTE_LENGTH);
return tmp;
}
//--Writes--
uint16_t EEPROM_WriteString(uint16_t address, char *strg, uint16_t length) {
memcpy(EEPROM_buffer, strg, length);
if (EEPROM_Write(address, length) != length) {
ERROR_SetError(ERROR_STORAGE_WRITE);
return 0;
}
return length;
}
uint16_t EEPROM_WriteUint32(uint16_t address, uint32_t data) {
memcpy(EEPROM_buffer, &data, CON_INT_LENGTH);
if (EEPROM_Write(address, CON_INT_LENGTH) != CON_INT_LENGTH) {
ERROR_SetError(ERROR_STORAGE_WRITE);
return 0;
}
return CON_INT_LENGTH;
}
uint16_t EEPROM_WriteInt32(uint16_t address, int32_t data) {
memcpy(EEPROM_buffer, &data, CON_INT_LENGTH);
if (EEPROM_Write(address, CON_INT_LENGTH) != CON_INT_LENGTH) {
ERROR_SetError(ERROR_STORAGE_WRITE);
return 0;
}
return CON_INT_LENGTH;
}
uint16_t EEPROM_WriteUint16(uint16_t address, uint16_t data) {
memcpy(EEPROM_buffer, &data, CON_SHORT_LENGTH);
if (EEPROM_Write(address, CON_SHORT_LENGTH) != CON_SHORT_LENGTH) {
ERROR_SetError(ERROR_STORAGE_WRITE);
return 0;
}
return CON_SHORT_LENGTH;
}
uint16_t EEPROM_WriteInt16(uint16_t address, int16_t data) {
memcpy(EEPROM_buffer, &data, CON_SHORT_LENGTH);
if (EEPROM_Write(address, CON_SHORT_LENGTH) != CON_SHORT_LENGTH) {
ERROR_SetError(ERROR_STORAGE_WRITE);
return 0;
}
return CON_SHORT_LENGTH;
}
uint16_t EEPROM_WriteUint8(uint16_t address, uint8_t data) {
memcpy(EEPROM_buffer, &data, CON_BYTE_LENGTH);
if (EEPROM_Write(address, CON_BYTE_LENGTH) != CON_BYTE_LENGTH) {
ERROR_SetError(ERROR_STORAGE_WRITE);
return 0;
}
return CON_BYTE_LENGTH;
}
uint16_t EEPROM_WriteInt8(uint16_t address, int8_t data) {
memcpy(EEPROM_buffer, &data, 1);
if (EEPROM_Write(address, 1) != 1) {
ERROR_SetError(ERROR_STORAGE_WRITE);
return 0;
}
return CON_BYTE_LENGTH;
}
//--Counter--
void EEPROM_UpdateCounterSlot() {
for (uint16_t i = 0; i < EEPROM_COUNTER_SLOTS; i++) {
EEPROM_counterValue = EEPROM_ReadUint32(EEPROM_COUNTER_OFFSET + (i << EEPROM_COUNTER_ROW_OFFSET_SHIFT), EEPROM_MAXIMUM_WRITES);
if (EEPROM_counterValue == CON_INT_MASK) EEPROM_counterValue = 0;
if (EEPROM_counterValue < EEPROM_MAXIMUM_WRITES) {
EEPROM_counterSlot = i;
return;
}
EEPROM_previousTotalFeeds += EEPROM_ReadUint32(EEPROM_COUNTER_OFFSET + (i << EEPROM_COUNTER_ROW_OFFSET_SHIFT) + EEPROM_COUNTER_TOTAL_FEEDS_OFFSET, 0);
}
ERROR_SetError(ERROR_STORAGE_COUNTER_COUNT);
EEPROM_counterSlot = EEPROM_COUNTER_SLOTS;
}
uint16_t EEPROM_CounterWriteUint32(uint16_t address, uint32_t data) {
if (EEPROM_counterValue >= EEPROM_MAXIMUM_WRITES) EEPROM_UpdateCounterSlot();
if (EEPROM_counterSlot >= EEPROM_COUNTER_SLOTS) return 0;
EEPROM_counterValue++;
address += EEPROM_counterSlot << EEPROM_COUNTER_ROW_OFFSET_SHIFT;
if (EEPROM_WriteUint32(address & EEPROM_COUNTER_ROW_MASK, EEPROM_counterValue) != CON_INT_LENGTH) return 0;
return EEPROM_WriteUint32(address, data);
}
uint16_t EEPROM_CounterWriteInt32(uint16_t address, int32_t data) {
if (EEPROM_counterValue >= EEPROM_MAXIMUM_WRITES) EEPROM_UpdateCounterSlot();
if (EEPROM_counterSlot >= EEPROM_COUNTER_SLOTS) return 0;
EEPROM_counterValue++;
address += EEPROM_counterSlot << EEPROM_COUNTER_ROW_OFFSET_SHIFT;
if (EEPROM_WriteUint32(address & EEPROM_COUNTER_ROW_MASK, EEPROM_counterValue) != CON_INT_LENGTH) return 0;
return EEPROM_WriteInt32(address, data);
}
uint16_t EEPROM_CounterCount(uint64_t totalFeeds, int32_t remainingParts) {
if (EEPROM_counterValue >= EEPROM_MAXIMUM_WRITES) EEPROM_UpdateCounterSlot();
if (EEPROM_counterSlot >= EEPROM_COUNTER_SLOTS) return 0;
EEPROM_counterValue++;
uint32_t totalFeedsRemaining = (uint32_t)((totalFeeds - EEPROM_previousTotalFeeds) & 0xFFFFFFFFL);
uint16_t address = (EEPROM_counterSlot << EEPROM_COUNTER_ROW_OFFSET_SHIFT) + EEPROM_COUNTER_OFFSET;
memcpy(&EEPROM_buffer[0], &EEPROM_counterValue, CON_INT_LENGTH);
memcpy(&EEPROM_buffer[EEPROM_COUNTER_TOTAL_FEEDS_OFFSET], &totalFeedsRemaining, CON_INT_LENGTH);
memcpy(&EEPROM_buffer[EEPROM_COUNTER_REMAINING_PARTS_OFFSET], &remainingParts, CON_INT_LENGTH);
return EEPROM_Write(address, EEPROM_COUNTER_ROW_Length);
}
uint32_t EEPROM_CounterReadUint32(uint16_t address, uint32_t def) {
if (EEPROM_counterValue >= EEPROM_MAXIMUM_WRITES) EEPROM_UpdateCounterSlot();
if (EEPROM_counterSlot >= EEPROM_COUNTER_SLOTS) return def;
address += EEPROM_counterSlot << EEPROM_COUNTER_ROW_OFFSET_SHIFT;
return EEPROM_ReadUint32(address, def);
}
int32_t EEPROM_CounterReadInt32(uint16_t address, int32_t def) {
if (EEPROM_counterValue >= EEPROM_MAXIMUM_WRITES) EEPROM_UpdateCounterSlot();
if (EEPROM_counterSlot >= EEPROM_COUNTER_SLOTS) return def;
address += EEPROM_counterSlot << EEPROM_COUNTER_ROW_OFFSET_SHIFT;
return EEPROM_ReadInt32(address, def);
}
uint64_t EEPROM_CounterCalcTotalFeeds(uint32_t readValue) {
return EEPROM_previousTotalFeeds + readValue;
}
//--Util--
uint32_t EEPROM_CheckUpdateRowCounter(uint16_t address) {
uint32_t value = EEPROM_ReadUint32(address & 0xFFF0, EEPROM_MAXIMUM_WRITES);
if (value == CON_INT_MASK) value = 0;
if (value >= EEPROM_MAXIMUM_WRITES) return EEPROM_MAXIMUM_WRITES;
value++;
EEPROM_WriteUint32(address, value);
return value;
}
uint8_t EEPROM_WriteHeader() {
EEPROM_initialized = 1;
for(int i = 0; i < EEPROM_HEADER_CRC_OFFSET; i++) {
EEPROM_buffer[i] = CON_BYTE_MASK;
}
uint32_t version = EEPROM_FORMAT_VERSION;
memcpy(&EEPROM_buffer[EEPROM_HEADER_FORMAT_VERSION_OFFSET], &version, CON_INT_LENGTH);
uint32_t id = HAL_GetUIDw0();
memcpy(&EEPROM_buffer[EEPROM_HEADER_DEVICE_ID_0_OFFSET], &id, CON_INT_LENGTH);
id = HAL_GetUIDw1();
memcpy(&EEPROM_buffer[EEPROM_HEADER_DEVICE_ID_1_OFFSET], &id, CON_INT_LENGTH);
id = HAL_GetUIDw2();
memcpy(&EEPROM_buffer[EEPROM_HEADER_DEVICE_ID_2_OFFSET], &id, CON_INT_LENGTH);
uint32_t crc = CRC_Calculate32(EEPROM_buffer, EEPROM_HEADER_CRC_OFFSET);
memcpy(&EEPROM_buffer[EEPROM_HEADER_CRC_OFFSET], &crc, CON_INT_LENGTH);
if (EEPROM_Write(EEPROM_HEADER_OFFSET, EEPROM_HEADER_LENGTH) == EEPROM_HEADER_LENGTH) {
EEPROM_initialized = 1;
return EEPROM_initialized;
}
EEPROM_initialized = 0;
ERROR_SetError(ERROR_STORAGE_INIT);
return EEPROM_initialized;
}
uint8_t EEPROM_WriteDefaults() {
if (EEPROM_CheckUpdateRowCounter(EEPROM_CONFIG_0_OFFSET + EEPROM_CONFIG_ROW_WRITE_0_OFFSET) < EEPROM_MAXIMUM_WRITES) {
EEPROM_WriteUint8(EEPROM_CONFIG_0_OFFSET + EEPROM_CONFIG_PART_PITCH_OFFSET, CONFIG_DEFAULT_PART_PITCH);
EEPROM_WriteUint8(EEPROM_CONFIG_0_OFFSET + EEPROM_CONFIG_FEED_SPEED_OFFSET, CONFIG_DEFAULT_FEED_SPEED);
EEPROM_WriteUint16(EEPROM_CONFIG_0_OFFSET + EEPROM_CONFIG_LOW_PARTS_WARNING_OFFSET, CONFIG_DEFAULT_LOW_PARTS_WARN);
} else {
ERROR_SetError(ERROR_STORAGE_CONFIG_COUNT);
}
if (EEPROM_CheckUpdateRowCounter(EEPROM_CONFIG_0_OFFSET + EEPROM_CONFIG_ROW_WRITE_1_OFFSET) < EEPROM_MAXIMUM_WRITES) {
EEPROM_WriteUint8(EEPROM_CONFIG_0_OFFSET + EEPROM_CONFIG_DISPLAY_BRIGHTNESS_OFFSET, CONFIG_DEFAULT_DISPLAY_BRIGHTNESS);
EEPROM_WriteUint8(EEPROM_CONFIG_0_OFFSET + EEPROM_CONFIG_MOTOR_DIRECTION_OFFSET, CONFIG_DEFAULT_MOTOR_DIRECTION);
EEPROM_WriteUint16(EEPROM_CONFIG_0_OFFSET + EEPROM_CONFIG_MOTOR_SLOWDOWN_DELAY_OFFSET, CONFIG_DEFAULT_MOTOR_SLOWDOWN_DELAY);
} else {
ERROR_SetError(ERROR_STORAGE_CONFIG_COUNT);
}
if (EEPROM_CheckUpdateRowCounter(EEPROM_CONFIG_0_OFFSET + EEPROM_CONFIG_ROW_WRITE_2_OFFSET) < EEPROM_MAXIMUM_WRITES) {
EEPROM_WriteInt32(EEPROM_CONFIG_0_OFFSET + EEPROM_CONFIG_TOTAL_PARTS_OFFSET, CONFIG_DEFAULT_TOTAL_PARTS);
} else {
ERROR_SetError(ERROR_STORAGE_CONFIG_COUNT);
}
EEPROM_UpdateCounterSlot();
EEPROM_CounterWriteUint32(EEPROM_COUNTER_OFFSET + EEPROM_COUNTER_TOTAL_FEEDS_OFFSET, 0);
EEPROM_CounterWriteInt32(EEPROM_COUNTER_OFFSET + EEPROM_COUNTER_REMAINING_PARTS_OFFSET, CONFIG_DEFAULT_REMAINING_PARTS);
if (EEPROM_CheckUpdateRowCounter(EEPROM_CONFIG_0_OFFSET + EEPROM_CONFIG_ROW_WRITE_3_OFFSET) < EEPROM_MAXIMUM_WRITES) {
char id[EEPROM_CONFIG_SHORT_ID_LENGTH];
for (int i = 0; i < EEPROM_CONFIG_SHORT_ID_LENGTH; i++) {
id[i] = 0;
}
uint32_t devID = HAL_GetUIDw0() ^ HAL_GetUIDw1() ^ HAL_GetUIDw2();
uint8_t devIDByte[CON_INT_LENGTH];
*(uint32_t*)&devIDByte = devID;
encode_ascii85(devIDByte, CON_INT_LENGTH, id, EEPROM_CONFIG_SHORT_ID_LENGTH);
EEPROM_WriteString(EEPROM_CONFIG_0_OFFSET + EEPROM_CONFIG_SHORT_ID_OFFSET, id, EEPROM_CONFIG_SHORT_ID_LENGTH);
EEPROM_WriteUint8(EEPROM_CONFIG_0_OFFSET + EEPROM_CONFIG_SHORT_ID_FILLER_0_OFFSET, 0);
EEPROM_WriteUint8(EEPROM_CONFIG_0_OFFSET + EEPROM_CONFIG_SHORT_ID_FILLER_1_OFFSET, 0);
} else {
ERROR_SetError(ERROR_STORAGE_CONFIG_COUNT);
}
if (EEPROM_CheckUpdateRowCounter(EEPROM_CONFIG_0_OFFSET + EEPROM_CONFIG_LONG_ID_WRITES_OFFSET) < EEPROM_MAXIMUM_WRITES) {
for (int i = 0; i < EEPROM_CONFIG_LONG_ID_LENGTH; i++) {
EEPROM_buffer[i] = 0;
memcpy(EEPROM_buffer, CONFIG_DEFAULT_LONG_PARTS_ID, sizeof(CONFIG_DEFAULT_LONG_PARTS_ID));
}
EEPROM_Write(EEPROM_CONFIG_0_OFFSET + EEPROM_CONFIG_LONG_ID_OFFSET, EEPROM_CONFIG_LONG_ID_LENGTH);
EEPROM_WriteUint8(EEPROM_CONFIG_0_OFFSET + EEPROM_CONFIG_LONG_ID_FILLER_OFFSET, 0);
} else {
ERROR_SetError(ERROR_STORAGE_CONFIG_COUNT);
}
return EEPROM_initialized;
}
uint8_t EEPROM_CheckHeader() {
if (EEPROM_Read(EEPROM_HEADER_OFFSET, EEPROM_HEADER_LENGTH) != EEPROM_HEADER_LENGTH) {
EEPROM_initialized = 0;
return EEPROM_initialized;
}
uint32_t version;
memcpy(&version, &EEPROM_buffer[EEPROM_HEADER_FORMAT_VERSION_OFFSET], CON_INT_LENGTH);
if (version == CON_INT_MASK) {
EEPROM_WriteHeader();
return EEPROM_WriteDefaults();
} else if (version != EEPROM_FORMAT_VERSION) {
EEPROM_initialized = 0;
ERROR_SetError(ERROR_STORAGE_HEADER);
return EEPROM_initialized;
}
uint32_t crc;
memcpy(&crc, &EEPROM_buffer[EEPROM_HEADER_CRC_OFFSET], CON_INT_LENGTH);
if (CRC_Calculate32(EEPROM_buffer, EEPROM_HEADER_CRC_OFFSET) != crc) {
EEPROM_initialized = 0;
ERROR_SetError(ERROR_STORAGE_HEADER);
return EEPROM_initialized;
}
uint32_t id;
memcpy(&id, &EEPROM_buffer[EEPROM_HEADER_DEVICE_ID_0_OFFSET], CON_INT_LENGTH);
if (id != HAL_GetUIDw0()) {
EEPROM_initialized = 0;
ERROR_SetError(ERROR_STORAGE_HEADER);
return EEPROM_initialized;
}
memcpy(&id, &EEPROM_buffer[EEPROM_HEADER_DEVICE_ID_1_OFFSET], CON_INT_LENGTH);
if (id != HAL_GetUIDw1()) {
EEPROM_initialized = 0;
ERROR_SetError(ERROR_STORAGE_HEADER);
return EEPROM_initialized;
}
memcpy(&id, &EEPROM_buffer[EEPROM_HEADER_DEVICE_ID_2_OFFSET], CON_INT_LENGTH);
if (id != HAL_GetUIDw2()) {
EEPROM_initialized = 0;
ERROR_SetError(ERROR_STORAGE_HEADER);
return EEPROM_initialized;
}
EEPROM_initialized = 1;
return EEPROM_initialized;
}
| 2.421875 | 2 |
2024-11-18T20:50:33.746161+00:00 | 2019-12-21T08:34:46 | af99d8e2874415e8c63753f2b5d6ae6322631744 | {
"blob_id": "af99d8e2874415e8c63753f2b5d6ae6322631744",
"branch_name": "refs/heads/master",
"committer_date": "2019-12-21T08:34:46",
"content_id": "bb732559748e0e3e988ea59380914541ccdedc60",
"detected_licenses": [
"MIT"
],
"directory_id": "524d13bf9f1166ba944e9597cc0f741e4a9bb3fc",
"extension": "c",
"filename": "serial_pl01x.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 114945769,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 514,
"license": "MIT",
"license_type": "permissive",
"path": "/arm/vexpress-a9/serial_pl01x.c",
"provenance": "stackv2-0118.json.gz:44514",
"repo_name": "mytchel/agatha",
"revision_date": "2019-12-21T08:34:46",
"revision_id": "c6831b8fe2d0d60939aa82777ceecc3a50a062ec",
"snapshot_id": "5020d177fb1e47db1ea7cb33821a652c182fa4c0",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/mytchel/agatha/c6831b8fe2d0d60939aa82777ceecc3a50a062ec/arm/vexpress-a9/serial_pl01x.c",
"visit_date": "2021-06-03T09:27:52.035513"
} | stackv2 | #include "../../sys/head.h"
#include "../kern/fns.h"
#include <stdarg.h>
#include <arm/pl01x.h>
static volatile struct pl01x_regs *regs;
static void
putc(char c)
{
if (c == '\n')
putc('\r');
while ((regs->fr & UART_PL01x_FR_TXFF))
;
regs->dr = c;
}
static void
puts(const char *c)
{
while (*c)
putc(*c++);
}
void
init_pl01x(size_t regs_pa)
{
size_t regs_len = 1 << 12;
regs = kernel_map(regs_pa, regs_len, false);
debug_puts = &puts;
debug(DEBUG_INFO, "kernel pl01x ready\n");
}
| 2.296875 | 2 |
2024-11-18T20:50:33.837730+00:00 | 2021-05-25T20:02:44 | 8f0a4de5c943907fc723bd0ba354f4dcc0afd297 | {
"blob_id": "8f0a4de5c943907fc723bd0ba354f4dcc0afd297",
"branch_name": "refs/heads/main",
"committer_date": "2021-05-25T20:02:44",
"content_id": "5e414026c86558bc4aa3cbec195ae307bc476f3c",
"detected_licenses": [
"MIT"
],
"directory_id": "c216d89c418e998513d0bccbe308f46be9222dd4",
"extension": "c",
"filename": "vla_lecture.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 359409672,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 397,
"license": "MIT",
"license_type": "permissive",
"path": "/challenge/challenge_adv_datatype/vla_lecture.c",
"provenance": "stackv2-0118.json.gz:44643",
"repo_name": "liangcorp/learning_c",
"revision_date": "2021-05-25T20:02:44",
"revision_id": "5d77d0beec5557d7f077fc0760e6c8513d820403",
"snapshot_id": "8235b00a776864eaeef6c4bddd9271e993ce1134",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/liangcorp/learning_c/5d77d0beec5557d7f077fc0760e6c8513d820403/challenge/challenge_adv_datatype/vla_lecture.c",
"visit_date": "2023-05-06T09:11:26.263777"
} | stackv2 | #include <stdio.h>
int main(void)
{
int i;
int sum = 0;
int size = 0;
printf("Enter the size of the array: ");
scanf("%d", &size);
int array[size];
printf("Enter %d element in the array: ", size);
for (i=0; i<size; i++)
scanf("%d", &array[i]);
for (i=0; i<size; i++)
sum = sum + array[i];
printf("Sum is %d\n", sum);
return 0;
}
| 3.640625 | 4 |
2024-11-18T20:50:34.125858+00:00 | 2021-01-12T10:23:40 | 096d05441cd0e7587fea787e1c662031f74bb3fe | {
"blob_id": "096d05441cd0e7587fea787e1c662031f74bb3fe",
"branch_name": "refs/heads/main",
"committer_date": "2021-01-12T10:23:40",
"content_id": "66664923eddebc8fd8fd57647b21d0a3b473e187",
"detected_licenses": [
"CC0-1.0"
],
"directory_id": "fade406d43c95e7cb25c129d126b1ae7a56f4f13",
"extension": "c",
"filename": "ServidorTCP6.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": null,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1376,
"license": "CC0-1.0",
"license_type": "permissive",
"path": "/practica 2.5/ServidorTCP6.c",
"provenance": "stackv2-0118.json.gz:44901",
"repo_name": "gonzalooosanz/asor_repo",
"revision_date": "2021-01-12T10:23:40",
"revision_id": "141f1fb71485f7a46cb5ebefff3e4dd9032779b8",
"snapshot_id": "43dbd40f9f8e34118f84526f1d80ee1278caae76",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/gonzalooosanz/asor_repo/141f1fb71485f7a46cb5ebefff3e4dd9032779b8/practica 2.5/ServidorTCP6.c",
"visit_date": "2023-02-16T04:31:17.563317"
} | stackv2 | #include <sys/types.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/socket.h>
#include <netdb.h>
#include <time.h>
#define BUF_SIZE 80
int main(int argc, char *argv[]) {
struct addrinfo hints, *result;
int sfd,clisd,rc;
struct sockaddr_storage peer_addr;
socklen_t peer_addr_len;
char buf[BUF_SIZE],host[NI_MAXHOST], service[NI_MAXSERV];
memset(&hints, 0, sizeof(struct addrinfo));
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
hints.ai_flags = AI_PASSIVE;
// .ej2 192.168.0.1 7777
rc = getaddrinfo(argv[1], argv[2], &hints, &result);
if(rc==-1){
printf("Error getaddrinfo \n");
return -1;
}
sfd = socket(result->ai_family, result->ai_socktype,0);
bind(sfd, result->ai_addr, result->ai_addrlen);
freeaddrinfo(result);
listen(sfd,15); //Añadir listen
while (1) {
clisd = accept(sfd,(struct sockaddr *)&peer_addr,&peer_addr_len);
getnameinfo((struct sockaddr *) &peer_addr,peer_addr_len, host, NI_MAXHOST,service, NI_MAXSERV, NI_NUMERICSERV);
printf("Conexión desde Host: %s Puerto:%s\n",host,service);
while(rc = recv(clisd,buf,79,0)){ //Tanto recv como send van con clisd
printf("recibiendo \n");
buf[rc]='\n';
printf("\t mensaje :%s\n",buf);
send(clisd, buf, BUF_SIZE, 0);
}
printf("saliendo ...\n");
}
return 0;
}
| 2.578125 | 3 |
2024-11-18T20:50:34.415726+00:00 | 2020-06-05T05:48:27 | 4380459402b79285f77ef673b4f1058983546074 | {
"blob_id": "4380459402b79285f77ef673b4f1058983546074",
"branch_name": "refs/heads/master",
"committer_date": "2020-06-05T05:48:27",
"content_id": "c866761f7cd093c87bccd46a4feb8da46c2cf57e",
"detected_licenses": [
"MIT",
"BSD-3-Clause"
],
"directory_id": "ee8d74387ffb644d35137b95cae9fcf6af3b0e02",
"extension": "c",
"filename": "handler.c",
"fork_events_count": 2,
"gha_created_at": "2019-12-10T01:02:29",
"gha_event_created_at": "2022-07-06T20:32:22",
"gha_language": "C",
"gha_license_id": "MIT",
"github_id": 226998855,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 3785,
"license": "MIT,BSD-3-Clause",
"license_type": "permissive",
"path": "/LLNL-yorick-fda4a1e/play/win/handler.c",
"provenance": "stackv2-0118.json.gz:45289",
"repo_name": "dle8/Kronos",
"revision_date": "2020-06-05T05:48:27",
"revision_id": "fefa5dc620c8b303016339536d126182c651fa49",
"snapshot_id": "c5b41d9cad708dca34e229b2cc11be498d0b960c",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/dle8/Kronos/fefa5dc620c8b303016339536d126182c651fa49/LLNL-yorick-fda4a1e/play/win/handler.c",
"visit_date": "2022-08-29T17:45:37.777518"
} | stackv2 | /*
* $Id: handler.c,v 1.1 2005-09-18 22:05:37 dhmunro Exp $
* MS Windows exception handling
* - w_interrupt raises a signal in worker thread from boss thread,
* idea from MSDN "Win32 Q&A" KillThrd library
* by Jeffrey Richter in Microsoft Systems Journal
*/
/* Copyright (c) 2005, The Regents of the University of California.
* All rights reserved.
* This file is part of yorick (http://yorick.sourceforge.net).
* Read the accompanying LICENSE file for details.
*/
#include "playw.h"
#include "pstdlib.h"
#include <process.h>
#include <float.h>
#ifndef _MCW_EM
/* some cygwin/mingw platforms fail to define these in float.h */
#define _MCW_EM 0x0008001f
#define _EM_OVERFLOW 0x00000004
#define _EM_ZERODIVIDE 0x00000008
#define _EM_INVALID 0x00000010
extern void _fpreset(void);
extern unsigned int _controlfp_s(unsigned int *unOld, unsigned int unNew,
unsigned int unMask);
#endif
#define W_SIGINT_DELAY 1000
static UINT wm_exception = 0;
static void (*w_on_exception)(int signal, char *errmsg)= 0;
static void w_handle_exception(MSG *msg);
static int sigint_active = 0;
static HANDLE sigint_abort = 0;
static DWORD WINAPI sigint_main(LPVOID lp);
static void w_interrupt(void);
volatile int p_signalling = 0;
void
p_handler(void (*on_exception)(int signal, char *errmsg))
{
w_on_exception = on_exception;
wm_exception = w_add_msg(w_handle_exception);
sigint_abort = CreateEvent(0,0,0,0);
w_fpu_setup();
w_siginit();
}
/* called by worker if an actual exception has been raised, or in
* in response to wm_exception warning message */
void
w_caught(void)
{
MSG msg;
int sig = p_signalling;
p_signalling = 0;
if (sigint_active) PulseEvent(sigint_abort);
w_on_exception(sig, (char *)0); /* blows up if no handler */
/* clear any pending exception warning messages off worker queue */
while (PeekMessage(&msg, NULL, wm_exception, wm_exception,
PM_REMOVE));
}
/* called as response to wm_exception warning message */
/* ARGSUSED */
static void
w_handle_exception(MSG *msg)
{
if (p_signalling) w_caught();
}
void
w_fpu_setup(void)
{
unsigned int old;
_fpreset();
_controlfp_s(&old, _MCW_EM &
~(_EM_ZERODIVIDE | _EM_OVERFLOW | _EM_INVALID), _MCW_EM);
}
int
w_sigint(int delay)
{
if (!w_on_exception) return 0;
if (delay && !p_signalling && !sigint_active) {
/* interrupt worker thread after W_SIGINT_DELAY */
HANDLE h;
UINT id;
p_signalling = PSIG_INT;
h = CreateThread(0,0, sigint_main, 0, 0, (void *)&id);
if (h) {
Sleep(0);
CloseHandle(h);
sigint_active = 1;
} else {
delay = 0;
}
}
if (!delay) w_interrupt();
return 1;
}
static DWORD WINAPI
sigint_main(LPVOID lp)
{
PostThreadMessage(w_id_worker, wm_exception, 0, 0);
if (WaitForSingleObject(sigint_abort, W_SIGINT_DELAY)==WAIT_TIMEOUT &&
p_signalling==PSIG_INT)
w_interrupt();
sigint_active = 0;
return 0;
}
#if defined(_X86_)
# define PC_NAME Eip
#elif defined(_MIPS_)
# define PC_NAME Fir
#elif defined(_ALPHA_)
# define PC_NAME Fir
#elif defined(_PPC_)
# define PC_NAME Iar
#else
# error need name of program counter in CONTEXT struct for this platform
#endif
static void
w_interrupt(void)
{
/* stop the worker, change its program counter to p_abort, resume
* -- claim is this always works under NT, but may sometimes fail
* under 95 if the thread is suspended in a bad place */
SuspendThread(w_worker);
if (WaitForSingleObject(w_worker, 0) == WAIT_TIMEOUT) {
CONTEXT ctx;
ctx.ContextFlags = CONTEXT_CONTROL;
GetThreadContext(w_worker, &ctx);
ctx.PC_NAME = (DWORD)p_abort;
SetThreadContext(w_worker, &ctx);
p_signalling = PSIG_INT;
ResumeThread(w_worker);
}
}
| 2.109375 | 2 |
2024-11-18T20:50:38.425504+00:00 | 2020-04-03T16:24:14 | f4379cf867cd1e0db18439ddcab0f50453ce296e | {
"blob_id": "f4379cf867cd1e0db18439ddcab0f50453ce296e",
"branch_name": "refs/heads/master",
"committer_date": "2020-04-03T16:24:14",
"content_id": "2bfb91c4b9d65edd103f0124256bb6642cb4802a",
"detected_licenses": [
"MIT"
],
"directory_id": "250799a773772192dbc4dfbb6ec029e67db84f4a",
"extension": "h",
"filename": "event_internal.h",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": null,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 856,
"license": "MIT",
"license_type": "permissive",
"path": "/event/event_internal.h",
"provenance": "stackv2-0118.json.gz:45547",
"repo_name": "dalalsunil1986/AppOS",
"revision_date": "2020-04-03T16:24:14",
"revision_id": "32f4709db44e01717b3e60ef06ba05b87e7f75eb",
"snapshot_id": "aeddc7b3f3b946ed442ac8cd547a3aac2bbed91a",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/dalalsunil1986/AppOS/32f4709db44e01717b3e60ef06ba05b87e7f75eb/event/event_internal.h",
"visit_date": "2022-04-13T13:42:26.408734"
} | stackv2 | #ifndef EVENT_INTERNAL_H
#define EVENT_INTERNAL_H
#include <appos.h>
#ifndef MAX_EVENT_QUEUES
#define MAX_EVENT_QUEUES 128 // Since EVENT is 1 Byte wide, MAX_EVENT_QUEUES could be 256 at most
#endif
#ifndef MAX_EVENT_NUMBER
#define MAX_EVENT_NUMBER 512
#endif
struct EventStruct
{
void *message;
size_t size;
};
struct QueueStruct
{
struct EventStruct *buffer;
size_t bufferSize;
int head;
int tail;
unsigned int elements;
};
void event_init();
bool enqueue_event(EVENT code, struct EventStruct *event);
bool dequeue_event(EVENT code, struct EventStruct *event);
struct QueueStruct *get_queue(int position);
#endif
| 2.15625 | 2 |
2024-11-18T20:50:38.995369+00:00 | 2022-07-01T14:36:28 | 2f4afbecdfe0ed48c0700cd12ac8f22cffc290bc | {
"blob_id": "2f4afbecdfe0ed48c0700cd12ac8f22cffc290bc",
"branch_name": "refs/heads/master",
"committer_date": "2022-07-01T14:36:28",
"content_id": "25c642916619b4c8f1020e6e7fb5cbb484e66758",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "f4faa0c46c9d335e71458ad989d080eaa1d7eeb9",
"extension": "c",
"filename": "SL_xeno_common.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 234793069,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 5309,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/src/SL_xeno_common.c",
"provenance": "stackv2-0118.json.gz:45933",
"repo_name": "sschaal2/SL",
"revision_date": "2022-07-01T14:36:28",
"revision_id": "c535fc18fcae2b6f96a5eb857b2d4e180d76479c",
"snapshot_id": "b2eeb432e61e8458d9477a3d03bd8727239ab1d7",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/sschaal2/SL/c535fc18fcae2b6f96a5eb857b2d4e180d76479c/src/SL_xeno_common.c",
"visit_date": "2022-07-17T10:43:05.338447"
} | stackv2 | /*!=============================================================================
==============================================================================
\file SL_xeno_common.c
\author Stefan Schaal
\date Nov 2009
==============================================================================
\remarks
File includes functions that are shared by many processors under
xenomai
============================================================================*/
// system headers
#include "SL_system_headers.h"
#include <execinfo.h>
#include <getopt.h>
// private includes
#include "SL.h"
#include "utility.h"
#include "SL_unix_common.h"
#include "SL_xeno_common.h"
// xenomai people recommend an aperiodic clock
#define XENO_CLOCK_PERIOD TM_ONESHOT //!< base clock rate in nano seconds
// global variables
long count_xenomai_mode_switches = -1;
// external variables
// local variabes
// global functions
// local functions
static void
action_upon_switch_other_servos(int sig __attribute__((unused)));
static void
action_upon_switch_task_servo(int sig __attribute__((unused)));
/*!*****************************************************************************
*******************************************************************************
\note initXeno
\date Oct. 2009
\remarks
xenomai specific initializations
*******************************************************************************
Function Parameters: [in]=input,[out]=output
none
******************************************************************************/
void
initXeno(char *task_name)
{
int rc;
struct sigaction sa;
// lock all of the pages currently and pages that become
// mapped into the address space of the process
mlockall(MCL_CURRENT | MCL_FUTURE);
sl_rt_mutex_init(&mutex1);
//become a real-time process
char name[100];
sprintf(name, "x%s_main_%d", task_name, parent_process_id);
rt_task_shadow(NULL, name, 0, 0);
// gsutanto:
// The task servo is monitored separately here, because otherwise the overall system becomes too sensitive:
// openGL servo continuously has real-time violations (because it is NOT real-time),
// cluttering the real-time violation indications of the task servo.
// It is sufficient to just activate mode-switches interrupt for the task servo only,
// assuming SL users only program additional tasks to be called from task servo,
// and do not tamper with any other servos (i.e. the motor servo is NOT modified and completely real-time-safe).
// You may see an example of real-time violation detection in the task servo here:
// https://atlas.is.localnet/confluence/display/AMDW/Automatic+Pin-Pointing+of+Real-Time+Violation+in+SL%27s+Task+Servo
if (strcmp(task_name, "task") == 0) // setup the real-time mode-switch interrupt handler for the task servo
{
// what to do when mode switches happen on task servo
signal(SIGDEBUG, action_upon_switch_task_servo);
}
else // setup the real-time mode-switch interrupt handler for other servos
{
// what to do when mode switches happen on other servos
signal(SIGDEBUG, action_upon_switch_other_servos);
}
// start the non real-time printing library
rt_print_auto_init(1);
// get the timer info
if ((rc=rt_timer_set_mode((RTIME) XENO_CLOCK_PERIOD)))
printf("rc_timer_set_mode returned %d\n",rc);
// check what we got
RT_TIMER_INFO info;
rt_timer_inquire(&info);
if (info.period == TM_ONESHOT)
printf("Timer Period = TM_ONESHOT\n");
else
printf("Timer Period = %ld [ns]\n",(long) info.period);
}
/*!*****************************************************************************
*******************************************************************************
\note action_upon_switch_other_servos
\date Sept. 2017
\remarks
what to do when mode switches occur on other servos
(only increments the real-time violation counts)
*******************************************************************************
Function Parameters: [in]=input,[out]=output
none
******************************************************************************/
static void
action_upon_switch_other_servos(int sig __attribute__((unused)))
{
void *bt[32];
int nentries;
// increment mode swich counter
++count_xenomai_mode_switches;
}
/*!*****************************************************************************
*******************************************************************************
\note action_upon_switch_task_servo
\date Sept. 2017
\remarks
what to do when mode switches occur on task servo
*******************************************************************************
Function Parameters: [in]=input,[out]=output
none
******************************************************************************/
static void
action_upon_switch_task_servo(int sig __attribute__((unused)))
{
void *bt[32];
int nentries;
// increment mode swich counter
++count_xenomai_mode_switches;
/* Dump a backtrace of the frame which caused the switch to
secondary mode:
(please un-comment the following block for real-time violation monitoring) */
/*
nentries = backtrace(bt,sizeof(bt) / sizeof(bt[0]));
backtrace_symbols_fd(bt,nentries,fileno(stdout));
getchar();*/
}
| 2.328125 | 2 |
2024-11-18T20:50:39.590952+00:00 | 2020-01-15T07:32:12 | 9909f08f51664e009bf3a15d0da00c6eb54f0325 | {
"blob_id": "9909f08f51664e009bf3a15d0da00c6eb54f0325",
"branch_name": "refs/heads/master",
"committer_date": "2020-01-15T07:32:12",
"content_id": "cc3239a081dcb43312df77aae853955e95af83f7",
"detected_licenses": [
"MIT",
"Ruby"
],
"directory_id": "a7a66b45f029aa2b6ad034df620f07d8574c8291",
"extension": "c",
"filename": "monster_engine_server.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 234013403,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2148,
"license": "MIT,Ruby",
"license_type": "permissive",
"path": "/ext/monster_engine/monster_engine_server.c",
"provenance": "stackv2-0118.json.gz:46190",
"repo_name": "monsterengine/monster_engine_ruby",
"revision_date": "2020-01-15T07:32:12",
"revision_id": "ee3a0ea2e90f69b950190b61b1fc9b4f47e1e8e4",
"snapshot_id": "b251e699ba9d76f5fa4466e8aad9412875d3c14f",
"src_encoding": "UTF-8",
"star_events_count": 3,
"url": "https://raw.githubusercontent.com/monsterengine/monster_engine_ruby/ee3a0ea2e90f69b950190b61b1fc9b4f47e1e8e4/ext/monster_engine/monster_engine_server.c",
"visit_date": "2020-12-12T01:50:37.995277"
} | stackv2 | #include "monster_engine.h"
#include <ruby/thread.h>
#include <sys/types.h>
#include <unistd.h>
extern const rb_data_type_t rb_plamo_app_type;
extern VALUE plamo_rb_event_thread(void*);
VALUE rb_cMonsterEngineServer;
static void deallocate(void *monster_engine_server) {
monster_engine_server_destroy(monster_engine_server);
}
const rb_data_type_t rb_monster_engine_server_type = {
"Server",
{
NULL,
deallocate,
NULL,
},
NULL,
NULL,
0,
};
static VALUE allocate(VALUE klass) {
return TypedData_Wrap_Struct(klass, &rb_monster_engine_server_type, NULL);
}
static VALUE initialize(VALUE self, VALUE rb_plamo_app, VALUE rb_monster_engine_config) {
rb_iv_set(self, "@config", rb_monster_engine_config);
PlamoApp *plamo_app;
TypedData_Get_Struct(rb_plamo_app, PlamoApp, &rb_plamo_app_type, plamo_app);
MonsterEngineConfig *monster_engine_config;
TypedData_Get_Struct(rb_monster_engine_config, MonsterEngineConfig, &rb_monster_engine_config_type, monster_engine_config);
DATA_PTR(self) = monster_engine_server_new(plamo_app, monster_engine_config);
return self;
}
typedef struct MonsterEngineRbCallbackSetting {
PlamoApp *plamo_app;
MonsterEngineConfig *monster_engine_config;
} MonsterEngineRbCallbackSetting;
static void* callback(void *monster_engine_server) {
monster_engine_server_start(monster_engine_server);
return NULL;
}
static VALUE start(VALUE self) {
VALUE rb_config = rb_iv_get(self, "@config");
const unsigned int workers = FIX2UINT(rb_iv_get(rb_config, "@workers"));
for (int i = 0; i < workers; i++) {
pid_t pid = fork();
if (pid == 0) {
rb_thread_create(plamo_rb_event_thread, NULL);
rb_thread_call_without_gvl(callback, DATA_PTR(self), RUBY_UBF_PROCESS, NULL);
break;
} else if (pid == -1) {
break;
}
}
while (true) {
sleep(1);
}
return Qnil;
}
void Init_monster_engine_server(void) {
rb_cMonsterEngineServer = rb_define_class_under(rb_mMonsterEngine, "Server", rb_cObject);
rb_define_method(rb_cMonsterEngineServer, "initialize", initialize, 2);
rb_define_method(rb_cMonsterEngineServer, "start", start, 0);
}
| 2.078125 | 2 |
2024-11-18T20:50:39.758496+00:00 | 2015-02-28T12:57:38 | f2d071fa45cbef9ed007f0c2e1c47581299fd8b7 | {
"blob_id": "f2d071fa45cbef9ed007f0c2e1c47581299fd8b7",
"branch_name": "refs/heads/master",
"committer_date": "2015-02-28T12:57:38",
"content_id": "e008b900063d3866738361d7837afd3edb1ae7f6",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "ed03b7fedefff41b7f9bafcf91c59106675e2713",
"extension": "c",
"filename": "evaldesc.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": null,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1645,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/Fac/Licence/IN604/evaldesc.c",
"provenance": "stackv2-0118.json.gz:46450",
"repo_name": "cha63506/archives-9",
"revision_date": "2015-02-28T12:57:38",
"revision_id": "7fae05284f71579f7ebaff0f84b42a07994562ae",
"snapshot_id": "7aacf2a279cb2d56c091e04662cd7bb681332547",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/cha63506/archives-9/7fae05284f71579f7ebaff0f84b42a07994562ae/Fac/Licence/IN604/evaldesc.c",
"visit_date": "2018-04-05T03:34:41.989316"
} | stackv2 | #include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <math.h>
#define AVANCER {jeton=getchar();numcar++;}
#define TEST_AVANCE(prevu) {if (jeton==(prevu)) AVANCER else ERREUR_SYNTAXE}
#define ERREUR_SYNTAXE {printf("\nMot non reconnu : erreur de syntaxe au caractère numéro %d, de jeton %d \n",numcar,jeton); exit(1);}
#define JETON jeton-'0'
int E();int Re(int n);int T();int Rt(int n);int F();int Rp(int n);int
P();
int jeton;
int numcar=0;
int E(){
printf("E->TRe\n");
return Re(T());
}
int Re(int n){
if(jeton=='+'){
printf("Re->+TRe\n");
AVANCER
return Re(n+T());
}
else if(jeton=='-'){
printf("Re->-TRe\n");
AVANCER
return Re(n-T());
}
else{
printf("Re->eps\n");
return n;
}
}
int T(){
printf("T->PRt\n");
return Rt(P());
}
int Rt(int n){
if(jeton=='*'){
printf("Rt->*PRt\n");
AVANCER
return Rt(n*P());
}
if(jeton=='/'){
printf("Rt->/PRt\n");
AVANCER
return Rt(n/P());
}
else{
printf("Rt->eps\n");
return n;
}
}
int P(){
printf("P->FRp\n");
return Rp(F());
}
int Rp(int n){
if(jeton=='^'){
printf("Rp->^PRp\n");
AVANCER
return Rp(pow(n,P()));
}
else{
printf("Rp->eps\n");
return n;
}
}
int F(){
if(jeton=='('){
AVANCER
int result=E();
TEST_AVANCE(')')
return result;
}
else
if(isdigit(jeton)){
printf("F->%d\n",JETON);
int result=JETON;
AVANCER
return result;
}
else ERREUR_SYNTAXE
}
int main(){
AVANCER
int result=E();
if(jeton==EOF||jeton=='\n')
printf("\nMot reconnu : result=%d\n",result);
else ERREUR_SYNTAXE
}
| 3.09375 | 3 |
2024-11-18T20:50:40.120303+00:00 | 2021-09-22T18:11:24 | f6407f61543ca81c8447b8229d19534fa565940d | {
"blob_id": "f6407f61543ca81c8447b8229d19534fa565940d",
"branch_name": "refs/heads/main",
"committer_date": "2021-09-22T18:11:24",
"content_id": "059687553a105a2d1b87d756071458170057e457",
"detected_licenses": [
"MIT"
],
"directory_id": "0aaf408abce8bdcb4149ba43bac1762ab3d1e54a",
"extension": "c",
"filename": "Organizador de Exercícios.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 409304532,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 253,
"license": "MIT",
"license_type": "permissive",
"path": "/Code/Organizador de Exercícios.c",
"provenance": "stackv2-0118.json.gz:46579",
"repo_name": "lucascesar918/C-Programs",
"revision_date": "2021-09-22T18:11:24",
"revision_id": "564710656e219067770a33c0514c694f1e26033f",
"snapshot_id": "94d4ca7084d7b780cc811db07861492a24fda879",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/lucascesar918/C-Programs/564710656e219067770a33c0514c694f1e26033f/Code/Organizador de Exercícios.c",
"visit_date": "2023-08-20T19:26:16.610915"
} | stackv2 | #include <stdio.h>
void organizador(char);
void main(){
char e;
printf("Digite o fim\n"); scanf("%c",&e);
puts("");
organizador(e);
}
void organizador(char f){
int i;
for (i='a';i<=f;i++){
printf("%c)\n",i);
}
} | 3.328125 | 3 |
2024-11-18T20:50:40.210414+00:00 | 2021-05-17T07:14:41 | 7727d9eb339369228d4238e8865d6c136af3e700 | {
"blob_id": "7727d9eb339369228d4238e8865d6c136af3e700",
"branch_name": "refs/heads/master",
"committer_date": "2021-05-17T07:21:11",
"content_id": "7a4baa881aed3920aa1bf6f710ce8227d539df9d",
"detected_licenses": [
"CC0-1.0"
],
"directory_id": "c52d6dfee26289e228be3b2a2620a225f4caa2ab",
"extension": "c",
"filename": "update.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": null,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 777,
"license": "CC0-1.0",
"license_type": "permissive",
"path": "/crypto_aead/ascon128v12/bi32_lowsize/update.c",
"provenance": "stackv2-0118.json.gz:46708",
"repo_name": "ericlagergren/ascon-c",
"revision_date": "2021-05-17T07:14:41",
"revision_id": "aa21b952d29ceffdd802bc03771cd7a3442a7a6f",
"snapshot_id": "e0462aaa1ad49ec09b500c82f71aa904dbe8313f",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/ericlagergren/ascon-c/aa21b952d29ceffdd802bc03771cd7a3442a7a6f/crypto_aead/ascon128v12/bi32_lowsize/update.c",
"visit_date": "2023-04-30T16:36:17.121061"
} | stackv2 | #include "api.h"
#include "ascon.h"
#include "permutations.h"
#include "printstate.h"
void ascon_update(state_t* s, uint8_t* out, const uint8_t* in, uint64_t len,
uint8_t mode) {
const int rate = 8;
const int nr = 6;
word_t tmp0;
int n = 0;
while (len) {
/* determine block size */
n = len < rate ? len : rate;
/* absorb data */
tmp0 = LOAD(in, n);
s->x0 = XOR(s->x0, tmp0);
/* extract data */
if (mode & ASCON_SQUEEZE) STORE(out, s->x0, n);
/* insert data */
if (mode & ASCON_INSERT) {
s->x0 = CLEAR(s->x0, n);
s->x0 = XOR(s->x0, tmp0);
}
/* compute permutation for full blocks */
if (n == rate) P(s, nr);
in += n;
out += n;
len -= n;
}
s->x0 = XOR(s->x0, PAD(n % 8));
}
| 2.390625 | 2 |
2024-11-18T20:50:41.801508+00:00 | 2022-12-27T00:34:04 | d1350813f620dd465f9f49cf46965683629b10af | {
"blob_id": "d1350813f620dd465f9f49cf46965683629b10af",
"branch_name": "refs/heads/master",
"committer_date": "2022-12-27T00:34:04",
"content_id": "6f5c66f66abb5700ac489f3a411024c82ac0c227",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "8ccfbfaba0aedc3f9cac964b2c84a8ddd2ab61fc",
"extension": "c",
"filename": "array_demo3.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 132975806,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 762,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/demo/array_demo3.c",
"provenance": "stackv2-0118.json.gz:47096",
"repo_name": "wfdoran/c-struct",
"revision_date": "2022-12-27T00:34:04",
"revision_id": "28b605f7d6adf13e138a823fb7349c3e9c52c597",
"snapshot_id": "6ab4bd272e8967c02f55e7712a67df7323c2fe00",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/wfdoran/c-struct/28b605f7d6adf13e138a823fb7349c3e9c52c597/demo/array_demo3.c",
"visit_date": "2023-01-09T04:42:59.982813"
} | stackv2 | #include <stdio.h>
#include <stdlib.h>
#include <time.h>
typedef struct {
int x;
float y;
} pair_t;
#define data_t char*
#define prefix str
#include <array.h>
#undef prefix
#undef data_t
int main(void) {
srand(time(NULL));
array_str_t *a = array_str_init();
array_str_append(a, "hello");
array_str_append(a, "world");
array_str_append(a, "this");
array_str_append(a, "is");
array_str_append(a, "a");
array_str_append(a, "test");
array_str_sort(a);
for (int i = 0; i < array_str_size(a); i++) {
printf("%s\n", array_str_get(a, i));
}
printf("%ld %ld\n", array_str_bisect(a, "hello"), array_str_bisect(a, "goodbye"));
array_str_destroy(&a);
return 0;
}
| 2.84375 | 3 |
2024-11-18T22:21:41.527073+00:00 | 2014-12-20T18:42:32 | 2c6d0e83b7e20182556fb7f301c09a7449928aaf | {
"blob_id": "2c6d0e83b7e20182556fb7f301c09a7449928aaf",
"branch_name": "refs/heads/master",
"committer_date": "2014-12-20T18:42:32",
"content_id": "b13707d56ef644a651d4d3d3378281614936e690",
"detected_licenses": [
"MIT"
],
"directory_id": "de02d73ec0d7c4e6fd620084862f3e48d092f6e4",
"extension": "c",
"filename": "sampled.C",
"fork_events_count": 1,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 7846147,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 3407,
"license": "MIT",
"license_type": "permissive",
"path": "/chord-0.1-vasil/lsd/sampled.C",
"provenance": "stackv2-0123.json.gz:514",
"repo_name": "vgslavov/XGossip",
"revision_date": "2014-12-20T18:42:32",
"revision_id": "d71e6d6eb2cb27f0cdd79678b90e6e3ab391ae08",
"snapshot_id": "945d6393deecab1c12f2eae9691d2b1a30c94a68",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/vgslavov/XGossip/d71e6d6eb2cb27f0cdd79678b90e6e3ab391ae08/chord-0.1-vasil/lsd/sampled.C",
"visit_date": "2021-01-02T09:44:29.674931"
} | stackv2 | #include <arpc.h>
#include <crypt.h>
#include <id_utils.h>
#include "sampler.h"
#include "sample_server.h"
#include <location.h>
#include <locationtable.h>
#include <modlogger.h>
#include <dhash_types.h>
#include <dhash_common.h>
#include <lsdctl_prot.h>
static char *logfname;
static vec<sampler *> samplers;
static ptr<sample_server> sserver;
static ptr<aclnt>
lsdctl_connect (str sockname)
{
int fd = unixsocket_connect (sockname);
if (fd < 0) {
fatal ("lsdctl_connect: Error connecting to %s: %s\n",
sockname.cstr (), strerror (errno));
}
ptr<aclnt> c = aclnt::alloc (axprt_unix::alloc (fd, 10*1024),
lsdctl_prog_1);
return c;
}
static void
start (ptr<lsdctl_lsdparameters> p, clnt_stat err)
{
if (err)
fatal << "Couldn't connect to local lsd to get sync parameters: "
<< err << "\n";
ptr<locationtable> locations = New refcounted<locationtable> (1024);
chord_node ret;
bzero (&ret, sizeof (ret));
for (u_int i = 0; i < 3; i++)
ret.coords.push_back (0);
ret.r.hostname = p->addr.hostname;
ret.r.port = p->addr.port;
sserver = New refcounted<sample_server>( ret.r.port+2 /*LAME CONVENTION */,
p->nvnodes );
for (int i = 0; i < p->nvnodes; i++) {
ret.vnode_num = i;
ret.x = make_chordID (ret.r.hostname, ret.r.port, i);
ptr<location> n = New refcounted<location> (ret);
//dbname format: ID.".c"
str dbname = strbuf () << ret.x << ".c";
sampler *s = New sampler (locations, n, p->adbdsock, dbname, DHASH_CONTENTHASH, p->dfrags, p->efrags);
samplers.push_back (s);
sserver->set_sampler( i, DHASH_CONTENTHASH, s );
dbname = strbuf () << ret.x << ".n";
s = New sampler (locations, n, p->adbdsock, dbname, DHASH_NOAUTH, p->nreplica, p->nreplica);
samplers.push_back (s);
sserver->set_sampler( i, DHASH_NOAUTH, s );
}
}
static void
halt ()
{
//dmalloc_log_unfreed();
warnx << "Exiting on command.\n";
while (samplers.size ()) {
sampler *s = samplers.pop_back ();
delete s;
}
exit (0);
}
void
start_logs ()
{
static int logfd (-1);
// XXX please don't call setlogfd or change errfd anywhere else...
if (logfname) {
if (logfd >= 0)
close (logfd);
logfd = open (logfname, O_RDWR | O_CREAT, 0666);
if (logfd < 0)
fatal << "Could not open log file " << logfd << " for appending.\n";
lseek (logfd, 0, SEEK_END);
errfd = logfd;
modlogger::setlogfd (logfd);
}
}
static void
usage ()
{
warnx << "Usage: " << progname
<< "\t[-C lsd-ctlsock]\n"
<< "\t[-L logfilename]\n"
<< "\t[-t]\n";
exit (1);
}
int
main (int argc, char **argv)
{
//mp_set_memory_functions( NULL, simple_realloc, NULL );
str lsdsock = "/tmp/lsdctl-sock";
char ch;
setprogname (argv[0]);
random_init ();
while ((ch = getopt (argc, argv, "C:L:t"))!=-1)
switch (ch) {
case 'C':
lsdsock = optarg;
break;
case 'L':
logfname = optarg;
break;
case 't':
modlogger::setmaxprio (modlogger::TRACE);
break;
default:
usage ();
break;
}
start_logs ();
sigcb(SIGHUP, wrap (&start_logs));
sigcb(SIGINT, wrap (&halt));
sigcb(SIGTERM, wrap (&halt));
ptr<aclnt> c = lsdctl_connect (lsdsock);
ptr<lsdctl_lsdparameters> p = New refcounted<lsdctl_lsdparameters> ();
c->timedcall (5, LSDCTL_GETLSDPARAMETERS, NULL, p,
wrap (&start, p));
amain ();
}
| 2.078125 | 2 |
2024-11-18T22:21:41.956313+00:00 | 2021-10-25T10:09:15 | 11ce18042713d93eeb5b068fbc2d203fd34981d4 | {
"blob_id": "11ce18042713d93eeb5b068fbc2d203fd34981d4",
"branch_name": "refs/heads/main",
"committer_date": "2021-10-25T10:09:15",
"content_id": "07bb00554b5734fac78b2f217cc6c16c49938a9b",
"detected_licenses": [
"MIT"
],
"directory_id": "56b809cc17ea6bef3f840158de653afef1080865",
"extension": "c",
"filename": "hello.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": null,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1836,
"license": "MIT",
"license_type": "permissive",
"path": "/16/hello.c",
"provenance": "stackv2-0123.json.gz:771",
"repo_name": "Mchine8916493/ldd-test",
"revision_date": "2021-10-25T10:09:15",
"revision_id": "7d082206aa50e076c48bf6df20220cc8f35b7256",
"snapshot_id": "9133345b66c02c5a75bfe31ae0d4edb403f408eb",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/Mchine8916493/ldd-test/7d082206aa50e076c48bf6df20220cc8f35b7256/16/hello.c",
"visit_date": "2023-08-28T20:53:56.946312"
} | stackv2 | /***********************************
@ @@@@ __/\__
@||@@/ @关注@ \ @@ /
@||@/ @@@@ /''\
科G栈
KGZ
***********************************/
/*
request_mem_region()
release_mem_region()
ioremap()
iounmap()
ioread32() ioread8()/ioread16()
iowrite32() iowrite8()/iowrite16()
*/
#include<linux/module.h>
#include<linux/io.h>
unsigned long gpio_base = 0x3f200000;
int gpio_len =0xb3;
struct timer_list t1;
int tdelay;
uint8_t flag=0;
void timer_fn(struct timer_list *t)
{
if(flag)
iowrite32(ioread32((void *)(gpio_base+0x1c))|(1<<4),(void*)(gpio_base+0x1c));
else
iowrite32(ioread32((void *)(gpio_base+0x28))|1<<4,(void*)(gpio_base+0x28));
flag=!flag;
mod_timer(&t1,jiffies+msecs_to_jiffies(1000));
}
static int __init hello_init(void)
{
printk(KERN_INFO "HELLO LINUX MODULE\n");
// if (! request_mem_region(gpio_base,gpio_len , "gpio")) {
// printk(KERN_INFO " can't get I/O mem address 0x%lx\n",
// gpio_base);
// return -ENODEV;
// }
gpio_base = (unsigned long)ioremap(gpio_base,gpio_len);
iowrite32(ioread32((void *)gpio_base)|(1<<12),(void*)gpio_base); //pin4 output
printk(KERN_INFO"gpio remap base:0x%lx\n",gpio_base);
printk(KERN_INFO"read %x %x %x\n",ioread8((void *)(gpio_base)),ioread16((void *)(gpio_base)),ioread32((void *)(gpio_base)));
timer_setup(&t1,timer_fn,0);
mod_timer(&t1,jiffies+msecs_to_jiffies(1000));
return 0;
}
static void __exit hello_exit(void)
{
printk(KERN_INFO "GOODBYE LINUX\n");
//release_mem_region(gpio_base,gpio_len);
del_timer(&t1);
iounmap((void *)gpio_base);
}
module_init(hello_init);
module_exit(hello_exit);
//描述性定义
MODULE_LICENSE("Dual BSD/GPL");//许可 GPL、GPL v2、Dual MPL/GPL、Proprietary(专有)等,没有内核会提示
MODULE_AUTHOR("KGZ"); //作者
MODULE_VERSION("V1.0"); //版本
| 2.421875 | 2 |
2024-11-18T22:21:45.508141+00:00 | 2023-08-27T19:14:02 | 37813558eb5a744c74445d5be3bb98afaa85791c | {
"blob_id": "37813558eb5a744c74445d5be3bb98afaa85791c",
"branch_name": "refs/heads/master",
"committer_date": "2023-08-27T19:14:02",
"content_id": "9f2de291bae369f660f22e4fcb2f1be5e54c7760",
"detected_licenses": [
"BSD-2-Clause"
],
"directory_id": "7c857119fe1505b1d80d6e62969661c06dc1a2f4",
"extension": "h",
"filename": "PciResourceSupport.h",
"fork_events_count": 770,
"gha_created_at": "2019-09-02T08:22:14",
"gha_event_created_at": "2023-09-03T12:41:33",
"gha_language": "C",
"gha_license_id": "BSD-2-Clause",
"github_id": 205810121,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 12309,
"license": "BSD-2-Clause",
"license_type": "permissive",
"path": "/MdeModulePkg/Bus/Pci/PciBusDxe/PciResourceSupport.h",
"provenance": "stackv2-0123.json.gz:2712",
"repo_name": "CloverHackyColor/CloverBootloader",
"revision_date": "2023-08-27T19:14:02",
"revision_id": "2711170df4f60b2ae5aa20add3e00f35cf57b7e5",
"snapshot_id": "7042ca7dd6b513d22be591a295e49071ae1482ee",
"src_encoding": "UTF-8",
"star_events_count": 4734,
"url": "https://raw.githubusercontent.com/CloverHackyColor/CloverBootloader/2711170df4f60b2ae5aa20add3e00f35cf57b7e5/MdeModulePkg/Bus/Pci/PciBusDxe/PciResourceSupport.h",
"visit_date": "2023-08-30T22:14:34.590134"
} | stackv2 | /** @file
PCI resources support functions declaration for PCI Bus module.
Copyright (c) 2006 - 2019, Intel Corporation. All rights reserved.<BR>
SPDX-License-Identifier: BSD-2-Clause-Patent
**/
#ifndef _EFI_PCI_RESOURCE_SUPPORT_H_
#define _EFI_PCI_RESOURCE_SUPPORT_H_
typedef enum {
PciResUsageTypical,
PciResUsagePadding
} PCI_RESOURCE_USAGE;
#define PCI_RESOURCE_SIGNATURE SIGNATURE_32 ('p', 'c', 'r', 'c')
typedef struct {
UINT32 Signature;
LIST_ENTRY Link;
LIST_ENTRY ChildList;
PCI_IO_DEVICE *PciDev;
UINT64 Alignment;
UINT64 Offset;
UINT8 Bar;
PCI_BAR_TYPE ResType;
UINT64 Length;
BOOLEAN Reserved;
PCI_RESOURCE_USAGE ResourceUsage;
BOOLEAN Virtual;
} PCI_RESOURCE_NODE;
#define RESOURCE_NODE_FROM_LINK(a) \
CR (a, PCI_RESOURCE_NODE, Link, PCI_RESOURCE_SIGNATURE)
/**
The function is used to skip VGA range.
@param Start Returned start address including VGA range.
@param Length The length of VGA range.
**/
VOID
SkipVGAAperture (
OUT UINT64 *Start,
IN UINT64 Length
);
/**
This function is used to skip ISA aliasing aperture.
@param Start Returned start address including ISA aliasing aperture.
@param Length The length of ISA aliasing aperture.
**/
VOID
SkipIsaAliasAperture (
OUT UINT64 *Start,
IN UINT64 Length
);
/**
This function inserts a resource node into the resource list.
The resource list is sorted in descend order.
@param Bridge PCI resource node for bridge.
@param ResNode Resource node want to be inserted.
**/
VOID
InsertResourceNode (
IN OUT PCI_RESOURCE_NODE *Bridge,
IN PCI_RESOURCE_NODE *ResNode
);
/**
This routine is used to merge two different resource trees in need of
resource degradation.
For example, if an upstream PPB doesn't support,
prefetchable memory decoding, the PCI bus driver will choose to call this function
to merge prefetchable memory resource list into normal memory list.
If the TypeMerge is TRUE, Res resource type is changed to the type of destination resource
type.
If Dst is NULL or Res is NULL, ASSERT ().
@param Dst Point to destination resource tree.
@param Res Point to source resource tree.
@param TypeMerge If the TypeMerge is TRUE, Res resource type is changed to the type of
destination resource type.
**/
VOID
MergeResourceTree (
IN PCI_RESOURCE_NODE *Dst,
IN PCI_RESOURCE_NODE *Res,
IN BOOLEAN TypeMerge
);
/**
This function is used to calculate the IO16 aperture
for a bridge.
@param Bridge PCI resource node for bridge.
**/
VOID
CalculateApertureIo16 (
IN PCI_RESOURCE_NODE *Bridge
);
/**
This function is used to calculate the resource aperture
for a given bridge device.
@param Bridge PCI resource node for given bridge device.
**/
VOID
CalculateResourceAperture (
IN PCI_RESOURCE_NODE *Bridge
);
/**
Get IO/Memory resource info for given PCI device.
@param PciDev Pci device instance.
@param IoNode Resource info node for IO .
@param Mem32Node Resource info node for 32-bit memory.
@param PMem32Node Resource info node for 32-bit Prefetchable Memory.
@param Mem64Node Resource info node for 64-bit memory.
@param PMem64Node Resource info node for 64-bit Prefetchable Memory.
**/
VOID
GetResourceFromDevice (
IN PCI_IO_DEVICE *PciDev,
IN OUT PCI_RESOURCE_NODE *IoNode,
IN OUT PCI_RESOURCE_NODE *Mem32Node,
IN OUT PCI_RESOURCE_NODE *PMem32Node,
IN OUT PCI_RESOURCE_NODE *Mem64Node,
IN OUT PCI_RESOURCE_NODE *PMem64Node
);
/**
This function is used to create a resource node.
@param PciDev Pci device instance.
@param Length Length of Io/Memory resource.
@param Alignment Alignment of resource.
@param Bar Bar index.
@param ResType Type of resource: IO/Memory.
@param ResUsage Resource usage.
@return PCI resource node created for given PCI device.
NULL means PCI resource node is not created.
**/
PCI_RESOURCE_NODE *
CreateResourceNode (
IN PCI_IO_DEVICE *PciDev,
IN UINT64 Length,
IN UINT64 Alignment,
IN UINT8 Bar,
IN PCI_BAR_TYPE ResType,
IN PCI_RESOURCE_USAGE ResUsage
);
/**
This function is used to create a IOV VF resource node.
@param PciDev Pci device instance.
@param Length Length of Io/Memory resource.
@param Alignment Alignment of resource.
@param Bar Bar index.
@param ResType Type of resource: IO/Memory.
@param ResUsage Resource usage.
@return PCI resource node created for given VF PCI device.
NULL means PCI resource node is not created.
**/
PCI_RESOURCE_NODE *
CreateVfResourceNode (
IN PCI_IO_DEVICE *PciDev,
IN UINT64 Length,
IN UINT64 Alignment,
IN UINT8 Bar,
IN PCI_BAR_TYPE ResType,
IN PCI_RESOURCE_USAGE ResUsage
);
/**
This function is used to extract resource request from
device node list.
@param Bridge Pci device instance.
@param IoNode Resource info node for IO.
@param Mem32Node Resource info node for 32-bit memory.
@param PMem32Node Resource info node for 32-bit Prefetchable Memory.
@param Mem64Node Resource info node for 64-bit memory.
@param PMem64Node Resource info node for 64-bit Prefetchable Memory.
**/
VOID
CreateResourceMap (
IN PCI_IO_DEVICE *Bridge,
IN OUT PCI_RESOURCE_NODE *IoNode,
IN OUT PCI_RESOURCE_NODE *Mem32Node,
IN OUT PCI_RESOURCE_NODE *PMem32Node,
IN OUT PCI_RESOURCE_NODE *Mem64Node,
IN OUT PCI_RESOURCE_NODE *PMem64Node
);
/**
This function is used to do the resource padding for a specific platform.
@param PciDev Pci device instance.
@param IoNode Resource info node for IO.
@param Mem32Node Resource info node for 32-bit memory.
@param PMem32Node Resource info node for 32-bit Prefetchable Memory.
@param Mem64Node Resource info node for 64-bit memory.
@param PMem64Node Resource info node for 64-bit Prefetchable Memory.
**/
VOID
ResourcePaddingPolicy (
IN PCI_IO_DEVICE *PciDev,
IN PCI_RESOURCE_NODE *IoNode,
IN PCI_RESOURCE_NODE *Mem32Node,
IN PCI_RESOURCE_NODE *PMem32Node,
IN PCI_RESOURCE_NODE *Mem64Node,
IN PCI_RESOURCE_NODE *PMem64Node
);
/**
This function is used to degrade resource if the upstream bridge
doesn't support certain resource. Degradation path is
PMEM64 -> MEM64 -> MEM32
PMEM64 -> PMEM32 -> MEM32
IO32 -> IO16.
@param Bridge Pci device instance.
@param Mem32Node Resource info node for 32-bit memory.
@param PMem32Node Resource info node for 32-bit Prefetchable Memory.
@param Mem64Node Resource info node for 64-bit memory.
@param PMem64Node Resource info node for 64-bit Prefetchable Memory.
**/
VOID
DegradeResource (
IN PCI_IO_DEVICE *Bridge,
IN PCI_RESOURCE_NODE *Mem32Node,
IN PCI_RESOURCE_NODE *PMem32Node,
IN PCI_RESOURCE_NODE *Mem64Node,
IN PCI_RESOURCE_NODE *PMem64Node
);
/**
Test whether bridge device support decode resource.
@param Bridge Bridge device instance.
@param Decode Decode type according to resource type.
@return TRUE The bridge device support decode resource.
@return FALSE The bridge device don't support decode resource.
**/
BOOLEAN
BridgeSupportResourceDecode (
IN PCI_IO_DEVICE *Bridge,
IN UINT32 Decode
);
/**
This function is used to program the resource allocated
for each resource node under specified bridge.
@param Base Base address of resource to be programmed.
@param Bridge PCI resource node for the bridge device.
@retval EFI_SUCCESS Successfully to program all resources
on given PCI bridge device.
@retval EFI_OUT_OF_RESOURCES Base is all one.
**/
EFI_STATUS
ProgramResource (
IN UINT64 Base,
IN PCI_RESOURCE_NODE *Bridge
);
/**
Program Bar register for PCI device.
@param Base Base address for PCI device resource to be programmed.
@param Node Point to resource node structure.
**/
VOID
ProgramBar (
IN UINT64 Base,
IN PCI_RESOURCE_NODE *Node
);
/**
Program IOV VF Bar register for PCI device.
@param Base Base address for PCI device resource to be programmed.
@param Node Point to resource node structure.
**/
EFI_STATUS
ProgramVfBar (
IN UINT64 Base,
IN PCI_RESOURCE_NODE *Node
);
/**
Program PCI-PCI bridge aperture.
@param Base Base address for resource.
@param Node Point to resource node structure.
**/
VOID
ProgramPpbApperture (
IN UINT64 Base,
IN PCI_RESOURCE_NODE *Node
);
/**
Program parent bridge for Option Rom.
@param PciDevice Pci device instance.
@param OptionRomBase Base address for Option Rom.
@param Enable Enable or disable PCI memory.
**/
VOID
ProgramUpstreamBridgeForRom (
IN PCI_IO_DEVICE *PciDevice,
IN UINT32 OptionRomBase,
IN BOOLEAN Enable
);
/**
Test whether resource exists for a bridge.
@param Bridge Point to resource node for a bridge.
@retval TRUE There is resource on the given bridge.
@retval FALSE There isn't resource on the given bridge.
**/
BOOLEAN
ResourceRequestExisted (
IN PCI_RESOURCE_NODE *Bridge
);
/**
Initialize resource pool structure.
@param ResourcePool Point to resource pool structure. This pool
is reset to all zero when returned.
@param ResourceType Type of resource.
**/
VOID
InitializeResourcePool (
IN OUT PCI_RESOURCE_NODE *ResourcePool,
IN PCI_BAR_TYPE ResourceType
);
/**
Destroy given resource tree.
@param Bridge PCI resource root node of resource tree.
**/
VOID
DestroyResourceTree (
IN PCI_RESOURCE_NODE *Bridge
);
/**
Insert resource padding for P2C.
@param PciDev Pci device instance.
@param IoNode Resource info node for IO.
@param Mem32Node Resource info node for 32-bit memory.
@param PMem32Node Resource info node for 32-bit Prefetchable Memory.
@param Mem64Node Resource info node for 64-bit memory.
@param PMem64Node Resource info node for 64-bit Prefetchable Memory.
**/
VOID
ResourcePaddingForCardBusBridge (
IN PCI_IO_DEVICE *PciDev,
IN PCI_RESOURCE_NODE *IoNode,
IN PCI_RESOURCE_NODE *Mem32Node,
IN PCI_RESOURCE_NODE *PMem32Node,
IN PCI_RESOURCE_NODE *Mem64Node,
IN PCI_RESOURCE_NODE *PMem64Node
);
/**
Program PCI Card device register for given resource node.
@param Base Base address of PCI Card device to be programmed.
@param Node Given resource node.
**/
VOID
ProgramP2C (
IN UINT64 Base,
IN PCI_RESOURCE_NODE *Node
);
/**
Create padding resource node.
@param PciDev Pci device instance.
@param IoNode Resource info node for IO.
@param Mem32Node Resource info node for 32-bit memory.
@param PMem32Node Resource info node for 32-bit Prefetchable Memory.
@param Mem64Node Resource info node for 64-bit memory.
@param PMem64Node Resource info node for 64-bit Prefetchable Memory.
**/
VOID
ApplyResourcePadding (
IN PCI_IO_DEVICE *PciDev,
IN PCI_RESOURCE_NODE *IoNode,
IN PCI_RESOURCE_NODE *Mem32Node,
IN PCI_RESOURCE_NODE *PMem32Node,
IN PCI_RESOURCE_NODE *Mem64Node,
IN PCI_RESOURCE_NODE *PMem64Node
);
/**
Get padding resource for PCI-PCI bridge.
@param PciIoDevice PCI-PCI bridge device instance.
@note Feature flag PcdPciBusHotplugDeviceSupport determines
whether need to pad resource for them.
**/
VOID
GetResourcePaddingPpb (
IN PCI_IO_DEVICE *PciIoDevice
);
#endif
| 2.375 | 2 |
2024-11-18T22:21:45.773171+00:00 | 2018-07-23T14:46:06 | f21ce58bcb1bb3f3e7dba7f04d92628501589981 | {
"blob_id": "f21ce58bcb1bb3f3e7dba7f04d92628501589981",
"branch_name": "refs/heads/master",
"committer_date": "2018-07-23T14:46:06",
"content_id": "c2eb160e74ebf55979362d66b2349e4b41f31407",
"detected_licenses": [
"MIT"
],
"directory_id": "8bbeb7b5721a9dbf40caa47a96e6961ceabb0128",
"extension": "c",
"filename": "770.Couples Holding Hands(情侣牵手).c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": null,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 3907,
"license": "MIT",
"license_type": "permissive",
"path": "/c/770.Couples Holding Hands(情侣牵手).c",
"provenance": "stackv2-0123.json.gz:3101",
"repo_name": "lishulongVI/leetcode",
"revision_date": "2018-07-23T14:46:06",
"revision_id": "6731e128be0fd3c0bdfe885c1a409ac54b929597",
"snapshot_id": "bb5b75642f69dfaec0c2ee3e06369c715125b1ba",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/lishulongVI/leetcode/6731e128be0fd3c0bdfe885c1a409ac54b929597/c/770.Couples Holding Hands(情侣牵手).c",
"visit_date": "2020-03-23T22:17:40.335970"
} | stackv2 | /*
<p>
N couples sit in 2N seats arranged in a row and want to hold hands. We want to know the minimum number of swaps so that every couple is sitting side by side. A <i>swap</i> consists of choosing <b>any</b> two people, then they stand up and switch seats.
</p><p>
The people and seats are represented by an integer from <code>0</code> to <code>2N-1</code>, the couples are numbered in order, the first couple being <code>(0, 1)</code>, the second couple being <code>(2, 3)</code>, and so on with the last couple being <code>(2N-2, 2N-1)</code>.
</p><p>
The couples' initial seating is given by <code>row[i]</code> being the value of the person who is initially sitting in the i-th seat.
<p><b>Example 1:</b><br /><pre>
<b>Input:</b> row = [0, 2, 1, 3]
<b>Output:</b> 1
<b>Explanation:</b> We only need to swap the second (row[1]) and third (row[2]) person.
</pre></p>
<p><b>Example 2:</b><br /><pre>
<b>Input:</b> row = [3, 2, 0, 1]
<b>Output:</b> 0
<b>Explanation:</b> All couples are already seated side by side.
</pre></p>
<p>
<b>Note:</b>
<ol>
<li> <code>len(row)</code> is even and in the range of <code>[4, 60]</code>.</li>
<li> <code>row</code> is guaranteed to be a permutation of <code>0...len(row)-1</code>.</li>
</ol><p>N 对情侣坐在连续排列的 2N 个座位上,想要牵到对方的手。 计算最少交换座位的次数,以便每对情侣可以并肩坐在一起。 <em>一</em>次交换可选择任意两人,让他们站起来交换座位。</p>
<p>人和座位用 <code>0</code> 到 <code>2N-1</code> 的整数表示,情侣们按顺序编号,第一对是 <code>(0, 1)</code>,第二对是 <code>(2, 3)</code>,以此类推,最后一对是 <code>(2N-2, 2N-1)</code>。</p>
<p>这些情侣的初始座位 <code>row[i]</code> 是由最初始坐在第 i 个座位上的人决定的。</p>
<p><strong>示例 1:</strong></p>
<pre>
<strong>输入:</strong> row = [0, 2, 1, 3]
<strong>输出:</strong> 1
<strong>解释:</strong> 我们只需要交换row[1]和row[2]的位置即可。
</pre>
<p><strong>示例 2:</strong></p>
<pre>
<strong>输入:</strong> row = [3, 2, 0, 1]
<strong>输出:</strong> 0
<strong>解释:</strong> 无需交换座位,所有的情侣都已经可以手牵手了。
</pre>
<p><strong>说明:</strong></p>
<ol>
<li><code>len(row)</code> 是偶数且数值在 <code>[4, 60]</code>范围内。</li>
<li>可以保证<code>row</code> 是序列 <code>0...len(row)-1</code> 的一个全排列。</li>
</ol>
<p>N 对情侣坐在连续排列的 2N 个座位上,想要牵到对方的手。 计算最少交换座位的次数,以便每对情侣可以并肩坐在一起。 <em>一</em>次交换可选择任意两人,让他们站起来交换座位。</p>
<p>人和座位用 <code>0</code> 到 <code>2N-1</code> 的整数表示,情侣们按顺序编号,第一对是 <code>(0, 1)</code>,第二对是 <code>(2, 3)</code>,以此类推,最后一对是 <code>(2N-2, 2N-1)</code>。</p>
<p>这些情侣的初始座位 <code>row[i]</code> 是由最初始坐在第 i 个座位上的人决定的。</p>
<p><strong>示例 1:</strong></p>
<pre>
<strong>输入:</strong> row = [0, 2, 1, 3]
<strong>输出:</strong> 1
<strong>解释:</strong> 我们只需要交换row[1]和row[2]的位置即可。
</pre>
<p><strong>示例 2:</strong></p>
<pre>
<strong>输入:</strong> row = [3, 2, 0, 1]
<strong>输出:</strong> 0
<strong>解释:</strong> 无需交换座位,所有的情侣都已经可以手牵手了。
</pre>
<p><strong>说明:</strong></p>
<ol>
<li><code>len(row)</code> 是偶数且数值在 <code>[4, 60]</code>范围内。</li>
<li>可以保证<code>row</code> 是序列 <code>0...len(row)-1</code> 的一个全排列。</li>
</ol>
*/
int minSwapsCouples(int* row, int rowSize) {
} | 3.390625 | 3 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.